packages/sql-semantics-sqlite/src/Lowering/Expression/ExpressionRule.php
1<?php
2
3declare(strict_types=1);
4
5namespace SqlSemantics\Platform\Sqlite\Lowering\Expression;
6
7use SqlParser\Lexer\Token;
8use SqlParser\Parser\Node;
9use SqlSemantics\Platform\Sqlite\Lowering\Lowering;
10use SqlSemantics\Platform\Sqlite\Model\Diagnostic\ImplementationGap;
11use SqlSemantics\Platform\Sqlite\Model\Lowering\Lists;
12use SqlSemantics\Platform\Sqlite\Model\Statement\Identifier\QualifiedName;
13use SqlSemantics\Platform\Sqlite\Model\Statement\Scalar;
14use SqlSemantics\Platform\Sqlite\Statement\Expression\BindParameter;
15use SqlSemantics\Platform\Sqlite\Statement\Expression\CaseBranch;
16use SqlSemantics\Platform\Sqlite\Statement\Expression\CaseExpression;
17use SqlSemantics\Platform\Sqlite\Statement\Expression\Cast;
18use SqlSemantics\Platform\Sqlite\Statement\Expression\Collate;
19use SqlSemantics\Platform\Sqlite\Statement\Expression\ColumnUse;
20use SqlSemantics\Platform\Sqlite\Statement\Expression\DoubleQuotedWord;
21use SqlSemantics\Platform\Sqlite\Statement\Expression\Grouped;
22use SqlSemantics\Platform\Sqlite\Statement\Expression\ParameterPrefix;
23use SqlSemantics\Platform\Sqlite\Statement\Expression\Raise;
24use SqlSemantics\Platform\Sqlite\Statement\Expression\RaiseAction;
25use SqlSemantics\Platform\Sqlite\Statement\Expression\RowExpression;
26use SqlSemantics\Platform\Sqlite\Statement\Expression\Subquery\Exists;
27use SqlSemantics\Platform\Sqlite\Statement\Expression\Subquery\ScalarSubquery;
28use SqlSemantics\Platform\Sqlite\Statement\Expression\TruthWord;
29
30/**
31 * Lowers expression productions into scalar structure.
32 *
33 * Rule: SQLITE-EXPR-001. Scope: expr (the forms that are no operator and no
34 * function call), exprlist, nexprlist, paren_exprlist, where_opt,
35 * case_operand, case_exprlist, case_else. Operands keep their written order
36 * and every parenthesis pair is kept as a grouping, so the structure states
37 * the evaluation order the parser chose. An unqualified word is a column
38 * use, a double-quoted word or a truth word by how it is written
39 * (SQLITE-DOUBLE-QUOTED-WORD-001, SQLITE-TRUTH-WORD-001). Terminates: every
40 * operand is a strict subtree and lists are flattened iteratively.
41 * Source: https://sqlite.org/lang_expr.html. Status: Implemented.
42 *
43 * @visibility SqlSemantics\Platform\Sqlite
44 */
45final class ExpressionRule
46{
47 private readonly OperatorRule $operators;
48
49 /**
50 * @param Lowering $lowering The lowering this rule belongs to
51 */
52 public function __construct(private readonly Lowering $lowering)
53 {
54 $this->operators = new OperatorRule($lowering);
55 }
56
57 /**
58 * Lowers one expression.
59 */
60 public function expression(Node $expression): Scalar
61 {
62 $form = $this->lowering->productions->form($expression);
63 $names = $this->lowering->names;
64
65 return match ($form->signature) {
66 'expr: term' => $this->term($form->node(0)),
67 'expr: LP expr RP' => new Grouped($this->expression($form->node(1))),
68 'expr: idj' => $this->word($form->token(0)),
69 'expr: nm DOT nm' => $this->column([$form->node(2), $form->node(0)]),
70 'expr: nm DOT nm DOT nm' => $this->column([$form->node(4), $form->node(2), $form->node(0)]),
71 'expr: VARIABLE' => $this->parameter($form->token(0)),
72 'expr: expr COLLATE ids' => new Collate($this->expression($form->node(0)), $names->token($form->token(2))),
73 'expr: CAST LP expr AS typetoken RP' => new Cast($this->expression($form->node(2)), $this->lowering->typeNames->named($form->node(4))),
74 'expr: LP nexprlist COMMA expr RP' => new RowExpression([...$this->items($form->node(1)), $this->expression($form->node(3))]),
75 'expr: LP select RP' => new ScalarSubquery($this->lowering->selects->select($form->node(1))),
76 'expr: EXISTS LP select RP' => new Exists($this->lowering->selects->select($form->node(2))),
77 'expr: CASE case_operand case_exprlist case_else END' => $this->conditional($form->node(1), $form->node(2), $form->node(3)),
78 'expr: RAISE LP IGNORE RP' => new Raise(RaiseAction::Ignore),
79 'expr: RAISE LP raisetype COMMA expr RP' => new Raise(RaiseAction::from($this->lowering->conflicts->raised($form->node(2))->value), $this->expression($form->node(4))),
80 default => $this->operators->expression($form),
81 };
82 }
83
84 /**
85 * Lowers a literal term.
86 */
87 public function term(Node $term): Scalar
88 {
89 return $this->lowering->literals->term($term);
90 }
91
92 /**
93 * Lowers an unqualified word by how it is written: in double quotes, as bare TRUE or FALSE, or as any other name.
94 */
95 public function word(Token $token): Scalar
96 {
97 if (str_starts_with($token->text, '"')) {
98 return new DoubleQuotedWord($this->lowering->names->token($token));
99 }
100 $truth = ['true' => true, 'false' => false][strtolower($token->text)] ?? null;
101 if ($truth !== null) {
102 return $this->lowering->leaves->record(new TruthWord($truth));
103 }
104
105 return new ColumnUse($this->lowering->names->token($token));
106 }
107
108 /**
109 * Lowers a qualified column use from its name nodes: the column, the table and the optional schema.
110 *
111 * @param array{0: Node, 1: Node, 2?: Node} $parts
112 */
113 public function column(array $parts): ColumnUse
114 {
115 $names = $this->lowering->names;
116 $schema = isset($parts[2]) ? $names->name($parts[2]) : null;
117 $table = $names->name($parts[1]);
118
119 return new ColumnUse($names->name($parts[0]), new QualifiedName($table, $schema));
120 }
121
122 /**
123 * Lowers a bind parameter token and records it as an operand leaf.
124 */
125 public function parameter(Token $token): BindParameter
126 {
127 return $this->lowering->leaves->record(new BindParameter(ParameterPrefix::from($token->text[0] ?? ''), substr($token->text, 1)));
128 }
129
130 /**
131 * Lowers a CASE expression from its operand, branches and ELSE part.
132 *
133 * @throws ImplementationGap When a production has no rule
134 */
135 public function conditional(Node $operand, Node $branches, Node $otherwise): CaseExpression
136 {
137 $productions = $this->lowering->productions;
138 $base = $productions->form($operand);
139 $list = $productions->form($branches);
140 $else = $productions->form($otherwise);
141 if (!in_array($base->signature, ['case_operand: expr', 'case_operand:'], true) || !in_array($list->signature, ['case_exprlist: case_exprlist WHEN expr THEN expr', 'case_exprlist: WHEN expr THEN expr'], true) || !in_array($else->signature, ['case_else: ELSE expr', 'case_else:'], true)) {
142 throw ImplementationGap::production($list);
143 }
144 $items = (new Lists())->items($branches);
145 $cases = [];
146 for ($index = 0; $index < count($items); $index += 2) {
147 $cases[] = new CaseBranch($this->expression($items[$index]), $this->expression($items[$index + 1]));
148 }
149
150 return new CaseExpression(
151 $base->signature === 'case_operand:' ? null : $this->expression($base->node(0)),
152 $cases,
153 $else->signature === 'case_else:' ? null : $this->expression($else->node(1)),
154 );
155 }
156
157 /**
158 * Lowers an `exprlist` into its expressions in written order.
159 *
160 * @return list<Scalar>
161 * @throws ImplementationGap When the production has no rule
162 */
163 public function list(Node $exprlist): array
164 {
165 $form = $this->lowering->productions->form($exprlist);
166
167 return match ($form->signature) {
168 'exprlist:' => [],
169 'exprlist: nexprlist' => $this->items($form->node(0)),
170 default => throw ImplementationGap::production($form),
171 };
172 }
173
174 /**
175 * Lowers a `nexprlist` into its expressions in written order.
176 *
177 * @return list<Scalar>
178 * @throws ImplementationGap When the production has no rule
179 */
180 public function items(Node $nexprlist): array
181 {
182 $form = $this->lowering->productions->form($nexprlist);
183 if ($form->signature !== 'nexprlist: nexprlist COMMA expr' && $form->signature !== 'nexprlist: expr') {
184 throw ImplementationGap::production($form);
185 }
186 $items = [];
187 foreach ((new Lists())->items($nexprlist) as $expression) {
188 $items[] = $this->expression($expression);
189 }
190
191 return $items;
192 }
193
194 /**
195 * Lowers a `paren_exprlist`: the expressions, or null when no parentheses are written.
196 *
197 * @return list<Scalar>|null
198 * @throws ImplementationGap When the production has no rule
199 */
200 public function optionalList(Node $list): ?array
201 {
202 $form = $this->lowering->productions->form($list);
203
204 return match ($form->signature) {
205 'paren_exprlist:' => null,
206 'paren_exprlist: LP exprlist RP' => $this->list($form->node(1)),
207 default => throw ImplementationGap::production($form),
208 };
209 }
210
211 /**
212 * Lowers a `where_opt`: the predicate, or null when the clause is absent.
213 *
214 * @throws ImplementationGap When the production has no rule
215 */
216 public function where(Node $where): ?Scalar
217 {
218 $form = $this->lowering->productions->form($where);
219
220 return match ($form->signature) {
221 'where_opt:' => null,
222 'where_opt: WHERE expr' => $this->expression($form->node(1)),
223 default => throw ImplementationGap::production($form),
224 };
225 }
226}
227