0
# Name Resolution
1
2
System for resolving code names and imports to their documentation locations using Sphinx inventory data and intersphinx references. This component maps parsed code names to their actual documentation URLs, enabling the generation of clickable links.
3
4
## Capabilities
5
6
### Core Resolution Functions
7
8
Primary functions for resolving name chains to documentation locations.
9
10
```python { .api }
11
def resolve_location(chain: Name, inventory: dict) -> str:
12
"""
13
Resolve a name chain to its final documented location.
14
15
Takes a parsed name (like 'numpy.array' or 'os.path.join') and follows
16
its import chain through the inventory to find the final documentation
17
location. Handles attribute access, method calls, and complex import patterns.
18
19
Parameters:
20
- chain: Name object containing import components and access pattern
21
- inventory: Dictionary mapping object names to documentation URLs
22
23
Returns:
24
- str: Final resolved location key for inventory lookup
25
26
Raises:
27
- CouldNotResolve: When the name chain cannot be resolved to a location
28
"""
29
```
30
31
### Exception Classes
32
33
Exceptions raised during the resolution process.
34
35
```python { .api }
36
class CouldNotResolve(Exception):
37
"""
38
Exception raised when name resolution fails.
39
40
Indicates that a name chain could not be traced to a documented
41
location, either due to missing inventory entries, complex import
42
patterns, or dynamically created objects.
43
"""
44
```
45
46
### Resolution Support Classes
47
48
Internal classes that support the resolution process.
49
50
```python { .api }
51
class Cursor:
52
"""
53
Cursor for following imports, attributes and calls to final types.
54
55
Represents the current position when traversing a name chain,
56
tracking the object location, current value, and whether we're
57
dealing with an instance or class.
58
"""
59
location: str # Current documentation location
60
value: Any # Current object value (if available)
61
instance: bool # Whether this is an instance vs class access
62
```
63
64
### Inventory Management
65
66
Functions for working with Sphinx inventory data and intersphinx references.
67
68
```python { .api }
69
def transpose_inventory(inv: dict, relative_to: str, *, use_tuple: bool = False) -> dict[str, str]:
70
"""
71
Transpose Sphinx inventory from {type: {name: (..., location)}} to {name: location}.
72
73
Converts Sphinx's nested inventory format to a flat mapping suitable
74
for efficient name resolution. Filters to Python domain objects only
75
and handles both local and intersphinx inventories.
76
77
Parameters:
78
- inv: Sphinx inventory in nested format
79
- relative_to: Directory to make file paths relative to
80
- use_tuple: Force using tuple interface for compatibility
81
82
Returns:
83
- dict[str, str]: Flat mapping from object names to documentation URLs
84
"""
85
86
# Inventory creation from Sphinx data
87
def make_inventory(app) -> dict[str, str]:
88
"""
89
Create object inventory from local info and intersphinx.
90
91
Combines local Sphinx domain objects with intersphinx inventories
92
to create a complete mapping of available documentation targets.
93
94
Parameters:
95
- app: Sphinx application instance
96
97
Returns:
98
- dict: Combined inventory mapping names to locations
99
"""
100
```
101
102
### Cache Management
103
104
Classes for managing resolution data across builds.
105
106
```python { .api }
107
class DataCache:
108
"""
109
Manages caching of transform data between builds.
110
111
Stores and retrieves source transformations to avoid re-parsing
112
unchanged documents, improving build performance.
113
"""
114
transforms: dict[str, list[SourceTransform]]
115
116
def __init__(self, doctree_dir: str, source_dir: str): ...
117
118
def read(self) -> None:
119
"""Load cached transform data from disk."""
120
121
def write(self) -> None:
122
"""Save current transform data to disk."""
123
```
124
125
## Resolution Process
126
127
### Name Chain Analysis
128
129
The resolution process follows these steps:
130
131
1. **Import Analysis**: Parse import statements to build base mappings
132
2. **Name Tracking**: Follow variable assignments and attribute access
133
3. **Chain Building**: Construct complete access chains from imports to usage
134
4. **Resolution**: Map chains to inventory locations
135
5. **Validation**: Verify resolved locations exist in inventory
136
137
### Import Pattern Examples
138
139
The resolver handles various import patterns:
140
141
```python
142
# Direct imports
143
import os
144
os.path.join() # Resolves to: os.path.join
145
146
# From imports
147
from os.path import join
148
join() # Resolves to: os.path.join
149
150
# Aliased imports
151
import numpy as np
152
np.array() # Resolves to: numpy.array
153
154
# Attribute chains
155
import matplotlib.pyplot as plt
156
plt.figure().add_subplot() # Resolves to: matplotlib.figure.Figure.add_subplot
157
158
# Complex patterns
159
from package.submodule import Class
160
instance = Class()
161
instance.method() # Resolves to: package.submodule.Class.method
162
```
163
164
## Usage Examples
165
166
### Inventory Mapping Configuration
167
168
Redirect or alias inventory locations:
169
170
```python
171
# conf.py
172
codeautolink_inventory_map = {
173
# Redirect deprecated names
174
'old.module.function': 'new.module.function',
175
176
# Handle moved classes
177
'package.OldClass': 'package.submodule.NewClass',
178
179
# Map aliases to canonical names
180
'np.array': 'numpy.array',
181
'plt.figure': 'matplotlib.pyplot.figure'
182
}
183
```
184
185
### Resolution Error Handling
186
187
Configure warnings for resolution issues:
188
189
```python
190
# conf.py - Enable detailed resolution warnings
191
codeautolink_warn_on_failed_resolve = True
192
codeautolink_warn_on_missing_inventory = True
193
194
# Example warning output:
195
# WARNING: Could not resolve `np.array` on line 42
196
# using path `numpy.array`.
197
# AttributeError: module 'numpy' has no attribute 'array'
198
#
199
# WARNING: Inventory missing `scipy.stats.norm.pdf`
200
# when resolving `norm.pdf` on line 18.
201
# Possibly missing documentation entry entirely,
202
# or the object has been relocated from the source file.
203
```
204
205
### Complex Resolution Examples
206
207
The resolver handles sophisticated patterns:
208
209
```python
210
# Method chaining
211
df.groupby('column').mean().plot()
212
# Resolves each step: pandas.DataFrame.groupby -> groupby.mean -> Series.plot
213
214
# Context managers
215
with open('file.txt') as f:
216
f.read()
217
# Resolves: builtins.open (context manager) -> TextIOWrapper.read
218
219
# Decorators
220
@property
221
def value(self):
222
return self._value
223
# Tracks decorator application and property creation
224
225
# Dynamic attribute access
226
getattr(obj, 'method_name')()
227
# Limited resolution - tracks what's statically analyzable
228
```
229
230
### Inventory Integration
231
232
The system integrates with Sphinx's inventory system:
233
234
```python
235
# Automatic inventory sources:
236
# - Local Sphinx domain objects (from autodoc, etc.)
237
# - Intersphinx inventories from external projects
238
# - Custom inventory mappings from configuration
239
240
# Example inventory entries:
241
inventory = {
242
'numpy.array': 'https://numpy.org/doc/stable/reference/generated/numpy.array.html',
243
'os.path.join': 'https://docs.python.org/3/library/os.path.html#os.path.join',
244
'matplotlib.pyplot.figure': 'https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.figure.html'
245
}
246
```
247
248
### Performance Optimization
249
250
The resolution system includes several optimizations:
251
252
```python
253
# Caching strategies:
254
# - Transform cache: Avoid re-parsing unchanged documents
255
# - Inventory cache: Reuse resolved inventory between builds
256
# - Name cache: Cache successful resolutions within a build
257
258
# Parallel processing support:
259
# - Thread-safe inventory access
260
# - Parallel document processing
261
# - Merge cached data from parallel workers
262
```
263
264
### Error Recovery
265
266
When resolution fails, the system provides fallback strategies:
267
268
```python
269
# Graceful degradation:
270
# 1. Try exact name match in inventory
271
# 2. Try parent module/class lookup
272
# 3. Try common alias mappings
273
# 4. Generate warning if configured
274
# 5. Skip link generation for unresolved names
275
276
# Partial resolution:
277
# Even if full chain fails, successfully resolved prefixes
278
# may still generate useful links (e.g., 'numpy.array.shape'
279
# may link 'numpy.array' even if 'shape' resolution fails)
280
```