Skip to main content

laravel_template_engine/
validate.rs

1//! Checks a template before it's saved: syntax, variables, loops, filters and settings, with
2//! messages for the person editing it.
3
4use std::collections::HashMap;
5
6use minijinja::machinery::ast::{self, CallArg, Expr, Stmt};
7use minijinja::machinery::{Span, parse};
8use minijinja::syntax::SyntaxConfig;
9use serde::Serialize;
10
11use crate::assets::Assets;
12use crate::config::TemplateEngineConfig;
13use crate::filters::{self, category_name, check_date_format, plural_categories};
14use crate::render::PAPERS;
15use crate::sandbox::{ArgKind, FUNCTIONS, FilterSpec, InputKind, TESTS};
16use crate::schema::{Field, Node, TypeInfo, find_type};
17use crate::template::{DocumentFormat, Kind, Settings, TemplateInput};
18
19/// One mistake in a template, for an editor to show next to the field.
20#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
21pub struct Issue {
22    /// Where: `name`, `content.uk.body`, `settings.to.1` and so on.
23    pub field: String,
24    /// The line in the field's text, from 1, for mistakes in a template's text.
25    pub line: Option<u32>,
26    /// The column in that line, from 1.
27    pub column: Option<u32>,
28    /// What kind of mistake, for code: `syntax`, `unknown_variable`, `not_a_list` and so on.
29    pub code: &'static str,
30    /// What's wrong, in words for the person editing the template.
31    pub message: String,
32    /// A fix, such as the variable that was probably meant.
33    pub suggestion: Option<String>,
34}
35
36impl Issue {
37    fn new(field: impl Into<String>, code: &'static str, message: impl Into<String>) -> Self {
38        Self {
39            field: field.into(),
40            line: None,
41            column: None,
42            code,
43            message: message.into(),
44            suggestion: None,
45        }
46    }
47
48    fn at(mut self, span: Span) -> Self {
49        self.line = Some(u32::from(span.start_line));
50        self.column = Some(u32::from(span.start_col) + 1);
51        self
52    }
53
54    fn suggest(mut self, suggestion: Option<String>) -> Self {
55        if let Some(suggestion) = &suggestion {
56            self.message = format!("{} Did you mean `{suggestion}`?", self.message);
57        }
58        self.suggestion = suggestion;
59        self
60    }
61}
62
63impl std::fmt::Display for Issue {
64    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
65        match self.line {
66            Some(line) => write!(f, "{} (line {line}): {}", self.field, self.message),
67            None => write!(f, "{}: {}", self.field, self.message),
68        }
69    }
70}
71
72/// Checks everything that doesn't need the database.
73/// What every text of a template is checked against.
74struct Context<'a> {
75    info: &'a TypeInfo,
76    filters: &'a [FilterSpec],
77    images: &'a [String],
78    layouts: &'a [String],
79    channels: &'a [String],
80    /// Whether pictures end up in a PDF, which can't load them from the internet.
81    pdf: bool,
82    config: &'a TemplateEngineConfig,
83}
84
85pub(crate) fn check_input(input: &TemplateInput, assets: &Assets, config: &TemplateEngineConfig) -> Vec<Issue> {
86    let mut issues = Vec::new();
87    let Some(info) = find_type(&input.type_key) else {
88        let keys: Vec<String> = crate::schema::types().iter().map(|t| t.key.to_owned()).collect();
89        let issue = Issue::new(
90            "type_key",
91            "unknown_type",
92            format!("There's no template type `{}`.", input.type_key),
93        );
94        issues.push(issue.suggest(closest(&input.type_key, keys.iter().map(String::as_str))));
95        return issues;
96    };
97    if input.name.trim().is_empty() {
98        issues.push(Issue::new("name", "required", "Give the template a name."));
99    }
100    if input.content.is_empty() {
101        issues.push(Issue::new(
102            "content",
103            "required",
104            "Add the text in at least one language.",
105        ));
106    }
107
108    let mut filters = filters::builtin();
109    filters.extend(assets.filters.iter().map(|f| f.spec.clone()));
110    let images = assets.image_names();
111    let layouts = assets.layout_names();
112    let channels = assets.channel_names();
113    let pdf = matches!(&input.settings, Settings::Document(d) if d.format == DocumentFormat::Pdf);
114    let ctx = Context {
115        info: &info,
116        filters: &filters,
117        images: &images,
118        layouts: &layouts,
119        channels: &channels,
120        pdf,
121        config,
122    };
123    for (locale, content) in &input.content {
124        let prefix = format!("content.{locale}");
125        if filters::icu_locale(locale).id.language.as_str() == "und" {
126            issues.push(Issue::new(
127                &prefix,
128                "unknown_locale",
129                format!("`{locale}` isn't a language code such as `uk` or `en`."),
130            ));
131            continue;
132        }
133        if input.kind() == Kind::Mail {
134            if content.subject.trim().is_empty() {
135                issues.push(Issue::new(
136                    format!("{prefix}.subject"),
137                    "required",
138                    "Write the subject.",
139                ));
140            }
141            check_text(
142                &mut issues,
143                &format!("{prefix}.subject"),
144                &content.subject,
145                &ctx,
146                locale,
147            );
148        }
149        if input.kind() == Kind::Notification && !content.subject.is_empty() {
150            check_text(
151                &mut issues,
152                &format!("{prefix}.subject"),
153                &content.subject,
154                &ctx,
155                locale,
156            );
157        }
158        if content.body.trim().is_empty() {
159            issues.push(Issue::new(format!("{prefix}.body"), "required", "Write the text."));
160        }
161        check_text(&mut issues, &format!("{prefix}.body"), &content.body, &ctx, locale);
162    }
163
164    let locale = input
165        .content
166        .keys()
167        .next()
168        .map_or(config.locale.as_str(), String::as_str);
169    check_settings(&mut issues, input, &ctx, locale);
170    issues
171}
172
173fn check_settings(issues: &mut Vec<Issue>, input: &TemplateInput, ctx: &Context<'_>, locale: &str) {
174    let info = ctx.info;
175    let layout = match &input.settings {
176        Settings::Mail(mail) => mail.layout.as_deref(),
177        Settings::Document(document) => document.layout.as_deref(),
178        _ => None,
179    };
180    if let Some(name) = layout.filter(|name| !ctx.layouts.iter().any(|l| l == name)) {
181        let message = if ctx.layouts.is_empty() {
182            format!("There's no layout `{name}`; developers add layouts in code.")
183        } else {
184            format!("There's no layout `{name}`.")
185        };
186        let suggestion = closest(name, ctx.layouts.iter().map(String::as_str));
187        issues.push(Issue::new("settings.layout", "unknown_layout", message).suggest(suggestion));
188    }
189    if let Settings::Document(document) = &input.settings {
190        check_document_style(issues, document);
191    }
192    match &input.settings {
193        Settings::Mail(mail) => {
194            if mail.to.is_empty() {
195                issues.push(Issue::new("settings.to", "required", "Choose who gets the email."));
196            }
197            let recipients = info.recipients();
198            for (list, entries) in [("to", &mail.to), ("cc", &mail.cc), ("bcc", &mail.bcc)] {
199                for (i, entry) in entries.iter().enumerate() {
200                    check_recipient(issues, &format!("settings.{list}.{i}"), entry, &recipients);
201                }
202            }
203            for (field, value) in [("settings.from", &mail.from), ("settings.reply_to", &mail.reply_to)] {
204                if let Some(address) = value.as_deref().filter(|a| !a.trim().is_empty())
205                    && parse_address(address).is_none()
206                {
207                    issues.push(Issue::new(
208                        field,
209                        "invalid_address",
210                        format!("`{address}` isn't an email address."),
211                    ));
212                }
213            }
214        }
215        Settings::Document(document) => {
216            if !PAPERS
217                .iter()
218                .any(|(name, ..)| *name == document.paper.to_ascii_lowercase())
219            {
220                let issue = Issue::new(
221                    "settings.paper",
222                    "invalid_paper",
223                    format!("`{}` isn't a paper size.", document.paper),
224                );
225                issues.push(issue.suggest(closest(&document.paper, PAPERS.iter().map(|(name, ..)| *name))));
226            }
227            if document.filename.trim().is_empty() {
228                issues.push(Issue::new("settings.filename", "required", "Give the file a name."));
229            }
230            check_text(issues, "settings.filename", &document.filename, ctx, locale);
231            if document.format == DocumentFormat::Pdf && !cfg!(feature = "pdf") {
232                issues.push(Issue::new(
233                    "settings.format",
234                    "pdf_disabled",
235                    "PDF documents need the `pdf` feature of laravel-template-engine; choose HTML or turn it on.",
236                ));
237            }
238        }
239        Settings::Notification(notification) => {
240            let channel = notification.channel.trim();
241            if channel.is_empty() {
242                issues.push(Issue::new(
243                    "settings.channel",
244                    "required",
245                    "Choose the channel the text is for.",
246                ));
247            } else if !ctx.channels.iter().any(|c| c == channel) {
248                let message = format!(
249                    "There's no channel `{channel}`. The channels are: {}.",
250                    ctx.channels
251                        .iter()
252                        .map(|c| format!("`{c}`"))
253                        .collect::<Vec<_>>()
254                        .join(", ")
255                );
256                let suggestion = closest(channel, ctx.channels.iter().map(String::as_str));
257                issues.push(Issue::new("settings.channel", "unknown_channel", message).suggest(suggestion));
258            }
259        }
260    }
261}
262
263fn check_document_style(issues: &mut Vec<Issue>, document: &crate::template::DocumentSettings) {
264    let margins = document.margins;
265    for (side, value) in [
266        ("top", margins.top),
267        ("right", margins.right),
268        ("bottom", margins.bottom),
269        ("left", margins.left),
270    ] {
271        if !(0.0..=100.0).contains(&value) {
272            let message = format!("The {side} margin should be between 0 and 100 mm.");
273            issues.push(Issue::new(format!("settings.margins.{side}"), "out_of_range", message));
274        }
275    }
276    if document.font_size.is_some_and(|size| !(4.0..=72.0).contains(&size)) {
277        issues.push(Issue::new(
278            "settings.font_size",
279            "out_of_range",
280            "The font size should be between 4 and 72 points.",
281        ));
282    }
283    if document
284        .line_height
285        .is_some_and(|height| !(0.5..=4.0).contains(&height))
286    {
287        issues.push(Issue::new(
288            "settings.line_height",
289            "out_of_range",
290            "The line spacing should be between 0.5 and 4.",
291        ));
292    }
293    if let Some(family) = &document.font_family
294        && crate::render::safe_font_family(family) != family.trim()
295    {
296        let message = format!("`{family}` isn't a font name; use letters, digits, spaces, `-` and `_`.");
297        issues.push(Issue::new("settings.font_family", "invalid_font", message));
298    }
299}
300
301fn check_recipient(issues: &mut Vec<Issue>, field: &str, entry: &str, recipients: &[String]) {
302    let entry = entry.trim();
303    if entry.contains('@') {
304        if parse_address(entry).is_none() {
305            issues.push(Issue::new(
306                field,
307                "invalid_address",
308                format!("`{entry}` isn't an email address."),
309            ));
310        }
311        return;
312    }
313    if !recipients.iter().any(|r| r == entry) {
314        let message = if recipients.is_empty() {
315            format!("`{entry}` isn't an email address, and this template type has no recipient variables.")
316        } else {
317            format!(
318                "`{entry}` is neither an email address nor a recipient variable ({}).",
319                recipients
320                    .iter()
321                    .map(|r| format!("`{r}`"))
322                    .collect::<Vec<_>>()
323                    .join(", ")
324            )
325        };
326        let suggestion = closest(entry, recipients.iter().map(String::as_str));
327        issues.push(Issue::new(field, "unknown_recipient", message).suggest(suggestion));
328    }
329}
330
331/// `ada@example.com` or `Ada <ada@example.com>` as an address and an optional name.
332pub(crate) fn parse_address(text: &str) -> Option<(String, Option<String>)> {
333    let text = text.trim();
334    let (name, email) = match (text.rfind('<'), text.strip_suffix('>')) {
335        (Some(open), Some(rest)) => (
336            Some(text[..open].trim().trim_matches('"').to_owned()),
337            &rest[open + 1..],
338        ),
339        _ => (None, text),
340    };
341    let (local, domain) = email.split_once('@')?;
342    let valid = !local.is_empty()
343        && domain.contains('.')
344        && !domain.starts_with('.')
345        && !domain.ends_with('.')
346        && !email.contains(char::is_whitespace)
347        && !domain.contains('@');
348    valid.then(|| (email.to_owned(), name.filter(|n| !n.is_empty())))
349}
350
351fn check_text(issues: &mut Vec<Issue>, field: &str, source: &str, ctx: &Context<'_>, locale: &str) {
352    let config = ctx.config;
353    if source.chars().count() > config.max_length {
354        issues.push(Issue::new(
355            field,
356            "too_long",
357            format!("The text is longer than {} characters.", config.max_length),
358        ));
359        return;
360    }
361    let ast = match parse(source, field, SyntaxConfig::default()) {
362        Ok(ast) => ast,
363        Err(error) => {
364            issues.push(syntax_issue(field, source, &error));
365            return;
366        }
367    };
368    let mut checker = Checker {
369        field,
370        root: &ctx.info.variables,
371        filters: ctx.filters,
372        images: ctx.images,
373        pdf: ctx.pdf,
374        locale,
375        max_depth: config.max_depth,
376        depth: 0,
377        too_deep: false,
378        scopes: vec![HashMap::new()],
379        issues: Vec::new(),
380    };
381    checker.stmt(&ast);
382    issues.append(&mut checker.issues);
383}
384
385fn syntax_issue(field: &str, source: &str, error: &minijinja::Error) -> Issue {
386    let mut issue = Issue::new(
387        field,
388        "syntax",
389        format!(
390            "The template's syntax is wrong: {}.",
391            error.detail().unwrap_or("unexpected text")
392        ),
393    );
394    if let Some(range) = error.range() {
395        let before = &source[..range.start.min(source.len())];
396        issue.line = Some(u32::try_from(before.matches('\n').count() + 1).unwrap_or(u32::MAX));
397        let column = before.rsplit('\n').next().map_or(0, |line| line.chars().count());
398        issue.column = Some(u32::try_from(column + 1).unwrap_or(u32::MAX));
399    } else if let Some(line) = error.line() {
400        issue.line = u32::try_from(line).ok();
401    }
402    issue
403}
404
405struct Checker<'a> {
406    field: &'a str,
407    root: &'a [Field],
408    filters: &'a [FilterSpec],
409    images: &'a [String],
410    pdf: bool,
411    locale: &'a str,
412    max_depth: usize,
413    depth: usize,
414    too_deep: bool,
415    scopes: Vec<HashMap<String, Node>>,
416    issues: Vec<Issue>,
417}
418
419impl Checker<'_> {
420    fn issue(&mut self, span: Span, code: &'static str, message: impl Into<String>) -> &mut Issue {
421        self.issues.push(Issue::new(self.field, code, message).at(span));
422        self.issues.last_mut().expect("just pushed")
423    }
424
425    fn forbid(&mut self, span: Span, what: &str) {
426        self.issue(
427            span,
428            "forbidden_tag",
429            format!("{what} can't be used in these templates."),
430        );
431    }
432
433    fn stmts(&mut self, stmts: &[Stmt<'_>]) {
434        for stmt in stmts {
435            self.stmt(stmt);
436        }
437    }
438
439    fn nested(&mut self, span: Span, body: impl FnOnce(&mut Self)) {
440        self.depth += 1;
441        if self.depth > self.max_depth && !self.too_deep {
442            self.too_deep = true;
443            let message = format!("`if` and `for` blocks are nested more than {} deep.", self.max_depth);
444            self.issue(span, "too_deep", message);
445        }
446        body(self);
447        self.depth -= 1;
448    }
449
450    fn stmt(&mut self, stmt: &Stmt<'_>) {
451        match stmt {
452            Stmt::Template(template) => self.stmts(&template.children),
453            Stmt::EmitExpr(emit) => {
454                self.expr(&emit.expr);
455            }
456            Stmt::EmitRaw(raw) => self.raw_images(raw.raw, raw.span()),
457            Stmt::ForLoop(for_loop) => self.for_loop(for_loop, for_loop.span()),
458            Stmt::IfCond(cond) => {
459                self.expr(&cond.expr);
460                self.nested(cond.span(), |this| {
461                    this.stmts(&cond.true_body);
462                    this.stmts(&cond.false_body);
463                });
464            }
465            Stmt::Set(set) => {
466                let node = self.expr(&set.expr);
467                self.bind(&set.target, node);
468            }
469            Stmt::SetBlock(set) => {
470                if let Some(filter) = &set.filter {
471                    self.expr(filter);
472                }
473                self.stmts(&set.body);
474                self.bind(&set.target, Node::Text);
475            }
476            Stmt::WithBlock(with) => {
477                let assigned: Vec<(&Expr<'_>, Node)> =
478                    with.assignments.iter().map(|(t, e)| (t, self.expr(e))).collect();
479                self.scopes.push(HashMap::new());
480                for (target, node) in assigned {
481                    self.bind(target, node);
482                }
483                self.stmts(&with.body);
484                self.scopes.pop();
485            }
486            Stmt::AutoEscape(s) => self.forbid(s.span(), "`autoescape`"),
487            Stmt::FilterBlock(s) => self.forbid(s.span(), "`filter` blocks"),
488            Stmt::Do(s) => self.forbid(s.span(), "`do`"),
489        }
490    }
491
492    fn for_loop(&mut self, for_loop: &ast::ForLoop<'_>, span: Span) {
493        if for_loop.recursive {
494            self.forbid(span, "Recursive loops");
495        }
496        let iter = self.expr(&for_loop.iter);
497        let item = match iter.required() {
498            Node::List(item) => (**item).clone(),
499            Node::Any => Node::Any,
500            other => {
501                let name = path_of(&for_loop.iter).unwrap_or_else(|| "this value".to_owned());
502                let kind = other.type_name();
503                let message = format!(
504                    "`{name}` is {} {kind}, not a list; `for` goes over lists.",
505                    article(kind)
506                );
507                let suggestion = self.list_near(&for_loop.iter);
508                let issue = self
509                    .issue(expr_span(&for_loop.iter).unwrap_or(span), "not_a_list", message)
510                    .clone();
511                *self.issues.last_mut().expect("just pushed") = issue.suggest(suggestion);
512                Node::Any
513            }
514        };
515        self.nested(span, |this| {
516            this.scopes.push(HashMap::new());
517            this.bind(&for_loop.target, item);
518            this.scopes
519                .last_mut()
520                .expect("scope")
521                .insert("loop".to_owned(), loop_node());
522            if let Some(filter) = &for_loop.filter_expr {
523                this.expr(filter);
524            }
525            this.stmts(&for_loop.body);
526            this.scopes.pop();
527            this.stmts(&for_loop.else_body);
528        });
529    }
530
531    /// A list to suggest instead of a non-list: one inside the object itself (`order.items` for
532    /// `order`), or next to the value (`order.items` for `order.total`).
533    fn list_near(&self, expr: &Expr<'_>) -> Option<String> {
534        let path = path_of(expr)?;
535        let first_list = |fields: Vec<Field>, prefix: &str| {
536            fields
537                .iter()
538                .find(|f| matches!(f.node.required(), Node::List(_)))
539                .map(|f| crate::schema::join(prefix, f.name))
540        };
541        if let Some(inside) = self.lookup_path(&path).and_then(|node| node.fields())
542            && let Some(found) = first_list(inside, &path)
543        {
544            return Some(found);
545        }
546        let (parent, _) = path.rsplit_once('.').unwrap_or(("", &path));
547        let siblings = if parent.is_empty() {
548            self.root.to_vec()
549        } else {
550            self.lookup_path(parent)?.fields()?
551        };
552        first_list(siblings, parent)
553    }
554
555    fn lookup_path(&self, path: &str) -> Option<Node> {
556        let mut parts = path.split('.');
557        let mut node = self.lookup(parts.next()?)?;
558        for part in parts {
559            node = node.fields()?.into_iter().find(|f| f.name == part)?.node;
560        }
561        Some(node)
562    }
563
564    fn bind(&mut self, target: &Expr<'_>, node: Node) {
565        let scope = self.scopes.last_mut().expect("scope");
566        match target {
567            Expr::Var(var) => {
568                scope.insert(var.id.to_owned(), node);
569            }
570            Expr::Tuple(tuple) => {
571                for item in &tuple.items {
572                    if let Expr::Var(var) = item {
573                        scope.insert(var.id.to_owned(), Node::Any);
574                    }
575                }
576            }
577            _ => {}
578        }
579    }
580
581    fn lookup(&self, name: &str) -> Option<Node> {
582        for scope in self.scopes.iter().rev() {
583            if let Some(node) = scope.get(name) {
584                return Some(node.clone());
585            }
586        }
587        self.root.iter().find(|f| f.name == name).map(|f| f.node.clone())
588    }
589
590    fn visible_names(&self) -> Vec<String> {
591        let mut names: Vec<String> = self.root.iter().map(|f| f.name.to_owned()).collect();
592        for scope in &self.scopes {
593            names.extend(scope.keys().cloned());
594        }
595        names
596    }
597
598    fn expr(&mut self, expr: &Expr<'_>) -> Node {
599        match expr {
600            Expr::Var(var) => {
601                if let Some(node) = self.lookup(var.id) {
602                    return node;
603                }
604                if FUNCTIONS.contains(&var.id) {
605                    let message = format!("`{0}` can only be called, as in `{0}(5)`.", var.id);
606                    self.issue(var.span(), "forbidden_call", message);
607                    return Node::Any;
608                }
609                let names = self.visible_names();
610                let suggestion = closest(var.id, names.iter().map(String::as_str));
611                let message = format!("There's no variable `{}`.", var.id);
612                let issue = Issue::new(self.field, "unknown_variable", message)
613                    .at(var.span())
614                    .suggest(suggestion);
615                self.issues.push(issue);
616                Node::Any
617            }
618            Expr::Const(constant) => const_node(&constant.value),
619            Expr::GetAttr(attr) => {
620                let base = self.expr(&attr.expr);
621                self.field_of(&base, &attr.expr, attr.name, attr.span())
622            }
623            Expr::GetItem(item) => {
624                let base = self.expr(&item.expr);
625                let key = self.expr(&item.subscript_expr);
626                match (base.required(), &item.subscript_expr) {
627                    (Node::List(inner), _) => (**inner).clone(),
628                    (Node::Object(_) | Node::Recipient, Expr::Const(c)) if c.value.as_str().is_some() => {
629                        let name = c.value.as_str().unwrap_or_default().to_owned();
630                        self.field_of(&base, &item.expr, &name, item.span())
631                    }
632                    _ => {
633                        let _ = key;
634                        Node::Any
635                    }
636                }
637            }
638            Expr::Slice(slice) => {
639                let base = self.expr(&slice.expr);
640                for part in [&slice.start, &slice.stop, &slice.step].into_iter().flatten() {
641                    self.expr(part);
642                }
643                base
644            }
645            Expr::UnaryOp(op) => {
646                self.expr(&op.expr);
647                match op.op {
648                    ast::UnaryOpKind::Not => Node::Bool,
649                    ast::UnaryOpKind::Neg => Node::Number,
650                }
651            }
652            Expr::BinOp(op) => self.bin_op(op),
653            Expr::Compare(compare) => {
654                self.expr(&compare.expr);
655                for op in &compare.ops {
656                    self.expr(&op.expr);
657                }
658                Node::Bool
659            }
660            Expr::IfExpr(if_expr) => {
661                self.expr(&if_expr.test_expr);
662                let node = self.expr(&if_expr.true_expr);
663                if let Some(other) = &if_expr.false_expr {
664                    self.expr(other);
665                }
666                node
667            }
668            Expr::Filter(filter) => self.filter(filter, filter.span()),
669            Expr::Test(test) => self.test(test, test.span()),
670            Expr::Call(call) => self.call(call, call.span()),
671            Expr::List(list) => {
672                let mut item = Node::Any;
673                for (i, entry) in list.items.iter().enumerate() {
674                    let node = self.expr(entry);
675                    if i == 0 {
676                        item = node;
677                    }
678                }
679                Node::List(Box::new(item))
680            }
681            Expr::Tuple(tuple) => {
682                for entry in &tuple.items {
683                    self.expr(entry);
684                }
685                Node::Any
686            }
687            Expr::Map(map) => {
688                for entry in map.keys.iter().chain(&map.values) {
689                    self.expr(entry);
690                }
691                Node::Any
692            }
693        }
694    }
695
696    /// Checks the `<img src>` written in the template's own text.
697    fn raw_images(&mut self, raw: &str, span: Span) {
698        for range in crate::assets::image_sources(raw) {
699            let src = raw[range.clone()].trim();
700            let Some(problem) = self.image_problem(src) else {
701                continue;
702            };
703            let before = &raw[..range.start];
704            let lines = before.matches('\n').count();
705            let column = before.rsplit('\n').next().map_or(0, |line| line.chars().count());
706            let mut issue = Issue::new(self.field, problem.0, problem.1).suggest(problem.2);
707            issue.line = Some(u32::from(span.start_line) + u32::try_from(lines).unwrap_or(0));
708            let start = if lines == 0 { u32::from(span.start_col) } else { 0 };
709            issue.column = Some(start + u32::try_from(column).unwrap_or(0) + 1);
710            self.issues.push(issue);
711        }
712    }
713
714    /// Why `src` won't show, if it won't: its code, the message and a suggestion.
715    fn image_problem(&self, src: &str) -> Option<(&'static str, String, Option<String>)> {
716        if self.images.iter().any(|name| name == src) || src.starts_with("data:image/") {
717            return None;
718        }
719        let lower = src.to_ascii_lowercase();
720        if lower.starts_with("https://") || lower.starts_with("http://") {
721            if !self.pdf {
722                return None;
723            }
724            let message = format!(
725                "PDFs don't load pictures from the internet, so `{src}` won't show; ask a developer to add it as a picture."
726            );
727            return Some(("remote_image", message, None));
728        }
729        let message = if self.images.is_empty() {
730            format!("There's no picture `{src}`; developers add pictures in code.")
731        } else {
732            format!(
733                "There's no picture `{src}`. The pictures are: {}.",
734                self.images
735                    .iter()
736                    .map(|n| format!("`{n}`"))
737                    .collect::<Vec<_>>()
738                    .join(", ")
739            )
740        };
741        Some((
742            "unknown_image",
743            message,
744            closest(src, self.images.iter().map(String::as_str)),
745        ))
746    }
747
748    fn test(&mut self, test: &ast::Test<'_>, span: Span) -> Node {
749        self.expr(&test.expr);
750        self.args(&test.args);
751        if !TESTS.contains(&test.name) {
752            let suggestion = closest(test.name, TESTS.iter().copied());
753            let issue = Issue::new(self.field, "unknown_test", format!("There's no test `{}`.", test.name));
754            self.issues.push(issue.at(span).suggest(suggestion));
755        }
756        Node::Bool
757    }
758
759    fn bin_op(&mut self, op: &ast::BinOp<'_>) -> Node {
760        use ast::BinOpKind as K;
761        let left = self.expr(&op.left);
762        self.expr(&op.right);
763        match op.op {
764            K::Eq | K::Ne | K::Lt | K::Lte | K::Gt | K::Gte | K::ScAnd | K::ScOr | K::In => Node::Bool,
765            K::Concat => Node::Text,
766            K::Add if *left.required() == Node::Text => Node::Text,
767            _ => Node::Number,
768        }
769    }
770
771    fn call(&mut self, call: &ast::Call<'_>, span: Span) -> Node {
772        self.args(&call.args);
773        if let Expr::Var(var) = &call.expr
774            && FUNCTIONS.contains(&var.id)
775        {
776            return Node::List(Box::new(Node::Number));
777        }
778        let name = path_of(&call.expr).unwrap_or_else(|| "this".to_owned());
779        let message = format!("`{name}(...)` can't be called; templates only call `range`.");
780        self.issue(span, "forbidden_call", message);
781        Node::Any
782    }
783
784    fn args(&mut self, args: &[CallArg<'_>]) -> Vec<Node> {
785        args.iter()
786            .map(|arg| match arg {
787                CallArg::Pos(e) | CallArg::Kwarg(_, e) | CallArg::PosSplat(e) | CallArg::KwargSplat(e) => self.expr(e),
788            })
789            .collect()
790    }
791
792    fn field_of(&mut self, base: &Node, base_expr: &Expr<'_>, name: &str, span: Span) -> Node {
793        let base_name = path_of(base_expr).unwrap_or_else(|| "this value".to_owned());
794        match base.required() {
795            Node::Any => Node::Any,
796            Node::Object(_) | Node::Recipient => {
797                let fields = base.fields().unwrap_or_default();
798                if let Some(field) = fields.iter().find(|f| f.name == name) {
799                    return field.node.clone();
800                }
801                let suggestion = closest(name, fields.iter().map(|f| f.name)).map(|n| format!("{base_name}.{n}"));
802                let message = format!("There's no `{base_name}.{name}`.");
803                self.issues.push(
804                    Issue::new(self.field, "unknown_variable", message)
805                        .at(span)
806                        .suggest(suggestion),
807                );
808                Node::Any
809            }
810            Node::List(_) => {
811                let message = format!(
812                    "`{base_name}` is a list, so it has no `{name}`; go over it with `{{% for item in {base_name} %}}` and use `item.{name}`."
813                );
814                self.issue(span, "unknown_variable", message);
815                Node::Any
816            }
817            other => {
818                let kind = other.type_name();
819                let message = format!("`{base_name}` is {} {kind}, so it has no `{name}`.", article(kind));
820                self.issue(span, "unknown_variable", message);
821                Node::Any
822            }
823        }
824    }
825
826    fn filter(&mut self, filter: &ast::Filter<'_>, span: Span) -> Node {
827        let input = filter.expr.as_ref().map_or(Node::Any, |e| self.expr(e));
828        self.args(&filter.args);
829        let Some(spec) = self.filters.iter().find(|f| f.name == filter.name).cloned() else {
830            let suggestion = closest(filter.name, self.filters.iter().map(|f| f.name));
831            let issue = Issue::new(
832                self.field,
833                "unknown_filter",
834                format!("There's no filter `{}`.", filter.name),
835            );
836            self.issues.push(issue.at(span).suggest(suggestion));
837            return Node::Any;
838        };
839
840        let positional: Vec<&Expr<'_>> = filter
841            .args
842            .iter()
843            .filter_map(|arg| match arg {
844                CallArg::Pos(e) => Some(e),
845                _ => None,
846            })
847            .collect();
848        if positional.len() < spec.min_args() || positional.len() > spec.max_args() {
849            let message = format!(
850                "`{}` takes {}; it was given {}.",
851                spec.name,
852                describe_args(&spec),
853                positional.len()
854            );
855            self.issue(span, "filter_arguments", message);
856        }
857        for (i, arg) in positional.iter().enumerate() {
858            let declared = spec.args.get(i).or(spec.args.last()).map_or(ArgKind::Any, |a| a.kind);
859            if let Expr::Const(constant) = arg {
860                let fits = match declared {
861                    ArgKind::Text => constant.value.as_str().is_some(),
862                    ArgKind::Number => constant.value.is_number(),
863                    ArgKind::Any => true,
864                };
865                if !fits {
866                    let wanted = if declared == ArgKind::Text {
867                        "text in quotes"
868                    } else {
869                        "a number"
870                    };
871                    let message = format!("`{}`'s argument {} should be {wanted}.", spec.name, i + 1);
872                    self.issue(constant.span(), "filter_arguments", message);
873                }
874            }
875        }
876        self.special_filter_checks(&spec, &positional, span);
877
878        let wrong_input = match (spec.input, input.required()) {
879            (InputKind::Number, Node::Text | Node::Bool | Node::List(_) | Node::Object(_) | Node::Recipient) => {
880                Some("a number")
881            }
882            (InputKind::Date, Node::Number | Node::Bool | Node::List(_) | Node::Object(_) | Node::Recipient) => {
883                Some("a date")
884            }
885            _ => None,
886        };
887        if let Some(wanted) = wrong_input {
888            let name = filter
889                .expr
890                .as_ref()
891                .and_then(path_of)
892                .unwrap_or_else(|| "the value".to_owned());
893            let kind = input.type_name();
894            let message = format!(
895                "`{}` needs {wanted}, but `{name}` is {} {kind}.",
896                spec.name,
897                article(kind)
898            );
899            self.issue(span, "filter_input", message);
900        }
901
902        match spec.name {
903            "round" | "abs" | "int" | "float" | "length" | "sum" => Node::Number,
904            "first" | "last" | "min" | "max" => match input.required() {
905                Node::List(item) => (**item).clone(),
906                _ => Node::Any,
907            },
908            "sort" | "reverse" | "unique" | "default" => input,
909            "money" | "number" | "date" | "plural" | "upper" | "lower" | "title" | "capitalize" | "trim"
910            | "replace" | "join" | "string" => Node::Text,
911            _ => Node::Any,
912        }
913    }
914
915    fn special_filter_checks(&mut self, spec: &FilterSpec, args: &[&Expr<'_>], span: Span) {
916        let constant = |i: usize| match args.get(i) {
917            Some(Expr::Const(c)) => c.value.as_str().map(ToOwned::to_owned),
918            _ => None,
919        };
920        match spec.name {
921            "date" => {
922                if let Some(format) = constant(0)
923                    && let Err(message) = check_date_format(&format)
924                {
925                    self.issue(span, "filter_arguments", message);
926                }
927            }
928            "money" => {
929                if let Some(code) = constant(0)
930                    && let Err(message) = filters::money(self.locale, &minijinja::Value::from(1), &code)
931                {
932                    self.issue(span, "filter_arguments", message);
933                }
934            }
935            "plural" => {
936                let Ok(categories) = plural_categories(self.locale) else {
937                    return;
938                };
939                if !args.is_empty() && args.len() < categories.len() {
940                    let names: Vec<&str> = categories.iter().map(|c| category_name(*c)).collect();
941                    let message = format!(
942                        "`{}` needs {} word forms for `plural`, one for each of: {}; it was given {}.",
943                        self.locale,
944                        categories.len(),
945                        names.join(", "),
946                        args.len()
947                    );
948                    self.issue(span, "plural_forms", message);
949                }
950            }
951            _ => {}
952        }
953    }
954}
955
956fn describe_args(spec: &FilterSpec) -> String {
957    let (min, max) = (spec.min_args(), spec.max_args());
958    let plural = |n: usize| if n == 1 { "argument" } else { "arguments" };
959    match (min, max) {
960        (_, usize::MAX) => format!("at least {min} {}", plural(min)),
961        (0, 0) => "no arguments".to_owned(),
962        (min, max) if min == max => format!("{min} {}", plural(min)),
963        (min, max) => format!("{min} to {max} arguments"),
964    }
965}
966
967fn article(kind: &str) -> &'static str {
968    if kind.starts_with(['a', 'e', 'i', 'o', 'u']) {
969        "an"
970    } else {
971        "a"
972    }
973}
974
975fn loop_node() -> Node {
976    let number = |name| Field::new(name, "", Node::Number);
977    let flag = |name| Field::new(name, "", Node::Bool);
978    Node::Object(vec![
979        number("index"),
980        number("index0"),
981        number("revindex"),
982        number("revindex0"),
983        number("length"),
984        number("depth"),
985        number("depth0"),
986        flag("first"),
987        flag("last"),
988    ])
989}
990
991fn const_node(value: &minijinja::Value) -> Node {
992    if value.as_str().is_some() {
993        Node::Text
994    } else if value.is_number() {
995        Node::Number
996    } else if value.kind() == minijinja::value::ValueKind::Bool {
997        Node::Bool
998    } else {
999        Node::Any
1000    }
1001}
1002
1003/// `order.items` for a chain of variables and attributes.
1004fn path_of(expr: &Expr<'_>) -> Option<String> {
1005    match expr {
1006        Expr::Var(var) => Some(var.id.to_owned()),
1007        Expr::GetAttr(attr) => Some(format!("{}.{}", path_of(&attr.expr)?, attr.name)),
1008        _ => None,
1009    }
1010}
1011
1012fn expr_span(expr: &Expr<'_>) -> Option<Span> {
1013    match expr {
1014        Expr::Var(e) => Some(e.span()),
1015        Expr::GetAttr(e) => Some(e.span()),
1016        Expr::GetItem(e) => Some(e.span()),
1017        Expr::Filter(e) => Some(e.span()),
1018        Expr::Call(e) => Some(e.span()),
1019        _ => None,
1020    }
1021}
1022
1023/// The candidate closest to `wanted`, when it's close enough to be a typo.
1024pub(crate) fn closest<'a>(wanted: &str, candidates: impl IntoIterator<Item = &'a str>) -> Option<String> {
1025    let limit = (wanted.chars().count() / 3).max(2);
1026    candidates
1027        .into_iter()
1028        .map(|candidate| (strsim::damerau_levenshtein(wanted, candidate), candidate))
1029        .filter(|(distance, _)| *distance <= limit)
1030        .min_by_key(|(distance, _)| *distance)
1031        .map(|(_, candidate)| candidate.to_owned())
1032}