blade-syntax 0.1.0

Lossless parser for Laravel Blade templates
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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
//! Builds a lossless rowan tree from the lexer's tokens.

use std::collections::HashSet;

use rowan::{GreenNode, GreenNodeBuilder, TextRange, TextSize};

use crate::SyntaxKind::{self, *};
use crate::SyntaxNode;
use crate::blocks::{
    BlockSpec, block_for_opener, custom_conditionals, is_builtin_closer, is_known_directive,
};
use crate::lexer::lex;

/// The result of parsing: a syntax tree that always reproduces the input exactly,
/// plus any problems found along the way.
#[derive(Debug, Clone)]
pub struct Parse {
    green: GreenNode,
    errors: Vec<ParseError>,
}

impl Parse {
    pub fn syntax(&self) -> SyntaxNode {
        SyntaxNode::new_root(self.green.clone())
    }

    pub fn errors(&self) -> &[ParseError] {
        &self.errors
    }
}

/// A problem in the template, such as an unclosed echo or block.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParseError {
    pub message: String,
    pub range: TextRange,
}

/// Parses Blade source. Never fails: problems are reported in [`Parse::errors`].
pub fn parse(text: &str) -> Parse {
    let tokens = lex(text);
    let names: HashSet<String> = tokens
        .iter()
        .filter(|(kind, _)| *kind == DIRECTIVE_NAME)
        .map(|(_, text)| text[1..].to_ascii_lowercase())
        .collect();
    let mut p = Parser {
        tokens,
        pos: 0,
        offset: TextSize::from(0),
        builder: GreenNodeBuilder::new(),
        errors: Vec::new(),
        stack: Vec::new(),
        custom: custom_conditionals(&names),
    };
    p.builder.start_node(ROOT.into());
    while !p.at_end() {
        p.item();
    }
    while let Some(frame) = p.stack.pop() {
        p.close_unfinished(frame);
    }
    p.builder.finish_node();
    Parse {
        green: p.builder.finish(),
        errors: p.errors,
    }
}

struct Parser<'a> {
    tokens: Vec<(SyntaxKind, &'a str)>,
    pos: usize,
    /// Byte offset of the current token in the input.
    offset: TextSize,
    builder: GreenNodeBuilder<'static>,
    errors: Vec<ParseError>,
    /// Blocks, tags and quoted values that are open, innermost last.
    stack: Vec<Frame>,
    /// Custom conditionals inferred for this file (see `blocks::custom_conditionals`).
    custom: HashSet<String>,
}

enum Frame {
    /// An open `BLOCK` and `BODY` node.
    Block {
        kind: BlockKind,
        /// The opener as written, e.g. `@pushOnce`, and where it is.
        name: String,
        range: TextRange,
    },
    /// An open `TAG` or `END_TAG` node.
    Tag {
        /// `<div` or `</div`, as written.
        name: String,
        /// Where the `<` or `</` is.
        range: TextRange,
    },
    /// An open `ATTR_VALUE` node, inside an open `ATTRIBUTE` if `in_attribute`.
    Value {
        in_attribute: bool,
        quote: char,
        /// Where the opening quote is.
        range: TextRange,
    },
}

impl Frame {
    /// Tags and quoted values are boundaries: a block can't be continued or closed
    /// from inside one that it doesn't contain.
    fn is_boundary(&self) -> bool {
        !matches!(self, Self::Block { .. })
    }
}

enum BlockKind {
    Builtin(&'static BlockSpec),
    /// A `Blade::if` conditional named `X`: `@X` / `@unlessX`, `@elseX`, `@endX`.
    Custom(String),
}

impl BlockKind {
    fn accepts_middle(&self, name: &str) -> bool {
        match self {
            Self::Builtin(spec) => spec.middle.contains(&name),
            Self::Custom(x) => name == "else" || name.strip_prefix("else") == Some(x),
        }
    }

    fn accepts_close(&self, name: &str) -> bool {
        match self {
            Self::Builtin(spec) => spec.close.contains(&name),
            Self::Custom(x) => name.strip_prefix("end") == Some(x),
        }
    }

