Skip to main content

blade_syntax/
parser.rs

1//! Builds a lossless rowan tree from the lexer's tokens.
2
3use std::collections::HashSet;
4
5use rowan::{GreenNode, GreenNodeBuilder, TextRange, TextSize};
6
7use crate::SyntaxKind::{self, *};
8use crate::SyntaxNode;
9use crate::blocks::{
10    BlockSpec, block_for_opener, custom_conditionals, is_builtin_closer, is_known_directive,
11};
12use crate::lexer::lex;
13
14/// The result of parsing: a syntax tree that always reproduces the input exactly,
15/// plus any problems found along the way.
16#[derive(Debug, Clone)]
17pub struct Parse {
18    green: GreenNode,
19    errors: Vec<ParseError>,
20}
21
22impl Parse {
23    pub fn syntax(&self) -> SyntaxNode {
24        SyntaxNode::new_root(self.green.clone())
25    }
26
27    pub fn errors(&self) -> &[ParseError] {
28        &self.errors
29    }
30}
31
32/// A problem in the template, such as an unclosed echo or block.
33#[derive(Debug, Clone, PartialEq, Eq)]
34pub struct ParseError {
35    pub message: String,
36    pub range: TextRange,
37}
38
39/// Parses Blade source. Never fails: problems are reported in [`Parse::errors`].
40pub fn parse(text: &str) -> Parse {
41    let tokens = lex(text);
42    let names: HashSet<String> = tokens
43        .iter()
44        .filter(|(kind, _)| *kind == DIRECTIVE_NAME)
45        .map(|(_, text)| text[1..].to_ascii_lowercase())
46        .collect();
47    let mut p = Parser {
48        tokens,
49        pos: 0,
50        offset: TextSize::from(0),
51        builder: GreenNodeBuilder::new(),
52        errors: Vec::new(),
53        stack: Vec::new(),
54        custom: custom_conditionals(&names),
55    };
56    p.builder.start_node(ROOT.into());
57    while !p.at_end() {
58        p.item();
59    }
60    while let Some(frame) = p.stack.pop() {
61        p.close_unfinished(frame);
62    }
63    p.builder.finish_node();
64    Parse {
65        green: p.builder.finish(),
66        errors: p.errors,
67    }
68}
69
70struct Parser<'a> {
71    tokens: Vec<(SyntaxKind, &'a str)>,
72    pos: usize,
73    /// Byte offset of the current token in the input.
74    offset: TextSize,
75    builder: GreenNodeBuilder<'static>,
76    errors: Vec<ParseError>,
77    /// Blocks, tags and quoted values that are open, innermost last.
78    stack: Vec<Frame>,
79    /// Custom conditionals inferred for this file (see `blocks::custom_conditionals`).
80    custom: HashSet<String>,
81}
82
83enum Frame {
84    /// An open `BLOCK` and `BODY` node.
85    Block {
86        kind: BlockKind,
87        /// The opener as written, e.g. `@pushOnce`, and where it is.
88        name: String,
89        range: TextRange,
90    },
91    /// An open `TAG` or `END_TAG` node.
92    Tag {
93        /// `<div` or `</div`, as written.
94        name: String,
95        /// Where the `<` or `</` is.
96        range: TextRange,
97    },
98    /// An open `ATTR_VALUE` node, inside an open `ATTRIBUTE` if `in_attribute`.
99    Value {
100        in_attribute: bool,
101        quote: char,
102        /// Where the opening quote is.
103        range: TextRange,
104    },
105}
106
107impl Frame {
108    /// Tags and quoted values are boundaries: a block can't be continued or closed
109    /// from inside one that it doesn't contain.
110    fn is_boundary(&self) -> bool {
111        !matches!(self, Self::Block { .. })
112    }
113}
114
115enum BlockKind {
116    Builtin(&'static BlockSpec),
117    /// A `Blade::if` conditional named `X`: `@X` / `@unlessX`, `@elseX`, `@endX`.
118    Custom(String),
119}
120
121impl BlockKind {
122    fn accepts_middle(&self, name: &str) -> bool {
123        match self {
124            Self::Builtin(spec) => spec.middle.contains(&name),
125            Self::Custom(x) => name == "else" || name.strip_prefix("else") == Some(x),
126        }
127    }
128
129    fn accepts_close(&self, name: &str) -> bool {
130        match self {
131            Self::Builtin(spec) => spec.close.contains(&name),
132            Self::Custom(x) => name.strip_prefix("end") == Some(x),
133        }
134    }
135
136    fn first_closer(&self) -> String {
137        match self {
138            Self::Builtin(spec) => spec.close[0].to_string(),
139            Self::Custom(x) => format!("end{x}"),
140        }
141    }
142}
143
144impl Parser<'_> {
145    fn item(&mut self) {
146        match self.current() {
147            Some(ECHO_OPEN) => self.delimited(ECHO, ECHO_CLOSE, "unclosed echo: expected }}"),
148            Some(RAW_ECHO_OPEN) => {
149                self.delimited(RAW_ECHO, RAW_ECHO_CLOSE, "unclosed raw echo: expected !!}")
150            }
151            Some(PHP_OPEN) => {
152                // PHP allows omitting `?>` at the end of a file, so no error here.
153                self.builder.start_node(PHP_TAG.into());
154                self.bump();
155                self.eat(PHP);
156                self.eat(PHP_CLOSE);
157                self.builder.finish_node();
158            }
159            Some(DIRECTIVE_NAME) => self.directive_item(),
160            Some(TAG_OPEN) => self.open_tag(TAG),
161            Some(END_TAG_OPEN) => self.open_tag(END_TAG),
162            Some(TAG_CLOSE | TAG_SELF_CLOSE) => self.close_tag(),
163            Some(ATTR_NAME) => self.attribute(),
164            Some(QUOTE) => self.quote(),
165            _ => self.bump(),
166        }
167    }
168
169    /// `<` or `</` and the tag name. The node stays open until `>` or `/>`.
170    fn open_tag(&mut self, node: SyntaxKind) {
171        // A tag that starts before the previous one's `>` leaves that one unfinished.
172        if matches!(self.stack.last(), Some(Frame::Tag { .. })) {
173            let tag = self.stack.pop().expect("checked last");
174            self.close_unfinished(tag);
175        }
176        let range = self.current_range();
177        let mut name = self.current_text().to_string();
178        self.builder.start_node(node.into());
179        self.bump();
180        if self.current() == Some(TAG_NAME) {
181            name.push_str(self.current_text());
182            self.bump();
183        }
184        self.stack.push(Frame::Tag { name, range });
185    }
186
187    /// `>` or `/>` ends the innermost tag. Blocks opened inside it are left unclosed.
188    fn close_tag(&mut self) {
189        let Some(i) = self
190            .stack
191            .iter()
192            .rposition(|f| matches!(f, Frame::Tag { .. }))
193        else {
194            self.bump();
195            return;
196        };
197        self.close_inner_frames(i);
198        self.stack.pop();
199        self.bump();
200        self.builder.finish_node(); // TAG or END_TAG
201    }
202
203    /// `name`, or `name = value` where the value is quoted, unquoted text or an echo.
204    fn attribute(&mut self) {
205        self.builder.start_node(ATTRIBUTE.into());
206        self.bump();
207        let ws = usize::from(self.current() == Some(WHITESPACE));
208        if self.nth(ws) != Some(EQ) {
209            self.builder.finish_node();
210            return;
211        }
212        self.eat(WHITESPACE);
213        self.bump(); // EQ
214        self.eat(WHITESPACE);
215        match self.current() {
216            Some(QUOTE) => {
217                // ATTRIBUTE stays open until the value's closing quote.
218                self.open_value(true);
219                return;
220            }
221            Some(TEXT) => self.bump(),
222            Some(ECHO_OPEN | RAW_ECHO_OPEN) => self.item(),
223            _ => {}
224        }
225        self.builder.finish_node();
226    }
227
228    /// A quote closes the innermost open value, or opens a value with no attribute
229    /// name before it (as in `{{ $name }}="x"`).
230    fn quote(&mut self) {
231        let open_value = self
232            .stack
233            .iter()
234            .rposition(Frame::is_boundary)
235            .and_then(|i| match self.stack[i] {
236                Frame::Value { in_attribute, .. } => Some((i, in_attribute)),
237                _ => None,
238            });
239        if let Some((i, in_attribute)) = open_value {
240            self.close_inner_frames(i);
241            self.stack.pop();
242            self.bump();
243            self.builder.finish_node(); // ATTR_VALUE
244            if in_attribute {
245                self.builder.finish_node(); // ATTRIBUTE
246            }
247        } else {
248            self.open_value(false);
249        }
250    }
251
252    fn open_value(&mut self, in_attribute: bool) {
253        let range = self.current_range();
254        let quote = self.current_text().chars().next().unwrap_or('"');
255        self.builder.start_node(ATTR_VALUE.into());
256        self.bump();
257        self.stack.push(Frame::Value {
258            in_attribute,
259            quote,
260            range,
261        });
262    }
263
264    /// Before a middle or closer applies to the block at stack index `i`: tags opened
265    /// inside it end here as partial `TAG` nodes, with no error, since the rest of the
266    /// tag follows the block. Blocks opened inside it are reported as unclosed.
267    fn close_split_tags(&mut self, i: usize) {
268        while self.stack.len() > i + 1 {
269            match self.stack.pop().expect("checked length") {
270                Frame::Tag { .. } => self.builder.finish_node(), // TAG or END_TAG
271                inner => self.close_unfinished(inner),
272            }
273        }
274    }
275
276    /// Closes, with errors, every frame above stack index `i`.
277    fn close_inner_frames(&mut self, i: usize) {
278        while self.stack.len() > i + 1 {
279            let inner = self.stack.pop().expect("checked length");
280            self.close_unfinished(inner);
281        }
282    }
283
284    /// An opener, optional PHP content, and the closer (or an error at the opener).
285    fn delimited(&mut self, node: SyntaxKind, close: SyntaxKind, message: &str) {
286        self.builder.start_node(node.into());
287        let open = self.current_range();
288        self.bump();
289        self.eat(PHP);
290        if !self.eat(close) {
291            self.error(message, open);
292        }
293        self.builder.finish_node();
294    }
295
296    fn directive_item(&mut self) {
297        match self.current_text() {
298            // The lexer only gives these names a raw body when spelled exactly like this.
299            "@verbatim" => self.raw_block(VERBATIM, TEXT, "@endverbatim"),
300            "@php" if self.is_php_block() => self.raw_block(PHP_BLOCK, PHP, "@endphp"),
301            _ => self.block_directive(),
302        }
303    }
304
305    /// A directive that may open, continue or close a block.
306    fn block_directive(&mut self) {
307        let name = self.current_text()[1..].to_ascii_lowercase();
308        // A block can be continued or closed from inside tags it opened (Blade splits
309        // tags across branches), but not from inside a quoted value: the value's node
310        // would have to end in the middle of the block.
311        let reachable = self
312            .stack
313            .iter()
314            .rposition(|f| matches!(f, Frame::Value { .. }))
315            .map_or(0, |i| i + 1);
316        let innermost_block = self.stack[reachable..]
317            .iter()
318            .rposition(|f| matches!(f, Frame::Block { .. }))
319            .map(|i| reachable + i);
320        if let Some(kind) = self.opener(&name) {
321            self.open_block(kind);
322        } else if let Some(i) = innermost_block.filter(
323            |&i| matches!(&self.stack[i], Frame::Block { kind, .. } if kind.accepts_middle(&name)),
324        ) {
325            self.close_split_tags(i);
326            self.builder.finish_node(); // BODY
327            self.directive();
328            self.builder.start_node(BODY.into());
329        } else if let Some(i) = self.stack[reachable..]
330            .iter()
331            .rposition(|f| matches!(f, Frame::Block { kind, .. } if kind.accepts_close(&name)))
332        {
333            self.close_split_tags(reachable + i);
334            self.close_block(reachable + i);
335        } else {
336            let range = self.current_range();
337            let text = self.current_text().to_string();
338            self.directive();
339            let custom_closer = name
340                .strip_prefix("end")
341                .is_some_and(|x| self.custom.contains(x));
342            if is_builtin_closer(&name) || custom_closer {
343                self.error(&format!("{text} without a matching opener"), range);
344            }
345        }
346    }
347
348    fn opener(&self, name: &str) -> Option<BlockKind> {
349        if let Some(spec) = block_for_opener(name, self.lookahead_args()) {
350            return Some(BlockKind::Builtin(spec));
351        }
352        let custom = name.strip_prefix("unless").unwrap_or(name);
353        self.custom
354            .contains(custom)
355            .then(|| BlockKind::Custom(custom.to_string()))
356    }
357
358    /// The `DIRECTIVE_ARGS` text belonging to the directive name at the cursor.
359    fn lookahead_args(&self) -> Option<&str> {
360        let mut i = self.pos + 1;
361        if matches!(self.tokens.get(i), Some((WHITESPACE, _))) {
362            i += 1;
363        }
364        match self.tokens.get(i) {
365            Some((DIRECTIVE_ARGS, text)) => Some(text),
366            _ => None,
367        }
368    }
369
370    fn open_block(&mut self, kind: BlockKind) {
371        let frame = Frame::Block {
372            kind,
373            name: self.current_text().to_string(),
374            range: self.current_range(),
375        };
376        self.builder.start_node(BLOCK.into());
377        self.directive();
378        self.builder.start_node(BODY.into());
379        self.stack.push(frame);
380    }
381
382    /// Closes the block at stack index `i` with the closer at the cursor. Blocks opened
383    /// inside it are left unclosed and reported.
384    fn close_block(&mut self, i: usize) {
385        self.close_inner_frames(i);
386        self.stack.pop();
387        self.builder.finish_node(); // BODY
388        self.directive();
389        self.builder.finish_node(); // BLOCK
390    }
391
392    /// Finishes the nodes of a frame that never got its closer, and reports it.
393    fn close_unfinished(&mut self, frame: Frame) {
394        match frame {
395            Frame::Block { kind, name, range } => {
396                self.builder.finish_node(); // BODY
397                self.builder.finish_node(); // BLOCK
398                let closer = kind.first_closer();
399                self.error(&format!("unclosed {name}: expected @{closer}"), range);
400            }
401            Frame::Tag { name, range } => {
402                self.builder.finish_node(); // TAG or END_TAG
403                self.error(&format!("unclosed tag {name}>: expected >"), range);
404            }
405            Frame::Value {
406                in_attribute,
407                quote,
408                range,
409            } => {
410                self.builder.finish_node(); // ATTR_VALUE
411                if in_attribute {
412                    self.builder.finish_node(); // ATTRIBUTE
413                }
414                self.error(
415                    &format!("unclosed attribute value: expected {quote}"),
416                    range,
417                );
418            }
419        }
420    }
421
422    /// `@php` without arguments is the block form. The lexer then follows it with the
423    /// raw body, the `@endphp`, or nothing at all.
424    fn is_php_block(&self) -> bool {
425        match self.tokens.get(self.pos + 1) {
426            None | Some((PHP, _)) => true,
427            Some((DIRECTIVE_NAME, text)) => *text == "@endphp",
428            Some(_) => false,
429        }
430    }
431
432    fn raw_block(&mut self, node: SyntaxKind, body: SyntaxKind, closer: &str) {
433        self.builder.start_node(node.into());
434        let opener = self.current_range();
435        let name = self.current_text().to_string();
436        // Raw-block names never take arguments, so text after them isn't checked.
437        self.directive_node();
438        self.eat(body);
439        if self.current() == Some(DIRECTIVE_NAME) && self.current_text() == closer {
440            self.directive_node();
441        } else {
442            self.error(&format!("unclosed {name}: expected {closer}"), opener);
443        }
444        self.builder.finish_node();
445    }
446
447    /// A directive, then a check for unclosed arguments if it's a name Blade knows.
448    fn directive(&mut self) {
449        let known = is_known_directive(&self.current_text()[1..].to_ascii_lowercase());
450        self.directive_node();
451        if known {
452            self.check_unclosed_args();
453        }
454    }
455
456    /// `DIRECTIVE_NAME (WHITESPACE? DIRECTIVE_ARGS)?`
457    fn directive_node(&mut self) {
458        self.builder.start_node(DIRECTIVE.into());
459        self.bump();
460        if self.current() == Some(WHITESPACE) {
461            self.bump();
462        }
463        self.eat(DIRECTIVE_ARGS);
464        self.builder.finish_node();
465    }
466
467    /// The lexer leaves unbalanced arguments as text, e.g. `@if($a` gives `TEXT "($a"`.
468    fn check_unclosed_args(&mut self) {
469        if self.current() != Some(TEXT) {
470            return;
471        }
472        let text = self.current_text();
473        let spaces = text.len() - text.trim_start_matches([' ', '\t']).len();
474        if text[spaces..].starts_with('(') {
475            let start = self.offset + TextSize::from(spaces as u32);
476            let end = self.offset + TextSize::of(text);
477            self.error(
478                "unclosed ( in directive arguments",
479                TextRange::new(start, end),
480            );
481        }
482    }
483
484    fn current(&self) -> Option<SyntaxKind> {
485        self.nth(0)
486    }
487
488    /// The kind of the token `n` places after the cursor.
489    fn nth(&self, n: usize) -> Option<SyntaxKind> {
490        self.tokens.get(self.pos + n).map(|(kind, _)| *kind)
491    }
492
493    fn current_text(&self) -> &str {
494        self.tokens.get(self.pos).map_or("", |(_, text)| text)
495    }
496
497    fn current_range(&self) -> TextRange {
498        TextRange::at(self.offset, TextSize::of(self.current_text()))
499    }
500
501    fn at_end(&self) -> bool {
502        self.pos >= self.tokens.len()
503    }
504
505    fn bump(&mut self) {
506        let (kind, text) = self.tokens[self.pos];
507        self.builder.token(kind.into(), text);
508        self.offset += TextSize::of(text);
509        self.pos += 1;
510    }
511
512    fn eat(&mut self, kind: SyntaxKind) -> bool {
513        if self.current() == Some(kind) {
514            self.bump();
515            true
516        } else {
517            false
518        }
519    }
520
521    fn error(&mut self, message: &str, range: TextRange) {
522        self.errors.push(ParseError {
523            message: message.to_string(),
524            range,
525        });
526    }
527}