quiltlang 0.4.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
use crate::lang::{Arity, FlatNode, Hole, InnerKind, Language, LanguagePost};
use crate::prelude::*;
use crate::qterm::{qsym, QTerm, QTermBuilder};
use miette::bail;
use std::fmt::Debug;
use std::iter::Peekable;
use std::vec::IntoIter;
use tree_sitter::{Parser, Point, Tree};

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

/// Parse multiple lines of code into a tree-sitter tree.
/// Lines must end with a newline character, except possibly the last line.
fn ts_parse_lines(parser: &mut Parser, lines: &[&str]) -> Result<Tree> {
    let mut callback = |_byte_offset: usize, point: Point| -> &str {
        if point.row < lines.len() {
            &lines[point.row][point.column..]
        } else {
            ""
        }
    };

    let Some(tree) = parser.parse_with_options(&mut callback, None, None) else {
        bail!("Failed to parse: {lines:?}");
    };
    if tree.root_node().has_error() {
        bail!(
            "Parsed with errors: {lines:?} {}",
            tree.root_node().to_sexp()
        )
    }
    Ok(tree)
}

#[inline]
fn drop_last(s: &str) -> &str {
    &s[..s.len() - 1]
}

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

/// Language provider used by `TSLanguage`
pub trait TSProvider {
    /// A tree-sitter parser
    fn parser(&mut self) -> &mut tree_sitter::Parser;
    /// A string representing a hole where another language is dropped in.
    /// Must not contain new-lines.
    fn hole_str(&self) -> &'static str;
    fn unwrap(&self, qterm: QTerm, _ikind: Option<InnerKind>) -> Result<(QTerm, InnerKind)> {
        Ok((qterm, Default::default()))
    }
    fn arity(&self, _tag: &str) -> Arity {
        Default::default()
    }
    /// The `InnerKind` a node with this tag denotes (used to derive
    /// [`Hole::ikind`] from the hole's position).
    fn typ(&self, _tag: &str) -> InnerKind {
        Default::default()
    }

    /// The [`InnerKind`] a hole at this tree-sitter node's position demands.
    ///
    /// Unlike [`typ`](TSProvider::typ), which only sees a node's *kind* (its
    /// tag), this is handed the node in its parse tree, so it can read context
    /// the tag alone can't express. The motivating case is [`InnerKind::Block`]:
    /// a Rust `block` is an expression by tag (`let x = { … }`), but in body
    /// position (`fn f() { … }`, `loop { … }`, `if c { … }`) it denotes a block
    /// body. The default ignores the extra context and falls back to
    /// `typ(node.kind())`.
    fn hole_kind(&self, node: tree_sitter::Node) -> InnerKind {
        self.typ(node.kind())
    }

    /// Classify a fully-parsed term to determine its kind.  Unlike [`typ`],
    /// which only sees the root tag, this can inspect the full term tree.
    /// The default falls back to `typ` on the root tag; override for languages
    /// where the wrapper node's tag is ambiguous (e.g. WGSL's `source_file`
    /// which can hold a statement + trailing `;` with `len == 2`).
    fn classify_term(&self, term: &QTerm) -> InnerKind {
        match term {
            QTerm::Tuple { tag, .. } => self.typ(tag),
            _ => InnerKind::default(),
        }
    }

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

#[derive(Default)]
pub struct TSLanguage<P: TSProvider> {
    provider: P,
}

#[derive(Debug)]
pub struct TSLanguagePost {
    pub holes: Box<[Hole]>,
    pub qterm: QTerm,
    pub hole_str: &'static str,
}

impl<P: TSProvider> Language for TSLanguage<P> {
    type Post = TSLanguagePost;

