Skip to content

Commit

Permalink
Clean: move type hints into docstrings
Browse files Browse the repository at this point in the history
  • Loading branch information
allison-casey committed Jul 27, 2021
1 parent ff567c6 commit 8e84a75
Show file tree
Hide file tree
Showing 4 changed files with 95 additions and 116 deletions.
100 changes: 47 additions & 53 deletions hy/compiler.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import ast, copy, importlib, inspect, keyword, pkgutil
import traceback, types
from typing import Any, Callable, Optional, Type, Union

from funcparserlib.parser import NoParseError, many

Expand All @@ -16,32 +15,32 @@
hy_ast_compile_flags = 0


def ast_compile(a: ast.AST, filename: str, mode: str) -> types.CodeType:
def ast_compile(a, filename, mode):
"""Compile AST.
Args:
a: instance of `ast.AST`
filename: Filename used for run-time error messages
mode: `compile` mode parameter
a (ast.AST): instance of `ast.AST`
filename (str): Filename used for run-time error messages
mode (str): `compile` mode parameter
Returns:
out : instance of `types.CodeType`
types.CodeType: instance of `types.CodeType`
"""
return compile(a, filename, mode, hy_ast_compile_flags)


def calling_module(n: int=1) -> types.ModuleType:
def calling_module(n=1):
"""Get the module calling, if available.
As a fallback, this will import a module using the calling frame's
globals value of `__name__`.
Args:
n: The number of levels up the stack from this function call.
The default is one level up.
n (int): The number of levels up the stack from this function call.
The default is `1` (level up).
Returns:
out: The module at stack level `n + 1` or `None`.
types.ModuleType: The module at stack level `n + 1` or `None`.
"""
frame_up = inspect.stack(0)[n + 1][0]
module = inspect.getmodule(frame_up)
Expand Down Expand Up @@ -273,19 +272,14 @@ def is_annotate_expression(model):
class HyASTCompiler(object):
"""A Hy-to-Python AST compiler"""

def __init__(
self,
module: Union[str, types.ModuleType],
filename: Optional[str] = None,
source: Optional[str] = None,
):
def __init__(self, module, filename=None, source=None):
"""
Args:
module: Module name or object in which the Hy tree is evaluated.
filename: The name of the file for the source to be compiled.
module (Union[str, types.ModuleType]): Module name or object in which the Hy tree is evaluated.
filename (Optional[str]): The name of the file for the source to be compiled.
This is optional information for informative error messages and
debugging.
source: The source for the file, if any, being compiled. This is optional
source (Optional[str]): The source for the file, if any, being compiled. This is optional
information for informative error messages and debugging.
"""
self.anon_var_count = 0
Expand Down Expand Up @@ -635,15 +629,15 @@ def get_compiler_module(module=None, compiler=None, calling_frame=False):


def hy_eval(
hytree: Object,
locals: Optional[dict] = None,
module: Optional[Union[str, types.ModuleType]] = None,
ast_callback: Optional[Callable] = None,
compiler: Optional[HyASTCompiler] = None,
filename: Optional[str] = None,
source: Optional[str] = None,
import_stdlib: bool = True,
) -> Any:
hytree,
locals=None,
module=None,
ast_callback=None,
compiler=None,
filename=None,
source=None,
import_stdlib=True,
):
"""Evaluates a quoted expression and returns the value.
If you're evaluating hand-crafted AST trees, make sure the line numbers
Expand All @@ -663,44 +657,44 @@ def hy_eval(
2
Args:
hytree:
hytree (Object):
The Hy AST object to evaluate.
locals:
locals (Optional[dict]):
Local environment in which to evaluate the Hy tree. Defaults to the
calling frame.
module:
module (Optional[Union[str, types.ModuleType]]):
Module, or name of the module, to which the Hy tree is assigned and
the global values are taken.
The module associated with `compiler` takes priority over this value.
When neither `module` nor `compiler` is specified, the calling frame's
module is used.
ast_callback:
ast_callback (Optional[Callable]):
A callback that is passed the Hy compiled tree and resulting
expression object, in that order, after compilation but before
evaluation.
compiler:
compiler (Optional[HyASTCompiler]):
An existing Hy compiler to use for compilation. Also serves as
the `module` value when given.
filename:
filename (Optional[str]):
The filename corresponding to the source for `tree`. This will be
overridden by the `filename` field of `tree`, if any; otherwise, it
defaults to "<string>". When `compiler` is given, its `filename` field
value is always used.
source:
source (Optional[str]):
A string containing the source code for `tree`. This will be
overridden by the `source` field of `tree`, if any; otherwise,
if `None`, an attempt will be made to obtain it from the module given by
`module`. When `compiler` is given, its `source` field value is always
used.
Returns:
Result of evaluating the Hy compiled tree.
Any: Result of evaluating the Hy compiled tree.
"""