    fn first_closer(&self) -> String {
        match self {
            Self::Builtin(spec) => spec.close[0].to_string(),
            Self::Custom(x) => format!("end{x}"),
        }
    }
}

impl Parser<'_> {
    fn item(&mut self) {
        match self.current() {
            Some(ECHO_OPEN) => self.delimited(ECHO, ECHO_CLOSE, "unclosed echo: expected }}"),
            Some(RAW_ECHO_OPEN) => {
                self.delimited(RAW_ECHO, RAW_ECHO_CLOSE, "unclosed raw echo: expected !!}")
            }
            Some(PHP_OPEN) => {
                // PHP allows omitting `?>` at the end of a file, so no error here.
                self.builder.start_node(PHP_TAG.into());
                self.bump();
                self.eat(PHP);
                self.eat(PHP_CLOSE);
                self.builder.finish_node();
            }
            Some(DIRECTIVE_NAME) => self.directive_item(),
            Some(TAG_OPEN) => self.open_tag(TAG),
            Some(END_TAG_OPEN) => self.open_tag(END_TAG),
            Some(TAG_CLOSE | TAG_SELF_CLOSE) => self.close_tag(),
            Some(ATTR_NAME) => self.attribute(),
            Some(QUOTE) => self.quote(),
            _ => self.bump(),
        }
    }

    /// `<` or `</` and the tag name. The node stays open until `>` or `/>`.
    fn open_tag(&mut self, node: SyntaxKind) {
        // A tag that starts before the previous one's `>` leaves that one unfinished.
        if matches!(self.stack.last(), Some(Frame::Tag { .. })) {
            let tag = self.stack.pop().expect("checked last");
            self.close_unfinished(tag);
        }
        let range = self.current_range();
        let mut name = self.current_text().to_string();
        self.builder.start_node(node.into());
        self.bump();
        if self.current() == Some(TAG_NAME) {
            name.push_str(self.current_text());
            self.bump();
        }
        self.stack.push(Frame::Tag { name, range });
    }

    /// `>` or `/>` ends the innermost tag. Blocks opened inside it are left unclosed.
    fn close_tag(&mut self) {
        let Some(i) = self
            .stack
            .iter()
            .rposition(|f| matches!(f, Frame::Tag { .. }))
        else {
            self.bump();
            return;
        };
        self.close_inner_frames(i);
        self.stack.pop();
        self.bump();
        self.builder.finish_node(); // TAG or END_TAG
    }

    /// `name`, or `name = value` where the value is quoted, unquoted text or an echo.
    fn attribute(&mut self) {
        self.builder.start_node(ATTRIBUTE.into());
        self.bump();
        let ws = usize::from(self.current() == Some(WHITESPACE));
        if self.nth(ws) != Some(EQ) {
            self.builder.finish_node();
            return;
        }
        self.eat(WHITESPACE);
        self.bump(); // EQ
        self.eat(WHITESPACE);
        match self.current() {
            Some(QUOTE) => {
                // ATTRIBUTE stays open until the value's closing quote.
                self.open_value(true);
                return;
            }
            Some(TEXT) => self.bump(),
            Some(ECHO_OPEN | RAW_ECHO_OPEN) => self.item(),
            _ => {}
        }
        self.builder.finish_node();
    }

    /// A quote closes the innermost open value, or opens a value with no attribute
    /// name before it (as in `{{ $name }}="x"`).
    fn quote(&mut self) {
        let open_value = self
            .stack
            .iter()
            .rposition(Frame::is_boundary)
            .and_then(|i| match self.stack[i] {
                Frame::Value { in_attribute, .. } => Some((i, in_attribute)),
                _ => None,
            });
        if let Some((i, in_attribute)) = open_value {
            self.close_inner_frames(i);
            self.stack.pop();
            self.bump();
            self.builder.finish_node(); // ATTR_VALUE
            if in_attribute {
                self.builder.finish_node(); // ATTRIBUTE
            }
        } else {
            self.open_value(false);
        }
    }

    fn open_value(&mut self, in_attribute: bool) {
        let range = self.current_range();
        let quote = self.current_text().chars().next().unwrap_or('"');
        self.builder.start_node(ATTR_VALUE.into());
        self.bump();
        self.stack.push(Frame::Value {
            in_attribute,
            quote,
            range,
        });
    }

    /// Before a middle or closer applies to the block at stack index `i`: tags opened
    /// inside it end here as partial `TAG` nodes, with no error, since the rest of the
    /// tag follows the block. Blocks opened inside it are reported as unclosed.
    fn close_split_tags(&mut self, i: usize) {
        while self.stack.len() > i + 1 {
            match self.stack.pop().expect("checked length") {
                Frame::Tag { .. } => self.builder.finish_node(), // TAG or END_TAG
                inner => self.close_unfinished(inner),
            }
        }
    }

