Builtins (virtual module)

Virtual module

Importing koskari.builtins assembles the standard library from compiled bootstrap sources. The bootstrap loader package is not documented here.

Constant-resolution fallbacks (for example True, False, None, and nil) are omitted from this reference.

Runtime features

Callables and predicates

!=

(!= VAL1 VAL2 *: VALS)

#dict

build_dict(*pairs, **kwargs) -> dict Build a dict from (key, value) pairs and keyword arguments.

#list

build_list(*args) -> list Build a list from arguments.

#list-append

list_append(list, item) -> None Append item to list; TypeError when list is not a list.

#set

build_set(*args) -> set Build a set from arguments.

#str

build_str(*args) -> str Join the str of each argument; an exact str is taken as it is.

#tuple

build_tuple(*args) -> tuple Build a tuple from arguments.

&

(& VAL AND_VAL *: AND_VALS)

*

(* VAL BY_VAL *: BY_VALS)

**

(** BASE EXP [MOD])

+

(+ VAL *: VALS)

-

(- VAL *: VALS)

/

(/ VAL DENOM *: DENOMS)

//

(// VAL DENOM *: DENOMS)

<

(< VAL1 VAL2 *: VALS)

<<(a, b, /)

Same as a << b.

<=

(<= VAL1 VAL2 *: VALS)

==

(== VAL1 VAL2 *: VALS)

>

(> VAL1 VAL2 *: VALS)

>=

(>= VAL1 VAL2 *: VALS)

>>(a, b, /)

Same as a >> b.

@

(@ VAL BY_VAL *: BY_VALS)

AttributeRef?(instance, /)

Check if an object is an instance.

ConstantRef?(instance, /)

Check if an object is an instance.

DynamicRef?(instance, /)

Check if an object is an instance.

ItemRef?(instance, /)

Check if an object is an instance.

MemoizedRef?(instance, /)

Check if an object is an instance.

None?(b, /)

Same as a is b.

ParamRef?(instance, /)

Check if an object is an instance.

ProcessResult?(instance, /)

Check if an object is an instance.

Ref?(instance, /)

Check if an object is an instance.

^

(^ VAL XOR_VAL *: XOR_VALS)

koskari.builtins.abs(x, /)

Return the absolute value of the argument.

active-pragma(key=None)

The pragma active in the current compilation turn, bound by the compiler into the active-compiler-pragma parameter. When no pragma is bound – a compiler built without one, or no compilation turn at all – a default pragma carrying every registered setting’s default answers instead. With no key, the pragma object; with a key, the value of that setting.

all?(iterable, /)

Return True if bool(x) is True for all values x in the iterable.

If the iterable is empty, return True.

any?(iterable, /)

Return True if bool(x) is True for any x in the iterable.

If the iterable is empty, return False.

apply-layout(block, target)

Apply a layout handler to a single block of form `(:#block: (HEAD ARG ...) ENTRY ...)`

Parameters:
  • block – the block to apply the layout handler to

  • target – a LayoutReader or a namespace whose module owns one

Returns:

the layout form

apply-layouts(blocks, target)

Walk a proper cons spine of forms and expand each :#block: through the layout handler namespace. Declared peer blocks are consumed from the cdr spine after each primary block; other forms are kept unchanged

Intended for binding as apply-blocks at runtime

Parameters:
  • blocks – proper cons list of forms

  • target – a LayoutReader or a namespace whose module owns one

Returns:

proper cons list of expanded forms

koskari.builtins.ascii(obj, /)

Return an ASCII-only representation of an object.

As repr(), return a string containing a printable representation of an object, but escape the non-ASCII characters in the string returned by repr() using \x, \u or \U escapes. This generates a string similar to that returned by repr() in Python 2.

koskari.builtins.bin(number, /)

Return the binary representation of an integer.

>>> bin(2796202)
'0b1010101010101010101010'
bool?(instance, /)

Check if an object is an instance.

bracket-cons

bracket_cons(head, *tail) -> new bracket-pair Like cons, but builds bracket-pair cells. No args implies bracket-nil.

bracket-splice(*segments)

The bracket analogue of the PAIR_SPLICE opcode: flatten the given segments (pairs, tuples, nil, or other iterables) into a single list whose leading cell is a bracket-pair. Only the head needs to be a bracket cell — repr is governed by the leading cell — so the tail stays plain pairs and no full-spine copy is made. An empty result is bracket-nil.

Parameters:

segments – the splice segments to concatenate

Returns:

the spliced bracket list

build-bare-syntax(name, slot, template)

Koskari runtime: (build-bare-syntax NAME SLOT TMPL), producing a Syntax carrying only a bare arm. SLOT names the called-by capture that TMPL refers to. Combine with + to attach the arm to an existing syntax

build-macro(name, *pattern_and_lambdas)

Koskari runtime: (build-macro NAME PAT LAMBDA ...)

build-proper(*values)

Create a proper list from the given values.

Parameters:

values – the values to include in the list

Returns:

a proper list, or nil if no values given

build-slice(start=None, stop=None, step=None)

Simple slice class constructor that accepts keyword arguments

build-special(name, *pattern_and_lambdas)

Koskari runtime: (build-special NAME PAT LAMBDA ...)

build-syntax(name, *pattern_template_pairs)

Koskari runtime: (build-syntax NAME ROW ...), each row a matcher function, its repeat variables, its pattern source and a template datum, as compile/syntax-rules and compile/syntax-match emit

bytearray?(instance, /)

Check if an object is an instance.

bytes?(instance, /)

Check if an object is an instance.

koskari.builtins.caddddr(p)
koskari.builtins.cadddr(p)
koskari.builtins.caddr(p)
koskari.builtins.cadr(p)
callable?(obj, /)

Return whether the object is callable (i.e., some kind of function).

Note that classes are callable, as are instances of classes with a __call__() method.

koskari.builtins.car(P) → object

Returns the head element of a koskari pair instance P.

koskari.builtins.cddddr(p)
koskari.builtins.cdddr(p)
koskari.builtins.cddr(p)
koskari.builtins.cdr(P) → object

Returns the tail element of a koskari pair instance P.

koskari.builtins.chr(i, /)

Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.

classmethod?(instance, /)

Check if an object is an instance.

koskari.builtins.compile(source_obj, ns)

Compile a source object into an Expression via the compiler from the given namespace

complex?(instance, /)

Check if an object is an instance.

koskari.builtins.cons(head, *tail) → new pair

Build a pair chain from the given sequence. No tail implies nil.

constantly?(instance, /)

Check if an object is an instance.

coroutine-fn(fn)

Convert an async function into a Python coroutine function. This is a compatibility layer for asyncio loops which specifically check for the coroutine type.

create-task(coro)

Create and schedule a Task from an awaitable, returning the Task itself. Tasks are handles: they are excluded from implicit auto-await, support cancellation and done-callbacks, and resolve under explicit await.

Python coroutines, Koskari Coroutines, and defers all pass asyncio.iscoroutine and schedule directly; exotic non-coroutine awaitables are adapted through as_coroutine first. Note that passing a defer consumes it – the Task owns its single shot.

datum?(instance, /)

Check if an object is an instance.

decimal?(instance, /)

Check if an object is an instance.

decorate-wraps(inner, wrapper)

Copies callable metadata from inner onto wrapper via functools.update_wrapper, returning wrapper. When inner is a coroutine function, wrapper is first passed through coroutine-fn and that result is returned, so it is a coroutine function too. Used by the call-with and call-parameterize decorator expansions so the delivered wrapper answers for the function it wraps.

defer?(instance, /)

Check if an object is an instance.

demand-apply

Invoke Koskari callable on the demand path with tuple and optional dict args

demand-call

Invoke Koskari callable synchronously without suspension

demand?(instance, /)

Check if an object is an instance.

koskari.builtins.deref(object, /)

deref(ref) => value Call ref.deref() to obtain the value held by the reference.

dict?(instance, /)

Check if an object is an instance.

koskari.builtins.dir([object]) → list of strings

If called without an argument, return the names in the current scope. Else, return an alphabetized list of names comprising (some of) the attributes of the given object, and of attributes reachable from it. If the object supplies a method named __dir__, it will be used; otherwise the default dir() logic is used and returns:

for a module object: the module’s attributes. for a class object: its attributes, and recursively the attributes

of its bases.

for any other object: its attributes, its class’s attributes, and

recursively the attributes of its class’s base classes.

environ-ref(key=None, default=None)
equal?

(== VAL1 VAL2 *: VALS)

koskari.builtins.evaluate(source_obj, ns)

Compile and evaluate a source object as an expression in the given namespace

filter?(instance, /)

Check if an object is an instance.

koskari.builtins.first(object, /)

car(P) -> object Returns the head element of a koskari pair instance P.

float?(instance, /)

Check if an object is an instance.

koskari.builtins.format(value, format_spec='', /)

Return type(value).__format__(value, format_spec)

Many built-in types implement format_spec according to the Format Specification Mini-language. See help(‘FORMATTING’).

If type(value) does not supply a method named __format__ and format_spec is empty, then str(value) is returned. See also help(‘SPECIALMETHODS’).

fraction?(instance)

Override for isinstance(instance, cls).

frozenset?(instance, /)

Check if an object is an instance.

ge?

(>= VAL1 VAL2 *: VALS)

get-compiler(ns)

The compiler for the module owning ns. Returns the bound __compiler__, or rebuilds one from __pragma__ and binds it when the load-time facet was detached

koskari.builtins.getattr(object, name[, default]) → value

Get a named attribute from an object.

getattr(x, ‘y’) is equivalent to x.y. When a default argument is given, it is returned when the attribute doesn’t exist; without it, an exception is raised in that case.

getattr*

getattr_star(obj, attrlist[, default]) -> value Chained attribute access through attrlist; optional default on AttributeError.

getitem*

getitem_star(obj, keylist[, default]) -> value Chained item access through keylist; optional default on LookupError.

gt?

(> VAL1 VAL2 *: VALS)

hasattr*

hasattr_star(obj, attrlist) -> bool Chained attribute presence test; false on first failed step.

hasattr?(obj, name, /)

Return whether the object has an attribute with the given name.

This is done by calling getattr(obj, name) and catching AttributeError.

koskari.builtins.hash(obj, /)

Return the integer hash value for the given object.

Two objects that compare equal must also have the same hash value, but the reverse is not necessarily true. Hash values may differ between Python processes. Not all objects are hashable; calling hash() on an unhashable object raises TypeError.

hasitem*

hasitem_star(obj, keylist) -> bool Chained item presence test; false on first failed step.

koskari.builtins.help(element, namespace=None)

Display help for name in namespace via the system pager

help-pragma-key(key)
koskari.builtins.hex(number, /)

Return the hexadecimal representation of an integer.

>>> hex(12648430)
'0xc0ffee'
koskari.builtins.id(obj, /)

Return the identity of an object.

This is guaranteed to be unique among simultaneously existing objects. (CPython uses the object’s memory address.)

koskari.builtins.identity(value) → value

Returns its argument unchanged.

koskari.builtins.in()

(in VAL CONTAINER)

in?

(in VAL CONTAINER)

koskari.builtins.input(prompt='', /)

Read a string from standard input. The trailing newline is stripped.

The prompt string, if given, is printed to standard output without a trailing newline before reading input.

If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError. On *nix systems, readline is used if available.

instance?

(instance? OBJ TYPE *: TYPES)

int?(instance, /)

Check if an object is an instance.

is-not?(a, b, /)

Same as a is not b.

is?(a, b, /)

Same as a is b.

koskari.builtins.iter(val)

Produce an iterator for an iterable value

keyword?(instance, /)

Check if an object is an instance.

le?

(<= VAL1 VAL2 *: VALS)

koskari.builtins.len(obj, /)

Return the number of items in a container.

list?(instance, /)

Check if an object is an instance.

lt?

(< VAL1 VAL2 *: VALS)

koskari.builtins.macroexpand(form, ns)

Expand a source form object in the given namespace. Repeat until the result is no longer a macro.

macroexpand-1(form, ns)

Apply an expansion step to a source form object in the given namespace.

map?(instance, /)

Check if an object is an instance.

koskari.builtins.max(iterable, *[, default=obj, key=func]) → value
koskari.builtins.max(arg1, arg2, *args, *[, key=func]) → value

With a single iterable argument, return its biggest item. The default keyword-only argument specifies an object to return if the provided iterable is empty. With two or more positional arguments, return the largest argument.

memoryview?(instance, /)

Check if an object is an instance.

koskari.builtins.min(iterable, *[, default=obj, key=func]) → value
koskari.builtins.min(arg1, arg2, *args, *[, key=func]) → value

With a single iterable argument, return its smallest item. The default keyword-only argument specifies an object to return if the provided iterable is empty. With two or more positional arguments, return the smallest argument.

koskari.builtins.next(it, default=<raise>)

Get the next item from an iterator.

If the iterator is exhausted, return the default value. If the default value is not provided, raise an error.

nil?(object, /)

nilp(value) -> bool True if value is an empty-list singleton (nil or bracket-nil).

not-equal?

(!= VAL1 VAL2 *: VALS)

not-in

(not-in VAL CONTAINER)

not-in?

(not-in VAL CONTAINER)

object?(instance, /)

Check if an object is an instance.

koskari.builtins.oct(number, /)

Return the octal representation of an integer.

>>> oct(342391)
'0o1234567'
on-demand?() -> bool

True if current context is being evaluated via demand-call and cannot use await to suspend.

koskari.builtins.open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

Open file and return a stream. Raise OSError upon failure.

file is either a text or byte string giving the name (and the path if the file isn’t in the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped. (If a file descriptor is given, it is closed when the returned I/O object is closed, unless closefd is set to False.)

mode is an optional string that specifies the mode in which the file is opened. It defaults to ‘r’ which means open for reading in text mode. Other common values are ‘w’ for writing (truncating the file if it already exists), ‘x’ for creating and writing to a new file, and ‘a’ for appending (which on some Unix systems, means that all writes append to the end of the file regardless of the current seek position). In text mode, if encoding is not specified the encoding used is platform dependent: locale.getencoding() is called to get the current locale encoding. (For reading and writing raw bytes use binary mode and leave encoding unspecified.) The available modes are:

Character

Meaning

‘r’

open for reading (default)

‘w’

open for writing, truncating the file first

‘x’

create a new file and open it for writing

‘a’

open for writing, appending to the end of the file if it exists

‘b’

binary mode

‘t’

text mode (default)

‘+’

open a disk file for updating (reading and writing)

The default mode is ‘rt’ (open for reading text). For binary random access, the mode ‘w+b’ opens and truncates the file to 0 bytes, while ‘r+b’ opens the file without truncation. The ‘x’ mode implies ‘w’ and raises an FileExistsError if the file already exists.

Python distinguishes between files opened in binary and text modes, even when the underlying operating system doesn’t. Files opened in binary mode (appending ‘b’ to the mode argument) return contents as bytes objects without any decoding. In text mode (the default, or when ‘t’ is appended to the mode argument), the contents of the file are returned as strings, the bytes having been first decoded using a platform-dependent encoding or using the specified encoding if given.

buffering is an optional integer used to set the buffering policy. Pass 0 to switch buffering off (only allowed in binary mode), 1 to select line buffering (only usable in text mode), and an integer > 1 to indicate the size of a fixed-size chunk buffer. When no buffering argument is given, the default buffering policy works as follows:

  • Binary files are buffered in fixed-size chunks; the size of the buffer is max(min(blocksize, 8 MiB), DEFAULT_BUFFER_SIZE) when the device block size is available. On most systems, the buffer will typically be 128 kilobytes long.

  • “Interactive” text files (files for which isatty() returns True) use line buffering. Other text files use the policy described above for binary files.

encoding is the name of the encoding used to decode or encode the file. This should only be used in text mode. The default encoding is platform dependent, but any encoding supported by Python can be passed. See the codecs module for the list of supported encodings.

errors is an optional string that specifies how encoding errors are to be handled—this argument should not be used in binary mode. Pass ‘strict’ to raise a ValueError exception if there is an encoding error (the default of None has the same effect), or pass ‘ignore’ to ignore errors. (Note that ignoring encoding errors can lead to data loss.) See the documentation for codecs.register or run ‘help(codecs.Codec)’ for a list of the permitted encoding error strings.

newline controls how universal newlines works (it only applies to text mode). It can be None, ‘’, ‘n’, ‘r’, and ‘rn’. It works as follows:

  • On input, if newline is None, universal newlines mode is enabled. Lines in the input can end in ‘n’, ‘r’, or ‘rn’, and these are translated into ‘n’ before being returned to the caller. If it is ‘’, universal newline mode is enabled, but line endings are returned to the caller untranslated. If it has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated.

  • On output, if newline is None, any ‘n’ characters written are translated to the system default line separator, os.linesep. If newline is ‘’ or ‘n’, no translation takes place. If newline is any of the other legal values, any ‘n’ characters written are translated to the given string.

If closefd is False, the underlying file descriptor will be kept open when the file is closed. This does not work when a file name is given and must be True in that case.

A custom opener can be used by passing a callable as opener. The underlying file descriptor for the file object is then obtained by calling opener with (file, flags). opener must return an open file descriptor (passing os.open as opener results in functionality similar to passing None).

open() returns a file object whose type depends on the mode, and through which the standard file operations such as reading and writing are performed. When open() is used to open a file in a text mode (‘w’, ‘r’, ‘wt’, ‘rt’, etc.), it returns a TextIOWrapper. When used to open a file in a binary mode, the returned class varies: in read binary mode, it returns a BufferedReader; in write binary and append binary modes, it returns a BufferedWriter, and in read/write mode, it returns a BufferedRandom.

It is also possible to use a string or bytearray as a file for both reading and writing. For strings StringIO can be used like a file opened in a text mode, and for bytes a BytesIO can be used like a file opened in a binary mode.

koskari.builtins.ord(character, /)

Return the ordinal value of a character.

If the argument is a one-character string, return the Unicode code point of that character.

If the argument is a bytes or bytearray object of length 1, return its single byte value.

pair?(instance, /)

Check if an object is an instance.

koskari.builtins.parameter()

parameter(name, default=…) => value Resolve the value bound to name: the enclosing parameterize extent first, then the root scope. Creates nothing and writes nothing. If unbound, return default when provided, otherwise raise NameError.

partial?(instance, /)

Check if an object is an instance.

koskari.builtins.print(*args, sep=' ', end='\n', file=None, flush=False)

Prints the values to a stream, or to sys.stdout by default.

sep

string inserted between values, default a space.

end

string appended after the last value, default a newline.

file

a file-like object (stream); defaults to the current sys.stdout.

flush

whether to forcibly flush the stream.

proper?(value)

Returns True if value is a proper list (a pair terminated by nil).

property?(instance, /)

Check if an object is an instance.

py-filter?(instance, /)

Check if an object is an instance.

py-map?(instance, /)

Check if an object is an instance.

py-repr(obj, /)

Return the canonical string representation of the object.

For many object types, including most builtins, eval(repr(obj)) == obj.

py-zip?(instance, /)

Check if an object is an instance.

range?(instance, /)

Check if an object is an instance.

recursive?(value)

Returns True if value is a recursive (circular) pair structure.

ref?(instance, /)

Check if an object is an instance.

koskari.builtins.repr(object, /)

kos_repr(obj) -> str Koskari-style string: str uses double quotes; then type registry; then __kos_repr__; otherwise repr(obj).

koskari.builtins.round(number, ndigits=None)

Round a number to a given precision in decimal digits.

The return value is an integer if ndigits is omitted or None. Otherwise the return value has the same type as the number. ndigits may be negative.

run-process(*args)

Run an argv to completion in a subprocess, returning a ProcessResult

Launches the argv with asyncio, captures stdout and stderr, and waits for the process to exit. The exit status is reported on the result, never raised; use ProcessResult.raise_for_status for strict handling.

set-car

setcar(P, obj) -> None Assigns the head element of a koskari pair instance P to obj.

set-cdr

setcdr(P, obj) -> None Assigns the tail element of a koskari pair instance P to obj.

set?(instance, /)

Check if an object is an instance.

koskari.builtins.setattr(obj, name, value, /)

Sets the named attribute on the given object to the specified value.

setattr(x, ‘y’, v) is equivalent to x.y = v

slice?(instance, /)

Check if an object is an instance.

koskari.builtins.sorted(iterable, key=None, reverse=False)

Koskari wrapper for Python’s sorted function. Automatically wraps the key argument as a demand.

Returns a new sorted list.

Example:

(sorted iterable key: (itemgetter 1 0))

Example using a thunk:

(sorted iterable key: { #((item %1 1) (item %1 0)) })
staticmethod?(instance, /)

Check if an object is an instance.

str?(instance, /)

Check if an object is an instance.

subclass?

(subclass? CLS BASE *: BASES)

koskari.builtins.sum(iterable, /, start=0)

Return the sum of a ‘start’ value (default: 0) plus an iterable of numbers

When the iterable is empty, return the start value. This function is intended specifically for use with numeric values and may reject non-numeric types.

symbol?(instance, /)

Check if an object is an instance.

tuple?(instance, /)

Check if an object is an instance.

type?(instance, /)

Check if an object is an instance.

koskari.builtins.unpack(value)

Return an iterator over the elements of value.

If value is a pair, returns its unpack iterator. Otherwise, returns iter(value).

Parameters:

value – a pair or other iterable

Returns:

an iterator

values?(instance, /)

Check if an object is an instance.

koskari.builtins.vars([object]) → dictionary

Without arguments, equivalent to locals(). With an argument, equivalent to object.__dict__.

zip?(instance, /)

Check if an object is an instance.

|

(| VAL OR_VAL *: OR_VALS)

Types

class koskari.builtins.ConstantRef

Bases: Ref

class koskari.builtins.MemoizedRef

Bases: Ref

class koskari.builtins.ParamRef

Bases: Ref

class koskari.builtins.AttributeRef

Bases: Ref

class koskari.builtins.ProcessResult(args, returncode, stdout, stderr)

Bases: object

The captured outcome of a completed subprocess.

Bundles the argv, exit status, and raw stdout/stderr of a finished process in the manner of an HTTP client’s Response object: capture everything, interpret afterwards. Helpers decode and parse the captured stdout; raise_for_status opts into strict exit-status handling.

class koskari.builtins.attrgetter(attr, /, *attrs)

Bases: object

Return a callable object that fetches the given attribute(s) from its operand. After f = attrgetter(‘name’), the call f(r) returns r.name. After g = attrgetter(‘name’, ‘date’), the call g(r) returns (r.name, r.date). After h = attrgetter(‘name.first’, ‘name.last’), the call h(r) returns (r.name.first, r.name.last).

class koskari.builtins.bytearray(iterable_of_ints)
class koskari.builtins.bytearray(string, encoding[, errors]) → bytearray
class koskari.builtins.bytearray(bytes_or_buffer) → mutable copy of bytes_or_buffer
class koskari.builtins.bytearray(int) → bytes array of size given by the parameter initialized with null bytes
class koskari.builtins.bytearray → empty bytes array

Bases: object

Construct a mutable bytearray object from:
  • an iterable yielding integers in range(256)

  • a text string encoded using the specified encoding

  • a bytes or a buffer object

  • any object implementing the buffer API.

  • an integer

class koskari.builtins.bytes(iterable_of_ints)
class koskari.builtins.bytes(string, encoding[, errors]) → bytes
class koskari.builtins.bytes(bytes_or_buffer) → immutable copy of bytes_or_buffer
class koskari.builtins.bytes(int) → bytes object of size given by the parameter initialized with null bytes
class koskari.builtins.bytes → empty bytes object

Bases: object

Construct an immutable array of bytes from:
  • an iterable yielding integers in range(256)

  • a text string encoded using the specified encoding

  • any object implementing the buffer API.

  • an integer

class koskari.builtins.classmethod(function, /)

Bases: object

Convert a function to be a class method.

A class method receives the class as implicit first argument, just like an instance method receives the instance. To declare a class method, use this idiom:

class C:

@classmethod def f(cls, arg1, arg2, argN):

…

It can be called either on the class (e.g. C.f()) or on an instance (e.g. C().f()). The instance is ignored except for its class. If a class method is called for a derived class, the derived class object is passed as the implied first argument.

Class methods are different than C++ or Java static methods. If you want those, see the staticmethod builtin.

class koskari.builtins.complex(real=0, imag=0)

Bases: object

Create a complex number from a string or numbers.

If a string is given, parse it as a complex number. If a single number is given, convert it to a complex number. If the ‘real’ or ‘imag’ arguments are given, create a complex number with the specified real and imaginary components.

class koskari.builtins.constantly

Bases: object

A callable that always returns the same value

class koskari.builtins.datum

Bases: object

Matched value with optional KosPair source position and capture binding name

koskari.builtins.decimal

alias of Decimal

class koskari.builtins.defer

Bases: object

class koskari.builtins.demand

Bases: _KosEvaluated

Callable adapter that runs its wrapped callable on the demand path

class koskari.builtins.dict
class koskari.builtins.dict(mapping) → new dictionary initialized from a mapping object's

Bases: object

(key, value) pairs dict(iterable) -> new dictionary initialized as if via:

d = {} for k, v in iterable:

d[k] = v

dict(**kwargs) -> new dictionary initialized with the name=value pairs

in the keyword argument list. For example: dict(one=1, two=2)

class koskari.builtins.enumerate(iterable, start=0)

Bases: object

Return an enumerate object.

iterable

an object supporting iteration

The enumerate object yields pairs containing a count (from start, which defaults to zero) and a value yielded by the iterable argument.

enumerate is useful for obtaining an indexed list:

(0, seq[0]), (1, seq[1]), (2, seq[2]), …

class koskari.builtins.filter

Bases: _KosEvaluated

KosFilter(func, iterable) - native lazy filter; a None func keeps truthy elements; iterable both asynchronously (ambient await, koskari-flattened) and synchronously (demand path)

class koskari.builtins.float(x=0, /)

Bases: object

Convert a string or number to a floating-point number, if possible.

koskari.builtins.fraction

alias of Fraction

class koskari.builtins.frozenset(iterable=(), /)

Bases: object

Build an immutable unordered collection of unique elements.

class koskari.builtins.gensym

Bases: symbol

A symbol scoped by expansion marks: gensym(name=None, predicate=None) mints a fresh mark, gensym(base, marks=…) spells base under the given marks

class koskari.builtins.int([x])
class koskari.builtins.int(x, base=10) → integer

Bases: object

Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.__int__(). For floating-point numbers, this truncates towards zero.

If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by ‘+’ or ‘-’ and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer iteral. >>> int(‘0b100’, base=0) 4

class koskari.builtins.itemgetter(item, /, *items)

Bases: object

Return a callable object that fetches the given item(s) from its operand. After f = itemgetter(2), the call f(r) returns r[2]. After g = itemgetter(2, 5, 3), the call g(r) returns (r[2], r[5], r[3])

class koskari.builtins.keyword

Bases: object

class koskari.builtins.list(iterable=(), /)

Bases: object

Built-in mutable sequence.

If no argument is given, the constructor creates a new empty list. The argument must be an iterable if specified.

class koskari.builtins.map

Bases: _KosEvaluated

KosMap(func, iterable, *iterables) - native lazy map; func takes one element from each iterable per step and the shortest iterable ends it; iterable both asynchronously (ambient await, koskari-flattened) and synchronously (demand path)

class koskari.builtins.memoryview(object)

Bases: object

Create a new memoryview object which references the given object.

class koskari.builtins.object

Bases:

The base class of the class hierarchy.

When called, it accepts no arguments and returns a new featureless instance that has no instance attributes and cannot be given any.

class koskari.builtins.pair

Bases: object

class koskari.builtins.partial

Bases: _KosEvaluated

KosPartial(func, *args, **keywords) - native KosCallable with the behavior of functools.partial

class koskari.builtins.property(fget=None, fset=None, fdel=None, doc=None)

Bases: property

py-filter

alias of filter

py-map

alias of map

py-zip

alias of zip

class koskari.builtins.range(stop)
class koskari.builtins.range(start, stop[, step]) → range object

Bases: object

Return an object that produces a sequence of integers from start (inclusive) to stop (exclusive) by step. range(i, j) produces i, i+1, i+2, …, j-1. start defaults to 0, and stop is omitted! range(4) produces 0, 1, 2, 3. These are exactly the valid indices for a list of 4 elements. When step is given, it specifies the increment (or decrement).

class koskari.builtins.reversed(sequence, /)

Bases: object

Return a reverse iterator over the values of the given sequence.

class koskari.builtins.set(iterable=(), /)

Bases: object

Build an unordered collection of unique elements.

class koskari.builtins.slice(stop)
class koskari.builtins.slice(start, stop[, step])

Bases: object

Create a slice object.

This is used for extended slicing (e.g. a[0:10:2]).

class koskari.builtins.staticmethod(function, /)

Bases: object

Convert a function to be a static method.

A static method does not receive an implicit first argument. To declare a static method, use this idiom:

class C:

@staticmethod def f(arg1, arg2, argN):

…

It can be called either on the class (e.g. C.f()) or on an instance (e.g. C().f()). Both the class and the instance are ignored, and neither is passed implicitly as the first argument to the method.

Static methods in Python are similar to those found in Java or C++. For a more advanced concept, see the classmethod builtin.

class koskari.builtins.str(object='')
class koskari.builtins.str(bytes_or_buffer[, encoding[, errors]]) → str

Bases: object

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to ‘utf-8’. errors defaults to ‘strict’.

class koskari.builtins.super() -> same as super(__class__, <first argument>)
class koskari.builtins.super(type) → unbound super object
class koskari.builtins.super(type, obj) -> bound super object; requires isinstance(obj, type)
class koskari.builtins.super(type, type2) → bound super object; requires

Bases: object

issubclass(type2, type) Typical use to call a cooperative superclass method: class C(B):

def meth(self, arg):

super().meth(arg)

This works for class methods too: class C(B):

@classmethod def cmeth(cls, arg):

super().cmeth(arg)

class koskari.builtins.symbol

Bases: object

class koskari.builtins.tuple(iterable=(), /)

Bases: object

Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable’s items.

If the argument is a tuple, the return value is the same object.

class koskari.builtins.type(object)
class koskari.builtins.type(name, bases, dict, **kwds) → a new type

Bases: object

class koskari.builtins.values

Bases: _KosEvaluated

class koskari.builtins.zip

Bases: _KosEvaluated

KosZip(*iterables) - native lazy zip; iterable both asynchronously (ambient await, koskari-flattened) and synchronously (demand path)

Exceptions

exception koskari.builtins.AttributeError

Bases: Exception

Attribute not found.

exception koskari.builtins.ImportError

Bases: Exception

Import can’t find module, or can’t find name in module.

exception koskari.builtins.NameError

Bases: Exception

Name not found globally.

exception koskari.builtins.ArithmeticError

Bases: Exception

Base class for arithmetic errors.

exception koskari.builtins.AssertionError

Bases: Exception

Assertion failed.

exception koskari.builtins.BaseException

Bases: object

Common base class for all exceptions

exception koskari.builtins.BaseExceptionGroup

Bases: BaseException

A combination of multiple unrelated exceptions.

exception koskari.builtins.BlockingIOError

Bases: OSError

I/O operation would block.

exception koskari.builtins.BrokenPipeError

Bases: ConnectionError

Broken pipe.

exception koskari.builtins.BufferError

Bases: Exception

Buffer error.

exception koskari.builtins.BytesWarning

Bases: Warning

Base class for warnings about bytes and buffer related problems, mostly related to conversion from str or comparing to str.

exception koskari.builtins.ChildProcessError

Bases: OSError

Child process error.

exception koskari.builtins.CompilerError(message, source=None, position=None, filename=None)

Bases: KoskariException

Base class for compile-phase errors

exception koskari.builtins.ConnectionAbortedError

Bases: ConnectionError

Connection aborted.

exception koskari.builtins.ConnectionError

Bases: OSError

Connection error.

exception koskari.builtins.ConnectionRefusedError

Bases: ConnectionError

Connection refused.

exception koskari.builtins.ConnectionResetError

Bases: ConnectionError

Connection reset.

exception koskari.builtins.DeprecationWarning

Bases: Warning

Base class for warnings about deprecated features.

exception koskari.builtins.EOFError

Bases: Exception

Read beyond end of file.

exception koskari.builtins.EncodingWarning

Bases: Warning

Base class for warnings about encodings.

koskari.builtins.EnvironmentError

alias of OSError

exception koskari.builtins.Exception

Bases: BaseException

Common base class for all non-exit exceptions.

exception koskari.builtins.ExceptionGroup

Bases: BaseExceptionGroup, Exception

exception koskari.builtins.FenceError(message, source=None, position=None, filename=None)

Bases: CompilerError

Fence expansion and foreign-source parse errors

exception koskari.builtins.FileExistsError

Bases: OSError

File already exists.

exception koskari.builtins.FileNotFoundError

Bases: OSError

File not found.

exception koskari.builtins.FloatingPointError

Bases: ArithmeticError

Floating-point operation failed.

exception koskari.builtins.FormatStringSyntaxError(message, location=None, filename=None, text=None)

Bases: ReaderSyntaxError

Errors in format string (f-string) syntax

exception koskari.builtins.FutureWarning

Bases: Warning

Base class for warnings about constructs that will change semantically in the future.

exception koskari.builtins.GeneratorExit

Bases: BaseException

Request that a generator exit.

koskari.builtins.IOError

alias of OSError

exception koskari.builtins.ImportWarning

Bases: Warning

Base class for warnings about probable mistakes in module imports

exception koskari.builtins.IndentationError

Bases: SyntaxError

Improper indentation.

exception koskari.builtins.IndexError

Bases: LookupError

Sequence index out of range.

exception koskari.builtins.InterruptedError

Bases: OSError

Interrupted by signal.

exception koskari.builtins.IsADirectoryError

Bases: OSError

Operation doesn’t work on directories.

exception koskari.builtins.KeyError

Bases: LookupError

Mapping key not found.

exception koskari.builtins.KeyboardInterrupt

Bases: BaseException

Program interrupted by user.

exception koskari.builtins.KoskariContinuationError(message, prompt_id=None, operation=None)

Bases: KoskariException

Base class for continuation capture and transfer errors.

The catch target for the whole category. Deliberately not a RuntimeError subclass: an overbroad except RuntimeError around a continuation-using call must not silently swallow these

exception koskari.builtins.KoskariException

Bases: Exception

Base class for error-driven Exceptions raised by Koskari.

exception koskari.builtins.KoskariPromptNotFound(message, prompt_id=None, operation=None)

Bases: KoskariContinuationError

No prompt matching the requested id exists on the dynamic chain.

The construct in operation (shift) has no enclosing delimiter; establish one. prompt_id identifies the delimiter the capture was seeking, letting a library recognize a failure against its own delimiter and leave foreign failures alone

exception koskari.builtins.KoskariPromptUnreachable(message, prompt_id=None, operation=None, boundary=None)

Bases: KoskariContinuationError

A matching prompt exists but a crossed node denied capture.

Adding a delimiter will not help; the region between the capture point and the delimiter must be restructured. boundary describes the denying node (for example a generator boundary)

exception koskari.builtins.KoskariSyncViolation

Bases: TypeError

exception koskari.builtins.KoskariSyntaxError(message, location=None, filename=None, text=None)

Bases: SyntaxError, KoskariException

An error in Koskari syntax, either during read or compile time.

exception koskari.builtins.LayoutError(message, location=None, filename=None, text=None)

Bases: ReaderError

Layout block structure errors

exception koskari.builtins.LookupError

Bases: Exception

Base class for lookup errors.

exception koskari.builtins.MemoryError

Bases: Exception

Out of memory.

exception koskari.builtins.NotADirectoryError

Bases: OSError

Operation only works on directories.

exception koskari.builtins.NotImplementedError

Bases: RuntimeError

Method or function hasn’t been implemented yet.

exception koskari.builtins.NotYetImplemented

Bases: KoskariException

Raised as a placeholder for features that have not been implemented yet.

exception koskari.builtins.OSError

Bases: Exception

Base class for I/O related errors.

exception koskari.builtins.OverflowError

Bases: ArithmeticError

Result too large to be represented.

exception koskari.builtins.ParametersError(message, source=None, position=None, filename=None)

Bases: CompilerError

Call-site parameter errors from koskari.compile.helpers.gather_parameters() validation

exception koskari.builtins.PendingDeprecationWarning

Bases: Warning

Base class for warnings about features which will be deprecated in the future.

exception koskari.builtins.PermissionError

Bases: OSError

Not enough permissions.

exception koskari.builtins.ProcessLookupError

Bases: OSError

Process not found.

exception koskari.builtins.PythonFinalizationError

Bases: RuntimeError

Operation blocked during Python finalization.

exception koskari.builtins.ReaderEOF(message, location=None, filename=None, text=None)

Bases: ReaderError

Stream ended before a delimited or quoted form finished reading.

Distinct from top-level READ_EOF (no form started). REPL callers may treat this as incomplete input; file loaders should surface it as an error.

exception koskari.builtins.ReaderError(message, location=None, filename=None, text=None)

Bases: KoskariSyntaxError

Base class for reader-phase errors

exception koskari.builtins.ReaderSyntaxError(message, location=None, filename=None, text=None)

Bases: ReaderError

Low-level parse errors during s-expression or layout reading

exception koskari.builtins.RecursionError

Bases: RuntimeError

Recursion limit exceeded.

exception koskari.builtins.ReferenceError

Bases: Exception

Weak ref proxy used after referent went away.

exception koskari.builtins.ResourceWarning

Bases: Warning

Base class for warnings about resource usage.

exception koskari.builtins.RuntimeError

Bases: Exception

Unspecified run-time error.

exception koskari.builtins.RuntimeWarning

Bases: Warning

Base class for warnings about dubious runtime behavior.

exception koskari.builtins.SpecialError(message, source=None, position=None, filename=None)

Bases: CompilerError

Special-form validation errors

exception koskari.builtins.StopAsyncIteration

Bases: Exception

Signal the end from iterator.__anext__().

exception koskari.builtins.StopIteration

Bases: Exception

Signal the end from iterator.__next__().

exception koskari.builtins.SyntaxError

Bases: Exception

Invalid syntax.

exception koskari.builtins.SyntaxMatchError(message, source=None, position=None, filename=None, *, syntax=None, patterns=None)

Bases: SpecialError

Syntax dispatch errors when no matcher arm matches the source form

exception koskari.builtins.SyntaxWarning

Bases: Warning

Base class for warnings about dubious syntax.

exception koskari.builtins.SystemError

Bases: Exception

Internal error in the Python interpreter.

Please report this to the Python maintainer, along with the traceback, the Python version, and the hardware/OS platform and version.

exception koskari.builtins.SystemExit

Bases: BaseException

Request to exit from the interpreter.

exception koskari.builtins.TabError

Bases: IndentationError

Improper mixture of spaces and tabs.

exception koskari.builtins.TimeoutError

Bases: OSError

Timeout expired.

exception koskari.builtins.TypeError

Bases: Exception

Inappropriate argument type.

exception koskari.builtins.UncaughtCompilerError(message, source=None, position=None, filename=None)

Bases: CompilerError

Wraps unexpected exceptions raised during compilation

exception koskari.builtins.UnicodeDecodeError

Bases: UnicodeError

Unicode decoding error.

exception koskari.builtins.UnicodeEncodeError

Bases: UnicodeError

Unicode encoding error.

exception koskari.builtins.UnicodeError

Bases: ValueError

Unicode related error.

exception koskari.builtins.UnicodeTranslateError

Bases: UnicodeError

Unicode translation error.

exception koskari.builtins.UnicodeWarning

Bases: Warning

Base class for warnings about Unicode related problems, mostly related to conversion problems.

exception koskari.builtins.UserWarning

Bases: Warning

Base class for warnings generated by user code.

exception koskari.builtins.ValueError

Bases: Exception

Inappropriate argument value (of correct type).

exception koskari.builtins.Warning

Bases: Exception

Base class for warning categories.

exception koskari.builtins.ZeroDivisionError

Bases: ArithmeticError

Second argument to a division or modulo operation was zero.

exception koskari.builtins._IncompleteInputError

Bases: SyntaxError

incomplete input.

Compile features

?

Accepts

  • (? condition then else)

  • (? condition then)

  • (? condition)

assert

Raise AssertionError when the expression is falsey if asserts are enabled. Evaluates as None otherwise.

Usage:

(assert expr)
(assert expr message)

Note that the enablement behavior is gated at compile-time, not run-time. The expr is not evaluated if asserts are disabled.

Asserts are enabled by default, but may be disabled per module via the compiler/enable-asserts pragma. The gate reads the pragma of the module being compiled, so each module answers for its own setting.

eg.:

(pragma [compiler/enable-asserts False])

Accepts

  • (assert expr message)

  • (assert expr)

attr*

Nested attribute access, where the name is evaluated in order from left to right.

For example:

(attr* obj name1 name2)

is equivalent to:

(attr (attr obj name1) name2)

Accepts

  • (attr* obj name)

  • (attr* obj name rest …)

bare-control-word

Gate for a bare control word: expands to the word’s call form, warning or refusing first when the compiling module’s compiler/bare-control-words pragma says so. Diagnostics carry the source position the bare word was captured at.

Accepts

  • (bare-control-word word)

bind!

Bind a reference to a name in the current scope

Accepts

  • (bind! name (item obj key))

  • (bind! name (attr obj key))

  • (bind! name (dynamic r …))

  • (bind! name (constant value))

  • (bind! name (memoized getfn))

  • (bind! name (parameter param-name default))

  • (bind! name (parameter param-name))

  • (bind! name (environ key default))

  • (bind! name (environ key))

  • (bind! name value)

bool

Compile-time object truthiness as a boolean.

Accepts

  • (bool value)

class

Defines a class and binds it to its name in the scope the form appears in.

Accepts

  • (class name supers body …)

compile/!=

Compile (compile/!= A B). Test inequality via __ne__

Accepts

  • (compile/!= (REST args min: 2))

  • (compile/!= (REST short))

compile/#list

Build a Python list from evaluated elements.

Elements are partitioned into constant runs and dynamic expressions. A fresh list is seeded from the first chunk, then extended in place: constant runs come straight from the pool (BUILD_LIST_EXTEND_CONST / BUILD_LIST_APPEND_CONST) and dynamic runs are appended from the stack (BUILD_LIST_APPEND). An all-constant literal reduces to one BUILD_LIST_CONST.

Accepts

  • (compile/#list (REST rest))

compile/#list-append

Append the value of EXPR to a list binding or list expression

Accepts

  • (compile/#list-append (sym :: symbol) (VALUE expr))

  • (compile/#list-append (VALUE list_expr) (VALUE expr))

compile/#str

Compile (compile/#str OBJ …). String conversion via __str__, variadic for f-string style multi-part concatenation

Accepts

  • (compile/#str (REST args))

compile/#tuple

Build a Python tuple from evaluated elements.

An all-constant literal reduces to one pooled CONST. A literal of constants and expressions pushes every element in order, each constant as its own CONST (the peephole folds a run into one instruction), and builds once with BUILD_ARGS. Only a splat, whose length the compiler cannot know, assembles the tuple with COMBINE_ARGS over the chunks.

Accepts

  • (compile/#tuple (REST rest))

compile/%

Compile (compile/% A B). Modulo via __mod__

Accepts

  • (compile/% (VALUE a) (VALUE b))

compile/&

Compile (compile/& A B …). Variadic bitwise AND via __and__

Accepts

  • (compile/& (BODY args))

compile/*

Compile (compile/* A B …). Variadic multiplication via __mul__

Accepts

  • (compile/* (BODY args))

compile/**

Compile (compile/** BASE EXP [MOD]). Exponentiation via __pow__

Accepts

  • (compile/** (BODY args))

compile/+

Compile (compile/+ A B …). Variadic addition via __add__

Accepts

  • (compile/+ (BODY args))

compile/-

Compile (compile/- A B …). Variadic subtraction via __sub__

Accepts

  • (compile/- (BODY args))

compile//

Compile (compile// A B …). True division via __truediv__

Accepts

  • (compile// (BODY args))

compile///

Compile (compile/// A B …). Variadic floor division via __floordiv__

Accepts

  • (compile/// (BODY args))

compile/<

Compile (compile/< A B). Test less-than via __lt__

Accepts

  • (compile/< (REST args min: 2))

  • (compile/< (REST short))

compile/<<

Compile (compile/<< A B). Left bit-shift via __lshift__

Accepts

  • (compile/<< (VALUE a) (VALUE b))

compile/<=

Compile (compile/<= A B). Test less-than-or-equal via __le__

Accepts

  • (compile/<= (REST args min: 2))

  • (compile/<= (REST short))

compile/==

Compile (compile/== A B). Test equality via __eq__

Accepts

  • (compile/== (REST args min: 2))

  • (compile/== (REST short))

compile/>

Compile (compile/> A B). Test greater-than via __gt__

Accepts

  • (compile/> (REST args min: 2))

  • (compile/> (REST short))

compile/>=

Compile (compile/>= A B). Test greater-than-or-equal via __ge__

Accepts

  • (compile/>= (REST args min: 2))

  • (compile/>= (REST short))

compile/>>

Compile (compile/>> A B). Right bit-shift via __rshift__

Accepts

  • (compile/>> (VALUE a) (VALUE b))

compile/@

Compile (compile/@ A B …). Variadic matrix multiplication via __matmul__

Accepts

  • (compile/@ (BODY args))

compile/^

Compile (compile/^ A B …). Variadic bitwise XOR via __xor__

Accepts

  • (compile/^ (BODY args))

compile/and

Compile (compile/and EXPR …). Short-circuit conjunction. Evaluates expressions left-to-right; returns the first falsy value without evaluating further. If all values are truthy, returns the last value. Zero arguments yields True

Accepts

  • (compile/and (REST exprs))

compile/apply-fence

Compile (compile/apply-fence NAME RAW META) — fence expansion.

Resolves fence/<NAME> in the module namespace, calls the handler with the raw fenced source text and a metadata dict, and compiles the source form it returns in place of the fence. META is an optional keyword plist carrying filename:, line:, col:, and options: entries.

Accepts

  • (compile/apply-fence (name :: symbol) (raw :: str) (meta :: pair))

  • (compile/apply-fence (name :: symbol) (raw :: str))

compile/attr

Compile (compile/attr OBJ SYM). Load attribute SYM from OBJ

Accepts

  • (compile/attr (VALUE obj) (sym :: symbol))

compile/await

Compile (compile/await) or (compile/await EXPR). Zero-arg: bare AWAIT (0). One-arg: evaluate EXPR, then AWAIT (1) on TOS.

Accepts

  • (compile/await)

  • (compile/await (VALUE expr))

compile/bare-syntax

Compile (compile/bare-syntax NAME SLOT TEMPLATE).

A bare arm expands the syntax name where it appears as a lone atom rather than at the head of a call form. SLOT names the called-by capture, the only binding TEMPLATE may refer to.

Lowers to (build-bare-syntax NAME-STR SLOT-STR (quote-syntax TEMPLATE)) for recompilation. The result is a Syntax carrying only that arm; use (compile/define NAME ...) to bind it, or extend-syntax to attach it to an existing syntax.

Accepts

  • (compile/bare-syntax (name :: symbol) (slot :: symbol) (VALUE template))

compile/begin

Accepts

  • (compile/begin)

  • (compile/begin (VALUE only))

  • (compile/begin (BODY body))

compile/bindq

Compile (compile/bindq SYM EXPR). Declare a new binding SYM and initialize it to EXPR

Accepts

  • (compile/bindq (DEFINE name) (VALUE value))

compile/bracket-cons

Variadic: (compile/bracket-cons EXPR1 EXPR2 … EXPR_TAIL), the bracket twin of compile/cons. Compile each expression in order, then emit BRACKET_CONS with arg = number of expressions. At least one argument (the tail).

Accepts

  • (compile/bracket-cons (BODY exprs))

compile/bracket-proper

Variadic: (compile/bracket-proper EXPR …). Compile each expression in order, then emit BRACKET_PROPER with arg = number of expressions: the proper bracket list of their values, bracket-nil as its tail. No arguments is bracket-nil.

Accepts

  • (compile/bracket-proper (REST exprs))

compile/break

Compile (compile/break) or (compile/break VAL). Exits innermost loop.

break supports use as a bare control word via the pragma compiler/bare-control-words

Accepts

  • (compile/break (OPTIONAL (VALUE val)))

compile/build-class

Compile (compile/build-class NAME (SUPERS) BODY…). Creates a class via PUSH_COLLECT/POP_COLLECT/BUILD_CLASS, runs body in CollectorNamespace, and leaves the class on the stack. NAME is the class’s name; no variable is defined. SUPERS may include superclass expressions and optional meta: Metaclass.

Accepts

  • (compile/build-class (name :: symbol) (VALUE supers) (REST body))

compile/bytecode

Accepts

  • (compile/bytecode (REPEAT segments (FORM (MATCH (VALUE op) (OPTIONAL (VALUE opa))))))

compile/call

Accepts

  • (compile/call (FORM (MATCH attr (VALUE obj) (attr :: symbol))))

  • (compile/call (FORM (MATCH attr (VALUE obj) (attr :: symbol))) (BODY args))

  • (compile/call (VALUE callable))

  • (compile/call (VALUE callable) (BODY args))

compile/call-attr

Accepts

  • (compile/call-attr (VALUE obj) (attr :: symbol))

  • (compile/call-attr (VALUE obj) (attr :: symbol) (BODY args))

compile/call/cc

Compile (compile/call/cc FN). Captures continuation, invokes FN with the continuation, and returns the result.

Accepts

  • (compile/call/cc (VALUE expr))

compile/capture/cc

Compile (compile/capture/cc K BODY…). Captures continuation, declare and stores to K, runs body.

Intentionally does not open a child namespace: K is bound directly into the enclosing scope so the continuation remains reachable after the body exits. This is the semantic distinction from compile/let/cc, which introduces a fresh child namespace that is discarded once its body completes.

Accepts

  • (compile/capture/cc (k :: symbol) (BODY body))

compile/car

Compile (compile/car EXPR). Emit code that evaluates EXPR, then pushes the car of that pair. One argument. Emits CAR 1; consecutive CAR/CDR instructions may be merged by the compiler compress pass.

Accepts

  • (compile/car (VALUE expr))

compile/cdr

Compile (compile/cdr EXPR). Emit code that evaluates EXPR, then pushes the cdr of that pair. One argument. Emits CDR 1; consecutive CDR/CAR instructions may be merged by the compiler compress pass.

Accepts

  • (compile/cdr (VALUE expr))

compile/check-exception

Accepts

  • (compile/check-exception (REST checks))

compile/clear-exception

Accepts

  • (compile/clear-exception)

compile/cond

Compile (compile/cond (TEST BODY…) (TEST BODY…) … (else: BODY…)). Conditionally executes body depending on a test expression. Multiple clauses; first truthful test’s body is evaluated and returned. No match yields None. The else: keyword as test is always true.

Accepts

  • (compile/cond (REPEAT clauses (FORM (MATCH (VALUE test) (BODY body)))))

compile/cons

Variadic: (compile/cons EXPR1 EXPR2 … EXPR_TAIL). Compile each expression in order (stack bottom = first element, top = tail), then emit CONS with arg = number of expressions. At least one argument (the tail).

Accepts

  • (compile/cons (BODY exprs))

compile/continue

Compile (compile/continue) or (compile/continue VAL). Restarts loop.

continue supports use as a bare control word via the pragma compiler/bare-control-words

Accepts

  • (compile/continue (OPTIONAL (VALUE val)))

compile/define

Compile (define (F ARGS…) BODY…), the function F of ARGS bound in the current scope, or (define X), (define X EXPR) and their typed variants, which are var’s

Accepts

  • (compile/define (FORM (MATCH (FORM (MATCH (fname :: symbol) : (VALUE return_type))) (REST formals))) (REST body))

  • (compile/define (FORM (MATCH (FORM (MATCH (fname :: symbol) type: (VALUE return_type))) (REST formals))) (REST body))

  • (compile/define (FORM (MATCH (fname :: symbol) (REST formals))) (REST body))

  • (compile/define (DEFINE name) : (VALUE return_type) (VALUE value))

  • (compile/define (DEFINE name) type: (VALUE return_type) (VALUE value))

  • (compile/define (DEFINE name) : (VALUE return_type))

  • (compile/define (DEFINE name) type: (VALUE return_type))

  • (compile/define (DEFINE name) (VALUE value))

  • (compile/define (DEFINE name))

compile/define-global

Compile (define-global (F ARGS…) BODY…), the function F of ARGS bound at the module, or (define-global X), (define-global X EXPR) and their typed variants, the shapes of (global var X …)

Accepts

  • (compile/define-global (FORM (MATCH (FORM (MATCH (fname :: symbol) : (VALUE return_type))) (REST formals))) (REST body))

  • (compile/define-global (FORM (MATCH (FORM (MATCH (fname :: symbol) type: (VALUE return_type))) (REST formals))) (REST body))

  • (compile/define-global (FORM (MATCH (fname :: symbol) (REST formals))) (REST body))

  • (compile/define-global (DEFINE name) : (VALUE return_type) (VALUE value))

  • (compile/define-global (DEFINE name) type: (VALUE return_type) (VALUE value))

  • (compile/define-global (DEFINE name) : (VALUE return_type))

  • (compile/define-global (DEFINE name) type: (VALUE return_type))

  • (compile/define-global (DEFINE name) (VALUE value))

  • (compile/define-global (DEFINE name))

compile/define-global-values

Compile (compile/define-global-values PATTERN VALUE), which evaluates VALUE and binds the names of PATTERN (symbol or unpack list, same shape as compile/define-values) at the module from any depth, or (compile/define-global-values PATTERN), which binds the names at the module and stores nothing

Accepts

  • (compile/define-global-values (lhs :: symbol) (VALUE expr))

  • (compile/define-global-values (lhs :: pair) (VALUE expr))

  • (compile/define-global-values (lhs :: pair))

compile/define-syntax

Define a syntax transformer

syntax-rules, macro-rules, and special-rules accept a literals list and a list of rules. Each rule is gated by a rule-shaped pattern.

syntax-match, macro-match, and special-match accept a list of rules. Each rule is a pair of a pattern and a template, where the pattern is an explicit match-style pattern.

syntax-rules and syntax-match map rules to templates. Templates are declarative transformations of the input source form.

macro-rules and macro-match map rules to macros. Macros are procedurally evaluated to produce an output form.

special-rules and special-match map rules to low-level compiler transformations.

bare-syntax accepts a called-by symbol and a template, and applies when the transformer’s name is used as a lone atom rather than at the head of a call form. A transformer has at most one bare form.

Transformers can be extended with extend-syntax

Accepts

  • (define-syntax name docstr (form …))

  • (define-syntax name (bare-syntax slot template))

  • (define-syntax name (syntax-rules literals rule …))

  • (define-syntax name (syntax-match rule …))

  • (define-syntax name (macro-rules literals rule …))

  • (define-syntax name (macro-match rule …))

  • (define-syntax name (special-rules literals rule …))

  • (define-syntax name (special-match rule …))

compile/define-values

Compile (compile/define-values PATTERN VALUE), which evaluates VALUE and binds fresh names from PATTERN (symbol or unpack list, same shape as compile/setq-values), or (compile/define-values PATTERN), which declares the pattern’s names and stores nothing

Accepts

  • (compile/define-values (lhs :: symbol) (VALUE expr))

  • (compile/define-values (lhs :: pair) (VALUE expr))

  • (compile/define-values (lhs :: pair))

compile/del-attr

Compile (compile/del-attr OBJ SYM). Delete attribute SYM from OBJ

Accepts

  • (compile/del-attr (VALUE obj) (sym :: symbol))

compile/del-item

Compile (compile/del-item OBJ KEY). Delete item at KEY from OBJ

Accepts

  • (compile/del-item (VALUE obj) (VALUE key))

compile/delq

Compile (compile/delq SYM). Clear the binding SYM, resetting it to unset

Accepts

  • (compile/delq (sym :: symbol))

compile/deref

Compile (compile/deref EXPR). Compile EXPR (produces ref on stack), then emit DEREF to call ref.deref() and push result.

Accepts

  • (compile/deref (VALUE arg))

compile/dir

Compile (compile/dir OBJ). Attribute listing via __dir__

Accepts

  • (compile/dir (VALUE obj))

compile/divmod

Compile (compile/divmod A B). Combined quotient and remainder

Accepts

  • (compile/divmod (VALUE a) (VALUE b))

compile/dyn-wind

Compile (compile/dyn-wind [before] [body] [after]). Body is required; at least one of before or after is required. Wraps before/after in (lambda [] …) thunks and emits PUSH_WIND / POP_WIND.

Accepts

  • (compile/dyn-wind (ONEOF (MATCH (FORM (MATCH before: (REST before))) (FORM (MATCH body: (REST body))) (FORM (MATCH after: (REST after)))) (MATCH (FORM (MATCH before: (REST before))) (FORM (MATCH after: (REST after))) (FORM (MATCH body: (REST body)))) (MATCH (FORM (MATCH body: (REST body))) (FORM (MATCH before: (REST before))) (FORM (MATCH after: (REST after)))) (MATCH (FORM (MATCH body: (REST body))) (FORM (MATCH after: (REST after))) (FORM (MATCH before: (REST before)))) (MATCH (FORM (MATCH after: (REST after))) (FORM (MATCH before: (REST before))) (FORM (MATCH body: (REST body)))) (MATCH (FORM (MATCH after: (REST after))) (FORM (MATCH body: (REST body))) (FORM (MATCH before: (REST before))))))

  • (compile/dyn-wind (ONEOF (MATCH (FORM (MATCH before: (REST before))) (FORM (MATCH body: (REST body)))) (MATCH (FORM (MATCH body: (REST body))) (FORM (MATCH before: (REST before))))))

  • (compile/dyn-wind (ONEOF (MATCH (FORM (MATCH body: (REST body))) (FORM (MATCH after: (REST after)))) (MATCH (FORM (MATCH after: (REST after))) (FORM (MATCH body: (REST body))))))

  • (compile/dyn-wind (MATCH (VALUE before_single) (VALUE body_single) (VALUE after_single)))

  • (compile/dyn-wind (MATCH (VALUE body_single) (VALUE after_single)))

compile/dyn-with

Compile (compile/dyn-with [name? expr] BODY…). Multi-shot context manager that participates in transfer plans (exit on unwind, enter on wind).

Accepts

  • (compile/dyn-with (USING binding) (BODY body))

compile/extend-syntax

Extends an existing Syntax definition with new rules. The newer rules take precedence over existing rules.

The original documentation is carried forward. A docstring given here is appended to it, describing what this extension adds.

Accepts

  • (extend-syntax name docstr (form …))

  • (extend-syntax name (bare-syntax slot template))

  • (extend-syntax name (syntax-rules literals rule …))

  • (extend-syntax name (syntax-match rule …))

  • (extend-syntax name (macro-rules literals rule …))

  • (extend-syntax name (macro-match rule …))

  • (extend-syntax name (special-rules literals rule …))

  • (extend-syntax name (special-match rule …))

compile/for-each

Compile (compile/for-each [BINDING EXPR] BODY… [else: ELSEBODY]) or (compile/for-each [[PATTERN…] EXPR] BODY… [else: ELSEBODY]). Iterates EXPR, binding each element to BINDING or unpacking via PATTERN. On natural exhaustion, runs ELSEBODY if provided. Break exits the loop early without running the else clause. The loop expression value is None unless break or else provides a value.

Accepts

  • (compile/for-each (BINDING binding) (BODY body))

  • (compile/for-each (USING_UNPACK using) (BODY body))

compile/format

Compile (compile/format OBJ [RULES]). Rules may be dynamic, constant str, or quoted symbol constant. The all-constant case folds to CONST here, where a bad rules value diagnoses at compile time; every other shape emits naively, and the processor’s format lowering ladder owns the demotion to OBJECT_FORMAT_CONST and the fused forms.

Accepts

  • (compile/format (VALUE obj))

  • (compile/format (VALUE obj) (VALUE rules))

compile/function

Compile (function [args] body) or (function name [args] body).

Unlike lambda, function does not implicitly bind the function object into its own scope. This allows a function to refer to an outer definition of itself, which may be wrapped such as via decorators.

Accepts

  • (compile/function (name :: symbol) : (VALUE return_type) (FORMALS formals) (BODY body))

  • (compile/function (name :: symbol) type: (VALUE return_type) (FORMALS formals) (BODY body))

  • (compile/function (name :: symbol) (FORMALS formals) (BODY body))

compile/gensym-thunk

Compile (compile/gensym-thunk BODY…) to a lambda with inferred formals.

This is the form which handles thunk-expressions.

Placeholders: %%1, %%2, … share gensyms per index; … becomes * rest

Accepts

  • (compile/gensym-thunk (REST body))

compile/globals

Compile (compile/globals). Push the outermost frame namespace (globals)

Accepts

  • (compile/globals)

compile/import

Compile (import MODULE) and (import [MODULE as: BIND]).

Plain dotted import binds the root package, Python-style: (import foo.bar) binds foo, with foo.bar reachable as an attribute. The bracketed member form binds BIND to the leaf module. Relative imports (leading dots) are always leaf-style.

Accepts

  • (compile/import (VALUE module))

compile/import-all-from

Compile (import-all-from MODULE): Python’s from MODULE import *.

Binds the module’s public names (__all__ when defined, otherwise the non-underscore dir() names) into the module namespace. Only allowed at module top level, matching Python.

Accepts

  • (compile/import-all-from (VALUE module))

compile/import-from

Compile (import-from NAME MEMBER…) where each MEMBER is either a plain symbol or a [ATTR as: BIND] rename form.

NAME is a symbol; leading dots indicate relative imports. At least one member is required. Emits a single IMPORT_FROM instruction carrying the module name, level, and parallel attr/bind name tuples.

Accepts

  • (compile/import-from (VALUE module) (BODY members))

compile/in

Compile (compile/in ITEM COLLECTION). Membership test via __contains__

Accepts

  • (compile/in (VALUE a) (VALUE b))

compile/inplace

Compile (compile/inplace OP VAR VALUE). In-place update: VAR OP= VALUE. OP is any numeric or bitwise operator (+, -, , /, //, %, *, @, &, |, ^, <<, >>).

Accepts

  • (inplace op (item obj name) value)

  • (inplace op (attr obj name) value)

  • (compile/inplace (op :: symbol) (var :: symbol) (VALUE value))

compile/inplace-attr

Compile (compile/inplace-attr OP OBJ ATTR VALUE…). Multiple values reduce left-to-right into OBJ.ATTR through a single fused instruction: VAR_ATTR_INPLACE when OBJ is a variable (resolution lowers it to FAST_ATTR_INPLACE), otherwise ATTR_INPLACE with OBJ on the stack.

Accepts

  • (compile/inplace-attr (op :: symbol) (VALUE obj) (attr :: symbol) (BODY values))

compile/inplace-item

Compile (compile/inplace-item OP OBJ KEY VALUE…). Multiple values reduce left-to-right through the single OBJECT_INPLACE instruction.

Accepts

  • (compile/inplace-item (op :: symbol) (VALUE obj) (VALUE key) (BODY values))

compile/instance?

Compile (compile/instance? OBJ TYPE …). Instance check against one or more types; a tuple operand is opened one level

Accepts

  • (compile/instance? (VALUE subject) (BODY types))

compile/is

Compile (compile/is A B). Identity test

Accepts

  • (compile/is (VALUE a) (VALUE b))

compile/is-not

Compile (compile/is-not A B). Negated identity test

Accepts

  • (compile/is-not (VALUE a) (VALUE b))

compile/item

Compile (compile/item OBJ KEY). Load item at KEY from OBJ

Accepts

  • (compile/item (VALUE obj) (VALUE key))

compile/iter

Compile (compile/iter OBJ). Iterator acquisition uniform over both protocols: a koskari AsyncGenerator passes through as itself, an async iterable yields its __aiter__, otherwise the sync __iter__ protocol

Accepts

  • (compile/iter (VALUE obj))

compile/lambda

Compile (lambda [args] body) or (lambda name [args] body).

The Named form binds name in the function scope for self-reference.

Accepts

  • (compile/lambda (name :: symbol) : (VALUE return_type) (FORMALS formals) (BODY body))

  • (compile/lambda (name :: symbol) type: (VALUE return_type) (FORMALS formals) (BODY body))

  • (compile/lambda : (VALUE return_type) (FORMALS formals) (BODY body))

  • (compile/lambda type: (VALUE return_type) (FORMALS formals) (BODY body))

  • (compile/lambda (name :: symbol) (FORMALS formals) (BODY body))

  • (compile/lambda (FORMALS formals) (BODY body))

compile/len

Compile (compile/len OBJ). Length query via __len__

Accepts

  • (compile/len (VALUE obj))

compile/let

Compile (compile/let BINDINGS BODY…) or (compile/let NAME BINDINGS BODY…). Named let expands to an immediately-invoked named lambda: (let foo [[a 1] [b 2]] …body) -> ((lambda foo [a b] …body) 1 2).

Accepts

  • (compile/let (name :: symbol) (BINDINGS bindings) (BODY body))

  • (compile/let (BINDINGS bindings) (BODY body))

compile/let/cc

Compile (compile/let/cc K BODY…). Pushes new namespace to hold K, captures continuation, binds to K, runs body. K must be a symbol

Accepts

  • (compile/let/cc (k :: symbol) (BODY body))

compile/letrec

Compile (compile/letrec BINDINGS BODY…). Each name is declared in a single child scope without initial values, then each RHS is evaluated and stored left-to-right with VAR_STORE (same effect as compile/setq) so lambdas may close over the same bindings before body runs.

Accepts

  • (compile/letrec (BINDINGS bindings) (BODY body))

compile/load-exception

Accepts

  • (compile/load-exception)

compile/macro-match

Compile (compile/macro-match NAME RULE …).

Rule rows are (PATTERN BODY...); each pattern is lowered here through koskari.matcher.parse_explicit_rule_pattern() to a matcher function of this module, and its slot order gives the generated formals. Lowers to a call of build-macro with, per rule, the function, its repeat variables, the quoted pattern and (lambda FORMALS . BODY). The built transformer is the value of the expression; use (compile/define NAME ...) to bind it.

Accepts

  • (compile/macro-match (name :: symbol) (REPEAT rules (FORM (MATCH pattern (BODY body))) min: 1))

compile/macro-rules

Compile (compile/macro-rules NAME LITERALS RULES…).

Rules are (PATTERN BODY...); the patterns are parsed here and lowered to matcher functions of this module. Lowers to a call of build-macro with, per rule, the function, its repeat variables, the quoted pattern and (lambda FORMALS . BODY), the formals being the pattern’s variables. The built transformer is the value of the expression; use (compile/define NAME ...) to bind it.

Accepts

  • (compile/macro-rules (name :: symbol) literals (REPEAT rules rule min: 1))

compile/match

Compile (compile/match SUBJECT [[PATTERN] BODY…] … [else: BODY…]). Evaluates SUBJECT once, then tries each arm’s pattern in order. The first matching arm binds its captured names and runs its body, whose value is the result. An [else: BODY…] arm always matches; with no else and no match the form yields None. Each arm’s pattern rides in its own delimiter list ahead of the body and is classified by the case-pattern dialect (see docs/guide/match-patterns.md).

A clause may carry a guard between the pattern and the body: [[PATTERN] when: COND BODY…] runs the body only when COND is truthy after the pattern matches and binds; unless: inverts the sense. A failed guard advances to the next arm with the subject intact, and the bound captures persist.

Accepts

  • (compile/match)

  • (compile/match (VALUE subject) (REPEAT clauses (FORM (MATCH (VALUE pattern) (BODY body)))))

compile/next

Compile (compile/next IT [DEFAULT]). One step of either iteration protocol via OBJECT_NEXT, ambient async: exhaustion raises StopIteration in the one-argument form and yields DEFAULT in the two-argument form

Accepts

  • (compile/next (VALUE it))

  • (compile/next (VALUE it) (VALUE default))

  • (compile/next (VALUE it) default: (VALUE default))

compile/nil?

Compile (nil? OBJ). True if OBJ is an empty-list singleton, either nil or bracket-nil. Emits NILP, which compression may lower to a CHECK_NIL when followed by a conditional jump.

Accepts

  • (compile/nil? (VALUE obj))

compile/not

Compile (compile/not OBJ). Boolean negation via __bool__ then invert

Accepts

  • (compile/not (VALUE obj))

compile/not-in

Compile (compile/not-in ITEM COLLECTION). Negated membership test

Accepts

  • (compile/not-in (VALUE a) (VALUE b))

compile/or

Compile (compile/or EXPR …). Short-circuit disjunction. Evaluates expressions left-to-right; returns the first truthy value without evaluating further. If all values are falsy, returns the last value. Zero arguments yields False

Accepts

  • (compile/or (REST exprs))

compile/parameter

Compile (compile/parameter NAME [DEFAULT]).

Resolves the value bound to NAME: the enclosing parameterize extent first, then the root scope. Neither store is written, and neither gains an entry on a miss. Without a binding DEFAULT answers, and with no DEFAULT the resolution raises NameError.

Accepts

  • (compile/parameter (name :: symbol))

  • (compile/parameter (name :: symbol) (VALUE default))

compile/parameterize

Compile (compile/parameterize [[name val] …] BODY…).

Sets named dynamic parameters for the duration of body; restores ambient values on exit. Consumers can use these parameters via define-parameter or parameterq

Accepts

  • (compile/parameterize (VALUE bindings) (BODY body))

compile/quasiquote

Compile (compile/quasiquote EXPR) — the backtick quasi-quote special form.

Emits CONST, PROPER, CONS, PAIR_SPLICE and their bracket twins to construct the quoted structure at runtime, with unquote and unquote-splicing sites evaluated as normal expressions.

Accepts

  • (compile/quasiquote (VALUE expr))

compile/quasiquote-syntax

Compile (compile/quasiquote-syntax EXPR) as quasiquote does, keeping the marks on the atoms it emits as constants. A procedural macro that a template defined builds its output with this form: the symbols the outer template wrote carry the outer expansion’s marks, and keeping them lets the output resolve to what that expansion bound. Unquote and unquote-splicing sites are the same as in quasiquote

Accepts

  • (compile/quasiquote-syntax (VALUE expr))

compile/quote

Compile (compile/quote FORM). A pair is rewritten as its requoted construction; any other datum becomes a constant, a symbol as its base since quoted data carries no marks

Accepts

  • (compile/quote (VALUE expr))

compile/quote-syntax

Compile (compile/quote-syntax FORM) as quote does, keeping the marks on the symbols. A syntax transformer’s patterns and templates are quoted this way: a template a macro-generating macro introduced carries the outer expansion’s marks, and its references must resolve to what that expansion bound

Accepts

  • (compile/quote-syntax (VALUE expr))

compile/raise

raise supports use as a bare control word via the pragma compiler/bare-control-words

Accepts

  • (compile/raise (OPTIONAL (VALUE expr)))

compile/ref-attr

Compile (compile/ref-attr OBJ SYM). Produce a mutable reference to attribute SYM on OBJ

Accepts

  • (compile/ref-attr (VALUE obj) (sym :: symbol))

compile/ref-item

Compile (compile/ref-item OBJ KEY). Produce a mutable reference to item at KEY in OBJ

Accepts

  • (compile/ref-item (VALUE obj) (VALUE key))

compile/refq

Compile (compile/refq SYM). Load the value of the binding named SYM

Accepts

  • (compile/refq (sym :: symbol))

compile/repr

Compile (compile/repr OBJ). String representation via __repr__

Accepts

  • (compile/repr (VALUE obj))

compile/reset

Compile (compile/reset EXPR…). Establishes a prompt (tag 0), runs body, pops prompt. Enables delimited continuations via compile/shift.

Accepts

  • (compile/reset (BODY body))

compile/return

Returns from function.

(return) ; returns None (return val) ; returns val (return vals …) ; returns tuple of vals (return k: v …) ; returns values object over complex arguments

return supports use as a bare control word via the pragma compiler/bare-control-words

Accepts

  • (compile/return (REST rest))

compile/set-attr

Compile (compile/set-attr OBJ SYM VAL). Store VAL into attribute SYM on OBJ

Accepts

  • (compile/set-attr (VALUE obj) (sym :: symbol) (VALUE val))

compile/set-item

Compile (compile/set-item OBJ KEY VAL). Store VAL at item KEY in OBJ

Accepts

  • (compile/set-item (VALUE obj) (VALUE key) (VALUE val))

compile/setq

Compile (compile/setq SYM EXPR). Store the value of EXPR into the existing binding SYM

Accepts

  • (compile/setq (sym :: symbol) (VALUE expr))

compile/setq-values

Compile (compile/setq-values PATTERN VALUE). Evaluate VALUE, then store into existing bindings given by PATTERN (symbol or unpack list, same as compile/for-each unpack binding)

Accepts

  • (compile/setq-values (lhs :: symbol) (VALUE expr))

  • (compile/setq-values (lhs :: pair) (VALUE expr))

compile/shift

Compile (compile/shift K EXPR…). Captures continuation, binds to K, runs handler body. K must be a symbol; tag 0.

Accepts

  • (compile/shift (k :: symbol) (BODY body))

compile/special-match

Compile (compile/special-match NAME RULE …).

Each rule pattern column is (compiler-formal pattern): the first subform names the compiler parameter (any symbol), the second is the nested MATCH pattern for parse_explicit_rule_pattern, lowered here to a matcher function of this module. Lowers to a call of build-special with, per rule, the function, its repeat variables, the quoted pattern and (lambda ...), as compile/macro-match does. The built transformer is the value of the expression; use (compile/define NAME ...) to bind it.

Accepts

  • (compile/special-match (name :: symbol) (REPEAT rules (FORM (MATCH (FORM (MATCH (compiler :: symbol) (VALUE pattern))) (BODY body))) min: 1))

compile/special-rules

Compile (compile/special-rules NAME LITERALS RULES…).

Each rule pattern column is (compiler-formal pattern): the first subform names the compiler parameter (any symbol), the second is the nested RULE pattern, lowered here with parse_syntax_rules_pattern() to a matcher function of this module. Lowers to a call of build-special with, per rule, the function, its repeat variables, the quoted pattern and (lambda ...). The macro name is not a literal: the inner pattern’s head is a formal of the arm bound to the symbol the special was invoked as. The built transformer is the value of the expression; use (compile/define NAME ...) to bind it.

Accepts

  • (compile/special-rules (name :: symbol) literals (REPEAT rules (FORM (MATCH (FORM (MATCH (compiler :: symbol) (VALUE pattern))) (BODY body))) min: 1))

compile/subclass?

Compile (compile/subclass? CLS BASE …). Subclass check against one or more bases; a tuple operand is opened one level

Accepts

  • (compile/subclass? (VALUE subject) (BODY types))

compile/switch

Compile (compile/switch VALUE (COMPARE BODY…) (COMPARE BODY…) … (else: BODY…)). Conditionally executes body depending on a compare expression. Multiple clauses; first compare expression’s body is evaluated and returned. No match evaluates as None. The else: keyword always matches.

Accepts

  • (compile/switch (VALUE value) (REPEAT clauses (FORM (MATCH (VALUE test) (BODY body)))))

compile/syntax-match

Compile (compile/syntax-match NAME RULE …).

Rule rows are (PATTERN TEMPLATE); each pattern is lowered here through koskari.matcher.parse_explicit_rule_pattern() to a matcher function of this module. Lowers to a call of build-syntax with, per rule, the function, its repeat variables, the quoted pattern and the quoted template. The built transformer is the value of the expression; use (compile/define NAME ...) to bind it.

Accepts

  • (compile/syntax-match (name :: symbol) (REPEAT rules rule min: 1))

compile/syntax-rules

Compile (compile/syntax-rules NAME LITERALS RULES…).

Each rule’s pattern is parsed here and lowered to a matcher function, a lambda of this module whose externs close over the module’s bindings; the form lowers to a call of build-syntax with, per rule, that function, its repeat variables, the quoted pattern and the quoted template. LITERALS is the literals list form from the source; the macro name is not a literal. The head of each pattern lowers to a CALLEDBY capture under its own name, binding the symbol the macro was invoked as, so a template may use it. The built transformer is the value of the expression; use (compile/define NAME ...) to bind it.

Accepts

  • (compile/syntax-rules (name :: symbol) literals (REPEAT rules rule min: 1))

compile/take-attr

Compile (compile/take-attr OBJ SYM). Get attribute SYM from OBJ, delete it, push the value

Accepts

  • (compile/take-attr (VALUE obj) (sym :: symbol))

compile/take-item

Compile (compile/take-item OBJ KEY). Get item at KEY from OBJ, delete it, push the value

Accepts

  • (compile/take-item (VALUE obj) (VALUE key))

compile/takeq

Compile (compile/takeq SYM). Deref SYM, clear the binding, push value

Accepts

  • (compile/takeq (sym :: symbol))

compile/truth

Compile (compile/truth OBJ). Boolean coercion via __bool__

Accepts

  • (compile/truth (VALUE obj))

compile/try

Compile (try BODY ARM… [(else: BODY…)] [(finally: BODY…)]), where each ARM is (except: BODY…), ([TYPEEXPR] BODY…), ([SYM TYPEEXPR] BODY…) or ([TYPEEXPR as: SYM] BODY…)

Accepts

  • (compile/try (VALUE body) (REPEAT catches (FORM (MATCH (ONEOF (bare :: (LITERAL except:)) (FORM (MATCH (VALUE expr) as: (name :: symbol))) (FORM (MATCH (name :: symbol) (VALUE expr))) (FORM (MATCH (VALUE expr)))) (REST body)))) (OPTIONAL (FORM (MATCH else: (REST else_body)))) (OPTIONAL (FORM (MATCH finally: (REST finally_body)))))

compile/type

Compile (compile/type OBJ). Type introspection via type()

Accepts

  • (compile/type (VALUE obj))

compile/unquote

Raise SpecialError — unquote is only valid inside quasiquote

Accepts

  • (compile/unquote (VALUE expr))

compile/unquote-splicing

Raise SpecialError — unquote-splicing is only valid inside quasiquote

Accepts

  • (compile/unquote-splicing (VALUE expr))

compile/use

Compile (use MODULE) and (use MODULE STEM…), where each STEM is a plain symbol or a [STEM as: BIND] rename form.

The koskari-native import: a stem names a feature, and every facet of it – the runtime binding, compile/stem, layout/stem – imports together, each bound under the bind stem with the same prefix, so a rename renames the family. A stem already carrying a facet prefix is literal. With no stems, lowers to import-all-from: the module’s materialized __all__ already carries every feature’s facets.

On a Python module, whose namespace has no facet keys, use behaves exactly as import-from and import-all-from do. Only allowed at module top level.

Accepts

  • (compile/use (VALUE module))

  • (compile/use (VALUE module) (BODY stems))

compile/var

Compile (var X), (var X EXPR), or the typed variants with X :: T / X type: T before the value or alone. Declares X in the scope the form appears in and stores the value

A pattern in the name position declares every name the pattern binds and unpacks the value into them, through define-values. Without a value the names are only declared.

Accepts

  • (var (PAIR pattern) (BIND value))

  • (var (PAIR pattern))

  • (compile/var (DEFINE name) : (VALUE return_type) (VALUE value))

  • (compile/var (DEFINE name) type: (VALUE return_type) (VALUE value))

  • (compile/var (DEFINE name) : (VALUE return_type))

  • (compile/var (DEFINE name) type: (VALUE return_type))

  • (compile/var (DEFINE name) (VALUE value))

  • (compile/var (DEFINE name))

compile/vars

Compile (compile/vars) or (compile/vars OBJ). With no operand, push the current frame namespace; with one, the attribute dict via __dict__

Accepts

  • (compile/vars)

  • (compile/vars (VALUE obj))

compile/while

Compile (compile/while TEST BODY… [else: ELSEBODY…]). Loop with break and continue support

Accepts

  • (compile/while (VALUE test) (BODY body))

compile/with

Compile (compile/with [name? expr] BODY…). Single-shot context manager

Accepts

  • (compile/with (USING binding) (BODY body))

compile/yield

Yields from function.

(yield) ; yields None (yield val) ; yields val (yield vals …) ; yields tuple of vals (yield k: v …) ; yields values object over complex arguments

yield supports use as a bare control word via the pragma compiler/bare-control-words

Accepts

  • (compile/yield (REST rest))

compile/yield-from

Compile (compile/yield-from EXPR). Evaluates EXPR, then yields from TOS via YIELD_FROM.

Accepts

  • (compile/yield-from (VALUE expr))

compile/|

Compile (compile/| A B …). Variadic bitwise OR via __or__

Accepts

  • (compile/| (BODY args))

compile/~

Compile (compile/~ OBJ). Bitwise inversion via __invert__

Accepts

  • (compile/~ (VALUE obj))

compileq

Accepts

  • (compileq form ns)

  • (compileq form)

datumq

Captures expr quoted, as written, in a datum, recording the source position

Accepts

  • (datumq expr pos)

  • (datumq expr)

declare-exports

Declare the module’s exported features

Each name is a feature stem: at the end of the module load, __all__ is materialized from the stems as the binding keys that actually exist – the runtime name, compile/stem, and layout/stem facets of each. A name written with a facet prefix is a literal single-binding export. The stems themselves persist as __features__.

eg.:

(declare-exports name1 name2 ...)

expands to:

(define-global __features__ #("name1" "name2" ...))

Accepts

  • (declare-exports)

  • (declare-exports [names …])

  • (declare-exports names …)

decorate

Handler for the decorator layout syntax, can also be used to apply decorator-style wrappers to an s-expr form.

Each decorator is applied to the accumulated subject via decorate-subject, outermost decorator first.

Accepts

  • (decorate [] fn)

  • (decorate [decorators …] (def name rest …))

  • (decorate [decorators …] (var name :: type value))

  • (decorate [decorators …] (var name type: type value))

  • (decorate [decorators …] (var name value))

  • (decorate [decorators …] (var name))

  • (decorate [decorators …] (var name :: type))

  • (decorate [decorators …] (var name type: type))

  • (decorate [decorators …] (global var name :: type value))

  • (decorate [decorators …] (global var name type: type value))

  • (decorate [decorators …] (global var name value))

  • (decorate [decorators …] (global var name))

  • (decorate [decorators …] (global var name :: type))

  • (decorate [decorators …] (global var name type: type))

  • (decorate [decorators …] (global def name rest …))

  • (decorate [decorators …] (global class name supers body …))

  • (decorate [decorators …] (class name supers body …))

  • (decorate [decorators …] (define ((name :: rtype) formals …) body …))

  • (decorate [decorators …] (define ((name type: rtype) formals …) body …))

  • (decorate [decorators …] (define (name formals …) body …))

  • (decorate [decorators …] (define name :: type value))

  • (decorate [decorators …] (define name type: type value))

  • (decorate [decorators …] (define name value))

  • (decorate [decorators …] (define name))

  • (decorate [decorators …] (define name :: type))

  • (decorate [decorators …] (define name type: type))

  • (decorate [decorators …] (define-global ((name :: rtype) formals …) body …))

  • (decorate [decorators …] (define-global ((name type: rtype) formals …) body …))

  • (decorate [decorators …] (define-global (name formals …) body …))

  • (decorate [decorators …] (define-global name :: type value))

  • (decorate [decorators …] (define-global name type: type value))

  • (decorate [decorators …] (define-global name value))

  • (decorate [decorators …] (define-global name))

  • (decorate [decorators …] (define-global name :: type))

  • (decorate [decorators …] (define-global name type: type))

  • (decorate [d rest …] fn)

decorate-nothing

The error for a decorator over a declaration. A declaration binds no value, so a decorator has nothing to transform and its result would be dropped; the decorate arms route every valueless binding subject here, which refuses it at compile time naming the form.

Accepts

  • (decorate-nothing form)

decorate-subject

Applies one decorator expression to a subject form.

A body-less extent form (let, with, parameterize) in decorator position is completed by grafting the subject in as its body, so the extent spans the evaluation of the subject itself. The call-time variants (call-with, call-parameterize) instead wrap the subject in a forwarding function that enters the extent per invocation, calls the subject with the passed arguments, and delivers its value after the extent closes. entry-point binds the subject as the module’s __entry__, the function the launcher calls with no arguments once the module has loaded as a program, and delivers the subject unchanged. Any other decorator expression is evaluated and invoked on the subject, mimicking function composition. Further shape arms can be registered with extend-syntax; registered arms are tried before the invocation arm.

Accepts

  • (decorate-subject (let bindings) subject)

  • (decorate-subject (with binding) subject)

  • (decorate-subject (parameterize params) subject)

  • (decorate-subject (call-with binding) subject)

  • (decorate-subject (call-parameterize params) subject)

  • (decorate-subject entry-point subject)

  • (decorate-subject deco subject)

decr!

Decrement a variable in-place. If value is not provided, decrement by 1.

Accepts

  • (decr! location)

  • (decr! location value)

def

Defines a function and binds it to its name in the scope the form appears in. A return type may follow the name as :: TYPE.

Accepts

  • (def name rest …)

default!

Assigns value to a storage location if that location is not already assigned to a truthy value of its own.

Accepts

  • (default! location value)

define-environ

Declare a name as an environment variable in a scope, with an optional default value if the environment variable is not set.

Accepts

  • (define-environ name default)

  • (define-environ name)

define-fence

Accepts

  • (define-fence name [source-str options] body …)

define-parameter

Declare a name as a parameter in a scope, with an optional default value.

Accepts

  • (define-parameter name)

  • (define-parameter name default)

del!

Clears a binding, or deletes an attribute, or item.

Accepts

  • (del! (item obj name))

  • (del! (attr obj name))

  • (del! name)

dict-each

Dict comprehension over a sequence.

With key: and value: clauses, each element stores KEY to VALUE. Otherwise the body is a (key value) pair per element. A when: or unless: clause filters, as does a body that is a single when or unless form, with the same whole-body rule as list-each. The sequence is evaluated first, in the scope the form is in, so a class-body name is in reach.

Accepts

  • (dict-each [binding seq] key: key value: value)

  • (dict-each [binding seq] when: condition key: key value: value)

  • (dict-each [binding seq] unless: condition key: key value: value)

  • (dict-each [binding seq] (when condition body …))

  • (dict-each [binding seq] (unless condition body …))

  • (dict-each [binding seq] when: condition body)

  • (dict-each [binding seq] when: condition body …)

  • (dict-each [binding seq] unless: condition body)

  • (dict-each [binding seq] unless: condition body …)

  • (dict-each [binding seq] body)

  • (dict-each [binding seq] body …)

each

Generator comprehension over a sequence

Accepts

  • (each [binding seq] (when condition body …))

  • (each [binding seq] (unless condition body …))

  • (each [binding seq] when: condition body)

  • (each [binding seq] when: condition body …)

  • (each [binding seq] unless: condition body)

  • (each [binding seq] unless: condition body …)

  • (each [binding seq] body)

  • (each [binding seq] body …)

flet

Binds local functions for the extent of a body, eg.:

(flet [[double [x] (* x 2)]
       [inc [x] (+ x 1)]]
  (double (inc 20)))

Each binding is an anonymous function; the initializers are evaluated in the enclosing scope, so a binding shadows an outer function of the same name but does not see its siblings in the same flet (no mutual recursion). Use labels when the functions must call one another.

Accepts

  • (flet [[name formals fbody …] …] body …)

function-compose

Composes multiple functions into a single function, eg.:

(function-compose fn1 (fn2 foo) fn3))

is equivalent to:

(lambda [*: args **: kwds]
  (fn1 ((fn2 foo) (fn3 *: args **: kwds))))

Note that this composition is syntactic, and the arguments are not evaluated until the composed function is called.

Accepts

  • (function-compose fn1)

  • (function-compose fn1 …)

global

A prefix over a binding form, binding it at the module rather than in the scope the form appears in. global var takes the shapes of var and lowers to define-global; global syntax lowers to define-syntax. The def and class arms are added where those forms are defined.

Followed by def, binds the function at the module rather than in the scope the form appears in.

Followed by class, binds the class at the module rather than in the scope the form appears in.

Accepts

  • (global class name supers body …)

  • (global def name rest …)

  • (global var (PAIR pattern) (BIND value))

  • (global var (PAIR pattern))

  • (global var (SYMBOL name) (REST rest))

  • (global syntax (SYMBOL name) (REST rest))

has?

True if the collection contains the element

Accepts

  • (has? collection element)

if

Evaluates the then body only when the condition is truthy. Evaluates the else body otherwise, or None if not provided.

Accepts

  • (if condition then: then else: else)

  • (if condition then else)

  • (if condition then)

incr!

Increment a variable in-place. If value is not provided, increment by 1.

Accepts

  • (incr! location)

  • (incr! location value)

inline-macro

Evaluate body and expand to the resulting form

Accepts

  • (inline-macro body …)

item*

Nested item access, where the key is evaluated in order from left to right.

For example:

(item* obj key1 key2 key3)

is equivalent to:

(item (item (item obj key1) key2) key3)

Accepts

  • (item* obj key)

  • (item* obj key rest …)

item-slice

Slice a sequence.

Example:

(item-slice sequence start ...)

is equivalent to:

(item sequence (slice start ...))

Accepts

  • (item-slice sequence)

  • (item-slice sequence args …)

labels

Binds local functions for the extent of a body, with the names visible to one another so the functions can be mutually recursive, eg.:

(labels [[even? [n] (if (== n 0) True (odd? (- n 1)))]
         [odd? [n] (if (== n 0) False (even? (- n 1)))]]
  (even? 10))

Each function is bound with var inside a shared scope, so a binding’s body sees every sibling in the same labels (unlike flet, whose initializers are evaluated in the enclosing scope and cannot see siblings).

Accepts

  • (labels [[name formals fbody …] …] body …)

let*

Nested let bindings, where the bindings are evaluated in order from left to right.

Accepts

  • (let* [] body …)

  • (let* [first] body …)

  • (let* [first rest …] body …)

let-syntax

Accepts

  • (let-syntax name (syntax-rules literals rule …) body …)

let-values

Evaluates body in a new scope with binding values defined from unpacking the sequence value according to pattern.

Example:

(let-values [[a b *: more] my-val]
  body ...)

performs an unpacking assignment from sequence my-val into the bindings a, b, and more, with more being a sequence of the remaining values.

Accepts

  • (let-values [pattern value] body …)

list-each

List comprehension over a sequence.

A body that is a single when or unless form is a filter: the collection happens inside the conditional, so skipped elements contribute nothing (no None gaps). This applies only when the conditional encompasses the whole body, and filters do not compose – a nested when is an ordinary expression whose None lands in the list. Write (when (and a b) …) for a composite check, or (if rule x None) to collect the None deliberately.

The sequence is evaluated first, in the scope the form is in, so a class-body name is in reach.

Accepts

  • (list-each [binding seq] (when condition body …))

  • (list-each [binding seq] (unless condition body …))

  • (list-each [binding seq] when: condition body)

  • (list-each [binding seq] when: condition body …)

  • (list-each [binding seq] unless: condition body)

  • (list-each [binding seq] unless: condition body …)

  • (list-each [binding seq] body)

  • (list-each [binding seq] body …)

macroexpandq

Quote and expand a source object in the given namespace, or the current globals namespace if unspecified. Repeat until the result is no longer a macro.

See also: macroexpand

Accepts

  • (macroexpandq form ns)

  • (macroexpandq form)

macroexpandq-1

Quote and expand a source object in the given namespace, or the current globals namespace if unspecified.

See also: macroexpand-1

Accepts

  • (macroexpandq-1 form ns)

  • (macroexpandq-1 form)

package-pragma

Update the pragma in the current module with the given settings, then record the result as the package default that sub-packages and sub-modules inherit

eg.:

(package-pragma [compiler/call-brackets 'error])

Declare in a package __init__, before any local (pragma …) overrides and before importing submodules; later local (pragma …) changes do not alter the recorded package default.

Accepts

  • (package-pragma)

  • (package-pragma [settings …] …)

  • (package-pragma setting)

parameterq

Resolve a parameter by literal name. Lowers to the PARAM opcode family; parameter remains for names computed at runtime.

Accepts

  • (parameterq name)

  • (parameterq name default)

pass

A no-op expression, evaluates to None

pass supports use as a bare control word via the pragma compiler/bare-control-words

Accepts

  • [pass]

pragma

Update the pragma in the current module with the given settings

eg.:

(pragma [compiler/call-brackets 'warn])

To get the value of a pragma key, use eg.:

(pragma compiler/call-brackets)

To get the pragma object, use:

(pragma)

Accepts

  • (pragma (REPEAT settings (LIST (SYMBOL key) (REST values))))

  • (pragma (SYMBOL key))

  • (pragma)

ref

Obtain a reference to a storage location

Accepts

  • (ref (item obj name))

  • (ref (attr obj name))

  • (ref (dynamic r …))

  • (ref (constant value))

  • (ref (memoized getfn))

  • (ref (parameter name default))

  • (ref (parameter name))

  • (ref (environ key default))

  • (ref (environ key))

  • (ref name)

set!

Flexible assignment syntax

Accepts

  • (set! (car p) value)

  • (set! (cdr p) value)

  • (set! (cadr p) value)

  • (set! (caddr p) value)

  • (set! (cadddr p) value)

  • (set! (caddddr p) value)

  • (set! (cddr p) value)

  • (set! (cdddr p) value)

  • (set! (cddddr p) value)

  • (set! (values pattern …) value)

  • (set! name (+ name value))

  • (set! name (- name value))

  • (set! name (* name value))

  • (set! name (/ name value))

  • (set! name (// name value))

  • (set! name (% name value))

  • (set! name (** name value))

  • (set! name (@ name value))

  • (set! name (<< name value))

  • (set! name (>> name value))

  • (set! name (& name value))

  • (set! name (^ name value))

  • (set! name (| name value))

  • (set! (item obj name) value)

  • (set! (attr obj name) value)

  • (set! (deref ref) value)

  • (set! name value)

syntax

Define a syntax transformer. At module top level it is bound as define-syntax binds it; inside a body it applies to the rest of that body.

Accepts

  • (syntax name rest …)

take!

Takes a value from a binding, attribute, or item, clearing it.

Accepts

  • (take! (item obj name))

  • (take! (attr obj name))

  • (take! name)

unassigned?

True if a storage location currently has no value

Accepts

  • (unassigned? location)

unless

Evaluates the body only when the condition is false. Evaluates as None otherwise.

Accepts

  • (unless condition then …)

when

Evaluates the body only when the condition is true Evaluates as None otherwise.

Accepts

  • (when condition then …)

when-main

Evaluates the body only when the current module’s name is “__main__”

Accepts

  • (when-main body …)

Reader features

layout/bare-syntax

Lower bare-syntax block to (bare-syntax SLOT TMPL), or with a leading name in the header, (bare-syntax NAME SLOT TMPL); a multi-form template body is wrapped in begin.

The header names the called-by slot; the body is expanded like any block body, then folded, before it becomes the template.

layout/block

the default block layout handler. Folds each body entry and splices the forms onto the header.

eg. foo x:

bar

becomes (foo x bar)

A keyword names a call argument. A line that opens with one splices as the keyword followed by the fold of the rest of the line, and a sub-block whose header opens with one splices as the keyword followed by the block’s value: a begin over the body for a bare keyword header, and the lowering of the block the rest of the header heads otherwise.

eg. foo x:

bar file: stderr sep: 1 2 end:

"eol"

becomes (foo x bar file: stderr sep: (1 2) end: (begin “eol”))

Reached as the handler of a keyword-headed block itself, it returns the pair of the keyword and the value, which is what any other layout folding such an entry receives.

layout/block-begin

block layout handler that wraps the folded body in compile/begin

eg. foo x:

bar

becomes (foo x (compile/begin bar))

layout/build-class

Lower build-class block to (build-class NAME SUPERS (begin BODY)). SUPERS may be omitted; when missing, use nil.

layout/class

Lower class block to (class NAME SUPERS (begin BODY)). SUPERS may be omitted; when missing, use nil.

layout/dyn-wind

Lower layout/dyn-wind block with before/body/after peers to (compile/dyn-wind [before] [body] [after]) for compilation.

body is required; at least one of before or after is required.

Usage:

dyn-wind:
  body-exprs ...
before:
  before-exprs ...
after:
  after-exprs ...

Peers

  • before

  • after

layout/for-each

Layout handler for for-each blocks

eg.:

for-each [x (range 0 3)]:
  (print x)
else:
  (print "done")

Peers

  • else

layout/global

Lower a global block through the layout of the word after global, with global put back in front: global class NAME: reads as the class block would, and a word with no layout of its own, or a bare global header, reads through the default block layout

eg. global class C:

x

becomes (global class C () (begin x))

layout/if

Lower if/elif/else block sources to compile/cond for compilation.

eg.:

if x:
  (print "x")
elif y:
  (print "y")
else:
  (print "other")
param source:

((if COND) . BODY) pair

param peers:

list of peer (header . body) pairs

Peers

  • elif

  • else

layout/inline-block

inlining layout handler which splices the elements of every body line onto the header as to produce a single list, folding nothing. Used in cases where layout blocks are only meant to break up long lines, rather than to express sub-expressions. A sub-block whose header opens with a keyword splices as the keyword and its value, as under layout/block.

eg. X foo:

bar (baz) qux alpha: beta

becomes (X foo bar (baz) qux alpha: beta)

layout/macro-match

Lower macro-match block to (macro-match (PATTERN . BODY...) ...).

Same rule shape as macro-rules blocks.

layout/macro-rules

Lower macro-rules block to (macro-rules (LIT ...) (PATTERN . BODY...) ...).

Same block shape as syntax-rules; only the emitted head differs.

layout/match

Lower a match block source into a flat match form for compilation

eg.:

match (get-value):
  case #[a b c]:
    (use a b c)
  case x :: int:
    (use x)
  case Point[x y]:
    (use x y)
  else:
    (other)

A raw layout: the case and else children arrive as block sources, so each case header (however many tokens) is structurally separate from its body. A body entry that is not a block is refused. The whole header tail becomes the clause’s pattern delimiter, giving

(compile/match VALUE
  [[PATTERN...] BODY...]
  ...
  [else: BODY...])

which is the same clause shape an s-expr author writes directly. A when / unless marker in a case header splits it into pattern and guard: case PATTERN when COND: emits [[PATTERN] when: COND BODY...].

param source:

((match VALUE) . BODY) pair with raw block children

param peers:

must be empty

layout/quasiquote

Unbox a synthetic quasiquote layout block to (compile/quasiquote INNER-BLOCK)

INNER-BLOCK is the raw :#block: from the quasiquoted form

layout/quasiquote-syntax

Unbox a synthetic quasiquote-syntax layout block, read from a #` block, to (compile/quasiquote-syntax INNER-BLOCK)

layout/quote

Unbox a synthetic quote layout block to (compile/quote INNER-BLOCK)

INNER-BLOCK is the raw :#block: from the quoted form, not layout-expanded

layout/quote-syntax

Unbox a synthetic quote-syntax layout block, read from a #' block, to (compile/quote-syntax INNER-BLOCK)

layout/special-match

Lower special-match block to (special-match (PATTERN . BODY...) ...).

Same rule shape as macro-match blocks.

layout/special-rules

Lower special-rules block to (special-rules (LIT ...) (PATTERN . BODY...) ...).

Same block shape as macro-rules; only the emitted head differs.

layout/switch

Lower a switch block source into a flat switch form for compilation

eg.:

switch (get-value):
  case [1]:
    (print "one")
  case [2]:
    (print "two")
  case [3 5]:
    (print "three")
  else:
    (print "other")

A raw layout: the case and else children arrive as block sources, so each header is structurally separate from its body and a case header can be held to exactly one condition list. A body entry that is not a block is refused. Emits

::
(switch VALUE

([COMP…] BODY…) … (else: BODY…))

param source:

((switch VALUE) . BODY) pair with raw block children

param peers:

must be empty

layout/syntax-match

Lower syntax-match block to (syntax-match (PATTERN . TMPL...) ...).

No literals list; each raw rule child supplies pattern and template forms.

layout/syntax-rules

Lower syntax-rules block to (syntax-rules (LIT ...) (PATTERN . TMPL...) ...).

Each raw rule child supplies the pattern column from its header and template forms from its body.

layout/try

Lower try/except/else/finally block sources to (try …) for compilation.

param source:

((try) . BODY) pair

param peers:

list of peer (header . body) pairs

Peers

  • except

  • else

  • finally

layout/while

Layout handler for while blocks

eg.:

while (< x 3):
  (print x)
  set! x (+ x 1)
else:
  (print "done")

Peers

  • else