module = get_compiler_module(module, compiler, True)
Expand Down Expand Up @@ -733,37 +727,37 @@ def hy_eval(


def hy_compile(
tree: Object,
module: Union[str, types.ModuleType],
root: Type[ast.AST] = ast.Module,
get_expr: bool = False,
compiler: Optional[HyASTCompiler] = None,
filename: Optional[str] = None,
source: Optional[str] = None,
import_stdlib: bool = True,
) -> ast.AST:
tree,
module,
root=ast.Module,
get_expr=False,
compiler=None,
filename=None,
source=None,
import_stdlib=True,
):
"""Compile a hy.models.Object tree into a Python AST Module.
Args:
tree: The Hy AST object to compile.
module: Module, or name of the module, in which the Hy tree is evaluated.
tree (Object): The Hy AST object to compile.
module (Union[str, types.ModuleType]): Module, or name of the module, in which the Hy tree is evaluated.
The module associated with `compiler` takes priority over this value.
root: Root object for the Python AST tree.
get_expr: If true, return a tuple with `(root_obj, last_expression)`.
compiler: An existing Hy compiler to use for compilation. Also serves as
root (Type[ast.AST]): Root object for the Python AST tree.
get_expr (bool): If true, return a tuple with `(root_obj, last_expression)`.
compiler (Optional[HyASTCompiler]): An existing Hy compiler to use for compilation. Also serves as
the `module` value when given.
filename: The filename corresponding to the source for `tree`. This will be
filename (Optional[str]): The filename corresponding to the source for `tree`. This will be
overridden by the `filename` field of `tree`, if any; otherwise, it
defaults to "<string>". When `compiler` is given, its `filename` field
value is always used.
source: A string containing the source code for `tree`. This will be
source (Optional[str]): A string containing the source code for `tree`. This will be
overridden by the `source` field of `tree`, if any; otherwise,
if `None`, an attempt will be made to obtain it from the module given by
`module`. When `compiler` is given, its `source` field value is always
used.
Returns:
A Python AST tree
ast.AST: A Python AST tree
"""
module = get_compiler_module(module, compiler, False)

Expand Down
36 changes: 16 additions & 20 deletions hy/errors.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
from typing import Optional, TYPE_CHECKING
import os
import re
import sys
Expand All @@ -11,9 +10,6 @@
from hy import _initialize_env_var
from hy._compat import PYPY

if TYPE_CHECKING:
from hy.models import Object

_hy_filter_internal_errors = _initialize_env_var('HY_FILTER_INTERNAL_ERRORS',
True)
COLORED = _initialize_env_var('HY_COLORED_ERRORS', False)
Expand All @@ -39,25 +35,25 @@ class HyLanguageError(HyError):

def __init__(
self,
message: str,
expression: Optional["Object"] = None,
filename: Optional[str] = None,
source: Optional[str] = None,
lineno: int = 1,
colno: int = 1,
message,
expression=None,
filename=None,
source=None,
lineno=1,
colno=1,
):
"""
Args:
message: The message to display for this error.
expression: The Hy expression generating this error.
filename: The filename for the source code generating this error.
Expression-provided information will take precedence of this value.
source: The actual source code generating this error. Expression-provided
information will take precedence of this value.
lineno: The line number of the error. Expression-provided information will
take precedence of this value.
colno: The column number of the error. Expression-provided information
will take precedence of this value.
message (str): The message to display for this error.
expression (Optional[Object]): The Hy expression generating this error.
filename (Optional[str]): The filename for the source code generating this error.
Expression-provided information will take precedence of this value. Defaults to `None`.
source (Optional[str]): The actual source code generating this error. Expression-provided
information will take precedence of this value. Defaults to `None`.
lineno (int): The line number of the error. Expression-provided information will
take precedence of this value. Defaults to `1`.
colno (int): The column number of the error. Expression-provided information
will take precedence of this value. Defaults to `1`.
"""
self.msg = message
self.compute_lineinfo(expression, filename, source, lineno, colno)
Expand Down
21 changes: 11 additions & 10 deletions hy/lex/__init__.py
Original file line number Diff line number Diff line change
@@ -1,28 +1,26 @@
import keyword
import re
import sys
from typing import Optional
import typing as t
import unicodedata

from hy.lex.exceptions import PrematureEndOfInput, LexException # NOQA
from hy.models import Expression, Object, Symbol
from hy.models import Expression, Symbol

try:
from io import StringIO
except ImportError:
from StringIO import StringIO


def hy_parse(source: str, filename: str = '<string>') -> Expression:
def hy_parse(source, filename='<string>'):
"""Parse a Hy source string.
Args:
source: Source code to parse.
filename: File name corresponding to source. Defaults to "<string>".
source (str): Source code to parse.
filename (str): File name corresponding to source. Defaults to "<string>".
Returns:
out : the parsed models wrapped in an hy.models.Expression
Expression: the parsed models wrapped in an hy.models.Expression
"""
_source = re.sub(r'\A#!.*', '', source)
res = Expression([Symbol("do")] +
Expand All @@ -39,12 +37,15 @@ def __init__(self, source, filename):
self.filename = filename


def tokenize(source: str, filename: Optional[str]=None) -> t.List[Object]:
def tokenize(source, filename=None):
""" Tokenize a Lisp file or string buffer into internal Hy objects.
Args:
source (str): The source to tokenize.
filename (str, optional): The filename corresponding to `source`.
source (str): The source to tokenize.
filename (Optional[str]): The filename corresponding to `source`.
Returns:
typing.List[Object]: list of hy object models
"""
from hy.lex.lexer import lexer
from hy.lex.parser import parser
Expand Down
Loading

0 comments on commit 8e84a75

Please sign in to comment.