quiltlang 0.6.0

Quilt, a polyglot metaprogramming language: source code with arrow-bracket syntax for embedding and manipulating code fragments of other languages at code-generation time.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
use crate::prelude::*;
use crate::qterm::QTerm;
use std::fmt::Debug;
use std::sync::Arc;

/**************************************************************/

/// Kinds of terms. These are sorts of messages for communicating between parsers.
///
/// The variants name the grammatical roles a fragment can play. Languages map
/// their tree-sitter node tags onto these via [`Language::typ`] /
/// [`Language::classify_term`], and holes record the kind their position
/// demands via [`TSProvider::hole_kind`](crate::treesitter::TSProvider::hole_kind).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum InnerKind {
    /// An expression — produces a value (e.g. `1 + 2`, a function call).
    Expr,
    /// A statement — runs for its effect and lives among siblings in a block
    /// (e.g. `let x = 1;`, an expression statement).
    Stmt,
    /// An item / top-level declaration (e.g. `fn`, `struct`, `impl`, `use`).
    /// Like [`Stmt`](InnerKind::Stmt) it sits among siblings rather than
    /// producing a value, but it is a definition rather than a runtime
    /// statement. [`InnerKind::is_stmt_like`] groups the two.
    Item,
    /// A brace-delimited block *body* — the `{ … }` of a function, loop, or
    /// branch. Distinct from a block used as a value (which is an
    /// [`Expr`](InnerKind::Expr)); see
    /// [`TSProvider::hole_kind`](crate::treesitter::TSProvider::hole_kind),
    /// which reads the surrounding tree to tell the two apart.
    Block,
    #[default]
    /// A whole file / module — a sequence of top-level items.
    File,
    // TODO: add more, language specific types, number, function, etc.
}

impl InnerKind {
    /// Whether a fragment of this kind lives in a "variadic" sibling position
    /// (a statement or an item) rather than producing a value. The expander's
    /// emit/splice heuristics treat statements and items alike, so they ask
    /// this instead of comparing against a single variant.
    #[must_use]
    pub fn is_stmt_like(self) -> bool {
        matches!(self, InnerKind::Stmt | InnerKind::Item)
    }

