diff --git a/README.md b/README.md index 619caf9..6a9b046 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,8 @@ Read the [USAGE.md](USAGE.md) file for code examples and documentation. - XML (`--xml`; including: SVG, MathML) - HTML (`--html`; SGML) - CSS (`--css`) + - JSON (`--json`) + - JavaScript (`--js`; written as s-expressions) - SExp (`--sexp`; S-expression, basically a macro expansion utility) - Plain Text (`--text`; renders escaped strings to text) @@ -171,7 +173,9 @@ seam run build.sex - [x] Add keyword macro arguments. - [x] Caching or checking time-stamps as to not regenerate unmodified source files: `(%write path :from (sources...) ...)`, and unchanged files are not rewritten. - [x] HTML object `style="..."` object should handle s-expressions well, (e.g. `(p :style (:color red :border none) Hello World)`) - - [ ] Add more supported formats (`JSON`, `JS`, `TOML`, &c.). + - [x] JSON output (`--json`, `%formatter/json`), the reverse of `%json`. + - [x] JavaScript output (`--js`, `%formatter/js`), written as s-expressions: `(const f (=> (x) (* x x)))`. + - [ ] Add more supported formats (`TOML`, &c.). - [x] Allow for arbitrary embedding of code with their REPLs, that can be run by a LISP interpreter (or any other language), for example. (e.g. `(%chez (+ 1 2))` executes `(+ 1 2)` with Chez-Scheme LISP, and places the result in the source (i.e. `3`). diff --git a/USAGE.md b/USAGE.md index c2f6458..a80f904 100644 --- a/USAGE.md +++ b/USAGE.md @@ -219,10 +219,76 @@ Lists made by `%range`, `%take`, `%drop`, `%get` (slices), `%reverse` and #### Formatters - `(%formatter/html ...)`, `(%formatter/xml ...)`, `(%formatter/css ...)`, - `(%formatter/text ...)` and `(%formatter/sexp ...)` generate their arguments - with that formatter, as text. Markup is kept as it is (raw), while text and - s-expressions are escaped in the output. `:document true` generates a whole - document, e.g. `(%write "out/index.html" (%formatter/html :document true ...))`. + `(%formatter/json ...)`, `(%formatter/js ...)`, `(%formatter/text ...)` and + `(%formatter/sexp ...)` generate their arguments with that formatter, as + text. Markup, JSON and JavaScript are kept as they are (raw), while text and s-expressions are escaped in the + output. `:document true` generates a whole document, e.g. + `(%write "out/index.html" (%formatter/html :document true ...))`. + +#### JSON, YAML and TOML +`(%json "...")`, `(%yaml "...")` and `(%toml "...")` read data into +s-expressions, defining each value under its path as well (e.g. `%a/0`), and +the JSON formatter (`--json`, or `%formatter/json`) writes it back out: +- a list of `:key value` attributes is an object, and any other list an array; +- strings are strings, and numbers are numbers; +- the symbols `true`, `false` and `null` are themselves, and other symbols are strings. + +So `(%json "{\"a\": [1, \"2\", null]}")` reads as `(:a (1 "2" null))`, which +is written out as `{"a":[1,"2",null]}` again. A file's top level is written as +one value if it is a single value, or else as the items of a list. A document +is indented, one item per line, while `%formatter/json` is compact unless given +`:document true`. + +JSON is raw text, so it is written as it is, and it can be given to a page's +scripts as a data block (strings containing ` (x (= y 1)) (+ x y))`, `(function name (params...) body...)`, + `async`, generators and `(class Name :extends Base members...)`. A function + returns its last expression. +- `(import D (a (as b c)) from "./a.js")` → `import D, {a, b as c} from "./a.js"`, + and `(export (const x 1))`, `(export default x)`, `(export (a b))`. +- To call a function named like one of these forms, escape it: `(\array 1)`. + +All of JavaScript's syntax is covered; see [docs/javascript.md](docs/javascript.md). + +A document is indented, one statement per line, while `%formatter/js` is +compact unless given `:document true`. The generated JavaScript is raw text, +so a `script` containing just that is written as it is. #### Shell-style variables `%{name...}` manipulates a variable's text, as `${name...}` does in a shell: diff --git a/crates/seam/src/assemble/html.rs b/crates/seam/src/assemble/html.rs index f041857..2e27127 100644 --- a/crates/seam/src/assemble/html.rs +++ b/crates/seam/src/assemble/html.rs @@ -3,8 +3,8 @@ use super::{child_whitespace, write_escaped, Escaping, GenerationError, MarkupFormatter, Formatter}; use super::{ text::PlainTextFormatter, - sexp::SExpFormatter, xml::XMLFormatter, + json, css::{self, CSSFormatter}, }; @@ -185,9 +185,16 @@ impl<'a> HTMLFormatter<'a> { } }, "script" => { - // TODO: Generating JavaScript from S-expressions is not implemented. - // For now, just treat it as a completely source-code preserving. - SExpFormatter::generate_children(f, rest)?; + // When just a string is passed, it is the script, written as is. + if let [ParseNode::String(script) | ParseNode::Raw(script)] = rest { + write!(f, "{}", script.value)?; + } else { + // TODO: Generating JavaScript from S-expressions is not implemented. + // For now, the source is kept as written (see [`generate_script`]). + for (index, node) in rest.iter().enumerate() { + generate_script(f, node, child_whitespace(index, node))?; + } + } }, "math" | "svg" => { // and are subsets of XML. XMLFormatter::generate_children(f, rest)?; @@ -238,6 +245,28 @@ const METADATA_ELEMENTS: [&str; 8] = [ ]; /// Lower-cased tag name of an element node, e.g. `(Body ...)` gives `body`. +/// Write the source of a script as it was written, except that strings are +/// JavaScript string literals, and raw text (e.g. JSON) is written as is. +fn generate_script<'a>(f: Formatter, node: &ParseNode<'a>, leading: &str) -> Result<(), GenerationError<'a>> { + write!(f, "{leading}")?; + match node { + ParseNode::Symbol(atom) | ParseNode::Number(atom) | ParseNode::Raw(atom) => write!(f, "{}", atom.value)?, + ParseNode::String(string) => json::write_string(f, &string.value)?, + ParseNode::List { nodes, end_token, .. } => { + write!(f, "(")?; + for node in nodes { + generate_script(f, node, node.leading_whitespace())?; + } + write!(f, "{})", end_token.leading_whitespace)?; + }, + ParseNode::Attribute { keyword, node, .. } => { + write!(f, ":{keyword}")?; + generate_script(f, node, node.leading_whitespace())?; + }, + } + Ok(()) +} + fn tag_name(node: &ParseNode) -> Option { match node { ParseNode::List { nodes, .. } => nodes.first() diff --git a/crates/seam/src/assemble/js.rs b/crates/seam/src/assemble/js.rs new file mode 100644 index 0000000..4945bdf --- /dev/null +++ b/crates/seam/src/assemble/js.rs @@ -0,0 +1,987 @@ +//! Output JavaScript, written as s-expressions. +//! A list is a call, `(f a b)` → `f(a, b)`, unless it starts with an operator +//! or a keyword, e.g. `(+ a b)` → `a + b`, `(. a b)` → `a.b`, +//! `(const x 1)` → `const x = 1`, `(=> (x) (* x x))` → `(x) => x * x`. +//! Symbols and numbers are written as they are, and strings as JavaScript strings. +//! The whole syntax is described in `docs/javascript.md`. + +use super::{MarkupFormatter, GenerationError, Formatter}; +use super::json::write_string; +use crate::parse::parser::{ParseNode, ParseTree}; + +#[derive(Debug, Clone)] +pub struct JSFormatter<'a> { + pub tree: ParseTree<'a>, +} + +/// Operators written between any number of operands, `(+ a b c)` → `a + b + c`. +const BINARY: &[&str] = &[ + "+", "-", "*", "/", "%", "**", + "&&", "||", "??", "&", "|", "^", "<<", ">>", ">>>", +]; +/// Operators written between exactly two operands. +const BINARY_TWO: &[&str] = &[ + "==", "===", "!=", "!==", "<", ">", "<=", ">=", "in", "instanceof", + "=", "+=", "-=", "*=", "/=", "%=", "**=", "&&=", "||=", "??=", + "&=", "|=", "^=", "<<=", ">>=", ">>>=", +]; +/// Operators written before their one operand, `(! a)` → `!a` +/// (`+` and `-` are too, when given one operand). +const UNARY: &[&str] = &["!", "~", "typeof", "void", "delete", "await", "++", "--", "..."]; +/// Keywords that start statements, which are not expressions. +const STATEMENTS: &[&str] = &[ + "const", "let", "var", "using", "await-using", + "if", "for", "for-await", "while", "do-while", "do", "switch", "try", + "return", "throw", "break", "continue", "debugger", "with", "export", "//", "/*", +]; +/// Keywords that start declarations, which can be exported. +const DECLARATIONS: &[&str] = &[ + "const", "let", "var", "using", "await-using", "function", "function*", "class", "async", +]; +/// Forms that are expressions, but written with their own syntax. +const EXPRESSIONS: &[&str] = &[ + ".", "?.", "[]", "array", "object", "regex", "`", "new", "?", ",", "=>", + "function", "function*", "async", "class", "++post", "--post", "yield", "yield*", +]; + +type Result<'a> = std::result::Result<(), GenerationError<'a>>; + +fn error<'a>(message: &str, node: &ParseNode<'a>) -> GenerationError<'a> { + GenerationError::new("JavaScript", message, node.site()) +} + +/// A symbol, unless it is escaped as a name, `\array`. +/// `+` and `-` and the like are read as numbers, so they are too. +fn word<'n>(node: &'n ParseNode) -> Option<&'n str> { + match node { + ParseNode::Symbol(symbol) if !(symbol.is_escaped() && is_identifier(&symbol.value)) => Some(&symbol.value), + ParseNode::Number(number) if number.value.parse::().is_err() + && !number.value.starts_with(|c: char| c.is_ascii_digit()) => Some(&number.value), + _ => None, + } +} + +/// Whether a node is the given word. +fn is_word(node: &ParseNode, expected: &str) -> bool { + word(node) == Some(expected) +} + +/// The keyword or operator a list starts with. +fn head<'n>(node: &'n ParseNode) -> Option<&'n str> { + node.list().and_then(|nodes| nodes.first()).and_then(word) +} + +/// The arguments of a list, after its head. +fn arguments<'n, 'a>(node: &'n ParseNode<'a>) -> &'n [ParseNode<'a>] { + node.list().map_or(&[], |nodes| nodes.get(1..).unwrap_or_default()) +} + +/// Whether a node is a statement, and not an expression. +fn is_statement(node: &ParseNode) -> bool { + let args = arguments(node); + match head(node) { + Some(keyword) if STATEMENTS.contains(&keyword) => true, + Some(label) if label.len() > 1 && label.ends_with(':') => true, + Some("import") => args.iter().any(|arg| is_word(arg, "from")), + Some("function" | "function*" | "class") => matches!(args.first(), Some(ParseNode::Symbol(_))), + Some("async") => args.first().is_some_and(is_statement), + _ => false, + } +} + +/// Whether a list is a pattern or a value written in brackets or braces. +fn is_pattern(node: &ParseNode) -> bool { + matches!(head(node), Some("array" | "object")) +} + +/// Whether a key can be written without quotes, `{a: 1}` and `x.a`. +fn is_identifier(key: &str) -> bool { + let mut chars = key.chars(); + chars.next().is_some_and(|c| c.is_alphabetic() || c == '_' || c == '$') + && chars.all(|c| c.is_alphanumeric() || c == '_' || c == '$') +} + +/// Whether an expression is written without any operator outside of +/// brackets, so it needs no parentheses as an operand. +fn is_primary(node: &ParseNode) -> bool { + match node { + ParseNode::List { nodes, .. } => match head(node) { + Some("." | "?." | "[]" | "array" | "object" | "regex" | "`") => true, + Some(keyword) => !(BINARY.contains(&keyword) || BINARY_TWO.contains(&keyword) + || UNARY.contains(&keyword) || EXPRESSIONS.contains(&keyword) + || STATEMENTS.contains(&keyword)), + // An object of attributes, or a call. + None => !nodes.is_empty(), + }, + ParseNode::Number(number) => !number.value.starts_with(['-', '+']), + _ => true, + } +} + +/// Whether an expression has no calls, so it can be the class of `new`. +fn is_constructor(node: &ParseNode) -> bool { + match node { + ParseNode::List { nodes, .. } => matches!(head(node), Some("." | "[]")) + && nodes[1..].iter().all(is_constructor), + _ => true, + } +} + +impl<'a> JSFormatter<'a> { + #[must_use] + pub fn new(tree: ParseTree<'a>) -> Self { + Self { + tree + } + } +} + +/// Start a new line at an indentation level, when pretty-printing, +/// or else separate with a space. +fn newline(f: Formatter, indent: Option) -> std::fmt::Result { + match indent { + Some(indent) => write!(f, "\n{:width$}", "", width = 2 * indent), + None => write!(f, " "), + } +} + +fn deeper(indent: Option) -> Option { + indent.map(|indent| indent + 1) +} + +/// Generate statements, one after another. +fn statements<'a>(f: Formatter, nodes: &[ParseNode<'a>], indent: Option) -> Result<'a> { + for (index, node) in nodes.iter().enumerate() { + if index > 0 { + newline(f, indent)?; + } + statement(f, node, indent)?; + } + Ok(()) +} + +/// Generate a block of statements in braces. With `returns`, the last +/// expression is returned, as it is the result of a function. +fn block<'a>(f: Formatter, nodes: &[ParseNode<'a>], indent: Option, returns: bool) -> Result<'a> { + write!(f, "{{")?; + let inner = deeper(indent); + for (index, node) in nodes.iter().enumerate() { + newline(f, inner)?; + if returns && index + 1 == nodes.len() && !is_statement(node) { + write!(f, "return ")?; + expression(f, node, inner)?; + write!(f, ";")?; + } else { + statement(f, node, inner)?; + } + } + if !nodes.is_empty() { + newline(f, indent)?; + } + write!(f, "}}")?; + Ok(()) +} + +/// A body of a statement: a block from `(do ...)`, or a single statement in braces. +fn branch<'a>(f: Formatter, node: &ParseNode<'a>, indent: Option) -> Result<'a> { + if head(node) == Some("do") { + block(f, arguments(node), indent, false) + } else { + block(f, std::slice::from_ref(node), indent, false) + } +} + +fn statement<'a>(f: Formatter, node: &ParseNode<'a>, indent: Option) -> Result<'a> { + let Some(keyword) = head(node) else { + return expression_statement(f, node, indent); + }; + let args = arguments(node); + match (keyword, args) { + ("const" | "let" | "var" | "using" | "await-using", _) => { + declaration(f, node, indent)?; + write!(f, ";")?; + }, + ("if", [condition, then, otherwise @ ..]) => { + write!(f, "if (")?; + expression(f, condition, indent)?; + write!(f, ") ")?; + branch(f, then, indent)?; + match otherwise { + [] => {}, + [otherwise] => { + write!(f, " else ")?; + if head(otherwise) == Some("if") { + statement(f, otherwise, indent)?; + } else { + branch(f, otherwise, indent)?; + } + }, + _ => return Err(error("`(if condition then else)' takes at most one else branch, \ + use `(do ...)' for more statements.", node)), + } + }, + ("for" | "for-await", [binding, of, iterable, body @ ..]) + if is_word(of, "of") || (keyword == "for" && is_word(of, "in")) => { + write!(f, "{} (", if keyword == "for" { "for" } else { "for await" })?; + if let Some("const" | "let" | "var" | "using" | "await-using") = head(binding) { + declaration(f, binding, indent)?; + } else { + write!(f, "const ")?; + expression(f, binding, indent)?; + } + write!(f, " {} ", word(of).unwrap_or_default())?; + expression(f, iterable, indent)?; + write!(f, ") ")?; + block(f, body, indent, false)?; + }, + ("for", [init, test, update, body @ ..]) => { + write!(f, "for (")?; + match init { + ParseNode::List { nodes, .. } if nodes.is_empty() => {}, + _ if matches!(head(init), Some("const" | "let" | "var")) => declaration(f, init, indent)?, + _ => expression(f, init, indent)?, + } + for part in [test, update] { + write!(f, ";")?; + if !matches!(part, ParseNode::List { nodes, .. } if nodes.is_empty()) { + write!(f, " ")?; + expression(f, part, indent)?; + } + } + write!(f, ") ")?; + block(f, body, indent, false)?; + }, + ("while", [condition, body @ ..]) => { + write!(f, "while (")?; + expression(f, condition, indent)?; + write!(f, ") ")?; + block(f, body, indent, false)?; + }, + ("do-while", [condition, body @ ..]) => { + write!(f, "do ")?; + block(f, body, indent, false)?; + write!(f, " while (")?; + expression(f, condition, indent)?; + write!(f, ");")?; + }, + ("do", body) => block(f, body, indent, false)?, + ("switch", [value, clauses @ ..]) => { + write!(f, "switch (")?; + expression(f, value, indent)?; + write!(f, ") {{")?; + let inner = deeper(indent); + for clause in clauses { + newline(f, inner)?; + let body = match (head(clause), arguments(clause)) { + (Some("case"), [value, body @ ..]) => { + write!(f, "case ")?; + expression(f, value, inner)?; + body + }, + (Some("default"), body) => { + write!(f, "default")?; + body + }, + _ => return Err(error("A `switch' has only `(case value body...)' \ + and `(default body...)' clauses.", clause)), + }; + write!(f, ":")?; + for node in body { + newline(f, deeper(inner))?; + statement(f, node, deeper(inner))?; + } + } + newline(f, indent)?; + write!(f, "}}")?; + }, + ("try", _) => { + let handlers = args.iter().rev() + .take_while(|node| matches!(head(node), Some("catch" | "finally"))) + .count(); + let (body, handlers) = args.split_at(args.len() - handlers); + if handlers.is_empty() { + return Err(error("`(try body... (catch e ...) (finally ...))' needs a `catch' or `finally'.", node)); + } + write!(f, "try ")?; + block(f, body, indent, false)?; + for handler in handlers { + match (head(handler), arguments(handler)) { + (Some("catch"), [binding, body @ ..]) => { + write!(f, " catch ")?; + if !matches!(binding, ParseNode::List { nodes, .. } if nodes.is_empty()) { + write!(f, "(")?; + expression(f, binding, indent)?; + write!(f, ") ")?; + } + block(f, body, indent, false)?; + }, + (Some("finally"), body) => { + write!(f, " finally ")?; + block(f, body, indent, false)?; + }, + _ => return Err(error("`(catch binding body...)' needs a binding, \ + or `()' for none.", handler)), + } + } + }, + ("return" | "throw", [value]) => { + write!(f, "{keyword} ")?; + expression(f, value, indent)?; + write!(f, ";")?; + }, + ("return" | "break" | "continue" | "debugger", []) => write!(f, "{keyword};")?, + ("break" | "continue", [label @ ParseNode::Symbol(_)]) => { + write!(f, "{keyword} ")?; + expression(f, label, indent)?; + write!(f, ";")?; + }, + ("with", [object, body @ ..]) => { + write!(f, "with (")?; + expression(f, object, indent)?; + write!(f, ") ")?; + block(f, body, indent, false)?; + }, + (label, body) if label.len() > 1 && label.ends_with(':') => { + write!(f, "{label} ")?; + match body { + [statement_] => statement(f, statement_, indent)?, + body => block(f, body, indent, false)?, + } + }, + ("//" | "/*", text) => { + // So `` cannot end a script. + let text = text.iter().map(text_of).collect::>().join(" ").replace(" 0 { + newline(f, indent)?; + } + write!(f, "// {line}")?; + } + // A line comment must end its line, even when compact. + if indent.is_none() { + writeln!(f)?; + } + } else { + write!(f, "/* {} */", text.replace("*/", "*\\/"))?; + } + }, + ("import", [source @ ParseNode::String(_), rest @ ..]) => { + write!(f, "import ")?; + expression(f, source, indent)?; + import_attributes(f, rest, indent)?; + write!(f, ";")?; + }, + ("import" | "export", _) if args.iter().any(|arg| is_word(arg, "from")) => { + write!(f, "{keyword} ")?; + module_clause(f, node, args, indent)?; + write!(f, ";")?; + }, + ("export", [default, value]) if is_word(default, "default") => { + write!(f, "export default ")?; + if is_statement(value) { + statement(f, value, indent)?; + } else { + expression(f, value, indent)?; + write!(f, ";")?; + } + }, + ("export", [declaration_]) if head(declaration_).is_some_and(|head| DECLARATIONS.contains(&head)) => { + // Only a named function or class is a declaration, not an expression. + if !(is_statement(declaration_) || matches!(head(declaration_), Some("const" | "let" | "var" | "using" | "await-using"))) { + return Err(error("Only a declaration, or a named function or class, can be exported; \ + use `(export default value)' to export a value.", declaration_)); + } + write!(f, "export ")?; + statement(f, declaration_, indent)?; + }, + ("export", [names @ ParseNode::List { .. }]) => { + write!(f, "export ")?; + module_clause(f, node, std::slice::from_ref(names), indent)?; + write!(f, ";")?; + }, + ("function" | "function*" | "class", [ParseNode::Symbol(_), ..]) => expression(f, node, indent)?, + ("async", [inner]) if is_statement(inner) => expression(f, node, indent)?, + _ if is_statement(node) => return Err(error(&format!("Malformed `{keyword}' statement."), node)), + _ => expression_statement(f, node, indent)?, + } + Ok(()) +} + +/// An expression as a statement, in parentheses if it would +/// otherwise read as a block or a declaration. +fn expression_statement<'a>(f: Formatter, node: &ParseNode<'a>, indent: Option) -> Result<'a> { + let mut buffer = String::new(); + expression(&mut buffer, node, indent)?; + let ambiguous = buffer.starts_with('{') || buffer.starts_with("let [") + || ["function", "class", "async function"].iter().any(|word| { + buffer.strip_prefix(word).is_some_and(|rest| !rest.starts_with(|c: char| c.is_alphanumeric() || c == '_' || c == '$')) + }); + if ambiguous { + write!(f, "({buffer});")?; + } else { + write!(f, "{buffer};")?; + } + Ok(()) +} + +/// The text of a comment. +fn text_of(node: &ParseNode) -> String { + match node { + ParseNode::String(atom) | ParseNode::Symbol(atom) | ParseNode::Number(atom) | ParseNode::Raw(atom) => atom.value.to_string(), + _ => String::new(), + } +} + +/// `(const x 1)`, `(let (a 1) (b))`, without the semicolon. +fn declaration<'a>(f: Formatter, node: &ParseNode<'a>, indent: Option) -> Result<'a> { + let keyword = head(node).unwrap_or_default(); + let args = arguments(node); + write!(f, "{} ", if keyword == "await-using" { "await using" } else { keyword })?; + let declarator = |f: Formatter, nodes: &[ParseNode<'a>]| -> Result<'a> { + match nodes { + [name] => expression(f, name, indent), + [name, value] => { + expression(f, name, indent)?; + write!(f, " = ")?; + expression(f, value, indent) + }, + _ => Err(error(&format!("`({keyword} name value)' takes a name and at most one value."), node)), + } + }; + match args { + [ParseNode::List { .. }, ..] if !is_pattern(&args[0]) => { + for (index, pair) in args.iter().enumerate() { + if index > 0 { + write!(f, ", ")?; + } + let ParseNode::List { nodes, .. } = pair else { + return Err(error(&format!("Each of several declarations is a list, \ + `({keyword} (a 1) (b 2))'."), pair)); + }; + declarator(f, nodes)?; + } + Ok(()) + }, + [] => Err(error(&format!("`({keyword} name value)' needs a name."), node)), + args => declarator(f, args), + } +} + +/// The words of an import or export, `D ({} a (as b c)) from "x"`. +fn module_clause<'a>(f: Formatter, node: &ParseNode<'a>, args: &[ParseNode<'a>], indent: Option) -> Result<'a> { + let from = args.iter().position(|arg| is_word(arg, "from")).unwrap_or(args.len()); + for (index, part) in args[..from].iter().enumerate() { + if index > 0 { + write!(f, ", ")?; + } + match part { + ParseNode::List { nodes, .. } if head(part) == Some("as") => specifier(f, part, &nodes[1..])?, + ParseNode::List { nodes, .. } => { + write!(f, "{{")?; + for (index, name) in nodes.iter().enumerate() { + write!(f, "{}", if index > 0 { ", " } else { "" })?; + match name { + ParseNode::List { nodes, .. } if head(name) == Some("as") => specifier(f, name, &nodes[1..])?, + name => module_name(f, name)?, + } + } + write!(f, "}}")?; + }, + part => module_name(f, part)?, + } + } + if let Some(rest) = args.get(from..).filter(|rest| !rest.is_empty()) { + let [_, source, attributes @ ..] = rest else { + return Err(error("`from' needs the module to come from.", node)); + }; + write!(f, " from ")?; + expression(f, source, indent)?; + import_attributes(f, attributes, indent)?; + } + Ok(()) +} + +/// `(as a b)` → `a as b`. +fn specifier<'a>(f: Formatter, node: &ParseNode<'a>, names: &[ParseNode<'a>]) -> Result<'a> { + let [name, alias] = names else { + return Err(error("`(as name alias)' takes a name and an alias.", node)); + }; + module_name(f, name)?; + write!(f, " as ")?; + module_name(f, alias) +} + +/// A name in an import or export, which may be a string. +fn module_name<'a>(f: Formatter, node: &ParseNode<'a>) -> Result<'a> { + match node { + ParseNode::String(name) => write_string(f, &name.value)?, + ParseNode::Symbol(name) | ParseNode::Number(name) => write!(f, "{}", name.value)?, + _ => return Err(error("Expected a name to import or export.", node)), + } + Ok(()) +} + +/// `:with (:type "json")` → ` with {type: "json"}`. +fn import_attributes<'a>(f: Formatter, nodes: &[ParseNode<'a>], indent: Option) -> Result<'a> { + for node in nodes { + match node { + ParseNode::Attribute { keyword, node: value, .. } if keyword == "with" => { + write!(f, " with ")?; + expression(f, value, indent)?; + }, + _ => return Err(error("Only `:with (:key value)' can come after the module.", node)), + } + } + Ok(()) +} + +/// `(function name? (params...) body...)`, returning its last expression. +fn function<'a>(f: Formatter, node: &ParseNode<'a>, indent: Option) -> Result<'a> { + let keyword = head(node).unwrap_or_default(); + let (name, rest) = match arguments(node) { + [ParseNode::Symbol(name), rest @ ..] => (Some(name), rest), + rest => (None, rest), + }; + let Some((params, body)) = rest.split_first() else { + return Err(error(&format!("`({keyword} name (params...) body...)' needs its parameters."), node)); + }; + write!(f, "{keyword}")?; + if let Some(name) = name { + write!(f, " {}", name.value)?; + } + parameters(f, params, indent)?; + write!(f, " ")?; + // A generator's result is what it yields, so it returns nothing itself. + block(f, body, indent, keyword == "function") +} + +/// Parameters in parentheses, `(a (= b 1))` → `(a, b = 1)`. +fn parameters<'a>(f: Formatter, params: &ParseNode<'a>, indent: Option) -> Result<'a> { + let ParseNode::List { nodes, .. } = params else { + return Err(error("Parameters are given as a list, e.g. `(a b)'.", params)); + }; + write!(f, "(")?; + list(f, nodes, indent)?; + write!(f, ")")?; + Ok(()) +} + +/// Expressions separated by commas. +fn list<'a>(f: Formatter, nodes: &[ParseNode<'a>], indent: Option) -> Result<'a> { + for (index, node) in nodes.iter().enumerate() { + if index > 0 { + write!(f, ", ")?; + } + expression(f, node, indent)?; + } + Ok(()) +} + +/// Generate an expression as an operand, in parentheses unless it is primary. +fn operand<'a>(f: Formatter, node: &ParseNode<'a>, indent: Option) -> Result<'a> { + if is_primary(node) { + expression(f, node, indent) + } else { + write!(f, "(")?; + expression(f, node, indent)?; + write!(f, ")")?; + Ok(()) + } +} + +/// A computed key, `([] k)`, of a property or a method. +fn computed<'n, 'a>(node: &'n ParseNode<'a>) -> Option<&'n ParseNode<'a>> { + match (head(node), arguments(node)) { + (Some("[]"), [key]) => Some(key), + _ => None, + } +} + +/// Generate an expression. +fn expression<'a>(f: Formatter, node: &ParseNode<'a>, indent: Option) -> Result<'a> { + let nodes = match node { + ParseNode::Symbol(atom) | ParseNode::Number(atom) | ParseNode::Raw(atom) => { + write!(f, "{}", atom.value)?; + return Ok(()); + }, + ParseNode::String(string) => { + write_string(f, &string.value)?; + return Ok(()); + }, + ParseNode::Attribute { .. } => return Err(error( + "A keyword attribute can only be part of an object (a list of attributes).", node)), + ParseNode::List { nodes, .. } => nodes, + }; + let Some(first) = nodes.first() else { + return Err(error("An empty list is not an expression, use `(array)' for an empty array \ + (`()' is only a hole in an array or an empty part of a `for').", node)); + }; + if first.is_attribute() { + return object(f, nodes, indent); + } + let args = &nodes[1..]; + let keyword = head(node).unwrap_or_default(); + match (keyword, args) { + ("." | "?.", [object, keys @ ..]) if !keys.is_empty() => { + let dot = if keyword == "." { "." } else { "?." }; + // `1.x` would read as the number `1.`, so it is `(1).x`. + if matches!(object, ParseNode::Number(_)) { + write!(f, "(")?; + expression(f, object, indent)?; + write!(f, ")")?; + } else { + operand(f, object, indent)?; + } + for key in keys { + match (key, computed(key)) { + (ParseNode::Symbol(name), _) if is_identifier(&name.value) || name.value.starts_with('#') => + write!(f, "{dot}{}", name.value)?, + (_, Some(key)) | (key, None) => { + write!(f, "{}[", if keyword == "." { "" } else { "?." })?; + expression(f, key, indent)?; + write!(f, "]")?; + }, + } + } + }, + ("[]", [object, keys @ ..]) if !keys.is_empty() => { + operand(f, object, indent)?; + for key in keys { + write!(f, "[")?; + expression(f, key, indent)?; + write!(f, "]")?; + } + }, + ("array", items) => { + write!(f, "[")?; + for (index, item) in items.iter().enumerate() { + if index > 0 { + write!(f, ", ")?; + } + match item { + // A hole. + ParseNode::List { nodes, .. } if nodes.is_empty() => { + if index + 1 == items.len() { + write!(f, ",")?; + } + }, + item => expression(f, item, indent)?, + } + } + write!(f, "]")?; + }, + ("object", entries) => object(f, entries, indent)?, + ("regex", [pattern, flags @ ..]) if flags.len() <= 1 => { + let pattern = text_of(pattern); + write!(f, "/")?; + if pattern.is_empty() { + write!(f, "(?:)")?; + } + // Every `/` is escaped, even in a class, so ` write!(f, "\\n")?, + '\r' => write!(f, "\\r")?, + '/' if !escaped => write!(f, "\\/")?, + c => write!(f, "{c}")?, + } + escaped = c == '\\' && !escaped; + } + write!(f, "/")?; + if let Some(flags) = flags.first() { + write!(f, "{}", text_of(flags))?; + } + }, + ("`", parts) => { + let parts = match parts { + [ParseNode::Attribute { keyword, node: tag, .. }, parts @ ..] if keyword == "tag" => { + operand(f, tag, indent)?; + parts + }, + parts => parts, + }; + write!(f, "`")?; + // Neighbouring strings are written together, so `previous` + // carries over from one to the next. + let mut previous = '\0'; + for part in parts { + if let ParseNode::String(text) = part { + let mut chars = text.value.chars().peekable(); + while let Some(c) = chars.next() { + match c { + '`' | '\\' => write!(f, "\\{c}")?, + '$' if chars.peek() == Some(&'{') => write!(f, "\\$")?, + // So `` cannot end a script. + '/' if previous == '<' => write!(f, "\\/")?, + c => write!(f, "{c}")?, + } + previous = c; + } + } else { + write!(f, "${{")?; + expression(f, part, indent)?; + write!(f, "}}")?; + previous = '}'; + } + } + write!(f, "`")?; + }, + ("new", [class, items @ ..]) => { + write!(f, "new ")?; + if is_constructor(class) && is_primary(class) { + expression(f, class, indent)?; + } else { + write!(f, "(")?; + expression(f, class, indent)?; + write!(f, ")")?; + } + write!(f, "(")?; + list(f, items, indent)?; + write!(f, ")")?; + }, + ("?", [condition, then, otherwise]) => { + operand(f, condition, indent)?; + write!(f, " ? ")?; + operand(f, then, indent)?; + write!(f, " : ")?; + operand(f, otherwise, indent)?; + }, + (",", items) if !items.is_empty() => { + write!(f, "(")?; + list(f, items, indent)?; + write!(f, ")")?; + }, + ("=>", [params, body @ ..]) if !body.is_empty() => { + parameters(f, params, indent)?; + write!(f, " => ")?; + match body { + [body] if body.list().is_some_and(|nodes| nodes.first().is_some_and(ParseNode::is_attribute)) + || head(body) == Some("object") => { + write!(f, "(")?; + expression(f, body, indent)?; + write!(f, ")")?; + }, + [body] if !is_statement(body) => expression(f, body, indent)?, + body => block(f, body, indent, true)?, + } + }, + ("function" | "function*", _) => function(f, node, indent)?, + ("async", [inner]) if matches!(head(inner), Some("function" | "function*" | "=>")) => { + write!(f, "async ")?; + expression(f, inner, indent)?; + }, + ("class", _) => class(f, node, indent)?, + ("+" | "-", [value]) => { + write!(f, "{keyword}")?; + operand(f, value, indent)?; + }, + ("++post" | "--post", [value]) => { + operand(f, value, indent)?; + write!(f, "{}", &keyword[..2])?; + }, + ("yield" | "yield*", []) if keyword == "yield" => write!(f, "yield")?, + ("yield" | "yield*", [value]) => { + write!(f, "{keyword} ")?; + operand(f, value, indent)?; + }, + (_, [value]) if UNARY.contains(&keyword) => { + let space = if keyword.starts_with(char::is_alphabetic) { " " } else { "" }; + write!(f, "{keyword}{space}")?; + operand(f, value, indent)?; + }, + (_, [first, rest @ ..]) if (BINARY.contains(&keyword) && !rest.is_empty()) + || (BINARY_TWO.contains(&keyword) && rest.len() == 1) => { + operand(f, first, indent)?; + for value in rest { + write!(f, " {keyword} ")?; + operand(f, value, indent)?; + } + }, + _ if is_statement(node) => return Err(error(&format!( + "`{keyword}' is a statement, not an expression{}.", + if keyword == "if" { ", use `(? condition then else)' instead" } else { "" }), node)), + _ if BINARY.contains(&keyword) || BINARY_TWO.contains(&keyword) + || UNARY.contains(&keyword) || EXPRESSIONS.contains(&keyword) => return Err(error(&format!( + "Wrong number of operands given to `{keyword}'."), node)), + // `(f?. x)` → `f?.(x)`. + (callee, _) if callee.len() > 2 && callee.ends_with("?.") => { + write!(f, "{callee}(")?; + list(f, args, indent)?; + write!(f, ")")?; + }, + // Otherwise, it is a call. + _ => { + operand(f, first, indent)?; + write!(f, "(")?; + list(f, args, indent)?; + write!(f, ")")?; + }, + } + Ok(()) +} + +/// A key of a property, method or field. +fn key<'a>(f: Formatter, node: &ParseNode<'a>, indent: Option) -> Result<'a> { + match (node, computed(node)) { + (ParseNode::Symbol(name) | ParseNode::Number(name), _) => write!(f, "{}", name.value)?, + (ParseNode::String(name), _) => write_string(f, &name.value)?, + (_, Some(key)) => { + write!(f, "[")?; + expression(f, key, indent)?; + write!(f, "]")?; + }, + _ => return Err(error("A key is a name, a string, or `([] key)' for a computed key.", node)), + } + Ok(()) +} + +/// A key written by a keyword attribute, quoted if it is not a name. +fn keyword_key(f: Formatter, keyword: &str) -> std::fmt::Result { + if is_identifier(keyword) || keyword.strip_prefix('#').is_some_and(is_identifier) { + write!(f, "{keyword}") + } else { + write_string(f, keyword) + } +} + +/// `(object :a 1 b (... c) (key k v) (m () ...))` → `{a: 1, b, ...c, [k]: v, m() {...}}`. +fn object<'a>(f: Formatter, entries: &[ParseNode<'a>], indent: Option) -> Result<'a> { + write!(f, "{{")?; + for (index, entry) in entries.iter().enumerate() { + write!(f, "{}", if index > 0 { ", " } else { "" })?; + match (entry, head(entry), arguments(entry)) { + (ParseNode::Attribute { keyword, node: value, .. }, _, _) => { + keyword_key(f, keyword)?; + write!(f, ": ")?; + expression(f, value, indent)?; + }, + (ParseNode::Symbol(name), _, _) => write!(f, "{}", name.value)?, + (_, Some("..." | "="), _) => expression(f, entry, indent)?, + (_, Some("key"), [name, value]) => { + write!(f, "[")?; + expression(f, name, indent)?; + write!(f, "]: ")?; + expression(f, value, indent)?; + }, + (ParseNode::List { .. }, _, _) => method(f, entry, indent)?, + _ => return Err(error("An entry of an object is `:key value', a name, `(... value)', \ + `(key k value)' or a method.", entry)), + } + } + write!(f, "}}")?; + Ok(()) +} + +/// A method of an object or class, `(name (params...) body...)`, with +/// `get`, `set`, `async` and `*` before it. +fn method<'a>(f: Formatter, node: &ParseNode<'a>, indent: Option) -> Result<'a> { + let nodes: &[ParseNode<'a>] = node.list().map_or(&[], |nodes| nodes); + match (head(node), nodes) { + (Some(kind @ ("get" | "set")), [_, name, ParseNode::List { .. }, ..]) if !matches!(name, ParseNode::List { .. }) || computed(name).is_some() => { + write!(f, "{kind} ")?; + method_body(f, node, name, &nodes[2], &nodes[3..], indent, kind == "get") + }, + (Some("async"), [_, inner]) => { + write!(f, "async ")?; + method(f, inner, indent) + }, + (Some("*"), [_, name, params, body @ ..]) => { + write!(f, "*")?; + method_body(f, node, name, params, body, indent, false) + }, + (_, [name, params @ ParseNode::List { .. }, body @ ..]) => { + let returns = !matches!(name, ParseNode::Symbol(name) if name.value == "constructor"); + method_body(f, node, name, params, body, indent, returns) + }, + _ => Err(error("A method is `(name (params...) body...)'.", node)), + } +} + +fn method_body<'a>(f: Formatter, node: &ParseNode<'a>, name: &ParseNode<'a>, params: &ParseNode<'a>, + body: &[ParseNode<'a>], indent: Option, returns: bool) -> Result<'a> { + if !matches!(params, ParseNode::List { .. }) { + return Err(error("A method is `(name (params...) body...)'.", node)); + } + key(f, name, indent)?; + parameters(f, params, indent)?; + write!(f, " ")?; + block(f, body, indent, returns) +} + +/// `(class Name? :extends Base members...)`. +fn class<'a>(f: Formatter, node: &ParseNode<'a>, indent: Option) -> Result<'a> { + let mut members = arguments(node); + write!(f, "class")?; + if let [ParseNode::Symbol(name), rest @ ..] = members { + write!(f, " {}", name.value)?; + members = rest; + } + if let [ParseNode::Attribute { keyword, node: base, .. }, rest @ ..] = members && keyword == "extends" { + write!(f, " extends ")?; + operand(f, base, indent)?; + members = rest; + } + write!(f, " {{")?; + let inner = deeper(indent); + for member in members { + newline(f, inner)?; + class_member(f, member, inner)?; + } + if !members.is_empty() { + newline(f, indent)?; + } + write!(f, "}}")?; + Ok(()) +} + +fn class_member<'a>(f: Formatter, member: &ParseNode<'a>, indent: Option) -> Result<'a> { + match (member, head(member), arguments(member)) { + (ParseNode::Attribute { keyword, node: value, .. }, _, _) => { + keyword_key(f, keyword)?; + write!(f, " = ")?; + expression(f, value, indent)?; + write!(f, ";")?; + }, + (_, Some("field"), [name, value @ ..]) if value.len() <= 1 => { + key(f, name, indent)?; + if let [value] = value { + write!(f, " = ")?; + expression(f, value, indent)?; + } + write!(f, ";")?; + }, + (_, Some("static"), [static_block]) if head(static_block) == Some("do") => { + write!(f, "static ")?; + block(f, arguments(static_block), indent, false)?; + }, + (_, Some("static"), members) if !members.is_empty() => { + for (index, inner) in members.iter().enumerate() { + if index > 0 { + newline(f, indent)?; + } + write!(f, "static ")?; + class_member(f, inner, indent)?; + } + }, + (ParseNode::List { .. }, _, _) => method(f, member, indent)?, + _ => return Err(error("A member of a class is `:field value', `(field name)', \ + a method, or `(static member)'.", member)), + } + Ok(()) +} + +impl<'a> MarkupFormatter<'a> for JSFormatter<'a> { + /// A document is indented, one statement per line. + fn document(&self) -> std::result::Result> { + let mut buf = String::new(); + statements(&mut buf, &self.tree, Some(0))?; + Ok(buf) + } + + /// Otherwise, it is compact, on one line. + fn generate(&self, f: Formatter) -> std::result::Result<(), GenerationError<'a>> { + statements(f, &self.tree, None) + } +} diff --git a/crates/seam/src/assemble/json.rs b/crates/seam/src/assemble/json.rs new file mode 100644 index 0000000..9868a27 --- /dev/null +++ b/crates/seam/src/assemble/json.rs @@ -0,0 +1,132 @@ +//! Output JSON, the reverse of reading JSON with `%json`. +//! A list of `:key value` attributes is an object, any other list is an +//! array; strings stay strings, numbers stay numbers, and the symbols +//! `true`, `false` and `null` are themselves. Other symbols are strings. + +use super::{MarkupFormatter, GenerationError, Formatter}; +use crate::parse::parser::{ParseNode, ParseTree}; +use crate::parse::expander::Number; + +#[derive(Debug, Clone)] +pub struct JSONFormatter<'a> { + pub tree: ParseTree<'a>, +} + +impl<'a> JSONFormatter<'a> { + #[must_use] + pub fn new(tree: ParseTree<'a>) -> Self { + Self { + tree + } + } + + /// Generate the tree as one value: a single value as itself, + /// otherwise as the items of a list. + fn generate_tree(&self, f: Formatter, indent: Option) -> Result<(), GenerationError<'a>> { + match &*self.tree { + [node] if !node.is_attribute() => Self::generate_value(f, node, indent), + nodes => Self::generate_items(f, nodes, indent), + } + } + + /// Generate a value, indenting nested lines by `indent` levels when pretty. + pub fn generate_value(f: Formatter, node: &ParseNode<'a>, indent: Option) -> Result<(), GenerationError<'a>> { + match node { + ParseNode::String(node) => write_string(f, &node.value)?, + ParseNode::Raw(node) => write!(f, "{}", node.value)?, + ParseNode::Symbol(node) => match node.value.as_ref() { + "true" | "false" | "null" => write!(f, "{}", node.value)?, + _ => write_string(f, &node.value)?, + }, + ParseNode::Number(atom) => match Number::of(node) { + Some(Number::Int(int)) => write!(f, "{int}")?, + Some(Number::Float(float)) if float.is_finite() => write!(f, "{float}")?, + _ => return Err(GenerationError::new("JSON", + &format!("`{}' is not a number JSON can represent.", atom.value), &atom.site)), + }, + ParseNode::List { nodes, .. } => Self::generate_items(f, nodes, indent)?, + ParseNode::Attribute { site, .. } => return Err(GenerationError::new("JSON", + "A keyword attribute can only be part of an object (a list of attributes).", site)), + } + Ok(()) + } + + /// Generate the items of a list, as an object if they are all + /// attributes, or as an array if none are. + fn generate_items(f: Formatter, nodes: &[ParseNode<'a>], indent: Option) -> Result<(), GenerationError<'a>> { + let object = nodes.first().is_some_and(ParseNode::is_attribute); + if let Some(odd) = nodes.iter().find(|node| node.is_attribute() != object) { + return Err(GenerationError::new("JSON", if object { + "An object (a list of attributes) cannot also have plain items." + } else { + "An array (a list of plain items) cannot also have keyword attributes." + }, odd.site())); + } + let (open, close) = if object { ("{", "}") } else { ("[", "]") }; + write!(f, "{open}")?; + let inner = indent.map(|indent| indent + 1); + for (index, node) in nodes.iter().enumerate() { + if index > 0 { + write!(f, ",")?; + } + newline(f, inner)?; + if let ParseNode::Attribute { keyword, node, .. } = node { + write_string(f, keyword)?; + write!(f, "{}", if indent.is_some() { ": " } else { ":" })?; + Self::generate_value(f, node, inner)?; + } else { + Self::generate_value(f, node, inner)?; + } + } + if !nodes.is_empty() { + newline(f, indent)?; + } + write!(f, "{close}")?; + Ok(()) + } +} + +/// Start a new line at an indentation level, when pretty-printing. +fn newline(f: Formatter, indent: Option) -> std::fmt::Result { + match indent { + Some(indent) => write!(f, "\n{:width$}", "", width = 2 * indent), + None => Ok(()), + } +} + +/// Write a JSON string literal (which is also a JavaScript string literal). +pub fn write_string(f: Formatter, text: &str) -> std::fmt::Result { + write!(f, "\"")?; + let mut previous = '\0'; + for c in text.chars() { + match c { + '"' => write!(f, "\\\"")?, + '\\' => write!(f, "\\\\")?, + // So `` in a string cannot end a script it is embedded in. + '/' if previous == '<' => write!(f, "\\/")?, + '\n' => write!(f, "\\n")?, + '\r' => write!(f, "\\r")?, + '\t' => write!(f, "\\t")?, + '\u{08}' => write!(f, "\\b")?, + '\u{0C}' => write!(f, "\\f")?, + c if c < ' ' => write!(f, "\\u{:04x}", c as u32)?, + c => write!(f, "{c}")?, + } + previous = c; + } + write!(f, "\"") +} + +impl<'a> MarkupFormatter<'a> for JSONFormatter<'a> { + /// A document is indented, one item per line. + fn document(&self) -> Result> { + let mut buf = String::new(); + self.generate_tree(&mut buf, Some(0))?; + Ok(buf) + } + + /// Otherwise, it is compact, on one line. + fn generate(&self, f: Formatter) -> Result<(), GenerationError<'a>> { + self.generate_tree(f, None) + } +} diff --git a/crates/seam/src/assemble/mod.rs b/crates/seam/src/assemble/mod.rs index b780fb3..887665b 100644 --- a/crates/seam/src/assemble/mod.rs +++ b/crates/seam/src/assemble/mod.rs @@ -168,3 +168,7 @@ pub mod xml; pub mod css; /// HTML5 HTML generation. pub mod html; +/// JSON generation. +pub mod json; +/// JavaScript generation. +pub mod js; diff --git a/crates/seam/src/bin.rs b/crates/seam/src/bin.rs index 9887f58..dcbc1b2 100644 --- a/crates/seam/src/bin.rs +++ b/crates/seam/src/bin.rs @@ -14,7 +14,7 @@ fn argument_fatal(msg: impl std::fmt::Display) -> ! { std::process::exit(1) } -const SUPPORTED_TARGETS: [&str; 5] = ["text", "sexp", "html", "xml", "css"]; +const SUPPORTED_TARGETS: [&str; 7] = ["text", "sexp", "html", "xml", "css", "json", "js"]; fn main() -> Result<(), Box> { let mut args = env::args().peekable(); @@ -128,6 +128,8 @@ fn generate_and_print(expander: seam::parse::expander::Expander, target: &str, i "html" => Box::new(seam::assemble::html::HTMLFormatter::new(tree)), "xml" => Box::new(seam::assemble::xml::XMLFormatter::new(tree)), "css" => Box::new(seam::assemble::css::CSSFormatter::new(tree)), + "json" => Box::new(seam::assemble::json::JSONFormatter::new(tree)), + "js" => Box::new(seam::assemble::js::JSFormatter::new(tree)), _ => { if SUPPORTED_TARGETS.contains(&target) { unreachable!("bug: target `{}' is not covered", target); diff --git a/crates/seam/src/parse/expander.rs b/crates/seam/src/parse/expander.rs index 00e8a30..eb13236 100644 --- a/crates/seam/src/parse/expander.rs +++ b/crates/seam/src/parse/expander.rs @@ -2467,12 +2467,12 @@ impl<'a> Expander<'a> { }) } - /// `(%formatter/html ...)` (and `text`, `xml`, `css`, `sexp`) generates its + /// `(%formatter/html ...)` (and `text`, `xml`, `css`, `json`, `js`, `sexp`) generates its /// arguments with that formatter, giving the result as text. With /// `:document true`, a whole document is generated. fn expand_formatter_macro(&self, format: &str, node: &ParseNode<'a>, params: &[ParseNode<'a>]) -> Result, ExpansionError<'a>> { - use crate::assemble::{MarkupFormatter, css::CSSFormatter, text::PlainTextFormatter, xml::XMLFormatter}; + use crate::assemble::{MarkupFormatter, css::CSSFormatter, js::JSFormatter, json::JSONFormatter, text::PlainTextFormatter, xml::XMLFormatter}; let params = self.expand_nodes(params)?; let mut document = false; let mut content = Vec::with_capacity(params.len()); @@ -2492,6 +2492,8 @@ impl<'a> Expander<'a> { "html" => Box::new(HTMLFormatter::new(tree)), "xml" => Box::new(XMLFormatter::new(tree)), "css" => Box::new(CSSFormatter::new(tree)), + "json" => Box::new(JSONFormatter::new(tree)), + "js" => Box::new(JSFormatter::new(tree)), "text" => Box::new(PlainTextFormatter::new(tree)), "sexp" => Box::new(SExpFormatter::new(tree)), _ => return Err(ExpansionError(format!("No such formatter, `{format}`."), node.owned_site())), @@ -2900,11 +2902,12 @@ impl<'a> Expander<'a> { let start = out.len(); match node { // Symbols starting with %... are replaced with their defined value. - ParseNode::Symbol(sym) if sym.value.starts_with("%{") && sym.value.ends_with('}') => { + ParseNode::Symbol(sym) if sym.macro_name().is_some_and(|name| name.starts_with('{')) + && sym.value.ends_with('}') => { out.push(self.expand_shell(sym)?); }, - ParseNode::Symbol(sym) if sym.value.starts_with('%') => { - let name = &sym.value[1..]; + ParseNode::Symbol(sym) if sym.macro_name().is_some() => { + let name = sym.macro_name().unwrap_or_default(); let lazy = self.lookup(name, |definition| match definition { Definition::Value(value) => { out.extend_from_slice(value); @@ -2932,7 +2935,7 @@ impl<'a> Expander<'a> { // Pathway: (%_ _ _) macro invocation. if let Some(name) = nodes.first() .and_then(ParseNode::symbol) - .and_then(|symbol| symbol.value.strip_prefix('%')) { + .and_then(|symbol| symbol.macro_name()) { out.extend(self.expand_invocation(name, node, &nodes[1..])?); } else { // Otherwise, if not a macro, just expand child nodes incase they are macros. @@ -3129,10 +3132,10 @@ fn list_index<'a>(index: &ParseNode<'a>, length: usize) -> Result Option { + pub(crate) fn of(node: &ParseNode) -> Option { let text: &str = &node.atomic()?.value; let (sign, digits) = match text.strip_prefix('-') { Some(digits) => (-1, digits), @@ -3499,6 +3502,23 @@ fn expand_yaml<'a>(context: &Expander<'a>, text: &str, sep: &str, site: &Site<'a site: Site<'a>, } + /// A scalar keeps its type: unquoted numbers, `true`, `false` and `null` + /// are numbers and symbols, and everything else is a string. + fn scalar<'a>(value: &str, style: yaml::scanner::TScalarStyle, site: Site<'a>) -> ParseNode<'a> { + let node = Node::new(value.to_owned(), &site, " "); + if style != yaml::scanner::TScalarStyle::Plain { + return ParseNode::String(node); + } + match yaml::Yaml::from_str(value) { + yaml::Yaml::Integer(int) => ParseNode::Number(Node { value: int.to_string().into(), ..node }), + yaml::Yaml::Real(real) if real.parse::().is_ok_and(f64::is_finite) + => ParseNode::Number(node), + yaml::Yaml::Boolean(boolean) => ParseNode::Symbol(Node { value: boolean.to_string().into(), ..node }), + yaml::Yaml::Null => ParseNode::Symbol(Node { value: "null".into(), ..node }), + _ => ParseNode::String(node), + } + } + impl EventSink<'_, '_> { fn qualified(&self, name: &str) -> String { if self.prefix.is_empty() { @@ -3518,12 +3538,8 @@ fn expand_yaml<'a>(context: &Expander<'a>, text: &str, sep: &str, site: &Site<'a ); match event { // Either defining a new variable or setting a variable to a string. - yaml::Event::Scalar(ref value, ..) => { - let mut string = ParseNode::String(Node { - value: value.clone().into(), - site: self.site, - leading_whitespace: String::from(" ").into(), - }); + yaml::Event::Scalar(ref value, style, ..) => { + let mut string = scalar(value, style, self.site); match self.defining { Some(ref name) => { // Define a variable under `name` with `value`. diff --git a/crates/seam/src/parse/parser.rs b/crates/seam/src/parse/parser.rs index 96147e5..d80cfc9 100644 --- a/crates/seam/src/parse/parser.rs +++ b/crates/seam/src/parse/parser.rs @@ -14,6 +14,21 @@ pub struct Node<'a> { pub leading_whitespace: Cow<'a, str>, } +impl Node<'_> { + /// Whether the atom was written starting with an escape, as in `\%`. + #[must_use] + pub fn is_escaped(&self) -> bool { + self.site.view().starts_with('\\') + } + + /// The name of the macro this symbol calls, `name` for `%name`. + /// A symbol written with an escape, `\%`, is not a macro. + #[must_use] + pub fn macro_name(&self) -> Option<&str> { + self.value.strip_prefix('%').filter(|_| !self.is_escaped()) + } +} + impl PartialEq for Node<'_> { fn eq(&self, other: &Self) -> bool { self.value == other.value @@ -483,7 +498,7 @@ impl<'a> Parser { // The first argument of a macro call `(%name ...)` has its leading // whitespace removed, unless it starts on a new line. if let [ParseNode::Symbol(head), first, ..] = elements.as_mut_slice() - && head.value.starts_with('%') + && head.macro_name().is_some() && !first.leading_whitespace().contains('\n') { first.set_leading_whitespace(""); } @@ -502,9 +517,10 @@ fn escape_sanitize(string: &str) -> Cow<'_, str> { return Cow::Borrowed(string); } let mut builder = String::with_capacity(string.len()); - let chars = string.chars(); - for c in chars { - if c == '\\' { continue; } + let mut chars = string.chars(); + while let Some(c) = chars.next() { + // `\c` is `c`, whatever it is, so `\\` is a backslash. + let c = if c == '\\' { chars.next().unwrap_or(c) } else { c }; builder.push(c); } Cow::Owned(builder) diff --git a/crates/seam/src/tests.rs b/crates/seam/src/tests.rs index 87bcb5d..f5e344c 100644 --- a/crates/seam/src/tests.rs +++ b/crates/seam/src/tests.rs @@ -246,7 +246,7 @@ mod cases { "\n\n\n\n

Hello World

\n\n"); // loose metadata goes in the head, until the first content. assert_html_document_eq("(title T) (p hi) (script \"x()\")", - "\n\n\nT\n\n\n

hi

\n\n"); + "\n\n\nT\n\n\n

hi

\n\n"); // an explicit head stays a head, rather than ending up in the body. assert_html_document_eq("(head (title T)) (p hi)", "\n\nT\n\n

hi

\n\n"); @@ -409,6 +409,113 @@ mod cases { assert_eq!(sexp(input).as_deref(), Ok(expect), "{input}"); } + /// Expand source to compact JSON. + fn json(source: &str) -> Result { + use assemble::MarkupFormatter; + let context = Context::new(); + let expander = tree_builder(&context, Some(""), source.to_owned(), false); + let tree = expander.expand().map_err(|err| format!("{err}"))?; + assemble::json::JSONFormatter::new(tree).display().map_err(|err| err.message) + } + + #[test] + fn test_json_formatter() { + let check = |source: &str, expect: &str| assert_eq!(json(source).as_deref(), Ok(expect), "{source}"); + check("(:name \"Sam\" :age 9 :tags (a \"b c\" 1.5) :ok true :none null)", + r#"{"name":"Sam","age":9,"tags":["a","b c",1.5],"ok":true,"none":null}"#); + check("1 0x10 +5 -2.5", "[1,16,5,-2.5]"); + check(":a 1 :b ()", r#"{"a":1,"b":[]}"#); + check("\"quote \\\" back \\\\ \\n \"", r#""quote \" back \\ \n <\/script>""#); + check("(%raw \"{}\")", "{}"); + assert!(json("(:a 1 b)").unwrap_err().contains("cannot also have plain items")); + assert!(json("(b :a 1)").unwrap_err().contains("cannot also have keyword attributes")); + // Reading JSON in and writing it out again gives the same JSON. + let original = r#"{"a":[1,{"b":null,"c":false}],"d":"2","e":1.5}"#; + check(&format!("(%json {original:?})"), original); + // Pretty-printed as a document. + assert_sexp_eq("(%string (%formatter/json :document true (:a (1) :b ())))", + "\"{\\n \\\"a\\\": [\\n 1\\n ],\\n \\\"b\\\": []\\n}\""); + // Raw text, like JSON, is written as is inside a script. + assert_eq!(literate_html("(%do (script :type application/json (%formatter/json (1 \"\"))))").as_deref(), + Ok(r#""#)); + // A script given as a single string is written as is, + // and otherwise its strings are JavaScript strings. + assert_eq!(literate_html("(%do (script \"let a = 1; f(a)\"))").as_deref(), + Ok("")); + assert_eq!(literate_html(r#"(%do (script f("é\n\"")))"#).as_deref(), + Ok(r#""#)); + } + + /// Expand source to JavaScript, compact or as a document. + fn js(source: &str, document: bool) -> Result { + use assemble::MarkupFormatter; + let context = Context::new(); + let expander = tree_builder(&context, Some(""), source.to_owned(), false); + let tree = expander.expand().map_err(|err| format!("{err}"))?; + let formatter = assemble::js::JSFormatter::new(tree); + if document { formatter.document() } else { formatter.display() }.map_err(|err| err.message) + } + + #[test] + fn test_js_formatter() { + let check = |source: &str, expect: &str| assert_eq!(js(source, false).as_deref(), Ok(expect), "{source}"); + check("(f a \"b\\n\") ((. a b c) 1) (sketch.scale 30 -30)", r#"f(a, "b\n"); a.b.c(1); sketch.scale(30, -30);"#); + check("(const x (+ 1 (* 2 3) (- y)))", "const x = 1 + (2 * 3) + (-y);"); + check("(let n) (= (. o \"a-b\" 0) (? (! ok) (array) (:a 1 :b-c 2)))", + r#"let n; o["a-b"][0] = ((!ok) ? [] : {a: 1, "b-c": 2});"#); + check("(const f (=> (x (= y 1)) (+ x y))) (const g (=> () (:a 1)))", + "const f = (x, y = 1) => x + y; const g = () => ({a: 1});"); + check("(import D (a (as b c)) from \"./a.js\" :with (:type \"json\")) (import (as * ns) from \"x\") (import \"y\")", + r#"import D, {a, b as c} from "./a.js" with {type: "json"}; import * as ns from "x"; import "y";"#); + check("(export default (new Map)) (export (const k 1)) (export (a (as b default))) (export * from \"x\")", + r#"export default new Map(); export const k = 1; export {a, b as default}; export * from "x";"#); + check("(const xs (array 1 () (... ys) ())) (let (a 1) (b)) (const (object a :b c (= d 1)) o)", + "const xs = [1, , ...ys, ,]; let a = 1, b; const {a, b: c, d = 1} = o;"); + check("([] a i j) (?. a b ([] i)) (f?. x) (\\% a b) (\\array 1) (++post i) (regex \"a/b c\" g)", + "a[i][j]; a?.b?.[i]; f?.(x); a % b; array(1); i++; /a\\/b c/g;"); + check("(object :a 1 b (key k 2) (m (x) x) (get g () 1)) ((function () 1))", + "({a: 1, b, [k]: 2, m(x) { return x; }, get g() { return 1; }}); (function() { return 1; })();"); + check("(` :tag t \"a`${\" x)", r"t`a\`\${${x}`;"); + check("(class A :extends B :x 1 (field y) (static :n 0) (constructor () (super)) (* g () (yield 1)))", + "class A extends B { x = 1; y; static n = 0; constructor() { super(); } *g() { yield 1; } }"); + check("(outer: (for (let i 0) () () (break outer))) (switch x (case 1) (default (f)))", + "outer: for (let i = 0;;) { break outer; } switch (x) { case 1: default: f(); }"); + check("(try (f) (catch () (g)) (finally (h))) (do-while (c) (f))", + "try { f(); } catch { g(); } finally { h(); } do { f(); } while (c());"); + // Text that could end a script is escaped, and numbers are not misread. + check("(` \"\") (regex \"[\")", + r"`<\/script>`; /[<\/]/; /* <\/script> */"); + check("(` \"<\" \"/script>\" x \"<\" y \"/\")", r"`<\/script>${x}<${y}/`;"); + check("(. 1 toString) (- -5) (new (getClass) 1)", "(1).toString; -(-5); new (getClass())(1);"); + assert!(js("(export (async (=> () 1)))", false).unwrap_err().contains("Only a declaration")); + assert!(js("(export (function () 1))", false).unwrap_err().contains("Only a declaration")); + check("(while (< i 3) (+= i 1) (await (tick)))", "while (i < 3) { i += 1; await tick(); }"); + check("(if a (f) (if b (g) (do (h) (return))))", "if (a) { f(); } else if (b) { g(); } else { h(); return; }"); + assert_eq!(js("(function add (a b) (const c (+ a b)) (* c 2)) (for x of xs (log x))", true).as_deref(), + Ok("function add(a, b) {\n const c = a + b;\n return c * 2;\n}\nfor (const x of xs) {\n log(x);\n}")); + assert!(js("(f (const x 1))", false).unwrap_err().contains("is a statement")); + assert!(js("(f (if a b))", false).unwrap_err().contains("use `(? condition then else)'")); + assert!(js("(* a)", false).unwrap_err().contains("Wrong number of operands")); + assert!(js("(f ())", false).unwrap_err().contains("use `(array)'")); + // Generated JavaScript is raw text, written as it is inside a script. + assert_eq!(literate_html("(%do (script (%formatter/js (console.log \"\"))))").as_deref(), + Ok(r#""#)); + } + + #[test] + fn test_escaped_symbols() { + // An escaped `%` is not a macro, and `\\` is a backslash. + assert_eq!(js("(\\% a b) (\\%= a b)", false).as_deref(), Ok("a % b; a %= b;")); + assert_eq!(js("(f a\\ b \\\\ \\;)", false).as_deref(), Ok("f(a b, \\, ;);")); + } + + #[test] + fn test_config_scalar_types() { + assert_sexp_eq("(%yaml \"a: 1\\nb: '1'\\nc: true\\nd: ~\\ne: 2.5\\nf: text\")", + "(:a 1 :b \"1\" :c true :d null :e 2.5 :f \"text\")"); + assert_sexp_eq("(%json \"[1, \\\"1\\\", null]\")", "(1 \"1\" null)"); + } + #[test] fn test_math() { assert_sexp_eq("(%+ 1 2 3) (%- 10 4 1) (%- 5) (%* 2 3.5) (%/ 6 3) (%/ 7 2)", "6 5 -5 7 2 3.5"); diff --git a/docs/javascript.md b/docs/javascript.md new file mode 100644 index 0000000..b024992 --- /dev/null +++ b/docs/javascript.md @@ -0,0 +1,179 @@ +# JavaScript in seam + +How all of JavaScript (ES2025, and the older constructs) is written as +s-expressions, for `--js` and `%formatter/js`. + +## Principles + +1. **A list is `(head arguments...)`.** If the head is one of the forms + below, it is that form; otherwise the list is a call, `(f a b)` → `f(a, b)`. +2. **Forms are JavaScript keywords, operators, or a few plain words** + (`array`, `object`, `key`, `regex`, `field`, ...). + To call a function that has the same name as a form, escape it: + `(\array 5)` → `array(5)`. Words that JavaScript only treats as keywords in + some places (`of`, `as`, `from`, `default`, `get`, `set`, `static`, + `async`, `constructor`) are only special in those same places. +3. **No precedence.** A nested operation is always put in parentheses, so + `(* (+ a b) c)` → `(a + b) * c`, and what you write is what runs. +4. **Atoms are written as they are,** except strings, which are written as + JavaScript strings. So names, `this`, `true`, `null`, numbers, `10n`, + `#private`, `i++`, `a.b.c` and simple regexes (`/a+/g`) need no form. +5. **Seam's own syntax still applies:** `;` starts a comment, `%` calls a + macro, `"` starts a string and `:` starts a keyword. Escape a character + with `\` to use it in a symbol: `(\% a b)` → `a % b`. Macros run before + the JavaScript is written, so `(const n %count)` puts a seam value into it. +6. **`(%raw "...")` is written exactly as given,** for anything not covered. + +## Literals + +| Seam | JavaScript | +|---|---| +| `x`, `this`, `null`, `undefined`, `NaN` | the same | +| `42`, `0x1F`, `1e3`, `10n`, `1_000` | the same | +| `"a \"b\"\n"` | `"a \"b\"\n"` | +| ``(` "Hi, " name "!")`` | `` `Hi, ${name}!` `` (strings are text, anything else is `${...}`) | +| ``(` :tag html "

" x "

")`` | ``html`

${x}

` `` | +| `/a+b/gi` | `/a+b/gi` (as a symbol) | +| `(regex "a b;c" gi)`, `(regex "a b")` | `/a b;c/gi`, `/a b/` (any pattern, flags optional) | + +## Arrays and objects + +| Seam | JavaScript | +|---|---| +| `(array 1 2 (... rest))`, `(array)` | `[1, 2, ...rest]`, `[]` | +| `(array 1 () 3)` | `[1, , 3]` (`()` is a hole) | +| `(:a 1 :b-c 2)` | `{a: 1, "b-c": 2}` (a list of attributes, as in JSON) | +| `(object :a 1 b (... other))` | `{a: 1, b, ...other}` (a bare name is shorthand) | +| `(object (key k 1))` | `{[k]: 1}` (a computed key) | +| `(object (greet (name) ...) (get size () ...) (set size (n) ...))` | `{greet(name) {...}, get size() {...}, set size(n) {...}}` | +| `(object (async (load () ...)) (* items () ...))` | `{async load() {...}, *items() {...}}` | +| `(object (([] Symbol.iterator) () ...))` | `{[Symbol.iterator]() {...}}` | +| `(object)` | `{}` | + +## Property access and calls + +| Seam | JavaScript | +|---|---| +| `(. a b c)` | `a.b.c` | +| `([] a i)`, `([] a i j)` | `a[i]`, `a[i][j]` | +| `(. a b ([] i) "x-y" 0)` | `a.b[i]["x-y"][0]` (`([] i)` is a computed key, as are strings and numbers) | +| `(?. a b)`, `(?. a ([] i))` | `a?.b`, `a?.[i]` (every step is optional) | +| `(. (?. a b) c)` | `a?.b.c` | +| `((. a b) 1 2)`, `(a.b 1 2)` | `a.b(1, 2)` | +| `(f?. x)`, `(a.b?. x)` | `f?.(x)`, `a.b?.(x)` | +| `(new Map)`, `(new Map (... pairs))` | `new Map()`, `new Map(...pairs)` | +| `(super x)`, `(. super method)` | `super(x)`, `super.method` | +| `(import "./a.js")` as an expression | `import("./a.js")` | +| `new.target`, `import.meta` | the same | + +## Operators + +| Seam | JavaScript | +|---|---| +| `(+ a b c)`, `(- a b)`, `(* a b)`, `(/ a b)`, `(\% a b)`, `(** a b)` | `a + b + c`, ... | +| `(- a)`, `(+ a)`, `(! a)`, `(~ a)` | `-a`, `+a`, `!a`, `~a` | +| `(typeof a)`, `(void a)`, `(delete (. a b))`, `(await p)` | `typeof a`, ... | +| `(== a b)`, `(=== a b)`, `(!= a b)`, `(!== a b)`, `(< a b)`, ... | exactly two operands | +| `(&& a b c)`, `(\|\| a b)`, `(?? a b)` | `a && b && c`, ... | +| `(& a b)`, `(\| a b)`, `(^ a b)`, `(<< a b)`, `(>> a b)`, `(>>> a b)` | bitwise | +| `(in k o)`, `(instanceof x C)`, `(in #x o)` | `k in o`, `x instanceof C`, `#x in o` | +| `(? c a b)` | `c ? a : b` | +| `(, a b c)` | `(a, b, c)` | +| `(++ x)`, `(-- x)`, `(++post x)`, `(--post x)` | `++x`, `--x`, `x++`, `x--` (or just the atoms `++i`, `i++`) | +| `(= x 1)`, `(+= x 1)`, `(\%= x 2)`, `(??= x 0)`, `(&&= x y)`, ... | assignment | +| `(= (array a b) (array b a))` | `[a, b] = [b, a]` (patterns, below) | +| `(yield x)`, `(yield* xs)`, `(yield)` | `yield x`, ... | + +## Patterns (destructuring) + +A pattern is wherever a name is bound: declarations, parameters, `for` and +`catch` bindings, and the left of `=`. + +| Seam | JavaScript | +|---|---| +| `(array a b (... rest))`, `(array a () c)` | `[a, b, ...rest]`, `[a, , c]` | +| `(object a :b c (= d 1) (... rest))` | `{a, b: c, d = 1, ...rest}` | +| `(object :b (object c))`, `(object (key k v))` | `{b: {c}}`, `{[k]: v}` | +| `(= x 1)` in a pattern or parameters | `x = 1` (a default) | + +## Declarations + +| Seam | JavaScript | +|---|---| +| `(const x 1)`, `(let x)`, `(var x 1)` | `const x = 1;`, ... | +| `(const (object a b) obj)` | `const {a, b} = obj;` | +| `(let (a 1) (b 2) (c))` | `let a = 1, b = 2, c;` (when the first argument is a list, but not a pattern) | +| `(using r (open))`, `(await-using r (open))` | `using r = open();`, `await using ...` | + +## Functions + +A function returns its last expression, unless that is a statement or the +function is a generator, constructor or setter. + +| Seam | JavaScript | +|---|---| +| `(function add (a b) (+ a b))` | `function add(a, b) { return a + b; }` | +| `(function (a) ...)` | an anonymous function expression | +| `(function* gen () (yield 1))` | `function* gen() {...}` | +| `(=> (x (= y 1) (... zs)) body...)` | `(x, y = 1, ...zs) => ...` | +| `(=> (x) (:a x))` | `(x) => ({a: x})` | +| `(async (function f () ...))`, `(async (=> () ...))`, `(async (function* ...))` | `async function f() {...}`, ... | +| `(return)` as the last statement | no value is returned | + +## Classes + +| Seam | JavaScript | +|---|---| +| `(class Point :extends Base members...)` | `class Point extends Base {...}` | +| `(class members...)`, `(class :extends Base ...)` | a class expression | +| `(constructor (x y) (super) (= (. this x) x))` | `constructor(x, y) {...}` | +| `:x 0`, `:#count 0`, `(field x)` | fields `x = 0;`, `#count = 0;`, `x;` | +| `(norm () ...)`, `(#helper () ...)`, `(([] Symbol.iterator) () ...)` | methods | +| `(get size () ...)`, `(set size (n) ...)` | accessors | +| `(static :count 0)`, `(static (create () ...))` | static members | +| `(static (do ...))` | a static block | +| `(async (load () ...))`, `(* items () ...)` | async and generator methods | +| `(\get () ...)` | a method named `get` | + +## Statements + +| Seam | JavaScript | +|---|---| +| `(do a b)` | `{ a; b; }` (a block) | +| `(if c a)`, `(if c a b)`, `(if c a (if d b e))` | `if`, `else`, `else if` (use `(do ...)` for several statements) | +| `(for (let i 0) (< i n) (++ i) body...)` | `for (let i = 0; i < n; ++i) {...}` (`()` for an empty part) | +| `(for x of xs body...)`, `(for k in o body...)` | `for (const x of xs) {...}` | +| `(for (let x) of xs ...)`, `(for (array k v) of m ...)` | `let`, or a pattern | +| `(for-await x of xs ...)` | `for await (const x of xs) {...}` | +| `(while c body...)`, `(do-while c body...)` | `while`, `do {...} while (c);` | +| `(switch x (case 1 a) (case 2) (case 3 b (break)) (default c))` | `switch` (a `case` with no body falls through) | +| `(try body... (catch e ...) (finally ...))` | `try` (`(catch () ...)` has no binding) | +| `(throw e)`, `(return x)`, `(return)` | the same | +| `(break)`, `(continue)`, `(break outer)` | the same | +| `(outer: (for ...))` | `outer: for ...` (a head ending in `:` is a label) | +| `(debugger)`, `(with o body...)` | the same | +| `"use strict"` as a statement | `"use strict";` | +| `(// "text")`, `(/* "text")` | `// text`, `/* text */` (comments in the output) | + +## Modules + +Imports and exports keep JavaScript's word order. A list of names is `{...}`. + +| Seam | JavaScript | +|---|---| +| `(import "./a.js")` as a statement | `import "./a.js";` | +| `(import D from "./a.js")` | `import D from "./a.js";` | +| `(import (as * ns) from "./a.js")` | `import * as ns from "./a.js";` | +| `(import D (a (as b c)) from "./a.js")` | `import D, {a, b as c} from "./a.js";` | +| `(import data from "./d.json" :with (:type "json"))` | `import data from "./d.json" with {type: "json"};` | +| `(export (const x 1))`, `(export (function f () ...))` | `export const x = 1;`, ... | +| `(export default expr)` | `export default expr;` | +| `(export (a (as b c)))` | `export {a, b as c};` | +| `(export (a) from "./a.js")`, `(export * from "./a.js")`, `(export (as * ns) from "./a.js")` | re-exports | + +## Notes + +- Names are written as they are, so a kebab-case `my-name` is written as + `my-name`, which JavaScript reads as `my - name`. +- `(a.b 1)` works because symbols are written as they are; `(. a b)` is + the same, and works on any expression. diff --git a/samples/blog/README.md b/samples/blog/README.md index 90c1caa..023a79e 100644 --- a/samples/blog/README.md +++ b/samples/blog/README.md @@ -1,7 +1,7 @@ # 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. +a shared layout, posts listed on an index by date, a tags page, and both an RSS and a JSON feed. ```sh cd samples/blog @@ -16,6 +16,9 @@ seam run build.sex # Writes the site into public/. - `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`. +- `feed.json.sex` is a [JSON Feed](https://jsonfeed.org), written as + s-expressions: a list of `:key value` attributes is an object, and any other + list an array (`seam --json feed.json.sex`). - `build.sex` renders every page with a formatter macro (`%formatter/html :document true ...`) and saves it with `%write`, giving the files each page is made `:from`, so a page is only made again when one diff --git a/samples/blog/build.sex b/samples/blog/build.sex index 303ac40..40e1e94 100644 --- a/samples/blog/build.sex +++ b/samples/blog/build.sex @@ -34,6 +34,8 @@ (%write (%path/join %public feed.xml) :from (%list %shared (%source feed.sex) %posts/files) (%formatter/xml :document true (%include "feed.sex"))) +(%write (%path/join %public feed.json) :from (%list %shared (%source feed.json.sex) %posts/files) + (%formatter/json :document true (%include "feed.json.sex"))) (%write (%path/join %public style.css) :from (%list (%source style.sex)) (%formatter/css (%include "style.sex"))) diff --git a/samples/blog/feed.json.sex b/samples/blog/feed.json.sex new file mode 100644 index 0000000..9e93a6d --- /dev/null +++ b/samples/blog/feed.json.sex @@ -0,0 +1,19 @@ +;; A JSON Feed (https://jsonfeed.org) of the posts. +;; Render it alone with `seam --json feed.json.sex`. +;; A list of `:key value` attributes becomes an object, any other list an array. +(%include "site.sex") + +(:version "https://jsonfeed.org/version/1.1" + :title %site-title + :home_page_url %site-url + :feed_url (%concat %site-url "feed.json") + :authors ((:name %author)) + :items (%list (%for post in %posts + (%let (((:slug _ :title _ :date _ :tags _ :description _ &&_) %post) + (url (%concat %site-url "posts/" %slug ".html"))) + (:id %url + :url %url + :title %title + :summary %description + :date_published (%concat %date "T00:00:00Z") + :tags %tags))))) diff --git a/samples/blog/site.sex b/samples/blog/site.sex index bf1c181..44014ed 100644 --- a/samples/blog/site.sex +++ b/samples/blog/site.sex @@ -60,7 +60,9 @@ (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"))) + :title %site-title :href (%concat %root "feed.xml")) + (link :rel alternate :type application/feed+json + :title %site-title :href (%concat %root "feed.json"))) (body (%include "includes/header.sex") (main %body) diff --git a/samples/js-concept.sex b/samples/js-concept.sex index 0f76cba..b4fbfc2 100644 --- a/samples/js-concept.sex +++ b/samples/js-concept.sex @@ -26,27 +26,31 @@ ;const points = []; ;const r = 0.4; -(import * as BC from "../lib/BasicCanvas.js") -(import { grid, ellipse } from "../lib/BasicCanvas.js") +;; The same, as s-expressions. Render it with `seam --js js-concept.sex`. + +(import (as * BC) from "../lib/BasicCanvas.js") +(import (grid ellipse) from "../lib/BasicShapes.js") (use BC) (const sketch (canvas_id "sketch")) -;; We have toistinguish operators from function calls. +;; Operators and keywords start a list, otherwise a list is a call. ((. sketch dimensions) 400 400) (sketch.translate 200 200) ;; Alternative (won't work with spaces). ((. sketch scale) 30 -30) -(= (. sketch fill) (Color `transparent`)) -(= sketch.stroke (Color `black`)) +;; JavaScript's templates `...` are strings instead. +(= (. sketch fill) (Color "transparent")) +(= sketch.stroke (Color "black")) +;; A function returns its last expression. (const gaussian (=> ((= mean 0) (= σ 1)) - (const ϑ (* (. Math TAU) ((. Math random))) + (const ϑ (* (. Math TAU) ((. Math random)))) (const ρ (Math.sqrt (* -2 (Math.log (- 1 (Math.random)))))) (const radius (* σ ρ)) - (Polar radius ϑ (P mean mean))))) + (Polar radius ϑ (P mean mean)))) -(const points []) +(const points (array)) (const r 0.4)