quilt/langs/typescript/meta.rs
1use miette::Result;
2
3use super::ops::{
4 build_qt_code, build_quote_code, build_str_code, build_tuple_code, build_unquote_code,
5 build_variadic_block,
6};
7use crate::lang::Arity;
8use crate::prelude::{Index, *};
9use crate::{
10 meta::{MetaLanguage, Piece, Prelude},
11 qterm::{QTerm, Repr},
12 term::CmdOrHole,
13};
14
15/**************************************************************/
16
17/// `←` inside a `⟨str⟩` quote, applied to the source's own `(items, sep)`.
18const STR_JOIN: &str = r#"((items, sep = "\n") => Array.from(items, String).join(sep))"#;
19
20#[derive(Default)]
21pub struct TypeScriptMetaLanguage;
22
23impl MetaLanguage for TypeScriptMetaLanguage {
24 fn expand_quote(
25 &self,
26 _lang1: &str,
27 tag: &str,
28 i: Index,
29 lang2: &str,
30 qterm: &Arc<QTerm>,
31 cmds: &[CmdOrHole],
32 ) -> Result<Arc<QTerm>> {
33 Ok(build_quote_code(tag, i, lang2, qterm, cmds))
34 }
35
36 fn expand_unquote(
37 &self,
38 _lang1: &str,
39 tag: &str,
40 i: Index,
41 lang2: &str,
42 qterm: &Arc<QTerm>,
43 cmds: &[CmdOrHole],
44 ) -> Result<Arc<QTerm>> {
45 Ok(build_unquote_code(tag, i, lang2, qterm, cmds))
46 }
47
48 fn expand_tuple(
49 &self,
50 _lang1: &str,
51 tag: &str,
52 qterms: &[Arc<QTerm>],
53 cmds: &[CmdOrHole],
54 arity: Arity,
55 ) -> Result<Arc<QTerm>> {
56 Ok(if arity == Arity::Variadic {
57 build_variadic_block(tag, cmds, qterms)
58 } else {
59 build_tuple_code(tag, cmds, qterms)
60 })
61 }
62
63 // `↑` is target-directed and written prefix, `↑(value)`: into TypeScript it
64 // spells the `qlift` function (number/string/boolean → TS literals); into
65 // HTML it spells `qlift_html`, which entity-escapes lifted strings at
66 // runtime, and into text `qlift_text`. All live in the `quilt-wasm`
67 // runtime.
68 fn lift_str(&self, target: &str) -> Result<&'static str> {
69 match target {
70 "typescript" | "ts" => Ok("qlift"),
71 "html" => Ok("qlift_html"),
72 // Into text: `qlift_text`, or `qlift_text_in_quotes` for a hole the
73 // author wrapped in `"…"` (`lift::text`). Both take an optional
74 // dialect object as a second argument.
75 "text" | "txt" => Ok("qlift_text"),
76 crate::lift::TEXT_IN_QUOTES => Ok("qlift_text_in_quotes"),
77 _ => miette::bail!("typescript can't lift into {target:?}: no spelling registered"),
78 }
79 }
80
81 fn reduce_str(&self, target: &str) -> Result<&'static str> {
82 match target {
83 "" | "typescript" | "ts" => Ok("reduce()"),
84 _ => miette::bail!("typescript can't reduce via {target:?}: no spelling registered"),
85 }
86 }
87
88 fn name_str(&self) -> Result<&'static str> {
89 Ok("name")
90 }
91
92 fn type_str(&self) -> Result<&'static str> {
93 Ok("QTerm")
94 }
95
96 /// `←` is *functional* here, as in Nix: written prefix with its argument
97 /// in parentheses, `←(items)` or `←(items, sep)`, it spells the runtime's
98 /// `qseq`, which turns a whole iterable of fragments into one term that
99 /// splices them in order — a newline between each by default, so a
100 /// sequence of statements spliced into a block stays one per line at the
101 /// block's indent:
102 ///
103 /// ```ts
104 /// const body = ts↖{
105 /// ↙←(names.map((n) => ts↖console.log(↙↑(n)↘);↗))↘
106 /// }↗;
107 /// ```
108 ///
109 /// Rust's imperative reading (append to a `b_` accumulator once around a
110 /// loop, issue #152) would need statements in expression position and a
111 /// mutable builder; the functional one needs neither, and is what
112 /// TypeScript code builds lists with anyway.
113 fn emit_str(&self) -> Result<&'static str> {
114 Ok("qseq")
115 }
116
117 /// Inside a `⟨str⟩` quote a lifted value must be text: into TypeScript
118 /// `↑` spells `qlift_str`, the literal's source as a string (a safe
119 /// integer goes straight through `String`). Into another language the
120 /// term-building lift still works, since a term interpolates as its
121 /// source. `⟨cst⟩` and `⟨qt⟩` quotes take terms, so they lift as before.
122 fn lift_str_in(&self, target: &str, repr: Repr) -> Result<&'static str> {
123 match (repr, target) {
124 (Repr::Str, "typescript" | "ts") => Ok("qlift_str"),
125 _ => self.lift_str(target),
126 }
127 }
128
129 /// `←(items)` joins the items into one string inside a `⟨str⟩` quote —
130 /// natively, with an inline arrow, so a `⟨str⟩` writer needs no runtime
131 /// for it — and builds a `qseq` term everywhere else.
132 fn emit_str_in(&self, repr: Repr) -> Result<&'static str> {
133 match repr {
134 Repr::Str => Ok(STR_JOIN),
135 Repr::Cst | Repr::Qt => self.emit_str(),
136 }
137 }
138
139 /// `⟨str⟩`: a template literal; `⟨qt⟩`: a flat builder chain. See
140 /// [`build_str_code`] and [`build_qt_code`].
141 fn expand_flat(&self, repr: Repr, _lang2: &str, pieces: &[Piece]) -> Result<Arc<QTerm>> {
142 Ok(match repr {
143 Repr::Str => build_str_code(pieces),
144 Repr::Qt => build_qt_code(pieces),
145 Repr::Cst => miette::bail!("a `⟨cst⟩` quote is not flattened"),
146 })
147 }
148
149 /// The `import { … } from "quilt"` an expanded file opens with (issue
150 /// #274) — bound by `quilt run` to `quilt-wasm/node`, and in the browser
151 /// demos by an import map to `examples/web/quilt-rt.js`.
152 ///
153 /// This is the one host where the prelude is not a constant, and the reason
154 /// the hook takes `targets` at all: TypeScript has no glob import, so the
155 /// list has to name every runtime function the expansion calls — and
156 /// [`lift_str`](Self::lift_str) is target-directed, so quoting a *new*
157 /// language adds a name to it. Written by hand that is boilerplate you can
158 /// get wrong in a way the source does not hint at: a file that starts
159 /// quoting HTML needs `qlift_html` added, and finds out at run time.
160 ///
161 /// Unknown targets are skipped rather than reported: a language with no
162 /// lift spelling here fails at the `↑` itself, with a message about that
163 /// glyph, which is a better place to hear it than a prelude.
164 fn prelude(&self, targets: &[&str]) -> Option<Prelude> {
165 // The builder vocabulary every expansion uses, in the order the
166 // hand-written imports have always listed it, with the lift spellings
167 // slotted in where `qlift` sat.
168 const HEAD: [&str; 11] = [
169 "tb",
170 "leaf",
171 "sym",
172 "quote",
173 "unquote",
174 "cmd",
175 "write",
176 "push",
177 "name",
178 "qseq",
179 "qlift_str",
180 ];
181 const TAIL: [&str; 3] = ["NL", "POP", "HOLE"];
182 let mut names: Vec<&str> = HEAD.to_vec();
183 for target in targets {
184 // A text quote can hold both spellings: the expander picks the
185 // in-quotes one per hole, from the characters around it, so the
186 // target list (languages, not positions) never names it.
187 let positions: &[&str] = if matches!(*target, "text" | "txt") {
188 &[target, crate::lift::TEXT_IN_QUOTES]
189 } else {
190 &[target]
191 };
192 for position in positions {
193 if let Ok(lift) = self.lift_str(position) {
194 if !names.contains(&lift) {
195 names.push(lift);
196 }
197 }
198 }
199 }
200 names.extend_from_slice(&TAIL);
201 Some(Prelude::new(
202 format!("import {{ {} }} from \"quilt\";", names.join(", ")),
203 // Both spellings of the specifier, because a duplicate *named*
204 // import is a hard `Duplicate identifier` error here — unlike the
205 // glob imports the other hosts inject, which double harmlessly.
206 ["from \"quilt\"", "from 'quilt'"],
207 ))
208 }
209}