    /// Whether a fragment of this kind is *code to run* rather than a value to
    /// insert — [`is_stmt_like`](Self::is_stmt_like) widened to include a whole
    /// sequence of statements.
    ///
    /// The two differ for exactly one case, and it matters: a ground unquote
    /// holding **several** statements parses with the file root
    /// (`source_file` / `module`), so `is_stmt_like` says `false` even though a
    /// statement sequence is the least value-like thing there is. The expander
    /// asks this when deciding whether to splice a ground unquote or emit it;
    /// see `Expander::expand`.
    #[must_use]
    pub fn is_code_like(self) -> bool {
        self.is_stmt_like() || matches!(self, InnerKind::File)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Arity {
    #[default]
    Unknown,
    Const(u8),
    Variadic,
}

impl Arity {
    /// Look a node kind up in one of the derived tables in
    /// [`langs::arity`](crate::langs::arity).
    ///
    /// `table` must be sorted — the generated ones are, and this binary searches
    /// them rather than scanning, because `arity` is asked once per node per
    /// expansion.
    ///
    /// A miss is [`Unknown`](Arity::Unknown), not `Const`: the grammar says only
    /// whether a kind *can* repeat, and a node that cannot still has whatever
    /// fixed number of children its rule spells out. Nothing in the expander
    /// distinguishes the two, so there is no arity to invent here.
    #[must_use]
    pub fn from_table(table: &[&str], tag: &str) -> Arity {
        if table.binary_search(&tag).is_ok() {
            Arity::Variadic
        } else {
            Arity::Unknown
        }
    }
}

/// The separator of a node kind found in one of the derived
/// `*_COMMA_SEPARATED` tables in [`langs::arity`](crate::langs::arity): `","`
/// on a hit, `None` otherwise. `table` must be sorted, as the generated ones
/// are.
#[must_use]
pub fn comma_separator(table: &[&str], tag: &str) -> Option<&'static str> {
    table.binary_search(&tag).is_ok().then_some(",")
}

#[derive(Debug, Clone, Default)]
pub struct Hole {
    pub otag: Box<str>, // outer tag: where this hole appears in the outer language
    /// Inner kind: what kind of thing can fill this hole, derived from `otag`
    /// via the outer language's [`Language::typ`]. Threaded into the nested
    /// `parse_pre` so an unquote body is parsed with the kind its position
    /// demands (e.g. a `{ }` in statement position) instead of a guess.
    pub ikind: Option<InnerKind>,
    pub prefix: Box<[Box<str>]>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FlatNode<'a> {
    Hole,
    /// A hole a one-line `↙…↘` splices its value into. It is a [`Hole`] in
    /// every respect but one: a column-sensitive language may align the
    /// splice to the hole's column (see
    /// [`TSProvider::align_splices`](crate::treesitter::TSProvider::align_splices)).
    /// A quote's hole is not one — at ground level its expansion is builder
    /// code (in a Lean host, a string literal, which padding would change) —
    /// and neither is a multi-line unquote's, whose own source lines the
    /// padding would shift when the term is written back as `.quilt`.
    ///
    /// [`Hole`]: FlatNode::Hole
    Splice,
    Str(&'a str),
    NewLine,
}

impl FlatNode<'_> {
    /// Whether this is a hole of either kind.
    #[must_use]
    pub fn is_hole(&self) -> bool {
        matches!(self, Self::Hole | Self::Splice)
    }
}

/// Whether `tag` is a node kind the target language uses for a comment.
///
/// Needed by the `.quilt`-source renderer (`STerm::coparse_quilt`, #223): a
/// Quilt glyph inside a comment is *raw text*, because the grammar's comment
/// token consumes the rest of the line and never applies the `escape` rule
/// inside one. Writing `\↙` there would produce a literal backslash rather than
/// an escape, so comment content is the one place source rendering must not
/// escape (#237).
///
/// This is a naming convention rather than a per-language table, deliberately:
/// every tree-sitter grammar quilt vendors spells its comment kinds `comment`,
/// `line_comment` or `block_comment`, and a table keyed by language is the
/// hardcoded-shape pattern issue #174 exists to prevent. It is not taken on
/// trust either — `quilt-conformance`'s `comment_tags_are_recognised` builds a
/// comment in every registered language from [`Comments::LINE`] and asserts the
/// tag its grammar produces satisfies this, so a language whose grammar names
/// comments differently fails there rather than silently losing its escapes.
#[must_use]
pub fn is_comment_tag(tag: &str) -> bool {
    tag == "comment" || tag.ends_with("_comment")
}

/// How a language spells comments: the static half of its surface syntax,
/// declared once beside its [`Language`] impl.
///
/// Read by name through [`langs::line_comment`](crate::langs::line_comment) and
/// [`langs::header_comment`](crate::langs::header_comment), which `define_omni!`
/// generates from the same table that maps names and aliases onto languages.
/// That is the whole point. The `DO NOT EDIT` header's marker started as a
/// `match` on the output file's *extension* inside the CLI (issue #136, where
/// every language got Rust's `//!`), then became a hand-written table beside the
/// language modules — either way a second place to register a language, free to
/// disagree with the first. Here there is no second place: a new language
/// implements this trait or it does not compile, and its aliases inherit the
/// answer by construction (issue #194).
///
/// Associated consts rather than [`Language`] methods, for two reasons. An
/// associated const makes a trait non-dyn-compatible, and `Language` is used as
/// `dyn Language` by `DynOmniLanguages`. And a const-valued lookup is a `match`
/// yielding a `&'static str`, where a `&self` method would mean *constructing* a
/// language — a tree-sitter `Parser` per call — to read one: quilt-lsp asks for
/// a line comment once per comment gap while projecting a document, so that cost
/// is not academic.
pub trait Comments {
    /// The line-comment introducer, e.g. `//`.
    ///
    /// `None` when no *prefix* can express one: HTML's comments are delimited
    /// (`<!-- … -->`, and a prefix alone would open one that never closes), and
    /// plain text has no comment syntax at all. Callers decide the fallback.
    const LINE: Option<&'static str> = Some("//");

