plotnik-compiler 0.3.2

Compiler for Plotnik query language (parser, analyzer, bytecode emitter)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
use rowan::{Checkpoint, TextRange};

use crate::diagnostics::DiagnosticKind;
use crate::parser::Parser;
use crate::parser::cst::token_sets::{
    ALT_RECOVERY_TOKENS, EXPR_FIRST_TOKENS, PREDICATE_OPS, SEPARATORS, SEQ_RECOVERY_TOKENS,
    TREE_RECOVERY_TOKENS,
};
use crate::parser::cst::{SyntaxKind, TokenSet};
use crate::parser::lexer::token_text;

use super::utils::capitalize_first;

impl Parser<'_, '_> {
    /// `(type ...)` | `(_ ...)` | `(ERROR)` | `(MISSING ...)` | `(RefName)` | `(expr/subtype)`
    /// PascalCase without children → Ref; with children → error but parses as Tree.
    pub(crate) fn parse_tree(&mut self) {
        let checkpoint = self.checkpoint();
        self.push_delimiter(SyntaxKind::ParenOpen);
        let open_paren_span = self.current_span(); // save span before bump
        self.bump(); // consume '('

        let mut is_ref = false;
        let mut ref_name: Option<String> = None;

        match self.current() {
            SyntaxKind::ParenClose => {
                // Empty tree `()` - validation phase will report EmptyTree error
                self.start_node_at(checkpoint, SyntaxKind::Tree);
            }
            SyntaxKind::Underscore => {
                self.start_node_at(checkpoint, SyntaxKind::Tree);
                self.bump();
            }
            SyntaxKind::Id => {
                let (r, n) = self.parse_tree_ref_or_node(checkpoint);
                is_ref = r;
                ref_name = n;
            }
            SyntaxKind::KwError => {
                self.parse_tree_error(checkpoint);
                return;
            }
            SyntaxKind::KwMissing => {
                self.parse_tree_missing(checkpoint);
                return;
            }
            _ => {
                // Tree-sitter style sequence: ((a) (b)) instead of {(a) (b)}
                // Parse as Seq so it works correctly, but warn to encourage {} syntax
                if self.currently_is_one_of(EXPR_FIRST_TOKENS) {
                    self.start_node_at(checkpoint, SyntaxKind::Seq);
                    self.diagnostics
                        .report(
                            self.source_id,
                            DiagnosticKind::TreeSitterSequenceSyntax,
                            open_paren_span,
                        )
                        .emit();
                } else {
                    self.start_node_at(checkpoint, SyntaxKind::Tree);
                }
            }
        }

        self.finish_tree_parsing(checkpoint, is_ref, ref_name);
    }

    fn parse_tree_ref_or_node(&mut self, checkpoint: Checkpoint) -> (bool, Option<String>) {
        let name = token_text(self.source, &self.tokens[self.pos]).to_string();
        let is_pascal_case = name.chars().next().is_some_and(|c| c.is_ascii_uppercase());
        self.bump();

        let mut is_ref = false;
        let mut ref_name = None;

        if is_pascal_case {
            is_ref = true;
            ref_name = Some(name);
        } else {
            self.start_node_at(checkpoint, SyntaxKind::Tree);
        }

        if self.currently_is(SyntaxKind::Slash) {
            if is_ref {
                self.start_node_at(checkpoint, SyntaxKind::Tree);
                self.error(DiagnosticKind::InvalidSupertypeSyntax);
                is_ref = false;
            }
            self.bump();
            match self.current() {
                SyntaxKind::Id => {
                    self.bump();
                }
                SyntaxKind::SingleQuote | SyntaxKind::DoubleQuote => {
                    self.bump_string_tokens();
                }
                _ => {
                    self.error(DiagnosticKind::ExpectedSubtype);
                }
            }
        }

        // Parse optional predicate: `(identifier == "foo")` or `(identifier =~ /pattern/)`
        if !is_ref && self.currently_is_one_of(PREDICATE_OPS) {
            self.parse_node_predicate();
        }

        (is_ref, ref_name)
    }

    /// Parse a node predicate: `== "value"`, `=~ /pattern/`, etc.
    fn parse_node_predicate(&mut self) {
        self.start_node(SyntaxKind::NodePredicate);

        // Consume the operator
        self.bump();

        // Parse the value (string or regex)
        match self.current() {
            SyntaxKind::SingleQuote | SyntaxKind::DoubleQuote => {
                self.bump_string_tokens();
            }
            SyntaxKind::RegexLiteral => {
                // Regex literal from compound token - wrap in Regex node
                self.start_node(SyntaxKind::Regex);
                self.bump();
                self.finish_node();
            }
            SyntaxKind::Slash => {
                // Standalone slash - parse as regex (fallback, shouldn't happen normally)
                self.parse_regex_literal();
            }
            _ => {
                self.error(DiagnosticKind::ExpectedPredicateValue);
            }
        }

        self.finish_node();
    }

