Skip to main content

inillucent_sql/
ast.rs

1//! The arena-backed abstract syntax tree.
2//!
3//! Invariant: a node is an index into an arena, never a box, so an adversarial
4//! nesting depth costs one vector push per node and a walker can be iterative.
5//! Every node carries the span it was parsed from, and no node has been
6//! normalised: `NOT IN`, `IS NOT DISTINCT FROM` and an implicit alias are all
7//! distinct nodes rather than reconstructions, because a diagnostic that has to
8//! guess what the user wrote points at the wrong place.
9//!
10//! Identifiers are interned once per parse. The interned form keeps the
11//! original spelling *and* an ASCII-folded lookup key, because SQL name
12//! resolution is case-insensitive while `sqlite_schema` records the spelling
13//! the user chose.
14
15use crate::lexer::{QuoteForm, Span};
16
17/// An identifier, interned per parse.
18#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
19pub struct NameId(pub u32);
20
21/// An expression node.
22#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
23pub struct ExprId(pub u32);
24
25/// A compound SELECT.
26#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
27pub struct SelectId(pub u32);
28
29/// One arm of a compound SELECT.
30#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
31pub struct SelectCoreId(pub u32);
32
33/// A FROM term.
34#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
35pub struct FromTermId(pub u32);
36
37/// A window definition.
38#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
39pub struct WindowId(pub u32);
40
41/// An interned identifier: what was written and what it matches.
42#[derive(Clone, Debug, PartialEq, Eq)]
43pub struct Name {
44    /// The identifier exactly as written, with quoting removed.
45    pub text: Vec<u8>,
46    /// The ASCII-folded key names are compared by.
47    pub folded: Vec<u8>,
48    /// How it was quoted, which decides whether it may become a string.
49    pub quote: QuoteForm,
50    /// Where it came from.
51    pub span: Span,
52}
53
54impl Name {
55    /// Returns the written spelling as text, for diagnostics and schema SQL.
56    pub fn as_str(&self) -> &str {
57        core::str::from_utf8(&self.text).unwrap_or("")
58    }
59}
60
61/// A literal value, kept as the bytes it was written as.
62#[derive(Clone, Debug, PartialEq, Eq)]
63pub enum Literal {
64    /// `NULL`.
65    Null,
66    /// `TRUE` or `FALSE`, which SQLite treats as 1 and 0.
67    Boolean(bool),
68    /// An integer literal, as written.
69    Integer(Vec<u8>),
70    /// A floating-point literal, as written.
71    Float(Vec<u8>),
72    /// A string literal, unescaped.
73    String(Vec<u8>),
74    /// A blob literal, decoded.
75    Blob(Vec<u8>),
76    /// `CURRENT_DATE`, `CURRENT_TIME` or `CURRENT_TIMESTAMP`.
77    CurrentDate,
78    /// `CURRENT_TIME`.
79    CurrentTime,
80    /// `CURRENT_TIMESTAMP`.
81    CurrentTimestamp,
82}
83
84/// A unary operator.
85#[derive(Clone, Copy, Debug, PartialEq, Eq)]
86pub enum UnaryOp {
87    /// `-x`
88    Negate,
89    /// `+x`, which SQLite keeps as a no-op that still forces evaluation.
90    Identity,
91    /// `~x`
92    BitNot,
93    /// `NOT x`
94    Not,
95}
96
97/// A binary operator.
98#[derive(Clone, Copy, Debug, PartialEq, Eq)]
99pub enum BinaryOp {
100    /// `OR`
101    Or,
102    /// `AND`
103    And,
104    /// `=`
105    Equal,
106    /// `<>`
107    NotEqual,
108    /// `<`
109    Less,
110    /// `<=`
111    LessEqual,
112    /// `>`
113    Greater,
114    /// `>=`
115    GreaterEqual,
116    /// `+`
117    Add,
118    /// `-`
119    Subtract,
120    /// `*`
121    Multiply,
122    /// `/`
123    Divide,
124    /// `%`
125    Modulo,
126    /// `||`
127    Concat,
128    /// `&`
129    BitAnd,
130    /// `|`
131    BitOr,
132    /// `<<`
133    ShiftLeft,
134    /// `>>`
135    ShiftRight,
136    /// `->`
137    Extract,
138    /// `->>`
139    ExtractText,
140    /// `MATCH`
141    Match,
142    /// `REGEXP`
143    Regexp,
144    /// `<->`
145    L2Distance,
146    /// `<=>`
147    CosineDistance,
148    /// `<#>`
149    NegativeInnerProduct,
150    /// `<+>`
151    L1Distance,
152    /// `<~>`
153    HammingDistance,
154    /// `<%>`
155    JaccardDistance,
156}
157
158/// Which pattern operator was written.
159#[derive(Clone, Copy, Debug, PartialEq, Eq)]
160pub enum PatternOp {
161    /// `LIKE`
162    Like,
163    /// `GLOB`
164    Glob,
165    /// `REGEXP`
166    Regexp,
167    /// `MATCH`
168    Match,
169}
170
171/// The right-hand side of `IN`.
172#[derive(Clone, Debug, PartialEq, Eq)]
173pub enum InRhs {
174    /// `IN (1, 2, 3)`, including the empty list.
175    List(Vec<ExprId>),
176    /// `IN (SELECT ...)`.
177    Select(SelectId),
178    /// `IN table` or `IN schema.table`.
179    Table {
180        /// The schema qualifier, when written.
181        database: Option<NameId>,
182        /// The table or table-valued function name.
183        table: NameId,
184        /// Arguments, when the name is a table-valued function.
185        arguments: Option<Vec<ExprId>>,
186    },
187}
188
189/// A `RAISE()` action inside a trigger body.
190#[derive(Clone, Copy, Debug, PartialEq, Eq)]
191pub enum RaiseAction {
192    /// `RAISE(IGNORE)`
193    Ignore,
194    /// `RAISE(ROLLBACK, msg)`
195    Rollback,
196    /// `RAISE(ABORT, msg)`
197    Abort,
198    /// `RAISE(FAIL, msg)`
199    Fail,
200}
201
202/// An expression, in the shape it was written.
203#[derive(Clone, Debug, PartialEq, Eq)]
204pub enum Expr {
205    /// A literal.
206    Literal(Literal),
207    /// A bound parameter.
208    Parameter {
209        /// The one-based parameter index assigned at parse time.
210        index: u32,
211        /// The written name, for `:name` style parameters.
212        name: Option<NameId>,
213    },
214    /// A column reference, with as much qualification as was written.
215    Column {
216        /// The schema qualifier.
217        database: Option<NameId>,
218        /// The table qualifier or alias.
219        table: Option<NameId>,
220        /// The column name.
221        column: NameId,
222    },
223    /// `*` or `table.*`, legal only where the grammar allows it.
224    Star {
225        /// The table qualifier, when written.
226        table: Option<NameId>,
227    },
228    /// A unary operator applied to one operand.
229    Unary {
230        /// Which operator.
231        op: UnaryOp,
232        /// The operand.
233        operand: ExprId,
234    },
235    /// A binary operator applied to two operands.
236    Binary {
237        /// Which operator.
238        op: BinaryOp,
239        /// The left operand.
240        left: ExprId,
241        /// The right operand.
242        right: ExprId,
243    },
244    /// `expr COLLATE name`.
245    Collate {
246        /// The operand.
247        operand: ExprId,
248        /// The collation name.
249        collation: NameId,
250    },
251    /// `CAST(expr AS type)`.
252    Cast {
253        /// The operand.
254        operand: ExprId,
255        /// The declared type, as written.
256        declared: NameId,
257    },
258    /// `expr [NOT] LIKE|GLOB|REGEXP|MATCH pattern [ESCAPE expr]`.
259    Pattern {
260        /// Whether `NOT` was written.
261        negated: bool,
262        /// Which operator.
263        op: PatternOp,
264        /// The value being matched.
265        operand: ExprId,
266        /// The pattern.
267        pattern: ExprId,
268        /// The `ESCAPE` argument, when written.
269        escape: Option<ExprId>,
270    },
271    /// `expr [NOT] BETWEEN low AND high`.
272    Between {
273        /// Whether `NOT` was written.
274        negated: bool,
275        /// The value being tested.
276        operand: ExprId,
277        /// The lower bound.
278        low: ExprId,
279        /// The upper bound.
280        high: ExprId,
281    },
282    /// `expr [NOT] IN rhs`.
283    In {
284        /// Whether `NOT` was written.
285        negated: bool,
286        /// The value being tested.
287        operand: ExprId,
288        /// What it is tested against.
289        rhs: InRhs,
290    },
291    /// `expr ISNULL` / `expr NOTNULL` / `expr IS [NOT] NULL`.
292    IsNull {
293        /// Whether the test is for not-null.
294        negated: bool,
295        /// The operand.
296        operand: ExprId,
297    },
298    /// `left IS [NOT] [DISTINCT FROM] right`.
299    Is {
300        /// Whether `NOT` was written.
301        negated: bool,
302        /// Whether the `DISTINCT FROM` spelling was used.
303        distinct_from: bool,
304        /// The left operand.
305        left: ExprId,
306        /// The right operand.
307        right: ExprId,
308    },
309    /// `CASE [operand] WHEN ... THEN ... [ELSE ...] END`.
310    Case {
311        /// The base operand, when the form has one.
312        operand: Option<ExprId>,
313        /// The `WHEN`/`THEN` pairs, in written order.
314        branches: Vec<(ExprId, ExprId)>,
315        /// The `ELSE` arm.
316        otherwise: Option<ExprId>,
317    },
318    /// A function call, aggregate or scalar or window.
319    Function {
320        /// The function name.
321        name: NameId,
322        /// Whether `DISTINCT` was written.
323        distinct: bool,
324        /// The arguments, or `None` for `count(*)`.
325        arguments: Option<Vec<ExprId>>,
326        /// An `ORDER BY` inside the argument list.
327        order_by: Vec<OrderTerm>,
328        /// A `FILTER (WHERE ...)` clause.
329        filter: Option<ExprId>,
330        /// An `OVER` clause.
331        over: Option<WindowId>,
332    },
333    /// `[NOT] EXISTS (SELECT ...)`.
334    Exists {
335        /// Whether `NOT` was written.
336        negated: bool,
337        /// The subquery.
338        select: SelectId,
339    },
340    /// A scalar subquery.
341    Subquery(SelectId),
342    /// A parenthesised list of two or more expressions.
343    RowValue(Vec<ExprId>),
344    /// `RAISE(...)`, legal only inside a trigger body.
345    Raise {
346        /// Which action.
347        action: RaiseAction,
348        /// The message, when the action takes one.
349        ///
350        /// An expression, as SQLite takes it: `RAISE(ABORT, 'too big: ' ||
351        /// NEW.n)` names the value that broke the rule, which is the reason to
352        /// write a guard trigger at all. It used to be a string literal only,
353        /// and anything else was a syntax error pointing at the `||`.
354        message: Option<ExprId>,
355    },
356}
357
358/// Ascending or descending.
359#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
360pub enum SortOrder {
361    /// `ASC`, the default.
362    #[default]
363    Ascending,
364    /// `DESC`.
365    Descending,
366}
367
368/// Where NULLs sort, when written explicitly.
369#[derive(Clone, Copy, Debug, PartialEq, Eq)]
370pub enum NullOrder {
371    /// `NULLS FIRST`.
372    First,
373    /// `NULLS LAST`.
374    Last,
375}
376
377/// One term of an `ORDER BY`.
378#[derive(Clone, Copy, Debug, PartialEq, Eq)]
379pub struct OrderTerm {
380    /// The expression, which may be an ordinal or an alias.
381    pub expr: ExprId,
382    /// The written or defaulted direction.
383    pub order: SortOrder,
384    /// The written null ordering, when there was one.
385    pub nulls: Option<NullOrder>,
386}
387
388/// One result column of a SELECT.
389#[derive(Clone, Debug, PartialEq, Eq)]
390pub struct ResultColumn {
391    /// The expression, which may be `*` or `table.*`.
392    pub expr: ExprId,
393    /// The alias, when one was written.
394    pub alias: Option<NameId>,
395    /// Whether the alias was written with `AS`.
396    pub alias_was_explicit: bool,
397    /// The span of the whole result column.
398    pub span: Span,
399}
400
401/// Which join was written.
402#[derive(Clone, Copy, Debug, PartialEq, Eq)]
403pub enum JoinKind {
404    /// A comma, which is a cross join that may still be reordered.
405    Comma,
406    /// `[INNER] JOIN`.
407    Inner,
408    /// `CROSS JOIN`, which SQLite refuses to reorder.
409    Cross,
410    /// `LEFT [OUTER] JOIN`.
411    Left,
412    /// `RIGHT [OUTER] JOIN`.
413    Right,
414    /// `FULL [OUTER] JOIN`.
415    Full,
416}
417
418/// The `ON` or `USING` constraint of a join.
419#[derive(Clone, Debug, PartialEq, Eq)]
420pub enum JoinConstraint {
421    /// No constraint was written.
422    None,
423    /// `ON expr`.
424    On(ExprId),
425    /// `USING (a, b)`.
426    Using(Vec<NameId>),
427}
428
429/// How a FROM term names its rows.
430#[derive(Clone, Debug, PartialEq, Eq)]
431pub enum FromSource {
432    /// A table, view or table-valued function.
433    Table {
434        /// The schema qualifier.
435        database: Option<NameId>,
436        /// The object name.
437        name: NameId,
438        /// Arguments, when it is a table-valued function.
439        arguments: Option<Vec<ExprId>>,
440        /// `INDEXED BY name`, or `NOT INDEXED`.
441        indexed_by: IndexHint,
442    },
443    /// A subquery.
444    Subquery(SelectId),
445    /// A parenthesised join, which is one term to whatever contains it.
446    Join(Vec<FromTermId>),
447}
448
449/// An `INDEXED BY` hint.
450#[derive(Clone, Copy, Debug, PartialEq, Eq)]
451pub enum IndexHint {
452    /// Nothing was written.
453    None,
454    /// `NOT INDEXED`.
455    NotIndexed,
456    /// `INDEXED BY name`.
457    IndexedBy(NameId),
458}
459
460/// One term of a FROM clause, with the join that attached it.
461#[derive(Clone, Debug, PartialEq, Eq)]
462pub struct FromTerm {
463    /// Where the rows come from.
464    pub source: FromSource,
465    /// The alias, when one was written.
466    pub alias: Option<NameId>,
467    /// The join that attaches this term to the one before it.
468    pub join: JoinKind,
469    /// Whether `NATURAL` was written.
470    pub natural: bool,
471    /// The `ON` or `USING` constraint.
472    pub constraint: JoinConstraint,
473    /// The span of the whole term.
474    pub span: Span,
475}
476
477/// A window frame's unit.
478#[derive(Clone, Copy, Debug, PartialEq, Eq)]
479pub enum FrameUnit {
480    /// `ROWS`.
481    Rows,
482    /// `RANGE`.
483    Range,
484    /// `GROUPS`.
485    Groups,
486}
487
488/// One end of a window frame.
489#[derive(Clone, Copy, Debug, PartialEq, Eq)]
490pub enum FrameBound {
491    /// `UNBOUNDED PRECEDING`.
492    UnboundedPreceding,
493    /// `expr PRECEDING`.
494    Preceding(ExprId),
495    /// `CURRENT ROW`.
496    CurrentRow,
497    /// `expr FOLLOWING`.
498    Following(ExprId),
499    /// `UNBOUNDED FOLLOWING`.
500    UnboundedFollowing,
501}
502
503/// A frame's `EXCLUDE` clause.
504#[derive(Clone, Copy, Debug, PartialEq, Eq)]
505pub enum FrameExclude {
506    /// `EXCLUDE NO OTHERS`, the default.
507    NoOthers,
508    /// `EXCLUDE CURRENT ROW`.
509    CurrentRow,
510    /// `EXCLUDE GROUP`.
511    Group,
512    /// `EXCLUDE TIES`.
513    Ties,
514}
515
516/// A window definition, named or inline.
517#[derive(Clone, Debug, PartialEq, Eq)]
518pub struct Window {
519    /// The window this one inherits from, when written.
520    pub base: Option<NameId>,
521    /// `PARTITION BY`.
522    pub partition_by: Vec<ExprId>,
523    /// `ORDER BY`.
524    pub order_by: Vec<OrderTerm>,
525    /// The frame unit, when a frame was written.
526    pub unit: Option<FrameUnit>,
527    /// The frame start.
528    pub start: Option<FrameBound>,
529    /// The frame end.
530    pub end: Option<FrameBound>,
531    /// The `EXCLUDE` clause.
532    pub exclude: FrameExclude,
533    /// The span of the definition.
534    pub span: Span,
535}
536
537/// The rows of one arm of a compound SELECT.
538#[derive(Clone, Debug, PartialEq, Eq)]
539pub enum SelectBody {
540    /// `SELECT ...`.
541    Select {
542        /// Whether `DISTINCT` was written.
543        distinct: bool,
544        /// Whether `ALL` was written.
545        all: bool,
546        /// The result columns.
547        columns: Vec<ResultColumn>,
548        /// The FROM terms, in written order.
549        from: Vec<FromTermId>,
550        /// The WHERE clause.
551        filter: Option<ExprId>,
552        /// The GROUP BY terms.
553        group_by: Vec<ExprId>,
554        /// The HAVING clause.
555        having: Option<ExprId>,
556        /// Named windows.
557        windows: Vec<(NameId, WindowId)>,
558    },
559    /// `VALUES (...), (...)`.
560    Values(Vec<Vec<ExprId>>),
561}
562
563/// One arm of a compound SELECT.
564#[derive(Clone, Debug, PartialEq, Eq)]
565pub struct SelectCore {
566    /// What the arm produces.
567    pub body: SelectBody,
568    /// The span of the arm.
569    pub span: Span,
570}
571
572/// A compound operator.
573#[derive(Clone, Copy, Debug, PartialEq, Eq)]
574pub enum CompoundOp {
575    /// `UNION`.
576    Union,
577    /// `UNION ALL`.
578    UnionAll,
579    /// `INTERSECT`.
580    Intersect,
581    /// `EXCEPT`.
582    Except,
583}
584
585/// A common table expression.
586#[derive(Clone, Debug, PartialEq, Eq)]
587pub struct CommonTableExpr {
588    /// The name it is bound to.
589    pub name: NameId,
590    /// The explicit column list, when written.
591    pub columns: Vec<NameId>,
592    /// `MATERIALIZED` or `NOT MATERIALIZED`, when written.
593    pub materialized: Option<bool>,
594    /// The query.
595    pub select: SelectId,
596}
597
598/// A `WITH` prefix.
599#[derive(Clone, Debug, PartialEq, Eq, Default)]
600pub struct With {
601    /// Whether `RECURSIVE` was written.
602    pub recursive: bool,
603    /// The CTEs, in written order.
604    pub ctes: Vec<CommonTableExpr>,
605}
606
607/// A complete SELECT: a `WITH` prefix, compound arms, and the tail clauses.
608#[derive(Clone, Debug, PartialEq, Eq)]
609pub struct Select {
610    /// The `WITH` prefix.
611    pub with: With,
612    /// The first arm.
613    pub first: SelectCoreId,
614    /// Later arms, each with the operator that joined it.
615    pub compounds: Vec<(CompoundOp, SelectCoreId)>,
616    /// The `ORDER BY`, which belongs to the whole compound.
617    pub order_by: Vec<OrderTerm>,
618    /// The `LIMIT` expression.
619    pub limit: Option<ExprId>,
620    /// The `OFFSET` expression.
621    pub offset: Option<ExprId>,
622    /// The span of the whole statement.
623    pub span: Span,
624}
625
626/// A conflict-resolution algorithm.
627#[derive(Clone, Copy, Debug, PartialEq, Eq)]
628pub enum ConflictAction {
629    /// `ROLLBACK`.
630    Rollback,
631    /// `ABORT`, the default.
632    Abort,
633    /// `FAIL`.
634    Fail,
635    /// `IGNORE`.
636    Ignore,
637    /// `REPLACE`.
638    Replace,
639}
640
641/// A column constraint, in written order.
642#[derive(Clone, Debug, PartialEq, Eq)]
643pub enum ColumnConstraint {
644    /// `PRIMARY KEY [ASC|DESC] [conflict] [AUTOINCREMENT]`.
645    PrimaryKey {
646        /// The written direction.
647        order: SortOrder,
648        /// The conflict clause.
649        on_conflict: Option<ConflictAction>,
650        /// Whether `AUTOINCREMENT` was written.
651        autoincrement: bool,
652    },
653    /// `NOT NULL [conflict]`.
654    NotNull(Option<ConflictAction>),
655    /// `NULL`, which SQLite accepts and ignores.
656    Null,
657    /// `UNIQUE [conflict]`.
658    Unique(Option<ConflictAction>),
659    /// `CHECK (expr)`.
660    ///
661    /// **No conflict clause**, which is SQLite's grammar and not an omission:
662    /// `ccons ::= CHECK LP expr RP` has no `onconf`, so
663    /// `b INTEGER CHECK(b < 9) ON CONFLICT IGNORE` is a syntax error there and
664    /// has to be one here. Only a *table*-level `CHECK` takes the clause - see
665    /// [`TableConstraint::Check`].
666    Check(ExprId),
667    /// `DEFAULT expr`.
668    Default(ExprId),
669    /// `COLLATE name`.
670    Collate(NameId),
671    /// `REFERENCES ...`.
672    References(ForeignKeyClause),
673    /// `GENERATED ALWAYS AS (expr) [STORED|VIRTUAL]`.
674    Generated {
675        /// The generating expression.
676        expr: ExprId,
677        /// Whether `STORED` was written.
678        stored: bool,
679    },
680}
681
682/// A foreign-key clause, on a column or on a table.
683#[derive(Clone, Debug, PartialEq, Eq)]
684pub struct ForeignKeyClause {
685    /// The parent table.
686    pub table: NameId,
687    /// The parent columns, when written.
688    pub columns: Vec<NameId>,
689    /// The `ON DELETE`/`ON UPDATE`/`MATCH` clauses, as written.
690    pub actions: Vec<ForeignKeyAction>,
691    /// Whether the constraint is deferrable.
692    pub deferrable: Option<bool>,
693    /// Whether it is initially deferred.
694    pub initially_deferred: bool,
695}
696
697/// One `ON DELETE`, `ON UPDATE` or `MATCH` clause.
698#[derive(Clone, Copy, Debug, PartialEq, Eq)]
699pub enum ForeignKeyAction {
700    /// `ON DELETE <action>`.
701    OnDelete(ReferentialAction),
702    /// `ON UPDATE <action>`.
703    OnUpdate(ReferentialAction),
704    /// `MATCH name`.
705    Match(NameId),
706}
707
708/// What a referential action does.
709#[derive(Clone, Copy, Debug, PartialEq, Eq)]
710pub enum ReferentialAction {
711    /// `SET NULL`.
712    SetNull,
713    /// `SET DEFAULT`.
714    SetDefault,
715    /// `CASCADE`.
716    Cascade,
717    /// `RESTRICT`.
718    Restrict,
719    /// `NO ACTION`.
720    NoAction,
721}
722
723/// One column of a `CREATE TABLE`.
724#[derive(Clone, Debug, PartialEq, Eq)]
725pub struct ColumnDef {
726    /// The column name.
727    pub name: NameId,
728    /// The declared type, exactly as written, when there was one.
729    pub declared_type: Option<Vec<u8>>,
730    /// The constraints, in written order, each with its optional name.
731    pub constraints: Vec<(Option<NameId>, ColumnConstraint)>,
732    /// The span of the definition.
733    pub span: Span,
734}
735
736/// One indexed column of a table constraint or an index.
737#[derive(Clone, Copy, Debug, PartialEq, Eq)]
738pub struct IndexedColumn {
739    /// The key expression, which may be a bare column.
740    pub expr: ExprId,
741    /// An explicit collation.
742    pub collation: Option<NameId>,
743    /// The direction.
744    pub order: SortOrder,
745}
746
747/// A table-level constraint.
748#[derive(Clone, Debug, PartialEq, Eq)]
749pub enum TableConstraint {
750    /// `PRIMARY KEY (...)`.
751    PrimaryKey {
752        /// The key columns.
753        columns: Vec<IndexedColumn>,
754        /// The conflict clause.
755        on_conflict: Option<ConflictAction>,
756        /// Whether `AUTOINCREMENT` was written.
757        autoincrement: bool,
758    },
759    /// `UNIQUE (...)`.
760    Unique {
761        /// The key columns.
762        columns: Vec<IndexedColumn>,
763        /// The conflict clause.
764        on_conflict: Option<ConflictAction>,
765    },
766    /// `CHECK (expr) [conflict]`.
767    ///
768    /// **Parsed and then ignored, which is what SQLite does with it.**
769    /// `tcons ::= CHECK LP expr RP onconf` accepts the clause and
770    /// `sqlite3AddCheckConstraint` never reads it, so
771    /// `CONSTRAINT small CHECK(b < 9) ON CONFLICT FAIL` behaves exactly as
772    /// `ABORT`: measured against the pinned 3.53.4, an `INSERT` of three rows
773    /// whose second fails keeps none of them.
774    ///
775    /// It is in the tree rather than discarded at the token because the table's
776    /// `CREATE` text is stored and re-parsed on every open, so the grammar has
777    /// to accept everything the text can hold. Not accepting it did not cost
778    /// one statement a clause - it made the `CREATE TABLE` a parse error, and
779    /// every statement after it said `no such table`.
780    Check {
781        /// The predicate.
782        expr: ExprId,
783        /// The conflict clause, accepted and not acted on.
784        on_conflict: Option<ConflictAction>,
785    },
786    /// `FOREIGN KEY (...) REFERENCES ...`.
787    ForeignKey {
788        /// The child columns.
789        columns: Vec<NameId>,
790        /// The parent reference.
791        clause: ForeignKeyClause,
792    },
793}
794
795/// The body of a `CREATE TABLE`.
796#[derive(Clone, Debug, PartialEq, Eq)]
797pub enum CreateTableBody {
798    /// A column list.
799    Columns {
800        /// The columns, in written order.
801        columns: Vec<ColumnDef>,
802        /// The table constraints, in written order, each with its name.
803        constraints: Vec<(Option<NameId>, TableConstraint)>,
804        /// Whether `WITHOUT ROWID` was written.
805        without_rowid: bool,
806        /// Whether `STRICT` was written.
807        strict: bool,
808    },
809    /// `CREATE TABLE ... AS SELECT ...`.
810    AsSelect(SelectId),
811}
812
813/// An `UPSERT` clause.
814#[derive(Clone, Debug, PartialEq, Eq)]
815pub struct Upsert {
816    /// The conflict target columns, when written.
817    pub target: Vec<IndexedColumn>,
818    /// The conflict target's `WHERE`.
819    pub target_filter: Option<ExprId>,
820    /// The `DO UPDATE SET` assignments, empty for `DO NOTHING`.
821    pub assignments: Vec<(Vec<NameId>, ExprId)>,
822    /// Whether the action is `DO UPDATE`.
823    pub do_update: bool,
824    /// The `DO UPDATE`'s `WHERE`.
825    pub filter: Option<ExprId>,
826}
827
828/// What an INSERT inserts.
829#[derive(Clone, Debug, PartialEq, Eq)]
830pub enum InsertSource {
831    /// `VALUES`, or any SELECT.
832    Select(SelectId),
833    /// `DEFAULT VALUES`.
834    DefaultValues,
835}
836
837/// An `INSERT` statement.
838#[derive(Clone, Debug, PartialEq, Eq)]
839pub struct Insert {
840    /// The `WITH` prefix.
841    pub with: With,
842    /// The conflict algorithm from `INSERT OR ...` or `REPLACE`.
843    pub on_conflict: Option<ConflictAction>,
844    /// The schema qualifier.
845    pub database: Option<NameId>,
846    /// The target table.
847    pub table: NameId,
848    /// The table alias.
849    pub alias: Option<NameId>,
850    /// The column list, when written.
851    pub columns: Vec<NameId>,
852    /// The rows.
853    pub source: InsertSource,
854    /// The `ON CONFLICT` clauses, in written order.
855    pub upserts: Vec<Upsert>,
856    /// The `RETURNING` columns.
857    pub returning: Vec<ResultColumn>,
858}
859
860/// An `UPDATE` statement.
861#[derive(Clone, Debug, PartialEq, Eq)]
862pub struct Update {
863    /// The `WITH` prefix.
864    pub with: With,
865    /// The conflict algorithm from `UPDATE OR ...`.
866    pub on_conflict: Option<ConflictAction>,
867    /// The target term, which carries its own alias and index hint.
868    pub target: FromTermId,
869    /// The `SET` assignments; a group of names is the `(a, b) = ...` form.
870    pub assignments: Vec<(Vec<NameId>, ExprId)>,
871    /// An `UPDATE ... FROM` clause.
872    pub from: Vec<FromTermId>,
873    /// The `WHERE` clause.
874    pub filter: Option<ExprId>,
875    /// The `RETURNING` columns.
876    pub returning: Vec<ResultColumn>,
877    /// The `ORDER BY`, which SQLite allows with `LIMIT`.
878    pub order_by: Vec<OrderTerm>,
879    /// The `LIMIT`.
880    pub limit: Option<ExprId>,
881    /// The `OFFSET`.
882    pub offset: Option<ExprId>,
883    /// Where the clause the reference build has no grammar for was written.
884    ///
885    /// `ORDER BY` and `LIMIT` on a `DELETE` or an `UPDATE` are a compile-time
886    /// option in SQLite, and the pinned build is not compiled with it - so the
887    /// reference answers `near "ORDER": syntax error` and points at the word.
888    /// The syntax register requires these to *parse* here, so the refusal is
889    /// the binder's; it needs the position to be able to point at the same
890    /// word, and this is where the parser leaves it.
891    pub limited_at: Option<(Limited, crate::lexer::Span)>,
892}
893
894/// Which of the two words a limited `DELETE` or `UPDATE` was written with.
895///
896/// The reference names the first one it cannot parse, so a statement carrying
897/// both reports `ORDER` and one carrying only a `LIMIT` reports `LIMIT`.
898#[derive(Clone, Copy, Debug, PartialEq, Eq)]
899pub enum Limited {
900    /// `ORDER BY`.
901    OrderBy,
902    /// `LIMIT`.
903    Limit,
904}
905
906impl Limited {
907    /// Returns the word the refusal quotes.
908    pub fn word(self) -> &'static str {
909        match self {
910            Limited::OrderBy => "ORDER",
911            Limited::Limit => "LIMIT",
912        }
913    }
914}
915
916/// A `DELETE` statement.
917#[derive(Clone, Debug, PartialEq, Eq)]
918pub struct Delete {
919    /// The `WITH` prefix.
920    pub with: With,
921    /// The target term.
922    pub target: FromTermId,
923    /// The `WHERE` clause.
924    pub filter: Option<ExprId>,
925    /// The `RETURNING` columns.
926    pub returning: Vec<ResultColumn>,
927    /// The `ORDER BY`.
928    pub order_by: Vec<OrderTerm>,
929    /// The `LIMIT`.
930    pub limit: Option<ExprId>,
931    /// The `OFFSET`.
932    pub offset: Option<ExprId>,
933    /// Where the clause the reference build has no grammar for was written.
934    ///
935    /// `ORDER BY` and `LIMIT` on a `DELETE` or an `UPDATE` are a compile-time
936    /// option in SQLite, and the pinned build is not compiled with it - so the
937    /// reference answers `near "ORDER": syntax error` and points at the word.
938    /// The syntax register requires these to *parse* here, so the refusal is
939    /// the binder's; it needs the position to be able to point at the same
940    /// word, and this is where the parser leaves it.
941    pub limited_at: Option<(Limited, crate::lexer::Span)>,
942}
943
944/// Which kind of object a `DROP` names.
945#[derive(Clone, Copy, Debug, PartialEq, Eq)]
946pub enum ObjectKind {
947    /// A table.
948    Table,
949    /// An index.
950    Index,
951    /// A view.
952    View,
953    /// A trigger.
954    Trigger,
955}
956
957/// What an `ALTER TABLE` does.
958#[derive(Clone, Debug, PartialEq, Eq)]
959pub enum AlterAction {
960    /// `RENAME TO name`.
961    RenameTo(NameId),
962    /// `RENAME [COLUMN] a TO b`.
963    RenameColumn {
964        /// The current name.
965        from: NameId,
966        /// The new name.
967        to: NameId,
968    },
969    /// `ADD [COLUMN] def`.
970    AddColumn(ColumnDef),
971    /// `DROP [COLUMN] name`.
972    DropColumn(NameId),
973}
974
975/// When a trigger fires.
976#[derive(Clone, Copy, Debug, PartialEq, Eq)]
977pub enum TriggerTime {
978    /// `BEFORE`.
979    Before,
980    /// `AFTER`.
981    After,
982    /// `INSTEAD OF`.
983    InsteadOf,
984}
985
986/// What a trigger fires on.
987#[derive(Clone, Debug, PartialEq, Eq)]
988pub enum TriggerEvent {
989    /// `DELETE`.
990    Delete,
991    /// `INSERT`.
992    Insert,
993    /// `UPDATE [OF a, b]`.
994    Update(Vec<NameId>),
995}
996
997/// A `PRAGMA` argument.
998#[derive(Clone, Debug, PartialEq, Eq)]
999pub enum PragmaValue {
1000    /// Nothing was written.
1001    None,
1002    /// `= value` or `(value)`.
1003    Value(ExprId),
1004    /// `(name)`, which is a bare word rather than an expression.
1005    Name(NameId),
1006}
1007
1008/// A parsed statement.
1009#[derive(Clone, Debug, PartialEq, Eq)]
1010pub enum Statement {
1011    /// An empty statement, which SQLite compiles to nothing.
1012    Empty,
1013    /// `SELECT` or `VALUES`.
1014    Select(SelectId),
1015    /// `INSERT` or `REPLACE`.
1016    Insert(Box<Insert>),
1017    /// `UPDATE`.
1018    Update(Box<Update>),
1019    /// `DELETE`.
1020    Delete(Box<Delete>),
1021    /// `CREATE TABLE`.
1022    CreateTable {
1023        /// Whether `TEMP` was written.
1024        temporary: bool,
1025        /// Whether `IF NOT EXISTS` was written.
1026        if_not_exists: bool,
1027        /// The schema qualifier.
1028        database: Option<NameId>,
1029        /// The table name.
1030        name: NameId,
1031        /// The body.
1032        body: CreateTableBody,
1033    },
1034    /// `CREATE INDEX`.
1035    CreateIndex {
1036        /// Whether `UNIQUE` was written.
1037        unique: bool,
1038        /// Whether `IF NOT EXISTS` was written.
1039        if_not_exists: bool,
1040        /// The schema qualifier.
1041        database: Option<NameId>,
1042        /// The index name.
1043        name: NameId,
1044        /// The table it indexes.
1045        table: NameId,
1046        /// The module named by `USING`, when one was.
1047        ///
1048        /// SQLite has no `USING` on `CREATE INDEX`; PostgreSQL does, and it is
1049        /// how pgvector spells `USING hnsw`. This engine borrows the spelling
1050        /// for the same purpose: an index whose structure is not a b-tree.
1051        /// A plain `CREATE INDEX` leaves it `None` and nothing
1052        /// downstream changes.
1053        using: Option<NameId>,
1054        /// The key columns.
1055        columns: Vec<IndexedColumn>,
1056        /// The storage parameters `WITH ( ... )` named, as written.
1057        ///
1058        /// `m = 16`, `ef_construction = 64` and the rest: raw `name = value`
1059        /// slices, in the order they were written, for the structure named by
1060        /// `using` to read. Empty for a plain `CREATE INDEX`, which has no
1061        /// structure to read them.
1062        settings: Vec<Vec<u8>>,
1063        /// The partial-index predicate.
1064        filter: Option<ExprId>,
1065    },
1066    /// `CREATE VIEW`.
1067    CreateView {
1068        /// Whether `TEMP` was written.
1069        temporary: bool,
1070        /// Whether `IF NOT EXISTS` was written.
1071        if_not_exists: bool,
1072        /// The schema qualifier.
1073        database: Option<NameId>,
1074        /// The view name.
1075        name: NameId,
1076        /// The explicit column list.
1077        columns: Vec<NameId>,
1078        /// The query.
1079        select: SelectId,
1080    },
1081    /// `CREATE TRIGGER`.
1082    CreateTrigger {
1083        /// Whether `TEMP` was written.
1084        temporary: bool,
1085        /// Whether `IF NOT EXISTS` was written.
1086        if_not_exists: bool,
1087        /// The schema qualifier.
1088        database: Option<NameId>,
1089        /// The trigger name.
1090        name: NameId,
1091        /// When it fires.
1092        time: Option<TriggerTime>,
1093        /// What it fires on.
1094        event: TriggerEvent,
1095        /// The table it is attached to.
1096        table: NameId,
1097        /// The schema qualifier on the table, as in `ON main.t`.
1098        table_database: Option<NameId>,
1099        /// Whether `FOR EACH ROW` was written.
1100        for_each_row: bool,
1101        /// The `WHEN` guard.
1102        when: Option<ExprId>,
1103        /// The body statements, in written order.
1104        body: Vec<Statement>,
1105    },
1106    /// `CREATE VIRTUAL TABLE`.
1107    CreateVirtualTable {
1108        /// Whether `IF NOT EXISTS` was written.
1109        if_not_exists: bool,
1110        /// The schema qualifier.
1111        database: Option<NameId>,
1112        /// The table name.
1113        name: NameId,
1114        /// The module name.
1115        module: NameId,
1116        /// The module arguments, as written source slices.
1117        arguments: Vec<Vec<u8>>,
1118    },
1119    /// `DROP TABLE|INDEX|VIEW|TRIGGER`.
1120    Drop {
1121        /// Which kind of object.
1122        kind: ObjectKind,
1123        /// Whether `IF EXISTS` was written.
1124        if_exists: bool,
1125        /// The schema qualifier.
1126        database: Option<NameId>,
1127        /// The object name.
1128        name: NameId,
1129    },
1130    /// `ALTER TABLE`.
1131    AlterTable {
1132        /// The schema qualifier.
1133        database: Option<NameId>,
1134        /// The table name.
1135        table: NameId,
1136        /// What to do to it.
1137        action: AlterAction,
1138    },
1139    /// `BEGIN`.
1140    Begin {
1141        /// `DEFERRED`, `IMMEDIATE` or `EXCLUSIVE`, when written.
1142        behaviour: Option<TransactionBehaviour>,
1143    },
1144    /// `COMMIT` or `END`.
1145    Commit,
1146    /// `ROLLBACK [TO savepoint]`.
1147    Rollback {
1148        /// The savepoint to roll back to.
1149        savepoint: Option<NameId>,
1150    },
1151    /// `SAVEPOINT name`.
1152    Savepoint(NameId),
1153    /// `RELEASE [SAVEPOINT] name`.
1154    Release(NameId),
1155    /// `PRAGMA`.
1156    Pragma {
1157        /// The schema qualifier.
1158        database: Option<NameId>,
1159        /// The pragma name.
1160        name: NameId,
1161        /// The argument.
1162        value: PragmaValue,
1163    },
1164    /// `ATTACH`.
1165    Attach {
1166        /// The file expression.
1167        file: ExprId,
1168        /// The schema name expression.
1169        schema: ExprId,
1170        /// The `KEY` expression.
1171        key: Option<ExprId>,
1172    },
1173    /// `DETACH`.
1174    Detach {
1175        /// The schema name expression.
1176        schema: ExprId,
1177    },
1178    /// `VACUUM`.
1179    Vacuum {
1180        /// The schema to vacuum.
1181        database: Option<NameId>,
1182        /// The `INTO` target.
1183        into: Option<ExprId>,
1184    },
1185    /// `ANALYZE`.
1186    Analyze {
1187        /// The schema qualifier.
1188        database: Option<NameId>,
1189        /// The object to analyze.
1190        name: Option<NameId>,
1191    },
1192    /// `REINDEX`.
1193    Reindex {
1194        /// The schema qualifier.
1195        database: Option<NameId>,
1196        /// The collation, table or index to reindex.
1197        name: Option<NameId>,
1198    },
1199    /// `EXPLAIN` or `EXPLAIN QUERY PLAN`.
1200    Explain {
1201        /// Whether `QUERY PLAN` was written.
1202        query_plan: bool,
1203        /// The statement being explained.
1204        inner: Box<Statement>,
1205    },
1206}
1207
1208/// The behaviour of a `BEGIN`.
1209#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1210pub enum TransactionBehaviour {
1211    /// `DEFERRED`.
1212    Deferred,
1213    /// `IMMEDIATE`.
1214    Immediate,
1215    /// `EXCLUSIVE`.
1216    Exclusive,
1217}
1218
1219/// How many name buffers [`Ast::clear`] keeps for the next parse to fill.
1220///
1221/// **Because `clear` empties `names`, which drops each `Name`'s two `Vec<u8>`
1222/// (task-2039).** The arena keeps its *vectors'* capacity across a clear and
1223/// not its *entries'*, so a connection re-compiling the same statement paid
1224/// two allocations per distinct name for ever. A statement names a handful of
1225/// things, so a short list of buffers covers the repeating case; a statement
1226/// that names hundreds gives the surplus back to the allocator rather than
1227/// holding it on a connection that will never name that many again.
1228const SPARE_NAME_BUFFERS: usize = 64;
1229
1230/// The largest name buffer [`Ast::clear`] keeps, in bytes of capacity.
1231///
1232/// A held buffer is memory the connection does not give back, so a long name -
1233/// a generated column alias, a quoted sentence - is dropped rather than kept.
1234/// With [`SPARE_NAME_BUFFERS`] this bounds what one arena holds between parses
1235/// at about 8 KiB.
1236const SPARE_NAME_CAPACITY: usize = 128;
1237
1238/// Which names share one hash of their spelling and quote form.
1239///
1240/// **A collision must not hand back the wrong `NameId`.** `NameId` equality is
1241/// read as "the same name" - the binder resolves a column reference by
1242/// comparing ids - so storing one index per hash and overwriting on collision
1243/// would silently make two different identifiers the same name. Every
1244/// candidate is compared against `Ast::names` before it is returned, and a
1245/// hash shared by two different spellings keeps both.
1246///
1247/// The single case is inline rather than a one-element `Vec` because that
1248/// `Vec` would be an allocation per distinct name, which is most of what
1249/// task-2039 removed. `Several` allocates, and needs a 64-bit collision to be
1250/// reached at all.
1251#[derive(Clone, Debug, PartialEq, Eq)]
1252enum Interned {
1253    /// The only name whose spelling and quote form hash to this value.
1254    One(u32),
1255    /// Two or more names that hashed the same, in the order they were interned.
1256    Several(Vec<u32>),
1257}
1258
1259/// The arena every node of one parse lives in.
1260#[derive(Clone, Debug, Default, Eq)]
1261pub struct Ast {
1262    names: Vec<Name>,
1263    /// Where a name already is, so `intern` is a lookup rather than a scan.
1264    ///
1265    /// **`intern` was a linear scan of every name interned so far, so N
1266    /// distinct identifiers cost N-squared comparisons (task-1932, H8).** The
1267    /// `SqlLength` default is 1 GiB, so a statement naming two hundred thousand
1268    /// distinct columns is well inside what the parser accepts and was
1269    /// quadratic to parse.
1270    ///
1271    /// **The key is a hash of the name and not the name itself (task-2039).**
1272    /// Owning `(folded, quote, text)` meant every lookup had to build an owned
1273    /// key to look up *with*, and finding the name already there still cost the
1274    /// folded copy plus two more from `key.clone()` on the way in - four
1275    /// allocations per distinct name, twelve of the ninety-three a compile of
1276    /// `SELECT a FROM t WHERE id = ?1` made. Hashing the bytes where they are
1277    /// and comparing the candidates against `names`, which already holds the
1278    /// spelling and the quote form, makes a hit free and leaves a miss paying
1279    /// only for what it stores.
1280    ///
1281    /// The hash comes from the map's own [`std::collections::hash_map::RandomState`],
1282    /// which is seeded per arena. That matters rather than being tidy: the
1283    /// parser accepts `Limit::Column * 64` distinct identifiers - 128,000 under
1284    /// the defaults - so a fixed hash an attacker could invert would let a
1285    /// statement drive every name into one `Several` and restore the quadratic
1286    /// parse this map exists to prevent.
1287    interned: std::collections::HashMap<u64, Interned>,
1288    /// Name byte buffers a previous parse used, waiting to be filled again.
1289    ///
1290    /// See [`SPARE_NAME_BUFFERS`]. Empty on a fresh arena, so the first parse
1291    /// pays what it always did and every parse after it does not.
1292    spare: Vec<Vec<u8>>,
1293    exprs: Vec<Expr>,
1294    expr_spans: Vec<Span>,
1295    /// How deep each expression's own subtree is, one entry per node.
1296    ///
1297    /// **`Limit::ExprDepth` was declared in `compat/limits.toml` and enforced
1298    /// nowhere (task-1932, H8).** The parser charges `Limit::ParserDepth` in
1299    /// `enter`/`leave`, which counts recursion, and the two are different
1300    /// measurements: a flat chain `a1 = 1 AND a2 = 2 AND ...` enters and leaves
1301    /// `parse_expr_bp` once per term, so the recursion counter never
1302    /// accumulates, while the tree grows one level per term with nothing
1303    /// counting it. SQLite refuses at depth 1000. A tree that deep is accepted
1304    /// here and then walked recursively by the binder, the planner and the
1305    /// executor, each of which overflows the stack at some depth nobody
1306    /// measured.
1307    ///
1308    /// A node's depth is one more than the deepest of its children, and a child
1309    /// is always already in the arena when its parent is added, so this is one
1310    /// pass over the child ids at `add_expr` rather than a walk.
1311    expr_depths: Vec<u32>,
1312    /// The deepest expression tree in the arena.
1313    max_expr_depth: u32,
1314    selects: Vec<Select>,
1315    cores: Vec<SelectCore>,
1316    from_terms: Vec<FromTerm>,
1317    windows: Vec<Window>,
1318    bytes: usize,
1319}
1320
1321/// Two arenas are equal when they hold the same nodes.
1322///
1323/// **Hand-written rather than derived, because `interned` and `spare` are not
1324/// content (task-2039).** `interned` is an index over `names` keyed by a hash
1325/// the arena seeds for itself, so two arenas parsed from the same text hold
1326/// the same names under different keys; `spare` is buffers the allocator has
1327/// not been given back yet, which the next parse may or may not use. Comparing
1328/// either would report two identical parses as different. The fields are
1329/// destructured by name and none is skipped with `..`, so a field added later
1330/// fails to compile here rather than being silently left out of equality.
1331impl PartialEq for Ast {
1332    /// @param other - the arena to compare against
1333    fn eq(&self, other: &Ast) -> bool {
1334        let Ast {
1335            names,
1336            interned: _,
1337            spare: _,
1338            exprs,
1339            expr_spans,
1340            expr_depths,
1341            max_expr_depth,
1342            selects,
1343            cores,
1344            from_terms,
1345            windows,
1346            bytes,
1347        } = self;
1348        *names == other.names
1349            && *exprs == other.exprs
1350            && *expr_spans == other.expr_spans
1351            && *expr_depths == other.expr_depths
1352            && *max_expr_depth == other.max_expr_depth
1353            && *selects == other.selects
1354            && *cores == other.cores
1355            && *from_terms == other.from_terms
1356            && *windows == other.windows
1357            && *bytes == other.bytes
1358    }
1359}
1360
1361impl Ast {
1362    /// Returns an empty arena.
1363    pub fn new() -> Ast {
1364        Ast::default()
1365    }
1366
1367    /// Empties the arena, keeping the memory it has already taken.
1368    ///
1369    /// **So that a second statement costs no allocations.** Every one of these
1370    /// vectors is empty at `Ast::new` and grows on its first push, so parsing
1371    /// `SELECT 1` takes half a dozen trips to the allocator - about 270 ns of a
1372    /// 1,337 ns prepare on this platform's CRT heap. A parser handed a cleared
1373    /// arena pushes into capacity that is already there.
1374    ///
1375    /// It is a `clear` rather than a `new` for exactly that reason, and the
1376    /// names are cleared with everything else: `intern` returns an existing id
1377    /// for equal text, so a name left behind from the previous statement would
1378    /// be a live id in the next one's arena.
1379    ///
1380    /// **The names keep their byte buffers even though the names go
1381    /// (task-2039).** Clearing `names` drops every `Name`, and a `Name` owns
1382    /// two `Vec<u8>` - so the vector's capacity survived a clear and the two
1383    /// allocations behind each entry in it did not, and a connection
1384    /// re-compiling one statement went back to the allocator twice per
1385    /// distinct name for ever. The buffers go on `spare` instead and `intern`
1386    /// fills them again. [`SPARE_NAME_BUFFERS`] is what bounds the list.
1387    pub fn clear(&mut self) {
1388        self.recycle_names();
1389        self.interned.clear();
1390        self.exprs.clear();
1391        self.expr_spans.clear();
1392        self.expr_depths.clear();
1393        self.max_expr_depth = 0;
1394        self.selects.clear();
1395        self.cores.clear();
1396        self.from_terms.clear();
1397        self.windows.clear();
1398        self.bytes = 0;
1399    }
1400
1401    /// Returns the number of arena bytes charged so far.
1402    ///
1403    /// This is what the `max_ast_bytes` limit is charged against. It counts the
1404    /// node structures rather than the source, because the source is borrowed.
1405    pub fn charged_bytes(&self) -> usize {
1406        self.bytes
1407    }
1408
1409    /// Interns an identifier, returning the id of an equal existing entry when
1410    /// there is one.
1411    ///
1412    /// **A map rather than a scan (task-1932, H8).** This walked every name
1413    /// interned so far and compared three fields against each, so a statement
1414    /// naming N distinct identifiers cost N-squared comparisons - and the
1415    /// `SqlLength` default is 1 GiB, which leaves room for hundreds of
1416    /// thousands of them. The key is exactly what the scan compared, so the
1417    /// answer is the same one and only the cost changed.
1418    ///
1419    /// The count is charged against `Limit::Column` for the same reason the
1420    /// depth is charged below: a bound that exists in `compat/limits.toml` and
1421    /// is enforced nowhere is not a bound. It is generous - a name is a column,
1422    /// a table, an alias, a function or a collation, so one statement
1423    /// legitimately interns more names than any one table has columns - and it
1424    /// is a ceiling on an arena that has to fit in memory rather than a
1425    /// statement about the schema.
1426    pub fn intern(&mut self, text: Vec<u8>, quote: QuoteForm, span: Span) -> NameId {
1427        let id = self.intern_bytes(&text, quote, span);
1428        Ast::keep_buffer(&mut self.spare, text);
1429        id
1430    }
1431
1432    /// Interns an identifier the caller does not own, returning the id of an
1433    /// equal existing entry when there is one.
1434    ///
1435    /// **The entry point that allocates nothing on a hit (task-2039).** The
1436    /// owned form above had to exist before the lookup could happen, so the
1437    /// parser called `identifier_text(..).into_owned()` on every identifier
1438    /// token whether or not the name was already interned - and `intern` then
1439    /// folded a copy and cloned the key, four allocations for a name the arena
1440    /// already held. This hashes the bytes where the source already has them.
1441    ///
1442    /// A miss allocates what it stores and nothing else: the spelling and the
1443    /// folded key, each taken from `spare` when a previous parse left one
1444    /// there.
1445    ///
1446    /// @param text - the identifier as written, with quoting already undone
1447    /// @param quote - how it was quoted, which decides whether it may become a
1448    ///   string
1449    /// @param span - where this occurrence came from
1450    pub fn intern_bytes(&mut self, text: &[u8], quote: QuoteForm, span: Span) -> NameId {
1451        let hash = self.hash_of(text, quote);
1452        if let Some(index) = self.find_interned(hash, text, quote) {
1453            return NameId(index);
1454        }
1455        let mut folded = Ast::take_buffer(&mut self.spare);
1456        folded.extend(text.iter().map(|byte| byte.to_ascii_lowercase()));
1457        let mut spelling = Ast::take_buffer(&mut self.spare);
1458        spelling.extend_from_slice(text);
1459        self.bytes = self.bytes.saturating_add(
1460            spelling
1461                .len()
1462                .saturating_add(folded.len())
1463                .saturating_add(32),
1464        );
1465        let index = self.names.len() as u32;
1466        self.names.push(Name {
1467            text: spelling,
1468            folded,
1469            quote,
1470            span,
1471        });
1472        self.remember_interned(hash, index);
1473        NameId(index)
1474    }
1475
1476    /// Returns the hash an identifier is filed under.
1477    ///
1478    /// The map's own hasher, so the seed belongs to this arena and no caller
1479    /// can choose names that collide. The folded key is not part of the hash:
1480    /// folding is a function of the spelling, so two identifiers written the
1481    /// same way and quoted the same way always fold the same, and no name is
1482    /// ever filed apart from itself.
1483    ///
1484    /// @param text - the identifier as written
1485    /// @param quote - how it was quoted
1486    fn hash_of(&self, text: &[u8], quote: QuoteForm) -> u64 {
1487        use std::hash::BuildHasher;
1488        self.interned.hasher().hash_one((text, quote))
1489    }
1490
1491    /// Returns the index of an interned name equal to this one, when there is
1492    /// one.
1493    ///
1494    /// Every candidate filed under the hash is compared against what `names`
1495    /// already holds, so a hash two different identifiers share returns the
1496    /// right one rather than whichever was stored last.
1497    ///
1498    /// @param hash - what [`Ast::hash_of`] returned for the identifier
1499    /// @param text - the identifier as written
1500    /// @param quote - how it was quoted
1501    fn find_interned(&self, hash: u64, text: &[u8], quote: QuoteForm) -> Option<u32> {
1502        let candidates: &[u32] = match self.interned.get(&hash)? {
1503            Interned::One(index) => core::slice::from_ref(index),
1504            Interned::Several(indexes) => indexes.as_slice(),
1505        };
1506        candidates.iter().copied().find(|index| {
1507            self.names
1508                .get(*index as usize)
1509                .is_some_and(|name| name.quote == quote && name.text == text)
1510        })
1511    }
1512
1513    /// Files a newly interned name under its hash.
1514    ///
1515    /// @param hash - what [`Ast::hash_of`] returned for the identifier
1516    /// @param index - where the name was pushed in `names`
1517    fn remember_interned(&mut self, hash: u64, index: u32) {
1518        use std::collections::hash_map::Entry;
1519        match self.interned.entry(hash) {
1520            Entry::Vacant(slot) => {
1521                slot.insert(Interned::One(index));
1522            }
1523            Entry::Occupied(mut slot) => match slot.get_mut() {
1524                Interned::Several(indexes) => indexes.push(index),
1525                Interned::One(first) => {
1526                    let first = *first;
1527                    slot.insert(Interned::Several(vec![first, index]));
1528                }
1529            },
1530        }
1531    }
1532
1533    /// Moves every name's byte buffers onto the free list and empties `names`.
1534    ///
1535    /// [`Ast::clear`] is the only caller, and its comment carries the argument.
1536    ///
1537    /// **Drained rather than taken.** `core::mem::take` on `self.names` leaves
1538    /// a `Vec` with no capacity behind, which hands the allocator back the one
1539    /// thing `clear` exists to keep - and cost a 256-byte `RawVec<Name>` regrow
1540    /// on every warm compile while this function was written that way. The
1541    /// free list and the names are separate fields, so the drain and the pushes
1542    /// borrow disjointly and neither has to be given up.
1543    fn recycle_names(&mut self) {
1544        let spare = &mut self.spare;
1545        for name in self.names.drain(..) {
1546            Ast::keep_buffer(spare, name.text);
1547            Ast::keep_buffer(spare, name.folded);
1548        }
1549    }
1550
1551    /// Keeps one byte buffer for the next parse, or gives it back.
1552    ///
1553    /// A buffer with no capacity never allocated, so keeping it would fill the
1554    /// list with entries that save nothing.
1555    ///
1556    /// @param spare - the free list to put it on
1557    /// @param buffer - the buffer nothing holds any more
1558    fn keep_buffer(spare: &mut Vec<Vec<u8>>, mut buffer: Vec<u8>) {
1559        if spare.len() >= SPARE_NAME_BUFFERS
1560            || buffer.capacity() == 0
1561            || buffer.capacity() > SPARE_NAME_CAPACITY
1562        {
1563            return;
1564        }
1565        buffer.clear();
1566        spare.push(buffer);
1567    }
1568
1569    /// Returns an empty byte buffer, reusing one a previous parse left.
1570    ///
1571    /// The buffer may be shorter than what is about to go into it, in which
1572    /// case filling it reallocates - which is the one allocation a fresh `Vec`
1573    /// would have made anyway, so a spare that is too small costs nothing over
1574    /// having no spare at all.
1575    ///
1576    /// @param spare - the free list to take from
1577    fn take_buffer(spare: &mut Vec<Vec<u8>>) -> Vec<u8> {
1578        spare.pop().unwrap_or_default()
1579    }
1580
1581    /// Returns how many distinct identifiers have been interned.
1582    pub fn name_count(&self) -> usize {
1583        self.names.len()
1584    }
1585
1586    /// Returns the depth of the deepest expression tree in the arena.
1587    ///
1588    /// What `Limit::ExprDepth` is charged against. See `expr_depths`.
1589    pub fn max_expr_depth(&self) -> u32 {
1590        self.max_expr_depth
1591    }
1592
1593    /// Returns how deep one expression's own subtree is.
1594    ///
1595    /// @param id - the node
1596    pub fn expr_depth(&self, id: ExprId) -> u32 {
1597        self.expr_depths.get(id.0 as usize).copied().unwrap_or(0)
1598    }
1599
1600    /// Returns an interned name.
1601    pub fn name(&self, id: NameId) -> Option<&Name> {
1602        self.names.get(id.0 as usize)
1603    }
1604
1605    /// Returns the folded key of an interned name, or an empty slice.
1606    pub fn folded(&self, id: NameId) -> &[u8] {
1607        self.names.get(id.0 as usize).map_or(&[], |n| &n.folded)
1608    }
1609
1610    /// Returns the written spelling of an interned name, or an empty slice.
1611    pub fn text(&self, id: NameId) -> &[u8] {
1612        self.names.get(id.0 as usize).map_or(&[], |n| &n.text)
1613    }
1614
1615    /// Adds an expression node.
1616    pub fn add_expr(&mut self, expr: Expr, span: Span) -> ExprId {
1617        self.bytes = self
1618            .bytes
1619            .saturating_add(core::mem::size_of::<Expr>().saturating_add(8));
1620        let depth = self.depth_of(&expr);
1621        self.max_expr_depth = self.max_expr_depth.max(depth);
1622        self.exprs.push(expr);
1623        self.expr_spans.push(span);
1624        self.expr_depths.push(depth);
1625        ExprId(self.exprs.len().saturating_sub(1) as u32)
1626    }
1627
1628    /// Returns how deep a node about to be added is.
1629    ///
1630    /// One more than the deepest of its children. Every child is already in the
1631    /// arena - the parser builds bottom up - so this reads their recorded
1632    /// depths rather than walking them, which is what keeps `add_expr` the
1633    /// constant-time push it was.
1634    ///
1635    /// A subquery's depth is one: the `SELECT` it names has an expression arena
1636    /// of its own and its own `max_expr_depth`, and charging the outer tree for
1637    /// the inner one would refuse a shallow expression that happens to contain
1638    /// a deep query rather than the deep query itself.
1639    ///
1640    /// @param expr - the node
1641    fn depth_of(&self, expr: &Expr) -> u32 {
1642        let deepest = |ids: &[ExprId]| -> u32 {
1643            ids.iter().map(|id| self.expr_depth(*id)).max().unwrap_or(0)
1644        };
1645        let children = match expr {
1646            Expr::Literal(_)
1647            | Expr::Parameter { .. }
1648            | Expr::Column { .. }
1649            | Expr::Star { .. }
1650            | Expr::Exists { .. }
1651            | Expr::Subquery(_)
1652            | Expr::Raise { message: None, .. } => 0,
1653            Expr::Raise {
1654                message: Some(message),
1655                ..
1656            } => self.expr_depth(*message),
1657            Expr::Unary { operand, .. }
1658            | Expr::Collate { operand, .. }
1659            | Expr::Cast { operand, .. }
1660            | Expr::IsNull { operand, .. } => self.expr_depth(*operand),
1661            Expr::Binary { left, right, .. } | Expr::Is { left, right, .. } => {
1662                self.expr_depth(*left).max(self.expr_depth(*right))
1663            }
1664            Expr::Pattern {
1665                operand,
1666                pattern,
1667                escape,
1668                ..
1669            } => self
1670                .expr_depth(*operand)
1671                .max(self.expr_depth(*pattern))
1672                .max(escape.map(|id| self.expr_depth(id)).unwrap_or(0)),
1673            Expr::Between {
1674                operand, low, high, ..
1675            } => self
1676                .expr_depth(*operand)
1677                .max(self.expr_depth(*low))
1678                .max(self.expr_depth(*high)),
1679            Expr::In { operand, rhs, .. } => {
1680                let right = match rhs {
1681                    InRhs::List(ids) => deepest(ids),
1682                    InRhs::Select(_) => 0,
1683                    InRhs::Table { arguments, .. } => {
1684                        arguments.as_deref().map(deepest).unwrap_or(0)
1685                    }
1686                };
1687                self.expr_depth(*operand).max(right)
1688            }
1689            Expr::Case {
1690                operand,
1691                branches,
1692                otherwise,
1693            } => {
1694                let mut deep = operand.map(|id| self.expr_depth(id)).unwrap_or(0);
1695                for (when, then) in branches {
1696                    deep = deep.max(self.expr_depth(*when)).max(self.expr_depth(*then));
1697                }
1698                deep.max(otherwise.map(|id| self.expr_depth(id)).unwrap_or(0))
1699            }
1700            Expr::Function {
1701                arguments, filter, ..
1702            } => arguments
1703                .as_deref()
1704                .map(deepest)
1705                .unwrap_or(0)
1706                .max(filter.map(|id| self.expr_depth(id)).unwrap_or(0)),
1707            Expr::RowValue(ids) => deepest(ids),
1708        };
1709        children.saturating_add(1)
1710    }
1711
1712    /// Returns an expression node.
1713    pub fn expr(&self, id: ExprId) -> Option<&Expr> {
1714        self.exprs.get(id.0 as usize)
1715    }
1716
1717    /// Returns the span an expression was parsed from.
1718    pub fn expr_span(&self, id: ExprId) -> Span {
1719        self.expr_spans
1720            .get(id.0 as usize)
1721            .copied()
1722            .unwrap_or_default()
1723    }
1724
1725    /// Returns the number of expression nodes in the arena.
1726    pub fn expr_count(&self) -> usize {
1727        self.exprs.len()
1728    }
1729
1730    /// Adds a compound SELECT.
1731    pub fn add_select(&mut self, select: Select) -> SelectId {
1732        self.bytes = self
1733            .bytes
1734            .saturating_add(core::mem::size_of::<Select>().saturating_add(32));
1735        self.selects.push(select);
1736        SelectId(self.selects.len().saturating_sub(1) as u32)
1737    }
1738
1739    /// Returns a compound SELECT.
1740    pub fn select(&self, id: SelectId) -> Option<&Select> {
1741        self.selects.get(id.0 as usize)
1742    }
1743
1744    /// Adds one arm of a compound SELECT.
1745    pub fn add_core(&mut self, core: SelectCore) -> SelectCoreId {
1746        self.bytes = self
1747            .bytes
1748            .saturating_add(core::mem::size_of::<SelectCore>().saturating_add(64));
1749        self.cores.push(core);
1750        SelectCoreId(self.cores.len().saturating_sub(1) as u32)
1751    }
1752
1753    /// Returns one arm of a compound SELECT.
1754    pub fn core(&self, id: SelectCoreId) -> Option<&SelectCore> {
1755        self.cores.get(id.0 as usize)
1756    }
1757
1758    /// Adds a FROM term.
1759    pub fn add_from_term(&mut self, term: FromTerm) -> FromTermId {
1760        self.bytes = self
1761            .bytes
1762            .saturating_add(core::mem::size_of::<FromTerm>().saturating_add(32));
1763        self.from_terms.push(term);
1764        FromTermId(self.from_terms.len().saturating_sub(1) as u32)
1765    }
1766
1767    /// Returns a FROM term.
1768    pub fn from_term(&self, id: FromTermId) -> Option<&FromTerm> {
1769        self.from_terms.get(id.0 as usize)
1770    }
1771
1772    /// Returns a FROM term for modification.
1773    ///
1774    /// A join's `ON` or `USING` clause follows the table it constrains, so the
1775    /// term is stored first and its constraint attached once the parser has
1776    /// read it. Building the term out of order instead would mean holding a
1777    /// half-built node across a recursive parse.
1778    pub fn from_term_mut(&mut self, id: FromTermId) -> Option<&mut FromTerm> {
1779        self.from_terms.get_mut(id.0 as usize)
1780    }
1781
1782    /// Adds a window definition.
1783    pub fn add_window(&mut self, window: Window) -> WindowId {
1784        self.bytes = self
1785            .bytes
1786            .saturating_add(core::mem::size_of::<Window>().saturating_add(32));
1787        self.windows.push(window);
1788        WindowId(self.windows.len().saturating_sub(1) as u32)
1789    }
1790
1791    /// Returns a window definition.
1792    pub fn window(&self, id: WindowId) -> Option<&Window> {
1793        self.windows.get(id.0 as usize)
1794    }
1795}
1796
1797#[cfg(test)]
1798mod tests {
1799    use super::*;
1800
1801    /// Interning is by folded key *and* spelling, so `a` and `A` are two
1802    /// entries that compare equal by key rather than one entry that has
1803    /// forgotten which spelling reached it.
1804    #[test]
1805    fn interning_keeps_the_spelling_and_folds_the_key() {
1806        let mut ast = Ast::new();
1807        let lower = ast.intern(b"abc".to_vec(), QuoteForm::Bare, Span::default());
1808        let upper = ast.intern(b"ABC".to_vec(), QuoteForm::Bare, Span::default());
1809        let again = ast.intern(b"abc".to_vec(), QuoteForm::Bare, Span::default());
1810        assert_eq!(lower, again);
1811        assert_ne!(lower, upper);
1812        assert_eq!(ast.folded(lower), ast.folded(upper));
1813        assert_eq!(ast.text(upper), b"ABC");
1814    }
1815
1816    /// Every node id resolves, and an id from another arena does not panic.
1817    #[test]
1818    fn an_unknown_id_returns_none_rather_than_panicking() {
1819        let ast = Ast::new();
1820        assert!(ast.expr(ExprId(7)).is_none());
1821        assert!(ast.select(SelectId(7)).is_none());
1822        assert!(ast.name(NameId(7)).is_none());
1823        assert_eq!(ast.expr_span(ExprId(7)), Span::default());
1824    }
1825
1826    /// The charge grows with the arena, which is what the limit is checked
1827    /// against before a deep parse allocates.
1828    #[test]
1829    fn the_arena_charges_for_what_it_holds() {
1830        let mut ast = Ast::new();
1831        let before = ast.charged_bytes();
1832        ast.add_expr(Expr::Literal(Literal::Null), Span::default());
1833        assert!(ast.charged_bytes() > before);
1834    }
1835
1836    /// The same name written twice is one entry however it arrives, so the
1837    /// borrowed entry point and the owned one agree.
1838    #[test]
1839    fn the_borrowed_and_owned_entry_points_intern_the_same_name() {
1840        let mut ast = Ast::new();
1841        let owned = ast.intern(b"col".to_vec(), QuoteForm::Bare, Span::default());
1842        let borrowed = ast.intern_bytes(b"col", QuoteForm::Bare, Span::default());
1843        assert_eq!(owned, borrowed);
1844        assert_eq!(ast.name_count(), 1);
1845        assert_eq!(ast.text(owned), b"col");
1846        assert_eq!(ast.folded(owned), b"col");
1847    }
1848
1849    /// The quote form is part of what makes a name, so `x` and `"x"` are two
1850    /// entries even though they spell the same word.
1851    #[test]
1852    fn the_quote_form_separates_two_names_that_spell_the_same_word() {
1853        let mut ast = Ast::new();
1854        let bare = ast.intern_bytes(b"x", QuoteForm::Bare, Span::default());
1855        let quoted = ast.intern_bytes(b"x", QuoteForm::Double, Span::default());
1856        assert_ne!(bare, quoted);
1857        assert_eq!(ast.name_count(), 2);
1858        assert_eq!(
1859            ast.intern_bytes(b"x", QuoteForm::Bare, Span::default()),
1860            bare
1861        );
1862        assert_eq!(
1863            ast.intern_bytes(b"x", QuoteForm::Double, Span::default()),
1864            quoted
1865        );
1866    }
1867
1868    /// A name filed under another name's hash gets its own id.
1869    ///
1870    /// **The failure the map is keyed on a hash to avoid (task-2039).** A map
1871    /// that stored one index per hash and trusted it would answer `gamma` with
1872    /// `alpha`'s id here, and `NameId` equality is read as "the same name" -
1873    /// the binder resolves a column reference by comparing ids - so two
1874    /// different identifiers becoming one id is a wrong query rather than a
1875    /// slow one. A 64-bit collision cannot be produced by interning names, so
1876    /// the collision is filed by hand: `remember_interned` is exactly what
1877    /// `intern_bytes` calls, with the hash of a different name.
1878    #[test]
1879    fn a_name_filed_under_another_names_hash_gets_its_own_id() {
1880        let mut ast = Ast::new();
1881        let alpha = ast.intern_bytes(b"alpha", QuoteForm::Bare, Span::default());
1882        let stolen = ast.hash_of(b"gamma", QuoteForm::Bare);
1883        ast.remember_interned(stolen, alpha.0);
1884
1885        let gamma = ast.intern_bytes(b"gamma", QuoteForm::Bare, Span::default());
1886        assert_ne!(gamma, alpha);
1887        assert_eq!(ast.text(gamma), b"gamma");
1888        assert_eq!(ast.text(alpha), b"alpha");
1889
1890        // And both are still found, from the one slot that now holds both.
1891        assert_eq!(
1892            ast.intern_bytes(b"gamma", QuoteForm::Bare, Span::default()),
1893            gamma
1894        );
1895        assert_eq!(
1896            ast.intern_bytes(b"alpha", QuoteForm::Bare, Span::default()),
1897            alpha
1898        );
1899        assert_eq!(ast.name_count(), 2);
1900    }
1901
1902    /// Two hundred names all reach their own id and find it again.
1903    ///
1904    /// The map is keyed on a hash now, so "every name is distinct" is a claim
1905    /// about the candidate comparison rather than about the map, and a scan of
1906    /// a real number of names is what checks it.
1907    #[test]
1908    fn many_names_each_keep_their_own_id() {
1909        let mut ast = Ast::new();
1910        let spellings: Vec<Vec<u8>> = (0..200)
1911            .map(|nth| format!("column_{nth}").into_bytes())
1912            .collect();
1913        let ids: Vec<NameId> = spellings
1914            .iter()
1915            .map(|text| ast.intern_bytes(text, QuoteForm::Bare, Span::default()))
1916            .collect();
1917        assert_eq!(ast.name_count(), 200);
1918        for (text, id) in spellings.iter().zip(&ids) {
1919            assert_eq!(
1920                ast.intern_bytes(text, QuoteForm::Bare, Span::default()),
1921                *id
1922            );
1923            assert_eq!(ast.text(*id), text.as_slice());
1924        }
1925        let mut sorted = ids.clone();
1926        sorted.sort_unstable();
1927        sorted.dedup();
1928        assert_eq!(sorted.len(), 200);
1929    }
1930
1931    /// `clear` keeps the names' byte buffers and the names vector's capacity.
1932    ///
1933    /// **Both halves, because losing either one costs an allocation per warm
1934    /// compile (task-2039).** The buffers are what a second parse of the same
1935    /// statement fills instead of asking the allocator; the vector's capacity
1936    /// is what `clear` existed to keep in the first place, and a `clear` that
1937    /// moved the names out by `core::mem::take` silently gave it back.
1938    #[test]
1939    fn clearing_keeps_the_name_buffers_and_the_names_capacity() {
1940        let mut ast = Ast::new();
1941        for nth in 0..4u32 {
1942            ast.intern_bytes(
1943                format!("c{nth}").as_bytes(),
1944                QuoteForm::Bare,
1945                Span::default(),
1946            );
1947        }
1948        let capacity = ast.names.capacity();
1949        assert!(capacity >= 4);
1950
1951        ast.clear();
1952        assert_eq!(ast.name_count(), 0);
1953        assert_eq!(ast.names.capacity(), capacity);
1954        // Two buffers a name: the spelling and the folded key.
1955        assert_eq!(ast.spare.len(), 8);
1956        assert!(ast.spare.iter().all(|buffer| buffer.is_empty()));
1957
1958        // And the next parse takes them back rather than allocating.
1959        for nth in 0..4u32 {
1960            ast.intern_bytes(
1961                format!("c{nth}").as_bytes(),
1962                QuoteForm::Bare,
1963                Span::default(),
1964            );
1965        }
1966        assert_eq!(ast.spare.len(), 0);
1967        assert_eq!(ast.name_count(), 4);
1968        assert_eq!(ast.text(NameId(2)), b"c2");
1969    }
1970
1971    /// The free list is bounded, so a statement naming thousands of things
1972    /// does not leave the connection holding them.
1973    #[test]
1974    fn the_free_list_does_not_grow_without_bound() {
1975        let mut ast = Ast::new();
1976        for nth in 0..2_000u32 {
1977            ast.intern_bytes(
1978                format!("column_{nth}").as_bytes(),
1979                QuoteForm::Bare,
1980                Span::default(),
1981            );
1982        }
1983        ast.clear();
1984        assert_eq!(ast.spare.len(), SPARE_NAME_BUFFERS);
1985
1986        // A name longer than a buffer worth keeping is dropped rather than
1987        // held, so one enormous alias does not pin its bytes for ever.
1988        let mut ast = Ast::new();
1989        let long = vec![b'z'; SPARE_NAME_CAPACITY.saturating_add(1)];
1990        ast.intern_bytes(&long, QuoteForm::Bare, Span::default());
1991        ast.clear();
1992        assert_eq!(ast.spare.len(), 0);
1993    }
1994
1995    /// Two arenas holding the same nodes are equal, and the index behind them
1996    /// is not part of that.
1997    ///
1998    /// `Ast` compares by hand because `interned` is keyed on a hash each arena
1999    /// seeds for itself, so a derived comparison would report two identical
2000    /// parses as different (task-2039).
2001    #[test]
2002    fn two_arenas_holding_the_same_names_are_equal() {
2003        let mut one = Ast::new();
2004        let mut two = Ast::new();
2005        for text in [b"alpha".as_slice(), b"beta".as_slice()] {
2006            one.intern_bytes(text, QuoteForm::Bare, Span::default());
2007            two.intern_bytes(text, QuoteForm::Bare, Span::default());
2008        }
2009        assert_eq!(one, two);
2010
2011        two.intern_bytes(b"gamma", QuoteForm::Bare, Span::default());
2012        assert_ne!(one, two);
2013    }
2014}