    /// The introducer for the `DO NOT EDIT` header the CLI writes onto a
    /// generated file, which has to be a comment *in the language just
    /// generated* — issue #136.
    ///
    /// Defaults to [`LINE`](Comments::LINE); Rust overrides it with `//!`, an
    /// inner doc comment, which documents the generated module rather than
    /// whatever item happens to follow the header.
    const HEADER: Option<&'static str> = Self::LINE;
}

// WARN: assumers no newlines
pub fn one_liner(s: &str) -> [FlatNode<'_>; 1] {
    [FlatNode::Str(s)]
}

pub fn flat_nodes(s: &str) -> Vec<FlatNode<'_>> {
    let lines = s.split('\n').collect::<Vec<_>>();
    let mut nodes = Vec::new();
    for (i, line) in lines.iter().enumerate() {
        if i > 0 {
            nodes.push(FlatNode::NewLine);
        }
        if !line.is_empty() {
            nodes.push(FlatNode::Str(line));
        }
    }
    nodes
}

impl std::ops::Add for &Hole {
    type Output = Hole;

    fn add(self, rhs: Self) -> Self::Output {
        let otag = rhs.otag.clone();
        let ikind = rhs.ikind;
        let mut prefix = self.prefix.to_vec();
        prefix.extend_from_slice(&rhs.prefix);
        let prefix = prefix.into();
        Hole {
            otag,
            ikind,
            prefix,
        }
    }
}

pub trait Language {
    type Post: LanguagePost;

    /// Parse a string into something that can be filled with plugs and a list of hole types.
    fn parse_pre(&mut self, ikind: Option<InnerKind>, code: &[FlatNode]) -> Result<Self::Post>;

    /// Convenience function to parse and fill with plugs.
    fn parse_with(&mut self, code: &[FlatNode], plugs: &[Arc<QTerm>]) -> Result<Arc<QTerm>> {
        self.parse_pre(Default::default(), code)?.parse_post(plugs)
    }

    /// Convenience function to parse without plugs.
    fn parse(&mut self, code: &[FlatNode]) -> Result<Arc<QTerm>> {
        self.parse_with(code, &[])
    }

    /// Convenience function to parse as a given `TermKind` and fill with plugs.
    fn parse_as(&mut self, ikind: Option<InnerKind>, code: &[FlatNode]) -> Result<Arc<QTerm>> {
        self.parse_pre(ikind, code)?.parse_post(&[])
    }

    fn parse_expr(&mut self, code: &[FlatNode]) -> Result<Arc<QTerm>> {
        self.parse_as(Some(InnerKind::Expr), code)
    }

    fn parse_stmt(&mut self, code: &[FlatNode]) -> Result<Arc<QTerm>> {
        self.parse_as(Some(InnerKind::Stmt), code)
    }

    fn parse_file(&mut self, code: &[FlatNode]) -> Result<Arc<QTerm>> {
        self.parse_as(Some(InnerKind::File), code)
    }

    fn parse_auto(&mut self, code: &[FlatNode]) -> Result<Arc<QTerm>> {
        self.parse_as(None, code)
    }

    fn arity(&self, _tag: &str) -> Arity {
        Default::default()
    }