    fn parse_pre(&mut self, ikind: Option<InnerKind>, code: &[FlatNode]) -> Result<Self::Post> {
        // convert node to sterm while populating holes.
        fn f<P: TSProvider>(
            provider: &P,
            node: tree_sitter::Node,
            lines: &[&str],
            hole_points: &mut Peekable<IntoIter<(usize, usize, usize)>>,
            holes: &mut Vec<Hole>,
            prefix: &mut Vec<Box<str>>,
            root: bool,
        ) -> QTerm {
            let range = node.range();
            let (start, end) = if root {
                (
                    Point::default(),
                    Point {
                        row: lines.len() - 1,
                        column: lines.last().unwrap().len(),
                    },
                )
            } else {
                (range.start_point, range.end_point)
            };
            let hole_str = provider.hole_str();

            // check if this is a hole
            if start.row == end.row
                && hole_points.peek() == Some(&(start.row, start.column, end.column))
            {
                hole_points.next();
                holes.push(Hole {
                    otag: node.kind().into(),
                    // `hole_kind` (not `typ`) so the surrounding tree can refine
                    // the kind — e.g. a body-position `block` becomes `Block`
                    // rather than the `Expr` its tag alone implies.
                    ikind: Some(provider.hole_kind(node)),
                    prefix: prefix.clone().into(),
                });
                return qsym(hole_str);
            }

            // A multiline *leaf* token (e.g. HTML `raw_text`): its lines are
            // real content, not inter-child whitespace, so write them
            // verbatim — continuation lines minus the current prefix. (The
            // gap logic below would misread them as indentation and drop
            // them.)
            if node.child_count() == 0 && start.row != end.row {
                let mut builder = tb(node.kind());
                builder.write(drop_last(&lines[start.row][start.column..]));
                let pre = prefix.concat();
                let rows = lines.iter().enumerate();
                for (row, line) in rows.take(end.row + 1).skip(start.row + 1) {
                    let line = if row == end.row {
                        &line[..end.column]
                    } else {
                        drop_last(line)
                    };
                    builder.nl();
                    builder.write(line.strip_prefix(&pre).unwrap_or(line));
                }
                return builder.build();
            }

            // otherwise, recurse into children
            fn process<'a>(
                builder: &'a mut QTermBuilder, // TODO: use TupleBuilder
                depth: &mut i32,
                lines: &[&str],
                prefix: &mut Vec<Box<str>>,
                p0: Point,
                p1: Point,
            ) -> &'a mut QTermBuilder {
                if p0.row == p1.row {
                    builder.write(&lines[p0.row][p0.column..p1.column])
                } else {
                    // drop the trailing newline
                    builder.write(drop_last(&lines[p0.row][p0.column..]));
                    // TODO: this makes a bunch of assumptions about the language
                    let new_prefix = &lines[p1.row][..p1.column];
                    loop {
                        if let Some(push) = new_prefix.strip_prefix(&prefix.concat()) {
                            if !push.is_empty() {
                                // println!("push: '{push}'");
                                prefix.push(push.into());
                                builder.push(push);
                                *depth += 1;
                            }
                            break;
                        }
                        // println!("pop");
                        prefix.pop();
                        builder.pop();
                        *depth -= 1;
                    }
                    for _ in 0..(p1.row - p0.row) {
                        builder.nl();
                    }
                    builder
                }
            }

            let mut builder = tb(node.kind());
            let mut depth: i32 = 0;
            let mut point = start;
            for i in 0..node.child_count() {
                let child = node.child(i).unwrap();
                let crange = child.range();
                process(
                    &mut builder,
                    &mut depth,
                    lines,
                    prefix,
                    point,
                    crange.start_point,
                );
                point = crange.end_point;
                builder.child(&arc(f(
                    provider,
                    child,
                    lines,
                    hole_points,
                    holes,
                    prefix,
                    false,
                )));
            }
            process(&mut builder, &mut depth, lines, prefix, point, end);
            for _ in 0..depth {
                prefix.pop();
                builder.pop();
            }
            builder.build()
        }

        let mut hole_points = vec![];
        let mut row: usize = 0;
        let mut col: usize = 0;

        let mut lines = vec![String::new()];
        for c in code {
            match c {
                FlatNode::Hole => {
                    lines.last_mut().unwrap().push_str(self.provider.hole_str());
                    let new_col = lines.last().unwrap().len();
                    hole_points.push((row, col, new_col));
                    col = new_col;
                }
                FlatNode::Str(s) => {
                    lines.last_mut().unwrap().push_str(s);
                    col += s.len();
                }
                FlatNode::NewLine => {
                    // Lines must end with a newline character, except possibly the last line.
                    lines.last_mut().unwrap().push('\n');
                    lines.push(String::new());
                    row += 1;
                    col = 0;
                }
            }
        }
        let lines = lines.iter().map(|s| s.as_ref()).collect::<Box<[_]>>();
        let tree = ts_parse_lines(self.provider.parser(), &lines)?;