    /// Closes, with errors, every frame above stack index `i`.
    fn close_inner_frames(&mut self, i: usize) {
        while self.stack.len() > i + 1 {
            let inner = self.stack.pop().expect("checked length");
            self.close_unfinished(inner);
        }
    }

    /// An opener, optional PHP content, and the closer (or an error at the opener).
    fn delimited(&mut self, node: SyntaxKind, close: SyntaxKind, message: &str) {
        self.builder.start_node(node.into());
        let open = self.current_range();
        self.bump();
        self.eat(PHP);
        if !self.eat(close) {
            self.error(message, open);
        }
        self.builder.finish_node();
    }

    fn directive_item(&mut self) {
        match self.current_text() {
            // The lexer only gives these names a raw body when spelled exactly like this.
            "@verbatim" => self.raw_block(VERBATIM, TEXT, "@endverbatim"),
            "@php" if self.is_php_block() => self.raw_block(PHP_BLOCK, PHP, "@endphp"),
            _ => self.block_directive(),
        }
    }

    /// A directive that may open, continue or close a block.
    fn block_directive(&mut self) {
        let name = self.current_text()[1..].to_ascii_lowercase();
        // A block can be continued or closed from inside tags it opened (Blade splits
        // tags across branches), but not from inside a quoted value: the value's node
        // would have to end in the middle of the block.
        let reachable = self
            .stack
            .iter()
            .rposition(|f| matches!(f, Frame::Value { .. }))
            .map_or(0, |i| i + 1);
        let innermost_block = self.stack[reachable..]
            .iter()
            .rposition(|f| matches!(f, Frame::Block { .. }))
            .map(|i| reachable + i);
        if let Some(kind) = self.opener(&name) {
            self.open_block(kind);
        } else if let Some(i) = innermost_block.filter(
            |&i| matches!(&self.stack[i], Frame::Block { kind, .. } if kind.accepts_middle(&name)),
        ) {
            self.close_split_tags(i);
            self.builder.finish_node(); // BODY
            self.directive();
            self.builder.start_node(BODY.into());
        } else if let Some(i) = self.stack[reachable..]
            .iter()
            .rposition(|f| matches!(f, Frame::Block { kind, .. } if kind.accepts_close(&name)))
        {
            self.close_split_tags(reachable + i);
            self.close_block(reachable + i);
        } else {
            let range = self.current_range();
            let text = self.current_text().to_string();
            self.directive();
            let custom_closer = name
                .strip_prefix("end")
                .is_some_and(|x| self.custom.contains(x));
            if is_builtin_closer(&name) || custom_closer {
                self.error(&format!("{text} without a matching opener"), range);
            }
        }
    }

    fn opener(&self, name: &str) -> Option<BlockKind> {
        if let Some(spec) = block_for_opener(name, self.lookahead_args()) {
            return Some(BlockKind::Builtin(spec));
        }
        let custom = name.strip_prefix("unless").unwrap_or(name);
        self.custom
            .contains(custom)
            .then(|| BlockKind::Custom(custom.to_string()))
    }

    /// The `DIRECTIVE_ARGS` text belonging to the directive name at the cursor.
    fn lookahead_args(&self) -> Option<&str> {
        let mut i = self.pos + 1;
        if matches!(self.tokens.get(i), Some((WHITESPACE, _))) {
            i += 1;
        }
        match self.tokens.get(i) {
            Some((DIRECTIVE_ARGS, text)) => Some(text),
            _ => None,
        }
    }

    fn open_block(&mut self, kind: BlockKind) {
        let frame = Frame::Block {
            kind,
            name: self.current_text().to_string(),
            range: self.current_range(),
        };
        self.builder.start_node(BLOCK.into());
        self.directive();
        self.builder.start_node(BODY.into());
        self.stack.push(frame);
    }

    /// Closes the block at stack index `i` with the closer at the cursor. Blocks opened
    /// inside it are left unclosed and reported.
    fn close_block(&mut self, i: usize) {
        self.close_inner_frames(i);
        self.stack.pop();
        self.builder.finish_node(); // BODY
        self.directive();
        self.builder.finish_node(); // BLOCK
    }

