Search is not available for this dataset
text stringlengths 75 104k |
|---|
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
... |
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:
... |
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) |
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... |
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:
... |
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... |
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... |
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(
... |
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... |
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... |
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... |
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=[
... |
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 ... |
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... |
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... |
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... |
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(
... |
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
),... |
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... |
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... |
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... |
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... |
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... |
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,
) |
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(
... |
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... |
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
) |
def set(members: Iterable[T], meta=None) -> Set[T]: # pylint:disable=redefined-builtin
"""Creates a new set."""
return Set(pset(members), meta=meta) |
def s(*members: T, meta=None) -> Set[T]:
"""Creates a new set from members."""
return Set(pset(members), meta=meta) |
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... |
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... |
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.... |
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... |
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... |
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=_... |
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),
... |
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... |
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 |
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... |
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) |
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) |
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... |
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)) |
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 |
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... |
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... |
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:
... |
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... |
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... |
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... |
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 |
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
... |
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... |
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 |
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)) |
def contains(coll, k):
"""Return true if o contains the key k."""
if isinstance(coll, IAssociative):
return coll.contains(k)
return k in coll |
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__, ... |
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) |
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... |
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... |
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:
... |
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") |
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... |
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 |
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)
... |
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 |
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... |
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)
... |
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)
... |
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_... |
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... |
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 ... |
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)) |
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... |
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... |
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)
__... |
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... |
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... |
def find_in_ns(ns_sym: sym.Symbol, name_sym: sym.Symbol) -> "Optional[Var]":
"""Return the value current bound to the name `name_sym` in the namespace
specified by `ns_sym`."""
ns = Namespace.get(ns_sym)
if ns:
return ns.find(name_sym)
return None |
def find(ns_qualified_sym: sym.Symbol) -> "Optional[Var]":
"""Return the value currently bound to the name in the namespace specified
by `ns_qualified_sym`."""
ns = Maybe(ns_qualified_sym.ns).or_else_raise(
lambda: ValueError(
f"Namespace must be specified in Symbol {... |
def find_safe(ns_qualified_sym: sym.Symbol) -> "Var":
"""Return the Var currently bound to the name in the namespace specified
by `ns_qualified_sym`. If no Var is bound to that name, raise an exception.
This is a utility method to return useful debugging information when code
refers to ... |
def add_default_import(cls, module: str):
"""Add a gated default import to the default imports.
In particular, we need to avoid importing 'basilisp.core' before we have
finished macro-expanding."""
if module in cls.GATED_IMPORTS:
cls.DEFAULT_IMPORTS.swap(lambda s: s.cons(sym... |
def add_alias(self, alias: sym.Symbol, namespace: "Namespace") -> None:
"""Add a Symbol alias for the given Namespace."""
self._aliases.swap(lambda m: m.assoc(alias, namespace)) |
def intern(self, sym: sym.Symbol, var: Var, force: bool = False) -> Var:
"""Intern the Var given in this namespace mapped by the given Symbol.
If the Symbol already maps to a Var, this method _will not overwrite_
the existing Var mapping unless the force keyword argument is given
and is ... |
def _intern(
m: lmap.Map, sym: sym.Symbol, new_var: Var, force: bool = False
) -> lmap.Map:
"""Swap function used by intern to atomically intern a new variable in
the symbol mapping for this Namespace."""
var = m.entry(sym, None)
if var is None or force:
return m.... |
def find(self, sym: sym.Symbol) -> Optional[Var]:
"""Find Vars mapped by the given Symbol input or None if no Vars are
mapped by that Symbol."""
v = self.interns.entry(sym, None)
if v is None:
return self.refers.entry(sym, None)
return v |
def add_import(
self, sym: sym.Symbol, module: types.ModuleType, *aliases: sym.Symbol
) -> None:
"""Add the Symbol as an imported Symbol in this Namespace. If aliases are given,
the aliases will be applied to the """
self._imports.swap(lambda m: m.assoc(sym, module))
if alias... |
def get_import(self, sym: sym.Symbol) -> Optional[types.ModuleType]:
"""Return the module if a moduled named by sym has been imported into
this Namespace, None otherwise.
First try to resolve a module directly with the given name. If no module
can be resolved, attempt to resolve the mod... |
def add_refer(self, sym: sym.Symbol, var: Var) -> None:
"""Refer var in this namespace under the name sym."""
if not var.is_private:
self._refers.swap(lambda s: s.assoc(sym, var)) |
def get_refer(self, sym: sym.Symbol) -> Optional[Var]:
"""Get the Var referred by Symbol or None if it does not exist."""
return self.refers.entry(sym, None) |
def __refer_all(cls, refers: lmap.Map, other_ns_interns: lmap.Map) -> lmap.Map:
"""Refer all _public_ interns from another namespace."""
final_refers = refers
for entry in other_ns_interns:
s: sym.Symbol = entry.key
var: Var = entry.value
if not var.is_private... |
def refer_all(self, other_ns: "Namespace"):
"""Refer all the Vars in the other namespace."""
self._refers.swap(Namespace.__refer_all, other_ns.interns) |
def __get_or_create(
ns_cache: NamespaceMap,
name: sym.Symbol,
module: types.ModuleType = None,
core_ns_name=CORE_NS,
) -> lmap.Map:
"""Private swap function used by `get_or_create` to atomically swap
the new namespace map into the global cache."""
ns = ns_cac... |
def get_or_create(
cls, name: sym.Symbol, module: types.ModuleType = None
) -> "Namespace":
"""Get the namespace bound to the symbol `name` in the global namespace
cache, creating it if it does not exist.
Return the namespace."""
return cls._NAMESPACES.swap(Namespace.__get_or... |
def get(cls, name: sym.Symbol) -> "Optional[Namespace]":
"""Get the namespace bound to the symbol `name` in the global namespace
cache. Return the namespace if it exists or None otherwise.."""
return cls._NAMESPACES.deref().entry(name, None) |
def remove(cls, name: sym.Symbol) -> Optional["Namespace"]:
"""Remove the namespace bound to the symbol `name` in the global
namespace cache and return that namespace.
Return None if the namespace did not exist in the cache."""
while True:
oldval: lmap.Map = cls._NAMESPACES.d... |
def __completion_matcher(text: str) -> CompletionMatcher:
"""Return a function which matches any symbol keys from map entries
against the given text."""
def is_match(entry: Tuple[sym.Symbol, Any]) -> bool:
return entry[0].name.startswith(text)
return is_match |
def __complete_alias(
self, prefix: str, name_in_ns: Optional[str] = None
) -> Iterable[str]:
"""Return an iterable of possible completions matching the given
prefix from the list of aliased namespaces. If name_in_ns is given,
further attempt to refine the list to matching names in t... |
def __complete_imports_and_aliases(
self, prefix: str, name_in_module: Optional[str] = None
) -> Iterable[str]:
"""Return an iterable of possible completions matching the given
prefix from the list of imports and aliased imports. If name_in_module
is given, further attempt to refine ... |
def __complete_interns(
self, value: str, include_private_vars: bool = True
) -> Iterable[str]:
"""Return an iterable of possible completions matching the given
prefix from the list of interned Vars."""
if include_private_vars:
is_match = Namespace.__completion_matcher(va... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.