laravel-template-engine 0.2.0

Templates for emails, documents and notifications that your team edits, stored in the database
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
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
//! Checks a template before it's saved: syntax, variables, loops, filters and settings, with
//! messages for the person editing it.

use std::collections::HashMap;

use minijinja::machinery::ast::{self, CallArg, Expr, Stmt};
use minijinja::machinery::{Span, parse};
use minijinja::syntax::SyntaxConfig;
use serde::Serialize;

use crate::config::TemplateEngineConfig;
use crate::filters::{self, category_name, check_date_format, plural_categories};
use crate::render::PAPERS;
use crate::sandbox::{ArgKind, FUNCTIONS, FilterSpec, InputKind, TESTS};
use crate::schema::{Field, Node, TypeInfo, find_type};
use crate::template::{DocumentFormat, Kind, Settings, TemplateInput};

/// One mistake in a template, for an editor to show next to the field.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Issue {
    /// Where: `name`, `content.uk.body`, `settings.to.1` and so on.
    pub field: String,
    /// The line in the field's text, from 1, for mistakes in a template's text.
    pub line: Option<u32>,
    /// The column in that line, from 1.
    pub column: Option<u32>,
    /// What kind of mistake, for code: `syntax`, `unknown_variable`, `not_a_list` and so on.
    pub code: &'static str,
    /// What's wrong, in words for the person editing the template.
    pub message: String,
    /// A fix, such as the variable that was probably meant.
    pub suggestion: Option<String>,
}

impl Issue {
    fn new(field: impl Into<String>, code: &'static str, message: impl Into<String>) -> Self {
        Self {
            field: field.into(),
            line: None,
            column: None,
            code,
            message: message.into(),
            suggestion: None,
        }
    }

    fn at(mut self, span: Span) -> Self {
        self.line = Some(u32::from(span.start_line));
        self.column = Some(u32::from(span.start_col) + 1);
        self
    }

    fn suggest(mut self, suggestion: Option<String>) -> Self {
        if let Some(suggestion) = &suggestion {
            self.message = format!("{} Did you mean `{suggestion}`?", self.message);
        }
        self.suggestion = suggestion;
        self
    }
}

impl std::fmt::Display for Issue {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self.line {
            Some(line) => write!(f, "{} (line {line}): {}", self.field, self.message),
            None => write!(f, "{}: {}", self.field, self.message),
        }
    }
}

/// Checks everything that doesn't need the database.
/// What every text of a template is checked against.
struct Context<'a> {
    info: &'a TypeInfo,
    filters: &'a [FilterSpec],
    images: &'a [String],
    layouts: &'a [String],
    /// Whether pictures end up in a PDF, which can't load them from the internet.
    pdf: bool,
    config: &'a TemplateEngineConfig,
}

pub(crate) fn check_input(
    input: &TemplateInput,
    custom: &[FilterSpec],
    images: &[String],
    layouts: &[String],
    config: &TemplateEngineConfig,
) -> Vec<Issue> {
    let mut issues = Vec::new();
    let Some(info) = find_type(&input.type_key) else {
        let keys: Vec<String> = crate::schema::types().iter().map(|t| t.key.to_owned()).collect();
        let issue = Issue::new(
            "type_key",
            "unknown_type",
            format!("There's no template type `{}`.", input.type_key),
        );
        issues.push(issue.suggest(closest(&input.type_key, keys.iter().map(String::as_str))));
        return issues;
    };
    if input.name.trim().is_empty() {
        issues.push(Issue::new("name", "required", "Give the template a name."));
    }
    if input.content.is_empty() {
        issues.push(Issue::new(
            "content",
            "required",
            "Add the text in at least one language.",
        ));
    }

    let mut filters = filters::builtin();
    filters.extend(custom.iter().cloned());
    let pdf = matches!(&input.settings, Settings::Document(d) if d.format == DocumentFormat::Pdf);
    let ctx = Context {
        info: &info,
        filters: &filters,
        images,
        layouts,
        pdf,
        config,
    };
    for (locale, content) in &input.content {
        let prefix = format!("content.{locale}");
        if filters::icu_locale(locale).id.language.as_str() == "und" {
            issues.push(Issue::new(
                &prefix,
                "unknown_locale",
                format!("`{locale}` isn't a language code such as `uk` or `en`."),
            ));
            continue;
        }
        if input.kind() == Kind::Mail {
            if content.subject.trim().is_empty() {
                issues.push(Issue::new(
                    format!("{prefix}.subject"),
                    "required",
                    "Write the subject.",
                ));
            }
            check_text(
                &mut issues,
                &format!("{prefix}.subject"),
                &content.subject,
                &ctx,
                locale,
            );
        }
        if content.body.trim().is_empty() {
            issues.push(Issue::new(format!("{prefix}.body"), "required", "Write the text."));
        }
        check_text(&mut issues, &format!("{prefix}.body"), &content.body, &ctx, locale);
    }

    let locale = input
        .content
        .keys()
        .next()
        .map_or(config.locale.as_str(), String::as_str);
    check_settings(&mut issues, input, &ctx, locale);
    issues
}

