Skip to content

Parser

parse and parse_file read QVR source into AST nodes (grammar) and raise ParseError on malformed syntax, before any tensor is created. A tree that parses may still have mismatched types, unresolved names, or unsupported effects, which later checking rejects.

parser

Parser for the quivers DSL.

The lexer/parser pipeline is delegated to panproto after overriding its qvr protocol with Quivers' packaged current grammar. The public parse entry point consumes .qvr source bytes and returns a Module of didactic models.

This package's submodules group the walker logic by topic:

  • ._registry for the panproto registry singleton, ParseError, and the _Tree view that every walker reads from.
  • ._helpers for the low-level helpers _required_text, _required_field, _field_text, and _walk_draw_arg.
  • .options for the [k=v, ...] option-block walkers.
  • .expressions for type / space / morphism-expression / let-arith walkers.
  • .program_steps for program-block step walkers.
  • .statements for the top-level _walk_statement dispatcher and every per-declaration walker (object, morphism, deduction, contraction, signature, encoder, decoder, loss, ...).
  • .core for the public parse / parse_file entry points, the whole-tree syntax validation that rejects ERROR and missing nodes, and the refusal of binders spelled as the reserved let words RESERVED_LET_WORDS.

Every public name is re-exported here so from quivers.dsl.parser import X keeps working unchanged.

RESERVED_LET_WORDS module-attribute

RESERVED_LET_WORDS: dict[str, str] = {'unit': 'the unit value', 'true': 'the Boolean literal true', 'false': 'the Boolean literal false', 'not': 'Boolean negation', 'factor': 'the factor comprehension', 'case': 'a case function', 'for': 'a tabulation'}

The words a let expression reads as something other than a name.

They are the unit value unit, the Booleans true and false, the negation not, and the expression keywords factor, case and for, each mapped to what it denotes. A binder spelled as one of them could never be referred to, since every later occurrence parses as the literal or the keyword, so a binder may not use them.

VALUE_METHODS module-attribute

VALUE_METHODS: Mapping[str, frozenset[str]] = MappingProxyType({'decoder': frozenset({'log_prob', 'sample'})})

Declaration kinds whose values have a fixed method interface, mapped to it.

A decoder's value has the interface of a distribution over terms (quivers.structural.decoder.Decoder): D.log_prob(term, code) and D.sample(code) call its methods. Any other segment after a decoder's name names a member it generates, such as D.law or D.nll.

BINDER_POSITIONS module-attribute

BINDER_POSITIONS: frozenset[tuple[str, str]] = frozenset({('notation_production', 'items'), ('qiec_value_parameter', 'name'), ('qiec_type_binder', 'name'), ('qiec_index_binder', 'name'), ('qiec_index_map_clause', 'parameters'), ('qiec_effect_binder', 'name'), ('qiec_local_binding', 'name'), ('qiec_case_static_binder', 'name'), ('qiec_instance_computation', 'name'), ('qiec_as_pattern', 'name'), ('qiec_binder_pattern', 'binders'), ('let_lambda', 'param'), ('let_factor_binder', 'var'), ('let_axis_binder', 'name'), ('program_decl', 'params'), ('typed_program_param', 'name'), ('sample_step', 'vars'), ('observe_step', 'vars'), ('call_step', 'vars'), ('let_step', 'name'), ('score_step', 'name'), ('marginalize_step', 'var'), ('var_tuple', '<child>'), ('rule_decl', 'variables'), ('schema_parameter', 'names'), ('contraction_input', 'name'), ('composition_rule_entry', 'params'), ('syntax_decl', 'params'), ('argument_variable', 'name'), ('encoder_op_rule', 'args'), ('encoder_op_rule', 'state'), ('encoder_op_rule', 'prefix'), ('encoder_init_rule', 'arg'), ('encoder_message_rule', 'src'), ('encoder_message_rule', 'tgt'), ('encoder_update_rule', 'self'), ('encoder_update_rule', 'msgs'), ('decoder_structure', 'arg'), ('decoder_primitive', 'arg'), ('decoder_factor', 'arg'), ('decoder_binder_select', 'arg'), ('string_graph_variable', 'name'), ('object_term_abstraction', 'names'), ('context_entry', 'name'), ('judgment_argument', 'name'), ('judgment_rule', 'schematic'), ('pattern_synonym_decl', 'parameters'), ('test_binder', 'name'), ('test_let', 'name'), ('let_case_branch', 'binder'), ('category_binder', 'name'), ('deduction_template', 'parameter')})

Positions binding a local name.

CLOSED_KINDS module-attribute

CLOSED_KINDS: frozenset[str] = frozenset({'deduction_atoms', 'deduction_binders', 'deduction_lexicon', 'deduction_lexicon_from_file', 'rule_instantiations', 'schema_constraint', 'deduction_category_set', 'semantic_clause', 'deduction_template', 'deduction_lexical_rule'})

Node kinds whose whole subtree is the private language of a deduction.

DECLARATION_POSITIONS module-attribute

DECLARATION_POSITIONS: dict[tuple[str, str], str] = {('notation_decl', 'name'): 'notation', ('category_decl', 'names'): 'category', ('object_decl', 'names'): 'object', ('morphism_decl', 'names'): 'morphism', ('define_decl', 'name'): 'define', ('computation_decl', 'name'): 'computation', ('typed_hole_decl', 'name'): 'computation', ('score_binding_decl', 'name'): 'computation', ('program_decl', 'name'): 'program', ('deduction_decl', 'name'): 'deduction', ('deduction_signature_decl', 'name'): 'deduction_signature', ('lexicon_decl', 'name'): 'lexicon', ('syntax_decl', 'name'): 'syntax', ('constructor_decl', 'name'): 'constructor', ('encoder_decl', 'name'): 'encoder', ('decoder_decl', 'name'): 'decoder', ('loss_decl', 'name'): 'loss', ('contraction_decl', 'name'): 'contraction', ('bundle_decl', 'name'): 'bundle', ('rule_decl', 'name'): 'rule', ('schema_decl', 'name'): 'schema', ('composition_decl', 'name'): 'composition', ('index_decl', 'name'): 'index', ('index_map_decl', 'name'): 'index_map', ('qiec_index_constructor', 'name'): 'constructor', ('indexed_family_decl', 'name'): 'family', ('qiec_constructor_decl', 'name'): 'constructor', ('effect_decl', 'name'): 'effect', ('effect_instance_decl', 'name'): 'instance', ('handler_decl', 'name'): 'handler', ('interpretation_decl', 'name'): 'computation', ('relation_decl', 'name'): 'relation', ('relation_compose_decl', 'name'): 'relation', ('relation_transform_decl', 'name'): 'relation', ('string_graph_decl', 'name'): 'string_graph', ('scoped_operation_decl', 'name'): 'scoped_operation', ('effect_law_decl', 'name'): 'effect_law', ('judgment_decl', 'name'): 'judgment', ('pattern_synonym_decl', 'name'): 'pattern', ('record_decl', 'name'): 'record', ('signature_decl', 'name'): 'signature', ('family_spec', 'name'): 'family', ('computation_spec', 'name'): 'computation', ('deduction_spec', 'name'): 'deduction', ('module_decl', 'name'): 'module', ('theory_decl', 'name'): 'theory', ('view_decl', 'name'): 'view', ('model_decl', 'name'): 'model', ('semiring_decl', 'name'): 'semiring'}

Positions declaring a module-level name, mapped to the declaration kind.

LABEL_POSITIONS module-attribute

LABEL_POSITIONS: frozenset[tuple[str, str]] = frozenset({('qiec_index_map_clause', 'constructor'), ('quotation', '<child>'), ('quotation_pattern', '<child>'), ('notation_group', '<child>'), ('notation_block', '<child>'), ('notation_production', 'name'), ('notation_relation', 'tighter'), ('notation_relation', 'looser'), ('notation_relation', 'same'), ('open_notation_decl', 'notation'), ('option_entry', 'key'), ('experiment_decl', 'name'), ('experiment_data', 'name'), ('experiment_fix', 'name'), ('experiment_fix', 'value'), ('experiment_sweep', 'name'), ('experiment_infer', 'method'), ('let_hole', 'name'), ('qiec_type_hole', 'name'), ('sharing_constraint', 'name'), ('pragma_entry', 'key'), ('pragma_entry', 'value'), ('constructor_kwarg', 'key'), ('named_draw_arg', 'parameter'), ('let_named_argument', 'name'), ('let_reduction', 'operator'), ('return_label_entry', 'label'), ('qiec_record_field_pattern', 'label'), ('scan_expr', 'outputs'), ('sample_step', 'operation'), ('interpretation_clause', 'constructor'), ('qiec_handler_operation_clause', 'operation'), ('qiec_operation_decl', 'name'), ('effect_site_estimator', 'name'), ('effect_site_estimator', 'method'), ('enum_set_literal', 'elements'), ('free_residuated_arg', 'op'), ('equation_decl', 'name'), ('judgment_rule', 'name'), ('deriving_class', 'name'), ('deduction_rule', 'name'), ('rule_instantiation', 'schema'), ('schema_constraint', 'parameter'), ('schema_constraint', 'domain'), ('object_spine', 'slash'), ('object_spine', 'argument'), ('object_spine', 'length'), ('object_sequence', 'argument'), ('object_sequence', 'length'), ('let_case_branch', 'label'), ('let_injection', 'label'), ('let_record_field', 'label'), ('qiec_row_field', 'label'), ('deduction_atoms', 'atoms'), ('deduction_binders', 'binders'), ('atom_features', 'name'), ('atom_feature', 'name'), ('atom_feature', 'set'), ('category_binder', 'set'), ('deduction_category_set', 'name'), ('deduction_template', 'name'), ('object_features', 'atom'), ('sort_decl', 'name'), ('vertex_kind_decl', 'name'), ('edge_kind_decl', 'name'), ('edge_kind_decl', 'src'), ('edge_kind_decl', 'tgt'), ('constructor_decl', 'codomain'), ('constructor_argument', 'sort'), ('argument_variable', 'sort'), ('encoder_dim', 'sort'), ('decoder_dim', 'sort'), ('encoder_init_rule', 'kind'), ('encoder_message_rule', 'edge_kind'), ('encoder_update_rule', 'vertex_kind'), ('encoder_var_init', 'var_sort'), ('encoder_var_init', 'annot_sort'), ('encoder_var_init', 'ty'), ('theory_parameter', 'name'), ('theory_sort', 'name'), ('theory_binder', 'names'), ('theory_binder', 'sort'), ('theory_operation', 'name'), ('theory_operation', 'inputs'), ('theory_operation', 'output'), ('theory_argument', 'parameter'), ('theory_rename', 'source'), ('theory_rename', 'target'), ('theory_hiding', 'names'), ('view_mapping', 'source'), ('view_mapping', 'target'), ('view_assumption', 'equations'), ('model_interpretation', 'symbol'), ('semiring_decl', 'algebra'), ('deduction_semiring', 'name')})

Positions whose token names nothing in a scope.

MODULE_POSITIONS module-attribute

MODULE_POSITIONS: frozenset[tuple[str, str]] = frozenset({('import_decl', 'path'), ('import_decl', 'alias'), ('import_list', 'names'), ('open_decl', 'module'), ('module_parameter', 'name'), ('qiec_module_parameter', 'name'), ('qiec_implicit_module_parameter', 'name'), ('hole_decl', 'path'), ('link_decl', 'hole'), ('link_decl', 'module')})

Positions of the module system's own statements.

OTHER_REFERENCE_POSITIONS module-attribute

OTHER_REFERENCE_POSITIONS: frozenset[tuple[str, str]] = frozenset({('notation_decl', 'syntax'), ('notation_production', 'template'), ('antiquotation', 'name'), ('argument_variable', 'annotation'), ('hole_decl', 'signature'), ('experiment_program', 'entry'), ('experiment_handle', 'instance'), ('share_decl', 'site'), ('share_decl', 'target'), ('bracket_index_arg', 'name'), ('signature_expr', 'base'), ('signature_expr', 'core'), ('deduction_extension', 'name'), ('lexicon_reference', 'name'), ('lexicon_decl', 'signature'), ('bundle_decl', 'rules'), ('cap_expr', 'object'), ('composition_rule_entry', 'key'), ('constructor_kwarg', 'value'), ('context_entry', 'type'), ('context_extension', 'context'), ('continuous_constructor', 'args'), ('cup_expr', 'object'), ('decoder_decl', 'sig_args'), ('decoder_decl', 'signature'), ('deriving_class', 'morphisms'), ('deriving_decl', 'family'), ('discrete_constructor', 'cardinality'), ('effect_law_owner_decl', 'owner'), ('encoder_decl', 'sig_args'), ('encoder_decl', 'signature'), ('encoder_op_rule', 'op'), ('equation_decl', 'left'), ('equation_decl', 'right'), ('family_call_arg', 'args'), ('family_call_arg', 'family'), ('free_monoid_expr', 'generators'), ('free_residuated_expr', 'generators'), ('ident_list', '<child>'), ('identity_expr', 'object'), ('interpretation_clause', 'operation'), ('interpretation_decl', 'deduction'), ('judgment_rule', 'conclusion'), ('judgment_rule', 'premises'), ('judgment_sort', 'argument'), ('judgment_sort', 'name'), ('list_arg', '<child>'), ('marginalize_step', 'args'), ('marginalize_step', 'morphism'), ('marginalize_step', 'static_args'), ('method_call', 'args'), ('morphism_call', 'args'), ('morphism_call', 'static_args'), ('morphism_init_family', 'args'), ('morphism_init_family', 'family'), ('named_draw_arg', 'value'), ('object_atom', '<child>'), ('object_effect_apply', 'effect'), ('object_term_abstraction', 'body'), ('object_term_application', 'arguments'), ('object_term_application', 'head'), ('object_term_instantiation', 'arguments'), ('object_term_instantiation', 'head'), ('observe_step', 'args'), ('observe_step', 'morphism'), ('observe_step', 'static_args'), ('option_call', 'args'), ('option_call', 'func'), ('option_entry', 'value'), ('option_list', 'item'), ('parser_arg', 'value'), ('qiec_call_computation', 'callee'), ('qiec_constructor_pattern', 'constructor'), ('qiec_constructor_value', 'constructor'), ('qiec_effect_ref', 'name'), ('qiec_effect_row_literal', 'lacks'), ('qiec_effect_row_literal', 'tail'), ('qiec_handle_computation', 'instance'), ('qiec_handler_application', 'name'), ('qiec_index_application', 'constructor'), ('qiec_index_name', 'name'), ('qiec_index_sort', 'signature'), ('qiec_name_pattern', 'name'), ('qiec_record_type', 'tail'), ('qiec_row_entry', 'name'), ('qiec_row_predicate', 'larger'), ('qiec_row_predicate', 'left'), ('qiec_row_predicate', 'result'), ('qiec_row_predicate', 'right'), ('qiec_type_application', 'constructor'), ('qiec_type_name', 'name'), ('qiec_user_index_sort', 'name'), ('qiec_variant_type', 'tail'), ('qiec_weighted_total', 'action'), ('qiec_weighted_total', 'addition'), ('relation_arc_decl', 'weight'), ('relation_auto_intersection_recipe', 'source'), ('relation_binary_recipe', 'other'), ('relation_binary_recipe', 'source'), ('relation_boundary_decl', 'weight'), ('relation_compose_decl', 'left'), ('relation_compose_decl', 'right'), ('relation_conditioning_recipe', 'source'), ('relation_join_recipe', 'other'), ('relation_join_recipe', 'source'), ('relation_projection_recipe', 'source'), ('relation_tape_decl', 'alphabet'), ('relation_unary_recipe', 'source'), ('return_label_entry', 'var'), ('return_step', 'return'), ('return_tuple', '<child>'), ('sample_step', 'args'), ('sample_step', 'morphism'), ('sample_step', 'static_args'), ('scan_expr', 'init'), ('score_binding_decl', 'graph'), ('score_binding_decl', 'relation'), ('splice_decl', 'generator'), ('string_graph_factor', 'relation'), ('string_graph_factor', 'scope'), ('string_graph_variable', 'alphabet'), ('theory_argument', 'theory'), ('theory_argument', 'view'), ('theory_decl', 'value'), ('theory_hiding', 'theory'), ('theory_include', 'theory'), ('theory_instantiation', 'theory'), ('theory_parameter', 'theory'), ('theory_renaming', 'theory'), ('theory_sum', 'shared'), ('theory_sum', 'summands'), ('view_decl', 'codomain'), ('view_decl', 'domain'), ('model_decl', 'source'), ('model_decl', 'theory'), ('model_decl', 'view'), ('model_interpretation', 'value'), ('semiring_decl', 'theory'), ('semiring_decl', 'carrier'), ('deduction_semiring', 'instance'), ('deduction_semiring', 'theory'), ('deduction_refines', 'base'), ('deduction_semantics', 'judgment')})

