Repository navigation
Lazy lists within the interpreter - #9
Merged
Merged
Conversation
- Set the workspace edition to 2024; crates now inherit it. - Apply the edition migration (redundant `ref` binding modifiers). - Drop `box_patterns` (removed from nightly, and unused), plus the unused `associated_type_defaults` and `proc_macro_span` features.
- `MarkupFormatter` now carries the source lifetime, so formatter errors no longer borrow the formatter. Nested formatters can be plain locals instead of being pushed into a `Vec` through a raw pointer. - Drop `CloneBox`/`impl_clone_box!`, whose pointer cast was undefined behaviour, and which nothing needs any more. - Drop `register_invocation`. It only existed to extend a borrow, and references into its growing `Vec` dangled on reallocation (crashing e.g. `samples/tests/html-test-1.sex` and `%sort :key (%lambda ...)`). - Use safe string slicing in the lexer and `escape_xml`. - Name the elided lifetimes rustc warned about.
A new `Context` owns every parsed source file and every scope in `typed_arena` arenas, so parse trees can borrow source code for as long as the context lives. This replaces the raw-pointer subparser and subcontext vectors, which dangled on reallocation and freed included sources while nodes still pointed into them. Scopes are now a chain of `Scope`s pointing to their parent, and `Expander` is a `Copy` view of a context at one scope. Entering a scope no longer clones every definition, parser and source file. Callers still create the scope a macro body runs in, so scoping stays dynamic for now. Callers now create a `seam::Context` and pass it to `tree_builder*`.
Macros now remember the scope they were defined in, and their bodies (and variables' values) expand in a new scope nested inside it, rather than inside the caller's scope. As a result: - Closures work: `(%define (adder n) (%lambda (x) %n %x))` returns a lambda that still sees `n` after `adder` has returned. - A macro no longer sees its caller's parameters or local definitions. - Macros defined in a `%namespace` keep using the namespace's own helpers, rather than failing to find them or using the caller's. Each evaluation of `%lambda` now gets a unique name from a counter, defined at the top-level so it can be applied wherever it is passed. Previously the name came from the call site, so lambdas made by the same `%lambda` expression (in a loop, or repeated calls) clashed.
`(%with (:title "Cake") (%layout))` expands its body with `%title` overriding any top-level definition of `title`, including inside any macros called from the body, such as a shared layout. Bindings are checked just before the top-level scope, so they never override local definitions such as macro parameters, nor helpers in a `%namespace`. The bindings are evaluated eagerly and may come from any expression giving keyword-value pairs, e.g. `(%with %meta ...)` with `&&meta`.
The version bump reflects the change in scoping semantics and the new `Context` argument to `tree_builder*`.
- Add `[workspace.lints]`: forbid `unsafe_code`, warn on `clippy::pedantic`, allowing only `missing_errors_doc`, `too_many_lines` and `items_after_statements`. - Fix every remaining warning: inline format arguments, `#[must_use]` on pure methods, take slices instead of unconsumed boxed parameters, merge identical match arms, canonical `Ord`/`PartialOrd` for glob sorting, let-else, etc. - Fix a panic in the CSS formatter when a rule has no selector: the error path unwrapped an empty iterator. - Fix the `Mandatroy` typo in the argument proc macro. - Remove a commented-out `IntoValue` impl.
`document()` used to search up to two levels deep for `html`, `head` and `body` anywhere in the tree, then add opening and closing tags around the generated text. This put an explicit `(head)` inside `<body>`, put loose `(title)` in the body, left `(html ...)` without a head or body, skipped all wrapping whenever a doctype was present, and treated `(div (body ...))` as the document body. Now `normalize_document` rearranges the tree into `(!DOCTYPE html) (html (head ...) (body ...))` before generating, looking only at the top-level and inside `(html ...)`. Like the HTML parsing algorithm, loose metadata goes into the head until the first piece of content, after which everything goes into the body. Explicit elements and their attributes are kept, and a complete document passes through untouched. Duplicate `head`/`body` elements, a `head` after content, and content outside `(html ...)` are reported as errors.
In literate mode, source is plain text kept exactly as written (as raw nodes), and only macro calls `(%...)` are parsed, using the existing list parser. `\(%` gives a literal `(%`. - `--literate` command line option, and a `literate` argument to the `tree_builder*` functions. - `:literate true` option for `%include`, and for `%embed`, which then expands the file's macros instead of returning its contents. - `%markdown` is literate by default (`:literate false` disables it); elements produced by macros within it are written as HTML. The expansion of a macro call written in the source now takes the call's leading whitespace, as built-in macros and variables already did, so `Hi (%name).` gives `Hi Sam.` rather than `Hi Sam.`.
The escaped character was consumed with `consume_char`, which already counts a new line, and then counted again.
`pre` copied the source text between its first and last tokens, so `(pre (%embed "file"))` wrote out the macro call rather than the file, and contents from another file hit an assertion and crashed. Now the source text is only copied when it contains no macro calls, and otherwise the expanded contents are written as plain-text.
- Expansion borrows its input: `expand_node`/`expand_nodes` take references and `expand_into` appends to a single output buffer, instead of moving owned subtrees and boxing every node's result. Macro bodies are no longer copied on every call. - Built-in macros take their arguments as a slice of the call node. The first argument's leading whitespace is now removed by the parser, rather than by copying every call's arguments at expansion time. - Macros live in the context's arena and are referred to as `&'a Macro`, replacing `Rc<Macro>`. Values (`%define x ...`, parameters, `%with` bindings) are stored directly, already expanded, and are no longer expanded again on every use. - A scope remembers if a macro was defined within it (`captured`). Uncaptured scopes are cleared and reused once a call, `%for` iteration or `%match` arm finishes, so memory grows with the depth of calls rather than their number (2,000 recursive calls with a 2,000 element argument: 951 MiB to 10 MiB, 0.87s to 0.39s). - An attribute whose value expands to nothing is now an error, rather than a panic from indexing an empty expansion.
- Every formatter now writes straight from the borrowed tree, with `generate_nodes`/`generate_children` taking slices and each node writer taking the leading whitespace to write. Previously each element copied its children (`rest.to_vec()`) and wrapped them in a new formatter, copying every subtree once per level of nesting. - HTML `document()` no longer builds a rearranged copy of the whole tree: `plan_document` sorts out the doctype, `html`, `head` and `body` as references to the written nodes, which are then written directly. Output is unchanged. 50,000 macro calls: 1.62s, 2364 MiB to 0.34s, 542 MiB. A 9.6 MB document: 1.37s, 2198 MiB to 0.60s, 875 MiB.
Node values, keywords and leading whitespace are now `Cow<'a, str>`, borrowed from the source text, and only allocated when an escape has to be removed or a macro produces new text. `ParseNode::leading_whitespace` returns the `Cow`, so copying whitespace between nodes stays a borrow. Literate text is likewise borrowed unless it contains `\(%` escapes.
`Site` held two fat string references (path and code) and four `usize` fields, taking 64 bytes on every node and token. It now refers to a `SourceFile` (owned by the lexer) and uses `u32` line and offsets: 24 bytes. `site.source` and `site.source_code` become methods. A parse node goes from 208 to 128 bytes. 50,000 macro calls: 493 MiB to 279 MiB; a 9.6 MB document: 798 MiB to 519 MiB.
`peek` lexed the next token and then rewound, and the parser peeks twice before consuming, so every token was lexed three times. The looked-ahead token is now kept (as byte ranges, so the lexer does not borrow from itself) and reused while the lexer is still at the position it was looked ahead from.
- `%get` walks its path by reference, copying only the result, rather than copying the whole list at every step. - `%reverse`, `%splat` and `%with` move the nodes they already own. - The YAML/TOML loaders move node lists in and out of nested collections rather than copying them. - Elements within literate Markdown are written straight into the text. - The argument parser matches on the `ArgPos` enum instead of boxing a `dyn ArgMatcher` for every argument and every lookup, and keys named arguments by borrowed `&str` instead of an owned `String`.
The `arguments!` proc macro generated code which cloned every argument out of the macro's parameters. The generated argument struct now holds references (`&'p Node<'a>`, `&'p [ParseNode<'a>]`, `&'p ParseNode<'a>`), so built-in macros only copy what they keep, e.g. the items `%sort` returns, or a lambda's body. `ArgParser::get` returns references with the parameters' lifetime rather than the parser's. This also removes the double copy of list arguments, which were cloned out of the parameters and then cloned again by `to_vec`.
`pre` copied source text from its first node to its closing parenthesis, deciding whether macros had been expanded by searching that text for `(%`. That wrote `(pre (%do x) y)` as `x) y`, left variables like `%name` unexpanded, dropped comments before the first node, switched modes on a literal `(%` in a string, and never escaped the text. Now the text is copied only when every node inside is exactly as written: from the same file, in order, with only whitespace and comments between them. Expanding a macro or variable always breaks this, so it is detected from the tree rather than the text. The copied text starts right after the tag and its attributes, so comments and spacing are kept. Otherwise, the expanded contents are written as plain-text. The text of `pre`, `title` and `textarea` is now escaped, so e.g. `(textarea </textarea><script>...)` can no longer inject markup. Escaping is written straight to the output through `write_escaped`, rather than building a new string for every text node.
Attribute values were written between quotes as-is, so a value containing a quote could end the attribute and add others, e.g. `(p :x "a\" onclick=\"f()" ...)` gave `<p x="a" onclick="f()">`. Values are now escaped (so `&` in URLs is also written correctly as `&`). The XML formatter writes attributes directly instead of formatting each into a new string, and no longer panics if given a node which is not an attribute.
…llocation. The schema is parsed with syn instead of a token state machine. Each call now matches arguments by position and keyword directly against constant rules, instead of building rule vectors, hash maps and owned strings per call. Missing mandatory arguments are counted per position (not per rule), repeated named arguments are an error, and the call node is passed explicitly instead of being picked up from the caller's scope. The unused ArgParser, extract_* helpers and regex dependency are removed.
…atoms. `:style (:color red)` becomes CSS declarations and `:class (a b)` a space-separated list. A raw string (e.g. from a formatter macro) is accepted as a style's CSS. S-expression output separates adjacent atoms which lost their whitespace in expansion.
…formatters.
New built-in macros:
- %if, %not, %and, %or, and comparisons (= != < > <= >=);
- arithmetic (+ - * / mod pow min max, exp sqrt ln log2 log10 abs
floor ceil round hypot) and %range;
- %take, %drop, %while, %split, %intercalate, %length, and %items,
%keys, %values for keyword lists; %get takes slices and negative
indices;
- %basename, %dirname, %extension; %write and %exec;
- %error and %try; %let; %quote and %eval;
- %formatter/html, xml, css, text and sexp;
- shell-style %{name...} variable manipulation.
User macros gain lazy parameters (~name, ~&rest), expanded where the
caller wrote them each time they are used, and typed parameters
(n:number, &xs:string, 🔑string default). %for now iterates over
whatever its list expression expands to, so (%for x in %xs ...) and
(%for (k v) in (%items %d) ...) work.
…nique, %contains. - %include and %embed look for files relative to the including file first, then in the include directories. - Macro calls inside Markdown code blocks and spans are shown as written, not expanded (otherwise a post quoting seam runs it). - %unique and %contains, for collecting and filtering tags. - %timestamp accepts a date without a time (as midnight). - "false" counts as false, as YAML and TOML booleans arrive as strings. - %intercalate keeps the separator's whitespace, not the items'.
Markdown posts with frontmatter, a shared layout, an index sorted by date, a tags page and an RSS feed, all generated by build.sex with %write and the formatter macros. Drafts are left out.
- `seam run file.sex` expands a file only for its side effects, echoing each `%write`, `%exec` and `%log` on STDOUT. - %path/cwd, this-file, this-directory, join, split, stem, with-extension, normalise, canonical, absolute, relative, exists, is-file, is-directory. - The blog builds with `seam run` from any directory, using write/html.
- XML and CSS write literate (Raw) text as it is, instead of failing. - Markdown content is rendered without frontmatter parsing once its frontmatter is split off, so a body starting with --- is kept. - %exec writes :stdin from another thread, so large input and output cannot deadlock on full pipes. - Typed lazy parameters (~n:number) are checked once expanded, each time they are used, instead of in their unexpanded form. - %embed sites its text in the embedded file, and %markdown names its literate source after that file, so %include, %embed and %path/this and %path/here within markdown work relative to the markdown file.
List nodes hold a List, which is either realised items or a lazy description of them: a range, a slice of a list, a list reversed, or lists chained together. Lazy lists make their items one at a time with len, item and items, and only realise (and keep) them all when dereferenced as a slice. %range, %take, %drop, %get slices, %reverse and %concat (now also of lists) make lazy lists, and %for, %length, %get, %while and %contains use them without realising. The language itself is unchanged.
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 2 potential issues.
❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.
Reviewed by Cursor Bugbot for commit c280593. Configure here.
A leading empty list in %concat no longer spaces out the first item. %get no longer realises a lazy list when looking up a keyword, and a numeric index out of bounds fails at once instead of searching the list for an attribute.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.

Lists stay ordinary lists in the language, but are lazy inside the interpreter: their items are made only as far as they are needed, and realised into a real list only when something needs them all.
Design
ParseNode::List'snodesis now aList(parse/list.rs), which is either realised items or a lazy description of them:first,step, length),List::len,List::item(i)andList::items()work without realising anything.Listdereferences to[ParseNode], realising (and caching, in aOnceCell) on first use, so every other piece of code, including the formatters, keeps working unchanged.DerefMutturns the list into owned realised items.arguments!now giveslistarguments as&List, so checking a macro's arguments never realises a list.What is lazy
%range: no longer capped at a million items, and the length is computed exactly for whole numbers.%takeand%drop,%get (first last)slices,%reverse.%concatof lists (new:(%concat (a b) (c))gives(a b c), just as it joins text). This is the chain.%foriterates items one at a time and never realises its list.%lengthand%get indexstay O(1), and%whileand%containsstop early.So
(%for i in (%take 3 (%range 1 1000000000000)) %i)or(%get 1000 (%range 0 1000000000000 2))finish at once.%mapand%filterstay eager. Their predicates are macros that can fail or have side effects, so running them lazily would change when errors and effects happen.Checks
New
test_lazy_lists(46 tests in total), clippy clean, andsamples/blogbuilds the same.Note
High Risk
Touches the parser, expander, and all formatters—the core compilation path—with new memory/lifetime model (
Context,List,Site/SourceFile) and many new language behaviors, so regressions could affect any macro or output format.Overview
Bumps seam to 0.5.0 with Rust 2024, workspace Clippy lints (including CI), drops the
regexdependency from macro argument parsing, and addstyped-arenafor expansion storage.Lazy lists replace eager
Box<[ParseNode]>in list nodes with a newListtype:%range, slices from%get,%take/%drop,%reverse, and%concatcan stay as descriptions until something needs a full slice (viaDeref/OnceCell).%forwalks items withList::itemwithout materialising huge sequences;%map/%filterstay eager so predicate side effects and errors behave as before. Macroarguments!passes lists as&Listso arity checks do not force realisation.Alongside that, the PR lands the broader 0.5.x platform: a shared
Contextfor files/scopes/lexical binding, literate parsing (--literate, raw text +(%macros),seam runfor side-effect macros, automatic HTML document wrapping, richer HTML/CSS generation (attributes,preverbatim source, selector functions), refactored formatters without the old unsafe formatter registry, and large README/USAGE updates plus new test fixtures.Reviewed by Cursor Bugbot for commit f56f088. Bugbot is set up for automated code reviews on this repo. Configure here.
Built on #10; merge that first, and this diff shrinks to just the lazy lists.