Skip to main content

rustlavel_view/
parser.rs

1//! Turning a token stream into a [`Template`].
2//!
3//! Every error a template author can make is caught here rather than at render
4//! time, and every one of them carries the file, line, and column: a view is
5//! edited by people who are not going to read a Rust backtrace.
6
7use crate::ast::{Branch, Node, Template, TemplateRef};
8use crate::expr::{self, Expr};
9use crate::lexer::{self, Token};
10use crate::source::{Span, line_column, syntax_error};
11use rustlavel_core::{Error, Result};
12use std::collections::BTreeMap;
13
14/// Lex and parse `source` as the view called `name`.
15pub fn parse(name: &str, source: &str) -> Result<Template> {
16    let mut parser = Parser {
17        tokens: lexer::tokenize(name, source)?,
18        pos: 0,
19        file: name,
20        source,
21        extends: None,
22        sections: BTreeMap::new(),
23    };
24
25    // With no stop set, `block` runs to the end of the file or fails trying.
26    let nodes = parser.block(&[])?;
27
28    Ok(Template {
29        name: name.to_string(),
30        nodes,
31        extends: parser.extends,
32        sections: parser.sections,
33    })
34}
35
36struct Parser<'a> {
37    tokens: Vec<Token>,
38    pos: usize,
39    file: &'a str,
40    source: &'a str,
41    extends: Option<TemplateRef>,
42    sections: BTreeMap<String, Vec<Node>>,
43}
44
45impl<'a> Parser<'a> {
46    /// Parse nodes until one of `stop` is reached; the stopping directive is
47    /// left for the caller to consume.
48    fn block(&mut self, stop: &[&str]) -> Result<Vec<Node>> {
49        let mut nodes = Vec::new();
50
51        while let Some(token) = self.tokens.get(self.pos).cloned() {
52            match &token {
53                Token::Text(text) => {
54                    self.pos += 1;
55                    nodes.push(Node::Text(text.clone()));
56                }
57                Token::Echo { source, offset, escaped } => {
58                    self.pos += 1;
59                    let expr = expr::parse(self.span(*offset, source.len()))?;
60                    nodes.push(Node::Echo { expr, escaped: *escaped });
61                }
62                Token::Directive { name, arguments, arguments_offset, offset } => {
63                    if stop.contains(&name.as_str()) {
64                        return Ok(nodes);
65                    }
66                    let span = self.span(*arguments_offset, arguments.len());
67                    let offset = *offset;
68                    self.pos += 1;
69                    match name.as_str() {
70                        "if" => nodes.push(self.conditional(span, offset)?),
71                        "foreach" => nodes.push(self.loop_over(span, offset)?),
72                        "section" => self.section(span, offset)?,
73                        "extends" => self.extends(span, offset)?,
74                        "yield" => nodes.push(self.yield_section(span)?),
75                        "lang" => nodes.push(self.lang(span)?),
76                        "include" => {
77                            let name = self.template_name(&span, "include")?;
78                            nodes.push(Node::Include(self.reference(name, offset)));
79                        }
80                        // Every remaining name closes a block that was never
81                        // opened — `@endif` on its own, and friends.
82                        _ => return Err(self.unexpected(&token)),
83                    }
84                }
85            }
86        }
87
88        Ok(nodes)
89    }
90
91    /// `@if(...) ... @elseif(...) ... @else ... @endif`.
92    fn conditional(&mut self, span: Span<'_>, offset: usize) -> Result<Node> {
93        const STOP: [&str; 3] = ["elseif", "else", "endif"];
94
95        let mut branches =
96            vec![Branch { condition: expr::parse(span)?, body: self.block(&STOP)? }];
97        let mut otherwise = None;
98
99        loop {
100            match self.tokens.get(self.pos).cloned() {
101                Some(Token::Directive { name, arguments, arguments_offset, .. })
102                    if name == "elseif" =>
103                {
104                    if otherwise.is_some() {
105                        return Err(self.here("`@elseif` cannot follow `@else`"));
106                    }
107                    let span = self.span(arguments_offset, arguments.len());
108                    self.pos += 1;
109                    branches.push(Branch {
110                        condition: expr::parse(span)?,
111                        body: self.block(&STOP)?,
112                    });
113                }
114                Some(Token::Directive { name, .. }) if name == "else" => {
115                    if otherwise.is_some() {
116                        return Err(self.here("`@else` appears twice in one `@if`"));
117                    }
118                    self.pos += 1;
119                    otherwise = Some(self.block(&STOP)?);
120                }
121                _ => break,
122            }
123        }
124
125        self.close("if", "endif", offset)?;
126        Ok(Node::If { branches, otherwise })
127    }
128
129    /// `@foreach(items as item) ... @endforeach`.
130    fn loop_over(&mut self, span: Span<'_>, offset: usize) -> Result<Node> {
131        let (subject, binding) = expr::parse_foreach(span)?;
132        let body = self.block(&["endforeach"])?;
133        self.close("foreach", "endforeach", offset)?;
134        Ok(Node::Foreach { subject, binding, body })
135    }
136
137    /// `@section("name") ... @endsection`, or the one-line
138    /// `@section("name", expr)` form.
139    fn section(&mut self, span: Span<'_>, offset: usize) -> Result<()> {
140        let arguments = expr::parse_arguments(span)?;
141        let name = self.literal(arguments.first(), &span, "section")?;
142
143        let body = match arguments.len() {
144            1 => {
145                let body = self.block(&["endsection"])?;
146                self.close("section", "endsection", offset)?;
147                body
148            }
149            2 => vec![Node::Echo { expr: arguments[1].clone(), escaped: true }],
150            _ => {
151                return Err(span.error(0, "`@section` takes a name and an optional value"));
152            }
153        };
154
155        // Two sections of one name in one file is always a mistake, and a
156        // silent "last one wins" is a miserable afternoon.
157        if self.sections.insert(name.clone(), body).is_some() {
158            return Err(syntax_error(
159                self.file,
160                self.source,
161                offset,
162                format!("`{name}` is defined by two `@section` blocks in this template"),
163            ));
164        }
165        Ok(())
166    }
167
168    /// `@extends("layouts.app")`.
169    fn extends(&mut self, span: Span<'_>, offset: usize) -> Result<()> {
170        let name = self.template_name(&span, "extends")?;
171        if self.extends.is_some() {
172            return Err(span.error(0, "a template can only `@extends` one layout"));
173        }
174        self.extends = Some(self.reference(name, offset));
175        Ok(())
176    }
177
178    /// `@yield("name")` or `@yield("name", "fallback")`.
179    fn yield_section(&mut self, span: Span<'_>) -> Result<Node> {
180        let arguments = expr::parse_arguments(span)?;
181        if arguments.len() > 2 {
182            return Err(span.error(0, "`@yield` takes a name and an optional fallback"));
183        }
184        Ok(Node::Yield {
185            section: self.literal(arguments.first(), &span, "yield")?,
186            default: arguments.get(1).cloned(),
187        })
188    }
189
190    /// `@lang("auth.sign_in")`, or with placeholders:
191    /// `@lang("auth.welcome", "name", user.name)`.
192    ///
193    /// Alternating name/value after the key rather than a map literal, because
194    /// this expression grammar has no map literal and inventing one for a
195    /// single directive is a worse trade than a convention. The names are
196    /// quoted like the key; the values are ordinary expressions, so a
197    /// placeholder can carry anything the page already has.
198    fn lang(&mut self, span: Span<'_>) -> Result<Node> {
199        let arguments = expr::parse_arguments(span)?;
200        let key = self.literal(arguments.first(), &span, "lang")?;
201
202        let rest = &arguments[1.min(arguments.len())..];
203        if rest.len() % 2 != 0 {
204            return Err(span.error(
205                0,
206                "`@lang` takes a key and then pairs of name and value, like \
207                 `@lang(\"mail.greeting\", \"name\", user.name)` — one name here has no value",
208            ));
209        }
210
211        let mut replacements = Vec::with_capacity(rest.len() / 2);
212        for pair in rest.chunks(2) {
213            let name = match &pair[0] {
214                Expr::Str(name) => name.clone(),
215                _ => {
216                    return Err(span.error(
217                        0,
218                        "a `@lang` placeholder name has to be quoted, like \
219                         `@lang(\"mail.greeting\", \"name\", user.name)`",
220                    ))
221                }
222            };
223            replacements.push((name, pair[1].clone()));
224        }
225
226        Ok(Node::Lang { key, replacements })
227    }
228
229    /// Read the single quoted view name a directive expects.
230    fn template_name(&self, span: &Span<'_>, directive: &str) -> Result<String> {
231        let arguments = expr::parse_arguments(*span)?;
232        if arguments.len() != 1 {
233            return Err(span.error(0, format!("`@{directive}` takes exactly one view name")));
234        }
235        self.literal(arguments.first(), span, directive)
236    }
237
238    /// Insist on a quoted literal: a view name is resolved at parse time, so it
239    /// cannot come from the data.
240    fn literal(&self, expr: Option<&Expr>, span: &Span<'_>, directive: &str) -> Result<String> {
241        match expr {
242            Some(Expr::Str(text)) => Ok(text.clone()),
243            _ => Err(span.error(
244                0,
245                format!("`@{directive}` needs a quoted name, like `@{directive}(\"layouts.app\")`"),
246            )),
247        }
248    }
249
250    fn reference(&self, name: String, offset: usize) -> TemplateRef {
251        let (line, column) = line_column(self.source, offset);
252        TemplateRef { name, file: self.file.to_string(), line, column }
253    }
254
255    /// A fragment of the source, borrowed from it rather than from `self` so
256    /// the parser can keep mutating while the span is in hand.
257    fn span(&self, offset: usize, len: usize) -> Span<'a> {
258        Span::new(self.file, self.source, offset, len)
259    }
260
261    /// Consume the directive that closes a block, blaming the opener when it
262    /// is missing — the opener is what the author has to go fix.
263    fn close(&mut self, opener: &str, closer: &str, offset: usize) -> Result<()> {
264        match self.tokens.get(self.pos) {
265            Some(Token::Directive { name, .. }) if name == closer => {
266                self.pos += 1;
267                Ok(())
268            }
269            _ => Err(syntax_error(
270                self.file,
271                self.source,
272                offset,
273                format!("`@{opener}` is never closed — add `@{closer}`"),
274            )),
275        }
276    }
277
278    /// An error at the token the parser is looking at.
279    fn here(&self, message: impl Into<String>) -> Error {
280        let offset = match self.tokens.get(self.pos) {
281            Some(Token::Directive { offset, .. }) | Some(Token::Echo { offset, .. }) => *offset,
282            _ => self.source.len(),
283        };
284        syntax_error(self.file, self.source, offset, message)
285    }
286
287    fn unexpected(&self, token: &Token) -> Error {
288        match token {
289            Token::Directive { name, offset, .. } => {
290                let opener = match name.as_str() {
291                    "endif" | "elseif" | "else" => "@if",
292                    "endforeach" => "@foreach",
293                    "endsection" => "@section",
294                    _ => "a block",
295                };
296                syntax_error(
297                    self.file,
298                    self.source,
299                    *offset,
300                    format!("`@{name}` has no matching `{opener}`"),
301                )
302            }
303            _ => self.here("unexpected token"),
304        }
305    }
306}
307
308#[cfg(test)]
309mod tests {
310    use super::*;
311
312    fn template(source: &str) -> Template {
313        parse("test", source).unwrap()
314    }
315
316    fn error(source: &str) -> (usize, usize, String) {
317        match parse("test", source).unwrap_err() {
318            Error::Template { line, column, message, .. } => (line, column, message),
319            other => panic!("expected a template error, got {other:?}"),
320        }
321    }
322
323    #[test]
324    fn builds_an_if_chain_with_every_arm() {
325        let nodes = template("@if(a)A@elseif(b)B@else C@endif").nodes;
326
327        match &nodes[0] {
328            Node::If { branches, otherwise } => {
329                assert_eq!(branches.len(), 2);
330                assert_eq!(branches[0].condition, Expr::Path("a".into()));
331                assert_eq!(branches[1].body, vec![Node::Text("B".into())]);
332                assert_eq!(otherwise.as_deref(), Some(&[Node::Text(" C".into())][..]));
333            }
334            other => panic!("expected an if, got {other:?}"),
335        }
336    }
337
338    #[test]
339    fn builds_a_foreach_with_its_binding() {
340        let nodes = template("@foreach(user.posts as post){{ post.title }}@endforeach").nodes;
341
342        match &nodes[0] {
343            Node::Foreach { subject, binding, body } => {
344                assert_eq!(subject, &Expr::Path("user.posts".into()));
345                assert_eq!(binding, "post");
346                assert_eq!(body.len(), 1);
347            }
348            other => panic!("expected a foreach, got {other:?}"),
349        }
350    }
351
352    #[test]
353    fn hoists_sections_out_of_the_node_stream() {
354        let parsed = template("@extends(\"layouts.app\")\n@section(\"body\")hi@endsection");
355
356        assert_eq!(parsed.extends.as_ref().map(|r| r.name.as_str()), Some("layouts.app"));
357        assert_eq!(parsed.sections["body"], vec![Node::Text("hi".into())]);
358        assert!(parsed.nodes.is_empty(), "{:?}", parsed.nodes);
359    }
360
361    #[test]
362    fn the_short_section_form_echoes_its_value() {
363        let parsed = template("@section(\"title\", page.name)");
364
365        assert_eq!(
366            parsed.sections["title"],
367            vec![Node::Echo { expr: Expr::Path("page.name".into()), escaped: true }]
368        );
369    }
370
371    #[test]
372    fn records_where_a_reference_was_written() {
373        let parsed = template("<p>\n  @include(\"parts.nav\")\n");
374
375        match &parsed.nodes[1] {
376            Node::Include(reference) => {
377                assert_eq!(reference.name, "parts.nav");
378                assert_eq!((reference.line, reference.column), (2, 3));
379            }
380            other => panic!("expected an include, got {other:?}"),
381        }
382    }
383
384    #[test]
385    fn an_unclosed_block_is_reported_at_the_line_it_opened() {
386        let (line, column, message) = error("<ul>\n@if(ready)\n  <li></li>\n</ul>\n");
387
388        assert_eq!((line, column), (2, 1));
389        assert!(message.contains("`@if` is never closed"), "{message}");
390    }
391
392    #[test]
393    fn a_stray_closing_directive_names_what_it_should_have_closed() {
394        let (line, _, message) = error("<p>ok</p>\n@endforeach\n");
395
396        assert_eq!(line, 2);
397        assert!(message.contains("@foreach"), "{message}");
398    }
399
400    #[test]
401    fn a_view_name_has_to_be_a_literal() {
402        let (_, _, message) = error("@include(page)");
403
404        assert!(message.contains("quoted name"), "{message}");
405    }
406
407    #[test]
408    fn two_sections_of_one_name_are_rejected() {
409        let (_, _, message) =
410            error("@section(\"a\")1@endsection\n@section(\"a\")2@endsection\n");
411
412        assert!(message.contains("two `@section`"), "{message}");
413    }
414
415    /// The key is resolved at parse time and cached with the template, so it
416    /// cannot come from the data — the same rule `@include` follows.
417    #[test]
418    fn a_lang_key_has_to_be_a_literal() {
419        let (_, _, message) = error(r#"@lang(key)"#);
420        assert!(message.contains("`@lang` needs a quoted name"), "{message}");
421    }
422
423    /// A placeholder without a value is a typo that would otherwise render the
424    /// name as if it were the phrase.
425    #[test]
426    fn a_lang_placeholder_needs_a_value() {
427        let (_, _, message) = error(r#"@lang("mail.greeting", "name")"#);
428        assert!(message.contains("no value"), "{message}");
429    }
430
431    #[test]
432    fn a_lang_placeholder_name_has_to_be_quoted() {
433        let (_, _, message) = error(r#"@lang("mail.greeting", name, user.name)"#);
434        assert!(message.contains("has to be quoted"), "{message}");
435    }
436
437    #[test]
438    fn a_lang_directive_keeps_its_key_and_pairs() {
439        let template = template(r#"@lang("auth.welcome", "name", user.name)"#);
440        match &template.nodes[0] {
441            Node::Lang { key, replacements } => {
442                assert_eq!(key, "auth.welcome");
443                assert_eq!(replacements.len(), 1);
444                assert_eq!(replacements[0].0, "name");
445            }
446            other => panic!("expected a Lang node, got {other:?}"),
447        }
448    }
449}