The remaining reference positions: each token names something in scope (a local, a declaration, an imported name, or a builtin) and trailing segments of a dotted one are a qualified path. Every identifier position of the grammar is in exactly one of these tables, which tests/dsl/test_name_positions.py checks against the grammar.

REFERENCE_POSITIONS module-attribute

REFERENCE_POSITIONS: dict[tuple[str, str], Position] = {('expr_ident', '<child>'): 'morphism', ('morphism_call', 'callee'): 'morphism', ('let_var', '<child>'): 'value', ('let_call', 'func'): 'value', ('qiec_effect_request', 'target'): 'request', ('module_path', 'name'): 'module', ('module_application', 'functor'): 'module'}

Reference positions whose trailing segments are read as members of a value. Every reference position not listed is other.

SEQUENTIAL_SCOPES module-attribute

SEQUENTIAL_SCOPES: dict[str, str] = {'program_decl': 'steps', 'marginalize_step': 'scope', 'test_decl': 'steps', 'example_decl': 'steps', 'property_decl': 'steps'}

Nodes whose list field binds sequentially: a step's binders are visible in the steps after it.

TREE_SCOPES module-attribute

TREE_SCOPES: dict[str, tuple[frozenset[str], frozenset[str]]] = {'qiec_pure_binding': (frozenset({'binder'}), frozenset({'then'})), 'qiec_bind_computation': (frozenset({'binder'}), frozenset({'then'})), 'qiec_case_branch': (frozenset({'pattern', 'constructor', 'binders', 'fields'}), frozenset({'body', 'guard'})), 'qiec_handler_return_clause': (frozenset({'binder'}), frozenset({'body'})), 'qiec_handler_operation_clause': (frozenset({'binders', 'parameters'}), frozenset({'body'})), 'qiec_instance_computation': (frozenset({'name'}), frozenset({'body'})), 'qiec_case_motive': (frozenset({'indices'}), frozenset({'result'})), 'qiec_index_map_clause': (frozenset({'parameters'}), frozenset({'body'})), 'interpretation_decl': (frozenset({'options'}), frozenset({'carrier'})), 'let_lambda': (frozenset({'param'}), frozenset({'body'})), 'let_factor': (frozenset({'binders'}), frozenset({'body', 'cases'})), 'let_tabulation': (frozenset({'binders'}), frozenset({'body'})), 'let_reduction': (frozenset({'binders'}), frozenset({'body'})), 'let_case_branch': (frozenset({'binder'}), frozenset({'body'})), 'lexicon_polymorphic_category': (frozenset({'binders'}), frozenset({'category'})), 'object_term_abstraction': (frozenset({'names'}), frozenset({'body'})), 'qiec_binder_pattern': (frozenset({'binders'}), frozenset({'body'})), 'marginalize_step': (frozenset({'var'}), frozenset({'scope'}))}

Nodes whose binders (found in the first fields) are visible in the subtrees of the second fields only.

VALUE_DECLARATION_KINDS module-attribute

VALUE_DECLARATION_KINDS: frozenset[str] = frozenset({'morphism', 'define', 'contraction', 'program', 'object', 'category'})

Declaration kinds whose values support member access: a morphism takes postfix forms, so f.dagger is the dagger of f. Every other declaration's dotted continuation names something it generates or contains (G.Item, Vec.Cons).

WHOLE_SCOPES module-attribute

WHOLE_SCOPES: dict[str, frozenset[str]] = {'notation_production': frozenset({'items'}), 'computation_decl': frozenset({'binders', 'parameters'}), 'typed_hole_decl': frozenset({'binders', 'parameters'}), 'handler_decl': frozenset({'binders', 'parameters'}), 'indexed_family_decl': frozenset({'parameters', 'indices'}), 'qiec_constructor_decl': frozenset({'binders'}), 'effect_decl': frozenset({'binders'}), 'qiec_operation_decl': frozenset({'binders'}), 'program_decl': frozenset({'binders', 'parameters', 'params'}), 'rule_decl': frozenset({'variables'}), 'schema_decl': frozenset({'parameters'}), 'contraction_decl': frozenset({'inputs'}), 'composition_rule_entry': frozenset({'params'}), 'syntax_decl': frozenset({'params'}), 'constructor_decl': frozenset({'arguments'}), 'constructor_argument': frozenset({'binds'}), 'encoder_op_rule': frozenset({'args', 'state', 'prefix'}), 'encoder_init_rule': frozenset({'arg'}), 'encoder_message_rule': frozenset({'src', 'tgt'}), 'encoder_update_rule': frozenset({'self', 'msgs'}), 'decoder_structure': frozenset({'arg'}), 'decoder_primitive': frozenset({'arg'}), 'decoder_factor': frozenset({'arg'}), 'decoder_binder_select': frozenset({'arg'}), 'string_graph_decl': frozenset({'variables'}), 'judgment_decl': frozenset({'arguments'}), 'judgment_rule': frozenset({'schematic'}), 'context_extension': frozenset({'entries'}), 'pattern_synonym_decl': frozenset({'binders', 'parameters'}), 'property_decl': frozenset({'binders'}), 'deduction_template': frozenset({'parameter'})}

Nodes whose binders (found anywhere in the listed fields) are visible in the whole node.

WRAPPER_KINDS module-attribute

WRAPPER_KINDS: frozenset[str] = frozenset({'exported_decl', 'meta_decl', 'implicit_decl'})

Wrappers around a top-level declaration.

MODULE_PARAMETER_KINDS module-attribute

MODULE_PARAMETER_KINDS: frozenset[str] = frozenset({'qiec_module_parameter', 'qiec_implicit_module_parameter'})

The parameter kinds that make a computation a region.

REGION_BODY_FIELDS module-attribute

REGION_BODY_FIELDS: frozenset[str] = frozenset({'body', 'items'})

The fields holding the statements of a region's body.

REGION_KINDS module-attribute

REGION_KINDS: frozenset[str] = frozenset({'module_decl', 'signature_decl'})

Nodes that open a scope of module-level names of their own: a module or signature body, and a computation with module parameters.

LINKING_WALKERS module-attribute

LINKING_WALKERS: dict[str, Callable[[_Tree, str], Statement]] = {'hole_decl': walk_hole, 'link_decl': walk_link, 'share_decl': walk_share}

The walker of each linking statement kind.

PREAMBLE_KINDS module-attribute

PREAMBLE_KINDS: frozenset[str] = frozenset({'hole_decl', 'link_decl'})

Linking statements that may stand among a module's imports: they do not end the imports, and may also follow declarations.

MODULE_LANGUAGE_KINDS module-attribute

MODULE_LANGUAGE_KINDS = frozenset({'signature_decl', 'module_decl', 'implicit_decl', 'family_spec', 'computation_spec', 'deduction_spec'})

The statement kinds this module walks.

NOTATION_STATEMENT_KINDS module-attribute

NOTATION_STATEMENT_KINDS = frozenset({'notation_decl', 'open_notation_decl'})

The vertex kinds of the notation statements.

EXPERIMENT_KIND module-attribute

EXPERIMENT_KIND = 'experiment_decl'

The vertex kind of an experiment declaration.

THEORY_WALKERS module-attribute

THEORY_WALKERS: dict[str, Callable[..., TheoryDecl | ViewDecl | ModelDecl]] = {'theory_decl': walk_theory_decl, 'view_decl': walk_view_decl, 'model_decl': walk_model_decl}

The walker of each theory-layer declaration kind.

Position

Position = Literal['morphism', 'value', 'request', 'module', 'other']

How trailing segments of a dotted reference are read.

In a morphism position (a morphism expression) segments after a value are postfix forms; in a value position (a pure expression) they are method calls or projections; in a request position (perform) the last segment is the operation; in a module position (a module expression) the whole name may name a module; anywhere else a dotted name is a qualified reference.

Role

Role = Literal['declaration', 'binder', 'reference', 'label', 'module']

What an identifier token is, by its grammar position.

StatementWalker

StatementWalker = Callable[[_Tree, str], Statement | list[Statement]]

Walks one statement vertex, as the statement dispatcher does.

NameUse didactic-model

NameUse(*, start: int, end: int, reference: str, members: int = 0)

Bases: Model

How the walkers read one name token.

ATTRIBUTE DESCRIPTION
start, end

The token's byte span.

TYPE: int

reference

The text the token's reference part reads as: the flat name name resolution assigned, or the token's own spelling of that part.

TYPE: str

members

How many trailing segments of the token select members of the referenced value (methods, postfix forms) rather than naming it.

TYPE: int

NameView didactic-model

NameView(*, uses: tuple[NameUse, ...] = (), line_offset: int = 0)

Bases: Model

How the parse walkers read the names of one file.

Name resolution decides, per token, which flat name a reference reads as and which trailing segments of a dotted token are member accesses. The walkers read every token through this view, so an ordinary walk produces a program whose references are already resolved.

ATTRIBUTE DESCRIPTION
uses

The tokens resolution decided something about, by start offset.

TYPE: tuple[NameUse, ...]

line_offset

Added to every line the walkers record, so the lines of the modules of one flat program do not overlap.

TYPE: int

ParseError

Bases: Exception

Raised when .qvr source fails to parse or wrap into AST nodes.

parse and parse_file raise it with a message that starts with the file path and locates the first syntax error.

ParseTree

ParseTree(schema, source: bytes)

Indexed view of a parsed panproto schema.

The walkers read a file's concrete syntax through it: its vertices, fields, and source text, the latter through the name view name resolution sets (set_view).

Source code in src/quivers/dsl/parser/_registry.py
def __init__(self, schema, source: bytes) -> None:
    self.schema = schema
    self.source = source
    self.vertices = {v.id: v for v in schema.vertices}
    self.children: dict[str, list] = {}
    for e in schema.edges:
        self.children.setdefault(e.src, []).append(e)
    self._consts: dict[str, dict[str, str]] = {}
    self._uses: dict[tuple[int, int], NameUse] = {}
    self._use_starts: list[int] = []
    self._use_list: list[NameUse] = []
    self.line_offset = 0
    self._parents: dict[str, str] | None = None

set_view

set_view(view: NameView) -> None

Read every later walk through view.

PARAMETER DESCRIPTION
view

The resolved names and the line offset.

TYPE: NameView

Source code in src/quivers/dsl/parser/_registry.py
def set_view(self, view: NameView) -> None:
    """Read every later walk through ``view``.

    Parameters
    ----------
    view : NameView
        The resolved names and the line offset.
    """
    ordered = sorted(view.uses, key=lambda use: use.start)
    self._uses = {(use.start, use.end): use for use in ordered}
    self._use_list = ordered
    self._use_starts = [use.start for use in ordered]
    self.line_offset = view.line_offset

name_use

name_use(vid: str) -> NameUse | None

The resolution of the name token spanning vid, if any.

PARAMETER DESCRIPTION
vid

A vertex whose span is exactly one name token.

TYPE: str

RETURNS DESCRIPTION
NameUse | None

What resolution decided for the token, or None when it decided nothing (the token reads as written).

Source code in src/quivers/dsl/parser/_registry.py
def name_use(self, vid: str) -> NameUse | None:
    """The resolution of the name token spanning ``vid``, if any.

    Parameters
    ----------
    vid : str
        A vertex whose span is exactly one name token.

    Returns
    -------
    NameUse | None
        What resolution decided for the token, or ``None`` when it
        decided nothing (the token reads as written).
    """
    c = self.consts(vid)
    sb = c.get("start-byte")
    eb = c.get("end-byte")
    if sb is None or eb is None:
        return None
    return self._uses.get((int(sb), int(eb)))

line_col_at

line_col_at(byte: int) -> tuple[int, int]

1-based line and 0-based column of a byte offset in the source.

Source code in src/quivers/dsl/parser/_registry.py
def line_col_at(self, byte: int) -> tuple[int, int]:
    """1-based line and 0-based column of a byte offset in the source."""
    prefix = self.source[:byte]
    line = prefix.count(b"\n") + 1 + self.line_offset
    last_nl = prefix.rfind(b"\n")
    col = (byte - last_nl - 1) if last_nl >= 0 else byte
    return line, col

Declared didactic-model

Declared(*, name: str, kind: str, statement: int, exported: bool = False, start: int = 0, end: int = 0, line: int = 0, column: int = 0, docs: tuple[str, ...] = (), region: str = '')

Bases: Model

A module-level name and one declaration of it.

ATTRIBUTE DESCRIPTION
name

The declared name.

TYPE: str

kind

The declaration kind (define, family, constructor...).

TYPE: str

statement

The index of the declaring top-level statement.

TYPE: int

exported

Whether export precedes the declaration.

TYPE: bool

start, end

The byte span of the declaring token.

TYPE: int

line, column

Its 1-based line and 0-based column.

TYPE: int

docs

The declaration's doc-comment lines.

TYPE: tuple[str, ...]

region

The region node whose body declares it, "" for the file.

TYPE: str

ExportedName didactic-model

ExportedName(*, name: str, statement: int, start: int, end: int, line: int = 0, column: int = 0, is_name: bool = True, region: str = '')

Bases: Model

A name made public by an export NAME statement.

ATTRIBUTE DESCRIPTION
name

The exported name as written.

TYPE: str

statement

The statement index.

TYPE: int

start, end

The byte span of the name.

TYPE: int

line, column

Its location.

TYPE: int

is_name

Whether the export names a declaration; False for an export of a compound expression, which name then spells.

TYPE: bool

FileNames didactic-model

FileNames(*, occurrences: tuple[Occurrence, ...] = (), declarations: tuple[Declared, ...] = (), imports: tuple[ModuleImport, ...] = (), opens: tuple[ModuleOpen, ...] = (), exported_names: tuple[ExportedName, ...] = (), holes: tuple[ModuleHole, ...] = (), links: tuple[ModuleLink, ...] = (), shares: tuple[SiteShare, ...] = (), regions: tuple[Region, ...] = (), nested: tuple[Occurrence, ...] = (), nested_declarations: tuple[Declared, ...] = (), nested_opens: tuple[ModuleOpen, ...] = (), nested_exports: tuple[ExportedName, ...] = (), statement_count: int = 0, first_declaration: int = 0)

Bases: Model

Everything a file says about names, read from its parse tree.

ATTRIBUTE DESCRIPTION
occurrences

Every identifier token, in source order.

TYPE: tuple[Occurrence, ...]

declarations

Every module-level declaration, in source order.

TYPE: tuple[Declared, ...]

imports

The import statements.

TYPE: tuple[ModuleImport, ...]

opens

The open statements.

TYPE: tuple[ModuleOpen, ...]

exported_names

The names of export NAME statements.

TYPE: tuple[ExportedName, ...]

holes

The hole statements.

TYPE: tuple[ModuleHole, ...]

links

The link statements.

TYPE: tuple[ModuleLink, ...]

shares

The share statements.

TYPE: tuple[SiteShare, ...]

regions

Every module, signature, and module-parameterized computation of the file, outermost first; the other fields hold the file's own names, and region gives a region's.

TYPE: tuple[Region, ...]

nested

The occurrences inside regions.

TYPE: tuple[Occurrence, ...]

nested_declarations

The declarations of region bodies.

TYPE: tuple[Declared, ...]

nested_opens

The open statements of region bodies.

TYPE: tuple[ModuleOpen, ...]

nested_exports

The export NAME statements of region bodies.

TYPE: tuple[ExportedName, ...]

statement_count

The number of top-level statements.

TYPE: int

first_declaration

The index of the first statement that is not an import, an open, a hole, or a link (the statement count when there is none).

TYPE: int

region_info

region_info(vid: str) -> Region

The record of one region.

PARAMETER DESCRIPTION
vid

The region node.

TYPE: str

RETURNS DESCRIPTION
Region

Its record.

RAISES DESCRIPTION
KeyError

If the file has no region at vid.

