@@ -1,48 +1,26 @@
1use std::collections::{HashMap, HashSet};
1use std::collections::{HashMap, HashSet};
3use std::path::{Path, PathBuf};
2use std::path::{Path, PathBuf};
5use crate::ast::*;
5use crate::ast::*;
6−use crate::syntax::{self, Syntax};
6+use crate::diagnostic::code;
7+pub use crate::diagnostic::{Diagnostic, Severity};
8+use crate::interp::{self, Sink};
9+use crate::syntax::{self, DirectiveArgs, LetForm, NodeKind, Segment, Tree};
10+use crate::value::{self, Value};
8// ---------------------------------------------------------------------------
12// ---------------------------------------------------------------------------
9// Public types
13// Public types
10// ---------------------------------------------------------------------------
14// ---------------------------------------------------------------------------
12−#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20−#[derive(Debug, Clone)]
21−pub struct Diagnostic {
23− pub column: Option<usize>,
25− pub severity: Severity,
26− pub source_line: Option<String>,
29pub struct ParseResult {
16pub struct ParseResult {
30 pub document: Document,
17 pub document: Document,
31 pub diagnostics: Vec<Diagnostic>,
18 pub diagnostics: Vec<Diagnostic>,
32 pub included_files: Vec<PathBuf>,
19 pub included_files: Vec<PathBuf>,
35−#[derive(Debug)]
22+/// An error that stops one line from being evaluated.
36−struct ParseError {
23+type ParseError = Diagnostic;
41−impl fmt::Display for ParseError {
42− fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
43− write!(f, "line {}: {}", self.line, self.message)
47// ---------------------------------------------------------------------------
25// ---------------------------------------------------------------------------
48// Internal types
26// Internal types
@@ -50,28 +28,166 @@ impl fmt::Display for ParseError {
51#[derive(Clone)]
29#[derive(Clone)]
52struct FnDef {
30struct FnDef {
53− params: Vec<String>,
31+ /// The parameters in the order they are declared; one without a
54− defaults: HashMap<String, String>,
32+ /// default is required.
55− body: Vec<Syntax>,
33+ params: Vec<syntax::Param>,
34+ /// The definition's line and its text (when it is one physical line),
35+ /// and its node, for diagnostics about a default.
37+ source: Option<String>,
39+ body: Vec<syntax::Node>,
40+ /// The file it is defined in, when that isn't the file being compiled
41+ /// (see `ParseContext::current_file`).
42+ file: Option<String>,
43+ /// The slots its body declares (`@slot NAME`), in order.
45+ /// Whether its body has a `@children` for the content of a call.
47+ /// Its scoped `@style`: its class (`hl-fn-NAME-HASH`), and the
48+ /// stylesheet nested under it, written into the page once the function
49+ /// is called (see `Document::scoped_css`).
50+ scoped: Option<(String, String)>,
51+ /// What was visible where it was defined: its body and its defaults
52+ /// see this, plus its parameters.
54+ /// It is named like a built-in element and its body calls that name
55+ /// outside any `@if`, meaning the element (`@let @nav` around `@nav`):
56+ /// it would call itself forever, so a call writes nothing (the
57+ /// definition's error says so).
62+ fn is_param(&self, name: &str) -> bool {
63+ self.params.iter().any(|p| p.name == name)
67+/// What a name means: every `@let`, parameter, loop variable and `@data`
68+/// binds one, and they share one namespace.
72+ Bundle(Rc<Vec<Attribute>>),
76+/// The names visible at a line: one frame per block it is in (the
77+/// standard library, the file, an element's children, an `@if` branch, an
78+/// iteration of `@each`, a function's body), the innermost last. A
79+/// definition goes into the innermost frame, so it is visible from its
80+/// line to the end of its block. A function keeps the frames visible
81+/// where it is defined; a frame is shared until one side changes it.
82+#[derive(Clone, Default)]
84+ frames: Vec<Rc<HashMap<String, Binding>>>,
89+ self.frames.push(Rc::default());
96+ /// Give `name` a meaning in the innermost frame, replacing what it
97+ /// meant there and hiding what it means outside it.
98+ fn define(&mut self, name: &str, binding: Binding) {
99+ if self.frames.is_empty() {
102+ if let Some(frame) = self.frames.last_mut() {
103+ Rc::make_mut(frame).insert(name.to_string(), binding);
107+ /// What `name` means here: the innermost definition.
108+ fn get(&self, name: &str) -> Option<&Binding> {
109+ self.frames.iter().rev().find_map(|frame| frame.get(name))
112+ fn value(&self, name: &str) -> Option<&Value> {
113+ match self.get(name)? {
114+ Binding::Value(value) => Some(value),
119+ fn bundle(&self, name: &str) -> Option<&Rc<Vec<Attribute>>> {
120+ match self.get(name)? {
121+ Binding::Bundle(attrs) => Some(attrs),
126+ fn function(&self, name: &str) -> Option<&Rc<FnDef>> {
127+ match self.get(name)? {
128+ Binding::Function(function) => Some(function),
133+ /// Every name visible here, with what it means.
134+ fn visible(&self) -> HashMap<&str, &Binding> {
135+ let mut names = HashMap::new();
136+ for frame in &self.frames {
137+ for (name, binding) in frame.iter() {
138+ names.insert(name.as_str(), binding);
144+ /// The names of the values visible here.
145+ fn value_names(&self) -> Vec<&str> {
148+ .filter(|(_, binding)| matches!(binding, Binding::Value(_)))
149+ .map(|(name, _)| name)
153+ /// The names of the bundles visible here.
154+ fn bundle_names(&self) -> Vec<&str> {
157+ .filter(|(_, binding)| matches!(binding, Binding::Bundle(_)))
158+ .map(|(name, _)| name)
163+impl interp::Scope for Env {
164+ fn get(&self, name: &str) -> Option<Value> {
165+ self.value(name).cloned()
58struct ParseContext {
169struct ParseContext {
59 /// Source line currently being parsed, for diagnostics raised deep
170 /// Source line currently being parsed, for diagnostics raised deep
60 /// inside helpers that don't take a line number.
171 /// inside helpers that don't take a line number.
61 current_line: usize,
172 current_line: usize,
62− /// Functions whose body has a scoped @style block.
173+ /// What the `@page` said, once one has run
63− scoped_functions: std::collections::HashSet<String>,
174+ page: Option<Page>,
64− page_title: Option<String>,
175+ /// Where that `@page` is, for the error a second one gets
65− lang: Option<String>,
176+ page_at: Option<String>,
66− favicon: Option<String>,
67 meta_tags: Vec<(String, String)>,
177 meta_tags: Vec<(String, String)>,
68 head_blocks: Vec<String>,
178 head_blocks: Vec<String>,
69− variables: HashMap<String, String>,
179+ /// The first `@meta` or `@head` that ran, for the warning a file
70− defines: HashMap<String, Vec<Attribute>>,
180+ /// without `@page` gets: a fragment has no `<head>` for them.
71− functions: HashMap<String, FnDef>,
181+ head_at: Option<usize>,
72− keyframes: Vec<(String, String)>,
182+ /// What each name means at the line being evaluated.
184+ /// Every function whose definition ran, by name (the last one), for
185+ /// the checks of code that never runs.
186+ defined_functions: HashMap<String, Rc<FnDef>>,
73 css_vars: Vec<(String, String)>,
187 css_vars: Vec<(String, String)>,
74 custom_css: Vec<String>,
188 custom_css: Vec<String>,
189+ /// The scoped `@style` of each function called so far
190+ scoped_css: Vec<String>,
75 og_tags: Vec<(String, String)>,
191 og_tags: Vec<(String, String)>,
76 diagnostics: Vec<Diagnostic>,
192 diagnostics: Vec<Diagnostic>,
77 base_path: Option<PathBuf>,
193 base_path: Option<PathBuf>,
@@ -91,42 +207,550 @@ struct ParseContext {
91 fn_lines: HashMap<String, usize>,
207 fn_lines: HashMap<String, usize>,
92 /// Line numbers of attribute bundle definitions (name -> line)
208 /// Line numbers of attribute bundle definitions (name -> line)
93 define_lines: HashMap<String, usize>,
209 define_lines: HashMap<String, usize>,
94− /// Canonical URL
210+ /// Syntax nodes evaluated at least once, by id.
95− canonical: Option<String>,
211+ visited: HashSet<usize>,
96− /// Base URL for relative links
212+ /// The id the next parsed tree starts at, so ids are unique across
97− base_url: Option<String>,
213+ /// the file, its includes and the standard library.
98− /// Track @import paths for circular dependency detection
214+ next_id: usize,
99− import_stack: Vec<PathBuf>,
215+ /// The file's tree and those of the files it includes, with the
216+ /// include chain that leads to each, for the checks of code that never
218+ trees: Vec<(Rc<Tree>, Option<String>)>,
219+ /// The files each `@include` line brought in (by the line's node id),
220+ /// with the include chain that leads to each, so the checks of
221+ /// `@slot` and `@children` see an included file's lines where the
222+ /// `@include` is written.
223+ included_by: Rc<IncludedBy>,
224+ /// Every function defined anywhere in the file or the files it
225+ /// includes, whether or not its definition runs.
226+ namespace: HashSet<String>,
227+ /// The line being evaluated, and its text as written when it is one
228+ /// physical line, for diagnostics that point at a column.
229+ current_source: (usize, Option<String>),
230+ /// Variable diagnostics already reported, so a line evaluated many
231+ /// times (in a loop, in a function) reports each problem once.
232+ /// Keyed by the syntax node (ids are unique across files), line,
233+ /// column and message.
234+ reported: HashSet<(usize, usize, Option<usize>, String)>,
235+ /// The id of the syntax node being evaluated.
236+ current_node: usize,
237+ /// The file whose lines are being evaluated, when it isn't the file
238+ /// being compiled: the standard library, or an included file (by its
240+ current_file: Option<String>,
241+ /// A call went deeper than [`MAX_CALL_DEPTH`]: the calls it is nested
242+ /// in expand to nothing, until the outermost one returns.
244+ /// A bundle's attributes are being read: a name that could be a
245+ /// parameter of the function the bundle is passed to is checked where
246+ /// the bundle is used instead.
248+ /// `@page`'s attributes are being read: a name close to `favicon` is
249+ /// a misspelled word of `@page`'s.
253+/// How deeply function calls may nest, so that a function that calls
254+/// itself without an `@if` that stops it is an error instead of a hang.
255+const MAX_CALL_DEPTH: usize = 64;
257+/// A CSS rule at the top level of a stylesheet that starts with `&`
258+/// (outside any `{}`, strings and comments).
259+fn has_top_level_ampersand(css: &str) -> bool {
260+ let mut depth = 0usize;
261+ let mut chars = css.chars().peekable();
262+ let mut at_rule_start = true;
263+ while let Some(c) = chars.next() {
265+ '/' if chars.peek() == Some(&'*') => {
268+ for c in chars.by_ref() {
269+ if last == '*' && c == '/' {
277+ for d in chars.by_ref() {
284+ '}' => depth = depth.saturating_sub(1),
285+ '&' if depth == 0 && at_rule_start => return true,
288+ at_rule_start = match c {
289+ '{' | '}' | ';' => true,
290+ c if c.is_whitespace() => at_rule_start,
297+/// Whether a file is a library (see [`Tree::is_library`]), with the files
298+/// its `@include` lines name read relative to `base`.
301+ base: Option<&Path>,
302+ ctx: &mut ParseContext,
303+ seen: &mut Vec<PathBuf>,
305+ tree.is_library_with(&mut |path| {
306+ if path.contains('$') {
309+ let resolved = base.map_or_else(|| PathBuf::from(path), |base| base.join(path));
310+ if seen.contains(&resolved) {
313+ seen.push(resolved.clone());
314+ let Ok(text) = ctx.read_file(&resolved) else {
317+ let included = syntax::parse(&text);
318+ is_library_file(&included, resolved.parent(), ctx, seen)
322+/// The frames around the file's top level: the standard library's and
323+/// the file's own (see [`load_prelude`]).
324+const FILE_FRAMES: usize = 2;
102/// Evaluates a syntax tree (see `syntax.rs`) into the document's nodes.
326/// Evaluates a syntax tree (see `syntax.rs`) into the document's nodes.
103struct Evaluator;
327struct Evaluator;
105impl ParseContext {
329impl ParseContext {
106− /// Evaluate an expression (see `expr.rs`), reporting errors at `line`.
330+ /// Bind a value to `name` in the innermost block.
107− fn eval(&mut self, src: &str, line: usize) -> Option<crate::expr::Value> {
331+ fn bind(&mut self, name: &str, value: Value) {
332+ self.env.define(name, Binding::Value(value));
335+ /// Evaluate an expression (see `expr.rs`) written at `line` and
336+ /// `column` (when known), reporting its errors there.
341+ column: Option<usize>,
342+ ) -> Option<crate::expr::Value> {
108 track_var_refs(src, &mut self.used_variables);
343 track_var_refs(src, &mut self.used_variables);
109− let vars = &self.variables;
344+ match crate::expr::eval(src, &self.env) {
110− let resolve = |name: &str| vars.get(name).cloned();
111− let result = crate::expr::eval(src, &resolve);
113 Ok(value) => Some(value),
345 Ok(value) => Some(value),
114− Err(message) => {
346+ Err(error) => {
115− self.diagnostics.push(Diagnostic {
347+ // Without the line to point into, show the expression
116− line,
348+ let shown = matches!(&self.current_source, (current, Some(_)) if *current == line);
117− column: None,
349+ let before = self.diagnostics.len();
118− message: format!("invalid expression: {}", message),
350+ self.report(error.at(0), line, column);
119− severity: Severity::Error,
351+ if !shown && let Some(diagnostic) = self.diagnostics.get_mut(before) {
120− source_line: Some(src.to_string()),
352+ diagnostic.source_line = Some(src.into());
127 /// Evaluate a condition; an invalid one is reported and counts as false.
359 /// Evaluate a condition; an invalid one is reported and counts as false.
128− fn condition(&mut self, src: &str, line: usize) -> bool {
360+ fn condition(&mut self, src: &str, line: usize, column: Option<usize>) -> bool {
129− self.eval(src, line).is_some_and(|value| value.truthy())
361+ self.eval(src, line, column)
362+ .is_some_and(|value| value.truthy())
365+ /// Fill in one slot of htmlang text written at `line` and `column`
366+ /// (when known), for `sink`: its escapes stand for themselves and its
367+ /// variables are filled in (see `interp.rs`). What can't be filled is
368+ /// left as written and reported; the flag says whether everything was
374+ column: Option<usize>,
376+ ) -> (String, bool) {
377+ let (filled, ok) = self.fill_protected(raw, line, column, sink);
378+ (restore_escapes(&filled), ok)
381+ /// [`fill`](Self::fill) for text.
382+ fn interpolate_text(&mut self, raw: &str, line: usize, column: Option<usize>) -> String {
383+ self.fill(raw, line, column, Sink::Text).0
386+ /// [`fill`](Self::fill), with the escapes still placeholders (see
387+ /// [`protect_escapes`]).
392+ column: Option<usize>,
394+ ) -> (String, bool) {
395+ let mut protected = protect_escapes(raw);
396+ if sink == Sink::Css {
397+ protected = keep_css_string_escapes(&protected);
399+ if !protected.contains('$') {
400+ return (protected, true);
402+ track_var_refs(&protected, &mut self.used_variables);
403+ let (out, problems) = interp::interpolate_for(&protected, &self.env, sink);
404+ let filled = problems.is_empty();
405+ for mut problem in problems {
406+ match &mut problem {
407+ interp::Problem::Undefined { offset, .. }
408+ | interp::Problem::CustomProperty { offset, .. }
409+ | interp::Problem::Invalid { offset, .. }
410+ | interp::Problem::Record { offset, .. } => {
411+ // An offset into the protected text, as one into `raw`
412+ *offset = protected[..*offset]
414+ .map(|c| escape_of(c).map_or(c.len_utf8(), str::len))
418+ self.report(problem, line, column);
423+ /// Fill in a value slot (an attribute's value, a `@let` value, `@meta`'s
424+ /// value) for `sink`, and say whether it is quoted text: one `"..."`, or
425+ /// one variable that holds quoted text. Quoted text keeps its quotes
431+ column: Option<usize>,
433+ ) -> (String, Option<Quoted>, bool) {
434+ if let Some(inner) = syntax::quoted_string(raw) {
435+ let (css, ok) = self.fill(raw, line, column, Sink::Css);
436+ // Already reported by the CSS pass, so filled in quietly
437+ let (text, _) = interp::interpolate(&protect_escapes(inner), &self.env);
438+ let quoted = Quoted {
439+ text: restore_escapes(&text),
442+ let out = match sink {
443+ Sink::Css => quoted.css.clone(),
444+ Sink::Text => quoted.text.clone(),
446+ return (out, Some(quoted), ok);
448+ let (out, ok) = self.fill(raw, line, column, sink);
449+ let quoted = whole_reference(raw, &self.env).and_then(|path| {
450+ match interp::resolve(&path, &self.env)? {
451+ Value::Quoted(quoted) => Some(quoted),
458+ /// The value of a value slot (a `@let` value, the source of `@each`, a
459+ /// parameter's value or default), written at `line` and `column`:
461+ /// - exactly one `$name` or `${...}` is the value it holds or gives,
462+ /// whatever its type (a list, a record, quoted text);
463+ /// - one `"..."` is quoted text;
464+ /// - commas outside quotes, brackets and `${...}`, and not escaped
465+ /// (`\,`), make a list, which prints as written;
466+ /// - `A..B` or `A..B step N` with whole numbers is a range;
467+ /// - anything else is text, with its variables filled in.
469+ /// What can't be filled in is reported; the flag says whether
471+ fn slot_value(&mut self, raw: &str, line: usize, column: Option<usize>) -> (Value, bool) {
472+ let trimmed = raw.trim();
473+ let column = column.map(|c| c + (raw.len() - raw.trim_start().len()));
474+ if let Some(value) = self.whole_value(trimmed, line, column) {
477+ if syntax::quoted_string(trimmed).is_some() {
478+ let (text, quoted, ok) = self.fill_value(trimmed, line, column, Sink::Text);
479+ return (quoted.map_or(Value::Str(text), Value::Quoted), ok);
481+ let parts = syntax::split_list(trimmed);
482+ if parts.len() > 1 {
483+ // Each item is a value of its own; the list prints as written
484+ let mut items = Vec::new();
485+ let mut written = String::new();
489+ let item = &trimmed[part.clone()];
490+ let lead = item.len() - item.trim_start().len();
491+ written.push_str(&trimmed[end..part.start + lead]);
492+ end = part.start + lead + item.trim().len();
493+ if item.trim().is_empty() {
496+ let at = column.map(|c| c + part.start + lead);
497+ let (value, text, filled) = self.item_value(item.trim(), line, at);
499+ written.push_str(&text);
502+ written.push_str(&trimmed[end..]);
503+ let list = value::List {
504+ items: Rc::new(items),
505+ written: Some(written.into()),
507+ return (Value::List(list), ok);
509+ let (text, ok) = self.fill(trimmed, line, column, Sink::Text);
510+ match value::written_range(&text) {
511+ Some(Ok(range)) => (range, ok),
512+ Some(Err(message)) => {
514+ interp::Problem::Invalid { message, offset: 0 },
518+ (Value::list(Vec::new()), false)
520+ None => (Value::Str(text), ok),
524+ /// An item of a list written in the source (see
525+ /// [`slot_value`](Self::slot_value)), and how it is written in the
531+ column: Option<usize>,
532+ ) -> (Value, String, bool) {
533+ let (value, ok) = match self.whole_value(item, line, column) {
534+ Some(value) => value,
535+ None if syntax::quoted_string(item).is_some() => {
536+ let (text, quoted, ok) = self.fill_value(item, line, column, Sink::Text);
537+ (quoted.map_or(Value::Str(text), Value::Quoted), ok)
540+ let (text, ok) = self.fill(item, line, column, Sink::Text);
541+ (Value::Str(text), ok)
544+ // Quoted text keeps its quotes in the list's text, as written
547+ .map_or_else(|| value.to_string(), str::to_string);
551+ /// The value of a slot that is exactly one `$name` or `${...}`, with its
552+ /// type; `None` when it is anything else.
557+ column: Option<usize>,
558+ ) -> Option<(Value, bool)> {
559+ let after = raw.strip_prefix('$')?;
560+ let (reference, len) = interp::reference(after, &self.env)?;
561+ if len != after.len() {
564+ track_var_refs(raw, &mut self.used_variables);
565+ let problem = match reference {
566+ interp::Reference::Var(path) => match interp::resolve(&path, &self.env) {
567+ Some(value) => return Some((value, true)),
568+ None => interp::Problem::Undefined {
573+ interp::Reference::Expr(source) => match crate::expr::eval(source, &self.env) {
574+ Ok(value) => return Some((value, true)),
575+ Err(crate::expr::Error::Invalid(message)) => {
576+ interp::Problem::Invalid { message, offset: 0 }
578+ Err(error) => error.at(2),
581+ self.report(problem, line, column);
582+ Some((Value::Str(raw.to_string()), false))
585+ /// Report a variable that can't be filled in, or an invalid `${...}`,
586+ /// at `offset` from `column`.
587+ fn report(&mut self, problem: interp::Problem, line: usize, column: Option<usize>) {
588+ let (line_text, column) = match &self.current_source {
589+ // The column is only shown with the line it points into
590+ (current, Some(text)) if *current == line => (Some(text.clone()), column),
593+ let diagnostic = match problem {
594+ interp::Problem::Undefined { name, offset } => {
595+ let column = column.map(|c| c + offset);
596+ let mut diagnostic = self.undefined(&name, line);
597+ if let Some(column) = column {
598+ diagnostic = diagnostic.column(column);
602+ interp::Problem::Invalid { message, offset } => {
603+ let diagnostic = Diagnostic::error(
604+ code::INVALID_EXPRESSION,
606+ format!("invalid expression: {}", message),
609+ Some(column) => diagnostic.column(column + offset),
613+ interp::Problem::CustomProperty { name, offset } => {
614+ let diagnostic = Diagnostic::error(
615+ code::INVALID_VALUE,
617+ interp::custom_property_message(&name),
619+ .subject(format!("${}", name))
620+ .suggest(Some(format!("var({})", name)));
622+ Some(column) => diagnostic.column(column + offset),
626+ interp::Problem::Record { message, offset } => {
627+ let diagnostic = Diagnostic::error(code::INVALID_VALUE, line, message);
629+ Some(column) => diagnostic.column(column + offset),
634+ let diagnostic = match line_text {
635+ Some(text) => diagnostic.source(text),
638+ self.push_once(diagnostic);
641+ /// Report a diagnostic unless the node being evaluated already did,
642+ /// so a line evaluated many times (in a loop, in a function) reports
643+ /// each problem once.
644+ fn push_once(&mut self, diagnostic: Diagnostic) {
649+ diagnostic.message.clone(),
651+ if self.reported.insert(key) {
652+ self.diagnostics.push(diagnostic);
656+ /// The error for `$name` with no definition: what the name is if it is
657+ /// something else, or the closest defined name.
658+ fn undefined(&mut self, name: &str, line: usize) -> Diagnostic {
659+ if self.env.bundle(name).is_some() {
660+ // Reported here, so not also as unused
661+ self.used_defines.insert(name.to_string());
662+ return Diagnostic::error(
663+ code::UNDEFINED_VARIABLE,
666+ "'${}' is an attribute bundle, not a value: it goes in an attribute list \
667+ as a whole attribute, `[${}]`",
673+ if self.env.function(name).is_some() {
674+ self.used_functions.insert(name.to_string());
675+ return Diagnostic::error(
676+ code::UNDEFINED_VARIABLE,
679+ "'${}' is a function, not a value: it is called as an element, `@{}`",
685+ // `$i-label` where `$i` is defined: a `-` joins a name
686+ if let Some((defined, rest)) = name
688+ .map(|(i, _)| (&name[..i], &name[i..]))
689+ .find(|(before, _)| self.env.value(before).is_some())
691+ return Diagnostic::error(
692+ code::UNDEFINED_VARIABLE,
695+ "undefined variable '${}': a `-` is part of a name. For '${}' followed \
696+ by '{}', write `${{{}}}{}`",
697+ name, defined, rest, defined, rest
702+ let suggestion = suggest_var_name(name, &self.env.value_names());
703+ let message = match (&suggestion, self.let_lines.get(name)) {
704+ (Some(closest), _) => format!(
705+ "undefined variable '${}', did you mean '${}'?",
708+ // Defined, but not where this line can see it
709+ (None, Some(_)) => format!(
710+ "undefined variable '${}': a `@let` defines it, but not where this line \
711+ can see it. A definition is visible from its line to the end of its \
712+ block, and a function's body sees what is defined above the function",
715+ (None, None) => format!("undefined variable '${}'", name),
717+ Diagnostic::error(code::UNDEFINED_VARIABLE, line, message)
719+ .suggest(suggestion)
722+ /// Note the node being evaluated, for diagnostics.
723+ fn enter(&mut self, node: &syntax::Node) {
724+ self.current_line = node.span.line;
725+ self.current_node = node.id;
727+ (node.line_count <= 1).then(|| format!("{}{}", " ".repeat(node.indent), node.source));
728+ self.current_source = (node.span.line, text);
731+ /// Parse a file's text into a tree whose ids don't clash with the
732+ /// trees parsed before it.
733+ fn parse_tree(&mut self, text: &str) -> Rc<Tree> {
734+ let tree = syntax::parse_from(text, self.next_id);
735+ self.next_id = tree.end_id;
739+ /// Read a file (once), relative to the current file.
740+ fn read_file(&mut self, resolved: &Path) -> std::io::Result<String> {
741+ if let Some(cached) = self.file_cache.get(resolved) {
742+ return Ok(cached.clone());
744+ let text = std::fs::read_to_string(resolved)?;
745+ self.file_cache.insert(resolved.to_path_buf(), text.clone());
749+ fn resolve(&self, filename: &str) -> PathBuf {
750+ match &self.base_path {
751+ Some(base) => base.join(filename),
752+ None => PathBuf::from(filename),
@@ -135,11 +759,19 @@ impl ParseContext {
135const PRELUDE: &str = include_str!("std.hl");
759const PRELUDE: &str = include_str!("std.hl");
137fn load_prelude(ctx: &mut ParseContext) {
761fn load_prelude(ctx: &mut ParseContext) {
138− let _ = Evaluator.eval_block(&syntax::parse(PRELUDE), ctx);
762+ // The library's definitions are in a block of their own, around the
763+ // file's, so the file's own `@let` of the same name hides them
765+ let tree = ctx.parse_tree(PRELUDE);
766+ collect_namespace(&tree.nodes, None, &mut HashSet::new(), ctx);
767+ ctx.current_file = Some("std.hl".to_string());
768+ let _ = Evaluator.eval_block(&tree.nodes, ctx);
769+ ctx.current_file = None;
139 // Library definitions aren't the file's own: never report them unused.
770 // Library definitions aren't the file's own: never report them unused.
140 ctx.fn_lines.clear();
771 ctx.fn_lines.clear();
141 ctx.define_lines.clear();
772 ctx.define_lines.clear();
142 ctx.let_lines.clear();
773 ctx.let_lines.clear();
145pub fn parse(input: &str) -> ParseResult {
777pub fn parse(input: &str) -> ParseResult {
@@ -147,21 +779,18 @@ pub fn parse(input: &str) -> ParseResult {
149pub fn parse_with_base(input: &str, base_path: Option<&Path>) -> ParseResult {
781pub fn parse_with_base(input: &str, base_path: Option<&Path>) -> ParseResult {
150− let tree = syntax::parse(input);
151 let mut ctx = ParseContext {
782 let mut ctx = ParseContext {
152 current_line: 0,
783 current_line: 0,
153− scoped_functions: std::collections::HashSet::new(),
784+ page: None,
154− page_title: None,
785+ page_at: None,
157 meta_tags: Vec::new(),
786 meta_tags: Vec::new(),
158 head_blocks: Vec::new(),
787 head_blocks: Vec::new(),
159− variables: HashMap::new(),
788+ head_at: None,
160− defines: HashMap::new(),
789+ env: Env::default(),
161− functions: HashMap::new(),
790+ defined_functions: HashMap::new(),
162− keyframes: Vec::new(),
163 css_vars: Vec::new(),
791 css_vars: Vec::new(),
164 custom_css: Vec::new(),
792 custom_css: Vec::new(),
793+ scoped_css: Vec::new(),
165 og_tags: Vec::new(),
794 og_tags: Vec::new(),
166 diagnostics: Vec::new(),
795 diagnostics: Vec::new(),
167 base_path: base_path.map(|p| p.to_path_buf()),
796 base_path: base_path.map(|p| p.to_path_buf()),
@@ -175,30 +804,85 @@ pub fn parse_with_base(input: &str, base_path: Option<&Path>) -> ParseResult {
175 let_lines: HashMap::new(),
804 let_lines: HashMap::new(),
176 fn_lines: HashMap::new(),
805 fn_lines: HashMap::new(),
177 define_lines: HashMap::new(),
806 define_lines: HashMap::new(),
178− canonical: None,
807+ visited: HashSet::new(),
179− base_url: None,
808+ next_id: 0,
180− import_stack: Vec::new(),
809+ trees: Vec::new(),
810+ included_by: Rc::default(),
811+ namespace: HashSet::new(),
812+ current_source: (0, None),
813+ reported: HashSet::new(),
182 load_prelude(&mut ctx);
820 load_prelude(&mut ctx);
183− let nodes = Evaluator.eval_block(&tree, &mut ctx);
821+ let tree = ctx.parse_tree(input);
184− validate_tree(&nodes, None, &mut ctx.diagnostics);
822+ ctx.diagnostics.extend(tree.diagnostics.iter().cloned());
185− check_unused(&mut ctx);
823+ ctx.trees.push((tree.clone(), None));
826+ base_path.map(Path::to_path_buf),
827+ &mut HashSet::new(),
830+ let nodes = Evaluator.eval_block(&tree.nodes, &mut ctx);
831+ check_unevaluated(&mut ctx);
832+ check_slot_places(&mut ctx);
833+ validate_tree(&nodes, None, false, &mut ctx.diagnostics);
834+ // A library's definitions are for the files that include it
835+ let library = is_library_file(&tree, base_path, &mut ctx, &mut Vec::new());
836+ let exported: HashSet<String> = if library {
839+ .filter_map(|node| match node.directive().map(|d| &d.args) {
840+ Some(DirectiveArgs::Let(def)) => Some(def.name.clone()),
847+ check_unused(&mut ctx, &exported);
848+ if let (None, Some(line)) = (&ctx.page, ctx.head_at)
851+ ctx.diagnostics.push(Diagnostic::warning(
854+ "a file without @page is a fragment, which has no <head>: @meta and @head are \
855+ left out of it (give the file a @page, or put them in the page that includes it)"
859+ dedupe(&mut ctx.diagnostics);
860+ // What the file itself defines at its top level
861+ let file = ctx.env.frames.last().cloned().unwrap_or_default();
862+ let mut variables = HashMap::new();
863+ let mut defines = HashMap::new();
864+ for (name, binding) in file.iter() {
866+ Binding::Value(value) => {
867+ variables.insert(name.clone(), value.to_string());
869+ Binding::Bundle(attrs) => {
870+ defines.insert(name.clone(), attrs.to_vec());
872+ Binding::Function(_) => {}
186 ParseResult {
875 ParseResult {
187 document: Document {
876 document: Document {
188− page_title: ctx.page_title,
877+ page: ctx.page,
190− favicon: ctx.favicon,
191 meta_tags: ctx.meta_tags,
878 meta_tags: ctx.meta_tags,
192 head_blocks: ctx.head_blocks,
879 head_blocks: ctx.head_blocks,
193− variables: ctx.variables,
880+ variables,
194− defines: ctx.defines,
881+ defines,
195− keyframes: ctx.keyframes,
196 css_vars: ctx.css_vars,
882 css_vars: ctx.css_vars,
197 custom_css: ctx.custom_css,
883 custom_css: ctx.custom_css,
884+ scoped_css: ctx.scoped_css,
198 og_tags: ctx.og_tags,
885 og_tags: ctx.og_tags,
199− canonical: ctx.canonical,
200− base_url: ctx.base_url,
201− preload_hints: collect_image_preload_hints(&nodes),
204 diagnostics: ctx.diagnostics,
888 diagnostics: ctx.diagnostics,
@@ -206,744 +890,878 @@ pub fn parse_with_base(input: &str, base_path: Option<&Path>) -> ParseResult {
209−/// Scan nodes for @image elements and generate preload hints for early images.
893+// ---------------------------------------------------------------------------
210−fn collect_image_preload_hints(nodes: &[Node]) -> Vec<crate::ast::PreloadHint> {
894+// Code that never runs: an untaken branch, an uncalled function, a loop over
211− let mut hints = Vec::new();
895+// an empty list
212− // Only preload the first few images (above-the-fold heuristic)
896+// ---------------------------------------------------------------------------
213− collect_images_recursive(nodes, &mut hints, 3);
217−fn collect_images_recursive(nodes: &[Node], hints: &mut Vec<crate::ast::PreloadHint>, max: usize) {
898+/// Collect the functions defined anywhere in `nodes` and in the files they
899+/// include (by a literal path), into `ctx.namespace`.
900+fn collect_namespace(
901+ nodes: &[syntax::Node],
902+ base: Option<PathBuf>,
903+ seen: &mut HashSet<PathBuf>,
904+ ctx: &mut ParseContext,
906+ let mut includes = Vec::new();
218 for node in nodes {
907 for node in nodes {
219− if hints.len() >= max {
908+ node.walk(&mut |node| match node.directive().map(|d| &d.args) {
220− return;
909+ Some(DirectiveArgs::Let(def)) if matches!(def.form, LetForm::Function(_)) => {
221− }
910+ ctx.namespace.insert(def.name.clone());
222− if let Node::Element(elem) = node {
223− if elem.kind == ElementKind::Image
224− && let Some(ref src) = elem.argument
226− && !src.starts_with("data:")
227− && !src.starts_with('#')
229− hints.push(crate::ast::PreloadHint {
231− as_type: "image".to_string(),
235− collect_images_recursive(&elem.children, hints, max);
912+ Some(DirectiveArgs::Text(Some(path))) if node.is_directive("include") => {
913+ includes.push(path.raw.clone());
918+ for path in includes {
919+ let path = path.trim_matches('"');
920+ if path.contains('$') {
923+ let resolved = match &base {
924+ Some(base) => base.join(path),
925+ None => PathBuf::from(path),
927+ if !seen.insert(resolved.clone()) {
930+ let Ok(text) = ctx.read_file(&resolved) else {
933+ let tree = syntax::parse(&text);
934+ let parent = resolved.parent().map(Path::to_path_buf);
935+ collect_namespace(&tree.nodes, parent, seen, ctx);
240−// ---------------------------------------------------------------------------
939+/// Check the lines that were never evaluated: element and function names,
241−// Preprocessing: strip comments/blanks, collapse @raw blocks
940+/// and the attributes of built-in elements (those that don't depend on a
242−// ---------------------------------------------------------------------------
941+/// variable). Names that come from data are only checked when evaluated.
243−
942+fn check_unevaluated(ctx: &mut ParseContext) {
244−// ---------------------------------------------------------------------------
943+ let trees = std::mem::take(&mut ctx.trees);
245−// Evaluation
944+ let mut seen = HashSet::new();
246−// ---------------------------------------------------------------------------
945+ for (tree, chain) in &trees {
247−
946+ let before = ctx.diagnostics.len();
248−impl Evaluator {
947+ for node in &tree.nodes {
249− fn eval_block(&mut self, block: &[Syntax], ctx: &mut ParseContext) -> Vec<Node> {
948+ check_unevaluated_node(node, ctx);
250− let mut nodes = Vec::new();
949+ }
251− for node in block {
950+ let mut found = ctx.diagnostics.split_off(before);
252− match self.eval(node, ctx) {
951+ if let Some(chain) = chain {
253− Ok(Some(new_nodes)) => nodes.extend(new_nodes),
952+ for d in &mut found {
254− Ok(None) => {}
953+ d.message = format!("{}\n in {}", d.message, chain);
255− // Record the error and go on, to report several in one pass
256− Err(e) => ctx.diagnostics.push(Diagnostic {
260− severity: Severity::Error,
261− source_line: Some(node.source()),
265− nodes
956+ // A file included twice is checked twice: report each problem once
266− }
957+ found.retain(|d| seen.insert((d.line, d.message.clone())));
267−
958+ ctx.diagnostics.extend(found);
268− /// Evaluate a block in its own scope: `@let` inside doesn't leak out.
269− fn eval_scoped(&mut self, block: &[Syntax], ctx: &mut ParseContext) -> Vec<Node> {
270− let saved_vars = ctx.variables.clone();
271− let nodes = self.eval_block(block, ctx);
272− ctx.variables = saved_vars;
276− fn eval(&mut self, node: &Syntax, ctx: &mut ParseContext) -> Result<Option<Vec<Node>>, ParseError> {
963+fn check_unevaluated_node(node: &syntax::Node, ctx: &mut ParseContext) {
277− let line_num = node.line();
964+ if !ctx.visited.contains(&node.id) {
278− ctx.current_line = line_num;
965+ let line = node.span.line;
279− if !matches!(node, Syntax::Raw { .. })
966+ // A reference from code that doesn't run still counts as a use
280− && let Some(filter) = old_filter_syntax(&node.source())
967+ track_var_refs(&node.source, &mut ctx.used_variables);
281− {
968+ let before = ctx.diagnostics.len();
282− ctx.diagnostics.push(Diagnostic {
969+ match &node.kind {
283− line: line_num,
970+ NodeKind::Element(element) => {
284− column: None,
971+ for head in &element.chain {
285− message: format!(
972+ check_head(head, line, ctx);
286− "`${}|{}` filters are functions now: write `${{{}(${})}}` (run `htmlang upgrade`)",
973+ }
287− filter.0, filter.1, filter.1, filter.0
974+ check_unevaluated_content(node, element, ctx);
288− ),
975+ if let Some(text) = &element.text {
289− severity: Severity::Warning,
976+ check_inline_heads(text, line, ctx);
290− source_line: Some(node.source()),
293− let (content, current_indent, children) = match node {
294− Syntax::Raw { text, .. } => return Ok(Some(vec![Node::Raw(text.clone())])),
295− Syntax::Function { name, params, defaults, body, .. } => {
296− self.define_function(name, params, defaults, body, line_num, ctx);
299− Syntax::If { branches } => {
300− // Every condition is checked (and its errors reported);
301− // the first that holds picks the branch.
302− let mut chosen = None;
303− for branch in branches {
304− let holds = match &branch.condition {
305− Some(condition) => ctx.condition(condition, branch.line),
308− if holds && chosen.is_none() {
309− chosen = Some(&branch.body);
312− return Ok(chosen.map(|body| self.eval_scoped(body, ctx)));
314− Syntax::Each { header, body, empty, .. } => {
979+ NodeKind::Text(text) => check_inline_heads(text, line, ctx),
315− return self.eval_each(header, body, empty, line_num, ctx).map(Some);
980+ // `@page`'s attributes are checked like an element's (a layout's
981+ // `@page` is in a function that may not run in this file)
982+ NodeKind::Directive(syntax::Directive {
984+ DirectiveArgs::Page {
985+ attrs: Some(list), ..
989+ let words: Vec<String> = crate::vocab::PAGE_WORDS
991+ .map(|w| w.to_string())
994+ check_attrs(&list.attrs, line, ctx, &words);
995+ ctx.in_page = false;
996+ check_page_tokens(&list.attrs, line, ctx);
317− Syntax::Line { text, indent, children, .. } => (text.clone(), *indent, children),
998+ _ => {}
320− // --- Directives ---
322− // Removed syntax gets a pointer to its replacement — unless the
323− // name is a user function (e.g. `@let divider`).
324− if content.starts_with('@')
325− && !ctx.functions.contains_key(extract_element_name(&content))
326− && let Some(hint) = removed_syntax_hint(&content)
328− return Err(ParseError {
333−
1000+ let text = written_line(node);
334− // @page [lang en, favicon /f.png, canonical URL, base URL] Title
1001+ for d in &mut ctx.diagnostics[before..] {
335− if let Some(rest) = content.strip_prefix("@page ") {
1002+ d.source_line.get_or_insert_with(|| text.as_str().into());
336− let rest = rest.trim_start();
337− let title = if rest.starts_with('[') {
338− let (attrs, title) = parse_attr_brackets_no_validate(rest, line_num, ctx)?;
340− let value = attr.value.unwrap_or_default();
341− match attr.key.as_str() {
342− "lang" => ctx.lang = Some(value),
343− "favicon" => ctx.favicon = Some(value),
344− "canonical" => ctx.canonical = Some(value),
345− "base" => ctx.base_url = Some(value),
346− other => ctx.diagnostics.push(Diagnostic {
350− "unknown @page attribute '{}' (expected lang, favicon, canonical or base)",
353− severity: Severity::Warning,
354− source_line: Some(content.clone()),
362− ctx.page_title = Some(substitute_vars(title.trim(), &ctx.variables));
1005+ for child in &node.children {
1006+ check_unevaluated_node(child, ctx);
1010+/// Check the content passed to the calls of a line that was never
1011+/// evaluated: its `@slot NAME` blocks, and, for a function without
1012+/// `@children`, any other content.
1013+fn check_unevaluated_content(
1014+ node: &syntax::Node,
1015+ element: &syntax::ElementLine,
1016+ ctx: &mut ParseContext,
1018+ let calls: Vec<Option<(String, Rc<FnDef>)>> = element
1022+ let function = ctx.defined_functions.get(&head.name)?;
1023+ Some((head.name.clone(), function.clone()))
1026+ check_fillers(node, element, &calls, ctx);
1027+ let last = calls.len() - 1;
1028+ for (i, call) in calls.iter().enumerate() {
1029+ let Some((name, function)) = call else {
1032+ if function.has_children || function.wraps_itself {
1035+ let content = if i == last {
1036+ element.text.is_some() || holds_content(&node.children, ctx)
1038+ element.chain[i + 1].name != "slot" || !slot_is_built_in(ctx)
1041+ let head = &element.chain[i];
1042+ ctx.push_once(no_children(
1045+ name_column(head, node.span.line),
367− if let Some(rest) = content.strip_prefix("@let ") {
1051+/// Check a head that was never evaluated: its name, and its attributes
368− let rest = rest.trim();
1052+/// (for a call, see [`check_call`]).
369−
1053+fn check_head(head: &syntax::Head, line: usize, ctx: &mut ParseContext) {
370− if !children.is_empty() {
1054+ let is_function =
371− return Err(ParseError {
1055+ ctx.namespace.contains(&head.name) || ctx.defined_functions.contains_key(&head.name);
372− line: line_num,
1056+ if is_function {
373− message: "@let with body requires a name".to_string(),
1057+ ctx.used_functions.insert(head.name.clone());
374− });
1058+ if let Some(function) = ctx.defined_functions.get(&head.name).cloned()
375− }
1059+ && !function.wraps_itself
377− if let Some((name, value)) = rest.split_once(' ') {
1061+ check_call(head, &function, line, ctx);
378− let value = value.trim();
1062+ }
379− // `@let name = EXPR` computes its value (see expr.rs); any
1063+ return;
380− // other value is literal text with `$var` interpolation.
1064+ }
381− if let Some(expression) = value.strip_prefix('=') {
1065+ let kind = match parse_element_kind(&head.name, line, ctx) {
382− let value = ctx
1066+ Ok(kind) => kind,
383− .eval(expression.trim(), line_num)
1067+ Err(e) => {
384− .map(|v| v.to_string())
1068+ ctx.diagnostics.push(e);
385− .unwrap_or_default();
1069+ return;
386− if name.starts_with("--") {
1070+ }
387− ctx.css_vars.push((name.to_string(), value.clone()));
1071+ };
388− }
1072+ if let Some(list) = &head.attrs {
389− ctx.variables.insert(name.to_string(), value);
1073+ check_attrs(&list.attrs, line, ctx, &[]);
390− ctx.let_lines.entry(name.to_string()).or_insert(line_num);
1074+ // A word for laying out children on an element that doesn't lay
391− return Ok(None);
1075+ // them out, as where the code runs (see `validate_tree`)
1076+ if !kind.layout().is_container() && !has_no_element(&kind) {
1077+ for attr in &list.attrs {
1078+ let base = crate::vocab::base_attribute(&attr.key);
1080+ && attr.choice.is_none()
1081+ && attr.prefixed.is_none()
1082+ && crate::vocab::CONTAINER_ATTRIBUTES.contains(&base)
1083+ && !crate::vocab::split_prefixes(&attr.key)
1085+ .contains(&"children:")
1087+ ctx.push_once(not_a_container(&kind, line, base).column(attr.span.column));
394− // Attribute bundle: @let name [attr1, attr2, ...]
1094+/// The attributes of a list that is never evaluated that can be checked
395− if value.starts_with('[') {
1095+/// together: not bundles or `if()`s. Names are checked; a value with a
396− let (attrs, _) = parse_attr_brackets(value, line_num, ctx)?;
1096+/// variable in it depends on what the variable holds, so only a literal
397− ctx.defines.insert(name.to_string(), attrs);
1097+/// value is (the other is checked as an empty value).
398− ctx.define_lines.entry(name.to_string()).or_insert(line_num);
1098+/// `@page`'s own rules (see `check_page_attr`) for a list that isn't
399− return Ok(None);
1099+/// evaluated, as written: a value made from a variable counts as given.
1100+fn check_page_tokens(tokens: &[syntax::Attr], line: usize, ctx: &mut ParseContext) {
1101+ for token in tokens {
1102+ match &token.choice {
1104+ for branch in &choice.branches {
1105+ check_page_tokens(branch.attrs(), line, ctx);
402− // Triple quotes: @let name """...""" (syntax.rs joins the
1108+ // Under prefixes there are only styles
403− // lines of a multi-line string)
1109+ None if token.key.starts_with('$') || token.prefixed.is_some() => {}
404− let value = if let Some(after_open) = value.strip_prefix("\"\"\"") {
1110+ None => {
405− after_open.strip_suffix("\"\"\"").unwrap_or(after_open)
1111+ let value = token.value.as_deref().map(|v| v.trim_matches('"'));
406− } else if value.starts_with('"') && value.ends_with('"') && value.len() >= 2 {
1112+ let value = match value {
407− // Support quoted string interpolation: @let greeting "Hello $name"
1113+ Some(v) if v.contains('$') => Some("$"),
408− &value[1..value.len() - 1]
1114+ other => other,
412− track_var_refs(value, &mut ctx.used_variables);
1116+ check_page_attr(
413− let value = substitute_vars(value, &ctx.variables);
1117+ &token.key,
414− if name.starts_with("--") {
1118+ token.html,
415− // CSS custom property
1119+ value,
416− ctx.css_vars.push((name.to_string(), value.clone()));
1120+ line,
417− }
1121+ Some(token.span.column),
418− ctx.variables.insert(name.to_string(), value);
1122+ ctx,
419− ctx.let_lines.entry(name.to_string()).or_insert(line_num);
1123+ );
424− // @meta NAME VALUE; `og:` names become Open Graph property tags
1129+fn literal_attrs(tokens: &[syntax::Attr]) -> Vec<syntax::Attr> {
425− if let Some(rest) = content.strip_prefix("@meta ") {
1130+ // A prefixed group is checked with its prefixes, as far as its own
426− let rest = rest.trim();
1131+ // attributes can be; a prefixed bundle or `if()` depends on what it holds
427− if let Some((name, value)) = rest.split_once(' ') {
1132+ let group = |a: &syntax::Attr| {
428− let value = substitute_vars(value.trim(), &ctx.variables);
1133+ let prefixed = a.prefixed.as_ref()?;
429− match name.trim().strip_prefix("og:") {
1134+ let syntax::Branch::Group { list, trailing } = &prefixed.target else {
430− Some(property) => ctx.og_tags.push((property.to_string(), value)),
1135+ return None;
431− None => ctx.meta_tags.push((name.trim().to_string(), value)),
1136+ };
432− }
1137+ let mut list = list.clone();
1138+ list.attrs = literal_attrs(&list.attrs);
1139+ let mut a = a.clone();
1140+ a.prefixed = Some(Box::new(syntax::Prefixed {
1141+ target: syntax::Branch::Group {
1143+ trailing: trailing.clone(),
1145+ ..(**prefixed).clone()
1149+ let groups = tokens.iter().filter_map(group);
1153+ let bundle = a.key.starts_with('$') && a.value.is_none() && !a.html;
1154+ a.choice.is_none() && a.prefixed.is_none() && !bundle
1157+ let mut a = a.clone();
1158+ let variable = |v: &String| v.contains('$');
1159+ if !a.key.contains('$') && a.value.as_ref().is_some_and(variable) {
1160+ a.value = Some(String::new());
1161+ a.raw = format!("{} ", a.key);
434− return Ok(None);
1163+ a
1169+/// Check a call that was never evaluated: how it passes its parameters
1170+/// (none written `name=value`, and every one without a default passed,
1171+/// when no bundle or `if()` could pass it), and its other attributes, like
1172+/// those of an element.
1173+fn check_call(head: &syntax::Head, function: &FnDef, line: usize, ctx: &mut ParseContext) {
1174+ let name = head.name.as_str();
1175+ let attrs = head.attrs.as_ref().map_or(&[][..], |list| &list.attrs[..]);
1176+ written_parameter_forms(name, function, attrs, line, ctx);
1177+ if let Some(list) = &head.attrs {
1178+ let params: Vec<String> = function.params.iter().map(|p| p.name.clone()).collect();
1179+ check_attrs(&list.attrs, line, ctx, ¶ms);
1181+ let unknown = attrs
1183+ .any(|a| a.choice.is_some() || (a.key.starts_with('$') && a.value.is_none()));
1187+ for param in function.params.iter().filter(|p| p.default.is_none()) {
1188+ if !attrs.iter().any(|a| a.key == param.name) {
1189+ let column = name_column(head, line);
1190+ ctx.push_once(missing_parameter(name, ¶m.name, line, column));
438− if content == "@head" || content.starts_with("@head ") {
1195+/// Report each parameter a call's list writes `name=value`, with the value
439− let trimmed = block_text(children).trim().to_string();
1196+/// as written and its column; returns their names, so the evaluated call
440− if !trimmed.is_empty() {
1197+/// doesn't report them again.
441− ctx.head_blocks.push(trimmed);
1198+fn written_parameter_forms(
443− return Ok(None);
1200+ function: &FnDef,
1201+ attrs: &[syntax::Attr],
1203+ ctx: &mut ParseContext,
1205+ let mut reported = Vec::new();
1206+ for attr in attrs {
1207+ if !(attr.html && function.is_param(&attr.key)) {
1210+ let at = if attr.span.line == 0 {
1215+ let value = attr.value.as_deref().unwrap_or("");
1216+ let diagnostic = parameter_form(name, &attr.key, value, at).column(attr.span.column);
1217+ ctx.push_once(match &ctx.current_source {
1218+ (current, Some(text)) if *current == at => diagnostic.source(text.clone()),
1221+ reported.push(attr.key.clone());
446− // --- @style block (raw CSS) ---
1226+fn check_inline_heads(text: &syntax::Text, line: usize, ctx: &mut ParseContext) {
447− if content.trim() == "@style" {
1227+ for segment in &text.segments {
448− let trimmed = block_text(children).trim().to_string();
1228+ if let Segment::Inline(inline) = segment {
449− if !trimmed.is_empty() {
1229+ check_head(&inline.head, line, ctx);
450− ctx.custom_css.push(trimmed);
1230+ if let Some(text) = &inline.text {
1231+ check_inline_heads(text, line, ctx);
1237+// ---------------------------------------------------------------------------
1239+// ---------------------------------------------------------------------------
456− // --- @markdown block or file (convert markdown to HTML) ---
1241+/// The `@else` lines that continue the `@if` or `@each` before `from`, and
457− if content.trim() == "@markdown" || content.trim().starts_with("@markdown ") {
1242+/// the position after them.
458− let arg = content.trim().strip_prefix("@markdown").unwrap().trim();
1243+fn else_branches(block: &[syntax::Node], from: usize, is_if: bool) -> (Vec<&syntax::Node>, usize) {
459− if arg.is_empty() {
1244+ let mut branches = Vec::new();
460− // Inline markdown block: indented children
1245+ let mut next = from;
461− let md_lines: Vec<String> = block_text(children).lines().map(String::from).collect();
1246+ let mut i = from;
462− let html = markdown_to_html(&md_lines);
1247+ while i < block.len() {
463− return Ok(Some(vec![Node::Raw(html)]));
1248+ let node = &block[i];
464− } else {
1249+ i += 1;
465− // External markdown file: @markdown file.md
1250+ if node.is_trivia() {
466− let filename = substitute_vars(arg, &ctx.variables);
1251+ continue;
467− let resolved = match &ctx.base_path {
1252+ }
468− Some(base) => base.join(&filename),
1253+ let condition = match node.directive().map(|d| &d.args) {
469− None => PathBuf::from(&filename),
1254+ Some(DirectiveArgs::Else { condition }) => condition.is_some(),
471− let md_text = if let Some(cached) = ctx.file_cache.get(&resolved) {
1256+ };
472− cached.clone()
1257+ if condition && !is_if {
473− } else {
1258+ break;
474− match std::fs::read_to_string(&resolved) {
1259+ }
475− Ok(text) => {
1260+ branches.push(node);
476− ctx.file_cache.insert(resolved.clone(), text.clone());
1261+ next = i;
477− text
1262+ if !condition {
480− ctx.diagnostics.push(Diagnostic {
1265+ }
481− line: line_num,
1266+ (branches, next)
483− message: format!("cannot read markdown '{}': {}", filename, e),
1268+
484− severity: Severity::Error,
1269+impl Evaluator {
485− source_line: Some(content.clone()),
1270+ fn eval_block(&mut self, block: &[syntax::Node], ctx: &mut ParseContext) -> Vec<Node> {
486− });
1271+ let mut nodes = Vec::new();
487− return Ok(None);
1272+ let mut i = 0;
488− }
1273+ while i < block.len() {
1274+ let node = &block[i];
1276+ if node.is_trivia() {
1279+ let result = match node.directive().map(|d| d.name()) {
1280+ Some(name @ ("if" | "each")) => {
1281+ let (branches, next) = else_branches(block, i, name == "if");
1284+ Ok(Some(self.eval_if(node, &branches, ctx)))
1286+ self.eval_each(node, branches.first().copied(), ctx)
491− ctx.included_files.push(resolved);
1289+ // Reported as a syntax error
492− let md_lines: Vec<String> = md_text.lines().map(|l| l.to_string()).collect();
1290+ Some("else") => {
493− let html = markdown_to_html(&md_lines);
1291+ ctx.visited.insert(node.id);
494− return Ok(Some(vec![Node::Raw(html)]));
1292+ Ok(None)
1294+ _ => self.eval(node, ctx),
1297+ Ok(Some(new_nodes)) => nodes.extend(new_nodes),
1299+ // Record the error and go on, to report several in one pass
1302+ .get_or_insert_with(|| node.source.as_str().into());
1303+ ctx.diagnostics.push(e);
1310+ /// Evaluate a block in its own scope: what it defines is visible to
1311+ /// the end of the block, and not after it.
1312+ fn eval_scoped(&mut self, block: &[syntax::Node], ctx: &mut ParseContext) -> Vec<Node> {
1314+ let nodes = self.eval_block(block, ctx);
1319+ /// `@if` with its `@else if` / `@else` branches. Every condition is
1320+ /// checked (and its errors reported); the first that holds picks the
1324+ node: &syntax::Node,
1325+ branches: &[&syntax::Node],
1326+ ctx: &mut ParseContext,
1328+ let mut chosen = None;
1329+ for branch in std::iter::once(node).chain(branches.iter().copied()) {
1330+ ctx.visited.insert(branch.id);
1332+ let holds = match branch.directive().map(|d| &d.args) {
1333+ Some(DirectiveArgs::Condition(condition))
1334+ | Some(DirectiveArgs::Else {
1335+ condition: Some(condition),
1337+ !condition.raw.is_empty()
1341+ Some(condition.span.column),
1344+ Some(DirectiveArgs::Else { condition: None }) => true,
1345+ // A syntax error, already reported
1348+ if holds && chosen.is_none() {
1349+ chosen = Some(&branch.children);
1352+ chosen.map_or_else(Vec::new, |body| self.eval_scoped(body, ctx))
500− // --- @assert directive (compile-time assertions) ---
1355+ fn eval(
502− if let Some(rest) = content.strip_prefix("@assert ") {
1357+ node: &syntax::Node,
503− let rest = rest.trim();
1358+ ctx: &mut ParseContext,
504− if !ctx.condition(rest, line_num) {
1359+ ) -> Result<Option<Vec<Node>>, ParseError> {
505− ctx.diagnostics.push(Diagnostic {
1360+ ctx.visited.insert(node.id);
506− line: line_num,
1361+ ctx.enter(node);
507− column: None,
1362+ match &node.kind {
508− message: format!("assertion failed: {}", rest),
1363+ NodeKind::Blank | NodeKind::Comment => Ok(None),
509− severity: Severity::Error,
1364+ // `@code` and `@textarea` show their body as text; `@script`'s
510− source_line: Some(content.clone()),
1365+ // goes into the page as it is
511− });
1366+ NodeKind::Verbatim(body) if body.escaped => {
1367+ let text = body.text.trim_matches('\n').to_string();
1368+ Ok(Some(vec![Node::Text(vec![TextSegment::Plain(text)])]))
1370+ NodeKind::Verbatim(body) => Ok(Some(vec![Node::Raw(body.text.clone())])),
1371+ NodeKind::Directive(directive) => {
1372+ let mut nodes = self.eval_directive(node, directive, ctx)?;
1373+ // A directive that takes no body: the lines indented under
1374+ // it (a syntax error) are evaluated as its siblings. A
1375+ // @let's body belongs to it even under a value (also an
1376+ // error), so it is never evaluated in place.
1377+ let takes_body = directive.spec.body != BodyKind::None;
1379+ let siblings = self.eval_block(&node.children, ctx);
1380+ nodes.get_or_insert_with(Vec::new).extend(siblings);
1384+ NodeKind::Element(element) => self.eval_element(node, element, ctx).map(Some),
1385+ NodeKind::Text(text) => {
1386+ let mut nodes = vec![Node::Text(text_segments(text, ctx))];
1387+ // Text takes no body: lines indented under it are its
1389+ nodes.extend(self.eval_block(&node.children, ctx));
516− if let Some(rest) = content.strip_prefix("@include ") {
1395+ fn eval_directive(
517− let rest = rest.trim();
1396+ &mut self,
518− let (filename, alias) = if let Some((file_part, alias_part)) = rest.rsplit_once(" as ")
1397+ node: &syntax::Node,
519− {
1398+ directive: &syntax::Directive,
520− (
1399+ ctx: &mut ParseContext,
521− file_part.trim().to_string(),
1400+ ) -> Result<Option<Vec<Node>>, ParseError> {
522− Some(alias_part.trim().to_string()),
1401+ let line_num = node.span.line;
523− )
1402+ let content = &node.source;
524− } else {
1403+ match (directive.name(), &directive.args) {
525− (rest.to_string(), None)
1404+ // @page [lang=en, favicon /f.png, background #f8fafc] Title
526− };
1405+ ("page", DirectiveArgs::Page { attrs, title }) => {
527− // Strip quotes from filename
1406+ let page = read_page(attrs.as_ref(), title.as_ref(), line_num, ctx);
528− let filename =
1407+ // A page has one root: a second `@page` (a layout called
529− if filename.starts_with('"') && filename.ends_with('"') && filename.len() >= 2 {
1408+ // twice, or one called after the page's own) is an error
530− filename[1..filename.len() - 1].to_string()
1409+ let here = match &ctx.current_file {
531− } else {
1410+ Some(file) => format!("line {} of {}", line_num, file),
532− filename
1411+ None => format!("line {}", line_num),
534− let filename = substitute_vars(&filename, &ctx.variables);
1413+ if let Some(first) = &ctx.page_at {
1414+ let again = if *first == here {
1415+ "this @page runs a second time (in a loop, or in a function called \
1419+ format!("a second @page (this page already has one, on {})", first)
1421+ let diagnostic = Diagnostic::error(
1422+ code::DUPLICATE_PAGE,
1425+ "{}: a page has one @page, the root element that styles its <body>",
1429+ .source(content.clone())
1431+ ctx.diagnostics.push(diagnostic);
1433+ ctx.page_at = Some(here);
1434+ ctx.page = Some(page);
536− // Glob support: if filename contains *, expand to multiple imports
1439+ ("let", DirectiveArgs::Let(def)) => {
537− if filename.contains('*') {
1440+ let name = def.name.as_str();
538− let base_dir = match &ctx.base_path {
1441+ // Values, bundles and functions share one namespace: a
539− Some(base) => base.clone(),
1442+ // definition replaces whatever the name meant in its block
540− None => PathBuf::from("."),
1443+ match &def.form {
541− };
1444+ LetForm::Function(function) => {
542− let pattern_path = Path::new(&filename);
1445+ self.define_function(name, &function.params, node, ctx);
543− let (glob_dir, glob_pattern) = match pattern_path.parent() {
544− Some(dir) if !dir.as_os_str().is_empty() => (
548− .unwrap_or_default()
552− _ => (base_dir.clone(), filename.clone()),
554− let matched_files = match std::fs::read_dir(&glob_dir) {
556− let mut files: Vec<PathBuf> = entries
559− let name = e.file_name().to_string_lossy().to_string();
560− glob_match(&glob_pattern, &name)
567− Err(e) => {
1447+ // `@let name = EXPR` computes its value (see expr.rs)
568− ctx.diagnostics.push(Diagnostic {
1448+ LetForm::Computed(expression) => {
569− line: line_num,
1449+ let value = ctx
570− column: None,
1450+ .eval(&expression.raw, line_num, Some(expression.span.column))
571− message: format!(
1451+ .unwrap_or_else(Value::empty);
572− "cannot read directory for glob '{}': {}",
1452+ set_variable(name, value, line_num, ctx);
574− ),
1454+ // Attribute bundle: @let name [attr1, attr2, ...]
575− severity: Severity::Error,
1455+ LetForm::Bundle(list) => {
576− source_line: Some(content.clone()),
1456+ ctx.in_bundle = true;
577− });
1457+ let attrs = parse_attr_list(&list.attrs, line_num, ctx, true, &[]);
578− return Ok(None);
1458+ ctx.in_bundle = false;
1459+ ctx.env.define(name, Binding::Bundle(Rc::new(attrs)));
1460+ ctx.define_lines.entry(name.to_string()).or_insert(line_num);
1462+ // `@let size 16px`, `@let fruits apple, banana`,
1463+ // `@let post $posts.0`: see `slot_value`
1464+ LetForm::Value(value) => {
1466+ ctx.slot_value(&value.raw, value.span.line, Some(value.span.column));
1467+ set_variable(name, value, line_num, ctx);
1469+ // Quoted text: `@let arrow "→ "`
1470+ LetForm::Quoted(value) => {
1471+ let raw = format!("\"{}\"", value.raw);
1472+ let column = value.span.column.saturating_sub(1);
1473+ let (text, quoted, _) =
1474+ ctx.fill_value(&raw, value.span.line, Some(column), Sink::Text);
1475+ let value = quoted.map_or(Value::Str(text), Value::Quoted);
1476+ set_variable(name, value, line_num, ctx);
581− if matched_files.is_empty() {
582− ctx.diagnostics.push(Diagnostic {
585− message: format!("no files matched glob pattern '{}'", filename),
586− severity: Severity::Warning,
587− source_line: Some(content.clone()),
591− let mut matched_nodes = Vec::new();
1479+ Ok(None)
592− for file_path in matched_files {
1480+ }
593− let rel_name = file_path
1481+
594− .strip_prefix(&base_dir)
1482+ // @meta NAME VALUE; `og:` names become Open Graph property tags
595− .unwrap_or(&file_path)
1483+ ("meta", DirectiveArgs::Text(Some(arg))) => {
596− .to_string_lossy()
1484+ let Some((name, value)) = arg.raw.split_once(char::is_whitespace) else {
597− .to_string();
1485+ ctx.diagnostics.push(
598− // Synthesize an @include line for each matched file
1486+ Diagnostic::error(
599− let import_line = match &alias {
1487+ code::MISSING_ARGUMENT,
600− Some(pfx) => {
1488+ line_num,
601− let stem = file_path
1489+ format!("@meta needs a name and a value: `@meta {} VALUE`", arg.raw),
603− .unwrap_or_default()
1491+ .source(content.clone()),
604− .to_string_lossy()
1492+ );
605− .to_string();
1493+ return Ok(None);
606− format!("@include \"{}\" as {}.{}", rel_name, pfx, stem)
1494+ };
607− }
1495+ let value_column = arg.span.column + arg.raw.len() - value.trim_start().len();
608− None => format!("@include \"{}\"", rel_name),
1496+ // An HTML attribute value: quoted text loses its quotes
609− };
1497+ let (value, _, _) =
610− matched_nodes.extend(self.eval_block(&syntax::parse(&import_line), ctx));
1498+ ctx.fill_value(value.trim(), line_num, Some(value_column), Sink::Text);
1499+ // The same tag twice says nothing more (a layout called
1500+ // twice): it is written once
1501+ let (tags, tag) = match name.trim().strip_prefix("og:") {
1502+ Some(property) => (&mut ctx.og_tags, (property.to_string(), value)),
1503+ None => (&mut ctx.meta_tags, (name.trim().to_string(), value)),
1505+ if !tags.contains(&tag) {
612− return Ok(Some(matched_nodes));
1508+ ctx.head_at.get_or_insert(line_num);
615− let resolved = match &ctx.base_path {
1512+ ("head", _) => {
616− Some(base) => base.join(&filename),
1513+ let text = verbatim_content(node);
617− None => PathBuf::from(&filename),
1514+ if !text.trim().is_empty() {
618− };
1515+ ctx.head_blocks.push(text.trim().to_string());
1516+ ctx.head_at.get_or_insert(line_num);
620− if ctx.include_stack.contains(&resolved) || ctx.import_stack.contains(&resolved) {
1521+ // @style: raw CSS
621− let cycle_chain = format_include_chain(&ctx.import_stack);
1522+ ("style", _) => {
622− ctx.diagnostics.push(Diagnostic {
1523+ let text = verbatim_content(node);
623− line: line_num,
1524+ // Only the @style at the top of a function's body is
624− column: None,
1525+ // scoped; anywhere else `&` is `:scope`, the whole page
625− message: format!(
1526+ if has_top_level_ampersand(&text) {
626− "circular include '{}' (cycle: {} → {})",
1527+ ctx.push_once(Diagnostic::warning(
627− filename, cycle_chain, filename
1528+ code::INVALID_VALUE,
628− ),
1529+ node.span.line,
629− severity: Severity::Error,
1530+ "`&` in this @style is the whole page: only an @style at the top of a \
630− source_line: Some(content.clone()),
1531+ function's body is scoped to the function, with `&` its root element"
631− });
1532+ .to_string(),
632− return Ok(None);
1533+ ));
1535+ if !text.trim().is_empty() {
1536+ ctx.custom_css.push(text.trim().to_string());
635− let imported_text = if let Some(cached) = ctx.file_cache.get(&resolved) {
1541+ // @markdown: an indented block, or a file
636− cached.clone()
1542+ ("markdown", DirectiveArgs::Text(file)) => {
637− } else {
1543+ let Some(file) = file else {
638− match std::fs::read_to_string(&resolved) {
1544+ let md_lines: Vec<String> = verbatim_text(&node.children)
639− Ok(text) => {
1545+ .lines()
640− ctx.file_cache.insert(resolved.clone(), text.clone());
1546+ .map(String::from)
641− text
1547+ .collect();
642− }
1548+ return Ok(Some(vec![Node::Raw(markdown_to_html(&md_lines))]));
1550+ let filename = ctx.interpolate_text(&file.raw, line_num, Some(file.span.column));
1551+ let resolved = ctx.resolve(&filename);
1552+ let md_text = match ctx.read_file(&resolved) {
643 Err(e) => {
1554 Err(e) => {
644− ctx.diagnostics.push(Diagnostic {
1555+ ctx.diagnostics.push(
645− line: line_num,
1556+ Diagnostic::error(
646− column: None,
1557+ code::UNREADABLE_FILE,
647− message: format!("cannot include '{}': {}", filename, e),
1558+ line_num,
648− severity: Severity::Error,
1559+ format!("cannot read markdown '{}': {}", filename, e),
649− source_line: Some(content.clone()),
1560+ )
650− });
1561+ .source(content.clone()),
651 return Ok(None);
1563 return Ok(None);
654− };
1566+ ctx.included_files.push(resolved);
1567+ let md_lines: Vec<String> = md_text.lines().map(|l| l.to_string()).collect();
1568+ Ok(Some(vec![Node::Raw(markdown_to_html(&md_lines))]))
656− ctx.included_files.push(resolved.clone());
1571+ ("include", DirectiveArgs::Text(Some(path))) => {
657− ctx.include_stack.push(resolved.clone());
1572+ self.eval_include(node.id, path, line_num, content, ctx)
658− ctx.import_stack.push(resolved.clone());
1573+ }
659− let saved_base = ctx.base_path.clone();
1574+
660− ctx.base_path = resolved.parent().map(|p| p.to_path_buf());
1575+ ("data", DirectiveArgs::Data { name, source, .. }) => {
661−
1576+ self.eval_data(name, source, line_num, content, ctx);
662− let diag_count_before = ctx.diagnostics.len();
1577+ Ok(None)
663− let mut included_nodes = Vec::new();
665− if let Some(ref prefix) = alias {
666− // Snapshot just the *key sets* before parsing — much cheaper
667− // than cloning the full HashMaps, since we only need to know
668− // which definitions are new afterwards.
669− let fn_keys_before: std::collections::HashSet<String> =
670− ctx.functions.keys().cloned().collect();
671− let define_keys_before: std::collections::HashSet<String> =
672− ctx.defines.keys().cloned().collect();
673− let var_keys_before: std::collections::HashSet<String> =
674− ctx.variables.keys().cloned().collect();
676− let _discarded_nodes = self.eval_block(&syntax::parse(&imported_text), ctx);
678− // Remove newly added entries and re-insert them under the prefix.
679− let new_fn_keys: Vec<String> = ctx
682− .filter(|k| !fn_keys_before.contains(*k))
685− for name in new_fn_keys {
686− if let Some(def) = ctx.functions.remove(&name) {
687− ctx.functions.insert(format!("{}.{}", prefix, name), def);
690− let new_define_keys: Vec<String> = ctx
693− .filter(|k| !define_keys_before.contains(*k))
696− for name in new_define_keys {
697− if let Some(attrs) = ctx.defines.remove(&name) {
698− ctx.defines.insert(format!("{}.{}", prefix, name), attrs);
701− let new_var_keys: Vec<String> = ctx
704− .filter(|k| !var_keys_before.contains(*k))
707− for name in new_var_keys {
708− if let Some(val) = ctx.variables.remove(&name)
709− && !name.starts_with("__")
711− ctx.variables.insert(format!("{}.{}", prefix, name), val);
715− included_nodes = self.eval_block(&syntax::parse(&imported_text), ctx);
718− // Annotate new diagnostics with import chain
1580+ // @raw: the rest of its line, or its indented body, verbatim
719− let import_chain = format_include_chain(&ctx.include_stack);
1581+ ("raw", _) => {
720− for d in &mut ctx.diagnostics[diag_count_before..] {
1582+ let text = verbatim_content(node);
721− d.message = format!("{}\n in {}", d.message, import_chain);
1583+ let text = text.trim_end_matches('\n');
1584+ Ok((!text.is_empty()).then(|| vec![Node::Raw(text.to_string())]))
724− ctx.base_path = saved_base;
1587+ // A header with a syntax error (reported), or a directive
725− ctx.include_stack.pop();
1588+ // without its argument
726− ctx.import_stack.pop();
1589+ _ => Ok(None),
727− return Ok(Some(included_nodes));
1590+ }
1596+ path: &syntax::Arg,
1599+ ctx: &mut ParseContext,
1600+ ) -> Result<Option<Vec<Node>>, ParseError> {
1601+ let (filename, column) = match path.raw.strip_prefix('"').and_then(|f| f.strip_suffix('"'))
1603+ Some(quoted) => (quoted, path.span.column + 1),
1604+ None => (path.raw.as_str(), path.span.column),
1606+ let filename = ctx.interpolate_text(filename, line_num, Some(column));
1607+ let resolved = ctx.resolve(&filename);
1609+ if ctx.include_stack.contains(&resolved) {
1610+ let cycle_chain = format_include_chain(&ctx.include_stack);
1611+ ctx.diagnostics.push(
1613+ code::CIRCULAR_INCLUDE,
1616+ "circular include '{}' (cycle: {} → {})",
1617+ filename, cycle_chain, filename
1625+ let imported_text = match ctx.read_file(&resolved) {
1628+ ctx.diagnostics.push(
1630+ code::UNREADABLE_FILE,
1632+ format!("cannot include '{}': {}", filename, e),
1640+ ctx.included_files.push(resolved.clone());
1641+ ctx.include_stack.push(resolved.clone());
1642+ let saved_base = ctx.base_path.clone();
1643+ ctx.base_path = resolved.parent().map(|p| p.to_path_buf());
1645+ let diag_count_before = ctx.diagnostics.len();
1646+ let import_chain = format_include_chain(&ctx.include_stack);
1647+ let tree = ctx.parse_tree(&imported_text);
1648+ ctx.diagnostics.extend(tree.diagnostics.iter().cloned());
1649+ ctx.trees.push((tree.clone(), Some(import_chain.clone())));
1650+ let files = Rc::make_mut(&mut ctx.included_by).entry(id).or_default();
1651+ if !files.iter().any(|(_, chain)| *chain == import_chain) {
1652+ files.push((tree.clone(), import_chain.clone()));
1654+ let saved_file = ctx.current_file.replace(import_chain.clone());
1655+ let defined_before: HashSet<String> = ctx
1658+ .chain(ctx.define_lines.keys())
1659+ .chain(ctx.fn_lines.keys())
1662+ let included_nodes = self.eval_block(&tree.nodes, ctx);
1663+ ctx.current_file = saved_file;
1664+ // An included file's definitions aren't reported unused here, where
1665+ // their lines aren't this file's: a library's are there to be
1666+ // picked from, and any other file reports its own when checked
1667+ let keep = |name: &String, _: &mut usize| defined_before.contains(name);
1668+ ctx.let_lines.retain(keep);
1669+ ctx.define_lines.retain(keep);
1670+ ctx.fn_lines.retain(keep);
1672+ // Annotate new diagnostics with import chain
1673+ for d in &mut ctx.diagnostics[diag_count_before..] {
1674+ d.message = format!("{}\n in {}", d.message, import_chain);
732− // --- @data (load JSON file into variables) ---
1677+ ctx.base_path = saved_base;
1678+ ctx.include_stack.pop();
1679+ Ok(Some(included_nodes))
734− // @data file.json top-level keys become variables
1682+ /// @data $name file.json values as $name.key
735− // @data $name file.json values as $name.key
1683+ /// @data $name dir/*.json a list of the files' records
736− // @data $name dir/*.json each file as $name.STEM.key; $name
1684+ /// @data $name [...] / {...} inline JSON
737− // lists the stems, $name._count counts them
1685+ /// @data $name env:NAME [DEFAULT] an environment variable
738− // @data $name env:NAME [DEFAULT] an environment variable
1686+ fn eval_data(
739− if let Some(rest) = content.strip_prefix("@data ") {
1687+ &mut self,
740− let rest = rest.trim();
1688+ prefix: &str,
741− let (prefix, filename) = match rest.strip_prefix('$') {
1689+ source: &syntax::Arg,
742− Some(named) => match named.split_once(char::is_whitespace) {
1690+ line_num: usize,
743− Some((name, source)) => (name.to_string(), source.trim().to_string()),
1691+ content: &str,
744− None => {
1692+ ctx: &mut ParseContext,
745− return Err(ParseError {
1693+ ) {
746− line: line_num,
1694+ let prefix = prefix.to_string();
747− message: "@data requires: @data $name SOURCE or @data file.json"
1695+ let filename = source.raw.as_str();
748− .to_string(),
1696+ if let Some(env) = filename.strip_prefix("env:") {
749− });
1697+ let (var, default) = match env.split_once(char::is_whitespace) {
750− }
1698+ Some((var, default)) => (var, Some(default.trim())),
751− },
1699+ None => (env, None),
752− None => (String::new(), rest.to_string()),
754−
1701+ let default_column = default.map(|d| source.span.column + filename.len() - d.len());
755− if let Some(env) = filename.strip_prefix("env:") {
1702+ let value = std::env::var(var)
756− let (var, default) = match env.split_once(char::is_whitespace) {
1703+ .ok()
757− Some((var, default)) => (var, Some(default.trim())),
1704+ .or_else(|| default.map(|d| ctx.interpolate_text(d, line_num, default_column)));
758− None => (env, None),
1705+ if value.is_none() {
759− };
1706+ ctx.diagnostics.push(
760− if prefix.is_empty() {
1707+ Diagnostic::warning(
761− return Err(ParseError {
1708+ code::UNSET_ENVIRONMENT,
762− line: line_num,
1709+ line_num,
763− message: format!("@data env:{} needs a name: @data $name env:{}", var, var),
1710+ format!(
766− let value = std::env::var(var)
768− .or_else(|| default.map(|d| substitute_vars(d, &ctx.variables)));
769− if value.is_none() {
770− ctx.diagnostics.push(Diagnostic {
774 "environment variable '{}' is not set and has no default",
1711 "environment variable '{}' is not set and has no default",
777− severity: Severity::Warning,
1714+ )
778− source_line: Some(content.clone()),
1715+ .source(content),
781− ctx.variables.insert(prefix, value.unwrap_or_default());
1718+ ctx.bind(&prefix, Value::Str(value.unwrap_or_default()));
785− let filename = substitute_vars(&filename, &ctx.variables);
1722+ // Inline JSON: @data $links [{"label": "Home", "url": "/"}]
1723+ let (json_text, source) = if filename.starts_with(['[', '{']) {
1724+ (filename.to_string(), "the inline data".to_string())
1726+ let filename = ctx.interpolate_text(filename, line_num, Some(source.span.column));
786 if filename.contains('*') {
1727 if filename.contains('*') {
787− if prefix.is_empty() {
1728+ self.load_data_glob(&prefix, &filename, line_num, content, ctx);
788− return Err(ParseError {
1729+ return;
790− message: format!("@data {} needs a name: @data $name {}", filename, filename),
793− self.load_data_glob(&prefix, &filename, line_num, &content, ctx);
796−
1731+ let resolved = ctx.resolve(&filename);
797− let filename = substitute_vars(&filename, &ctx.variables);
1732+ match std::fs::read_to_string(&resolved) {
798− let resolved = match &ctx.base_path {
1733+ Ok(text) => {
799− Some(base) => base.join(&filename),
1734+ ctx.included_files.push(resolved);
800− None => PathBuf::from(&filename),
1735+ (text, format!("'{}'", filename))
803− let json_text = match std::fs::read_to_string(&resolved) {
806− ctx.diagnostics.push(Diagnostic {
809− message: format!("cannot load data '{}': {}", filename, e),
810− severity: Severity::Error,
811− source_line: Some(content.clone()),
817− match parse_json_with_error(&json_text) {
819− if prefix.is_empty() {
820− // No prefix: top-level object keys become variables directly
821− if let JsonValue::Object(pairs) = &json {
822− for (key, val) in pairs {
823− let mut sub = HashMap::new();
824− flatten_json(key, val, &mut sub);
826− ctx.variables.insert(k, v);
830− ctx.diagnostics.push(Diagnostic {
833− message: "@data without prefix requires a JSON object at top level"
835− severity: Severity::Error,
836− source_line: Some(content.clone()),
840− let mut sub = HashMap::new();
841− flatten_json(&prefix, &json, &mut sub);
843− ctx.variables.insert(k, v);
848− ctx.diagnostics.push(Diagnostic {
851− message: format!("invalid JSON in '{}': {}", filename, detail),
852− severity: Severity::Error,
853− source_line: Some(content.clone()),
857−
1738+ ctx.diagnostics.push(
858− ctx.included_files.push(resolved);
1739+ Diagnostic::error(
859− return Ok(None);
1740+ code::UNREADABLE_FILE,
861−
1742+ format!("cannot load data '{}': {}", filename, e),
863− // --- @if / @else ---
1744+ .source(content),
865− if content.trim() == "@else" || content.trim().starts_with("@else if ") {
1746+ return;
866− return Err(ParseError {
868− message: "@else without matching @if".to_string(),
872− // --- @each loop ---
874− // --- @warn / @debug ---
876− if let Some(rest) = content.strip_prefix("@warn ") {
877− let msg = substitute_vars(rest.trim(), &ctx.variables);
878− ctx.diagnostics.push(Diagnostic {
882− severity: Severity::Warning,
883− source_line: Some(content.clone()),
889− // --- @keyframes directive ---
891− if let Some(rest) = content.strip_prefix("@keyframes ") {
892− let name = rest.trim().to_string();
893− if name.is_empty() {
894− return Err(ParseError {
896− message: "@keyframes requires a name".to_string(),
899− let mut body = String::new();
900− for_each_line(children, &mut |node| {
901− if let Syntax::Line { text, .. } = node {
902− let trimmed = text.trim();
903− // Support htmlang-style: from [opacity 0] / to [opacity 1] / 50% [transform scale(1.5)]
904− if let Some(kf_css) = parse_keyframe_line(trimmed) {
905− body.push_str(&kf_css);
907− body.push_str(trimmed);
911− ctx.keyframes.push((name, body));
917− // --- Function call ---
919− if content.starts_with('@') {
920− let name = extract_element_name(&content);
921− if ctx.functions.contains_key(name) {
922− ctx.used_functions.insert(name.to_string());
923− let nodes = self.expand_fn_call(name, &content, children, line_num, ctx)?;
924− return Ok(Some(nodes));
1750+ match parse_json_with_error(&json_text) {
1751+ Ok(json) => ctx.bind(&prefix, json_value(json)),
1752+ Err(detail) => ctx.diagnostics.push(
1754+ code::INVALID_JSON,
1756+ format!("invalid JSON in {}: {}", source, detail),
930− if content.starts_with('@') || content.starts_with('[') {
931− let node = self.parse_element_line(&content, children, line_num, ctx)?;
932− return Ok(Some(vec![inline_svg(node, line_num, ctx)]));
935− // --- Bare text ---
938− check_undefined_vars(&content, &ctx.variables, line_num, current_indent);
939− ctx.diagnostics.extend(var_warnings);
940− track_var_refs(&content, &mut ctx.used_variables);
941− let segments = parse_text_segments(&content, ctx);
942− Ok(Some(vec![Node::Text(segments)]))
945− /// `@data $name dir/*.json`: load every matching file as
1763+ /// `@data $name dir/*.json`: a list with one record per matching file
946− /// `$name.STEM.key`, list the stems in `$name` and count them.
1764+ /// (in name order), whose `file` is the file's name without extension.
947 fn load_data_glob(
1765 fn load_data_glob(
948 &mut self,
1766 &mut self,
949 name: &str,
1767 name: &str,
@@ -973,18 +1791,20 @@ impl Evaluator {
974 .collect(),
1792 .collect(),
975 Err(e) => {
1793 Err(e) => {
976− ctx.diagnostics.push(Diagnostic {
1794+ ctx.diagnostics.push(
977− line: line_num,
1795+ Diagnostic::new(
978− column: None,
1796+ code::UNREADABLE_FILE,
979− message: format!("cannot read directory for '{}': {}", pattern, e),
1797+ Severity::Error,
980− severity: Severity::Error,
1798+ line_num,
981− source_line: Some(content.to_string()),
1799+ format!("cannot read directory for '{}': {}", pattern, e),
1801+ .source(content.to_string()),
986 files.sort();
1806 files.sort();
987− let mut stems = Vec::new();
1807+ let mut records = Vec::new();
988 for file in files {
1808 for file in files {
989 let stem = file
1809 let stem = file
990 .file_stem()
1810 .file_stem()
@@ -994,277 +1814,454 @@ impl Evaluator {
994 let text = match std::fs::read_to_string(&file) {
1814 let text = match std::fs::read_to_string(&file) {
995 Ok(text) => text,
1815 Ok(text) => text,
996 Err(e) => {
1816 Err(e) => {
997− ctx.diagnostics.push(Diagnostic {
1817+ ctx.diagnostics.push(
998− line: line_num,
1818+ Diagnostic::new(
999− column: None,
1819+ code::UNREADABLE_FILE,
1000− message: format!("cannot load data '{}': {}", file.display(), e),
1820+ Severity::Error,
1001− severity: Severity::Error,
1821+ line_num,
1002− source_line: Some(content.to_string()),
1822+ format!("cannot load data '{}': {}", file.display(), e),
1824+ .source(content.to_string()),
1004 continue;
1826 continue;
1007 match parse_json_with_error(&text) {
1829 match parse_json_with_error(&text) {
1008− Ok(json) => {
1830+ Ok(JsonValue::Object(mut pairs)) => {
1009− let mut vars = HashMap::new();
1831+ if !pairs.iter().any(|(key, _)| key == "file") {
1010− flatten_json(&format!("{}.{}", name, stem), &json, &mut vars);
1832+ pairs.push(("file".to_string(), JsonValue::Str(stem)));
1011− ctx.variables.extend(vars);
1833+ }
1012− stems.push(stem);
1834+ records.push(JsonValue::Object(pairs));
1014− Err(detail) => ctx.diagnostics.push(Diagnostic {
1836+ Ok(_) => ctx.diagnostics.push(
1015− line: line_num,
1837+ Diagnostic::new(
1016− column: None,
1838+ code::INVALID_JSON,
1017− message: format!("invalid JSON in '{}': {}", file.display(), detail),
1839+ Severity::Error,
1018− severity: Severity::Error,
1840+ line_num,
1019− source_line: Some(content.to_string()),
1841+ format!("'{}' should hold a JSON object", file.display()),
1843+ .source(content.to_string()),
1845+ Err(detail) => ctx.diagnostics.push(
1847+ code::INVALID_JSON,
1850+ format!("invalid JSON in '{}': {}", file.display(), detail),
1852+ .source(content.to_string()),
1022 ctx.included_files.push(file);
1855 ctx.included_files.push(file);
1024− ctx.variables
1857+ ctx.bind(name, json_value(JsonValue::Array(records)));
1025− .insert(format!("{}._count", name), stems.len().to_string());
1026− ctx.variables.insert(name.to_string(), stems.join(", "));
1860+ /// `@each $item in LIST` or `@each $item, $index in LIST`, with the
1861+ /// `@else` that follows it. LIST is a value (see
1862+ /// [`ParseContext::slot_value`]): a list written with commas, a range,
1863+ /// or one `$name` or `${...}` that holds a list. Each item is bound
1864+ /// whole to `$item`, and each iteration is a block of its own.
1029 fn eval_each(
1865 fn eval_each(
1030 &mut self,
1866 &mut self,
1031− header: &str,
1867+ node: &syntax::Node,
1032− body: &[Syntax],
1868+ empty_branch: Option<&syntax::Node>,
1035 ctx: &mut ParseContext,
1869 ctx: &mut ParseContext,
1036− ) -> Result<Vec<Node>, ParseError> {
1870+ ) -> Result<Option<Vec<Node>>, ParseError> {
1037− // Support: @each $var in list OR @each $var, $index in list
1871+ ctx.visited.insert(node.id);
1038− // OR @each $name, $url in Alice /alice, Bob /bob (destructuring)
1872+ if let Some(branch) = empty_branch {
1039− let (var_names, list_str) = if let Some((before_in, after_in)) = header.split_once(" in ") {
1873+ ctx.visited.insert(branch.id);
1040− let before_in = before_in.trim();
1874+ }
1041− let vars: Vec<String> = before_in
1875+ ctx.enter(node);
1042− .split(',')
1876+ // A malformed header is a syntax error, already reported
1043− .map(|v| v.trim().strip_prefix('$').unwrap_or(v.trim()).to_string())
1877+ let Some(DirectiveArgs::Each(header)) = node.directive().map(|d| &d.args) else {
1044− .collect();
1878+ return Ok(None);
1045− (vars, after_in.trim().to_string())
1047− return Err(ParseError {
1049− message: "@each requires: @each $var in list".to_string(),
1052− let var_name = var_names[0].clone();
1880+ let body = &node.children;
1053− let index_var = var_names.get(1).cloned();
1881+ let empty: &[syntax::Node] = empty_branch.map_or(&[], |b| &b.children);
1054−
1882+ let (item, index) = (header.item.as_str(), header.index.as_deref());
1055− if list_str.trim_end().ends_with(']') && list_str.contains("[page ") {
1883+ let list = &header.list;
1056− return Err(ParseError {
1884+ // `[...]` is an attribute list or JSON elsewhere, not a list here
1057− line: line_num,
1885+ let bracketed = list.raw.starts_with('[') && list.raw.ends_with(']');
1058− message: "@each pagination (`[page N]`) was removed: split the list or \
1886+ let (source, filled) = match bracketed {
1059− filter it with @if"
1887+ true => (Value::empty(), false),
1060− .to_string(),
1888+ false => ctx.slot_value(&list.raw, list.span.line, Some(list.span.column)),
1890+ let not_a_list = |message: String, ctx: &ParseContext| {
1891+ let diagnostic = Diagnostic::error(code::INVALID_LOOP, list.span.line, message)
1892+ .column(list.span.column)
1893+ .subject(list.raw.as_str());
1894+ match &ctx.current_source {
1895+ (current, Some(text)) if *current == list.span.line => {
1896+ diagnostic.source(text.clone())
1902+ let inner = list.raw[1..list.raw.len() - 1].trim().to_string();
1903+ let diagnostic = not_a_list(
1905+ "@each takes a list written without brackets, `@each ${} in {}`; \
1906+ JSON data goes in `@data`",
1911+ .suggest(Some(inner));
1912+ ctx.push_once(diagnostic);
1063− track_var_refs(&list_str, &mut ctx.used_variables);
1914+ let items: Vec<Value> = match source {
1064− let list_str = substitute_vars(&list_str, &ctx.variables);
1915+ Value::List(list) => list.items.to_vec(),
1065− // Support range syntax: @each $i in 1..5 or @each $i in 0..100 step 10
1916+ // Reported (an undefined `$name`, brackets): there is nothing
1066− let items: Vec<String> = if let Some((start_s, rest)) = list_str.split_once("..") {
1917+ // to repeat
1067− let (end_s, step) = if let Some((e, s)) = rest.split_once(" step ") {
1918+ _ if !filled => Vec::new(),
1068− (e.trim(), s.trim().parse::<i64>().unwrap_or(1).max(1))
1919+ Value::Record(_) => {
1069− } else {
1920+ let diagnostic = not_a_list(
1070− (rest.trim(), 1i64)
1921+ format!(
1071− };
1922+ "@each repeats for the items of a list, and `{}` is a record: \
1072− if let (Ok(start), Ok(end)) = (start_s.trim().parse::<i64>(), end_s.parse::<i64>())
1923+ loop over a list of records, or use its fields",
1074− numeric_range(start, end, step)
1925+ ),
1077− .split(',')
1928+ ctx.push_once(diagnostic);
1078− .map(|s| s.trim().to_string())
1929+ Vec::new()
1079− .filter(|s| !s.is_empty())
1082− } else {
1931+ // Empty text (a field a record doesn't have) is no items; any
1083− list_str
1932+ // other value is one
1084− .split(',')
1933+ value if value.to_string().is_empty() => Vec::new(),
1085− .map(|s| s.trim().to_string())
1934+ value => vec![value],
1086− .filter(|s| !s.is_empty())
1090− if body.is_empty() {
1937+ if body.iter().all(syntax::Node::is_trivia) {
1091− return Ok(Vec::new());
1938+ return Ok(Some(Vec::new()));
1093− // An empty list renders the @else body
1094 if items.is_empty() {
1940 if items.is_empty() {
1095− return Ok(self.eval_scoped(empty, ctx));
1941+ return Ok(Some(self.eval_scoped(empty, ctx)));
1097−
1943+ let mut nodes = Vec::new();
1098− let saved_vars = ctx.variables.clone();
1944+ for (i, value) in items.into_iter().enumerate() {
1099− let mut all_nodes = Vec::new();
1945+ ctx.env.push();
1100−
1946+ ctx.bind(item, value);
1101− let has_extra_vars = var_names.len() > 2
1947+ if let Some(index) = index {
1102− || (var_names.len() == 2 && items.first().is_some_and(|it| it.contains(' ')));
1948+ ctx.bind(index, Value::Num(i as f64));
1104− for (i, item) in items.iter().enumerate() {
1105− // Always expose $_index for the current iteration
1106− ctx.variables.insert("_index".to_string(), i.to_string());
1107− if has_extra_vars {
1108− // Destructuring: split item by spaces and assign to each variable
1109− let parts: Vec<&str> = item.splitn(var_names.len(), ' ').collect();
1110− for (vi, vn) in var_names.iter().enumerate() {
1111− let val = parts.get(vi).unwrap_or(&"").to_string();
1112− ctx.variables.insert(vn.clone(), val);
1115− ctx.variables.insert(var_name.clone(), item.clone());
1116− if let Some(ref idx_name) = index_var {
1117− ctx.variables.insert(idx_name.clone(), i.to_string());
1120− all_nodes.extend(self.eval_block(body, ctx));
1950+ nodes.extend(self.eval_block(body, ctx));
1122−
1953+ Ok(Some(nodes))
1123− ctx.variables = saved_vars;
1127 fn define_function(
1956 fn define_function(
1128 &mut self,
1957 &mut self,
1129 name: &str,
1958 name: &str,
1130− params: &[String],
1959+ params: &[syntax::Param],
1131− defaults: &HashMap<String, String>,
1960+ node: &syntax::Node,
1134 ctx: &mut ParseContext,
1961 ctx: &mut ParseContext,
1963+ let line_num = node.span.line;
1964+ let body = &node.children;
1136 // An @style block at the top of the body is scoped to the
1965 // An @style block at the top of the body is scoped to the
1137− // function: its rules apply inside a `.hl-NAME` wrapper.
1966+ // function: its rules apply inside a `.hl-fn-NAME-HASH` wrapper (a
1138− let (style, body): (Vec<&Syntax>, Vec<&Syntax>) = body
1967+ // generated class never has a second `-`, so the two can't meet).
1139− .iter()
1968+ // The hash is the stylesheet's, so two functions of one name with
1140− .partition(|node| matches!(node, Syntax::Line { text, .. } if text == "@style"));
1969+ // two stylesheets, in two files, don't style each other's elements
1141− if !style.is_empty() {
1970+ // in a page that has both. It is written into the page when the
1142− let mut scoped_css = String::new();
1971+ // function is called.
1143− for node in style {
1972+ let (style, body): (Vec<&syntax::Node>, Vec<&syntax::Node>) =
1144− if let Syntax::Line { children, .. } = node {
1973+ body.iter().partition(|node| node.is_directive("style"));
1145− for_each_line(children, &mut |node| {
1974+ let scoped = (!style.is_empty()).then(|| {
1146− if let Syntax::Line { text, .. } = node
1975+ let css: String = style
1147− && !text.trim().is_empty()
1976+ .iter()
1148− {
1977+ .map(|node| {
1149− scoped_css.push_str(&format!(".hl-{} {}\n", name, text.trim()));
1978+ ctx.visited.insert(node.id);
1150− }
1979+ verbatim_content(node)
1153− }
1982+ let digits = crate::codegen::CLASS_DIGITS;
1154− if !scoped_css.is_empty() {
1983+ let hash = crate::codegen::hash_digits(crate::codegen::stable_hash(&css), digits);
1155− ctx.custom_css.push(scoped_css);
1984+ let class = format!("hl-fn-{}-{}", name, hash);
1156− }
1985+ // Nested under the scope class, so any CSS works (multi-line
1157− ctx.scoped_functions.insert(name.to_string());
1986+ // rules, at-rules)
1158− }
1987+ let css = if css.trim().is_empty() {
1990+ format!(".{} {{\n{}}}", class, css)
1995+ // A default is filled in only when a call leaves its parameter
1996+ // out, so the names in it count as used here
1997+ for default in params.iter().filter_map(|p| p.default.as_ref()) {
1998+ track_var_refs(default, &mut ctx.used_variables);
1160 ctx.fn_lines.entry(name.to_string()).or_insert(line_num);
2000 ctx.fn_lines.entry(name.to_string()).or_insert(line_num);
1161− ctx.functions.insert(
2001+ let wraps_itself = ElementKind::from_name(name).is_some()
1162− name.to_string(),
2002+ && body.iter().any(|node| calls_unguarded(node, name));
1163− FnDef {
2003+ if wraps_itself {
1164− params: params.to_vec(),
2004+ ctx.push_once(
1165− defaults: defaults.clone(),
2005+ Diagnostic::error(
1166− body: body.into_iter().cloned().collect(),
2006+ code::RECURSIVE_CALL,
2009+ "@{0} in the body of `@let @{0}` calls the function itself, not the \
2010+ element @{0}, so it would never stop: give the function another name \
2011+ (such as @site-{0})",
2018+ for node in &body {
2019+ node.walk(&mut |node| {
2020+ if let Some(d) = marker_in_text(node) {
2025+ let body: Vec<syntax::Node> = body.into_iter().cloned().collect();
2026+ let (slots, has_children) = declared_slots(&body, ctx);
2027+ let function = Rc::new(FnDef {
2028+ params: params.to_vec(),
2030+ source: ctx.current_source.1.clone(),
2033+ file: ctx.current_file.clone(),
2037+ env: ctx.env.clone(),
2040+ ctx.defined_functions
2041+ .insert(name.to_string(), function.clone());
2042+ ctx.env.define(name, Binding::Function(function));
1171− fn expand_fn_call(
2045+ /// An element line: a chain of elements and function calls, the last of
2046+ /// which gets the indented children.
1172 &mut self,
2048 &mut self,
1173− name: &str,
2049+ node: &syntax::Node,
1174− content: &str,
2050+ element: &syntax::ElementLine,
1175− children: &[Syntax],
1177 ctx: &mut ParseContext,
2051 ctx: &mut ParseContext,
1178 ) -> Result<Vec<Node>, ParseError> {
2052 ) -> Result<Vec<Node>, ParseError> {
1179− // Recursive function cycle detection
2053+ // An unclosed attribute list is a syntax error, already reported
1180− if ctx.fn_call_stack.contains(&name.to_string()) {
2054+ if element
1181− return Err(ParseError {
2055+ .chain
1182− line: line_num,
2056+ .iter()
1183− message: format!(
2057+ .any(|h| h.attrs.as_ref().is_some_and(|a| !a.closed))
1184− "recursive function call to @{} (call stack: {})",
2058+ {
1185− name,
2059+ return Ok(Vec::new());
1186− ctx.fn_call_stack.join(" -> ")
1190− ctx.fn_call_stack.push(name.to_string());
2061+ let line_num = node.span.line;
1191−
2062+ let last = element.chain.len() - 1;
1192− // Parse [param value, ...] arguments
2063+ // Each head is read where it is written, left to right. The
1193− let rest = &content[1 + name.len()..];
2064+ // children belong to the last one, so the chain is built right to
1194− let rest = rest.trim_start();
2065+ // left, each link wrapping the next.
1195−
2066+ let mut links = Vec::new();
1196− let (args, trailing_text) = if rest.starts_with('[') {
2067+ for (i, head) in element.chain.iter().enumerate() {
1197− parse_attr_brackets_no_validate(rest, line_num, ctx)?
2068+ let text = if i == last {
1198− } else {
2069+ element.text.as_ref()
1199− (Vec::new(), rest.to_string())
2070+ } else {
2073+ links.push(resolve(head, text, line_num, &node.source, ctx)?);
2075+ let calls: Vec<Option<(String, Rc<FnDef>)>> = links
2077+ .map(|link| match link {
2078+ Resolved::Call(call) => Some((call.name.clone(), call.function.clone())),
2079+ Resolved::Element(_) => None,
2082+ let mut current = self.eval_scoped(&node.children, ctx);
2083+ // After the lines under the call ran, so the files they include
2085+ check_fillers(node, element, &calls, ctx);
2086+ for link in links.into_iter().rev() {
2087+ current = self.complete(link, current, ctx)?;
1202− // Clone function definition (releases borrow on ctx). If the function is
2092+ /// Give a resolved `@name` its children: an element holds them, and a
1203− // missing (shouldn't normally happen — callers check ctx.functions.contains_key
2093+ /// function's body puts them where its `@children` is.
1204− // first — but we avoid panicking on malformed state).
2094+ fn complete(
1205− let fn_def = match ctx.functions.get(name) {
2095+ &mut self,
1206− Some(def) => def.clone(),
2096+ resolved: Resolved,
1207− None => {
2097+ children: Vec<Node>,
1208− ctx.fn_call_stack.pop();
2098+ ctx: &mut ParseContext,
1209− return Err(ParseError {
2099+ ) -> Result<Vec<Node>, ParseError> {
1210− line: line_num,
2100+ match resolved {
1211− message: format!("undefined function @{}", name),
2101+ Resolved::Element(mut element) => {
1212− });
2102+ element.children.extend(children);
2103+ let line = element.line_num;
2104+ Ok(vec![inline_svg(Node::Element(element), line, ctx)])
1214− };
2106+ Resolved::Call(call) => self.expand_fn_call(*call, children, ctx),
1216− // Parse caller's children, separating named slots from default children
2110+ fn expand_fn_call(
1217− let all_caller_children = self.eval_block(children, ctx);
2111+ &mut self,
2113+ all_caller_children: Vec<Node>,
2114+ ctx: &mut ParseContext,
2115+ ) -> Result<Vec<Node>, ParseError> {
2121+ text: trailing_text,
2128+ let (name, content) = (name.as_str(), content.as_str());
2130+ // Separate the caller's `@slot NAME` blocks from its other
2131+ // children. A block for a slot the function doesn't declare was
2132+ // reported where it is written (see `check_fillers`), like one
1218 let mut slot_contents: HashMap<String, Vec<Node>> = HashMap::new();
2134 let mut slot_contents: HashMap<String, Vec<Node>> = HashMap::new();
1219 let mut caller_children = Vec::new();
2135 let mut caller_children = Vec::new();
1220 for child in all_caller_children {
2136 for child in all_caller_children {
1221− if let Node::Element(ref elem) = child
2137+ if let Node::Element(elem) = child {
1222− && let ElementKind::Slot(ref slot_name) = elem.kind
2138+ match elem.kind {
1223− && !slot_name.is_empty()
2139+ ElementKind::Slot(slot_name) => {
1224− {
2140+ slot_contents
1225− slot_contents
2141+ .entry(slot_name)
1226− .entry(slot_name.clone())
2142+ .or_default()
1227− .or_default()
2143+ .extend(elem.children);
1228− .extend(elem.children.clone());
2144+ }
2145+ kind => caller_children.push(Node::Element(Element { kind, ..elem })),
1229 continue;
2147 continue;
1231 caller_children.push(child);
2149 caller_children.push(child);
1233− // Text after the call, as in `@badge [color red] New`, is content:
2151+ // Text after the call, as in `@card [color red] New`, is content:
1234− // it goes first among the caller's children.
2152+ // it goes first among the caller's children, and like them it is
1235− let trailing_text = trailing_text.trim();
2153+ // evaluated where the call is written.
1236− if !trailing_text.is_empty() {
2154+ if let Some(text) = &trailing_text {
1237− caller_children.insert(0, Node::Text(parse_text_segments(trailing_text, ctx)));
2155+ caller_children.insert(0, Node::Text(text_segments(text, ctx)));
2157+ // Content goes where the body's `@children` is: without one, it
2158+ // would be dropped
2159+ if !fn_def.has_children && !caller_children.is_empty() {
2160+ let (column, text) = match &name_at {
2161+ Some((column, text)) => (Some(*column), text.as_str()),
2162+ None => (None, content),
2164+ ctx.push_once(no_children(name, line_num, column).source(text));
2167+ if fn_def.wraps_itself {
2168+ return Ok(Vec::new());
2170+ // Only the body is inside the call, so a function may appear in the
2171+ // content its caller passes it. A function may call itself, under
2172+ // a condition that stops it; one that doesn't stop goes too deep.
2174+ return Ok(Vec::new());
2176+ if ctx.fn_call_stack.len() >= MAX_CALL_DEPTH {
2177+ ctx.too_deep = true;
2178+ return Err(too_deep(name, &ctx.fn_call_stack, line_num).source(content));
2182+ ctx.current_source.clone(),
2185+ ctx.fn_call_stack.push(name.to_string());
1240− // Save variable state, inject function parameters
2187+ // The body runs where the function is defined: it sees what was
1241− let saved_vars = ctx.variables.clone();
2188+ // visible there, the function itself (so it can call itself), and
2189+ // its parameters, bound by name in the order they are declared. A
2190+ // default is filled in at the call, seeing the same, with the
2191+ // parameters before it.
2192+ let caller_env = std::mem::replace(&mut ctx.env, fn_def.env.clone());
2194+ ctx.env.define(name, Binding::Function(fn_def.clone()));
1242 let mut consumed = vec![false; args.len()];
2195 let mut consumed = vec![false; args.len()];
1243− for (i, param) in fn_def.params.iter().enumerate() {
2196+ for param in &fn_def.params {
1244− let named = args.iter().position(|a| a.key == *param);
2197+ let mut passed = None;
1245− // Positional fallback, unless that argument is named for a
2198+ for (j, arg) in args.iter().enumerate() {
1246− // different parameter.
2199+ if arg.key != param.name {
1247− let positional = args
2200+ continue;
1249− .filter(|a| !fn_def.params.contains(&a.key) && a.value.is_some())
1252− .filter(|&j| args[j].value.is_some())
1255− consumed[j] = true;
1256− args[j].value.clone()
1258− .or_else(|| fn_def.defaults.get(param).cloned())
1259− .unwrap_or_default();
1260− if let Some(j) = named {
1261 consumed[j] = true;
2202 consumed[j] = true;
2203+ // The later one wins, as for any attribute: one written
2204+ // after a bundle overrides it, and only one written twice
2205+ // in the call's own list is reported
2206+ if passed.is_some() && written_keys.iter().filter(|k| **k == param.name).count() > 1
2209+ Diagnostic::warning(
2210+ code::DUPLICATE_ATTRIBUTE,
2213+ "parameter '{}' of @{} is passed twice: the later one wins",
2218+ .subject(param.name.as_str()),
2221+ // Written `name=value` in the call's own list is reported
2222+ // as written; this is one from a bundle
2223+ if arg.html && !written_form.contains(&arg.key) {
2224+ let value = arg.value.as_deref().unwrap_or("");
2225+ ctx.push_once(parameter_form(name, &arg.key, value, line_num).source(content));
1263− ctx.variables.insert(param.clone(), value);
2229+ let value = match passed {
2230+ // A parameter's name alone is true: `@post-card [featured]`
2231+ Some(j) if args[j].value.is_none() => Value::Bool(true),
2232+ // What the call passed, with its type: a record, a list,
2234+ Some(j) => values[j].clone().unwrap_or_else(|| {
2235+ let arg = &args[j];
2236+ match &arg.quoted {
2237+ Some(quoted) => Value::Quoted(quoted.clone()),
2238+ None => Value::Str(arg.value.clone().unwrap_or_default()),
2241+ None => match ¶m.default {
2243+ let before = ctx.diagnostics.len();
2244+ let value = fill_default(&fn_def, param, default, ctx);
2245+ point_at_call(ctx, before, &fn_def, name, line_num, content);
2249+ let (column, text) = match &name_at {
2250+ Some((column, text)) => (Some(*column), text.as_str()),
2251+ None => (None, content),
2254+ missing_parameter(name, ¶m.name, line_num, column).source(text),
2260+ ctx.bind(¶m.name, value);
1265 // Arguments that aren't parameters are attributes for the
2262 // Arguments that aren't parameters are attributes for the
1266 // function's root element, so a function can be styled like an
2263 // function's root element, so a function can be styled like an
1267− // element: `@badge [background red] New`.
2264+ // element: `@card [background red] New`.
1268 let forwarded: Vec<Attribute> = args
2265 let forwarded: Vec<Attribute> = args
1270 .zip(&consumed)
2267 .zip(&consumed)
@@ -1272,224 +2269,1435 @@ impl Evaluator {
1272 .map(|(a, _)| a.clone())
2269 .map(|(a, _)| a.clone())
1273 .collect();
2270 .collect();
1275− // Evaluate the body with the parameters in scope
2272+ // Evaluate the body with the parameters in scope, as lines of the
1276− let body_nodes = self.eval_block(&fn_def.body, ctx);
2273+ // file that defines the function
2274+ let caller_file = std::mem::replace(&mut ctx.current_file, fn_def.file.clone());
2275+ let before = ctx.diagnostics.len();
2276+ let mut body_nodes = self.eval_block(&fn_def.body, ctx);
2277+ ctx.current_file = caller_file;
2278+ point_at_call(ctx, before, &fn_def, name, line_num, content);
1278− // Restore variables and call stack
2280+ // Back to the caller's names and call stack
1279− ctx.variables = saved_vars;
2281+ ctx.env = caller_env;
1280 ctx.fn_call_stack.pop();
2282 ctx.fn_call_stack.pop();
2283+ if ctx.fn_call_stack.is_empty() {
2284+ ctx.too_deep = false;
2286+ (ctx.current_line, ctx.current_source, ctx.current_node) = caller;
2288+ // What the body wrote is the call's
2289+ belongs_to_call(&mut body_nodes, name, line_num);
1282 // Replace @children with caller's children and @slot with slot content
2291 // Replace @children with caller's children and @slot with slot content
1283 let mut result_nodes =
2292 let mut result_nodes =
1284 replace_children_and_slots(body_nodes, &caller_children, &slot_contents);
2293 replace_children_and_slots(body_nodes, &caller_children, &slot_contents);
1286− if !forwarded.is_empty() {
2295+ // Attributes that aren't parameters style the function's root
2296+ // element, and a scoped @style's class goes on it too.
2297+ let scope_class = fn_def.scoped.as_ref().map(|(class, _)| class.clone());
2298+ if !forwarded.is_empty() || scope_class.is_some() {
1287 let mut roots = result_nodes.iter_mut().filter_map(|n| match n {
2299 let mut roots = result_nodes.iter_mut().filter_map(|n| match n {
1288 Node::Element(e) => Some(e),
2300 Node::Element(e) => Some(e),
1289 _ => None,
2301 _ => None,
1291− match (roots.next(), roots.next()) {
2303+ let root = match (roots.next(), roots.next()) {
1292− (Some(root), None) => root.attrs.extend(forwarded),
2304+ (Some(root), None) => Some(root),
1293− _ => ctx.diagnostics.push(Diagnostic {
2305+ _ => None,
1294− line: line_num,
2306+ };
1295− column: None,
2307+ let mut problems = Vec::new();
1296− message: format!(
2308+ match root {
1297− "attributes {} on @{} are not parameters, and its body has no single \
2309+ Some(root) => {
1298− root element to receive them",
2310+ // A call's `class=` adds to the root's own classes
1299− forwarded
2311+ for attr in forwarded {
1300− .iter()
2312+ let existing = (attr.html && attr.key == "class")
1301− .map(|a| format!("'{}'", a.key))
2313+ .then(|| root.attrs.iter_mut().find(|a| a.html && a.key == "class"))
1302− .collect::<Vec<_>>()
2314+ .flatten();
1303− .join(", "),
2315+ match existing {
1304− name
2316+ Some(class) => {
2317+ let mut value = class.value.take().unwrap_or_default();
2318+ for name in attr.value.as_deref().unwrap_or("").split_whitespace() {
2319+ if !value.split_whitespace().any(|c| c == name) {
2321+ value.push_str(name);
2324+ class.value = Some(value.trim().to_string());
2326+ None => root.attrs.push(attr),
2329+ // The scoped `@style` goes into the page once, when the
2330+ // function is first called
2331+ if let Some((_, css)) = &fn_def.scoped
2333+ && !ctx.scoped_css.contains(css)
2335+ ctx.scoped_css.push(css.clone());
2337+ if let Some(class) = scope_class {
2338+ match root.attrs.iter_mut().find(|a| a.html && a.key == "class") {
2340+ let existing = attr.value.take().unwrap_or_default();
2342+ Some(format!("{} {}", existing, class).trim().to_string());
2344+ None => root.attrs.push(Attribute {
2345+ key: "class".to_string(),
2346+ value: Some(class),
2354+ if !forwarded.is_empty() {
2355+ problems.push(format!(
2356+ "attributes {} on @{} are not parameters, and its body has no single \
2357+ root element to receive them",
2360+ .map(|a| format!("'{}'", a.key))
2361+ .collect::<Vec<_>>()
2366+ if scope_class.is_some() {
2367+ problems.push(format!(
2368+ "@{} has a scoped @style, but its body has no single root element \
2375+ for message in problems {
2376+ ctx.diagnostics.push(
2377+ Diagnostic::error(code::NO_SINGLE_ROOT, line_num, message)
2388+/// A `@name` read where it is written: a built-in element, or a call.
2394+/// A call of a function, with its arguments evaluated where it is written.
2397+ function: Rc<FnDef>,
2398+ args: Vec<Attribute>,
2399+ /// The value of each argument that passes a parameter, with its type
2400+ /// (see [`ParseContext::slot_value`]), in the order of `args`.
2401+ values: Vec<Option<Value>>,
2402+ /// Text after the attributes, which is content.
2403+ text: Option<syntax::Text>,
2404+ /// Parameters written `name=value`, already reported.
2405+ written_form: Vec<String>,
2406+ /// The keys written in the call's own list, not from a bundle.
2407+ written_keys: Vec<String>,
2409+ /// The column of the call's name and the line it is on, for a missing
2411+ name_at: Option<(usize, String)>,
2412+ /// The line as written, for diagnostics.
2416+/// What `@name` is where it is written: a call of the function `name`
2417+/// when one is defined, else the built-in element. A whole line, each link
2418+/// of a chain and an inline element in text all resolve here.
2420+ head: &syntax::Head,
2421+ text: Option<&syntax::Text>,
2424+ ctx: &mut ParseContext,
2425+) -> Result<Resolved, ParseError> {
2426+ let Some(function) = ctx.env.function(&head.name).cloned() else {
2427+ return parse_single_element(head, text, line, ctx).map(Resolved::Element);
2429+ ctx.used_functions.insert(head.name.clone());
2430+ let params: Vec<String> = function.params.iter().map(|p| p.name.clone()).collect();
2431+ let written = head.attrs.as_ref().map_or(&[][..], |list| &list.attrs[..]);
2432+ let written_form = written_parameter_forms(&head.name, &function, written, line, ctx);
2433+ let written_keys = written.iter().map(|a| a.key.clone()).collect();
2434+ // Parameters are bound by name; every other attribute goes to the
2435+ // root element, and is checked like any attribute
2436+ let (args, values) = parse_attrs(written, line, ctx, true, ¶ms)
2439+ let name_at = name_column(head, line).zip(match &ctx.current_source {
2440+ (current, Some(text)) if *current == line => Some(text.clone()),
2443+ Ok(Resolved::Call(Box::new(Call {
2444+ name: head.name.clone(),
2448+ text: text.cloned(),
2453+ source: source.to_string(),
2457+/// A line of another file (the standard library, an included file) means
2458+/// nothing in this one: the problems reported since `before` while
2459+/// evaluating the function (its body, a default) are moved to the call.
2461+ ctx: &mut ParseContext,
2468+ if function.file == ctx.current_file {
2471+ let defined_in = function
2474+ .unwrap_or("the file being compiled");
2475+ for d in &mut ctx.diagnostics[before..] {
2476+ d.message = format!(
2477+ "{}\n in @{} (line {} of {})",
2478+ d.message, name, d.line, defined_in
2483+ d.suggestion = None;
2484+ d.source_line = Some(source.into());
2488+/// A call nested deeper than [`MAX_CALL_DEPTH`].
2489+fn too_deep(name: &str, stack: &[String], line: usize) -> Diagnostic {
2490+ let message = if stack.iter().any(|n| n == name) {
2492+ "recursive function call to @{} goes more than {} calls deep: a function that \
2493+ calls itself needs a condition that stops it (`@if`)",
2494+ name, MAX_CALL_DEPTH
2498+ "function calls nest more than {} deep at @{} (starting with {})",
2504+ .map(|n| format!("@{}", n))
2505+ .collect::<Vec<_>>()
2509+ Diagnostic::error(code::RECURSIVE_CALL, line, message).subject(name)
2512+/// Mark what a function's body wrote as the call's: it gets the call's
2513+/// line, so what is reported about it points at the call, and the name of
2514+/// the function, unless a call inside the body already claimed it.
2515+fn belongs_to_call(nodes: &mut [Node], function: &str, line: usize) {
2516+ fn claim(element: &mut Element, function: &str, line: usize) {
2517+ element.line_num = line;
2518+ element.function.get_or_insert_with(|| function.to_string());
2519+ belongs_to_call(&mut element.children, function, line);
2521+ for node in nodes {
2523+ Node::Element(element) => claim(element, function, line),
2524+ Node::Text(segments) => {
2525+ for segment in segments {
2526+ if let TextSegment::Inline(element) = segment {
2527+ claim(element, function, line);
2536+/// What an inline `{@name ...}` stands for in its line of text: an
2537+/// element; the text of a function whose body is text; or, for a body with
2538+/// several roots, its nodes as a fragment.
2539+fn inline_segments(mut nodes: Vec<Node>, line: usize) -> Vec<TextSegment> {
2540+ if let [Node::Element(_)] = nodes.as_slice()
2541+ && let Some(Node::Element(element)) = nodes.pop()
2543+ return vec![TextSegment::Inline(element)];
2545+ if nodes.iter().all(|n| matches!(n, Node::Text(_))) {
2546+ let mut segments = Vec::new();
2547+ for node in nodes {
2548+ if let Node::Text(run) = node {
2549+ if !segments.is_empty() {
2550+ segments.push(TextSegment::Plain(" ".to_string()));
2552+ segments.extend(run);
2557+ vec![TextSegment::Inline(Element {
2558+ kind: ElementKind::Fragment,
2567+/// Fill in the default of a parameter that a call leaves out, like the
2568+/// value of an attribute passed for it: variables are filled in, one
2569+/// `$name` keeps its type and one `"..."` is quoted text. It sees what the
2570+/// body sees: the names visible where the function is defined, and the
2571+/// parameters before it. Its problems are reported at the definition, once.
2574+ param: &syntax::Param,
2576+ ctx: &mut ParseContext,
2578+ // A default that uses a later parameter is an error in the
2579+ // definition; the later one isn't bound yet, so don't report it again
2583+ .skip_while(|p| p.name != param.name)
2585+ let names = interp::names(default);
2586+ if later.clone().any(|p| names.contains(&p.name.as_str())) {
2587+ return Value::empty();
2589+ let line = param.span.line;
2590+ let at_head = line == fn_def.line && fn_def.source.is_some();
2592+ at_head.then(|| param.span.column + (param.span.end - param.span.start) - default.len());
2595+ &mut ctx.current_source,
2596+ (fn_def.line, fn_def.source.clone()),
2598+ std::mem::replace(&mut ctx.current_node, fn_def.node),
2600+ let (value, _) = ctx.slot_value(default, line, column);
2601+ (ctx.current_source, ctx.current_node) = caller;
2605+/// Read `@page`'s attribute list and title. The page is the root element,
2606+/// and its attributes are checked like any element's: `key=value` (and a
2607+/// bare boolean HTML attribute) go on `<html>`, styles on `<body>`, and
2608+/// `favicon FILE` is its one word of htmlang's own.
2610+ attrs: Option<&syntax::AttrList>,
2611+ title: Option<&syntax::Arg>,
2613+ ctx: &mut ParseContext,
2615+ let mut page = Page::default();
2616+ if let Some(list) = attrs {
2617+ let words: Vec<String> = crate::vocab::PAGE_WORDS
2619+ .map(|w| w.to_string())
2621+ ctx.in_page = true;
2622+ let read = parse_attr_list(&list.attrs, line, ctx, true, &words);
2623+ ctx.in_page = false;
2624+ // How many of each name have been read, to find where the next
2626+ let mut seen: HashMap<String, usize> = HashMap::new();
2628+ let boolean = attr.value.is_none() && crate::vocab::is_html_flag(&attr.key);
2629+ // Where it is written, when it is written in the list itself
2630+ let nth = seen.entry(attr.key.clone()).or_default();
2634+ .filter(|token| token.key == attr.key)
2636+ .map(|token| token.span.column);
2641+ .map(|q| q.text.clone())
2642+ .or(attr.value.clone());
2643+ if !check_page_attr(&attr.key, attr.html, value.as_deref(), line, column, ctx) {
2646+ if words.contains(&attr.key) {
2647+ if page.favicon.is_some() {
2648+ let diagnostic = Diagnostic::warning(
2649+ code::DUPLICATE_ATTRIBUTE,
2651+ "duplicate attribute 'favicon': the later one wins".to_string(),
2653+ .subject("favicon");
2654+ ctx.diagnostics.push(at_attribute(diagnostic, column, ctx));
2656+ // The file itself goes into the page when it can be read
2657+ // (relative to the file); otherwise it is linked
2658+ page.favicon = value.map(|path| match std::fs::read(ctx.resolve(&path)) {
2659+ Ok(data) => crate::codegen::data_uri(&path, &data),
2662+ } else if attr.html || boolean {
2663+ page.html_attrs.push(attr);
2665+ page.styles.push(attr);
2669+ page.title = match title {
2670+ Some(title) => ctx.interpolate_text(&title.raw, title.span.line, Some(title.span.column)),
2671+ None => String::new(),
2676+/// `@page`'s own rules for one of its attributes, checked where the
2677+/// `@page` runs and where it doesn't (a layout that isn't called): its
2678+/// word is written `favicon FILE`, and `inline` belongs to `@image`.
2679+/// Returns whether the attribute can be used (a `favicon` with its file,
2680+/// or any other attribute but `inline`).
2684+ value: Option<&str>,
2686+ column: Option<usize>,
2687+ ctx: &mut ParseContext,
2689+ let report = |ctx: &mut ParseContext, diagnostic: Diagnostic| {
2690+ let diagnostic = at_attribute(diagnostic, column, ctx);
2691+ ctx.diagnostics.push(diagnostic);
2693+ if crate::vocab::PAGE_WORDS.contains(&key) {
2698+ code::PARAMETER_FORM,
2701+ "'{0}' is @page's own word, not an HTML attribute: write `{0} {1}`",
2703+ value.filter(|v| !v.is_empty()).unwrap_or("FILE")
1306− severity: Severity::Warning,
2705+ )
1307− source_line: Some(content.to_string()),
2706+ .subject(format!("{}=", key))
1308− }),
2707+ .suggest(Some(format!("{} ", key))),
2710+ if value.is_none_or(|v| v.trim().is_empty()) {
2714+ code::MISSING_VALUE,
2716+ format!("'{0}' needs its file: `{0} favicon.png`", key),
2724+ if !html && crate::vocab::base_attribute(key) == "inline" {
2728+ code::UNEXPECTED_ARGUMENT,
2730+ "`inline` puts an image's file into the page, and @page has none: it only \
2734+ .subject("inline"),
2741+/// A parameter passed `name=value`, the form of an HTML attribute.
2742+fn parameter_form(function: &str, key: &str, value: &str, line: usize) -> Diagnostic {
2744+ code::PARAMETER_FORM,
2747+ "'{}' is a parameter of @{}: parameters are written `name value`, so write `{} {}`",
2748+ key, function, key, value
2751+ .subject(format!("{}=", key))
2752+ .suggest(Some(format!("{} ", key)))
2755+/// A call that leaves out a parameter without a default.
2756+fn missing_parameter(
2760+ column: Option<usize>,
2762+ let diagnostic = Diagnostic::error(
2763+ code::MISSING_PARAMETER,
2766+ "@{} needs '{}': the parameter has no default, so pass it as `{} VALUE`",
2767+ function, param, param
2772+ Some(column) => diagnostic.column(column),
2773+ None => diagnostic,
2777+/// The column of a call's `@name`, when it is on the call's line.
2778+fn name_column(head: &syntax::Head, line: usize) -> Option<usize> {
2779+ (head.name_span.line == line).then_some(head.name_span.column)
2782+/// Define `$name`, or, for `--name`, the CSS custom property on `:root`
2783+/// (which gets quoted text with its quotes, and is read with
2784+/// `var(--name)`, never as a variable). `@let name.field value` gives the
2785+/// record `$name` that field (or the list `$name` a new item at that
2786+/// index), as a new value in this block.
2787+fn set_variable(name: &str, value: Value, line_num: usize, ctx: &mut ParseContext) {
2788+ if name.starts_with("--") {
2791+ .map_or_else(|| value.to_string(), str::to_string);
2792+ let at_line = |diagnostic: Diagnostic, ctx: &ParseContext| match &ctx.current_source {
2793+ (current, Some(text)) if *current == line_num => diagnostic.source(text.clone()),
2796+ // `:root` is one place for the whole page: a declaration inside a
2797+ // block (an element, a loop, a function's body) would not be
2798+ // kept to it, and each run would replace the last
2799+ if ctx.env.frames.len() > FILE_FRAMES {
2800+ let diagnostic = Diagnostic::error(
2801+ code::INVALID_DEFINITION,
2804+ "`@let {name}` declares {name} on :root, for the whole page, so it goes at \
2805+ the top level of the file: to set it on an element and what is inside \
2806+ it, write `[{name} value]` on that element"
2810+ ctx.push_once(at_line(diagnostic, ctx));
2813+ match css_breakout(&css) {
2815+ let diagnostic = Diagnostic::error(
2816+ code::INVALID_VALUE,
2819+ "the value of '{}' has {}: `{}` can't be written into the page's CSS",
2823+ .subject(css.as_str());
2824+ ctx.push_once(at_line(diagnostic, ctx));
2826+ None => match ctx.css_vars.iter_mut().find(|(n, _)| n == name) {
2827+ Some(declared) => {
2828+ let diagnostic = Diagnostic::warning(
2829+ code::DUPLICATE_ATTRIBUTE,
2832+ "{name} is declared again: :root has one value for the whole page, \
2833+ so every element gets this one, also above this line (a theme \
2834+ redefines a token on an element: `[dark:{name} {css}]`)"
2839+ ctx.push_once(at_line(diagnostic, ctx));
2841+ None => ctx.css_vars.push((name.to_string(), css)),
2846+ let mut path = name.split('.');
2847+ let root = path.next().unwrap_or(name);
2848+ let fields: Vec<&str> = path.collect();
2849+ let value = match fields.is_empty() {
2851+ false => match with_field(ctx.env.value(root).cloned(), root, &fields, value) {
2852+ Ok(value) => value,
2855+ Diagnostic::error(code::INVALID_DEFINITION, line_num, message).subject(name);
2856+ let diagnostic = match &ctx.current_source {
2857+ (current, Some(text)) if *current == line_num => {
2858+ diagnostic.source(text.clone())
2862+ ctx.push_once(diagnostic);
2863+ // Reported: the name keeps what it held
2864+ ctx.let_lines.entry(root.to_string()).or_insert(line_num);
2869+ ctx.bind(root, value);
2870+ ctx.let_lines.entry(root.to_string()).or_insert(line_num);
2873+/// `value` (the value of `$name`) with the field at `path` set to `new`:
2874+/// a record's field, or the item of a list at an index it has. A name
2875+/// without a value, or one whose value is empty (a field a record doesn't
2876+/// have), becomes a record; any other value has no fields to set.
2878+ value: Option<Value>,
2882+) -> Result<Value, String> {
2883+ let Some((field, rest)) = path.split_first() else {
2886+ let inner = format!("{}.{}", name, field);
2888+ Some(Value::Record(fields)) => {
2889+ let mut fields = fields.as_ref().clone();
2890+ match fields.iter().position(|(key, _)| key == field) {
2892+ let old = std::mem::replace(&mut fields[i].1, Value::empty());
2893+ fields[i].1 = with_field(Some(old), &inner, rest, new)?;
2895+ None => fields.push((field.to_string(), with_field(None, &inner, rest, new)?)),
2897+ Ok(Value::Record(Rc::new(fields)))
2899+ Some(Value::List(list)) => {
2900+ let count = list.items.len();
2901+ let Some(i) = field.parse::<usize>().ok().filter(|&i| i < count) else {
2902+ return Err(format!(
2903+ "`${}` is {}, so `.{}` isn't one of its items (they are `.0` to `.{}`)",
2905+ Value::List(list).describe(),
2907+ count.saturating_sub(1)
2910+ let mut items = list.items.as_ref().clone();
2911+ let old = std::mem::replace(&mut items[i], Value::empty());
2912+ items[i] = with_field(Some(old), &inner, rest, new)?;
2913+ // Its items changed, so it no longer prints as written
2914+ Ok(Value::list(items))
2916+ None => Ok(Value::Record(Rc::new(vec![(
2918+ with_field(None, &inner, rest, new)?,
2920+ Some(value) if value.to_string().is_empty() => with_field(None, name, path, new),
2921+ Some(value) => Err(format!(
2922+ "`@let {}.{}` sets a field of a record, but `${}` is {} (`{}`), which has no fields",
2932+/// What a verbatim directive holds (`@head`, `@style`, `@raw`): the rest
2933+/// of its line (`@style .a { color: red }`), or else its indented block.
2934+/// The two together are a syntax error, reported by the tree; the line
2936+fn verbatim_content(node: &syntax::Node) -> String {
2937+ match node.directive().map(|d| &d.args) {
2938+ Some(DirectiveArgs::Text(Some(line))) => format!("{}\n", line.raw),
2939+ _ => verbatim_text(&node.children),
2943+/// The text of a verbatim body (`@head`, `@style`, `@markdown`, `@raw`).
2944+fn verbatim_text(children: &[syntax::Node]) -> String {
2945+ let mut text = String::new();
2946+ for child in children {
2947+ if let NodeKind::Verbatim(body) = &child.kind {
2948+ text.push_str(&body.text);
2955+// ---------------------------------------------------------------------------
2956+// @children replacement
2957+// ---------------------------------------------------------------------------
2959+fn replace_children_and_slots(
2961+ caller_children: &[Node],
2962+ slot_contents: &HashMap<String, Vec<Node>>,
2964+ let mut result = Vec::new();
2965+ for node in nodes {
2967+ Node::Element(elem) if elem.kind == ElementKind::Children => {
2968+ if caller_children.is_empty() && !elem.children.is_empty() {
2969+ // Use @children's own children as default/fallback content
2970+ result.extend(elem.children);
2972+ result.extend(caller_children.iter().cloned());
2975+ Node::Element(elem) if matches!(&elem.kind, ElementKind::Slot(name) if !name.is_empty()) =>
2977+ if let ElementKind::Slot(ref name) = elem.kind {
2978+ if let Some(content) = slot_contents.get(name) {
2979+ result.extend(content.iter().cloned());
2981+ // If no content provided for this slot, use the slot's own children as default
2982+ else if !elem.children.is_empty() {
2983+ result.extend(elem.children);
2987+ Node::Element(mut elem) => {
2989+ replace_children_and_slots(elem.children, caller_children, slot_contents);
2990+ result.push(Node::Element(elem));
2992+ other => result.push(other),
2998+// ---------------------------------------------------------------------------
2999+// Where @slot and @children are written
3000+// ---------------------------------------------------------------------------
3002+/// The files each `@include` line brought in, by the line's node id, with
3003+/// the include chain that leads to each.
3004+type IncludedBy = HashMap<usize, Vec<(Rc<Tree>, String)>>;
3006+/// The lines of the files an `@include` line brings in, and the include
3007+/// chain of each (for diagnostics).
3008+type Included<'a, 'f> = &'f dyn Fn(&syntax::Node) -> Vec<(&'a [syntax::Node], Option<&'a str>)>;
3010+/// Whether `name` is a function here: defined so far, or anywhere in the
3011+/// file and the files it includes.
3012+fn is_function(name: &str, ctx: &ParseContext) -> bool {
3013+ ctx.env.function(name).is_some() || ctx.namespace.contains(name)
3016+/// Whether `name` is one slot name: letters, digits, `-` and `_`,
3017+/// starting with a letter (like a function's name).
3018+fn is_slot_name(name: &str) -> bool {
3019+ name.chars().next().is_some_and(char::is_alphabetic)
3022+ .all(|c| c.is_alphanumeric() || c == '-' || c == '_')
3025+/// What a `@slot` or `@children` line is written in.
3026+#[derive(Clone, Copy)]
3028+ /// The top of a file or of a function's body, or a built-in element
3030+ Element(Option<&'a str>),
3031+ /// A call: its content.
3035+/// Where a line is, for [`slot_uses`].
3036+#[derive(Clone, Copy)]
3038+ /// Inside a function's body.
3041+ /// Outside a body: the call (and its line) whose content it is in.
3042+ call: Option<(&'a str, usize)>,
3043+ /// The include chain of the file it is in, when that isn't the file
3044+ /// being compiled.
3045+ file: Option<&'a str>,
3049+ /// The top of a file, or of a function's body.
3050+ fn top(body: bool) -> Self {
3053+ place: Place::Element(None),
3060+/// What [`slot_uses`] knows about the names and files it walks.
3061+struct Scan<'a, 'f> {
3062+ is_function: &'f dyn Fn(&str) -> bool,
3063+ included: Included<'a, 'f>,
3064+ /// Visit the bodies of the functions defined in the lines too.
3068+/// A `@slot` or `@children` written in a file, and where.
3069+struct SlotUse<'a> {
3070+ node: &'a syntax::Node,
3071+ head: &'a syntax::Head,
3072+ /// The text after it, which is a slot's name; `None` when it isn't
3073+ /// the last head of its chain.
3074+ text: Option<&'a syntax::Text>,
3075+ /// Written inline in a line of text, `{@slot x}`.
3081+ fn is_slot(&self) -> bool {
3082+ self.head.name == "slot"
3085+ /// The slot's name as written.
3086+ fn name(&self) -> &str {
3087+ self.text.map_or("", |t| t.raw.trim())
3090+ /// A `@slot NAME` that marks a place in a function's body (not one
3091+ /// that fills a slot of a call).
3092+ fn declares(&self) -> bool {
3093+ self.is_slot() && !self.inline && !matches!(self.at.place, Place::Call)
3097+/// Where each `@slot` and `@children` in `block` is written. A `@slot`
3098+/// directly under a call (under its `@if`, `@else` and `@each` too) fills
3099+/// one of its slots; anywhere else in a function's body it declares one.
3100+/// An included file's lines are where its `@include` is.
3102+ block: &'a [syntax::Node],
3104+ scan: &Scan<'a, '_>,
3105+ out: &mut Vec<SlotUse<'a>>,
3108+ text: &'a syntax::Text,
3109+ node: &'a syntax::Node,
3111+ scan: &Scan<'a, '_>,
3112+ out: &mut Vec<SlotUse<'a>>,
3114+ for segment in &text.segments {
3115+ if let Segment::Inline(inline_element) = segment {
3116+ let head = &inline_element.head;
3117+ if matches!(head.name.as_str(), "slot" | "children")
3118+ && !(scan.is_function)(&head.name)
3123+ text: inline_element.text.as_ref(),
3128+ if let Some(text) = &inline_element.text {
3129+ inline(text, node, at, scan, out);
3134+ for node in block {
3136+ NodeKind::Directive(directive) => match &directive.args {
3137+ DirectiveArgs::Let(def) if matches!(def.form, LetForm::Function(_)) => {
3138+ if scan.into_lets {
3143+ slot_uses(&node.children, top, scan, out);
3146+ // A value's body is an error of its own
3147+ DirectiveArgs::Let(_) => {}
3148+ _ if directive.spec.body == BodyKind::Verbatim => {}
3149+ // `@if`, `@else` and `@each` put their lines in place, and
3150+ // `@include` its file's; the lines under a directive that
3151+ // takes no body are its siblings
3153+ for (lines, file) in (scan.included)(node) {
3154+ slot_uses(lines, At { file, ..at }, scan, out);
3156+ slot_uses(&node.children, at, scan, out);
3159+ NodeKind::Element(line) => {
3161+ let last = line.chain.len() - 1;
3162+ for (i, head) in line.chain.iter().enumerate() {
3163+ let text = if i == last { line.text.as_ref() } else { None };
3164+ let function = (scan.is_function)(&head.name);
3165+ if !function && matches!(head.name.as_str(), "slot" | "children") {
3173+ } else if let Some(text) = text {
3174+ inline(text, node, at, scan, out);
3177+ at.place = Place::Call;
3179+ at.call = Some((&head.name, node.span.line));
3182+ at.place = Place::Element(Some(&head.name));
3185+ slot_uses(&node.children, at, scan, out);
3187+ NodeKind::Text(text) => {
3188+ inline(text, node, at, scan, out);
3189+ slot_uses(&node.children, at, scan, out);
3191+ NodeKind::Blank | NodeKind::Comment | NodeKind::Verbatim(_) => {}
3196+/// The slots a function's body declares, and whether it has a
3197+/// `@children`, when it is defined. The files its `@include` lines bring
3198+/// in count too: they are read now, since they run only at a call.
3199+fn declared_slots(body: &[syntax::Node], ctx: &mut ParseContext) -> (Vec<String>, bool) {
3200+ let mut files = HashMap::new();
3203+ ctx.base_path.clone(),
3208+ let included = |node: &syntax::Node| match files.get(&node.id) {
3209+ Some(tree) => vec![(&tree.nodes[..], None)],
3210+ None => Vec::new(),
3212+ let is_function = |name: &str| is_function(name, ctx);
3213+ slots_of(body, &is_function, &included)
3216+/// Read and parse the files the `@include` lines in `nodes` bring in (by
3217+/// a literal path, relative to `base`), and the files those include, by
3218+/// the node id of each `@include` line.
3220+ nodes: &[syntax::Node],
3221+ base: Option<PathBuf>,
3222+ stack: &mut Vec<PathBuf>,
3223+ ctx: &mut ParseContext,
3224+ files: &mut HashMap<usize, Rc<Tree>>,
3226+ let mut includes = Vec::new();
3227+ for node in nodes {
3228+ node.walk(&mut |node| {
3229+ if let Some(DirectiveArgs::Text(Some(path))) = node.directive().map(|d| &d.args)
3230+ && node.is_directive("include")
3232+ includes.push((node.id, path.raw.clone()));
3236+ for (id, path) in includes {
3237+ let path = path.trim_matches('"');
3238+ if path.contains('$') {
1311−
3241+ let resolved = match &base {
1312− // A function with a scoped @style wraps its output in the scope class
3242+ Some(base) => base.join(path),
1313− if ctx.scoped_functions.contains(name) {
3243+ None => PathBuf::from(path),
1314− let wrapper = Element {
3244+ };
1315− kind: ElementKind::El,
3245+ if stack.contains(&resolved) {
1316− attrs: vec![Attribute {
3246+ continue;
1317− key: "class".to_string(),
1318− value: Some(format!("hl-{}", name)),
1322− children: result_nodes,
1325− result_nodes = vec![Node::Element(wrapper)];
1327−
3248+ let Ok(text) = ctx.read_file(&resolved) else {
1328− Ok(result_nodes)
3249+ continue;
3251+ let tree = ctx.parse_tree(&text);
3252+ stack.push(resolved.clone());
3253+ let parent = resolved.parent().map(Path::to_path_buf);
3254+ read_includes(&tree.nodes, parent, stack, ctx, files);
3256+ files.insert(id, tree);
1331− fn parse_element_line(
3260+/// The slots a function's body declares (`@slot NAME`, in order), and
1332− &mut self,
3261+/// whether it has a `@children` for the content of a call. A `@slot`
1333− content: &str,
3262+/// directly under a call in the body fills that call's slot instead, so
1334− children: &[Syntax],
3263+/// `is_function` says which names are functions. The files the body
1335− line_num: usize,
3264+/// includes aren't read.
1336− ctx: &mut ParseContext,
3265+pub fn function_slots(
1337− ) -> Result<Node, ParseError> {
3266+ body: &[syntax::Node],
1338− let segments = split_chain(content);
3267+ is_function: &dyn Fn(&str) -> bool,
3268+) -> (Vec<String>, bool) {
3269+ slots_of(body, is_function, &|_| Vec::new())
1340− // Parse each segment into an Element
3272+fn slots_of<'a>(
1341− let mut elements: Vec<Element> = Vec::new();
3273+ body: &'a [syntax::Node],
1342− for seg in &segments {
3274+ is_function: &dyn Fn(&str) -> bool,
1343− let elem = parse_single_element(seg.trim(), line_num, ctx)?;
3275+ included: Included<'a, '_>,
1344− elements.push(elem);
3276+) -> (Vec<String>, bool) {
3282+ let mut uses = Vec::new();
3283+ slot_uses(body, At::top(true), &scan, &mut uses);
3284+ let mut slots: Vec<String> = Vec::new();
3285+ for slot in uses.iter().filter(|u| u.declares()) {
3286+ let name = slot.name();
3287+ if is_slot_name(name) && !slots.iter().any(|s| s == name) {
3288+ slots.push(name.to_string());
3291+ let has_children = uses.iter().any(|u| !u.is_slot() && !u.inline);
3292+ (slots, has_children)
1347− // Parse indented children (belong to the innermost element)
3295+/// The line as written, indented, when it is one physical line, so a
1348− let children = self.eval_block(children, ctx);
3296+/// column points into it.
3297+fn written_line(node: &syntax::Node) -> String {
3298+ match node.line_count <= 1 {
3299+ true => format!("{}{}", " ".repeat(node.indent), node.source),
3300+ false => node.source.clone(),
1350− // Build chain right-to-left: rightmost gets children, each wraps the next
3304+/// The lines of the files an `@include` line brought in when it ran, from
1351− let mut current_children = children;
3305+/// `included_by`.
1352− for mut elem in elements.into_iter().rev() {
3306+fn ran_includes<'a>(
1353− elem.children.extend(current_children);
3307+ included_by: &'a IncludedBy,
1354− current_children = vec![Node::Element(elem)];
3308+ node: &syntax::Node,
1355− }
3309+) -> Vec<(&'a [syntax::Node], Option<&'a str>)> {
3310+ match included_by.get(&node.id) {
3311+ Some(files) => files
3313+ .map(|(tree, chain)| (&tree.nodes[..], Some(chain.as_str())))
3315+ None => Vec::new(),
1357− current_children.into_iter().next().ok_or(ParseError {
3319+/// Check where every `@slot` and `@children` of the file and the files it
1358− line: line_num,
3320+/// includes is written, whether or not it runs: a slot has one name, a
1359− message: "element chain produced no nodes (this is a parser bug)".to_string(),
3321+/// function's body marks places with them, and a call fills its slots
3322+/// with `@slot` blocks directly under it. An included file's lines are
3323+/// where its `@include` is (in a body, under a call), so an `@include`
3324+/// that never ran leaves its file unchecked.
3325+fn check_slot_places(ctx: &mut ParseContext) {
3326+ let trees = std::mem::take(&mut ctx.trees);
3327+ let included_by = ctx.included_by.clone();
3328+ let is_function = |name: &str| is_function(name, ctx);
3330+ is_function: &is_function,
3331+ included: &|node| ran_includes(&included_by, node),
3334+ let mut uses = Vec::new();
3335+ for (tree, _) in trees.iter().filter(|(_, chain)| chain.is_none()) {
3336+ slot_uses(&tree.nodes, At::top(false), &scan, &mut uses);
3338+ let found: Vec<Diagnostic> = uses
3340+ .filter_map(|slot| {
3341+ let mut d = slot_problem(slot)?;
3342+ if d.column.is_none() {
3343+ d = d.column(slot.head.name_span.column);
3345+ d = d.source(written_line(slot.node));
3346+ if let Some(file) = slot.at.file {
3347+ d.message = format!("{}\n in {}", d.message, file);
3352+ ctx.diagnostics.extend(found);
3356+/// What is wrong with a `@slot` or `@children` where it is written.
3357+fn slot_problem(slot: &SlotUse) -> Option<Diagnostic> {
3358+ let line = slot.node.span.line;
3359+ let what = if slot.is_slot() {
3360+ match slot.name() {
3361+ "" => "@slot".to_string(),
3362+ name => format!("@slot {}", name),
3365+ "@children".to_string()
3368+ return Some(Diagnostic::error(
3369+ code::MISPLACED_SLOT,
3372+ "{} goes on a line of its own: inline in text it marks and fills nothing",
3377+ if let Some(list) = &slot.head.attrs {
3380+ code::UNEXPECTED_ARGUMENT,
3383+ "{} takes no attributes: it is replaced by content, so style the \
3384+ element around it",
3388+ .column(list.span.column),
3391+ if slot.is_slot() {
3392+ let name = slot.name();
3393+ if name.is_empty() {
3394+ return Some(Diagnostic::error(
3395+ code::MISSING_ARGUMENT,
3397+ "@slot needs a name: `@slot footer` (the caller's content without a \
3398+ name goes where `@children` is)"
3402+ if !is_slot_name(name) {
3403+ let joined = name.split_whitespace().collect::<Vec<_>>().join("-");
3404+ let suggestion = is_slot_name(&joined).then_some(joined);
3405+ let column = slot.text.map(|t| t.span.column);
3406+ let d = Diagnostic::error(
3407+ code::INVALID_SLOT_NAME,
3410+ "'{}' is not a slot name: a slot's name is one word of letters, digits, \
3411+ `-` and `_`, starting with a letter, and its content goes on the lines \
3417+ .suggest(suggestion);
3418+ return Some(match column {
3419+ Some(column) => d.column(column),
3423+ if matches!(slot.at.place, Place::Call) || slot.at.body {
3426+ let message = match (slot.at.call, slot.at.place) {
3427+ (Some((call, call_line)), Place::Element(Some(element))) => format!(
3428+ "{} is inside @{}, so it fills nothing: a @slot block that fills a slot of \
3429+ @{} (line {}) goes directly under the call",
3430+ what, element, call, call_line
3433+ "{} is outside a function's body: `@slot NAME` marks a place in a body \
3434+ (`@let @name`), and directly under a call it fills one",
3438+ return Some(Diagnostic::error(code::MISPLACED_SLOT, line, message));
3443+ let message = match slot.at.call {
3444+ Some((call, _)) => format!(
3445+ "@children is outside a function's body, so it stands for nothing: the content \
3446+ for @{} is written directly under the call",
3449+ None => "@children is outside a function's body: it marks where a body puts the \
3450+ content of each call"
3453+ Some(Diagnostic::error(code::MISPLACED_SLOT, line, message))
1364−// ---------------------------------------------------------------------------
3456+/// A `@slot NAME` block that fills a slot of a call.
1365−// @children replacement
3457+struct Filler<'a> {
1366−// ---------------------------------------------------------------------------
3458+ node: &'a syntax::Node,
3459+ text: &'a syntax::Text,
3460+ /// The include chain of the file it is in, when that isn't the file
3461+ /// being compiled.
3462+ file: Option<&'a str>,
1368−fn replace_children_and_slots(
3465+/// Whether `@slot` is the built-in element here, and not a function
1369− nodes: Vec<Node>,
3466+/// defined so far that took its name.
1370− caller_children: &[Node],
3467+fn slot_is_built_in(ctx: &ParseContext) -> bool {
1371− slot_contents: &HashMap<String, Vec<Node>>,
3468+ ctx.env.function("slot").is_none()
1372−) -> Vec<Node> {
3469+}
1373− let mut result = Vec::new();
3470+
1374− for node in nodes {
3471+/// The `@slot NAME` blocks directly under a call, in `block` (under its
1375− match node {
3472+/// `@if`, `@else` and `@each` too, and in the files its `@include` lines
1376− Node::Element(elem) if elem.kind == ElementKind::Children => {
3473+/// brought in).
1377− if caller_children.is_empty() && !elem.children.is_empty() {
3474+fn fillers<'a>(
1378− // Use @children's own children as default/fallback content
3475+ block: &'a [syntax::Node],
1379− result.extend(elem.children);
3476+ file: Option<&'a str>,
1380− } else {
3477+ included: &'a IncludedBy,
1381− result.extend(caller_children.iter().cloned());
3478+ out: &mut Vec<Filler<'a>>,
3480+ for node in block {
3482+ NodeKind::Directive(directive)
3483+ if matches!(directive.name(), "if" | "else" | "each") =>
3485+ fillers(&node.children, file, included, out);
3487+ NodeKind::Directive(directive) if directive.name() == "include" => {
3488+ for (lines, file) in ran_includes(included, node) {
3489+ fillers(lines, file, included, out);
1384− Node::Element(elem) if matches!(&elem.kind, ElementKind::Slot(name) if !name.is_empty()) =>
3492+ NodeKind::Element(line) if line.chain.len() == 1 && line.chain[0].name == "slot" => {
1385− {
3493+ if let Some(text) = &line.text {
1386− if let ElementKind::Slot(ref name) = elem.kind {
3494+ out.push(Filler { node, text, file });
1387− if let Some(content) = slot_contents.get(name) {
1388− result.extend(content.iter().cloned());
1390− // If no content provided for this slot, use the slot's own children as default
1391− else if !elem.children.is_empty() {
1392− result.extend(elem.children);
1396− Node::Element(mut elem) => {
3497+ _ => {}
1397− elem.children =
3498+ }
1398− replace_children_and_slots(elem.children, caller_children, slot_contents);
3499+ }
1399− result.push(Node::Element(elem));
3500+}
3502+/// Whether `block`, the lines under a call, holds content other than
3503+/// `@slot` blocks (under `@if`, `@else` and `@each` too): text, an
3504+/// element, raw HTML, Markdown or an included file. For code that doesn't
3506+fn holds_content(block: &[syntax::Node], ctx: &ParseContext) -> bool {
3507+ block.iter().any(|node| match &node.kind {
3508+ NodeKind::Directive(directive) => match directive.name() {
3509+ "if" | "else" | "each" => holds_content(&node.children, ctx),
3510+ name => matches!(name, "raw" | "markdown" | "include"),
3512+ NodeKind::Element(line) => {
3513+ line.chain[0].name != "slot" || !slot_is_built_in(ctx) || line.chain.len() > 1
3515+ NodeKind::Text(_) => true,
3520+/// Check the `@slot NAME` blocks passed to each call of a line against
3521+/// the slots its function declares. `calls` has the function of each head
3522+/// of the chain that is a call.
3524+ node: &syntax::Node,
3525+ element: &syntax::ElementLine,
3526+ calls: &[Option<(String, Rc<FnDef>)>],
3527+ ctx: &mut ParseContext,
3529+ if !slot_is_built_in(ctx) {
3532+ let included = ctx.included_by.clone();
3533+ let last = element.chain.len() - 1;
3534+ for (i, call) in calls.iter().enumerate() {
3535+ let Some((name, function)) = call else {
3538+ let mut found = Vec::new();
3540+ fillers(&node.children, None, &included, &mut found);
3541+ } else if i + 1 == last
3542+ && element.chain[last].name == "slot"
3543+ && let Some(text) = &element.text
3545+ // `@card > @slot footer`
3546+ found.push(Filler {
3552+ for filler in found {
3553+ let slot = filler.text.raw.trim();
3554+ if !is_slot_name(slot) || function.slots.iter().any(|s| s == slot) {
1401− other => result.push(other),
3557+ let mut d = unknown_slot(name, slot, &function.slots, filler.text.span.line)
3558+ .column(filler.text.span.column)
3559+ .source(written_line(filler.node));
3560+ if let Some(file) = filler.file {
3561+ d.message = format!("{}\n in {}", d.message, file);
1407−// ---------------------------------------------------------------------------
3568+/// A `@slot NAME` block for a slot the function doesn't declare.
1408−// Element parsing
3569+fn unknown_slot(function: &str, slot: &str, slots: &[String], line: usize) -> Diagnostic {
1409−// ---------------------------------------------------------------------------
3570+ let candidates: Vec<&str> = slots.iter().map(String::as_str).collect();
3571+ let suggestion = suggest_closest(slot, &candidates);
3572+ let message = match (slots.is_empty(), suggestion) {
3573+ (true, _) => format!(
3574+ "@{} has no slot '{}': its body declares no slots (`@slot NAME`)",
3577+ (false, Some(close)) => format!(
3578+ "@{} has no slot '{}', did you mean '{}'? (its slots: {})",
3584+ (false, None) => format!(
3585+ "@{} has no slot '{}' (its slots: {})",
3591+ Diagnostic::error(code::UNKNOWN_SLOT, line, message)
3593+ .suggest(suggestion)
1411−fn extract_element_name(content: &str) -> &str {
3596+/// Content passed to a function whose body has no `@children`.
1412− let without_at = &content[1..];
3597+fn no_children(function: &str, line: usize, column: Option<usize>) -> Diagnostic {
1413− match without_at.find([' ', '[']) {
3598+ let d = Diagnostic::error(
1414− Some(i) => &without_at[..i],
3599+ code::UNEXPECTED_CONTENT,
1415− None => without_at,
3600+ line,
3602+ "@{0} takes no content: its body has no `@children`, so the text and lines \
3603+ passed to it would be dropped (pass text as a parameter, `@{0} [name value]`, \
3604+ or add `@children` to the body)",
3608+ .subject(function);
3610+ Some(column) => d.column(column),
3615+// ---------------------------------------------------------------------------
3617+// ---------------------------------------------------------------------------
3619+/// Build the element for `@name [attrs] text` (on its own line, in a chain,
3620+/// or inline in text).
1419fn parse_single_element(
3621fn parse_single_element(
1420− content: &str,
3622+ head: &syntax::Head,
3623+ text: Option<&syntax::Text>,
1421 line_num: usize,
3624 line_num: usize,
1422 ctx: &mut ParseContext,
3625 ctx: &mut ParseContext,
1423) -> Result<Element, ParseError> {
3626) -> Result<Element, ParseError> {
1424− let (kind, rest) = if content.starts_with('[') {
3627+ let kind = parse_element_kind(&head.name, line_num, ctx)?;
1425− // Implicit @el
3628+ let mut attrs = head.attrs.as_ref().map_or_else(Vec::new, |list| {
1426− (ElementKind::El, content.to_string())
3629+ parse_attr_list(&list.attrs, line_num, ctx, true, &[])
1427− } else if let Some(without_at) = content.strip_prefix('@') {
3630+ });
1428− match without_at.find([' ', '[']) {
3631+
1429− Some(i) => {
3632+ // The leading argument: for an element whose row names a leading
1430− let kind_str = &without_at[..i];
3633+ // attribute (`@link`'s href, `@image`'s src, `@form`'s action, ...),
1431− let rest = if without_at.as_bytes()[i] == b'[' {
3634+ // the first token of the text fills it, split before anything is
1432− without_at[i..].to_string()
3635+ // filled in, and the rest is content (an error on an element without
1433− } else {
3636+ // content). `@slot`'s whole text is its name. Any other element's text
1434− without_at[i + 1..].to_string()
3637+ // is content, parsed like any line of text, as in `@el [padding 8]
1435− };
3638+ // Hello` or `@h2 Meet {@text htmlang}`; its layout decides how it
1436− match parse_element_kind(kind_str, line_num) {
3639+ // combines with the lines under it.
1437− Ok(kind) => (kind, rest),
3640+ let mut children = Vec::new();
1438− Err(mut e) => {
3641+ let mut argument = None;
1439− // Also suggest user-defined functions
3642+ let leading = kind.arg().attributes();
1440− if let Some(fn_suggestion) = suggest_fn_name(kind_str, ctx) {
3643+ match text {
1441− e.message =
3644+ Some(text) if !leading.is_empty() => {
1442− format!("{}, or did you mean @{}?", e.message, fn_suggestion);
3645+ let (token, rest) = text.split_leading();
1443− }
3646+ let given = attrs
1444− return Err(e);
3647+ .iter()
1445− }
3648+ .find(|a| a.html && leading.contains(&a.key.as_str()))
3649+ .map(|a| (a.key.clone(), a.value.clone().unwrap_or_default()));
3650+ if let Some((key, value)) = given {
3651+ // The attribute wins; the text is content, as if the
3652+ // element had no leading argument
3653+ ctx.push_once(leading_twice(&kind, &token, &key, &value, text, ctx));
3654+ if !takes_no_text(&kind) {
3655+ children.push(Node::Text(text_segments(text, ctx)));
1447− }
3657+ } else if let Some(d) = bad_leading_token(&kind, &token, &text.raw, ctx) {
1448− None => match parse_element_kind(without_at, line_num) {
3658+ // Nothing is taken as the argument; the line is content
1449− Ok(kind) => (kind, String::new()),
3659+ ctx.push_once(d);
1450− Err(mut e) => {
3660+ if !takes_no_text(&kind) {
1451− if let Some(fn_suggestion) = suggest_fn_name(without_at, ctx) {
3661+ children.push(Node::Text(text_segments(text, ctx)));
1452− e.message = format!("{}, or did you mean @{}?", e.message, fn_suggestion);
3662+ }
3664+ let column = Some(token.span.column);
3665+ if let Some(d) = text_as_url(&kind, &token, ctx) {
3669+ ctx.fill_value(&token.raw, text.span.line, column, Sink::Text)
3672+ if let Some(rest) = rest {
3673+ if let Some(d) = chain_after_argument(&kind, &token.raw, &rest, ctx) {
3676+ if takes_no_text(&kind) {
3677+ let d = after_the_leading_argument(&kind, &token.raw, &rest);
3678+ let d = at_attribute(d, Some(rest.span.column), ctx);
3681+ children.push(Node::Text(text_segments(&rest, ctx)));
1458− } else {
3686+ Some(text) if matches!(kind, ElementKind::Slot(_)) => {
1459− return Err(ParseError {
3687+ argument =
1460− line: line_num,
3688+ Some(ctx.interpolate_text(&text.raw, text.span.line, Some(text.span.column)));
1461− message: format!("expected @element or [attrs], got: {}", content),
1465− // Parse optional [attrs]
1466− let (attrs, rest) = if rest.starts_with('[') {
1467− parse_attr_brackets(&rest, line_num, ctx)?
1472− let rest = rest.trim().to_string();
1473− track_var_refs(&rest, &mut ctx.used_variables);
1475− // For @link, first token of rest is URL, remainder is inline text
1476− let mut children = Vec::new();
1477− let argument = if rest.is_empty() {
1479− } else if kind == ElementKind::Link {
1480− let rest_sub = substitute_vars(&rest, &ctx.variables);
1481− if let Some((url, text)) = rest_sub.split_once(' ') {
1482− let text = text.trim();
1483− if !text.is_empty() {
1484− children.push(Node::Text(parse_text_segments(text, ctx)));
1486− Some(url.to_string())
1490− } else {
3690+ Some(text) => children.push(Node::Text(text_segments(text, ctx))),
1491− Some(substitute_vars(&rest, &ctx.variables))
3691+ // `@link [href=/about]`: the attribute is the leading argument, so
1492− };
3692+ // both forms compile the same (`@image [src=a.svg, inline]`). Not
3693+ // for `@source`, whose attribute depends on where it is.
3694+ None if leading.len() == 1 => {
3695+ if let Some(i) = attrs.iter().position(|a| a.html && a.key == leading[0]) {
3696+ argument = Some(attrs.remove(i).value.unwrap_or_default());
1494 // For @slot, the argument is the slot name
3702 // For @slot, the argument is the slot name
1495 let kind = if let ElementKind::Slot(_) = kind {
3703 let kind = if let ElementKind::Slot(_) = kind {
@@ -1498,201 +3706,352 @@ fn parse_single_element(
1501− // Every other element treats its argument as leading text content, as
1502− // in `@el [padding 8] Hello` or `@paragraph Read {@link /more more}`.
1503− let argument = match argument {
1504− Some(_) if !argument_is_special(&kind) && !renders_argument_as_text(&kind) => {
1505− children.insert(0, Node::Text(parse_text_segments(&rest, ctx)));
1511 Ok(Element {
3709 Ok(Element {
1514 argument,
3712 argument,
1515 children,
3713 children,
1516 line_num,
3714 line_num,
1520−/// Elements whose argument is not text content: a URL, a source, an action,
3719+/// Whether `node` or a line inside it calls `@name` outside any `@if`
1521−/// or a slot name.
3720+/// (in a chain, or inline in text).
1522−fn argument_is_special(kind: &ElementKind) -> bool {
3721+fn calls_unguarded(node: &syntax::Node, name: &str) -> bool {
1523− matches!(
3722+ if node.is_directive("if") || node.is_directive("else") {
1524− kind,
3723+ return false;
1525− ElementKind::Link | ElementKind::Image | ElementKind::Script | ElementKind::Slot(_)
3724+ }
1526− ) || kind
3725+ let text_calls = |text: &syntax::Text| {
1527− .spec()
3726+ text.segments
1528− .is_some_and(|spec| matches!(spec.arg, TagArg::Attr(_)))
3727+ .iter()
1529−}
3728+ .any(|s| matches!(s, Segment::Inline(inline) if inline.head.name == name))
1531−/// The directive names (without `@`) the parser recognizes, for tools such
3730+ let here = match &node.kind {
1532−/// as the language server.
3731+ NodeKind::Element(element) => {
1533−pub fn known_directives() -> &'static [&'static str] {
3732+ element.chain.iter().any(|head| head.name == name)
1534− KNOWN_DIRECTIVES
3733+ || element.text.as_ref().is_some_and(text_calls)
1536−
3735+ NodeKind::Text(text) => text_calls(text),
1537−const KNOWN_DIRECTIVES: &[&str] = &[
3736+ _ => false,
1539− "let",
3738+ here || node
1540− "include",
3739+ .children
1541− "raw",
3740+ .iter()
1542− "keyframes",
3741+ .any(|child| calls_unguarded(child, name))
1555−fn parse_element_kind(s: &str, line_num: usize) -> Result<ElementKind, ParseError> {
3744+/// `@td [padding 8] @children`: `@children` and `@slot NAME` mark where a
1556− if let Some(kind) = ElementKind::from_name(s) {
3745+/// call's content goes only on a line of their own; after an element's
1557− return Ok(kind);
3746+/// attributes, or in a verbatim body, they are text.
3747+fn marker_in_text(node: &syntax::Node) -> Option<Diagnostic> {
3748+ let is_marker = |text: &str| {
3749+ let text = text.trim();
3750+ text == "@children" || text == "@slot" || text.starts_with("@slot ")
3752+ let mut line = node.span.line;
3753+ let mut source = written_line(node);
3754+ let (marker, message) = match &node.kind {
3755+ NodeKind::Element(element) => {
3756+ let text = element.text.as_ref()?;
3757+ if !is_marker(&text.raw) {
3760+ let name = &element.chain.last()?.name;
3761+ let marker = text.raw.trim().to_string();
3762+ let message = format!(
3763+ "`{marker}` after @{name}'s attributes is text: it marks where a call's content \
3764+ goes only on a line of its own, so write it on the next line, indented under \
3769+ NodeKind::Verbatim(verbatim) if verbatim.escaped => {
3770+ let (i, written) = verbatim
3774+ .find(|(_, l)| is_marker(l))?;
3775+ let marker = written.trim().to_string();
3777+ source = written.to_string();
3778+ let message = format!(
3779+ "`{marker}` in a verbatim body is text: the body is written as it is, so it can't \
3780+ hold a call's content (pass the text as a parameter instead)"
3787+ Diagnostic::error(code::MISPLACED_SLOT, line, message)
3793+/// A first word that can't be a leading argument: an inline element
3794+/// (`@link {@b x} y`), or a quote that isn't closed (`@link "a b`).
3795+fn bad_leading_token(
3796+ kind: &ElementKind,
3797+ token: &syntax::Arg,
3799+ ctx: &ParseContext,
3800+) -> Option<Diagnostic> {
3801+ let what = leading_name(kind);
3802+ let name = kind.name();
3803+ let message = if token.raw.starts_with("{@") {
3805+ "@{0} takes its {1} first, before any text: write `@{0} VALUE {2}`, or give it as \
3811+ } else if token.raw.starts_with('"') && syntax::quoted_string(&token.raw).is_none() {
3813+ "@{}'s {} starts with a `\"` that isn't closed: close it (`\"...\"`), or write \
3814+ `\\\"` for a quote in the value",
3820+ let d = Diagnostic::error(code::UNEXPECTED_ARGUMENT, token.span.line, message)
3821+ .subject(token.raw.clone());
3822+ Some(at_attribute(d, Some(token.span.column), ctx))
3825+/// A first word taken as a URL that reads as text: a word with a capital
3826+/// and nothing a URL or a file name has, as in `@link [hx-get=/panel] Open
3827+/// panel`, whose href would be `Open`. It still is (a relative URL can be
3828+/// such a word), with a warning.
3829+fn text_as_url(kind: &ElementKind, token: &syntax::Arg, ctx: &ParseContext) -> Option<Diagnostic> {
3830+ const URLS: &[&str] = &["href", "src", "srcset", "action", "data"];
3831+ let word = token.raw.as_str();
3832+ let reads_as_text = word.starts_with(char::is_uppercase)
3833+ && !word.contains([
3834+ '/', '.', ':', '#', '?', '=', '&', '%', '~', '$', '{', '\\', '"',
3836+ if !reads_as_text || !kind.arg().attributes().iter().any(|a| URLS.contains(a)) {
1559− if let Some(hint) = removed_syntax_hint(&format!("@{}", s)) {
3839+ let name = kind.name();
1560− return Err(ParseError {
3840+ let attr = leading_name(kind);
1561− line: line_num,
3841+ let text = if takes_no_text(kind) {
1562− message: hint,
3842+ String::new()
3844+ format!(": write the {attr} before the text, or put the text on the lines under it")
3846+ let message = format!(
3847+ "@{name} takes '{word}', its first word, as its {attr}{text}. A relative URL that \
3848+ starts with a capital is written `./{word}`"
3850+ let d = Diagnostic::warning(code::TEXT_AS_URL, token.span.line, message).subject(word);
3851+ Some(at_attribute(d, Some(token.span.column), ctx))
3854+/// `@link /a > @image logo.png`: a `>` chains only after an element's
3855+/// name or its `[attributes]`, so after a leading argument it is text.
3856+/// Said when what follows names an element or a function.
3857+fn chain_after_argument(
3858+ kind: &ElementKind,
3860+ rest: &syntax::Text,
3861+ ctx: &ParseContext,
3862+) -> Option<Diagnostic> {
3863+ let after = rest.raw.strip_prefix('>')?;
3864+ let name_start = after.trim_start().strip_prefix('@')?;
3865+ if after.len() == after.trim_start().len() {
1565− let all_known: Vec<&str> = ElementKind::all_names()
3868+ let name: String = name_start
1566− .chain(KNOWN_DIRECTIVES.iter().copied())
3869+ .chars()
3870+ .take_while(|c| c.is_ascii_alphanumeric() || *c == '-')
1567 .collect();
3871 .collect();
1568− let message = match suggest_closest(s, &all_known) {
3872+ if ElementKind::from_name(&name).is_none() && ctx.env.function(&name).is_none() {
1569− Some(closest) => format!("unknown element @{}, did you mean @{}?", s, closest),
3873+ return None;
1570− None => format!("unknown element @{}", s),
3874+ }
1571− };
3875+ let attr = leading_name(kind);
1572− Err(ParseError {
3876+ let d = Diagnostic::warning(
1573− line: line_num,
3877+ code::UNEXPECTED_ARGUMENT,
1574− message,
3878+ rest.span.line,
3880+ "`{}` after @{}'s {} is text, not a chain: `>` chains after an element's name or \
3881+ its [attributes], so write `@{} [{}={}] {}`",
3882+ rest.raw.trim_end(),
3888+ rest.raw.trim_end()
3891+ .subject(rest.raw.trim_end());
3892+ Some(at_attribute(d, Some(rest.span.column), ctx))
1578−/// Directives and element names removed when the language was simplified,
3895+/// A leading argument given twice, as the first token and as its
1579−/// with what replaces each. `htmlang upgrade` rewrites all of them.
3896+/// attribute: `@link [href=/a] About`.
1580−const REMOVED_SYNTAX: &[(&str, &str)] = &[
3897+fn leading_twice(
1581− ("@fn", "use `@let name $param` with an indented body"),
3898+ kind: &ElementKind,
1582− ("@define", "use `@let name [attributes]`"),
3899+ token: &syntax::Arg,
1583− ("@mixin", "use `@let name [attributes]`"),
3900+ key: &str,
1584− ("@unless", "use `@if not <condition>`"),
3901+ value: &str,
1585− ("@for", "use `@each $i in 1..10`"),
3902+ text: &syntax::Text,
1586− ("@repeat", "use `@each $_ in 1..N`"),
3903+ ctx: &ParseContext,
1587− (
3904+) -> Diagnostic {
1588− "@switch",
3905+ let name = kind.name();
1589− "use `@match`, with `@let __switch [...]` inside a case for its attributes",
3906+ let what = leading_name(kind);
1590− ),
3907+ // The value as one token: quoted when it is empty or has a space in it
1591− ("@use", "use `@include`"),
3908+ let value = if !value.is_empty() && syntax::leading_token_len(value) == value.len() {
1592− (
3909+ value.to_string()
1593− "@import",
3910+ } else {
1594− "use `@include` (a file with only definitions emits no content)",
3911+ format!("\"{}\"", value.replace('\\', "\\\\").replace('"', "\\\""))
1596− ("@with", "use `@let alias $source`"),
3913+ let written = if takes_no_text(kind) {
1597− (
3914+ format!("@{} {}", name, value)
1598− "@layout",
3915+ } else {
1599− "make the layout a function (`@let layout` with `@children`) and call it",
3916+ format!("@{} {} {}", name, value, text.raw)
1601− (
3918+ let d = Diagnostic::error(
1602− "@extends",
3919+ code::DUPLICATE_ATTRIBUTE,
1603− "make the layout a function (`@let layout` with `@children` and `@slot`), \
3920+ text.span.line,
1604− `@include` its file and call it",
3921+ format!(
1605− ),
3922+ "@{} takes its first word '{}' as its {}, and it also has {}=: give it once, \
1606− ("@scope", "write the `@scope` rule in an `@style` block"),
3923+ as `{}`",
1607− (
3924+ name, token.raw, what, key, written
1608− "@starting-style",
3925+ ),
1609− "write the `@starting-style` rule in an `@style` block",
3926+ )
1610− ),
3927+ .subject(token.raw.clone());
1611− ("@css-property", "write an `@property` rule in an `@style` block"),
3928+ at_attribute(d, Some(token.span.column), ctx)
1612− ("@lang", "use `@page [lang ...] Title`"),
3929+}
1613− ("@favicon", "use `@page [favicon ...] Title`"),
1614− ("@canonical", "use `@page [canonical ...] Title`"),
1615− ("@base", "use `@page [base ...] Title`"),
1616− ("@og", "use `@meta og:NAME VALUE`"),
1617− ("@debug", "use `@warn`"),
1618− ("@svg", "use `@image [inline] file.svg`"),
1619− ("@match", "use `@if $x == a` / `@else if $x == b` / `@else`"),
1620− ("@case", "use `@if $x == a` / `@else if $x == b` / `@else`"),
1621− ("@default", "use `@else` in an `@if` chain"),
1622− ("@theme", "use a `@let --name value` line per token"),
1625− "put a `<script type=\"application/ld+json\">` in `@head`",
1627− ("@font-face", "write the `@font-face` rule in an `@style` block"),
1630− "write a manifest.json file and link it from `@head`",
1632− ("@breakpoint", "write the media query in an `@style` block"),
1633− ("@deprecated", "remove it"),
1636− "use `@data $name dir/*.json` (each file becomes `$name.STEM.key`)",
1638− ("@env", "use `@data $name env:NAME [default]`"),
1641− "download the data before building and use `@data $name file.json`",
1645− "put each locale's strings in a JSON file and use `@data $t locales/$lang.json`",
1647− ("@defer", "remove it: the content is already in the page"),
1648− ("@log", "use `@warn`"),
1651− "use `@let`: an `@style` block in a function body is scoped to it",
1653− ("@col", "use `@column`"),
1654− ("@p", "use `@paragraph`"),
1655− ("@img", "use `@image`"),
1656− ("@li", "use `@item`"),
1657− ("@btn", "use `@button`"),
1658− ("@ul", "use `@list`"),
1659− ("@divider", "use `@hr`"),
1660− ("@opt", "use `@option`"),
1663−/// Attributes that became standard-library bundles or plain CSS.
3931+/// The attribute an element's leading argument fills, for messages.
1664−fn removed_attribute_hint(name: &str) -> Option<&'static str> {
3932+fn leading_name(kind: &ElementKind) -> &'static str {
1665− match name {
3933+ match kind.arg() {
1666− "skeleton" => Some("use the `$skeleton` bundle"),
3934+ TagArg::Source => "srcset in @picture or src elsewhere",
1667− "no-scrollbar" => Some("use the `$no-scrollbar` bundle"),
3935+ arg => arg.attribute(false).unwrap_or("argument"),
1668− "gradient" => Some("use `background linear-gradient(...)`"),
1669− "animate" => Some("use `animation`"),
1670− "inset-area" => Some("use `position-area`"),
1671− "gap-x" => Some("use `column-gap`"),
1672− "gap-y" => Some("use `row-gap`"),
1673− "shadow" => Some("use `box-shadow`"),
1674− "blur" => Some("use `filter blur(...)`"),
1675− "backdrop-blur" => Some("use `backdrop-filter blur(...)`"),
1676− "truncate" => Some("use the `$truncate` bundle"),
1677− "critical" => Some("remove it"),
1678− "grid" => Some("use `@grid`, or `display grid`"),
1683−/// If `content` starts with removed syntax, the error message for it.
3939+/// Whether text after an element's leading argument has nowhere to go:
1684−fn removed_syntax_hint(content: &str) -> Option<String> {
3940+/// an element without content (`@image`, `@source`, ...), or `@optgroup`,
1685− let trimmed = content.trim_start();
3941+/// which holds only `@option` lines, so `@optgroup Citrus fruits` would
1686− REMOVED_SYNTAX.iter().find_map(|(name, replacement)| {
3942+/// otherwise make `Citrus` the label and drop `fruits`.
1687− let rest = trimmed.strip_prefix(name)?;
3943+fn takes_no_text(kind: &ElementKind) -> bool {
1688− if !(rest.is_empty() || rest.starts_with([' ', '['])) {
3944+ kind.layout() == Layout::Void || kind.is_tag("optgroup")
3947+/// Text after the leading argument of an element without content:
3948+/// `@image logo.png Our logo`.
3949+fn after_the_leading_argument(kind: &ElementKind, token: &str, rest: &syntax::Text) -> Diagnostic {
3950+ let name = kind.name();
3951+ let attr = leading_name(kind);
3952+ let alt = if matches!(kind, ElementKind::Image) || kind.is_tag("area") {
3953+ " For a text alternative, write `alt=...`."
3957+ let holds = if kind.layout() == Layout::Void {
3958+ "it has no content"
3960+ "it holds only the elements on the lines under it"
3962+ let bare = syntax::quoted_string(token).unwrap_or(token);
3964+ code::UNEXPECTED_ARGUMENT,
3967+ "@{0} takes one word after its attributes, its {1} ('{2}'), and {5}, so '{3}' \
3968+ would go nowhere. A value with a space in it is quoted: `\"{6} {3}\"`.{4}",
3969+ name, attr, token, rest.raw, alt, holds, bare
3972+ .subject(rest.raw.clone())
3975+/// The element named `name`, or an "unknown element" error that suggests
3976+/// the closest element, directive or function.
3977+fn parse_element_kind(
3980+ ctx: &mut ParseContext,
3981+) -> Result<ElementKind, ParseError> {
3982+ if let Some(kind) = ElementKind::from_name(name) {
3985+ // A known name in a place it can't go: say why instead of suggesting
3986+ // the name itself.
3987+ let misplaced = if crate::ast::directive(name).is_some() {
1691 Some(format!(
3988 Some(format!(
1692− "`{}` was removed: {} (run `htmlang upgrade` to rewrite it automatically)",
3989+ "unknown element @{}: @{} is a directive, which goes at the start of its own line",
1693− name, replacement
3990+ name, name
1695− })
3992+ } else if ctx.env.bundle(name).is_some() {
3994+ "unknown element @{}: '{}' is an attribute bundle, used as `[${}]` \
3995+ (a function is defined with `@let @{}`)",
3996+ name, name, name, name
3998+ } else if ctx.env.value(name).is_some() {
4000+ "unknown element @{}: '{}' is a value, used as `${}` \
4001+ (a function is defined with `@let @{}`)",
4002+ name, name, name, name
4004+ } else if ctx.namespace.contains(name) {
4005+ ctx.used_functions.insert(name.to_string());
4007+ "unknown element @{}: the function @{} isn't visible here. A definition is \
4008+ visible from its line to the end of its block, and a function's body sees what \
4009+ is defined above the function, so define @{} above this line, outside the block \
4013+ } else if matches!(name, "svg" | "math" | "template") {
4015+ "unknown element @{}: htmlang doesn't write <{}>; put its markup in the page with \
4020+ " (or an SVG file with `@image [inline] file.svg`)"
4028+ if let Some(message) = misplaced {
4029+ return Err(Diagnostic::error(code::UNKNOWN_ELEMENT, line_num, message).subject(name));
4031+ let all_known: Vec<&str> = ElementKind::all_names()
4032+ .chain(DIRECTIVES.iter().map(|d| d.name))
4034+ // An HTML element htmlang writes under its own name (`@a` is `@link`).
4035+ let written_otherwise = crate::ast::HTML_NAMES_WRITTEN_OTHERWISE
4037+ .find(|(html, _)| *html == name)
4038+ .map(|(_, htmlang)| *htmlang);
4039+ let closest = written_otherwise.or_else(|| suggest_closest(name, &all_known));
4040+ let mut message = match (closest, written_otherwise) {
4041+ (Some(closest), Some(_)) => format!(
4042+ "unknown element @{}, did you mean @{}? (@{} writes <{}>)",
4043+ name, closest, closest, name
4045+ (Some(closest), None) => format!("unknown element @{}, did you mean @{}?", name, closest),
4046+ (None, _) => format!("unknown element @{}", name),
4048+ let function = suggest_fn_name(name, ctx);
4049+ if let Some(function) = &function {
4050+ message = format!("{}, or did you mean @{}?", message, function);
4052+ Err(Diagnostic::error(code::UNKNOWN_ELEMENT, line_num, message)
4054+ .suggest(closest.map(str::to_string).or(function)))
1698/// Format include/import stack as a readable chain for error messages.
4057/// Format include/import stack as a readable chain for error messages.
@@ -1763,34 +4122,37 @@ fn suggest_closest<'a>(input: &str, candidates: &[&'a str]) -> Option<&'a str> {
1766−/// Suggest the closest user-defined function name for typos.
4125+/// Suggest the closest user-defined function name for typos, from the
4126+/// functions defined so far and those defined anywhere in the file.
1767fn suggest_fn_name(input: &str, ctx: &ParseContext) -> Option<String> {
4127fn suggest_fn_name(input: &str, ctx: &ParseContext) -> Option<String> {
1768 let input_chars: Vec<char> = input.chars().collect();
4128 let input_chars: Vec<char> = input.chars().collect();
1769 let max_allowed = 2usize.min(input_chars.len().saturating_sub(1));
4129 let max_allowed = 2usize.min(input_chars.len().saturating_sub(1));
1770− let mut best: Option<String> = None;
4130+ let mut best: Option<(usize, &String)> = None;
1771− let mut best_dist = usize::MAX;
4131+ let visible: Vec<&String> = ctx.defined_functions.keys().collect();
1772− for name in ctx.functions.keys() {
4132+ for name in visible.into_iter().chain(ctx.namespace.iter()) {
1773 let nlen = name.chars().count();
4133 let nlen = name.chars().count();
1774 if nlen.abs_diff(input_chars.len()) > max_allowed {
4134 if nlen.abs_diff(input_chars.len()) > max_allowed {
1775 continue;
4135 continue;
1777 let name_chars: Vec<char> = name.chars().collect();
4137 let name_chars: Vec<char> = name.chars().collect();
1778− let dist = levenshtein_bounded(&input_chars, &name_chars, max_allowed);
4138+ let dist = levenshtein_bounded(&input_chars, &name_chars, max_allowed);
1779− if dist < best_dist && dist <= max_allowed {
4139+ if dist <= max_allowed && best.is_none_or(|b| (dist, name) < b) {
1780− best_dist = dist;
4140+ best = Some((dist, name));
1781− best = Some(name.clone());
1784− best
4143+ best.map(|(_, name)| name.clone())
1787/// Suggest the closest variable name for undefined `$var` references.
4146/// Suggest the closest variable name for undefined `$var` references.
1788−fn suggest_var_name(input: &str, vars: &HashMap<String, String>) -> Option<String> {
4147+fn suggest_var_name(input: &str, vars: &[&str]) -> Option<String> {
1789 let input_chars: Vec<char> = input.chars().collect();
4148 let input_chars: Vec<char> = input.chars().collect();
1790 let max_allowed = 2usize.min(input_chars.len().saturating_sub(1));
4149 let max_allowed = 2usize.min(input_chars.len().saturating_sub(1));
1791 let mut best: Option<String> = None;
4150 let mut best: Option<String> = None;
1792 let mut best_dist = usize::MAX;
4151 let mut best_dist = usize::MAX;
1793− for name in vars.keys() {
4152+ let mut vars = vars.to_vec();
4153+ // The same answer every time, whatever the order of the names
4154+ vars.sort_unstable();
1794 let nlen = name.chars().count();
4156 let nlen = name.chars().count();
1795 if nlen.abs_diff(input_chars.len()) > max_allowed {
4157 if nlen.abs_diff(input_chars.len()) > max_allowed {
1796 continue;
4158 continue;
@@ -1799,986 +4161,1988 @@ fn suggest_var_name(input: &str, vars: &HashMap<String, String>) -> Option<Strin
1799 let dist = levenshtein_bounded(&input_chars, &name_chars, max_allowed);
4161 let dist = levenshtein_bounded(&input_chars, &name_chars, max_allowed);
1800 if dist < best_dist && dist <= max_allowed {
4162 if dist < best_dist && dist <= max_allowed {
1801 best_dist = dist;
4163 best_dist = dist;
1802− best = Some(name.clone());
4164+ best = Some(name.to_string());
1808−/// Check for undefined `$var` references and return "did you mean?" diagnostics.
1809−/// `indent` is the line's leading whitespace, which `input` has had trimmed;
1810−/// reported columns and source lines include it.
1811−fn check_undefined_vars(
1813− vars: &HashMap<String, String>,
1816−) -> Vec<Diagnostic> {
1817− let mut warnings = Vec::new();
1818− if !input.contains('$') {
1821− let chars: Vec<char> = input.chars().collect();
1823− while i < chars.len() {
1825− && i + 1 < chars.len()
1826− && (chars[i + 1].is_alphanumeric() || chars[i + 1] == '_' || chars[i + 1] == '-')
1830− let mut end = start;
1831− while end < chars.len()
1832− && (chars[end].is_alphanumeric()
1833− || chars[end] == '-'
1834− || chars[end] == '_'
1835− || chars[end] == '.')
1839− while end > start && chars[end - 1] == '.' {
1842− let name: String = chars[start..end].iter().collect();
1843− if !name.is_empty()
1844− && !vars.contains_key(&name)
1845− && let Some(closest) = suggest_var_name(&name, vars)
1847− warnings.push(Diagnostic {
1849− column: Some(indent + col),
1851− "undefined variable '${}', did you mean '${}'?",
1854− severity: Severity::Warning,
1855− source_line: Some(format!("{}{}", " ".repeat(indent), input)),
1866// ---------------------------------------------------------------------------
4170// ---------------------------------------------------------------------------
1867// Attribute parsing
4171// Attribute parsing
1868// ---------------------------------------------------------------------------
4172// ---------------------------------------------------------------------------
1870−/// Attributes that expect purely numeric values (px-based) or values with CSS units.
4174+/// The quoted strings of a CSS value, without their quotes.
1871−const NUMERIC_ATTRS: &[&str] = &[
4175+fn css_strings(value: &str) -> Vec<&str> {
1872− "spacing",
4176+ let mut strings = Vec::new();
1873− "gap",
4177+ let mut start = None;
1874− "padding",
4178+ let mut escaped = false;
1875− "padding-x",
4179+ for (i, c) in value.char_indices() {
1876− "padding-y",
4180+ match (c, start) {
1877− "padding-top",
4181+ _ if escaped => escaped = false,
1878− "padding-bottom",
4182+ ('\\', Some(_)) => escaped = true,
1879− "padding-left",
4183+ ('"', None) => start = Some(i + 1),
1880− "padding-right",
4184+ ('"', Some(from)) => {
1881− "min-width",
4185+ strings.push(&value[from..i]);
1882− "max-width",
4186+ start = None;
1896−const CSS_UNIT_SUFFIXES: &[&str] = &[
1897− "px", "%", "rem", "em", "vh", "vw", "vmin", "vmax", "dvh", "svh", "lvh", "ch", "ex", "cm",
1898− "mm", "in", "pt", "pc", "fr",
1901−fn has_css_unit(value: &str) -> bool {
1902− CSS_UNIT_SUFFIXES.iter().any(|u| value.ends_with(u))
1903− || value.starts_with("var(")
1904− || value.starts_with("calc(")
1905− || value.starts_with("clamp(")
1906− || value.starts_with("min(")
1907− || value.starts_with("max(")
1910−/// Attributes that accept numeric OR keyword values.
1911−const NUMERIC_OR_KEYWORD_ATTRS: &[&str] = &["width", "height"];
1912−const SIZE_KEYWORDS: &[&str] = &["fill", "shrink"];
1914−fn validate_attr_value(attr: &Attribute, line_num: usize, ctx: &mut ParseContext) {
1915− let base_key = crate::vocab::base_attribute(attr.key.as_str());
1917− if let Some(val) = &attr.value {
1918− if NUMERIC_ATTRS.contains(&base_key) {
1919− // All space-separated parts must be numeric or have a CSS unit
1920− for part in val.split_whitespace() {
1921− if part.parse::<f64>().is_err() && !has_css_unit(part) {
1922− ctx.diagnostics.push(Diagnostic {
1926− "'{}' expects a numeric value (with optional unit), got '{}'",
1929− severity: Severity::Warning,
1935− } else if NUMERIC_OR_KEYWORD_ATTRS.contains(&base_key) {
4188+ _ => {}
1936− let is_keyword = SIZE_KEYWORDS.contains(&val.as_str());
4189+ }
1937− let is_numeric = val.parse::<f64>().is_ok();
4190+ }
1938− let has_unit = has_css_unit(val);
4191+ strings
1939− if !is_keyword && !is_numeric && !has_unit {
4192+}
1940− ctx.diagnostics.push(Diagnostic {
4193+
1941− line: line_num,
4194+/// An `if(...)` in a CSS value that isn't CSS's if(): CSS writes each
1942− column: None,
4195+/// branch `CONDITION: VALUE`, so an if() without a `:` is something else.
1943− message: format!(
4196+/// Quoted CSS strings are text, not calls.
1944− "'{}' expects a number or one of [{}], got '{}'",
4197+fn not_css_if(value: &str) -> Option<&str> {
1945− attr.key,
4198+ let mut quote = None;
1946− SIZE_KEYWORDS.join(", "),
4199+ let mut prev = None;
1947− val
4200+ let mut chars = value.char_indices();
1948− ),
4201+ while let Some((at, c)) = chars.next() {
1949− severity: Severity::Warning,
4202+ match quote {
1950− source_line: None,
4203+ Some(_) if c == '\\' => {
1951− });
4204+ chars.next();
1953− } else if base_key == "opacity" {
4206+ Some(q) if c == q => quote = None,
1954− if let Ok(v) = val.parse::<f64>() {
4207+ Some(_) => {}
1955− if !(0.0..=1.0).contains(&v) {
4208+ None if matches!(c, '"' | '\'') => quote = Some(c),
1956− ctx.diagnostics.push(Diagnostic {
4209+ None => {
1957− line: line_num,
4210+ let word_before =
1958− column: None,
4211+ prev.is_some_and(|p: char| p.is_alphanumeric() || matches!(p, '-' | '_'));
1959− message: format!("'opacity' should be between 0 and 1, got '{}'", val),
4212+ if !word_before && value[at..].starts_with("if(") {
1960− severity: Severity::Warning,
4213+ let mut depth = 0;
1961− source_line: None,
4214+ let close = value[at + 2..].char_indices().find_map(|(i, c)| {
4220+ (depth == 0).then_some(at + 2 + i)
4222+ let end = close.map_or(value.len(), |c| c + 1);
4223+ if !value[at + 3..end].contains(':') {
4224+ return Some(&value[at..end]);
1965− ctx.diagnostics.push(Diagnostic {
1968− message: format!("'opacity' expects a numeric value, got '{}'", val),
1969− severity: Severity::Warning,
1973− } else if base_key == "z-index" {
4228+ }
1974− if val.parse::<i32>().is_err() {
4229+ prev = Some(c);
1975− ctx.diagnostics.push(Diagnostic {
4230+ }
1976− line: line_num,
4231+ None
1977− column: None,
4232+}
1978− message: format!("'z-index' expects an integer, got '{}'", val),
4233+
1979− severity: Severity::Warning,
4234+/// Why a CSS value can't be written into a rule as it is, whatever it
1980− source_line: None,
4235+/// means: a `;` (outside parentheses, where CSS's own `if()` uses it), a
1981− });
4236+/// `{` or a `}` would end the declaration or the rule, and an unclosed
4237+/// quote or parenthesis would run on into the rules after it. Quoted
4238+/// strings are text, and a backslash escapes the character after it, as
4239+/// in CSS. A `</style` anywhere, even in a string, would end the page's
4240+/// `<style>` element and start HTML.
4241+fn css_breakout(value: &str) -> Option<&'static str> {
4242+ if value.to_ascii_lowercase().contains("</style") {
4243+ return Some("a `</style`, which would end the page's style element");
4245+ let mut quote = None;
4246+ let mut depth = 0usize;
4247+ let mut chars = value.chars();
4248+ while let Some(c) = chars.next() {
1983− } else if base_key == "display" {
4253+ (Some(q), c) if c == q => quote = None,
1984− const DISPLAY_VALUES: &[&str] = &[
4254+ (Some(_), _) => {}
1985− "none",
4255+ (None, '"' | '\'') => quote = Some(c),
1986− "block",
4256+ (None, '(') => depth += 1,
1987− "inline",
4257+ (None, ')') if depth == 0 => return Some("a `)` that closes nothing"),
1988− "inline-block",
4258+ (None, ')') => depth -= 1,
1989− "flex",
4259+ (None, ';') if depth == 0 => return Some("a `;`, which would end the declaration"),
1990− "inline-flex",
4260+ (None, '{' | '}') => return Some("a `{` or `}`, which would end the CSS rule"),
1991− "grid",
4261+ _ => {}
1992− "inline-grid",
4262+ }
1994− "table-row",
4264+ match (quote, depth) {
1995− "table-cell",
4265+ (Some('"'), _) => Some("a `\"` that isn't closed"),
1996− "contents",
4266+ (Some(_), _) => Some("a `'` that isn't closed"),
1997− "flow-root",
4267+ (None, 0) => None,
1998− "list-item",
4268+ (None, _) => Some("a `(` that isn't closed"),
2000− if !DISPLAY_VALUES.contains(&val.as_str()) && !val.starts_with("var(") {
4270+}
2001− let suggestion = suggest_closest(val, DISPLAY_VALUES);
4271+
2002− let msg = match suggestion {
4272+/// The hex colors of a CSS value that don't have 3, 4, 6 or 8 hex
2003− Some(s) => format!("unknown display value '{}', did you mean '{}'?", val, s),
4273+/// digits. A `#` word in a CSS value is a color, except inside `url(...)`
2004− None => format!("unknown display value '{}'", val),
4274+/// and quoted strings.
2005− };
4275+fn bad_hex_colors(value: &str) -> Vec<&str> {
2006− ctx.diagnostics.push(Diagnostic {
4276+ let mut bad = Vec::new();
2007− line: line_num,
4277+ let mut quote = None;
2008− column: None,
4278+ let mut in_url = 0usize;
2009− message: msg,
4279+ let mut depth = 0usize;
2010− severity: Severity::Warning,
4280+ let mut chars = value.char_indices().peekable();
2011− source_line: None,
4281+ while let Some((at, c)) = chars.next() {
2012− });
4282+ match (quote, c) {
2014− } else if base_key == "position" {
4286+ (Some(q), c) if c == q => quote = None,
2015− const POSITION_VALUES: &[&str] = &["static", "relative", "absolute", "fixed", "sticky"];
4287+ (Some(_), _) => {}
2016− if !POSITION_VALUES.contains(&val.as_str()) && !val.starts_with("var(") {
4288+ (None, '"' | '\'') => quote = Some(c),
2017− let suggestion = suggest_closest(val, POSITION_VALUES);
4289+ (None, '(') => {
2018− let msg = match suggestion {
4290+ depth += 1;
2019− Some(s) => format!("unknown position value '{}', did you mean '{}'?", val, s),
4291+ if value[..at].ends_with("url") && in_url == 0 {
2020− None => format!("unknown position value '{}'", val),
4292+ in_url = depth;
2022− ctx.diagnostics.push(Diagnostic {
2026− severity: Severity::Warning,
2030− } else if base_key == "overflow" || base_key == "overflow-x" || base_key == "overflow-y" {
4295+ (None, ')') => {
2031− const OVERFLOW_VALUES: &[&str] = &["visible", "hidden", "scroll", "auto", "clip"];
4296+ if in_url == depth {
2032− if !OVERFLOW_VALUES.contains(&val.as_str()) && !val.starts_with("var(") {
4297+ in_url = 0;
2033− let suggestion = suggest_closest(val, OVERFLOW_VALUES);
4298+ }
2034− let msg = match suggestion {
4299+ depth = depth.saturating_sub(1);
2035− Some(s) => format!("unknown overflow value '{}', did you mean '{}'?", val, s),
2036− None => format!("unknown overflow value '{}'", val),
2038− ctx.diagnostics.push(Diagnostic {
2042− severity: Severity::Warning,
2046− } else if base_key == "text-align" {
4301+ (None, '#') if in_url == 0 => {
2047− const TEXT_ALIGN_VALUES: &[&str] =
4302+ let end = value[at + 1..]
2048− &["left", "right", "center", "justify", "start", "end"];
4303+ .find(|c: char| !(c.is_alphanumeric() || c == '-' || c == '_'))
2049− if !TEXT_ALIGN_VALUES.contains(&val.as_str()) && !val.starts_with("var(") {
4304+ .map_or(value.len(), |n| at + 1 + n);
2050− let suggestion = suggest_closest(val, TEXT_ALIGN_VALUES);
4305+ let hex = &value[at + 1..end];
2051− let msg = match suggestion {
4306+ if !(matches!(hex.len(), 3 | 4 | 6 | 8)
2052− Some(s) => format!("unknown text-align value '{}', did you mean '{}'?", val, s),
4307+ && hex.chars().all(|c| c.is_ascii_hexdigit()))
2053− None => format!("unknown text-align value '{}'", val),
4308+ {
2054− };
4309+ bad.push(&value[at..end]);
2055− ctx.diagnostics.push(Diagnostic {
4310+ }
2059− severity: Severity::Warning,
2063− } else if base_key == "cursor" {
4312+ _ => {}
2064− const CURSOR_VALUES: &[&str] = &[
4313+ }
2066− "default",
4315+ bad
2069− "wait",
4318+/// A diagnostic about an attribute, with its column and source line when
2070− "text",
4319+/// it is on the line being evaluated.
2071− "move",
4320+fn at_attribute(diagnostic: Diagnostic, column: Option<usize>, ctx: &ParseContext) -> Diagnostic {
2072− "not-allowed",
4321+ match (&ctx.current_source, column) {
2073− "crosshair",
4322+ ((current, Some(text)), Some(column)) if *current == diagnostic.line => {
2074− "grab",
4323+ diagnostic.column(column).source(text.clone())
2076− "help",
4325+ _ => diagnostic,
2078− "col-resize",
4327+}
2080− "n-resize",
4329+/// Check a style's value. Values go to the CSS as written, so only what
2081− "s-resize",
4330+/// can't be wrong in any CSS is checked: a value that would break out of
2082− "e-resize",
4331+/// its rule is an error (and it is left out); a hex color without 3, 4, 6
2083− "w-resize",
4332+/// or 8 digits, an `if()` that isn't CSS's and a quoted font stack are
2084− "zoom-in",
4333+/// warnings. Returns whether the value can be written.
2085− "zoom-out",
4334+fn check_css_value(
2086− "context-menu",
4335+ attr: &Attribute,
2087− "cell",
4336+ base: &str,
2088− "copy",
4337+ line: usize,
2089− "alias",
4338+ column: Option<usize>,
2090− "no-drop",
4339+ ctx: &mut ParseContext,
2092− if !CURSOR_VALUES.contains(&val.as_str())
4341+ let Some(value) = &attr.value else {
2093− && !val.starts_with("url(")
4342+ return true;
2094− && !val.starts_with("var(")
4343+ };
4344+ if let Some(reason) = css_breakout(value) {
4345+ let diagnostic = Diagnostic::error(
4346+ code::INVALID_VALUE,
4349+ "the value of '{}' has {}: `{}` can't be written into the page's CSS",
4350+ attr.key, reason, value
4353+ .subject(value.as_str());
4354+ ctx.diagnostics.push(at_attribute(diagnostic, column, ctx));
4357+ if crate::vocab::is_custom_property(base) {
4361+ let warn = |ctx: &mut ParseContext, diagnostic: Diagnostic| {
4362+ let diagnostic = at_attribute(diagnostic, column, ctx);
4363+ ctx.diagnostics.push(diagnostic);
4365+ // In CSS, a quoted font-family is one family, commas and all
4366+ if base == "font-family"
4367+ && let Some(family) = css_strings(value).into_iter().find(|s| s.contains(','))
4372+ .collect::<Vec<_>>()
4376+ Diagnostic::warning(
4377+ code::INVALID_VALUE,
4380+ "font-family \"{}\" is one family, whose name has a comma in it: \
4381+ for a font stack, write `font-family {}`",
4385+ .subject(format!("\"{}\"", family))
4386+ .suggest(Some(stack)),
4389+ if let Some(call) = not_css_if(value) {
4392+ Diagnostic::warning(
4393+ code::INVALID_VALUE,
4396+ "'{}' is not CSS's if(), whose branches are written \
4397+ `if(CONDITION: VALUE; else: VALUE)`",
4404+ for color in bad_hex_colors(value) {
4407+ Diagnostic::warning(
4408+ code::INVALID_COLOR,
4411+ "invalid hex color '{}': a hex color has 3, 4, 6 or 8 hex digits",
4421+/// An unknown prefix: the message, the text it is about, and what to write
4422+/// instead, when something is close enough.
4423+struct PrefixProblem {
4426+ suggestion: Option<String>,
4429+/// What is wrong with the prefix `rest` starts with, when the known
4430+/// prefixes are already split off it and what is left still starts with
4431+/// one: a word and a `:` (`hovr:`), or a word and a parenthesised argument
4432+/// and a `:` (`nth-chld(2):`). Selector prefixes are CSS's pseudo-classes
4433+/// and pseudo-elements under their CSS names, so an unknown one gets the
4434+/// closest name as a suggestion. Only names with the same first letter are
4435+/// suggested: `odd:` is two edits from `md:`, which it doesn't mean.
4436+fn unknown_prefix(rest: &str) -> Option<PrefixProblem> {
4437+ use crate::vocab::{self, Pseudo};
4438+ let name_len = rest.find(|c: char| !(c.is_ascii_alphanumeric() || c == '-'))?;
4439+ let name = &rest[..name_len];
4440+ if name.is_empty() {
4443+ if rest[name_len..].starts_with('(') {
4444+ // `name(...):`: a pseudo-class with an argument
4445+ let close = vocab::closing_paren(rest, name_len)?;
4446+ if !rest[close + 1..].starts_with(':') {
4449+ let written = &rest[..close + 2];
4450+ if matches!(vocab::pseudo(name), Some(Pseudo::Class | Pseudo::Element)) {
4451+ let bare = format!("{}:", name);
4452+ return Some(PrefixProblem {
4454+ "'{}': `{}` takes no argument: write `{}`",
4456+ vocab::pseudo_selector(&bare).unwrap_or_default(),
4459+ subject: written.to_string(),
4460+ suggestion: Some(bare),
4463+ let functional: Vec<&str> = vocab::functional_pseudos()
4465+ .filter(|p| p.chars().next() == name.chars().next())
4467+ let suggestion = suggest_closest(name, &functional)
4468+ .filter(|&closest| closest != name)
4469+ .map(|closest| format!("{}(", closest));
4470+ let written = format!("{}(", name);
4471+ let message = match &suggestion {
4472+ Some(closest) => format!("unknown prefix '{}', did you mean '{}'?", written, closest),
4473+ None => format!("unknown prefix '{}'", written),
4475+ return Some(PrefixProblem {
4481+ if !rest[name_len..].starts_with(':') {
4484+ let written = &rest[..name_len + 1];
4485+ // `has:`: its argument is missing
4486+ if vocab::pseudo(name) == Some(Pseudo::Function) {
4487+ return Some(PrefixProblem {
4489+ "'{}': `:{}()` takes an argument, in parentheses, as in CSS: `{}(...):`",
4490+ written, name, name
4492+ subject: written.to_string(),
4496+ let prefixes = vocab::all_prefixes();
4497+ let candidates: Vec<&str> = prefixes
4499+ .map(String::as_str)
4500+ .filter(|p| p.chars().next() == written.chars().next())
4502+ // The closest name that starts with the same letter (`hvoer:` →
4503+ // `hover:`), else the first that starts with the word written and a `-`
4504+ // (`first:` → `first-child:`)
4505+ let suggestion = suggest_closest(written, &candidates)
4507+ let longer = format!("{}-", name);
4508+ candidates.iter().copied().find(|p| p.starts_with(&longer))
4510+ .filter(|&closest| closest != written)
4511+ .map(str::to_string);
4512+ let message = match &suggestion {
4513+ Some(closest) => format!("unknown prefix '{}', did you mean '{}'?", written, closest),
4514+ None => format!("unknown prefix '{}'", written),
4516+ Some(PrefixProblem {
4518+ subject: written.to_string(),
4523+/// Check an attribute's element prefix (`@td:padding 8`), when it has one:
4524+/// it names a built-in element that has an HTML tag of its own (not a
4525+/// function, and not `@el`, whose `<div>` other elements write too), there
4526+/// is one, not with `children:`, and what it styles is a CSS property, not
4527+/// one of htmlang's words, which compile against each element's layout and
4528+/// its parent's. Returns false, after reporting, when the attribute can't
4530+fn check_element_prefixes(
4535+ column: Option<usize>,
4536+ ctx: &mut ParseContext,
4538+ use crate::ast::ElementKind;
4540+ let elements: Vec<&str> = prefixes
4543+ .filter(|p| vocab::element_prefix(p).is_some())
4545+ let Some(&prefix) = elements.first() else {
4548+ let fail = |ctx: &mut ParseContext,
4549+ code: &'static str,
4552+ suggestion: Option<String>| {
4553+ let diagnostic = Diagnostic::error(code, line, message)
4555+ .suggest(suggestion);
4556+ let diagnostic = at_attribute(diagnostic, column, ctx);
4557+ ctx.diagnostics.push(diagnostic);
4560+ let name = vocab::element_prefix(prefix).unwrap_or_default();
4561+ if is_function(name, ctx) {
4564+ code::INVALID_PREFIX,
4566+ "'{}': @{} is a function, and `{}` would pick elements out by their HTML tag, \
4567+ which a function doesn't have: style what @{} writes in its body, or pass it \
4569+ attr.key, name, prefix, name
4575+ match ElementKind::from_name(name) {
4577+ let own: Vec<&str> = ElementKind::all_names()
4578+ .filter(|n| ElementKind::from_name(n).is_some_and(|k| k.own_tag().is_some()))
4580+ // An HTML name htmlang writes under another (`@a:` is `@link:`)
4581+ let (written_otherwise, shared) = match crate::ast::HTML_NAMES_WRITTEN_OTHERWISE
4583+ .find(|(html, _)| *html == name)
2096− let suggestion = suggest_closest(val, CURSOR_VALUES);
4585+ Some((_, htmlang)) if own.contains(htmlang) => (Some(*htmlang), false),
2097− let msg = match suggestion {
4586+ Some(_) => (None, true),
2098− Some(s) => format!("unknown cursor value '{}', did you mean '{}'?", val, s),
4587+ None => (None, false),
2099− None => format!("unknown cursor value '{}'", val),
4588+ };
2100− };
4589+ // `@each:`, `@markdown:`: a directive, which is no element
2101− ctx.diagnostics.push(Diagnostic {
4590+ if crate::ast::directive(name).is_some() {
2102− line: line_num,
4591+ return fail(
2103− column: None,
4592+ ctx,
2104− message: msg,
4593+ code::UNKNOWN_PREFIX,
2105− severity: Severity::Warning,
4594+ format!(
2106− source_line: None,
4595+ "unknown element @{} in '{}': @{} is a directive, and an element \
2107− });
4596+ prefix names an element with an HTML tag of its own, such as `@td:`",
2109− } else if base_key == "font-weight" {
4603+ // `@div:`, `@span:`: several elements write it
2110− const WEIGHT_VALUES: &[&str] = &[
4604+ if shared {
2111− "normal", "bold", "bolder", "lighter", "100", "200", "300", "400", "500", "600",
4605+ return fail(
2112− "700", "800", "900",
4606+ ctx,
2113− ];
4607+ code::UNKNOWN_PREFIX,
2114− if !WEIGHT_VALUES.contains(&val.as_str()) && !val.starts_with("var(") {
4608+ format!(
2115− ctx.diagnostics.push(Diagnostic {
4609+ "unknown element @{} in '{}': htmlang writes <{}> for several \
2116− line: line_num,
4610+ elements, so no element prefix picks it out",
2117− column: None,
4611+ name, prefix, name
2119− "'font-weight' expects a weight keyword or number 100-900, got '{}'",
2122− severity: Severity::Warning,
4613+ prefix,
2123− source_line: None,
4614+ None,
2126− } else if base_key == "color" || base_key == "background" {
4617+ // A name with the same first letter first (`@tdd:` is `@td:`)
2127− // Validate named CSS colors (only if not hex, rgb, hsl, var, etc.)
4618+ let same_letter: Vec<&str> = own
2128− if !val.starts_with('#')
4619+ .iter()
2129− && !val.starts_with("rgb")
4620+ .copied()
2130− && !val.starts_with("hsl")
4621+ .filter(|n| n.chars().next() == name.chars().next())
2131− && !val.starts_with("var(")
4622+ .collect();
2132− && !val.starts_with("linear-gradient")
4623+ let closest = written_otherwise
2133− && !val.starts_with("radial-gradient")
4624+ .or_else(|| suggest_closest(name, &same_letter))
2134− && !val.starts_with("conic-gradient")
4625+ .or_else(|| suggest_closest(name, &own));
2135− && !val.starts_with("oklch")
4626+ let message = match (closest, written_otherwise) {
2136− && !val.starts_with("oklab")
4627+ (Some(closest), Some(_)) => format!(
2137− && !val.starts_with("color(")
4628+ "unknown element @{} in '{}', did you mean '@{}:'? (@{} writes <{}>)",
2138− && !val.starts_with("light-dark(")
4629+ name, prefix, closest, closest, name
2139− && !val.contains("url(")
4630+ ),
2140− && !val.contains(' ')
4631+ (Some(closest), None) => format!(
2141− // skip shorthand multi-value
4632+ "unknown element @{} in '{}', did you mean '@{}:'?",
2142− {
4633+ name, prefix, closest
2143− const NAMED_COLORS: &[&str] = &[
4634+ ),
2144− "transparent",
4635+ (None, _) => format!("unknown element @{} in '{}'", name, prefix),
2145− "currentcolor",
4636+ };
2146− "inherit",
4637+ let suggestion = closest.map(|c| format!("@{}:", c));
2147− "initial",
4638+ fail(ctx, code::UNKNOWN_PREFIX, message, prefix, suggestion)
2149− "black",
4640+ Some(kind) if kind.own_tag().is_none() => {
2150− "white",
4641+ let reason = match kind.tag() {
2151− "red",
4642+ None => format!(
2152− "green",
4643+ "@{} writes no element of its own, so there is nothing for `{}` to style",
2153− "blue",
4644+ name, prefix
2155− "orange",
4646+ Some(_) if kind.is_verbatim() => {
2156− "purple",
4647+ format!("@{} isn't shown, so there is nothing to style", name)
2158− "brown",
4649+ Some("span") => format!(
2159− "gray",
4650+ "@{} writes a <span>, as every line of text in a row or column does, so \
2160− "grey",
4651+ `{}` can't pick it out",
2161− "cyan",
4652+ name, prefix
2163− "lime",
4654+ Some(tag) => {
2164− "olive",
4655+ let others: Vec<String> = ElementKind::all_names()
2165− "navy",
4656+ .filter(|n| {
2166− "teal",
4657+ *n != name
2167− "aqua",
4658+ && ElementKind::from_name(n).and_then(|k| k.tag()) == Some(tag)
2169− "maroon",
4660+ .map(|n| format!("@{}", n))
2170− "silver",
4661+ .collect();
2171− "coral",
4662+ let others = match others.split_last() {
2172− "salmon",
4663+ Some((last, [])) => last.clone(),
2173− "tomato",
4664+ Some((last, rest)) => format!("{} and {}", rest.join(", "), last),
2174− "crimson",
4665+ None => String::new(),
2212− if !NAMED_COLORS.contains(&val.to_lowercase().as_str()) {
2213− let lower = val.to_lowercase();
2214− let suggestion = suggest_closest(&lower, NAMED_COLORS);
2215− let msg = match suggestion {
2216− Some(s) => format!("unknown color '{}', did you mean '{}'?", val, s),
2217− None => format!("unknown color '{}'", val),
2219− ctx.diagnostics.push(Diagnostic {
4667+ format!(
2220− line: line_num,
4668+ "@{} writes a <{}>, as {} do, so `{}` can't pick it out",
2221− column: None,
4669+ name, tag, others, prefix
2222− message: msg,
4670+ )
2223− severity: Severity::Warning,
4675+ code::INVALID_PREFIX,
4677+ "'{}': {}. Give those elements their styles themselves, or a bundle \
4678+ (`@let name [...]`, used as `[$name]`)",
4685+ Some(_) if elements.len() > 1 => fail(
4687+ code::INVALID_PREFIX,
4689+ "'{}': a style takes one element prefix, which styles every such element \
4690+ inside this one, at any depth",
4696+ Some(_) if prefixes.contains(&vocab::CHILDREN) => fail(
4698+ code::INVALID_PREFIX,
4700+ "'{}': `children:` and `{}` each say which elements the style is for: write \
4707+ Some(_) if vocab::is_htmlang_word(base, attr.value.as_deref()) => {
4708+ let value = attr.value.as_deref().map(str::trim);
4709+ let css = match (base, value) {
4710+ ("spacing", _) => " (`gap`)",
4711+ ("wrap", _) => " (`flex-wrap wrap`)",
4712+ ("grid-cols", _) => " (`grid-template-columns`)",
4713+ ("grid-rows", _) => " (`grid-template-rows`)",
4714+ ("col-span", _) => " (`grid-column span N`)",
4715+ ("row-span", _) => " (`grid-row span N`)",
4716+ ("width", Some("fill")) => " (`flex 1` in a row, `width 100%` otherwise)",
4717+ ("height", Some("fill")) => " (`flex 1` in a column, `height 100%` otherwise)",
4718+ ("width", _) => " (`flex-shrink 0` in a row, `width fit-content` otherwise)",
4719+ ("height", _) => " (`flex-shrink 0` in a column, `height fit-content` otherwise)",
4720+ ("center-x", _) => " (`margin-inline auto`)",
4721+ ("center-y", _) => " (`margin-block auto`)",
4724+ let word = match value {
4725+ Some(v) if matches!(base, "width" | "height") => format!("{} {}", base, v),
4726+ _ => base.to_string(),
4730+ code::INVALID_PREFIX,
4732+ "'{}': `{}` is one of htmlang's layout words, which compile against each \
4733+ element's layout and its parent's, and `{}` styles elements whose \
4734+ parents it doesn't know: write `{}` on the elements themselves, or the \
4736+ attr.key, word, prefix, word, css
2232−fn parse_attr_brackets(
4746+/// Check an attribute's prefixes: each is known, their selector prefixes
2233− input: &str,
4747+/// read left to right with a pseudo-element (`before:`) last, the argument
2234− line_num: usize,
4748+/// of `has(...)` or `nth-child(...)` can be written into the CSS, and a word that
4749+/// places an element in its parent (`width fill`, `center-x`, `align-*`)
4750+/// isn't under `children:`, whose styles go on the children. Media,
4751+/// container and width prefixes go anywhere. Returns false, after
4752+/// reporting, when the attribute can't be written.
4756+ column: Option<usize>,
2235 ctx: &mut ParseContext,
4757 ctx: &mut ParseContext,
2236−) -> Result<(Vec<Attribute>, String), ParseError> {
4758+) -> bool {
2237− parse_attr_brackets_inner(input, line_num, ctx, true)
4759+ use crate::vocab;
2238−}
4760+ let (prefixes, base) = vocab::split_prefixes(&attr.key);
4762+ |ctx: &mut ParseContext, message: String, subject: &str, suggestion: Option<String>| {
4763+ let diagnostic = Diagnostic::error(code::INVALID_PREFIX, line, message)
4765+ .suggest(suggestion);
4766+ let diagnostic = at_attribute(diagnostic, column, ctx);
4767+ ctx.diagnostics.push(diagnostic);
2240−fn parse_attr_brackets_no_validate(
4771+ if let Some(problem) = unknown_prefix(base) {
2241− input: &str,
4772+ let diagnostic = Diagnostic::error(code::UNKNOWN_PREFIX, line, problem.message)
2242− line_num: usize,
4773+ .subject(problem.subject)
2243− ctx: &mut ParseContext,
4774+ .suggest(problem.suggestion);
2244−) -> Result<(Vec<Attribute>, String), ParseError> {
4775+ let diagnostic = at_attribute(diagnostic, column, ctx);
2245− parse_attr_brackets_inner(input, line_num, ctx, false)
4776+ ctx.diagnostics.push(diagnostic);
4779+ if !check_element_prefixes(attr, &prefixes, base, line, column, ctx) {
4782+ // The argument of `has(...)` or `nth-child(...)` goes into the CSS as
4784+ for prefix in &prefixes {
4785+ if let Some(reason) = css_breakout(prefix.trim_end_matches(':')) {
4789+ "the prefix '{}' has {}: it can't be written into the page's CSS",
4797+ // `nth-child():` or `has( ):`: CSS has no pseudo-class with an empty
4799+ let empty_argument = |prefix: &str| {
4801+ .strip_suffix("):")
4802+ .and_then(|p| p.split_once('('))
4803+ .is_some_and(|(_, argument)| argument.trim().is_empty())
4805+ if let Some(empty) = prefixes.iter().find(|p| empty_argument(p)) {
4809+ "'{}': `:{}()` takes an argument between its parentheses, as in CSS",
4811+ vocab::pseudo_name(empty)
4817+ // A pseudo-element is the last selector prefix: CSS has no
4818+ // `::before:hover`
4819+ let selectors: Vec<&str> = prefixes
4822+ .filter(|p| vocab::at_rule_rank(p).is_none())
4824+ // Only one: an element has one `::before`, which has no `::after`
4825+ let elements: Vec<&str> = selectors
4828+ .filter(|p| vocab::is_pseudo_element(p))
4830+ if elements.len() > 1 {
4834+ "'{}': `{}` and `{}` each select a pseudo-element, and a style applies to one \
4836+ attr.key, elements[0], elements[1]
4842+ if let Some(at) = selectors.iter().position(|p| vocab::is_pseudo_element(p))
4843+ && at + 1 < selectors.len()
4845+ let element = selectors[at];
4846+ // The same prefixes, with the pseudo-element moved after the other
4847+ // selector prefixes
4848+ let mut order: Vec<&str> = prefixes.iter().copied().filter(|p| *p != element).collect();
4849+ let last_selector = order
4851+ .rposition(|p| vocab::at_rule_rank(p).is_none())
4852+ .map_or(order.len(), |i| i + 1);
4853+ order.insert(last_selector, element);
4854+ let fixed = format!("{}{}", order.concat(), base);
4858+ "'{}': `{}` selects a pseudo-element, which comes after the other selector \
4859+ prefixes, as in CSS: write `{}`",
4860+ attr.key, element, fixed
4866+ // Under `children:` the styles go on the children, whose parent is this
4867+ // element: a word that places an element in its parent can't say where
4868+ if prefixes.contains(&"children:") && vocab::places_in_parent(base, attr.value.as_deref()) {
4869+ // The CSS of `fill` and `shrink` depends on the direction: along
4870+ // it, they are flex properties
4871+ let (word, css) = match (base, attr.value.as_deref().map(str::trim)) {
4872+ ("width", Some("fill")) => (
4874+ " (`children:flex 1` in a row, `children:width 100%` otherwise)",
4876+ ("height", Some("fill")) => (
4878+ " (`children:flex 1` in a column, `children:height 100%` otherwise)",
4880+ ("width", Some(_)) => (
4882+ " (`children:flex-shrink 0` in a row, `children:width fit-content` otherwise)",
4884+ ("height", Some(_)) => (
4886+ " (`children:flex-shrink 0` in a column, `children:height fit-content` \
4894+ "'{}{}': `{}` places an element in its parent, and under `children:` that \
4895+ parent is this element: write `{}` on the children themselves, or the CSS \
4900+ .map_or(String::new(), |v| format!(" {}", v.trim())),
2248−fn parse_attr_brackets_inner(
4912+/// Check an attribute written as a style or a flag (not `key=value`): its
2249− input: &str,
4913+/// prefix, its name, and, for a style, its value. A name htmlang doesn't
2250− line_num: usize,
4914+/// know but CSS could have (`corner-shape`) is passed to the CSS as written,
4915+/// with a warning; custom properties (`--brand`) and vendor-prefixed ones
4916+/// (`-webkit-...`) without one. Anything that can't be written into the
4917+/// page is an error; returns false then, and the attribute is left out.
4921+ column: Option<usize>,
4922+ before: Option<&Attribute>,
2251 ctx: &mut ParseContext,
4923 ctx: &mut ParseContext,
2252− validate: bool,
4924+) -> bool {
2253−) -> Result<(Vec<Attribute>, String), ParseError> {
4925+ use crate::vocab;
2254− let mut depth = 0;
4926+ let (prefixes, base) = vocab::split_prefixes(&attr.key);
2255− let mut end_pos = 0;
4927+ let fail = |ctx: &mut ParseContext, code: &'static str, message: String, subject: &str| {
4928+ let diagnostic = Diagnostic::error(code, line, message).subject(subject);
4929+ let diagnostic = at_attribute(diagnostic, column, ctx);
4930+ ctx.diagnostics.push(diagnostic);
2257− for (i, c) in input.char_indices() {
4934+ if !check_prefixes(attr, line, column, ctx) {
2258− match c {
4935+ return false;
2259− '[' => depth += 1,
4936+ }
2260− ']' => {
4937+ let prefixed = !prefixes.is_empty();
2261− depth -= 1;
4938+ // `md:id=x`: `=` makes an HTML attribute, which has no states
2262− if depth == 0 {
4939+ if prefixed && let Some((name, _)) = base.split_once('=') {
2263− end_pos = i;
4940+ return fail(
2265− }
4942+ code::INVALID_PREFIX,
4944+ "'{}': a prefix applies to a style, and `{}=` is an HTML attribute",
4950+ let Some(value) = &attr.value else {
4951+ // `inline` puts a file into the page as it compiles, which no
4952+ // state or media condition can undo
4953+ if base == "inline" && prefixed {
4956+ code::INVALID_PREFIX,
4958+ "'{}': `inline` puts the image's file into the page, which can't depend \
4965+ if vocab::HTMLANG_FLAGS.contains(&base) {
4968+ if vocab::is_html_flag(base) {
2267− _ => {}
4972+ return fail(
4974+ code::INVALID_PREFIX,
4976+ "'{}': a prefix applies to a style, and '{}' is an HTML attribute",
2269− }
4982+ if vocab::is_style_attribute(base)
4983+ || vocab::is_custom_property(base)
4984+ || vocab::is_vendor_property(base)
4988+ code::MISSING_VALUE,
4989+ format!("'{}' needs a value: `{} VALUE`", attr.key, attr.key),
4993+ if vocab::is_html_attribute(base) && !prefixed {
4996+ code::HTML_ATTRIBUTE_FORM,
4998+ "'{}' is an HTML attribute that isn't a flag: write `{}=VALUE`",
5004+ return unknown_attribute(attr, base, line, column, before, true, ctx);
2271− if depth != 0 {
5007+ if vocab::HTMLANG_FLAGS.contains(&base) {
2272− return Err(ParseError {
5008+ return fail(
2273− line: line_num,
5009+ ctx,
2274− message: "unclosed '[' in attribute list".to_string(),
5010+ code::INVALID_VALUE,
5012+ "'{}' is a flag and takes no value: write `{}` alone",
5018+ if vocab::is_style_attribute(base)
5019+ || vocab::is_custom_property(base)
5020+ || vocab::is_vendor_property(base)
5022+ return check_css_value(attr, base, line, column, ctx);
5024+ if vocab::is_html_attribute(base) && !prefixed {
5025+ let diagnostic = Diagnostic::error(
5026+ code::HTML_ATTRIBUTE_FORM,
5029+ "'{}' is an HTML attribute: write `{}={}`",
5030+ attr.key, attr.key, value
5033+ .subject(attr.key.as_str());
5034+ let diagnostic = at_attribute(diagnostic, column, ctx);
5035+ ctx.diagnostics.push(diagnostic);
5038+ let passes = vocab::is_property_name(base);
5039+ unknown_attribute(attr, base, line, column, before, !passes, ctx)
5040+ && check_css_value(attr, base, line, column, ctx)
2278− let attrs_inner = &input[1..end_pos];
5043+/// Whether an attribute of a bundle could pass a parameter to a function
2279− let remaining = input[end_pos + 1..].trim().to_string();
5044+/// it is spliced into (`@let t [title Hello]`): a name without a prefix
2280− let attrs = parse_attr_list(attrs_inner, line_num, ctx, validate);
5045+/// that isn't a style or a flag. Such a name is checked where the bundle is
5047+fn could_be_parameter(attr: &Attribute) -> bool {
5049+ let key = attr.key.as_str();
5051+ attr.value.is_none() && (vocab::HTMLANG_FLAGS.contains(&key) || vocab::is_html_flag(key));
5054+ && !vocab::is_style_attribute(key)
5055+ && key.starts_with(|c: char| c.is_alphabetic())
5058+ .all(|c| c.is_alphanumeric() || matches!(c, '-' | '_'))
2282− Ok((attrs, remaining))
5061+/// At a call, a name close to one of the function's parameters is a
5062+/// misspelled parameter, not an attribute for its root: report it, and
5063+/// return true (it is left out).
5064+fn misspelled_parameter(
5066+ text_keys: &[String],
5068+ column: Option<usize>,
5069+ ctx: &mut ParseContext,
5071+ if text_keys.is_empty() || !could_be_parameter(attr) {
5074+ let params: Vec<&str> = text_keys.iter().map(String::as_str).collect();
5075+ let Some(closest) = suggest_closest(&attr.key, ¶ms) else {
5078+ let what = if ctx.in_page {
5083+ let diagnostic = Diagnostic::error(
5084+ code::UNKNOWN_ATTRIBUTE,
5087+ "unknown {} '{}', did you mean '{}'?",
5088+ what, attr.key, closest
5091+ .subject(attr.key.as_str())
5092+ .suggest(Some(closest));
5093+ let diagnostic = at_attribute(diagnostic, column, ctx);
5094+ ctx.diagnostics.push(diagnostic);
2285−fn is_valid_hex_color(s: &str) -> bool {
5098+/// An attribute name htmlang doesn't know. A style whose name CSS could
2286− if !s.starts_with('#') {
5099+/// have goes to the CSS as written, with a warning; anything else (a flag,
2287− return true; // Not a hex color, skip
5100+/// a name that isn't a word) is an error. Returns whether it is kept.
5101+fn unknown_attribute(
5105+ column: Option<usize>,
5106+ before: Option<&Attribute>,
5108+ ctx: &mut ParseContext,
5110+ // `@td padding 8`: an element prefix without its colon
5111+ if let Some(name) = base.strip_prefix('@')
5112+ && crate::ast::ElementKind::from_name(name).is_some()
5114+ let example = match attr.value.as_deref() {
5115+ Some(value) => format!("{}:{}", attr.key, value.trim()),
5116+ None => format!("{}:padding 8", attr.key),
5118+ let diagnostic = Diagnostic::error(
5119+ code::UNKNOWN_ATTRIBUTE,
5122+ "unknown attribute '{}': an element prefix ends in a colon, as in `{}`",
5127+ let diagnostic = at_attribute(diagnostic, column, ctx);
5128+ ctx.diagnostics.push(diagnostic);
2289− let hex = &s[1..];
5131+ // `[card]` where `card` is a bundle: it is used as `$card`
2290− matches!(hex.len(), 3 | 4 | 6 | 8) && hex.chars().all(|c| c.is_ascii_hexdigit())
5132+ if attr.value.is_none() && ctx.env.bundle(base).is_some() && base == attr.key {
5133+ ctx.used_defines.insert(base.to_string());
5134+ let diagnostic = Diagnostic::error(
5135+ code::UNKNOWN_ATTRIBUTE,
5138+ "unknown attribute '{}': '{}' is an attribute bundle, used as `${}`",
5143+ .suggest(Some(format!("${}", base)));
5144+ let diagnostic = at_attribute(diagnostic, column, ctx);
5145+ ctx.diagnostics.push(diagnostic);
5148+ // `hover:title x`: an HTML attribute's name is not a suggestion for
5151+ suggest_closest(base, &crate::vocab::all_attributes()).filter(|&closest| closest != base);
5152+ // `hx-trigger=load, every 2s`: right after a `key=value`, a name that
5153+ // isn't close to one htmlang knows is the rest of that value, which
5154+ // the comma ended. It is left out.
5155+ let cut = before.filter(|b| b.html && b.value.is_some());
5156+ let rest = match &attr.value {
5157+ Some(value) => format!("{} {}", attr.key, value),
5158+ None => attr.key.clone(),
5160+ let joined = cut.map(|cut| {
5161+ let value = cut.value.as_deref().unwrap_or("");
5163+ format!("{}={}", cut.key, value),
5164+ format!("{}={}\\, {}", cut.key, value, rest),
5167+ if let (Some((cut, joined)), None) = (&joined, suggestion) {
5168+ let diagnostic = Diagnostic::error(
5172+ "unknown attribute '{}' after `{}`: if '{}' is the rest of its value, the comma \
5173+ ended it. To keep a comma in a value, write `\\,`: `{}`",
5174+ base, cut, rest, joined
5178+ let diagnostic = at_attribute(diagnostic, column, ctx);
5179+ ctx.diagnostics.push(diagnostic);
5182+ let mut message = match (&suggestion, error) {
5183+ (Some(closest), true) => {
5185+ "unknown attribute '{}', did you mean '{}'?",
5189+ (None, true) => format!("unknown attribute '{}'", attr.key),
5190+ (Some(closest), false) => format!(
5191+ "unknown CSS property '{}', did you mean '{}'? It is written to the CSS as it is",
5194+ (None, false) => format!(
5195+ "unknown CSS property '{}': it is written to the CSS as it is",
5199+ // `box-shadow 0 1px red, 0 2px blue` or `font-family Inter,
5200+ // sans-serif`: the comma ended the attribute, and the rest of the
5201+ // value became one
5202+ let rest_of_a_value = !base.starts_with(|c: char| c.is_ascii_alphabetic() || c == '-')
5203+ || (suggestion.is_none() && attr.value.is_none() && before.is_some());
5204+ if joined.is_some() || (rest_of_a_value && error) {
5205+ if !message.ends_with('?') {
5209+ Some((cut, joined)) => message.push_str(&format!(
5210+ " If it is the rest of `{}`, the comma ended it: write `{}`",
5214+ .push_str(" A comma separates attributes: to keep one in a value, write `\\,`"),
5217+ let severity = if error {
5222+ let diagnostic = Diagnostic::new(code::UNKNOWN_ATTRIBUTE, severity, line, message)
5224+ .suggest(suggestion);
5225+ let diagnostic = at_attribute(diagnostic, column, ctx);
5226+ ctx.diagnostics.push(diagnostic);
5230+/// Evaluate the attributes of a list: bundles are spliced in, `if()`
5231+/// chooses, and variables fill values. A variable fills only the value it
5232+/// is written in: attributes come from bundles, never from text. With
5233+/// `validate`, unknown names and invalid values are reported. `text_keys`
5234+/// are a called function's parameters: their values are text rather than
5235+/// CSS, and they aren't checked as attributes.
2293fn parse_attr_list(
5236fn parse_attr_list(
2294− input: &str,
5237+ tokens: &[syntax::Attr],
2295 line_num: usize,
5238 line_num: usize,
2296 ctx: &mut ParseContext,
5239 ctx: &mut ParseContext,
2297 validate: bool,
5240 validate: bool,
5241+ text_keys: &[String],
2298) -> Vec<Attribute> {
5242) -> Vec<Attribute> {
2299− let mut attrs = Vec::new();
5243+ parse_attrs(tokens, line_num, ctx, validate, text_keys)
2300− let mut seen_keys: Vec<String> = Vec::new();
5244+ .into_iter()
2301−
5245+ .map(|(attr, _)| attr)
2302− for part in split_commas(input) {
5246+ .collect()
2303− let part = part.trim();
5247+}
2304− // A whole attribute `if(cond, a, b)` is the chosen branch's text.
5248+
2305− let chosen;
5249+/// [`parse_attr_list`], with the value of each attribute whose key is one
2306− let part = match choose_if(part, ctx, line_num) {
5250+/// of `text_keys` (a call's parameters) as a value with its type (see
2307− Some(branch) => {
5251+/// [`ParseContext::slot_value`]), so a parameter can get a list or a
2308− chosen = branch;
5252+/// record.
2309− chosen.as_str()
5253+fn parse_attrs(
2310− }
5254+ tokens: &[syntax::Attr],
2311− None => part,
5255+ line_num: usize,
5256+ ctx: &mut ParseContext,
5258+ text_keys: &[String],
5259+) -> Vec<(Attribute, Option<Value>)> {
5260+ let mut read = ReadAttrs::default();
5261+ read_attrs(tokens, "", line_num, ctx, validate, text_keys, &mut read);
5265+/// The attributes of a list read so far, and the keys written (for the
5266+/// duplicate check).
5269+ attrs: Vec<(Attribute, Option<Value>)>,
5270+ seen_keys: Vec<(String, bool)>,
5273+/// [`parse_attrs`] for the attributes of `tokens`, each under the prefixes
5274+/// `prefix` (`md:` for those of `md:[...]`), which distribute over a
5275+/// group, a bundle and the branch an `if()` takes. Only styles take a
5276+/// prefix, so an HTML attribute there is an error.
5278+ tokens: &[syntax::Attr],
5281+ ctx: &mut ParseContext,
5283+ text_keys: &[String],
5284+ out: &mut ReadAttrs,
5286+ let mut chosen = Vec::new();
5297+ for token in &chosen {
5298+ let line = if token.span.line == 0 {
2313− if part.is_empty() {
5303+ let (key, value, html) = (token.key.clone(), token.value.clone(), token.html);
5304+ let column = |at: usize| Some(token.span.column + at);
5306+ // `md:[...]`, `md:$card`, `md:if(...)`: the prefixes apply to each
5307+ // attribute there, and a prefix a parameter can't have
5308+ if let Some(prefixed) = &token.prefixed {
5309+ if let Some(inner) = group_prefix(token, prefixed, prefix, line, ctx) {
5311+ prefixed.target.attrs(),
5323+ // `$name` (or `${name}`) alone: an attribute bundle, spliced in
5324+ let bundle = key.strip_prefix('$').filter(|_| value.is_none() && !html);
5325+ let bundle = bundle.and_then(|after| match interp::reference(after, &ctx.env)? {
5326+ (interp::Reference::Var(name), len) if len == after.len() => Some(name),
5329+ if let Some(name) = bundle {
5330+ if let Some(define_attrs) = ctx.env.bundle(&name).cloned() {
5331+ ctx.used_defines.insert(name.clone());
5332+ for attr in define_attrs.iter() {
5333+ if !prefix.is_empty() {
5334+ let prefixed = Attribute {
5335+ key: format!("{}{}", prefix, attr.key),
5338+ if prefixed_parameter(&prefixed, text_keys, line, column(0), validate, ctx)
5342+ if let Some(attr) =
5343+ prefixed_member(attr, prefix, &name, line, column(0), validate, ctx)
5345+ out.attrs.push((attr, None));
5349+ let attrs = &out.attrs;
5350+ // Checked here, where it is either a parameter or not
5351+ let checked_here = validate
5353+ && could_be_parameter(attr)
5354+ && !text_keys.contains(&attr.key);
5356+ && (misspelled_parameter(attr, text_keys, line, column(0), ctx)
5357+ || !check_attribute(
5361+ attrs.last().map(|(a, _)| a),
5367+ out.attrs.push((attr.clone(), None));
5370+ not_a_bundle(&name, line, column(0), ctx);
2314 continue;
5372 continue;
2316−
5374+ // A name never comes from a variable
2317− // $define reference — expand attribute bundle
5375+ if key.contains('$') {
2318− if let Some(name) = part.strip_prefix('$')
5376+ track_var_refs(&key, &mut ctx.used_variables);
2319− && let Some(define_attrs) = ctx.defines.get(name)
5377+ ctx.diagnostics.push(
2320− {
5378+ Diagnostic::error(
2321− ctx.used_defines.insert(name.to_string());
5379+ code::ATTRIBUTE_FROM_VARIABLE,
2322− attrs.extend(define_attrs.clone());
5380+ line,
5382+ "'{}': an attribute's name can't come from a variable. A variable \
5383+ fills a value (`padding $size`), and whole attributes come from a \
5384+ bundle (`@let name [padding 8]`, used as `[$name]`)",
5388+ .subject(key.as_str()),
2323 continue;
5390 continue;
2326− track_var_refs(part, &mut ctx.used_variables);
5393+ // Only a style has states: `md:[id=x]`, `md:id=x`
2327−
5394+ if html && (!prefix.is_empty() || !crate::vocab::split_prefixes(&key).0.is_empty()) {
2328− if let Some((attr, condition)) = split_trailing_if(part) {
5395+ let written = format!("{}{}", prefix, key);
2329− ctx.diagnostics.push(Diagnostic {
5396+ let (name, _) = crate::vocab::split_prefixes(&written);
2330− line: line_num,
5397+ let diagnostic = Diagnostic::error(
2331− column: None,
5398+ code::INVALID_PREFIX,
2332− message: format!(
5399+ line,
2333− "`KEY if CONDITION` was removed: write `if({}, {})`",
5400+ format!(
2334− condition, attr
5401+ "'{}=': a prefix applies to a style, and `{}=` is an HTML attribute, \
5402+ which has no states",
5404+ &written[name.concat().len()..]
2336− severity: Severity::Error,
5406+ )
2337− source_line: None,
5407+ .subject(token.key.as_str());
2338− });
5408+ let diagnostic = at_attribute(diagnostic, column(0), ctx);
5409+ ctx.diagnostics.push(diagnostic);
2339 continue;
5410 continue;
2341− // A value `if(cond, a, b)` picks `a` or `b` (free text) by `cond`;
5412+ let key = if prefix.is_empty() {
2342− // an empty choice leaves the attribute out.
5413+ key
2343− let Some(part) = choose_if_value(part, ctx, line_num) else {
5414+ } else {
2344− continue;
5415+ format!("{}{}", prefix, key)
2346− let part = substitute_vars(&part, &ctx.variables);
2348− let attr = if let Some((key, value)) = split_html_attribute(&part) {
5418+ // A value's variables are filled in. A style's value is CSS, where
2349− Attribute {
5419+ // quoted text keeps its quotes; an HTML attribute's (and a
2350− key: key.to_string(),
5420+ // parameter's) is text, where it loses them.
2351− value: Some(value.to_string()),
5421+ let sink = if html || text_keys.contains(&key) {
2352− html: true,
5422+ Sink::Text
2354− } else if let Some((key, value)) = part.split_once(' ') {
2355− let value = value.trim().to_string();
2357− key: key.trim().to_string(),
2358− value: Some(value),
2361 } else {
5423 } else {
2362− Attribute {
5424+ Sink::Css
2363− key: part.to_string(),
5425+ };
2364− value: None,
5426+ let mut filled = true;
2365− html: false,
5427+ let mut quoted = None;
5428+ let mut typed = None;
5429+ let value = match value {
5431+ // A parameter's value keeps its type
5432+ Some(value) if !html && text_keys.contains(&key) => {
5433+ let at = column(token.raw.len() - value.len());
5434+ let (value, ok) = ctx.slot_value(&value, line, at);
5436+ if let Value::Quoted(q) = &value {
5437+ quoted = Some(q.clone());
5439+ let text = value.to_string();
5440+ typed = Some(value);
5444+ let at = column(token.raw.len() - value.len());
5445+ let (text, is_quoted, ok) = ctx.fill_value(&value, line, at, sink);
5447+ quoted = is_quoted;
5451+ let attr = Attribute {
5457+ // A value that couldn't be filled in is already reported, and a
5458+ // parameter's value is text for the function
5459+ let validate = validate && filled && !text_keys.contains(&attr.key);
2369− // Warn on duplicate attributes (compare full key so pseudo-class
5461+ // A duplicate is reported (compare the full key, so `border` and
2370− // variants like `border` and `hover:border` are not conflated)
5462+ // `hover:border` differ, and the form, so `width=800` and
5463+ // `width 200` do too), and the later one wins
2371 if validate {
5464 if validate {
2372− if seen_keys.contains(&attr.key) {
5465+ let seen = (normal_key(&attr.key), attr.html);
2373− ctx.diagnostics.push(Diagnostic {
5466+ if out.seen_keys.contains(&seen) {
2374− line: line_num,
5467+ let written = if attr.html { "=" } else { "" };
2375− column: None,
5468+ let message = format!(
2376− message: format!("duplicate attribute '{}'", attr.key),
5469+ "duplicate attribute '{}{}': the later one wins",
2377− severity: Severity::Warning,
5470+ attr.key, written
2378− source_line: None,
5471+ );
2379− });
5472+ let diagnostic = Diagnostic::warning(code::DUPLICATE_ATTRIBUTE, line, message)
5473+ .subject(attr.key.as_str());
5474+ let diagnostic = at_attribute(diagnostic, column(0), ctx);
5475+ ctx.diagnostics.push(diagnostic);
2380 } else {
5476 } else {
2381− seen_keys.push(attr.key.clone());
5477+ out.seen_keys.push(seen);
2384− // Color validation for hex colors
5481+ if validate && misspelled_parameter(&attr, text_keys, line, column(0), ctx) {
2385− if !attr.html
5482+ continue;
2386− && matches!(crate::vocab::base_attribute(&attr.key), "background" | "color")
5483+ }
2387− && let Some(ref val) = attr.value
5484+ if prefixed_parameter(&attr, text_keys, line, column(0), validate, ctx) {
2388− && val.starts_with('#')
5485+ continue;
2389− && !is_valid_hex_color(val)
5486+ }
2390− {
5487+ if validate && attr.html && attr.key == "class" {
2391− ctx.diagnostics.push(Diagnostic {
5488+ reserved_class(&attr, line, column(0), ctx);
2392− line: line_num,
5489+ }
2393− column: None,
5490+ // `padding=4`: a style written as an HTML attribute, which the
2394− message: format!("invalid hex color '{}'", val),
5491+ // browser ignores (`width=` and `height=` are real on some
2395− severity: Severity::Warning,
5492+ // elements, see `validate_tree`)
2396− source_line: None,
5493+ if validate
2397− });
5494+ && attr.html
2398− }
5495+ && crate::vocab::is_style_attribute(&attr.key)
5496+ && !crate::vocab::HTML_ATTRIBUTES.contains(&attr.key.as_str())
5498+ let value = token.value.as_deref().unwrap_or("").trim();
5499+ let diagnostic = Diagnostic::warning(
5500+ code::HTML_ATTRIBUTE_FORM,
5503+ "'{0}={1}' is an HTML attribute, but {0} is a style: write `{0} {1}`",
5507+ .subject(token.raw.as_str())
5508+ .suggest(Some(format!("{} {}", attr.key, value)));
5509+ let diagnostic = at_attribute(diagnostic, column(0), ctx);
5510+ ctx.diagnostics.push(diagnostic);
2401− // Warn on unknown attributes. `key=value` HTML attributes may use any
5513+ // A style or a flag: its name is checked, and what can't be
2402− // name; everything else must be a known style.
5514+ // written into the page is an error and left out
2403− if validate && !attr.html {
5515+ let checked = validate && !attr.html && !(ctx.in_bundle && could_be_parameter(&attr));
2404− let base_key = crate::vocab::base_attribute(attr.key.as_str());
5516+ let before = out.attrs.last().map(|(a, _)| a);
2405− let is_boolean_html =
5517+ if checked && !check_attribute(&attr, line, column(0), before, ctx) {
2406− attr.value.is_none() && crate::vocab::BOOLEAN_HTML_ATTRS.contains(&base_key);
5518+ continue;
2407− // A removed attribute that shares its name with a CSS property
2408− // (bare `grid`) still gets its hint.
2409− let removed = removed_attribute_hint(base_key)
2410− .filter(|_| attr.value.is_none() || !crate::vocab::is_css_property(base_key));
2411− if let Some(hint) = removed {
2412− ctx.diagnostics.push(Diagnostic {
2416− "attribute '{}' was removed: {} (run `htmlang upgrade`)",
2419− severity: Severity::Warning,
2422− } else if is_boolean_html || crate::vocab::is_style_attribute(base_key) {
2423− validate_attr_value(&attr, line_num, ctx);
2424− } else if crate::vocab::HTML_ATTRIBUTES.contains(&base_key)
2425− || base_key.starts_with("aria-")
2426− || base_key.starts_with("data-")
2428− ctx.diagnostics.push(Diagnostic {
2432− "'{}' is an HTML attribute: write `{}={}` (run `htmlang upgrade`)",
2435− attr.value.as_deref().unwrap_or("")
2437− severity: Severity::Warning,
2441− let suggestion = suggest_closest(base_key, &crate::vocab::all_attributes());
2442− let msg = match suggestion {
2445− "unknown attribute '{}', did you mean '{}'?",
2449− None => format!("unknown attribute '{}'", attr.key),
2451− ctx.diagnostics.push(Diagnostic {
2455− severity: Severity::Warning,
2461− attrs.push(attr);
5521+ out.attrs.push((attr, typed));
2467−/// Split an HTML attribute written `key=value` (`alt=`, `type=email`,
5525+/// At a call, a parameter under prefixes (`md:title x`, `md:[title x]`):
2468−/// `aria-label=Close menu`). Returns `None` for style attributes.
5526+/// a parameter has one value, with no states, so it is reported (with
2469−fn split_html_attribute(part: &str) -> Option<(&str, &str)> {
5527+/// `validate`) and left out; returns true then. A parameter named like a
2470− let first_token = part.split(char::is_whitespace).next()?;
5528+/// style (`color`) is a style under a prefix, for the root element.
2471− let eq = first_token.find('=')?;
5529+fn prefixed_parameter(
2472− let key = &part[..eq];
5530+ attr: &Attribute,
2473− let valid_key = key.starts_with(|c: char| c.is_ascii_alphabetic())
5531+ text_keys: &[String],
2474− && key
5532+ line: usize,
2475− .chars()
5533+ column: Option<usize>,
2476− .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'));
5534+ validate: bool,
2477− valid_key.then(|| (key, part[eq + 1..].trim()))
5535+ ctx: &mut ParseContext,
5537+ let (prefixes, name) = crate::vocab::split_prefixes(&attr.key);
5539+ || prefixes.is_empty()
5540+ || !text_keys.iter().any(|k| k == name)
5541+ || crate::vocab::is_style_attribute(name)
5546+ let what = if ctx.in_page {
5551+ let diagnostic = Diagnostic::error(
5552+ code::INVALID_PREFIX,
5555+ "'{}': `{}` is {}, which has one value, and a prefix applies to a style, \
5557+ attr.key, name, what
5560+ .subject(attr.key.as_str());
5561+ let diagnostic = at_attribute(diagnostic, column, ctx);
5562+ ctx.diagnostics.push(diagnostic);
2480−fn split_commas(input: &str) -> Vec<&str> {
5567+/// The prefixes of a prefixed group, bundle or `if()` inside `outer` (the
2481− let mut parts = Vec::new();
5568+/// prefixes of the groups it is in), when they are all known; else the
2482− let mut start = 0;
5569+/// unknown one is reported. Text after a group's `]` is an error too.
2483− let mut depth = 0;
5570+fn group_prefix(
2484− let mut in_quotes = false;
5571+ token: &syntax::Attr,
2485−
5572+ prefixed: &syntax::Prefixed,
2486− for (i, c) in input.char_indices() {
5573+ outer: &str,
2487− match c {
5574+ line: usize,
2488− '"' => in_quotes = !in_quotes,
5575+ ctx: &mut ParseContext,
2489− _ if in_quotes => {}
5576+) -> Option<String> {
2490− '[' | '(' => depth += 1,
5577+ let at = |ctx: &ParseContext, diagnostic: Diagnostic, span: syntax::Span| match &ctx
2491− ']' | ')' => depth -= 1,
5578+ .current_source
2492− ',' if depth == 0 => {
5579+ {
2493− parts.push(&input[start..i]);
5580+ (current, Some(text)) if span.line != 0 && *current == span.line => {
2494− start = i + 1;
5581+ diagnostic.column(span.column).source(text.clone())
5585+ if let syntax::Branch::Group {
5586+ trailing: Some(trailing),
5588+ } = &prefixed.target
5590+ let diagnostic = Diagnostic::error(
5591+ code::UNEXPECTED_ARGUMENT,
5594+ "'{}' after the `]` of `{}[...]`: the prefixes apply to the attributes in the \
5595+ group, so it goes inside it",
5596+ trailing.raw, prefixed.prefix
5599+ .subject(trailing.raw.as_str());
5600+ let diagnostic = at(ctx, diagnostic, trailing.span);
5601+ ctx.push_once(diagnostic);
5603+ let (known, rest) = crate::vocab::split_prefixes(&prefixed.prefix);
5604+ if !rest.is_empty() {
5605+ let problem = unknown_prefix(rest).unwrap_or_else(|| {
5606+ let written = rest.split_inclusive(':').next().unwrap_or(rest);
5608+ message: format!("unknown prefix '{}'", written),
5609+ subject: written.to_string(),
5613+ let diagnostic = Diagnostic::error(code::UNKNOWN_PREFIX, line, problem.message)
5614+ .subject(problem.subject)
5615+ .suggest(problem.suggestion);
5616+ let diagnostic = at(ctx, diagnostic, token.span);
5617+ ctx.push_once(diagnostic);
2499− parts.push(&input[start..]);
5620+ Some(format!("{}{}", outer, known.concat()))
2503−// ---------------------------------------------------------------------------
5623+/// An attribute of the bundle `bundle`, spliced in under `prefix`
2504−// Chain splitting (the > operator)
5624+/// (`md:$card`): the same attribute with the prefixes in front, when it can
2505−// ---------------------------------------------------------------------------
5625+/// take them. An HTML attribute can't; a style's prefixes are checked, as
2506−
5626+/// is a flag or a name that isn't a style (a bundle's parameter), which
2507−fn split_chain(content: &str) -> Vec<String> {
5627+/// under a prefix are attributes like any other.
2508− let mut segments = Vec::new();
5628+fn prefixed_member(
2509− let mut current = String::new();
5629+ attr: &Attribute,
2510− let chars: Vec<char> = content.chars().collect();
5630+ prefix: &str,
2511− let mut i = 0;
5631+ bundle: &str,
2512− let mut bracket_depth = 0;
5632+ line: usize,
2513−
5633+ column: Option<usize>,
2514− while i < chars.len() {
5634+ validate: bool,
2515− if chars[i] == '[' {
5635+ ctx: &mut ParseContext,
2516− bracket_depth += 1;
5636+) -> Option<Attribute> {
5637+ let key = format!("{}{}", prefix, attr.key);
5640+ let diagnostic = Diagnostic::error(
5641+ code::INVALID_PREFIX,
5644+ "'{}${}': the bundle has `{}=`, an HTML attribute, and a prefix applies to \
5645+ styles, which have states",
5646+ prefix, bundle, attr.key
5649+ .subject(format!("{}${}", prefix, bundle));
5650+ let diagnostic = at_attribute(diagnostic, column, ctx);
5651+ ctx.diagnostics.push(diagnostic);
2518− if chars[i] == ']' {
5653+ return None;
2519− bracket_depth -= 1;
5654+ }
5655+ let prefixed = Attribute {
5660+ let fine = if attr.value.is_none() || could_be_parameter(attr) {
5661+ check_attribute(&prefixed, line, column, None, ctx)
5663+ check_prefixes(&prefixed, line, column, ctx)
2522− // Match " > @" outside brackets
5672+/// `class=hl-x`: the `hl-` prefix is htmlang's, for its generated classes,
2523− if bracket_depth == 0
5673+/// whose rules would then apply to the element too. It goes into the page
2524− && i + 3 < chars.len()
5674+/// as written, so this is a warning.
2525− && chars[i] == ' '
5675+fn reserved_class(attr: &Attribute, line: usize, column: Option<usize>, ctx: &mut ParseContext) {
2526− && chars[i + 1] == '>'
5676+ let classes = attr.value.as_deref().unwrap_or_default();
2527− && chars[i + 2] == ' '
5677+ for class in classes.split_whitespace() {
2528− && chars[i + 3] == '@'
5678+ if class.starts_with(crate::codegen::CLASS_PREFIX) {
2529− {
5679+ let diagnostic = Diagnostic::warning(
2530− segments.push(current.trim().to_string());
5680+ code::INVALID_VALUE,
2531− current = String::new();
5681+ line,
2532− i += 3; // skip " > ", keep the "@"
5682+ format!(
2533− continue;
5683+ "class '{}' starts with `{}`, which htmlang keeps for the classes it \
5684+ generates, so their styles could apply to this element: give it \
5687+ crate::codegen::CLASS_PREFIX
5691+ let diagnostic = at_attribute(diagnostic, column, ctx);
5692+ ctx.diagnostics.push(diagnostic);
2536− current.push(chars[i]);
2540− if !current.trim().is_empty() {
5697+/// A style's key as the CSS reads it, for finding duplicates: its at-rule
2541− segments.push(current.trim().to_string());
5698+/// prefixes in one order (`dark:md:` is `md:dark:`), then its selector
5699+/// prefixes as written, whose order is the selector's.
5700+fn normal_key(key: &str) -> String {
5701+ let (prefixes, name) = crate::vocab::split_prefixes(key);
5702+ let mut at: Vec<(usize, &str)> = prefixes
5704+ .filter_map(|p| crate::vocab::at_rule_rank(p).map(|rank| (rank, *p)))
5706+ at.sort_unstable();
5708+ let mut normal: String = at.iter().map(|(_, p)| *p).collect();
5709+ for prefix in prefixes
5711+ .filter(|p| crate::vocab::at_rule_rank(p).is_none())
5713+ normal.push_str(prefix);
5715+ normal.push_str(name);
2544− segments
5719+/// `[$name]` where `$name` isn't an attribute bundle.
5720+fn not_a_bundle(name: &str, line: usize, column: Option<usize>, ctx: &mut ParseContext) {
5721+ track_var_refs(&format!("${}", name), &mut ctx.used_variables);
5722+ let is_value = interp::name_len(name) > 0 && interp::resolve(name, &ctx.env).is_some();
5723+ let diagnostic = if is_value {
5725+ code::ATTRIBUTE_FROM_VARIABLE,
5728+ "'${}' is a value, not an attribute: attributes come from a bundle \
5729+ (`@let name [padding 8]`, used as `[$name]`), and a value fills an \
5730+ attribute's value (`padding ${}`)",
5735+ } else if ctx.env.function(name).is_some() {
5736+ ctx.used_functions.insert(name.to_string());
5738+ code::UNDEFINED_VARIABLE,
5741+ "'${}' is a function, not an attribute bundle: it is called as an element, \
5748+ let mut bundles = ctx.env.bundle_names();
5749+ bundles.sort_unstable();
5750+ let suggestion = suggest_closest(name, &bundles);
5751+ let message = match suggestion {
5752+ Some(closest) => format!(
5753+ "undefined attribute bundle '${}', did you mean '${}'?",
5756+ None => format!("undefined attribute bundle '${}'", name),
5758+ Diagnostic::error(code::UNDEFINED_VARIABLE, line, message)
5760+ .suggest(suggestion)
5762+ let diagnostic = match (&ctx.current_source, column) {
5763+ ((current, Some(text)), Some(column)) if *current == line => {
5764+ diagnostic.column(column).source(text.clone())
5768+ ctx.diagnostics.push(diagnostic);
2547// ---------------------------------------------------------------------------
5771// ---------------------------------------------------------------------------
2548// Text segment parsing (inline {...} elements)
5772// Text segment parsing (inline {...} elements)
2549// ---------------------------------------------------------------------------
5773// ---------------------------------------------------------------------------
2551−fn parse_text_segments(input: &str, ctx: &mut ParseContext) -> Vec<TextSegment> {
5775+/// While a slot is filled in, each escape (see [`syntax::ESCAPES`]) is a
2552− let mut segments = Vec::new();
5776+/// private-use placeholder, U+E000 plus its place in the table, so it
2553− let mut current_text = String::new();
5777+/// can't start a variable, a quote or an inline element. Afterwards it
2554− let chars: Vec<char> = input.chars().collect();
5778+/// becomes what it stands for.
5779+fn protect_escapes(text: &str) -> String {
5780+ if !text.contains('\\') {
5781+ return text.to_string();
5783+ let mut out = String::with_capacity(text.len());
2555 let mut i = 0;
5784 let mut i = 0;
5785+ while let Some(c) = text[i..].chars().next() {
5786+ let len = syntax::escape_len(&text[i..]);
5792+ let escape = &text[i..i + len];
5793+ let index = syntax::ESCAPES.iter().position(|e| *e == escape);
5794+ out.extend(index.and_then(|n| char::from_u32(0xE000 + n as u32)));
2557− while i < chars.len() {
5800+/// The escape a placeholder stands for, as written (`\,`).
2558− if chars[i] == '{' && i + 1 < chars.len() && chars[i + 1] == '@' {
5801+fn escape_of(c: char) -> Option<&'static str> {
2559− // Flush accumulated plain text
5802+ let index = (c as u32).checked_sub(0xE000)?;
2560− if !current_text.is_empty() {
5803+ syntax::ESCAPES.get(index as usize).copied()
2561− segments.push(TextSegment::Plain(substitute_vars(
5804+}
2565− current_text.clear();
2570− let start = i + 1; // after {
2573− if i >= chars.len() {
2576− if chars[i] == '{' {
2578− } else if chars[i] == '}' {
2587− let inner: String = chars[start..i].iter().collect();
5806+fn restore_escapes(text: &str) -> String {
2588− i += 1; // skip }
5807+ text.chars()
5808+ .fold(String::with_capacity(text.len()), |mut out, c| {
5809+ match escape_of(c) {
5810+ // What the escape stands for: what follows the backslash
5811+ Some(escape) => out.push_str(&escape[1..]),
5812+ None => out.push(c),
2590− match parse_single_element(&inner, ctx.current_line, ctx) {
5818+/// Inside the quoted strings of a CSS value, `\"` and `\\` mean in CSS what
2591− Ok(elem) => segments.push(TextSegment::Inline(elem)),
5819+/// they mean in htmlang, so they stay as written there.
2592− Err(e) => {
5820+fn keep_css_string_escapes(protected: &str) -> String {
2593− // Keep the braces as literal text, but flag what looks
5821+ let mut out = String::with_capacity(protected.len());
2594− // like a mistyped inline element.
5822+ let mut inside = false;
2595− if inner.trim_start().starts_with('@') {
5823+ for c in protected.chars() {
2596− ctx.diagnostics.push(Diagnostic {
5824+ match escape_of(c) {
2597− line: ctx.current_line,
5825+ Some(escape @ ("\\\"" | "\\\\")) if inside => out.push_str(escape),
2598− column: None,
5826+ _ => {
2599− message: e.message,
5827+ if c == '"' {
2600− severity: Severity::Warning,
5828+ inside = !inside;
2601− source_line: Some(input.to_string()),
2604− current_text.push('{');
2605− current_text.push_str(&inner);
2606− current_text.push('}');
2610− current_text.push(chars[i]);
2615− if !current_text.is_empty() {
2616− segments.push(TextSegment::Plain(substitute_vars(
2625−// ---------------------------------------------------------------------------
5837+/// Evaluate text: fill in the variables of its plain runs and build its
2626−// Variable substitution
5838+/// inline elements. Each run is one slot, so a value can't make markup.
2627−// ---------------------------------------------------------------------------
5839+fn text_segments(text: &syntax::Text, ctx: &mut ParseContext) -> Vec<TextSegment> {
2628−
5840+ let mut segments = Vec::new();
2629−// ---------------------------------------------------------------------------
5841+ // The plain text so far, and where it starts
2630−// Condition evaluation for @if
5842+ let mut plain = String::new();
2631−// ---------------------------------------------------------------------------
5843+ let mut start: Option<syntax::Span> = None;
2632−
5844+ let flush = |plain: &mut String,
2633−/// Inclusive integer range from `start` to `end` (counting down when
5845+ start: &mut Option<syntax::Span>,
2634−/// `start > end`), stepping by `step`. Stops instead of overflowing.
5846+ segments: &mut Vec<TextSegment>,
2635−fn numeric_range(start: i64, end: i64, step: i64) -> Vec<String> {
5847+ ctx: &mut ParseContext| {
2636− let mut items = Vec::new();
5848+ if !plain.is_empty() {
2637− let mut n = start;
5849+ let at = start.unwrap_or(text.span);
2638− if start <= end {
5850+ let filled = ctx.interpolate_text(plain, at.line, Some(at.column));
2639− while n <= end {
5851+ segments.push(TextSegment::Plain(filled));
2640− items.push(n.to_string());
5852+ plain.clear();
2641− match n.checked_add(step) {
2642− Some(next) => n = next,
2646− } else {
5854+ *start = None;
2647− while n >= end {
5855+ };
2648− items.push(n.to_string());
5856+ for segment in &text.segments {
2649− match n.checked_sub(step) {
5857+ match segment {
2650− Some(next) => n = next,
5858+ Segment::Plain { raw, span } => {
2651− None => break,
5859+ start.get_or_insert(*span);
5860+ plain.push_str(raw);
5862+ Segment::Inline(inline) => {
5863+ let line = ctx.current_line;
5864+ match resolve(&inline.head, inline.text.as_ref(), line, &text.raw, ctx) {
5866+ if !inline.closed {
5867+ let d = Diagnostic::warning(
5868+ code::UNCLOSED_BRACKET,
5871+ "unclosed `{{`: the inline @{} runs to the end of the line. \
5872+ An inline element ends with `}}` (a brace that is text is \
5877+ let d = at_attribute(d, Some(inline.span.column), ctx);
5880+ flush(&mut plain, &mut start, &mut segments, ctx);
5881+ // A function called inline gets no children: its
5882+ // content is the text after its attributes
5883+ match Evaluator.complete(resolved, Vec::new(), ctx) {
5884+ Ok(nodes) => segments.extend(inline_segments(nodes, line)),
5887+ .get_or_insert_with(|| text.raw.as_str().into());
5888+ ctx.diagnostics.push(e);
5893+ // A misspelled element is an error inline too (a
5894+ // brace that is text is written `\{`); the braces
5896+ e.source_line = Some(text.raw.as_str().into());
5897+ ctx.diagnostics.push(e);
5898+ start.get_or_insert(inline.span);
5900+ plain.push_str(&inline.raw);
2655− items
5909+ flush(&mut plain, &mut start, &mut segments, ctx);
5913+/// The variable `raw` is, when it is exactly one `$name` or `${name}`.
5914+fn whole_reference(raw: &str, env: &Env) -> Option<String> {
5915+ let after = raw.trim().strip_prefix('$')?;
5916+ match interp::reference(after, env)? {
5917+ (interp::Reference::Var(path), len) if len == after.len() => Some(path),
2659−
5922+/// The attributes of `tokens` after each whole-attribute `if()` has
2660−/// Find a leftover `key if condition` (ignoring ` if ` inside parentheses
5923+/// chosen (see [`syntax::Choice`]), in order, into `out`. The branch not
2661−/// or quotes), to point at `if()`.
5924+/// taken isn't evaluated; with `validate`, its attribute names are checked
2662−fn split_trailing_if(part: &str) -> Option<(&str, &str)> {
5925+/// like code that doesn't run, under the prefixes `prefix` the `if()` is
2663− let mut depth = 0;
5926+/// under (`hover:if(...)`).
2664− let mut quote = None;
5927+fn choose_attrs(
2665− for (i, c) in part.char_indices() {
5928+ tokens: &[syntax::Attr],
2666− match c {
5929+ prefix: &str,
2667− '"' | '\'' if quote == Some(c) => quote = None,
5930+ line_num: usize,
2668− '"' | '\'' if quote.is_none() => quote = Some(c),
5931+ ctx: &mut ParseContext,
2669− _ if quote.is_some() => {}
5932+ validate: bool,
2670− '(' => depth += 1,
5933+ text_keys: &[String],
2671− ')' => depth -= 1,
5934+ out: &mut Vec<syntax::Attr>,
2672− _ if depth == 0 && part[i..].starts_with(" if ") => {
5935+) {
2673− return Some((&part[..i], part[i + 4..].trim()));
5936+ for token in tokens {
5937+ let Some(choice) = &token.choice else {
5938+ out.push(token.clone());
5941+ let Some(condition) = choice_shape(token, choice, line_num, ctx) else {
5944+ let taken = match condition.span.line {
5945+ 0 => ctx.condition(&condition.raw, line_num, None),
5946+ line => ctx.condition(&condition.raw, line, Some(condition.span.column)),
5948+ let (chosen, other) = match taken {
5949+ true => (choice.branches.first(), choice.branches.get(1)),
5950+ false => (choice.branches.get(1), choice.branches.first()),
5952+ if let Some(other) = other {
5953+ track_var_refs(&branch_text(other), &mut ctx.used_variables);
5955+ check_branch(token, other, prefix, line_num, ctx, text_keys);
5958+ if let Some(branch) = chosen {
2681−/// Evaluate `if(cond, a)` or `if(cond, a, b)` when it is all of `text`,
5972+/// Report what is wrong with the shape of `if()`: an empty condition, a
2682−/// returning the chosen branch (empty when `cond` fails and there is no `b`).
5973+/// number of branches other than one or two, text after a group's `]`.
2683−fn choose_if(text: &str, ctx: &mut ParseContext, line: usize) -> Option<String> {
5974+/// Returns the condition when the `if()` can be evaluated.
2684− let inner = text.strip_prefix("if(")?.strip_suffix(')')?;
5975+fn choice_shape<'a>(
2685− let args = split_if_args(inner);
5976+ token: &syntax::Attr,
2686− // `if(a) (b)` isn't one call
5977+ choice: &'a syntax::Choice,
2687− if split_trailing_paren(inner) || !(2..=3).contains(&args.len()) {
5978+ line_num: usize,
2688− return None;
5979+ ctx: &mut ParseContext,
2689− }
5980+) -> Option<&'a syntax::Arg> {
2690− let branch = if ctx.condition(args[0].trim(), line) {
5981+ let line = if token.span.line == 0 {
2691− args[1]
5982+ line_num
2692 } else {
5983 } else {
2693− args.get(2).copied().unwrap_or("")
5984+ token.span.line
2695− Some(branch.trim().to_string())
5986+ // The line the column points into, when it is the one being evaluated
2696−}
5987+ let source = |ctx: &ParseContext, diagnostic: Diagnostic, at: usize| match &ctx.current_source {
2697−
5988+ (current, Some(text)) if *current == at => diagnostic.source(text.clone()),
2698−/// Whether the parentheses in `inner` close before its end, as in the
5989+ _ => diagnostic,
2699−/// inside of `if(a)(b)`.
5990+ };
2700−fn split_trailing_paren(inner: &str) -> bool {
5991+ for branch in &choice.branches {
2701− let mut depth = 0i32;
5992+ if let syntax::Branch::Group {
2702− let mut quote = None;
5993+ trailing: Some(trailing),
2703− for c in inner.chars() {
5994+ ..
2704− match c {
5995+ } = branch
2705− '"' | '\'' if quote == Some(c) => quote = None,
5996+ {
2706− '"' | '\'' if quote.is_none() => quote = Some(c),
5997+ let diagnostic = source(
2707− _ if quote.is_some() => {}
5998+ ctx,
2708− '(' => depth += 1,
5999+ Diagnostic::error(
2709− ')' => {
6000+ code::UNEXPECTED_ARGUMENT,
2710− depth -= 1;
6001+ trailing.span.line,
2711− if depth < 0 {
6002+ format!(
2712− return true;
6003+ "'{}' after the `]` of a group in if(): a branch is one attribute, \
2713− }
6004+ one `[group]` of attributes or one `$bundle`",
2714− }
6005+ trailing.raw
6008+ .column(trailing.span.column)
6009+ .subject(trailing.raw.as_str()),
6010+ trailing.span.line,
6012+ ctx.push_once(diagnostic);
6015+ match &choice.condition {
6016+ Some(condition) if (1..=2).contains(&choice.branches.len()) => Some(condition),
6018+ let diagnostic = source(
6021+ code::INVALID_EXPRESSION,
6024+ "`{}`: if() takes a condition and one or two branches, \
6025+ `if(CONDITION, A, B)`",
6029+ .column(token.span.column),
6032+ ctx.push_once(diagnostic);
2721−/// Resolve a value written `if(cond, a, b)`: evaluate `cond` and keep the
6038+/// A branch's text, for the names it uses.
2722−/// chosen branch's text, or `None` when the choice is empty. Other
6039+fn branch_text(branch: &syntax::Branch) -> String {
2723−/// attributes are returned unchanged.
6040+ let raws: Vec<&str> = branch.attrs().iter().map(|a| a.raw.as_str()).collect();
2724−fn choose_if_value(part: &str, ctx: &mut ParseContext, line: usize) -> Option<String> {
6041+ raws.join(", ")
2725− let Some(pos) = part.find(['=', ' ']) else {
6042+}
2726− return Some(part.to_string());
6043+
2727− };
6044+/// Check attributes that are never evaluated (in code that doesn't run,
2728− let (head, value) = part.split_at(pos + 1);
6045+/// or the branch an `if()` didn't take), as far as they can be checked:
2729− match choose_if(value.trim(), ctx, line) {
6046+/// names are, and literal values; a value with a variable depends on what
2730− Some(branch) if branch.is_empty() => None,
6047+/// the variable holds. Each branch of an `if()` is checked on its own.
2731− Some(branch) => Some(format!("{}{}", head, branch)),
6048+fn check_attrs(tokens: &[syntax::Attr], line: usize, ctx: &mut ParseContext, text_keys: &[String]) {
2732− None => Some(part.to_string()),
6049+ parse_attr_list(&literal_attrs(tokens), line, ctx, true, text_keys);
6050+ check_choices(tokens, "", line, ctx, text_keys);
6053+/// [`check_attrs`] for a branch of the `if()` `token`, under the prefixes
6054+/// `prefix` it is under: `hover:if($on, color red, [id=x])` checks
6055+/// `hover:[id=x]`, an error whichever branch is taken.
6057+ token: &syntax::Attr,
6058+ branch: &syntax::Branch,
6061+ ctx: &mut ParseContext,
6062+ text_keys: &[String],
6064+ if prefix.is_empty() {
6065+ check_attrs(branch.attrs(), line, ctx, text_keys);
6068+ let list = syntax::AttrList {
6069+ attrs: branch.attrs().to_vec(),
6072+ quoted_close: None,
6074+ let grouped = syntax::Attr {
6075+ key: prefix.to_string(),
6078+ raw: token.raw.clone(),
6081+ prefixed: Some(Box::new(syntax::Prefixed {
6082+ prefix: prefix.to_string(),
6083+ prefix_span: token.span,
6084+ target: syntax::Branch::Group {
6090+ check_attrs(std::slice::from_ref(&grouped), line, ctx, text_keys);
2736−fn split_if_args(input: &str) -> Vec<&str> {
6093+/// [`check_attrs`] for the branches of each `if()` of `tokens`, which are
2737− let mut parts = Vec::new();
6094+/// under the prefixes `prefix`, also inside a prefixed group or as a
2738− let mut start = 0;
6095+/// prefixed `if()`.
2739− let mut depth = 0;
6096+fn check_choices(
2740− let mut quote = None;
6097+ tokens: &[syntax::Attr],
2741− for (i, c) in input.char_indices() {
6098+ prefix: &str,
2742− match c {
6099+ line: usize,
2743− '"' | '\'' if quote == Some(c) => quote = None,
6100+ ctx: &mut ParseContext,
2744− '"' | '\'' if quote.is_none() => quote = Some(c),
6101+ text_keys: &[String],
2745− _ if quote.is_some() => {}
6102+) {
2746− '(' => depth += 1,
6103+ for token in tokens {
2747− ')' => depth -= 1,
6104+ if let Some(choice) = &token.choice
2748− ',' if depth == 0 => {
6105+ && choice_shape(token, choice, line, ctx).is_some()
2749− parts.push(&input[start..i]);
6106+ {
2750− start = i + 1;
6107+ for branch in &choice.branches {
6108+ check_branch(token, branch, prefix, line, ctx, text_keys);
6111+ if let Some(prefixed) = &token.prefixed {
6112+ let inner = format!("{}{}", prefix, prefixed.prefix);
6113+ check_choices(prefixed.target.attrs(), &inner, line, ctx, text_keys);
2755− parts.push(&input[start..]);
2759// ---------------------------------------------------------------------------
6118// ---------------------------------------------------------------------------
2760// Post-parse validation (context-dependent warnings)
6119// Post-parse validation (context-dependent warnings)
2761// ---------------------------------------------------------------------------
6120// ---------------------------------------------------------------------------
2763−/// Attributes that only make sense on container elements (@row, @column, @el).
2764−const CONTAINER_ONLY_ATTRS: &[&str] = &[
2775fn element_kind_name(kind: &ElementKind) -> String {
6122fn element_kind_name(kind: &ElementKind) -> String {
2776 format!("@{}", kind.name())
6123 format!("@{}", kind.name())
2779−fn is_container(kind: &ElementKind) -> bool {
6126+/// HTML elements whose start tag ends an open `<p>`: written inside a
2780− matches!(kind, ElementKind::Row | ElementKind::Column | ElementKind::El)
6127+/// `@paragraph`, the browser moves them out of it. (`div` isn't here:
2781− || kind.spec().is_some_and(|spec| spec.container)
6128+/// inside text, htmlang writes its `<div>`s as `<span>`s.)
6130+const ENDS_A_PARAGRAPH: &[&str] = &[
6131+ "address", "article", "aside", "blockquote", "dd", "details", "dialog", "dl", "dt",
6132+ "fieldset", "figcaption", "figure", "footer", "form", "h1", "h2", "h3", "h4", "h5", "h6",
6133+ "header", "hgroup", "hr", "li", "main", "menu", "nav", "ol", "p", "pre", "search",
6134+ "section", "summary", "table", "ul",
6137+/// The HTML element `kind` is written as, if the browser would take it out
6139+fn ends_a_paragraph(kind: &ElementKind) -> Option<&'static str> {
6140+ let html = match kind {
6141+ ElementKind::Paragraph => "p",
6142+ ElementKind::Tag(spec) => spec.html,
6145+ ENDS_A_PARAGRAPH.contains(&html).then_some(html)
2784/// Stricter checks for `htmlang lint`, on top of the diagnostics every
6148/// Stricter checks for `htmlang lint`, on top of the diagnostics every
@@ -2788,147 +6152,171 @@ pub fn lint(nodes: &[Node]) -> Vec<Diagnostic> {
2788 fn walk(nodes: &[Node], depth: usize, out: &mut Vec<Diagnostic>) {
6152 fn walk(nodes: &[Node], depth: usize, out: &mut Vec<Diagnostic>) {
2789 for node in nodes {
6153 for node in nodes {
2790 let Node::Element(elem) = node else { continue };
6154 let Node::Element(elem) = node else { continue };
2791− let mut warn = |message: String| {
6155+ let start = out.len();
2792− out.push(Diagnostic {
6156+ let mut warn = |code: &'static str, message: String| {
2793− line: elem.line_num,
6157+ out.push(Diagnostic::warning(code, elem.line_num, message))
2796− severity: Severity::Warning,
2800 if depth > 10 {
6159 if depth > 10 {
2801− warn(format!(
6160+ warn(
2802− "deeply nested element ({} levels): consider simplifying",
6161+ code::DEEP_NESTING,
2803− depth
6162+ format!(
2804− ));
6163+ "deeply nested element ({} levels): consider simplifying",
2806− if matches!(elem.kind, ElementKind::Row | ElementKind::Column | ElementKind::El)
6168+ // A function's body may draw with an empty element (a spacer,
6169+ // a dot): only one written in the page is flagged
6170+ if elem.kind.layout().is_container()
2807 && elem.children.is_empty()
6171 && elem.children.is_empty()
6172+ && elem.function.is_none()
2809− warn(format!("empty container (@{}) has no children", elem.kind.name()));
6174+ warn(
6175+ code::EMPTY_CONTAINER,
6176+ format!("empty container (@{}) has no children", elem.kind.name()),
2811 if elem.kind.is_tag("button") && !elem.attrs.iter().any(|a| a.key == "type") {
6179 if elem.kind.is_tag("button") && !elem.attrs.iter().any(|a| a.key == "type") {
2812− warn("@button missing 'type' attribute (defaults to submit)".to_string());
6180+ warn(
6181+ code::MISSING_BUTTON_TYPE,
6182+ "@button missing 'type' attribute (defaults to submit)".to_string(),
6185+ in_function_body(elem, &mut out[start..]);
2814 walk(&elem.children, depth + 1, out);
6186 walk(&elem.children, depth + 1, out);
2817 let mut out = Vec::new();
6189 let mut out = Vec::new();
2818 walk(nodes, 0, &mut out);
6190 walk(nodes, 0, &mut out);
2822−
6195+/// `in_paragraph`: the nodes are inside a `@paragraph` (and not inside a
6196+/// `@button` in it, which the browser keeps whole).
2823fn validate_tree(
6197fn validate_tree(
2824 nodes: &[Node],
6198 nodes: &[Node],
2825 parent_kind: Option<&ElementKind>,
6199 parent_kind: Option<&ElementKind>,
6200+ in_paragraph: bool,
2826 diagnostics: &mut Vec<Diagnostic>,
6201 diagnostics: &mut Vec<Diagnostic>,
2828 for node in nodes {
6203 for node in nodes {
6204+ // An element inside a line of text (`{@kbd ...}`, an inline call)
6205+ // is checked like one on a line of its own
6206+ if let Node::Text(segments) = node {
6207+ let inline: Vec<Node> = segments
6209+ .filter_map(|segment| match segment {
6210+ TextSegment::Inline(elem) => Some(Node::Element(elem.clone())),
6214+ validate_tree(&inline, parent_kind, in_paragraph, diagnostics);
2829 if let Node::Element(elem) = node {
6216 if let Node::Element(elem) = node {
6217+ let start = diagnostics.len();
6218+ dropped_by_the_element(elem, diagnostics);
6219+ if in_paragraph && let Some(html) = ends_a_paragraph(&elem.kind) {
6221+ Diagnostic::warning(
6222+ code::BLOCK_IN_PARAGRAPH,
6225+ "{0} inside @paragraph: HTML ends a <p> before a <{1}>, so the \
6226+ browser moves the <{1}> out of the paragraph. Put {0} after the \
6227+ paragraph, or use @el, @row or @grid, which are laid out inline \
6229+ element_kind_name(&elem.kind),
6233+ .subject(elem.kind.name()),
2830 for attr in &elem.attrs {
6236 for attr in &elem.attrs {
2831 let base = crate::vocab::base_attribute(&attr.key);
6237 let base = crate::vocab::base_attribute(&attr.key);
2833− && attr.value.as_deref() == Some("fill")
2834− && !matches!(parent_kind, Some(ElementKind::Row))
2836− diagnostics.push(Diagnostic {
2837− line: elem.line_num,
2839− message: "'width fill' works best inside @row; using 100% as fallback"
2841− severity: Severity::Warning,
2845− if base == "height"
2846− && attr.value.as_deref() == Some("fill")
2847− && !matches!(parent_kind, Some(ElementKind::Column))
2849− diagnostics.push(Diagnostic {
2850− line: elem.line_num,
2852− message: "'height fill' works best inside @column; using 100% as fallback"
2854− severity: Severity::Warning,
2859− // Container-only attributes on non-container elements
6239+ // htmlang's words for laying out children, on an element
2860− if CONTAINER_ONLY_ATTRS.contains(&base) && !is_container(&elem.kind) {
6240+ // that doesn't lay out its children: left out (codegen)
2861− diagnostics.push(Diagnostic {
6241+ if !attr.html
2862− line: elem.line_num,
6242+ && crate::vocab::CONTAINER_ATTRIBUTES.contains(&base)
2863− column: None,
6243+ && !elem.kind.layout().is_container()
2864− message: format!(
6244+ && !has_no_element(&elem.kind)
2865− "'{}' has no effect on {} (only works on @row, @column, @el)",
6245+ && !crate::vocab::split_prefixes(&attr.key)
2867− element_kind_name(&elem.kind)
6247+ .contains(&"children:")
2869− severity: Severity::Warning,
6249+ diagnostics.push(not_a_container(&elem.kind, elem.line_num, base));
2874 // Form-specific: placeholder only on @input/@textarea
6252 // Form-specific: placeholder only on @input/@textarea
2875 if base == "placeholder"
6253 if base == "placeholder"
2876 && !(elem.kind.is_tag("input") || elem.kind.is_tag("textarea"))
6254 && !(elem.kind.is_tag("input") || elem.kind.is_tag("textarea"))
2878− diagnostics.push(Diagnostic {
6256+ diagnostics.push(Diagnostic::new(
2879− line: elem.line_num,
6257+ code::NO_EFFECT,
2880− column: None,
6258+ Severity::Warning,
2881− message: format!(
6259+ elem.line_num,
2882 "'placeholder' has no effect on {} (only works on @input, @textarea)",
6261 "'placeholder' has no effect on {} (only works on @input, @textarea)",
2883 element_kind_name(&elem.kind)
6262 element_kind_name(&elem.kind)
2885− severity: Severity::Warning,
6264+ ));
2890− // 'for' only on @label
6267+ // 'for' only on @label and @output
2891− if base == "for" && !elem.kind.is_tag("label") {
6268+ if base == "for" && !(elem.kind.is_tag("label") || elem.kind.is_tag("output")) {
2892− diagnostics.push(Diagnostic {
6269+ diagnostics.push(Diagnostic::new(
2893− line: elem.line_num,
6270+ code::NO_EFFECT,
2894− column: None,
6271+ Severity::Warning,
2895− message: format!(
6272+ elem.line_num,
2896− "'for' has no effect on {} (only works on @label)",
6273+ format!(
6274+ "'for' has no effect on {} (only works on @label and @output)",
2897 element_kind_name(&elem.kind)
6275 element_kind_name(&elem.kind)
2899− severity: Severity::Warning,
6277+ ));
2904− // 'rows'/'cols' only on @textarea
6280+ // `width=` and `height=` are HTML attributes of media and
2905− if (base == "rows" || base == "cols") && !elem.kind.is_tag("textarea")
6281+ // embedded content only; elsewhere they are styles
6283+ && (base == "width" || base == "height")
6284+ && !matches!(elem.kind, ElementKind::Image)
6286+ "video", "canvas", "iframe", "embed", "object", "input", "source",
6289+ .any(|tag| elem.kind.is_tag(tag))
2907− diagnostics.push(Diagnostic {
6291+ let value = attr.value.as_deref().unwrap_or("");
2908− line: elem.line_num,
6292+ diagnostics.push(
2909− column: None,
6293+ Diagnostic::warning(
2910− message: format!(
6294+ code::HTML_ATTRIBUTE_FORM,
2911− "'{}' has no effect on {} (only works on @textarea)",
6295+ elem.line_num,
2912− base,
6296+ format!(
2913− element_kind_name(&elem.kind)
6297+ "'{0}={1}' has no effect on {2}, which has no {0} attribute: \
2914− ),
6298+ the style is written `{0} {1}`",
2915− severity: Severity::Warning,
6299+ base,
2916− source_line: None,
6300+ value,
2917− });
6301+ element_kind_name(&elem.kind)
6304+ .subject(format!("{}={}", base, value)),
2920− // 'ordered' only on @list
6308+ // 'rows'/'cols' only on @textarea
2921− if base == "ordered" && !elem.kind.is_tag("list") {
6309+ if (base == "rows" || base == "cols") && !elem.kind.is_tag("textarea") {
2922− diagnostics.push(Diagnostic {
6310+ diagnostics.push(Diagnostic::new(
2923− line: elem.line_num,
6311+ code::NO_EFFECT,
2924− column: None,
6312+ Severity::Warning,
2925− message: format!(
6313+ elem.line_num,
2926− "'ordered' has no effect on {} (only works on @list)",
6314+ format!(
6315+ "'{}' has no effect on {} (only works on @textarea)",
2927 element_kind_name(&elem.kind)
6317 element_kind_name(&elem.kind)
2929− severity: Severity::Warning,
6319+ ));
2934 // Media-specific attributes only on @video/@audio
6322 // Media-specific attributes only on @video/@audio
@@ -2943,40 +6331,35 @@ fn validate_tree(
2943 | "preload"
6331 | "preload"
2944 ) && !matches!(elem.kind.name(), "video" | "audio")
6332 ) && !matches!(elem.kind.name(), "video" | "audio")
2946− diagnostics.push(Diagnostic {
6334+ diagnostics.push(Diagnostic::new(
2947− line: elem.line_num,
6335+ code::NO_EFFECT,
2948− column: None,
6336+ Severity::Warning,
2949− message: format!(
6337+ elem.line_num,
2950 "'{}' has no effect on {} (only works on @video, @audio)",
6339 "'{}' has no effect on {} (only works on @video, @audio)",
2952 element_kind_name(&elem.kind)
6341 element_kind_name(&elem.kind)
2954− severity: Severity::Warning,
6343+ ));
2959 // Missing alt text on @image
6346 // Missing alt text on @image
2960 if matches!(elem.kind, ElementKind::Image) && !elem.attrs.iter().any(|a| a.key == "alt")
6347 if matches!(elem.kind, ElementKind::Image) && !elem.attrs.iter().any(|a| a.key == "alt")
2962− diagnostics.push(Diagnostic {
6349+ diagnostics.push(Diagnostic::new(
2963− line: elem.line_num,
6350+ code::MISSING_ALT,
2964− column: None,
6351+ Severity::Warning,
2965− message: "@image missing 'alt' attribute (accessibility)".to_string(),
6352+ elem.line_num,
2966− severity: Severity::Warning,
6353+ "@image missing 'alt' attribute (accessibility)".to_string(),
2967− source_line: None,
6354+ ));
2970− if elem.kind.is_tag("input")
6356+ if elem.kind.is_tag("input") && !elem.attrs.iter().any(|a| a.key == "type") {
2971− && !elem.attrs.iter().any(|a| a.key == "type")
6357+ diagnostics.push(Diagnostic::new(
2972− {
6358+ code::MISSING_INPUT_TYPE,
2973− diagnostics.push(Diagnostic {
6359+ Severity::Warning,
2974− line: elem.line_num,
6360+ elem.line_num,
2975− column: None,
6361+ "@input missing 'type' attribute (defaults to 'text')".to_string(),
2976− message: "@input missing 'type' attribute (defaults to 'text')".to_string(),
6362+ ));
2977− severity: Severity::Warning,
2981 if matches!(elem.kind, ElementKind::Link) {
6364 if matches!(elem.kind, ElementKind::Link) {
2982 // For @link, argument is the URL, not text content
6365 // For @link, argument is the URL, not text content
@@ -2987,44 +6370,50 @@ fn validate_tree(
2988 .any(|a| a.key == "aria-label" || a.key == "title")
6371 .any(|a| a.key == "aria-label" || a.key == "title")
2990− diagnostics.push(Diagnostic {
6373+ diagnostics.push(Diagnostic::new(
2991− line: elem.line_num,
6374+ code::MISSING_LINK_TEXT,
2992− column: None,
6375+ Severity::Warning,
2993− message: "@link has no visible text or aria-label (accessibility)"
6376+ elem.line_num,
2994− .to_string(),
6377+ "@link has no visible text or aria-label (accessibility)".to_string(),
2995− severity: Severity::Warning,
6378+ ));
3001− // Contrast ratio check for hex color pairs
6382+ // Contrast ratio check for hex color pairs, each pair on the
3002− {
6383+ // same elements: the element's own, or those an element prefix
3003− let bg_color = elem
6384+ // (`@td:`) picks out inside it
3004− .attrs
6385+ let inside = |key: &str| {
3005− .iter()
6386+ crate::vocab::split_prefixes(key)
3006− .find(|a| crate::vocab::base_attribute(&a.key) == "background")
6387+ .0
3007− .and_then(|a| a.value.as_deref());
6388+ .into_iter()
3008− let fg_color = elem
6389+ .find_map(crate::vocab::element_prefix)
3009− .attrs
6390+ .map(str::to_string)
3011− .find(|a| crate::vocab::base_attribute(&a.key) == "color")
6392+ let mut targets: Vec<Option<String>> = Vec::new();
3012− .and_then(|a| a.value.as_deref());
6393+ for attr in elem.attrs.iter().filter(|a| !a.html) {
6394+ let target = inside(&attr.key);
6395+ if !targets.contains(&target) {
6396+ targets.push(target);
6399+ for target in targets {
6400+ let color = |property: &str| {
6403+ .filter(|a| !a.html && inside(&a.key) == target)
6404+ .find(|a| crate::vocab::base_attribute(&a.key) == property)
6405+ .and_then(|a| a.value.as_deref())
6407+ let (bg_color, fg_color) = (color("background"), color("color"));
3013 if let (Some(bg), Some(fg)) = (bg_color, fg_color)
6408 if let (Some(bg), Some(fg)) = (bg_color, fg_color)
3014− && let (Some(bg_rgb), Some(fg_rgb)) = (crate::expr::parse_hex_rgb(bg), crate::expr::parse_hex_rgb(fg))
6409+ && let (Some(bg_rgb), Some(fg_rgb)) = (parse_hex_rgb(bg), parse_hex_rgb(fg))
3016 let ratio = contrast_ratio(bg_rgb, fg_rgb);
6411 let ratio = contrast_ratio(bg_rgb, fg_rgb);
3017 if ratio < 4.5 {
6412 if ratio < 4.5 {
3018− diagnostics.push(Diagnostic {
6413+ diagnostics.push(Diagnostic::new(code::LOW_CONTRAST, Severity::Warning, elem.line_num, format!(
3019− line: elem.line_num,
3022 "low contrast ratio {:.1}:1 between '{}' and '{}' (WCAG AA requires 4.5:1)",
6414 "low contrast ratio {:.1}:1 between '{}' and '{}' (WCAG AA requires 4.5:1)",
3023 ratio, fg, bg
6415 ratio, fg, bg
3025− severity: Severity::Warning,
@@ -3039,45 +6428,34 @@ fn validate_tree(
3039 let has_title = elem.attrs.iter().any(|a| a.key == "title");
6428 let has_title = elem.attrs.iter().any(|a| a.key == "title");
3040 let in_label = parent_kind.is_some_and(|k| k.is_tag("label"));
6429 let in_label = parent_kind.is_some_and(|k| k.is_tag("label"));
3041 if !has_id && !has_aria_label && !has_title && !in_label {
6430 if !has_id && !has_aria_label && !has_title && !in_label {
3042− diagnostics.push(Diagnostic {
6431+ diagnostics.push(Diagnostic::new(code::MISSING_LABEL, Severity::Warning, elem.line_num, format!(
3043− line: elem.line_num,
3046 "{} should have an 'id' (with matching @label[for]), 'aria-label', or be wrapped in @label (accessibility)",
6432 "{} should have an 'id' (with matching @label[for]), 'aria-label', or be wrapped in @label (accessibility)",
3047 element_kind_name(&elem.kind)
6433 element_kind_name(&elem.kind)
3049− severity: Severity::Warning,
3055 // @iframe should have title attribute
6438 // @iframe should have title attribute
3056− if elem.kind.is_tag("iframe")
6439+ if elem.kind.is_tag("iframe") && !elem.attrs.iter().any(|a| a.key == "title") {
3057− && !elem.attrs.iter().any(|a| a.key == "title")
6440+ diagnostics.push(Diagnostic::new(
3058− {
6441+ code::MISSING_TITLE,
3059− diagnostics.push(Diagnostic {
6442+ Severity::Warning,
3060− line: elem.line_num,
6443+ elem.line_num,
3061− column: None,
6444+ "@iframe missing 'title' attribute (accessibility)".to_string(),
3062− message: "@iframe missing 'title' attribute (accessibility)".to_string(),
6445+ ));
3063− severity: Severity::Warning,
3068 // @button should have accessible text
6448 // @button should have accessible text
3069 if elem.kind.is_tag("button") {
6449 if elem.kind.is_tag("button") {
3070− let has_text = elem.argument.is_some() || !elem.children.is_empty();
6450+ let has_text = !elem.children.is_empty();
3071 let has_aria = elem.attrs.iter().any(|a| a.key == "aria-label");
6451 let has_aria = elem.attrs.iter().any(|a| a.key == "aria-label");
3072 if !has_text && !has_aria {
6452 if !has_text && !has_aria {
3073− diagnostics.push(Diagnostic {
6453+ diagnostics.push(Diagnostic::new(
3074− line: elem.line_num,
6454+ code::MISSING_BUTTON_TEXT,
3075− column: None,
6455+ Severity::Warning,
3076− message: "@button has no text content or aria-label (accessibility)"
6456+ elem.line_num,
3077− .to_string(),
6457+ "@button has no text content or aria-label (accessibility)".to_string(),
3078− severity: Severity::Warning,
6458+ ));
@@ -3090,16 +6468,15 @@ fn validate_tree(
3090 let has_track = elem
6468 let has_track = elem
3091 .children
6469 .children
3093− .any(|c| matches!(c, Node::Element(e) if e.kind.is_tag("source")));
6471+ .any(|c| matches!(c, Node::Element(e) if e.kind.is_tag("track")));
3094 if !has_aria && !has_track {
6472 if !has_aria && !has_track {
3095− diagnostics.push(Diagnostic {
6473+ diagnostics.push(Diagnostic::new(
3096− line: elem.line_num,
6474+ code::MISSING_CAPTIONS,
3097− column: None,
6475+ Severity::Warning,
3098− message: "@video should have aria-label or captions for accessibility"
6476+ elem.line_num,
6477+ "@video should have aria-label or a captions @track for accessibility"
3099 .to_string(),
6478 .to_string(),
3100− severity: Severity::Warning,
6479+ ));
@@ -3109,20 +6486,204 @@ fn validate_tree(
3109 && let Ok(n) = val.parse::<i32>()
6486 && let Ok(n) = val.parse::<i32>()
3110 && n > 0
6487 && n > 0
3112− diagnostics.push(Diagnostic {
6489+ diagnostics.push(Diagnostic::new(code::POSITIVE_TABINDEX, Severity::Warning, elem.line_num, format!("tabindex {} is positive — avoid positive tabindex values as they disrupt natural tab order", n)));
3113− line: elem.line_num,
3115− message: format!("tabindex {} is positive — avoid positive tabindex values as they disrupt natural tab order", n),
3116− severity: Severity::Warning,
6491+ in_function_body(elem, &mut diagnostics[start..]);
6493+ // An element that ends the <p> takes what is inside it out of
6494+ // the paragraph too, so only it is reported
6495+ let in_paragraph = elem.kind == ElementKind::Paragraph
6497+ && ends_a_paragraph(&elem.kind).is_none()
6498+ && !elem.kind.is_tag("button"));
6499+ validate_tree(&elem.children, Some(&elem.kind), in_paragraph, diagnostics);
6504+/// What an element has no place for in HTML, which would otherwise be
6505+/// left out of the page: attributes on `@fragment` (which has no element
6506+/// of its own), styles on `@script` (which isn't shown), a body under a
6507+/// `@script` that has a src (which the browser doesn't run), an element
6508+/// under a `@script` (whose body is code), and content in a void element
6509+/// such as `@input`.
6510+fn dropped_by_the_element(elem: &Element, diagnostics: &mut Vec<Diagnostic>) {
6511+ let name = elem.kind.name();
6512+ let keys = |attrs: Vec<&Attribute>| {
6515+ .map(|a| format!("'{}'", a.key))
6516+ .collect::<Vec<_>>()
6519+ let mut error = |code: &'static str, message: String| {
6520+ diagnostics.push(Diagnostic::error(code, elem.line_num, message).subject(name))
6522+ if elem.kind == ElementKind::Fragment && !elem.attrs.is_empty() {
6524+ code::UNEXPECTED_ARGUMENT,
6526+ "@fragment has no element of its own to put attributes on, so {} would go \
6527+ nowhere: put them on its children, or use @el",
6528+ keys(elem.attrs.iter().collect())
6532+ // The leading argument given twice: an attribute passed to the root
6533+ // of a function whose body gives the argument (written on one line,
6534+ // it is reported where it is read, and the attribute wins there)
6535+ if let Some(argument) = &elem.argument
6536+ && let Some(attr) = elem
6539+ .find(|a| a.html && elem.kind.arg().attributes().contains(&a.key.as_str()))
6542+ code::DUPLICATE_ATTRIBUTE,
6544+ "@{} takes '{}' as its {}, and it also has {}={}: give it once",
6547+ leading_name(&elem.kind),
6549+ attr.value.as_deref().unwrap_or("")
6553+ if elem.kind.is_verbatim() {
6554+ let styles: Vec<&Attribute> = elem
6557+ .filter(|a| !a.html && !crate::vocab::is_html_flag(&a.key))
6559+ if !styles.is_empty() {
6561+ code::UNEXPECTED_ARGUMENT,
6563+ "@{} isn't shown on the page, so its styles {} would go nowhere",
6569+ let src = elem.argument.clone().or_else(|| {
6572+ .find(|a| a.html && a.key == "src")
6573+ .map(|a| a.value.clone().unwrap_or_default())
6575+ if let Some(src) = src
6576+ && !elem.children.is_empty()
6579+ code::UNEXPECTED_CONTENT,
6581+ "@{0} has both a src ('{1}') and a body: the browser runs only the file, \
6582+ so the body would go nowhere. Put the code in {1}, or leave out the src",
6586+ } else if let Some(Node::Element(child)) = elem
6589+ .find(|child| matches!(child, Node::Element(_)))
6591+ // `@script > @b x`: its body is code, not elements
6593+ code::UNEXPECTED_CONTENT,
6595+ "@{} holds its code as the lines under it, kept as written, so @{} would \
6603+ if elem.kind != ElementKind::Image && elem.attrs.iter().any(|a| !a.html && a.key == "inline") {
6605+ code::UNEXPECTED_ARGUMENT,
6607+ "`inline` puts an image's file into the page, and @{} has none: it only \
6613+ if elem.kind.layout() == Layout::Void && !elem.children.is_empty() {
6615+ code::UNEXPECTED_CONTENT,
6617+ "@{} takes no content: it is an element without a closing tag, so its text \
6618+ and indented lines would go nowhere",
6625+/// `@fragment`, `@script`, `@children` and `@slot`, whose attributes are
6626+/// reported on their own (see `dropped_by_the_element`).
6627+fn has_no_element(kind: &ElementKind) -> bool {
6630+ ElementKind::Fragment | ElementKind::Children | ElementKind::Slot(_)
6631+ ) || kind.is_verbatim()
6634+/// htmlang's word `word` for laying out children (`spacing`, `wrap`,
6635+/// `grid-cols`, `grid-rows`) on an element that doesn't lay out its
6636+/// children: an error, and the word is left out.
6637+fn not_a_container(kind: &ElementKind, line: usize, word: &str) -> Diagnostic {
6638+ let name = element_kind_name(kind);
6639+ let (what, instead) = match kind.layout() {
6641+ "is text, whose lines and children flow together with no gap between them",
6642+ "; to space the children out, put them in an @el or @row",
6644+ Layout::Void => ("has no content to lay out", ""),
6646+ "keeps HTML's own layout",
6647+ "; for a flex layout of your own, write CSS, such as `display flex, gap 8`",
6654+ "'{0}' can't go on {1}: {1} {2}. `{0}` works on a row, column or grid \
6655+ (@el, @row, @grid, @section, ...){3}",
6656+ word, name, what, instead
3121− validate_tree(&elem.children, Some(&elem.kind), diagnostics);
6662+/// Diagnostics about an element a function's body wrote are reported at
6663+/// the call (see `belongs_to_call`); say which body the element is in.
6664+fn in_function_body(elem: &Element, diagnostics: &mut [Diagnostic]) {
6665+ if let Some(function) = &elem.function {
6666+ for d in diagnostics {
6667+ d.message = format!("{}\n in the body of @{}", d.message, function);
6672+/// Report each diagnostic once: a line that runs many times (in a loop, in
6673+/// a function called from one place many times) reports its problems once.
6674+fn dedupe(diagnostics: &mut Vec<Diagnostic>) {
6675+ let mut seen = HashSet::new();
6676+ diagnostics.retain(|d| {
3126fn relative_luminance(r: u8, g: u8, b: u8) -> f64 {
6687fn relative_luminance(r: u8, g: u8, b: u8) -> f64 {
3127 fn linearize(c: u8) -> f64 {
6688 fn linearize(c: u8) -> f64 {
3128 let s = c as f64 / 255.0;
6689 let s = c as f64 / 255.0;
@@ -3135,6 +6696,24 @@ fn relative_luminance(r: u8, g: u8, b: u8) -> f64 {
3135 0.2126 * linearize(r) + 0.7152 * linearize(g) + 0.0722 * linearize(b)
6696 0.2126 * linearize(r) + 0.7152 * linearize(g) + 0.0722 * linearize(b)
6699+/// The red, green and blue of a `#rgb` or `#rrggbb` colour.
6700+fn parse_hex_rgb(s: &str) -> Option<(u8, u8, u8)> {
6701+ let s = s.strip_prefix('#')?;
6702+ if !s.bytes().all(|b| b.is_ascii_hexdigit()) {
6705+ let channel = |i: usize, len: usize| u8::from_str_radix(&s[i..i + len], 16).ok();
6708+ channel(0, 1)? * 17,
6709+ channel(1, 1)? * 17,
6710+ channel(2, 1)? * 17,
6712+ 6 => Some((channel(0, 2)?, channel(2, 2)?, channel(4, 2)?)),
3138fn contrast_ratio(c1: (u8, u8, u8), c2: (u8, u8, u8)) -> f64 {
6717fn contrast_ratio(c1: (u8, u8, u8), c2: (u8, u8, u8)) -> f64 {
3139 let l1 = relative_luminance(c1.0, c1.1, c1.2);
6718 let l1 = relative_luminance(c1.0, c1.1, c1.2);
3140 let l2 = relative_luminance(c2.0, c2.1, c2.2);
6719 let l2 = relative_luminance(c2.0, c2.1, c2.2);
@@ -3142,66 +6721,48 @@ fn contrast_ratio(c1: (u8, u8, u8), c2: (u8, u8, u8)) -> f64 {
3142 (lighter + 0.05) / (darker + 0.05)
6721 (lighter + 0.05) / (darker + 0.05)
3145−// ---------------------------------------------------------------------------
3146−// Variable substitution
3147−// ---------------------------------------------------------------------------
3149−/// Interpolate `$name` variables and `${expr}` expressions into text.
3150−/// Undefined variables, and expressions that don't evaluate, are left as
3151−/// written so they show up in the output.
3152−fn substitute_vars(input: &str, vars: &HashMap<String, String>) -> String {
3153− if !input.contains('$') {
3154− return input.to_string();
3156− let is_name_char = |c: char| c.is_alphanumeric() || matches!(c, '_' | '-' | '.');
3157− let mut result = String::with_capacity(input.len());
3158− let mut rest = input;
3159− while let Some(pos) = rest.find('$') {
3160− result.push_str(&rest[..pos]);
3161− let after = &rest[pos + 1..];
3162− if after.starts_with('{')
3163− && let Some(close) = matching_brace(after)
3165− let source = &after[1..close];
3166− let resolve = |name: &str| vars.get(name).cloned();
3167− match crate::expr::eval(source, &resolve) {
3168− Ok(value) => result.push_str(&value.to_string()),
3169− Err(_) => result.push_str(&rest[pos..pos + 1 + close + 1]),
3171− rest = &after[close + 1..];
3174− let mut end = after.find(|c: char| !is_name_char(c)).unwrap_or(after.len());
3175− while end > 0 && after[..end].ends_with('.') {
3178− let name = &after[..end];
3179− match vars.get(name) {
3180− Some(value) if !name.is_empty() => result.push_str(value),
3183− result.push_str(name);
3186− rest = &after[end..];
3188− result.push_str(rest);
3192/// `@image [inline] icon.svg` becomes the SVG's markup, with `width`,
6724/// `@image [inline] icon.svg` becomes the SVG's markup, with `width`,
3193−/// `height`, `color` / `fill`, `class=` and `id=` applied to the `<svg>`
6725+/// `height`, `color` / `fill` and the HTML attributes (`class=`, `id=`,
3194−/// tag. Other nodes are returned unchanged.
6726+/// `aria-label=`, ...) applied to the `<svg>` tag; any other attribute is
6727+/// an error. Other nodes are returned unchanged.
3195fn inline_svg(node: Node, line_num: usize, ctx: &mut ParseContext) -> Node {
6728fn inline_svg(node: Node, line_num: usize, ctx: &mut ParseContext) -> Node {
3196 let Node::Element(elem) = &node else {
6729 let Node::Element(elem) = &node else {
3197 return node;
6730 return node;
3199− let is_inline_svg = elem.kind == ElementKind::Image
6732+ let inline = elem.kind == ElementKind::Image
3200 && elem.attrs.iter().any(|a| a.key == "inline" && !a.html)
6733 && elem.attrs.iter().any(|a| a.key == "inline" && !a.html)
3201− && elem.argument.as_deref().is_some_and(|src| src.ends_with(".svg"));
6734+ && elem.argument.as_deref().is_some_and(|src| !src.is_empty());
3202− if !is_inline_svg {
6735+ if !inline {
3203 return node;
6736 return node;
6738+ // A raster image: its file, read relative to this one, as a `data:` URI
6742+ .is_some_and(|src| src.ends_with(".svg"))
6744+ let Node::Element(mut elem) = node else {
6747+ let filename = elem.argument.clone().unwrap_or_default();
6748+ let resolved = ctx.resolve(&filename);
6749+ match std::fs::read(&resolved) {
6751+ elem.argument = Some(crate::codegen::data_uri(&filename, &data));
6752+ ctx.included_files.push(resolved);
6754+ Err(e) => ctx.diagnostics.push(Diagnostic::new(
6755+ code::UNREADABLE_FILE,
6759+ "cannot load image '{}' to put it into the page: {}",
6764+ return Node::Element(elem);
3205 let filename = elem.argument.clone().unwrap_or_default();
6766 let filename = elem.argument.clone().unwrap_or_default();
3206 let resolved = match &ctx.base_path {
6767 let resolved = match &ctx.base_path {
3207 Some(base) => base.join(&filename),
6768 Some(base) => base.join(&filename),
@@ -3210,145 +6771,104 @@ fn inline_svg(node: Node, line_num: usize, ctx: &mut ParseContext) -> Node {
3210 let mut svg = match std::fs::read_to_string(&resolved) {
6771 let mut svg = match std::fs::read_to_string(&resolved) {
3211 Ok(text) => text.trim().to_string(),
6772 Ok(text) => text.trim().to_string(),
3212 Err(e) => {
6773 Err(e) => {
3213− ctx.diagnostics.push(Diagnostic {
6774+ ctx.diagnostics.push(Diagnostic::new(
3214− line: line_num,
6775+ code::UNREADABLE_FILE,
3215− column: None,
6776+ Severity::Error,
3216− message: format!("cannot load SVG '{}': {}", filename, e),
6777+ line_num,
3217− severity: Severity::Error,
6778+ format!("cannot load SVG '{}': {}", filename, e),
3218− source_line: None,
6779+ ));
3220 return node;
6780 return node;
3223 ctx.included_files.push(resolved);
6783 ctx.included_files.push(resolved);
6784+ // The file's markup has no class of its own, so a style reaches it only
6785+ // as one of the root's attributes: anything else is reported, never
6786+ // left out silently
6787+ let mut left_out: Vec<String> = Vec::new();
6788+ // The styles go in the root's `style=`, where a length takes its unit
6789+ // and `var(--name)` works, as in any CSS
6790+ let mut style: Vec<String> = Vec::new();
3224 for attr in &elem.attrs {
6791 for attr in &elem.attrs {
3225− let Some(value) = &attr.value else { continue };
6792+ let target = match (attr.key.as_str(), attr.html, &attr.value) {
3226− let target = match (attr.key.as_str(), attr.html) {
6793+ ("inline", false, None) | ("src", true, _) => continue,
3227− ("width", false) | ("height", false) => attr.key.as_str(),
6794+ // `fill` and `shrink` are layout words, which need a class
3228− ("color", false) | ("fill", false) => "fill",
6795+ ("width" | "height", false, Some(value))
3229− ("class", true) | ("id", true) => attr.key.as_str(),
6796+ if matches!(value.as_str(), "fill" | "shrink") =>
3230− _ => continue,
6797+ {
3231− };
6798+ left_out.push(format!("{} {}", attr.key, value));
3232− svg = set_svg_attr(&svg, target, value);
6799+ continue;
3237−/// The first `$name|filter` (old filter syntax) in `text`, as (name, filter).
3238−fn old_filter_syntax(text: &str) -> Option<(String, String)> {
3239− const FILTERS: &[&str] = &[
3240− "uppercase", "lowercase", "capitalize", "trim", "length", "reverse", "truncate",
3241− "replace", "default", "lighten", "darken", "alpha", "mix",
3243− let mut rest = text;
3244− while let Some(pos) = rest.find('$') {
3245− let after = &rest[pos + 1..];
3247− .find(|c: char| !(c.is_alphanumeric() || matches!(c, '_' | '-' | '.')))
3248− .unwrap_or(after.len());
3249− if let Some(filter) = after[end..].strip_prefix('|') {
3250− let name_end = filter.find(|c: char| !c.is_ascii_alphabetic()).unwrap_or(filter.len());
3251− if end > 0 && FILTERS.contains(&&filter[..name_end]) {
3252− return Some((after[..end].to_string(), filter[..name_end].to_string()));
3254− }
6801+ ("width" | "height", false, Some(value)) => {
3255− rest = &after[end..];
6802+ let value = crate::vocab::with_px(&attr.key, value);
3256− }
6803+ style.push(format!("{}:{}", attr.key, value));
3257− None
6804+ continue;
3260−/// Index of the `}` matching the `{` that `s` starts with (skipping
3261−/// braces inside string literals).
3262−fn matching_brace(s: &str) -> Option<usize> {
3264− let mut in_string = false;
3265− for (i, c) in s.char_indices() {
3267− '"' => in_string = !in_string,
3268− _ if in_string => {}
3276− _ => {}
6806+ ("color" | "fill", false, Some(value)) => {
3277− }
6807+ style.push(format!("fill:{}", value));
3280−}
6810+ ("style", true, Some(value)) => {
3281−
6811+ style.insert(0, value.trim().trim_end_matches(';').to_string());
3282−/// Parse a keyframe line in htmlang syntax: `from [opacity 0]` / `50% [transform scale(1.5)]`
6812+ continue;
3283−fn parse_keyframe_line(line: &str) -> Option<String> {
6813+ }
3284− let (selector, rest) = if let Some(rest) = line.strip_prefix("from") {
6814+ ("alt", true, _) => {
3285− ("from", rest.trim())
6815+ left_out.push("alt".to_string());
3286− } else if let Some(rest) = line.strip_prefix("to") {
6816+ continue;
3287− ("to", rest.trim())
6817+ }
3288− } else if let Some(pct_end) = line.find('%') {
6818+ (key, true, Some(_)) => key,
3289− let rest = line[pct_end + 1..].trim();
6819+ (key, false, None) if crate::vocab::is_html_flag(key) => key,
3290− let selector = &line[..pct_end + 1];
6820+ _ => {
3291− (selector, rest)
6821+ left_out.push(attr.key.clone());
3292− } else {
6822+ continue;
3293− return None;
6823+ }
3295−
6825+ let value = attr.value.as_deref().unwrap_or("");
3296− if !rest.starts_with('[') || !rest.ends_with(']') {
6826+ svg = set_svg_attr(&svg, target, &html_escape_md(value));
3299−
6828+ if !style.is_empty() {
3300− let inner = &rest[1..rest.len() - 1];
6829+ // After the file's own `style=`, which stays: these come later, so
3301− // Parse comma-separated key-value pairs into CSS
6830+ // they win where both set a property
3302− let mut css = String::new();
6831+ let mut value = html_escape_md(&style.join(";"));
3303− for part in split_commas(inner) {
6832+ if let Some(own) = svg_attr_value(&svg, "style")
3304− let part = part.trim();
6833+ .map(|range| svg[range].trim().trim_end_matches(';').to_string())
3305− if part.is_empty() {
6834+ .filter(|own| !own.is_empty())
3307− }
6836+ value = format!("{};{}", own, value);
3308− if let Some((key, value)) = part.split_once(' ') {
3309− css.push_str(key.trim());
3311− css.push_str(value.trim());
6838+ svg = set_svg_attr(&svg, "style", &value);
3315−
6840+ if !left_out.is_empty() {
3316− if css.is_empty() {
6841+ let alt = left_out.iter().any(|name| name == "alt");
3317− return None;
6842+ let names = left_out
6844+ .map(|name| format!("'{}'", name))
6845+ .collect::<Vec<_>>()
6847+ let mut message = format!(
6848+ "{} can't go on an inline SVG: `@image [inline]` puts the file's own markup into the page, which takes `width` and `height` as lengths, `color` or `fill` (as its fill) and HTML attributes (`class=`, `aria-label=`, ...)",
6852+ message.push_str("; an SVG has no alt text: name it with `aria-label=` and `role=img`");
6854+ ctx.diagnostics.push(Diagnostic::new(
6855+ code::UNEXPECTED_ARGUMENT,
3319−
6861+ Node::Raw(svg)
3320− Some(format!("{}{{{}}}", selector, css))
3323// ---------------------------------------------------------------------------
6864// ---------------------------------------------------------------------------
3324// Variable usage tracking
6865// Variable usage tracking
3325// ---------------------------------------------------------------------------
6866// ---------------------------------------------------------------------------
3327−/// Scan a string for $name references and record them in the used set.
6868+/// Record the names a string refers to (by syntax) as used.
3328fn track_var_refs(input: &str, used: &mut HashSet<String>) {
6869fn track_var_refs(input: &str, used: &mut HashSet<String>) {
3329− if !input.contains('$') {
6870+ if input.contains('$') {
3330− return;
6871+ used.extend(interp::names(input).into_iter().map(String::from));
3332− let chars: Vec<char> = input.chars().collect();
3334− while i < chars.len() {
3336− && i + 1 < chars.len()
3337− && (chars[i + 1].is_alphanumeric() || chars[i + 1] == '_' || chars[i + 1] == '-')
3340− let mut end = start;
3341− while end < chars.len()
3342− && (chars[end].is_alphanumeric() || chars[end] == '-' || chars[end] == '_')
3346− let name: String = chars[start..end].iter().collect();
@@ -3356,49 +6876,63 @@ fn track_var_refs(input: &str, used: &mut HashSet<String>) {
3356// Unused definition warnings
6876// Unused definition warnings
3357// ---------------------------------------------------------------------------
6877// ---------------------------------------------------------------------------
3359−fn check_unused(ctx: &mut ParseContext) {
6879+/// Warn about definitions nothing uses, except `exported` ones (the
6880+/// definitions of a library, for the files that include it).
6881+fn check_unused(ctx: &mut ParseContext, exported: &HashSet<String>) {
3360 // Check unused @let variables
6882 // Check unused @let variables
3361 for (name, &line) in &ctx.let_lines {
6883 for (name, &line) in &ctx.let_lines {
3362− if name.starts_with("--") {
6884+ if exported.contains(name) {
3363− continue; // CSS vars are always used
6885+ // A library's names are for other files (a custom property
6886+ // isn't a variable, so it is never listed here)
3365 if !ctx.used_variables.contains(name) {
6889 if !ctx.used_variables.contains(name) {
3366− ctx.diagnostics.push(Diagnostic {
6890+ ctx.diagnostics.push(
3367− line,
6891+ Diagnostic::new(
3368− column: None,
6892+ code::UNUSED_VARIABLE,
3369− message: format!("unused variable '${}' (defined but never referenced)", name),
6893+ Severity::Warning,
3370− severity: Severity::Warning,
6894+ line,
3371− source_line: None,
6895+ format!("unused variable '${}' (defined but never referenced)", name),
6897+ .subject(name.as_str()),
3376− // Check unused attribute bundles (@let name [...])
6902+ // Check unused attribute bundles (@let name [...]). A `$name` in code
6903+ // that doesn't run (an `if()` branch or `@if` not taken) counts too.
3377 for (name, &line) in &ctx.define_lines {
6904 for (name, &line) in &ctx.define_lines {
3378− if !ctx.used_defines.contains(name) {
6905+ if !ctx.used_defines.contains(name)
3379− ctx.diagnostics.push(Diagnostic {
6906+ && !ctx.used_variables.contains(name)
3380− line,
6907+ && !exported.contains(name)
3381− column: None,
6908+ {
3382− message: format!(
6909+ ctx.diagnostics.push(
3383− "unused attribute bundle '${}' (defined but never referenced)",
6910+ Diagnostic::new(
3384− name
6911+ code::UNUSED_BUNDLE,
3385− ),
6912+ Severity::Warning,
3386− severity: Severity::Warning,
6913+ line,
3387− source_line: None,
6914+ format!(
3388− });
6915+ "unused attribute bundle '${}' (defined but never referenced)",
6919+ .subject(name.as_str()),
3392 // Check unused functions (@let name ... with body)
6924 // Check unused functions (@let name ... with body)
3393 for (name, &line) in &ctx.fn_lines {
6925 for (name, &line) in &ctx.fn_lines {
3394− if !ctx.used_functions.contains(name) {
6926+ if !ctx.used_functions.contains(name) && !exported.contains(name) {
3395− ctx.diagnostics.push(Diagnostic {
6927+ ctx.diagnostics.push(
3396− line,
6928+ Diagnostic::new(
3397− column: None,
6929+ code::UNUSED_FUNCTION,
3398− message: format!("unused function '@{}' (defined but never called)", name),
6930+ Severity::Warning,
3399− severity: Severity::Warning,
6931+ line,
3400− source_line: None,
6932+ format!("unused function '@{}' (defined but never called)", name),
6934+ .subject(name.as_str()),
@@ -3484,34 +7018,6 @@ fn parse_json_with_error(input: &str) -> Result<JsonValue, String> {
3487−/// Visit the lines of a block in source order, children after their line.
3488−fn for_each_line<'a>(block: &'a [Syntax], f: &mut impl FnMut(&'a Syntax)) {
3489− for node in block {
3491− if let Syntax::Line { children, .. } = node {
3492− for_each_line(children, f);
3497−/// The text of a block whose lines are content, not htmlang (`@head`,
3498−/// `@style`, `@markdown`): each line trimmed, verbatim text as is.
3499−fn block_text(block: &[Syntax]) -> String {
3500− let mut text = String::new();
3501− for_each_line(block, &mut |node| match node {
3502− Syntax::Line { text: line, .. } => {
3503− text.push_str(line.trim());
3506− Syntax::Raw { text: raw, .. } => {
3507− text.push_str(raw);
3515fn parse_json_value(chars: &[char], mut pos: usize) -> Option<(JsonValue, usize)> {
7021fn parse_json_value(chars: &[char], mut pos: usize) -> Option<(JsonValue, usize)> {
3516 pos = skip_ws(chars, pos);
7022 pos = skip_ws(chars, pos);
3517 if pos >= chars.len() {
7023 if pos >= chars.len() {
@@ -3692,75 +7198,21 @@ fn skip_ws(chars: &[char], mut pos: usize) -> usize {
3695−/// Flatten a JSON value into variable assignments.
7201+/// A JSON value as an htmlang value: an object is a record, an array a
3696−/// - Top-level object: each key becomes `prefix.key`
7202+/// list, a string text (never quoted text), `null` empty. A number keeps
3697−/// - Top-level array: `prefix` becomes comma-separated, `prefix._count` set
7203+/// the text it is written with (`1.50`), and reads as a number.
3698−/// - Array of objects: each item becomes space-separated values for @each destructuring
7204+fn json_value(json: JsonValue) -> Value {
3699−fn flatten_json(prefix: &str, value: &JsonValue, vars: &mut HashMap<String, String>) {
7205+ match json {
3700− match value {
7206+ JsonValue::Null => Value::empty(),
3701− JsonValue::Str(s) => {
7207+ JsonValue::Bool(b) => Value::Bool(b),
3702− vars.insert(prefix.to_string(), s.clone());
7208+ JsonValue::Number(n) | JsonValue::Str(n) => Value::Str(n),
3703− }
7209+ JsonValue::Array(items) => Value::list(items.into_iter().map(json_value).collect()),
3704− JsonValue::Number(n) => {
7210+ JsonValue::Object(pairs) => Value::Record(Rc::new(
3705− vars.insert(prefix.to_string(), n.clone());
7211+ pairs
3706− }
7212+ .into_iter()
3707− JsonValue::Bool(b) => {
7213+ .map(|(key, value)| (key, json_value(value)))
3708− vars.insert(prefix.to_string(), b.to_string());
7214+ .collect(),
3710− JsonValue::Null => {
3711− vars.insert(prefix.to_string(), String::new());
3713− JsonValue::Object(pairs) => {
3714− for (key, val) in pairs {
3715− flatten_json(&format!("{}.{}", prefix, key), val, vars);
3718− JsonValue::Array(items) => {
3719− vars.insert(format!("{}._count", prefix), items.len().to_string());
3720− // Check if all items are objects with the same keys
3721− let all_objects = items.iter().all(|v| matches!(v, JsonValue::Object(_)));
3722− if all_objects && !items.is_empty() {
3723− // Collect keys from first object for destructuring
3724− if let JsonValue::Object(first_pairs) = &items[0] {
3725− let keys: Vec<String> = first_pairs.iter().map(|(k, _)| k.clone()).collect();
3726− vars.insert(format!("{}._keys", prefix), keys.join(","));
3728− // Each item becomes space-separated values, items comma-separated
3729− let csv: Vec<String> = items
3732− if let JsonValue::Object(pairs) = item {
3735− .map(|(_, v)| json_value_to_string(v))
3736− .collect::<Vec<_>>()
3739− json_value_to_string(item)
3743− vars.insert(prefix.to_string(), csv.join(","));
3745− // Primitive array: comma-separated
3746− let csv: Vec<String> = items.iter().map(json_value_to_string).collect();
3747− vars.insert(prefix.to_string(), csv.join(","));
3749− // Also set indexed access: prefix.0, prefix.1, etc.
3750− for (i, item) in items.iter().enumerate() {
3751− flatten_json(&format!("{}.{}", prefix, i), item, vars);
3757−fn json_value_to_string(v: &JsonValue) -> String {
3759− JsonValue::Str(s) => s.clone(),
3760− JsonValue::Number(n) => n.clone(),
3761− JsonValue::Bool(b) => b.to_string(),
3762− JsonValue::Null => String::new(),
3763− JsonValue::Array(_) | JsonValue::Object(_) => String::new(),
@@ -3768,6 +7220,29 @@ fn json_value_to_string(v: &JsonValue) -> String {
3768// SVG attribute injection helper
7220// SVG attribute injection helper
3769// ---------------------------------------------------------------------------
7221// ---------------------------------------------------------------------------
7223+/// Where the root `<svg ...>` tag's `attr_name="..."` value is, as a byte
7224+/// range of `svg`. Only the opening tag is read, so a child's attribute is
7225+/// never found, and the name must follow whitespace, so `width` doesn't
7226+/// match `stroke-width`.
7227+fn svg_attr_value(svg: &str, attr_name: &str) -> Option<std::ops::Range<usize>> {
7228+ let tag_start = svg.find("<svg")?;
7229+ let tag_end = svg[tag_start..]
7231+ .map(|p| tag_start + p)
7232+ .unwrap_or(svg.len());
7233+ let tag = &svg[tag_start..tag_end];
7234+ let pattern = format!("{}=\"", attr_name);
7235+ let (pos, _) = tag.match_indices(&pattern).find(|(pos, _)| {
7239+ .is_some_and(char::is_whitespace)
7241+ let value_start = tag_start + pos + pattern.len();
7242+ let end = svg[value_start..tag_end].find('"')?;
7243+ Some(value_start..value_start + end)
3771fn set_svg_attr(svg: &str, attr_name: &str, value: &str) -> String {
7246fn set_svg_attr(svg: &str, attr_name: &str, value: &str) -> String {
3772 // Only the opening <svg ...> tag is touched, so child attributes such as
7247 // Only the opening <svg ...> tag is touched, so child attributes such as
3773 // `stroke-width` are left alone.
7248 // `stroke-width` are left alone.
@@ -3778,26 +7253,14 @@ fn set_svg_attr(svg: &str, attr_name: &str, value: &str) -> String {
3778 .find('>')
7253 .find('>')
3779 .map(|p| tag_start + p)
7254 .map(|p| tag_start + p)
3780 .unwrap_or(svg.len());
7255 .unwrap_or(svg.len());
3781− let tag = &svg[tag_start..tag_end];
3783− // Replace an existing attribute (must be preceded by whitespace so that
7257+ // Replace an existing attribute
3784− // `width` doesn't match `stroke-width`).
7258+ if let Some(existing) = svg_attr_value(svg, attr_name) {
3785− let pattern = format!("{}=\"", attr_name);
7259+ let mut result = String::with_capacity(svg.len());
3786− let existing = tag.match_indices(&pattern).find(|(pos, _)| {
7260+ result.push_str(&svg[..existing.start]);
3787− tag[..*pos]
7261+ result.push_str(value);
3788− .chars()
7262+ result.push_str(&svg[existing.end..]);
3789− .next_back()
7263+ return result;
3790− .is_some_and(char::is_whitespace)
3792− if let Some((pos, _)) = existing {
3793− let value_start = tag_start + pos + pattern.len();
3794− if let Some(end) = svg[value_start..tag_end].find('"') {
3795− let mut result = String::with_capacity(svg.len());
3796− result.push_str(&svg[..value_start]);
3797− result.push_str(value);
3798− result.push_str(&svg[value_start + end..]);
3803 // Otherwise inject it into the opening tag (before a self-closing `/`).
7266 // Otherwise inject it into the opening tag (before a self-closing `/`).
@@ -4120,7 +7583,10 @@ mod tests {
4121 fn parses_page_directive() {
7584 fn parses_page_directive() {
4122 let r = parse_ok("@page My Title\n");
7585 let r = parse_ok("@page My Title\n");
4123− assert_eq!(r.document.page_title.as_deref(), Some("My Title"));
7586+ assert_eq!(
7587+ r.document.page.map(|p| p.title).as_deref(),