GitHub

API reference for ast.

The schema AST (Effect's SchemaAST): one node per kind of value.

A schema object (Bottom) wraps one of these. Each node knows the text of what it expects (get_expected, "string") and parses a value of its own kind (parse), then runs its checks (Filter / FilterGroup) on the value. annotations hold documentation and message overrides (identifier, message, expected, ...), keyed in snake_case.

Python mappings: Number accepts int and float (JavaScript has one number type), BigInt accepts int, Null is None; bool is neither a number nor a bigint. Enum is a Python enum.Enum, decoded from its values. Symbol and UniqueSymbol have no Python counterpart; S.Undefined, S.Void and S.ObjectKeyword are declarations here, not nodes.

Values

AttributeTypeDescription
resolve_description(AST) -> (str | None)

The node's description annotation (Effect's resolveDescription).

resolve_identifier(AST) -> (str | None)

The node's identifier annotation (Effect's resolveIdentifier).

resolve_title(AST) -> (str | None)

The node's title annotation (Effect's resolveTitle).

STRUCTURALLiteral['~structural'] = '~structural'

The annotation of a check of a value's shape (a length, a size, a key count): it holds on both sides of a composite whose parts transform.

SENTINELSLiteral['~sentinels'] = '~sentinels'

The annotation of a declaration's sentinels: (key, literal) pairs its values hold, as a struct's required literal keys.

jsonDeclaration

Any JSON value (is_json), unchanged.

string_treeDeclaration

Any string tree (is_string_tree), unchanged: an opaque value's to_codec_string_tree form.

any_Any
big_intBigInt
booleanBoolean
neverNever
nullNull
numberNumber
stringString
unknownUnknown
whole_numberNumber
MISSINGMissing

An absent value (see the module).

MISSING_EXITFinal[Success[object]]
BIG_INT_PATTERNLiteral['-?\\d+'] = '-?\\d+'
FINITE_PATTERNLiteral['[+-]?(?:\\d+(?:\\.\\d+)?|\\.\\d+)(?:[Ee][+-]?\\d+)?'] = '[+-]?(?:\\d+(?:\\.\\d+)?|\\.\\d+)(?:[Ee][+-]?\\d+)?'