Source code in src/quivers/dsl/parser/scopes.py
def region_info(self, vid: str) -> Region:
    """The record of one region.

    Parameters
    ----------
    vid : str
        The region node.

    Returns
    -------
    Region
        Its record.

    Raises
    ------
    KeyError
        If the file has no region at ``vid``.
    """
    for region in self.regions:
        if region.vid == vid:
            return region
    raise KeyError(vid)

region

region(vid: str) -> FileNames

The names of one region, as a file's names are.

PARAMETER DESCRIPTION
vid

The region node, "" for the file itself.

TYPE: str

RETURNS DESCRIPTION
FileNames

The region's occurrences, declarations, opens, and exports; its regions are the whole file's.

Source code in src/quivers/dsl/parser/scopes.py
def region(self, vid: str) -> FileNames:
    """The names of one region, as a file's names are.

    Parameters
    ----------
    vid : str
        The region node, ``""`` for the file itself.

    Returns
    -------
    FileNames
        The region's occurrences, declarations, opens, and exports;
        its regions are the whole file's.
    """
    if not vid:
        return self
    info = self.region_info(vid)
    return FileNames(
        occurrences=tuple(item for item in self.nested if item.region == vid),
        declarations=tuple(
            item for item in self.nested_declarations if item.region == vid
        ),
        opens=tuple(item for item in self.nested_opens if item.region == vid),
        exported_names=tuple(
            item for item in self.nested_exports if item.region == vid
        ),
        regions=self.regions,
        nested=self.nested,
        nested_declarations=self.nested_declarations,
        nested_opens=self.nested_opens,
        nested_exports=self.nested_exports,
        statement_count=len(info.statements),
    )

children_of

children_of(vid: str) -> tuple[Region, ...]

The regions directly inside a region.

PARAMETER DESCRIPTION
vid

The region node, "" for the file.

TYPE: str

RETURNS DESCRIPTION
tuple[Region, ...]

The regions whose parent it is, in source order.

Source code in src/quivers/dsl/parser/scopes.py
def children_of(self, vid: str) -> tuple[Region, ...]:
    """The regions directly inside a region.

    Parameters
    ----------
    vid : str
        The region node, ``""`` for the file.

    Returns
    -------
    tuple[Region, ...]
        The regions whose parent it is, in source order.
    """
    return tuple(region for region in self.regions if region.parent == vid)

declared_names

declared_names() -> frozenset[str]

The module-level names the file declares.

RETURNS DESCRIPTION
frozenset[str]

Each declared name once.

Source code in src/quivers/dsl/parser/scopes.py
def declared_names(self) -> frozenset[str]:
    """The module-level names the file declares.

    Returns
    -------
    frozenset[str]
        Each declared name once.
    """
    return frozenset(item.name for item in self.declarations)

kinds_of

kinds_of(name: str) -> frozenset[str]

The declaration kinds of a module-level name.

PARAMETER DESCRIPTION
name

A declared name.

TYPE: str

RETURNS DESCRIPTION
frozenset[str]

Every kind the name is declared with (empty when undeclared).

Source code in src/quivers/dsl/parser/scopes.py
def kinds_of(self, name: str) -> frozenset[str]:
    """The declaration kinds of a module-level name.

    Parameters
    ----------
    name : str
        A declared name.

    Returns
    -------
    frozenset[str]
        Every kind the name is declared with (empty when undeclared).
    """
    return frozenset(item.kind for item in self.declarations if item.name == name)

ImportedName didactic-model

ImportedName(*, name: str, start: int, end: int, line: int = 0, column: int = 0)

Bases: Model

One name in an import or open list.

ATTRIBUTE DESCRIPTION
name

The name as written.

TYPE: str

start, end

Its byte span.

TYPE: int

line, column

Its location.

TYPE: int

ModuleHole didactic-model

ModuleHole(*, path: str, signature: str, statement: int = 0, path_start: int = 0, path_end: int = 0, signature_start: int = 0, signature_end: int = 0, line: int = 0, column: int = 0)

Bases: Model

A hole statement.

ATTRIBUTE DESCRIPTION
path

The dotted module path the hole occupies.

TYPE: str

signature

The signature reference as written.

TYPE: str

statement

The statement index.

TYPE: int

path_start, path_end

The byte span of the path token.

TYPE: int

signature_start, signature_end

The byte span of the signature token.

TYPE: int

line, column

The location of the path token.

TYPE: int

ModuleImport didactic-model

ModuleImport(*, path: str, alias: str | None = None, items: tuple[ImportedName, ...] | None = None, hidden: tuple[ImportedName, ...] = (), reexport: bool = False, meta: bool = False, statement: int = 0, path_start: int = 0, path_end: int = 0, alias_start: int = 0, alias_end: int = 0, line: int = 0, column: int = 0)

Bases: Model

An import statement.

ATTRIBUTE DESCRIPTION
path

The dotted module path.

TYPE: str

alias

The as name, when given.

TYPE: str | None

items

The selected names, or None when there is no selection list.

TYPE: tuple[ImportedName, ...] | None

hidden

The names after hiding.

TYPE: tuple[ImportedName, ...]

reexport

Whether export precedes the import.

TYPE: bool

meta

Whether meta precedes the import, which makes the module available to the importing module's meta phase only.

TYPE: bool

statement

The statement index.

TYPE: int

path_start, path_end

The byte span of the path token.

TYPE: int

alias_start, alias_end

The byte span of the alias token (0 when absent).

TYPE: int

line, column

The location of the path token.

TYPE: int

ModuleLink(*, hole: str, module: str, statement: int = 0, hole_start: int = 0, hole_end: int = 0, module_start: int = 0, module_end: int = 0, line: int = 0, column: int = 0)

Bases: Model

A link statement.

ATTRIBUTE DESCRIPTION
hole

The dotted path of the hole it fills.

TYPE: str

module

The dotted path of the filling module.

TYPE: str

statement

The statement index.

TYPE: int

hole_start, hole_end

The byte span of the hole token.

TYPE: int

module_start, module_end

The byte span of the module token.

TYPE: int

line, column

The location of the hole token.

TYPE: int

ModuleOpen didactic-model

ModuleOpen(*, module: str, items: tuple[ImportedName, ...] | None = None, hidden: tuple[ImportedName, ...] = (), statement: int = 0, start: int = 0, end: int = 0, line: int = 0, column: int = 0, region: str = '')

Bases: Model

An open statement.

ATTRIBUTE DESCRIPTION
module

The opened alias or module path.

TYPE: str

items

The selected names, or None when there is no selection list.

TYPE: tuple[ImportedName, ...] | None

hidden

The names after hiding.

TYPE: tuple[ImportedName, ...]

statement

The statement index.

TYPE: int

start, end

The byte span of the module token.

TYPE: int

line, column

Its location.

TYPE: int

Occurrence didactic-model

Occurrence(*, start: int, end: int, text: str, role: Role, parent_kind: str, field: str, statement: int, local: bool = False, position: Position = 'other', declaration_kind: str = '', line: int = 0, column: int = 0, region: str = '', pun: bool = False)

Bases: Model

One identifier token and what its position makes it.

ATTRIBUTE DESCRIPTION
start, end

The token's byte span.

TYPE: int

text

The token as written, possibly a dotted path.

TYPE: str

role

What the token is.

TYPE: Role

parent_kind, field

The grammar position: the parent's node kind and the field (or <child> for an unnamed child).

TYPE: str

statement

The index of the enclosing top-level statement.

TYPE: int

local

Whether a local binder in scope binds the first segment.

TYPE: bool

position

How trailing segments of a dotted reference are read.

TYPE: Position

declaration_kind

For a declaration, its kind.

TYPE: str

line, column

The token's 1-based line and 0-based column.

TYPE: int

region

The region node the token belongs to (a module or signature body, or a computation with module parameters), "" for the file.

TYPE: str

pun

Whether the token is a pun [W] of a step's bindings: a reference whose spelling is also the label it binds.

TYPE: bool

segments property

segments: tuple[str, ...]

The dotted segments of the token.

RETURNS DESCRIPTION
tuple[str, ...]

The segments, outermost first.

SiteShare didactic-model

SiteShare(*, site: str, target: str, statement: int = 0, site_start: int = 0, site_end: int = 0, target_start: int = 0, target_end: int = 0, line: int = 0, column: int = 0)

Bases: Model

A share statement.

ATTRIBUTE DESCRIPTION
site, target

The two paths as written.

TYPE: str

statement

The statement index.

TYPE: int

site_start, site_end, target_start, target_end

The byte spans of the two path tokens.

TYPE: int

line, column

The location of the statement's first path.

TYPE: int

Region didactic-model

Region(*, vid: str, kind: Literal['module', 'signature', 'template'], name: str, parent: str = '', statements: tuple[str, ...] = (), parameters: tuple[RegionParameter, ...] = (), implicit: bool = False, exported: bool = False, statement: int = 0, start: int = 0, end: int = 0, line: int = 0, column: int = 0)

Bases: Model

A node that opens a scope of module-level names of its own.

A module body, a signature body, and a computation with module parameters each declare names, bind module parameters, or both, and resolve every other name in the scope around them.

ATTRIBUTE DESCRIPTION
vid

The region node.

TYPE: str

kind

A module (structure or functor), a signature, or a computation with module parameters.

TYPE: Literal['module', 'signature', 'template']

name

The declared name.

TYPE: str

parent

The enclosing region node, "" for the file.

TYPE: str

statements

The statements of its body, in order (the computation itself for a template).

TYPE: tuple[str, ...]

parameters

Its module parameters, in order.

TYPE: tuple[RegionParameter, ...]

implicit

Whether implicit precedes the module.

TYPE: bool

exported

Whether export precedes it.

TYPE: bool

statement

The index of the declaring statement in the parent region.

TYPE: int

start, end

The byte span of the name.

TYPE: int

line, column

The location of the name.

TYPE: int

RegionParameter didactic-model

RegionParameter(*, name: str, vid: str, signature: str, implicit: bool = False, start: int = 0, end: int = 0, line: int = 0, column: int = 0)

Bases: Model

A module parameter of a region: a functor's, or a computation's.

ATTRIBUTE DESCRIPTION
name

The parameter's name.

TYPE: str

vid

The parameter node.

TYPE: str

signature

Its signature_expr node.

TYPE: str

implicit

Whether calls leave the argument to instance resolution.

TYPE: bool

start, end

The byte span of the name.

TYPE: int

line, column

Its location.

TYPE: int

LexicalBody didactic-model

LexicalBody(*, atoms: tuple[str, ...] = (), features: tuple[AtomFeatures, ...] = (), category_sets: tuple[CategorySetDecl, ...] = (), semantics: SemanticsDecl | None = None, templates: tuple[LexicalTemplate, ...] = (), lexical_rules: tuple[LexicalRuleDecl, ...] = (), refines: str = '')

Bases: Model

The lexical parts of one deduction body.

PARAMETER DESCRIPTION
atoms

Every declared atom, a featured one by its name.

TYPE: tuple[str, ...] DEFAULT: ()

features

The atoms declared with features.

TYPE: tuple[AtomFeatures, ...] DEFAULT: ()

category_sets

The categories lines.

TYPE: tuple[CategorySetDecl, ...] DEFAULT: ()

semantics

The semantics block, if any.

TYPE: SemanticsDecl | None DEFAULT: None

templates

The template lines.

TYPE: tuple[LexicalTemplate, ...] DEFAULT: ()

lexical_rules

The lexical rule lines.

TYPE: tuple[LexicalRuleDecl, ...] DEFAULT: ()

refines

The deduction a refines line names, or empty.

TYPE: str DEFAULT: ''

DeductionBody didactic-model

DeductionBody(*, atoms: tuple[str, ...] = (), binders: tuple[str, ...] = (), rules: tuple[SequentRule, ...] = (), lexicon: tuple[LexiconEntry, ...] = (), lexicon_from_file: str | None = None, lexicon_from_file_options: tuple[OptionEntry, ...] = (), extends: tuple[DeductionExtension, ...] = (), lexicons: tuple[LexiconReference, ...] = (), instantiations: tuple[RuleInstantiation, ...] = (), lexicon_line: int = 0, lexicon_col: int = 0)

Bases: Model

The parts of one deduction or deduction-signature body.

PARAMETER DESCRIPTION
atoms

The declared atoms.

TYPE: tuple[str, ...] DEFAULT: ()

binders

The declared binder constructors.

TYPE: tuple[str, ...] DEFAULT: ()

rules

The rules and rule schemata.

TYPE: tuple[SequentRule, ...] DEFAULT: ()

lexicon

The entries of inline lexicon blocks.

TYPE: tuple[LexiconEntry, ...] DEFAULT: ()

lexicon_from_file

The path of a lexicon from line, if any.

TYPE: str | None DEFAULT: None

lexicon_from_file_options

That line's options.

TYPE: tuple[OptionEntry, ...] DEFAULT: ()

extends

The extends entries.

TYPE: tuple[DeductionExtension, ...] DEFAULT: ()

lexicons

The lexicon modules named on lexicon lines.

TYPE: tuple[LexiconReference, ...] DEFAULT: ()

instantiations

The rules entries.

TYPE: tuple[RuleInstantiation, ...] DEFAULT: ()

lexicon_line

Where the first inline lexicon block or lexicon from line starts (line 0 when there is none), for refusing one in a signature.

TYPE: int DEFAULT: 0

lexicon_col

Where the first inline lexicon block or lexicon from line starts (line 0 when there is none), for refusing one in a signature.

TYPE: int DEFAULT: 0

file_names

file_names(tree: _Tree, file_path: str = '<source>', *, constructors: frozenset[str] | None = None) -> FileNames

Collect the name occurrences of a parsed file.

PARAMETER DESCRIPTION
tree

The parsed tree.

TYPE: _Tree

file_path

The path recorded on diagnostics.

TYPE: str DEFAULT: '<source>'

constructors

The constructor names in unqualified scope; the file's own when omitted.

TYPE: frozenset[str] | None DEFAULT: None

RETURNS DESCRIPTION
FileNames

The occurrences, declarations, imports, opens, and exports.

RAISES DESCRIPTION
ParseError

If a declaration or binder is qualified, an import alias is qualified, or an import or open follows a declaration.

Source code in src/quivers/dsl/parser/core.py
def file_names(
    tree: _Tree,
    file_path: str = "<source>",
    *,
    constructors: frozenset[str] | None = None,
) -> FileNames:
    """Collect the name occurrences of a parsed file.

    Parameters
    ----------
    tree : _Tree
        The parsed tree.
    file_path : str
        The path recorded on diagnostics.
    constructors : frozenset[str] | None
        The constructor names in unqualified scope; the file's own when
        omitted.

    Returns
    -------
    FileNames
        The occurrences, declarations, imports, opens, and exports.

    Raises
    ------
    ParseError
        If a declaration or binder is qualified, an import alias is
        qualified, or an import or open follows a declaration.
    """
    try:
        names = analyze_names(tree, constructors=constructors)
    except ParseError as error:
        raise ParseError(f"{file_path}: {error}") from error
    statements = top_level_statements(tree)
    for index, vid in enumerate(statements):
        if index < names.first_declaration:
            continue
        kind = tree.kind(vid)
        if kind == "exported_decl":
            inner = tree.field(vid, "declaration")
            kind = tree.kind(inner) if inner is not None else kind
        if kind in ("import_decl", "open_decl"):
            line, col = tree.line_col(vid)
            word = "import" if kind == "import_decl" else "open"
            raise ParseError(
                f"{file_path}: `{word}` at line {line}, col {col} follows a "
                "declaration; a module's imports and opens come before its "
                "declarations"
            )
    return names

parse

parse(source: str | bytes, file_path: str = '<source>') -> Module

Parse .qvr source into a Module.

PARAMETER DESCRIPTION
source

The source text, or its UTF-8 bytes.

TYPE: str | bytes

file_path

The path recorded on diagnostics.

TYPE: str DEFAULT: '<source>'

RETURNS DESCRIPTION
Module

The module's statements in source order.

RAISES DESCRIPTION
ParseError

If the source has a syntax error or a node the AST cannot represent.

Source code in src/quivers/dsl/parser/core.py
def parse(source: str | bytes, file_path: str = "<source>") -> Module:
    """Parse `.qvr` source into a `Module`.

    Parameters
    ----------
    source : str | bytes
        The source text, or its UTF-8 bytes.
    file_path : str
        The path recorded on diagnostics.

    Returns
    -------
    Module
        The module's statements in source order.

    Raises
    ------
    ParseError
        If the source has a syntax error or a node the AST cannot
        represent.
    """
    tree = parse_tree(source, file_path)
    names = file_names(tree, file_path)
    tree.set_view(local_name_view(names))
    return walk_tree(tree, names, file_path)