    /// Finishes the nodes of a frame that never got its closer, and reports it.
    fn close_unfinished(&mut self, frame: Frame) {
        match frame {
            Frame::Block { kind, name, range } => {
                self.builder.finish_node(); // BODY
                self.builder.finish_node(); // BLOCK
                let closer = kind.first_closer();
                self.error(&format!("unclosed {name}: expected @{closer}"), range);
            }
            Frame::Tag { name, range } => {
                self.builder.finish_node(); // TAG or END_TAG
                self.error(&format!("unclosed tag {name}>: expected >"), range);
            }
            Frame::Value {
                in_attribute,
                quote,
                range,
            } => {
                self.builder.finish_node(); // ATTR_VALUE
                if in_attribute {
                    self.builder.finish_node(); // ATTRIBUTE
                }
                self.error(
                    &format!("unclosed attribute value: expected {quote}"),
                    range,
                );
            }
        }
    }

    /// `@php` without arguments is the block form. The lexer then follows it with the
    /// raw body, the `@endphp`, or nothing at all.
    fn is_php_block(&self) -> bool {
        match self.tokens.get(self.pos + 1) {
            None | Some((PHP, _)) => true,
            Some((DIRECTIVE_NAME, text)) => *text == "@endphp",
            Some(_) => false,
        }
    }

    fn raw_block(&mut self, node: SyntaxKind, body: SyntaxKind, closer: &str) {
        self.builder.start_node(node.into());
        let opener = self.current_range();
        let name = self.current_text().to_string();
        // Raw-block names never take arguments, so text after them isn't checked.
        self.directive_node();
        self.eat(body);
        if self.current() == Some(DIRECTIVE_NAME) && self.current_text() == closer {
            self.directive_node();
        } else {
            self.error(&format!("unclosed {name}: expected {closer}"), opener);
        }
        self.builder.finish_node();
    }

    /// A directive, then a check for unclosed arguments if it's a name Blade knows.
    fn directive(&mut self) {
        let known = is_known_directive(&self.current_text()[1..].to_ascii_lowercase());
        self.directive_node();
        if known {
            self.check_unclosed_args();
        }
    }

    /// `DIRECTIVE_NAME (WHITESPACE? DIRECTIVE_ARGS)?`
    fn directive_node(&mut self) {
        self.builder.start_node(DIRECTIVE.into());
        self.bump();
        if self.current() == Some(WHITESPACE) {
            self.bump();
        }
        self.eat(DIRECTIVE_ARGS);
        self.builder.finish_node();
    }

    /// The lexer leaves unbalanced arguments as text, e.g. `@if($a` gives `TEXT "($a"`.
    fn check_unclosed_args(&mut self) {
        if self.current() != Some(TEXT) {
            return;
        }
        let text = self.current_text();
        let spaces = text.len() - text.trim_start_matches([' ', '\t']).len();
        if text[spaces..].starts_with('(') {
            let start = self.offset + TextSize::from(spaces as u32);
            let end = self.offset + TextSize::of(text);
            self.error(
                "unclosed ( in directive arguments",
                TextRange::new(start, end),
            );
        }
    }

    fn current(&self) -> Option<SyntaxKind> {
        self.nth(0)
    }

    /// The kind of the token `n` places after the cursor.
    fn nth(&self, n: usize) -> Option<SyntaxKind> {
        self.tokens.get(self.pos + n).map(|(kind, _)| *kind)
    }

    fn current_text(&self) -> &str {
        self.tokens.get(self.pos).map_or("", |(_, text)| text)
    }

    fn current_range(&self) -> TextRange {
        TextRange::at(self.offset, TextSize::of(self.current_text()))
    }

    fn at_end(&self) -> bool {
        self.pos >= self.tokens.len()
    }

    fn bump(&mut self) {
        let (kind, text) = self.tokens[self.pos];
        self.builder.token(kind.into(), text);
        self.offset += TextSize::of(text);
        self.pos += 1;
    }

    fn eat(&mut self, kind: SyntaxKind) -> bool {
        if self.current() == Some(kind) {
            self.bump();
            true
        } else {
            false
        }
    }

    fn error(&mut self, message: &str, range: TextRange) {
        self.errors.push(ParseError {
            message: message.to_string(),
            range,
        });
    }
}