Skip to content

Commit

Permalink
Fix: Lint errors
Browse files Browse the repository at this point in the history
  • Loading branch information
allison-casey committed Mar 10, 2021
1 parent 8781dd9 commit 5a5c1ee
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 43 deletions.
39 changes: 18 additions & 21 deletions sphinxcontrib/hy_documenters.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,11 @@
import traceback
from inspect import getfullargspec
from itertools import islice, starmap
from typing import Any, Callable, List, Optional, Tuple, TypeVar
from typing import Any, Callable, List, TypeVar, Dict

import hy
from docutils.nodes import Node
from docutils.statemachine import StringList
from sphinx import version_info
from sphinx.ext.autodoc import ALL, INSTANCEATTR, bool_option
from sphinx.ext.autodoc import ALL, bool_option
from sphinx.ext.autodoc import Documenter as PyDocumenter
from sphinx.ext.autodoc import FunctionDocumenter as PyFunctionDocumenter
from sphinx.ext.autodoc import MethodDocumenter as PyMethodDocumenter
Expand All @@ -19,7 +17,7 @@
from sphinx.ext.autodoc import PropertyDocumenter as PyPropertyDocumenter
from sphinx.ext.autodoc import AttributeDocumenter as PyAttributeDocumenter
from sphinx.ext.autodoc import DecoratorDocumenter as PyDecoratorDocumenter
from sphinx.ext.autodoc import ObjectMember, ObjectMembers, special_member_re
from sphinx.ext.autodoc import ObjectMember
from sphinx.ext.autodoc.directive import (
AutodocDirective,
DocumenterBridge,
Expand All @@ -31,19 +29,17 @@
import hy.core.macros
from sphinx.ext.autodoc.importer import Attribute, import_module
from sphinx.ext.autodoc.mock import mock
from sphinx.pycode import ModuleAnalyzer, PycodeError
from sphinx.locale import __
from sphinx.util import inspect
from sphinx.util.docstrings import extract_metadata
from sphinx.util.inspect import (
getall,
getannotations,
getdoc,
getmro,
getslots,
isenumclass,
safe_getattr,
)
from sphinx.util.typing import is_system_TypeVar
from sphinx.util.typing import is_system_TypeVar, _stringify_py36

logger = logging.getLogger("hy-domain")

Expand All @@ -53,7 +49,7 @@
(?P<classes>.*\.)? # Module and/or class name(s)
(?P<object>.+?) \s* # Thing name
(?:\s*\^(?P<retann>.*?)\s*)? # Optional: return annotation
(?: # Arguments and close or just close
(?: # Arguments/close or just close
(?:\[(?:\s*(?P<arguments>.*)\s*\]\))?) | # Optional: arguments
(?:\)))
$""",
Expand All @@ -70,6 +66,7 @@

NoneType = type(None)


def get_object_members(subject: Any, objpath: List[str], attrgetter, analyzer=None):
"""Get members and attributes of target object."""
from sphinx.ext.autodoc import INSTANCEATTR
Expand Down Expand Up @@ -117,7 +114,7 @@ def get_object_members(subject: Any, objpath: List[str], attrgetter, analyzer=No
for i, cls in enumerate(getmro(subject)):
try:
for name in getannotations(cls):
name = unmangle(cls, name)
name = hy.unmangle(cls, name)
if name and name not in members:
members[name] = Attribute(name, i == 0, INSTANCEATTR)
except AttributeError:
Expand Down Expand Up @@ -242,7 +239,7 @@ def import_object(

def stringify(annotation: Any) -> str:
"""Stringify type annotation object."""
from sphinx.util import inspect # lazy loading
# from sphinx.util import inspect # lazy loading

if isinstance(annotation, str):
if annotation.startswith("'") and annotation.endswith("'"):
Expand Down Expand Up @@ -311,7 +308,7 @@ def _stringify_py37(annotation: Any) -> str:
elif qualname == "Callable":
args = ", ".join(stringify(a) for a in annotation.__args__[:-1])
returns = stringify(annotation.__args__[-1])
return "%(of %s [%s] %s)" % (qualname, args, returns)
return "(of %s [%s] %s)" % (qualname, args, returns)
elif str(annotation).startswith("typing.Annotated"): # for py39+
return stringify(annotation.__args__[0])
elif all(is_system_TypeVar(a) for a in annotation.__args__):
Expand Down Expand Up @@ -443,9 +440,9 @@ def is_hy(member, membername, parent):


class HyAutodocDirective(AutodocDirective):
"""A directive class for all autodoc directives. It works as a dispatcher of Documenters.
It invokes a Documenter on running. After the processing, it parses and returns
the generated content by Documenter.
"""A directive class for all autodoc directives. It works as a dispatcher
of Documenters. It invokes a Documenter on running. After the processing,
it parses and returns the generated content by Documenter.
"""