parse_file

parse_file(path: str | Path) -> Module

Parse a .qvr file at path.

PARAMETER DESCRIPTION
path

The file to read.

TYPE: str | Path

RETURNS DESCRIPTION
Module

The file's statements in source order.

RAISES DESCRIPTION
OSError

If the file cannot be read.

ParseError

If the file does not parse.

Source code in src/quivers/dsl/parser/core.py
def parse_file(path: str | Path) -> Module:
    """Parse a `.qvr` file at `path`.

    Parameters
    ----------
    path : str | Path
        The file to read.

    Returns
    -------
    Module
        The file's statements in source order.

    Raises
    ------
    OSError
        If the file cannot be read.
    ParseError
        If the file does not parse.
    """
    p = Path(path)
    return parse(p.read_bytes(), str(p))

parse_tree

parse_tree(source: str | bytes, file_path: str = '<source>') -> _Tree

Parse .qvr source into its validated concrete syntax tree.

PARAMETER DESCRIPTION
source

The source text, or its UTF-8 bytes.

TYPE: str | bytes

file_path

The path recorded on diagnostics.

TYPE: str DEFAULT: '<source>'

RETURNS DESCRIPTION
_Tree

The tree, free of syntax damage and of reserved binder names.

RAISES DESCRIPTION
ParseError

If the source has a syntax error.

Source code in src/quivers/dsl/parser/core.py
def parse_tree(source: str | bytes, file_path: str = "<source>") -> _Tree:
    """Parse `.qvr` source into its validated concrete syntax tree.

    Parameters
    ----------
    source : str | bytes
        The source text, or its UTF-8 bytes.
    file_path : str
        The path recorded on diagnostics.

    Returns
    -------
    _Tree
        The tree, free of syntax damage and of reserved binder names.

    Raises
    ------
    ParseError
        If the source has a syntax error.
    """
    if isinstance(source, str):
        source_bytes = source.encode("utf-8")
    else:
        source_bytes = source

    try:
        schema = _registry().parse_with_protocol("qvr", source_bytes, file_path)
    except panproto.PanprotoError as exc:
        raise ParseError(f"{file_path}: panproto failed to parse: {exc}") from exc
    tree = _Tree(schema, source_bytes)

    # A reserved binder name breaks every later reference to it, so it is
    # reported where it is bound, ahead of the syntax damage it causes.
    _reject_reserved_binders(tree, file_path)
    _reject_malformed(tree, file_path)

    if not any(tree.kind(vid) == "source_file" for vid in tree.vertices):
        raise ParseError(
            f"{file_path}: source failed to parse (the tree has no source_file "
            "root); check that every program body ends with a return step"
        )
    return tree

walk_tree

walk_tree(tree: _Tree, names: FileNames, file_path: str = '<source>') -> Module

Walk a parsed tree into a Module, reading names through its view.

PARAMETER DESCRIPTION
tree

The parsed tree, with the name view to read it through.

TYPE: _Tree

names

The file's name occurrences, from file_names.

TYPE: FileNames

file_path

The path recorded on diagnostics.

TYPE: str DEFAULT: '<source>'

RETURNS DESCRIPTION
Module

The module's statements in source order. export before a declaration contributes the declaration and an ExportDecl for each name it declares.

RAISES DESCRIPTION
ParseError

If a node does not walk, or export precedes something that declares no name.

Source code in src/quivers/dsl/parser/core.py
def walk_tree(tree: _Tree, names: FileNames, file_path: str = "<source>") -> Module:
    """Walk a parsed tree into a `Module`, reading names through its view.

    Parameters
    ----------
    tree : _Tree
        The parsed tree, with the name view to read it through.
    names : FileNames
        The file's name occurrences, from `file_names`.
    file_path : str
        The path recorded on diagnostics.

    Returns
    -------
    Module
        The module's statements in source order. ``export`` before a
        declaration contributes the declaration and an `ExportDecl` for
        each name it declares.

    Raises
    ------
    ParseError
        If a node does not walk, or ``export`` precedes something that
        declares no name.
    """
    return walk_statements(
        tree, names, tuple(enumerate(top_level_statements(tree))), file_path
    )

walk_statements

walk_statements(tree: _Tree, names: FileNames, statements: tuple[tuple[int, str], ...], file_path: str = '<source>') -> Module

Walk some statements of a module or region, reading names through the view.

PARAMETER DESCRIPTION
tree

The parsed tree, with the name view to read it through.

TYPE: _Tree

names

The names of the module or region the statements belong to.

TYPE: FileNames

statements

Each statement vertex with its index in the module or region.

TYPE: tuple[tuple[int, str], ...]

file_path

The path recorded on diagnostics.

TYPE: str DEFAULT: '<source>'

RETURNS DESCRIPTION
Module

The statements in order, and the tests and experiments among them.

RAISES DESCRIPTION
ParseError

If a node does not walk, or export precedes something that declares no name.

Source code in src/quivers/dsl/parser/core.py
def walk_statements(
    tree: _Tree,
    names: FileNames,
    statements: tuple[tuple[int, str], ...],
    file_path: str = "<source>",
) -> Module:
    """Walk some statements of a module or region, reading names through the view.

    Parameters
    ----------
    tree : _Tree
        The parsed tree, with the name view to read it through.
    names : FileNames
        The names of the module or region the statements belong to.
    statements : tuple[tuple[int, str], ...]
        Each statement vertex with its index in the module or region.
    file_path : str
        The path recorded on diagnostics.

    Returns
    -------
    Module
        The statements in order, and the tests and experiments among them.

    Raises
    ------
    ParseError
        If a node does not walk, or ``export`` precedes something that
        declares no name.
    """
    statements_out: list[Statement] = []
    tests: list[TestDecl] = []
    experiments: list[ExperimentDecl] = []
    for index, child in statements:
        ckind = tree.kind(child)
        if ckind in TEST_KINDS:
            tests.append(walk_test_decl(tree, child))
            continue
        if ckind == EXPERIMENT_KIND:
            experiments.append(walk_experiment_decl(tree, child))
            continue
        # An exported declaration's doc comment rides the `export` wrapper;
        # the examples it carries document the declaration inside.
        documented = (
            tree.field(child, "declaration") if ckind == "exported_decl" else child
        )
        name = tree.field(documented, "name") if documented is not None else None
        if documented is not None and name is not None:
            tests.extend(
                doc_examples(
                    tree,
                    documented,
                    tree.text(name),
                    lambda example, line: _parse_doc_example(example, line, file_path),
                )
            )
        statements_out.extend(_walk_top_level(tree, child, names, index, file_path))
    return Module(
        statements=tuple(statements_out),
        tests=tuple(tests),
        experiments=tuple(experiments),
    )

local_name_view

local_name_view(names: FileNames) -> NameView

The name view of a file read without its imports.

PARAMETER DESCRIPTION
names

The file's name occurrences.

TYPE: FileNames

RETURNS DESCRIPTION
NameView

A view that marks the member accesses decidable from the file alone and renames nothing.

Source code in src/quivers/dsl/parser/names.py
def local_name_view(names: FileNames) -> NameView:
    """The name view of a file read without its imports.

    Parameters
    ----------
    names : FileNames
        The file's name occurrences.

    Returns
    -------
    NameView
        A view that marks the member accesses decidable from the file
        alone and renames nothing.
    """
    uses: list[NameUse] = []
    for occurrence in names.occurrences:
        members = _member_count(occurrence, names)
        if members:
            segments = occurrence.segments
            uses.append(
                NameUse(
                    start=occurrence.start,
                    end=occurrence.end,
                    reference=".".join(segments[: len(segments) - members]),
                    members=members,
                )
            )
    return NameView(uses=tuple(uses))

split_member_path

split_member_path(tree: _Tree, vid: str) -> tuple[str, tuple[str, ...]]

Split a name token into its reference and its member accesses.

PARAMETER DESCRIPTION
tree

The parsed tree, with its name view.

TYPE: _Tree

vid

A vertex spanning exactly one name token.

TYPE: str

RETURNS DESCRIPTION
tuple[str, tuple[str, ...]]

The reference, as resolution reads it, and the member segments that follow it, outermost first (empty when the whole token is a reference).

Source code in src/quivers/dsl/parser/names.py
def split_member_path(tree: _Tree, vid: str) -> tuple[str, tuple[str, ...]]:
    """Split a name token into its reference and its member accesses.

    Parameters
    ----------
    tree : _Tree
        The parsed tree, with its name view.
    vid : str
        A vertex spanning exactly one name token.

    Returns
    -------
    tuple[str, tuple[str, ...]]
        The reference, as resolution reads it, and the member segments
        that follow it, outermost first (empty when the whole token is a
        reference).
    """
    use = tree.name_use(vid)
    if use is None:
        return tree.text(vid), ()
    consts = tree.consts(vid)
    original = tree.source[int(consts["start-byte"]) : int(consts["end-byte"])].decode(
        "utf-8"
    )
    segments = original.split(".")
    members = tuple(segments[len(segments) - use.members :]) if use.members else ()
    return use.reference, members

split_request_target

split_request_target(tree: _Tree, vid: str) -> tuple[str, str]

Split a perform target into its instance and its operation.

PARAMETER DESCRIPTION
tree

The parsed tree, with its name view.

TYPE: _Tree

vid

The target token of an effect request.

TYPE: str

RETURNS DESCRIPTION
tuple[str, str]

The instance, as resolution reads it, and the operation, the last segment.

RAISES DESCRIPTION
ValueError

If the target has a single segment, so names no operation.

Source code in src/quivers/dsl/parser/names.py
def split_request_target(tree: _Tree, vid: str) -> tuple[str, str]:
    """Split a ``perform`` target into its instance and its operation.

    Parameters
    ----------
    tree : _Tree
        The parsed tree, with its name view.
    vid : str
        The target token of an effect request.

    Returns
    -------
    tuple[str, str]
        The instance, as resolution reads it, and the operation, the last
        segment.

    Raises
    ------
    ValueError
        If the target has a single segment, so names no operation.
    """
    text = tree.text(vid)
    instance, separator, operation = text.rpartition(".")
    if not separator or not instance:
        raise ValueError(
            f"`perform {text}` names no operation; write `perform instance.operation(...)`"
        )
    return instance, operation

value_members

value_members(position: str, kinds: Iterable[str], remainder: tuple[str, ...]) -> int

How many of the segments after a declaration's name select members of its value.

PARAMETER DESCRIPTION
position

The reference position of the dotted path.

TYPE: str

kinds

The declaration kinds of the name the path starts with.

TYPE: Iterable[str]

remainder

The segments after that name.

TYPE: tuple[str, ...]

RETURNS DESCRIPTION
int

Every segment of remainder in a morphism expression when the declaration is morphism-valued (VALUE_DECLARATION_KINDS); one when remainder is a single method of the interface every kind of the declaration has (VALUE_METHODS); zero otherwise, so the segments name a generated member.

Source code in src/quivers/dsl/parser/names.py
def value_members(
    position: str, kinds: Iterable[str], remainder: tuple[str, ...]
) -> int:
    """How many of the segments after a declaration's name select members of its value.

    Parameters
    ----------
    position : str
        The reference position of the dotted path.
    kinds : Iterable[str]
        The declaration kinds of the name the path starts with.
    remainder : tuple[str, ...]
        The segments after that name.

    Returns
    -------
    int
        Every segment of ``remainder`` in a morphism expression when the
        declaration is morphism-valued (`VALUE_DECLARATION_KINDS`); one when
        ``remainder`` is a single method of the interface every kind of the
        declaration has (`VALUE_METHODS`); zero otherwise, so the segments
        name a generated member.
    """
    found = frozenset(kinds)
    if not remainder or not found or position not in ("morphism", "value"):
        return 0
    if position == "morphism" and found <= VALUE_DECLARATION_KINDS:
        return len(remainder)
    if len(remainder) == 1 and all(
        remainder[0] in VALUE_METHODS.get(kind, frozenset()) for kind in found
    ):
        return 1
    return 0

analyze_names

analyze_names(tree: _Tree, *, constructors: frozenset[str] | None = None) -> FileNames

Collect every name occurrence of a parsed file.

PARAMETER DESCRIPTION
tree

The parsed tree.

TYPE: _Tree

constructors

The constructor names in unqualified scope, which a bare name in a pattern refers to instead of binding. Defaults to the file's own.

TYPE: frozenset[str] | None DEFAULT: None

RETURNS DESCRIPTION
FileNames

The occurrences, declarations, imports, opens, and exported names.

RAISES DESCRIPTION
ParseError

If a declaration or binder is spelled as a qualified path, an import alias is qualified, or an open is exported.

Source code in src/quivers/dsl/parser/scopes.py
def analyze_names(
    tree: _Tree, *, constructors: frozenset[str] | None = None
) -> FileNames:
    """Collect every name occurrence of a parsed file.

    Parameters
    ----------
    tree : _Tree
        The parsed tree.
    constructors : frozenset[str] | None
        The constructor names in unqualified scope, which a bare name in a
        pattern refers to instead of binding. Defaults to the file's own.

    Returns
    -------
    FileNames
        The occurrences, declarations, imports, opens, and exported names.

    Raises
    ------
    ParseError
        If a declaration or binder is spelled as a qualified path, an
        import alias is qualified, or an ``open`` is exported.
    """
    walk = _Walk(
        tree,
        declared_constructors(tree) if constructors is None else constructors,
    )
    statements = top_level_statements(tree)
    first_declaration = len(statements)
    for index, vid in enumerate(statements):
        walk.statement = index
        kind = tree.kind(vid)
        inner_kind = kind
        if kind == "exported_decl":
            inner = tree.field(vid, "declaration")
            inner_kind = tree.kind(inner) if inner is not None else kind
        if inner_kind not in _PREAMBLE_KINDS and first_declaration == len(statements):
            first_declaration = index
        walk.statement_node(vid, exported=False)
    occurrences = sorted(walk.occurrences, key=lambda item: item.start)
    nested_declarations: list[Declared] = []
    for region in walk.regions:
        nested_declarations.extend(
            _attach_docs(
                tree,
                list(region.statements),
                [item for item in walk.declarations if item.region == region.vid],
            )
        )
    return FileNames(
        occurrences=tuple(item for item in occurrences if not item.region),
        declarations=_attach_docs(
            tree,
            statements,
            [item for item in walk.declarations if not item.region],
        ),
        imports=tuple(walk.imports),
        opens=tuple(item for item in walk.opens if not item.region),
        exported_names=tuple(item for item in walk.exported_names if not item.region),
        regions=tuple(walk.regions),
        nested=tuple(item for item in occurrences if item.region),
        nested_declarations=tuple(
            sorted(nested_declarations, key=lambda item: item.start)
        ),
        nested_opens=tuple(item for item in walk.opens if item.region),
        nested_exports=tuple(item for item in walk.exported_names if item.region),
        holes=tuple(walk.holes),
        links=tuple(walk.links),
        shares=tuple(walk.shares),
        statement_count=len(statements),
        first_declaration=first_declaration,
    )

declared_constructors

declared_constructors(tree: _Tree) -> frozenset[str]

The constructor names a file declares at module level.

PARAMETER DESCRIPTION
tree

The parsed tree.

TYPE: _Tree

RETURNS DESCRIPTION
frozenset[str]

The names of every family, index, and signature constructor.

Source code in src/quivers/dsl/parser/scopes.py
def declared_constructors(tree: _Tree) -> frozenset[str]:
    """The constructor names a file declares at module level.

    Parameters
    ----------
    tree : _Tree
        The parsed tree.

    Returns
    -------
    frozenset[str]
        The names of every family, index, and signature constructor.
    """
    walk = _Walk(tree, frozenset())
    names: set[str] = set()
    for vid in tree.vertices:
        if tree.kind(vid) != "identifier":
            continue
        kind, field = walk.position_of(vid)
        if DECLARATION_POSITIONS.get((kind, field)) == "constructor":
            names.add(tree.text(vid))
    return frozenset(names)

top_level_statements

top_level_statements(tree: _Tree) -> list[str]

The top-level statement vertices of a tree, in source order.

PARAMETER DESCRIPTION
tree

The parsed tree.