    /// Parse a regex literal: `/pattern/`
    ///
    /// Regex literals consume all content verbatim (including whitespace and
    /// comment-like sequences) until an unescaped closing `/` is found.
    fn parse_regex_literal(&mut self) {
        self.start_node(SyntaxKind::Regex);
        self.bump(); // opening '/'

        let mut found_close = false;

        while !self.eof() && !self.has_fatal_error() {
            let kind = self.nth_raw(0);

            // Inside regex, include ALL tokens (trivia too)
            if kind != SyntaxKind::Slash {
                self.bump();
                continue;
            }

            // Check for escaped slash by counting trailing backslashes in source
            let slash_start: usize = self.tokens[self.pos].span.start().into();
            let backslash_count = self.source[..slash_start]
                .chars()
                .rev()
                .take_while(|&c| c == '\\')
                .count();

            // Odd number of backslashes means the slash is escaped
            if backslash_count % 2 == 1 {
                self.bump();
                continue;
            }

            found_close = true;
            break;
        }

        if found_close {
            self.bump(); // closing '/'
        } else {
            self.error(DiagnosticKind::UnclosedRegex);
        }

        self.finish_node();
    }

    fn parse_tree_error(&mut self, checkpoint: Checkpoint) {
        self.start_node_at(checkpoint, SyntaxKind::Tree);
        self.bump(); // KwError
        if !self.currently_is(SyntaxKind::ParenClose) {
            self.error(DiagnosticKind::ErrorTakesNoArguments);
            self.parse_children(SyntaxKind::ParenClose, TREE_RECOVERY_TOKENS);
        }
        self.pop_delimiter();
        self.expect(SyntaxKind::ParenClose, "closing ')' for (ERROR)");
        self.finish_node();
    }

    fn parse_tree_missing(&mut self, checkpoint: Checkpoint) {
        self.start_node_at(checkpoint, SyntaxKind::Tree);
        self.bump(); // KwMissing
        match self.current() {
            SyntaxKind::Id => {
                self.bump();
            }
            SyntaxKind::SingleQuote | SyntaxKind::DoubleQuote => {
                self.bump_string_tokens();
            }
            SyntaxKind::ParenClose => {}
            _ => {
                self.parse_children(SyntaxKind::ParenClose, TREE_RECOVERY_TOKENS);
            }
        }
        self.pop_delimiter();
        self.expect(SyntaxKind::ParenClose, "closing ')' for (MISSING)");
        self.finish_node();
    }

    fn finish_tree_parsing(
        &mut self,
        checkpoint: Checkpoint,
        is_ref: bool,
        ref_name: Option<String>,
    ) {
        let has_children = !self.currently_is(SyntaxKind::ParenClose);

        if is_ref && has_children {
            self.start_node_at(checkpoint, SyntaxKind::Tree);
            let children_start = self.current_span().start();
            self.parse_children(SyntaxKind::ParenClose, TREE_RECOVERY_TOKENS);
            let children_end = self.last_non_trivia_end().unwrap_or(children_start);
            let children_span = TextRange::new(children_start, children_end);

            if let Some(name) = &ref_name {
                self.diagnostics
                    .report(
                        self.source_id,
                        DiagnosticKind::RefCannotHaveChildren,
                        children_span,
                    )
                    .message(name)
                    .emit();
            }
        } else if is_ref {
            self.start_node_at(checkpoint, SyntaxKind::Ref);
        } else {
            self.parse_children(SyntaxKind::ParenClose, TREE_RECOVERY_TOKENS);
        }

        self.pop_delimiter();
        self.expect(
            SyntaxKind::ParenClose,
            if is_ref && !has_children {
                "closing ')' for reference"
            } else {
                "closing ')' for tree"
            },
        );
        self.finish_node();
    }

    fn parse_children(&mut self, until: SyntaxKind, recovery: TokenSet) {
        loop {
            if self.eof() {
                let (construct, kind) = match until {
                    SyntaxKind::ParenClose => ("node", DiagnosticKind::UnclosedTree),
                    SyntaxKind::BraceClose => ("sequence", DiagnosticKind::UnclosedSequence),
                    _ => panic!(
                        "parse_children: unexpected delimiter {:?} (only ParenClose/BraceClose supported)",
                        until
                    ),
                };
                let open = self.delimiter_stack.last().unwrap_or_else(|| {
                    panic!(
                        "parse_children: unclosed {construct} at EOF but delimiter_stack is empty \
                         (caller must push delimiter before calling)"
                    )
                });
                self.error_unclosed_delimiter(kind, format!("{construct} started here"), open.span);
                break;
            }
            if self.has_fatal_error() {
                break;
            }
            if self.currently_is(until) {
                break;
            }
            if self.currently_is_one_of(SEPARATORS) {
                self.error_skip_separator();
                continue;
            }
            if self.currently_is_one_of(EXPR_FIRST_TOKENS) {
                self.parse_expr();
                continue;
            }
            if self.currently_is(SyntaxKind::TsPredicate) {
                self.error_and_bump(DiagnosticKind::UnsupportedPredicate);
                continue;
            }
            if self.currently_is_one_of(recovery) {
                break;
            }
            self.error_and_bump_with_hint(
                DiagnosticKind::UnexpectedToken,
                "try `(child)` or close with `)`",
            );
        }
    }

