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::assets::Assets;
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};
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Issue {
pub field: String,
pub line: Option<u32>,
pub column: Option<u32>,
pub code: &'static str,
pub message: String,
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),
}
}
}
struct Context<'a> {
info: &'a TypeInfo,
filters: &'a [FilterSpec],
images: &'a [String],
layouts: &'a [String],
channels: &'a [String],
pdf: bool,
config: &'a TemplateEngineConfig,
}
pub(crate) fn check_input(input: &TemplateInput, assets: &Assets, 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(assets.filters.iter().map(|f| f.spec.clone()));
let images = assets.image_names();
let layouts = assets.layout_names();
let channels = assets.channel_names();
let pdf = matches!(&input.settings, Settings::Document(d) if d.format == DocumentFormat::Pdf);
let ctx = Context {
info: &info,
filters: &filters,
images: &images,
layouts: &layouts,
channels: &channels,
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 input.kind() == Kind::Notification && !content.subject.is_empty() {
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(),
_ => None,
};
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.",
));
}
}
Settings::Notification(notification) => {
let channel = notification.channel.trim();
if channel.is_empty() {
issues.push(Issue::new(
"settings.channel",
"required",
"Choose the channel the text is for.",
));
} else if !ctx.channels.iter().any(|c| c == channel) {
let message = format!(
"There's no channel `{channel}`. The channels are: {}.",
ctx.channels
.iter()
.map(|c| format!("`{c}`"))
.collect::<Vec<_>>()
.join(", ")
);
let suggestion = closest(channel, ctx.channels.iter().map(String::as_str));
issues.push(Issue::new("settings.channel", "unknown_channel", message).suggest(suggestion));
}
}
}
}
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));
}
}
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);
});
}
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
}
}
}
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);
}
}
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
}
}
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,
}
}
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())
}