TYPE: _Tree

RETURNS DESCRIPTION
list[str]

The vertex ids, comments excluded.

RAISES DESCRIPTION
ParseError

If the tree has no source_file root.

Source code in src/quivers/dsl/parser/scopes.py
def top_level_statements(tree: _Tree) -> list[str]:
    """The top-level statement vertices of a tree, in source order.

    Parameters
    ----------
    tree : _Tree
        The parsed tree.

    Returns
    -------
    list[str]
        The vertex ids, comments excluded.

    Raises
    ------
    ParseError
        If the tree has no ``source_file`` root.
    """
    root = next(
        (vid for vid in tree.vertices if tree.kind(vid) == "source_file"),
        None,
    )
    if root is None:
        raise ParseError("the tree has no source_file root")
    return [
        child
        for child in tree.positional(root)
        if tree.kind(child) not in _COMMENT_KINDS
    ]

walk_hole

walk_hole(tree: _Tree, vid: str) -> HoleDecl

Walk a hole P : S statement.

PARAMETER DESCRIPTION
tree

The parse tree.

TYPE: _Tree

vid

The hole_decl vertex.

TYPE: str

RETURNS DESCRIPTION
HoleDecl

The statement.

RAISES DESCRIPTION
ParseError

If the statement lacks its path or signature.

Source code in src/quivers/dsl/parser/linking.py
def walk_hole(tree: _Tree, vid: str) -> HoleDecl:
    """Walk a ``hole P : S`` statement.

    Parameters
    ----------
    tree : _Tree
        The parse tree.
    vid : str
        The ``hole_decl`` vertex.

    Returns
    -------
    HoleDecl
        The statement.

    Raises
    ------
    ParseError
        If the statement lacks its path or signature.
    """
    line, col = tree.line_col(vid)
    return HoleDecl(
        path=_raw(tree, _required(tree, vid, "path")),
        signature=tree.text(_required(tree, vid, "signature")),
        docs=_docs(tree, vid),
        line=line,
        col=col,
    )
walk_link(tree: _Tree, vid: str) -> LinkDecl

Walk a link P = M statement.

PARAMETER DESCRIPTION
tree

The parse tree.

TYPE: _Tree

vid

The link_decl vertex.

TYPE: str

RETURNS DESCRIPTION
LinkDecl

The statement.

RAISES DESCRIPTION
ParseError

If the statement lacks its hole or module.

Source code in src/quivers/dsl/parser/linking.py
def walk_link(tree: _Tree, vid: str) -> LinkDecl:
    """Walk a ``link P = M`` statement.

    Parameters
    ----------
    tree : _Tree
        The parse tree.
    vid : str
        The ``link_decl`` vertex.

    Returns
    -------
    LinkDecl
        The statement.

    Raises
    ------
    ParseError
        If the statement lacks its hole or module.
    """
    line, col = tree.line_col(vid)
    return LinkDecl(
        hole=_raw(tree, _required(tree, vid, "hole")),
        module=_raw(tree, _required(tree, vid, "module")),
        docs=_docs(tree, vid),
        line=line,
        col=col,
    )

walk_share

walk_share(tree: _Tree, vid: str) -> ShareDecl

Walk a share x with y statement.

PARAMETER DESCRIPTION
tree

The parse tree.

TYPE: _Tree

vid

The share_decl vertex.

TYPE: str

RETURNS DESCRIPTION
ShareDecl

The statement, its two paths resolved through the name view.

RAISES DESCRIPTION
ParseError

If the statement lacks either path.

Source code in src/quivers/dsl/parser/linking.py
def walk_share(tree: _Tree, vid: str) -> ShareDecl:
    """Walk a ``share x with y`` statement.

    Parameters
    ----------
    tree : _Tree
        The parse tree.
    vid : str
        The ``share_decl`` vertex.

    Returns
    -------
    ShareDecl
        The statement, its two paths resolved through the name view.

    Raises
    ------
    ParseError
        If the statement lacks either path.
    """
    line, col = tree.line_col(vid)
    return ShareDecl(
        site=tree.text(_required(tree, vid, "site")),
        target=tree.text(_required(tree, vid, "target")),
        docs=_docs(tree, vid),
        line=line,
        col=col,
    )

walk_module_expr

walk_module_expr(t: _Tree, vid: str) -> ModuleExpr

Walk a module expression.

PARAMETER DESCRIPTION
t

The tree.

TYPE: _Tree

vid

A module-expression vertex.

TYPE: str

RETURNS DESCRIPTION
ModuleExpr

The expression.

RAISES DESCRIPTION
ParseError

If the vertex is not a module expression.

Source code in src/quivers/dsl/parser/module_language.py
def walk_module_expr(t: _Tree, vid: str) -> ModuleExpr:
    """Walk a module expression.

    Parameters
    ----------
    t : _Tree
        The tree.
    vid : str
        A module-expression vertex.

    Returns
    -------
    ModuleExpr
        The expression.

    Raises
    ------
    ParseError
        If the vertex is not a module expression.
    """
    kind = t.kind(vid)
    line, col = t.line_col(vid)
    if kind == "module_path":
        return ModulePath(name=_field_text(t, vid, "name"), line=line, col=col)
    if kind == "module_application":
        return ModuleApplication(
            functor=_field_text(t, vid, "functor"),
            arguments=tuple(
                walk_module_expr(t, item) for item in t.fields(vid, "arguments")
            ),
            line=line,
            col=col,
        )
    if kind == "module_seal":
        return ModuleSeal(
            module=walk_module_expr(t, _required_field(t, vid, "module")),
            signature=walk_signature_expr(t, _required_field(t, vid, "signature")),
            line=line,
            col=col,
        )
    if kind == "module_paren":
        return walk_module_expr(t, _required_field(t, vid, "module"))
    raise ParseError(f"line {line}, col {col}: {kind!r} is not a module expression")

walk_module_language_statement

walk_module_language_statement(t: _Tree, vid: str, walk_statement: StatementWalker) -> Statement

Walk one module-language statement.

PARAMETER DESCRIPTION
t

The tree.

TYPE: _Tree

vid

A vertex whose kind is in MODULE_LANGUAGE_KINDS.

TYPE: str

walk_statement

Walks the statements of a body or a signature.

TYPE: StatementWalker

RETURNS DESCRIPTION
Statement

The walked statement.

RAISES DESCRIPTION
ParseError

If the vertex is not a module-language statement.

Source code in src/quivers/dsl/parser/module_language.py
def walk_module_language_statement(
    t: _Tree, vid: str, walk_statement: StatementWalker
) -> Statement:
    """Walk one module-language statement.

    Parameters
    ----------
    t : _Tree
        The tree.
    vid : str
        A vertex whose kind is in `MODULE_LANGUAGE_KINDS`.
    walk_statement : StatementWalker
        Walks the statements of a body or a signature.

    Returns
    -------
    Statement
        The walked statement.

    Raises
    ------
    ParseError
        If the vertex is not a module-language statement.
    """
    kind = t.kind(vid)
    line, col = t.line_col(vid)
    if kind == "signature_decl":
        definition = t.field(vid, "definition")
        return SignatureDecl(
            name=_field_text(t, vid, "name"),
            items=_walk_body(t, t.fields(vid, "items"), walk_statement),
            definition=(
                walk_signature_expr(t, definition) if definition is not None else None
            ),
            equations=tuple(
                equation
                for laws in t.fields(vid, "laws")
                for equation in walk_syntax_equations(t, laws)[0]
            ),
            docs=_docs(t, vid),
            line=line,
            col=col,
        )
    if kind == "module_decl":
        return _walk_module_decl(t, vid, walk_statement)
    if kind == "implicit_decl":
        return ImplicitDecl(
            declaration=_walk_module_decl(
                t, _required_field(t, vid, "declaration"), walk_statement
            ),
            line=line,
            col=col,
        )
    if kind == "family_spec":
        definition = t.field(vid, "definition")
        return QiecFamilySpec(
            name=_field_text(t, vid, "name"),
            parameters=_walk_telescope_field(t, vid, "parameters"),
            indices=_walk_index_telescope_field(t, vid, "indices"),
            result_kind=_walk_kind(t, _required_field(t, vid, "kind")),
            definition=_walk_type(t, definition) if definition is not None else None,
            docs=_docs(t, vid),
            line=line,
            col=col,
        )
    if kind == "computation_spec":
        for item in t.fields(vid, "parameters"):
            if t.kind(item) in _MODULE_PARAMETER_KINDS:
                item_line, item_col = t.line_col(item)
                raise ParseError(
                    f"line {item_line}, col {item_col}: a computation specified in "
                    "a signature takes no module parameter; specify the module "
                    "as an item of the signature instead"
                )
        return QiecComputationSpec(
            name=_field_text(t, vid, "name"),
            binders=_walk_telescope_field(t, vid, "binders"),
            parameters=tuple(
                _walk_value_parameter(t, item) for item in t.fields(vid, "parameters")
            ),
            result_type=_walk_type(t, _required_field(t, vid, "result")),
            effects=_walk_effect_row(t, _required_field(t, vid, "row")),
            docs=_docs(t, vid),
            line=line,
            col=col,
        )
    if kind == "deduction_spec":
        return DeductionSpec(
            name=_field_text(t, vid, "name"),
            domain=_walk_object_type(t, _required_field(t, vid, "domain")),
            codomain=_walk_object_type(t, _required_field(t, vid, "codomain")),
            docs=_docs(t, vid),
            line=line,
            col=col,
        )
    raise ParseError(f"line {line}, col {col}: {kind!r} is not a module-language form")

walk_signature_expr

walk_signature_expr(t: _Tree, vid: str) -> SignatureExpr

Walk a signature reference and its sharing constraints.

PARAMETER DESCRIPTION
t

The tree.

TYPE: _Tree

vid

A signature_expr vertex.

TYPE: str

RETURNS DESCRIPTION
SignatureExpr

The reference, read through the tree's name view.

Source code in src/quivers/dsl/parser/module_language.py
def walk_signature_expr(t: _Tree, vid: str) -> SignatureExpr:
    """Walk a signature reference and its sharing constraints.

    Parameters
    ----------
    t : _Tree
        The tree.
    vid : str
        A ``signature_expr`` vertex.

    Returns
    -------
    SignatureExpr
        The reference, read through the tree's name view.
    """
    line, col = t.line_col(vid)
    return SignatureExpr(
        base=_field_text(t, vid, "base"),
        constraints=tuple(
            SharingConstraint(
                name=_field_text(t, item, "name"),
                type_expr=_walk_type(t, _required_field(t, item, "type")),
                line=t.line_col(item)[0],
                col=t.line_col(item)[1],
            )
            for item in t.fields(vid, "constraints")
        ),
        line=line,
        col=col,
    )

walk_fin_type

walk_fin_type(t: _Tree, vid: str) -> QiecTypeExpr

Walk Fin n.

PARAMETER DESCRIPTION
t

The parse tree.

TYPE: _Tree

vid

A qiec_fin_type vertex.

TYPE: str

RETURNS DESCRIPTION
QiecTypeExpr

The positional index set.

Source code in src/quivers/dsl/parser/axes.py
def walk_fin_type(t: _Tree, vid: str) -> QiecTypeExpr:
    """Walk ``Fin n``.

    Parameters
    ----------
    t : _Tree
        The parse tree.
    vid : str
        A ``qiec_fin_type`` vertex.

    Returns
    -------
    QiecTypeExpr
        The positional index set.
    """
    line, col = t.line_col(vid)
    return QiecFinType(
        extent=_walk_index(t, _required_field(t, vid, "extent")),
        line=line,
        col=col,
    )

walk_reduction

walk_reduction(t: _Tree, vid: str) -> LetExprNode

Walk logsumexp over w : World. e.

PARAMETER DESCRIPTION
t

The parse tree.

TYPE: _Tree

vid

A let_reduction vertex.

TYPE: str

RETURNS DESCRIPTION
LetExprNode

The reduction.

Source code in src/quivers/dsl/parser/axes.py
def walk_reduction(t: _Tree, vid: str) -> LetExprNode:
    """Walk ``logsumexp over w : World. e``.

    Parameters
    ----------
    t : _Tree
        The parse tree.
    vid : str
        A ``let_reduction`` vertex.

    Returns
    -------
    LetExprNode
        The reduction.
    """
    line, col = t.line_col(vid)
    return LetExprReduction(
        operator=_field_text(t, vid, "operator"),
        binders=_walk_binders(t, vid),
        body=_walk_let_arith(t, _required_field(t, vid, "body")),
        line=line,
        col=col,
    )

walk_tabulation

walk_tabulation(t: _Tree, vid: str) -> LetExprNode

Walk for w : World. e.

PARAMETER DESCRIPTION
t

The parse tree.

TYPE: _Tree

vid

A let_tabulation vertex.

TYPE: str

RETURNS DESCRIPTION
LetExprNode

The tabulation.

Source code in src/quivers/dsl/parser/axes.py
def walk_tabulation(t: _Tree, vid: str) -> LetExprNode:
    """Walk ``for w : World. e``.

    Parameters
    ----------
    t : _Tree
        The parse tree.
    vid : str
        A ``let_tabulation`` vertex.

    Returns
    -------
    LetExprNode
        The tabulation.
    """
    line, col = t.line_col(vid)
    return LetExprTabulation(
        binders=_walk_binders(t, vid),
        body=_walk_let_arith(t, _required_field(t, vid, "body")),
        line=line,
        col=col,
    )

walk_tensor_type

walk_tensor_type(t: _Tree, vid: str) -> QiecTypeExpr

Walk (E)[T1, ..., Tk].

PARAMETER DESCRIPTION
t

The parse tree.

TYPE: _Tree

vid

A qiec_tensor_type vertex.

TYPE: str

RETURNS DESCRIPTION
QiecTypeExpr

The tensor type.

RAISES DESCRIPTION
ParseError

If it lists no axis.

Source code in src/quivers/dsl/parser/axes.py
def walk_tensor_type(t: _Tree, vid: str) -> QiecTypeExpr:
    """Walk ``(E)[T1, ..., Tk]``.

    Parameters
    ----------
    t : _Tree
        The parse tree.
    vid : str
        A ``qiec_tensor_type`` vertex.

    Returns
    -------
    QiecTypeExpr
        The tensor type.

    Raises
    ------
    ParseError
        If it lists no axis.
    """
    line, col = t.line_col(vid)
    axes = tuple(_walk_type(t, child) for child in t.fields(vid, "axes"))
    if not axes:
        raise ParseError(f"a tensor type lists no axis at {vid}")
    return QiecTensorType(
        element=_walk_type(t, _required_field(t, vid, "element")),
        axes=axes,
        line=line,
        col=col,
    )

walk_lexical_body

walk_lexical_body(t: _Tree, vid: str, *, pragma: PragmaWalker) -> LexicalBody

Walk the lexical lines of a deduction body.

PARAMETER DESCRIPTION
t

The parse tree.

TYPE: _Tree

vid

The deduction_decl vertex.

TYPE: str

pragma

Walks a lexicon_pragma.

TYPE: PragmaWalker

RETURNS DESCRIPTION
LexicalBody

The parts, in source order.

RAISES DESCRIPTION
ParseError

If a line is malformed, a deduction has two semantics blocks or two refines lines, or a lexical rule has other than one premise.

