quilt/treesitter.rs
1use crate::lang::{Arity, FlatNode, Hole, InnerKind, Language, LanguagePost};
2use crate::prelude::*;
3use crate::qterm::{qsym, QTerm, QTermBuilder};
4use crate::term::CmdOrHole;
5use miette::bail;
6use std::fmt::Debug;
7use std::iter::Peekable;
8use std::vec::IntoIter;
9use tree_sitter::{Parser, Point, Tree};
10
11/**************************************************************/
12
13/// Parse multiple lines of code into a tree-sitter tree.
14/// Lines must end with a newline character, except possibly the last line.
15fn ts_parse_lines(parser: &mut Parser, lines: &[&str]) -> Result<Tree> {
16 let mut callback = |_byte_offset: usize, point: Point| -> &str {
17 if point.row < lines.len() {
18 &lines[point.row][point.column..]
19 } else {
20 ""
21 }
22 };
23
24 let Some(tree) = parser.parse_with_options(&mut callback, None, None) else {
25 bail!("Failed to parse: {lines:?}");
26 };
27 if tree.root_node().has_error() {
28 bail!(
29 "Parsed with errors: {lines:?} {}",
30 tree.root_node().to_sexp()
31 )
32 }
33 Ok(tree)
34}
35
36#[inline]
37fn drop_last(s: &str) -> &str {
38 &s[..s.len() - 1]
39}
40
41/**************************************************************/
42
43/// Where a hole's placeholder sits in the flattened code: one row, a byte
44/// range of it, and whether the hole is a [`FlatNode::Splice`].
45#[derive(Debug, Clone, Copy)]
46struct HolePoint {
47 row: usize,
48 start: usize,
49 end: usize,
50 splice: bool,
51}
52
53impl HolePoint {
54 fn at(&self) -> (usize, usize, usize) {
55 (self.row, self.start, self.end)
56 }
57}
58
59/// Language provider used by `TSLanguage`
60pub trait TSProvider {
61 /// A tree-sitter parser
62 fn parser(&mut self) -> &mut tree_sitter::Parser;
63 /// A string representing a hole where another language is dropped in.
64 /// Must not contain new-lines.
65 fn hole_str(&self) -> &'static str;
66 fn unwrap(&self, qterm: QTerm, _ikind: Option<InnerKind>) -> Result<(QTerm, InnerKind)> {
67 Ok((qterm, Default::default()))
68 }
69 fn arity(&self, _tag: &str) -> Arity {
70 Default::default()
71 }
72 /// See [`Language::separator`].
73 fn separator(&self, _tag: &str) -> Option<&'static str> {
74 None
75 }
76 /// Whether a term spliced into a hole mid-line has its continuation lines
77 /// aligned to the hole's *column*, not just to the line's indentation.
78 ///
79 /// Off by default: in most languages a multi-line splice reads fine at the
80 /// line's indent, and aligning to the column would push every spliced
81 /// block far to the right. A language whose grammar is column-sensitive
82 /// turns it on — in Lean, `def x : S := ↙s↘` with `s` a two-line structure
83 /// instance put the second field left of the first, which is a parse error
84 /// (Lean's `checkColGe`).
85 fn align_splices(&self) -> bool {
86 false
87 }
88 /// The `InnerKind` a node with this tag denotes (used to derive
89 /// [`Hole::ikind`] from the hole's position).
90 fn typ(&self, _tag: &str) -> InnerKind {
91 Default::default()
92 }
93
94 /// The [`InnerKind`] a hole at this tree-sitter node's position demands.
95 ///
96 /// Unlike [`typ`](TSProvider::typ), which only sees a node's *kind* (its
97 /// tag), this is handed the node in its parse tree, so it can read context
98 /// the tag alone can't express. The motivating case is [`InnerKind::Block`]:
99 /// a Rust `block` is an expression by tag (`let x = { … }`), but in body
100 /// position (`fn f() { … }`, `loop { … }`, `if c { … }`) it denotes a block
101 /// body. The default ignores the extra context and falls back to
102 /// `typ(node.kind())`.
103 fn hole_kind(&self, node: tree_sitter::Node) -> InnerKind {
104 self.typ(node.kind())
105 }
106
107 /// Classify a fully-parsed term to determine its kind. Unlike [`typ`],
108 /// which only sees the root tag, this can inspect the full term tree.
109 /// The default falls back to `typ` on the root tag; override for languages
110 /// where the wrapper node's tag is ambiguous (e.g. WGSL's `source_file`
111 /// which can hold a statement + trailing `;` with `len == 2`).
112 fn classify_term(&self, term: &QTerm) -> InnerKind {
113 match term {
114 QTerm::Tuple { tag, .. } => self.typ(tag),
115 _ => InnerKind::default(),
116 }
117 }
118
119 /// See [`Language::ident_tag`](crate::lang::Language::ident_tag).
120 fn ident_tag(&self) -> &'static str {
121 "identifier"
122 }
123
124 fn hashbang(&self) -> Option<&'static str> {
125 None
126 }
127
128 /// See [`Language::machine_spec`](crate::lang::Language::machine_spec).
129 fn machine_spec(&self) -> Option<crate::machine::MachineSpec> {
130 None
131 }
132
133 /// See [`Language::native_machine`](crate::lang::Language::native_machine).
134 fn native_machine(&self) -> Option<Box<dyn crate::machine::Machine>> {
135 None
136 }
137
138 /// See [`Language::repl_spec`](crate::lang::Language::repl_spec).
139 fn repl_spec(&self) -> Option<crate::machine::ReplSpec> {
140 None
141 }
142
143 /// The syntactic contexts a *fragment* — a match arm, an enum variant, a
144 /// constructor, anything that is a valid piece of a file but not a file —
145 /// is retried inside when it does not parse on its own. Tried in order;
146 /// see [`FragmentWrapper`] and [`TSLanguage::parse_fragment`].
147 fn fragment_wrappers(&self) -> &'static [FragmentWrapper] {
148 &[]
149 }
150}
151
152/// A synthetic context that makes a fragment parse, and how to find the
153/// fragment in it again.
154///
155/// The root of every grammar is a whole file, so a quote of something that
156/// only exists *inside* a construct — `rs↖Foo::A(a) => f(a),↗`, a match arm;
157/// `lean↖| zero↗`, a constructor — is a parse error on its own. The fix is the
158/// one Lean's `#check` and SQL's `SELECT` wrappers already use for bare terms:
159/// parse the fragment inside the smallest construct that accepts it, then take
160/// the construct away again.
161///
162/// The fragment sits on lines of its own between [`before`](Self::before) and
163/// [`after`](Self::after), so it keeps its columns (and with them its indent
164/// prefixes). After the parse, the first [`container`](Self::container) node
165/// must hold exactly one child tagged one of [`fragments`](Self::fragments);
166/// that child is the result. Comments directly before it, and the
167/// [`leading`](Self::leading) kinds (Rust's `#[attr]`, which the grammar hangs
168/// on the list rather than on the variant), are folded into it, so a doc
169/// comment travels with the thing it documents.
170///
171/// The result must write back as the quoted text, byte for byte (modulo the
172/// whitespace around it), or the wrapper is not used: a trailing `,` the
173/// container would own, or a second fragment, falls through to the original
174/// parse error.
175#[derive(Debug, Clone, Copy)]
176pub struct FragmentWrapper {
177 /// Text on the line(s) before the fragment, e.g. `match q {`.
178 pub before: &'static str,
179 /// Text on the line(s) after the fragment, e.g. `}`.
180 pub after: &'static str,
181 /// The node kind whose child the fragment is, e.g. `match_block`.
182 pub container: &'static str,
183 /// The node kinds the fragment may be, e.g. `match_arm`.
184 pub fragments: &'static [&'static str],
185 /// Sibling kinds, beyond comments, that belong to the fragment after them.
186 pub leading: &'static [&'static str],
187}
188
189impl FragmentWrapper {
190 /// Find the fragment in `term`, the parse of the wrapped code: the one
191 /// [`fragments`](Self::fragments) child of the first
192 /// [`container`](Self::container), with the comments and
193 /// [`leading`](Self::leading) siblings right before it folded in.
194 fn extract(&self, term: &QTerm) -> Option<Arc<QTerm>> {
195 let QTerm::Tuple { tag, terms, cmds } = term else {
196 return None;
197 };
198 if &**tag != self.container {
199 return terms.iter().find_map(|t| self.extract(t));
200 }
201 let tag_of = |t: &QTerm| match t {
202 QTerm::Tuple { tag, .. } => Some(tag.clone()),
203 _ => None,
204 };
205 let mut hits = terms
206 .iter()
207 .enumerate()
208 .filter(|(_, t)| tag_of(t).is_some_and(|tag| self.fragments.contains(&&*tag)));
209 let (j, _) = hits.next()?;
210 if hits.next().is_some() {
211 return None;
212 }
213 let mut i = j;
214 while i > 0
215 && tag_of(&terms[i - 1]).is_some_and(|tag| {
216 crate::lang::is_comment_tag(&tag) || self.leading.contains(&&*tag)
217 })
218 {
219 i -= 1;
220 }
221 if i == j {
222 return Some(terms[j].clone());
223 }
224 // Fold children `i..j` into child `j`: its tag, their holes and the
225 // text between them, then its own commands.
226 let QTerm::Tuple {
227 tag: jtag,
228 terms: jterms,
229 cmds: jcmds,
230 } = &*terms[j]
231 else {
232 return None;
233 };
234 let holes: Vec<usize> = cmds
235 .iter()
236 .enumerate()
237 .filter_map(|(k, c)| matches!(c, CmdOrHole::Hole).then_some(k))
238 .collect();
239 let between = &cmds[holes[i]..holes[j]];
240 // A prefix pushed between them would be popped after the container,
241 // not inside the fragment.
242 if between
243 .iter()
244 .any(|c| matches!(c, CmdOrHole::Cmd(StrCmd::Push(_) | StrCmd::Pop)))
245 {
246 return None;
247 }
248 let mut new_terms = terms[i..j].to_vec();
249 new_terms.extend(jterms.iter().cloned());
250 let mut new_cmds = between.to_vec();
251 new_cmds.extend(jcmds.iter().cloned());
252 Some(tuple(jtag, &new_terms, &new_cmds))
253 }
254}
255
256/// The text `code` stands for, with each hole spelled `hole_str`.
257fn flat_text(code: &[FlatNode], hole_str: &str) -> String {
258 code.iter()
259 .map(|c| match c {
260 FlatNode::Hole | FlatNode::Splice => hole_str,
261 FlatNode::Str(s) => s,
262 FlatNode::NewLine => "\n",
263 })
264 .collect()
265}
266
267/// How many holes `term` holds: tuples tagged `hole_str`.
268fn count_holes(term: &QTerm, hole_str: &str) -> usize {
269 match term {
270 QTerm::Tuple { tag, .. } if &**tag == hole_str => 1,
271 QTerm::Tuple { terms, .. } => terms.iter().map(|t| count_holes(t, hole_str)).sum(),
272 _ => 0,
273 }
274}
275
276#[derive(Default)]
277pub struct TSLanguage<P: TSProvider> {
278 provider: P,
279}
280
281#[derive(Debug)]
282pub struct TSLanguagePost {
283 pub holes: Box<[Hole]>,
284 pub qterm: QTerm,
285 pub hole_str: &'static str,
286}
287
288impl<P: TSProvider> TSLanguage<P> {
289 /// Parse `code` as the grammar's root (a whole file) and nothing else:
290 /// [`parse_pre`](Language::parse_pre) without the
291 /// [fragment](Self::parse_fragment) retry. A language with retries of its
292 /// own (Lean's `#check`) calls this, so that it can order them.
293 pub fn parse_plain(
294 &mut self,
295 ikind: Option<InnerKind>,
296 code: &[FlatNode],
297 ) -> Result<TSLanguagePost> {
298 // convert node to sterm while populating holes.
299 fn f<P: TSProvider>(
300 provider: &P,
301 node: tree_sitter::Node,
302 lines: &[&str],
303 hole_points: &mut Peekable<IntoIter<HolePoint>>,
304 holes: &mut Vec<Hole>,
305 prefix: &mut Vec<Box<str>>,
306 root: bool,
307 ) -> QTerm {
308 let range = node.range();
309 let (start, end) = if root {
310 (
311 Point::default(),
312 Point {
313 row: lines.len() - 1,
314 column: lines.last().unwrap().len(),
315 },
316 )
317 } else {
318 (range.start_point, range.end_point)
319 };
320 let hole_str = provider.hole_str();
321
322 // check if this is a hole
323 if start.row == end.row
324 && hole_points
325 .peek()
326 .is_some_and(|h| h.at() == (start.row, start.column, end.column))
327 {
328 hole_points.next();
329 holes.push(Hole {
330 otag: node.kind().into(),
331 // `hole_kind` (not `typ`) so the surrounding tree can refine
332 // the kind — e.g. a body-position `block` becomes `Block`
333 // rather than the `Expr` its tag alone implies.
334 ikind: Some(provider.hole_kind(node)),
335 prefix: prefix.clone().into(),
336 });
337 return qsym(hole_str);
338 }
339
340 // A multiline *token*: its lines are real content, not inter-child
341 // whitespace, so write them verbatim — continuation lines minus the
342 // current prefix. (The gap logic below would misread them as
343 // indentation and drop them.)
344 //
345 // "Token" is `no named children`, not `no children at all`. A leaf
346 // like HTML's `raw_text` has none; but Rust's `block_comment` has
347 // two *anonymous* ones, `/*` and `*/`, and so used to fall through
348 // to the gap logic — which read the text before `*/` on the last
349 // line as an indentation prefix and repeated it over every line of
350 // the comment. A node whose children are all anonymous has no
351 // structure to recurse into, so nothing is lost by treating it as
352 // one token. Found by `bin/fuzz`, issue #161.
353 //
354 // A hole *can* hide inside one, though — this comment used to say
355 // otherwise, on the grounds that a hole parses as a named node. It
356 // does only when it stands alone; inside a multi-line string or
357 // comment the token swallows it (issue #221), which is why the rows
358 // below go through [`write_run`] rather than `builder.write`.
359 let all_anonymous =
360 (0..node.child_count()).all(|i| node.child(i).is_some_and(|c| !c.is_named()));
361 if all_anonymous && start.row != end.row {
362 let mut builder = tb(node.kind());
363 let first = &lines[start.row][start.column..];
364 write_run(
365 provider,
366 node,
367 &mut builder,
368 lines,
369 hole_points,
370 holes,
371 prefix,
372 start.row,
373 start.column,
374 start.column + drop_last(first).len(),
375 );
376 let pre = prefix.concat();
377 let rows = lines.iter().enumerate();
378 for (row, line) in rows.take(end.row + 1).skip(start.row + 1) {
379 let c1 = if row == end.row {
380 end.column
381 } else {
382 drop_last(line).len()
383 };
384 // The continuation lines are written minus the current
385 // prefix, so the run starts after it — and a hole's column
386 // is an index into the *whole* line, which is why this is a
387 // column rather than a `strip_prefix` on the slice.
388 //
389 // A line that does *not* carry the prefix — a string
390 // literal's second line written flush left, say — is
391 // content the prefix is not part of, so it must not gain
392 // one on the way out: its newline is written raw, which
393 // the prefix writer leaves alone. `nl` would re-indent it
394 // to the code around the token and change the program's
395 // string.
396 let indented = line[..c1].starts_with(&pre);
397 let c0 = usize::from(indented) * pre.len();
398 if indented {
399 builder.nl();
400 } else {
401 builder.write("\n");
402 }
403 write_run(
404 provider,
405 node,
406 &mut builder,
407 lines,
408 hole_points,
409 holes,
410 prefix,
411 row,
412 c0,
413 c1,
414 );
415 }
416 return builder.build();
417 }
418
419 // Write `lines[row][c0..c1]`, splitting the run at any hole point
420 // that falls inside it.
421 //
422 // `__QUILT_HOLE__` is spelled so it lexes as an ordinary
423 // identifier/word, and hole detection matches a node whose range
424 // *equals* the hole's. That holds only where the hole stands alone:
425 // inside a string, inside a comment, or glued to neighbouring text
426 // (`__QUILT_HOLE__.service` is one word), the token around it
427 // swallows it, no node ever matches, and the point went unconsumed —
428 // surfacing much later, and somewhere else, as "Ran out of holes"
429 // (issue #221).
430 //
431 // Splitting the run is what a dedicated `quilt_hole` token in each
432 // grammar would otherwise have to do — and cannot, since
433 // `tree-sitter generate` panics on that rule (see the forks). It is
434 // also strictly more general: it asks nothing of the grammar, so
435 // every language gets it at once, and the resulting term is the one
436 // you want either way — the hole becomes a child of the token it
437 // sits in, with the text on each side written around it.
438 //
439 // This cannot steal a point from a node that would have matched it
440 // exactly: a run is either a leaf's own text or a gap between
441 // children, traversal is in document order, and an exact match is
442 // consumed at the top of [`f`] before any run is written.
443 #[allow(clippy::too_many_arguments)]
444 fn write_run<P: TSProvider>(
445 provider: &P,
446 node: tree_sitter::Node,
447 builder: &mut QTermBuilder,
448 lines: &[&str],
449 hole_points: &mut Peekable<IntoIter<HolePoint>>,
450 holes: &mut Vec<Hole>,
451 prefix: &[Box<str>],
452 row: usize,
453 c0: usize,
454 c1: usize,
455 ) {
456 let mut col = c0;
457 while let Some(&HolePoint {
458 row: r,
459 start: s,
460 end: e,
461 ..
462 }) = hole_points.peek()
463 {
464 if r != row || s < col || e > c1 {
465 break;
466 }
467 hole_points.next();
468 if s > col {
469 builder.write(&lines[row][col..s]);
470 }
471 holes.push(Hole {
472 // The token the hole sits inside is the closest thing to
473 // a node of its own that it has.
474 otag: node.kind().into(),
475 ikind: Some(provider.hole_kind(node)),
476 prefix: prefix.to_vec().into(),
477 });
478 builder.child(&arc(qsym(provider.hole_str())));
479 col = e;
480 }
481 builder.write(&lines[row][col..c1]);
482 }
483
484 // The padding that aligns a splice at `node` to its column (see
485 // [`TSProvider::align_splices`]): the text between the line's
486 // prefix and the hole, every character but a tab turned into a
487 // space — empty when nothing precedes the hole on its line, where
488 // the line's indent is already its column. The push still marks
489 // the splice as aligned, so host text spliced there is laid out at
490 // that column too (#310). `None` when `node` is not a splice (a
491 // one-line unquote's hole, [`FlatNode::Splice`]), or when another
492 // hole precedes it on its line — that hole's splice has a width
493 // only known when the term is built.
494 fn splice_pad<P: TSProvider>(
495 provider: &P,
496 node: tree_sitter::Node,
497 lines: &[&str],
498 hole_points: &mut Peekable<IntoIter<HolePoint>>,
499 prefix: &[Box<str>],
500 ) -> Option<String> {
501 let (start, end) = (node.start_position(), node.end_position());
502 let at = (start.row, start.column, end.column);
503 if start.row != end.row
504 || !hole_points.peek().is_some_and(|h| h.splice && h.at() == at)
505 {
506 return None;
507 }
508 let before = &lines[start.row][..start.column];
509 let before = before.strip_prefix(&*prefix.concat()).unwrap_or(before);
510 if before.contains(provider.hole_str()) {
511 return None;
512 }
513 Some(
514 before
515 .chars()
516 .map(|c| if c == '\t' { '\t' } else { ' ' })
517 .collect(),
518 )
519 }
520
521 // otherwise, recurse into children
522 #[allow(clippy::too_many_arguments)]
523 fn process<'a, P: TSProvider>(
524 provider: &P,
525 node: tree_sitter::Node,
526 builder: &'a mut QTermBuilder, // TODO: use TupleBuilder
527 depth: &mut i32,
528 lines: &[&str],
529 hole_points: &mut Peekable<IntoIter<HolePoint>>,
530 holes: &mut Vec<Hole>,
531 prefix: &mut Vec<Box<str>>,
532 p0: Point,
533 p1: Point,
534 ) -> &'a mut QTermBuilder {
535 if p0.row == p1.row {
536 write_run(
537 provider,
538 node,
539 builder,
540 lines,
541 hole_points,
542 holes,
543 prefix,
544 p0.row,
545 p0.column,
546 p1.column,
547 );
548 builder
549 } else {
550 // drop the trailing newline
551 builder.write(drop_last(&lines[p0.row][p0.column..]));
552 // TODO: this makes a bunch of assumptions about the language
553 let new_prefix = &lines[p1.row][..p1.column];
554 loop {
555 if let Some(push) = new_prefix.strip_prefix(&prefix.concat()) {
556 if !push.is_empty() {
557 // println!("push: '{push}'");
558 prefix.push(push.into());
559 builder.push(push);
560 *depth += 1;
561 }
562 break;
563 }
564 // println!("pop");
565 prefix.pop();
566 builder.pop();
567 *depth -= 1;
568 }
569 for _ in 0..(p1.row - p0.row) {
570 builder.nl();
571 }
572 builder
573 }
574 }
575
576 let mut builder = tb(node.kind());
577 let mut depth: i32 = 0;
578 let mut point = start;
579 for i in 0..node.child_count() {
580 let child = node.child(i).unwrap();
581 let crange = child.range();
582 process(
583 provider,
584 node,
585 &mut builder,
586 &mut depth,
587 lines,
588 hole_points,
589 holes,
590 prefix,
591 point,
592 crange.start_point,
593 );
594 point = crange.end_point;
595 // A hole that follows text on its line is padded out to its
596 // column for the length of the splice, if the language asks.
597 let pad = provider
598 .align_splices()
599 .then(|| splice_pad(provider, child, lines, hole_points, prefix))
600 .flatten();
601 if let Some(pad) = &pad {
602 builder.push(pad);
603 }
604 builder.child(&arc(f(
605 provider,
606 child,
607 lines,
608 hole_points,
609 holes,
610 prefix,
611 false,
612 )));
613 if pad.is_some() {
614 builder.pop();
615 }
616 }
617 process(
618 provider,
619 node,
620 &mut builder,
621 &mut depth,
622 lines,
623 hole_points,
624 holes,
625 prefix,
626 point,
627 end,
628 );
629 for _ in 0..depth {
630 prefix.pop();
631 builder.pop();
632 }
633 builder.build()
634 }
635
636 let mut hole_points = vec![];
637 let mut row: usize = 0;
638 let mut col: usize = 0;
639
640 let mut lines = vec![String::new()];
641 for c in code {
642 match c {
643 FlatNode::Hole | FlatNode::Splice => {
644 lines.last_mut().unwrap().push_str(self.provider.hole_str());
645 let new_col = lines.last().unwrap().len();
646 hole_points.push(HolePoint {
647 row,
648 start: col,
649 end: new_col,
650 splice: *c == FlatNode::Splice,
651 });
652 col = new_col;
653 }
654 FlatNode::Str(s) => {
655 // A `Str` can carry raw newlines: a multi-line `/* … */`
656 // plain comment reaches here as one node, newlines and all.
657 // `lines` must stay one entry per *physical* line, because
658 // every `Point` tree-sitter hands back below indexes it by
659 // row — an embedded `\n` that did not push a new entry
660 // leaves the two counting differently, and the tree then
661 // addresses rows this vector does not have. Found by
662 // `bin/fuzz` (issue #161): `lines[p1.row]` panicked with an
663 // index out of bounds, and a plain `/* a\nb */` failed to
664 // parse at all.
665 let mut parts = s.split('\n');
666 let first = parts.next().unwrap_or_default();
667 lines.last_mut().unwrap().push_str(first);
668 col += first.len();
669 for part in parts {
670 lines.last_mut().unwrap().push('\n');
671 lines.push(part.to_string());
672 row += 1;
673 col = part.len();
674 }
675 }
676 FlatNode::NewLine => {
677 // Lines must end with a newline character, except possibly the last line.
678 lines.last_mut().unwrap().push('\n');
679 lines.push(String::new());
680 row += 1;
681 col = 0;
682 }
683 }
684 }
685 let lines = lines.iter().map(|s| s.as_ref()).collect::<Box<[_]>>();
686 let tree = ts_parse_lines(self.provider.parser(), &lines)?;
687
688 let mut hole_points = hole_points.into_iter().peekable();
689 let mut holes = vec![];
690 let mut prefix = vec![];
691 let qterm = f(
692 &self.provider,
693 tree.root_node(),
694 &lines,
695 &mut hole_points,
696 &mut holes,
697 &mut prefix,
698 true,
699 );
700 let (qterm, _ikind) = self.provider.unwrap(qterm, ikind)?;
701 let holes = holes.into();
702 let hole_str = self.provider.hole_str();
703
704 Ok(TSLanguagePost {
705 holes,
706 qterm,
707 hole_str,
708 })
709 }
710
711 /// Parse `code` as a *fragment*: inside each of the provider's
712 /// [`fragment_wrappers`](TSProvider::fragment_wrappers) in turn, keeping
713 /// the first whose fragment writes back as `code` did. `None` when none
714 /// does — the caller reports its own error, since the wrappers are an
715 /// implementation detail.
716 pub fn parse_fragment(&mut self, code: &[FlatNode]) -> Option<TSLanguagePost> {
717 let hole_str = self.provider.hole_str();
718 let text = flat_text(code, hole_str);
719 let want = text.trim();
720 if want.is_empty() {
721 return None;
722 }
723 let holes = code.iter().filter(|c| c.is_hole()).count();
724 for w in self.provider.fragment_wrappers() {
725 let mut wrapped = Vec::with_capacity(code.len() + 4);
726 wrapped.push(FlatNode::Str(w.before));
727 wrapped.push(FlatNode::NewLine);
728 wrapped.extend_from_slice(code);
729 wrapped.push(FlatNode::NewLine);
730 wrapped.push(FlatNode::Str(w.after));
731 let Ok(post) = self.parse_plain(None, &wrapped) else {
732 continue;
733 };
734 let Some(qterm) = w.extract(&post.qterm) else {
735 continue;
736 };
737 // Byte-exact, and every hole inside it: nothing of the wrapper is
738 // left, and nothing of the fragment was lost.
739 if qterm.coparse() == want && count_holes(&qterm, hole_str) == holes {
740 return Some(TSLanguagePost {
741 qterm: (*qterm).clone(),
742 ..post
743 });
744 }
745 }
746 None
747 }
748}
749
750impl<P: TSProvider> Language for TSLanguage<P> {
751 type Post = TSLanguagePost;
752
753 /// [`parse_plain`](Self::parse_plain), then — only if that fails — the
754 /// [fragment](Self::parse_fragment) retry, reporting the plain parse's
755 /// error when that fails too.
756 fn parse_pre(&mut self, ikind: Option<InnerKind>, code: &[FlatNode]) -> Result<Self::Post> {
757 match self.parse_plain(ikind, code) {
758 Ok(post) => Ok(post),
759 Err(err) => self.parse_fragment(code).ok_or(err),
760 }
761 }
762
763 fn arity(&self, tag: &str) -> Arity {
764 self.provider.arity(tag)
765 }
766
767 fn separator(&self, tag: &str) -> Option<&'static str> {
768 self.provider.separator(tag)
769 }
770
771 fn typ(&self, tag: &str) -> InnerKind {
772 self.provider.typ(tag)
773 }
774
775 fn classify_term(&self, term: &QTerm) -> InnerKind {
776 self.provider.classify_term(term)
777 }
778
779 fn ident_tag(&self) -> &'static str {
780 self.provider.ident_tag()
781 }
782
783 fn hashbang(&self) -> Option<&'static str> {
784 self.provider.hashbang()
785 }
786
787 fn machine_spec(&self) -> Option<crate::machine::MachineSpec> {
788 self.provider.machine_spec()
789 }
790
791 fn repl_spec(&self) -> Option<crate::machine::ReplSpec> {
792 self.provider.repl_spec()
793 }
794
795 fn native_machine(&self) -> Option<Box<dyn crate::machine::Machine>> {
796 self.provider.native_machine()
797 }
798}
799
800impl LanguagePost for TSLanguagePost {
801 fn holes(&self) -> &[Hole] {
802 &self.holes
803 }
804
805 fn parse_post(&self, plugs: &[Arc<QTerm>]) -> Result<Arc<QTerm>> {
806 // fill the holes with plugs
807 fn fill<'a>(
808 qterm: &QTerm,
809 plugs: &mut impl Iterator<Item = &'a Arc<QTerm>>,
810 hole_str: &str,
811 ) -> Arc<QTerm> {
812 match qterm {
813 QTerm::Quote {
814 tag,
815 index,
816 lang,
817 term,
818 cmds,
819 span,
820 repr,
821 } => arc(crate::qterm::qquote_repr_at(
822 tag,
823 *index,
824 lang,
825 fill(term, plugs, hole_str),
826 cmds,
827 span.clone(),
828 *repr,
829 )),
830 QTerm::Unquote {
831 tag,
832 index,
833 lang,
834 term,
835 cmds,
836 span,
837 } => arc(crate::qterm::qunquote_at(
838 tag,
839 *index,
840 lang,
841 fill(term, plugs, hole_str),
842 cmds,
843 span.clone(),
844 )),
845 QTerm::Tuple { tag, terms, cmds } => {
846 if &**tag == hole_str {
847 return plugs.next().unwrap().clone();
848 }
849 tuple(
850 tag,
851 &terms
852 .iter()
853 .map(|t| fill(t, plugs, hole_str))
854 .collect::<Vec<_>>(),
855 cmds,
856 )
857 }
858 }
859 }
860
861 assert_eq!(plugs.len(), self.holes.len());
862 Ok(fill(&self.qterm, &mut plugs.iter(), self.hole_str))
863 }
864}
865
866/**************************************************************/
867
868#[derive(Default)]
869pub struct DynTSLanguage<P: TSProvider>(TSLanguage<P>);
870
871impl<P: TSProvider> Language for DynTSLanguage<P> {
872 type Post = Box<dyn LanguagePost>;
873
874 fn parse_pre(&mut self, ikind: Option<InnerKind>, code: &[FlatNode]) -> Result<Self::Post> {
875 Ok(bx(self.0.parse_pre(ikind, code)?) as Self::Post)
876 }
877
878 fn arity(&self, tag: &str) -> Arity {
879 self.0.arity(tag)
880 }
881
882 fn separator(&self, tag: &str) -> Option<&'static str> {
883 self.0.separator(tag)
884 }
885
886 fn typ(&self, tag: &str) -> InnerKind {
887 self.0.typ(tag)
888 }
889
890 fn classify_term(&self, term: &QTerm) -> InnerKind {
891 self.0.classify_term(term)
892 }
893
894 fn ident_tag(&self) -> &'static str {
895 self.0.ident_tag()
896 }
897
898 fn hashbang(&self) -> Option<&'static str> {
899 self.0.hashbang()
900 }
901
902 fn machine_spec(&self) -> Option<crate::machine::MachineSpec> {
903 self.0.machine_spec()
904 }
905
906 fn repl_spec(&self) -> Option<crate::machine::ReplSpec> {
907 self.0.repl_spec()
908 }
909
910 fn native_machine(&self) -> Option<Box<dyn crate::machine::Machine>> {
911 self.0.native_machine()
912 }
913}
914
915impl<T: LanguagePost> LanguagePost for Box<T> {
916 fn holes(&self) -> &[Hole] {
917 self.as_ref().holes()
918 }
919
920 fn parse_post(&self, plugs: &[Arc<QTerm>]) -> Result<Arc<QTerm>> {
921 self.as_ref().parse_post(plugs)
922 }
923}
924
925/**************************************************************/
926
927#[cfg(test)]
928mod tests {
929 use super::*;
930 use crate::langs::rust::lang::RustProvider;
931
932 /// Parse a string of code into a tree-sitter tree.
933 fn ts_parse(parser: &mut Parser, code: &str) -> Result<Tree> {
934 let Some(tree) = parser.parse(code, None) else {
935 bail!("Failed to parse: {code}");
936 };
937 if tree.root_node().has_error() {
938 bail!("Parsed with errors: {code}")
939 }
940 Ok(tree)
941 }
942
943 #[test]
944 fn test_ts_parse_lines() -> Result<()> {
945 let lines = [
946 "fn foo() {\n",
947 " println!(\"Hello\");\n",
948 " println!(\"World\");\n",
949 "}",
950 ];
951 let mut provider = RustProvider::default();
952 let parser = provider.parser();
953
954 let code = lines.join("");
955 let tree_1 = ts_parse(parser, &code)?;
956 let tree_2 = ts_parse(parser, &code)?;
957 assert_eq!(tree_1.root_node().to_sexp(), tree_2.root_node().to_sexp());
958 Ok(())
959 }
960
961 #[test]
962 fn test_ts_parse_lines_empty() -> Result<()> {
963 let lines: [&'static str; 0] = [];
964 let mut provider = RustProvider::default();
965 let parser = provider.parser();
966
967 let code = lines.join("");
968 let tree_1 = ts_parse(parser, &code)?;
969 let tree_2 = ts_parse(parser, &code)?;
970 assert_eq!(tree_1.root_node().to_sexp(), tree_2.root_node().to_sexp());
971 Ok(())
972 }
973}