option_spec = DummyOptionSpec()
Expand Down Expand Up @@ -511,7 +508,7 @@ class HyDocumenter(PyDocumenter):
def parse_name(self) -> bool:
try:
explicit_modname, path, base, args, retann = match_hy_sig(self.name)
except AttributeError as e:
except AttributeError:
self.directive.warn(
"invalid signature for auto%s (%r)" % self.objtype, self.name
)
Expand Down Expand Up @@ -628,11 +625,11 @@ def document_members(self, all_members=False):
members_check_module, members = self.get_object_members(want_all)

# document non-skipped members
memberdocumenters = [] # type: List[Tuple[Documenter, bool]]
memberdocumenters = []
wanted_members = self.filter_members(members, want_all)
module_macros = [
member for member in members if getattr(member, "__macro__", False)
]
# module_macros = [
# member for member in members if getattr(member, "__macro__", False)
# ]
for (mname, member, isattr) in wanted_members:
classes = [
cls
Expand Down
52 changes: 30 additions & 22 deletions sphinxcontrib/hydomain.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,14 @@
from sphinx.application import Sphinx
from sphinx.directives import directives
from sphinx.domains import Domain, ObjType
from sphinx.domains.python import (ModuleEntry, ObjectEntry, PyModule,
PyObject, PythonModuleIndex, pairindextypes)
from sphinx.domains.python import (
ModuleEntry,
ObjectEntry,
PyModule,
PyObject,
PythonModuleIndex,
pairindextypes,
)
from sphinx.environment import BuildEnvironment
from sphinx.locale import _, __
from sphinx.pycode.ast import parse as ast_parse
Expand All @@ -49,6 +55,7 @@
)
hy_var_re = re.compile(r"^([\w.]*\.)?(.+?)$")


# ** Node Types
class desc_hyparameterlist(addnodes.desc_parameterlist):
child_text_separator = " "
Expand All @@ -65,7 +72,9 @@ def astext(self) -> str:

class desc_hyreturns(addnodes.desc_returns):
def astext(self) -> str:
return ' -> ^' + super().astext()
return " -> ^" + super().astext()


# ** Helper methods
def bool_option(arg):
return True
Expand All @@ -86,6 +95,7 @@ def signature_from_str(signature: str) -> inspect.Signature:

return signature_from_ast(function)


def _parse_arglist(arglist: str, env: BuildEnvironment = None):
params = desc_hyparameterlist(arglist)
sig = signature_from_str("[%s]" % arglist)
Expand Down Expand Up @@ -158,13 +168,13 @@ def annotate(param):


