Search is not available for this dataset
text
stringlengths
75
104k
def _with_meta(gen_node): """Wraps the node generated by gen_node in a :with-meta AST node if the original form has meta. :with-meta AST nodes are used for non-quoted collection literals and for function expressions.""" @wraps(gen_node) def with_meta( ctx: ParserContext, form: ...
def __deftype_impls( # pylint: disable=too-many-branches ctx: ParserContext, form: ISeq ) -> Tuple[List[DefTypeBase], List[Method]]: """Roll up deftype* declared bases and method implementations.""" current_interface_sym: Optional[sym.Symbol] = None current_interface: Optional[DefTypeBase] = None i...
def _assert_no_recur(node: Node) -> None: """Assert that `recur` forms do not appear in any position of this or child AST nodes.""" if node.op == NodeOp.RECUR: raise ParserException( "recur must appear in tail position", form=node.form, lisp_ast=node ) elif node.op in {NodeOp...
def _assert_recur_is_tail(node: Node) -> None: # pylint: disable=too-many-branches """Assert that `recur` forms only appear in the tail position of this or child AST nodes. `recur` forms may only appear in `do` nodes (both literal and synthetic `do` nodes) and in either the :then or :else expression o...
def __resolve_namespaced_symbol( # pylint: disable=too-many-branches ctx: ParserContext, form: sym.Symbol ) -> Union[MaybeClass, MaybeHostForm, VarRef]: """Resolve a namespaced symbol into a Python name or Basilisp Var.""" assert form.ns is not None if form.ns == ctx.current_ns.name: v = ctx.c...
def __resolve_bare_symbol( ctx: ParserContext, form: sym.Symbol ) -> Union[MaybeClass, VarRef]: """Resolve a non-namespaced symbol into a Python name or a local Basilisp Var.""" assert form.ns is None # Look up the symbol in the namespace mapping of the current namespace. v = ctx.current_ns.fin...
def _resolve_sym( ctx: ParserContext, form: sym.Symbol ) -> Union[MaybeClass, MaybeHostForm, VarRef]: """Resolve a Basilisp symbol as a Var or Python name.""" # Support special class-name syntax to instantiate new classes # (Classname. *args) # (aliased.Classname. *args) # (fully.qualified...
def parse_ast(ctx: ParserContext, form: ReaderForm) -> Node: """Take a Lisp form as an argument and produce a Basilisp syntax tree matching the clojure.tools.analyzer AST spec.""" return _parse_ast(ctx, form).assoc(top_level=True)
def warn_on_shadowed_var(self) -> bool: """If True, warn when a def'ed Var name is shadowed in an inner scope. Implied by warn_on_shadowed_name. The value of warn_on_shadowed_name supersedes the value of this flag.""" return self.warn_on_shadowed_name or self._opts.entry( WA...
def put_new_symbol( # pylint: disable=too-many-arguments self, s: sym.Symbol, binding: Binding, warn_on_shadowed_name: bool = True, warn_on_shadowed_var: bool = True, warn_if_unused: bool = True, ): """Add a new symbol to the symbol table. This funct...
def map_lrepr( entries: Callable[[], Iterable[Tuple[Any, Any]]], start: str, end: str, meta=None, **kwargs, ) -> str: """Produce a Lisp representation of an associative collection, bookended with the start and end string supplied. The entries argument must be a callable which will produc...
def seq_lrepr( iterable: Iterable[Any], start: str, end: str, meta=None, **kwargs ) -> str: """Produce a Lisp representation of a sequential collection, bookended with the start and end string supplied. The keyword arguments will be passed along to lrepr for the sequence elements.""" print_level = k...
def lrepr( # pylint: disable=too-many-arguments o: Any, human_readable: bool = False, print_dup: bool = PRINT_DUP, print_length: PrintCountSetting = PRINT_LENGTH, print_level: PrintCountSetting = PRINT_LEVEL, print_meta: bool = PRINT_META, print_readably: bool = PRINT_READABLY, ) -> str: ...
def _lrepr_fallback( # pylint: disable=too-many-arguments o: Any, human_readable: bool = False, print_dup: bool = PRINT_DUP, print_length: PrintCountSetting = PRINT_LENGTH, print_level: PrintCountSetting = PRINT_LEVEL, print_meta: bool = PRINT_META, print_readably: bool = PRINT_READABLY, ) ...
def visit(self, f: Callable[..., None], *args, **kwargs): """Visit all immediate children of this node, calling f(child, *args, **kwargs) on each child.""" for child_kw in self.children: child_attr = munge(child_kw.name) if child_attr.endswith("s"): iter_...
def fix_missing_locations( self, start_loc: Optional[Tuple[int, int]] = None ) -> "Node": """Return a transformed copy of this node with location in this node's environment updated to match the `start_loc` if given, or using its existing location otherwise. All child nodes will be re...
def _emit_ast_string(module: ast.AST) -> None: # pragma: no cover """Emit the generated Python AST string either to standard out or to the *generated-python* dynamic Var for the current namespace. If the BASILISP_EMIT_GENERATED_PYTHON env var is not set True, this method is a no-op.""" # TODO: even...
def compile_and_exec_form( # pylint: disable= too-many-arguments form: ReaderForm, ctx: CompilerContext, module: types.ModuleType, wrapped_fn_name: str = _DEFAULT_FN, collect_bytecode: Optional[BytecodeCollector] = None, ) -> Any: """Compile and execute the given form. This function will be mos...
def _incremental_compile_module( optimizer: PythonASTOptimizer, py_ast: GeneratedPyAST, mod: types.ModuleType, source_filename: str, collect_bytecode: Optional[BytecodeCollector] = None, ) -> None: """Incrementally compile a stream of AST nodes in module mod. The source_filename will be pas...
def _bootstrap_module( gctx: GeneratorContext, optimizer: PythonASTOptimizer, mod: types.ModuleType, collect_bytecode: Optional[BytecodeCollector] = None, ) -> None: """Bootstrap a new module with imports and other boilerplate.""" _incremental_compile_module( optimizer, py_module...
def compile_module( forms: Iterable[ReaderForm], ctx: CompilerContext, module: types.ModuleType, collect_bytecode: Optional[BytecodeCollector] = None, ) -> None: """Compile an entire Basilisp module into Python bytecode which can be executed as a Python module. This function is designed to ...
def compile_bytecode( code: List[types.CodeType], gctx: GeneratorContext, optimizer: PythonASTOptimizer, module: types.ModuleType, ) -> None: """Compile cached bytecode into the given module. The Basilisp import hook attempts to cache bytecode while compiling Basilisp namespaces. When the c...
def sequence(s: Iterable) -> ISeq[Any]: """Create a Sequence from Iterable s.""" try: i = iter(s) return _Sequence(i, next(i)) except StopIteration: return EMPTY
def munge(s: str, allow_builtins: bool = False) -> str: """Replace characters which are not valid in Python symbols with valid replacement strings.""" new_str = [] for c in s: new_str.append(_MUNGE_REPLACEMENTS.get(c, c)) new_s = "".join(new_str) if keyword.iskeyword(new_s): re...
def demunge(s: str) -> str: """Replace munged string components with their original representation.""" def demunge_replacer(match: Match) -> str: full_match = match.group(0) replacement = _DEMUNGE_REPLACEMENTS.get(full_match, None) if replacement: return replacement ...
def fraction(numerator: int, denominator: int) -> Fraction: """Create a Fraction from a numerator and denominator.""" return Fraction(numerator=numerator, denominator=denominator)
def get_handler(level: str, fmt: str) -> logging.Handler: """Get the default logging handler for Basilisp.""" handler: logging.Handler = logging.NullHandler() if os.getenv("BASILISP_USE_DEV_LOGGER") == "true": handler = logging.StreamHandler() handler.setFormatter(logging.Formatter(fmt)) ha...
def map(kvs: Mapping[K, V], meta=None) -> Map[K, V]: # pylint:disable=redefined-builtin """Creates a new map.""" return Map(pmap(initial=kvs), meta=meta)
def timed(f: Optional[Callable[[int], None]] = None): """Time the execution of code in the with-block, calling the function f (if it is given) with the resulting time in nanoseconds.""" start = time.perf_counter() yield end = time.perf_counter() if f: ns = int((end - start) * 1_000_000_0...
def partition(coll, n: int): """Partition coll into groups of size n.""" assert n > 0 start = 0 stop = n while stop <= len(coll): yield tuple(e for e in coll[start:stop]) start += n stop += n if start < len(coll) < stop: stop = len(coll) yield tuple(e for ...
def _with_loc(f: W) -> W: """Wrap a reader function in a decorator to supply line and column information along with relevant forms.""" @functools.wraps(f) def with_lineno_and_col(ctx): meta = lmap.map( {READER_LINE_KW: ctx.reader.line, READER_COL_KW: ctx.reader.col} ) ...
def _read_namespaced( ctx: ReaderContext, allowed_suffix: Optional[str] = None ) -> Tuple[Optional[str], str]: """Read a namespaced token from the input stream.""" ns: List[str] = [] name: List[str] = [] reader = ctx.reader has_ns = False while True: token = reader.peek() if ...
def _read_coll( ctx: ReaderContext, f: Callable[[Collection[Any]], Union[llist.List, lset.Set, vector.Vector]], end_token: str, coll_name: str, ): """Read a collection from the input stream and create the collection using f.""" coll: List = [] reader = ctx.reader while True: ...
def _read_list(ctx: ReaderContext) -> llist.List: """Read a list element from the input stream.""" start = ctx.reader.advance() assert start == "(" return _read_coll(ctx, llist.list, ")", "list")
def _read_vector(ctx: ReaderContext) -> vector.Vector: """Read a vector element from the input stream.""" start = ctx.reader.advance() assert start == "[" return _read_coll(ctx, vector.vector, "]", "vector")
def _read_set(ctx: ReaderContext) -> lset.Set: """Return a set from the input stream.""" start = ctx.reader.advance() assert start == "{" def set_if_valid(s: Collection) -> lset.Set: if len(s) != len(set(s)): raise SyntaxError("Duplicated values in set") return lset.set(s) ...
def _read_map(ctx: ReaderContext) -> lmap.Map: """Return a map from the input stream.""" reader = ctx.reader start = reader.advance() assert start == "{" d: MutableMapping[Any, Any] = {} while True: if reader.peek() == "}": reader.next_token() break k = _r...
def _read_num( # noqa: C901 # pylint: disable=too-many-statements ctx: ReaderContext ) -> MaybeNumber: """Return a numeric (complex, Decimal, float, int, Fraction) from the input stream.""" chars: List[str] = [] reader = ctx.reader is_complex = False is_decimal = False is_float = False ...
def _read_str(ctx: ReaderContext, allow_arbitrary_escapes: bool = False) -> str: """Return a string from the input stream. If allow_arbitrary_escapes is True, do not throw a SyntaxError if an unknown escape sequence is encountered.""" s: List[str] = [] reader = ctx.reader while True: to...
def _read_sym(ctx: ReaderContext) -> MaybeSymbol: """Return a symbol from the input stream. If a symbol appears in a syntax quoted form, the reader will attempt to resolve the symbol using the resolver in the ReaderContext `ctx`. The resolver will look into the current namespace for an alias or nam...
def _read_kw(ctx: ReaderContext) -> keyword.Keyword: """Return a keyword from the input stream.""" start = ctx.reader.advance() assert start == ":" ns, name = _read_namespaced(ctx) if "." in name: raise SyntaxError("Found '.' in keyword name") return keyword.keyword(name, ns=ns)
def _read_meta(ctx: ReaderContext) -> IMeta: """Read metadata and apply that to the next object in the input stream.""" start = ctx.reader.advance() assert start == "^" meta = _read_next_consuming_comment(ctx) meta_map: Optional[lmap.Map[LispForm, LispForm]] = None if isinstance(meta, symbo...
def _read_function(ctx: ReaderContext) -> llist.List: """Read a function reader macro from the input stream.""" if ctx.is_in_anon_fn: raise SyntaxError(f"Nested #() definitions not allowed") with ctx.in_anon_fn(): form = _read_list(ctx) arg_set = set() def arg_suffix(arg_num): ...
def _read_quoted(ctx: ReaderContext) -> llist.List: """Read a quoted form from the input stream.""" start = ctx.reader.advance() assert start == "'" next_form = _read_next_consuming_comment(ctx) return llist.l(_QUOTE, next_form)
def _expand_syntax_quote( ctx: ReaderContext, form: IterableLispForm ) -> Iterable[LispForm]: """Expand syntax quoted forms to handle unquoting and unquote-splicing. The unquoted form (unquote x) becomes: (list x) The unquote-spliced form (unquote-splicing x) becomes x All other f...
def _process_syntax_quoted_form(ctx: ReaderContext, form: ReaderForm) -> ReaderForm: """Post-process syntax quoted forms to generate forms that can be assembled into the correct types at runtime. Lists are turned into: (basilisp.core/seq (basilisp.core/concat [& rest])) Vectors are tu...
def _read_syntax_quoted(ctx: ReaderContext) -> ReaderForm: """Read a syntax-quote and set the syntax-quoting state in the reader.""" start = ctx.reader.advance() assert start == "`" with ctx.syntax_quoted(): return _process_syntax_quoted_form(ctx, _read_next_consuming_comment(ctx))
def _read_unquote(ctx: ReaderContext) -> LispForm: """Read an unquoted form and handle any special logic of unquoting. Unquoted forms can take two, well... forms: `~form` is read as `(unquote form)` and any nested forms are read literally and passed along to the compiler untouched. `~@form`...
def _read_deref(ctx: ReaderContext) -> LispForm: """Read a derefed form from the input stream.""" start = ctx.reader.advance() assert start == "@" next_form = _read_next_consuming_comment(ctx) return llist.l(_DEREF, next_form)
def _read_character(ctx: ReaderContext) -> str: """Read a character literal from the input stream. Character literals may appear as: - \\a \\b \\c etc will yield 'a', 'b', and 'c' respectively - \\newline, \\space, \\tab, \\formfeed, \\backspace, \\return yield the named characters ...
def _read_regex(ctx: ReaderContext) -> Pattern: """Read a regex reader macro from the input stream.""" s = _read_str(ctx, allow_arbitrary_escapes=True) try: return langutil.regex_from_str(s) except re.error: raise SyntaxError(f"Unrecognized regex pattern syntax: {s}")
def _read_reader_macro(ctx: ReaderContext) -> LispReaderForm: """Return a data structure evaluated as a reader macro from the input stream.""" start = ctx.reader.advance() assert start == "#" token = ctx.reader.peek() if token == "{": return _read_set(ctx) elif token == "(": ...
def _read_comment(ctx: ReaderContext) -> LispReaderForm: """Read (and ignore) a single-line comment from the input stream. Return the next form after the next line break.""" reader = ctx.reader start = reader.advance() assert start == ";" while True: token = reader.peek() if newl...
def _read_next_consuming_comment(ctx: ReaderContext) -> ReaderForm: """Read the next full form from the input stream, consuming any reader comments completely.""" while True: v = _read_next(ctx) if v is ctx.eof: return ctx.eof if v is COMMENT or isinstance(v, Comment): ...
def _read_next(ctx: ReaderContext) -> LispReaderForm: # noqa: C901 """Read the next full form from the input stream.""" reader = ctx.reader token = reader.peek() if token == "(": return _read_list(ctx) elif token == "[": return _read_vector(ctx) elif token == "{": return...
def read( stream, resolver: Resolver = None, data_readers: DataReaders = None, eof: Any = EOF, is_eof_error: bool = False, ) -> Iterable[ReaderForm]: """Read the contents of a stream as a Lisp expression. Callers may optionally specify a namespace resolver, which will be used to adjudic...
def read_str( s: str, resolver: Resolver = None, data_readers: DataReaders = None, eof: Any = None, is_eof_error: bool = False, ) -> Iterable[ReaderForm]: """Read the contents of a string as a Lisp expression. Keyword arguments to this function have the same meanings as those of basilis...
def read_file( filename: str, resolver: Resolver = None, data_readers: DataReaders = None, eof: Any = None, is_eof_error: bool = False, ) -> Iterable[ReaderForm]: """Read the contents of a file as a Lisp expression. Keyword arguments to this function have the same meanings as those of b...
def _update_loc(self, c): """Update the internal line and column buffers after a new character is added. The column number is set to 0, so the first character on the next line is column number 1.""" if newline_chars.match(c): self._col.append(0) self._lin...
def pushback(self) -> None: """Push one character back onto the stream, allowing it to be read again.""" if abs(self._idx - 1) > self._pushback_depth: raise IndexError("Exceeded pushback depth") self._idx -= 1
def next_token(self) -> str: """Advance the stream forward by one character and return the next token in the stream.""" if self._idx < StreamReader.DEFAULT_INDEX: self._idx += 1 else: c = self._stream.read(1) self._update_loc(c) self._buffe...
def _basilisp_bytecode( mtime: int, source_size: int, code: List[types.CodeType] ) -> bytes: """Return the bytes for a Basilisp bytecode cache file.""" data = bytearray(MAGIC_NUMBER) data.extend(_w_long(mtime)) data.extend(_w_long(source_size)) data.extend(marshal.dumps(code)) # type: ignore ...
def _get_basilisp_bytecode( fullname: str, mtime: int, source_size: int, cache_data: bytes ) -> List[types.CodeType]: """Unmarshal the bytes from a Basilisp bytecode cache file, validating the file header prior to returning. If the file header does not match, throw an exception.""" exc_details = {"n...
def _cache_from_source(path: str) -> str: """Return the path to the cached file for the given path. The original path does not have to exist.""" cache_path, cache_file = os.path.split(importlib.util.cache_from_source(path)) filename, _ = os.path.splitext(cache_file) return os.path.join(cache_path, f...
def hook_imports(): """Hook into Python's import machinery with a custom Basilisp code importer. Once this is called, Basilisp code may be called from within Python code using standard `import module.submodule` syntax.""" if any([isinstance(o, BasilispImporter) for o in sys.meta_path]): ret...
def find_spec( self, fullname: str, path, # Optional[List[str]] # MyPy complains this is incompatible with supertype target: types.ModuleType = None, ) -> Optional[importlib.machinery.ModuleSpec]: """Find the ModuleSpec for the specified Basilisp module. Returns Non...
def _exec_cached_module( self, fullname: str, loader_state: Mapping[str, str], path_stats: Mapping[str, int], module: types.ModuleType, ): """Load and execute a cached Basilisp module.""" filename = loader_state["filename"] cache_filename = loader_stat...
def _exec_module( self, fullname: str, loader_state: Mapping[str, str], path_stats: Mapping[str, int], module: types.ModuleType, ): """Load and execute a non-cached Basilisp module.""" filename = loader_state["filename"] cache_filename = loader_state["...
def exec_module(self, module): """Compile the Basilisp module into Python code. Basilisp is fundamentally a form-at-a-time compilation, meaning that each form in a module may require code compiled from an earlier form, so we incrementally compile a Python module by evaluating a single t...
def symbol(name: str, ns: Optional[str] = None, meta=None) -> Symbol: """Create a new symbol.""" return Symbol(name, ns=ns, meta=meta)
def complete( text: str, kw_cache: atom.Atom["PMap[int, Keyword]"] = __INTERN ) -> Iterable[str]: """Return an iterable of possible completions for the given text.""" assert text.startswith(":") interns = kw_cache.deref() text = text[1:] if "/" in text: prefix, suffix = text.split("/", ...
def __get_or_create( kw_cache: "PMap[int, Keyword]", h: int, name: str, ns: Optional[str] ) -> PMap: """Private swap function used to either get the interned keyword instance from the input string.""" if h in kw_cache: return kw_cache kw = Keyword(name, ns=ns) return kw_cache.set(h, kw)
def keyword( name: str, ns: Optional[str] = None, kw_cache: atom.Atom["PMap[int, Keyword]"] = __INTERN, ) -> Keyword: """Create a new keyword.""" h = hash((name, ns)) return kw_cache.swap(__get_or_create, h, name, ns)[h]
def _chain_py_ast(*genned: GeneratedPyAST,) -> Tuple[PyASTStream, PyASTStream]: """Chain a sequence of generated Python ASTs into a tuple of dependency nodes""" deps = chain.from_iterable(map(lambda n: n.dependencies, genned)) nodes = map(lambda n: n.node, genned) return deps, nodes
def _load_attr(name: str, ctx: ast.AST = ast.Load()) -> ast.Attribute: """Generate recursive Python Attribute AST nodes for resolving nested names.""" attrs = name.split(".") def attr_node(node, idx): if idx >= len(attrs): node.ctx = ctx return node return attr_n...
def _simple_ast_generator(gen_ast): """Wrap simpler AST generators to return a GeneratedPyAST.""" @wraps(gen_ast) def wrapped_ast_generator(ctx: GeneratorContext, form: LispForm) -> GeneratedPyAST: return GeneratedPyAST(node=gen_ast(ctx, form)) return wrapped_ast_generator
def _collection_ast( ctx: GeneratorContext, form: Iterable[Node] ) -> Tuple[PyASTStream, PyASTStream]: """Turn a collection of Lisp forms into Python AST nodes.""" return _chain_py_ast(*map(partial(gen_py_ast, ctx), form))
def _clean_meta(form: IMeta) -> LispForm: """Remove reader metadata from the form's meta map.""" assert form.meta is not None, "Form must have non-null 'meta' attribute" meta = form.meta.dissoc(reader.READER_LINE_KW, reader.READER_COL_KW) if len(meta) == 0: return None return cast(lmap.Map, ...
def _ast_with_loc( py_ast: GeneratedPyAST, env: NodeEnv, include_dependencies: bool = False ) -> GeneratedPyAST: """Hydrate Generated Python AST nodes with line numbers and column offsets if they exist in the node environment.""" if env.line is not None: py_ast.node.lineno = env.line if...
def _with_ast_loc(f): """Wrap a generator function in a decorator to supply line and column information to the returned Python AST node. Dependency nodes will not be hydrated, functions whose returns need dependency nodes to be hydrated should use `_with_ast_loc_deps` below.""" @wraps(f) def wi...
def _with_ast_loc_deps(f): """Wrap a generator function in a decorator to supply line and column information to the returned Python AST node and dependency nodes. Dependency nodes should likely only be included if they are new nodes created in the same function wrapped by this function. Otherwise, depe...
def _is_dynamic(v: Var) -> bool: """Return True if the Var holds a value which should be compiled to a dynamic Var access.""" return ( Maybe(v.meta) .map(lambda m: m.get(SYM_DYNAMIC_META_KEY, None)) # type: ignore .or_else_get(False) )
def _is_redefable(v: Var) -> bool: """Return True if the Var can be redefined.""" return ( Maybe(v.meta) .map(lambda m: m.get(SYM_REDEF_META_KEY, None)) # type: ignore .or_else_get(False) )
def statementize(e: ast.AST) -> ast.AST: """Transform non-statements into ast.Expr nodes so they can stand alone as statements.""" # noinspection PyPep8 if isinstance( e, ( ast.Assign, ast.AnnAssign, ast.AugAssign, ast.Expr, ast...
def expressionize( body: GeneratedPyAST, fn_name: str, args: Optional[Iterable[ast.arg]] = None, vargs: Optional[ast.arg] = None, ) -> ast.FunctionDef: """Given a series of expression AST nodes, create a function AST node with the given name that can be called and will return the result of t...
def __should_warn_on_redef( ctx: GeneratorContext, defsym: sym.Symbol, safe_name: str, def_meta: lmap.Map ) -> bool: """Return True if the compiler should emit a warning about this name being redefined.""" no_warn_on_redef = def_meta.entry(SYM_NO_WARN_ON_REDEF_META_KEY, False) if no_warn_on_redef: ...
def _def_to_py_ast( # pylint: disable=too-many-branches ctx: GeneratorContext, node: Def ) -> GeneratedPyAST: """Return a Python AST Node for a `def` expression.""" assert node.op == NodeOp.DEF defsym = node.name is_defn = False if node.init is not None: # Since Python function defini...
def _deftype_to_py_ast( # pylint: disable=too-many-branches ctx: GeneratorContext, node: DefType ) -> GeneratedPyAST: """Return a Python AST Node for a `deftype*` expression.""" assert node.op == NodeOp.DEFTYPE type_name = munge(node.name) ctx.symbol_table.new_symbol(sym.symbol(node.name), type_nam...
def _do_to_py_ast(ctx: GeneratorContext, node: Do) -> GeneratedPyAST: """Return a Python AST Node for a `do` expression.""" assert node.op == NodeOp.DO assert not node.is_body body_ast = GeneratedPyAST.reduce( *map(partial(gen_py_ast, ctx), chain(node.statements, [node.ret])) ) fn_body...
def _synthetic_do_to_py_ast(ctx: GeneratorContext, node: Do) -> GeneratedPyAST: """Return AST elements generated from reducing a synthetic Lisp :do node (e.g. a :do node which acts as a body for another node).""" assert node.op == NodeOp.DO assert node.is_body # TODO: investigate how to handle recu...
def __fn_name(s: Optional[str]) -> str: """Generate a safe Python function name from a function name symbol. If no symbol is provided, generate a name with a default prefix.""" return genname("__" + munge(Maybe(s).or_else_get(_FN_PREFIX)))
def __fn_args_to_py_ast( ctx: GeneratorContext, params: Iterable[Binding], body: Do ) -> Tuple[List[ast.arg], Optional[ast.arg], List[ast.AST]]: """Generate a list of Python AST nodes from function method parameters.""" fn_args, varg = [], None fn_body_ast: List[ast.AST] = [] for binding in params: ...
def __single_arity_fn_to_py_ast( ctx: GeneratorContext, node: Fn, method: FnMethod, def_name: Optional[str] = None, meta_node: Optional[MetaNode] = None, ) -> GeneratedPyAST: """Return a Python AST node for a function with a single arity.""" assert node.op == NodeOp.FN assert method.op =...
def __multi_arity_dispatch_fn( # pylint: disable=too-many-arguments,too-many-locals ctx: GeneratorContext, name: str, arity_map: Mapping[int, str], default_name: Optional[str] = None, max_fixed_arity: Optional[int] = None, meta_node: Optional[MetaNode] = None, is_async: bool = False, ) -> G...
def __multi_arity_fn_to_py_ast( # pylint: disable=too-many-locals ctx: GeneratorContext, node: Fn, methods: Collection[FnMethod], def_name: Optional[str] = None, meta_node: Optional[MetaNode] = None, ) -> GeneratedPyAST: """Return a Python AST node for a function with multiple arities.""" a...
def _fn_to_py_ast( ctx: GeneratorContext, node: Fn, def_name: Optional[str] = None, meta_node: Optional[MetaNode] = None, ) -> GeneratedPyAST: """Return a Python AST Node for a `fn` expression.""" assert node.op == NodeOp.FN if len(node.methods) == 1: return __single_arity_fn_to_py_a...
def __if_body_to_py_ast( ctx: GeneratorContext, node: Node, result_name: str ) -> GeneratedPyAST: """Generate custom `if` nodes to handle `recur` bodies. Recur nodes can appear in the then and else expressions of `if` forms. Recur nodes generate Python `continue` statements, which we would otherwise ...
def _if_to_py_ast(ctx: GeneratorContext, node: If) -> GeneratedPyAST: """Generate an intermediate if statement which assigns to a temporary variable, which is returned as the expression value at the end of evaluation. Every expression in Basilisp is true if it is not the literal values nil or false...
def _import_to_py_ast(ctx: GeneratorContext, node: Import) -> GeneratedPyAST: """Return a Python AST node for a Basilisp `import*` expression.""" assert node.op == NodeOp.IMPORT last = None deps: List[ast.AST] = [] for alias in node.aliases: safe_name = munge(alias.name) try: ...
def _invoke_to_py_ast(ctx: GeneratorContext, node: Invoke) -> GeneratedPyAST: """Return a Python AST Node for a Basilisp function invocation.""" assert node.op == NodeOp.INVOKE fn_ast = gen_py_ast(ctx, node.fn) args_deps, args_nodes = _collection_ast(ctx, node.args) return GeneratedPyAST( ...