From 05e4ce9c523151400270d1205600d107a10d5c8b Mon Sep 17 00:00:00 2001 From: Demonstrandum Date: Tue, 3 Nov 2026 02:26:39 +0000 Subject: [PATCH 1/6] Features for building a blog: relative includes, code in Markdown, %unique, %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'. --- USAGE.md | 15 ++- crates/seam/src/parse/expander.rs | 120 +++++++++++++++++--- crates/seam/src/tests.rs | 19 ++++ crates/seam/tests/fixtures/code.md | 8 ++ crates/seam/tests/fixtures/nested/inner.sex | 1 + crates/seam/tests/fixtures/nested/outer.sex | 1 + 6 files changed, 146 insertions(+), 18 deletions(-) create mode 100644 crates/seam/tests/fixtures/code.md create mode 100644 crates/seam/tests/fixtures/nested/inner.sex create mode 100644 crates/seam/tests/fixtures/nested/outer.sex diff --git a/USAGE.md b/USAGE.md index 951dc8c..6a6e958 100644 --- a/USAGE.md +++ b/USAGE.md @@ -92,7 +92,8 @@ Literate mode is enabled with: Elements produced by macros within Markdown are written as HTML. Frontmatter and content are expanded separately, so `:only frontmatter` or `:only content` expands just that part, and the content can use the - frontmatter's definitions. + frontmatter's definitions. Macro calls inside code (blocks and spans) are + shown as written, not expanded. ## Macros @@ -106,7 +107,9 @@ will be treated as macros. - `%ifdef` checks if a symbol is defined, e.g. `(ifdef username (span Hello %username))`, or with an else-clause: `(ifdef title (title My Blog - %title) (title My Blog))`. - `%include` will include an entire file's contents into another, e.g. - `(%include "components/footer.sex")`. + `(%include "components/footer.sex")`. Paths are looked up relative to the + including file first, then in each include directory (`-I`, and the + working directory). `%embed` finds files the same way. - `%date` standard `strftime` function, works of current system time, e.g. `(span :id timestamp Uploaded on (%date "%Y-%m-%d"))`. - `%log` will simply log any information to STDERR, e.g. `(%log Hello, World!)`. @@ -117,7 +120,8 @@ will be treated as macros. #### Conditions and arithmetic - `(%if condition then else)` expands only the chosen branch. Nothing, `()`, - `false` and `""` are false; anything else is true. + `false` (or `"false"`, as YAML and TOML booleans arrive) and `""` are false; + anything else is true. - `%not`, `%and` and `%or`, where `%and` and `%or` stop expanding their arguments as soon as the answer is known. - Comparisons `%=`, `%!=`, `%<`, `%>`, `%<=` and `%>=` (numbers by value, @@ -137,6 +141,7 @@ will be treated as macros. - `(%split , "a,b")` gives `("a" "b")`; `(%split | (a b | c))` gives `((a b) (c))`. - `(%intercalate ", " %tags)` puts the separator between the items (unwrapped). - `(%length list)` counts items, or the characters of a string. +- `(%unique list)` drops repeated items; `(%contains item list)` tests membership. - `(%items dict)`, `(%keys dict)` and `(%values dict)` for keyword lists: `(%for (key value) in (%items (:a 1 :b 2)) ...)`. - `%for` iterates over the items of the list its expression gives @@ -299,3 +304,7 @@ let tree = expander.expand()?; This way you can easily construct websites with reusable components, cut down on copy-pasting, and generate it statically. Ideal for a blog, especially using the `(%markdown ...)` macro. + +See [`samples/blog`](samples/blog) for a whole blog: Markdown posts with +frontmatter, a shared layout, a tags page and an RSS feed, all generated by +`seam --text build.sex` with `%write` and the formatter macros. diff --git a/crates/seam/src/parse/expander.rs b/crates/seam/src/parse/expander.rs index a77f5a0..42b055c 100644 --- a/crates/seam/src/parse/expander.rs +++ b/crates/seam/src/parse/expander.rs @@ -707,6 +707,19 @@ impl<'a> Expander<'a> { expanded } + /// Directories to look for a file named at `site` in: first the directory + /// of the file it is written in (if it is a file), then the include directories. + fn search_directories(&self, site: &Site<'a>) -> Vec { + let includes = self.context.includes.borrow(); + let mut directories = Vec::with_capacity(includes.len() + 1); + let source = std::path::Path::new(site.source()); + if source.is_file() && let Some(parent) = source.parent() { + directories.push(parent.to_path_buf()); + } + directories.extend(includes.iter().cloned()); + directories + } + /// Parse and expand literate source: plain text with embedded `(%...)` macro calls. fn expand_literate(&self, name: String, source: String, site: &Site<'a>) -> Result, ExpansionError<'a>> { @@ -732,7 +745,7 @@ impl<'a> Expander<'a> { let mut parser: Result = Err( include_error(Box::new("No path tested."))); // Try all include directories until one is successful. - for include_dir in self.context.includes.borrow().iter() { + for include_dir in self.search_directories(site) { let path = include_dir.join(&**path); parser = super::parser_for_file(&path, literate) .or_else(|err| { @@ -784,7 +797,7 @@ impl<'a> Expander<'a> { let mut value: Result = Err( embed_error(Box::new("No path tested."))); // Try all include directories until one is successful. - for include_dir in self.context.includes.borrow().iter() { + for include_dir in self.search_directories(site) { let path = include_dir.join(&**path); value = std::fs::read_to_string(path) .map_err(|err| embed_error(Box::new(err))); @@ -863,7 +876,7 @@ impl<'a> Expander<'a> { // Split off the frontmatter first, so that literate expansion // only runs over the part (or parts) actually being used. - let (frontmatter, body) = split_frontmatter(contents, &options.parse) + let MarkdownParts { frontmatter, body, code } = split_frontmatter(contents, &options.parse) .map_err(markdown_error)?; // Expand any `(%...)` calls in a part, keeping line numbers // relative to the whole string by padding with new lines. @@ -892,7 +905,9 @@ impl<'a> Expander<'a> { }; // Render the markdown content as raw HTML. let to_html = |(body, line): (&str, usize)| -> Result, ExpansionError<'a>> { - let body = expand(body, line)?; + // Macro calls within code are shown, not expanded. + let body = if literate && !code.is_empty() { Cow::Owned(escape_ranges(body, &code)) } else { Cow::Borrowed(body) }; + let body = expand(&body, line)?; let html = markdown::to_html_with_options(&body, &options) .map_err(markdown_error)?; Ok(Box::new([ @@ -1091,7 +1106,12 @@ impl<'a> Expander<'a> { datetime.timestamp() } else { // Parse NaiveDateTime instead and get timzone from attribute, or default to local time. - let datetime = match chrono::NaiveDateTime::parse_from_str(date_string, format) { + // A date without a time is taken to be at midnight. + let datetime = chrono::NaiveDateTime::parse_from_str(date_string, format) + .or_else(|err| chrono::NaiveDate::parse_from_str(date_string, format) + .map(|date| date.and_time(chrono::NaiveTime::MIN)) + .map_err(|_| err)); + let datetime = match datetime { Ok(datetime) => datetime, Err(err) => return Err(ExpansionError( format!("Failed to parse date: {err}"), @@ -2128,16 +2148,51 @@ impl<'a> Expander<'a> { let Some((separator, list)) = params.split_first() else { return Err(ExpansionError::new("Expected a separator, and a list.", node.site())); }; + // The separator's whitespace is kept, but not the items' own. let mut expanded = vec![]; for (index, item) in list_argument(list).iter().enumerate() { + let mut item = item.clone(); if index > 0 { expanded.push(separator.clone()); + item.set_leading_whitespace(""); } - expanded.push(item.clone()); + expanded.push(item); + } + if let Some(first) = expanded.first_mut() { + first.set_leading_whitespace(node.leading_whitespace().clone()); } Ok(expanded.into_boxed_slice()) } + /// `(%unique list)`, the list without repeated items (keeping the first of each). + fn expand_unique_macro(&self, node: &ParseNode<'a>, params: &[ParseNode<'a>]) + -> Result, ExpansionError<'a>> { + let params = self.expand_nodes(params)?; + let mut seen = std::collections::HashSet::new(); + let mut items = vec![]; + for item in list_argument(¶ms) { + if seen.insert(node_text(item)?) { + items.push(item.clone()); + } + } + Ok(Box::new([list_node(node, without_leading(items))])) + } + + /// `(%contains item list)`, whether the list has an item equal to the given one. + fn expand_contains_macro(&self, node: &ParseNode<'a>, params: &[ParseNode<'a>]) + -> Result, ExpansionError<'a>> { + let params = self.expand_nodes(params)?; + let Some((item, list)) = params.split_first() else { + return Err(ExpansionError::new("Expected an item, and a list.", node.site())); + }; + let item = node_text(item)?; + let mut found = false; + for other in list_argument(list) { + found |= node_text(other)? == item; + } + Ok(Box::new([bool_node(node, found)])) + } + /// `(%length list)` counts a list's items, `(%length text)` its characters. fn expand_length_macro(&self, node: &ParseNode<'a>, params: &[ParseNode<'a>]) -> Result, ExpansionError<'a>> { @@ -2608,6 +2663,8 @@ impl<'a> Expander<'a> { "split" => self.expand_split_macro(node, params), "intercalate" => self.expand_intercalate_macro(node, params), "length" => self.expand_length_macro(node, params), + "unique" => self.expand_unique_macro(node, params), + "contains" => self.expand_contains_macro(node, params), "items" | "keys" | "values" => self.expand_dictionary_macro(name, node, params), "basename" | "dirname" | "extension" => self.expand_path_macro(name, node, params), "write" => self.expand_write_macro(node, params), @@ -2737,11 +2794,12 @@ fn list_argument<'p, 'a>(arguments: &'p [ParseNode<'a>]) -> &'p [ParseNode<'a>] } /// Whether expanded nodes count as true: nothing, `()`, `false` and `""` are false. +/// (`"false"` is false too, being how YAML and TOML booleans arrive.) fn truthy(nodes: &[ParseNode]) -> bool { match nodes { [] => false, [node] => !(node.null() - || node.symbol().is_some_and(|symbol| symbol.value == "false") + || node.atomic().is_some_and(|atom| atom.value == "false") || node.string().is_some_and(|string| string.value.is_empty())), _ => true, } @@ -3033,22 +3091,54 @@ enum Frontmatter { Toml(String), } -/// Split markdown into its frontmatter (if any) and the rest of the -/// document, along with the line the rest starts on (counting from 0). +/// Markdown split into its frontmatter (if any) and the rest of the document, +/// along with the line the rest starts on (counting from 0), and the byte +/// ranges of code (blocks and spans) within the rest. +struct MarkdownParts<'s> { + frontmatter: Option, + body: (&'s str, usize), + code: Vec>, +} + fn split_frontmatter<'s>(contents: &'s str, options: &markdown::ParseOptions) --> Result<(Option, (&'s str, usize)), markdown::message::Message> { +-> Result, markdown::message::Message> { use markdown::mdast; - let mdast::Node::Root(root) = markdown::to_mdast(contents, options)? else { - unreachable!() - }; + fn find_code(node: &mdast::Node, code: &mut Vec>) { + match node { + mdast::Node::Code(mdast::Code { position: Some(position), .. }) + | mdast::Node::InlineCode(mdast::InlineCode { position: Some(position), .. }) => + code.push(position.start.offset..position.end.offset), + _ => for child in node.children().into_iter().flatten() { + find_code(child, code); + }, + } + } + let ast = markdown::to_mdast(contents, options)?; + let mut code = vec![]; + find_code(&ast, &mut code); + let mdast::Node::Root(root) = ast else { unreachable!() }; let (frontmatter, position) = match root.children.into_iter().next() { Some(mdast::Node::Yaml(mdast::Yaml { value, position })) => (Frontmatter::Yaml(value), position), Some(mdast::Node::Toml(mdast::Toml { value, position })) => (Frontmatter::Toml(value), position), - _ => return Ok((None, (contents, 0))), + _ => return Ok(MarkdownParts { frontmatter: None, body: (contents, 0), code }), }; let end = position.map_or(0, |position| position.end.offset); let (head, body) = contents.split_at(end); - Ok((Some(frontmatter), (body, head.matches('\n').count()))) + let code = code.into_iter().map(|range| range.start - end..range.end - end).collect(); + Ok(MarkdownParts { frontmatter: Some(frontmatter), body: (body, head.matches('\n').count()), code }) +} + +/// Escape macro calls within the given ranges of text, so literate expansion leaves them be. +fn escape_ranges(text: &str, ranges: &[std::ops::Range]) -> String { + let mut escaped = String::with_capacity(text.len()); + let mut last = 0; + for range in ranges { + escaped += &text[last..range.start]; + escaped += &text[range.clone()].replace("(%", "\\(%"); + last = range.end; + } + escaped += &text[last..]; + escaped } /// Join expanded nodes back into text, such as for markdown: text and atoms diff --git a/crates/seam/src/tests.rs b/crates/seam/src/tests.rs index 598fcb2..fbedce0 100644 --- a/crates/seam/src/tests.rs +++ b/crates/seam/src/tests.rs @@ -518,6 +518,25 @@ mod cases { assert!(sexp("(%exec false)").unwrap_err().contains("`%exec false' failed")); } + #[test] + fn test_relative_include() { + // a file's includes are found relative to it first. + assert_sexp_eq("(%include \"tests/fixtures/nested/outer.sex\")", "(found inner)"); + } + + #[test] + fn test_markdown_code_is_not_expanded() { + assert_output_eq("(%markdown :only content (%embed \"tests/fixtures/code.md\"))", + "\"

