mirror of
https://github.com/sphinx-doc/sphinx.git
synced 2025-02-25 18:55:22 -06:00
Merge pull request #9017 from tk0miya/refactor_vartypes_domains
refactor: Use PEP-526 based variable annotation (sphinx.domains)
This commit is contained in:
commit
09a037006c
@ -50,8 +50,8 @@ class ObjType:
|
|||||||
|
|
||||||
def __init__(self, lname: str, *roles: Any, **attrs: Any) -> None:
|
def __init__(self, lname: str, *roles: Any, **attrs: Any) -> None:
|
||||||
self.lname = lname
|
self.lname = lname
|
||||||
self.roles = roles # type: Tuple
|
self.roles: Tuple = roles
|
||||||
self.attrs = self.known_attrs.copy() # type: Dict
|
self.attrs: Dict = self.known_attrs.copy()
|
||||||
self.attrs.update(attrs)
|
self.attrs.update(attrs)
|
||||||
|
|
||||||
|
|
||||||
@ -88,9 +88,9 @@ class Index(ABC):
|
|||||||
:rst:role:`ref` role.
|
:rst:role:`ref` role.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
name = None # type: str
|
name: str = None
|
||||||
localname = None # type: str
|
localname: str = None
|
||||||
shortname = None # type: str
|
shortname: str = None
|
||||||
|
|
||||||
def __init__(self, domain: "Domain") -> None:
|
def __init__(self, domain: "Domain") -> None:
|
||||||
if self.name is None or self.localname is None:
|
if self.name is None or self.localname is None:
|
||||||
@ -181,31 +181,31 @@ class Domain:
|
|||||||
#: domain label: longer, more descriptive (used in messages)
|
#: domain label: longer, more descriptive (used in messages)
|
||||||
label = ''
|
label = ''
|
||||||
#: type (usually directive) name -> ObjType instance
|
#: type (usually directive) name -> ObjType instance
|
||||||
object_types = {} # type: Dict[str, ObjType]
|
object_types: Dict[str, ObjType] = {}
|
||||||
#: directive name -> directive class
|
#: directive name -> directive class
|
||||||
directives = {} # type: Dict[str, Any]
|
directives: Dict[str, Any] = {}
|
||||||
#: role name -> role callable
|
#: role name -> role callable
|
||||||
roles = {} # type: Dict[str, Union[RoleFunction, XRefRole]]
|
roles: Dict[str, Union[RoleFunction, XRefRole]] = {}
|
||||||
#: a list of Index subclasses
|
#: a list of Index subclasses
|
||||||
indices = [] # type: List[Type[Index]]
|
indices: List[Type[Index]] = []
|
||||||
#: role name -> a warning message if reference is missing
|
#: role name -> a warning message if reference is missing
|
||||||
dangling_warnings = {} # type: Dict[str, str]
|
dangling_warnings: Dict[str, str] = {}
|
||||||
#: node_class -> (enum_node_type, title_getter)
|
#: node_class -> (enum_node_type, title_getter)
|
||||||
enumerable_nodes = {} # type: Dict[Type[Node], Tuple[str, Callable]]
|
enumerable_nodes: Dict[Type[Node], Tuple[str, Callable]] = {}
|
||||||
|
|
||||||
#: data value for a fresh environment
|
#: data value for a fresh environment
|
||||||
initial_data = {} # type: Dict
|
initial_data: Dict = {}
|
||||||
#: data value
|
#: data value
|
||||||
data = None # type: Dict
|
data: Dict = None
|
||||||
#: data version, bump this when the format of `self.data` changes
|
#: data version, bump this when the format of `self.data` changes
|
||||||
data_version = 0
|
data_version = 0
|
||||||
|
|
||||||
def __init__(self, env: "BuildEnvironment") -> None:
|
def __init__(self, env: "BuildEnvironment") -> None:
|
||||||
self.env = env # type: BuildEnvironment
|
self.env: BuildEnvironment = env
|
||||||
self._role_cache = {} # type: Dict[str, Callable]
|
self._role_cache: Dict[str, Callable] = {}
|
||||||
self._directive_cache = {} # type: Dict[str, Callable]
|
self._directive_cache: Dict[str, Callable] = {}
|
||||||
self._role2type = {} # type: Dict[str, List[str]]
|
self._role2type: Dict[str, List[str]] = {}
|
||||||
self._type2role = {} # type: Dict[str, str]
|
self._type2role: Dict[str, str] = {}
|
||||||
|
|
||||||
# convert class variables to instance one (to enhance through API)
|
# convert class variables to instance one (to enhance through API)
|
||||||
self.object_types = dict(self.object_types)
|
self.object_types = dict(self.object_types)
|
||||||
@ -226,8 +226,8 @@ class Domain:
|
|||||||
for rolename in obj.roles:
|
for rolename in obj.roles:
|
||||||
self._role2type.setdefault(rolename, []).append(name)
|
self._role2type.setdefault(rolename, []).append(name)
|
||||||
self._type2role[name] = obj.roles[0] if obj.roles else ''
|
self._type2role[name] = obj.roles[0] if obj.roles else ''
|
||||||
self.objtypes_for_role = self._role2type.get # type: Callable[[str], List[str]]
|
self.objtypes_for_role: Callable[[str], List[str]] = self._role2type.get
|
||||||
self.role_for_objtype = self._type2role.get # type: Callable[[str], str]
|
self.role_for_objtype: Callable[[str], str] = self._type2role.get
|
||||||
|
|
||||||
def setup(self) -> None:
|
def setup(self) -> None:
|
||||||
"""Set up domain object."""
|
"""Set up domain object."""
|
||||||
|
@ -725,7 +725,7 @@ class ASTDeclSpecsSimple(ASTBaseBase):
|
|||||||
self.attrs + other.attrs)
|
self.attrs + other.attrs)
|
||||||
|
|
||||||
def _stringify(self, transform: StringifyTransform) -> str:
|
def _stringify(self, transform: StringifyTransform) -> str:
|
||||||
res = [] # type: List[str]
|
res: List[str] = []
|
||||||
res.extend(transform(attr) for attr in self.attrs)
|
res.extend(transform(attr) for attr in self.attrs)
|
||||||
if self.storage:
|
if self.storage:
|
||||||
res.append(self.storage)
|
res.append(self.storage)
|
||||||
@ -779,7 +779,7 @@ class ASTDeclSpecs(ASTBase):
|
|||||||
self.trailingTypeSpec = trailing
|
self.trailingTypeSpec = trailing
|
||||||
|
|
||||||
def _stringify(self, transform: StringifyTransform) -> str:
|
def _stringify(self, transform: StringifyTransform) -> str:
|
||||||
res = [] # type: List[str]
|
res: List[str] = []
|
||||||
l = transform(self.leftSpecs)
|
l = transform(self.leftSpecs)
|
||||||
if len(l) > 0:
|
if len(l) > 0:
|
||||||
res.append(l)
|
res.append(l)
|
||||||
@ -797,7 +797,7 @@ class ASTDeclSpecs(ASTBase):
|
|||||||
def describe_signature(self, signode: TextElement, mode: str,
|
def describe_signature(self, signode: TextElement, mode: str,
|
||||||
env: "BuildEnvironment", symbol: "Symbol") -> None:
|
env: "BuildEnvironment", symbol: "Symbol") -> None:
|
||||||
verify_description_mode(mode)
|
verify_description_mode(mode)
|
||||||
modifiers = [] # type: List[Node]
|
modifiers: List[Node] = []
|
||||||
|
|
||||||
def _add(modifiers: List[Node], text: str) -> None:
|
def _add(modifiers: List[Node], text: str) -> None:
|
||||||
if len(modifiers) > 0:
|
if len(modifiers) > 0:
|
||||||
@ -1369,9 +1369,9 @@ class ASTDeclaration(ASTBaseBase):
|
|||||||
self.declaration = declaration
|
self.declaration = declaration
|
||||||
self.semicolon = semicolon
|
self.semicolon = semicolon
|
||||||
|
|
||||||
self.symbol = None # type: Symbol
|
self.symbol: Symbol = None
|
||||||
# set by CObject._add_enumerator_to_parent
|
# set by CObject._add_enumerator_to_parent
|
||||||
self.enumeratorScopedSymbol = None # type: Symbol
|
self.enumeratorScopedSymbol: Symbol = None
|
||||||
|
|
||||||
def clone(self) -> "ASTDeclaration":
|
def clone(self) -> "ASTDeclaration":
|
||||||
return ASTDeclaration(self.objectType, self.directiveType,
|
return ASTDeclaration(self.objectType, self.directiveType,
|
||||||
@ -1503,8 +1503,8 @@ class Symbol:
|
|||||||
declaration: ASTDeclaration, docname: str, line: int) -> None:
|
declaration: ASTDeclaration, docname: str, line: int) -> None:
|
||||||
self.parent = parent
|
self.parent = parent
|
||||||
# declarations in a single directive are linked together
|
# declarations in a single directive are linked together
|
||||||
self.siblingAbove = None # type: Symbol
|
self.siblingAbove: Symbol = None
|
||||||
self.siblingBelow = None # type: Symbol
|
self.siblingBelow: Symbol = None
|
||||||
self.ident = ident
|
self.ident = ident
|
||||||
self.declaration = declaration
|
self.declaration = declaration
|
||||||
self.docname = docname
|
self.docname = docname
|
||||||
@ -1513,8 +1513,8 @@ class Symbol:
|
|||||||
self._assert_invariants()
|
self._assert_invariants()
|
||||||
|
|
||||||
# Remember to modify Symbol.remove if modifications to the parent change.
|
# Remember to modify Symbol.remove if modifications to the parent change.
|
||||||
self._children = [] # type: List[Symbol]
|
self._children: List[Symbol] = []
|
||||||
self._anonChildren = [] # type: List[Symbol]
|
self._anonChildren: List[Symbol] = []
|
||||||
# note: _children includes _anonChildren
|
# note: _children includes _anonChildren
|
||||||
if self.parent:
|
if self.parent:
|
||||||
self.parent._children.append(self)
|
self.parent._children.append(self)
|
||||||
@ -2195,7 +2195,7 @@ class DefinitionParser(BaseParser):
|
|||||||
# "(" expression ")"
|
# "(" expression ")"
|
||||||
# id-expression -> we parse this with _parse_nested_name
|
# id-expression -> we parse this with _parse_nested_name
|
||||||
self.skip_ws()
|
self.skip_ws()
|
||||||
res = self._parse_literal() # type: ASTExpression
|
res: ASTExpression = self._parse_literal()
|
||||||
if res is not None:
|
if res is not None:
|
||||||
return res
|
return res
|
||||||
res = self._parse_paren_expression()
|
res = self._parse_paren_expression()
|
||||||
@ -2270,7 +2270,7 @@ class DefinitionParser(BaseParser):
|
|||||||
prefix = self._parse_primary_expression()
|
prefix = self._parse_primary_expression()
|
||||||
|
|
||||||
# and now parse postfixes
|
# and now parse postfixes
|
||||||
postFixes = [] # type: List[ASTPostfixOp]
|
postFixes: List[ASTPostfixOp] = []
|
||||||
while True:
|
while True:
|
||||||
self.skip_ws()
|
self.skip_ws()
|
||||||
if self.skip_string_and_ws('['):
|
if self.skip_string_and_ws('['):
|
||||||
@ -2488,7 +2488,7 @@ class DefinitionParser(BaseParser):
|
|||||||
else:
|
else:
|
||||||
# TODO: add handling of more bracket-like things, and quote handling
|
# TODO: add handling of more bracket-like things, and quote handling
|
||||||
brackets = {'(': ')', '{': '}', '[': ']'}
|
brackets = {'(': ')', '{': '}', '[': ']'}
|
||||||
symbols = [] # type: List[str]
|
symbols: List[str] = []
|
||||||
while not self.eof:
|
while not self.eof:
|
||||||
if (len(symbols) == 0 and self.current_char in end):
|
if (len(symbols) == 0 and self.current_char in end):
|
||||||
break
|
break
|
||||||
@ -2504,7 +2504,7 @@ class DefinitionParser(BaseParser):
|
|||||||
return ASTFallbackExpr(value.strip())
|
return ASTFallbackExpr(value.strip())
|
||||||
|
|
||||||
def _parse_nested_name(self) -> ASTNestedName:
|
def _parse_nested_name(self) -> ASTNestedName:
|
||||||
names = [] # type: List[Any]
|
names: List[Any] = []
|
||||||
|
|
||||||
self.skip_ws()
|
self.skip_ws()
|
||||||
rooted = False
|
rooted = False
|
||||||
@ -2857,7 +2857,7 @@ class DefinitionParser(BaseParser):
|
|||||||
return ASTInitializer(bracedInit)
|
return ASTInitializer(bracedInit)
|
||||||
|
|
||||||
if outer == 'member':
|
if outer == 'member':
|
||||||
fallbackEnd = [] # type: List[str]
|
fallbackEnd: List[str] = []
|
||||||
elif outer is None: # function parameter
|
elif outer is None: # function parameter
|
||||||
fallbackEnd = [',', ')']
|
fallbackEnd = [',', ')']
|
||||||
else:
|
else:
|
||||||
@ -3004,7 +3004,7 @@ class DefinitionParser(BaseParser):
|
|||||||
|
|
||||||
def parse_pre_v3_type_definition(self) -> ASTDeclaration:
|
def parse_pre_v3_type_definition(self) -> ASTDeclaration:
|
||||||
self.skip_ws()
|
self.skip_ws()
|
||||||
declaration = None # type: DeclarationType
|
declaration: DeclarationType = None
|
||||||
if self.skip_word('struct'):
|
if self.skip_word('struct'):
|
||||||
typ = 'struct'
|
typ = 'struct'
|
||||||
declaration = self._parse_struct()
|
declaration = self._parse_struct()
|
||||||
@ -3027,7 +3027,7 @@ class DefinitionParser(BaseParser):
|
|||||||
'macro', 'struct', 'union', 'enum', 'enumerator', 'type'):
|
'macro', 'struct', 'union', 'enum', 'enumerator', 'type'):
|
||||||
raise Exception('Internal error, unknown directiveType "%s".' % directiveType)
|
raise Exception('Internal error, unknown directiveType "%s".' % directiveType)
|
||||||
|
|
||||||
declaration = None # type: DeclarationType
|
declaration: DeclarationType = None
|
||||||
if objectType == 'member':
|
if objectType == 'member':
|
||||||
declaration = self._parse_type_with_init(named=True, outer='member')
|
declaration = self._parse_type_with_init(named=True, outer='member')
|
||||||
elif objectType == 'function':
|
elif objectType == 'function':
|
||||||
@ -3066,7 +3066,7 @@ class DefinitionParser(BaseParser):
|
|||||||
|
|
||||||
def parse_expression(self) -> Union[ASTExpression, ASTType]:
|
def parse_expression(self) -> Union[ASTExpression, ASTType]:
|
||||||
pos = self.pos
|
pos = self.pos
|
||||||
res = None # type: Union[ASTExpression, ASTType]
|
res: Union[ASTExpression, ASTType] = None
|
||||||
try:
|
try:
|
||||||
res = self._parse_expression()
|
res = self._parse_expression()
|
||||||
self.skip_ws()
|
self.skip_ws()
|
||||||
@ -3213,7 +3213,7 @@ class CObject(ObjectDescription[ASTDeclaration]):
|
|||||||
return super().run()
|
return super().run()
|
||||||
|
|
||||||
def handle_signature(self, sig: str, signode: TextElement) -> ASTDeclaration:
|
def handle_signature(self, sig: str, signode: TextElement) -> ASTDeclaration:
|
||||||
parentSymbol = self.env.temp_data['c:parent_symbol'] # type: Symbol
|
parentSymbol: Symbol = self.env.temp_data['c:parent_symbol']
|
||||||
|
|
||||||
parser = DefinitionParser(sig, location=signode, config=self.env.config)
|
parser = DefinitionParser(sig, location=signode, config=self.env.config)
|
||||||
try:
|
try:
|
||||||
@ -3277,10 +3277,10 @@ class CObject(ObjectDescription[ASTDeclaration]):
|
|||||||
return ast
|
return ast
|
||||||
|
|
||||||
def before_content(self) -> None:
|
def before_content(self) -> None:
|
||||||
lastSymbol = self.env.temp_data['c:last_symbol'] # type: Symbol
|
lastSymbol: Symbol = self.env.temp_data['c:last_symbol']
|
||||||
assert lastSymbol
|
assert lastSymbol
|
||||||
self.oldParentSymbol = self.env.temp_data['c:parent_symbol']
|
self.oldParentSymbol = self.env.temp_data['c:parent_symbol']
|
||||||
self.oldParentKey = self.env.ref_context['c:parent_key'] # type: LookupKey
|
self.oldParentKey: LookupKey = self.env.ref_context['c:parent_key']
|
||||||
self.env.temp_data['c:parent_symbol'] = lastSymbol
|
self.env.temp_data['c:parent_symbol'] = lastSymbol
|
||||||
self.env.ref_context['c:parent_key'] = lastSymbol.get_lookup_key()
|
self.env.ref_context['c:parent_key'] = lastSymbol.get_lookup_key()
|
||||||
|
|
||||||
@ -3351,7 +3351,7 @@ class CNamespaceObject(SphinxDirective):
|
|||||||
rootSymbol = self.env.domaindata['c']['root_symbol']
|
rootSymbol = self.env.domaindata['c']['root_symbol']
|
||||||
if self.arguments[0].strip() in ('NULL', '0', 'nullptr'):
|
if self.arguments[0].strip() in ('NULL', '0', 'nullptr'):
|
||||||
symbol = rootSymbol
|
symbol = rootSymbol
|
||||||
stack = [] # type: List[Symbol]
|
stack: List[Symbol] = []
|
||||||
else:
|
else:
|
||||||
parser = DefinitionParser(self.arguments[0],
|
parser = DefinitionParser(self.arguments[0],
|
||||||
location=self.get_source_info(),
|
location=self.get_source_info(),
|
||||||
@ -3462,7 +3462,7 @@ class AliasTransform(SphinxTransform):
|
|||||||
maxdepth -= 1
|
maxdepth -= 1
|
||||||
recurse = True
|
recurse = True
|
||||||
|
|
||||||
nodes = [] # type: List[Node]
|
nodes: List[Node] = []
|
||||||
if not skipThis:
|
if not skipThis:
|
||||||
signode = addnodes.desc_signature('', '')
|
signode = addnodes.desc_signature('', '')
|
||||||
nodes.append(signode)
|
nodes.append(signode)
|
||||||
@ -3470,7 +3470,7 @@ class AliasTransform(SphinxTransform):
|
|||||||
|
|
||||||
if recurse:
|
if recurse:
|
||||||
if skipThis:
|
if skipThis:
|
||||||
childContainer = nodes # type: Union[List[Node], addnodes.desc]
|
childContainer: Union[List[Node], addnodes.desc] = nodes
|
||||||
else:
|
else:
|
||||||
content = addnodes.desc_content()
|
content = addnodes.desc_content()
|
||||||
desc = addnodes.desc()
|
desc = addnodes.desc()
|
||||||
@ -3516,8 +3516,8 @@ class AliasTransform(SphinxTransform):
|
|||||||
node.replace_self(signode)
|
node.replace_self(signode)
|
||||||
continue
|
continue
|
||||||
|
|
||||||
rootSymbol = self.env.domains['c'].data['root_symbol'] # type: Symbol
|
rootSymbol: Symbol = self.env.domains['c'].data['root_symbol']
|
||||||
parentSymbol = rootSymbol.direct_lookup(parentKey) # type: Symbol
|
parentSymbol: Symbol = rootSymbol.direct_lookup(parentKey)
|
||||||
if not parentSymbol:
|
if not parentSymbol:
|
||||||
print("Target: ", sig)
|
print("Target: ", sig)
|
||||||
print("ParentKey: ", parentKey)
|
print("ParentKey: ", parentKey)
|
||||||
@ -3583,7 +3583,7 @@ class CAliasObject(ObjectDescription):
|
|||||||
node['objtype'] = node['desctype'] = self.objtype
|
node['objtype'] = node['desctype'] = self.objtype
|
||||||
node['noindex'] = True
|
node['noindex'] = True
|
||||||
|
|
||||||
self.names = [] # type: List[str]
|
self.names: List[str] = []
|
||||||
aliasOptions = {
|
aliasOptions = {
|
||||||
'maxdepth': self.options.get('maxdepth', 1),
|
'maxdepth': self.options.get('maxdepth', 1),
|
||||||
'noroot': 'noroot' in self.options,
|
'noroot': 'noroot' in self.options,
|
||||||
@ -3661,7 +3661,7 @@ class CExprRole(SphinxRole):
|
|||||||
if asCode:
|
if asCode:
|
||||||
# render the expression as inline code
|
# render the expression as inline code
|
||||||
self.class_type = 'c-expr'
|
self.class_type = 'c-expr'
|
||||||
self.node_type = nodes.literal # type: Type[TextElement]
|
self.node_type: Type[TextElement] = nodes.literal
|
||||||
else:
|
else:
|
||||||
# render the expression as inline text
|
# render the expression as inline text
|
||||||
self.class_type = 'c-texpr'
|
self.class_type = 'c-texpr'
|
||||||
@ -3740,10 +3740,10 @@ class CDomain(Domain):
|
|||||||
'expr': CExprRole(asCode=True),
|
'expr': CExprRole(asCode=True),
|
||||||
'texpr': CExprRole(asCode=False)
|
'texpr': CExprRole(asCode=False)
|
||||||
}
|
}
|
||||||
initial_data = {
|
initial_data: Dict[str, Union[Symbol, Dict[str, Tuple[str, str, str]]]] = {
|
||||||
'root_symbol': Symbol(None, None, None, None, None),
|
'root_symbol': Symbol(None, None, None, None, None),
|
||||||
'objects': {}, # fullname -> docname, node_id, objtype
|
'objects': {}, # fullname -> docname, node_id, objtype
|
||||||
} # type: Dict[str, Union[Symbol, Dict[str, Tuple[str, str, str]]]]
|
}
|
||||||
|
|
||||||
def clear_doc(self, docname: str) -> None:
|
def clear_doc(self, docname: str) -> None:
|
||||||
if Symbol.debug_show_tree:
|
if Symbol.debug_show_tree:
|
||||||
@ -3801,10 +3801,10 @@ class CDomain(Domain):
|
|||||||
logger.warning('Unparseable C cross-reference: %r\n%s', target, e,
|
logger.warning('Unparseable C cross-reference: %r\n%s', target, e,
|
||||||
location=node)
|
location=node)
|
||||||
return None, None
|
return None, None
|
||||||
parentKey = node.get("c:parent_key", None) # type: LookupKey
|
parentKey: LookupKey = node.get("c:parent_key", None)
|
||||||
rootSymbol = self.data['root_symbol']
|
rootSymbol = self.data['root_symbol']
|
||||||
if parentKey:
|
if parentKey:
|
||||||
parentSymbol = rootSymbol.direct_lookup(parentKey) # type: Symbol
|
parentSymbol: Symbol = rootSymbol.direct_lookup(parentKey)
|
||||||
if not parentSymbol:
|
if not parentSymbol:
|
||||||
print("Target: ", target)
|
print("Target: ", target)
|
||||||
print("ParentKey: ", parentKey)
|
print("ParentKey: ", parentKey)
|
||||||
|
@ -94,7 +94,7 @@ class VersionChange(SphinxDirective):
|
|||||||
domain = cast(ChangeSetDomain, self.env.get_domain('changeset'))
|
domain = cast(ChangeSetDomain, self.env.get_domain('changeset'))
|
||||||
domain.note_changeset(node)
|
domain.note_changeset(node)
|
||||||
|
|
||||||
ret = [node] # type: List[Node]
|
ret: List[Node] = [node]
|
||||||
ret += messages
|
ret += messages
|
||||||
return ret
|
return ret
|
||||||
|
|
||||||
@ -105,9 +105,9 @@ class ChangeSetDomain(Domain):
|
|||||||
name = 'changeset'
|
name = 'changeset'
|
||||||
label = 'changeset'
|
label = 'changeset'
|
||||||
|
|
||||||
initial_data = {
|
initial_data: Dict = {
|
||||||
'changes': {}, # version -> list of ChangeSet
|
'changes': {}, # version -> list of ChangeSet
|
||||||
} # type: Dict
|
}
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def changesets(self) -> Dict[str, List[ChangeSet]]:
|
def changesets(self) -> Dict[str, List[ChangeSet]]:
|
||||||
|
@ -518,10 +518,10 @@ _id_operator_unary_v2 = {
|
|||||||
'!': 'nt', 'not': 'nt',
|
'!': 'nt', 'not': 'nt',
|
||||||
'~': 'co', 'compl': 'co'
|
'~': 'co', 'compl': 'co'
|
||||||
}
|
}
|
||||||
_id_char_from_prefix = {
|
_id_char_from_prefix: Dict[Optional[str], str] = {
|
||||||
None: 'c', 'u8': 'c',
|
None: 'c', 'u8': 'c',
|
||||||
'u': 'Ds', 'U': 'Di', 'L': 'w'
|
'u': 'Ds', 'U': 'Di', 'L': 'w'
|
||||||
} # type: Dict[Any, str]
|
}
|
||||||
# these are ordered by preceedence
|
# these are ordered by preceedence
|
||||||
_expression_bin_ops = [
|
_expression_bin_ops = [
|
||||||
['||', 'or'],
|
['||', 'or'],
|
||||||
@ -751,7 +751,7 @@ class ASTNestedName(ASTBase):
|
|||||||
# prefix. however, only the identifier part should be a link, such
|
# prefix. however, only the identifier part should be a link, such
|
||||||
# that template args can be a link as well.
|
# that template args can be a link as well.
|
||||||
# For 'lastIsName' we should also prepend template parameter lists.
|
# For 'lastIsName' we should also prepend template parameter lists.
|
||||||
templateParams = [] # type: List[Any]
|
templateParams: List[Any] = []
|
||||||
if mode == 'lastIsName':
|
if mode == 'lastIsName':
|
||||||
assert symbol is not None
|
assert symbol is not None
|
||||||
if symbol.declaration.templatePrefix is not None:
|
if symbol.declaration.templatePrefix is not None:
|
||||||
@ -2057,7 +2057,7 @@ class ASTDeclSpecsSimple(ASTBase):
|
|||||||
self.attrs + other.attrs)
|
self.attrs + other.attrs)
|
||||||
|
|
||||||
def _stringify(self, transform: StringifyTransform) -> str:
|
def _stringify(self, transform: StringifyTransform) -> str:
|
||||||
res = [] # type: List[str]
|
res: List[str] = []
|
||||||
res.extend(transform(attr) for attr in self.attrs)
|
res.extend(transform(attr) for attr in self.attrs)
|
||||||
if self.storage:
|
if self.storage:
|
||||||
res.append(self.storage)
|
res.append(self.storage)
|
||||||
@ -2144,7 +2144,7 @@ class ASTDeclSpecs(ASTBase):
|
|||||||
return ''.join(res)
|
return ''.join(res)
|
||||||
|
|
||||||
def _stringify(self, transform: StringifyTransform) -> str:
|
def _stringify(self, transform: StringifyTransform) -> str:
|
||||||
res = [] # type: List[str]
|
res: List[str] = []
|
||||||
l = transform(self.leftSpecs)
|
l = transform(self.leftSpecs)
|
||||||
if len(l) > 0:
|
if len(l) > 0:
|
||||||
res.append(l)
|
res.append(l)
|
||||||
@ -3635,9 +3635,9 @@ class ASTDeclaration(ASTBase):
|
|||||||
self.trailingRequiresClause = trailingRequiresClause
|
self.trailingRequiresClause = trailingRequiresClause
|
||||||
self.semicolon = semicolon
|
self.semicolon = semicolon
|
||||||
|
|
||||||
self.symbol = None # type: Symbol
|
self.symbol: Symbol = None
|
||||||
# set by CPPObject._add_enumerator_to_parent
|
# set by CPPObject._add_enumerator_to_parent
|
||||||
self.enumeratorScopedSymbol = None # type: Symbol
|
self.enumeratorScopedSymbol: Symbol = None
|
||||||
|
|
||||||
def clone(self) -> "ASTDeclaration":
|
def clone(self) -> "ASTDeclaration":
|
||||||
templatePrefixClone = self.templatePrefix.clone() if self.templatePrefix else None
|
templatePrefixClone = self.templatePrefix.clone() if self.templatePrefix else None
|
||||||
@ -3857,8 +3857,8 @@ class Symbol:
|
|||||||
docname: str, line: int) -> None:
|
docname: str, line: int) -> None:
|
||||||
self.parent = parent
|
self.parent = parent
|
||||||
# declarations in a single directive are linked together
|
# declarations in a single directive are linked together
|
||||||
self.siblingAbove = None # type: Symbol
|
self.siblingAbove: Symbol = None
|
||||||
self.siblingBelow = None # type: Symbol
|
self.siblingBelow: Symbol = None
|
||||||
self.identOrOp = identOrOp
|
self.identOrOp = identOrOp
|
||||||
self.templateParams = templateParams # template<templateParams>
|
self.templateParams = templateParams # template<templateParams>
|
||||||
self.templateArgs = templateArgs # identifier<templateArgs>
|
self.templateArgs = templateArgs # identifier<templateArgs>
|
||||||
@ -3869,8 +3869,8 @@ class Symbol:
|
|||||||
self._assert_invariants()
|
self._assert_invariants()
|
||||||
|
|
||||||
# Remember to modify Symbol.remove if modifications to the parent change.
|
# Remember to modify Symbol.remove if modifications to the parent change.
|
||||||
self._children = [] # type: List[Symbol]
|
self._children: List[Symbol] = []
|
||||||
self._anonChildren = [] # type: List[Symbol]
|
self._anonChildren: List[Symbol] = []
|
||||||
# note: _children includes _anonChildren
|
# note: _children includes _anonChildren
|
||||||
if self.parent:
|
if self.parent:
|
||||||
self.parent._children.append(self)
|
self.parent._children.append(self)
|
||||||
@ -3940,7 +3940,7 @@ class Symbol:
|
|||||||
self.parent = None
|
self.parent = None
|
||||||
|
|
||||||
def clear_doc(self, docname: str) -> None:
|
def clear_doc(self, docname: str) -> None:
|
||||||
newChildren = [] # type: List[Symbol]
|
newChildren: List[Symbol] = []
|
||||||
for sChild in self._children:
|
for sChild in self._children:
|
||||||
sChild.clear_doc(docname)
|
sChild.clear_doc(docname)
|
||||||
if sChild.declaration and sChild.docname == docname:
|
if sChild.declaration and sChild.docname == docname:
|
||||||
@ -4972,7 +4972,7 @@ class DefinitionParser(BaseParser):
|
|||||||
# fold-expression
|
# fold-expression
|
||||||
# id-expression -> we parse this with _parse_nested_name
|
# id-expression -> we parse this with _parse_nested_name
|
||||||
self.skip_ws()
|
self.skip_ws()
|
||||||
res = self._parse_literal() # type: ASTExpression
|
res: ASTExpression = self._parse_literal()
|
||||||
if res is not None:
|
if res is not None:
|
||||||
return res
|
return res
|
||||||
self.skip_ws()
|
self.skip_ws()
|
||||||
@ -5000,7 +5000,7 @@ class DefinitionParser(BaseParser):
|
|||||||
if self.skip_string(close):
|
if self.skip_string(close):
|
||||||
return [], False
|
return [], False
|
||||||
|
|
||||||
exprs = [] # type: List[Union[ASTExpression, ASTBracedInitList]]
|
exprs: List[Union[ASTExpression, ASTBracedInitList]] = []
|
||||||
trailingComma = False
|
trailingComma = False
|
||||||
while True:
|
while True:
|
||||||
self.skip_ws()
|
self.skip_ws()
|
||||||
@ -5079,7 +5079,7 @@ class DefinitionParser(BaseParser):
|
|||||||
# | "typeid" "(" type-id ")"
|
# | "typeid" "(" type-id ")"
|
||||||
|
|
||||||
prefixType = None
|
prefixType = None
|
||||||
prefix = None # type: Any
|
prefix: Any = None
|
||||||
self.skip_ws()
|
self.skip_ws()
|
||||||
|
|
||||||
cast = None
|
cast = None
|
||||||
@ -5162,7 +5162,7 @@ class DefinitionParser(BaseParser):
|
|||||||
raise self._make_multi_error(errors, header) from eInner
|
raise self._make_multi_error(errors, header) from eInner
|
||||||
|
|
||||||
# and now parse postfixes
|
# and now parse postfixes
|
||||||
postFixes = [] # type: List[ASTPostfixOp]
|
postFixes: List[ASTPostfixOp] = []
|
||||||
while True:
|
while True:
|
||||||
self.skip_ws()
|
self.skip_ws()
|
||||||
if prefixType in ['expr', 'cast', 'typeid']:
|
if prefixType in ['expr', 'cast', 'typeid']:
|
||||||
@ -5392,7 +5392,7 @@ class DefinitionParser(BaseParser):
|
|||||||
# logical-or-expression
|
# logical-or-expression
|
||||||
# | logical-or-expression "?" expression ":" assignment-expression
|
# | logical-or-expression "?" expression ":" assignment-expression
|
||||||
# | logical-or-expression assignment-operator initializer-clause
|
# | logical-or-expression assignment-operator initializer-clause
|
||||||
exprs = [] # type: List[Union[ASTExpression, ASTBracedInitList]]
|
exprs: List[Union[ASTExpression, ASTBracedInitList]] = []
|
||||||
ops = []
|
ops = []
|
||||||
orExpr = self._parse_logical_or_expression(inTemplate=inTemplate)
|
orExpr = self._parse_logical_or_expression(inTemplate=inTemplate)
|
||||||
exprs.append(orExpr)
|
exprs.append(orExpr)
|
||||||
@ -5465,7 +5465,7 @@ class DefinitionParser(BaseParser):
|
|||||||
else:
|
else:
|
||||||
# TODO: add handling of more bracket-like things, and quote handling
|
# TODO: add handling of more bracket-like things, and quote handling
|
||||||
brackets = {'(': ')', '{': '}', '[': ']', '<': '>'}
|
brackets = {'(': ')', '{': '}', '[': ']', '<': '>'}
|
||||||
symbols = [] # type: List[str]
|
symbols: List[str] = []
|
||||||
while not self.eof:
|
while not self.eof:
|
||||||
if (len(symbols) == 0 and self.current_char in end):
|
if (len(symbols) == 0 and self.current_char in end):
|
||||||
break
|
break
|
||||||
@ -5528,7 +5528,7 @@ class DefinitionParser(BaseParser):
|
|||||||
if self.skip_string('>'):
|
if self.skip_string('>'):
|
||||||
return ASTTemplateArgs([], False)
|
return ASTTemplateArgs([], False)
|
||||||
prevErrors = []
|
prevErrors = []
|
||||||
templateArgs = [] # type: List[Union[ASTType, ASTTemplateArgConstant]]
|
templateArgs: List[Union[ASTType, ASTTemplateArgConstant]] = []
|
||||||
packExpansion = False
|
packExpansion = False
|
||||||
while 1:
|
while 1:
|
||||||
pos = self.pos
|
pos = self.pos
|
||||||
@ -5580,8 +5580,8 @@ class DefinitionParser(BaseParser):
|
|||||||
return ASTTemplateArgs(templateArgs, packExpansion)
|
return ASTTemplateArgs(templateArgs, packExpansion)
|
||||||
|
|
||||||
def _parse_nested_name(self, memberPointer: bool = False) -> ASTNestedName:
|
def _parse_nested_name(self, memberPointer: bool = False) -> ASTNestedName:
|
||||||
names = [] # type: List[ASTNestedNameElement]
|
names: List[ASTNestedNameElement] = []
|
||||||
templates = [] # type: List[bool]
|
templates: List[bool] = []
|
||||||
|
|
||||||
self.skip_ws()
|
self.skip_ws()
|
||||||
rooted = False
|
rooted = False
|
||||||
@ -5594,7 +5594,7 @@ class DefinitionParser(BaseParser):
|
|||||||
else:
|
else:
|
||||||
template = False
|
template = False
|
||||||
templates.append(template)
|
templates.append(template)
|
||||||
identOrOp = None # type: Union[ASTIdentifier, ASTOperator]
|
identOrOp: Union[ASTIdentifier, ASTOperator] = None
|
||||||
if self.skip_word_and_ws('operator'):
|
if self.skip_word_and_ws('operator'):
|
||||||
identOrOp = self._parse_operator()
|
identOrOp = self._parse_operator()
|
||||||
else:
|
else:
|
||||||
@ -6097,7 +6097,7 @@ class DefinitionParser(BaseParser):
|
|||||||
return ASTInitializer(bracedInit)
|
return ASTInitializer(bracedInit)
|
||||||
|
|
||||||
if outer == 'member':
|
if outer == 'member':
|
||||||
fallbackEnd = [] # type: List[str]
|
fallbackEnd: List[str] = []
|
||||||
elif outer == 'templateParam':
|
elif outer == 'templateParam':
|
||||||
fallbackEnd = [',', '>']
|
fallbackEnd = [',', '>']
|
||||||
elif outer is None: # function parameter
|
elif outer is None: # function parameter
|
||||||
@ -6376,7 +6376,7 @@ class DefinitionParser(BaseParser):
|
|||||||
def _parse_template_parameter_list(self) -> ASTTemplateParams:
|
def _parse_template_parameter_list(self) -> ASTTemplateParams:
|
||||||
# only: '<' parameter-list '>'
|
# only: '<' parameter-list '>'
|
||||||
# we assume that 'template' has just been parsed
|
# we assume that 'template' has just been parsed
|
||||||
templateParams = [] # type: List[ASTTemplateParam]
|
templateParams: List[ASTTemplateParam] = []
|
||||||
self.skip_ws()
|
self.skip_ws()
|
||||||
if not self.skip_string("<"):
|
if not self.skip_string("<"):
|
||||||
self.fail("Expected '<' after 'template'")
|
self.fail("Expected '<' after 'template'")
|
||||||
@ -6499,11 +6499,11 @@ class DefinitionParser(BaseParser):
|
|||||||
|
|
||||||
def _parse_template_declaration_prefix(self, objectType: str
|
def _parse_template_declaration_prefix(self, objectType: str
|
||||||
) -> Optional[ASTTemplateDeclarationPrefix]:
|
) -> Optional[ASTTemplateDeclarationPrefix]:
|
||||||
templates = [] # type: List[Union[ASTTemplateParams, ASTTemplateIntroduction]]
|
templates: List[Union[ASTTemplateParams, ASTTemplateIntroduction]] = []
|
||||||
while 1:
|
while 1:
|
||||||
self.skip_ws()
|
self.skip_ws()
|
||||||
# the saved position is only used to provide a better error message
|
# the saved position is only used to provide a better error message
|
||||||
params = None # type: Union[ASTTemplateParams, ASTTemplateIntroduction]
|
params: Union[ASTTemplateParams, ASTTemplateIntroduction] = None
|
||||||
pos = self.pos
|
pos = self.pos
|
||||||
if self.skip_word("template"):
|
if self.skip_word("template"):
|
||||||
try:
|
try:
|
||||||
@ -6559,7 +6559,7 @@ class DefinitionParser(BaseParser):
|
|||||||
msg += str(nestedName)
|
msg += str(nestedName)
|
||||||
self.warn(msg)
|
self.warn(msg)
|
||||||
|
|
||||||
newTemplates = [] # type: List[Union[ASTTemplateParams, ASTTemplateIntroduction]]
|
newTemplates: List[Union[ASTTemplateParams, ASTTemplateIntroduction]] = []
|
||||||
for i in range(numExtra):
|
for i in range(numExtra):
|
||||||
newTemplates.append(ASTTemplateParams([]))
|
newTemplates.append(ASTTemplateParams([]))
|
||||||
if templatePrefix and not isMemberInstantiation:
|
if templatePrefix and not isMemberInstantiation:
|
||||||
@ -6579,7 +6579,7 @@ class DefinitionParser(BaseParser):
|
|||||||
templatePrefix = None
|
templatePrefix = None
|
||||||
requiresClause = None
|
requiresClause = None
|
||||||
trailingRequiresClause = None
|
trailingRequiresClause = None
|
||||||
declaration = None # type: Any
|
declaration: Any = None
|
||||||
|
|
||||||
self.skip_ws()
|
self.skip_ws()
|
||||||
if self.match(_visibility_re):
|
if self.match(_visibility_re):
|
||||||
@ -6878,7 +6878,7 @@ class CPPObject(ObjectDescription[ASTDeclaration]):
|
|||||||
return super().run()
|
return super().run()
|
||||||
|
|
||||||
def handle_signature(self, sig: str, signode: desc_signature) -> ASTDeclaration:
|
def handle_signature(self, sig: str, signode: desc_signature) -> ASTDeclaration:
|
||||||
parentSymbol = self.env.temp_data['cpp:parent_symbol'] # type: Symbol
|
parentSymbol: Symbol = self.env.temp_data['cpp:parent_symbol']
|
||||||
|
|
||||||
parser = DefinitionParser(sig, location=signode, config=self.env.config)
|
parser = DefinitionParser(sig, location=signode, config=self.env.config)
|
||||||
try:
|
try:
|
||||||
@ -6925,10 +6925,10 @@ class CPPObject(ObjectDescription[ASTDeclaration]):
|
|||||||
return ast
|
return ast
|
||||||
|
|
||||||
def before_content(self) -> None:
|
def before_content(self) -> None:
|
||||||
lastSymbol = self.env.temp_data['cpp:last_symbol'] # type: Symbol
|
lastSymbol: Symbol = self.env.temp_data['cpp:last_symbol']
|
||||||
assert lastSymbol
|
assert lastSymbol
|
||||||
self.oldParentSymbol = self.env.temp_data['cpp:parent_symbol']
|
self.oldParentSymbol = self.env.temp_data['cpp:parent_symbol']
|
||||||
self.oldParentKey = self.env.ref_context['cpp:parent_key'] # type: LookupKey
|
self.oldParentKey: LookupKey = self.env.ref_context['cpp:parent_key']
|
||||||
self.env.temp_data['cpp:parent_symbol'] = lastSymbol
|
self.env.temp_data['cpp:parent_symbol'] = lastSymbol
|
||||||
self.env.ref_context['cpp:parent_key'] = lastSymbol.get_lookup_key()
|
self.env.ref_context['cpp:parent_key'] = lastSymbol.get_lookup_key()
|
||||||
|
|
||||||
@ -6991,7 +6991,7 @@ class CPPNamespaceObject(SphinxDirective):
|
|||||||
rootSymbol = self.env.domaindata['cpp']['root_symbol']
|
rootSymbol = self.env.domaindata['cpp']['root_symbol']
|
||||||
if self.arguments[0].strip() in ('NULL', '0', 'nullptr'):
|
if self.arguments[0].strip() in ('NULL', '0', 'nullptr'):
|
||||||
symbol = rootSymbol
|
symbol = rootSymbol
|
||||||
stack = [] # type: List[Symbol]
|
stack: List[Symbol] = []
|
||||||
else:
|
else:
|
||||||
parser = DefinitionParser(self.arguments[0],
|
parser = DefinitionParser(self.arguments[0],
|
||||||
location=self.get_source_info(),
|
location=self.get_source_info(),
|
||||||
@ -7103,7 +7103,7 @@ class AliasTransform(SphinxTransform):
|
|||||||
maxdepth -= 1
|
maxdepth -= 1
|
||||||
recurse = True
|
recurse = True
|
||||||
|
|
||||||
nodes = [] # type: List[Node]
|
nodes: List[Node] = []
|
||||||
if not skipThis:
|
if not skipThis:
|
||||||
signode = addnodes.desc_signature('', '')
|
signode = addnodes.desc_signature('', '')
|
||||||
nodes.append(signode)
|
nodes.append(signode)
|
||||||
@ -7111,7 +7111,7 @@ class AliasTransform(SphinxTransform):
|
|||||||
|
|
||||||
if recurse:
|
if recurse:
|
||||||
if skipThis:
|
if skipThis:
|
||||||
childContainer = nodes # type: Union[List[Node], addnodes.desc]
|
childContainer: Union[List[Node], addnodes.desc] = nodes
|
||||||
else:
|
else:
|
||||||
content = addnodes.desc_content()
|
content = addnodes.desc_content()
|
||||||
desc = addnodes.desc()
|
desc = addnodes.desc()
|
||||||
@ -7160,15 +7160,15 @@ class AliasTransform(SphinxTransform):
|
|||||||
node.replace_self(signode)
|
node.replace_self(signode)
|
||||||
continue
|
continue
|
||||||
|
|
||||||
rootSymbol = self.env.domains['cpp'].data['root_symbol'] # type: Symbol
|
rootSymbol: Symbol = self.env.domains['cpp'].data['root_symbol']
|
||||||
parentSymbol = rootSymbol.direct_lookup(parentKey) # type: Symbol
|
parentSymbol: Symbol = rootSymbol.direct_lookup(parentKey)
|
||||||
if not parentSymbol:
|
if not parentSymbol:
|
||||||
print("Target: ", sig)
|
print("Target: ", sig)
|
||||||
print("ParentKey: ", parentKey)
|
print("ParentKey: ", parentKey)
|
||||||
print(rootSymbol.dump(1))
|
print(rootSymbol.dump(1))
|
||||||
assert parentSymbol # should be there
|
assert parentSymbol # should be there
|
||||||
|
|
||||||
symbols = [] # type: List[Symbol]
|
symbols: List[Symbol] = []
|
||||||
if isShorthand:
|
if isShorthand:
|
||||||
assert isinstance(ast, ASTNamespace)
|
assert isinstance(ast, ASTNamespace)
|
||||||
ns = ast
|
ns = ast
|
||||||
@ -7247,7 +7247,7 @@ class CPPAliasObject(ObjectDescription):
|
|||||||
# 'desctype' is a backwards compatible attribute
|
# 'desctype' is a backwards compatible attribute
|
||||||
node['objtype'] = node['desctype'] = self.objtype
|
node['objtype'] = node['desctype'] = self.objtype
|
||||||
|
|
||||||
self.names = [] # type: List[str]
|
self.names: List[str] = []
|
||||||
aliasOptions = {
|
aliasOptions = {
|
||||||
'maxdepth': self.options.get('maxdepth', 1),
|
'maxdepth': self.options.get('maxdepth', 1),
|
||||||
'noroot': 'noroot' in self.options,
|
'noroot': 'noroot' in self.options,
|
||||||
@ -7307,7 +7307,7 @@ class CPPExprRole(SphinxRole):
|
|||||||
if asCode:
|
if asCode:
|
||||||
# render the expression as inline code
|
# render the expression as inline code
|
||||||
self.class_type = 'cpp-expr'
|
self.class_type = 'cpp-expr'
|
||||||
self.node_type = nodes.literal # type: Type[TextElement]
|
self.node_type: Type[TextElement] = nodes.literal
|
||||||
else:
|
else:
|
||||||
# render the expression as inline text
|
# render the expression as inline text
|
||||||
self.class_type = 'cpp-texpr'
|
self.class_type = 'cpp-texpr'
|
||||||
@ -7488,10 +7488,10 @@ class CPPDomain(Domain):
|
|||||||
logger.warning('Unparseable C++ cross-reference: %r\n%s', t, ex,
|
logger.warning('Unparseable C++ cross-reference: %r\n%s', t, ex,
|
||||||
location=node)
|
location=node)
|
||||||
return None, None
|
return None, None
|
||||||
parentKey = node.get("cpp:parent_key", None) # type: LookupKey
|
parentKey: LookupKey = node.get("cpp:parent_key", None)
|
||||||
rootSymbol = self.data['root_symbol']
|
rootSymbol = self.data['root_symbol']
|
||||||
if parentKey:
|
if parentKey:
|
||||||
parentSymbol = rootSymbol.direct_lookup(parentKey) # type: Symbol
|
parentSymbol: Symbol = rootSymbol.direct_lookup(parentKey)
|
||||||
if not parentSymbol:
|
if not parentSymbol:
|
||||||
print("Target: ", target)
|
print("Target: ", target)
|
||||||
print("ParentKey: ", parentKey.data)
|
print("ParentKey: ", parentKey.data)
|
||||||
@ -7645,7 +7645,7 @@ class CPPDomain(Domain):
|
|||||||
target = node.get('reftarget', None)
|
target = node.get('reftarget', None)
|
||||||
if target is None:
|
if target is None:
|
||||||
return None
|
return None
|
||||||
parentKey = node.get("cpp:parent_key", None) # type: LookupKey
|
parentKey: LookupKey = node.get("cpp:parent_key", None)
|
||||||
if parentKey is None or len(parentKey.data) <= 0:
|
if parentKey is None or len(parentKey.data) <= 0:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
@ -42,7 +42,7 @@ class JSObject(ObjectDescription[Tuple[str, str]]):
|
|||||||
has_arguments = False
|
has_arguments = False
|
||||||
|
|
||||||
#: what is displayed right before the documentation entry
|
#: what is displayed right before the documentation entry
|
||||||
display_prefix = None # type: str
|
display_prefix: str = None
|
||||||
|
|
||||||
#: If ``allow_nesting`` is ``True``, the object prefixes will be accumulated
|
#: If ``allow_nesting`` is ``True``, the object prefixes will be accumulated
|
||||||
#: based on directive nesting
|
#: based on directive nesting
|
||||||
@ -262,7 +262,7 @@ class JSModule(SphinxDirective):
|
|||||||
mod_name = self.arguments[0].strip()
|
mod_name = self.arguments[0].strip()
|
||||||
self.env.ref_context['js:module'] = mod_name
|
self.env.ref_context['js:module'] = mod_name
|
||||||
noindex = 'noindex' in self.options
|
noindex = 'noindex' in self.options
|
||||||
ret = [] # type: List[Node]
|
ret: List[Node] = []
|
||||||
if not noindex:
|
if not noindex:
|
||||||
domain = cast(JavaScriptDomain, self.env.get_domain('js'))
|
domain = cast(JavaScriptDomain, self.env.get_domain('js'))
|
||||||
|
|
||||||
@ -346,10 +346,10 @@ class JavaScriptDomain(Domain):
|
|||||||
'attr': JSXRefRole(),
|
'attr': JSXRefRole(),
|
||||||
'mod': JSXRefRole(),
|
'mod': JSXRefRole(),
|
||||||
}
|
}
|
||||||
initial_data = {
|
initial_data: Dict[str, Dict[str, Tuple[str, str]]] = {
|
||||||
'objects': {}, # fullname -> docname, node_id, objtype
|
'objects': {}, # fullname -> docname, node_id, objtype
|
||||||
'modules': {}, # modname -> docname, node_id
|
'modules': {}, # modname -> docname, node_id
|
||||||
} # type: Dict[str, Dict[str, Tuple[str, str]]]
|
}
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def objects(self) -> Dict[str, Tuple[str, str, str]]:
|
def objects(self) -> Dict[str, Tuple[str, str, str]]:
|
||||||
|
@ -41,10 +41,10 @@ class MathDomain(Domain):
|
|||||||
name = 'math'
|
name = 'math'
|
||||||
label = 'mathematics'
|
label = 'mathematics'
|
||||||
|
|
||||||
initial_data = {
|
initial_data: Dict = {
|
||||||
'objects': {}, # labelid -> (docname, eqno)
|
'objects': {}, # labelid -> (docname, eqno)
|
||||||
'has_equations': {}, # docname -> bool
|
'has_equations': {}, # docname -> bool
|
||||||
} # type: Dict
|
}
|
||||||
dangling_warnings = {
|
dangling_warnings = {
|
||||||
'eq': 'equation not found: %(target)s',
|
'eq': 'equation not found: %(target)s',
|
||||||
}
|
}
|
||||||
|
@ -97,8 +97,8 @@ def type_to_xref(text: str, env: BuildEnvironment = None) -> addnodes.pending_xr
|
|||||||
# nested classes. But python domain can't access the real python object because this
|
# nested classes. But python domain can't access the real python object because this
|
||||||
# module should work not-dynamically.
|
# module should work not-dynamically.
|
||||||
shortname = text.split('.')[-1]
|
shortname = text.split('.')[-1]
|
||||||
contnodes = [pending_xref_condition('', shortname, condition='resolved'),
|
contnodes: List[Node] = [pending_xref_condition('', shortname, condition='resolved'),
|
||||||
pending_xref_condition('', text, condition='*')] # type: List[Node]
|
pending_xref_condition('', text, condition='*')]
|
||||||
else:
|
else:
|
||||||
contnodes = [nodes.Text(text)]
|
contnodes = [nodes.Text(text)]
|
||||||
|
|
||||||
@ -112,7 +112,7 @@ def _parse_annotation(annotation: str, env: BuildEnvironment = None) -> List[Nod
|
|||||||
if isinstance(node, ast.Attribute):
|
if isinstance(node, ast.Attribute):
|
||||||
return [nodes.Text("%s.%s" % (unparse(node.value)[0], node.attr))]
|
return [nodes.Text("%s.%s" % (unparse(node.value)[0], node.attr))]
|
||||||
elif isinstance(node, ast.BinOp):
|
elif isinstance(node, ast.BinOp):
|
||||||
result = unparse(node.left) # type: List[Node]
|
result: List[Node] = unparse(node.left)
|
||||||
result.extend(unparse(node.op))
|
result.extend(unparse(node.op))
|
||||||
result.extend(unparse(node.right))
|
result.extend(unparse(node.right))
|
||||||
return result
|
return result
|
||||||
@ -239,7 +239,7 @@ def _pseudo_parse_arglist(signode: desc_signature, arglist: str) -> None:
|
|||||||
string literal (e.g. default argument value).
|
string literal (e.g. default argument value).
|
||||||
"""
|
"""
|
||||||
paramlist = addnodes.desc_parameterlist()
|
paramlist = addnodes.desc_parameterlist()
|
||||||
stack = [paramlist] # type: List[Element]
|
stack: List[Element] = [paramlist]
|
||||||
try:
|
try:
|
||||||
for argument in arglist.split(','):
|
for argument in arglist.split(','):
|
||||||
argument = argument.strip()
|
argument = argument.strip()
|
||||||
@ -910,7 +910,7 @@ class PyModule(SphinxDirective):
|
|||||||
modname = self.arguments[0].strip()
|
modname = self.arguments[0].strip()
|
||||||
noindex = 'noindex' in self.options
|
noindex = 'noindex' in self.options
|
||||||
self.env.ref_context['py:module'] = modname
|
self.env.ref_context['py:module'] = modname
|
||||||
ret = [] # type: List[Node]
|
ret: List[Node] = []
|
||||||
if not noindex:
|
if not noindex:
|
||||||
# note module to the domain
|
# note module to the domain
|
||||||
node_id = make_id(self.env, self.state.document, 'module', modname)
|
node_id = make_id(self.env, self.state.document, 'module', modname)
|
||||||
@ -1021,10 +1021,9 @@ class PythonModuleIndex(Index):
|
|||||||
|
|
||||||
def generate(self, docnames: Iterable[str] = None
|
def generate(self, docnames: Iterable[str] = None
|
||||||
) -> Tuple[List[Tuple[str, List[IndexEntry]]], bool]:
|
) -> Tuple[List[Tuple[str, List[IndexEntry]]], bool]:
|
||||||
content = {} # type: Dict[str, List[IndexEntry]]
|
content: Dict[str, List[IndexEntry]] = {}
|
||||||
# list of prefixes to ignore
|
# list of prefixes to ignore
|
||||||
ignores = None # type: List[str]
|
ignores: List[str] = self.domain.env.config['modindex_common_prefix'] # type: ignore
|
||||||
ignores = self.domain.env.config['modindex_common_prefix'] # type: ignore
|
|
||||||
ignores = sorted(ignores, key=len, reverse=True)
|
ignores = sorted(ignores, key=len, reverse=True)
|
||||||
# list of all modules, sorted by module name
|
# list of all modules, sorted by module name
|
||||||
modules = sorted(self.domain.data['modules'].items(),
|
modules = sorted(self.domain.data['modules'].items(),
|
||||||
@ -1087,7 +1086,7 @@ class PythonDomain(Domain):
|
|||||||
"""Python language domain."""
|
"""Python language domain."""
|
||||||
name = 'py'
|
name = 'py'
|
||||||
label = 'Python'
|
label = 'Python'
|
||||||
object_types = {
|
object_types: Dict[str, ObjType] = {
|
||||||
'function': ObjType(_('function'), 'func', 'obj'),
|
'function': ObjType(_('function'), 'func', 'obj'),
|
||||||
'data': ObjType(_('data'), 'data', 'obj'),
|
'data': ObjType(_('data'), 'data', 'obj'),
|
||||||
'class': ObjType(_('class'), 'class', 'exc', 'obj'),
|
'class': ObjType(_('class'), 'class', 'exc', 'obj'),
|
||||||
@ -1098,7 +1097,7 @@ class PythonDomain(Domain):
|
|||||||
'attribute': ObjType(_('attribute'), 'attr', 'obj'),
|
'attribute': ObjType(_('attribute'), 'attr', 'obj'),
|
||||||
'property': ObjType(_('property'), 'attr', '_prop', 'obj'),
|
'property': ObjType(_('property'), 'attr', '_prop', 'obj'),
|
||||||
'module': ObjType(_('module'), 'mod', 'obj'),
|
'module': ObjType(_('module'), 'mod', 'obj'),
|
||||||
} # type: Dict[str, ObjType]
|
}
|
||||||
|
|
||||||
directives = {
|
directives = {
|
||||||
'function': PyFunction,
|
'function': PyFunction,
|
||||||
@ -1126,10 +1125,10 @@ class PythonDomain(Domain):
|
|||||||
'mod': PyXRefRole(),
|
'mod': PyXRefRole(),
|
||||||
'obj': PyXRefRole(),
|
'obj': PyXRefRole(),
|
||||||
}
|
}
|
||||||
initial_data = {
|
initial_data: Dict[str, Dict[str, Tuple[Any]]] = {
|
||||||
'objects': {}, # fullname -> docname, objtype
|
'objects': {}, # fullname -> docname, objtype
|
||||||
'modules': {}, # modname -> docname, synopsis, platform, deprecated
|
'modules': {}, # modname -> docname, synopsis, platform, deprecated
|
||||||
} # type: Dict[str, Dict[str, Tuple[Any]]]
|
}
|
||||||
indices = [
|
indices = [
|
||||||
PythonModuleIndex,
|
PythonModuleIndex,
|
||||||
]
|
]
|
||||||
@ -1194,7 +1193,7 @@ class PythonDomain(Domain):
|
|||||||
if not name:
|
if not name:
|
||||||
return []
|
return []
|
||||||
|
|
||||||
matches = [] # type: List[Tuple[str, ObjectEntry]]
|
matches: List[Tuple[str, ObjectEntry]] = []
|
||||||
|
|
||||||
newname = None
|
newname = None
|
||||||
if searchmode == 1:
|
if searchmode == 1:
|
||||||
@ -1285,7 +1284,7 @@ class PythonDomain(Domain):
|
|||||||
) -> List[Tuple[str, Element]]:
|
) -> List[Tuple[str, Element]]:
|
||||||
modname = node.get('py:module')
|
modname = node.get('py:module')
|
||||||
clsname = node.get('py:class')
|
clsname = node.get('py:class')
|
||||||
results = [] # type: List[Tuple[str, Element]]
|
results: List[Tuple[str, Element]] = []
|
||||||
|
|
||||||
# always search in "refspecific" mode with the :any: role
|
# always search in "refspecific" mode with the :any: role
|
||||||
matches = self.find_obj(env, modname, clsname, target, None, 1)
|
matches = self.find_obj(env, modname, clsname, target, None, 1)
|
||||||
|
@ -218,9 +218,9 @@ class ReSTDomain(Domain):
|
|||||||
'dir': XRefRole(),
|
'dir': XRefRole(),
|
||||||
'role': XRefRole(),
|
'role': XRefRole(),
|
||||||
}
|
}
|
||||||
initial_data = {
|
initial_data: Dict[str, Dict[Tuple[str, str], str]] = {
|
||||||
'objects': {}, # fullname -> docname, objtype
|
'objects': {}, # fullname -> docname, objtype
|
||||||
} # type: Dict[str, Dict[Tuple[str, str], str]]
|
}
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def objects(self) -> Dict[Tuple[str, str], Tuple[str, str]]:
|
def objects(self) -> Dict[Tuple[str, str], Tuple[str, str]]:
|
||||||
@ -259,7 +259,7 @@ class ReSTDomain(Domain):
|
|||||||
def resolve_any_xref(self, env: BuildEnvironment, fromdocname: str, builder: Builder,
|
def resolve_any_xref(self, env: BuildEnvironment, fromdocname: str, builder: Builder,
|
||||||
target: str, node: pending_xref, contnode: Element
|
target: str, node: pending_xref, contnode: Element
|
||||||
) -> List[Tuple[str, Element]]:
|
) -> List[Tuple[str, Element]]:
|
||||||
results = [] # type: List[Tuple[str, Element]]
|
results: List[Tuple[str, Element]] = []
|
||||||
for objtype in self.object_types:
|
for objtype in self.object_types:
|
||||||
todocname, node_id = self.objects.get((objtype, target), (None, None))
|
todocname, node_id = self.objects.get((objtype, target), (None, None))
|
||||||
if todocname:
|
if todocname:
|
||||||
|
@ -50,8 +50,8 @@ class GenericObject(ObjectDescription[str]):
|
|||||||
"""
|
"""
|
||||||
A generic x-ref directive registered with Sphinx.add_object_type().
|
A generic x-ref directive registered with Sphinx.add_object_type().
|
||||||
"""
|
"""
|
||||||
indextemplate = ''
|
indextemplate: str = ''
|
||||||
parse_node = None # type: Callable[[GenericObject, BuildEnvironment, str, desc_signature], str] # NOQA
|
parse_node: Callable[["GenericObject", "BuildEnvironment", str, desc_signature], str] = None # NOQA
|
||||||
|
|
||||||
def handle_signature(self, sig: str, signode: desc_signature) -> str:
|
def handle_signature(self, sig: str, signode: desc_signature) -> str:
|
||||||
if self.parse_node:
|
if self.parse_node:
|
||||||
@ -148,7 +148,7 @@ class Target(SphinxDirective):
|
|||||||
node['ids'].append(old_node_id)
|
node['ids'].append(old_node_id)
|
||||||
|
|
||||||
self.state.document.note_explicit_target(node)
|
self.state.document.note_explicit_target(node)
|
||||||
ret = [node] # type: List[Node]
|
ret: List[Node] = [node]
|
||||||
if self.indextemplate:
|
if self.indextemplate:
|
||||||
indexentry = self.indextemplate % (fullname,)
|
indexentry = self.indextemplate % (fullname,)
|
||||||
indextype = 'single'
|
indextype = 'single'
|
||||||
@ -343,11 +343,11 @@ class Glossary(SphinxDirective):
|
|||||||
# be* a definition list.
|
# be* a definition list.
|
||||||
|
|
||||||
# first, collect single entries
|
# first, collect single entries
|
||||||
entries = [] # type: List[Tuple[List[Tuple[str, str, int]], StringList]]
|
entries: List[Tuple[List[Tuple[str, str, int]], StringList]] = []
|
||||||
in_definition = True
|
in_definition = True
|
||||||
in_comment = False
|
in_comment = False
|
||||||
was_empty = True
|
was_empty = True
|
||||||
messages = [] # type: List[Node]
|
messages: List[Node] = []
|
||||||
for line, (source, lineno) in zip(self.content, self.content.items):
|
for line, (source, lineno) in zip(self.content, self.content.items):
|
||||||
# empty line -> add to last definition
|
# empty line -> add to last definition
|
||||||
if not line:
|
if not line:
|
||||||
@ -402,9 +402,9 @@ class Glossary(SphinxDirective):
|
|||||||
# now, parse all the entries into a big definition list
|
# now, parse all the entries into a big definition list
|
||||||
items = []
|
items = []
|
||||||
for terms, definition in entries:
|
for terms, definition in entries:
|
||||||
termtexts = [] # type: List[str]
|
termtexts: List[str] = []
|
||||||
termnodes = [] # type: List[Node]
|
termnodes: List[Node] = []
|
||||||
system_messages = [] # type: List[Node]
|
system_messages: List[Node] = []
|
||||||
for line, source, lineno in terms:
|
for line, source, lineno in terms:
|
||||||
parts = split_term_classifiers(line)
|
parts = split_term_classifiers(line)
|
||||||
# parse the term with inline markup
|
# parse the term with inline markup
|
||||||
@ -443,7 +443,7 @@ class Glossary(SphinxDirective):
|
|||||||
def token_xrefs(text: str, productionGroup: str = '') -> List[Node]:
|
def token_xrefs(text: str, productionGroup: str = '') -> List[Node]:
|
||||||
if len(productionGroup) != 0:
|
if len(productionGroup) != 0:
|
||||||
productionGroup += ':'
|
productionGroup += ':'
|
||||||
retnodes = [] # type: List[Node]
|
retnodes: List[Node] = []
|
||||||
pos = 0
|
pos = 0
|
||||||
for m in token_re.finditer(text):
|
for m in token_re.finditer(text):
|
||||||
if m.start() > pos:
|
if m.start() > pos:
|
||||||
@ -486,7 +486,7 @@ class ProductionList(SphinxDirective):
|
|||||||
|
|
||||||
def run(self) -> List[Node]:
|
def run(self) -> List[Node]:
|
||||||
domain = cast(StandardDomain, self.env.get_domain('std'))
|
domain = cast(StandardDomain, self.env.get_domain('std'))
|
||||||
node = addnodes.productionlist() # type: Element
|
node: Element = addnodes.productionlist()
|
||||||
self.set_source_info(node)
|
self.set_source_info(node)
|
||||||
# The backslash handling is from ObjectDescription.get_signatures
|
# The backslash handling is from ObjectDescription.get_signatures
|
||||||
nl_escape_re = re.compile(r'\\\n')
|
nl_escape_re = re.compile(r'\\\n')
|
||||||
@ -559,7 +559,7 @@ class StandardDomain(Domain):
|
|||||||
name = 'std'
|
name = 'std'
|
||||||
label = 'Default'
|
label = 'Default'
|
||||||
|
|
||||||
object_types = {
|
object_types: Dict[str, ObjType] = {
|
||||||
'term': ObjType(_('glossary term'), 'term', searchprio=-1),
|
'term': ObjType(_('glossary term'), 'term', searchprio=-1),
|
||||||
'token': ObjType(_('grammar token'), 'token', searchprio=-1),
|
'token': ObjType(_('grammar token'), 'token', searchprio=-1),
|
||||||
'label': ObjType(_('reference label'), 'ref', 'keyword',
|
'label': ObjType(_('reference label'), 'ref', 'keyword',
|
||||||
@ -567,17 +567,17 @@ class StandardDomain(Domain):
|
|||||||
'envvar': ObjType(_('environment variable'), 'envvar'),
|
'envvar': ObjType(_('environment variable'), 'envvar'),
|
||||||
'cmdoption': ObjType(_('program option'), 'option'),
|
'cmdoption': ObjType(_('program option'), 'option'),
|
||||||
'doc': ObjType(_('document'), 'doc', searchprio=-1)
|
'doc': ObjType(_('document'), 'doc', searchprio=-1)
|
||||||
} # type: Dict[str, ObjType]
|
}
|
||||||
|
|
||||||
directives = {
|
directives: Dict[str, Type[Directive]] = {
|
||||||
'program': Program,
|
'program': Program,
|
||||||
'cmdoption': Cmdoption, # old name for backwards compatibility
|
'cmdoption': Cmdoption, # old name for backwards compatibility
|
||||||
'option': Cmdoption,
|
'option': Cmdoption,
|
||||||
'envvar': EnvVar,
|
'envvar': EnvVar,
|
||||||
'glossary': Glossary,
|
'glossary': Glossary,
|
||||||
'productionlist': ProductionList,
|
'productionlist': ProductionList,
|
||||||
} # type: Dict[str, Type[Directive]]
|
}
|
||||||
roles = {
|
roles: Dict[str, Union[RoleFunction, XRefRole]] = {
|
||||||
'option': OptionXRefRole(warn_dangling=True),
|
'option': OptionXRefRole(warn_dangling=True),
|
||||||
'envvar': EnvVarXRefRole(),
|
'envvar': EnvVarXRefRole(),
|
||||||
# links to tokens in grammar productions
|
# links to tokens in grammar productions
|
||||||
@ -595,7 +595,7 @@ class StandardDomain(Domain):
|
|||||||
'keyword': XRefRole(warn_dangling=True),
|
'keyword': XRefRole(warn_dangling=True),
|
||||||
# links to documents
|
# links to documents
|
||||||
'doc': XRefRole(warn_dangling=True, innernodeclass=nodes.inline),
|
'doc': XRefRole(warn_dangling=True, innernodeclass=nodes.inline),
|
||||||
} # type: Dict[str, Union[RoleFunction, XRefRole]]
|
}
|
||||||
|
|
||||||
initial_data = {
|
initial_data = {
|
||||||
'progoptions': {}, # (program, name) -> docname, labelid
|
'progoptions': {}, # (program, name) -> docname, labelid
|
||||||
@ -620,11 +620,12 @@ class StandardDomain(Domain):
|
|||||||
'option': 'unknown option: %(target)s',
|
'option': 'unknown option: %(target)s',
|
||||||
}
|
}
|
||||||
|
|
||||||
enumerable_nodes = { # node_class -> (figtype, title_getter)
|
# node_class -> (figtype, title_getter)
|
||||||
|
enumerable_nodes: Dict[Type[Node], Tuple[str, Callable]] = {
|
||||||
nodes.figure: ('figure', None),
|
nodes.figure: ('figure', None),
|
||||||
nodes.table: ('table', None),
|
nodes.table: ('table', None),
|
||||||
nodes.container: ('code-block', None),
|
nodes.container: ('code-block', None),
|
||||||
} # type: Dict[Type[Node], Tuple[str, Callable]]
|
}
|
||||||
|
|
||||||
def __init__(self, env: "BuildEnvironment") -> None:
|
def __init__(self, env: "BuildEnvironment") -> None:
|
||||||
super().__init__(env)
|
super().__init__(env)
|
||||||
@ -706,7 +707,7 @@ class StandardDomain(Domain):
|
|||||||
return self.data.setdefault('anonlabels', {}) # labelname -> docname, labelid
|
return self.data.setdefault('anonlabels', {}) # labelname -> docname, labelid
|
||||||
|
|
||||||
def clear_doc(self, docname: str) -> None:
|
def clear_doc(self, docname: str) -> None:
|
||||||
key = None # type: Any
|
key: Any = None
|
||||||
for key, (fn, _l) in list(self.progoptions.items()):
|
for key, (fn, _l) in list(self.progoptions.items()):
|
||||||
if fn == docname:
|
if fn == docname:
|
||||||
del self.progoptions[key]
|
del self.progoptions[key]
|
||||||
@ -992,7 +993,7 @@ class StandardDomain(Domain):
|
|||||||
def resolve_any_xref(self, env: "BuildEnvironment", fromdocname: str,
|
def resolve_any_xref(self, env: "BuildEnvironment", fromdocname: str,
|
||||||
builder: "Builder", target: str, node: pending_xref,
|
builder: "Builder", target: str, node: pending_xref,
|
||||||
contnode: Element) -> List[Tuple[str, Element]]:
|
contnode: Element) -> List[Tuple[str, Element]]:
|
||||||
results = [] # type: List[Tuple[str, Element]]
|
results: List[Tuple[str, Element]] = []
|
||||||
ltarget = target.lower() # :ref: lowercases its target automatically
|
ltarget = target.lower() # :ref: lowercases its target automatically
|
||||||
for role in ('ref', 'option'): # do not try "keyword"
|
for role in ('ref', 'option'): # do not try "keyword"
|
||||||
res = self.resolve_xref(env, fromdocname, builder, role,
|
res = self.resolve_xref(env, fromdocname, builder, role,
|
||||||
|
Loading…
Reference in New Issue
Block a user