    /// Alternation/choice: `[expr1 expr2 ...]` or `[Label: expr ...]`
    pub(crate) fn parse_alt(&mut self) {
        self.start_node(SyntaxKind::Alt);
        self.push_delimiter(SyntaxKind::BracketOpen);
        self.expect(SyntaxKind::BracketOpen, "opening '[' for alternation");

        self.parse_alt_children();

        self.pop_delimiter();
        self.expect(SyntaxKind::BracketClose, "closing ']' for alternation");
        self.finish_node();
    }

    /// Parse alternation children, handling both tagged `Label: expr` and unlabeled expressions.
    fn parse_alt_children(&mut self) {
        loop {
            if self.eof() {
                let open = self.delimiter_stack.last().unwrap_or_else(|| {
                    panic!(
                        "parse_alt_children: unclosed alternation at EOF but delimiter_stack is empty \
                         (caller must push delimiter before calling)"
                    )
                });
                self.error_unclosed_delimiter(
                    DiagnosticKind::UnclosedAlternation,
                    "alternation started here",
                    open.span,
                );
                break;
            }
            if self.has_fatal_error() {
                break;
            }
            if self.currently_is(SyntaxKind::BracketClose) {
                break;
            }
            if self.currently_is_one_of(SEPARATORS) {
                self.error_skip_separator();
                continue;
            }

            // LL(2): Id followed by Colon → branch label or field (check casing)
            if self.currently_is(SyntaxKind::Id) && self.next_is(SyntaxKind::Colon) {
                let text = token_text(self.source, &self.tokens[self.pos]);
                let first_char = text.chars().next().unwrap_or('a');
                if first_char.is_ascii_uppercase() {
                    self.parse_branch();
                } else {
                    self.parse_branch_lowercase_label();
                }
                continue;
            }
            // Anchors cannot appear directly in alternations - they create empty branches
            if self.currently_is(SyntaxKind::Dot) {
                self.error(DiagnosticKind::AnchorInAlternation);
                self.skip_token();
                continue;
            }
            if self.currently_is_one_of(EXPR_FIRST_TOKENS) {
                self.start_node(SyntaxKind::Branch);
                self.parse_expr();
                self.finish_node();
                continue;
            }
            if self.currently_is_one_of(ALT_RECOVERY_TOKENS) {
                break;
            }
            self.error_and_bump_with_hint(
                DiagnosticKind::UnexpectedToken,
                "try `(node)` or close with `]`",
            );
        }
    }

    /// Tagged alternation branch: `Label: expr`
    fn parse_branch(&mut self) {
        self.start_node(SyntaxKind::Branch);

        let span = self.current_span();
        let text = token_text(self.source, &self.tokens[self.pos]);
        self.bump();
        self.validate_branch_label(text, span);

        self.expect(SyntaxKind::Colon, "':' after branch label");

        if self.currently_is_one_of(EXPR_FIRST_TOKENS) {
            self.parse_expr();
        } else {
            self.error(DiagnosticKind::ExpectedExpression);
        }

        self.finish_node();
    }

    /// Parse a branch with lowercase label - parse as Branch but emit error.
    fn parse_branch_lowercase_label(&mut self) {
        self.start_node(SyntaxKind::Branch);

        let span = self.current_span();
        let label_text = token_text(self.source, &self.tokens[self.pos]);
        let capitalized = capitalize_first(label_text);

        self.error_with_fix(
            DiagnosticKind::LowercaseBranchLabel,
            span,
            "branch labels map to enum variants",
            format!("use `{}`", capitalized),
            capitalized,
        );

        self.bump();
        self.expect(SyntaxKind::Colon, "':' after branch label");

        if self.currently_is_one_of(EXPR_FIRST_TOKENS) {
            self.parse_expr();
        } else {
            self.error(DiagnosticKind::ExpectedExpression);
        }

        self.finish_node();
    }

    /// Sibling sequence: `{expr1 expr2 ...}`
    pub(crate) fn parse_seq(&mut self) {
        self.start_node(SyntaxKind::Seq);
        self.push_delimiter(SyntaxKind::BraceOpen);
        self.expect(SyntaxKind::BraceOpen, "opening '{' for sequence");

        self.parse_children(SyntaxKind::BraceClose, SEQ_RECOVERY_TOKENS);

        self.pop_delimiter();
        self.expect(SyntaxKind::BraceClose, "closing '}' for sequence");
        self.finish_node();
    }

    /// Skip a separator token (comma or pipe) and emit helpful error.
    fn error_skip_separator(&mut self) {
        let kind = self.current();
        let span = self.current_span();
        // Invariant: only called when SEPARATORS.contains(kind), which only has Comma and Pipe
        let char_name = match kind {
            SyntaxKind::Comma => ",",
            SyntaxKind::Pipe => "|",
            _ => panic!(
                "error_skip_separator: unexpected token {:?} (only Comma/Pipe expected)",
                kind
            ),
        };
        self.error_with_fix(
            DiagnosticKind::InvalidSeparator,
            span,
            format!("plotnik uses whitespace, not `{}`", char_name),
            "remove",
            "",
        );
        self.skip_token();
    }
}