fn check_settings(issues: &mut Vec<Issue>, input: &TemplateInput, ctx: &Context<'_>, locale: &str) {
    let info = ctx.info;
    let layout = match &input.settings {
        Settings::Mail(mail) => mail.layout.as_deref(),
        Settings::Document(document) => document.layout.as_deref(),
    };
    if let Some(name) = layout.filter(|name| !ctx.layouts.iter().any(|l| l == name)) {
        let message = if ctx.layouts.is_empty() {
            format!("There's no layout `{name}`; developers add layouts in code.")
        } else {
            format!("There's no layout `{name}`.")
        };
        let suggestion = closest(name, ctx.layouts.iter().map(String::as_str));
        issues.push(Issue::new("settings.layout", "unknown_layout", message).suggest(suggestion));
    }
    if let Settings::Document(document) = &input.settings {
        check_document_style(issues, document);
    }
    match &input.settings {
        Settings::Mail(mail) => {
            if mail.to.is_empty() {
                issues.push(Issue::new("settings.to", "required", "Choose who gets the email."));
            }
            let recipients = info.recipients();
            for (list, entries) in [("to", &mail.to), ("cc", &mail.cc), ("bcc", &mail.bcc)] {
                for (i, entry) in entries.iter().enumerate() {
                    check_recipient(issues, &format!("settings.{list}.{i}"), entry, &recipients);
                }
            }
            for (field, value) in [("settings.from", &mail.from), ("settings.reply_to", &mail.reply_to)] {
                if let Some(address) = value.as_deref().filter(|a| !a.trim().is_empty())
                    && parse_address(address).is_none()
                {
                    issues.push(Issue::new(
                        field,
                        "invalid_address",
                        format!("`{address}` isn't an email address."),
                    ));
                }
            }
        }
        Settings::Document(document) => {
            if !PAPERS
                .iter()
                .any(|(name, ..)| *name == document.paper.to_ascii_lowercase())
            {
                let issue = Issue::new(
                    "settings.paper",
                    "invalid_paper",
                    format!("`{}` isn't a paper size.", document.paper),
                );
                issues.push(issue.suggest(closest(&document.paper, PAPERS.iter().map(|(name, ..)| *name))));
            }
            if document.filename.trim().is_empty() {
                issues.push(Issue::new("settings.filename", "required", "Give the file a name."));
            }
            check_text(issues, "settings.filename", &document.filename, ctx, locale);
            if document.format == DocumentFormat::Pdf && !cfg!(feature = "pdf") {
                issues.push(Issue::new(
                    "settings.format",
                    "pdf_disabled",
                    "PDF documents need the `pdf` feature of laravel-template-engine; choose HTML or turn it on.",
                ));
            }
        }
    }
}

fn check_document_style(issues: &mut Vec<Issue>, document: &crate::template::DocumentSettings) {
    let margins = document.margins;
    for (side, value) in [
        ("top", margins.top),
        ("right", margins.right),
        ("bottom", margins.bottom),
        ("left", margins.left),
    ] {
        if !(0.0..=100.0).contains(&value) {
            let message = format!("The {side} margin should be between 0 and 100 mm.");
            issues.push(Issue::new(format!("settings.margins.{side}"), "out_of_range", message));
        }
    }
    if document.font_size.is_some_and(|size| !(4.0..=72.0).contains(&size)) {
        issues.push(Issue::new(
            "settings.font_size",
            "out_of_range",
            "The font size should be between 4 and 72 points.",
        ));
    }
    if document
        .line_height
        .is_some_and(|height| !(0.5..=4.0).contains(&height))
    {
        issues.push(Issue::new(
            "settings.line_height",
            "out_of_range",
            "The line spacing should be between 0.5 and 4.",
        ));
    }
    if let Some(family) = &document.font_family
        && crate::render::safe_font_family(family) != family.trim()
    {
        let message = format!("`{family}` isn't a font name; use letters, digits, spaces, `-` and `_`.");
        issues.push(Issue::new("settings.font_family", "invalid_font", message));
    }
}

