packages/sql-formatter/src/Core/Syntax/Document.php

1<?php
2
3declare(strict_types=1);
4
5namespace SqlFormatter\Core\Syntax;
6
7use SqlParser\Lexer\Token;
8use SqlParser\Parser\Node;
9
10/**
11 * Tokens and grammar-derived layout marks, indexed in source order.
12 *
13 * @visibility SqlFormatter
14 */
15final class Document
16{
17    /**
18     * @var list<Token>
19     */
20    public array $tokens = [];
21    /**
22     * @var array<int, int> Clause start to last keyword token
23     */
24    public array $clauses = [];
25    /**
26     * @var array<int, true>
27     */
28    public array $commas = [];
29    /**
30     * @var array<int, true>
31     */
32    public array $logical = [];
33    /**
34     * @var array<int, true>
35     */
36    public array $unary = [];
37    /**
38     * @var array<int, int> Parenthesis pairs
39     */
40    public array $pairs = [];
41    /**
42     * @var array<int, true>
43     */
44    public array $blocks = [];
45    /**
46     * @var array<int, int>
47     */
48    public array $casePairs = [];
49    /**
50     * @var array<int, true>
51     */
52    public array $caseBranches = [];
53
54    /**
55     * Retains trivia following the root node.
56     */
57    public function __construct(public readonly string $trailing)
58    {
59    }
60
61    /**
62     * Collects tokens and determines grammar and nesting boundaries.
63     */
64    public static function from(Node $tree, Rules $rules): self
65    {
66        $document = new self($tree->trailing);
67        (new Analyzer($document, $rules))->visit($tree);
68        Brackets::mark($document);
69        return $document;
70    }
71
72}
73