Finite decimal text, with an optional exponent (Effect's FINITE_PATTERN).

STRING_PATTERNLiteral['[\\s\\S]*?'] = '[\\s\\S]*?'

Any text, newlines included (Effect's STRING_PATTERN).

Types

TypeDefinitionDescription
Annotationstype Annotations = Mapping[str, object]
Checkstype Checks = tuple[Check[Any], *(tuple[Check[Any], ...])]

The checks of a node, run in order on the value it parsed.

Sentineltype Sentinel = tuple[Hashable, LiteralValue]

A required key (or a tuple's index) and the literal it must hold.

Checktype Check[T] = Filter[T] | FilterGroup[T]
FilterIssuetype FilterIssue = str | Issue | tuple[Path, str | Issue]

One failure a filter function reports: a message, an issue, or either at a path below the value (Effect's { path, issue }).

FilterOutputtype FilterOutput = bool | FilterIssue | list[FilterIssue] | None

What a filter function gives: True / None / [] to accept, False ("Expected <expected>"), one failure or a list of them.

ClassSidetype ClassSide = _Literal['decode', 'encode', 'type', 'encoded']
DeclarationParsertype DeclarationParser = Callable[[object, Declaration, ParseOptions], ParseResult]
DeclarationRuntype DeclarationRun = Callable[[tuple[AST, ...]], DeclarationParser]
Encodingtype Encoding = tuple[Link, *(tuple[Link, ...])]
EnumSidetype EnumSide = _Literal['decode', 'encode', 'type', 'encoded']
LiteralValuetype LiteralValue = str | int | float | bool | None
ParseResulttype ParseResult = Exit[object, Issue] | Effect[object, Issue, Any]

A parse's outcome: an Exit when it ran synchronously, else the Effect that finishes it.

UnionModetype UnionMode = _Literal['any_of', 'one_of']

Classes

Functions

is_optional

is_optional(ast) -> bool

A struct key holding ast may be missing (Effect's isOptional: the node is optional_key).

ParameterTypeDescription
astAST

Returns bool

def is_optional(ast: AST) -> bool:
    """A struct key holding ``ast`` may be missing (Effect's ``isOptional``:
    the node is ``optional_key``)."""
    return ast.optional_key

resolve_at

resolve_at(key) -> Callable[[AST], object]

The annotation key of the annotations describing a node (its last check's when it has checks, else its own), or None (Effect's resolveAt).

ParameterTypeDescription
keystr

Returns Callable[[AST], object]

def resolve_at(key: str) -> Callable[[AST], object]:
    """The annotation ``key`` of the annotations describing a node (its last
    check's when it has checks, else its own), or ``None`` (Effect's
    ``resolveAt``)."""

    def at(ast: AST) -> object:
        return (ast.resolve() or {}).get(key)

    return at

annotate

annotate[N: AST](ast, annotations) -> N

ast with annotations merged over its own; on a node with checks they go to the last check, which then describes the node.

ParameterTypeDescription
astN
annotationsAnnotations

Returns N

def annotate[N: AST](ast: N, annotations: Annotations) -> N:
    """``ast`` with ``annotations`` merged over its own; on a node with
    checks they go to the last check, which then describes the node."""
    if ast.checks:
        *rest, last = ast.checks
        return replace_checks(ast, (*rest, last.annotate(**annotations)))
    return copy(ast, annotations={**(ast.annotations or {}), **annotations})

append_checks

append_checks[N: AST](ast, checks) -> N

ast with checks run after its own.

ParameterTypeDescription
astN
checksChecks

Returns N

def append_checks[N: AST](ast: N, checks: Checks) -> N:
    """``ast`` with ``checks`` run after its own."""
    return replace_checks(ast, (*ast.checks, *checks) if ast.checks else checks)

invalid_type

invalid_type(ast, input, options) -> Failure[Issue]
ParameterTypeDescription
astAST
inputobject
optionsParseOptions

Returns Failure[Issue]

def invalid_type(ast: AST, input: object, options: ParseOptions) -> Failure[Issue]:
    return fail_exit(InvalidType(ast, reported(input, options)))

issue_of

issue_of(failure) -> Issue | None

The issue of a failed parse, or None when its cause holds anything else (a defect is never a mismatch).

ParameterTypeDescription
failureFailure[Issue]

Returns Issue | None

def issue_of(failure: Failure[Issue]) -> Issue | None:
    """The issue of a failed parse, or ``None`` when its cause holds
    anything else (a defect is never a mismatch)."""
    reasons = failure.cause.reasons
    if reasons and all(isinstance(r, Fail) and is_issue(r.error) for r in reasons):
        first = reasons[0]
        return first.error if isinstance(first, Fail) else None
    return None

join_checks

join_checks(first, second) -> Checks | None
ParameterTypeDescription
firstChecks | None
secondChecks | None

Returns Checks | None

def join_checks(first: Checks | None, second: Checks | None) -> Checks | None:
    if first is None:
        return second
    if second is None:
        return first
    return (*first, *second)

map_or_same

map_or_same[A](items, f) -> tuple[A, ...]

f of each item, or items itself when f returns every item unchanged (is), Effect's mapOrSame.

ParameterTypeDescription
itemstuple[A, ...]
fCallable[[A], A]

Returns tuple[A, ...]

def map_or_same[A](items: tuple[A, ...], f: Callable[[A], A]) -> tuple[A, ...]:
    """``f`` of each item, or ``items`` itself when ``f`` returns every item
    unchanged (``is``), Effect's ``mapOrSame``."""
    out: list[A] | None = None
    for i, item in enumerate(items):
        mapped = f(item)
        if out is not None:
            out.append(mapped)
        elif mapped is not item:
            out = [*items[:i], mapped]
    return items if out is None else tuple(out)

replace_checks

replace_checks[N: AST](ast, checks) -> N

ast with checks in place of its own; ast itself when they are the same tuple. A Suspend takes no checks (its target does).

ParameterTypeDescription
astN
checksChecks | None

Returns N

def replace_checks[N: AST](ast: N, checks: Checks | None) -> N:
    """``ast`` with ``checks`` in place of its own; ``ast`` itself when they
    are the same tuple. A ``Suspend`` takes no checks (its target does)."""
    if ast.tag == "Suspend" and checks:
        raise ValueError("Cannot add checks to Suspend")
    return ast if ast.checks is checks else copy(ast, checks=checks)

replace_context

replace_context[A: AST](node, *, key_annotations=None, optional_key=None) -> A

node with another key context (Effect's replaceContext): a copy sharing node's body (its owner), node itself when the context is its own, or the owner when the context is the owner's.

ParameterTypeDescription
nodeA
key_annotationsAnnotations | None = None
optional_keybool | None = None

Returns A

def replace_context[A: AST](
    node: A, *, key_annotations: Annotations | None = None, optional_key: bool | None = None
) -> A:
    """``node`` with another key context (Effect's ``replaceContext``): a
    copy sharing ``node``'s body (its ``owner``), ``node`` itself when the
    context is its own, or the owner when the context is the owner's."""
    return _in_context(
        node,
        node.key_annotations if key_annotations is None else key_annotations,
        node.optional_key if optional_key is None else optional_key,
        node.constructor_default,
    )

replace_encoding

replace_encoding[N: AST](ast, encoding) -> N

ast decoding through encoding instead of its own; ast itself when it is the same.

ParameterTypeDescription
astN
encodingEncoding | None

Returns N

def replace_encoding[N: AST](ast: N, encoding: Encoding | None) -> N:
    """``ast`` decoding through ``encoding`` instead of its own; ``ast``
    itself when it is the same."""
    return ast if ast.encoding is encoding else copy(ast, encoding=encoding)

structural_checks

structural_checks(checks) -> Checks | None

The structural checks among checks, a group's structural members taken out of it (Effect's extractStructuralChecks).

ParameterTypeDescription
checksChecks

Returns Checks | None

def structural_checks(checks: Checks) -> Checks | None:
    """The structural checks among ``checks``, a group's structural members
    taken out of it (Effect's ``extractStructuralChecks``)."""
    out: list[Check[Any]] = []
    _extract_structural(checks, out)
    return (out[0], *out[1:]) if out else None

with_constructor_default

with_constructor_default[A: AST](ast, default) -> A

ast whose missing key or element a constructor fills with default's value (Effect's SchemaAST.withConstructorDefault); the copy shares ast's body.

ParameterTypeDescription
astA
defaultEffect[object, Issue]

Returns A

def with_constructor_default[A: AST](ast: A, default: Effect[object, Issue]) -> A:
    """``ast`` whose missing key or element a constructor fills with
    ``default``'s value (Effect's ``SchemaAST.withConstructorDefault``); the
    copy shares ``ast``'s body."""
    require_effect(default, "default")
    return _in_context(ast, ast.key_annotations, ast.optional_key, default)

collect_sentinels

collect_sentinels(ast) -> tuple[Sentinel, ...]

The required literal keys of a mapping node and the required literal elements of a tuple, by index (Effect's collectSentinels); a union's are those all its members share, a declaration's its "~sentinels" annotation.

ParameterTypeDescription
astAST

Returns tuple[Sentinel, ...]

def collect_sentinels(ast: AST) -> tuple[Sentinel, ...]:
    """The required literal keys of a mapping node and the required literal
    elements of a tuple, by index (Effect's ``collectSentinels``); a union's
    are those all its members share, a declaration's its ``"~sentinels"``
    annotation."""
    return _sentinels(ast, _Memo())

collect_issues

collect_issues(checks, value, ast, options) -> tuple[Issue, *(tuple[Issue, ...])] | None

The failures of checks on value, or None.

ParameterTypeDescription
checksSequence[Check[object]]
valueobject
astAST
optionsParseOptions

Returns tuple[Issue, *(tuple[Issue, ...])] | None

def collect_issues(
    checks: Sequence[Check[object]], value: object, ast: AST, options: ParseOptions
) -> tuple[Issue, *tuple[Issue, ...]] | None:
    """The failures of ``checks`` on ``value``, or ``None``."""
    issues: list[_issue.Filter] = []
    _collect(checks, value, ast, options, issues)
    return (issues[0], *issues[1:]) if issues else None

filter_of

filter_of[T](predicate, annotations=None, abort=False) -> Filter[T]

make_filter with the annotations as one mapping.

ParameterTypeDescription
predicateCallable[[T], FilterOutput]
annotationsAnnotations | None = None
abortbool = False

Returns Filter[T]

def filter_of[T](
    predicate: Callable[[T], FilterOutput],
    annotations: Annotations | None = None,
    abort: bool = False,
) -> Filter[T]:
    """``make_filter`` with the annotations as one mapping."""

    def run(input: T, ast: AST, options: ParseOptions) -> Issue | None:
        return normalize_filter_output(ast, predicate(input), input, options)

    return Filter(run, annotations, abort)

has_check

has_check(checks, id) -> bool

Whether a check with the representation id id is among checks or the groups inside them (Effect's hasCheck).

ParameterTypeDescription
checksSequence[Check[Any]] | None
idstr

Returns bool

def has_check(checks: Sequence[Check[Any]] | None, id: str) -> bool:
    """Whether a check with the ``representation`` id ``id`` is among
    ``checks`` or the groups inside them (Effect's ``hasCheck``)."""
    for check in checks or ():
        if isinstance(check, FilterGroup):
            if has_check(check.checks, id):
                return True
            continue
        representation = (check.annotations or {}).get("representation")
        if isinstance(representation, Mapping) and representation.get("id") == id:  # pyright: ignore[reportUnknownMemberType]
            return True
    return False

make_filter

make_filter[T](predicate, /, *, abort=False, **annotations) -> Filter[T]

A filter from a function returning a FilterOutput (Effect's makeFilter).

ParameterTypeDescription
predicateCallable[[T], FilterOutput]
abortbool = False
annotationsobject = {}

Returns Filter[T]

def make_filter[T](
    predicate: Callable[[T], FilterOutput], /, *, abort: bool = False, **annotations: object
) -> Filter[T]:
    """A filter from a function returning a ``FilterOutput`` (Effect's
    ``makeFilter``)."""

    return filter_of(predicate, annotations or None, abort)

make_filter_by_guard

make_filter_by_guard[T](guard, annotations=None) -> Filter[T]

A filter accepting what guard accepts; it always aborts, as the checks after a guard may rely on it.

ParameterTypeDescription
guardCallable[[T], bool]
annotationsAnnotations | None = None

Returns Filter[T]

def make_filter_by_guard[T](
    guard: Callable[[T], bool], annotations: Annotations | None = None
) -> Filter[T]:
    """A filter accepting what ``guard`` accepts; it always aborts, as the
    checks after a guard may rely on it."""

    def run(input: T, ast: AST, options: ParseOptions) -> Issue | None:
        return None if guard(input) else InvalidValue(None, reported(input, options))

    return Filter(run, annotations, True)

normalize_filter_output

normalize_filter_output(ast, out, input, options) -> Issue | None

The issue a filter function's output stands for, or None.

ParameterTypeDescription
astAST
outFilterOutput
inputobject
optionsParseOptions

Returns Issue | None

def normalize_filter_output(
    ast: AST, out: FilterOutput, input: object, options: ParseOptions
) -> Issue | None:
    """The issue a filter function's output stands for, or ``None``."""
    if out is None or out is True:
        return None
    if out is False:
        return InvalidValue(None, reported(input, options))
    if not isinstance(out, list):
        return _filter_issue(out, input, options)
    issues = [_filter_issue(entry, input, options) for entry in out]
    if not issues:
        return None
    if len(issues) == 1:
        return issues[0]
    return Composite(ast, (issues[0], *issues[1:]), reported(input, options))

check_instance

check_instance(shape, instance, options) -> Exit[object, Issue]

instance after the class's own checks.

ParameterTypeDescription
shapeClassShape
instanceobject
optionsParseOptions

Returns Exit[object, Issue]

def check_instance(
    shape: ClassShape, instance: object, options: ParseOptions
) -> Exit[object, Issue]:
    """``instance`` after the class's own checks."""
    checks = shape.checks
    if checks is None or options.get("disable_checks"):
        return Success(instance)
    try:
        issues = collect_issues(checks, instance, shape.fields, options)
    except Exception as defect:
        return die_exit(defect)
    if issues is None:
        return Success(instance)
    return fail_exit(Composite(shape.fields, issues, reported(instance, options)))

struct

struct(fields, checks=None, annotations=None) -> Objects

A struct of fields, keys in order; a field is optional when its node is optional_key.

ParameterTypeDescription
fieldsMapping[str, AST]
checksChecks | None = None
annotationsAnnotations | None = None

Returns Objects

def struct(
    fields: Mapping[str, AST], checks: Checks | None = None, annotations: Annotations | None = None
) -> Objects:
    """A struct of ``fields``, keys in order; a field is optional when its
    node is ``optional_key``."""
    return Objects(
        tuple(PropertySignature(name, node, node.optional_key) for name, node in fields.items()),
        annotations=annotations,
        checks=checks,
    )

struct_with_rest

struct_with_rest(ast, records) -> Objects

ast's keys and every record's keys and key patterns, with all their checks. A node with an encoding raises ValueError, as does a key two of them declare.

ParameterTypeDescription
astObjects
recordsSequence[Objects]

Returns Objects

def struct_with_rest(ast: Objects, records: Sequence[Objects]) -> Objects:
    """``ast``'s keys and every record's keys and key patterns, with all
    their checks. A node with an encoding raises ``ValueError``, as does a
    key two of them declare."""
    if ast.encoding is not None or any(r.encoding is not None for r in records):
        raise ValueError("StructWithRest does not support encodings")
    properties = list(ast.properties)
    index_signatures = list(ast.index_signatures)
    checks = ast.checks
    for record in records:
        for p in record.properties:
            if any(q.name == p.name for q in properties):
                raise ValueError(f"Duplicate identifier: {_json_text.stringify(p.name)}. ts(2300)")
        properties += record.properties
        index_signatures += record.index_signatures
        checks = join_checks(checks, record.checks)
    return Objects(tuple(properties), tuple(index_signatures), checks=checks)

tuple_

tuple_(elements, checks=None) -> Arrays

A fixed tuple of elements; an element is optional when its node is optional_key.

ParameterTypeDescription
elementsSequence[AST]
checksChecks | None = None

Returns Arrays

def tuple_(elements: Sequence[AST], checks: Checks | None = None) -> Arrays:
    """A fixed tuple of ``elements``; an element is optional when its node
    is ``optional_key``."""
    return Arrays(tuple(Element(node, node.optional_key) for node in elements), checks=checks)

tuple_with_rest

tuple_with_rest(ast, rest) -> Arrays

ast's elements, then rest (see Arrays), with its checks; a node with an encoding raises ValueError.

ParameterTypeDescription
astArrays
restSequence[AST]

Returns Arrays

def tuple_with_rest(ast: Arrays, rest: Sequence[AST]) -> Arrays:
    """``ast``'s elements, then ``rest`` (see ``Arrays``), with its checks;
    a node with an encoding raises ``ValueError``."""
    if ast.encoding is not None:
        raise ValueError("TupleWithRest does not support encodings")
    return Arrays(ast.elements, tuple(rest), ast.mutable, checks=ast.checks)

union

union(members, mode='any_of', checks=None) -> Union

A union of members in order.

ParameterTypeDescription
membersSequence[AST]
modeUnionMode = 'any_of'
checksChecks | None = None

Returns Union

def union(
    members: Sequence[AST], mode: UnionMode = "any_of", checks: Checks | None = None
) -> Union:
    """A union of ``members`` in order."""
    return Union(tuple(members), mode, checks=checks)

parse_at_key

parse_at_key(ast, key, node, value, *, input, options) -> ParseResult

value (input's part at key) parsed by node; an issue is reported as ast's at key (Effect's makeCompositeAtKey).

ParameterTypeDescription
astAST
keyHashable
nodeAST
valueobject
inputobject
optionsParseOptions

Returns ParseResult

def parse_at_key(
    ast: AST,
    key: Hashable,
    node: AST,
    value: object,
    *,
    input: object,
    options: ParseOptions,
) -> ParseResult:
    """``value`` (``input``'s part at ``key``) parsed by ``node``; an issue
    is reported as ``ast``'s at ``key`` (Effect's ``makeCompositeAtKey``)."""

    def at_key(exit: Exit[object, Issue]) -> Exit[object, Issue]:
        if type(exit) is Success:
            return exit
        failure = cast("Failure[Issue]", exit)
        issue = issue_of(failure)
        if issue is None:
            return failure
        return fail_exit(Composite(ast, (Pointer((key,), issue),), reported(input, options)))

    return then(node.parse(value, options), at_key)

decode_to

decode_to[A: AST](from_, to, transformation) -> A

to, decoding from values of from_ through transformation (Effect's decodeTo): a link appended to to's encoding.

ParameterTypeDescription
from_AST
toA
transformationLinkTransformation

Returns A

def decode_to[A: AST](from_: AST, to: A, transformation: LinkTransformation) -> A:
    """``to``, decoding from values of ``from_`` through ``transformation``
    (Effect's ``decodeTo``): a link appended to ``to``'s encoding."""
    link = Link(from_, transformation)
    out = replace(to, encoding=(*to.encoding, link) if to.encoding else (link,))
    object.__setattr__(out, "body_owner", to.body_owner or to.owner())
    return out

optional_key

optional_key[A: AST](ast) -> A

ast as a struct key that may be missing on the encoded side, down to its most encoded node (Effect's optionalKey).

ParameterTypeDescription
astA

Returns A

def optional_key[A: AST](ast: A) -> A:
    """``ast`` as a struct key that may be missing on the encoded side, down
    to its most encoded node (Effect's ``optionalKey``)."""
    # _base imports this module.
    from pyfect.schema.ast._base import replace_context

    encoding = ast.encoding
    if encoding is None:
        return ast if ast.optional_key else replace_context(ast, optional_key=True)
    last = encoding[-1]
    chain: Encoding = (*encoding[:-1], Link(optional_key(last.to), last.transformation))
    return replace(ast, encoding=chain, optional_key=True)

to_encoded

to_encoded(ast) -> AST

The node's encoded side, as a node of its own (Effect's toEncoded): made once, and its own encoded side.

ParameterTypeDescription
astAST

Returns AST

def to_encoded(ast: AST) -> AST:
    """The node's encoded side, as a node of its own (Effect's ``toEncoded``):
    made once, and its own encoded side."""
    memo = ast._encoded_side  # pyright: ignore[reportPrivateUsage]
    if not memo:
        encoded = ast.flip().to_type()
        memo.append(encoded)
        own = encoded._encoded_side  # pyright: ignore[reportPrivateUsage]
        if not own:
            own.append(encoded)
    return memo[0]

is_json

is_json(value) -> bool

value is None, a string, a boolean, an int, a finite float, or a list / tuple / string-keyed Mapping of JSON values. A cycle is not JSON; a value shared twice (a DAG) is. Iterative, so any depth works.

ParameterTypeDescription
valueobject

Returns bool

def is_json(value: object) -> bool:
    """``value`` is ``None``, a string, a boolean, an ``int``, a finite
    ``float``, or a ``list`` / ``tuple`` / string-keyed ``Mapping`` of JSON
    values. A cycle is not JSON; a value shared twice (a DAG) is. Iterative,
    so any depth works."""
    return _is_tree(value, _is_json_leaf)

is_string_tree

is_string_tree(value) -> bool

value is a string, None (Effect's undefined), or a list / tuple / string-keyed Mapping of string trees (Effect's isStringTree); a cycle is not one.

ParameterTypeDescription
valueobject

Returns bool

def is_string_tree(value: object) -> bool:
    """``value`` is a string, ``None`` (Effect's ``undefined``), or a
    ``list`` / ``tuple`` / string-keyed ``Mapping`` of string trees (Effect's
    ``isStringTree``); a cycle is not one."""
    return _is_tree(value, _is_string_tree_leaf)

format_literal

format_literal(literal) -> str

A literal as Effect prints it: strings quoted, null, true.

ParameterTypeDescription
literalLiteralValue

Returns str

def format_literal(literal: LiteralValue) -> str:
    """A literal as Effect prints it: strings quoted, ``null``, ``true``."""
    match literal:
        case None:
            return "null"
        case bool():
            return "true" if literal else "false"
        case int() | float():
            return js_number(literal)
        case str():
            return json_quote(literal)

same_literal

same_literal(literal, input) -> bool

input is literal, as JavaScript's === reads them.

ParameterTypeDescription
literalLiteralValue
inputobject

Returns bool

def same_literal(literal: LiteralValue, input: object) -> bool:
    """``input`` is ``literal``, as JavaScript's ``===`` reads them."""
    match literal:
        case None:
            return input is None
        case bool():
            return isinstance(input, bool) and input == literal
        case int() | float():
            return (
                isinstance(input, (int, float)) and not isinstance(input, bool) and input == literal
            )
        case str():
            return isinstance(input, str) and input == literal

get_index_signature_keys

get_index_signature_keys(input, parameter, options=None) -> list[Any]

The keys of input that an index signature with parameter takes (Effect's getIndexSignatureKeys): those its encoded side accepts. A union's are its members' in member order, each key once.

ParameterTypeDescription
inputMapping[Any, object]
parameterAST
optionsParseOptions | None = None

Returns list[Any]

def get_index_signature_keys(
    input: Mapping[Any, object], parameter: AST, options: ParseOptions | None = None
) -> list[Any]:
    """The keys of ``input`` that an index signature with ``parameter``
    takes (Effect's ``getIndexSignatureKeys``): those its encoded side
    accepts. A union's are its members' in member order, each key once."""
    return _index_signature_keys(input, to_encoded(parameter), options or {})

record

record(key, value) -> Objects

Effect's record: each literal key (a Literal, or one in a union) is a required property, listed once; any other key node is an index signature. Never takes no key.

ParameterTypeDescription
keyAST
valueAST

Returns Objects

def record(key: AST, value: AST) -> Objects:
    """Effect's ``record``: each literal key (a ``Literal``, or one in a
    union) is a required property, listed once; any other key node is an
    index signature. ``Never`` takes no key."""
    literals: list[LiteralValue] = []
    parameters: list[AST] = []
    _split_keys(key, literals, parameters)
    return Objects(
        tuple(PropertySignature(name, value) for name in literals),
        tuple(IndexSignature(parameter, value) for parameter in parameters),
    )

call

call[*Ts](f, *args) -> ParseResult

f(*args), a user callback (a getter's function, a middleware): a raise is a defect, as in Effect.

ParameterTypeDescription
fCallable[[*Ts], ParseResult]
args*Ts = ()

Returns ParseResult

def call[*Ts](f: Callable[[*Ts], ParseResult], /, *args: *Ts) -> ParseResult:
    """``f(*args)``, a user callback (a getter's function, a middleware):
    a raise is a defect, as in Effect."""
    try:
        return f(*args)
    except Exception as defect:
        return die_exit(defect)

flat_map

flat_map(result, f) -> ParseResult

f of the parsed value; a failure stays as it is.

ParameterTypeDescription
resultParseResult
fCallable[[object], ParseResult]

Returns ParseResult

def flat_map(result: ParseResult, f: Callable[[object], ParseResult]) -> ParseResult:
    """``f`` of the parsed value; a failure stays as it is."""
    if isinstance(result, Success):
        return f(result.value)
    if isinstance(result, Failure):
        return result
    return result.flat_map(lambda value: to_effect(f(value)))

is_exit

is_exit(result) -> TypeIs[Exit[object, Issue]]
ParameterTypeDescription
resultParseResult

Returns TypeIs[Exit[object, Issue]]

def is_exit(result: ParseResult) -> TypeIs[Exit[object, Issue]]:
    return isinstance(result, (Success, Failure))

map_issue

map_issue(result, f) -> ParseResult

Each issue of a failure changed by f; defects stay.

ParameterTypeDescription
resultParseResult
fCallable[[Issue], Issue]

Returns ParseResult

def map_issue(result: ParseResult, f: Callable[[Issue], Issue]) -> ParseResult:
    """Each issue of a failure changed by ``f``; defects stay."""
    if isinstance(result, Success):
        return result
    if isinstance(result, Failure):
        return Failure(result.cause.map(f))
    return result.map_error(f)

map_value

map_value(result, f) -> ParseResult

The parsed value changed by f.

ParameterTypeDescription
resultParseResult
fCallable[[object], object]

Returns ParseResult

def map_value(result: ParseResult, f: Callable[[object], object]) -> ParseResult:
    """The parsed value changed by ``f``."""
    if isinstance(result, Success):
        return Success(f(result.value))
    if isinstance(result, Failure):
        return result
    return result.map(f)

run_now

run_now(result) -> Exit[object, Issue]

The outcome, running an effect to its end on this thread (for the synchronous adapters and checks; its services must be provided).

ParameterTypeDescription
resultParseResult

Returns Exit[object, Issue]

def run_now(result: ParseResult) -> Exit[object, Issue]:
    """The outcome, running an effect to its end on this thread (for the
    synchronous adapters and checks; its services must be provided)."""
    if isinstance(result, (Success, Failure)):
        return result
    return run_sync_exit(cast("Effect[object, Issue, Never]", result))

then

then(result, f) -> ParseResult

f of the outcome, whichever it is: called now for an Exit, when the effect ends otherwise.

ParameterTypeDescription
resultParseResult
fCallable[[Exit[object, Issue]], ParseResult]

Returns ParseResult

def then(result: ParseResult, f: Callable[[Exit[object, Issue]], ParseResult]) -> ParseResult:
    """``f`` of the outcome, whichever it is: called now for an ``Exit``,
    when the effect ends otherwise."""
    if isinstance(result, (Success, Failure)):
        return f(result)
    return result.exit().flat_map(lambda exit: to_effect(f(exit)))

to_effect

to_effect(result) -> Effect[object, Issue, Any]
ParameterTypeDescription
resultParseResult

Returns Effect[object, Issue, Any]

def to_effect(result: ParseResult) -> Effect[object, Issue, Any]:
    if isinstance(result, (Success, Failure)):
        return from_exit(result)
    return result

match_part

match_part(node, text, options) -> bool

text is a segment of the part node (Effect's matchPart).

ParameterTypeDescription
nodeAST
textstr
optionsParseOptions

Returns bool

def match_part(node: AST, text: str, options: ParseOptions) -> bool:
    """``text`` is a segment of the part ``node`` (Effect's ``matchPart``)."""
    return _match_span(node, text, 0, len(text), options)