fn check_recipient(issues: &mut Vec<Issue>, field: &str, entry: &str, recipients: &[String]) {
    let entry = entry.trim();
    if entry.contains('@') {
        if parse_address(entry).is_none() {
            issues.push(Issue::new(
                field,
                "invalid_address",
                format!("`{entry}` isn't an email address."),
            ));
        }
        return;
    }
    if !recipients.iter().any(|r| r == entry) {
        let message = if recipients.is_empty() {
            format!("`{entry}` isn't an email address, and this template type has no recipient variables.")
        } else {
            format!(
                "`{entry}` is neither an email address nor a recipient variable ({}).",
                recipients
                    .iter()
                    .map(|r| format!("`{r}`"))
                    .collect::<Vec<_>>()
                    .join(", ")
            )
        };
        let suggestion = closest(entry, recipients.iter().map(String::as_str));
        issues.push(Issue::new(field, "unknown_recipient", message).suggest(suggestion));
    }
}

/// `ada@example.com` or `Ada <ada@example.com>` as an address and an optional name.
pub(crate) fn parse_address(text: &str) -> Option<(String, Option<String>)> {
    let text = text.trim();
    let (name, email) = match (text.rfind('<'), text.strip_suffix('>')) {
        (Some(open), Some(rest)) => (
            Some(text[..open].trim().trim_matches('"').to_owned()),
            &rest[open + 1..],
        ),
        _ => (None, text),
    };
    let (local, domain) = email.split_once('@')?;
    let valid = !local.is_empty()
        && domain.contains('.')
        && !domain.starts_with('.')
        && !domain.ends_with('.')
        && !email.contains(char::is_whitespace)
        && !domain.contains('@');
    valid.then(|| (email.to_owned(), name.filter(|n| !n.is_empty())))
}

fn check_text(issues: &mut Vec<Issue>, field: &str, source: &str, ctx: &Context<'_>, locale: &str) {
    let config = ctx.config;
    if source.chars().count() > config.max_length {
        issues.push(Issue::new(
            field,
            "too_long",
            format!("The text is longer than {} characters.", config.max_length),
        ));
        return;
    }
    let ast = match parse(source, field, SyntaxConfig::default()) {
        Ok(ast) => ast,
        Err(error) => {
            issues.push(syntax_issue(field, source, &error));
            return;
        }
    };
    let mut checker = Checker {
        field,
        root: &ctx.info.variables,
        filters: ctx.filters,
        images: ctx.images,
        pdf: ctx.pdf,
        locale,
        max_depth: config.max_depth,
        depth: 0,
        too_deep: false,
        scopes: vec![HashMap::new()],
        issues: Vec::new(),
    };
    checker.stmt(&ast);
    issues.append(&mut checker.issues);
}

fn syntax_issue(field: &str, source: &str, error: &minijinja::Error) -> Issue {
    let mut issue = Issue::new(
        field,
        "syntax",
        format!(
            "The template's syntax is wrong: {}.",
            error.detail().unwrap_or("unexpected text")
        ),
    );
    if let Some(range) = error.range() {
        let before = &source[..range.start.min(source.len())];
        issue.line = Some(u32::try_from(before.matches('\n').count() + 1).unwrap_or(u32::MAX));
        let column = before.rsplit('\n').next().map_or(0, |line| line.chars().count());
        issue.column = Some(u32::try_from(column + 1).unwrap_or(u32::MAX));
    } else if let Some(line) = error.line() {
        issue.line = u32::try_from(line).ok();
    }
    issue
}

struct Checker<'a> {
    field: &'a str,
    root: &'a [Field],
    filters: &'a [FilterSpec],
    images: &'a [String],
    pdf: bool,
    locale: &'a str,
    max_depth: usize,
    depth: usize,
    too_deep: bool,
    scopes: Vec<HashMap<String, Node>>,
    issues: Vec<Issue>,
}