    /// The token that separates the repeated children of a variadic node of
    /// kind `tag` — `","` for an array, an argument list, a Python list — or
    /// `None` when they are not separated (a block, a statement list).
    ///
    /// The expander asks this for a splice into such a node (`[↙xs↘]`,
    /// `f(↙xs↘)`) and has the builder separate the elements the splice
    /// contributes, which otherwise come out back to back (#293). The answer
    /// is derived from the grammar, like [`arity`](Self::arity)'s.
    fn separator(&self, _tag: &str) -> Option<&'static str> {
        None
    }

    fn typ(&self, _tag: &str) -> InnerKind {
        Default::default()
    }

    /// Classify a fully-parsed `QTerm` to determine its grammatical kind.
    ///
    /// This is the *accurate* version of [`typ`]: unlike `typ`, which receives
    /// only the root tag name, `classify_term` can inspect the full term tree.
    /// This matters for languages (e.g. WGSL) where a single statement is
    /// wrapped in a `source_file` node with a trailing `;` sibling, so the
    /// root tag alone gives `File` even though the fragment is really `Stmt`.
    ///
    /// The default implementation falls back to `typ` on the root tag, which
    /// is correct for languages whose `unwrap` always squashes the wrapper.
    fn classify_term(&self, term: &QTerm) -> InnerKind {
        match term {
            QTerm::Tuple { tag, .. } => self.typ(tag),
            _ => InnerKind::default(),
        }
    }

    /// The node kind this language spells a bare identifier with.
    ///
    /// The expander needs it for the one term it constructs itself rather than
    /// parsing: an operator (`↑`, `↓`, `←`) inside an as-yet-unresolved quote is
    /// deferred as its glyph, to be spelled out when that stage runs. That
    /// placeholder used to be hardcoded as `leaf("identifier", …)` in
    /// `multi.rs` — a Rust tag applied to every language, and simply not a node
    /// kind bash or zsh define (they have `word`); see issue #174, finding E2.
    ///
    /// The default is right for every language here except the shells.
    fn ident_tag(&self) -> &'static str {
        "identifier"
    }

    /// Shebang line used to run an expanded file of this language, if supported.
    /// e.g. `"#!/usr/bin/env rust-script"` or `"#!/usr/bin/env python3"`.
    ///
    /// Use [`parse_hashbang`] to turn one into a command — the interpreter is not
    /// always the last word.
    fn hashbang(&self) -> Option<&'static str> {
        None
    }

    /// How to drive this language as a stateful
    /// [`Machine`](crate::machine::Machine): the runner and spellings a
    /// [`ScriptMachine`](crate::machine::ScriptMachine) needs. The same
    /// pattern as [`hashbang`](Self::hashbang) (and usually derived from it
    /// via [`MachineSpec::from_hashbang`](crate::machine::MachineSpec::from_hashbang));
    /// `None` means no script machine — a richer provider may still exist.
    /// See `docs/design/machines.md`.
    fn machine_spec(&self) -> Option<crate::machine::MachineSpec> {
        None
    }

    /// How to drive this language as a *persistent*
    /// [`ReplMachine`](crate::machine::ReplMachine): a long-lived interactive
    /// interpreter fed on stdin, so state is real process state rather than
    /// [`machine_spec`](Self::machine_spec)'s replayed history. Preferred
    /// over the script spec when both exist
    /// (see [`spawn_machine`](crate::machine::spawn_machine)).
    fn repl_spec(&self) -> Option<crate::machine::ReplSpec> {
        None
    }

    /// A machine for this language that needs no interpreter at all — state
    /// held in-process, as terms. HTML's is a document
    /// ([`HtmlMachine`](crate::machine::HtmlMachine)); a language with a
    /// native evaluator would answer the same way. Preferred over both
    /// subprocess providers by
    /// [`spawn_machine`](crate::machine::spawn_machine), and spawned fresh on
    /// each call — the returned machine is the caller's.
    fn native_machine(&self) -> Option<Box<dyn crate::machine::Machine>> {
        None
    }
}

/// Split a [`Language::hashbang`] into the program to execute and the arguments
/// that precede the script path.
///
/// `quilt run` used to take `split_whitespace().next_back()` — the *last* word —
/// which is the interpreter only when the shebang has no arguments. TypeScript's
/// is `#!/usr/bin/env -S node --experimental-strip-types`, so that yielded
/// `--experimental-strip-types` and `quilt run foo.ts.quilt` tried to execute the
/// flag (issue #174, finding F).
///
/// `env` is unwrapped the way `env -S` does it: its own options (`-S`, `-i`,
/// `-u NAME`, `--`) and any `VAR=value` assignments are skipped, and the first
/// remaining word is the real program. Everything after it is an argument to that
/// program.
///
/// Returns `None` when no program can be identified — an empty shebang, or one
/// that is nothing but `env` and its options.
#[must_use]
pub fn parse_hashbang(hashbang: &str) -> Option<(&str, Vec<&str>)> {
    let mut words = hashbang.trim_start_matches("#!").split_whitespace();
    let first = words.next()?;

    // A non-`env` interpreter is used as given: `#!/bin/sh -e` → ("/bin/sh", ["-e"]).
    if basename(first) != "env" {
        return Some((first, words.collect()));
    }

    // `env` itself: skip its options and any environment assignments to find the
    // program it would exec.
    let mut program = None;
    while let Some(word) = words.next() {
        match word {
            // `-u NAME` / `--unset=NAME` take a value; the others are flags.
            "-u" | "--unset" => {
                words.next();
            }
            "--" => {}
            _ if word.starts_with('-') => {}
            // `VAR=value` sets the child's environment rather than naming it.
            _ if word.contains('=') => {}
            _ => {
                program = Some(word);
                break;
            }
        }
    }
    Some((program?, words.collect()))
}

