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