impl Checker<'_> {
    fn issue(&mut self, span: Span, code: &'static str, message: impl Into<String>) -> &mut Issue {
        self.issues.push(Issue::new(self.field, code, message).at(span));
        self.issues.last_mut().expect("just pushed")
    }

    fn forbid(&mut self, span: Span, what: &str) {
        self.issue(
            span,
            "forbidden_tag",
            format!("{what} can't be used in these templates."),
        );
    }

    fn stmts(&mut self, stmts: &[Stmt<'_>]) {
        for stmt in stmts {
            self.stmt(stmt);
        }
    }

    fn nested(&mut self, span: Span, body: impl FnOnce(&mut Self)) {
        self.depth += 1;
        if self.depth > self.max_depth && !self.too_deep {
            self.too_deep = true;
            let message = format!("`if` and `for` blocks are nested more than {} deep.", self.max_depth);
            self.issue(span, "too_deep", message);
        }
        body(self);
        self.depth -= 1;
    }

    fn stmt(&mut self, stmt: &Stmt<'_>) {
        match stmt {
            Stmt::Template(template) => self.stmts(&template.children),
            Stmt::EmitExpr(emit) => {
                self.expr(&emit.expr);
            }
            Stmt::EmitRaw(raw) => self.raw_images(raw.raw, raw.span()),
            Stmt::ForLoop(for_loop) => self.for_loop(for_loop, for_loop.span()),
            Stmt::IfCond(cond) => {
                self.expr(&cond.expr);
                self.nested(cond.span(), |this| {
                    this.stmts(&cond.true_body);
                    this.stmts(&cond.false_body);
                });
            }
            Stmt::Set(set) => {
                let node = self.expr(&set.expr);
                self.bind(&set.target, node);
            }
            Stmt::SetBlock(set) => {
                if let Some(filter) = &set.filter {
                    self.expr(filter);
                }
                self.stmts(&set.body);
                self.bind(&set.target, Node::Text);
            }
            Stmt::WithBlock(with) => {
                let assigned: Vec<(&Expr<'_>, Node)> =
                    with.assignments.iter().map(|(t, e)| (t, self.expr(e))).collect();
                self.scopes.push(HashMap::new());
                for (target, node) in assigned {
                    self.bind(target, node);
                }
                self.stmts(&with.body);
                self.scopes.pop();
            }
            Stmt::AutoEscape(s) => self.forbid(s.span(), "`autoescape`"),
            Stmt::FilterBlock(s) => self.forbid(s.span(), "`filter` blocks"),
            Stmt::Do(s) => self.forbid(s.span(), "`do`"),
        }
    }

    fn for_loop(&mut self, for_loop: &ast::ForLoop<'_>, span: Span) {
        if for_loop.recursive {
            self.forbid(span, "Recursive loops");
        }
        let iter = self.expr(&for_loop.iter);
        let item = match iter.required() {
            Node::List(item) => (**item).clone(),
            Node::Any => Node::Any,
            other => {
                let name = path_of(&for_loop.iter).unwrap_or_else(|| "this value".to_owned());
                let kind = other.type_name();
                let message = format!(
                    "`{name}` is {} {kind}, not a list; `for` goes over lists.",
                    article(kind)
                );
                let suggestion = self.list_near(&for_loop.iter);
                let issue = self
                    .issue(expr_span(&for_loop.iter).unwrap_or(span), "not_a_list", message)
                    .clone();
                *self.issues.last_mut().expect("just pushed") = issue.suggest(suggestion);
                Node::Any
            }
        };
        self.nested(span, |this| {
            this.scopes.push(HashMap::new());
            this.bind(&for_loop.target, item);
            this.scopes
                .last_mut()
                .expect("scope")
                .insert("loop".to_owned(), loop_node());
            if let Some(filter) = &for_loop.filter_expr {
                this.expr(filter);
            }
            this.stmts(&for_loop.body);
            this.scopes.pop();
            this.stmts(&for_loop.else_body);
        });
    }

    /// A list to suggest instead of a non-list: one inside the object itself (`order.items` for
    /// `order`), or next to the value (`order.items` for `order.total`).
    fn list_near(&self, expr: &Expr<'_>) -> Option<String> {
        let path = path_of(expr)?;
        let first_list = |fields: Vec<Field>, prefix: &str| {
            fields
                .iter()
                .find(|f| matches!(f.node.required(), Node::List(_)))
                .map(|f| crate::schema::join(prefix, f.name))
        };
        if let Some(inside) = self.lookup_path(&path).and_then(|node| node.fields())
            && let Some(found) = first_list(inside, &path)
        {
            return Some(found);
        }
        let (parent, _) = path.rsplit_once('.').unwrap_or(("", &path));
        let siblings = if parent.is_empty() {
            self.root.to_vec()
        } else {
            self.lookup_path(parent)?.fields()?
        };
        first_list(siblings, parent)
    }

    fn lookup_path(&self, path: &str) -> Option<Node> {
        let mut parts = path.split('.');
        let mut node = self.lookup(parts.next()?)?;
        for part in parts {
            node = node.fields()?.into_iter().find(|f| f.name == part)?.node;
        }
        Some(node)
    }

    fn bind(&mut self, target: &Expr<'_>, node: Node) {
        let scope = self.scopes.last_mut().expect("scope");
        match target {
            Expr::Var(var) => {
                scope.insert(var.id.to_owned(), node);
            }
            Expr::Tuple(tuple) => {
                for item in &tuple.items {
                    if let Expr::Var(var) = item {
                        scope.insert(var.id.to_owned(), Node::Any);
                    }
                }
            }
            _ => {}
        }
    }

    fn lookup(&self, name: &str) -> Option<Node> {
        for scope in self.scopes.iter().rev() {
            if let Some(node) = scope.get(name) {
                return Some(node.clone());
            }
        }
        self.root.iter().find(|f| f.name == name).map(|f| f.node.clone())
    }

    fn visible_names(&self) -> Vec<String> {
        let mut names: Vec<String> = self.root.iter().map(|f| f.name.to_owned()).collect();
        for scope in &self.scopes {
            names.extend(scope.keys().cloned());
        }
        names
    }

    fn expr(&mut self, expr: &Expr<'_>) -> Node {
        match expr {
            Expr::Var(var) => {
                if let Some(node) = self.lookup(var.id) {
                    return node;
                }
                if FUNCTIONS.contains(&var.id) {
                    let message = format!("`{0}` can only be called, as in `{0}(5)`.", var.id);
                    self.issue(var.span(), "forbidden_call", message);
                    return Node::Any;
                }
                let names = self.visible_names();
                let suggestion = closest(var.id, names.iter().map(String::as_str));
                let message = format!("There's no variable `{}`.", var.id);
                let issue = Issue::new(self.field, "unknown_variable", message)
                    .at(var.span())
                    .suggest(suggestion);
                self.issues.push(issue);
                Node::Any
            }
            Expr::Const(constant) => const_node(&constant.value),
            Expr::GetAttr(attr) => {
                let base = self.expr(&attr.expr);
                self.field_of(&base, &attr.expr, attr.name, attr.span())
            }
            Expr::GetItem(item) => {
                let base = self.expr(&item.expr);
                let key = self.expr(&item.subscript_expr);
                match (base.required(), &item.subscript_expr) {
                    (Node::List(inner), _) => (**inner).clone(),
                    (Node::Object(_) | Node::Recipient, Expr::Const(c)) if c.value.as_str().is_some() => {
                        let name = c.value.as_str().unwrap_or_default().to_owned();
                        self.field_of(&base, &item.expr, &name, item.span())
                    }
                    _ => {
                        let _ = key;
                        Node::Any
                    }
                }
            }
            Expr::Slice(slice) => {
                let base = self.expr(&slice.expr);
                for part in [&slice.start, &slice.stop, &slice.step].into_iter().flatten() {
                    self.expr(part);
                }
                base
            }
            Expr::UnaryOp(op) => {
                self.expr(&op.expr);
                match op.op {
                    ast::UnaryOpKind::Not => Node::Bool,
                    ast::UnaryOpKind::Neg => Node::Number,
                }
            }
            Expr::BinOp(op) => self.bin_op(op),
            Expr::Compare(compare) => {
                self.expr(&compare.expr);
                for op in &compare.ops {
                    self.expr(&op.expr);
                }
                Node::Bool
            }
            Expr::IfExpr(if_expr) => {
                self.expr(&if_expr.test_expr);
                let node = self.expr(&if_expr.true_expr);
                if let Some(other) = &if_expr.false_expr {
                    self.expr(other);
                }
                node
            }
            Expr::Filter(filter) => self.filter(filter, filter.span()),
            Expr::Test(test) => self.test(test, test.span()),
            Expr::Call(call) => self.call(call, call.span()),
            Expr::List(list) => {
                let mut item = Node::Any;
                for (i, entry) in list.items.iter().enumerate() {
                    let node = self.expr(entry);
                    if i == 0 {
                        item = node;
                    }
                }
                Node::List(Box::new(item))
            }
            Expr::Tuple(tuple) => {
                for entry in &tuple.items {
                    self.expr(entry);
                }
                Node::Any
            }
            Expr::Map(map) => {
                for entry in map.keys.iter().chain(&map.values) {
                    self.expr(entry);
                }
                Node::Any
            }
        }
    }

    /// Checks the `<img src>` written in the template's own text.
    fn raw_images(&mut self, raw: &str, span: Span) {
        for range in crate::assets::image_sources(raw) {
            let src = raw[range.clone()].trim();
            let Some(problem) = self.image_problem(src) else {
                continue;
            };
            let before = &raw[..range.start];
            let lines = before.matches('\n').count();
            let column = before.rsplit('\n').next().map_or(0, |line| line.chars().count());
            let mut issue = Issue::new(self.field, problem.0, problem.1).suggest(problem.2);
            issue.line = Some(u32::from(span.start_line) + u32::try_from(lines).unwrap_or(0));
            let start = if lines == 0 { u32::from(span.start_col) } else { 0 };
            issue.column = Some(start + u32::try_from(column).unwrap_or(0) + 1);
            self.issues.push(issue);
        }
    }

    /// Why `src` won't show, if it won't: its code, the message and a suggestion.
    fn image_problem(&self, src: &str) -> Option<(&'static str, String, Option<String>)> {
        if self.images.iter().any(|name| name == src) || src.starts_with("data:image/") {
            return None;
        }
        let lower = src.to_ascii_lowercase();
        if lower.starts_with("https://") || lower.starts_with("http://") {
            if !self.pdf {
                return None;
            }
            let message = format!(
                "PDFs don't load pictures from the internet, so `{src}` won't show; ask a developer to add it as a picture."
            );
            return Some(("remote_image", message, None));
        }
        let message = if self.images.is_empty() {
            format!("There's no picture `{src}`; developers add pictures in code.")
        } else {
            format!(
                "There's no picture `{src}`. The pictures are: {}.",
                self.images
                    .iter()
                    .map(|n| format!("`{n}`"))
                    .collect::<Vec<_>>()
                    .join(", ")
            )
        };
        Some((
            "unknown_image",
            message,
            closest(src, self.images.iter().map(String::as_str)),
        ))
    }

    fn test(&mut self, test: &ast::Test<'_>, span: Span) -> Node {
        self.expr(&test.expr);
        self.args(&test.args);
        if !TESTS.contains(&test.name) {
            let suggestion = closest(test.name, TESTS.iter().copied());
            let issue = Issue::new(self.field, "unknown_test", format!("There's no test `{}`.", test.name));
            self.issues.push(issue.at(span).suggest(suggestion));
        }
        Node::Bool
    }

    fn bin_op(&mut self, op: &ast::BinOp<'_>) -> Node {
        use ast::BinOpKind as K;
        let left = self.expr(&op.left);
        self.expr(&op.right);
        match op.op {
            K::Eq | K::Ne | K::Lt | K::Lte | K::Gt | K::Gte | K::ScAnd | K::ScOr | K::In => Node::Bool,
            K::Concat => Node::Text,
            K::Add if *left.required() == Node::Text => Node::Text,
            _ => Node::Number,
        }
    }

    fn call(&mut self, call: &ast::Call<'_>, span: Span) -> Node {
        self.args(&call.args);
        if let Expr::Var(var) = &call.expr
            && FUNCTIONS.contains(&var.id)
        {
            return Node::List(Box::new(Node::Number));
        }
        let name = path_of(&call.expr).unwrap_or_else(|| "this".to_owned());
        let message = format!("`{name}(...)` can't be called; templates only call `range`.");
        self.issue(span, "forbidden_call", message);
        Node::Any
    }

    fn args(&mut self, args: &[CallArg<'_>]) -> Vec<Node> {
        args.iter()
            .map(|arg| match arg {
                CallArg::Pos(e) | CallArg::Kwarg(_, e) | CallArg::PosSplat(e) | CallArg::KwargSplat(e) => self.expr(e),
            })
            .collect()
    }

    fn field_of(&mut self, base: &Node, base_expr: &Expr<'_>, name: &str, span: Span) -> Node {
        let base_name = path_of(base_expr).unwrap_or_else(|| "this value".to_owned());
        match base.required() {
            Node::Any => Node::Any,
            Node::Object(_) | Node::Recipient => {
                let fields = base.fields().unwrap_or_default();
                if let Some(field) = fields.iter().find(|f| f.name == name) {
                    return field.node.clone();
                }
                let suggestion = closest(name, fields.iter().map(|f| f.name)).map(|n| format!("{base_name}.{n}"));
                let message = format!("There's no `{base_name}.{name}`.");
                self.issues.push(
                    Issue::new(self.field, "unknown_variable", message)
                        .at(span)
                        .suggest(suggestion),
                );
                Node::Any
            }
            Node::List(_) => {
                let message = format!(
                    "`{base_name}` is a list, so it has no `{name}`; go over it with `{{% for item in {base_name} %}}` and use `item.{name}`."
                );
                self.issue(span, "unknown_variable", message);
                Node::Any
            }
            other => {
                let kind = other.type_name();
                let message = format!("`{base_name}` is {} {kind}, so it has no `{name}`.", article(kind));
                self.issue(span, "unknown_variable", message);
                Node::Any
            }
        }
    }

    fn filter(&mut self, filter: &ast::Filter<'_>, span: Span) -> Node {
        let input = filter.expr.as_ref().map_or(Node::Any, |e| self.expr(e));
        self.args(&filter.args);
        let Some(spec) = self.filters.iter().find(|f| f.name == filter.name).cloned() else {
            let suggestion = closest(filter.name, self.filters.iter().map(|f| f.name));
            let issue = Issue::new(
                self.field,
                "unknown_filter",
                format!("There's no filter `{}`.", filter.name),
            );
            self.issues.push(issue.at(span).suggest(suggestion));
            return Node::Any;
        };

        let positional: Vec<&Expr<'_>> = filter
            .args
            .iter()
            .filter_map(|arg| match arg {
                CallArg::Pos(e) => Some(e),
                _ => None,
            })
            .collect();
        if positional.len() < spec.min_args() || positional.len() > spec.max_args() {
            let message = format!(
                "`{}` takes {}; it was given {}.",
                spec.name,
                describe_args(&spec),
                positional.len()
            );
            self.issue(span, "filter_arguments", message);
        }
        for (i, arg) in positional.iter().enumerate() {
            let declared = spec.args.get(i).or(spec.args.last()).map_or(ArgKind::Any, |a| a.kind);
            if let Expr::Const(constant) = arg {
                let fits = match declared {
                    ArgKind::Text => constant.value.as_str().is_some(),
                    ArgKind::Number => constant.value.is_number(),
                    ArgKind::Any => true,
                };
                if !fits {
                    let wanted = if declared == ArgKind::Text {
                        "text in quotes"
                    } else {
                        "a number"
                    };
                    let message = format!("`{}`'s argument {} should be {wanted}.", spec.name, i + 1);
                    self.issue(constant.span(), "filter_arguments", message);
                }
            }
        }
        self.special_filter_checks(&spec, &positional, span);

        let wrong_input = match (spec.input, input.required()) {
            (InputKind::Number, Node::Text | Node::Bool | Node::List(_) | Node::Object(_) | Node::Recipient) => {
                Some("a number")
            }
            (InputKind::Date, Node::Number | Node::Bool | Node::List(_) | Node::Object(_) | Node::Recipient) => {
                Some("a date")
            }
            _ => None,
        };
        if let Some(wanted) = wrong_input {
            let name = filter
                .expr
                .as_ref()
                .and_then(path_of)
                .unwrap_or_else(|| "the value".to_owned());
            let kind = input.type_name();
            let message = format!(
                "`{}` needs {wanted}, but `{name}` is {} {kind}.",
                spec.name,
                article(kind)
            );
            self.issue(span, "filter_input", message);
        }

        match spec.name {
            "round" | "abs" | "int" | "float" | "length" | "sum" => Node::Number,
            "first" | "last" | "min" | "max" => match input.required() {
                Node::List(item) => (**item).clone(),
                _ => Node::Any,
            },
            "sort" | "reverse" | "unique" | "default" => input,
            "money" | "number" | "date" | "plural" | "upper" | "lower" | "title" | "capitalize" | "trim"
            | "replace" | "join" | "string" => Node::Text,
            _ => Node::Any,
        }
    }

    fn special_filter_checks(&mut self, spec: &FilterSpec, args: &[&Expr<'_>], span: Span) {
        let constant = |i: usize| match args.get(i) {
            Some(Expr::Const(c)) => c.value.as_str().map(ToOwned::to_owned),
            _ => None,
        };
        match spec.name {
            "date" => {
                if let Some(format) = constant(0)
                    && let Err(message) = check_date_format(&format)
                {
                    self.issue(span, "filter_arguments", message);
                }
            }
            "money" => {
                if let Some(code) = constant(0)
                    && let Err(message) = filters::money(self.locale, &minijinja::Value::from(1), &code)
                {
                    self.issue(span, "filter_arguments", message);
                }
            }
            "plural" => {
                let Ok(categories) = plural_categories(self.locale) else {
                    return;
                };
                if !args.is_empty() && args.len() < categories.len() {
                    let names: Vec<&str> = categories.iter().map(|c| category_name(*c)).collect();
                    let message = format!(
                        "`{}` needs {} word forms for `plural`, one for each of: {}; it was given {}.",
                        self.locale,
                        categories.len(),
                        names.join(", "),
                        args.len()
                    );
                    self.issue(span, "plural_forms", message);
                }
            }
            _ => {}
        }
    }
}

fn describe_args(spec: &FilterSpec) -> String {
    let (min, max) = (spec.min_args(), spec.max_args());
    let plural = |n: usize| if n == 1 { "argument" } else { "arguments" };
    match (min, max) {
        (_, usize::MAX) => format!("at least {min} {}", plural(min)),
        (0, 0) => "no arguments".to_owned(),
        (min, max) if min == max => format!("{min} {}", plural(min)),
        (min, max) => format!("{min} to {max} arguments"),
    }
}

fn article(kind: &str) -> &'static str {
    if kind.starts_with(['a', 'e', 'i', 'o', 'u']) {
        "an"
    } else {
        "a"
    }
}

fn loop_node() -> Node {
    let number = |name| Field::new(name, "", Node::Number);
    let flag = |name| Field::new(name, "", Node::Bool);
    Node::Object(vec![
        number("index"),
        number("index0"),
        number("revindex"),
        number("revindex0"),
        number("length"),
        number("depth"),
        number("depth0"),
        flag("first"),
        flag("last"),
    ])
}

fn const_node(value: &minijinja::Value) -> Node {
    if value.as_str().is_some() {
        Node::Text
    } else if value.is_number() {
        Node::Number
    } else if value.kind() == minijinja::value::ValueKind::Bool {
        Node::Bool
    } else {
        Node::Any
    }
}

/// `order.items` for a chain of variables and attributes.
fn path_of(expr: &Expr<'_>) -> Option<String> {
    match expr {
        Expr::Var(var) => Some(var.id.to_owned()),
        Expr::GetAttr(attr) => Some(format!("{}.{}", path_of(&attr.expr)?, attr.name)),
        _ => None,
    }
}

fn expr_span(expr: &Expr<'_>) -> Option<Span> {
    match expr {
        Expr::Var(e) => Some(e.span()),
        Expr::GetAttr(e) => Some(e.span()),
        Expr::GetItem(e) => Some(e.span()),
        Expr::Filter(e) => Some(e.span()),
        Expr::Call(e) => Some(e.span()),
        _ => None,
    }
}

/// The candidate closest to `wanted`, when it's close enough to be a typo.
pub(crate) fn closest<'a>(wanted: &str, candidates: impl IntoIterator<Item = &'a str>) -> Option<String> {
    let limit = (wanted.chars().count() / 3).max(2);
    candidates
        .into_iter()
        .map(|candidate| (strsim::damerau_levenshtein(wanted, candidate), candidate))
        .filter(|(distance, _)| *distance <= limit)
        .min_by_key(|(distance, _)| *distance)
        .map(|(_, candidate)| candidate.to_owned())
}