Skip to content

Land #2–#7 on master - #10

Merged
Demonstrandum merged 35 commits into
masterfrom
blog
Nov 3, 2026
Merged

Demonstrandum merged 35 commits into
masterfrom
blog

Conversation

@Demonstrandum

@Demonstrandum Demonstrandum commented Nov 3, 2026 •

Copy link
Copy Markdown
Owner

#2–#7 were stacked PRs, and each was merged into the branch below it instead of into master, so master only has #1. This branch has all of them, plus the fixes for Bugbot's findings on them, and brings them to master in one go:

Every piece was reviewed and passed CI in its own PR.


Note

Medium Risk
Very large behavioral surface (macro semantics, HTML/CSS assembly, literate parsing, and seam run with %write/%exec), though much of it was reviewed in the stacked PRs and CI now enforces Clippy.

Overview
This lands the stacked work from PRs #2–#7 as seam 0.5.0: a large language and tooling upgrade, not a single narrow fix.

Macro language and expansion adds lexical scoping, %with, lazy ~ parameters, %quote/%eval, %try, typed macro parameters, and a long list of built-ins (conditions, math, list/path helpers, shell-style %{...}, formatter macros, %write/%exec, %error, etc.). The library API now requires an arena-backed Context when expanding; tree_builder_* take Context, a path/stream, and an optional literate flag. Macro call argument checking was rewritten ( regex removed; simpler ArgRule / proc-macro arguments!).

Output and CLI: --literate and literate %include/%embed/%markdown keep plain text and only expand (%...). seam run expands for side effects only and echoes actions on STDOUT (like make). HTML generation plans full documents (doctype, html/head/body, metadata routing) instead of string-wrapping; pre can preserve verbatim source when nothing inside was macro-expanded; :style and related attributes accept s-expression property lists. CSS output gains selector functions (e.g. :nth-child). Formatters no longer use RefCell/unsafe nested registration—shared generate_nodes/generate_children helpers instead.

Project hygiene: workspace moves to Rust 2024, unsafe_code = forbid, workspace Clippy in CI, typed-arena for lifetimes. Docs (README checklist, USAGE.md) and a samples/blog static site driven by seam run build.sex document the new workflow.

Reviewed by Cursor Bugbot for commit b6d9d84. Bugbot is set up for automated code reviews on this repo. Configure here.

- 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
`&amp;`). 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.
@Demonstrandum
Demonstrandum merged commit d73cd1b into master Nov 3, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant