Skip to main content

quilt/
lang.rs

1use crate::prelude::*;
2use crate::qterm::QTerm;
3use std::fmt::Debug;
4use std::sync::Arc;
5
6/**************************************************************/
7
8/// Kinds of terms. These are sorts of messages for communicating between parsers.
9///
10/// The variants name the grammatical roles a fragment can play. Languages map
11/// their tree-sitter node tags onto these via [`Language::typ`] /
12/// [`Language::classify_term`], and holes record the kind their position
13/// demands via [`TSProvider::hole_kind`](crate::treesitter::TSProvider::hole_kind).
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
15pub enum InnerKind {
16    /// An expression — produces a value (e.g. `1 + 2`, a function call).
17    Expr,
18    /// A statement — runs for its effect and lives among siblings in a block
19    /// (e.g. `let x = 1;`, an expression statement).
20    Stmt,
21    /// An item / top-level declaration (e.g. `fn`, `struct`, `impl`, `use`).
22    /// Like [`Stmt`](InnerKind::Stmt) it sits among siblings rather than
23    /// producing a value, but it is a definition rather than a runtime
24    /// statement. [`InnerKind::is_stmt_like`] groups the two.
25    Item,
26    /// A brace-delimited block *body* — the `{ … }` of a function, loop, or
27    /// branch. Distinct from a block used as a value (which is an
28    /// [`Expr`](InnerKind::Expr)); see
29    /// [`TSProvider::hole_kind`](crate::treesitter::TSProvider::hole_kind),
30    /// which reads the surrounding tree to tell the two apart.
31    Block,
32    #[default]
33    /// A whole file / module — a sequence of top-level items.
34    File,
35    // TODO: add more, language specific types, number, function, etc.
36}
37
38impl InnerKind {
39    /// Whether a fragment of this kind lives in a "variadic" sibling position
40    /// (a statement or an item) rather than producing a value. The expander's
41    /// emit/splice heuristics treat statements and items alike, so they ask
42    /// this instead of comparing against a single variant.
43    #[must_use]
44    pub fn is_stmt_like(self) -> bool {
45        matches!(self, InnerKind::Stmt | InnerKind::Item)
46    }
47
48    /// Whether a fragment of this kind is *code to run* rather than a value to
49    /// insert — [`is_stmt_like`](Self::is_stmt_like) widened to include a whole
50    /// sequence of statements.
51    ///
52    /// The two differ for exactly one case, and it matters: a ground unquote
53    /// holding **several** statements parses with the file root
54    /// (`source_file` / `module`), so `is_stmt_like` says `false` even though a
55    /// statement sequence is the least value-like thing there is. The expander
56    /// asks this when deciding whether to splice a ground unquote or emit it;
57    /// see `Expander::expand`.
58    #[must_use]
59    pub fn is_code_like(self) -> bool {
60        self.is_stmt_like() || matches!(self, InnerKind::File)
61    }
62}
63
64#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
65pub enum Arity {
66    #[default]
67    Unknown,
68    Const(u8),
69    Variadic,
70}
71
72impl Arity {
73    /// Look a node kind up in one of the derived tables in
74    /// [`langs::arity`](crate::langs::arity).
75    ///
76    /// `table` must be sorted — the generated ones are, and this binary searches
77    /// them rather than scanning, because `arity` is asked once per node per
78    /// expansion.
79    ///
80    /// A miss is [`Unknown`](Arity::Unknown), not `Const`: the grammar says only
81    /// whether a kind *can* repeat, and a node that cannot still has whatever
82    /// fixed number of children its rule spells out. Nothing in the expander
83    /// distinguishes the two, so there is no arity to invent here.
84    #[must_use]
85    pub fn from_table(table: &[&str], tag: &str) -> Arity {
86        if table.binary_search(&tag).is_ok() {
87            Arity::Variadic
88        } else {
89            Arity::Unknown
90        }
91    }
92}
93
94/// The separator of a node kind found in one of the derived
95/// `*_COMMA_SEPARATED` tables in [`langs::arity`](crate::langs::arity): `","`
96/// on a hit, `None` otherwise. `table` must be sorted, as the generated ones
97/// are.
98#[must_use]
99pub fn comma_separator(table: &[&str], tag: &str) -> Option<&'static str> {
100    table.binary_search(&tag).is_ok().then_some(",")
101}
102
103#[derive(Debug, Clone, Default)]
104pub struct Hole {
105    pub otag: Box<str>, // outer tag: where this hole appears in the outer language
106    /// Inner kind: what kind of thing can fill this hole, derived from `otag`
107    /// via the outer language's [`Language::typ`]. Threaded into the nested
108    /// `parse_pre` so an unquote body is parsed with the kind its position
109    /// demands (e.g. a `{ }` in statement position) instead of a guess.
110    pub ikind: Option<InnerKind>,
111    pub prefix: Box<[Box<str>]>,
112}
113
114#[derive(Debug, Clone, PartialEq, Eq)]
115pub enum FlatNode<'a> {
116    Hole,
117    /// A hole a one-line `↙…↘` splices its value into. It is a [`Hole`] in
118    /// every respect but one: a column-sensitive language may align the
119    /// splice to the hole's column (see
120    /// [`TSProvider::align_splices`](crate::treesitter::TSProvider::align_splices)).
121    /// A quote's hole is not one — at ground level its expansion is builder
122    /// code (in a Lean host, a string literal, which padding would change) —
123    /// and neither is a multi-line unquote's, whose own source lines the
124    /// padding would shift when the term is written back as `.quilt`.
125    ///
126    /// [`Hole`]: FlatNode::Hole
127    Splice,
128    Str(&'a str),
129    NewLine,
130}
131
132impl FlatNode<'_> {
133    /// Whether this is a hole of either kind.
134    #[must_use]
135    pub fn is_hole(&self) -> bool {
136        matches!(self, Self::Hole | Self::Splice)
137    }
138}
139
140/// Whether `tag` is a node kind the target language uses for a comment.
141///
142/// Needed by the `.quilt`-source renderer (`STerm::coparse_quilt`, #223): a
143/// Quilt glyph inside a comment is *raw text*, because the grammar's comment
144/// token consumes the rest of the line and never applies the `escape` rule
145/// inside one. Writing `\↙` there would produce a literal backslash rather than
146/// an escape, so comment content is the one place source rendering must not
147/// escape (#237).
148///
149/// This is a naming convention rather than a per-language table, deliberately:
150/// every tree-sitter grammar quilt vendors spells its comment kinds `comment`,
151/// `line_comment` or `block_comment`, and a table keyed by language is the
152/// hardcoded-shape pattern issue #174 exists to prevent. It is not taken on
153/// trust either — `quilt-conformance`'s `comment_tags_are_recognised` builds a
154/// comment in every registered language from [`Comments::LINE`] and asserts the
155/// tag its grammar produces satisfies this, so a language whose grammar names
156/// comments differently fails there rather than silently losing its escapes.
157#[must_use]
158pub fn is_comment_tag(tag: &str) -> bool {
159    tag == "comment" || tag.ends_with("_comment")
160}
161
162/// How a language spells comments: the static half of its surface syntax,
163/// declared once beside its [`Language`] impl.
164///
165/// Read by name through [`langs::line_comment`](crate::langs::line_comment) and
166/// [`langs::header_comment`](crate::langs::header_comment), which `define_omni!`
167/// generates from the same table that maps names and aliases onto languages.
168/// That is the whole point. The `DO NOT EDIT` header's marker started as a
169/// `match` on the output file's *extension* inside the CLI (issue #136, where
170/// every language got Rust's `//!`), then became a hand-written table beside the
171/// language modules — either way a second place to register a language, free to
172/// disagree with the first. Here there is no second place: a new language
173/// implements this trait or it does not compile, and its aliases inherit the
174/// answer by construction (issue #194).
175///
176/// Associated consts rather than [`Language`] methods, for two reasons. An
177/// associated const makes a trait non-dyn-compatible, and `Language` is used as
178/// `dyn Language` by `DynOmniLanguages`. And a const-valued lookup is a `match`
179/// yielding a `&'static str`, where a `&self` method would mean *constructing* a
180/// language — a tree-sitter `Parser` per call — to read one: quilt-lsp asks for
181/// a line comment once per comment gap while projecting a document, so that cost
182/// is not academic.
183pub trait Comments {
184    /// The line-comment introducer, e.g. `//`.
185    ///
186    /// `None` when no *prefix* can express one: HTML's comments are delimited
187    /// (`<!-- … -->`, and a prefix alone would open one that never closes), and
188    /// plain text has no comment syntax at all. Callers decide the fallback.
189    const LINE: Option<&'static str> = Some("//");
190
191    /// The introducer for the `DO NOT EDIT` header the CLI writes onto a
192    /// generated file, which has to be a comment *in the language just
193    /// generated* — issue #136.
194    ///
195    /// Defaults to [`LINE`](Comments::LINE); Rust overrides it with `//!`, an
196    /// inner doc comment, which documents the generated module rather than
197    /// whatever item happens to follow the header.
198    const HEADER: Option<&'static str> = Self::LINE;
199}
200
201// WARN: assumers no newlines
202pub fn one_liner(s: &str) -> [FlatNode<'_>; 1] {
203    [FlatNode::Str(s)]
204}
205
206pub fn flat_nodes(s: &str) -> Vec<FlatNode<'_>> {
207    let lines = s.split('\n').collect::<Vec<_>>();
208    let mut nodes = Vec::new();
209    for (i, line) in lines.iter().enumerate() {
210        if i > 0 {
211            nodes.push(FlatNode::NewLine);
212        }
213        if !line.is_empty() {
214            nodes.push(FlatNode::Str(line));
215        }
216    }
217    nodes
218}
219
220impl std::ops::Add for &Hole {
221    type Output = Hole;
222
223    fn add(self, rhs: Self) -> Self::Output {
224        let otag = rhs.otag.clone();
225        let ikind = rhs.ikind;
226        let mut prefix = self.prefix.to_vec();
227        prefix.extend_from_slice(&rhs.prefix);
228        let prefix = prefix.into();
229        Hole {
230            otag,
231            ikind,
232            prefix,
233        }
234    }
235}
236
237pub trait Language {
238    type Post: LanguagePost;
239
240    /// Parse a string into something that can be filled with plugs and a list of hole types.
241    fn parse_pre(&mut self, ikind: Option<InnerKind>, code: &[FlatNode]) -> Result<Self::Post>;
242
243    /// Convenience function to parse and fill with plugs.
244    fn parse_with(&mut self, code: &[FlatNode], plugs: &[Arc<QTerm>]) -> Result<Arc<QTerm>> {
245        self.parse_pre(Default::default(), code)?.parse_post(plugs)
246    }
247
248    /// Convenience function to parse without plugs.
249    fn parse(&mut self, code: &[FlatNode]) -> Result<Arc<QTerm>> {
250        self.parse_with(code, &[])
251    }
252
253    /// Convenience function to parse as a given `TermKind` and fill with plugs.
254    fn parse_as(&mut self, ikind: Option<InnerKind>, code: &[FlatNode]) -> Result<Arc<QTerm>> {
255        self.parse_pre(ikind, code)?.parse_post(&[])
256    }
257
258    fn parse_expr(&mut self, code: &[FlatNode]) -> Result<Arc<QTerm>> {
259        self.parse_as(Some(InnerKind::Expr), code)
260    }
261
262    fn parse_stmt(&mut self, code: &[FlatNode]) -> Result<Arc<QTerm>> {
263        self.parse_as(Some(InnerKind::Stmt), code)
264    }
265
266    fn parse_file(&mut self, code: &[FlatNode]) -> Result<Arc<QTerm>> {
267        self.parse_as(Some(InnerKind::File), code)
268    }
269
270    fn parse_auto(&mut self, code: &[FlatNode]) -> Result<Arc<QTerm>> {
271        self.parse_as(None, code)
272    }
273
274    fn arity(&self, _tag: &str) -> Arity {
275        Default::default()
276    }
277
278    /// The token that separates the repeated children of a variadic node of
279    /// kind `tag` — `","` for an array, an argument list, a Python list — or
280    /// `None` when they are not separated (a block, a statement list).
281    ///
282    /// The expander asks this for a splice into such a node (`[↙xs↘]`,
283    /// `f(↙xs↘)`) and has the builder separate the elements the splice
284    /// contributes, which otherwise come out back to back (#293). The answer
285    /// is derived from the grammar, like [`arity`](Self::arity)'s.
286    fn separator(&self, _tag: &str) -> Option<&'static str> {
287        None
288    }
289
290    fn typ(&self, _tag: &str) -> InnerKind {
291        Default::default()
292    }
293
294    /// Classify a fully-parsed `QTerm` to determine its grammatical kind.
295    ///
296    /// This is the *accurate* version of [`typ`]: unlike `typ`, which receives
297    /// only the root tag name, `classify_term` can inspect the full term tree.
298    /// This matters for languages (e.g. WGSL) where a single statement is
299    /// wrapped in a `source_file` node with a trailing `;` sibling, so the
300    /// root tag alone gives `File` even though the fragment is really `Stmt`.
301    ///
302    /// The default implementation falls back to `typ` on the root tag, which
303    /// is correct for languages whose `unwrap` always squashes the wrapper.
304    fn classify_term(&self, term: &QTerm) -> InnerKind {
305        match term {
306            QTerm::Tuple { tag, .. } => self.typ(tag),
307            _ => InnerKind::default(),
308        }
309    }
310
311    /// The node kind this language spells a bare identifier with.
312    ///
313    /// The expander needs it for the one term it constructs itself rather than
314    /// parsing: an operator (`↑`, `↓`, `←`) inside an as-yet-unresolved quote is
315    /// deferred as its glyph, to be spelled out when that stage runs. That
316    /// placeholder used to be hardcoded as `leaf("identifier", …)` in
317    /// `multi.rs` — a Rust tag applied to every language, and simply not a node
318    /// kind bash or zsh define (they have `word`); see issue #174, finding E2.
319    ///
320    /// The default is right for every language here except the shells.
321    fn ident_tag(&self) -> &'static str {
322        "identifier"
323    }
324
325    /// Shebang line used to run an expanded file of this language, if supported.
326    /// e.g. `"#!/usr/bin/env rust-script"` or `"#!/usr/bin/env python3"`.
327    ///
328    /// Use [`parse_hashbang`] to turn one into a command — the interpreter is not
329    /// always the last word.
330    fn hashbang(&self) -> Option<&'static str> {
331        None
332    }
333
334    /// How to drive this language as a stateful
335    /// [`Machine`](crate::machine::Machine): the runner and spellings a
336    /// [`ScriptMachine`](crate::machine::ScriptMachine) needs. The same
337    /// pattern as [`hashbang`](Self::hashbang) (and usually derived from it
338    /// via [`MachineSpec::from_hashbang`](crate::machine::MachineSpec::from_hashbang));
339    /// `None` means no script machine — a richer provider may still exist.
340    /// See `docs/design/machines.md`.
341    fn machine_spec(&self) -> Option<crate::machine::MachineSpec> {
342        None
343    }
344
345    /// How to drive this language as a *persistent*
346    /// [`ReplMachine`](crate::machine::ReplMachine): a long-lived interactive
347    /// interpreter fed on stdin, so state is real process state rather than
348    /// [`machine_spec`](Self::machine_spec)'s replayed history. Preferred
349    /// over the script spec when both exist
350    /// (see [`spawn_machine`](crate::machine::spawn_machine)).
351    fn repl_spec(&self) -> Option<crate::machine::ReplSpec> {
352        None
353    }
354
355    /// A machine for this language that needs no interpreter at all — state
356    /// held in-process, as terms. HTML's is a document
357    /// ([`HtmlMachine`](crate::machine::HtmlMachine)); a language with a
358    /// native evaluator would answer the same way. Preferred over both
359    /// subprocess providers by
360    /// [`spawn_machine`](crate::machine::spawn_machine), and spawned fresh on
361    /// each call — the returned machine is the caller's.
362    fn native_machine(&self) -> Option<Box<dyn crate::machine::Machine>> {
363        None
364    }
365}
366
367/// Split a [`Language::hashbang`] into the program to execute and the arguments
368/// that precede the script path.
369///
370/// `quilt run` used to take `split_whitespace().next_back()` — the *last* word —
371/// which is the interpreter only when the shebang has no arguments. TypeScript's
372/// is `#!/usr/bin/env -S node --experimental-strip-types`, so that yielded
373/// `--experimental-strip-types` and `quilt run foo.ts.quilt` tried to execute the
374/// flag (issue #174, finding F).
375///
376/// `env` is unwrapped the way `env -S` does it: its own options (`-S`, `-i`,
377/// `-u NAME`, `--`) and any `VAR=value` assignments are skipped, and the first
378/// remaining word is the real program. Everything after it is an argument to that
379/// program.
380///
381/// Returns `None` when no program can be identified — an empty shebang, or one
382/// that is nothing but `env` and its options.
383#[must_use]
384pub fn parse_hashbang(hashbang: &str) -> Option<(&str, Vec<&str>)> {
385    let mut words = hashbang.trim_start_matches("#!").split_whitespace();
386    let first = words.next()?;
387
388    // A non-`env` interpreter is used as given: `#!/bin/sh -e` → ("/bin/sh", ["-e"]).
389    if basename(first) != "env" {
390        return Some((first, words.collect()));
391    }
392
393    // `env` itself: skip its options and any environment assignments to find the
394    // program it would exec.
395    let mut program = None;
396    while let Some(word) = words.next() {
397        match word {
398            // `-u NAME` / `--unset=NAME` take a value; the others are flags.
399            "-u" | "--unset" => {
400                words.next();
401            }
402            "--" => {}
403            _ if word.starts_with('-') => {}
404            // `VAR=value` sets the child's environment rather than naming it.
405            _ if word.contains('=') => {}
406            _ => {
407                program = Some(word);
408                break;
409            }
410        }
411    }
412    Some((program?, words.collect()))
413}
414
415/// The final path component of `path`, for comparing a program name against
416/// `env` without caring whether the shebang spelled it `/usr/bin/env`.
417fn basename(path: &str) -> &str {
418    path.rsplit('/').next().unwrap_or(path)
419}
420
421pub trait LanguagePost: Debug {
422    /// Get the hole types that this language supports.
423    fn holes(&self) -> &[Hole];
424    /// Fill with plugs.
425    fn parse_post(&self, plugs: &[Arc<QTerm>]) -> Result<Arc<QTerm>>;
426}
427
428/**************************************************************/
429
430impl Language for Box<dyn Language<Post = Box<dyn LanguagePost>>> {
431    type Post = Box<dyn LanguagePost>;
432
433    fn parse_pre(&mut self, ikind: Option<InnerKind>, code: &[FlatNode]) -> Result<Self::Post> {
434        self.as_mut().parse_pre(ikind, code)
435    }
436
437    fn arity(&self, tag: &str) -> Arity {
438        self.as_ref().arity(tag)
439    }
440
441    fn separator(&self, tag: &str) -> Option<&'static str> {
442        self.as_ref().separator(tag)
443    }
444
445    fn typ(&self, tag: &str) -> InnerKind {
446        self.as_ref().typ(tag)
447    }
448
449    fn classify_term(&self, term: &QTerm) -> InnerKind {
450        self.as_ref().classify_term(term)
451    }
452
453    fn ident_tag(&self) -> &'static str {
454        self.as_ref().ident_tag()
455    }
456
457    fn hashbang(&self) -> Option<&'static str> {
458        self.as_ref().hashbang()
459    }
460
461    fn machine_spec(&self) -> Option<crate::machine::MachineSpec> {
462        self.as_ref().machine_spec()
463    }
464
465    fn repl_spec(&self) -> Option<crate::machine::ReplSpec> {
466        self.as_ref().repl_spec()
467    }
468
469    fn native_machine(&self) -> Option<Box<dyn crate::machine::Machine>> {
470        self.as_ref().native_machine()
471    }
472}
473
474impl LanguagePost for Box<dyn LanguagePost> {
475    fn holes(&self) -> &[Hole] {
476        self.as_ref().holes()
477    }
478
479    fn parse_post(&self, plugs: &[Arc<QTerm>]) -> Result<Arc<QTerm>> {
480        self.as_ref().parse_post(plugs)
481    }
482}
483
484/**************************************************************/
485
486#[cfg(test)]
487mod tests {
488    use super::parse_hashbang;
489
490    /// Every shebang a `Language` in this repo declares must name its
491    /// interpreter, not a flag. TypeScript's is the case that regressed.
492    #[test]
493    fn parses_the_declared_hashbangs() {
494        let cases = [
495            ("#!/usr/bin/env rust-script", "rust-script", vec![]),
496            ("#!/usr/bin/env python3", "python3", vec![]),
497            ("#!/usr/bin/env bash", "bash", vec![]),
498            ("#!/usr/bin/env zsh", "zsh", vec![]),
499            (
500                "#!/usr/bin/env -S node --experimental-strip-types",
501                "node",
502                vec!["--experimental-strip-types"],
503            ),
504        ];
505        for (hashbang, program, args) in cases {
506            assert_eq!(
507                parse_hashbang(hashbang),
508                Some((program, args)),
509                "{hashbang:?} did not resolve to its interpreter"
510            );
511        }
512    }
513
514    /// Shapes Quilt does not use today but that `env` accepts, so a language
515    /// adding one is not a surprise breakage.
516    #[test]
517    fn parses_other_env_shapes() {
518        // A direct interpreter, with its own flag.
519        assert_eq!(
520            parse_hashbang("#!/bin/sh -e"),
521            Some(("/bin/sh", vec!["-e"]))
522        );
523        // `env` with an environment assignment, and with `-u NAME`.
524        assert_eq!(
525            parse_hashbang("#!/usr/bin/env FOO=1 python3 -X dev"),
526            Some(("python3", vec!["-X", "dev"]))
527        );
528        assert_eq!(
529            parse_hashbang("#!/usr/bin/env -u FOO -S node"),
530            Some(("node", vec![]))
531        );
532        // A bare `env` names no program.
533        assert_eq!(parse_hashbang("#!/usr/bin/env -S"), None);
534        assert_eq!(parse_hashbang("#!"), None);
535    }
536}