Source code in src/quivers/dsl/parser/lexical.py
def walk_lexical_body(t: _Tree, vid: str, *, pragma: PragmaWalker) -> LexicalBody:
    """Walk the lexical lines of a deduction body.

    Parameters
    ----------
    t : _Tree
        The parse tree.
    vid : str
        The ``deduction_decl`` vertex.
    pragma : PragmaWalker
        Walks a ``lexicon_pragma``.

    Returns
    -------
    LexicalBody
        The parts, in source order.

    Raises
    ------
    ParseError
        If a line is malformed, a deduction has two ``semantics`` blocks
        or two ``refines`` lines, or a lexical rule has other than one
        premise.
    """
    atoms: list[str] = []
    features: list[AtomFeatures] = []
    sets: list[CategorySetDecl] = []
    semantics: SemanticsDecl | None = None
    templates: list[LexicalTemplate] = []
    lexical_rules: list[LexicalRuleDecl] = []
    refines = ""
    for child in t.positional(vid):
        kind = t.kind(child)
        line, col = t.line_col(child)
        if kind == "deduction_atoms":
            for item in t.fields(child, "atoms"):
                if t.kind(item) == "atom_features":
                    featured = _walk_atom_features(t, item)
                    atoms.append(featured.atom)
                    features.append(featured)
                else:
                    atoms.append(t.text(item))
        elif kind == "deduction_category_set":
            sets.append(
                CategorySetDecl(
                    name=_required_text(t, t.field(child, "name"), child, "name"),
                    members=tuple(
                        _walk_type(t, member) for member in t.fields(child, "members")
                    ),
                    line=line,
                    col=col,
                )
            )
        elif kind == "deduction_semantics":
            if semantics is not None:
                raise ParseError(
                    f"line {line}, col {col}: a deduction has one semantics block"
                )
            semantics = SemanticsDecl(
                judgment=_required_text(
                    t, t.field(child, "judgment"), child, "judgment"
                ),
                clauses=tuple(
                    _walk_semantic_clause(t, clause)
                    for clause in t.fields(child, "clauses")
                ),
                line=line,
                col=col,
            )
        elif kind == "deduction_template":
            templates.append(_walk_template(t, child, pragma))
        elif kind == "deduction_lexical_rule":
            rule = t.field(child, "rule")
            if rule is None:
                raise ParseError(f"deduction_lexical_rule missing rule at {child}")
            lexical_rules.append(_walk_lexical_rule(t, rule, pragma))
        elif kind == "deduction_refines":
            if refines:
                raise ParseError(
                    f"line {line}, col {col}: a deduction refines one deduction"
                )
            refines = _required_text(t, t.field(child, "base"), child, "base")
    return LexicalBody(
        atoms=tuple(atoms),
        features=tuple(features),
        category_sets=tuple(sets),
        semantics=semantics,
        templates=tuple(templates),
        lexical_rules=tuple(lexical_rules),
        refines=refines,
    )

walk_polymorphic_category

walk_polymorphic_category(t: _Tree, vid: str) -> LexiconCategoryPolymorphic

Walk a ∀ X in S, ... . C category.

PARAMETER DESCRIPTION
t

The parse tree.

TYPE: _Tree

vid

The lexicon_polymorphic_category vertex.

TYPE: str

RETURNS DESCRIPTION
LexiconCategoryPolymorphic

The category schema.

RAISES DESCRIPTION
ParseError

If the schema has no category.

Source code in src/quivers/dsl/parser/lexical.py
def walk_polymorphic_category(t: _Tree, vid: str) -> LexiconCategoryPolymorphic:
    """Walk a ``∀ X in S, ... . C`` category.

    Parameters
    ----------
    t : _Tree
        The parse tree.
    vid : str
        The ``lexicon_polymorphic_category`` vertex.

    Returns
    -------
    LexiconCategoryPolymorphic
        The category schema.

    Raises
    ------
    ParseError
        If the schema has no category.
    """
    category = t.field(vid, "category")
    if category is None:
        raise ParseError(f"lexicon_polymorphic_category missing category at {vid}")
    return LexiconCategoryPolymorphic(
        binders=_walk_binders(t, vid),
        category=walk_rule_pattern(t, category),
    )

walk_deduction_body

walk_deduction_body(t: _Tree, vid: str, *, entry: EntryWalker, pragma: PragmaWalker) -> DeductionBody

Walk the body entries of a deduction or a deduction signature.

PARAMETER DESCRIPTION
t

The parse tree.

TYPE: _Tree

vid

The deduction_decl or deduction_signature_decl vertex.

TYPE: str

entry

Walks a lexicon entry.

TYPE: EntryWalker

pragma

Walks a rule's pragma.

TYPE: PragmaWalker

RETURNS DESCRIPTION
DeductionBody

Its parts, in source order.

RAISES DESCRIPTION
ParseError

If an entry is malformed.

Source code in src/quivers/dsl/parser/deduction_modules.py
def walk_deduction_body(
    t: _Tree, vid: str, *, entry: EntryWalker, pragma: PragmaWalker
) -> DeductionBody:
    """Walk the body entries of a deduction or a deduction signature.

    Parameters
    ----------
    t : _Tree
        The parse tree.
    vid : str
        The ``deduction_decl`` or ``deduction_signature_decl`` vertex.
    entry : EntryWalker
        Walks a lexicon entry.
    pragma : PragmaWalker
        Walks a rule's pragma.

    Returns
    -------
    DeductionBody
        Its parts, in source order.

    Raises
    ------
    ParseError
        If an entry is malformed.
    """
    atoms: list[str] = []
    binders: list[str] = []
    rules: list[SequentRule] = []
    lexicon: list[LexiconEntry] = []
    from_file: str | None = None
    from_file_options: tuple[OptionEntry, ...] = ()
    extends: list[DeductionExtension] = []
    lexicons: list[LexiconReference] = []
    instantiations: list[RuleInstantiation] = []
    lexicon_at: list[tuple[int, int]] = []
    for child in t.positional(vid):
        kind = t.kind(child)
        if kind == "deduction_atoms":
            atoms.extend(t.text(atom) for atom in t.fields(child, "atoms"))
        elif kind == "deduction_binders":
            binders.extend(t.text(binder) for binder in t.fields(child, "binders"))
        elif kind == "deduction_rule":
            rules.append(_walk_rule(t, child, pragma))
        elif kind == "deduction_lexicon":
            lexicon_at.append(t.line_col(child))
            lexicon.extend(
                entry(t, item)
                for item in t.positional(child)
                if t.kind(item) == "lexicon_entry"
            )
        elif kind == "deduction_lexicon_from_file":
            lexicon_at.append(t.line_col(child))
            path = _required_text(t, t.field(child, "path"), child, "path")
            if path.startswith('"') and path.endswith('"'):
                path = path[1:-1]
            from_file = path
            options = t.field(child, "options")
            from_file_options = _walk_option_block(t, options) if options else ()
        elif kind == "deduction_extends":
            for item in t.fields(child, "signatures"):
                line, col = t.line_col(item)
                extends.append(
                    DeductionExtension(
                        name=_required_text(t, t.field(item, "name"), item, "name"),
                        constraints=_walk_constraints(t, item),
                        weights=_weight_mode(t, item),
                        line=line,
                        col=col,
                    )
                )
        elif kind == "deduction_lexicon_modules":
            for item in t.fields(child, "lexicons"):
                line, col = t.line_col(item)
                lexicons.append(
                    LexiconReference(
                        name=_required_text(t, t.field(item, "name"), item, "name"),
                        weights=_weight_mode(t, item),
                        line=line,
                        col=col,
                    )
                )
        elif kind == "rule_instantiations":
            for item in t.fields(child, "instantiations"):
                line, col = t.line_col(item)
                condition = t.field(item, "condition")
                instantiations.append(
                    RuleInstantiation(
                        schema=_required_text(
                            t, t.field(item, "schema"), item, "schema"
                        ),
                        constraints=_walk_constraints(t, item),
                        condition=(
                            _walk_let_arith(t, condition)
                            if condition is not None
                            else None
                        ),
                        line=line,
                        col=col,
                    )
                )
    return DeductionBody(
        atoms=tuple(atoms),
        binders=tuple(binders),
        rules=tuple(rules),
        lexicon=tuple(lexicon),
        lexicon_from_file=from_file,
        lexicon_from_file_options=from_file_options,
        extends=tuple(extends),
        lexicons=tuple(lexicons),
        instantiations=tuple(instantiations),
        lexicon_line=lexicon_at[0][0] if lexicon_at else 0,
        lexicon_col=lexicon_at[0][1] if lexicon_at else 0,
    )

walk_deduction_signature_decl

walk_deduction_signature_decl(t: _Tree, vid: str, *, docs: tuple[str, ...], entry: EntryWalker, pragma: PragmaWalker) -> DeductionSignatureDecl

Walk a deduction signature declaration.

PARAMETER DESCRIPTION
t

The parse tree.

TYPE: _Tree

vid

The deduction_signature_decl vertex.

TYPE: str

docs

Its doc comment.

TYPE: tuple[str, ...]

entry

Walks a lexicon entry.

TYPE: EntryWalker

pragma

Walks a rule's pragma.

TYPE: PragmaWalker

RETURNS DESCRIPTION
DeductionSignatureDecl

The signature.

RAISES DESCRIPTION
ParseError

If the body holds a lexicon block or a lexicon line: a signature has no lexicon, and lexical entries typed against it are a lexicon NAME for S module.

Source code in src/quivers/dsl/parser/deduction_modules.py
def walk_deduction_signature_decl(
    t: _Tree,
    vid: str,
    *,
    docs: tuple[str, ...],
    entry: EntryWalker,
    pragma: PragmaWalker,
) -> DeductionSignatureDecl:
    """Walk a ``deduction signature`` declaration.

    Parameters
    ----------
    t : _Tree
        The parse tree.
    vid : str
        The ``deduction_signature_decl`` vertex.
    docs : tuple[str, ...]
        Its doc comment.
    entry : EntryWalker
        Walks a lexicon entry.
    pragma : PragmaWalker
        Walks a rule's pragma.

    Returns
    -------
    DeductionSignatureDecl
        The signature.

    Raises
    ------
    ParseError
        If the body holds a lexicon block or a ``lexicon`` line: a
        signature has no lexicon, and lexical entries typed against it
        are a ``lexicon NAME for S`` module.
    """
    line, col = t.line_col(vid)
    name = _required_text(t, t.field(vid, "name"), vid, "name")
    body = walk_deduction_body(t, vid, entry=entry, pragma=pragma)
    if body.lexicon_line or body.lexicons:
        where = (
            (body.lexicon_line, body.lexicon_col)
            if body.lexicon_line
            else (body.lexicons[0].line, body.lexicons[0].col)
        )
        raise ParseError(
            f"line {where[0]}, col {where[1]}: deduction signature {name!r} declares "
            "no lexicon; write its entries in a lexicon module "
            f"`lexicon NAME for {name}` and take it with a `lexicon NAME` line of "
            "the deduction that extends the signature"
        )
    return DeductionSignatureDecl(
        name=name,
        extends=body.extends,
        atoms=body.atoms,
        binders=body.binders,
        rules=body.rules,
        instantiations=body.instantiations,
        docs=docs,
        line=line,
        col=col,
        deriving=walk_deriving_field(t, vid),
    )

walk_lexicon_decl

walk_lexicon_decl(t: _Tree, vid: str, *, docs: tuple[str, ...], entry: EntryWalker) -> LexiconDecl

Walk a lexicon NAME for S declaration.

PARAMETER DESCRIPTION
t

The parse tree.

TYPE: _Tree

vid

The lexicon_decl vertex.

TYPE: str

docs

Its doc comment.

TYPE: tuple[str, ...]

entry

Walks a lexicon entry.

TYPE: EntryWalker

RETURNS DESCRIPTION
LexiconDecl

The lexicon module.

RAISES DESCRIPTION
ParseError

If its name or signature is missing.

Source code in src/quivers/dsl/parser/deduction_modules.py
def walk_lexicon_decl(
    t: _Tree, vid: str, *, docs: tuple[str, ...], entry: EntryWalker
) -> LexiconDecl:
    """Walk a ``lexicon NAME for S`` declaration.

    Parameters
    ----------
    t : _Tree
        The parse tree.
    vid : str
        The ``lexicon_decl`` vertex.
    docs : tuple[str, ...]
        Its doc comment.
    entry : EntryWalker
        Walks a lexicon entry.

    Returns
    -------
    LexiconDecl
        The lexicon module.

    Raises
    ------
    ParseError
        If its name or signature is missing.
    """
    line, col = t.line_col(vid)
    return LexiconDecl(
        name=_required_text(t, t.field(vid, "name"), vid, "name"),
        signature=_required_text(t, t.field(vid, "signature"), vid, "signature"),
        atoms=tuple(
            t.text(atom)
            for atoms in t.fields(vid, "atoms")
            for atom in t.fields(atoms, "atoms")
        ),
        entries=tuple(entry(t, item) for item in t.fields(vid, "entries")),
        docs=docs,
        line=line,
        col=col,
    )

walk_rule_pattern

walk_rule_pattern(t: _Tree, vid: str) -> ObjectExpr

Walk a premise or conclusion of a rule, reading slash spines.

PARAMETER DESCRIPTION
t

The parse tree.

TYPE: _Tree

vid

An object-expression vertex.

TYPE: str

RETURNS DESCRIPTION
ObjectExpr

The pattern; a spine becomes an ObjectSpine, and a name sequence an ObjectSequence.

RAISES DESCRIPTION
ParseError

If a spine is malformed.

Source code in src/quivers/dsl/parser/deduction_modules.py
def walk_rule_pattern(t: _Tree, vid: str) -> ObjectExpr:
    """Walk a premise or conclusion of a rule, reading slash spines.

    Parameters
    ----------
    t : _Tree
        The parse tree.
    vid : str
        An object-expression vertex.

    Returns
    -------
    ObjectExpr
        The pattern; a spine becomes an `ObjectSpine`, and a name sequence
        an `ObjectSequence`.

    Raises
    ------
    ParseError
        If a spine is malformed.
    """
    kind = t.kind(vid)
    line, col = t.line_col(vid)
    if kind == "object_paren":
        return walk_rule_pattern(t, t.positional(vid)[0])
    if kind == "object_spine":
        head = t.field(vid, "head")
        if head is None:
            raise ParseError(f"object_spine missing head at {vid}")
        return ObjectSpine(
            head=walk_rule_pattern(t, head),
            slash=_required_text(t, t.field(vid, "slash"), vid, "slash"),
            argument=_required_text(t, t.field(vid, "argument"), vid, "argument"),
            length=_required_text(t, t.field(vid, "length"), vid, "length"),
            line=line,
            col=col,
        )
    if kind == "object_sequence":
        return ObjectSequence(
            argument=_required_text(t, t.field(vid, "argument"), vid, "argument"),
            length=_required_text(t, t.field(vid, "length"), vid, "length"),
            line=line,
            col=col,
        )
    if kind == "object_effect_apply":
        effect = _required_text(t, t.field(vid, "effect"), vid, "effect")
        return ObjectEffectApply(
            effect=effect,
            args=tuple(walk_rule_pattern(t, arg) for arg in t.fields(vid, "args")),
            line=line,
            col=col,
        )
    return _walk_type(t, vid)

walk_notation_items

walk_notation_items(t: _Tree, vid: str) -> tuple[NotationItem, ...]

Walk the token tree under a quotation or a group.

PARAMETER DESCRIPTION
t

The parse tree.

TYPE: _Tree

vid

A quotation, quotation_pattern, or notation_group vertex.

TYPE: str

RETURNS DESCRIPTION
tuple[NotationItem, ...]

Its items in source order.

RAISES DESCRIPTION
ParseError

If a child is not a token-tree item.

Source code in src/quivers/dsl/parser/notation.py
def walk_notation_items(t: _Tree, vid: str) -> tuple[NotationItem, ...]:
    """Walk the token tree under a quotation or a group.

    Parameters
    ----------
    t : _Tree
        The parse tree.
    vid : str
        A ``quotation``, ``quotation_pattern``, or ``notation_group``
        vertex.

    Returns
    -------
    tuple[NotationItem, ...]
        Its items in source order.

    Raises
    ------
    ParseError
        If a child is not a token-tree item.
    """
    items: list[NotationItem] = []
    for child in t.positional(vid):
        kind = t.kind(child)
        line, col = t.line_col(child)
        start, end = _span(t, child)
        category = _ATOM_CATEGORIES.get(kind)
        if category is not None:
            items.append(
                NotationAtom(
                    category=category,
                    text=_raw(t, child),
                    start=start,
                    end=end,
                    line=line,
                    col=col,
                )
            )
            continue
        if kind == "notation_block":
            items.extend(walk_notation_items(t, child))
            continue
        if kind == "notation_group":
            opener = _OPENERS.get(t.source[start : start + 1].decode("utf-8"))
            if opener is None:
                raise ParseError(
                    f"line {line}, col {col}: a group opens with (, [, or {{"
                )
            items.append(
                NotationGroup(
                    opener=opener,
                    items=walk_notation_items(t, child),
                    start=start,
                    end=end,
                    line=line,
                    col=col,
                )
            )
            continue
        if kind == "antiquotation":
            name = t.field(child, "name")
            value = t.field(child, "value")
            items.append(
                NotationAntiquote(
                    name=None if name is None else t.text(name),
                    value=None if value is None else _walk_let_arith(t, value),
                    start=start,
                    end=end,
                    line=line,
                    col=col,
                )
            )
            continue
        raise ParseError(f"line {line}, col {col}: {kind} is not a quotation token")
    return tuple(items)

