quilt/langs/sql/lang.rs
1//! The SQL target language.
2//!
3//! SQL is only ever a *quoted* language (e.g. `sql↖ … ↗` inside Rust): Quilt
4//! parses SQL fragments into a `QTerm` and the host language's `MetaLanguage`
5//! (Rust's) drives expansion. There is therefore no `SqlMetaLanguage` — only
6//! this `Language` impl, built on the shared tree-sitter helper.
7//!
8//! The point of quoting SQL rather than concatenating strings is that a value
9//! spliced with `↑` becomes a *literal node*, not text: `LiftTo<Sql> for str`
10//! (see [`crate::lift`]) builds a `literal` whose spelling is a standard SQL
11//! string with every `'` doubled, so a value can never close the literal and
12//! continue the statement. The conformance battery reparses every lifted
13//! literal in this grammar, which is what keeps that claim honest (#219).
14//!
15//! Two shapes of fragment are accepted, mirroring how the grammar is layered:
16//!
17//! * A **statement** — `sql↖SELECT * FROM t WHERE id = ↙id.↑↘↗` — parses on its
18//! own, since `program` is a repeat of statements.
19//! * A bare **expression** — `sql↖id = ↙id.↑↘↗`, the shape a composable
20//! predicate takes — does not: `program` holds statements, so a lone
21//! expression is a parse error. [`SqlLanguage`] retries such a fragment
22//! inside [`SELECT_PREFIX`] and strips the wrapper back off, the same
23//! technique `langs::lean::lang` uses with `#check …`.
24//!
25//! The same wrapper serves a hole standing where a whole *statement* goes
26//! (`↙stmt↘;` on its own line), which a bare identifier cannot occupy either —
27//! see [`statement_hole_ordinals`] (#234).
28
29use crate::{
30 lang::{Arity, Comments, FlatNode, InnerKind, Language, LanguagePost},
31 prelude::*,
32 qterm::QTerm,
33 term::CmdOrHole,
34 treesitter::{TSLanguage, TSLanguagePost, TSProvider},
35};
36use miette::{bail, Result};
37use tree_sitter::Parser;
38
39/**************************************************************/
40
41pub struct SqlProvider(tree_sitter::Parser);
42
43impl Default for SqlProvider {
44 fn default() -> Self {
45 let mut parser = Parser::new();
46 parser
47 .set_language(&crate::grammars::sql::LANGUAGE.into())
48 .expect("Error loading SQL parser");
49 Self(parser)
50 }
51}
52
53impl TSProvider for SqlProvider {
54 fn parser(&mut self) -> &mut tree_sitter::Parser {
55 &mut self.0
56 }
57
58 /// The machine for SQL is a database connection: a live `sqlite3` whose
59 /// temp tables and attached state are its definitions — which makes SQL
60 /// the first *target-only* language with a machine
61 /// (docs/design/machines.md). A query is any SQL expression (spelled
62 /// through `SELECT …;`), the typing judgment is sqlite's `typeof`, and
63 /// `-bail` keeps the contract that a rejected feed is an `Err` rather
64 /// than a silently-logged diagnostic. The sentinel is a `SELECT` of a
65 /// string literal, which prints as its own line.
66 /// Registered in `machine::repl_spec`; see `PythonProvider::machine_spec`.
67 fn repl_spec(&self) -> Option<crate::machine::ReplSpec> {
68 crate::machine::repl_spec("sql")
69 }
70
71 fn hole_str(&self) -> &'static str {
72 // `__QUILT_HOLE__` matches this grammar's `_identifier` regex
73 // (`/[A-Za-z_À-ſ][0-9A-Za-z_À-ſ]*/`), so it parses
74 // as an `identifier` wherever one may appear — predicate operand,
75 // select expression, relation name, `IN` list element — with **no
76 // grammar patch at all**, the same free ride nix and lean get. The
77 // range-based hole detection in `treesitter.rs` then recognises it by
78 // its byte range. `test/corpus/quilt.txt` in the fork pins those four
79 // positions.
80 //
81 // The one position this does *not* reach unaided is a bare hole as a
82 // whole statement (`SELECT 1; ↙stmt↘; SELECT 2;`): no SQL statement
83 // starts with a bare identifier, so that is a parse error. That case is
84 // handled a level up, by the `SELECT …` wrapper retry in
85 // `SqlLanguage::parse_pre` — see `statement_hole_ordinals` (#234).
86 "__QUILT_HOLE__"
87 }
88
89 fn hashbang(&self) -> Option<&'static str> {
90 // SQL is executed by a database, not by an interpreter reading a
91 // shebang, and `#!` is not comment syntax in SQL.
92 None
93 }
94
95 /// Derived from the grammar's `REPEAT` rules by `bin/gen-arity`, not
96 /// hand-curated — see `quilt/src/langs/arity.rs` (#202).
97 fn arity(&self, tag: &str) -> Arity {
98 Arity::from_table(crate::langs::arity::SQL, tag)
99 }
100
101 /// `,` for the kinds `bin/gen-arity` finds comma-separated (#293).
102 fn separator(&self, tag: &str) -> Option<&'static str> {
103 crate::lang::comma_separator(crate::langs::arity::SQL_COMMA_SEPARATED, tag)
104 }
105
106 /// SQL is layered `program` → statement → clause → expression, so the tag
107 /// alone answers this: the three things `program`'s repeat holds are
108 /// statement-like, everything else is a value or a part of one.
109 fn typ(&self, tag: &str) -> InnerKind {
110 match tag {
111 "program" => InnerKind::File,
112 // The `choice` inside `program`'s repeat: a plain statement, a
113 // `BEGIN … COMMIT` transaction, or a T-SQL `BEGIN … END` block.
114 "statement" | "transaction" | "block" => InnerKind::Stmt,
115 // Clauses (`select`, `from`, `where`, …) and operands alike. SQL
116 // has no kind between "statement" and "value", and clauses are
117 // spliced the same way operands are.
118 _ => InnerKind::Expr,
119 }
120 }
121
122 /// Squash the `program` wrapper around a single quoted fragment so the term
123 /// is the fragment itself. A fragment with several statements (or one with
124 /// its terminating `;`) stays a `program`, since dropping the wrapper would
125 /// lose the separators.
126 fn unwrap(&self, qterm: QTerm, ikind: Option<InnerKind>) -> Result<(QTerm, InnerKind)> {
127 let QTerm::Tuple { tag, terms, .. } = &qterm else {
128 return Ok((qterm, InnerKind::default()));
129 };
130 if &**tag != "program" {
131 return Ok((qterm, InnerKind::default()));
132 }
133 if terms.len() != 1 {
134 // Empty, several statements, or a statement plus its trailing `;`.
135 // `classify_term` recognises the last of those as a `Stmt`.
136 let kind = self.classify_term(&qterm);
137 return Ok((qterm, kind));
138 }
139 let kind = self.classify_term(&terms[0]);
140 Ok((qterm.squash(), ikind.unwrap_or(kind)))
141 }
142
143 /// Classify a fully-parsed SQL term as expression / statement / file.
144 ///
145 /// Needed (rather than plain [`typ`](TSProvider::typ)) because a
146 /// single-statement fragment arrives wrapped in `program` — and, when it
147 /// keeps its terminating `;`, wrapped in a *two*-child `program` whose root
148 /// tag alone would read `File` for what is really one statement.
149 ///
150 /// One more override: a *parenthesized* select at statement level — the
151 /// grammar's `statement("(", select, ")")` — classifies as
152 /// [`Expr`](InnerKind::Expr). Parentheses are exactly how SQL marks "the
153 /// value of this query" (a scalar subquery), and machine-eval routing
154 /// rides classification: `db.↓(…)` on a parenthesized query must
155 /// *answer* it, not feed it as an effect.
156 fn classify_term(&self, term: &QTerm) -> InnerKind {
157 match term {
158 QTerm::Tuple { tag, terms, .. } if &**tag == "program" => match terms.len() {
159 1 => self.classify_term(&terms[0]),
160 // A single statement plus its trailing `;`: still a `Stmt`.
161 2 if is_semi(&terms[1]) => self.classify_term(&terms[0]),
162 // Empty (0) or several statements (3+): a whole script.
163 _ => InnerKind::File,
164 },
165 // Only the opener is checked: with a splice hole in the body the
166 // parser can hang the closing `)` off the inner `select` instead
167 // of the `statement`, so requiring the 3-child shape would read
168 // the same source two ways depending on whether it was spliced.
169 QTerm::Tuple { tag, terms, .. }
170 if &**tag == "statement"
171 && matches!(
172 terms.first().map(AsRef::as_ref),
173 Some(QTerm::Tuple { tag, .. }) if &**tag == "("
174 ) =>
175 {
176 InnerKind::Expr
177 }
178 QTerm::Tuple { tag, .. } => self.typ(tag),
179 _ => InnerKind::default(),
180 }
181 }
182}
183
184/// Is this term the anonymous `;` statement terminator?
185fn is_semi(term: &QTerm) -> bool {
186 matches!(term, QTerm::Tuple { tag, terms, .. } if &**tag == ";" && terms.is_empty())
187}
188
189/**************************************************************/
190
191/// The synthetic statement a bare *expression* fragment is parsed inside.
192///
193/// SQL's `program` holds **statements**, so `sql↖id = 1↗` is a parse error on
194/// its own — unlike Rust or Python, whose `source_file` accepts a bare
195/// expression. Since expression-level composition is much of the point of
196/// quoting (`sql↖SELECT * FROM t WHERE ↙pred↘↗`), [`SqlLanguage`] retries a
197/// failed parse inside `SELECT …`, the smallest SQL statement that takes an
198/// arbitrary expression, and then strips the wrapper back off. See
199/// [`strip_select`].
200const SELECT_PREFIX: &str = "SELECT ";
201
202/// Undo the [`SELECT_PREFIX`] wrapper: given the parsed statement, return just
203/// the expression it wrapped.
204///
205/// The input is what [`SqlProvider::unwrap`] hands back, so the `program` root
206/// has already been squashed away and this starts at the `statement`. The rest
207/// of the chain is fixed by the grammar — `statement` → `select` →
208/// `select_expression` → `term` → the expression — and every link is checked
209/// here rather than assumed, because the retry can succeed on input that is not
210/// a lone expression at all (`SELECT a, b` gives a two-`term`
211/// `select_expression`; `SELECT 1; DROP TABLE t` leaves the multi-statement
212/// `program` unsquashed). Anything but the exact single-expression shape is
213/// refused, and the caller then reports the *original* parse error.
214fn strip_select(qterm: &QTerm) -> Result<Arc<QTerm>> {
215 /// The single child of a tuple with the expected tag, or an error.
216 fn only_child<'a>(term: &'a QTerm, want: &str) -> Result<&'a Arc<QTerm>> {
217 let QTerm::Tuple { tag, terms, .. } = term else {
218 bail!("sql: expected a {want:?} tuple after wrapping, got a quote/unquote");
219 };
220 if &**tag != want || terms.len() != 1 {
221 bail!("sql: expected a 1-child {want:?} tuple after wrapping, got {tag:?}");
222 }
223 Ok(&terms[0])
224 }
225
226 let select = only_child(qterm, "statement")?;
227 // `select` is `seq(keyword_select, optional(keyword_distinct),
228 // select_expression)`, so an un-aliased one has exactly two children.
229 let QTerm::Tuple { tag, terms, cmds } = &**select else {
230 bail!("sql: expected a `select` tuple after wrapping, got a quote/unquote");
231 };
232 if &**tag != "select" || terms.len() != 2 {
233 bail!("sql: expected a 2-child `select` tuple after wrapping, got {tag:?}");
234 }
235 // Nothing may follow the select expression, or dropping the wrapper would
236 // lose text.
237 let last_hole = cmds
238 .iter()
239 .rposition(|c| matches!(c, CmdOrHole::Hole))
240 .expect("select tuple has children");
241 if cmds[last_hole + 1..]
242 .iter()
243 .any(|c| !matches!(c, CmdOrHole::Cmd(StrCmd::Write(s)) if s.is_empty()))
244 {
245 bail!("sql: unexpected trailing text after the `SELECT` wrapper's expression");
246 }
247 // Peel the two wrapper layers, `select_expression` then `term`.
248 //
249 // Either can be *absent*, and that is not a failure. `select_expression`,
250 // `term` and the expression beneath them span exactly the same bytes when
251 // the fragment is a lone hole (`sql↖↙v↘↗`), and `build_nodes` replaces the
252 // outermost node whose range matches the hole — so the layers are simply
253 // not in the tree. A layer that *is* present must hold exactly one child:
254 // `SELECT a, b` gives `select_expression` two `term`s and `SELECT x AS y`
255 // gives `term` an alias sibling, and neither is a lone expression.
256 let mut inner = terms[1].clone();
257 for layer in ["select_expression", "term"] {
258 let QTerm::Tuple { tag, terms, .. } = &*inner else {
259 bail!("sql: expected a tuple inside the `SELECT` wrapper, got a quote/unquote");
260 };
261 if &**tag != layer {
262 break;
263 }
264 if terms.len() != 1 {
265 bail!("sql: the `SELECT` wrapper holds a {layer:?} with {} children, not a lone expression", terms.len());
266 }
267 let next = terms[0].clone();
268 inner = next;
269 }
270 Ok(inner)
271}
272
273/// Ordinals (into the fragment's hole sequence) of holes that stand where a
274/// whole **statement** goes:
275///
276/// ```text
277/// SELECT 1;
278/// ↙stmt↘;
279/// SELECT 2;
280/// ```
281///
282/// `program` is `repeat(seq(choice(statement, transaction, block), ';'))` and no
283/// SQL statement begins with a bare identifier, so such a hole is a parse error
284/// on its own. Wrapping just these holes in [`SELECT_PREFIX`] makes them
285/// statements; [`strip_wrapped_selects`] removes the wrapper again.
286///
287/// A hole qualifies when nothing but whitespace precedes it on its line and
288/// nothing but whitespace and **at most one `;`** follows it. The `;` is the
289/// difference from the Lean version this is modelled on
290/// (`langs::lean::lang::line_hole_ordinals`): SQL statements are terminated, so
291/// the natural spelling puts the separator right after the hole. Allowing the
292/// bare form too covers the trailing statement `program` lets go unterminated.
293///
294/// Deliberately line-based rather than `;`-scanning: a `;` inside a string
295/// literal is ordinary text in the flat node stream, and a scanner that split on
296/// it would wrap holes that are not in statement position at all. Anything this
297/// declines simply falls back to the original parse error.
298fn statement_hole_ordinals(code: &[FlatNode]) -> Vec<usize> {
299 /// The text on one side of a hole, up to the nearest line break — or `None`
300 /// if another hole intervenes, which means this one is not alone.
301 fn text_run<'a>(nodes: impl Iterator<Item = &'a FlatNode<'a>>) -> Option<String> {
302 let mut out = String::new();
303 for node in nodes {
304 match node {
305 FlatNode::NewLine => break,
306 FlatNode::Str(s) => out.push_str(s),
307 FlatNode::Hole | FlatNode::Splice => return None,
308 }
309 }
310 Some(out)
311 }
312
313 let mut out = Vec::new();
314 for (i, node) in code.iter().enumerate() {
315 if !node.is_hole() {
316 continue;
317 }
318 let ordinal = code[..i].iter().filter(|n| n.is_hole()).count();
319 let before = text_run(code[..i].iter().rev());
320 let after = text_run(code[i + 1..].iter());
321 let alone = matches!(before, Some(ref b) if b.trim().is_empty())
322 && matches!(after, Some(ref a) if matches!(a.trim(), "" | ";"));
323 if alone {
324 out.push(ordinal);
325 }
326 }
327 out
328}
329
330/// Rebuild `code` with [`SELECT_PREFIX`] inserted before each hole whose ordinal
331/// is in `targets`.
332fn wrap_statement_holes<'a>(code: &[FlatNode<'a>], targets: &[usize]) -> Vec<FlatNode<'a>> {
333 let mut out = Vec::with_capacity(code.len() + targets.len());
334 let mut ordinal = 0usize;
335 for node in code {
336 if node.is_hole() {
337 if targets.contains(&ordinal) {
338 out.push(FlatNode::Str(SELECT_PREFIX));
339 }
340 ordinal += 1;
341 }
342 out.push(node.clone());
343 }
344 out
345}
346
347/// Undo [`wrap_statement_holes`] in the parsed tree: replace each `statement`
348/// that wraps one of the holes we wrapped with that hole itself.
349///
350/// Only the wrappers *we* introduced are removed — holes are counted in tree
351/// order and matched against `targets` — so a genuine `SELECT ↙col↘` written by
352/// the author survives untouched.
353///
354/// The shape searched for is `statement(select(keyword_select, <hole>))`: the
355/// hole spans the same bytes as the `select_expression`, `term` and `field` that
356/// would otherwise sit between, and `build_nodes` replaces the outermost node
357/// whose range matches, so those layers are not in the tree. That is the same
358/// collapse [`strip_select`] peels through.
359///
360/// Returns the rewritten term and **how many wrappers were removed**. The caller
361/// requires that to equal `targets.len()` and discards the retry otherwise: a
362/// target that did not come back in the expected shape means the prefix landed
363/// somewhere other than statement position — inside a string literal, say — and
364/// keeping such a tree would silently splice a stray `SELECT` into the output.
365/// Failing there costs only the original parse error, which is what the user
366/// would have seen anyway.
367fn strip_wrapped_selects(
368 term: &Arc<QTerm>,
369 hole_str: &str,
370 targets: &[usize],
371) -> (Arc<QTerm>, usize) {
372 /// Is this the `statement(select(keyword_select, <hole>))` we introduced?
373 fn wrapped_hole<'a>(terms: &'a [Arc<QTerm>], hole_str: &str) -> Option<&'a Arc<QTerm>> {
374 let [only] = terms else { return None };
375 let QTerm::Tuple {
376 tag: sel,
377 terms: sel_terms,
378 ..
379 } = &**only
380 else {
381 return None;
382 };
383 if &**sel != "select" {
384 return None;
385 }
386 let [_keyword, hole] = &sel_terms[..] else {
387 return None;
388 };
389 matches!(&**hole, QTerm::Tuple { tag, .. } if &**tag == hole_str).then_some(hole)
390 }
391
392 fn walk(
393 term: &Arc<QTerm>,
394 hole_str: &str,
395 targets: &[usize],
396 ordinal: &mut usize,
397 stripped: &mut usize,
398 ) -> Arc<QTerm> {
399 let QTerm::Tuple { tag, terms, cmds } = &**term else {
400 // Quotes/unquotes cannot appear inside a freshly parsed fragment.
401 return term.clone();
402 };
403
404 if &**tag == "statement" {
405 if let Some(hole) = wrapped_hole(terms, hole_str) {
406 if targets.contains(ordinal) {
407 *ordinal += 1;
408 *stripped += 1;
409 return hole.clone();
410 }
411 }
412 }
413
414 if &**tag == hole_str {
415 *ordinal += 1;
416 return term.clone();
417 }
418
419 let children: Vec<Arc<QTerm>> = terms
420 .iter()
421 .map(|t| walk(t, hole_str, targets, ordinal, stripped))
422 .collect();
423 tuple(tag, &children, cmds)
424 }
425
426 let mut ordinal = 0usize;
427 let mut stripped = 0usize;
428 let out = walk(term, hole_str, targets, &mut ordinal, &mut stripped);
429 (out, stripped)
430}
431
432/// The SQL `Language`: [`TSLanguage<SqlProvider>`] plus the bare-expression
433/// retry described on [`SELECT_PREFIX`], and the statement-position hole
434/// wrapper described on [`statement_hole_ordinals`].
435#[derive(Default)]
436pub struct SqlLanguage(TSLanguage<SqlProvider>);
437
438impl Comments for SqlLanguage {
439 /// `--` is the one line comment every dialect agrees on; `#` is a `MySQL`
440 /// extension, and this one spelling has to serve `sql`, `mysql` and
441 /// `mariadb` alike.
442 const LINE: Option<&'static str> = Some("--");
443}
444
445impl Language for SqlLanguage {
446 type Post = TSLanguagePost;
447
448 fn parse_pre(&mut self, ikind: Option<InnerKind>, code: &[FlatNode]) -> Result<Self::Post> {
449 // A statement fragment (and a whole script) parses on its own; only a
450 // bare expression needs the wrapper, so try plain first and keep this a
451 // no-op for everything else.
452 let err = match self.0.parse_pre(ikind, code) {
453 Ok(post) => return Ok(post),
454 Err(e) => e,
455 };
456
457 let mut wrapped = Vec::with_capacity(code.len() + 1);
458 wrapped.push(FlatNode::Str(SELECT_PREFIX));
459 wrapped.extend_from_slice(code);
460
461 // Report the *original* error whenever the retry doesn't yield a clean
462 // single-expression `SELECT` — the wrapper is an implementation detail,
463 // and naming it would only mislead.
464 if let Some(post) = self
465 .0
466 .parse_pre(Some(InnerKind::Expr), &wrapped)
467 .ok()
468 .and_then(|post| {
469 let qterm = strip_select(&post.qterm).ok()?;
470 Some(TSLanguagePost {
471 qterm: (*qterm).clone(),
472 ..post
473 })
474 })
475 {
476 return Ok(post);
477 }
478
479 // Last resort: holes at *statement* position, which a bare identifier
480 // cannot occupy. Wrap only those holes and strip the wrappers back out
481 // of the tree, leaving every other hole alone.
482 let targets = statement_hole_ordinals(code);
483 if !targets.is_empty() {
484 let wrapped = wrap_statement_holes(code, &targets);
485 if let Some(post) = self.0.parse_pre(ikind, &wrapped).ok().and_then(|post| {
486 let hole_str = post.hole_str;
487 let (qterm, stripped) =
488 strip_wrapped_selects(&arc(post.qterm.clone()), hole_str, &targets);
489 // Every wrapper we added must have come back out; see
490 // `strip_wrapped_selects`.
491 if stripped != targets.len() {
492 return None;
493 }
494 // The wrapped holes were measured against the *wrapper*'s
495 // position, so they came back `Expr` (a select expression).
496 // What can actually fill them is a statement — the same answer
497 // `langs::lean::lang::hole_kind` gives a hole in a `by`/`do`
498 // body, and what `multi.rs` threads into the host parse of the
499 // unquote body.
500 let mut holes = post.holes.into_vec();
501 for &t in &targets {
502 if let Some(hole) = holes.get_mut(t) {
503 hole.ikind = Some(InnerKind::Stmt);
504 }
505 }
506 Some(TSLanguagePost {
507 qterm: (*qterm).clone(),
508 holes: holes.into_boxed_slice(),
509 hole_str,
510 })
511 }) {
512 return Ok(post);
513 }
514 }
515
516 Err(err)
517 }
518
519 fn arity(&self, tag: &str) -> Arity {
520 self.0.arity(tag)
521 }
522
523 fn separator(&self, tag: &str) -> Option<&'static str> {
524 self.0.separator(tag)
525 }
526
527 fn typ(&self, tag: &str) -> InnerKind {
528 self.0.typ(tag)
529 }
530
531 fn classify_term(&self, term: &QTerm) -> InnerKind {
532 self.0.classify_term(term)
533 }
534
535 fn hashbang(&self) -> Option<&'static str> {
536 self.0.hashbang()
537 }
538
539 fn machine_spec(&self) -> Option<crate::machine::MachineSpec> {
540 self.0.machine_spec()
541 }
542
543 fn repl_spec(&self) -> Option<crate::machine::ReplSpec> {
544 self.0.repl_spec()
545 }
546}
547
548/// Boxed-`Post` form of [`SqlLanguage`], for the dynamic registry.
549#[derive(Default)]
550pub struct DynSqlLanguage(SqlLanguage);
551
552impl Language for DynSqlLanguage {
553 type Post = Box<dyn LanguagePost>;
554
555 fn parse_pre(&mut self, ikind: Option<InnerKind>, code: &[FlatNode]) -> Result<Self::Post> {
556 Ok(bx(self.0.parse_pre(ikind, code)?) as Self::Post)
557 }
558
559 fn arity(&self, tag: &str) -> Arity {
560 self.0.arity(tag)
561 }
562
563 fn separator(&self, tag: &str) -> Option<&'static str> {
564 self.0.separator(tag)
565 }
566
567 fn typ(&self, tag: &str) -> InnerKind {
568 self.0.typ(tag)
569 }
570
571 fn classify_term(&self, term: &QTerm) -> InnerKind {
572 self.0.classify_term(term)
573 }
574
575 fn hashbang(&self) -> Option<&'static str> {
576 self.0.hashbang()
577 }
578
579 fn machine_spec(&self) -> Option<crate::machine::MachineSpec> {
580 self.0.machine_spec()
581 }
582
583 fn repl_spec(&self) -> Option<crate::machine::ReplSpec> {
584 self.0.repl_spec()
585 }
586}