Skip to main content

Module parser

Module parser 

Source
Expand description

Script parser: Tok stream to Step.

The single parser for string scripts and braced-macro token streams. The string entry points at the bottom of this module lex with lex_str and lower here; the braced-macro frontend fuses span-adjacent literals, runs the same scanner, and lowers here.

Statement boundaries resolve here from grammar state, never in the lexers: groups arrive structurally atomic, so at each nesting level a Newline/Semicolon ends the statement. Continuation exceptions (trailing =, IN, trailing ASYNC, bare wrapper heads) land with their structural slices; the decision point is boundary_ends_statement.

Coverage: generic commands (head word plus gap-split args with quote-accurate joins), guards (leading [..] groups; in-body brackets splice to raw text), LET/SET/RETURN with the full expression tiers, static calls and RUN-exec with instruction exactness, single-command wrappers (WITH_IO/TIMEOUT/ISOLATED/ ASYNC), io-blocks, AWAIT/CANCEL, multi-element statements, block statements (IF/FOR/WHILE/FUNC/REMOTE/TYPE/ IMPORT/EXPORT), guard blocks, and a whole-script post-pass (prelude order, COPY placement, EXPORT membership). Comments ride as TokKind::Comment markers plus mid-line ///#//* gap rules.

Design record: shared lowering cores with parser-native token classification. Each item below states what is shared and what is parser-native (verified by the lexer-agreement oracle and the fuzz harness).

  • Argument assembly matches single-quoted-string quoted=true and multi-fragment space-or-empty joins by the joint flag.
  • key_char/bare_run/value_run implement the guard key/value charsets (everything but : = ! , | ( ) ] $, whitespace, and comment opens; eq values cross gaps like the atomic span).
  • ns_guard validates namespaces with shared messages.
  • Guard validation strings (any(...)/all(...)/eq(...) shapes) carry shared messages.
  • parse_guard_groups folds stacked brackets with All (the statement-guard stash semantics).
  • The expression tiers implement or/and/compare/ordering/add/mul/ unary/atom precedence over Tok; lowering runs through the shared constructors (make_arith, make_compare, apply_unary_neg, reject_boundary, classify_numeric_text, canonicalize_spelling, lower_block_string).
  • Static call resolution is truly shared (resolve_call_name, check_func_ident in resolve.rs).
  • Instruction tokens are truly shared (InsToken, lower_env_tokens, lower_expand_tokens, canonical_assignment_arg in commands.rs); only the token-level classifiers (key runs, boundaries, call shapes, expression extension) are parser-native.
  • Numeric _-separator shape gating, bare-word charsets, and --prefix dispatch match the lexical rules (durations, paths, and versions lex as bare words; -f stays literal).
  • Wrapper validators are truly shared (check_tty_wrapping, reject_async_in_capture, reject_pipe_stdout_in_capture, rewrite_isolated_inherit, contains_inherit_env, reject_nested_inherit_env, merge_bindings, IoBindingSet, and_guard_exprs, reject_with_io_in_async in commands.rs; in commands.rs); only the token-level shape classifiers (duration gate, binding splitter, await/cancel shapes, block-vs-template, inherit keys) are parser-native.
  • The element loop lowers consecutive elements to end of run: structural pairs end mid-line and trailing elements form following steps (guards attach to the first only); the WITH_IO pending wait holds bare brackets across separators.
  • Block headers: IF/FOR/WHILE conditions miss to generic on expression failure (inline-block failures propagate); FUNC paren-group params parse with gap_nl discipline (shared helper, like call args); REMOTE targets/blocks/bindings; TYPE maximal shape match; IMPORT/EXPORT lists. Shared validators are truly shared (validate_remote_copy_placement, contains_remote_block, collect_remote_body_symbols, validate_exports in commands.rs).
  • Scope marking: top-level guard nesting bumps each level (stateful pending_scope_enters); wrapper and guard-block bodies pin 0/0 (parse_body_steps without marking).
  • Comment handling: statement-position comments vanish (releasing ELSE holds), gap positions skip, arg positions type or glue literally; /* depth protects separators in the splitter, and group scanning copies comments through for the recursive re-lex.

Structs§

ParseCtx
Parse context: shared lowering dispatcher plus module table for static call resolution, with FUNC/import frames per braced body.
ParsedScript
Parsed script with single-file EXPORT metadata. steps is the linear execution plan, func_exports the EXPORT func names in source order, type_exports the EXPORT TYPE names in source order, and func_docs maps top-level FUNC base names to (summary, docs) collected from the immediately preceding # comment block.
TokenError
Backend error. Carries the statement index and message; the string entry points below map it to crate::ParseError. Lowering failures from the shared lower dispatcher stringify through here so success paths compare exactly.

Functions§

parse_expression_str
Parse one expression from source text with an empty module scope, for tooling that shows lowering without running (docs demos, explain output). No imports exist here, so bare function calls fail and qualified calls fail against the empty table; only INSPECT passes through untouched. Arithmetic, comparison, variables, env reads, keypaths, and literals lower normally, with literal only subtrees folded before flattening.
parse_guard_expr_str
Parse one guard expression from source text (a bare guard_seq: predicates, not/any/all, comma lists), for tooling and tests.
parse_script
Parse a script with an unknown host environment.
parse_script_with_exports
Parse without modules plus EXPORT metadata. Used by tests and tooling that lower with the shared mock.
parse_script_with_modules
Parse with a module provenance table so calls resolve statically: qualified MODULE::NAME checks membership, bare NAME resolves through SCRIPT definitions and IMPORTed modules, and anything else fails at parse time instead of at runtime.
parse_script_with_modules_and_exports
Parse with modules plus single-file EXPORT metadata and # doc comments for top-level FUNCs. Used by the MCP host; the linear runner keeps using parse_script_with_modules and ignores exports.
parse_script_with_preseed
Parse a snippet with an enclosing parse’s visible scope state, so re-parsed inner commands (async bodies) resolve calls identically. The snippet never defines, only reads: seeds affect lookup alone.
parse_tokens
Parse a token stream (either lexer) into steps. Markers normalize to 0/0 like the fuzz harness; scopes arrive with block slices.
parse_tokens_with_ctx
Parse with an explicit context (module table for call resolution). parse_tokens uses empty modules.