INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Hydrate Generated Python AST nodes with line numbers and column offsets if they exist in the node environment.
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...
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.
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...
Wrap a generator function in a decorator to supply line and column information to the returned Python AST node and dependency nodes.
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...
Return True if the Var holds a value which should be compiled to a dynamic Var access.
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) )
Return True if the Var can be redefined.
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) )
Transform non - statements into ast. Expr nodes so they can stand alone as statements.
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...
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 the final expression in the input body nodes.
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...
Return True if the compiler should emit a warning about this name being redefined.
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: ...
Return a Python AST Node for a def expression.
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...
Return a Python AST Node for a deftype * expression.
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...
Return a Python AST Node for a do expression.
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...
Return AST elements generated from reducing a synthetic Lisp: do node ( e. g. a: do node which acts as a body for another node ).
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...
Generate a safe Python function name from a function name symbol. If no symbol is provided generate a name with a default prefix.
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)))
Generate a list of Python AST nodes from function method parameters.
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: ...
Return a Python AST node for a function with a single arity.
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 =...
Return the Python AST nodes for a argument - length dispatch function for multi - arity functions.
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...
Return a Python AST node for a function with multiple arities.
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...
Return a Python AST Node for a fn expression.
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...
Generate custom if nodes to handle recur bodies.
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 ...
Generate an intermediate if statement which assigns to a temporary variable which is returned as the expression value at the end of evaluation.
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...
Return a Python AST node for a Basilisp import * expression.
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: ...
Return a Python AST Node for a Basilisp function invocation.
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( ...
Return a Python AST Node for a let * expression.
def _let_to_py_ast(ctx: GeneratorContext, node: Let) -> GeneratedPyAST: """Return a Python AST Node for a `let*` expression.""" assert node.op == NodeOp.LET with ctx.new_symbol_table("let"): let_body_ast: List[ast.AST] = [] for binding in node.bindings: init_node = binding.init ...
Return a Python AST Node for a loop * expression.
def _loop_to_py_ast(ctx: GeneratorContext, node: Loop) -> GeneratedPyAST: """Return a Python AST Node for a `loop*` expression.""" assert node.op == NodeOp.LOOP with ctx.new_symbol_table("loop"): binding_names = [] init_bindings: List[ast.AST] = [] for binding in node.bindings: ...
Return a Python AST Node for a quote expression.
def _quote_to_py_ast(ctx: GeneratorContext, node: Quote) -> GeneratedPyAST: """Return a Python AST Node for a `quote` expression.""" assert node.op == NodeOp.QUOTE return _const_node_to_py_ast(ctx, node.expr)
Return a Python AST node for recur occurring inside a fn *.
def __fn_recur_to_py_ast(ctx: GeneratorContext, node: Recur) -> GeneratedPyAST: """Return a Python AST node for `recur` occurring inside a `fn*`.""" assert node.op == NodeOp.RECUR assert ctx.recur_point.is_variadic is not None recur_nodes: List[ast.AST] = [] recur_deps: List[ast.AST] = [] for ex...
Return a Python AST node for recur occurring inside a deftype * method.
def __deftype_method_recur_to_py_ast( ctx: GeneratorContext, node: Recur ) -> GeneratedPyAST: """Return a Python AST node for `recur` occurring inside a `deftype*` method.""" assert node.op == NodeOp.RECUR recur_nodes: List[ast.AST] = [] recur_deps: List[ast.AST] = [] for expr in node.exprs: ...
Return a Python AST node for recur occurring inside a loop.
def __loop_recur_to_py_ast(ctx: GeneratorContext, node: Recur) -> GeneratedPyAST: """Return a Python AST node for `recur` occurring inside a `loop`.""" assert node.op == NodeOp.RECUR recur_deps: List[ast.AST] = [] recur_targets: List[ast.Name] = [] recur_exprs: List[ast.AST] = [] for name, expr...
Return a Python AST Node for a recur expression.
def _recur_to_py_ast(ctx: GeneratorContext, node: Recur) -> GeneratedPyAST: """Return a Python AST Node for a `recur` expression. Note that `recur` nodes can only legally appear in two AST locations: (1) in :then or :else expressions in :if nodes, and (2) in :ret expressions in :do nodes As su...
Return a Python AST Node for a set! expression.
def _set_bang_to_py_ast(ctx: GeneratorContext, node: SetBang) -> GeneratedPyAST: """Return a Python AST Node for a `set!` expression.""" assert node.op == NodeOp.SET_BANG val_temp_name = genname("set_bang_val") val_ast = gen_py_ast(ctx, node.val) target = node.target assert isinstance( ...
Return a Python AST Node for a throw expression.
def _throw_to_py_ast(ctx: GeneratorContext, node: Throw) -> GeneratedPyAST: """Return a Python AST Node for a `throw` expression.""" assert node.op == NodeOp.THROW throw_fn = genname(_THROW_PREFIX) exc_ast = gen_py_ast(ctx, node.exception) raise_body = ast.Raise(exc=exc_ast.node, cause=None) r...
Return a Python AST Node for a try expression.
def _try_to_py_ast(ctx: GeneratorContext, node: Try) -> GeneratedPyAST: """Return a Python AST Node for a `try` expression.""" assert node.op == NodeOp.TRY try_expr_name = genname("try_expr") body_ast = _synthetic_do_to_py_ast(ctx, node.body) catch_handlers = list( map(partial(__catch_to_p...
Generate a Python AST node for accessing a locally defined Python variable.
def _local_sym_to_py_ast( ctx: GeneratorContext, node: Local, is_assigning: bool = False ) -> GeneratedPyAST: """Generate a Python AST node for accessing a locally defined Python variable.""" assert node.op == NodeOp.LOCAL sym_entry = ctx.symbol_table.find_symbol(sym.symbol(node.name)) assert sym_e...
Generate Var. find calls for the named symbol.
def __var_find_to_py_ast( var_name: str, ns_name: str, py_var_ctx: ast.AST ) -> GeneratedPyAST: """Generate Var.find calls for the named symbol.""" return GeneratedPyAST( node=ast.Attribute( value=ast.Call( func=_FIND_VAR_FN_NAME, args=[ ...
Generate a Python AST node for accessing a Var.
def _var_sym_to_py_ast( ctx: GeneratorContext, node: VarRef, is_assigning: bool = False ) -> GeneratedPyAST: """Generate a Python AST node for accessing a Var. If the Var is marked as :dynamic or :redef or the compiler option USE_VAR_INDIRECTION is active, do not compile to a direct access. If the ...
Generate a Python AST node for Python interop method calls.
def _interop_call_to_py_ast(ctx: GeneratorContext, node: HostCall) -> GeneratedPyAST: """Generate a Python AST node for Python interop method calls.""" assert node.op == NodeOp.HOST_CALL target_ast = gen_py_ast(ctx, node.target) args_deps, args_nodes = _collection_ast(ctx, node.args) return Genera...
Generate a Python AST node for Python interop property access.
def _interop_prop_to_py_ast( ctx: GeneratorContext, node: HostField, is_assigning: bool = False ) -> GeneratedPyAST: """Generate a Python AST node for Python interop property access.""" assert node.op == NodeOp.HOST_FIELD target_ast = gen_py_ast(ctx, node.target) return GeneratedPyAST( nod...
Generate a Python AST node for accessing a potential Python module variable name.
def _maybe_class_to_py_ast(_: GeneratorContext, node: MaybeClass) -> GeneratedPyAST: """Generate a Python AST node for accessing a potential Python module variable name.""" assert node.op == NodeOp.MAYBE_CLASS return GeneratedPyAST( node=ast.Name( id=Maybe(_MODULE_ALIASES.get(node.cl...
Generate a Python AST node for accessing a potential Python module variable name with a namespace.
def _maybe_host_form_to_py_ast( _: GeneratorContext, node: MaybeHostForm ) -> GeneratedPyAST: """Generate a Python AST node for accessing a potential Python module variable name with a namespace.""" assert node.op == NodeOp.MAYBE_HOST_FORM return GeneratedPyAST( node=_load_attr( ...
Generate a Python AST node for Python interop method calls.
def _with_meta_to_py_ast( ctx: GeneratorContext, node: WithMeta, **kwargs ) -> GeneratedPyAST: """Generate a Python AST node for Python interop method calls.""" assert node.op == NodeOp.WITH_META handle_expr = _WITH_META_EXPR_HANDLER.get(node.expr.op) assert ( handle_expr is not None ),...
Generate Python AST nodes for constant Lisp forms.
def _const_val_to_py_ast(ctx: GeneratorContext, form: LispForm) -> GeneratedPyAST: """Generate Python AST nodes for constant Lisp forms. Nested values in collections for :const nodes are not parsed, so recursive structures need to call into this function to generate Python AST nodes for nested elements...
Turn a quoted collection literal of Lisp forms into Python AST nodes.
def _collection_literal_to_py_ast( ctx: GeneratorContext, form: Iterable[LispForm] ) -> Iterable[GeneratedPyAST]: """Turn a quoted collection literal of Lisp forms into Python AST nodes. This function can only handle constant values. It does not call back into the generic AST generators, so only consta...
Generate Python AST nodes for a: const Lisp AST node.
def _const_node_to_py_ast(ctx: GeneratorContext, lisp_ast: Const) -> GeneratedPyAST: """Generate Python AST nodes for a :const Lisp AST node. Nested values in collections for :const nodes are not parsed. Consequently, this function cannot be called recursively for those nested values. Instead, call `_c...
Take a Lisp AST node as an argument and produce zero or more Python AST nodes.
def gen_py_ast(ctx: GeneratorContext, lisp_ast: Node) -> GeneratedPyAST: """Take a Lisp AST node as an argument and produce zero or more Python AST nodes. This is the primary entrypoint for generating AST nodes from Lisp syntax. It may be called recursively to compile child forms.""" op: NodeOp = l...
Generate the Python Import AST node for importing all required language support modules.
def _module_imports(ctx: GeneratorContext) -> Iterable[ast.Import]: """Generate the Python Import AST node for importing all required language support modules.""" # Yield `import basilisp` so code attempting to call fully qualified # `basilisp.lang...` modules don't result in compiler errors yield a...
Generate the Python From... Import AST node for importing language support modules.
def _from_module_import() -> ast.ImportFrom: """Generate the Python From ... Import AST node for importing language support modules.""" return ast.ImportFrom( module="basilisp.lang.runtime", names=[ast.alias(name="Var", asname=_VAR_ALIAS)], level=0, )
Assign a Python variable named ns_var to the value of the current namespace.
def _ns_var( py_ns_var: str = _NS_VAR, lisp_ns_var: str = LISP_NS_VAR, lisp_ns_ns: str = CORE_NS ) -> ast.Assign: """Assign a Python variable named `ns_var` to the value of the current namespace.""" return ast.Assign( targets=[ast.Name(id=py_ns_var, ctx=ast.Store())], value=ast.Call( ...
Bootstrap a new module with imports and other boilerplate.
def py_module_preamble(ctx: GeneratorContext,) -> GeneratedPyAST: """Bootstrap a new module with imports and other boilerplate.""" preamble: List[ast.AST] = [] preamble.extend(_module_imports(ctx)) preamble.append(_from_module_import()) preamble.append(_ns_var()) return GeneratedPyAST(node=ast.N...
If True warn when a Var reference cannot be direct linked ( iff use_var_indirection is False )..
def warn_on_var_indirection(self) -> bool: """If True, warn when a Var reference cannot be direct linked (iff use_var_indirection is False)..""" return not self.use_var_indirection and self._opts.entry( WARN_ON_VAR_INDIRECTION, True )
Creates a new set.
def set(members: Iterable[T], meta=None) -> Set[T]: # pylint:disable=redefined-builtin """Creates a new set.""" return Set(pset(members), meta=meta)
Creates a new set from members.
def s(*members: T, meta=None) -> Set[T]: """Creates a new set from members.""" return Set(pset(members), meta=meta)
Return a list of body nodes trimming out unreachable code ( any statements appearing after break continue and return nodes ).
def _filter_dead_code(nodes: Iterable[ast.AST]) -> List[ast.AST]: """Return a list of body nodes, trimming out unreachable code (any statements appearing after `break`, `continue`, and `return` nodes).""" new_nodes: List[ast.AST] = [] for node in nodes: if isinstance(node, (ast.Break, ast.Contin...
Eliminate dead code from except handler bodies.
def visit_ExceptHandler(self, node: ast.ExceptHandler) -> Optional[ast.AST]: """Eliminate dead code from except handler bodies.""" new_node = self.generic_visit(node) assert isinstance(new_node, ast.ExceptHandler) return ast.copy_location( ast.ExceptHandler( t...
Eliminate no - op constant expressions which are in the tree as standalone statements.
def visit_Expr(self, node: ast.Expr) -> Optional[ast.Expr]: """Eliminate no-op constant expressions which are in the tree as standalone statements.""" if isinstance( node.value, ( ast.Constant, # type: ignore ast.Name, ast....
Eliminate dead code from function bodies.
def visit_FunctionDef(self, node: ast.FunctionDef) -> Optional[ast.AST]: """Eliminate dead code from function bodies.""" new_node = self.generic_visit(node) assert isinstance(new_node, ast.FunctionDef) return ast.copy_location( ast.FunctionDef( name=new_node.n...
Eliminate dead code from if/ elif bodies.
def visit_If(self, node: ast.If) -> Optional[ast.AST]: """Eliminate dead code from if/elif bodies.""" new_node = self.generic_visit(node) assert isinstance(new_node, ast.If) return ast.copy_location( ast.If( test=new_node.test, body=_filter_dea...
Eliminate dead code from while bodies.
def visit_While(self, node: ast.While) -> Optional[ast.AST]: """Eliminate dead code from while bodies.""" new_node = self.generic_visit(node) assert isinstance(new_node, ast.While) return ast.copy_location( ast.While( test=new_node.test, body=_...
Eliminate dead code from except try bodies.
def visit_Try(self, node: ast.Try) -> Optional[ast.AST]: """Eliminate dead code from except try bodies.""" new_node = self.generic_visit(node) assert isinstance(new_node, ast.Try) return ast.copy_location( ast.Try( body=_filter_dead_code(new_node.body), ...
Create a new empty Basilisp Python module. Modules are created for each Namespace when it is created.
def _new_module(name: str, doc=None) -> types.ModuleType: """Create a new empty Basilisp Python module. Modules are created for each Namespace when it is created.""" mod = types.ModuleType(name, doc=doc) mod.__loader__ = None mod.__package__ = None mod.__spec__ = None mod.__basilisp_bootstra...
If o is a ISeq return the first element from o. If o is None return None. Otherwise coerces o to a Seq and returns the first.
def first(o): """If o is a ISeq, return the first element from o. If o is None, return None. Otherwise, coerces o to a Seq and returns the first.""" if o is None: return None if isinstance(o, ISeq): return o.first s = to_seq(o) if s is None: return None return s.first
If o is a ISeq return the elements after the first in o. If o is None returns an empty seq. Otherwise coerces o to a seq and returns the rest.
def rest(o) -> Optional[ISeq]: """If o is a ISeq, return the elements after the first in o. If o is None, returns an empty seq. Otherwise, coerces o to a seq and returns the rest.""" if o is None: return None if isinstance(o, ISeq): s = o.rest if s is None: return lse...
Returns the nth rest sequence of coll or coll if i is 0.
def nthrest(coll, i: int): """Returns the nth rest sequence of coll, or coll if i is 0.""" while True: if coll is None: return None if i == 0: return coll i -= 1 coll = rest(coll)
Returns the nth next sequence of coll.
def nthnext(coll, i: int) -> Optional[ISeq]: """Returns the nth next sequence of coll.""" while True: if coll is None: return None if i == 0: return to_seq(coll) i -= 1 coll = next_(coll)
Creates a new sequence where o is the first element and seq is the rest. If seq is None return a list containing o. If seq is not a ISeq attempt to coerce it to a ISeq and then cons o onto the resulting sequence.
def cons(o, seq) -> ISeq: """Creates a new sequence where o is the first element and seq is the rest. If seq is None, return a list containing o. If seq is not a ISeq, attempt to coerce it to a ISeq and then cons o onto the resulting sequence.""" if seq is None: return llist.l(o) if isinstan...
Coerce the argument o to a ISeq. If o is None return None.
def to_seq(o) -> Optional[ISeq]: """Coerce the argument o to a ISeq. If o is None, return None.""" if o is None: return None if isinstance(o, ISeq): return _seq_or_nil(o) if isinstance(o, ISeqable): return _seq_or_nil(o.seq()) return _seq_or_nil(lseq.sequence(o))
Concatenate the sequences given by seqs into a single ISeq.
def concat(*seqs) -> ISeq: """Concatenate the sequences given by seqs into a single ISeq.""" allseqs = lseq.sequence(itertools.chain(*filter(None, map(to_seq, seqs)))) if allseqs is None: return lseq.EMPTY return allseqs
Apply function f to the arguments provided. The last argument must always be coercible to a Seq. Intermediate arguments are not modified. For example: ( apply max [ 1 2 3 ] ) ; = > 3 ( apply max 4 [ 1 2 3 ] ) ; = > 4
def apply(f, args): """Apply function f to the arguments provided. The last argument must always be coercible to a Seq. Intermediate arguments are not modified. For example: (apply max [1 2 3]) ;=> 3 (apply max 4 [1 2 3]) ;=> 4""" final = list(args[:-1]) try: last = ar...
Apply function f to the arguments provided. The last argument must always be coercible to a Mapping. Intermediate arguments are not modified. For example: ( apply builtins/ dict {: a 1 } {: b 2 } ) ; = > #py {: a 1: b 2 } ( apply builtins/ dict {: a 1 } {: a 2 } ) ; = > #py {: a 2 }
def apply_kw(f, args): """Apply function f to the arguments provided. The last argument must always be coercible to a Mapping. Intermediate arguments are not modified. For example: (apply builtins/dict {:a 1} {:b 2}) ;=> #py {:a 1 :b 2} (apply builtins/dict {:a 1} {:a 2}) ;=> #py {:a...
Returns the ith element of coll ( 0 - indexed ) if it exists. None otherwise. If i is out of bounds throws an IndexError unless notfound is specified.
def nth(coll, i, notfound=__nth_sentinel): """Returns the ith element of coll (0-indexed), if it exists. None otherwise. If i is out of bounds, throws an IndexError unless notfound is specified.""" if coll is None: return None try: return coll[i] except IndexError as ex: ...
Associate keys to values in associative data structure m. If m is None returns a new Map with key - values kvs.
def assoc(m, *kvs): """Associate keys to values in associative data structure m. If m is None, returns a new Map with key-values kvs.""" if m is None: return lmap.Map.empty().assoc(*kvs) if isinstance(m, IAssociative): return m.assoc(*kvs) raise TypeError( f"Object of type {t...
Updates the value for key k in associative data structure m with the return value from calling f ( old_v * args ). If m is None use an empty map. If k is not in m old_v will be None.
def update(m, k, f, *args): """Updates the value for key k in associative data structure m with the return value from calling f(old_v, *args). If m is None, use an empty map. If k is not in m, old_v will be None.""" if m is None: return lmap.Map.empty().assoc(k, f(None, *args)) if isinstance...
Conjoin xs to collection. New elements may be added in different positions depending on the type of coll. conj returns the same type as coll. If coll is None return a list with xs conjoined.
def conj(coll, *xs): """Conjoin xs to collection. New elements may be added in different positions depending on the type of coll. conj returns the same type as coll. If coll is None, return a list with xs conjoined.""" if coll is None: l = llist.List.empty() return l.cons(*xs) if isi...
Return a function which is the partial application of f with args.
def partial(f, *args): """Return a function which is the partial application of f with args.""" @functools.wraps(f) def partial_f(*inner_args): return f(*itertools.chain(args, inner_args)) return partial_f
Dereference a Deref object and return its contents.
def deref(o, timeout_s=None, timeout_val=None): """Dereference a Deref object and return its contents. If o is an object implementing IBlockingDeref and timeout_s and timeout_val are supplied, deref will wait at most timeout_s seconds, returning timeout_val if timeout_s seconds elapse and o has not ...
Compare two objects by value. Unlike the standard Python equality operator this function does not consider 1 == True or 0 == False. All other equality operations are the same and performed using Python s equality operator.
def equals(v1, v2) -> bool: """Compare two objects by value. Unlike the standard Python equality operator, this function does not consider 1 == True or 0 == False. All other equality operations are the same and performed using Python's equality operator.""" if isinstance(v1, (bool, type(None))) or isins...
Division reducer. If both arguments are integers return a Fraction. Otherwise return the true division of x and y.
def divide(x: LispNumber, y: LispNumber) -> LispNumber: """Division reducer. If both arguments are integers, return a Fraction. Otherwise, return the true division of x and y.""" if isinstance(x, int) and isinstance(y, int): return Fraction(x, y) return x / y
Return a sorted sequence of the elements in coll. If a comparator function f is provided compare elements in coll using f.
def sort(coll, f=None) -> Optional[ISeq]: """Return a sorted sequence of the elements in coll. If a comparator function f is provided, compare elements in coll using f.""" return to_seq(sorted(coll, key=Maybe(f).map(functools.cmp_to_key).value))
Return true if o contains the key k.
def contains(coll, k): """Return true if o contains the key k.""" if isinstance(coll, IAssociative): return coll.contains(k) return k in coll
Return the value of k in m. Return default if k not found in m.
def get(m, k, default=None): """Return the value of k in m. Return default if k not found in m.""" if isinstance(m, IAssociative): return m.entry(k, default=default) try: return m[k] except (KeyError, IndexError, TypeError) as e: logger.debug("Ignored %s: %s", type(e).__name__, ...
Recursively convert Python collections into Lisp collections.
def to_lisp(o, keywordize_keys: bool = True): """Recursively convert Python collections into Lisp collections.""" if not isinstance(o, (dict, frozenset, list, set, tuple)): return o else: # pragma: no cover return _to_lisp_backup(o, keywordize_keys=keywordize_keys)
Recursively convert Lisp collections into Python collections.
def to_py(o, keyword_fn: Callable[[kw.Keyword], Any] = _kw_name): """Recursively convert Lisp collections into Python collections.""" if isinstance(o, ISeq): return _to_py_list(o, keyword_fn=keyword_fn) elif not isinstance( o, (IPersistentList, IPersistentMap, IPersistentSet, IPersistentVect...
Produce a string representation of an object. If human_readable is False the string representation of Lisp objects is something that can be read back in by the reader as the same object.
def lrepr(o, human_readable: bool = False) -> str: """Produce a string representation of an object. If human_readable is False, the string representation of Lisp objects is something that can be read back in by the reader as the same object.""" core_ns = Namespace.get(sym.symbol(CORE_NS)) assert cor...
Completer function for Python s readline/ libedit implementation.
def repl_complete(text: str, state: int) -> Optional[str]: """Completer function for Python's readline/libedit implementation.""" # Can't complete Keywords, Numerals if __NOT_COMPLETEABLE.match(text): return None elif text.startswith(":"): completions = kw.complete(text) else: ...
Collect Python starred arguments into a Basilisp list.
def _collect_args(args) -> ISeq: """Collect Python starred arguments into a Basilisp list.""" if isinstance(args, tuple): return llist.list(args) raise TypeError("Python variadic arguments should always be a tuple")
Trampoline a function repeatedly until it is finished recurring to help avoid stack growth.
def _trampoline(f): """Trampoline a function repeatedly until it is finished recurring to help avoid stack growth.""" @functools.wraps(f) def trampoline(*args, **kwargs): while True: ret = f(*args, **kwargs) if isinstance(ret, _TrampolineArgs): args = ret...
Decorator to set attributes on a function. Returns the original function after setting the attributes named by the keyword arguments.
def _with_attrs(**kwargs): """Decorator to set attributes on a function. Returns the original function after setting the attributes named by the keyword arguments.""" def decorator(f): for k, v in kwargs.items(): setattr(f, k, v) return f return decorator
Return a new function with the given meta. If the function f already has a meta map then merge the
def _fn_with_meta(f, meta: Optional[lmap.Map]): """Return a new function with the given meta. If the function f already has a meta map, then merge the """ if not isinstance(meta, lmap.Map): raise TypeError("meta must be a map") if inspect.iscoroutinefunction(f): @functools.wraps(f) ...
Create a Basilisp function setting meta and supplying a with_meta method implementation.
def _basilisp_fn(f): """Create a Basilisp function, setting meta and supplying a with_meta method implementation.""" assert not hasattr(f, "meta") f._basilisp_fn = True f.meta = None f.with_meta = partial(_fn_with_meta, f) return f
Initialize the dynamic * ns * variable in the Namespace which_ns.
def init_ns_var(which_ns: str = CORE_NS, ns_var_name: str = NS_VAR_NAME) -> Var: """Initialize the dynamic `*ns*` variable in the Namespace `which_ns`.""" core_sym = sym.Symbol(which_ns) core_ns = Namespace.get_or_create(core_sym) ns_var = Var.intern(core_sym, sym.Symbol(ns_var_name), core_ns, dynamic=T...
Set the value of the dynamic variable * ns * in the current thread.
def set_current_ns( ns_name: str, module: types.ModuleType = None, ns_var_name: str = NS_VAR_NAME, ns_var_ns: str = NS_VAR_NS, ) -> Var: """Set the value of the dynamic variable `*ns*` in the current thread.""" symbol = sym.Symbol(ns_name) ns = Namespace.get_or_create(symbol, module=module) ...
Context manager for temporarily changing the value of basilisp. core/ * ns *.
def ns_bindings( ns_name: str, module: types.ModuleType = None, ns_var_name: str = NS_VAR_NAME, ns_var_ns: str = NS_VAR_NS, ): """Context manager for temporarily changing the value of basilisp.core/*ns*.""" symbol = sym.Symbol(ns_name) ns = Namespace.get_or_create(symbol, module=module) ...
Context manager to pop the most recent bindings for basilisp. core/ * ns * after completion of the code under management.
def remove_ns_bindings(ns_var_name: str = NS_VAR_NAME, ns_var_ns: str = NS_VAR_NS): """Context manager to pop the most recent bindings for basilisp.core/*ns* after completion of the code under management.""" ns_var_sym = sym.Symbol(ns_var_name, ns=ns_var_ns) ns_var = Maybe(Var.find(ns_var_sym)).or_else_...
Get the value of the dynamic variable * ns * in the current thread.
def get_current_ns( ns_var_name: str = NS_VAR_NAME, ns_var_ns: str = NS_VAR_NS ) -> Namespace: """Get the value of the dynamic variable `*ns*` in the current thread.""" ns_sym = sym.Symbol(ns_var_name, ns=ns_var_ns) ns: Namespace = Maybe(Var.find(ns_sym)).map(lambda v: v.value).or_else_raise( la...
Resolve the aliased symbol in the current namespace.
def resolve_alias(s: sym.Symbol, ns: Optional[Namespace] = None) -> sym.Symbol: """Resolve the aliased symbol in the current namespace.""" if s in _SPECIAL_FORMS: return s ns = Maybe(ns).or_else(get_current_ns) if s.ns is not None: aliased_ns = ns.get_alias(sym.symbol(s.ns)) if ...
Resolve the aliased symbol to a Var from the specified namespace or the current namespace if none is specified.
def resolve_var(s: sym.Symbol, ns: Optional[Namespace] = None) -> Optional[Var]: """Resolve the aliased symbol to a Var from the specified namespace, or the current namespace if none is specified.""" return Var.find(resolve_alias(s, ns))
Add generated Python code to a dynamic variable in which_ns.
def add_generated_python( generated_python: str, var_name: str = _GENERATED_PYTHON_VAR_NAME, which_ns: Optional[str] = None, ) -> None: """Add generated Python code to a dynamic variable in which_ns.""" if which_ns is None: which_ns = get_current_ns().name ns_sym = sym.Symbol(var_name, n...
Return the value of the * print - generated - python * dynamic variable.
def print_generated_python( var_name: str = _PRINT_GENERATED_PY_VAR_NAME, core_ns_name: str = CORE_NS ) -> bool: """Return the value of the `*print-generated-python*` dynamic variable.""" ns_sym = sym.Symbol(var_name, ns=core_ns_name) return ( Maybe(Var.find(ns_sym)) .map(lambda v: v.val...
Bootstrap the environment with functions that are are difficult to express with the very minimal lisp environment.
def bootstrap(ns_var_name: str = NS_VAR_NAME, core_ns_name: str = CORE_NS) -> None: """Bootstrap the environment with functions that are are difficult to express with the very minimal lisp environment.""" core_ns_sym = sym.symbol(core_ns_name) ns_var_sym = sym.symbol(ns_var_name, ns=core_ns_name) __...
Intern the value bound to the symbol name in namespace ns.
def intern( ns: sym.Symbol, name: sym.Symbol, val, dynamic: bool = False, meta=None ) -> "Var": """Intern the value bound to the symbol `name` in namespace `ns`.""" var_ns = Namespace.get_or_create(ns) var = var_ns.intern(name, Var(var_ns, name, dynamic=dynamic, meta=meta)) v...
Create a new unbound Var instance to the symbol name in namespace ns.
def intern_unbound( ns: sym.Symbol, name: sym.Symbol, dynamic: bool = False, meta=None ) -> "Var": """Create a new unbound `Var` instance to the symbol `name` in namespace `ns`.""" var_ns = Namespace.get_or_create(ns) return var_ns.intern(name, Var(var_ns, name, dynamic=dynamic, meta...