Text 2, (%+ 1 1) and:

\\n
(%+ 1 1)\\n
\\n\""); + } + + #[test] + fn test_unique_contains_and_dates() { + assert_sexp_eq("(%unique (a b a c b)) (%contains b (a b)) (%contains z (a b)) (%if \"false\" y n)", + "(a b c) true false n"); + assert_sexp_eq("(%timestamp \"%Y-%m-%d\" 2024-03-10 :timezone 0)", "1710028800"); + } + #[test] fn test_escaped_newline_line_numbers() { // an escaped new line in a symbol only counts as one line. diff --git a/crates/seam/tests/fixtures/code.md b/crates/seam/tests/fixtures/code.md new file mode 100644 index 0000000..37e52c0 --- /dev/null +++ b/crates/seam/tests/fixtures/code.md @@ -0,0 +1,8 @@ +--- +title: Code +--- +Text (%+ 1 1), `(%+ 1 1)` and: + +``` +(%+ 1 1) +``` diff --git a/crates/seam/tests/fixtures/nested/inner.sex b/crates/seam/tests/fixtures/nested/inner.sex new file mode 100644 index 0000000..f6693dd --- /dev/null +++ b/crates/seam/tests/fixtures/nested/inner.sex @@ -0,0 +1 @@ +(found inner) diff --git a/crates/seam/tests/fixtures/nested/outer.sex b/crates/seam/tests/fixtures/nested/outer.sex new file mode 100644 index 0000000..86a9180 --- /dev/null +++ b/crates/seam/tests/fixtures/nested/outer.sex @@ -0,0 +1 @@ +(%include "inner.sex") From a0f9385195b7797b8eb53cb3f4c6e878a8dc67a1 Mon Sep 17 00:00:00 2001 From: Demonstrandum Date: Tue, 3 Nov 2026 02:26:39 +0000 Subject: [PATCH 2/6] Add a working blog example, realising the blog concept. 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. --- samples/blog/.gitignore | 1 + samples/blog/README.md | 24 ++++++++ samples/blog/build.sex | 21 +++++++ samples/blog/feed.sex | 20 +++++++ samples/blog/includes/footer.sex | 3 + samples/blog/includes/header.sex | 6 ++ samples/blog/index.sex | 7 +++ samples/blog/post.sex | 7 +++ samples/blog/posts/hello-world.md | 15 +++++ samples/blog/posts/macros.md | 24 ++++++++ samples/blog/posts/one-file-many-pages.md | 25 +++++++++ samples/blog/posts/unfinished.md | 8 +++ samples/blog/site.sex | 67 +++++++++++++++++++++++ samples/blog/style.sex | 55 +++++++++++++++++++ samples/blog/tags.sex | 16 ++++++ 15 files changed, 299 insertions(+) create mode 100644 samples/blog/.gitignore create mode 100644 samples/blog/README.md create mode 100644 samples/blog/build.sex create mode 100644 samples/blog/feed.sex create mode 100644 samples/blog/includes/footer.sex create mode 100644 samples/blog/includes/header.sex create mode 100644 samples/blog/index.sex create mode 100644 samples/blog/post.sex create mode 100644 samples/blog/posts/hello-world.md create mode 100644 samples/blog/posts/macros.md create mode 100644 samples/blog/posts/one-file-many-pages.md create mode 100644 samples/blog/posts/unfinished.md create mode 100644 samples/blog/site.sex create mode 100644 samples/blog/style.sex create mode 100644 samples/blog/tags.sex diff --git a/samples/blog/.gitignore b/samples/blog/.gitignore new file mode 100644 index 0000000..364fdec --- /dev/null +++ b/samples/blog/.gitignore @@ -0,0 +1 @@ +public/ diff --git a/samples/blog/README.md b/samples/blog/README.md new file mode 100644 index 0000000..c3e0309 --- /dev/null +++ b/samples/blog/README.md @@ -0,0 +1,24 @@ +# A blog in seam + +A small but complete blog, built from the ideas in [`../blog-concept`](../blog-concept): +a shared layout, posts listed on an index by date, a tags page and an RSS feed. + +```sh +cd samples/blog +seam --text build.sex # Writes the site into public/. +``` + +- `site.sex` defines everything shared: the site's details, `%posts` (every + post's frontmatter, without drafts, newest first) and the `%page` layout. +- `posts/*.md` are the posts, in Markdown with YAML frontmatter + (`title`, `date`, `tags`, `description`, and `draft: true` to leave one out). + Markdown is literate, so posts may call macros, e.g. `(%length %posts)`. +- `index.sex`, `tags.sex` and `feed.sex` are pages, which can each be rendered + alone (`seam --html index.sex`, `seam --xml feed.sex`), while `post.sex` + renders a post given its details by `%with`. +- `build.sex` renders every page with a formatter macro + (`%formatter/html :document true ...`) and saves it with `%write`. +- `style.sex` is the stylesheet, in seam's CSS syntax. + +Paths (`%glob`, `%write`) are relative to the working directory, so run +`seam` from this directory. diff --git a/samples/blog/build.sex b/samples/blog/build.sex new file mode 100644 index 0000000..1b98fa8 --- /dev/null +++ b/samples/blog/build.sex @@ -0,0 +1,21 @@ +;; Builds the whole site into `public/`. Run it from this directory: +;; seam --text build.sex +;; Each page is generated with a formatter macro, and written with `%write`. +(%include "site.sex") + +(%define (write-html path &content) + (%write (%concat "public/" %path) (%formatter/html :document true %content))) + +(%write-html "index.html" (%include "index.sex")) +(%write-html "tags.html" (%include "tags.sex")) + +(%for post in %posts + (%write-html (%concat "posts/" (%get slug %post) ".html") + (%with %post + (%with (:root "../") + (%include "post.sex"))))) + +(%write "public/feed.xml" (%formatter/xml :document true (%include "feed.sex"))) +(%write "public/style.css" (%formatter/css (%include "style.sex"))) + +(%log Built (%length %posts) posts into public/) diff --git a/samples/blog/feed.sex b/samples/blog/feed.sex new file mode 100644 index 0000000..2c30ea2 --- /dev/null +++ b/samples/blog/feed.sex @@ -0,0 +1,20 @@ +;; An RSS feed of the posts. Render it alone with `seam --xml feed.sex`. +(%include "site.sex") + +(%define (rfc-822 date) + (%date "%a, %d %b %Y %H:%M:%S +0000" (%timestamp "%Y-%m-%d" %date :timezone 0) :timezone 0)) + +(rss :version "2.0" + (channel + (title %site-title) + (link %site-url) + (description Notes on building websites with seam.) + (%for post in %posts + (%let (((:slug _ :title _ :date _ :description _ &&_) %post) + (url (%concat %site-url "posts/" %slug ".html"))) + (item + (title %title) + (link %url) + (guid %url) + (pubDate (%rfc-822 %date)) + (description %description)))))) diff --git a/samples/blog/includes/footer.sex b/samples/blog/includes/footer.sex new file mode 100644 index 0000000..2d54fab --- /dev/null +++ b/samples/blog/includes/footer.sex @@ -0,0 +1,3 @@ +(footer + (p © (%date "%Y") %author · + Built with (a :href "https://github.com/Demonstrandum/seam" seam).)) diff --git a/samples/blog/includes/header.sex b/samples/blog/includes/header.sex new file mode 100644 index 0000000..07775ed --- /dev/null +++ b/samples/blog/includes/header.sex @@ -0,0 +1,6 @@ +(header + (a :class site-title :href (%concat %root "index.html") %site-title) + (nav + (a :href (%concat %root "index.html") Posts) + (a :href (%concat %root "tags.html") Tags) + (a :href (%concat %root "feed.xml") Feed))) diff --git a/samples/blog/index.sex b/samples/blog/index.sex new file mode 100644 index 0000000..dd74296 --- /dev/null +++ b/samples/blog/index.sex @@ -0,0 +1,7 @@ +;; The list of posts. Render it alone with `seam --html index.sex`. +(%include "site.sex") + +(%page + (h1 Posts) + (%for post in %posts + (%post-summary %post))) diff --git a/samples/blog/post.sex b/samples/blog/post.sex new file mode 100644 index 0000000..753ff00 --- /dev/null +++ b/samples/blog/post.sex @@ -0,0 +1,7 @@ +;; A single post, rendered by `build.sex` with the post's details +;; (`%title`, `%date`, `%file`, ...) given by `%with`. +(%page + (article + (h1 %title) + (%post-meta %date %minutes %tags) + (%markdown :only content (%embed %file)))) diff --git a/samples/blog/posts/hello-world.md b/samples/blog/posts/hello-world.md new file mode 100644 index 0000000..c280a72 --- /dev/null +++ b/samples/blog/posts/hello-world.md @@ -0,0 +1,15 @@ +--- +title: Hello, World +date: 2024-03-10 +tags: [meta, seam] +description: Why this site is written in s-expressions. +--- + +Welcome! This site is generated by [seam](https://github.com/Demonstrandum/seam), +from a handful of `.sex` files and some Markdown posts like this one. + +Every page shares one layout, written once as a macro in `site.sex`. +Each page passes its own details to it with `%with`, which is how this page +knows its title is "(%do %title)". + +There are (%length %posts) posts so far. diff --git a/samples/blog/posts/macros.md b/samples/blog/posts/macros.md new file mode 100644 index 0000000..ae3b3eb --- /dev/null +++ b/samples/blog/posts/macros.md @@ -0,0 +1,24 @@ +--- +title: Macros All the Way Down +date: 2024-05-02 +tags: [seam, macros] +description: The index, tags page and feed are all built from macros. +--- + +The list of posts on the index isn't written by hand. `site.sex` globs the +`posts/` directory, reads each post's frontmatter, drops the drafts and +sorts the rest by date: + +```lisp +(%define posts + (%sort :order descending :key (%lambda ((:date _ &&_)) %date) + (%list (%for file in (%glob "posts/*.md") + (%let ((post (%read-post %file))) + (%if (%not (%get draft %post)) %post)))))) +``` + +The reading time beside each post is arithmetic on its word count, and the +tags page is just `%unique` over every post's tags. + +Markdown is *literate*: text is left alone, but macro calls are expanded, +so this sentence can say that two squared is (%pow 2 2). diff --git a/samples/blog/posts/one-file-many-pages.md b/samples/blog/posts/one-file-many-pages.md new file mode 100644 index 0000000..d89699e --- /dev/null +++ b/samples/blog/posts/one-file-many-pages.md @@ -0,0 +1,25 @@ +--- +title: One File, Many Pages +date: 2024-11-02 +tags: [seam, build] +description: How build.sex writes the whole site. +--- + +Normally `seam` turns one file into one document. `build.sex` instead +generates every page itself, with a *formatter macro* to render each one, +and `%write` to save it: + +```lisp +(%for post in %posts + (%write-html (%concat "posts/" (%get slug %post) ".html") + (%with %post + (%with (:root "../") + (%include "post.sex"))))) +``` + +The feed is the same, with `%formatter/xml`, and so is the stylesheet, with +`%formatter/css`. Building the site is then just: + +```sh +seam --text build.sex +``` diff --git a/samples/blog/posts/unfinished.md b/samples/blog/posts/unfinished.md new file mode 100644 index 0000000..b26fe26 --- /dev/null +++ b/samples/blog/posts/unfinished.md @@ -0,0 +1,8 @@ +--- +title: An Unfinished Draft +date: 2024-12-01 +tags: [drafts] +draft: true +--- + +Drafts are left out of the site. diff --git a/samples/blog/site.sex b/samples/blog/site.sex new file mode 100644 index 0000000..f08f1f8 --- /dev/null +++ b/samples/blog/site.sex @@ -0,0 +1,67 @@ +;; Definitions shared by every page: the site's details, its posts and its layout. +;; Including this file defines things, and outputs nothing. + +(%define site-title "Seam Notes") +(%define site-url "https://example.com/") +(%define author "Samuel") +;; The path from a page back to the site's root (pages in a +;; subdirectory override it, with `(%with (:root "../") ...)`). +(%define root "") + +;; A post's details, read from its Markdown frontmatter. +(%define (read-post file:string) + (%markdown :only frontmatter (%embed %file)) + (:file %file + :slug (%basename :suffix md %file) + :title %title + :date %date + :tags (%ifdef tags %tags ()) + :description %{description:-} + :draft %{draft:-false} + :minutes (%max 1 (%round (%/ (%length (%split " " (%embed %file))) 200))))) + +;; Every published post, newest first. +(%define posts + (%sort :order descending :key (%lambda ((:date _ &&_)) %date) + (%list (%for file in (%glob "posts/*.md") + (%let ((post (%read-post %file))) + (%if (%not (%get draft %post)) %post)))))) + +(%define (pretty-date date) + (%date "%B %-d, %Y" (%timestamp "%Y-%m-%d" %date :timezone 0) :timezone 0)) + +(%define (post-url slug) (%concat %root "posts/" %slug ".html")) + +(%define (tag-links tags:list) + (%intercalate ", " + (%for tag in %tags (a :class tag :href (%concat %root "tags.html#" %tag) %tag)))) + +;; The date, reading time and tags of a post. +(%define (post-meta date minutes tags) + (p :class meta + (time :datetime %date (%pretty-date %date)) + · %minutes min read + (%if %tags (%do · (%tag-links %tags))))) + +;; A post's title and summary, as listed on the index. +(%define (post-summary post) + (%let (((:slug _ :title _ :date _ :tags _ :description _ :minutes _ &&_) %post)) + (article :class summary + (h2 (a :href (%post-url %slug) %title)) + (%post-meta %date %minutes %tags) + (p %description)))) + +;; The page skeleton. `%title` and `%root` may be given with `%with`. +(%define (page &body) + (html :lang en + (head + (meta :charset utf-8) + (meta :name viewport :content "width=device-width, initial-scale=1") + (title (%ifdef title (%concat %title " — " %site-title) %site-title)) + (link :rel stylesheet :href (%concat %root "style.css")) + (link :rel alternate :type application/rss+xml + :title %site-title :href (%concat %root "feed.xml"))) + (body + (%include "includes/header.sex") + (main %body) + (%include "includes/footer.sex")))) diff --git a/samples/blog/style.sex b/samples/blog/style.sex new file mode 100644 index 0000000..d738b78 --- /dev/null +++ b/samples/blog/style.sex @@ -0,0 +1,55 @@ +;; The site's stylesheet. Render it alone with `seam --css style.sex`. +(html + :--text "#222" + :--muted "#666" + :--accent "#b5452b" + :--background "#fdfcf9") + +(body + :max-width 42rem + :margin (0 auto) + :padding (0 1rem) + :font-family (Charter, Georgia, serif) + :line-height 1.6 + :color (var --text) + :background (var --background)) + +(header + :display flex + :flex-wrap wrap + :justify-content space-between + :align-items baseline + :padding (1.5rem 0) + :border-bottom (1px solid "#ddd")) + +(header .site-title + :font-size 1.4rem + :font-weight bold + :color (var --text) + :text-decoration none) + +(nav a :margin-left 1rem) + +(a :color (var --accent)) + +(.meta + :color (var --muted) + :font-size 0.9rem) + +(.summary :margin (2rem 0)) +(.summary h2 :margin-bottom 0) +(.summary h2 a + :color (var --text) + :text-decoration none) + +(pre + :padding 1rem + :overflow-x auto + :background "#f3f1ec") + +(footer + :margin-top 3rem + :padding (1rem 0) + :border-top (1px solid "#ddd") + :color (var --muted) + :font-size 0.9rem) diff --git a/samples/blog/tags.sex b/samples/blog/tags.sex new file mode 100644 index 0000000..1e91f57 --- /dev/null +++ b/samples/blog/tags.sex @@ -0,0 +1,16 @@ +;; Every tag, with the posts tagged with it. +(%include "site.sex") + +(%define all-tags + (%sort (%unique (%list (%for post in %posts (%splat (%get tags %post))))))) + +(%with (:title Tags) + (%page + (h1 Tags) + (%for tag in %all-tags + (section :id %tag + (h2 %tag) + (ul + (%for post in %posts + (%if (%contains %tag (%get tags %post)) + (li (a :href (%post-url (%get slug %post)) (%get title %post)))))))))) From e70ad3c57c7d1c71d7f215e17f5ac12af5b7588a Mon Sep 17 00:00:00 2001 From: Demonstrandum Date: Tue, 3 Nov 2026 13:43:41 +0000 Subject: [PATCH 3/6] Add seam run, reporting side effects like make, and %path/... macros. - `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. --- README.md | 10 ++ USAGE.md | 44 +++++- crates/seam/src/bin.rs | 25 ++- crates/seam/src/parse/expander.rs | 181 +++++++++++++++++++++- crates/seam/src/tests.rs | 15 ++ crates/seam/tests/fixtures/here.sex | 1 + samples/blog/README.md | 8 +- samples/blog/build.sex | 23 +-- samples/blog/posts/one-file-many-pages.md | 4 +- samples/blog/site.sex | 2 +- 10 files changed, 282 insertions(+), 31 deletions(-) create mode 100644 crates/seam/tests/fixtures/here.sex diff --git a/README.md b/README.md index 3dbca86..87cb194 100644 --- a/README.md +++ b/README.md @@ -89,6 +89,14 @@ seam --sexp <<< '(hello (%define subject world) %subject)' #stdout: # (hello world) ``` +To run a file only for what its macros do, such as writing files with +`%write`, use `seam run`, which reports each action like `make` does: +```sh +seam run build.sex +#stdout: +# write public/index.html +# ... +``` ## Checklist - [x] Literate mode for parser+lexer, where string nodes are not escaped and parentheses are converted to symbols. @@ -106,6 +114,8 @@ seam --sexp <<< '(hello (%define subject world) %subject)' - [x] Shell-style `${var:...}` string manipulation, written `%{var:...}`. - [x] `%while`, `%take`, `%drop`, `%split` on symbols in lists, `%intercalate`. - [x] `(%basename :suffix "txt" /path/file.txt)` (-> `file`), `(%dirname /path/file.txt)` (-> `/path`) and `(%extension /path/file.txt)` (-> `txt`), macros for paths. + - [x] `%path/...` macros: `cwd`, `this-file`, `this-directory`, `join`, `split`, `stem`, `with-extension`, `normalise`, `canonical`, `absolute`, `relative`, `exists`, `is-file` and `is-directory`. + - [x] `seam run file.sex`, running a file for its side effects (`%write`, `%exec`), reported on STDOUT like `make`. - [x] Math operators: `+`, `-`, `*`, `/`, `mod`, `pow`, `exp`, `sqrt`, `ln`, `log2`, `log10`, `hypot` (`%log` already logs), along with comparisons, `%if`, `%and`, `%or`, `%not` and `%range`. - [x] User `(%error msg)` macro for aborting compilation. diff --git a/USAGE.md b/USAGE.md index 6a6e958..8405f30 100644 --- a/USAGE.md +++ b/USAGE.md @@ -95,6 +95,22 @@ Literate mode is enabled with: frontmatter's definitions. Macro calls inside code (blocks and spans) are shown as written, not expanded. +### Running build scripts + +`seam run file.sex` expands a file only for what its macros *do*, such as +writing files with `%write` or running programs with `%exec`, and discards +the document it would otherwise generate. Like `make`, it reports each action +on STDOUT as it happens, and `%log` prints there too: +```sh +seam run build.sex +#stdout: +# write public/index.html +# write public/posts/hello-world.html +# exec git rev-parse --short HEAD +# log Built 3 posts. +``` +No target format is given, and the other options (`-I`, `--literate`) work as usual. + ## Macros In addition to the basic syntax, *symbols* prepended with a ‘`%`’ character, @@ -112,7 +128,8 @@ will be treated as macros. working directory). `%embed` finds files the same way. - `%date` standard `strftime` function, works of current system time, e.g. `(span :id timestamp Uploaded on (%date "%Y-%m-%d"))`. -- `%log` will simply log any information to STDERR, e.g. `(%log Hello, World!)`. +- `%log` will simply log any information to STDERR (STDOUT under `seam run`), + e.g. `(%log Hello, World!)`. - `%with` overrides top-level definitions for everything within it, e.g. `(%with (:title "Pound Cake") (%layout))` (see [Scoping](#scoping)). - `%let` binds patterns for its body, each seeing the ones before it, e.g. @@ -149,10 +166,29 @@ will be treated as macros. #### Paths, files and programs - `(%basename :suffix md posts/hi.md)` → `hi`, `(%dirname posts/hi.md)` → - `posts`, `(%extension posts/hi.md)` → `md`. + `posts`, `(%extension posts/hi.md)` → `md` (also `%path/basename`, + `%path/dirname` and `%path/extension`). +- `(%path/cwd)` is the (absolute) directory seam is run from, and + `(%path/this-file)` and `(%path/this-directory)` are the absolute path of the + file the call is written in, and its directory (the current directory, for + source read from STDIN). Relative paths given to `%glob`, `%write`, `%exec` + and the like are from the current directory, so + `(%path/join (%path/this-directory) posts)` refers to `posts` next to the + file wherever seam is run from. +- `(%path/join a b/c d.txt)` → `a/b/c/d.txt`, and `(%path/split /a/b.md)` → + `("/" a b.md)`. +- `(%path/stem a/b.tar.gz)` → `b.tar`, `(%path/with-extension a/b.md html)` → + `a/b.html` (an empty extension removes it). +- `(%path/normalise a/./b/../c)` → `a/c`, without looking at the file system, + while `(%path/canonical path)` resolves links too, and the file must exist. +- `(%path/absolute path :from dir)` resolves a path from a directory (by default, + the current one), and `(%path/relative path :from dir)` gives the way to a path + from a directory: `(%path/relative /a/b/c :from /a/d)` → `../b/c`. +- `(%path/exists path)`, `(%path/is-file path)` and `(%path/is-directory path)` + are `true` or `false`. - `(%write path content...)` writes the content's text to a file (making directories as needed), expanding to nothing. With the formatter macros - below, one source file can generate a whole site. + below, one source file can generate a whole site, run with `seam run`. - `(%exec program arguments... :stdin text)` runs a program and gives its output, e.g. `(%exec git rev-parse --short HEAD)`. @@ -307,4 +343,4 @@ especially using the `(%markdown ...)` macro. See [`samples/blog`](samples/blog) for a whole blog: Markdown posts with frontmatter, a shared layout, a tags page and an RSS feed, all generated by -`seam --text build.sex` with `%write` and the formatter macros. +`seam run build.sex` with `%write` and the formatter macros. diff --git a/crates/seam/src/bin.rs b/crates/seam/src/bin.rs index 3e25e6e..9887f58 100644 --- a/crates/seam/src/bin.rs +++ b/crates/seam/src/bin.rs @@ -17,9 +17,13 @@ fn argument_fatal(msg: impl std::fmt::Display) -> ! { const SUPPORTED_TARGETS: [&str; 5] = ["text", "sexp", "html", "xml", "css"]; fn main() -> Result<(), Box> { - let mut args = env::args(); + let mut args = env::args().peekable(); let _ = args.next(); // Discard. + // `seam run file.sex` expands a file only for its side effects + // (`%write`, `%exec`, ...), which are reported on STDOUT instead. + let run = args.next_if(|arg| arg == "run").is_some(); + // Command line flags and options. let mut files = Vec::new(); let mut target = String::new(); @@ -74,7 +78,11 @@ fn main() -> Result<(), Box> { if files.is_empty() { from_stdin = true; } - if target.is_empty() { + if run { + if !target.is_empty() { + argument_fatal(format!("`seam run' takes no target format, but `--{target}' was given.")); + } + } else if target.is_empty() { argument_fatal("No such target format exists / \ no target format given."); } @@ -84,19 +92,28 @@ fn main() -> Result<(), Box> { let context = seam::Context::new(); let builder = seam::tree_builder_stream(&context, &mut stdin, literate)?; builder.add_includes(include_dirs.iter()); - generate_and_print(builder, &target, is_doc); + if run { execute(builder) } else { generate_and_print(builder, &target, is_doc) } } for file in files { let context = seam::Context::new(); let builder = seam::tree_builder_file(&context, &file, literate)?; builder.add_includes(include_dirs.iter()); - generate_and_print(builder, &target, is_doc); + if run { execute(builder) } else { generate_and_print(builder, &target, is_doc) } } Ok(()) } +/// Expand a file only for its side effects, discarding the document. +fn execute(expander: seam::parse::expander::Expander) { + expander.set_echo(true); + if let Err(e) = expander.expand() { + eprintln!("{e}"); + std::process::exit(1); + } +} + fn generate_and_print(expander: seam::parse::expander::Expander, target: &str, is_doc: bool) { let tree = match expander.expand() { Ok(tree) => tree, diff --git a/crates/seam/src/parse/expander.rs b/crates/seam/src/parse/expander.rs index 42b055c..bb62b74 100644 --- a/crates/seam/src/parse/expander.rs +++ b/crates/seam/src/parse/expander.rs @@ -117,6 +117,9 @@ pub struct Context<'a> { /// Stack of `%with` bindings, which override top-level definitions /// for as long as the body of the `%with` is being expanded. dynamic: RefCell>>>, + /// Whether macros with side effects (`%write`, `%exec`, `%log`) + /// report what they do on `STDOUT`, as when running a build script. + echo: Cell, } impl Context<'_> { @@ -130,6 +133,7 @@ impl Context<'_> { includes: RefCell::new(BTreeSet::from([PathBuf::from(".")])), lambdas: Cell::new(0), dynamic: RefCell::new(Vec::new()), + echo: Cell::new(false), } } } @@ -214,6 +218,20 @@ impl<'a> Expander<'a> { } } + /// Have macros with side effects report what they do on `STDOUT`, + /// like `make` echoing commands, for when the expanded document itself + /// is not wanted (`seam run`). `%log` then prints there too. + pub fn set_echo(&self, echo: bool) { + self.context.echo.set(echo); + } + + /// Report an action on `STDOUT`, if echoing. + fn echo(&self, action: &str, detail: impl fmt::Display) { + if self.context.echo.get() { + println!("{} {detail}", format!("{action:>5}").bold().green()); + } + } + /// Hand a parser over to the context, which keeps it alive for `'a`. fn register_parser(&self, parser: Parser) -> &'a Parser { self.context.parsers.alloc(parser) @@ -1152,8 +1170,12 @@ impl<'a> Expander<'a> { } } - eprintln!("{} {} {}: {}", "[#]".bold(), "log".bold().yellow(), - node.site(), words.join(" ")); + if self.context.echo.get() { + self.echo("log", words.join(" ")); + } else { + eprintln!("{} {} {}: {}", "[#]".bold(), "log".bold().yellow(), + node.site(), words.join(" ")); + } Ok(Box::new([])) } @@ -2224,16 +2246,99 @@ impl<'a> Expander<'a> { Ok(Box::new([list_node(node, spaced(items))])) } - /// `(%basename path :suffix ext)`, `(%dirname path)` and `(%extension path)`. - fn expand_path_macro(&self, part: &str, node: &ParseNode<'a>, params: &[ParseNode<'a>]) + /// The `%path/...` macros (also `%basename`, `%dirname` and `%extension`): + /// taking paths apart, joining and resolving them, and asking about files. + fn expand_path_macro(&self, operation: &str, node: &ParseNode<'a>, params: &[ParseNode<'a>]) -> Result, ExpansionError<'a>> { + use std::path::Path; let params = self.expand_nodes(params)?; + let failed = |error: String| ExpansionError(format!("`%path/{operation}': {error}"), node.owned_site()); + let cwd = || std::env::current_dir().map_err(|error| failed(error.to_string())); + let path_node = |path: &Path| ParseNode::String(Node::new( + path.to_string_lossy().into_owned(), node.site(), node.leading_whitespace().clone())); + + // Paths of where seam is, and of the file this call is written in. + let this_file = || { + let source = Path::new(node.site().source()); + if source.is_file() { + Ok(normalise(&cwd()?.join(source))) + } else { + Err(failed(String::from("this call is not written in a file."))) + } + }; + match operation { + "cwd" | "this-file" | "this-directory" => { + arguments! { node, ¶ms; }?; + let path = match operation { + "cwd" => cwd()?, + "this-file" => this_file()?, + _ => match this_file() { + Ok(file) => file.parent().map_or_else(|| file.clone(), Path::to_path_buf), + Err(_) => cwd()?, + }, + }; + return Ok(Box::new([path_node(&path)])); + }, + "join" => { + let args = arguments! { node, ¶ms; rest: literal, }?; + let path: PathBuf = args.rest.iter().map(|part| part.value.as_ref()).collect(); + return Ok(Box::new([path_node(&path)])); + }, + "absolute" | "relative" => { + let args = arguments! { node, ¶ms; + mandatory(1): literal, + optional("from"): literal, + }?; + let base = match args.from { + Some(from) => normalise(&cwd()?.join(from.value.as_ref())), + None => cwd()?, + }; + // `%path/absolute` resolves the path from `:from`, while + // `%path/relative` gives the way to it (from where we are) from `:from`. + let path = args.number.1.value.as_ref(); + let path = if operation == "absolute" { + normalise(&base.join(path)) + } else { + relative_path(&normalise(&cwd()?.join(path)), &base) + }; + return Ok(Box::new([path_node(&path)])); + }, + "with-extension" => { + let args = arguments! { node, ¶ms; + mandatory(1): literal, + mandatory(2): literal, + }?; + let path = Path::new(args.number.1.value.as_ref()).with_extension(args.number.2.value.as_ref()); + return Ok(Box::new([path_node(&path)])); + }, + "split" => { + let args = arguments! { node, ¶ms; mandatory(1): literal, }?; + let parts = Path::new(args.number.1.value.as_ref()).components() + .map(|part| ParseNode::String(Node::new( + part.as_os_str().to_string_lossy().into_owned(), node.site(), " "))) + .collect(); + return Ok(Box::new([list_node(node, without_leading(parts))])); + }, + "exists" | "is-file" | "is-directory" => { + let args = arguments! { node, ¶ms; mandatory(1): literal, }?; + let path = Path::new(args.number.1.value.as_ref()); + let answer = match operation { + "exists" => path.exists(), + "is-file" => path.is_file(), + _ => path.is_dir(), + }; + return Ok(Box::new([bool_node(node, answer)])); + }, + _ => {}, + } + + // The rest each give a part of the path they are given. let args = arguments! { node, ¶ms; mandatory(1): literal, optional("suffix"): literal, }?; - let path = std::path::Path::new(args.number.1.value.as_ref()); - let result: String = match part { + let path = Path::new(args.number.1.value.as_ref()); + let result: String = match operation { "basename" => { let name = path.file_name().map_or(String::new(), |name| name.to_string_lossy().into_owned()); match args.suffix { @@ -2244,12 +2349,18 @@ impl<'a> Expander<'a> { _ => name, } }, + "stem" => path.file_stem().map_or(String::new(), |stem| stem.to_string_lossy().into_owned()), "dirname" => match path.parent() { Some(parent) if !parent.as_os_str().is_empty() => parent.to_string_lossy().into_owned(), _ => String::from(if path.has_root() { "/" } else { "." }), }, "extension" => path.extension().map_or(String::new(), |ext| ext.to_string_lossy().into_owned()), - _ => unreachable!(), + "normalise" | "normalize" => normalise(path).to_string_lossy().into_owned(), + "canonical" => std::fs::canonicalize(path) + .map_err(|error| failed(format!("`{}': {error}", path.display())))? + .to_string_lossy().into_owned(), + _ => return Err(ExpansionError::new( + format!("Macro not found (`path/{operation}')."), &node.owned_site())), }; let path = params.iter().find(|param| !param.is_attribute()).unwrap_or(node); let value = result_string(&args.number.1.value, result); @@ -2380,6 +2491,7 @@ impl<'a> Expander<'a> { } std::fs::write(path, text) }; + self.echo("write", path.display()); write().map_err(|error| ExpansionError( format!("Could not write `{}': {error}", path.display()), node.owned_site()))?; Ok(Box::new([])) @@ -2398,6 +2510,13 @@ impl<'a> Expander<'a> { }?; let program: &str = &args.number.1.value; let failed = |error: String| ExpansionError(format!("`%exec {program}' failed: {error}"), node.owned_site()); + if self.context.echo.get() { + let command: Vec = std::iter::once(program) + .chain(args.rest.iter().map(|arg| arg.value.as_ref())) + .map(shell_quote) + .collect(); + self.echo("exec", command.join(" ")); + } let mut child = std::process::Command::new(program) .args(args.rest.iter().map(|arg| arg.value.as_ref())) .stdin(std::process::Stdio::piped()) @@ -2667,6 +2786,8 @@ impl<'a> Expander<'a> { "contains" => self.expand_contains_macro(node, params), "items" | "keys" | "values" => self.expand_dictionary_macro(name, node, params), "basename" | "dirname" | "extension" => self.expand_path_macro(name, node, params), + _ if name.starts_with("path/") + => self.expand_path_macro(&name["path/".len()..], node, params), "write" => self.expand_write_macro(node, params), "exec" => self.expand_exec_macro(node, params), _ if name.starts_with("formatter/") @@ -3129,6 +3250,52 @@ fn split_frontmatter<'s>(contents: &'s str, options: &markdown::ParseOptions) } /// Escape macro calls within the given ranges of text, so literate expansion leaves them be. +/// Tidy a path without looking at the file system: +/// drop `.` parts, and remove a `..` along with the part before it. +fn normalise(path: &std::path::Path) -> PathBuf { + use std::path::Component; + let mut result = PathBuf::new(); + for part in path.components() { + match part { + Component::CurDir => {}, + Component::ParentDir => match result.components().next_back() { + Some(Component::Normal(_)) => { result.pop(); }, + Some(Component::RootDir | Component::Prefix(_)) => {}, + _ => result.push(".."), + }, + _ => result.push(part), + } + } + if result.as_os_str().is_empty() { + result.push("."); + } + result +} + +/// The path to `path` from the directory `base`, both absolute and normalised. +fn relative_path(path: &std::path::Path, base: &std::path::Path) -> PathBuf { + let path: Vec<_> = path.components().collect(); + let base: Vec<_> = base.components().collect(); + let common = path.iter().zip(&base).take_while(|(a, b)| a == b).count(); + let mut result: PathBuf = std::iter::repeat_n(std::path::Component::ParentDir, base.len() - common).collect(); + result.extend(&path[common..]); + if result.as_os_str().is_empty() { + result.push("."); + } + result +} + +/// Quote a word for display as part of a shell command, only if needed. +fn shell_quote(word: &str) -> String { + let plain = !word.is_empty() && word.chars().all(|c| + c.is_alphanumeric() || "-_./:=+,@%".contains(c)); + if plain { + word.to_owned() + } else { + format!("'{}'", word.replace('\'', r"'\''")) + } +} + fn escape_ranges(text: &str, ranges: &[std::ops::Range]) -> String { let mut escaped = String::with_capacity(text.len()); let mut last = 0; diff --git a/crates/seam/src/tests.rs b/crates/seam/src/tests.rs index fbedce0..fdeda43 100644 --- a/crates/seam/src/tests.rs +++ b/crates/seam/src/tests.rs @@ -439,6 +439,21 @@ mod cases { fn test_path_macros() { assert_sexp_eq("(%basename :suffix txt /a/f.txt) (%basename /a/f.txt) (%dirname /a/f.txt) (%dirname f) (%extension /a/f.txt)", "f f.txt /a . txt"); + assert_sexp_eq("(%path/basename a/b.md) (%path/stem a/b.tar.gz) (%path/with-extension a/b.md html) (%path/join a b/c d.txt)", + "b.md b.tar \"a/b.html\" \"a/b/c/d.txt\""); + assert_sexp_eq("(%path/split /a/b.md) (%path/normalise a/./b/../../../c) (%path/normalise /../a)", + "(\"/\" \"a\" \"b.md\") ../c /a"); + assert_sexp_eq("(%path/absolute :from /a/b ../c) (%path/relative /a/b/c :from /a/d) (%path/relative /a :from /a)", + "\"/a/c\" \"../b/c\" \".\""); + assert_sexp_eq("(%path/exists Cargo.toml) (%path/is-file src) (%path/is-directory src) (%path/exists nowhere)", + "true false true false"); + let cwd = std::env::current_dir().unwrap(); + assert_sexp_eq("(%path/cwd) (%path/relative (%path/cwd))", &format!("\"{}\" \".\"", cwd.display())); + // Paths of the file a call is written in, which a string of source is not. + assert_sexp_eq("(%include \"tests/fixtures/here.sex\")", + &format!("\"{0}/tests/fixtures/here.sex\" \"{0}/tests/fixtures\"", cwd.display())); + assert!(sexp("(%path/this-file)").is_err()); + assert_sexp_eq("(%path/this-directory)", &format!("\"{}\"", cwd.display())); } #[test] diff --git a/crates/seam/tests/fixtures/here.sex b/crates/seam/tests/fixtures/here.sex new file mode 100644 index 0000000..4e77ee3 --- /dev/null +++ b/crates/seam/tests/fixtures/here.sex @@ -0,0 +1 @@ +(%path/this-file) (%path/this-directory) diff --git a/samples/blog/README.md b/samples/blog/README.md index c3e0309..721e424 100644 --- a/samples/blog/README.md +++ b/samples/blog/README.md @@ -5,7 +5,7 @@ a shared layout, posts listed on an index by date, a tags page and an RSS feed. ```sh cd samples/blog -seam --text build.sex # Writes the site into public/. +seam run build.sex # Writes the site into public/. ``` - `site.sex` defines everything shared: the site's details, `%posts` (every @@ -20,5 +20,7 @@ seam --text build.sex # Writes the site into public/. (`%formatter/html :document true ...`) and saves it with `%write`. - `style.sex` is the stylesheet, in seam's CSS syntax. -Paths (`%glob`, `%write`) are relative to the working directory, so run -`seam` from this directory. +Paths given to `%glob` and `%write` are relative to the working directory, so +`site.sex` and `build.sex` find their files from `(%path/this-directory)`, and +the blog builds from anywhere: `seam run samples/blog/build.sex` also writes +into `samples/blog/public/`. diff --git a/samples/blog/build.sex b/samples/blog/build.sex index 1b98fa8..df9d3bb 100644 --- a/samples/blog/build.sex +++ b/samples/blog/build.sex @@ -1,21 +1,24 @@ -;; Builds the whole site into `public/`. Run it from this directory: -;; seam --text build.sex +;; Builds the whole site into `public/`, next to this file: +;; seam run build.sex ;; Each page is generated with a formatter macro, and written with `%write`. (%include "site.sex") -(%define (write-html path &content) - (%write (%concat "public/" %path) (%formatter/html :document true %content))) +;; Where to write the site, from wherever seam is run. +(%define public (%path/relative (%path/join (%path/this-directory) public))) -(%write-html "index.html" (%include "index.sex")) -(%write-html "tags.html" (%include "tags.sex")) +(%define (write/html path &content) + (%write (%path/join %public %path) (%formatter/html :document true %content))) + +(%write/html "index.html" (%include "index.sex")) +(%write/html "tags.html" (%include "tags.sex")) (%for post in %posts - (%write-html (%concat "posts/" (%get slug %post) ".html") + (%write/html (%concat "posts/" (%get slug %post) ".html") (%with %post (%with (:root "../") (%include "post.sex"))))) -(%write "public/feed.xml" (%formatter/xml :document true (%include "feed.sex"))) -(%write "public/style.css" (%formatter/css (%include "style.sex"))) +(%write (%path/join %public feed.xml) (%formatter/xml :document true (%include "feed.sex"))) +(%write (%path/join %public style.css) (%formatter/css (%include "style.sex"))) -(%log Built (%length %posts) posts into public/) +(%log Built (%length %posts) posts into %public) diff --git a/samples/blog/posts/one-file-many-pages.md b/samples/blog/posts/one-file-many-pages.md index d89699e..fc2cd09 100644 --- a/samples/blog/posts/one-file-many-pages.md +++ b/samples/blog/posts/one-file-many-pages.md @@ -11,7 +11,7 @@ and `%write` to save it: ```lisp (%for post in %posts - (%write-html (%concat "posts/" (%get slug %post) ".html") + (%write/html (%concat "posts/" (%get slug %post) ".html") (%with %post (%with (:root "../") (%include "post.sex"))))) @@ -21,5 +21,5 @@ The feed is the same, with `%formatter/xml`, and so is the stylesheet, with `%formatter/css`. Building the site is then just: ```sh -seam --text build.sex +seam run build.sex ``` diff --git a/samples/blog/site.sex b/samples/blog/site.sex index f08f1f8..88c7215 100644 --- a/samples/blog/site.sex +++ b/samples/blog/site.sex @@ -23,7 +23,7 @@ ;; Every published post, newest first. (%define posts (%sort :order descending :key (%lambda ((:date _ &&_)) %date) - (%list (%for file in (%glob "posts/*.md") + (%list (%for file in (%glob (%path/relative (%path/join (%path/this-directory) "posts/*.md"))) (%let ((post (%read-post %file))) (%if (%not (%get draft %post)) %post)))))) From fba3accfc6dec11c10d71d022264a633ebdbeae6 Mon Sep 17 00:00:00 2001 From: Demonstrandum Date: Tue, 3 Nov 2026 13:46:31 +0000 Subject: [PATCH 4/6] Rename %path/this-file to %path/here. --- README.md | 2 +- USAGE.md | 2 +- crates/seam/src/parse/expander.rs | 8 ++++---- crates/seam/src/tests.rs | 2 +- crates/seam/tests/fixtures/here.sex | 2 +- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 87cb194..a77ead3 100644 --- a/README.md +++ b/README.md @@ -114,7 +114,7 @@ seam run build.sex - [x] Shell-style `${var:...}` string manipulation, written `%{var:...}`. - [x] `%while`, `%take`, `%drop`, `%split` on symbols in lists, `%intercalate`. - [x] `(%basename :suffix "txt" /path/file.txt)` (-> `file`), `(%dirname /path/file.txt)` (-> `/path`) and `(%extension /path/file.txt)` (-> `txt`), macros for paths. - - [x] `%path/...` macros: `cwd`, `this-file`, `this-directory`, `join`, `split`, `stem`, `with-extension`, `normalise`, `canonical`, `absolute`, `relative`, `exists`, `is-file` and `is-directory`. + - [x] `%path/...` macros: `cwd`, `here`, `this-directory`, `join`, `split`, `stem`, `with-extension`, `normalise`, `canonical`, `absolute`, `relative`, `exists`, `is-file` and `is-directory`. - [x] `seam run file.sex`, running a file for its side effects (`%write`, `%exec`), reported on STDOUT like `make`. - [x] Math operators: `+`, `-`, `*`, `/`, `mod`, `pow`, `exp`, `sqrt`, `ln`, `log2`, `log10`, `hypot` (`%log` already logs), along with comparisons, `%if`, `%and`, `%or`, `%not` and `%range`. diff --git a/USAGE.md b/USAGE.md index 8405f30..6f6d65f 100644 --- a/USAGE.md +++ b/USAGE.md @@ -169,7 +169,7 @@ will be treated as macros. `posts`, `(%extension posts/hi.md)` → `md` (also `%path/basename`, `%path/dirname` and `%path/extension`). - `(%path/cwd)` is the (absolute) directory seam is run from, and - `(%path/this-file)` and `(%path/this-directory)` are the absolute path of the + `(%path/here)` and `(%path/this-directory)` are the absolute path of the file the call is written in, and its directory (the current directory, for source read from STDIN). Relative paths given to `%glob`, `%write`, `%exec` and the like are from the current directory, so diff --git a/crates/seam/src/parse/expander.rs b/crates/seam/src/parse/expander.rs index bb62b74..6107ec5 100644 --- a/crates/seam/src/parse/expander.rs +++ b/crates/seam/src/parse/expander.rs @@ -2258,7 +2258,7 @@ impl<'a> Expander<'a> { path.to_string_lossy().into_owned(), node.site(), node.leading_whitespace().clone())); // Paths of where seam is, and of the file this call is written in. - let this_file = || { + let here = || { let source = Path::new(node.site().source()); if source.is_file() { Ok(normalise(&cwd()?.join(source))) @@ -2267,12 +2267,12 @@ impl<'a> Expander<'a> { } }; match operation { - "cwd" | "this-file" | "this-directory" => { + "cwd" | "here" | "this-directory" => { arguments! { node, ¶ms; }?; let path = match operation { "cwd" => cwd()?, - "this-file" => this_file()?, - _ => match this_file() { + "here" => here()?, + _ => match here() { Ok(file) => file.parent().map_or_else(|| file.clone(), Path::to_path_buf), Err(_) => cwd()?, }, diff --git a/crates/seam/src/tests.rs b/crates/seam/src/tests.rs index fdeda43..04c531b 100644 --- a/crates/seam/src/tests.rs +++ b/crates/seam/src/tests.rs @@ -452,7 +452,7 @@ mod cases { // Paths of the file a call is written in, which a string of source is not. assert_sexp_eq("(%include \"tests/fixtures/here.sex\")", &format!("\"{0}/tests/fixtures/here.sex\" \"{0}/tests/fixtures\"", cwd.display())); - assert!(sexp("(%path/this-file)").is_err()); + assert!(sexp("(%path/here)").is_err()); assert_sexp_eq("(%path/this-directory)", &format!("\"{}\"", cwd.display())); } diff --git a/crates/seam/tests/fixtures/here.sex b/crates/seam/tests/fixtures/here.sex index 4e77ee3..7f28a1b 100644 --- a/crates/seam/tests/fixtures/here.sex +++ b/crates/seam/tests/fixtures/here.sex @@ -1 +1 @@ -(%path/this-file) (%path/this-directory) +(%path/here) (%path/this-directory) From 6a04caa7959cf70938dd834290e310224cf85c98 Mon Sep 17 00:00:00 2001 From: Demonstrandum Date: Tue, 3 Nov 2026 13:49:19 +0000 Subject: [PATCH 5/6] Make %path/here the file's directory, and %path/this the file. --- README.md | 2 +- USAGE.md | 6 +++--- crates/seam/src/parse/expander.rs | 8 ++++---- crates/seam/src/tests.rs | 8 ++++---- crates/seam/tests/fixtures/here.sex | 1 - crates/seam/tests/fixtures/paths.sex | 1 + samples/blog/README.md | 2 +- samples/blog/build.sex | 2 +- samples/blog/site.sex | 2 +- 9 files changed, 16 insertions(+), 16 deletions(-) delete mode 100644 crates/seam/tests/fixtures/here.sex create mode 100644 crates/seam/tests/fixtures/paths.sex diff --git a/README.md b/README.md index a77ead3..916ba2e 100644 --- a/README.md +++ b/README.md @@ -114,7 +114,7 @@ seam run build.sex - [x] Shell-style `${var:...}` string manipulation, written `%{var:...}`. - [x] `%while`, `%take`, `%drop`, `%split` on symbols in lists, `%intercalate`. - [x] `(%basename :suffix "txt" /path/file.txt)` (-> `file`), `(%dirname /path/file.txt)` (-> `/path`) and `(%extension /path/file.txt)` (-> `txt`), macros for paths. - - [x] `%path/...` macros: `cwd`, `here`, `this-directory`, `join`, `split`, `stem`, `with-extension`, `normalise`, `canonical`, `absolute`, `relative`, `exists`, `is-file` and `is-directory`. + - [x] `%path/...` macros: `cwd`, `this`, `here`, `join`, `split`, `stem`, `with-extension`, `normalise`, `canonical`, `absolute`, `relative`, `exists`, `is-file` and `is-directory`. - [x] `seam run file.sex`, running a file for its side effects (`%write`, `%exec`), reported on STDOUT like `make`. - [x] Math operators: `+`, `-`, `*`, `/`, `mod`, `pow`, `exp`, `sqrt`, `ln`, `log2`, `log10`, `hypot` (`%log` already logs), along with comparisons, `%if`, `%and`, `%or`, `%not` and `%range`. diff --git a/USAGE.md b/USAGE.md index 6f6d65f..b489650 100644 --- a/USAGE.md +++ b/USAGE.md @@ -169,11 +169,11 @@ will be treated as macros. `posts`, `(%extension posts/hi.md)` → `md` (also `%path/basename`, `%path/dirname` and `%path/extension`). - `(%path/cwd)` is the (absolute) directory seam is run from, and - `(%path/here)` and `(%path/this-directory)` are the absolute path of the - file the call is written in, and its directory (the current directory, for + `(%path/this)` is the absolute path of the file the call is written in, and + `(%path/here)` is its directory (the current directory, for source read from STDIN). Relative paths given to `%glob`, `%write`, `%exec` and the like are from the current directory, so - `(%path/join (%path/this-directory) posts)` refers to `posts` next to the + `(%path/join (%path/here) posts)` refers to `posts` next to the file wherever seam is run from. - `(%path/join a b/c d.txt)` → `a/b/c/d.txt`, and `(%path/split /a/b.md)` → `("/" a b.md)`. diff --git a/crates/seam/src/parse/expander.rs b/crates/seam/src/parse/expander.rs index 6107ec5..c2ce3ba 100644 --- a/crates/seam/src/parse/expander.rs +++ b/crates/seam/src/parse/expander.rs @@ -2258,7 +2258,7 @@ impl<'a> Expander<'a> { path.to_string_lossy().into_owned(), node.site(), node.leading_whitespace().clone())); // Paths of where seam is, and of the file this call is written in. - let here = || { + let this = || { let source = Path::new(node.site().source()); if source.is_file() { Ok(normalise(&cwd()?.join(source))) @@ -2267,12 +2267,12 @@ impl<'a> Expander<'a> { } }; match operation { - "cwd" | "here" | "this-directory" => { + "cwd" | "this" | "here" => { arguments! { node, ¶ms; }?; let path = match operation { "cwd" => cwd()?, - "here" => here()?, - _ => match here() { + "this" => this()?, + _ => match this() { Ok(file) => file.parent().map_or_else(|| file.clone(), Path::to_path_buf), Err(_) => cwd()?, }, diff --git a/crates/seam/src/tests.rs b/crates/seam/src/tests.rs index 04c531b..041e670 100644 --- a/crates/seam/src/tests.rs +++ b/crates/seam/src/tests.rs @@ -450,10 +450,10 @@ mod cases { let cwd = std::env::current_dir().unwrap(); assert_sexp_eq("(%path/cwd) (%path/relative (%path/cwd))", &format!("\"{}\" \".\"", cwd.display())); // Paths of the file a call is written in, which a string of source is not. - assert_sexp_eq("(%include \"tests/fixtures/here.sex\")", - &format!("\"{0}/tests/fixtures/here.sex\" \"{0}/tests/fixtures\"", cwd.display())); - assert!(sexp("(%path/here)").is_err()); - assert_sexp_eq("(%path/this-directory)", &format!("\"{}\"", cwd.display())); + assert_sexp_eq("(%include \"tests/fixtures/paths.sex\")", + &format!("\"{0}/tests/fixtures/paths.sex\" \"{0}/tests/fixtures\"", cwd.display())); + assert!(sexp("(%path/this)").is_err()); + assert_sexp_eq("(%path/here)", &format!("\"{}\"", cwd.display())); } #[test] diff --git a/crates/seam/tests/fixtures/here.sex b/crates/seam/tests/fixtures/here.sex deleted file mode 100644 index 7f28a1b..0000000 --- a/crates/seam/tests/fixtures/here.sex +++ /dev/null @@ -1 +0,0 @@ -(%path/here) (%path/this-directory) diff --git a/crates/seam/tests/fixtures/paths.sex b/crates/seam/tests/fixtures/paths.sex new file mode 100644 index 0000000..d20c17f --- /dev/null +++ b/crates/seam/tests/fixtures/paths.sex @@ -0,0 +1 @@ +(%path/this) (%path/here) diff --git a/samples/blog/README.md b/samples/blog/README.md index 721e424..59b9bba 100644 --- a/samples/blog/README.md +++ b/samples/blog/README.md @@ -21,6 +21,6 @@ seam run build.sex # Writes the site into public/. - `style.sex` is the stylesheet, in seam's CSS syntax. Paths given to `%glob` and `%write` are relative to the working directory, so -`site.sex` and `build.sex` find their files from `(%path/this-directory)`, and +`site.sex` and `build.sex` find their files from `(%path/here)`, and the blog builds from anywhere: `seam run samples/blog/build.sex` also writes into `samples/blog/public/`. diff --git a/samples/blog/build.sex b/samples/blog/build.sex index df9d3bb..e7f3073 100644 --- a/samples/blog/build.sex +++ b/samples/blog/build.sex @@ -4,7 +4,7 @@ (%include "site.sex") ;; Where to write the site, from wherever seam is run. -(%define public (%path/relative (%path/join (%path/this-directory) public))) +(%define public (%path/relative (%path/join (%path/here) public))) (%define (write/html path &content) (%write (%path/join %public %path) (%formatter/html :document true %content))) diff --git a/samples/blog/site.sex b/samples/blog/site.sex index 88c7215..bf1c181 100644 --- a/samples/blog/site.sex +++ b/samples/blog/site.sex @@ -23,7 +23,7 @@ ;; Every published post, newest first. (%define posts (%sort :order descending :key (%lambda ((:date _ &&_)) %date) - (%list (%for file in (%glob (%path/relative (%path/join (%path/this-directory) "posts/*.md"))) + (%list (%for file in (%glob (%path/relative (%path/join (%path/here) "posts/*.md"))) (%let ((post (%read-post %file))) (%if (%not (%get draft %post)) %post)))))) From b6d9d84807714747e0b7a0d5dab4d51500a3b9e0 Mon Sep 17 00:00:00 2001 From: Demonstrandum Date: Tue, 3 Nov 2026 14:10:59 +0000 Subject: [PATCH 6/6] Fix Bugbot findings from the stacked PRs. - 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. --- crates/seam/src/assemble/css.rs | 7 +- crates/seam/src/assemble/xml.rs | 6 +- crates/seam/src/parse/expander.rs | 151 ++++++++++++++-------- crates/seam/src/parse/lexer.rs | 6 + crates/seam/src/parse/parser.rs | 6 + crates/seam/src/tests.rs | 38 ++++++ crates/seam/tests/fixtures/nested/note.md | 1 + crates/seam/tests/fixtures/rule.md | 7 + 8 files changed, 163 insertions(+), 59 deletions(-) create mode 100644 crates/seam/tests/fixtures/nested/note.md create mode 100644 crates/seam/tests/fixtures/rule.md diff --git a/crates/seam/src/assemble/css.rs b/crates/seam/src/assemble/css.rs index a397ddd..6857b65 100644 --- a/crates/seam/src/assemble/css.rs +++ b/crates/seam/src/assemble/css.rs @@ -39,10 +39,13 @@ impl<'a> CSSFormatter<'a> { and property-value pairs, wrapped in parentheses.", &site.to_owned())); }, + // Raw text (e.g. hand-written CSS around literate macro calls) is written as it is. + ParseNode::Raw(node) => { + write!(f, "{leading}{}", node.value)?; + }, ParseNode::Symbol(node) | ParseNode::Number(node) - | ParseNode::String(node) - | ParseNode::Raw(node) => { + | ParseNode::String(node) => { let site = node.site; return Err(GenerationError::new("CSS", "Symbolic node not expected here, CSS documents \ diff --git a/crates/seam/src/assemble/xml.rs b/crates/seam/src/assemble/xml.rs index 32c7f0d..ca97738 100644 --- a/crates/seam/src/assemble/xml.rs +++ b/crates/seam/src/assemble/xml.rs @@ -40,6 +40,10 @@ impl<'a> XMLFormatter<'a> { write!(f, "{leading}")?; write_escaped(f, &node.value)?; }, + // Raw text (e.g. the text of literate source) is written as it is. + ParseNode::Raw(node) => { + write!(f, "{leading}{}", node.value)?; + }, ParseNode::List { nodes: list, end_token, .. } => { write!(f, "{leading}")?; let head = list.first(); @@ -110,7 +114,7 @@ impl<'a> XMLFormatter<'a> { write!(f, "")?; }, - _ => return Err(GenerationError::new("XML", + ParseNode::Attribute { .. } => return Err(GenerationError::new("XML", &format!("Unexpected {} node when generating.", node.node_type()), node.site())) } diff --git a/crates/seam/src/parse/expander.rs b/crates/seam/src/parse/expander.rs index c2ce3ba..27dd19b 100644 --- a/crates/seam/src/parse/expander.rs +++ b/crates/seam/src/parse/expander.rs @@ -95,8 +95,10 @@ enum Definition<'a> { Value(Box<[ParseNode<'a>]>), /// A macro, e.g. from `(%define (f ...) ...)` or `(%lambda ...)`. Macro(&'a Macro<'a>), - /// A lazy argument, expanded in the caller's scope each time it is used. - Thunk(Box<[ParseNode<'a>]>, &'a Scope<'a>), + /// A lazy argument, expanded in the caller's scope each time it is used, + /// and then checked against its parameter's type, if it has one + /// (given as the macro, and the index of the parameter in its types). + Thunk(Box<[ParseNode<'a>]>, &'a Scope<'a>, Option<(&'a Macro<'a>, usize)>), } /// Owns everything that outlives a single macro expansion: @@ -812,28 +814,33 @@ impl<'a> Expander<'a> { // Open file, and read contents! let embed_error = |error: Box| ExpansionError( format!("{error}"), site.to_owned()); - let mut value: Result = Err( + let mut value: Result<(PathBuf, String), ExpansionError> = Err( embed_error(Box::new("No path tested."))); // Try all include directories until one is successful. for include_dir in self.search_directories(site) { let path = include_dir.join(&**path); - value = std::fs::read_to_string(path) + value = std::fs::read_to_string(&path) + .map(|contents| (path, contents)) .map_err(|err| embed_error(Box::new(err))); if value.is_ok() { break; } } - let value = value?; + let (path, value) = value?; + let path = path.to_string_lossy().into_owned(); // Literate embeds expand the macros found in the file's text. if literate { - let mut expanded = self.expand_literate(path.to_string(), value, site)?; + let mut expanded = self.expand_literate(path, value, site)?; if let Some(first) = expanded.first_mut() { first.set_leading_whitespace(node.leading_whitespace().clone()); } return Ok(expanded); } + // The text is sited in its own file, so that macros given it (such as + // `%markdown`) know where it came from, e.g. to find files next to it. + let file = self.register_parser(Parser::new(Lexer::new(path, value))).file(); Ok(Box::new([ ParseNode::String(Node { - value: value.into(), - site: node.owned_site(), + value: Cow::Borrowed(&file.code), + site: Site::new(file, 1, 0, 0, file.code.len()), leading_whitespace: node.leading_whitespace().clone(), }), ])) @@ -869,32 +876,32 @@ impl<'a> Expander<'a> { let sep: &str = args.separator.map_or("/", |sep| &sep.value); // Embedded HTML is passed through by default, `:allow-html false` escapes it. let allow_html = args.allow_html.is_none_or(|option| option.value == "true"); - // Live dangerously / trust the author: - let danger = markdown::CompileOptions { - allow_dangerous_html: allow_html, - allow_dangerous_protocol: true, - ..markdown::CompileOptions::default() - }; - // Flavour options: - let flavour = markdown::ParseOptions { - gfm_strikethrough_single_tilde: false, - math_text_single_dollar: true, - constructs: markdown::Constructs { - frontmatter: true, - gfm_table: true, - gfm_task_list_item: true, - ..markdown::Constructs::default() + let options = |frontmatter| markdown::Options { + // Live dangerously / trust the author: + compile: markdown::CompileOptions { + allow_dangerous_html: allow_html, + allow_dangerous_protocol: true, + ..markdown::CompileOptions::default() + }, + // Flavour options: + parse: markdown::ParseOptions { + gfm_strikethrough_single_tilde: false, + math_text_single_dollar: true, + constructs: markdown::Constructs { + frontmatter, + gfm_table: true, + gfm_task_list_item: true, + ..markdown::Constructs::default() + }, + ..markdown::ParseOptions::default() }, - ..markdown::ParseOptions::default() }; - // Options. - let options = markdown::Options { parse: flavour, compile: danger, }; let markdown_error = |err: markdown::message::Message| ExpansionError( format!("Failed to render markdown: {err}"), site); // Split off the frontmatter first, so that literate expansion // only runs over the part (or parts) actually being used. - let MarkdownParts { frontmatter, body, code } = split_frontmatter(contents, &options.parse) + let MarkdownParts { frontmatter, body, code } = split_frontmatter(contents, &options(true).parse) .map_err(markdown_error)?; // Expand any `(%...)` calls in a part, keeping line numbers // relative to the whole string by padding with new lines. @@ -902,8 +909,10 @@ impl<'a> Expander<'a> { if !literate || !text.contains("(%") { return Ok(text.to_owned()); } - let source = "\n".repeat(line) + text; - let expanded = self.expand_literate(format!("{} (markdown)", site.source()), source, &site)?; + // Named after the file the markdown is from (for finding files relative + // to it), and padded to the lines of the markdown within it. + let source = "\n".repeat(site.line.saturating_sub(1) as usize + line) + text; + let expanded = self.expand_literate(site.source().to_owned(), source, &site)?; nodes_to_text(&expanded) }; // Convert frontmatter into macro definitions. @@ -921,12 +930,14 @@ impl<'a> Expander<'a> { } Ok(()) }; - // Render the markdown content as raw HTML. + // Render the markdown content as raw HTML. Its frontmatter is already split + // off, so a body starting with `---` is not taken for more frontmatter. + let body_options = options(false); let to_html = |(body, line): (&str, usize)| -> Result, ExpansionError<'a>> { // Macro calls within code are shown, not expanded. let body = if literate && !code.is_empty() { Cow::Owned(escape_ranges(body, &code)) } else { Cow::Borrowed(body) }; let body = expand(&body, line)?; - let html = markdown::to_html_with_options(&body, &options) + let html = markdown::to_html_with_options(&body, &body_options) .map_err(markdown_error)?; Ok(Box::new([ ParseNode::Raw(Node { @@ -2395,7 +2406,7 @@ impl<'a> Expander<'a> { let (name, operation) = inner.split_at(split.unwrap_or(inner.len())); let value: Option> = match self.lookup(name, |definition| match definition { Definition::Value(value) => Ok(value.clone()), - Definition::Thunk(nodes, env) => self.within(env).expand_nodes(nodes), + Definition::Thunk(nodes, env, typed) => self.expand_thunk(nodes, env, *typed), Definition::Macro(_) => Err(error(format!("`{name}' is a macro, not a variable."))), }) { Some(value) => match &*value? { @@ -2524,11 +2535,19 @@ impl<'a> Expander<'a> { .stderr(std::process::Stdio::piped()) .spawn() .map_err(|error| failed(error.to_string()))?; - if let Some(mut stdin) = child.stdin.take() { - let input = args.stdin.map_or("", |input| input.value.as_ref()); - stdin.write_all(input.as_bytes()).map_err(|error| failed(error.to_string()))?; - } + // Input is written from another thread while the output is read, + // so that neither side blocks on a full pipe waiting for the other. + let input = args.stdin.map_or_else(Vec::new, |input| input.value.as_bytes().to_vec()); + let writer = child.stdin.take().map(|mut stdin| std::thread::spawn(move || stdin.write_all(&input))); let output = child.wait_with_output().map_err(|error| failed(error.to_string()))?; + if let Some(writer) = writer { + match writer.join() { + // A program may finish without reading all its input. + Ok(Err(error)) if error.kind() != std::io::ErrorKind::BrokenPipe => return Err(failed(error.to_string())), + Err(_) => return Err(failed(String::from("could not write its input."))), + Ok(_) => {}, + } + } if !output.status.success() { return Err(failed(String::from_utf8_lossy(&output.stderr).trim_end().to_owned())); } @@ -2647,27 +2666,31 @@ impl<'a> Expander<'a> { Ok(arguments.into_boxed_slice()) } - /// Check the arguments bound to typed parameters. + /// Check the arguments bound to typed parameters, except lazy ones, + /// which are checked once expanded, each time they are used. fn check_types(&self, mac: &Macro<'a>) -> Result<(), ExpansionError<'a>> { let definitions = self.scope.definitions.borrow(); - for (name, kind, rest) in &mac.types { - let Some(Definition::Value(nodes)) = definitions.get(name) else { continue }; - let wrong = if *rest { - nodes.iter().find(|node| !kind.admits(node)) - } else { - nodes.iter().find(|node| !kind.admits(node)).or(if nodes.len() == 1 { None } else { nodes.first() }) - }; - if let Some(node) = wrong { - return Err(ExpansionError( - format!("Argument `{name}' of `%{}' must be a {}, got a {} instead.", - mac.name, kind.name(), node.node_type()), - node.owned_site())); + for (index, (name, ..)) in mac.types.iter().enumerate() { + if mac.lazy.contains(name) { + continue; } + let Some(Definition::Value(nodes)) = definitions.get(name) else { continue }; + check_type(mac, index, nodes)?; } Ok(()) } - fn apply_macro(&self, mac: &Macro<'a>, node: &ParseNode<'a>, params: &[ParseNode<'a>]) + /// Expand a lazy argument where it was written, and check its type. + fn expand_thunk(&self, nodes: &[ParseNode<'a>], env: &'a Scope<'a>, typed: Option<(&'a Macro<'a>, usize)>) + -> Result, ExpansionError<'a>> { + let expanded = self.within(env).expand_nodes(nodes)?; + if let Some((mac, index)) = typed { + check_type(mac, index, &expanded)?; + } + Ok(expanded) + } + + fn apply_macro(&self, mac: &'a Macro<'a>, node: &ParseNode<'a>, params: &[ParseNode<'a>]) -> Result, ExpansionError<'a>> { // The body is expanded in a new scope within the scope the macro // was defined in (lexical scoping), not the scope of the caller. @@ -2681,7 +2704,8 @@ impl<'a> Expander<'a> { for name in &mac.lazy { if let Some(definition) = definitions.get_mut(name) && let Definition::Value(nodes) = definition { - *definition = Definition::Thunk(std::mem::take(nodes), self.scope); + let typed = mac.types.iter().position(|(typed, ..)| typed == name).map(|index| (mac, index)); + *definition = Definition::Thunk(std::mem::take(nodes), self.scope, typed); } } } @@ -2701,7 +2725,7 @@ impl<'a> Expander<'a> { Definition::Macro(mac) => Ok(*mac), // A variable may also be called, with no arguments: `(%name)`. Definition::Value(value) if params.is_empty() => Err(Ok(value.clone())), - Definition::Thunk(nodes, env) if params.is_empty() => Err(self.within(env).expand_nodes(nodes)), + Definition::Thunk(nodes, env, typed) if params.is_empty() => Err(self.expand_thunk(nodes, env, *typed)), Definition::Value(_) | Definition::Thunk(..) => Err(Ok(Box::default())), }); let mac = match definition { @@ -2812,10 +2836,8 @@ impl<'a> Expander<'a> { out.extend_from_slice(value); Ok(None) }, - Definition::Thunk(nodes, env) => { - for node in nodes { - self.within(env).expand_into(node, out)?; - } + Definition::Thunk(nodes, env, typed) => { + out.extend(self.expand_thunk(nodes, env, *typed)?); Ok(None) }, Definition::Macro(mac) if mac.params.is_empty() => Ok(Some(*mac)), @@ -2914,6 +2936,23 @@ fn list_argument<'p, 'a>(arguments: &'p [ParseNode<'a>]) -> &'p [ParseNode<'a>] } } +/// Check the argument bound to a macro's typed parameter (the `index`-th of its types). +fn check_type<'a>(mac: &Macro<'a>, index: usize, nodes: &[ParseNode<'a>]) -> Result<(), ExpansionError<'a>> { + let (name, kind, rest) = &mac.types[index]; + let wrong = if *rest { + nodes.iter().find(|node| !kind.admits(node)) + } else { + nodes.iter().find(|node| !kind.admits(node)).or(if nodes.len() == 1 { None } else { nodes.first() }) + }; + match wrong { + Some(node) => Err(ExpansionError( + format!("Argument `{name}' of `%{}' must be a {}, got a {} instead.", + mac.name, kind.name(), node.node_type()), + node.owned_site())), + None => Ok(()), + } +} + /// Whether expanded nodes count as true: nothing, `()`, `false` and `""` are false. /// (`"false"` is false too, being how YAML and TOML booleans arrive.) fn truthy(nodes: &[ParseNode]) -> bool { diff --git a/crates/seam/src/parse/lexer.rs b/crates/seam/src/parse/lexer.rs index fb0e963..db97d92 100644 --- a/crates/seam/src/parse/lexer.rs +++ b/crates/seam/src/parse/lexer.rs @@ -130,6 +130,12 @@ impl<'a> Lexer { &self.file.code } + /// The source file being read. + #[must_use] + pub fn file(&self) -> &SourceFile { + &self.file + } + fn increment_byte_offsets(&self, offset: usize) { let i = self.byte_offset.get(); let j = self.byte_offset_line.get(); diff --git a/crates/seam/src/parse/parser.rs b/crates/seam/src/parse/parser.rs index 1c49493..f1a9477 100644 --- a/crates/seam/src/parse/parser.rs +++ b/crates/seam/src/parse/parser.rs @@ -367,6 +367,12 @@ impl<'a> Parser { self.lexer.get_source() } + /// The source file being parsed. + #[must_use] + pub fn file(&self) -> &super::tokens::SourceFile { + self.lexer.file() + } + /// Parse whole source code, finishing off the lexer. pub fn parse(&'a self) -> Result, Box> { if self.literate { diff --git a/crates/seam/src/tests.rs b/crates/seam/src/tests.rs index 041e670..9852c76 100644 --- a/crates/seam/src/tests.rs +++ b/crates/seam/src/tests.rs @@ -33,6 +33,19 @@ fn literate_html(source: &str) -> Result { assemble::html::HTMLFormatter::new(tree).display().map_err(|err| err.message) } +/// Expand literate source and render it with the given formatter. +fn literate_as(source: &str, format: &str) -> Result { + use assemble::MarkupFormatter; + let context = Context::new(); + let expander = tree_builder(&context, Some(""), source.to_owned(), true); + let tree = expander.expand().map_err(|err| format!("{err}"))?; + let formatter: Box = match format { + "xml" => Box::new(assemble::xml::XMLFormatter::new(tree)), + _ => Box::new(assemble::css::CSSFormatter::new(tree)), + }; + formatter.display().map_err(|err| err.message) +} + /// Expand source and render it as CSS. fn css(source: &str) -> Result { use assemble::MarkupFormatter; @@ -489,6 +502,11 @@ mod cases { .contains("Argument `n' of `%r' must be a number, got a symbol instead.")); assert!(sexp("(%define (r &xs:number) ok) (%r 1 a)").unwrap_err().contains("`xs'")); assert!(sexp("(%define (g :n:number x) %n)").unwrap_err().contains("Default value of `:n'")); + // Lazy arguments are checked once expanded, each time they are used. + assert_sexp_eq("(%define (twice ~n:number) %n %n) (%twice (%+ 1 2))", " 3 3"); + assert!(sexp("(%define (twice ~n:number) %n %n) (%twice (%concat a b))").unwrap_err() + .contains("Argument `n' of `%twice' must be a number, got a string instead.")); + assert_sexp_eq("(%define (unless c ~body:number) (%if %c () %body)) (%unless true (%error x))", " ()"); } #[test] @@ -531,6 +549,26 @@ mod cases { fn test_exec_macro() { assert_sexp_eq("(%exec echo hi there) (%exec tr a-z A-Z :stdin shout)", "\"hi there\" \"SHOUT\""); assert!(sexp("(%exec false)").unwrap_err().contains("`%exec false' failed")); + // Input and output larger than a pipe's buffer do not deadlock. + let big = "x".repeat(1 << 20); + assert_sexp_eq(&format!("(%length (%exec cat :stdin \"{big}\"))"), "1048576"); + } + + #[test] + fn test_literate_xml_and_css() { + assert_eq!(literate_as("Hi (%do (i x)) & bye", "xml").as_deref(), Ok("Hi x & bye")); + assert_eq!(literate_as("body { margin: 0; }\n(%do (p :color red))", "css").as_deref(), + Ok("body { margin: 0; }\np {\n color: red;\n}")); + } + + #[test] + fn test_markdown_from_its_file() { + // Once its frontmatter is split off, a body starting with `---` is still content. + assert_output_eq("(%markdown :only content (%embed \"tests/fixtures/rule.md\"))", + "\"
\\n

not: frontmatter

\\n

Text.

\\n\""); + // Macros in embedded markdown find files from, and know of, the markdown's own file. + assert_output_eq("(%markdown (%embed \"tests/fixtures/nested/note.md\"))", + "\"

Inner: inner, from note.md in nested.

\\n\""); } #[test] diff --git a/crates/seam/tests/fixtures/nested/note.md b/crates/seam/tests/fixtures/nested/note.md new file mode 100644 index 0000000..de5da00 --- /dev/null +++ b/crates/seam/tests/fixtures/nested/note.md @@ -0,0 +1 @@ +Inner: (%include "inner.sex"), from (%path/basename (%path/this)) in (%path/basename (%path/here)). diff --git a/crates/seam/tests/fixtures/rule.md b/crates/seam/tests/fixtures/rule.md new file mode 100644 index 0000000..a516c12 --- /dev/null +++ b/crates/seam/tests/fixtures/rule.md @@ -0,0 +1,7 @@ +--- +title: Rule +--- +--- +not: frontmatter +--- +Text.