Repository navigation
Literate mode - #8
Closed
Demonstrandum wants to merge 28 commits into
Closed
Demonstrandum wants to merge 28 commits into
Demonstrandum wants to merge 28 commits into
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.
Rewrite arguments!, remove dead API, fix small TODOs
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.
❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.
Reviewed by Cursor Bugbot for commit 2009ea5. Configure here.
| _ => return Err(GenerationError::new("XML", | ||
| &format!("Unexpected {} node when generating.", node.node_type()), | ||
| &node.site())) | ||
| node.site())) |
There was a problem hiding this comment.
Literate output rejected by XML and CSS
Medium Severity
Literate parsing emits text as Raw nodes, but the XML and CSS formatters still treat Raw as unexpected and error. seam --xml --literate or seam --css --literate therefore fails on ordinary text, while HTML and plain-text formatters accept it.
Additional Locations (2)
Reviewed by Cursor Bugbot for commit 2009ea5. Configure here.
Owner
Author
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.


Note
Medium Risk
Large behavioral and breaking library API changes (Context, HTML document wrapping, scoping) across parsing, expansion, and assembly, though covered by extensive new tests.
Overview
Seam 0.5.0 adds literate mode: plain text is preserved and only
(%...)regions are parsed, with--literate,:literateon%include/%embed, and literate-by-default%markdown(including frontmatter/content split). Lexical scoping and%withfor dynamic top-level overrides are implemented, with docs and tests for closures, namespaces, and layout metadata.HTML/CSS output is reworked: fragments get browser-like auto-wrapping (
doctype/html/head/body, metadata into<head>until content), smarter<pre>(verbatim source vs expanded/plain-text), escaped attribute values, and CSS selector functions such as:nth-child.Internals: expansion goes through an arena-backed
Context; sources useSourceFile/Sitewith borrowedCownodes; formatters drop unsafe nestedCloneBoxregistration in favor of staticgenerate_nodes/generate_children; macro arg checking dropsregexfor compile-timearguments!rules. Workspace moves to Rust 2024,unsafeforbidden, Clippy in CI, and library entry points now requireContext::new().Reviewed by Cursor Bugbot for commit 2009ea5. Bugbot is set up for automated code reviews on this repo. Configure here.