walk_notation_statement

walk_notation_statement(t: _Tree, vid: str) -> Statement

Walk a notation declaration or an open notation statement.

PARAMETER DESCRIPTION
t

The parse tree.

TYPE: _Tree

vid

A vertex whose kind is in NOTATION_STATEMENT_KINDS.

TYPE: str

RETURNS DESCRIPTION
Statement

The NotationDecl or OpenNotationDecl.

RAISES DESCRIPTION
ParseError

If the vertex is not a notation statement.

Source code in src/quivers/dsl/parser/notation.py
def walk_notation_statement(t: _Tree, vid: str) -> Statement:
    """Walk a notation declaration or an ``open notation`` statement.

    Parameters
    ----------
    t : _Tree
        The parse tree.
    vid : str
        A vertex whose kind is in `NOTATION_STATEMENT_KINDS`.

    Returns
    -------
    Statement
        The `NotationDecl` or `OpenNotationDecl`.

    Raises
    ------
    ParseError
        If the vertex is not a notation statement.
    """
    kind = t.kind(vid)
    line, col = t.line_col(vid)
    if kind == "notation_decl":
        return NotationDecl(
            name=_field_text(t, vid, "name"),
            syntax=_field_text(t, vid, "syntax"),
            productions=tuple(
                _walk_production(t, child) for child in t.fields(vid, "productions")
            ),
            relations=tuple(
                _walk_relation(t, child) for child in t.fields(vid, "relations")
            ),
            docs=_docs(t, vid),
            line=line,
            col=col,
        )
    if kind == "open_notation_decl":
        return OpenNotationDecl(
            target=_raw(t, _required_field(t, vid, "notation")), line=line, col=col
        )
    raise ParseError(f"unexpected notation statement kind: {kind}")

walk_quotation

walk_quotation(t: _Tree, vid: str) -> QiecQuotation

Walk a quotation vertex in a value position.

PARAMETER DESCRIPTION
t

The parse tree.

TYPE: _Tree

vid

The quotation vertex.

TYPE: str

RETURNS DESCRIPTION
QiecQuotation

The quotation with its token tree.

Source code in src/quivers/dsl/parser/notation.py
def walk_quotation(t: _Tree, vid: str) -> QiecQuotation:
    """Walk a ``quotation`` vertex in a value position.

    Parameters
    ----------
    t : _Tree
        The parse tree.
    vid : str
        The ``quotation`` vertex.

    Returns
    -------
    QiecQuotation
        The quotation with its token tree.
    """
    line, col = t.line_col(vid)
    return QiecQuotation(
        items=walk_notation_items(t, vid),
        source=_raw(t, vid),
        start=_span(t, vid)[0],
        line=line,
        col=col,
    )

walk_quotation_pattern

walk_quotation_pattern(t: _Tree, vid: str) -> QiecQuotationPattern

Walk a quotation_pattern vertex.

PARAMETER DESCRIPTION
t

The parse tree.

TYPE: _Tree

vid

The quotation_pattern vertex.

TYPE: str

RETURNS DESCRIPTION
QiecQuotationPattern

The pattern with its token tree.

RAISES DESCRIPTION
ParseError

If an antiquotation in the pattern is $(e), which names no pattern variable.

Source code in src/quivers/dsl/parser/notation.py
def walk_quotation_pattern(t: _Tree, vid: str) -> QiecQuotationPattern:
    """Walk a ``quotation_pattern`` vertex.

    Parameters
    ----------
    t : _Tree
        The parse tree.
    vid : str
        The ``quotation_pattern`` vertex.

    Returns
    -------
    QiecQuotationPattern
        The pattern with its token tree.

    Raises
    ------
    ParseError
        If an antiquotation in the pattern is ``$(e)``, which names no
        pattern variable.
    """
    line, col = t.line_col(vid)
    items = walk_notation_items(t, vid)
    _refuse_value_antiquotes(items)
    return QiecQuotationPattern(
        items=items, source=_raw(t, vid), start=_span(t, vid)[0], line=line, col=col
    )

walk_judgment_decl

walk_judgment_decl(t: _Tree, vid: str, line: int, col: int, *, docs: tuple[str, ...], pragma: Callable[[_Tree, str], tuple[OptionEntry, ...]]) -> JudgmentDecl

Read a judgment declaration.

PARAMETER DESCRIPTION
t

The parse tree.

TYPE: _Tree

vid

The judgment_decl vertex.

TYPE: str

line

Its position.

TYPE: int

col

Its position.

TYPE: int

docs

Its doc comment lines, read by the statement walker.

TYPE: tuple of str

pragma

The walker of a rule's trailing pragma.

TYPE: Callable

RETURNS DESCRIPTION
JudgmentDecl

The declaration.

RAISES DESCRIPTION
ParseError

If an argument has no mode or a rule no conclusion.

Source code in src/quivers/dsl/parser/object_terms.py
def walk_judgment_decl(
    t: _Tree,
    vid: str,
    line: int,
    col: int,
    *,
    docs: tuple[str, ...],
    pragma: Callable[[_Tree, str], tuple[OptionEntry, ...]],
) -> JudgmentDecl:
    """Read a ``judgment`` declaration.

    Parameters
    ----------
    t : _Tree
        The parse tree.
    vid : str
        The ``judgment_decl`` vertex.
    line, col : int
        Its position.
    docs : tuple of str
        Its doc comment lines, read by the statement walker.
    pragma : Callable
        The walker of a rule's trailing pragma.

    Returns
    -------
    JudgmentDecl
        The declaration.

    Raises
    ------
    ParseError
        If an argument has no mode or a rule no conclusion.
    """
    arguments: list[JudgmentArgumentDecl] = []
    for argument in t.fields(vid, "arguments"):
        sort = t.field(argument, "sort")
        words = " ".join(_tokens(t, argument)).split()
        mode = "out" if "out" in words else "in" if "in" in words else None
        if sort is None or mode is None:
            raise ParseError(
                f"line {line}, col {col}: a judgment argument needs a mode"
            )
        entry = t.field(sort, "argument")
        arguments.append(
            JudgmentArgumentDecl(
                name=_field_text(t, argument, "name"),
                sort=_field_text(t, sort, "name"),
                argument=t.text(entry) if entry is not None else None,
                mode=mode,
            )
        )
    rules: list[JudgmentRuleDecl] = []
    for rule in t.fields(vid, "rules"):
        rule_line, rule_col = t.line_col(rule)
        conclusion = t.field(rule, "conclusion")
        if conclusion is None:
            raise ParseError(
                f"line {rule_line}, col {rule_col}: a rule needs a conclusion"
            )
        written = t.field(rule, "pragma")
        rules.append(
            JudgmentRuleDecl(
                name=_field_text(t, rule, "name"),
                schematic=tuple(t.text(s) for s in t.fields(rule, "schematic")),
                premises=tuple(
                    walk_object_term(t, p) for p in t.fields(rule, "premises")
                ),
                conclusion=walk_object_term(t, conclusion),
                options=pragma(t, written) if written else (),
                line=rule_line,
                col=rule_col,
            )
        )
    options_vid = t.field(vid, "options")
    return JudgmentDecl(
        name=_field_text(t, vid, "name"),
        arguments=tuple(arguments),
        rules=tuple(rules),
        options=_walk_option_block(t, options_vid) if options_vid else (),
        docs=docs,
        line=line,
        col=col,
    )

walk_object_term

walk_object_term(t: _Tree, vid: str) -> PatternSyntax

Read a written second-order term.

PARAMETER DESCRIPTION
t

The parse tree.

TYPE: _Tree

vid

An _object_term or _object_term_argument vertex.

TYPE: str

RETURNS DESCRIPTION
PatternSyntax

The term as written, names unresolved.

RAISES DESCRIPTION
ParseError

If the vertex is not a term, or a binder's dot follows a name with no space so that the name and the body read as one dotted name.

Source code in src/quivers/dsl/parser/object_terms.py
def walk_object_term(t: _Tree, vid: str) -> PatternSyntax:
    """Read a written second-order term.

    Parameters
    ----------
    t : _Tree
        The parse tree.
    vid : str
        An ``_object_term`` or ``_object_term_argument`` vertex.

    Returns
    -------
    PatternSyntax
        The term as written, names unresolved.

    Raises
    ------
    ParseError
        If the vertex is not a term, or a binder's dot follows a name with
        no space so that the name and the body read as one dotted name.
    """
    kind = t.kind(vid)
    line, col = t.line_col(vid)
    if kind == "identifier":
        return PatternSyntax(kind="name", name=t.text(vid), line=line, col=col)
    if kind == "string":
        return PatternSyntax(
            kind="leaf", leaf=ast.literal_eval(t.text(vid)), line=line, col=col
        )
    if kind == "integer":
        return PatternSyntax(kind="leaf", leaf=int(t.text(vid)), line=line, col=col)
    if kind == "object_term_application":
        return PatternSyntax(
            kind="apply",
            name=_field_text(t, vid, "head"),
            args=tuple(walk_object_term(t, a) for a in t.fields(vid, "arguments")),
            line=line,
            col=col,
        )
    if kind == "object_term_instantiation":
        head = _field_text(t, vid, "head")
        return PatternSyntax(
            kind="instance",
            name=head,
            args=tuple(walk_object_term(t, a) for a in t.fields(vid, "arguments")),
            line=line,
            col=col,
        )
    if kind == "object_term_abstraction":
        body = t.field(vid, "body")
        if body is None:
            raise ParseError(f"line {line}, col {col}: an abstraction needs a body")
        return PatternSyntax(
            kind="abstract",
            names=tuple(t.text(n) for n in t.fields(vid, "names")),
            args=(walk_object_term(t, body),),
            line=line,
            col=col,
        )
    if kind == "context_extension":
        context = t.field(vid, "context")
        if context is None or t.kind(context) != "identifier":
            raise ParseError(
                f"line {line}, col {col}: a context extension starts with a context "
                "name, as in `(ctx, x : A)`"
            )
        entries = t.fields(vid, "entries")
        types = []
        for entry in entries:
            type_vid = t.field(entry, "type")
            if type_vid is None:
                raise ParseError(
                    f"line {line}, col {col}: a context entry needs a type"
                )
            types.append(walk_object_term(t, type_vid))
        return PatternSyntax(
            kind="extend",
            name=t.text(context),
            names=tuple(_field_text(t, entry, "name") for entry in entries),
            args=tuple(types),
            line=line,
            col=col,
        )
    raise ParseError(f"line {line}, col {col}: {kind} is not a term")

walk_syntax_equations

walk_syntax_equations(t: _Tree, vid: str) -> tuple[tuple[EquationDecl, ...], tuple[OptionEntry, ...], bool]

Read a signature's equations block.

PARAMETER DESCRIPTION
t

The parse tree.

TYPE: _Tree

vid

The syntax_equations vertex.

TYPE: str

RETURNS DESCRIPTION
tuple

The equations, the block's options, and whether termination is assumed.

Source code in src/quivers/dsl/parser/object_terms.py
def walk_syntax_equations(
    t: _Tree, vid: str
) -> tuple[tuple[EquationDecl, ...], tuple[OptionEntry, ...], bool]:
    """Read a signature's ``equations`` block.

    Parameters
    ----------
    t : _Tree
        The parse tree.
    vid : str
        The ``syntax_equations`` vertex.

    Returns
    -------
    tuple
        The equations, the block's options, and whether termination is
        assumed.
    """
    options_vid = t.field(vid, "options")
    options = _walk_option_block(t, options_vid) if options_vid else ()
    equations: list[EquationDecl] = []
    for equation in t.fields(vid, "equations"):
        line, col = t.line_col(equation)
        left = t.field(equation, "left")
        right = t.field(equation, "right")
        if left is None or right is None:
            raise ParseError(f"line {line}, col {col}: an equation needs two sides")
        oriented = any("~>" in text for text in _tokens(t, equation))
        equations.append(
            EquationDecl(
                name=_field_text(t, equation, "name"),
                left=walk_object_term(t, left),
                right=walk_object_term(t, right),
                oriented=oriented,
                line=line,
                col=col,
            )
        )
    assumed = bool(t.fields(vid, "assumptions"))
    return tuple(equations), options, assumed

literal_json

literal_json(t: _Tree, vid: str) -> str

The canonical JSON text of a literal experiment value.

PARAMETER DESCRIPTION
t

The parse tree.

TYPE: _Tree

vid

The value's vertex: a number, a string, true/false, or a list of them.

TYPE: str

RETURNS DESCRIPTION
str

Its JSON text, with sorted keys and no insignificant whitespace.

RAISES DESCRIPTION
ParseError

If the value is not a literal.

Source code in src/quivers/dsl/parser/experiments.py
def literal_json(t: _Tree, vid: str) -> str:
    """The canonical JSON text of a literal experiment value.

    Parameters
    ----------
    t : _Tree
        The parse tree.
    vid : str
        The value's vertex: a number, a string, ``true``/``false``, or a
        list of them.

    Returns
    -------
    str
        Its JSON text, with sorted keys and no insignificant whitespace.

    Raises
    ------
    ParseError
        If the value is not a literal.
    """
    return json.dumps(_json_value(t, vid), sort_keys=True, separators=(",", ":"))

string_content

string_content(text: str) -> str

The characters a string literal denotes.

PARAMETER DESCRIPTION
text

The literal, quotes included.

TYPE: str

RETURNS DESCRIPTION
str

Its content, with each backslash escape replaced by the character it escapes.

Source code in src/quivers/dsl/parser/experiments.py
def string_content(text: str) -> str:
    """The characters a string literal denotes.

    Parameters
    ----------
    text : str
        The literal, quotes included.

    Returns
    -------
    str
        Its content, with each backslash escape replaced by the character
        it escapes.
    """
    return _ESCAPE.sub(lambda match: match.group(1), text[1:-1])

walk_experiment_decl

walk_experiment_decl(t: _Tree, vid: str) -> ExperimentDecl

Walk an experiment declaration.

PARAMETER DESCRIPTION
t

The parse tree, with the name view to read references through.

TYPE: _Tree

vid

The experiment_decl vertex.

TYPE: str

RETURNS DESCRIPTION
ExperimentDecl

The declaration.

RAISES DESCRIPTION
ParseError

If a clause that may occur once occurs twice, the program, infer, or seed clause is missing, or a value is not a literal; each located at the clause.