def _pseudo_parse_arglist(signode: desc_signature, arglist: str) -> None:
""""Parse" a list of arguments separated by commas.
""" "Parse" a list of arguments separated by commas.
Arguments can have "optional" annotations given by enclosing them in
brackets. Currently, this will split at any comma, even if it's inside a
string literal (e.g. default argument value).
"""
paramlist = desc_hyparameterlist()
stack = [paramlist] # type: List[Element]
# stack = [paramlist] # type: List[Element]
try:
raise IndexError()
# for argument in arglist.split(','):
Expand Down Expand Up @@ -406,7 +416,6 @@ def handle_signature(self, sig: str, signode) -> Tuple[str, str]:

signode += addnodes.desc_name(name, name)


if arglist:
try:
signode += _parse_arglist(arglist, self.env)
Expand All @@ -415,9 +424,7 @@ def handle_signature(self, sig: str, signode) -> Tuple[str, str]:
# it supports to represent optional arguments (ex. "func(foo [, bar])")
_pseudo_parse_arglist(signode, arglist)
except NotImplementedError as exc:
logging.warning(
"could not parse arglist (%r): %s", exc
)
logging.warning("could not parse arglist (%r): %s", exc)
_pseudo_parse_arglist(signode, arglist)
else:
if self.needs_arglist():
Expand All @@ -431,7 +438,6 @@ def handle_signature(self, sig: str, signode) -> Tuple[str, str]:
if should_wrap:
signode += addnodes.desc_addname(")", ")")


if retann:
pyretann = hy2py(retann)
children = _parse_annotation(pyretann, self.env)
Expand Down Expand Up @@ -515,9 +521,7 @@ def after_content(self) -> None:

class HyFunction(HyObject):
option_spec = HyObject.option_spec.copy()
option_spec.update({
"async": directives.flag
})
option_spec.update({"async": directives.flag})

def get_index_text(self, modname: str, name: Tuple[str, str]) -> str:
return None
Expand Down Expand Up @@ -638,8 +642,6 @@ def handle_signature(self, sig: str, signode) -> Tuple[str, str]:
if prefix:
signode += addnodes.desc_addname(prefix, prefix)



if retann:
pyretann = hy2py(retann)
children = _parse_annotation(pyretann, self.env)
Expand All @@ -650,9 +652,7 @@ def handle_signature(self, sig: str, signode) -> Tuple[str, str]:
try:
signode += _parse_arglist(arglist, self.env)
except NotImplementedError as exc:
logging.warning(
"could not parse arglist (%r): %s", exc
)
logging.warning("could not parse arglist (%r): %s", exc)
# _pseudo_parse_arglist(signode, arglist)
else:
if self.needs_arglist():
Expand All @@ -672,7 +672,10 @@ class HyVariable(HyObject):
option_spec = HyObject.option_spec.copy()

option_spec.update(
{"type": directives.unchanged, "value": directives.unchanged,}
{
"type": directives.unchanged,
"value": directives.unchanged,
}
)

def handle_signature(self, sig: str, signode: desc_signature) -> Tuple[str, str]:
Expand Down Expand Up @@ -744,7 +747,9 @@ class HyClass(HyObject):

option_spec = HyObject.option_spec.copy()
option_spec.update(
{"final": directives.flag,}
{
"final": directives.flag,
}
)

allow_nesting = True
Expand Down Expand Up @@ -879,7 +884,10 @@ class HyAttribute(HyObject):

option_spec = PyObject.option_spec.copy()
option_spec.update(
{"type": directives.unchanged, "value": directives.unchanged,}
{
"type": directives.unchanged,
"value": directives.unchanged,
}
)

def handle_signature(self, sig: str, signode: desc_signature) -> Tuple[str, str]:
Expand Down Expand Up @@ -988,7 +996,6 @@ class HyDomain(Domain):
"meth": HyXRefRole(),
"attr": HyXRefRole(),
"exc": HyXRefRole(),
"class": HyXRefRole(),
"const": HyXRefRole(),
"mod": HyXRefRole(),
"obj": HyXRefRole(),
Expand Down Expand Up @@ -1236,6 +1243,7 @@ def v_hyreturns(self, node):
def d_hyreturns(self, node):
pass


def v_hyparameterlist(self, node):
self.first_param = True
if len(node):
Expand Down

0 comments on commit 5a5c1ee

Please sign in to comment.