packages/sql-semantics-mysql/src/Lowering/TableDefinition/Spine.php
1<?php
2
3declare(strict_types=1);
4
5namespace SqlSemantics\Platform\MySql\Lowering\TableDefinition;
6
7use SqlParser\Parser\Node;
8use SqlSemantics\Platform\MySql\Lowering\Lowering;
9use SqlSemantics\Platform\MySql\Model\Diagnostic\ImplementationGap;
10
11/**
12 * Flattens the recursive list rules of the table definition family and checks every production of the spine.
13 *
14 * Rule: MYSQL-TABLE-DEFINITION-LIST-001. A list node and every nested node
15 * of the same rule must match one of the list productions the caller names;
16 * the nodes of the rules the caller asks for are returned in source order,
17 * separators and noise rules left out. Terminates: an explicit stack over
18 * strict subtrees.
19 * Source: https://dev.mysql.com/doc/refman/8.4/en/create-table.html. Status: Implemented.
20 *
21 * @visibility SqlSemantics\Platform\MySql
22 */
23final class Spine
24{
25 /**
26 * @param Lowering $lowering The lowering this rule belongs to
27 */
28 public function __construct(private readonly Lowering $lowering)
29 {
30 }
31
32 /**
33 * Answers the item nodes of a list in source order.
34 *
35 * @param list<string> $signatures The productions of the list rule
36 * @param list<string> $items The rule names of the items to return
37 * @return list<Node>
38 * @throws ImplementationGap When a spine node matches another production
39 */
40 public function items(Node $list, array $signatures, array $items): array
41 {
42 $found = [];
43 $pending = [$list];
44 while ($pending !== []) {
45 $current = array_pop($pending);
46 if (!$current instanceof Node) {
47 continue;
48 }
49 if ($current->name === $list->name) {
50 $form = $this->lowering->productions->form($current);
51 if (!in_array($form->signature, $signatures, true)) {
52 throw ImplementationGap::production($form);
53 }
54 for ($index = count($current->children) - 1; $index >= 0; $index--) {
55 $pending[] = $current->children[$index];
56 }
57 } elseif (in_array($current->name, $items, true)) {
58 $found[] = $current;
59 }
60 }
61
62 return $found;
63 }
64}
65