/// The final path component of `path`, for comparing a program name against
/// `env` without caring whether the shebang spelled it `/usr/bin/env`.
fn basename(path: &str) -> &str {
    path.rsplit('/').next().unwrap_or(path)
}

pub trait LanguagePost: Debug {
    /// Get the hole types that this language supports.
    fn holes(&self) -> &[Hole];
    /// Fill with plugs.
    fn parse_post(&self, plugs: &[Arc<QTerm>]) -> Result<Arc<QTerm>>;
}

/**************************************************************/

impl Language for Box<dyn Language<Post = Box<dyn LanguagePost>>> {
    type Post = Box<dyn LanguagePost>;

    fn parse_pre(&mut self, ikind: Option<InnerKind>, code: &[FlatNode]) -> Result<Self::Post> {
        self.as_mut().parse_pre(ikind, code)
    }

    fn arity(&self, tag: &str) -> Arity {
        self.as_ref().arity(tag)
    }

    fn separator(&self, tag: &str) -> Option<&'static str> {
        self.as_ref().separator(tag)
    }

    fn typ(&self, tag: &str) -> InnerKind {
        self.as_ref().typ(tag)
    }

    fn classify_term(&self, term: &QTerm) -> InnerKind {
        self.as_ref().classify_term(term)
    }

    fn ident_tag(&self) -> &'static str {
        self.as_ref().ident_tag()
    }

    fn hashbang(&self) -> Option<&'static str> {
        self.as_ref().hashbang()
    }

    fn machine_spec(&self) -> Option<crate::machine::MachineSpec> {
        self.as_ref().machine_spec()
    }

    fn repl_spec(&self) -> Option<crate::machine::ReplSpec> {
        self.as_ref().repl_spec()
    }

    fn native_machine(&self) -> Option<Box<dyn crate::machine::Machine>> {
        self.as_ref().native_machine()
    }
}

impl LanguagePost for Box<dyn LanguagePost> {
    fn holes(&self) -> &[Hole] {
        self.as_ref().holes()
    }

    fn parse_post(&self, plugs: &[Arc<QTerm>]) -> Result<Arc<QTerm>> {
        self.as_ref().parse_post(plugs)
    }
}

/**************************************************************/

#[cfg(test)]
mod tests {
    use super::parse_hashbang;

    /// Every shebang a `Language` in this repo declares must name its
    /// interpreter, not a flag. TypeScript's is the case that regressed.
    #[test]
    fn parses_the_declared_hashbangs() {
        let cases = [
            ("#!/usr/bin/env rust-script", "rust-script", vec![]),
            ("#!/usr/bin/env python3", "python3", vec![]),
            ("#!/usr/bin/env bash", "bash", vec![]),
            ("#!/usr/bin/env zsh", "zsh", vec![]),
            (
                "#!/usr/bin/env -S node --experimental-strip-types",
                "node",
                vec!["--experimental-strip-types"],
            ),
        ];
        for (hashbang, program, args) in cases {
            assert_eq!(
                parse_hashbang(hashbang),
                Some((program, args)),
                "{hashbang:?} did not resolve to its interpreter"
            );
        }
    }

    /// Shapes Quilt does not use today but that `env` accepts, so a language
    /// adding one is not a surprise breakage.
    #[test]
    fn parses_other_env_shapes() {
        // A direct interpreter, with its own flag.
        assert_eq!(
            parse_hashbang("#!/bin/sh -e"),
            Some(("/bin/sh", vec!["-e"]))
        );
        // `env` with an environment assignment, and with `-u NAME`.
        assert_eq!(
            parse_hashbang("#!/usr/bin/env FOO=1 python3 -X dev"),
            Some(("python3", vec!["-X", "dev"]))
        );
        assert_eq!(
            parse_hashbang("#!/usr/bin/env -u FOO -S node"),
            Some(("node", vec![]))
        );
        // A bare `env` names no program.
        assert_eq!(parse_hashbang("#!/usr/bin/env -S"), None);
        assert_eq!(parse_hashbang("#!"), None);
    }
}