Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down Expand Up @@ -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`).
Expand Down
74 changes: 70 additions & 4 deletions USAGE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `</` are written `<\/`, so the
data cannot end the `script` tag):
```lisp
(script :type application/json :id posts (%formatter/json %posts))
(script """
const posts = JSON.parse(document.getElementById("posts").textContent);
""")
```
JavaScript itself is best written as a single string, as above, which is
written as it is. Otherwise, a script's contents are kept as written, with
strings written as JavaScript strings, but seam's syntax still applies: `;`
starts a comment, for instance. To write JavaScript as s-expressions instead,
use the JavaScript formatter.

#### JavaScript
The JavaScript formatter (`--js`, or `%formatter/js`) writes s-expressions as
JavaScript, so a script can use macros, and seam's comments and strings, safely:
```lisp
(script (%formatter/js
(const posts (%formatter/json %posts))
(for post of posts
(console.log (. post title) "—" (. post date)))))
```
- A list is a call, `(f a b)` → `f(a, b)`, and `((. a b) 1)` → `a.b(1)`.
Symbols are written as they are, so `(console.log x)` works too.
- Operators start a list: `(+ a b c)` → `a + b + c`, `(- a)` → `-a`, and the
same for comparisons, `&&`, `||`, `??`, `!`, `typeof`, `await` and
assignments (`=`, `+=`, ...). Nested operations are always put in
parentheses, so precedence never matters. `%` is escaped, `(\% a b)`.
- `(. a b "c-d" 0)` → `a.b["c-d"][0]`, `([] a i)` → `a[i]`, `(?. a b)` →
`a?.b`, `(f?. x)` → `f?.(x)`, `(new Map)` → `new Map()`, `(? c a b)` → `c ? a : b`.
- `(array 1 (... xs))` → `[1, ...xs]`, `(object a :b 1)` → `{a, b: 1}`, and a
list of attributes is an object too, `(:a 1 :b-c 2)` → `{a: 1, "b-c": 2}`.
These are also destructuring patterns, `(const (object a b) o)`.
- Declarations `(const x 1)` and `(let (a 1) (b 2))`; statements
`(if c then else)` (use `(do ...)` for several), `(for x of xs ...)`,
`(for (let i 0) (< i n) (++ i) ...)`, `while`, `do-while`, `switch`, `try`
and labels; `(=> (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:
Expand Down
37 changes: 33 additions & 4 deletions crates/seam/src/assemble/html.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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},
};

Expand Down Expand Up @@ -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" => { // <math> and <svg> are subsets of XML.
XMLFormatter::generate_children(f, rest)?;
Expand Down Expand Up @@ -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<String> {
match node {
ParseNode::List { nodes, .. } => nodes.first()
Expand Down
Loading
Loading