        let mut hole_points = hole_points.into_iter().peekable();
        let mut holes = vec![];
        let mut prefix = vec![];
        let qterm = f(
            &self.provider,
            tree.root_node(),
            &lines,
            &mut hole_points,
            &mut holes,
            &mut prefix,
            true,
        );
        let (qterm, _ikind) = self.provider.unwrap(qterm, ikind)?;
        let holes = holes.into();
        let hole_str = self.provider.hole_str();

        Ok(Self::Post {
            holes,
            qterm,
            hole_str,
        })
    }

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

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

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

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

impl LanguagePost for TSLanguagePost {
    fn holes(&self) -> &[Hole] {
        &self.holes
    }

    fn parse_post(&self, plugs: &[Arc<QTerm>]) -> Result<Arc<QTerm>> {
        // fill the holes with plugs
        fn fill<'a>(
            qterm: &QTerm,
            plugs: &mut impl Iterator<Item = &'a Arc<QTerm>>,
            hole_str: &str,
        ) -> Arc<QTerm> {
            match qterm {
                QTerm::Quote {
                    tag,
                    index,
                    lang,
                    term,
                    cmds,
                    span,
                } => arc(crate::qterm::qquote_at(
                    tag,
                    *index,
                    lang,
                    fill(term, plugs, hole_str),
                    cmds,
                    span.clone(),
                )),
                QTerm::Unquote {
                    tag,
                    index,
                    lang,
                    term,
                    cmds,
                    span,
                } => arc(crate::qterm::qunquote_at(
                    tag,
                    *index,
                    lang,
                    fill(term, plugs, hole_str),
                    cmds,
                    span.clone(),
                )),
                QTerm::Tuple { tag, terms, cmds } => {
                    if &**tag == hole_str {
                        return plugs.next().unwrap().clone();
                    }
                    tuple(
                        tag,
                        &terms
                            .iter()
                            .map(|t| fill(t, plugs, hole_str))
                            .collect::<Vec<_>>(),
                        cmds,
                    )
                }
            }
        }

        assert_eq!(plugs.len(), self.holes.len());
        Ok(fill(&self.qterm, &mut plugs.iter(), self.hole_str))
    }
}

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

#[derive(Default)]
pub struct DynTSLanguage<P: TSProvider>(TSLanguage<P>);

impl<P: TSProvider> Language for DynTSLanguage<P> {
    type Post = Box<dyn LanguagePost>;

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

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

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

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

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

impl<T: LanguagePost> LanguagePost for Box<T> {
    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::*;
    use crate::langs::rust::lang::RustProvider;

    /// Parse a string of code into a tree-sitter tree.
    fn ts_parse(parser: &mut Parser, code: &str) -> Result<Tree> {
        let Some(tree) = parser.parse(code, None) else {
            bail!("Failed to parse: {code}");
        };
        if tree.root_node().has_error() {
            bail!("Parsed with errors: {code}")
        }
        Ok(tree)
    }

    #[test]
    fn test_ts_parse_lines() -> Result<()> {
        let lines = [
            "fn foo() {\n",
            "    println!(\"Hello\");\n",
            "    println!(\"World\");\n",
            "}",
        ];
        let mut provider = RustProvider::default();
        let parser = provider.parser();

        let code = lines.join("");
        let tree_1 = ts_parse(parser, &code)?;
        let tree_2 = ts_parse(parser, &code)?;
        assert_eq!(tree_1.root_node().to_sexp(), tree_2.root_node().to_sexp());
        Ok(())
    }

    #[test]
    fn test_ts_parse_lines_empty() -> Result<()> {
        let lines: [&'static str; 0] = [];
        let mut provider = RustProvider::default();
        let parser = provider.parser();

        let code = lines.join("");
        let tree_1 = ts_parse(parser, &code)?;
        let tree_2 = ts_parse(parser, &code)?;
        assert_eq!(tree_1.root_node().to_sexp(), tree_2.root_node().to_sexp());
        Ok(())
    }
}