Source code in src/quivers/dsl/parser/experiments.py
def walk_experiment_decl(t: _Tree, vid: str) -> ExperimentDecl:
    """Walk an ``experiment`` declaration.

    Parameters
    ----------
    t : _Tree
        The parse tree, with the name view to read references through.
    vid : str
        The ``experiment_decl`` vertex.

    Returns
    -------
    ExperimentDecl
        The declaration.

    Raises
    ------
    ParseError
        If a clause that may occur once occurs twice, the ``program``,
        ``infer``, or ``seed`` clause is missing, or a value is not a
        literal; each located at the clause.
    """
    line, col = t.line_col(vid)
    name = _raw(t, _required_field(t, vid, "name"))
    seen: dict[str, str] = {}
    data: list[ExperimentData] = []
    fixed: list[ExperimentValue] = []
    sweeps: list[ExperimentSweep] = []
    tolerances: list[ExperimentValue] = []
    links: list[ExperimentLink] = []
    handlers: list[ExperimentHandler] = []
    program = ""
    program_line = 0
    infer: ExperimentInfer | None = None
    seed: int | None = None
    reference: ExperimentReference | None = None
    for clause in t.fields(vid, "clauses"):
        kind = t.kind(clause)
        clause_line, clause_col = t.line_col(clause)
        if kind in _SINGLE_CLAUSES:
            if kind in seen:
                raise _located(
                    t,
                    clause,
                    f"experiment {name} has a second {_CLAUSE_WORD[kind]} clause; "
                    f"the first is at {seen[kind]}",
                )
            seen[kind] = f"line {clause_line}"
        if kind == "experiment_program":
            program = _field_text(t, clause, "entry")
            program_line = clause_line
        elif kind == "experiment_data":
            data.append(
                ExperimentData(
                    name=_raw(t, _required_field(t, clause, "name")),
                    path=string_content(_raw(t, _required_field(t, clause, "path"))),
                    pin=_pin(t, clause),
                    line=clause_line,
                    col=clause_col,
                )
            )
        elif kind == "experiment_fix":
            fixed.append(_named_value(t, clause, "name", "value"))
        elif kind == "experiment_infer":
            infer = ExperimentInfer(
                method=_raw(t, _required_field(t, clause, "method")),
                options=tuple(_option(t, item) for item in t.fields(clause, "options")),
                line=clause_line,
                col=clause_col,
            )
        elif kind == "experiment_seed":
            seed = int(_raw(t, _required_field(t, clause, "value")))
        elif kind == "experiment_sweep":
            values = tuple(
                json.dumps(_json_value(t, item), sort_keys=True, separators=(",", ":"))
                for item in t.fields(_required_field(t, clause, "values"), "item")
            )
            if not values:
                raise _located(t, clause, "a sweep needs at least one point")
            sweeps.append(
                ExperimentSweep(
                    name=_raw(t, _required_field(t, clause, "name")),
                    values=values,
                    line=clause_line,
                    col=clause_col,
                )
            )
        elif kind == "experiment_reference":
            reference = ExperimentReference(
                path=string_content(_raw(t, _required_field(t, clause, "path"))),
                pin=_pin(t, clause),
                line=clause_line,
                col=clause_col,
            )
        elif kind == "experiment_tolerance":
            tolerances.extend(_option(t, item) for item in t.fields(clause, "entries"))
        elif kind == "link_decl":
            links.append(
                ExperimentLink(
                    hole=_raw(t, _required_field(t, clause, "hole")),
                    module=_raw(t, _required_field(t, clause, "module")),
                    line=clause_line,
                    col=clause_col,
                )
            )
        elif kind == "experiment_handle":
            handlers.append(_handler(t, clause))
        else:
            raise _located(t, clause, f"unexpected experiment clause {kind}")

    def missing(word: str) -> ParseError:
        return ParseError(
            f"line {line}, col {col}: experiment {name} has no {word} clause; "
            "an experiment states its entry (program), its inference "
            "configuration (infer), and its seed (seed)"
        )

    if not program:
        raise missing("program")
    if infer is None:
        raise missing("infer")
    if seed is None:
        raise missing("seed")
    return ExperimentDecl(
        name=name,
        program=program,
        program_line=program_line,
        infer=infer,
        seed=seed,
        data=tuple(data),
        fixed=tuple(fixed),
        sweeps=tuple(sweeps),
        reference=reference,
        tolerances=tuple(tolerances),
        links=tuple(links),
        handlers=tuple(handlers),
        docs=_docs(t, vid),
        line=line,
        col=col,
    )

walk_deduction_semiring

walk_deduction_semiring(t: _Tree, vid: str | None) -> DeductionSemiring | None

Read the semiring parameter of a deduction header, if it has one.

PARAMETER DESCRIPTION
t

The parse tree.

TYPE: _Tree

vid

The deduction_semiring vertex, or None for a header without one.

TYPE: str or None

RETURNS DESCRIPTION
DeductionSemiring or None

The parameter.

Source code in src/quivers/dsl/parser/semirings.py
def walk_deduction_semiring(t: _Tree, vid: str | None) -> DeductionSemiring | None:
    """Read the semiring parameter of a deduction header, if it has one.

    Parameters
    ----------
    t : _Tree
        The parse tree.
    vid : str or None
        The ``deduction_semiring`` vertex, or ``None`` for a header
        without one.

    Returns
    -------
    DeductionSemiring or None
        The parameter.
    """
    if vid is None:
        return None
    line, col = t.line_col(vid)
    instance = t.field(vid, "instance")
    theory = t.field(vid, "theory")
    return DeductionSemiring(
        name=_field_text(t, vid, "name"),
        instance=None if instance is None else t.text(instance),
        theory=None if theory is None else t.text(theory),
        line=line,
        col=col,
    )

walk_semiring_decl

walk_semiring_decl(t: _Tree, vid: str, *, docs: tuple[str, ...] = ()) -> SemiringDecl

Read a semiring declaration.

PARAMETER DESCRIPTION
t

The parse tree.

TYPE: _Tree

vid

The semiring_decl vertex.

TYPE: str

docs

Its doc comment lines.

TYPE: tuple of str DEFAULT: ()

RETURNS DESCRIPTION
SemiringDecl

The declaration.

Source code in src/quivers/dsl/parser/semirings.py
def walk_semiring_decl(
    t: _Tree, vid: str, *, docs: tuple[str, ...] = ()
) -> SemiringDecl:
    """Read a ``semiring`` declaration.

    Parameters
    ----------
    t : _Tree
        The parse tree.
    vid : str
        The ``semiring_decl`` vertex.
    docs : tuple of str
        Its doc comment lines.

    Returns
    -------
    SemiringDecl
        The declaration.
    """
    line, col = t.line_col(vid)
    assumptions: list[ViewAssumptionDecl] = []
    for assumption in t.fields(vid, "assumptions"):
        for equation in t.fields(assumption, "equations"):
            a_line, a_col = t.line_col(equation)
            assumptions.append(
                ViewAssumptionDecl(equation=t.text(equation), line=a_line, col=a_col)
            )
    return SemiringDecl(
        name=_field_text(t, vid, "name"),
        theory=_field_text(t, vid, "theory"),
        algebra=_field_text(t, vid, "algebra"),
        carrier=_field_text(t, vid, "carrier"),
        assumptions=tuple(assumptions),
        docs=docs,
        line=line,
        col=col,
    )

walk_model_decl

walk_model_decl(t: _Tree, vid: str, *, docs: tuple[str, ...] = ()) -> ModelDecl

Read a model declaration.

PARAMETER DESCRIPTION
t

The parse tree.

TYPE: _Tree

vid

The model_decl vertex.

TYPE: str

docs

Its doc comment lines.

TYPE: tuple of str DEFAULT: ()

RETURNS DESCRIPTION
ModelDecl

The declaration.

RAISES DESCRIPTION
ParseError

If the construction is neither reduct nor free.

Source code in src/quivers/dsl/parser/theories.py
def walk_model_decl(t: _Tree, vid: str, *, docs: tuple[str, ...] = ()) -> ModelDecl:
    """Read a ``model`` declaration.

    Parameters
    ----------
    t : _Tree
        The parse tree.
    vid : str
        The ``model_decl`` vertex.
    docs : tuple of str
        Its doc comment lines.

    Returns
    -------
    ModelDecl
        The declaration.

    Raises
    ------
    ParseError
        If the construction is neither ``reduct`` nor ``free``.
    """
    line, col = t.line_col(vid)
    name = _field_text(t, vid, "name")
    construction = t.field(vid, "construction")
    if construction is not None:
        word = t.text(construction)
        if word not in ("reduct", "free"):
            raise ParseError(
                f"line {line}, col {col}: a model is constructed by `reduct` or `free`"
            )
        return ModelDecl(
            name=name,
            construction="reduct" if word == "reduct" else "free",
            source=_field_text(t, vid, "source"),
            view=_field_text(t, vid, "view"),
            docs=docs,
            line=line,
            col=col,
        )
    interpretations: list[ModelInterpretationDecl] = []
    for interpretation in t.fields(vid, "interpretations"):
        i_line, i_col = t.line_col(interpretation)
        interpretations.append(
            ModelInterpretationDecl(
                symbol=_field_text(t, interpretation, "symbol"),
                value=_field_text(t, interpretation, "value"),
                line=i_line,
                col=i_col,
            )
        )
    return ModelDecl(
        name=name,
        theory=_field_text(t, vid, "theory"),
        interpretations=tuple(interpretations),
        docs=docs,
        line=line,
        col=col,
    )

walk_theory_decl

walk_theory_decl(t: _Tree, vid: str, *, docs: tuple[str, ...] = ()) -> TheoryDecl

Read a theory declaration.

PARAMETER DESCRIPTION
t

The parse tree.

TYPE: _Tree

vid

The theory_decl vertex.

TYPE: str

docs

Its doc comment lines.

TYPE: tuple of str DEFAULT: ()

RETURNS DESCRIPTION
TheoryDecl

The declaration.

RAISES DESCRIPTION
ParseError

If the body declares two equations blocks.

Source code in src/quivers/dsl/parser/theories.py
def walk_theory_decl(t: _Tree, vid: str, *, docs: tuple[str, ...] = ()) -> TheoryDecl:
    """Read a ``theory`` declaration.

    Parameters
    ----------
    t : _Tree
        The parse tree.
    vid : str
        The ``theory_decl`` vertex.
    docs : tuple of str
        Its doc comment lines.

    Returns
    -------
    TheoryDecl
        The declaration.

    Raises
    ------
    ParseError
        If the body declares two ``equations`` blocks.
    """
    line, col = t.line_col(vid)
    parameters: list[TheoryParameterDecl] = []
    for parameter in t.fields(vid, "parameters"):
        p_line, p_col = t.line_col(parameter)
        parameters.append(
            TheoryParameterDecl(
                name=_field_text(t, parameter, "name"),
                theory=_field_text(t, parameter, "theory"),
                line=p_line,
                col=p_col,
            )
        )
    values = _expression_vertices(t, vid, "value")
    value = walk_theory_expression(t, values[0]) if values else None
    includes: list[TheoryIncludeDecl] = []
    for include in t.fields(vid, "includes"):
        i_line, i_col = t.line_col(include)
        options_vid = t.field(include, "options")
        includes.append(
            TheoryIncludeDecl(
                theory=walk_theory_expression(t, _one_expression(t, include, "theory")),
                options=_walk_option_block(t, options_vid) if options_vid else (),
                line=i_line,
                col=i_col,
            )
        )
    sorts: list[TheorySortDecl] = []
    for block in t.fields(vid, "sorts"):
        for sort in t.fields(block, "sorts"):
            s_line, s_col = t.line_col(sort)
            sorts.append(
                TheorySortDecl(
                    name=_field_text(t, sort, "name"),
                    parameters=tuple(
                        _walk_binder(t, b) for b in t.fields(sort, "parameters")
                    ),
                    line=s_line,
                    col=s_col,
                )
            )
    operations: list[TheoryOperationDecl] = []
    for block in t.fields(vid, "operations"):
        for operation in t.fields(block, "operations"):
            o_line, o_col = t.line_col(operation)
            output = t.field(operation, "output")
            if output is None:
                raise ParseError(
                    f"line {o_line}, col {o_col}: an operation needs a sort"
                )
            operations.append(
                TheoryOperationDecl(
                    name=_field_text(t, operation, "name"),
                    inputs=tuple(
                        _walk_input(t, i) for i in t.fields(operation, "inputs")
                    ),
                    output=walk_object_term(t, output),
                    line=o_line,
                    col=o_col,
                )
            )
    blocks = t.fields(vid, "equations")
    if len(blocks) > 1:
        b_line, b_col = t.line_col(blocks[1])
        raise ParseError(
            f"line {b_line}, col {b_col}: a theory has one `equations` block"
        )
    equations: tuple[EquationDecl, ...] = ()
    equation_options: tuple[OptionEntry, ...] = ()
    assumed = False
    if blocks:
        equations, equation_options, assumed = walk_syntax_equations(t, blocks[0])
    return TheoryDecl(
        name=_field_text(t, vid, "name"),
        parameters=tuple(parameters),
        value=value,
        includes=tuple(includes),
        sorts=tuple(sorts),
        operations=tuple(operations),
        equations=equations,
        equation_options=equation_options,
        assume_terminating=assumed,
        docs=docs,
        line=line,
        col=col,
    )

walk_theory_expression

walk_theory_expression(t: _Tree, vid: str) -> TheoryExpr

Read a theory expression.

PARAMETER DESCRIPTION
t

The parse tree.

TYPE: _Tree

vid

A theory-expression vertex.

TYPE: str

RETURNS DESCRIPTION
TheoryExpr

The expression.

RAISES DESCRIPTION
ParseError

If the vertex is not a theory expression.

Source code in src/quivers/dsl/parser/theories.py
def walk_theory_expression(t: _Tree, vid: str) -> TheoryExpr:
    """Read a theory expression.

    Parameters
    ----------
    t : _Tree
        The parse tree.
    vid : str
        A theory-expression vertex.

    Returns
    -------
    TheoryExpr
        The expression.

    Raises
    ------
    ParseError
        If the vertex is not a theory expression.
    """
    kind = t.kind(vid)
    line, col = t.line_col(vid)
    if kind == "identifier":
        return TheoryRef(name=t.text(vid), line=line, col=col)
    if kind == "theory_sum":
        return TheorySum(
            summands=tuple(
                walk_theory_expression(t, s)
                for s in _expression_vertices(t, vid, "summands")
            ),
            shared=tuple(t.text(s) for s in t.fields(vid, "shared")),
            line=line,
            col=col,
        )
    if kind == "theory_instantiation":
        arguments: list[TheoryArgument] = []
        for argument in t.fields(vid, "arguments"):
            a_line, a_col = t.line_col(argument)
            view = t.field(argument, "view")
            arguments.append(
                TheoryArgument(
                    parameter=_field_text(t, argument, "parameter"),
                    theory=_field_text(t, argument, "theory"),
                    view=None if view is None else t.text(view),
                    line=a_line,
                    col=a_col,
                )
            )
        return TheoryInstantiation(
            theory=_field_text(t, vid, "theory"),
            arguments=tuple(arguments),
            line=line,
            col=col,
        )
    if kind == "theory_renaming":
        renames: list[TheoryRename] = []
        for rename in t.fields(vid, "renames"):
            r_line, r_col = t.line_col(rename)
            renames.append(
                TheoryRename(
                    source=_field_text(t, rename, "source"),
                    target=_field_text(t, rename, "target"),
                    line=r_line,
                    col=r_col,
                )
            )
        return TheoryRenaming(
            theory=walk_theory_expression(t, _one_expression(t, vid, "theory")),
            renames=tuple(renames),
            line=line,
            col=col,
        )
    if kind == "theory_hiding":
        return TheoryHiding(
            theory=walk_theory_expression(t, _one_expression(t, vid, "theory")),
            names=tuple(t.text(n) for n in t.fields(vid, "names")),
            line=line,
            col=col,
        )
    raise ParseError(f"line {line}, col {col}: {kind} is not a theory expression")

walk_view_decl

walk_view_decl(t: _Tree, vid: str, *, docs: tuple[str, ...] = ()) -> ViewDecl

Read a view declaration.

PARAMETER DESCRIPTION
t

The parse tree.

TYPE: _Tree

vid

The view_decl vertex.

TYPE: str

docs

Its doc comment lines.

TYPE: tuple of str DEFAULT: ()

RETURNS DESCRIPTION
ViewDecl

The declaration.

RAISES DESCRIPTION
ParseError

If a mapping lacks a side.

Source code in src/quivers/dsl/parser/theories.py
def walk_view_decl(t: _Tree, vid: str, *, docs: tuple[str, ...] = ()) -> ViewDecl:
    """Read a ``view`` declaration.

    Parameters
    ----------
    t : _Tree
        The parse tree.
    vid : str
        The ``view_decl`` vertex.
    docs : tuple of str
        Its doc comment lines.

    Returns
    -------
    ViewDecl
        The declaration.

    Raises
    ------
    ParseError
        If a mapping lacks a side.
    """
    line, col = t.line_col(vid)
    mappings: list[ViewMappingDecl] = []
    for mapping in t.fields(vid, "mappings"):
        m_line, m_col = t.line_col(mapping)
        source = t.field(mapping, "source")
        target = t.field(mapping, "target")
        if source is None or target is None:
            raise ParseError(f"line {m_line}, col {m_col}: a mapping needs two sides")
        mappings.append(
            ViewMappingDecl(
                source=walk_object_term(t, source),
                target=walk_object_term(t, target),
                line=m_line,
                col=m_col,
            )
        )
    assumptions: list[ViewAssumptionDecl] = []
    for assumption in t.fields(vid, "assumptions"):
        for equation in t.fields(assumption, "equations"):
            a_line, a_col = t.line_col(equation)
            assumptions.append(
                ViewAssumptionDecl(equation=t.text(equation), line=a_line, col=a_col)
            )
    return ViewDecl(
        name=_field_text(t, vid, "name"),
        domain=_field_text(t, vid, "domain"),
        codomain=_field_text(t, vid, "codomain"),
        mappings=tuple(mappings),
        assumptions=tuple(assumptions),
        docs=docs,
        line=line,
        col=col,
    )