@@ -1,48 +1,26 @@
11use std::collections::{HashMap, HashSet};
2−use std::fmt;
32use std::path::{Path, PathBuf};
3+use std::rc::Rc;
44
55use 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};
711
812// ---------------------------------------------------------------------------
913// Public types
1014// ---------------------------------------------------------------------------
1115
12−#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13−pub enum Severity {
14− Error,
15− Warning,
16− Info,
17− Help,
18−}
19−
20−#[derive(Debug, Clone)]
21−pub struct Diagnostic {
22− pub line: usize,
23− pub column: Option<usize>,
24− pub message: String,
25− pub severity: Severity,
26− pub source_line: Option<String>,
27−}
28−
2916pub struct ParseResult {
3017 pub document: Document,
3118 pub diagnostics: Vec<Diagnostic>,
3219 pub included_files: Vec<PathBuf>,
3320}
3421
35−#[derive(Debug)]
36−struct ParseError {
37− line: usize,
38− message: String,
39−}
40−
41−impl fmt::Display for ParseError {
42− fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
43− write!(f, "line {}: {}", self.line, self.message)
44− }
45−}
22+/// An error that stops one line from being evaluated.
23+type ParseError = Diagnostic;
4624
4725// ---------------------------------------------------------------------------
4826// Internal types
@@ -50,27 +28,166 @@ impl fmt::Display for ParseError {
5028
5129#[derive(Clone)]
5230struct FnDef {
53− params: Vec<String>,
54− defaults: HashMap<String, String>,
55− body: Vec<Syntax>,
31+ /// The parameters in the order they are declared; one without a
32+ /// default is required.
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.
36+ line: usize,
37+ source: Option<String>,
38+ node: usize,
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.
44+ slots: Vec<String>,
45+ /// Whether its body has a `@children` for the content of a call.
46+ has_children: bool,
47+ /// Its scoped `@style`, nested under its `.hl-fn-NAME` class: written
48+ /// into the page once the function is called (see
49+ /// `Document::scoped_css`).
50+ scoped: Option<String>,
51+ /// What was visible where it was defined: its body and its defaults
52+ /// see this, plus its parameters.
53+ env: Env,
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).
58+ wraps_itself: bool,
59+}
60+
61+impl FnDef {
62+ fn is_param(&self, name: &str) -> bool {
63+ self.params.iter().any(|p| p.name == name)
64+ }
65+}
66+
67+/// What a name means: every `@let`, parameter, loop variable and `@data`
68+/// binds one, and they share one namespace.
69+#[derive(Clone)]
70+enum Binding {
71+ Value(Value),
72+ Bundle(Rc<Vec<Attribute>>),
73+ Function(Rc<FnDef>),
74+}
75+
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)]
83+struct Env {
84+ frames: Vec<Rc<HashMap<String, Binding>>>,
85+}
86+
87+impl Env {
88+ fn push(&mut self) {
89+ self.frames.push(Rc::default());
90+ }
91+
92+ fn pop(&mut self) {
93+ self.frames.pop();
94+ }
95+
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() {
100+ self.push();
101+ }
102+ if let Some(frame) = self.frames.last_mut() {
103+ Rc::make_mut(frame).insert(name.to_string(), binding);
104+ }
105+ }
106+
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))
110+ }
111+
112+ fn value(&self, name: &str) -> Option<&Value> {
113+ match self.get(name)? {
114+ Binding::Value(value) => Some(value),
115+ _ => None,
116+ }
117+ }
118+
119+ fn bundle(&self, name: &str) -> Option<&Rc<Vec<Attribute>>> {
120+ match self.get(name)? {
121+ Binding::Bundle(attrs) => Some(attrs),
122+ _ => None,
123+ }
124+ }
125+
126+ fn function(&self, name: &str) -> Option<&Rc<FnDef>> {
127+ match self.get(name)? {
128+ Binding::Function(function) => Some(function),
129+ _ => None,
130+ }
131+ }
132+
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);
139+ }
140+ }
141+ names
142+ }
143+
144+ /// The names of the values visible here.
145+ fn value_names(&self) -> Vec<&str> {
146+ self.visible()
147+ .into_iter()
148+ .filter(|(_, binding)| matches!(binding, Binding::Value(_)))
149+ .map(|(name, _)| name)
150+ .collect()
151+ }
152+
153+ /// The names of the bundles visible here.
154+ fn bundle_names(&self) -> Vec<&str> {
155+ self.visible()
156+ .into_iter()
157+ .filter(|(_, binding)| matches!(binding, Binding::Bundle(_)))
158+ .map(|(name, _)| name)
159+ .collect()
160+ }
161+}
162+
163+impl interp::Scope for Env {
164+ fn get(&self, name: &str) -> Option<Value> {
165+ self.value(name).cloned()
166+ }
56167}
57168
58169struct ParseContext {
59170 /// Source line currently being parsed, for diagnostics raised deep
60171 /// inside helpers that don't take a line number.
61172 current_line: usize,
62− /// Functions whose body has a scoped @style block.
63− scoped_functions: std::collections::HashSet<String>,
64− page_title: Option<String>,
65− lang: Option<String>,
66− favicon: Option<String>,
173+ /// What the `@page` said, once one has run
174+ page: Option<Page>,
175+ /// Where that `@page` is, for the error a second one gets
176+ page_at: Option<String>,
67177 meta_tags: Vec<(String, String)>,
68178 head_blocks: Vec<String>,
69− variables: HashMap<String, String>,
70− defines: HashMap<String, Vec<Attribute>>,
71− functions: HashMap<String, FnDef>,
179+ /// The first `@meta` or `@head` that ran, for the warning a file
180+ /// without `@page` gets: a fragment has no `<head>` for them.
181+ head_at: Option<usize>,
182+ /// What each name means at the line being evaluated.
183+ env: Env,
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>>,
72187 css_vars: Vec<(String, String)>,
73188 custom_css: Vec<String>,
189+ /// The scoped `@style` of each function called so far
190+ scoped_css: Vec<String>,
74191 og_tags: Vec<(String, String)>,
75192 diagnostics: Vec<Diagnostic>,
76193 base_path: Option<PathBuf>,
@@ -90,35 +207,550 @@ struct ParseContext {
90207 fn_lines: HashMap<String, usize>,
91208 /// Line numbers of attribute bundle definitions (name -> line)
92209 define_lines: HashMap<String, usize>,
210+ /// Syntax nodes evaluated at least once, by id.
211+ visited: HashSet<usize>,
212+ /// The id the next parsed tree starts at, so ids are unique across
213+ /// the file, its includes and the standard library.
214+ next_id: usize,
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
217+ /// runs.
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
239+ /// include chain).
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.
243+ too_deep: bool,
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.
247+ in_bundle: bool,
248+ /// `@page`'s attributes are being read: a name close to `favicon` is
249+ /// a misspelled word of `@page`'s.
250+ in_page: bool,
251+}
252+
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;
256+
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() {
264+ match c {
265+ '/' if chars.peek() == Some(&'*') => {
266+ chars.next();
267+ let mut last = ' ';
268+ for c in chars.by_ref() {
269+ if last == '*' && c == '/' {
270+ break;
271+ }
272+ last = c;
273+ }
274+ continue;
275+ }
276+ '"' | '\'' => {
277+ for d in chars.by_ref() {
278+ if d == c {
279+ break;
280+ }
281+ }
282+ }
283+ '{' => depth += 1,
284+ '}' => depth = depth.saturating_sub(1),
285+ '&' if depth == 0 && at_rule_start => return true,
286+ _ => {}
287+ }
288+ at_rule_start = match c {
289+ '{' | '}' | ';' => true,
290+ c if c.is_whitespace() => at_rule_start,
291+ _ => false,
292+ };
293+ }
294+ false
295+}
296+
297+/// Whether a file is a library (see [`Tree::is_library`]), with the files
298+/// its `@include` lines name read relative to `base`.
299+fn is_library_file(
300+ tree: &Tree,
301+ base: Option<&Path>,
302+ ctx: &mut ParseContext,
303+ seen: &mut Vec<PathBuf>,
304+) -> bool {
305+ tree.is_library_with(&mut |path| {
306+ if path.contains('$') {
307+ return false;
308+ }
309+ let resolved = base.map_or_else(|| PathBuf::from(path), |base| base.join(path));
310+ if seen.contains(&resolved) {
311+ return false;
312+ }
313+ seen.push(resolved.clone());
314+ let Ok(text) = ctx.read_file(&resolved) else {
315+ return false;
316+ };
317+ let included = syntax::parse(&text);
318+ is_library_file(&included, resolved.parent(), ctx, seen)
319+ })
93320}
94321
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;
325+
95326/// Evaluates a syntax tree (see `syntax.rs`) into the document's nodes.
96327struct Evaluator;
97328
98329impl ParseContext {
99− /// Evaluate an expression (see `expr.rs`), reporting errors at `line`.
100− fn eval(&mut self, src: &str, line: usize) -> Option<crate::expr::Value> {
330+ /// Bind a value to `name` in the innermost block.
331+ fn bind(&mut self, name: &str, value: Value) {
332+ self.env.define(name, Binding::Value(value));
333+ }
334+
335+ /// Evaluate an expression (see `expr.rs`) written at `line` and
336+ /// `column` (when known), reporting its errors there.
337+ fn eval(
338+ &mut self,
339+ src: &str,
340+ line: usize,
341+ column: Option<usize>,
342+ ) -> Option<crate::expr::Value> {
101343 track_var_refs(src, &mut self.used_variables);
102− let vars = &self.variables;
103− let result = crate::expr::eval(src, &|name: &str| lookup(vars, name));
104− match result {
344+ match crate::expr::eval(src, &self.env) {
105345 Ok(value) => Some(value),
106− Err(message) => {
107− self.diagnostics.push(Diagnostic {
108− line,
109− column: None,
110− message: format!("invalid expression: {}", message),
111− severity: Severity::Error,
112− source_line: Some(src.to_string()),
113− });
346+ Err(error) => {
347+ // Without the line to point into, show the expression
348+ let shown = matches!(&self.current_source, (current, Some(_)) if *current == line);
349+ let before = self.diagnostics.len();
350+ self.report(error.at(0), line, column);
351+ if !shown && let Some(diagnostic) = self.diagnostics.get_mut(before) {
352+ diagnostic.source_line = Some(src.into());
353+ }
114354 None
115355 }
116356 }
117357 }
118358
119359 /// Evaluate a condition; an invalid one is reported and counts as false.
120− fn condition(&mut self, src: &str, line: usize) -> bool {
121− self.eval(src, line).is_some_and(|value| value.truthy())
360+ fn condition(&mut self, src: &str, line: usize, column: Option<usize>) -> bool {
361+ self.eval(src, line, column)
362+ .is_some_and(|value| value.truthy())
363+ }
364+
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
369+ /// filled.
370+ fn fill(
371+ &mut self,
372+ raw: &str,
373+ line: usize,
374+ column: Option<usize>,
375+ sink: Sink,
376+ ) -> (String, bool) {
377+ let (filled, ok) = self.fill_protected(raw, line, column, sink);
378+ (restore_escapes(&filled), ok)
379+ }
380+
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
384+ }
385+
386+ /// [`fill`](Self::fill), with the escapes still placeholders (see
387+ /// [`protect_escapes`]).
388+ fn fill_protected(
389+ &mut self,
390+ raw: &str,
391+ line: usize,
392+ column: Option<usize>,
393+ sink: Sink,
394+ ) -> (String, bool) {
395+ let mut protected = protect_escapes(raw);
396+ if sink == Sink::Css {
397+ protected = keep_css_string_escapes(&protected);
398+ }
399+ if !protected.contains('$') {
400+ return (protected, true);
401+ }
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]
413+ .chars()
414+ .map(|c| escape_of(c).map_or(c.len_utf8(), str::len))
415+ .sum();
416+ }
417+ }
418+ self.report(problem, line, column);
419+ }
420+ (out, filled)
421+ }
422+
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
426+ /// only in CSS.
427+ fn fill_value(
428+ &mut self,
429+ raw: &str,
430+ line: usize,
431+ column: Option<usize>,
432+ sink: Sink,
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),
440+ css,
441+ };
442+ let out = match sink {
443+ Sink::Css => quoted.css.clone(),
444+ Sink::Text => quoted.text.clone(),
445+ };
446+ return (out, Some(quoted), ok);
447+ }
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),
452+ _ => None,
453+ }
454+ });
455+ (out, quoted, ok)
456+ }
457+
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`:
460+ ///
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.
468+ ///
469+ /// What can't be filled in is reported; the flag says whether
470+ /// everything was.
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) {
475+ return value;
476+ }
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);
480+ }
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();
486+ let mut ok = true;
487+ let mut end = 0;
488+ for part in parts {
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() {
494+ continue;
495+ }
496+ let at = column.map(|c| c + part.start + lead);
497+ let (value, text, filled) = self.item_value(item.trim(), line, at);
498+ ok &= filled;
499+ written.push_str(&text);
500+ items.push(value);
501+ }
502+ written.push_str(&trimmed[end..]);
503+ let list = value::List {
504+ items: Rc::new(items),
505+ written: Some(written.into()),
506+ };
507+ return (Value::List(list), ok);
508+ }
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)) => {
513+ self.report(
514+ interp::Problem::Invalid { message, offset: 0 },
515+ line,
516+ column,
517+ );
518+ (Value::list(Vec::new()), false)
519+ }
520+ None => (Value::Str(text), ok),
521+ }
522+ }
523+
524+ /// An item of a list written in the source (see
525+ /// [`slot_value`](Self::slot_value)), and how it is written in the
526+ /// list's text.
527+ fn item_value(
528+ &mut self,
529+ item: &str,
530+ line: usize,
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)
538+ }
539+ None => {
540+ let (text, ok) = self.fill(item, line, column, Sink::Text);
541+ (Value::Str(text), ok)
542+ }
543+ };
544+ // Quoted text keeps its quotes in the list's text, as written
545+ let text = value
546+ .quoted_css()
547+ .map_or_else(|| value.to_string(), str::to_string);
548+ (value, text, ok)
549+ }
550+
551+ /// The value of a slot that is exactly one `$name` or `${...}`, with its
552+ /// type; `None` when it is anything else.
553+ fn whole_value(
554+ &mut self,
555+ raw: &str,
556+ line: usize,
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() {
562+ return None;
563+ }
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 {
569+ name: path,
570+ offset: 0,
571+ },
572+ },
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 }
577+ }
578+ Err(error) => error.at(2),
579+ },
580+ };
581+ self.report(problem, line, column);
582+ Some((Value::Str(raw.to_string()), false))
583+ }
584+
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),
591+ _ => (None, None),
592+ };
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);
599+ }
600+ diagnostic
601+ }
602+ interp::Problem::Invalid { message, offset } => {
603+ let diagnostic = Diagnostic::error(
604+ code::INVALID_EXPRESSION,
605+ line,
606+ format!("invalid expression: {}", message),
607+ );
608+ match column {
609+ Some(column) => diagnostic.column(column + offset),
610+ None => diagnostic,
611+ }
612+ }
613+ interp::Problem::CustomProperty { name, offset } => {
614+ let diagnostic = Diagnostic::error(
615+ code::INVALID_VALUE,
616+ line,
617+ interp::custom_property_message(&name),
618+ )
619+ .subject(format!("${}", name))
620+ .suggest(Some(format!("var({})", name)));
621+ match column {
622+ Some(column) => diagnostic.column(column + offset),
623+ None => diagnostic,
624+ }
625+ }
626+ interp::Problem::Record { message, offset } => {
627+ let diagnostic = Diagnostic::error(code::INVALID_VALUE, line, message);
628+ match column {
629+ Some(column) => diagnostic.column(column + offset),
630+ None => diagnostic,
631+ }
632+ }
633+ };
634+ let diagnostic = match line_text {
635+ Some(text) => diagnostic.source(text),
636+ None => diagnostic,
637+ };
638+ self.push_once(diagnostic);
639+ }
640+
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) {
645+ let key = (
646+ self.current_node,
647+ diagnostic.line,
648+ diagnostic.column,
649+ diagnostic.message.clone(),
650+ );
651+ if self.reported.insert(key) {
652+ self.diagnostics.push(diagnostic);
653+ }
654+ }
655+
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,
664+ line,
665+ format!(
666+ "'${}' is an attribute bundle, not a value: it goes in an attribute list \
667+ as a whole attribute, `[${}]`",
668+ name, name
669+ ),
670+ )
671+ .subject(name);
672+ }
673+ if self.env.function(name).is_some() {
674+ self.used_functions.insert(name.to_string());
675+ return Diagnostic::error(
676+ code::UNDEFINED_VARIABLE,
677+ line,
678+ format!(
679+ "'${}' is a function, not a value: it is called as an element, `@{}`",
680+ name, name
681+ ),
682+ )
683+ .subject(name);
684+ }
685+ // `$i-label` where `$i` is defined: a `-` joins a name
686+ if let Some((defined, rest)) = name
687+ .match_indices('-')
688+ .map(|(i, _)| (&name[..i], &name[i..]))
689+ .find(|(before, _)| self.env.value(before).is_some())
690+ {
691+ return Diagnostic::error(
692+ code::UNDEFINED_VARIABLE,
693+ line,
694+ format!(
695+ "undefined variable '${}': a `-` is part of a name. For '${}' followed \
696+ by '{}', write `${{{}}}{}`",
697+ name, defined, rest, defined, rest
698+ ),
699+ )
700+ .subject(name);
701+ }
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 '${}'?",
706+ name, closest
707+ ),
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",
713+ name
714+ ),
715+ (None, None) => format!("undefined variable '${}'", name),
716+ };
717+ Diagnostic::error(code::UNDEFINED_VARIABLE, line, message)
718+ .subject(name)
719+ .suggest(suggestion)
720+ }
721+
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;
726+ let text =
727+ (node.line_count <= 1).then(|| format!("{}{}", " ".repeat(node.indent), node.source));
728+ self.current_source = (node.span.line, text);
729+ }
730+
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;
736+ Rc::new(tree)
737+ }
738+
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());
743+ }
744+ let text = std::fs::read_to_string(resolved)?;
745+ self.file_cache.insert(resolved.to_path_buf(), text.clone());
746+ Ok(text)
747+ }
748+
749+ fn resolve(&self, filename: &str) -> PathBuf {
750+ match &self.base_path {
751+ Some(base) => base.join(filename),
752+ None => PathBuf::from(filename),
753+ }
122754 }
123755}
124756
@@ -127,11 +759,19 @@ impl ParseContext {
127759const PRELUDE: &str = include_str!("std.hl");
128760
129761fn load_prelude(ctx: &mut ParseContext) {
130− 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
764+ ctx.env.push();
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;
131770 // Library definitions aren't the file's own: never report them unused.
132771 ctx.fn_lines.clear();
133772 ctx.define_lines.clear();
134773 ctx.let_lines.clear();
774+ ctx.env.push();
135775}
136776
137777pub fn parse(input: &str) -> ParseResult {
@@ -139,20 +779,18 @@ pub fn parse(input: &str) -> ParseResult {
139779}
140780
141781pub fn parse_with_base(input: &str, base_path: Option<&Path>) -> ParseResult {
142− let tree = syntax::parse(input);
143782 let mut ctx = ParseContext {
144783 current_line: 0,
145− scoped_functions: std::collections::HashSet::new(),
146− page_title: None,
147− lang: None,
148− favicon: None,
784+ page: None,
785+ page_at: None,
149786 meta_tags: Vec::new(),
150787 head_blocks: Vec::new(),
151− variables: HashMap::new(),
152− defines: HashMap::new(),
153− functions: HashMap::new(),
788+ head_at: None,
789+ env: Env::default(),
790+ defined_functions: HashMap::new(),
154791 css_vars: Vec::new(),
155792 custom_css: Vec::new(),
793+ scoped_css: Vec::new(),
156794 og_tags: Vec::new(),
157795 diagnostics: Vec::new(),
158796 base_path: base_path.map(|p| p.to_path_buf()),
@@ -166,22 +804,84 @@ pub fn parse_with_base(input: &str, base_path: Option<&Path>) -> ParseResult {
166804 let_lines: HashMap::new(),
167805 fn_lines: HashMap::new(),
168806 define_lines: HashMap::new(),
807+ visited: HashSet::new(),
808+ next_id: 0,
809+ trees: Vec::new(),
810+ included_by: Rc::default(),
811+ namespace: HashSet::new(),
812+ current_source: (0, None),
813+ reported: HashSet::new(),
814+ current_node: 0,
815+ current_file: None,
816+ too_deep: false,
817+ in_bundle: false,
818+ in_page: false,
169819 };
170820 load_prelude(&mut ctx);
171− let nodes = Evaluator.eval_block(&tree, &mut ctx);
172− validate_tree(&nodes, None, &mut ctx.diagnostics);
173− check_unused(&mut ctx);
821+ let tree = ctx.parse_tree(input);
822+ ctx.diagnostics.extend(tree.diagnostics.iter().cloned());
823+ ctx.trees.push((tree.clone(), None));
824+ collect_namespace(
825+ &tree.nodes,
826+ base_path.map(Path::to_path_buf),
827+ &mut HashSet::new(),
828+ &mut ctx,
829+ );
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 {
837+ tree.nodes
838+ .iter()
839+ .filter_map(|node| match node.directive().map(|d| &d.args) {
840+ Some(DirectiveArgs::Let(def)) => Some(def.name.clone()),
841+ _ => None,
842+ })
843+ .collect()
844+ } else {
845+ HashSet::new()
846+ };
847+ check_unused(&mut ctx, &exported);
848+ if let (None, Some(line)) = (&ctx.page, ctx.head_at)
849+ && !library
850+ {
851+ ctx.diagnostics.push(Diagnostic::warning(
852+ code::NO_EFFECT,
853+ line,
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)"
856+ .to_string(),
857+ ));
858+ }
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() {
865+ match binding {
866+ Binding::Value(value) => {
867+ variables.insert(name.clone(), value.to_string());
868+ }
869+ Binding::Bundle(attrs) => {
870+ defines.insert(name.clone(), attrs.to_vec());
871+ }
872+ Binding::Function(_) => {}
873+ }
874+ }
174875 ParseResult {
175876 document: Document {
176− page_title: ctx.page_title,
177− lang: ctx.lang,
178− favicon: ctx.favicon,
877+ page: ctx.page,
179878 meta_tags: ctx.meta_tags,
180879 head_blocks: ctx.head_blocks,
181− variables: ctx.variables,
182− defines: ctx.defines,
880+ variables,
881+ defines,
183882 css_vars: ctx.css_vars,
184883 custom_css: ctx.custom_css,
884+ scoped_css: ctx.scoped_css,
185885 og_tags: ctx.og_tags,
186886 nodes,
187887 },
@@ -191,458 +891,873 @@ pub fn parse_with_base(input: &str, base_path: Option<&Path>) -> ParseResult {
191891}
192892
193893// ---------------------------------------------------------------------------
194−// Preprocessing: strip comments/blanks, collapse @raw blocks
195−// ---------------------------------------------------------------------------
196−
197−// ---------------------------------------------------------------------------
198−// Evaluation
894+// Code that never runs: an untaken branch, an uncalled function, a loop over
895+// an empty list
199896// ---------------------------------------------------------------------------
200897
201−impl Evaluator {
202− fn eval_block(&mut self, block: &[Syntax], ctx: &mut ParseContext) -> Vec<Node> {
203− let mut nodes = Vec::new();
204− for node in block {
205− match self.eval(node, ctx) {
206− Ok(Some(new_nodes)) => nodes.extend(new_nodes),
207− Ok(None) => {}
208− // Record the error and go on, to report several in one pass
209− Err(e) => ctx.diagnostics.push(Diagnostic {
210− line: e.line,
211− column: None,
212− message: e.message,
213− severity: Severity::Error,
214− source_line: Some(node.source()),
215− }),
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,
905+) {
906+ let mut includes = Vec::new();
907+ for node in nodes {
908+ node.walk(&mut |node| match node.directive().map(|d| &d.args) {
909+ Some(DirectiveArgs::Let(def)) if matches!(def.form, LetForm::Function(_)) => {
910+ ctx.namespace.insert(def.name.clone());
216911 }
912+ Some(DirectiveArgs::Text(Some(path))) if node.is_directive("include") => {
913+ includes.push(path.raw.clone());
914+ }
915+ _ => {}
916+ });
917+ }
918+ for path in includes {
919+ let path = path.trim_matches('"');
920+ if path.contains('$') {
921+ continue;
217922 }
218− nodes
923+ let resolved = match &base {
924+ Some(base) => base.join(path),
925+ None => PathBuf::from(path),
926+ };
927+ if !seen.insert(resolved.clone()) {
928+ continue;
929+ }
930+ let Ok(text) = ctx.read_file(&resolved) else {
931+ continue;
932+ };
933+ let tree = syntax::parse(&text);
934+ let parent = resolved.parent().map(Path::to_path_buf);
935+ collect_namespace(&tree.nodes, parent, seen, ctx);
219936 }
937+}
220938
221− /// Evaluate a block in its own scope: `@let` inside doesn't leak out.
222− fn eval_scoped(&mut self, block: &[Syntax], ctx: &mut ParseContext) -> Vec<Node> {
223− let saved_vars = ctx.variables.clone();
224− let nodes = self.eval_block(block, ctx);
225− ctx.variables = saved_vars;
226− nodes
939+/// Check the lines that were never evaluated: element and function names,
940+/// and the attributes of built-in elements (those that don't depend on a
941+/// variable). Names that come from data are only checked when evaluated.
942+fn check_unevaluated(ctx: &mut ParseContext) {
943+ let trees = std::mem::take(&mut ctx.trees);
944+ let mut seen = HashSet::new();
945+ for (tree, chain) in &trees {
946+ let before = ctx.diagnostics.len();
947+ for node in &tree.nodes {
948+ check_unevaluated_node(node, ctx);
949+ }
950+ let mut found = ctx.diagnostics.split_off(before);
951+ if let Some(chain) = chain {
952+ for d in &mut found {
953+ d.message = format!("{}\n in {}", d.message, chain);
954+ }
955+ }
956+ // A file included twice is checked twice: report each problem once
957+ found.retain(|d| seen.insert((d.line, d.message.clone())));
958+ ctx.diagnostics.extend(found);
227959 }
960+ ctx.trees = trees;
961+}
228962
229− fn eval(
230− &mut self,
231− node: &Syntax,
232− ctx: &mut ParseContext,
233− ) -> Result<Option<Vec<Node>>, ParseError> {
234− let line_num = node.line();
235− ctx.current_line = line_num;
236− let (content, current_indent, children) = match node {
237− Syntax::Raw { text, .. } => return Ok(Some(vec![Node::Raw(text.clone())])),
238− Syntax::Function {
239− name,
240− params,
241− defaults,
242− body,
243− ..
244− } => {
245− self.define_function(name, params, defaults, body, line_num, ctx);
246− return Ok(None);
247− }
248− Syntax::If { branches } => {
249− // Every condition is checked (and its errors reported);
250− // the first that holds picks the branch.
251− let mut chosen = None;
252− for branch in branches {
253− let holds = match &branch.condition {
254− Some(condition) => ctx.condition(condition, branch.line),
255− None => true,
256− };
257− if holds && chosen.is_none() {
258− chosen = Some(&branch.body);
259− }
963+fn check_unevaluated_node(node: &syntax::Node, ctx: &mut ParseContext) {
964+ if !ctx.visited.contains(&node.id) {
965+ let line = node.span.line;
966+ // A reference from code that doesn't run still counts as a use
967+ track_var_refs(&node.source, &mut ctx.used_variables);
968+ let before = ctx.diagnostics.len();
969+ match &node.kind {
970+ NodeKind::Element(element) => {
971+ for head in &element.chain {
972+ check_head(head, line, ctx);
973+ }
974+ check_unevaluated_content(node, element, ctx);
975+ if let Some(text) = &element.text {
976+ check_inline_heads(text, line, ctx);
260977 }
261− return Ok(chosen.map(|body| self.eval_scoped(body, ctx)));
262978 }
263− Syntax::Each {
264− header,
265− body,
266− empty,
979+ NodeKind::Text(text) => check_inline_heads(text, line, ctx),
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 {
983+ args:
984+ DirectiveArgs::Page {
985+ attrs: Some(list), ..
986+ },
267987 ..
268− } => {
269− return self.eval_each(header, body, empty, line_num, ctx).map(Some);
988+ }) => {
989+ let words: Vec<String> = crate::vocab::PAGE_WORDS
990+ .iter()
991+ .map(|w| w.to_string())
992+ .collect();
993+ ctx.in_page = true;
994+ check_attrs(&list.attrs, line, ctx, &words);
995+ ctx.in_page = false;
996+ check_page_tokens(&list.attrs, line, ctx);
270997 }
271− Syntax::Line {
272− text,
273− indent,
274− children,
275− ..
276− } => (text.clone(), *indent, children),
277− };
278−
279− // --- Directives ---
280−
281− // @page [lang en, favicon /f.png] Title
282− if let Some(rest) = content.strip_prefix("@page ") {
283− let rest = rest.trim_start();
284− let title = if rest.starts_with('[') {
285− let (attrs, title) = parse_attr_brackets_no_validate(rest, line_num, ctx)?;
286− for attr in attrs {
287− let value = attr.value.unwrap_or_default();
288− match attr.key.as_str() {
289− "lang" => ctx.lang = Some(value),
290− "favicon" => ctx.favicon = Some(value),
291− other => ctx.diagnostics.push(Diagnostic {
292− line: line_num,
293− column: None,
294− message: format!(
295− "unknown @page attribute '{}' (expected lang or favicon)",
296− other
297− ),
298− severity: Severity::Warning,
299− source_line: Some(content.clone()),
300− }),
301− }
302− }
303− title
304− } else {
305− rest.to_string()
306− };
307− ctx.page_title = Some(substitute_vars(title.trim(), &ctx.variables));
308− return Ok(None);
998+ _ => {}
309999 }
1000+ let text = written_line(node);
1001+ for d in &mut ctx.diagnostics[before..] {
1002+ d.source_line.get_or_insert_with(|| text.as_str().into());
1003+ }
1004+ }
1005+ for child in &node.children {
1006+ check_unevaluated_node(child, ctx);
1007+ }
1008+}
3101009
311− if let Some(rest) = content.strip_prefix("@let ") {
312− let rest = rest.trim();
313−
314− if !children.is_empty() {
315− return Err(ParseError {
316− line: line_num,
317− message: "@let with body requires a name".to_string(),
318− });
319− }
320−
321− if let Some((name, value)) = rest.split_once(' ') {
322− let value = value.trim();
323− // `@let name = EXPR` computes its value (see expr.rs); any
324− // other value is literal text with `$var` interpolation.
325− if let Some(expression) = value.strip_prefix('=') {
326− let value = ctx
327− .eval(expression.trim(), line_num)
328− .map(|v| v.to_string())
329− .unwrap_or_default();
330− if name.starts_with("--") {
331− ctx.css_vars.push((name.to_string(), value.clone()));
332− }
333− ctx.variables.insert(name.to_string(), value);
334− ctx.let_lines.entry(name.to_string()).or_insert(line_num);
335− return Ok(None);
336− }
337−
338− // Attribute bundle: @let name [attr1, attr2, ...]
339− if value.starts_with('[') {
340− let (attrs, _) = parse_attr_brackets(value, line_num, ctx)?;
341− ctx.defines.insert(name.to_string(), attrs);
342− ctx.define_lines.entry(name.to_string()).or_insert(line_num);
343− return Ok(None);
344− }
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,
1017+) {
1018+ let calls: Vec<Option<(String, Rc<FnDef>)>> = element
1019+ .chain
1020+ .iter()
1021+ .map(|head| {
1022+ let function = ctx.defined_functions.get(&head.name)?;
1023+ Some((head.name.clone(), function.clone()))
1024+ })
1025+ .collect();
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 {
1030+ continue;
1031+ };
1032+ if function.has_children || function.wraps_itself {
1033+ continue;
1034+ }
1035+ let content = if i == last {
1036+ element.text.is_some() || holds_content(&node.children, ctx)
1037+ } else {
1038+ element.chain[i + 1].name != "slot" || !slot_is_built_in(ctx)
1039+ };
1040+ if content {
1041+ let head = &element.chain[i];
1042+ ctx.push_once(no_children(
1043+ name,
1044+ node.span.line,
1045+ name_column(head, node.span.line),
1046+ ));
1047+ }
1048+ }
1049+}
3451050
346− let value = if value.starts_with('"') && value.ends_with('"') && value.len() >= 2 {
347− // Support quoted string interpolation: @let greeting "Hello $name"
348− &value[1..value.len() - 1]
349− } else {
350− value
351− };
352− track_var_refs(value, &mut ctx.used_variables);
353− let value = substitute_vars(value, &ctx.variables);
354− if name.starts_with("--") {
355− // CSS custom property
356− ctx.css_vars.push((name.to_string(), value.clone()));
1051+/// Check a head that was never evaluated: its name, and its attributes
1052+/// (for a call, see [`check_call`]).
1053+fn check_head(head: &syntax::Head, line: usize, ctx: &mut ParseContext) {
1054+ let is_function =
1055+ ctx.namespace.contains(&head.name) || ctx.defined_functions.contains_key(&head.name);
1056+ if is_function {
1057+ ctx.used_functions.insert(head.name.clone());
1058+ if let Some(function) = ctx.defined_functions.get(&head.name).cloned()
1059+ && !function.wraps_itself
1060+ {
1061+ check_call(head, &function, line, ctx);
1062+ }
1063+ return;
1064+ }
1065+ let kind = match parse_element_kind(&head.name, line, ctx) {
1066+ Ok(kind) => kind,
1067+ Err(e) => {
1068+ ctx.diagnostics.push(e);
1069+ return;
1070+ }
1071+ };
1072+ if let Some(list) = &head.attrs {
1073+ check_attrs(&list.attrs, line, ctx, &[]);
1074+ // A word for laying out children on an element that doesn't lay
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);
1079+ if !attr.html
1080+ && attr.choice.is_none()
1081+ && attr.prefixed.is_none()
1082+ && crate::vocab::CONTAINER_ATTRIBUTES.contains(&base)
1083+ && !crate::vocab::split_prefixes(&attr.key)
1084+ .0
1085+ .contains(&"children:")
1086+ {
1087+ ctx.push_once(not_a_container(&kind, line, base).column(attr.span.column));
3571088 }
358− ctx.variables.insert(name.to_string(), value);
359− ctx.let_lines.entry(name.to_string()).or_insert(line_num);
3601089 }
361− return Ok(None);
3621090 }
1091+ }
1092+}
3631093
364− // @meta NAME VALUE; `og:` names become Open Graph property tags
365− if let Some(rest) = content.strip_prefix("@meta ") {
366− let rest = rest.trim();
367− if let Some((name, value)) = rest.split_once(' ') {
368− let value = substitute_vars(value.trim(), &ctx.variables);
369− match name.trim().strip_prefix("og:") {
370− Some(property) => ctx.og_tags.push((property.to_string(), value)),
371− None => ctx.meta_tags.push((name.trim().to_string(), value)),
1094+/// The attributes of a list that is never evaluated that can be checked
1095+/// together: not bundles or `if()`s. Names are checked; a value with a
1096+/// variable in it depends on what the variable holds, so only a literal
1097+/// value is (the other is checked as an empty value).
1098+/// `@page`'s own rules (see `check_page_attr`) for a list that isn't
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 {
1103+ Some(choice) => {
1104+ for branch in &choice.branches {
1105+ check_page_tokens(branch.attrs(), line, ctx);
3721106 }
3731107 }
374− return Ok(None);
1108+ // Under prefixes there are only styles
1109+ None if token.key.starts_with('$') || token.prefixed.is_some() => {}
1110+ None => {
1111+ let value = token.value.as_deref().map(|v| v.trim_matches('"'));
1112+ let value = match value {
1113+ Some(v) if v.contains('$') => Some("$"),
1114+ other => other,
1115+ };
1116+ check_page_attr(
1117+ &token.key,
1118+ token.html,
1119+ value,
1120+ line,
1121+ Some(token.span.column),
1122+ ctx,
1123+ );
1124+ }
3751125 }
1126+ }
1127+}
3761128
377− if content == "@head" || content.starts_with("@head ") {
378− let trimmed = block_text(children).trim().to_string();
379− if !trimmed.is_empty() {
380− ctx.head_blocks.push(trimmed);
1129+fn literal_attrs(tokens: &[syntax::Attr]) -> Vec<syntax::Attr> {
1130+ // A prefixed group is checked with its prefixes, as far as its own
1131+ // attributes can be; a prefixed bundle or `if()` depends on what it holds
1132+ let group = |a: &syntax::Attr| {
1133+ let prefixed = a.prefixed.as_ref()?;
1134+ let syntax::Branch::Group { list, trailing } = &prefixed.target else {
1135+ return None;
1136+ };
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 {
1142+ list,
1143+ trailing: trailing.clone(),
1144+ },
1145+ ..(**prefixed).clone()
1146+ }));
1147+ Some(a)
1148+ };
1149+ let groups = tokens.iter().filter_map(group);
1150+ tokens
1151+ .iter()
1152+ .filter(|a| {
1153+ let bundle = a.key.starts_with('$') && a.value.is_none() && !a.html;
1154+ a.choice.is_none() && a.prefixed.is_none() && !bundle
1155+ })
1156+ .map(|a| {
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);
3811162 }
382− return Ok(None);
1163+ a
1164+ })
1165+ .chain(groups)
1166+ .collect()
1167+}
1168+
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);
1180+ }
1181+ let unknown = attrs
1182+ .iter()
1183+ .any(|a| a.choice.is_some() || (a.key.starts_with('$') && a.value.is_none()));
1184+ if unknown {
1185+ return;
1186+ }
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));
3831191 }
1192+ }
1193+}
3841194
385− // --- @style block (raw CSS) ---
386− if content.trim() == "@style" {
387− let trimmed = block_text(children).trim().to_string();
388− if !trimmed.is_empty() {
389− ctx.custom_css.push(trimmed);
390− }
391− return Ok(None);
1195+/// Report each parameter a call's list writes `name=value`, with the value
1196+/// as written and its column; returns their names, so the evaluated call
1197+/// doesn't report them again.
1198+fn written_parameter_forms(
1199+ name: &str,
1200+ function: &FnDef,
1201+ attrs: &[syntax::Attr],
1202+ line: usize,
1203+ ctx: &mut ParseContext,
1204+) -> Vec<String> {
1205+ let mut reported = Vec::new();
1206+ for attr in attrs {
1207+ if !(attr.html && function.is_param(&attr.key)) {
1208+ continue;
3921209 }
1210+ let at = if attr.span.line == 0 {
1211+ line
1212+ } else {
1213+ attr.span.line
1214+ };
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()),
1219+ _ => diagnostic,
1220+ });
1221+ reported.push(attr.key.clone());
1222+ }
1223+ reported
1224+}
3931225
394− // --- @markdown block or file (convert markdown to HTML) ---
395− if content.trim() == "@markdown" || content.trim().starts_with("@markdown ") {
396− let arg = content.trim().strip_prefix("@markdown").unwrap().trim();
397− if arg.is_empty() {
398− // Inline markdown block: indented children
399− let md_lines: Vec<String> =
400− block_text(children).lines().map(String::from).collect();
401− let html = markdown_to_html(&md_lines);
402− return Ok(Some(vec![Node::Raw(html)]));
403− } else {
404− // External markdown file: @markdown file.md
405− let filename = substitute_vars(arg, &ctx.variables);
406− let resolved = match &ctx.base_path {
407− Some(base) => base.join(&filename),
408− None => PathBuf::from(&filename),
409− };
410− let md_text = if let Some(cached) = ctx.file_cache.get(&resolved) {
411− cached.clone()
412− } else {
413− match std::fs::read_to_string(&resolved) {
414− Ok(text) => {
415− ctx.file_cache.insert(resolved.clone(), text.clone());
416− text
417− }
418− Err(e) => {
419− ctx.diagnostics.push(Diagnostic {
420− line: line_num,
421− column: None,
422− message: format!("cannot read markdown '{}': {}", filename, e),
423− severity: Severity::Error,
424− source_line: Some(content.clone()),
425− });
426− return Ok(None);
427− }
428− }
429− };
430− ctx.included_files.push(resolved);
431− let md_lines: Vec<String> = md_text.lines().map(|l| l.to_string()).collect();
432− let html = markdown_to_html(&md_lines);
433− return Ok(Some(vec![Node::Raw(html)]));
1226+fn check_inline_heads(text: &syntax::Text, line: usize, ctx: &mut ParseContext) {
1227+ for segment in &text.segments {
1228+ if let Segment::Inline(inline) = segment {
1229+ check_head(&inline.head, line, ctx);
1230+ if let Some(text) = &inline.text {
1231+ check_inline_heads(text, line, ctx);
4341232 }
4351233 }
1234+ }
1235+}
4361236
437− if let Some(rest) = content.strip_prefix("@include ") {
438− let rest = rest.trim();
439− let filename = rest
440− .strip_prefix('"')
441− .and_then(|f| f.strip_suffix('"'))
442− .unwrap_or(rest);
443− let filename = substitute_vars(filename, &ctx.variables);
1237+// ---------------------------------------------------------------------------
1238+// Evaluation
1239+// ---------------------------------------------------------------------------
4441240
445− let resolved = match &ctx.base_path {
446− Some(base) => base.join(&filename),
447− None => PathBuf::from(&filename),
448− };
1241+/// The `@else` lines that continue the `@if` or `@each` before `from`, and
1242+/// the position after them.
1243+fn else_branches(block: &[syntax::Node], from: usize, is_if: bool) -> (Vec<&syntax::Node>, usize) {
1244+ let mut branches = Vec::new();
1245+ let mut next = from;
1246+ let mut i = from;
1247+ while i < block.len() {
1248+ let node = &block[i];
1249+ i += 1;
1250+ if node.is_trivia() {
1251+ continue;
1252+ }
1253+ let condition = match node.directive().map(|d| &d.args) {
1254+ Some(DirectiveArgs::Else { condition }) => condition.is_some(),
1255+ _ => break,
1256+ };
1257+ if condition && !is_if {
1258+ break;
1259+ }
1260+ branches.push(node);
1261+ next = i;
1262+ if !condition {
1263+ break;
1264+ }
1265+ }
1266+ (branches, next)
1267+}
4491268
450− if ctx.include_stack.contains(&resolved) {
451− let cycle_chain = format_include_chain(&ctx.include_stack);
452− ctx.diagnostics.push(Diagnostic {
453− line: line_num,
454− column: None,
455− message: format!(
456− "circular include '{}' (cycle: {} → {})",
457− filename, cycle_chain, filename
458− ),
459− severity: Severity::Error,
460− source_line: Some(content.clone()),
461− });
462− return Ok(None);
1269+impl Evaluator {
1270+ fn eval_block(&mut self, block: &[syntax::Node], ctx: &mut ParseContext) -> Vec<Node> {
1271+ let mut nodes = Vec::new();
1272+ let mut i = 0;
1273+ while i < block.len() {
1274+ let node = &block[i];
1275+ i += 1;
1276+ if node.is_trivia() {
1277+ continue;
4631278 }
464−
465− let imported_text = if let Some(cached) = ctx.file_cache.get(&resolved) {
466− cached.clone()
467− } else {
468− match std::fs::read_to_string(&resolved) {
469− Ok(text) => {
470− ctx.file_cache.insert(resolved.clone(), text.clone());
471− text
472− }
473− Err(e) => {
474− ctx.diagnostics.push(Diagnostic {
475− line: line_num,
476− column: None,
477− message: format!("cannot include '{}': {}", filename, e),
478− severity: Severity::Error,
479− source_line: Some(content.clone()),
480− });
481− return Ok(None);
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");
1282+ i = next;
1283+ if name == "if" {
1284+ Ok(Some(self.eval_if(node, &branches, ctx)))
1285+ } else {
1286+ self.eval_each(node, branches.first().copied(), ctx)
4821287 }
4831288 }
1289+ // Reported as a syntax error
1290+ Some("else") => {
1291+ ctx.visited.insert(node.id);
1292+ Ok(None)
1293+ }
1294+ _ => self.eval(node, ctx),
4841295 };
485−
486− ctx.included_files.push(resolved.clone());
487− ctx.include_stack.push(resolved.clone());
488− let saved_base = ctx.base_path.clone();
489− ctx.base_path = resolved.parent().map(|p| p.to_path_buf());
490−
491− let diag_count_before = ctx.diagnostics.len();
492−
493− let included_nodes = self.eval_block(&syntax::parse(&imported_text), ctx);
494−
495− // Annotate new diagnostics with import chain
496− let import_chain = format_include_chain(&ctx.include_stack);
497− for d in &mut ctx.diagnostics[diag_count_before..] {
498− d.message = format!("{}\n in {}", d.message, import_chain);
1296+ match result {
1297+ Ok(Some(new_nodes)) => nodes.extend(new_nodes),
1298+ Ok(None) => {}
1299+ // Record the error and go on, to report several in one pass
1300+ Err(mut e) => {
1301+ e.source_line
1302+ .get_or_insert_with(|| node.source.as_str().into());
1303+ ctx.diagnostics.push(e);
1304+ }
4991305 }
500−
501− ctx.base_path = saved_base;
502− ctx.include_stack.pop();
503− return Ok(Some(included_nodes));
5041306 }
1307+ nodes
1308+ }
5051309
506− // --- @data (load JSON file into variables) ---
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> {
1313+ ctx.env.push();
1314+ let nodes = self.eval_block(block, ctx);
1315+ ctx.env.pop();
1316+ nodes
1317+ }
5071318
508− // @data $name file.json values as $name.key
509− // @data $name dir/*.json a list of the files' records
510− // @data $name [...] / {...} inline JSON
511− // @data $name env:NAME [DEFAULT] an environment variable
512− if let Some(rest) = content.strip_prefix("@data ") {
513− let rest = rest.trim();
514− let Some((prefix, filename)) = rest
515− .strip_prefix('$')
516− .and_then(|named| named.split_once(char::is_whitespace))
517− .map(|(name, source)| (name.to_string(), source.trim().to_string()))
518− else {
519− return Err(ParseError {
520− line: line_num,
521− message: format!(
522− "@data needs a name: write `@data $name {}` and use `$name.key`",
523− rest.trim_start_matches('$')
524− ),
525− });
1319+ /// `@if` with its `@else if` / `@else` branches. Every condition is
1320+ /// checked (and its errors reported); the first that holds picks the
1321+ /// branch.
1322+ fn eval_if(
1323+ &mut self,
1324+ node: &syntax::Node,
1325+ branches: &[&syntax::Node],
1326+ ctx: &mut ParseContext,
1327+ ) -> Vec<Node> {
1328+ let mut chosen = None;
1329+ for branch in std::iter::once(node).chain(branches.iter().copied()) {
1330+ ctx.visited.insert(branch.id);
1331+ ctx.enter(branch);
1332+ let holds = match branch.directive().map(|d| &d.args) {
1333+ Some(DirectiveArgs::Condition(condition))
1334+ | Some(DirectiveArgs::Else {
1335+ condition: Some(condition),
1336+ }) => {
1337+ !condition.raw.is_empty()
1338+ && ctx.condition(
1339+ &condition.raw,
1340+ branch.span.line,
1341+ Some(condition.span.column),
1342+ )
1343+ }
1344+ Some(DirectiveArgs::Else { condition: None }) => true,
1345+ // A syntax error, already reported
1346+ _ => false,
5261347 };
1348+ if holds && chosen.is_none() {
1349+ chosen = Some(&branch.children);
1350+ }
1351+ }
1352+ chosen.map_or_else(Vec::new, |body| self.eval_scoped(body, ctx))
1353+ }
1354+
1355+ fn eval(
1356+ &mut self,
1357+ node: &syntax::Node,
1358+ ctx: &mut ParseContext,
1359+ ) -> Result<Option<Vec<Node>>, ParseError> {
1360+ ctx.visited.insert(node.id);
1361+ ctx.enter(node);
1362+ match &node.kind {
1363+ NodeKind::Blank | NodeKind::Comment => Ok(None),
1364+ // `@code` and `@textarea` show their body as text; `@script`'s
1365+ // goes into the page as it is
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)])]))
1369+ }
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;
1378+ if !takes_body {
1379+ let siblings = self.eval_block(&node.children, ctx);
1380+ nodes.get_or_insert_with(Vec::new).extend(siblings);
1381+ }
1382+ Ok(nodes)
1383+ }
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
1388+ // siblings
1389+ nodes.extend(self.eval_block(&node.children, ctx));
1390+ Ok(Some(nodes))
1391+ }
1392+ }
1393+ }
5271394
528− if let Some(env) = filename.strip_prefix("env:") {
529− let (var, default) = match env.split_once(char::is_whitespace) {
530− Some((var, default)) => (var, Some(default.trim())),
531− None => (env, None),
1395+ fn eval_directive(
1396+ &mut self,
1397+ node: &syntax::Node,
1398+ directive: &syntax::Directive,
1399+ ctx: &mut ParseContext,
1400+ ) -> Result<Option<Vec<Node>>, ParseError> {
1401+ let line_num = node.span.line;
1402+ let content = &node.source;
1403+ match (directive.name(), &directive.args) {
1404+ // @page [lang=en, favicon /f.png, background #f8fafc] Title
1405+ ("page", DirectiveArgs::Page { attrs, title }) => {
1406+ let page = read_page(attrs.as_ref(), title.as_ref(), line_num, ctx);
1407+ // A page has one root: a second `@page` (a layout called
1408+ // twice, or one called after the page's own) is an error
1409+ let here = match &ctx.current_file {
1410+ Some(file) => format!("line {} of {}", line_num, file),
1411+ None => format!("line {}", line_num),
5321412 };
533− let value = std::env::var(var)
534− .ok()
535− .or_else(|| default.map(|d| substitute_vars(d, &ctx.variables)));
536− if value.is_none() {
537− ctx.diagnostics.push(Diagnostic {
538− line: line_num,
539− column: None,
540− message: format!(
541− "environment variable '{}' is not set and has no default",
542− var
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 \
1416+ twice)"
1417+ .to_string()
1418+ } else {
1419+ format!("a second @page (this page already has one, on {})", first)
1420+ };
1421+ let diagnostic = Diagnostic::error(
1422+ code::DUPLICATE_PAGE,
1423+ line_num,
1424+ format!(
1425+ "{}: a page has one @page, the root element that styles its <body>",
1426+ again
5431427 ),
544− severity: Severity::Warning,
545− source_line: Some(content.clone()),
546− });
1428+ )
1429+ .source(content.clone())
1430+ .subject("@page");
1431+ ctx.diagnostics.push(diagnostic);
1432+ } else {
1433+ ctx.page_at = Some(here);
1434+ ctx.page = Some(page);
5471435 }
548− ctx.variables.insert(prefix, value.unwrap_or_default());
549− return Ok(None);
1436+ Ok(None)
5501437 }
5511438
552− // Inline JSON: @data $links [{"label": "Home", "url": "/"}]
553− let (json_text, source) = if filename.starts_with(['[', '{']) {
554− (filename, "the inline data".to_string())
555− } else {
556− let filename = substitute_vars(&filename, &ctx.variables);
557− if filename.contains('*') {
558− self.load_data_glob(&prefix, &filename, line_num, &content, ctx);
1439+ ("let", DirectiveArgs::Let(def)) => {
1440+ let name = def.name.as_str();
1441+ // Values, bundles and functions share one namespace: a
1442+ // definition replaces whatever the name meant in its block
1443+ match &def.form {
1444+ LetForm::Function(function) => {
1445+ self.define_function(name, &function.params, node, ctx);
1446+ }
1447+ // `@let name = EXPR` computes its value (see expr.rs)
1448+ LetForm::Computed(expression) => {
1449+ let value = ctx
1450+ .eval(&expression.raw, line_num, Some(expression.span.column))
1451+ .unwrap_or_else(Value::empty);
1452+ set_variable(name, value, line_num, ctx);
1453+ }
1454+ // Attribute bundle: @let name [attr1, attr2, ...]
1455+ LetForm::Bundle(list) => {
1456+ ctx.in_bundle = true;
1457+ let attrs = parse_attr_list(&list.attrs, line_num, ctx, true, &[]);
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);
1461+ }
1462+ // `@let size 16px`, `@let fruits apple, banana`,
1463+ // `@let post $posts.0`: see `slot_value`
1464+ LetForm::Value(value) => {
1465+ let (value, _) =
1466+ ctx.slot_value(&value.raw, value.span.line, Some(value.span.column));
1467+ set_variable(name, value, line_num, ctx);
1468+ }
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);
1477+ }
1478+ }
1479+ Ok(None)
1480+ }
1481+
1482+ // @meta NAME VALUE; `og:` names become Open Graph property tags
1483+ ("meta", DirectiveArgs::Text(Some(arg))) => {
1484+ let Some((name, value)) = arg.raw.split_once(char::is_whitespace) else {
1485+ ctx.diagnostics.push(
1486+ Diagnostic::error(
1487+ code::MISSING_ARGUMENT,
1488+ line_num,
1489+ format!("@meta needs a name and a value: `@meta {} VALUE`", arg.raw),
1490+ )
1491+ .source(content.clone()),
1492+ );
5591493 return Ok(None);
1494+ };
1495+ let value_column = arg.span.column + arg.raw.len() - value.trim_start().len();
1496+ // An HTML attribute value: quoted text loses its quotes
1497+ let (value, _, _) =
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)),
1504+ };
1505+ if !tags.contains(&tag) {
1506+ tags.push(tag);
1507+ }
1508+ ctx.head_at.get_or_insert(line_num);
1509+ Ok(None)
1510+ }
1511+
1512+ ("head", _) => {
1513+ let text = verbatim_content(node);
1514+ if !text.trim().is_empty() {
1515+ ctx.head_blocks.push(text.trim().to_string());
1516+ ctx.head_at.get_or_insert(line_num);
1517+ }
1518+ Ok(None)
1519+ }
1520+
1521+ // @style: raw CSS
1522+ ("style", _) => {
1523+ let text = verbatim_content(node);
1524+ // Only the @style at the top of a function's body is
1525+ // scoped; anywhere else `&` is `:scope`, the whole page
1526+ if has_top_level_ampersand(&text) {
1527+ ctx.push_once(Diagnostic::warning(
1528+ code::INVALID_VALUE,
1529+ node.span.line,
1530+ "`&` in this @style is the whole page: only an @style at the top of a \
1531+ function's body is scoped to the function, with `&` its root element"
1532+ .to_string(),
1533+ ));
1534+ }
1535+ if !text.trim().is_empty() {
1536+ ctx.custom_css.push(text.trim().to_string());
5601537 }
561− let resolved = match &ctx.base_path {
562− Some(base) => base.join(&filename),
563− None => PathBuf::from(&filename),
1538+ Ok(None)
1539+ }
1540+
1541+ // @markdown: an indented block, or a file
1542+ ("markdown", DirectiveArgs::Text(file)) => {
1543+ let Some(file) = file else {
1544+ let md_lines: Vec<String> = verbatim_text(&node.children)
1545+ .lines()
1546+ .map(String::from)
1547+ .collect();
1548+ return Ok(Some(vec![Node::Raw(markdown_to_html(&md_lines))]));
5641549 };
565− match std::fs::read_to_string(&resolved) {
566− Ok(text) => {
567− ctx.included_files.push(resolved);
568− (text, format!("'{}'", filename))
569− }
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) {
1553+ Ok(text) => text,
5701554 Err(e) => {
571− ctx.diagnostics.push(Diagnostic {
572− line: line_num,
573− column: None,
574− message: format!("cannot load data '{}': {}", filename, e),
575− severity: Severity::Error,
576− source_line: Some(content.clone()),
577− });
1555+ ctx.diagnostics.push(
1556+ Diagnostic::error(
1557+ code::UNREADABLE_FILE,
1558+ line_num,
1559+ format!("cannot read markdown '{}': {}", filename, e),
1560+ )
1561+ .source(content.clone()),
1562+ );
5781563 return Ok(None);
5791564 }
580− }
581− };
582− match parse_json_with_error(&json_text) {
583− Ok(json) => flatten_json(&prefix, &json, &mut ctx.variables),
584− Err(detail) => ctx.diagnostics.push(Diagnostic {
585− line: line_num,
586− column: None,
587− message: format!("invalid JSON in {}: {}", source, detail),
588− severity: Severity::Error,
589− source_line: Some(content.clone()),
590− }),
1565+ };
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))]))
5911569 }
592− return Ok(None);
593− }
5941570
595− // --- @if / @else ---
1571+ ("include", DirectiveArgs::Text(Some(path))) => {
1572+ self.eval_include(node.id, path, line_num, content, ctx)
1573+ }
5961574
597− if content.trim() == "@else" || content.trim().starts_with("@else if ") {
598− return Err(ParseError {
599− line: line_num,
600− message: "@else without matching @if".to_string(),
601− });
602− }
1575+ ("data", DirectiveArgs::Data { name, source, .. }) => {
1576+ self.eval_data(name, source, line_num, content, ctx);
1577+ Ok(None)
1578+ }
6031579
604− // --- @each loop ---
1580+ // @raw: the rest of its line, or its indented body, verbatim
1581+ ("raw", _) => {
1582+ let text = verbatim_content(node);
1583+ let text = text.trim_end_matches('\n');
1584+ Ok((!text.is_empty()).then(|| vec![Node::Raw(text.to_string())]))
1585+ }
6051586
606− // @raw: its indented body, or the rest of the line, verbatim
607− if content == "@raw" {
608− let text = block_text(children);
609− let text = text.trim_end_matches('\n');
610− return Ok((!text.is_empty()).then(|| vec![Node::Raw(text.to_string())]));
611− }
612− if let Some(rest) = content.strip_prefix("@raw ") {
613− return Ok(Some(vec![Node::Raw(rest.to_string())]));
1587+ // A header with a syntax error (reported), or a directive
1588+ // without its argument
1589+ _ => Ok(None),
6141590 }
1591+ }
6151592
616− // --- Function call ---
1593+ fn eval_include(
1594+ &mut self,
1595+ id: usize,
1596+ path: &syntax::Arg,
1597+ line_num: usize,
1598+ content: &str,
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('"'))
1602+ {
1603+ Some(quoted) => (quoted, path.span.column + 1),
1604+ None => (path.raw.as_str(), path.span.column),
1605+ };
1606+ let filename = ctx.interpolate_text(filename, line_num, Some(column));
1607+ let resolved = ctx.resolve(&filename);
1608+
1609+ if ctx.include_stack.contains(&resolved) {
1610+ let cycle_chain = format_include_chain(&ctx.include_stack);
1611+ ctx.diagnostics.push(
1612+ Diagnostic::error(
1613+ code::CIRCULAR_INCLUDE,
1614+ line_num,
1615+ format!(
1616+ "circular include '{}' (cycle: {} → {})",
1617+ filename, cycle_chain, filename
1618+ ),
1619+ )
1620+ .source(content),
1621+ );
1622+ return Ok(None);
1623+ }
6171624
618− if content.starts_with('@') {
619− let name = extract_element_name(&content);
620− if ctx.functions.contains_key(name) {
621− ctx.used_functions.insert(name.to_string());
622− let nodes = self.expand_fn_call(name, &content, children, line_num, ctx)?;
623− return Ok(Some(nodes));
1625+ let imported_text = match ctx.read_file(&resolved) {
1626+ Ok(text) => text,
1627+ Err(e) => {
1628+ ctx.diagnostics.push(
1629+ Diagnostic::error(
1630+ code::UNREADABLE_FILE,
1631+ line_num,
1632+ format!("cannot include '{}': {}", filename, e),
1633+ )
1634+ .source(content),
1635+ );
1636+ return Ok(None);
6241637 }
1638+ };
1639+
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());
1644+
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()));
1653+ }
1654+ let saved_file = ctx.current_file.replace(import_chain.clone());
1655+ let defined_before: HashSet<String> = ctx
1656+ .let_lines
1657+ .keys()
1658+ .chain(ctx.define_lines.keys())
1659+ .chain(ctx.fn_lines.keys())
1660+ .cloned()
1661+ .collect();
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);
1671+
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);
6251675 }
6261676
627− // --- Elements ---
1677+ ctx.base_path = saved_base;
1678+ ctx.include_stack.pop();
1679+ Ok(Some(included_nodes))
1680+ }
6281681
629− if content.starts_with('@') {
630− let node = self.parse_element_line(&content, children, line_num, ctx)?;
631− return Ok(Some(vec![inline_svg(node, line_num, ctx)]));
1682+ /// @data $name file.json values as $name.key
1683+ /// @data $name dir/*.json a list of the files' records
1684+ /// @data $name [...] / {...} inline JSON
1685+ /// @data $name env:NAME [DEFAULT] an environment variable
1686+ fn eval_data(
1687+ &mut self,
1688+ prefix: &str,
1689+ source: &syntax::Arg,
1690+ line_num: usize,
1691+ content: &str,
1692+ ctx: &mut ParseContext,
1693+ ) {
1694+ let prefix = prefix.to_string();
1695+ let filename = source.raw.as_str();
1696+ if let Some(env) = filename.strip_prefix("env:") {
1697+ let (var, default) = match env.split_once(char::is_whitespace) {
1698+ Some((var, default)) => (var, Some(default.trim())),
1699+ None => (env, None),
1700+ };
1701+ let default_column = default.map(|d| source.span.column + filename.len() - d.len());
1702+ let value = std::env::var(var)
1703+ .ok()
1704+ .or_else(|| default.map(|d| ctx.interpolate_text(d, line_num, default_column)));
1705+ if value.is_none() {
1706+ ctx.diagnostics.push(
1707+ Diagnostic::warning(
1708+ code::UNSET_ENVIRONMENT,
1709+ line_num,
1710+ format!(
1711+ "environment variable '{}' is not set and has no default",
1712+ var
1713+ ),
1714+ )
1715+ .source(content),
1716+ );
1717+ }
1718+ ctx.bind(&prefix, Value::Str(value.unwrap_or_default()));
1719+ return;
6321720 }
6331721
634− // --- Bare text ---
635−
636− let var_warnings = check_undefined_vars(
637− &protect_escapes(&content),
638− &ctx.variables,
639− line_num,
640− current_indent,
641− );
642− ctx.diagnostics.extend(var_warnings);
643− track_var_refs(&content, &mut ctx.used_variables);
644− let segments = parse_text_segments(&content, ctx);
645− Ok(Some(vec![Node::Text(segments)]))
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())
1725+ } else {
1726+ let filename = ctx.interpolate_text(filename, line_num, Some(source.span.column));
1727+ if filename.contains('*') {
1728+ self.load_data_glob(&prefix, &filename, line_num, content, ctx);
1729+ return;
1730+ }
1731+ let resolved = ctx.resolve(&filename);
1732+ match std::fs::read_to_string(&resolved) {
1733+ Ok(text) => {
1734+ ctx.included_files.push(resolved);
1735+ (text, format!("'{}'", filename))
1736+ }
1737+ Err(e) => {
1738+ ctx.diagnostics.push(
1739+ Diagnostic::error(
1740+ code::UNREADABLE_FILE,
1741+ line_num,
1742+ format!("cannot load data '{}': {}", filename, e),
1743+ )
1744+ .source(content),
1745+ );
1746+ return;
1747+ }
1748+ }
1749+ };
1750+ match parse_json_with_error(&json_text) {
1751+ Ok(json) => ctx.bind(&prefix, json_value(json)),
1752+ Err(detail) => ctx.diagnostics.push(
1753+ Diagnostic::error(
1754+ code::INVALID_JSON,
1755+ line_num,
1756+ format!("invalid JSON in {}: {}", source, detail),
1757+ )
1758+ .source(content),
1759+ ),
1760+ }
6461761 }
6471762
6481763 /// `@data $name dir/*.json`: a list with one record per matching file
@@ -676,13 +1791,15 @@ impl Evaluator {
6761791 })
6771792 .collect(),
6781793 Err(e) => {
679− ctx.diagnostics.push(Diagnostic {
680− line: line_num,
681− column: None,
682− message: format!("cannot read directory for '{}': {}", pattern, e),
683− severity: Severity::Error,
684− source_line: Some(content.to_string()),
685− });
1794+ ctx.diagnostics.push(
1795+ Diagnostic::new(
1796+ code::UNREADABLE_FILE,
1797+ Severity::Error,
1798+ line_num,
1799+ format!("cannot read directory for '{}': {}", pattern, e),
1800+ )
1801+ .source(content.to_string()),
1802+ );
6861803 return;
6871804 }
6881805 };
@@ -697,13 +1814,15 @@ impl Evaluator {
6971814 let text = match std::fs::read_to_string(&file) {
6981815 Ok(text) => text,
6991816 Err(e) => {
700− ctx.diagnostics.push(Diagnostic {
701− line: line_num,
702− column: None,
703− message: format!("cannot load data '{}': {}", file.display(), e),
704− severity: Severity::Error,
705− source_line: Some(content.to_string()),
706− });
1817+ ctx.diagnostics.push(
1818+ Diagnostic::new(
1819+ code::UNREADABLE_FILE,
1820+ Severity::Error,
1821+ line_num,
1822+ format!("cannot load data '{}': {}", file.display(), e),
1823+ )
1824+ .source(content.to_string()),
1825+ );
7071826 continue;
7081827 }
7091828 };
@@ -714,253 +1833,424 @@ impl Evaluator {
7141833 }
7151834 records.push(JsonValue::Object(pairs));
7161835 }
717− Ok(_) => ctx.diagnostics.push(Diagnostic {
718− line: line_num,
719− column: None,
720− message: format!("'{}' should hold a JSON object", file.display()),
721− severity: Severity::Error,
722− source_line: Some(content.to_string()),
723− }),
724− Err(detail) => ctx.diagnostics.push(Diagnostic {
725− line: line_num,
726− column: None,
727− message: format!("invalid JSON in '{}': {}", file.display(), detail),
728− severity: Severity::Error,
729− source_line: Some(content.to_string()),
730− }),
1836+ Ok(_) => ctx.diagnostics.push(
1837+ Diagnostic::new(
1838+ code::INVALID_JSON,
1839+ Severity::Error,
1840+ line_num,
1841+ format!("'{}' should hold a JSON object", file.display()),
1842+ )
1843+ .source(content.to_string()),
1844+ ),
1845+ Err(detail) => ctx.diagnostics.push(
1846+ Diagnostic::new(
1847+ code::INVALID_JSON,
1848+ Severity::Error,
1849+ line_num,
1850+ format!("invalid JSON in '{}': {}", file.display(), detail),
1851+ )
1852+ .source(content.to_string()),
1853+ ),
7311854 }
7321855 ctx.included_files.push(file);
7331856 }
734− flatten_json(name, &JsonValue::Array(records), &mut ctx.variables);
1857+ ctx.bind(name, json_value(JsonValue::Array(records)));
7351858 }
7361859
737− /// `@each $item in LIST` or `@each $item, $index in LIST`. A LIST from
738− /// JSON binds each record or value to `$item`; any other list is text,
739− /// split on commas, or a range `A..B [step N]`.
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.
7401865 fn eval_each(
7411866 &mut self,
742− header: &str,
743− body: &[Syntax],
744− empty: &[Syntax],
745− line_num: usize,
1867+ node: &syntax::Node,
1868+ empty_branch: Option<&syntax::Node>,
7461869 ctx: &mut ParseContext,
747− ) -> Result<Vec<Node>, ParseError> {
748− let Some((names, list_src)) = header.split_once(" in ") else {
749− return Err(ParseError {
750− line: line_num,
751− message: "@each requires: @each $item in LIST".to_string(),
752− });
753− };
754− let names: Vec<&str> = names
755− .split(',')
756− .map(|v| v.trim().trim_start_matches('$'))
757− .collect();
758− if names.len() > 2 {
759− return Err(ParseError {
760− line: line_num,
761− message: "@each takes `$item` or `$item, $index`: to loop over records, \
762− load them with @data and use `$item.key`"
763− .to_string(),
764− });
1870+ ) -> Result<Option<Vec<Node>>, ParseError> {
1871+ ctx.visited.insert(node.id);
1872+ if let Some(branch) = empty_branch {
1873+ ctx.visited.insert(branch.id);
7651874 }
766− let (item, index) = (names[0], names.get(1).copied());
767− let list_src = list_src.trim();
768− track_var_refs(list_src, &mut ctx.used_variables);
769−
770− // A list loaded from JSON, by name
771− let data_list = list_src.strip_prefix('$').and_then(|name| {
772− let len = ctx
773− .variables
774− .get(&format!("{}#", name))?
775− .parse::<usize>()
776− .ok()?;
777− Some((name.to_string(), len))
778− });
779− let undefined = list_src.strip_prefix('$').filter(|name| {
780− name.chars()
781− .all(|c| c.is_alphanumeric() || matches!(c, '_' | '-' | '.'))
782− && !ctx.variables.contains_key(*name)
783− });
784− let text_items: Vec<String> = match (&data_list, undefined) {
785− (Some(_), _) => Vec::new(),
786− // A missing variable is an empty list: quietly for a record's
787− // missing field (`$post.tags`), with a warning otherwise
788− (None, Some(name)) => {
789− let root = name.split('.').next().unwrap_or(name);
790− if !ctx.variables.contains_key(root) {
791− ctx.diagnostics.push(Diagnostic {
792− line: line_num,
793− column: None,
794− message: format!("undefined variable '${}'", name),
795− severity: Severity::Warning,
796− source_line: Some(format!("@each {}", header)),
797− });
1875+ ctx.enter(node);
1876+ // A malformed header is a syntax error, already reported
1877+ let Some(DirectiveArgs::Each(header)) = node.directive().map(|d| &d.args) else {
1878+ return Ok(None);
1879+ };
1880+ let body = &node.children;
1881+ let empty: &[syntax::Node] = empty_branch.map_or(&[], |b| &b.children);
1882+ let (item, index) = (header.item.as_str(), header.index.as_deref());
1883+ let list = &header.list;
1884+ // `[...]` is an attribute list or JSON elsewhere, not a list here
1885+ let bracketed = list.raw.starts_with('[') && list.raw.ends_with(']');
1886+ let (source, filled) = match bracketed {
1887+ true => (Value::empty(), false),
1888+ false => ctx.slot_value(&list.raw, list.span.line, Some(list.span.column)),
1889+ };
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())
7981897 }
1898+ _ => diagnostic,
1899+ }
1900+ };
1901+ if bracketed {
1902+ let inner = list.raw[1..list.raw.len() - 1].trim().to_string();
1903+ let diagnostic = not_a_list(
1904+ format!(
1905+ "@each takes a list written without brackets, `@each ${} in {}`; \
1906+ JSON data goes in `@data`",
1907+ item, inner
1908+ ),
1909+ ctx,
1910+ )
1911+ .suggest(Some(inner));
1912+ ctx.push_once(diagnostic);
1913+ }
1914+ let items: Vec<Value> = match source {
1915+ Value::List(list) => list.items.to_vec(),
1916+ // Reported (an undefined `$name`, brackets): there is nothing
1917+ // to repeat
1918+ _ if !filled => Vec::new(),
1919+ Value::Record(_) => {
1920+ let diagnostic = not_a_list(
1921+ format!(
1922+ "@each repeats for the items of a list, and `{}` is a record: \
1923+ loop over a list of records, or use its fields",
1924+ list.raw
1925+ ),
1926+ ctx,
1927+ );
1928+ ctx.push_once(diagnostic);
7991929 Vec::new()
8001930 }
801− (None, None) => text_list_items(&substitute_vars(list_src, &ctx.variables)),
1931+ // Empty text (a field a record doesn't have) is no items; any
1932+ // other value is one
1933+ value if value.to_string().is_empty() => Vec::new(),
1934+ value => vec![value],
8021935 };
803− let count = data_list.as_ref().map_or(text_items.len(), |(_, len)| *len);
8041936
805− if body.is_empty() {
806− return Ok(Vec::new());
1937+ if body.iter().all(syntax::Node::is_trivia) {
1938+ return Ok(Some(Vec::new()));
8071939 }
808− if count == 0 {
809− return Ok(self.eval_scoped(empty, ctx));
1940+ if items.is_empty() {
1941+ return Ok(Some(self.eval_scoped(empty, ctx)));
8101942 }
811− let saved_vars = ctx.variables.clone();
8121943 let mut nodes = Vec::new();
813− for i in 0..count {
814− match &data_list {
815− Some((name, _)) => bind_item(&mut ctx.variables, &format!("{}.{}", name, i), item),
816− None => {
817− let text = text_items.get(i).cloned().unwrap_or_default();
818− ctx.variables.insert(item.to_string(), text);
819− }
820− }
1944+ for (i, value) in items.into_iter().enumerate() {
1945+ ctx.env.push();
1946+ ctx.bind(item, value);
8211947 if let Some(index) = index {
822− ctx.variables.insert(index.to_string(), i.to_string());
1948+ ctx.bind(index, Value::Num(i as f64));
8231949 }
8241950 nodes.extend(self.eval_block(body, ctx));
1951+ ctx.env.pop();
8251952 }
826− ctx.variables = saved_vars;
827− Ok(nodes)
1953+ Ok(Some(nodes))
8281954 }
8291955
8301956 fn define_function(
8311957 &mut self,
8321958 name: &str,
833− params: &[String],
834− defaults: &HashMap<String, String>,
835− body: &[Syntax],
836− line_num: usize,
1959+ params: &[syntax::Param],
1960+ node: &syntax::Node,
8371961 ctx: &mut ParseContext,
8381962 ) {
1963+ let line_num = node.span.line;
1964+ let body = &node.children;
8391965 // An @style block at the top of the body is scoped to the
840− // function: its rules apply inside a `.hl-NAME` wrapper.
841− let (style, body): (Vec<&Syntax>, Vec<&Syntax>) = body
842− .iter()
843− .partition(|node| matches!(node, Syntax::Line { text, .. } if text == "@style"));
844− if !style.is_empty() {
1966+ // function: its rules apply inside a `.hl-fn-NAME` wrapper (a
1967+ // generated class never has a second `-`, so the two can't meet).
1968+ // It is written into the page when the function is called.
1969+ let (style, body): (Vec<&syntax::Node>, Vec<&syntax::Node>) =
1970+ body.iter().partition(|node| node.is_directive("style"));
1971+ let scoped = (!style.is_empty()).then(|| {
8451972 let css: String = style
8461973 .iter()
847− .filter_map(|node| match node {
848− Syntax::Line { children, .. } => Some(block_text(children)),
849− _ => None,
1974+ .map(|node| {
1975+ ctx.visited.insert(node.id);
1976+ verbatim_content(node)
8501977 })
8511978 .collect();
8521979 // Nested under the scope class, so any CSS works (multi-line
8531980 // rules, at-rules)
854− if !css.trim().is_empty() {
855− ctx.custom_css.push(format!(".hl-{} {{\n{}}}", name, css));
1981+ if css.trim().is_empty() {
1982+ String::new()
1983+ } else {
1984+ format!(".hl-fn-{} {{\n{}}}", name, css)
8561985 }
857− ctx.scoped_functions.insert(name.to_string());
858− }
1986+ });
8591987
1988+ // A default is filled in only when a call leaves its parameter
1989+ // out, so the names in it count as used here
1990+ for default in params.iter().filter_map(|p| p.default.as_ref()) {
1991+ track_var_refs(default, &mut ctx.used_variables);
1992+ }
8601993 ctx.fn_lines.entry(name.to_string()).or_insert(line_num);
861− ctx.functions.insert(
862− name.to_string(),
863− FnDef {
864− params: params.to_vec(),
865− defaults: defaults.clone(),
866− body: body.into_iter().cloned().collect(),
867− },
868− );
1994+ let wraps_itself = ElementKind::from_name(name).is_some()
1995+ && body.iter().any(|node| calls_unguarded(node, name));
1996+ if wraps_itself {
1997+ ctx.push_once(
1998+ Diagnostic::error(
1999+ code::RECURSIVE_CALL,
2000+ line_num,
2001+ format!(
2002+ "@{0} in the body of `@let @{0}` calls the function itself, not the \
2003+ element @{0}, so it would never stop: give the function another name \
2004+ (such as @site-{0})",
2005+ name
2006+ ),
2007+ )
2008+ .subject(name),
2009+ );
2010+ }
2011+ for node in &body {
2012+ node.walk(&mut |node| {
2013+ if let Some(d) = marker_in_text(node) {
2014+ ctx.push_once(d);
2015+ }
2016+ });
2017+ }
2018+ let body: Vec<syntax::Node> = body.into_iter().cloned().collect();
2019+ let (slots, has_children) = declared_slots(&body, ctx);
2020+ let function = Rc::new(FnDef {
2021+ params: params.to_vec(),
2022+ line: line_num,
2023+ source: ctx.current_source.1.clone(),
2024+ node: node.id,
2025+ body,
2026+ file: ctx.current_file.clone(),
2027+ slots,
2028+ has_children,
2029+ scoped,
2030+ env: ctx.env.clone(),
2031+ wraps_itself,
2032+ });
2033+ ctx.defined_functions
2034+ .insert(name.to_string(), function.clone());
2035+ ctx.env.define(name, Binding::Function(function));
8692036 }
8702037
871− fn expand_fn_call(
2038+ /// An element line: a chain of elements and function calls, the last of
2039+ /// which gets the indented children.
2040+ fn eval_element(
8722041 &mut self,
873− name: &str,
874− content: &str,
875− children: &[Syntax],
876− line_num: usize,
2042+ node: &syntax::Node,
2043+ element: &syntax::ElementLine,
8772044 ctx: &mut ParseContext,
8782045 ) -> Result<Vec<Node>, ParseError> {
879− // Recursive function cycle detection
880− if ctx.fn_call_stack.contains(&name.to_string()) {
881− return Err(ParseError {
882− line: line_num,
883− message: format!(
884− "recursive function call to @{} (call stack: {})",
885− name,
886− ctx.fn_call_stack.join(" -> ")
887− ),
888− });
2046+ // An unclosed attribute list is a syntax error, already reported
2047+ if element
2048+ .chain
2049+ .iter()
2050+ .any(|h| h.attrs.as_ref().is_some_and(|a| !a.closed))
2051+ {
2052+ return Ok(Vec::new());
8892053 }
890− ctx.fn_call_stack.push(name.to_string());
891−
892− // Parse [param value, ...] arguments
893− let rest = &content[1 + name.len()..];
894− let rest = rest.trim_start();
895−
896− let (args, trailing_text) = if rest.starts_with('[') {
897− parse_attr_brackets_no_validate(rest, line_num, ctx)?
898− } else {
899− (Vec::new(), rest.to_string())
900− };
2054+ let line_num = node.span.line;
2055+ let last = element.chain.len() - 1;
2056+ // Each head is read where it is written, left to right. The
2057+ // children belong to the last one, so the chain is built right to
2058+ // left, each link wrapping the next.
2059+ let mut links = Vec::new();
2060+ for (i, head) in element.chain.iter().enumerate() {
2061+ let text = if i == last {
2062+ element.text.as_ref()
2063+ } else {
2064+ None
2065+ };
2066+ links.push(resolve(head, text, line_num, &node.source, ctx)?);
2067+ }
2068+ let calls: Vec<Option<(String, Rc<FnDef>)>> = links
2069+ .iter()
2070+ .map(|link| match link {
2071+ Resolved::Call(call) => Some((call.name.clone(), call.function.clone())),
2072+ Resolved::Element(_) => None,
2073+ })
2074+ .collect();
2075+ let mut current = self.eval_scoped(&node.children, ctx);
2076+ // After the lines under the call ran, so the files they include
2077+ // are read
2078+ check_fillers(node, element, &calls, ctx);
2079+ for link in links.into_iter().rev() {
2080+ current = self.complete(link, current, ctx)?;
2081+ }
2082+ Ok(current)
2083+ }
9012084
902− // Clone function definition (releases borrow on ctx). If the function is
903− // missing (shouldn't normally happen — callers check ctx.functions.contains_key
904− // first — but we avoid panicking on malformed state).
905− let fn_def = match ctx.functions.get(name) {
906− Some(def) => def.clone(),
907− None => {
908− ctx.fn_call_stack.pop();
909− return Err(ParseError {
910− line: line_num,
911− message: format!("undefined function @{}", name),
912− });
2085+ /// Give a resolved `@name` its children: an element holds them, and a
2086+ /// function's body puts them where its `@children` is.
2087+ fn complete(
2088+ &mut self,
2089+ resolved: Resolved,
2090+ children: Vec<Node>,
2091+ ctx: &mut ParseContext,
2092+ ) -> Result<Vec<Node>, ParseError> {
2093+ match resolved {
2094+ Resolved::Element(mut element) => {
2095+ element.children.extend(children);
2096+ let line = element.line_num;
2097+ Ok(vec![inline_svg(Node::Element(element), line, ctx)])
9132098 }
914− };
2099+ Resolved::Call(call) => self.expand_fn_call(*call, children, ctx),
2100+ }
2101+ }
9152102
916− // Parse caller's children, separating named slots from default children
917− let all_caller_children = self.eval_block(children, ctx);
2103+ fn expand_fn_call(
2104+ &mut self,
2105+ call: Call,
2106+ all_caller_children: Vec<Node>,
2107+ ctx: &mut ParseContext,
2108+ ) -> Result<Vec<Node>, ParseError> {
2109+ let Call {
2110+ name,
2111+ function: fn_def,
2112+ args,
2113+ values,
2114+ text: trailing_text,
2115+ written_form,
2116+ written_keys,
2117+ line: line_num,
2118+ name_at,
2119+ source: content,
2120+ } = call;
2121+ let (name, content) = (name.as_str(), content.as_str());
2122+
2123+ // Separate the caller's `@slot NAME` blocks from its other
2124+ // children. A block for a slot the function doesn't declare was
2125+ // reported where it is written (see `check_fillers`), like one
2126+ // without a name.
9182127 let mut slot_contents: HashMap<String, Vec<Node>> = HashMap::new();
9192128 let mut caller_children = Vec::new();
9202129 for child in all_caller_children {
921− if let Node::Element(ref elem) = child
922− && let ElementKind::Slot(ref slot_name) = elem.kind
923− && !slot_name.is_empty()
924− {
925− slot_contents
926− .entry(slot_name.clone())
927− .or_default()
928− .extend(elem.children.clone());
2130+ if let Node::Element(elem) = child {
2131+ match elem.kind {
2132+ ElementKind::Slot(slot_name) => {
2133+ slot_contents
2134+ .entry(slot_name)
2135+ .or_default()
2136+ .extend(elem.children);
2137+ }
2138+ kind => caller_children.push(Node::Element(Element { kind, ..elem })),
2139+ }
9292140 continue;
9302141 }
9312142 caller_children.push(child);
9322143 }
9332144 // Text after the call, as in `@card [color red] New`, is content:
934− // it goes first among the caller's children.
935− let trailing_text = trailing_text.trim();
936− if !trailing_text.is_empty() {
937− caller_children.insert(0, Node::Text(parse_text_segments(trailing_text, ctx)));
2145+ // it goes first among the caller's children, and like them it is
2146+ // evaluated where the call is written.
2147+ if let Some(text) = &trailing_text {
2148+ caller_children.insert(0, Node::Text(text_segments(text, ctx)));
2149+ }
2150+ // Content goes where the body's `@children` is: without one, it
2151+ // would be dropped
2152+ if !fn_def.has_children && !caller_children.is_empty() {
2153+ let (column, text) = match &name_at {
2154+ Some((column, text)) => (Some(*column), text.as_str()),
2155+ None => (None, content),
2156+ };
2157+ ctx.push_once(no_children(name, line_num, column).source(text));
9382158 }
9392159
940− // Save variable state, inject function parameters
941− let saved_vars = ctx.variables.clone();
2160+ if fn_def.wraps_itself {
2161+ return Ok(Vec::new());
2162+ }
2163+ // Only the body is inside the call, so a function may appear in the
2164+ // content its caller passes it. A function may call itself, under
2165+ // a condition that stops it; one that doesn't stop goes too deep.
2166+ if ctx.too_deep {
2167+ return Ok(Vec::new());
2168+ }
2169+ if ctx.fn_call_stack.len() >= MAX_CALL_DEPTH {
2170+ ctx.too_deep = true;
2171+ return Err(too_deep(name, &ctx.fn_call_stack, line_num).source(content));
2172+ }
2173+ let caller = (
2174+ ctx.current_line,
2175+ ctx.current_source.clone(),
2176+ ctx.current_node,
2177+ );
2178+ ctx.fn_call_stack.push(name.to_string());
2179+
2180+ // The body runs where the function is defined: it sees what was
2181+ // visible there, the function itself (so it can call itself), and
2182+ // its parameters, bound by name in the order they are declared. A
2183+ // default is filled in at the call, seeing the same, with the
2184+ // parameters before it.
2185+ let caller_env = std::mem::replace(&mut ctx.env, fn_def.env.clone());
2186+ ctx.env.push();
2187+ ctx.env.define(name, Binding::Function(fn_def.clone()));
9422188 let mut consumed = vec![false; args.len()];
943− for (i, param) in fn_def.params.iter().enumerate() {
944− let named = args.iter().position(|a| a.key == *param);
945− // Positional fallback, unless that argument is named for a
946− // different parameter.
947− let positional = args
948− .get(i)
949− .filter(|a| !fn_def.params.contains(&a.key) && a.value.is_some())
950− .map(|_| i);
951− let value = named
952− .filter(|&j| args[j].value.is_some())
953− .or(positional)
954− .and_then(|j| {
955− consumed[j] = true;
956− args[j].value.clone()
957− })
958− .or_else(|| fn_def.defaults.get(param).cloned())
959− .unwrap_or_default();
960− if let Some(j) = named {
2189+ for param in &fn_def.params {
2190+ let mut passed = None;
2191+ for (j, arg) in args.iter().enumerate() {
2192+ if arg.key != param.name {
2193+ continue;
2194+ }
9612195 consumed[j] = true;
2196+ // The later one wins, as for any attribute: one written
2197+ // after a bundle overrides it, and only one written twice
2198+ // in the call's own list is reported
2199+ if passed.is_some() && written_keys.iter().filter(|k| **k == param.name).count() > 1
2200+ {
2201+ ctx.push_once(
2202+ Diagnostic::warning(
2203+ code::DUPLICATE_ATTRIBUTE,
2204+ line_num,
2205+ format!(
2206+ "parameter '{}' of @{} is passed twice: the later one wins",
2207+ param.name, name
2208+ ),
2209+ )
2210+ .source(content)
2211+ .subject(param.name.as_str()),
2212+ );
2213+ }
2214+ // Written `name=value` in the call's own list is reported
2215+ // as written; this is one from a bundle
2216+ if arg.html && !written_form.contains(&arg.key) {
2217+ let value = arg.value.as_deref().unwrap_or("");
2218+ ctx.push_once(parameter_form(name, &arg.key, value, line_num).source(content));
2219+ }
2220+ passed = Some(j);
9622221 }
963− ctx.variables.insert(param.clone(), value);
2222+ let value = match passed {
2223+ // A parameter's name alone is true: `@post-card [featured]`
2224+ Some(j) if args[j].value.is_none() => Value::Bool(true),
2225+ // What the call passed, with its type: a record, a list,
2226+ // quoted text
2227+ Some(j) => values[j].clone().unwrap_or_else(|| {
2228+ let arg = &args[j];
2229+ match &arg.quoted {
2230+ Some(quoted) => Value::Quoted(quoted.clone()),
2231+ None => Value::Str(arg.value.clone().unwrap_or_default()),
2232+ }
2233+ }),
2234+ None => match ¶m.default {
2235+ Some(default) => {
2236+ let before = ctx.diagnostics.len();
2237+ let value = fill_default(&fn_def, param, default, ctx);
2238+ point_at_call(ctx, before, &fn_def, name, line_num, content);
2239+ value
2240+ }
2241+ None => {
2242+ let (column, text) = match &name_at {
2243+ Some((column, text)) => (Some(*column), text.as_str()),
2244+ None => (None, content),
2245+ };
2246+ ctx.push_once(
2247+ missing_parameter(name, ¶m.name, line_num, column).source(text),
2248+ );
2249+ Value::empty()
2250+ }
2251+ },
2252+ };
2253+ ctx.bind(¶m.name, value);
9642254 }
9652255 // Arguments that aren't parameters are attributes for the
9662256 // function's root element, so a function can be styled like an
@@ -972,12 +2262,24 @@ impl Evaluator {
9722262 .map(|(a, _)| a.clone())
9732263 .collect();
9742264
975− // Evaluate the body with the parameters in scope
976− let body_nodes = self.eval_block(&fn_def.body, ctx);
2265+ // Evaluate the body with the parameters in scope, as lines of the
2266+ // file that defines the function
2267+ let caller_file = std::mem::replace(&mut ctx.current_file, fn_def.file.clone());
2268+ let before = ctx.diagnostics.len();
2269+ let mut body_nodes = self.eval_block(&fn_def.body, ctx);
2270+ ctx.current_file = caller_file;
2271+ point_at_call(ctx, before, &fn_def, name, line_num, content);
9772272
978− // Restore variables and call stack
979− ctx.variables = saved_vars;
2273+ // Back to the caller's names and call stack
2274+ ctx.env = caller_env;
9802275 ctx.fn_call_stack.pop();
2276+ if ctx.fn_call_stack.is_empty() {
2277+ ctx.too_deep = false;
2278+ }
2279+ (ctx.current_line, ctx.current_source, ctx.current_node) = caller;
2280+
2281+ // What the body wrote is the call's
2282+ belongs_to_call(&mut body_nodes, name, line_num);
9812283
9822284 // Replace @children with caller's children and @slot with slot content
9832285 let mut result_nodes =
@@ -985,10 +2287,7 @@ impl Evaluator {
9852287
9862288 // Attributes that aren't parameters style the function's root
9872289 // element, and a scoped @style's class goes on it too.
988− let scope_class = ctx
989− .scoped_functions
990− .contains(name)
991− .then(|| format!("hl-{}", name));
2290+ let scope_class = fn_def.scoped.is_some().then(|| format!("hl-fn-{}", name));
9922291 if !forwarded.is_empty() || scope_class.is_some() {
9932292 let mut roots = result_nodes.iter_mut().filter_map(|n| match n {
9942293 Node::Element(e) => Some(e),
@@ -1001,7 +2300,33 @@ impl Evaluator {
10012300 let mut problems = Vec::new();
10022301 match root {
10032302 Some(root) => {
1004− root.attrs.extend(forwarded);
2303+ // A call's `class=` adds to the root's own classes
2304+ for attr in forwarded {
2305+ let existing = (attr.html && attr.key == "class")
2306+ .then(|| root.attrs.iter_mut().find(|a| a.html && a.key == "class"))
2307+ .flatten();
2308+ match existing {
2309+ Some(class) => {
2310+ let mut value = class.value.take().unwrap_or_default();
2311+ for name in attr.value.as_deref().unwrap_or("").split_whitespace() {
2312+ if !value.split_whitespace().any(|c| c == name) {
2313+ value.push(' ');
2314+ value.push_str(name);
2315+ }
2316+ }
2317+ class.value = Some(value.trim().to_string());
2318+ }
2319+ None => root.attrs.push(attr),
2320+ }
2321+ }
2322+ // The scoped `@style` goes into the page once, when the
2323+ // function is first called
2324+ if let Some(css) = &fn_def.scoped
2325+ && !css.is_empty()
2326+ && !ctx.scoped_css.contains(css)
2327+ {
2328+ ctx.scoped_css.push(css.clone());
2329+ }
10052330 if let Some(class) = scope_class {
10062331 match root.attrs.iter_mut().find(|a| a.html && a.key == "class") {
10072332 Some(attr) => {
@@ -1013,6 +2338,7 @@ impl Evaluator {
10132338 key: "class".to_string(),
10142339 value: Some(class),
10152340 html: true,
2341+ quoted: None,
10162342 }),
10172343 }
10182344 }
@@ -1040,52 +2366,586 @@ impl Evaluator {
10402366 }
10412367 }
10422368 for message in problems {
1043− ctx.diagnostics.push(Diagnostic {
1044− line: line_num,
1045− column: None,
1046− message,
1047− severity: Severity::Warning,
1048− source_line: Some(content.to_string()),
1049− });
2369+ ctx.diagnostics.push(
2370+ Diagnostic::error(code::NO_SINGLE_ROOT, line_num, message)
2371+ .source(content)
2372+ .subject(name),
2373+ );
10502374 }
10512375 }
10522376
10532377 Ok(result_nodes)
10542378 }
2379+}
10552380
1056− fn parse_element_line(
1057− &mut self,
1058− content: &str,
1059− children: &[Syntax],
1060− line_num: usize,
1061− ctx: &mut ParseContext,
1062− ) -> Result<Node, ParseError> {
1063− let segments = split_chain(content);
2381+/// A `@name` read where it is written: a built-in element, or a call.
2382+enum Resolved {
2383+ Element(Element),
2384+ Call(Box<Call>),
2385+}
2386+
2387+/// A call of a function, with its arguments evaluated where it is written.
2388+struct Call {
2389+ name: String,
2390+ function: Rc<FnDef>,
2391+ args: Vec<Attribute>,
2392+ /// The value of each argument that passes a parameter, with its type
2393+ /// (see [`ParseContext::slot_value`]), in the order of `args`.
2394+ values: Vec<Option<Value>>,
2395+ /// Text after the attributes, which is content.
2396+ text: Option<syntax::Text>,
2397+ /// Parameters written `name=value`, already reported.
2398+ written_form: Vec<String>,
2399+ /// The keys written in the call's own list, not from a bundle.
2400+ written_keys: Vec<String>,
2401+ line: usize,
2402+ /// The column of the call's name and the line it is on, for a missing
2403+ /// parameter.
2404+ name_at: Option<(usize, String)>,
2405+ /// The line as written, for diagnostics.
2406+ source: String,
2407+}
2408+
2409+/// What `@name` is where it is written: a call of the function `name`
2410+/// when one is defined, else the built-in element. A whole line, each link
2411+/// of a chain and an inline element in text all resolve here.
2412+fn resolve(
2413+ head: &syntax::Head,
2414+ text: Option<&syntax::Text>,
2415+ line: usize,
2416+ source: &str,
2417+ ctx: &mut ParseContext,
2418+) -> Result<Resolved, ParseError> {
2419+ let Some(function) = ctx.env.function(&head.name).cloned() else {
2420+ return parse_single_element(head, text, line, ctx).map(Resolved::Element);
2421+ };
2422+ ctx.used_functions.insert(head.name.clone());
2423+ let params: Vec<String> = function.params.iter().map(|p| p.name.clone()).collect();
2424+ let written = head.attrs.as_ref().map_or(&[][..], |list| &list.attrs[..]);
2425+ let written_form = written_parameter_forms(&head.name, &function, written, line, ctx);
2426+ let written_keys = written.iter().map(|a| a.key.clone()).collect();
2427+ // Parameters are bound by name; every other attribute goes to the
2428+ // root element, and is checked like any attribute
2429+ let (args, values) = parse_attrs(written, line, ctx, true, ¶ms)
2430+ .into_iter()
2431+ .unzip();
2432+ let name_at = name_column(head, line).zip(match &ctx.current_source {
2433+ (current, Some(text)) if *current == line => Some(text.clone()),
2434+ _ => None,
2435+ });
2436+ Ok(Resolved::Call(Box::new(Call {
2437+ name: head.name.clone(),
2438+ function,
2439+ args,
2440+ values,
2441+ text: text.cloned(),
2442+ written_form,
2443+ written_keys,
2444+ line,
2445+ name_at,
2446+ source: source.to_string(),
2447+ })))
2448+}
2449+
2450+/// A line of another file (the standard library, an included file) means
2451+/// nothing in this one: the problems reported since `before` while
2452+/// evaluating the function (its body, a default) are moved to the call.
2453+fn point_at_call(
2454+ ctx: &mut ParseContext,
2455+ before: usize,
2456+ function: &FnDef,
2457+ name: &str,
2458+ line: usize,
2459+ source: &str,
2460+) {
2461+ if function.file == ctx.current_file {
2462+ return;
2463+ }
2464+ let defined_in = function
2465+ .file
2466+ .as_deref()
2467+ .unwrap_or("the file being compiled");
2468+ for d in &mut ctx.diagnostics[before..] {
2469+ d.message = format!(
2470+ "{}\n in @{} (line {} of {})",
2471+ d.message, name, d.line, defined_in
2472+ );
2473+ d.line = line;
2474+ d.column = None;
2475+ d.subject = None;
2476+ d.suggestion = None;
2477+ d.source_line = Some(source.into());
2478+ }
2479+}
2480+
2481+/// A call nested deeper than [`MAX_CALL_DEPTH`].
2482+fn too_deep(name: &str, stack: &[String], line: usize) -> Diagnostic {
2483+ let message = if stack.iter().any(|n| n == name) {
2484+ format!(
2485+ "recursive function call to @{} goes more than {} calls deep: a function that \
2486+ calls itself needs a condition that stops it (`@if`)",
2487+ name, MAX_CALL_DEPTH
2488+ )
2489+ } else {
2490+ format!(
2491+ "function calls nest more than {} deep at @{} (starting with {})",
2492+ MAX_CALL_DEPTH,
2493+ name,
2494+ stack
2495+ .iter()
2496+ .take(3)
2497+ .map(|n| format!("@{}", n))
2498+ .collect::<Vec<_>>()
2499+ .join(" → ")
2500+ )
2501+ };
2502+ Diagnostic::error(code::RECURSIVE_CALL, line, message).subject(name)
2503+}
2504+
2505+/// Mark what a function's body wrote as the call's: it gets the call's
2506+/// line, so what is reported about it points at the call, and the name of
2507+/// the function, unless a call inside the body already claimed it.
2508+fn belongs_to_call(nodes: &mut [Node], function: &str, line: usize) {
2509+ fn claim(element: &mut Element, function: &str, line: usize) {
2510+ element.line_num = line;
2511+ element.function.get_or_insert_with(|| function.to_string());
2512+ belongs_to_call(&mut element.children, function, line);
2513+ }
2514+ for node in nodes {
2515+ match node {
2516+ Node::Element(element) => claim(element, function, line),
2517+ Node::Text(segments) => {
2518+ for segment in segments {
2519+ if let TextSegment::Inline(element) = segment {
2520+ claim(element, function, line);
2521+ }
2522+ }
2523+ }
2524+ Node::Raw(_) => {}
2525+ }
2526+ }
2527+}
10642528
1065− // Parse each segment into an Element
1066− let mut elements: Vec<Element> = Vec::new();
1067− for seg in &segments {
1068− let elem = parse_single_element(seg.trim(), line_num, ctx)?;
1069− elements.push(elem);
2529+/// What an inline `{@name ...}` stands for in its line of text: an
2530+/// element; the text of a function whose body is text; or, for a body with
2531+/// several roots, its nodes as a fragment.
2532+fn inline_segments(mut nodes: Vec<Node>, line: usize) -> Vec<TextSegment> {
2533+ if let [Node::Element(_)] = nodes.as_slice()
2534+ && let Some(Node::Element(element)) = nodes.pop()
2535+ {
2536+ return vec![TextSegment::Inline(element)];
2537+ }
2538+ if nodes.iter().all(|n| matches!(n, Node::Text(_))) {
2539+ let mut segments = Vec::new();
2540+ for node in nodes {
2541+ if let Node::Text(run) = node {
2542+ if !segments.is_empty() {
2543+ segments.push(TextSegment::Plain(" ".to_string()));
2544+ }
2545+ segments.extend(run);
2546+ }
10702547 }
2548+ return segments;
2549+ }
2550+ vec![TextSegment::Inline(Element {
2551+ kind: ElementKind::Fragment,
2552+ attrs: Vec::new(),
2553+ argument: None,
2554+ children: nodes,
2555+ line_num: line,
2556+ function: None,
2557+ })]
2558+}
10712559
1072− // Parse indented children (belong to the innermost element)
1073− let children = self.eval_block(children, ctx);
2560+/// Fill in the default of a parameter that a call leaves out, like the
2561+/// value of an attribute passed for it: variables are filled in, one
2562+/// `$name` keeps its type and one `"..."` is quoted text. It sees what the
2563+/// body sees: the names visible where the function is defined, and the
2564+/// parameters before it. Its problems are reported at the definition, once.
2565+fn fill_default(
2566+ fn_def: &FnDef,
2567+ param: &syntax::Param,
2568+ default: &str,
2569+ ctx: &mut ParseContext,
2570+) -> Value {
2571+ // A default that uses a later parameter is an error in the
2572+ // definition; the later one isn't bound yet, so don't report it again
2573+ let later = fn_def
2574+ .params
2575+ .iter()
2576+ .skip_while(|p| p.name != param.name)
2577+ .skip(1);
2578+ let names = interp::names(default);
2579+ if later.clone().any(|p| names.contains(&p.name.as_str())) {
2580+ return Value::empty();
2581+ }
2582+ let line = param.span.line;
2583+ let at_head = line == fn_def.line && fn_def.source.is_some();
2584+ let column =
2585+ at_head.then(|| param.span.column + (param.span.end - param.span.start) - default.len());
2586+ let caller = (
2587+ std::mem::replace(
2588+ &mut ctx.current_source,
2589+ (fn_def.line, fn_def.source.clone()),
2590+ ),
2591+ std::mem::replace(&mut ctx.current_node, fn_def.node),
2592+ );
2593+ let (value, _) = ctx.slot_value(default, line, column);
2594+ (ctx.current_source, ctx.current_node) = caller;
2595+ value
2596+}
10742597
1075− // Build chain right-to-left: rightmost gets children, each wraps the next
1076− let mut current_children = children;
1077− for mut elem in elements.into_iter().rev() {
1078− elem.children.extend(current_children);
1079− current_children = vec![Node::Element(elem)];
2598+/// Read `@page`'s attribute list and title. The page is the root element,
2599+/// and its attributes are checked like any element's: `key=value` (and a
2600+/// bare boolean HTML attribute) go on `<html>`, styles on `<body>`, and
2601+/// `favicon FILE` is its one word of htmlang's own.
2602+fn read_page(
2603+ attrs: Option<&syntax::AttrList>,
2604+ title: Option<&syntax::Arg>,
2605+ line: usize,
2606+ ctx: &mut ParseContext,
2607+) -> Page {
2608+ let mut page = Page::default();
2609+ if let Some(list) = attrs {
2610+ let words: Vec<String> = crate::vocab::PAGE_WORDS
2611+ .iter()
2612+ .map(|w| w.to_string())
2613+ .collect();
2614+ ctx.in_page = true;
2615+ let read = parse_attr_list(&list.attrs, line, ctx, true, &words);
2616+ ctx.in_page = false;
2617+ // How many of each name have been read, to find where the next
2618+ // one is written
2619+ let mut seen: HashMap<String, usize> = HashMap::new();
2620+ for attr in read {
2621+ let boolean = attr.value.is_none()
2622+ && crate::vocab::BOOLEAN_HTML_ATTRS.contains(&attr.key.as_str());
2623+ // Where it is written, when it is written in the list itself
2624+ let nth = seen.entry(attr.key.clone()).or_default();
2625+ let column = list
2626+ .attrs
2627+ .iter()
2628+ .filter(|token| token.key == attr.key)
2629+ .nth(*nth)
2630+ .map(|token| token.span.column);
2631+ *nth += 1;
2632+ let value = attr
2633+ .quoted
2634+ .as_ref()
2635+ .map(|q| q.text.clone())
2636+ .or(attr.value.clone());
2637+ if !check_page_attr(&attr.key, attr.html, value.as_deref(), line, column, ctx) {
2638+ continue;
2639+ }
2640+ if words.contains(&attr.key) {
2641+ if page.favicon.is_some() {
2642+ let diagnostic = Diagnostic::warning(
2643+ code::DUPLICATE_ATTRIBUTE,
2644+ line,
2645+ "duplicate attribute 'favicon': the later one wins".to_string(),
2646+ )
2647+ .subject("favicon");
2648+ ctx.diagnostics.push(at_attribute(diagnostic, column, ctx));
2649+ }
2650+ // The file itself goes into the page when it can be read
2651+ // (relative to the file); otherwise it is linked
2652+ page.favicon = value.map(|path| match std::fs::read(ctx.resolve(&path)) {
2653+ Ok(data) => crate::codegen::data_uri(&path, &data),
2654+ Err(_) => path,
2655+ });
2656+ } else if attr.html || boolean {
2657+ page.html_attrs.push(attr);
2658+ } else {
2659+ page.styles.push(attr);
2660+ }
10802661 }
2662+ }
2663+ page.title = match title {
2664+ Some(title) => ctx.interpolate_text(&title.raw, title.span.line, Some(title.span.column)),
2665+ None => String::new(),
2666+ };
2667+ page
2668+}
10812669
1082− current_children.into_iter().next().ok_or(ParseError {
1083− line: line_num,
1084− message: "element chain produced no nodes (this is a parser bug)".to_string(),
1085− })
2670+/// `@page`'s own rules for one of its attributes, checked where the
2671+/// `@page` runs and where it doesn't (a layout that isn't called): its
2672+/// word is written `favicon FILE`, and `inline` belongs to `@image`.
2673+/// Returns whether the attribute can be used (a `favicon` with its file,
2674+/// or any other attribute but `inline`).
2675+fn check_page_attr(
2676+ key: &str,
2677+ html: bool,
2678+ value: Option<&str>,
2679+ line: usize,
2680+ column: Option<usize>,
2681+ ctx: &mut ParseContext,
2682+) -> bool {
2683+ let report = |ctx: &mut ParseContext, diagnostic: Diagnostic| {
2684+ let diagnostic = at_attribute(diagnostic, column, ctx);
2685+ ctx.diagnostics.push(diagnostic);
2686+ };
2687+ if crate::vocab::PAGE_WORDS.contains(&key) {
2688+ if html {
2689+ report(
2690+ ctx,
2691+ Diagnostic::error(
2692+ code::PARAMETER_FORM,
2693+ line,
2694+ format!(
2695+ "'{0}' is @page's own word, not an HTML attribute: write `{0} {1}`",
2696+ key,
2697+ value.filter(|v| !v.is_empty()).unwrap_or("FILE")
2698+ ),
2699+ )
2700+ .subject(format!("{}=", key))
2701+ .suggest(Some(format!("{} ", key))),
2702+ );
2703+ }
2704+ if value.is_none_or(|v| v.trim().is_empty()) {
2705+ report(
2706+ ctx,
2707+ Diagnostic::error(
2708+ code::MISSING_VALUE,
2709+ line,
2710+ format!("'{0}' needs its file: `{0} favicon.png`", key),
2711+ )
2712+ .subject(key),
2713+ );
2714+ return false;
2715+ }
2716+ return true;
2717+ }
2718+ if !html && crate::vocab::base_attribute(key) == "inline" {
2719+ report(
2720+ ctx,
2721+ Diagnostic::error(
2722+ code::UNEXPECTED_ARGUMENT,
2723+ line,
2724+ "`inline` puts an image's file into the page, and @page has none: it only \
2725+ goes on @image"
2726+ .to_string(),
2727+ )
2728+ .subject("inline"),
2729+ );
2730+ return false;
2731+ }
2732+ true
2733+}
2734+
2735+/// A parameter passed `name=value`, the form of an HTML attribute.
2736+fn parameter_form(function: &str, key: &str, value: &str, line: usize) -> Diagnostic {
2737+ Diagnostic::error(
2738+ code::PARAMETER_FORM,
2739+ line,
2740+ format!(
2741+ "'{}' is a parameter of @{}: parameters are written `name value`, so write `{} {}`",
2742+ key, function, key, value
2743+ ),
2744+ )
2745+ .subject(format!("{}=", key))
2746+ .suggest(Some(format!("{} ", key)))
2747+}
2748+
2749+/// A call that leaves out a parameter without a default.
2750+fn missing_parameter(
2751+ function: &str,
2752+ param: &str,
2753+ line: usize,
2754+ column: Option<usize>,
2755+) -> Diagnostic {
2756+ let diagnostic = Diagnostic::error(
2757+ code::MISSING_PARAMETER,
2758+ line,
2759+ format!(
2760+ "@{} needs '{}': the parameter has no default, so pass it as `{} VALUE`",
2761+ function, param, param
2762+ ),
2763+ )
2764+ .subject(param);
2765+ match column {
2766+ Some(column) => diagnostic.column(column),
2767+ None => diagnostic,
2768+ }
2769+}
2770+
2771+/// The column of a call's `@name`, when it is on the call's line.
2772+fn name_column(head: &syntax::Head, line: usize) -> Option<usize> {
2773+ (head.name_span.line == line).then_some(head.name_span.column)
2774+}
2775+
2776+/// Define `$name`, or, for `--name`, the CSS custom property on `:root`
2777+/// (which gets quoted text with its quotes, and is read with
2778+/// `var(--name)`, never as a variable). `@let name.field value` gives the
2779+/// record `$name` that field (or the list `$name` a new item at that
2780+/// index), as a new value in this block.
2781+fn set_variable(name: &str, value: Value, line_num: usize, ctx: &mut ParseContext) {
2782+ if name.starts_with("--") {
2783+ let css = value
2784+ .quoted_css()
2785+ .map_or_else(|| value.to_string(), str::to_string);
2786+ let at_line = |diagnostic: Diagnostic, ctx: &ParseContext| match &ctx.current_source {
2787+ (current, Some(text)) if *current == line_num => diagnostic.source(text.clone()),
2788+ _ => diagnostic,
2789+ };
2790+ // `:root` is one place for the whole page: a declaration inside a
2791+ // block (an element, a loop, a function's body) would not be
2792+ // kept to it, and each run would replace the last
2793+ if ctx.env.frames.len() > FILE_FRAMES {
2794+ let diagnostic = Diagnostic::error(
2795+ code::INVALID_DEFINITION,
2796+ line_num,
2797+ format!(
2798+ "`@let {name}` declares {name} on :root, for the whole page, so it goes at \
2799+ the top level of the file: to set it on an element and what is inside \
2800+ it, write `[{name} value]` on that element"
2801+ ),
2802+ )
2803+ .subject(name);
2804+ ctx.push_once(at_line(diagnostic, ctx));
2805+ return;
2806+ }
2807+ match css_breakout(&css) {
2808+ Some(reason) => {
2809+ let diagnostic = Diagnostic::error(
2810+ code::INVALID_VALUE,
2811+ line_num,
2812+ format!(
2813+ "the value of '{}' has {}: `{}` can't be written into the page's CSS",
2814+ name, reason, css
2815+ ),
2816+ )
2817+ .subject(css.as_str());
2818+ ctx.push_once(at_line(diagnostic, ctx));
2819+ }
2820+ None => match ctx.css_vars.iter_mut().find(|(n, _)| n == name) {
2821+ Some(declared) => {
2822+ let diagnostic = Diagnostic::warning(
2823+ code::DUPLICATE_ATTRIBUTE,
2824+ line_num,
2825+ format!(
2826+ "{name} is declared again: :root has one value for the whole page, \
2827+ so every element gets this one, also above this line (a theme \
2828+ redefines a token on an element: `[dark:{name} {css}]`)"
2829+ ),
2830+ )
2831+ .subject(name);
2832+ declared.1 = css;
2833+ ctx.push_once(at_line(diagnostic, ctx));
2834+ }
2835+ None => ctx.css_vars.push((name.to_string(), css)),
2836+ },
2837+ }
2838+ return;
2839+ }
2840+ let mut path = name.split('.');
2841+ let root = path.next().unwrap_or(name);
2842+ let fields: Vec<&str> = path.collect();
2843+ let value = match fields.is_empty() {
2844+ true => value,
2845+ false => match with_field(ctx.env.value(root).cloned(), root, &fields, value) {
2846+ Ok(value) => value,
2847+ Err(message) => {
2848+ let diagnostic =
2849+ Diagnostic::error(code::INVALID_DEFINITION, line_num, message).subject(name);
2850+ let diagnostic = match &ctx.current_source {
2851+ (current, Some(text)) if *current == line_num => {
2852+ diagnostic.source(text.clone())
2853+ }
2854+ _ => diagnostic,
2855+ };
2856+ ctx.push_once(diagnostic);
2857+ // Reported: the name keeps what it held
2858+ ctx.let_lines.entry(root.to_string()).or_insert(line_num);
2859+ return;
2860+ }
2861+ },
2862+ };
2863+ ctx.bind(root, value);
2864+ ctx.let_lines.entry(root.to_string()).or_insert(line_num);
2865+}
2866+
2867+/// `value` (the value of `$name`) with the field at `path` set to `new`:
2868+/// a record's field, or the item of a list at an index it has. A name
2869+/// without a value, or one whose value is empty (a field a record doesn't
2870+/// have), becomes a record; any other value has no fields to set.
2871+fn with_field(
2872+ value: Option<Value>,
2873+ name: &str,
2874+ path: &[&str],
2875+ new: Value,
2876+) -> Result<Value, String> {
2877+ let Some((field, rest)) = path.split_first() else {
2878+ return Ok(new);
2879+ };
2880+ let inner = format!("{}.{}", name, field);
2881+ match value {
2882+ Some(Value::Record(fields)) => {
2883+ let mut fields = fields.as_ref().clone();
2884+ match fields.iter().position(|(key, _)| key == field) {
2885+ Some(i) => {
2886+ let old = std::mem::replace(&mut fields[i].1, Value::empty());
2887+ fields[i].1 = with_field(Some(old), &inner, rest, new)?;
2888+ }
2889+ None => fields.push((field.to_string(), with_field(None, &inner, rest, new)?)),
2890+ }
2891+ Ok(Value::Record(Rc::new(fields)))
2892+ }
2893+ Some(Value::List(list)) => {
2894+ let count = list.items.len();
2895+ let Some(i) = field.parse::<usize>().ok().filter(|&i| i < count) else {
2896+ return Err(format!(
2897+ "`${}` is {}, so `.{}` isn't one of its items (they are `.0` to `.{}`)",
2898+ name,
2899+ Value::List(list).describe(),
2900+ field,
2901+ count.saturating_sub(1)
2902+ ));
2903+ };
2904+ let mut items = list.items.as_ref().clone();
2905+ let old = std::mem::replace(&mut items[i], Value::empty());
2906+ items[i] = with_field(Some(old), &inner, rest, new)?;
2907+ // Its items changed, so it no longer prints as written
2908+ Ok(Value::list(items))
2909+ }
2910+ None => Ok(Value::Record(Rc::new(vec![(
2911+ field.to_string(),
2912+ with_field(None, &inner, rest, new)?,
2913+ )]))),
2914+ Some(value) if value.to_string().is_empty() => with_field(None, name, path, new),
2915+ Some(value) => Err(format!(
2916+ "`@let {}.{}` sets a field of a record, but `${}` is {} (`{}`), which has no fields",
2917+ name,
2918+ path.join("."),
2919+ name,
2920+ value.describe(),
2921+ value
2922+ )),
2923+ }
2924+}
2925+
2926+/// What a verbatim directive holds (`@head`, `@style`, `@raw`): the rest
2927+/// of its line (`@style .a { color: red }`), or else its indented block.
2928+/// The two together are a syntax error, reported by the tree; the line
2929+/// wins.
2930+fn verbatim_content(node: &syntax::Node) -> String {
2931+ match node.directive().map(|d| &d.args) {
2932+ Some(DirectiveArgs::Text(Some(line))) => format!("{}\n", line.raw),
2933+ _ => verbatim_text(&node.children),
10862934 }
10872935}
10882936
2937+/// The text of a verbatim body (`@head`, `@style`, `@markdown`, `@raw`).
2938+fn verbatim_text(children: &[syntax::Node]) -> String {
2939+ let mut text = String::new();
2940+ for child in children {
2941+ if let NodeKind::Verbatim(body) = &child.kind {
2942+ text.push_str(&body.text);
2943+ text.push('\n');
2944+ }
2945+ }
2946+ text
2947+}
2948+
10892949// ---------------------------------------------------------------------------
10902950// @children replacement
10912951// ---------------------------------------------------------------------------
@@ -1130,91 +2990,705 @@ fn replace_children_and_slots(
11302990}
11312991
11322992// ---------------------------------------------------------------------------
1133−// Element parsing
2993+// Where @slot and @children are written
11342994// ---------------------------------------------------------------------------
11352995
1136−fn extract_element_name(content: &str) -> &str {
1137− let without_at = &content[1..];
1138− match without_at.find([' ', '[']) {
1139− Some(i) => &without_at[..i],
1140− None => without_at,
2996+/// The files each `@include` line brought in, by the line's node id, with
2997+/// the include chain that leads to each.
2998+type IncludedBy = HashMap<usize, Vec<(Rc<Tree>, String)>>;
2999+
3000+/// The lines of the files an `@include` line brings in, and the include
3001+/// chain of each (for diagnostics).
3002+type Included<'a, 'f> = &'f dyn Fn(&syntax::Node) -> Vec<(&'a [syntax::Node], Option<&'a str>)>;
3003+
3004+/// Whether `name` is a function here: defined so far, or anywhere in the
3005+/// file and the files it includes.
3006+fn is_function(name: &str, ctx: &ParseContext) -> bool {
3007+ ctx.env.function(name).is_some() || ctx.namespace.contains(name)
3008+}
3009+
3010+/// Whether `name` is one slot name: letters, digits, `-` and `_`,
3011+/// starting with a letter (like a function's name).
3012+fn is_slot_name(name: &str) -> bool {
3013+ name.chars().next().is_some_and(char::is_alphabetic)
3014+ && name
3015+ .chars()
3016+ .all(|c| c.is_alphanumeric() || c == '-' || c == '_')
3017+}
3018+
3019+/// What a `@slot` or `@children` line is written in.
3020+#[derive(Clone, Copy)]
3021+enum Place<'a> {
3022+ /// The top of a file or of a function's body, or a built-in element
3023+ /// (by its name).
3024+ Element(Option<&'a str>),
3025+ /// A call: its content.
3026+ Call,
3027+}
3028+
3029+/// Where a line is, for [`slot_uses`].
3030+#[derive(Clone, Copy)]
3031+struct At<'a> {
3032+ /// Inside a function's body.
3033+ body: bool,
3034+ place: Place<'a>,
3035+ /// Outside a body: the call (and its line) whose content it is in.
3036+ call: Option<(&'a str, usize)>,
3037+ /// The include chain of the file it is in, when that isn't the file
3038+ /// being compiled.
3039+ file: Option<&'a str>,
3040+}
3041+
3042+impl At<'_> {
3043+ /// The top of a file, or of a function's body.
3044+ fn top(body: bool) -> Self {
3045+ At {
3046+ body,
3047+ place: Place::Element(None),
3048+ call: None,
3049+ file: None,
3050+ }
11413051 }
11423052}
11433053
1144−fn parse_single_element(
1145− content: &str,
1146− line_num: usize,
1147− ctx: &mut ParseContext,
1148−) -> Result<Element, ParseError> {
1149− let (kind, rest) = if let Some(without_at) = content.strip_prefix('@') {
1150− match without_at.find([' ', '[']) {
1151− Some(i) => {
1152− let kind_str = &without_at[..i];
1153− let rest = if without_at.as_bytes()[i] == b'[' {
1154− without_at[i..].to_string()
1155− } else {
1156− without_at[i + 1..].to_string()
1157− };
1158− match parse_element_kind(kind_str, line_num) {
1159− Ok(kind) => (kind, rest),
1160− Err(mut e) => {
1161− // Also suggest user-defined functions
1162− if let Some(fn_suggestion) = suggest_fn_name(kind_str, ctx) {
1163− e.message =
1164− format!("{}, or did you mean @{}?", e.message, fn_suggestion);
1165− }
1166− return Err(e);
1167− }
3054+/// What [`slot_uses`] knows about the names and files it walks.
3055+struct Scan<'a, 'f> {
3056+ is_function: &'f dyn Fn(&str) -> bool,
3057+ included: Included<'a, 'f>,
3058+ /// Visit the bodies of the functions defined in the lines too.
3059+ into_lets: bool,
3060+}
3061+
3062+/// A `@slot` or `@children` written in a file, and where.
3063+struct SlotUse<'a> {
3064+ node: &'a syntax::Node,
3065+ head: &'a syntax::Head,
3066+ /// The text after it, which is a slot's name; `None` when it isn't
3067+ /// the last head of its chain.
3068+ text: Option<&'a syntax::Text>,
3069+ /// Written inline in a line of text, `{@slot x}`.
3070+ inline: bool,
3071+ at: At<'a>,
3072+}
3073+
3074+impl SlotUse<'_> {
3075+ fn is_slot(&self) -> bool {
3076+ self.head.name == "slot"
3077+ }
3078+
3079+ /// The slot's name as written.
3080+ fn name(&self) -> &str {
3081+ self.text.map_or("", |t| t.raw.trim())
3082+ }
3083+
3084+ /// A `@slot NAME` that marks a place in a function's body (not one
3085+ /// that fills a slot of a call).
3086+ fn declares(&self) -> bool {
3087+ self.is_slot() && !self.inline && !matches!(self.at.place, Place::Call)
3088+ }
3089+}
3090+
3091+/// Where each `@slot` and `@children` in `block` is written. A `@slot`
3092+/// directly under a call (under its `@if`, `@else` and `@each` too) fills
3093+/// one of its slots; anywhere else in a function's body it declares one.
3094+/// An included file's lines are where its `@include` is.
3095+fn slot_uses<'a>(
3096+ block: &'a [syntax::Node],
3097+ at: At<'a>,
3098+ scan: &Scan<'a, '_>,
3099+ out: &mut Vec<SlotUse<'a>>,
3100+) {
3101+ fn inline<'a>(
3102+ text: &'a syntax::Text,
3103+ node: &'a syntax::Node,
3104+ at: At<'a>,
3105+ scan: &Scan<'a, '_>,
3106+ out: &mut Vec<SlotUse<'a>>,
3107+ ) {
3108+ for segment in &text.segments {
3109+ if let Segment::Inline(inline_element) = segment {
3110+ let head = &inline_element.head;
3111+ if matches!(head.name.as_str(), "slot" | "children")
3112+ && !(scan.is_function)(&head.name)
3113+ {
3114+ out.push(SlotUse {
3115+ node,
3116+ head,
3117+ text: inline_element.text.as_ref(),
3118+ inline: true,
3119+ at,
3120+ });
3121+ }
3122+ if let Some(text) = &inline_element.text {
3123+ inline(text, node, at, scan, out);
11683124 }
11693125 }
1170− None => match parse_element_kind(without_at, line_num) {
1171− Ok(kind) => (kind, String::new()),
1172− Err(mut e) => {
1173− if let Some(fn_suggestion) = suggest_fn_name(without_at, ctx) {
1174− e.message = format!("{}, or did you mean @{}?", e.message, fn_suggestion);
3126+ }
3127+ }
3128+ for node in block {
3129+ match &node.kind {
3130+ NodeKind::Directive(directive) => match &directive.args {
3131+ DirectiveArgs::Let(def) if matches!(def.form, LetForm::Function(_)) => {
3132+ if scan.into_lets {
3133+ let top = At {
3134+ file: at.file,
3135+ ..At::top(true)
3136+ };
3137+ slot_uses(&node.children, top, scan, out);
11753138 }
1176− return Err(e);
3139+ }
3140+ // A value's body is an error of its own
3141+ DirectiveArgs::Let(_) => {}
3142+ _ if directive.spec.body == BodyKind::Verbatim => {}
3143+ // `@if`, `@else` and `@each` put their lines in place, and
3144+ // `@include` its file's; the lines under a directive that
3145+ // takes no body are its siblings
3146+ _ => {
3147+ for (lines, file) in (scan.included)(node) {
3148+ slot_uses(lines, At { file, ..at }, scan, out);
3149+ }
3150+ slot_uses(&node.children, at, scan, out);
11773151 }
11783152 },
3153+ NodeKind::Element(line) => {
3154+ let mut at = at;
3155+ let last = line.chain.len() - 1;
3156+ for (i, head) in line.chain.iter().enumerate() {
3157+ let text = if i == last { line.text.as_ref() } else { None };
3158+ let function = (scan.is_function)(&head.name);
3159+ if !function && matches!(head.name.as_str(), "slot" | "children") {
3160+ out.push(SlotUse {
3161+ node,
3162+ head,
3163+ text,
3164+ inline: false,
3165+ at,
3166+ });
3167+ } else if let Some(text) = text {
3168+ inline(text, node, at, scan, out);
3169+ }
3170+ if function {
3171+ at.place = Place::Call;
3172+ if !at.body {
3173+ at.call = Some((&head.name, node.span.line));
3174+ }
3175+ } else {
3176+ at.place = Place::Element(Some(&head.name));
3177+ }
3178+ }
3179+ slot_uses(&node.children, at, scan, out);
3180+ }
3181+ NodeKind::Text(text) => {
3182+ inline(text, node, at, scan, out);
3183+ slot_uses(&node.children, at, scan, out);
3184+ }
3185+ NodeKind::Blank | NodeKind::Comment | NodeKind::Verbatim(_) => {}
11793186 }
1180− } else {
1181− return Err(ParseError {
1182− line: line_num,
1183− message: format!("expected @element or [attrs], got: {}", content),
3187+ }
3188+}
3189+
3190+/// The slots a function's body declares, and whether it has a
3191+/// `@children`, when it is defined. The files its `@include` lines bring
3192+/// in count too: they are read now, since they run only at a call.
3193+fn declared_slots(body: &[syntax::Node], ctx: &mut ParseContext) -> (Vec<String>, bool) {
3194+ let mut files = HashMap::new();
3195+ read_includes(
3196+ body,
3197+ ctx.base_path.clone(),
3198+ &mut Vec::new(),
3199+ ctx,
3200+ &mut files,
3201+ );
3202+ let included = |node: &syntax::Node| match files.get(&node.id) {
3203+ Some(tree) => vec![(&tree.nodes[..], None)],
3204+ None => Vec::new(),
3205+ };
3206+ let is_function = |name: &str| is_function(name, ctx);
3207+ slots_of(body, &is_function, &included)
3208+}
3209+
3210+/// Read and parse the files the `@include` lines in `nodes` bring in (by
3211+/// a literal path, relative to `base`), and the files those include, by
3212+/// the node id of each `@include` line.
3213+fn read_includes(
3214+ nodes: &[syntax::Node],
3215+ base: Option<PathBuf>,
3216+ stack: &mut Vec<PathBuf>,
3217+ ctx: &mut ParseContext,
3218+ files: &mut HashMap<usize, Rc<Tree>>,
3219+) {
3220+ let mut includes = Vec::new();
3221+ for node in nodes {
3222+ node.walk(&mut |node| {
3223+ if let Some(DirectiveArgs::Text(Some(path))) = node.directive().map(|d| &d.args)
3224+ && node.is_directive("include")
3225+ {
3226+ includes.push((node.id, path.raw.clone()));
3227+ }
11843228 });
3229+ }
3230+ for (id, path) in includes {
3231+ let path = path.trim_matches('"');
3232+ if path.contains('$') {
3233+ continue;
3234+ }
3235+ let resolved = match &base {
3236+ Some(base) => base.join(path),
3237+ None => PathBuf::from(path),
3238+ };
3239+ if stack.contains(&resolved) {
3240+ continue;
3241+ }
3242+ let Ok(text) = ctx.read_file(&resolved) else {
3243+ continue;
3244+ };
3245+ let tree = ctx.parse_tree(&text);
3246+ stack.push(resolved.clone());
3247+ let parent = resolved.parent().map(Path::to_path_buf);
3248+ read_includes(&tree.nodes, parent, stack, ctx, files);
3249+ stack.pop();
3250+ files.insert(id, tree);
3251+ }
3252+}
3253+
3254+/// The slots a function's body declares (`@slot NAME`, in order), and
3255+/// whether it has a `@children` for the content of a call. A `@slot`
3256+/// directly under a call in the body fills that call's slot instead, so
3257+/// `is_function` says which names are functions. The files the body
3258+/// includes aren't read.
3259+pub fn function_slots(
3260+ body: &[syntax::Node],
3261+ is_function: &dyn Fn(&str) -> bool,
3262+) -> (Vec<String>, bool) {
3263+ slots_of(body, is_function, &|_| Vec::new())
3264+}
3265+
3266+fn slots_of<'a>(
3267+ body: &'a [syntax::Node],
3268+ is_function: &dyn Fn(&str) -> bool,
3269+ included: Included<'a, '_>,
3270+) -> (Vec<String>, bool) {
3271+ let scan = Scan {
3272+ is_function,
3273+ included,
3274+ into_lets: false,
3275+ };
3276+ let mut uses = Vec::new();
3277+ slot_uses(body, At::top(true), &scan, &mut uses);
3278+ let mut slots: Vec<String> = Vec::new();
3279+ for slot in uses.iter().filter(|u| u.declares()) {
3280+ let name = slot.name();
3281+ if is_slot_name(name) && !slots.iter().any(|s| s == name) {
3282+ slots.push(name.to_string());
3283+ }
3284+ }
3285+ let has_children = uses.iter().any(|u| !u.is_slot() && !u.inline);
3286+ (slots, has_children)
3287+}
3288+
3289+/// The line as written, indented, when it is one physical line, so a
3290+/// column points into it.
3291+fn written_line(node: &syntax::Node) -> String {
3292+ match node.line_count <= 1 {
3293+ true => format!("{}{}", " ".repeat(node.indent), node.source),
3294+ false => node.source.clone(),
3295+ }
3296+}
3297+
3298+/// The lines of the files an `@include` line brought in when it ran, from
3299+/// `included_by`.
3300+fn ran_includes<'a>(
3301+ included_by: &'a IncludedBy,
3302+ node: &syntax::Node,
3303+) -> Vec<(&'a [syntax::Node], Option<&'a str>)> {
3304+ match included_by.get(&node.id) {
3305+ Some(files) => files
3306+ .iter()
3307+ .map(|(tree, chain)| (&tree.nodes[..], Some(chain.as_str())))
3308+ .collect(),
3309+ None => Vec::new(),
3310+ }
3311+}
3312+
3313+/// Check where every `@slot` and `@children` of the file and the files it
3314+/// includes is written, whether or not it runs: a slot has one name, a
3315+/// function's body marks places with them, and a call fills its slots
3316+/// with `@slot` blocks directly under it. An included file's lines are
3317+/// where its `@include` is (in a body, under a call), so an `@include`
3318+/// that never ran leaves its file unchecked.
3319+fn check_slot_places(ctx: &mut ParseContext) {
3320+ let trees = std::mem::take(&mut ctx.trees);
3321+ let included_by = ctx.included_by.clone();
3322+ let is_function = |name: &str| is_function(name, ctx);
3323+ let scan = Scan {
3324+ is_function: &is_function,
3325+ included: &|node| ran_includes(&included_by, node),
3326+ into_lets: true,
11853327 };
3328+ let mut uses = Vec::new();
3329+ for (tree, _) in trees.iter().filter(|(_, chain)| chain.is_none()) {
3330+ slot_uses(&tree.nodes, At::top(false), &scan, &mut uses);
3331+ }
3332+ let found: Vec<Diagnostic> = uses
3333+ .iter()
3334+ .filter_map(|slot| {
3335+ let mut d = slot_problem(slot)?;
3336+ if d.column.is_none() {
3337+ d = d.column(slot.head.name_span.column);
3338+ }
3339+ d = d.source(written_line(slot.node));
3340+ if let Some(file) = slot.at.file {
3341+ d.message = format!("{}\n in {}", d.message, file);
3342+ }
3343+ Some(d)
3344+ })
3345+ .collect();
3346+ ctx.diagnostics.extend(found);
3347+ ctx.trees = trees;
3348+}
11863349
1187− // Parse optional [attrs]
1188− let (attrs, rest) = if rest.starts_with('[') {
1189− parse_attr_brackets(&rest, line_num, ctx)?
3350+/// What is wrong with a `@slot` or `@children` where it is written.
3351+fn slot_problem(slot: &SlotUse) -> Option<Diagnostic> {
3352+ let line = slot.node.span.line;
3353+ let what = if slot.is_slot() {
3354+ match slot.name() {
3355+ "" => "@slot".to_string(),
3356+ name => format!("@slot {}", name),
3357+ }
11903358 } else {
1191− (Vec::new(), rest)
3359+ "@children".to_string()
11923360 };
3361+ if slot.inline {
3362+ return Some(Diagnostic::error(
3363+ code::MISPLACED_SLOT,
3364+ line,
3365+ format!(
3366+ "{} goes on a line of its own: inline in text it marks and fills nothing",
3367+ what
3368+ ),
3369+ ));
3370+ }
3371+ if let Some(list) = &slot.head.attrs {
3372+ return Some(
3373+ Diagnostic::error(
3374+ code::UNEXPECTED_ARGUMENT,
3375+ line,
3376+ format!(
3377+ "{} takes no attributes: it is replaced by content, so style the \
3378+ element around it",
3379+ what
3380+ ),
3381+ )
3382+ .column(list.span.column),
3383+ );
3384+ }
3385+ if slot.is_slot() {
3386+ let name = slot.name();
3387+ if name.is_empty() {
3388+ return Some(Diagnostic::error(
3389+ code::MISSING_ARGUMENT,
3390+ line,
3391+ "@slot needs a name: `@slot footer` (the caller's content without a \
3392+ name goes where `@children` is)"
3393+ .to_string(),
3394+ ));
3395+ }
3396+ if !is_slot_name(name) {
3397+ let joined = name.split_whitespace().collect::<Vec<_>>().join("-");
3398+ let suggestion = is_slot_name(&joined).then_some(joined);
3399+ let column = slot.text.map(|t| t.span.column);
3400+ let d = Diagnostic::error(
3401+ code::INVALID_SLOT_NAME,
3402+ line,
3403+ format!(
3404+ "'{}' is not a slot name: a slot's name is one word of letters, digits, \
3405+ `-` and `_`, starting with a letter, and its content goes on the lines \
3406+ under it",
3407+ name
3408+ ),
3409+ )
3410+ .subject(name)
3411+ .suggest(suggestion);
3412+ return Some(match column {
3413+ Some(column) => d.column(column),
3414+ None => d,
3415+ });
3416+ }
3417+ if matches!(slot.at.place, Place::Call) || slot.at.body {
3418+ return None;
3419+ }
3420+ let message = match (slot.at.call, slot.at.place) {
3421+ (Some((call, call_line)), Place::Element(Some(element))) => format!(
3422+ "{} is inside @{}, so it fills nothing: a @slot block that fills a slot of \
3423+ @{} (line {}) goes directly under the call",
3424+ what, element, call, call_line
3425+ ),
3426+ _ => format!(
3427+ "{} is outside a function's body: `@slot NAME` marks a place in a body \
3428+ (`@let @name`), and directly under a call it fills one",
3429+ what
3430+ ),
3431+ };
3432+ return Some(Diagnostic::error(code::MISPLACED_SLOT, line, message));
3433+ }
3434+ if slot.at.body {
3435+ return None;
3436+ }
3437+ let message = match slot.at.call {
3438+ Some((call, _)) => format!(
3439+ "@children is outside a function's body, so it stands for nothing: the content \
3440+ for @{} is written directly under the call",
3441+ call
3442+ ),
3443+ None => "@children is outside a function's body: it marks where a body puts the \
3444+ content of each call"
3445+ .to_string(),
3446+ };
3447+ Some(Diagnostic::error(code::MISPLACED_SLOT, line, message))
3448+}
11933449
1194− let rest = rest.trim().to_string();
1195− track_var_refs(&rest, &mut ctx.used_variables);
3450+/// A `@slot NAME` block that fills a slot of a call.
3451+struct Filler<'a> {
3452+ node: &'a syntax::Node,
3453+ text: &'a syntax::Text,
3454+ /// The include chain of the file it is in, when that isn't the file
3455+ /// being compiled.
3456+ file: Option<&'a str>,
3457+}
11963458
1197− // For @link, first token of rest is URL, remainder is inline text
1198− let mut children = Vec::new();
1199− let argument = if rest.is_empty() {
1200− None
1201− } else if kind == ElementKind::Link {
1202− let rest_sub = substitute_vars(&protect_escapes(&rest), &ctx.variables);
1203− if let Some((url, text)) = rest_sub.split_once(' ') {
1204− let text = text.trim();
1205− if !text.is_empty() {
1206− children.push(Node::Text(parse_text_segments(text, ctx)));
1207− }
1208− Some(restore_escapes(url))
1209− } else {
1210− Some(restore_escapes(&rest_sub))
3459+/// Whether `@slot` is the built-in element here, and not a function
3460+/// defined so far that took its name.
3461+fn slot_is_built_in(ctx: &ParseContext) -> bool {
3462+ ctx.env.function("slot").is_none()
3463+}
3464+
3465+/// The `@slot NAME` blocks directly under a call, in `block` (under its
3466+/// `@if`, `@else` and `@each` too, and in the files its `@include` lines
3467+/// brought in).
3468+fn fillers<'a>(
3469+ block: &'a [syntax::Node],
3470+ file: Option<&'a str>,
3471+ included: &'a IncludedBy,
3472+ out: &mut Vec<Filler<'a>>,
3473+) {
3474+ for node in block {
3475+ match &node.kind {
3476+ NodeKind::Directive(directive)
3477+ if matches!(directive.name(), "if" | "else" | "each") =>
3478+ {
3479+ fillers(&node.children, file, included, out);
3480+ }
3481+ NodeKind::Directive(directive) if directive.name() == "include" => {
3482+ for (lines, file) in ran_includes(included, node) {
3483+ fillers(lines, file, included, out);
3484+ }
3485+ }
3486+ NodeKind::Element(line) if line.chain.len() == 1 && line.chain[0].name == "slot" => {
3487+ if let Some(text) = &line.text {
3488+ out.push(Filler { node, text, file });
3489+ }
3490+ }
3491+ _ => {}
12113492 }
1212− } else {
1213− Some(restore_escapes(&substitute_vars(
1214− &protect_escapes(&rest),
1215− &ctx.variables,
1216− )))
3493+ }
3494+}
3495+
3496+/// Whether `block`, the lines under a call, holds content other than
3497+/// `@slot` blocks (under `@if`, `@else` and `@each` too): text, an
3498+/// element, raw HTML, Markdown or an included file. For code that doesn't
3499+/// run.
3500+fn holds_content(block: &[syntax::Node], ctx: &ParseContext) -> bool {
3501+ block.iter().any(|node| match &node.kind {
3502+ NodeKind::Directive(directive) => match directive.name() {
3503+ "if" | "else" | "each" => holds_content(&node.children, ctx),
3504+ name => matches!(name, "raw" | "markdown" | "include"),
3505+ },
3506+ NodeKind::Element(line) => {
3507+ line.chain[0].name != "slot" || !slot_is_built_in(ctx) || line.chain.len() > 1
3508+ }
3509+ NodeKind::Text(_) => true,
3510+ _ => false,
3511+ })
3512+}
3513+
3514+/// Check the `@slot NAME` blocks passed to each call of a line against
3515+/// the slots its function declares. `calls` has the function of each head
3516+/// of the chain that is a call.
3517+fn check_fillers(
3518+ node: &syntax::Node,
3519+ element: &syntax::ElementLine,
3520+ calls: &[Option<(String, Rc<FnDef>)>],
3521+ ctx: &mut ParseContext,
3522+) {
3523+ if !slot_is_built_in(ctx) {
3524+ return;
3525+ }
3526+ let included = ctx.included_by.clone();
3527+ let last = element.chain.len() - 1;
3528+ for (i, call) in calls.iter().enumerate() {
3529+ let Some((name, function)) = call else {
3530+ continue;
3531+ };
3532+ let mut found = Vec::new();
3533+ if i == last {
3534+ fillers(&node.children, None, &included, &mut found);
3535+ } else if i + 1 == last
3536+ && element.chain[last].name == "slot"
3537+ && let Some(text) = &element.text
3538+ {
3539+ // `@card > @slot footer`
3540+ found.push(Filler {
3541+ node,
3542+ text,
3543+ file: None,
3544+ });
3545+ }
3546+ for filler in found {
3547+ let slot = filler.text.raw.trim();
3548+ if !is_slot_name(slot) || function.slots.iter().any(|s| s == slot) {
3549+ continue;
3550+ }
3551+ let mut d = unknown_slot(name, slot, &function.slots, filler.text.span.line)
3552+ .column(filler.text.span.column)
3553+ .source(written_line(filler.node));
3554+ if let Some(file) = filler.file {
3555+ d.message = format!("{}\n in {}", d.message, file);
3556+ }
3557+ ctx.push_once(d);
3558+ }
3559+ }
3560+}
3561+
3562+/// A `@slot NAME` block for a slot the function doesn't declare.
3563+fn unknown_slot(function: &str, slot: &str, slots: &[String], line: usize) -> Diagnostic {
3564+ let candidates: Vec<&str> = slots.iter().map(String::as_str).collect();
3565+ let suggestion = suggest_closest(slot, &candidates);
3566+ let message = match (slots.is_empty(), suggestion) {
3567+ (true, _) => format!(
3568+ "@{} has no slot '{}': its body declares no slots (`@slot NAME`)",
3569+ function, slot
3570+ ),
3571+ (false, Some(close)) => format!(
3572+ "@{} has no slot '{}', did you mean '{}'? (its slots: {})",
3573+ function,
3574+ slot,
3575+ close,
3576+ slots.join(", ")
3577+ ),
3578+ (false, None) => format!(
3579+ "@{} has no slot '{}' (its slots: {})",
3580+ function,
3581+ slot,
3582+ slots.join(", ")
3583+ ),
12173584 };
3585+ Diagnostic::error(code::UNKNOWN_SLOT, line, message)
3586+ .subject(slot)
3587+ .suggest(suggestion)
3588+}
3589+
3590+/// Content passed to a function whose body has no `@children`.
3591+fn no_children(function: &str, line: usize, column: Option<usize>) -> Diagnostic {
3592+ let d = Diagnostic::error(
3593+ code::UNEXPECTED_CONTENT,
3594+ line,
3595+ format!(
3596+ "@{0} takes no content: its body has no `@children`, so the text and lines \
3597+ passed to it would be dropped (pass text as a parameter, `@{0} [name value]`, \
3598+ or add `@children` to the body)",
3599+ function
3600+ ),
3601+ )
3602+ .subject(function);
3603+ match column {
3604+ Some(column) => d.column(column),
3605+ None => d,
3606+ }
3607+}
3608+
3609+// ---------------------------------------------------------------------------
3610+// Element parsing
3611+// ---------------------------------------------------------------------------
3612+
3613+/// Build the element for `@name [attrs] text` (on its own line, in a chain,
3614+/// or inline in text).
3615+fn parse_single_element(
3616+ head: &syntax::Head,
3617+ text: Option<&syntax::Text>,
3618+ line_num: usize,
3619+ ctx: &mut ParseContext,
3620+) -> Result<Element, ParseError> {
3621+ let kind = parse_element_kind(&head.name, line_num, ctx)?;
3622+ let mut attrs = head.attrs.as_ref().map_or_else(Vec::new, |list| {
3623+ parse_attr_list(&list.attrs, line_num, ctx, true, &[])
3624+ });
3625+
3626+ // The leading argument: for an element whose row names a leading
3627+ // attribute (`@link`'s href, `@image`'s src, `@form`'s action, ...),
3628+ // the first token of the text fills it, split before anything is
3629+ // filled in, and the rest is content (an error on an element without
3630+ // content). `@slot`'s whole text is its name. Any other element's text
3631+ // is content, parsed like any line of text, as in `@el [padding 8]
3632+ // Hello` or `@h2 Meet {@text htmlang}`; its layout decides how it
3633+ // combines with the lines under it.
3634+ let mut children = Vec::new();
3635+ let mut argument = None;
3636+ let leading = kind.arg().attributes();
3637+ match text {
3638+ Some(text) if !leading.is_empty() => {
3639+ let (token, rest) = text.split_leading();
3640+ let given = attrs
3641+ .iter()
3642+ .find(|a| a.html && leading.contains(&a.key.as_str()))
3643+ .map(|a| (a.key.clone(), a.value.clone().unwrap_or_default()));
3644+ if let Some((key, value)) = given {
3645+ // The attribute wins; the text is content, as if the
3646+ // element had no leading argument
3647+ ctx.push_once(leading_twice(&kind, &token, &key, &value, text, ctx));
3648+ if !takes_no_text(&kind) {
3649+ children.push(Node::Text(text_segments(text, ctx)));
3650+ }
3651+ } else if let Some(d) = bad_leading_token(&kind, &token, &text.raw, ctx) {
3652+ // Nothing is taken as the argument; the line is content
3653+ ctx.push_once(d);
3654+ if !takes_no_text(&kind) {
3655+ children.push(Node::Text(text_segments(text, ctx)));
3656+ }
3657+ } else {
3658+ let column = Some(token.span.column);
3659+ argument = Some(
3660+ ctx.fill_value(&token.raw, text.span.line, column, Sink::Text)
3661+ .0,
3662+ );
3663+ if let Some(rest) = rest {
3664+ if let Some(d) = chain_after_argument(&kind, &token.raw, &rest, ctx) {
3665+ ctx.push_once(d);
3666+ }
3667+ if takes_no_text(&kind) {
3668+ let d = after_the_leading_argument(&kind, &token.raw, &rest);
3669+ let d = at_attribute(d, Some(rest.span.column), ctx);
3670+ ctx.push_once(d);
3671+ } else {
3672+ children.push(Node::Text(text_segments(&rest, ctx)));
3673+ }
3674+ }
3675+ }
3676+ }
3677+ Some(text) if matches!(kind, ElementKind::Slot(_)) => {
3678+ argument =
3679+ Some(ctx.interpolate_text(&text.raw, text.span.line, Some(text.span.column)));
3680+ }
3681+ Some(text) => children.push(Node::Text(text_segments(text, ctx))),
3682+ // `@link [href=/about]`: the attribute is the leading argument, so
3683+ // both forms compile the same (`@image [src=a.svg, inline]`). Not
3684+ // for `@source`, whose attribute depends on where it is.
3685+ None if leading.len() == 1 => {
3686+ if let Some(i) = attrs.iter().position(|a| a.html && a.key == leading[0]) {
3687+ argument = Some(attrs.remove(i).value.unwrap_or_default());
3688+ }
3689+ }
3690+ None => {}
3691+ }
12183692
12193693 // For @slot, the argument is the slot name
12203694 let kind = if let ElementKind::Slot(_) = kind {
@@ -1223,62 +3697,323 @@ fn parse_single_element(
12233697 kind
12243698 };
12253699
1226− // Every other element treats its argument as leading text content, as
1227− // in `@el [padding 8] Hello` or `@paragraph Read {@link /more more}`.
1228− let argument = match argument {
1229− Some(_) if !argument_is_special(&kind) && !renders_argument_as_text(&kind) => {
1230− children.insert(0, Node::Text(parse_text_segments(&rest, ctx)));
1231− None
1232− }
1233− other => other,
1234− };
1235−
12363700 Ok(Element {
12373701 kind,
12383702 attrs,
12393703 argument,
12403704 children,
12413705 line_num,
3706+ function: None,
12423707 })
12433708}
12443709
1245−/// Elements whose argument is not text content: a URL, a source, an action,
1246−/// or a slot name.
1247−fn argument_is_special(kind: &ElementKind) -> bool {
1248− matches!(
1249− kind,
1250− ElementKind::Link | ElementKind::Image | ElementKind::Script | ElementKind::Slot(_)
1251− ) || kind
1252− .spec()
1253− .is_some_and(|spec| matches!(spec.arg, TagArg::Attr(_)))
3710+/// Whether `node` or a line inside it calls `@name` outside any `@if`
3711+/// (in a chain, or inline in text).
3712+fn calls_unguarded(node: &syntax::Node, name: &str) -> bool {
3713+ if node.is_directive("if") || node.is_directive("else") {
3714+ return false;
3715+ }
3716+ let text_calls = |text: &syntax::Text| {
3717+ text.segments
3718+ .iter()
3719+ .any(|s| matches!(s, Segment::Inline(inline) if inline.head.name == name))
3720+ };
3721+ let here = match &node.kind {
3722+ NodeKind::Element(element) => {
3723+ element.chain.iter().any(|head| head.name == name)
3724+ || element.text.as_ref().is_some_and(text_calls)
3725+ }
3726+ NodeKind::Text(text) => text_calls(text),
3727+ _ => false,
3728+ };
3729+ here || node
3730+ .children
3731+ .iter()
3732+ .any(|child| calls_unguarded(child, name))
3733+}
3734+
3735+/// `@td [padding 8] @children`: `@children` and `@slot NAME` mark where a
3736+/// call's content goes only on a line of their own; after an element's
3737+/// attributes, or in a verbatim body, they are text.
3738+fn marker_in_text(node: &syntax::Node) -> Option<Diagnostic> {
3739+ let is_marker = |text: &str| {
3740+ let text = text.trim();
3741+ text == "@children" || text == "@slot" || text.starts_with("@slot ")
3742+ };
3743+ let mut line = node.span.line;
3744+ let mut source = written_line(node);
3745+ let (marker, message) = match &node.kind {
3746+ NodeKind::Element(element) => {
3747+ let text = element.text.as_ref()?;
3748+ if !is_marker(&text.raw) {
3749+ return None;
3750+ }
3751+ let name = &element.chain.last()?.name;
3752+ let marker = text.raw.trim().to_string();
3753+ let message = format!(
3754+ "`{marker}` after @{name}'s attributes is text: it marks where a call's content \
3755+ goes only on a line of its own, so write it on the next line, indented under \
3756+ @{name}"
3757+ );
3758+ (marker, message)
3759+ }
3760+ NodeKind::Verbatim(verbatim) if verbatim.escaped => {
3761+ let (i, written) = verbatim
3762+ .text
3763+ .lines()
3764+ .enumerate()
3765+ .find(|(_, l)| is_marker(l))?;
3766+ let marker = written.trim().to_string();
3767+ line += i;
3768+ source = written.to_string();
3769+ let message = format!(
3770+ "`{marker}` in a verbatim body is text: the body is written as it is, so it can't \
3771+ hold a call's content (pass the text as a parameter instead)"
3772+ );
3773+ (marker, message)
3774+ }
3775+ _ => return None,
3776+ };
3777+ Some(
3778+ Diagnostic::error(code::MISPLACED_SLOT, line, message)
3779+ .subject(marker)
3780+ .source(source),
3781+ )
3782+}
3783+
3784+/// A first word that can't be a leading argument: an inline element
3785+/// (`@link {@b x} y`), or a quote that isn't closed (`@link "a b`).
3786+fn bad_leading_token(
3787+ kind: &ElementKind,
3788+ token: &syntax::Arg,
3789+ text: &str,
3790+ ctx: &ParseContext,
3791+) -> Option<Diagnostic> {
3792+ let what = leading_name(kind);
3793+ let name = kind.name();
3794+ let message = if token.raw.starts_with("{@") {
3795+ format!(
3796+ "@{0} takes its {1} first, before any text: write `@{0} VALUE {2}`, or give it as \
3797+ `[{1}=VALUE]`",
3798+ name,
3799+ what,
3800+ text.trim()
3801+ )
3802+ } else if token.raw.starts_with('"') && syntax::quoted_string(&token.raw).is_none() {
3803+ format!(
3804+ "@{}'s {} starts with a `\"` that isn't closed: close it (`\"...\"`), or write \
3805+ `\\\"` for a quote in the value",
3806+ name, what
3807+ )
3808+ } else {
3809+ return None;
3810+ };
3811+ let d = Diagnostic::error(code::UNEXPECTED_ARGUMENT, token.span.line, message)
3812+ .subject(token.raw.clone());
3813+ Some(at_attribute(d, Some(token.span.column), ctx))
3814+}
3815+
3816+/// `@link /a > @image logo.png`: a `>` chains only after an element's
3817+/// name or its `[attributes]`, so after a leading argument it is text.
3818+/// Said when what follows names an element or a function.
3819+fn chain_after_argument(
3820+ kind: &ElementKind,
3821+ token: &str,
3822+ rest: &syntax::Text,
3823+ ctx: &ParseContext,
3824+) -> Option<Diagnostic> {
3825+ let after = rest.raw.strip_prefix('>')?;
3826+ let name_start = after.trim_start().strip_prefix('@')?;
3827+ if after.len() == after.trim_start().len() {
3828+ return None;
3829+ }
3830+ let name: String = name_start
3831+ .chars()
3832+ .take_while(|c| c.is_ascii_alphanumeric() || *c == '-')
3833+ .collect();
3834+ if ElementKind::from_name(&name).is_none() && ctx.env.function(&name).is_none() {
3835+ return None;
3836+ }
3837+ let attr = leading_name(kind);
3838+ let d = Diagnostic::warning(
3839+ code::UNEXPECTED_ARGUMENT,
3840+ rest.span.line,
3841+ format!(
3842+ "`{}` after @{}'s {} is text, not a chain: `>` chains after an element's name or \
3843+ its [attributes], so write `@{} [{}={}] {}`",
3844+ rest.raw.trim_end(),
3845+ kind.name(),
3846+ attr,
3847+ kind.name(),
3848+ attr,
3849+ token,
3850+ rest.raw.trim_end()
3851+ ),
3852+ )
3853+ .subject(rest.raw.trim_end());
3854+ Some(at_attribute(d, Some(rest.span.column), ctx))
3855+}
3856+
3857+/// A leading argument given twice, as the first token and as its
3858+/// attribute: `@link [href=/a] About`.
3859+fn leading_twice(
3860+ kind: &ElementKind,
3861+ token: &syntax::Arg,
3862+ key: &str,
3863+ value: &str,
3864+ text: &syntax::Text,
3865+ ctx: &ParseContext,
3866+) -> Diagnostic {
3867+ let name = kind.name();
3868+ let what = leading_name(kind);
3869+ // The value as one token: quoted when it is empty or has a space in it
3870+ let value = if !value.is_empty() && syntax::leading_token_len(value) == value.len() {
3871+ value.to_string()
3872+ } else {
3873+ format!("\"{}\"", value.replace('\\', "\\\\").replace('"', "\\\""))
3874+ };
3875+ let written = if takes_no_text(kind) {
3876+ format!("@{} {}", name, value)
3877+ } else {
3878+ format!("@{} {} {}", name, value, text.raw)
3879+ };
3880+ let d = Diagnostic::error(
3881+ code::DUPLICATE_ATTRIBUTE,
3882+ text.span.line,
3883+ format!(
3884+ "@{} takes its first word '{}' as its {}, and it also has {}=: give it once, \
3885+ as `{}`",
3886+ name, token.raw, what, key, written
3887+ ),
3888+ )
3889+ .subject(token.raw.clone());
3890+ at_attribute(d, Some(token.span.column), ctx)
3891+}
3892+
3893+/// The attribute an element's leading argument fills, for messages.
3894+fn leading_name(kind: &ElementKind) -> &'static str {
3895+ match kind.arg() {
3896+ TagArg::Source => "srcset in @picture or src elsewhere",
3897+ arg => arg.attribute(false).unwrap_or("argument"),
3898+ }
12543899}
12553900
1256−/// The directive names (without `@`) the parser recognizes, for tools such
1257−/// as the language server.
1258−pub fn known_directives() -> &'static [&'static str] {
1259− KNOWN_DIRECTIVES
3901+/// Whether text after an element's leading argument has nowhere to go:
3902+/// an element without content (`@image`, `@source`, ...), or `@optgroup`,
3903+/// which holds only `@option` lines, so `@optgroup Citrus fruits` would
3904+/// otherwise make `Citrus` the label and drop `fruits`.
3905+fn takes_no_text(kind: &ElementKind) -> bool {
3906+ kind.layout() == Layout::Void || kind.is_tag("optgroup")
12603907}
12613908
1262−const KNOWN_DIRECTIVES: &[&str] = &[
1263− "page", "let", "include", "raw", "if", "else", "each", "meta", "head", "style", "markdown",
1264− "data",
1265−];
3909+/// Text after the leading argument of an element without content:
3910+/// `@image logo.png Our logo`.
3911+fn after_the_leading_argument(kind: &ElementKind, token: &str, rest: &syntax::Text) -> Diagnostic {
3912+ let name = kind.name();
3913+ let attr = leading_name(kind);
3914+ let alt = if matches!(kind, ElementKind::Image) || kind.is_tag("area") {
3915+ " For a text alternative, write `alt=...`."
3916+ } else {
3917+ ""
3918+ };
3919+ let holds = if kind.layout() == Layout::Void {
3920+ "it has no content"
3921+ } else {
3922+ "it holds only the elements on the lines under it"
3923+ };
3924+ let bare = syntax::quoted_string(token).unwrap_or(token);
3925+ Diagnostic::error(
3926+ code::UNEXPECTED_ARGUMENT,
3927+ rest.span.line,
3928+ format!(
3929+ "@{0} takes one word after its attributes, its {1} ('{2}'), and {5}, so '{3}' \
3930+ would go nowhere. A value with a space in it is quoted: `\"{6} {3}\"`.{4}",
3931+ name, attr, token, rest.raw, alt, holds, bare
3932+ ),
3933+ )
3934+ .subject(rest.raw.clone())
3935+}
12663936
1267−fn parse_element_kind(s: &str, line_num: usize) -> Result<ElementKind, ParseError> {
1268− if let Some(kind) = ElementKind::from_name(s) {
3937+/// The element named `name`, or an "unknown element" error that suggests
3938+/// the closest element, directive or function.
3939+fn parse_element_kind(
3940+ name: &str,
3941+ line_num: usize,
3942+ ctx: &mut ParseContext,
3943+) -> Result<ElementKind, ParseError> {
3944+ if let Some(kind) = ElementKind::from_name(name) {
12693945 return Ok(kind);
12703946 }
3947+ // A known name in a place it can't go: say why instead of suggesting
3948+ // the name itself.
3949+ let misplaced = if crate::ast::directive(name).is_some() {
3950+ Some(format!(
3951+ "unknown element @{}: @{} is a directive, which goes at the start of its own line",
3952+ name, name
3953+ ))
3954+ } else if ctx.env.bundle(name).is_some() {
3955+ Some(format!(
3956+ "unknown element @{}: '{}' is an attribute bundle, used as `[${}]` \
3957+ (a function is defined with `@let @{}`)",
3958+ name, name, name, name
3959+ ))
3960+ } else if ctx.env.value(name).is_some() {
3961+ Some(format!(
3962+ "unknown element @{}: '{}' is a value, used as `${}` \
3963+ (a function is defined with `@let @{}`)",
3964+ name, name, name, name
3965+ ))
3966+ } else if ctx.namespace.contains(name) {
3967+ ctx.used_functions.insert(name.to_string());
3968+ Some(format!(
3969+ "unknown element @{}: the function @{} isn't visible here. A definition is \
3970+ visible from its line to the end of its block, and a function's body sees what \
3971+ is defined above the function, so define @{} above this line, outside the block \
3972+ it is in",
3973+ name, name, name
3974+ ))
3975+ } else if matches!(name, "svg" | "math" | "template") {
3976+ Some(format!(
3977+ "unknown element @{}: htmlang doesn't write <{}>; put its markup in the page with \
3978+ @raw{}",
3979+ name,
3980+ name,
3981+ if name == "svg" {
3982+ " (or an SVG file with `@image [inline] file.svg`)"
3983+ } else {
3984+ ""
3985+ }
3986+ ))
3987+ } else {
3988+ None
3989+ };
3990+ if let Some(message) = misplaced {
3991+ return Err(Diagnostic::error(code::UNKNOWN_ELEMENT, line_num, message).subject(name));
3992+ }
12713993 let all_known: Vec<&str> = ElementKind::all_names()
1272− .chain(KNOWN_DIRECTIVES.iter().copied())
3994+ .chain(DIRECTIVES.iter().map(|d| d.name))
12733995 .collect();
1274− let message = match suggest_closest(s, &all_known) {
1275− Some(closest) => format!("unknown element @{}, did you mean @{}?", s, closest),
1276− None => format!("unknown element @{}", s),
3996+ // An HTML element htmlang writes under its own name (`@a` is `@link`).
3997+ let written_otherwise = crate::ast::HTML_NAMES_WRITTEN_OTHERWISE
3998+ .iter()
3999+ .find(|(html, _)| *html == name)
4000+ .map(|(_, htmlang)| *htmlang);
4001+ let closest = written_otherwise.or_else(|| suggest_closest(name, &all_known));
4002+ let mut message = match (closest, written_otherwise) {
4003+ (Some(closest), Some(_)) => format!(
4004+ "unknown element @{}, did you mean @{}? (@{} writes <{}>)",
4005+ name, closest, closest, name
4006+ ),
4007+ (Some(closest), None) => format!("unknown element @{}, did you mean @{}?", name, closest),
4008+ (None, _) => format!("unknown element @{}", name),
12774009 };
1278− Err(ParseError {
1279− line: line_num,
1280− message,
1281− })
4010+ let function = suggest_fn_name(name, ctx);
4011+ if let Some(function) = &function {
4012+ message = format!("{}, or did you mean @{}?", message, function);
4013+ }
4014+ Err(Diagnostic::error(code::UNKNOWN_ELEMENT, line_num, message)
4015+ .subject(name)
4016+ .suggest(closest.map(str::to_string).or(function)))
12824017}
12834018
12844019/// Format include/import stack as a readable chain for error messages.
@@ -1349,34 +4084,37 @@ fn suggest_closest<'a>(input: &str, candidates: &[&'a str]) -> Option<&'a str> {
13494084 best
13504085}
13514086
1352−/// Suggest the closest user-defined function name for typos.
4087+/// Suggest the closest user-defined function name for typos, from the
4088+/// functions defined so far and those defined anywhere in the file.
13534089fn suggest_fn_name(input: &str, ctx: &ParseContext) -> Option<String> {
13544090 let input_chars: Vec<char> = input.chars().collect();
13554091 let max_allowed = 2usize.min(input_chars.len().saturating_sub(1));
1356− let mut best: Option<String> = None;
1357− let mut best_dist = usize::MAX;
1358− for name in ctx.functions.keys() {
4092+ let mut best: Option<(usize, &String)> = None;
4093+ let visible: Vec<&String> = ctx.defined_functions.keys().collect();
4094+ for name in visible.into_iter().chain(ctx.namespace.iter()) {
13594095 let nlen = name.chars().count();
13604096 if nlen.abs_diff(input_chars.len()) > max_allowed {
13614097 continue;
13624098 }
13634099 let name_chars: Vec<char> = name.chars().collect();
13644100 let dist = levenshtein_bounded(&input_chars, &name_chars, max_allowed);
1365− if dist < best_dist && dist <= max_allowed {
1366− best_dist = dist;
1367− best = Some(name.clone());
4101+ if dist <= max_allowed && best.is_none_or(|b| (dist, name) < b) {
4102+ best = Some((dist, name));
13684103 }
13694104 }
1370− best
4105+ best.map(|(_, name)| name.clone())
13714106}
13724107
13734108/// Suggest the closest variable name for undefined `$var` references.
1374−fn suggest_var_name(input: &str, vars: &HashMap<String, String>) -> Option<String> {
4109+fn suggest_var_name(input: &str, vars: &[&str]) -> Option<String> {
13754110 let input_chars: Vec<char> = input.chars().collect();
13764111 let max_allowed = 2usize.min(input_chars.len().saturating_sub(1));
13774112 let mut best: Option<String> = None;
13784113 let mut best_dist = usize::MAX;
1379− for name in vars.keys().filter(|k| !k.ends_with('#')) {
4114+ let mut vars = vars.to_vec();
4115+ // The same answer every time, whatever the order of the names
4116+ vars.sort_unstable();
4117+ for name in vars {
13804118 let nlen = name.chars().count();
13814119 if nlen.abs_diff(input_chars.len()) > max_allowed {
13824120 continue;
@@ -1385,993 +4123,1950 @@ fn suggest_var_name(input: &str, vars: &HashMap<String, String>) -> Option<Strin
13854123 let dist = levenshtein_bounded(&input_chars, &name_chars, max_allowed);
13864124 if dist < best_dist && dist <= max_allowed {
13874125 best_dist = dist;
1388− best = Some(name.clone());
4126+ best = Some(name.to_string());
13894127 }
13904128 }
13914129 best
13924130}
13934131
1394−/// Check for undefined `$var` references and return "did you mean?" diagnostics.
1395−/// `indent` is the line's leading whitespace, which `input` has had trimmed;
1396−/// reported columns and source lines include it.
1397−fn check_undefined_vars(
1398− input: &str,
1399− vars: &HashMap<String, String>,
1400− line_num: usize,
1401− indent: usize,
1402−) -> Vec<Diagnostic> {
1403− let mut warnings = Vec::new();
1404− if !input.contains('$') {
1405− return warnings;
1406− }
1407− let chars: Vec<char> = input.chars().collect();
1408− let mut i = 0;
1409− while i < chars.len() {
1410− if chars[i] == '$'
1411− && i + 1 < chars.len()
1412− && (chars[i + 1].is_alphanumeric() || chars[i + 1] == '_' || chars[i + 1] == '-')
1413− {
1414− let col = i;
1415− let start = i + 1;
1416− let mut end = start;
1417− while end < chars.len()
1418− && (chars[end].is_alphanumeric()
1419− || chars[end] == '-'
1420− || chars[end] == '_'
1421− || chars[end] == '.')
1422− {
1423− end += 1;
1424− }
1425− while end > start && chars[end - 1] == '.' {
1426− end -= 1;
1427− }
1428− let name: String = chars[start..end].iter().collect();
1429− if !name.is_empty()
1430− && !vars.contains_key(&name)
1431− && let Some(closest) = suggest_var_name(&name, vars)
1432− {
1433− warnings.push(Diagnostic {
1434− line: line_num,
1435− column: Some(indent + col),
1436− message: format!(
1437− "undefined variable '${}', did you mean '${}'?",
1438− name, closest
1439− ),
1440− severity: Severity::Warning,
1441− source_line: Some(format!("{}{}", " ".repeat(indent), input)),
1442− });
1443− }
1444− i = end;
1445− } else {
1446− i += 1;
1447− }
1448− }
1449− warnings
1450−}
1451−
14524132// ---------------------------------------------------------------------------
14534133// Attribute parsing
14544134// ---------------------------------------------------------------------------
14554135
1456−/// Attributes that expect purely numeric values (px-based) or values with CSS units.
1457−const NUMERIC_ATTRS: &[&str] = &[
1458− "spacing",
1459− "gap",
1460− "padding",
1461− "padding-top",
1462− "padding-bottom",
1463− "padding-left",
1464− "padding-right",
1465− "min-width",
1466− "max-width",
1467− "min-height",
1468− "max-height",
1469− "border-radius",
1470− "font-size",
1471− "column-gap",
1472− "row-gap",
1473− "top",
1474− "right",
1475− "bottom",
1476− "left",
1477− "letter-spacing",
1478−];
1479−
1480−const CSS_UNIT_SUFFIXES: &[&str] = &[
1481− "px", "%", "rem", "em", "vh", "vw", "vmin", "vmax", "dvh", "svh", "lvh", "ch", "ex", "cm",
1482− "mm", "in", "pt", "pc", "fr",
1483−];
1484−
1485−fn has_css_unit(value: &str) -> bool {
1486− CSS_UNIT_SUFFIXES.iter().any(|u| value.ends_with(u))
1487− || value.starts_with("var(")
1488− || value.starts_with("calc(")
1489− || value.starts_with("clamp(")
1490− || value.starts_with("min(")
1491− || value.starts_with("max(")
1492−}
1493−
1494−/// Attributes that accept numeric OR keyword values.
1495−const NUMERIC_OR_KEYWORD_ATTRS: &[&str] = &["width", "height"];
1496−const SIZE_KEYWORDS: &[&str] = &["fill", "shrink"];
1497−
1498−fn validate_attr_value(attr: &Attribute, line_num: usize, ctx: &mut ParseContext) {
1499− let base_key = crate::vocab::base_attribute(attr.key.as_str());
1500−
1501− if let Some(val) = &attr.value {
1502− if NUMERIC_ATTRS.contains(&base_key) {
1503− // All space-separated parts must be numeric or have a CSS unit
1504− for part in val.split_whitespace() {
1505− if part.parse::<f64>().is_err() && !has_css_unit(part) {
1506− ctx.diagnostics.push(Diagnostic {
1507− line: line_num,
1508− column: None,
1509− message: format!(
1510− "'{}' expects a numeric value (with optional unit), got '{}'",
1511− attr.key, val
1512− ),
1513− severity: Severity::Warning,
1514− source_line: None,
1515− });
1516− return;
1517− }
4136+/// The quoted strings of a CSS value, without their quotes.
4137+fn css_strings(value: &str) -> Vec<&str> {
4138+ let mut strings = Vec::new();
4139+ let mut start = None;
4140+ let mut escaped = false;
4141+ for (i, c) in value.char_indices() {
4142+ match (c, start) {
4143+ _ if escaped => escaped = false,
4144+ ('\\', Some(_)) => escaped = true,
4145+ ('"', None) => start = Some(i + 1),
4146+ ('"', Some(from)) => {
4147+ strings.push(&value[from..i]);
4148+ start = None;
15184149 }
1519− } else if NUMERIC_OR_KEYWORD_ATTRS.contains(&base_key) {
1520− let is_keyword = SIZE_KEYWORDS.contains(&val.as_str());
1521− let is_numeric = val.parse::<f64>().is_ok();
1522− let has_unit = has_css_unit(val);
1523− if !is_keyword && !is_numeric && !has_unit {
1524− ctx.diagnostics.push(Diagnostic {
1525− line: line_num,
1526− column: None,
1527− message: format!(
1528− "'{}' expects a number or one of [{}], got '{}'",
1529− attr.key,
1530− SIZE_KEYWORDS.join(", "),
1531− val
1532− ),
1533− severity: Severity::Warning,
1534− source_line: None,
1535− });
4150+ _ => {}
4151+ }
4152+ }
4153+ strings
4154+}
4155+
4156+/// An `if(...)` in a CSS value that isn't CSS's if(): CSS writes each
4157+/// branch `CONDITION: VALUE`, so an if() without a `:` is something else.
4158+/// Quoted CSS strings are text, not calls.
4159+fn not_css_if(value: &str) -> Option<&str> {
4160+ let mut quote = None;
4161+ let mut prev = None;
4162+ let mut chars = value.char_indices();
4163+ while let Some((at, c)) = chars.next() {
4164+ match quote {
4165+ Some(_) if c == '\\' => {
4166+ chars.next();
15364167 }
1537− } else if base_key == "opacity" {
1538− if let Ok(v) = val.parse::<f64>() {
1539− if !(0.0..=1.0).contains(&v) {
1540− ctx.diagnostics.push(Diagnostic {
1541− line: line_num,
1542− column: None,
1543− message: format!("'opacity' should be between 0 and 1, got '{}'", val),
1544− severity: Severity::Warning,
1545− source_line: None,
4168+ Some(q) if c == q => quote = None,
4169+ Some(_) => {}
4170+ None if matches!(c, '"' | '\'') => quote = Some(c),
4171+ None => {
4172+ let word_before =
4173+ prev.is_some_and(|p: char| p.is_alphanumeric() || matches!(p, '-' | '_'));
4174+ if !word_before && value[at..].starts_with("if(") {
4175+ let mut depth = 0;
4176+ let close = value[at + 2..].char_indices().find_map(|(i, c)| {
4177+ match c {
4178+ '(' => depth += 1,
4179+ ')' => depth -= 1,
4180+ _ => {}
4181+ }
4182+ (depth == 0).then_some(at + 2 + i)
15464183 });
4184+ let end = close.map_or(value.len(), |c| c + 1);
4185+ if !value[at + 3..end].contains(':') {
4186+ return Some(&value[at..end]);
4187+ }
15474188 }
1548− } else {
1549− ctx.diagnostics.push(Diagnostic {
1550− line: line_num,
1551− column: None,
1552− message: format!("'opacity' expects a numeric value, got '{}'", val),
1553− severity: Severity::Warning,
1554− source_line: None,
1555− });
15564189 }
1557− } else if base_key == "z-index" {
1558− if val.parse::<i32>().is_err() {
1559− ctx.diagnostics.push(Diagnostic {
1560− line: line_num,
1561− column: None,
1562− message: format!("'z-index' expects an integer, got '{}'", val),
1563− severity: Severity::Warning,
1564− source_line: None,
1565− });
4190+ }
4191+ prev = Some(c);
4192+ }
4193+ None
4194+}
4195+
4196+/// Why a CSS value can't be written into a rule as it is, whatever it
4197+/// means: a `;` (outside parentheses, where CSS's own `if()` uses it), a
4198+/// `{` or a `}` would end the declaration or the rule, and an unclosed
4199+/// quote or parenthesis would run on into the rules after it. Quoted
4200+/// strings are text, and a backslash escapes the character after it, as
4201+/// in CSS. A `</style` anywhere, even in a string, would end the page's
4202+/// `<style>` element and start HTML.
4203+fn css_breakout(value: &str) -> Option<&'static str> {
4204+ if value.to_ascii_lowercase().contains("</style") {
4205+ return Some("a `</style`, which would end the page's style element");
4206+ }
4207+ let mut quote = None;
4208+ let mut depth = 0usize;
4209+ let mut chars = value.chars();
4210+ while let Some(c) = chars.next() {
4211+ match (quote, c) {
4212+ (_, '\\') => {
4213+ chars.next();
15664214 }
1567− } else if base_key == "display" {
1568− const DISPLAY_VALUES: &[&str] = &[
1569− "none",
1570− "block",
1571− "inline",
1572− "inline-block",
1573− "flex",
1574− "inline-flex",
1575− "grid",
1576− "inline-grid",
1577− "table",
1578− "table-row",
1579− "table-cell",
1580− "contents",
1581− "flow-root",
1582− "list-item",
1583− ];
1584− if !DISPLAY_VALUES.contains(&val.as_str()) && !val.starts_with("var(") {
1585− let suggestion = suggest_closest(val, DISPLAY_VALUES);
1586− let msg = match suggestion {
1587− Some(s) => format!("unknown display value '{}', did you mean '{}'?", val, s),
1588− None => format!("unknown display value '{}'", val),
1589− };
1590− ctx.diagnostics.push(Diagnostic {
1591− line: line_num,
1592− column: None,
1593− message: msg,
1594− severity: Severity::Warning,
1595− source_line: None,
1596− });
4215+ (Some(q), c) if c == q => quote = None,
4216+ (Some(_), _) => {}
4217+ (None, '"' | '\'') => quote = Some(c),
4218+ (None, '(') => depth += 1,
4219+ (None, ')') if depth == 0 => return Some("a `)` that closes nothing"),
4220+ (None, ')') => depth -= 1,
4221+ (None, ';') if depth == 0 => return Some("a `;`, which would end the declaration"),
4222+ (None, '{' | '}') => return Some("a `{` or `}`, which would end the CSS rule"),
4223+ _ => {}
4224+ }
4225+ }
4226+ match (quote, depth) {
4227+ (Some('"'), _) => Some("a `\"` that isn't closed"),
4228+ (Some(_), _) => Some("a `'` that isn't closed"),
4229+ (None, 0) => None,
4230+ (None, _) => Some("a `(` that isn't closed"),
4231+ }
4232+}
4233+
4234+/// The hex colors of a CSS value that don't have 3, 4, 6 or 8 hex
4235+/// digits. A `#` word in a CSS value is a color, except inside `url(...)`
4236+/// and quoted strings.
4237+fn bad_hex_colors(value: &str) -> Vec<&str> {
4238+ let mut bad = Vec::new();
4239+ let mut quote = None;
4240+ let mut in_url = 0usize;
4241+ let mut depth = 0usize;
4242+ let mut chars = value.char_indices().peekable();
4243+ while let Some((at, c)) = chars.next() {
4244+ match (quote, c) {
4245+ (_, '\\') => {
4246+ chars.next();
15974247 }
1598− } else if base_key == "position" {
1599− const POSITION_VALUES: &[&str] = &["static", "relative", "absolute", "fixed", "sticky"];
1600− if !POSITION_VALUES.contains(&val.as_str()) && !val.starts_with("var(") {
1601− let suggestion = suggest_closest(val, POSITION_VALUES);
1602− let msg = match suggestion {
1603− Some(s) => format!("unknown position value '{}', did you mean '{}'?", val, s),
1604− None => format!("unknown position value '{}'", val),
1605− };
1606− ctx.diagnostics.push(Diagnostic {
1607− line: line_num,
1608− column: None,
1609− message: msg,
1610− severity: Severity::Warning,
1611− source_line: None,
1612− });
4248+ (Some(q), c) if c == q => quote = None,
4249+ (Some(_), _) => {}
4250+ (None, '"' | '\'') => quote = Some(c),
4251+ (None, '(') => {
4252+ depth += 1;
4253+ if value[..at].ends_with("url") && in_url == 0 {
4254+ in_url = depth;
4255+ }
16134256 }
1614− } else if base_key == "overflow" || base_key == "overflow-x" || base_key == "overflow-y" {
1615− const OVERFLOW_VALUES: &[&str] = &["visible", "hidden", "scroll", "auto", "clip"];
1616− if !OVERFLOW_VALUES.contains(&val.as_str()) && !val.starts_with("var(") {
1617− let suggestion = suggest_closest(val, OVERFLOW_VALUES);
1618− let msg = match suggestion {
1619− Some(s) => format!("unknown overflow value '{}', did you mean '{}'?", val, s),
1620− None => format!("unknown overflow value '{}'", val),
1621− };
1622− ctx.diagnostics.push(Diagnostic {
1623− line: line_num,
1624− column: None,
1625− message: msg,
1626− severity: Severity::Warning,
1627− source_line: None,
1628− });
4257+ (None, ')') => {
4258+ if in_url == depth {
4259+ in_url = 0;
4260+ }
4261+ depth = depth.saturating_sub(1);
16294262 }
1630− } else if base_key == "text-align" {
1631− const TEXT_ALIGN_VALUES: &[&str] =
1632− &["left", "right", "center", "justify", "start", "end"];
1633− if !TEXT_ALIGN_VALUES.contains(&val.as_str()) && !val.starts_with("var(") {
1634− let suggestion = suggest_closest(val, TEXT_ALIGN_VALUES);
1635− let msg = match suggestion {
1636− Some(s) => format!("unknown text-align value '{}', did you mean '{}'?", val, s),
1637− None => format!("unknown text-align value '{}'", val),
1638− };
1639− ctx.diagnostics.push(Diagnostic {
1640− line: line_num,
1641− column: None,
1642− message: msg,
1643− severity: Severity::Warning,
1644− source_line: None,
1645− });
4263+ (None, '#') if in_url == 0 => {
4264+ let end = value[at + 1..]
4265+ .find(|c: char| !(c.is_alphanumeric() || c == '-' || c == '_'))
4266+ .map_or(value.len(), |n| at + 1 + n);
4267+ let hex = &value[at + 1..end];
4268+ if !(matches!(hex.len(), 3 | 4 | 6 | 8)
4269+ && hex.chars().all(|c| c.is_ascii_hexdigit()))
4270+ {
4271+ bad.push(&value[at..end]);
4272+ }
16464273 }
1647− } else if base_key == "cursor" {
1648− const CURSOR_VALUES: &[&str] = &[
1649− "auto",
1650− "default",
1651− "none",
1652− "pointer",
1653− "wait",
1654− "text",
1655− "move",
1656− "not-allowed",
1657− "crosshair",
1658− "grab",
1659− "grabbing",
1660− "help",
1661− "progress",
1662− "col-resize",
1663− "row-resize",
1664− "n-resize",
1665− "s-resize",
1666− "e-resize",
1667− "w-resize",
1668− "zoom-in",
1669− "zoom-out",
1670− "context-menu",
1671− "cell",
1672− "copy",
1673− "alias",
1674− "no-drop",
1675− ];
1676− if !CURSOR_VALUES.contains(&val.as_str())
1677− && !val.starts_with("url(")
1678− && !val.starts_with("var(")
4274+ _ => {}
4275+ }
4276+ }
4277+ bad
4278+}
4279+
4280+/// A diagnostic about an attribute, with its column and source line when
4281+/// it is on the line being evaluated.
4282+fn at_attribute(diagnostic: Diagnostic, column: Option<usize>, ctx: &ParseContext) -> Diagnostic {
4283+ match (&ctx.current_source, column) {
4284+ ((current, Some(text)), Some(column)) if *current == diagnostic.line => {
4285+ diagnostic.column(column).source(text.clone())
4286+ }
4287+ _ => diagnostic,
4288+ }
4289+}
4290+
4291+/// Check a style's value. Values go to the CSS as written, so only what
4292+/// can't be wrong in any CSS is checked: a value that would break out of
4293+/// its rule is an error (and it is left out); a hex color without 3, 4, 6
4294+/// or 8 digits, an `if()` that isn't CSS's and a quoted font stack are
4295+/// warnings. Returns whether the value can be written.
4296+fn check_css_value(
4297+ attr: &Attribute,
4298+ base: &str,
4299+ line: usize,
4300+ column: Option<usize>,
4301+ ctx: &mut ParseContext,
4302+) -> bool {
4303+ let Some(value) = &attr.value else {
4304+ return true;
4305+ };
4306+ if let Some(reason) = css_breakout(value) {
4307+ let diagnostic = Diagnostic::error(
4308+ code::INVALID_VALUE,
4309+ line,
4310+ format!(
4311+ "the value of '{}' has {}: `{}` can't be written into the page's CSS",
4312+ attr.key, reason, value
4313+ ),
4314+ )
4315+ .subject(value.as_str());
4316+ ctx.diagnostics.push(at_attribute(diagnostic, column, ctx));
4317+ return false;
4318+ }
4319+ if crate::vocab::is_custom_property(base) {
4320+ return true;
4321+ }
4322+
4323+ let warn = |ctx: &mut ParseContext, diagnostic: Diagnostic| {
4324+ let diagnostic = at_attribute(diagnostic, column, ctx);
4325+ ctx.diagnostics.push(diagnostic);
4326+ };
4327+ // In CSS, a quoted font-family is one family, commas and all
4328+ if base == "font-family"
4329+ && let Some(family) = css_strings(value).into_iter().find(|s| s.contains(','))
4330+ {
4331+ let stack = family
4332+ .split(',')
4333+ .map(str::trim)
4334+ .collect::<Vec<_>>()
4335+ .join("\\, ");
4336+ warn(
4337+ ctx,
4338+ Diagnostic::warning(
4339+ code::INVALID_VALUE,
4340+ line,
4341+ format!(
4342+ "font-family \"{}\" is one family, whose name has a comma in it: \
4343+ for a font stack, write `font-family {}`",
4344+ family, stack
4345+ ),
4346+ )
4347+ .subject(format!("\"{}\"", family))
4348+ .suggest(Some(stack)),
4349+ );
4350+ }
4351+ if let Some(call) = not_css_if(value) {
4352+ warn(
4353+ ctx,
4354+ Diagnostic::warning(
4355+ code::INVALID_VALUE,
4356+ line,
4357+ format!(
4358+ "'{}' is not CSS's if(), whose branches are written \
4359+ `if(CONDITION: VALUE; else: VALUE)`",
4360+ call
4361+ ),
4362+ )
4363+ .subject(call),
4364+ );
4365+ }
4366+ for color in bad_hex_colors(value) {
4367+ warn(
4368+ ctx,
4369+ Diagnostic::warning(
4370+ code::INVALID_COLOR,
4371+ line,
4372+ format!(
4373+ "invalid hex color '{}': a hex color has 3, 4, 6 or 8 hex digits",
4374+ color
4375+ ),
4376+ )
4377+ .subject(color),
4378+ );
4379+ }
4380+ true
4381+}
4382+
4383+/// An unknown prefix: the message, the text it is about, and what to write
4384+/// instead, when something is close enough.
4385+struct PrefixProblem {
4386+ message: String,
4387+ subject: String,
4388+ suggestion: Option<String>,
4389+}
4390+
4391+/// What is wrong with the prefix `rest` starts with, when the known
4392+/// prefixes are already split off it and what is left still starts with
4393+/// one: a word and a `:` (`hovr:`), or a word and a parenthesised argument
4394+/// and a `:` (`nth-chld(2):`). Selector prefixes are CSS's pseudo-classes
4395+/// and pseudo-elements under their CSS names, so an unknown one gets the
4396+/// closest name as a suggestion. Only names with the same first letter are
4397+/// suggested: `odd:` is two edits from `md:`, which it doesn't mean.
4398+fn unknown_prefix(rest: &str) -> Option<PrefixProblem> {
4399+ use crate::vocab::{self, Pseudo};
4400+ let name_len = rest.find(|c: char| !(c.is_ascii_alphanumeric() || c == '-'))?;
4401+ let name = &rest[..name_len];
4402+ if name.is_empty() {
4403+ return None;
4404+ }
4405+ if rest[name_len..].starts_with('(') {
4406+ // `name(...):`: a pseudo-class with an argument
4407+ let close = vocab::closing_paren(rest, name_len)?;
4408+ if !rest[close + 1..].starts_with(':') {
4409+ return None;
4410+ }
4411+ let written = &rest[..close + 2];
4412+ if matches!(vocab::pseudo(name), Some(Pseudo::Class | Pseudo::Element)) {
4413+ let bare = format!("{}:", name);
4414+ return Some(PrefixProblem {
4415+ message: format!(
4416+ "'{}': `{}` takes no argument: write `{}`",
4417+ written,
4418+ vocab::pseudo_selector(&bare).unwrap_or_default(),
4419+ bare
4420+ ),
4421+ subject: written.to_string(),
4422+ suggestion: Some(bare),
4423+ });
4424+ }
4425+ let functional: Vec<&str> = vocab::functional_pseudos()
4426+ .into_iter()
4427+ .filter(|p| p.chars().next() == name.chars().next())
4428+ .collect();
4429+ let suggestion = suggest_closest(name, &functional)
4430+ .filter(|&closest| closest != name)
4431+ .map(|closest| format!("{}(", closest));
4432+ let written = format!("{}(", name);
4433+ let message = match &suggestion {
4434+ Some(closest) => format!("unknown prefix '{}', did you mean '{}'?", written, closest),
4435+ None => format!("unknown prefix '{}'", written),
4436+ };
4437+ return Some(PrefixProblem {
4438+ message,
4439+ subject: written,
4440+ suggestion,
4441+ });
4442+ }
4443+ if !rest[name_len..].starts_with(':') {
4444+ return None;
4445+ }
4446+ let written = &rest[..name_len + 1];
4447+ // `has:`: its argument is missing
4448+ if vocab::pseudo(name) == Some(Pseudo::Function) {
4449+ return Some(PrefixProblem {
4450+ message: format!(
4451+ "'{}': `:{}()` takes an argument, in parentheses, as in CSS: `{}(...):`",
4452+ written, name, name
4453+ ),
4454+ subject: written.to_string(),
4455+ suggestion: None,
4456+ });
4457+ }
4458+ let prefixes = vocab::all_prefixes();
4459+ let candidates: Vec<&str> = prefixes
4460+ .iter()
4461+ .map(String::as_str)
4462+ .filter(|p| p.chars().next() == written.chars().next())
4463+ .collect();
4464+ // The closest name that starts with the same letter (`hvoer:` →
4465+ // `hover:`), else the first that starts with the word written and a `-`
4466+ // (`first:` → `first-child:`)
4467+ let suggestion = suggest_closest(written, &candidates)
4468+ .or_else(|| {
4469+ let longer = format!("{}-", name);
4470+ candidates.iter().copied().find(|p| p.starts_with(&longer))
4471+ })
4472+ .filter(|&closest| closest != written)
4473+ .map(str::to_string);
4474+ let message = match &suggestion {
4475+ Some(closest) => format!("unknown prefix '{}', did you mean '{}'?", written, closest),
4476+ None => format!("unknown prefix '{}'", written),
4477+ };
4478+ Some(PrefixProblem {
4479+ message,
4480+ subject: written.to_string(),
4481+ suggestion,
4482+ })
4483+}
4484+
4485+/// Check an attribute's element prefix (`@td:padding 8`), when it has one:
4486+/// it names a built-in element that has an HTML tag of its own (not a
4487+/// function, and not `@el`, whose `<div>` other elements write too), there
4488+/// is one, not with `children:`, and what it styles is a CSS property, not
4489+/// one of htmlang's words, which compile against each element's layout and
4490+/// its parent's. Returns false, after reporting, when the attribute can't
4491+/// be written.
4492+fn check_element_prefixes(
4493+ attr: &Attribute,
4494+ prefixes: &[&str],
4495+ base: &str,
4496+ line: usize,
4497+ column: Option<usize>,
4498+ ctx: &mut ParseContext,
4499+) -> bool {
4500+ use crate::ast::ElementKind;
4501+ use crate::vocab;
4502+ let elements: Vec<&str> = prefixes
4503+ .iter()
4504+ .copied()
4505+ .filter(|p| vocab::element_prefix(p).is_some())
4506+ .collect();
4507+ let Some(&prefix) = elements.first() else {
4508+ return true;
4509+ };
4510+ let fail = |ctx: &mut ParseContext,
4511+ code: &'static str,
4512+ message: String,
4513+ subject: &str,
4514+ suggestion: Option<String>| {
4515+ let diagnostic = Diagnostic::error(code, line, message)
4516+ .subject(subject)
4517+ .suggest(suggestion);
4518+ let diagnostic = at_attribute(diagnostic, column, ctx);
4519+ ctx.diagnostics.push(diagnostic);
4520+ false
4521+ };
4522+ let name = vocab::element_prefix(prefix).unwrap_or_default();
4523+ if is_function(name, ctx) {
4524+ return fail(
4525+ ctx,
4526+ code::INVALID_PREFIX,
4527+ format!(
4528+ "'{}': @{} is a function, and `{}` would pick elements out by their HTML tag, \
4529+ which a function doesn't have: style what @{} writes in its body, or pass it \
4530+ attributes",
4531+ attr.key, name, prefix, name
4532+ ),
4533+ prefix,
4534+ None,
4535+ );
4536+ }
4537+ match ElementKind::from_name(name) {
4538+ None => {
4539+ let own: Vec<&str> = ElementKind::all_names()
4540+ .filter(|n| ElementKind::from_name(n).is_some_and(|k| k.own_tag().is_some()))
4541+ .collect();
4542+ // An HTML name htmlang writes under another (`@a:` is `@link:`)
4543+ let (written_otherwise, shared) = match crate::ast::HTML_NAMES_WRITTEN_OTHERWISE
4544+ .iter()
4545+ .find(|(html, _)| *html == name)
16794546 {
1680− let suggestion = suggest_closest(val, CURSOR_VALUES);
1681− let msg = match suggestion {
1682− Some(s) => format!("unknown cursor value '{}', did you mean '{}'?", val, s),
1683− None => format!("unknown cursor value '{}'", val),
1684− };
1685− ctx.diagnostics.push(Diagnostic {
1686− line: line_num,
1687− column: None,
1688− message: msg,
1689− severity: Severity::Warning,
1690− source_line: None,
1691− });
4547+ Some((_, htmlang)) if own.contains(htmlang) => (Some(*htmlang), false),
4548+ Some(_) => (None, true),
4549+ None => (None, false),
4550+ };
4551+ // `@each:`, `@markdown:`: a directive, which is no element
4552+ if crate::ast::directive(name).is_some() {
4553+ return fail(
4554+ ctx,
4555+ code::UNKNOWN_PREFIX,
4556+ format!(
4557+ "unknown element @{} in '{}': @{} is a directive, and an element \
4558+ prefix names an element with an HTML tag of its own, such as `@td:`",
4559+ name, prefix, name
4560+ ),
4561+ prefix,
4562+ None,
4563+ );
16924564 }
1693− } else if base_key == "font-weight" {
1694− const WEIGHT_VALUES: &[&str] = &[
1695− "normal", "bold", "bolder", "lighter", "100", "200", "300", "400", "500", "600",
1696− "700", "800", "900",
1697− ];
1698− if !WEIGHT_VALUES.contains(&val.as_str()) && !val.starts_with("var(") {
1699− ctx.diagnostics.push(Diagnostic {
1700− line: line_num,
1701− column: None,
1702− message: format!(
1703− "'font-weight' expects a weight keyword or number 100-900, got '{}'",
1704− val
4565+ // `@div:`, `@span:`: several elements write it
4566+ if shared {
4567+ return fail(
4568+ ctx,
4569+ code::UNKNOWN_PREFIX,
4570+ format!(
4571+ "unknown element @{} in '{}': htmlang writes <{}> for several \
4572+ elements, so no element prefix picks it out",
4573+ name, prefix, name
17054574 ),
1706− severity: Severity::Warning,
1707− source_line: None,
1708− });
4575+ prefix,
4576+ None,
4577+ );
17094578 }
1710− } else if base_key == "color" || base_key == "background" {
1711− // Validate named CSS colors (only if not hex, rgb, hsl, var, etc.)
1712− if !val.starts_with('#')
1713− && !val.starts_with("rgb")
1714− && !val.starts_with("hsl")
1715− && !val.starts_with("var(")
1716− && !val.starts_with("linear-gradient")
1717− && !val.starts_with("radial-gradient")
1718− && !val.starts_with("conic-gradient")
1719− && !val.starts_with("oklch")
1720− && !val.starts_with("oklab")
1721− && !val.starts_with("color(")
1722− && !val.starts_with("light-dark(")
1723− && !val.contains("url(")
1724− && !val.contains(' ')
1725− // skip shorthand multi-value
1726− {
1727− const NAMED_COLORS: &[&str] = &[
1728− "transparent",
1729− "currentcolor",
1730− "inherit",
1731− "initial",
1732− "unset",
1733− "black",
1734− "white",
1735− "red",
1736− "green",
1737− "blue",
1738− "yellow",
1739− "orange",
1740− "purple",
1741− "pink",
1742− "brown",
1743− "gray",
1744− "grey",
1745− "cyan",
1746− "magenta",
1747− "lime",
1748− "olive",
1749− "navy",
1750− "teal",
1751− "aqua",
1752− "fuchsia",
1753− "maroon",
1754− "silver",
1755− "coral",
1756− "salmon",
1757− "tomato",
1758− "crimson",
1759− "firebrick",
1760− "darkred",
1761− "indigo",
1762− "violet",
1763− "plum",
1764− "orchid",
1765− "thistle",
1766− "lavender",
1767− "gold",
1768− "khaki",
1769− "wheat",
1770− "tan",
1771− "sienna",
1772− "chocolate",
1773− "peru",
1774− "beige",
1775− "ivory",
1776− "linen",
1777− "snow",
1778− "seashell",
1779− "mintcream",
1780− "skyblue",
1781− "steelblue",
1782− "royalblue",
1783− "dodgerblue",
1784− "cornflowerblue",
1785− "slategray",
1786− "slategrey",
1787− "dimgray",
1788− "dimgrey",
1789− "lightgray",
1790− "lightgrey",
1791− "darkgray",
1792− "darkgrey",
1793− "gainsboro",
1794− "whitesmoke",
1795− ];
1796− if !NAMED_COLORS.contains(&val.to_lowercase().as_str()) {
1797− let lower = val.to_lowercase();
1798− let suggestion = suggest_closest(&lower, NAMED_COLORS);
1799− let msg = match suggestion {
1800− Some(s) => format!("unknown color '{}', did you mean '{}'?", val, s),
1801− None => format!("unknown color '{}'", val),
4579+ // A name with the same first letter first (`@tdd:` is `@td:`)
4580+ let same_letter: Vec<&str> = own
4581+ .iter()
4582+ .copied()
4583+ .filter(|n| n.chars().next() == name.chars().next())
4584+ .collect();
4585+ let closest = written_otherwise
4586+ .or_else(|| suggest_closest(name, &same_letter))
4587+ .or_else(|| suggest_closest(name, &own));
4588+ let message = match (closest, written_otherwise) {
4589+ (Some(closest), Some(_)) => format!(
4590+ "unknown element @{} in '{}', did you mean '@{}:'? (@{} writes <{}>)",
4591+ name, prefix, closest, closest, name
4592+ ),
4593+ (Some(closest), None) => format!(
4594+ "unknown element @{} in '{}', did you mean '@{}:'?",
4595+ name, prefix, closest
4596+ ),
4597+ (None, _) => format!("unknown element @{} in '{}'", name, prefix),
4598+ };
4599+ let suggestion = closest.map(|c| format!("@{}:", c));
4600+ fail(ctx, code::UNKNOWN_PREFIX, message, prefix, suggestion)
4601+ }
4602+ Some(kind) if kind.own_tag().is_none() => {
4603+ let reason = match kind.tag() {
4604+ None => format!(
4605+ "@{} writes no element of its own, so there is nothing for `{}` to style",
4606+ name, prefix
4607+ ),
4608+ Some(_) if kind.is_verbatim() => {
4609+ format!("@{} isn't shown, so there is nothing to style", name)
4610+ }
4611+ Some("span") => format!(
4612+ "@{} writes a <span>, as every line of text in a row or column does, so \
4613+ `{}` can't pick it out",
4614+ name, prefix
4615+ ),
4616+ Some(tag) => {
4617+ let others: Vec<String> = ElementKind::all_names()
4618+ .filter(|n| {
4619+ *n != name
4620+ && ElementKind::from_name(n).and_then(|k| k.tag()) == Some(tag)
4621+ })
4622+ .map(|n| format!("@{}", n))
4623+ .collect();
4624+ let others = match others.split_last() {
4625+ Some((last, [])) => last.clone(),
4626+ Some((last, rest)) => format!("{} and {}", rest.join(", "), last),
4627+ None => String::new(),
18024628 };
1803− ctx.diagnostics.push(Diagnostic {
1804− line: line_num,
1805− column: None,
1806− message: msg,
1807− severity: Severity::Warning,
1808− source_line: None,
1809− });
4629+ format!(
4630+ "@{} writes a <{}>, as {} do, so `{}` can't pick it out",
4631+ name, tag, others, prefix
4632+ )
18104633 }
4634+ };
4635+ fail(
4636+ ctx,
4637+ code::INVALID_PREFIX,
4638+ format!(
4639+ "'{}': {}. Give those elements their styles themselves, or a bundle \
4640+ (`@let name [...]`, used as `[$name]`)",
4641+ attr.key, reason
4642+ ),
4643+ prefix,
4644+ None,
4645+ )
4646+ }
4647+ Some(_) if elements.len() > 1 => fail(
4648+ ctx,
4649+ code::INVALID_PREFIX,
4650+ format!(
4651+ "'{}': a style takes one element prefix, which styles every such element \
4652+ inside this one, at any depth",
4653+ attr.key
4654+ ),
4655+ &attr.key,
4656+ None,
4657+ ),
4658+ Some(_) if prefixes.contains(&vocab::CHILDREN) => fail(
4659+ ctx,
4660+ code::INVALID_PREFIX,
4661+ format!(
4662+ "'{}': `children:` and `{}` each say which elements the style is for: write \
4663+ one of them",
4664+ attr.key, prefix
4665+ ),
4666+ &attr.key,
4667+ None,
4668+ ),
4669+ Some(_) if vocab::is_htmlang_word(base, attr.value.as_deref()) => {
4670+ let value = attr.value.as_deref().map(str::trim);
4671+ let css = match (base, value) {
4672+ ("spacing", _) => " (`gap`)",
4673+ ("wrap", _) => " (`flex-wrap wrap`)",
4674+ ("grid-cols", _) => " (`grid-template-columns`)",
4675+ ("grid-rows", _) => " (`grid-template-rows`)",
4676+ ("col-span", _) => " (`grid-column span N`)",
4677+ ("row-span", _) => " (`grid-row span N`)",
4678+ ("width", Some("fill")) => " (`flex 1` in a row, `width 100%` otherwise)",
4679+ ("height", Some("fill")) => " (`flex 1` in a column, `height 100%` otherwise)",
4680+ ("width", _) => " (`flex-shrink 0` in a row, `width fit-content` otherwise)",
4681+ ("height", _) => " (`flex-shrink 0` in a column, `height fit-content` otherwise)",
4682+ ("center-x", _) => " (`margin-inline auto`)",
4683+ ("center-y", _) => " (`margin-block auto`)",
4684+ _ => "",
4685+ };
4686+ let word = match value {
4687+ Some(v) if matches!(base, "width" | "height") => format!("{} {}", base, v),
4688+ _ => base.to_string(),
4689+ };
4690+ fail(
4691+ ctx,
4692+ code::INVALID_PREFIX,
4693+ format!(
4694+ "'{}': `{}` is one of htmlang's layout words, which compile against each \
4695+ element's layout and its parent's, and `{}` styles elements whose \
4696+ parents it doesn't know: write `{}` on the elements themselves, or the \
4697+ CSS you mean{}",
4698+ attr.key, word, prefix, word, css
4699+ ),
4700+ &attr.key,
4701+ None,
4702+ )
4703+ }
4704+ Some(_) => true,
4705+ }
4706+}
4707+
4708+/// Check an attribute's prefixes: each is known, their selector prefixes
4709+/// read left to right with a pseudo-element (`before:`) last, the argument
4710+/// of `has(...)` or `nth-child(...)` can be written into the CSS, and a word that
4711+/// places an element in its parent (`width fill`, `center-x`, `align-*`)
4712+/// isn't under `children:`, whose styles go on the children. Media,
4713+/// container and width prefixes go anywhere. Returns false, after
4714+/// reporting, when the attribute can't be written.
4715+fn check_prefixes(
4716+ attr: &Attribute,
4717+ line: usize,
4718+ column: Option<usize>,
4719+ ctx: &mut ParseContext,
4720+) -> bool {
4721+ use crate::vocab;
4722+ let (prefixes, base) = vocab::split_prefixes(&attr.key);
4723+ let fail =
4724+ |ctx: &mut ParseContext, message: String, subject: &str, suggestion: Option<String>| {
4725+ let diagnostic = Diagnostic::error(code::INVALID_PREFIX, line, message)
4726+ .subject(subject)
4727+ .suggest(suggestion);
4728+ let diagnostic = at_attribute(diagnostic, column, ctx);
4729+ ctx.diagnostics.push(diagnostic);
4730+ false
4731+ };
4732+
4733+ if let Some(problem) = unknown_prefix(base) {
4734+ let diagnostic = Diagnostic::error(code::UNKNOWN_PREFIX, line, problem.message)
4735+ .subject(problem.subject)
4736+ .suggest(problem.suggestion);
4737+ let diagnostic = at_attribute(diagnostic, column, ctx);
4738+ ctx.diagnostics.push(diagnostic);
4739+ return false;
4740+ }
4741+ if !check_element_prefixes(attr, &prefixes, base, line, column, ctx) {
4742+ return false;
4743+ }
4744+ // The argument of `has(...)` or `nth-child(...)` goes into the CSS as
4745+ // written
4746+ for prefix in &prefixes {
4747+ if let Some(reason) = css_breakout(prefix.trim_end_matches(':')) {
4748+ return fail(
4749+ ctx,
4750+ format!(
4751+ "the prefix '{}' has {}: it can't be written into the page's CSS",
4752+ prefix, reason
4753+ ),
4754+ prefix,
4755+ None,
4756+ );
4757+ }
4758+ }
4759+ // `nth-child():` or `has( ):`: CSS has no pseudo-class with an empty
4760+ // argument
4761+ let empty_argument = |prefix: &str| {
4762+ prefix
4763+ .strip_suffix("):")
4764+ .and_then(|p| p.split_once('('))
4765+ .is_some_and(|(_, argument)| argument.trim().is_empty())
4766+ };
4767+ if let Some(empty) = prefixes.iter().find(|p| empty_argument(p)) {
4768+ return fail(
4769+ ctx,
4770+ format!(
4771+ "'{}': `:{}()` takes an argument between its parentheses, as in CSS",
4772+ attr.key,
4773+ vocab::pseudo_name(empty)
4774+ ),
4775+ empty,
4776+ None,
4777+ );
4778+ }
4779+ // A pseudo-element is the last selector prefix: CSS has no
4780+ // `::before:hover`
4781+ let selectors: Vec<&str> = prefixes
4782+ .iter()
4783+ .copied()
4784+ .filter(|p| vocab::at_rule_rank(p).is_none())
4785+ .collect();
4786+ // Only one: an element has one `::before`, which has no `::after`
4787+ let elements: Vec<&str> = selectors
4788+ .iter()
4789+ .copied()
4790+ .filter(|p| vocab::is_pseudo_element(p))
4791+ .collect();
4792+ if elements.len() > 1 {
4793+ return fail(
4794+ ctx,
4795+ format!(
4796+ "'{}': `{}` and `{}` each select a pseudo-element, and a style applies to one \
4797+ of them",
4798+ attr.key, elements[0], elements[1]
4799+ ),
4800+ &attr.key,
4801+ None,
4802+ );
4803+ }
4804+ if let Some(at) = selectors.iter().position(|p| vocab::is_pseudo_element(p))
4805+ && at + 1 < selectors.len()
4806+ {
4807+ let element = selectors[at];
4808+ // The same prefixes, with the pseudo-element moved after the other
4809+ // selector prefixes
4810+ let mut order: Vec<&str> = prefixes.iter().copied().filter(|p| *p != element).collect();
4811+ let last_selector = order
4812+ .iter()
4813+ .rposition(|p| vocab::at_rule_rank(p).is_none())
4814+ .map_or(order.len(), |i| i + 1);
4815+ order.insert(last_selector, element);
4816+ let fixed = format!("{}{}", order.concat(), base);
4817+ return fail(
4818+ ctx,
4819+ format!(
4820+ "'{}': `{}` selects a pseudo-element, which comes after the other selector \
4821+ prefixes, as in CSS: write `{}`",
4822+ attr.key, element, fixed
4823+ ),
4824+ &attr.key,
4825+ Some(fixed),
4826+ );
4827+ }
4828+ // Under `children:` the styles go on the children, whose parent is this
4829+ // element: a word that places an element in its parent can't say where
4830+ if prefixes.contains(&"children:") && vocab::places_in_parent(base, attr.value.as_deref()) {
4831+ // The CSS of `fill` and `shrink` depends on the direction: along
4832+ // it, they are flex properties
4833+ let (word, css) = match (base, attr.value.as_deref().map(str::trim)) {
4834+ ("width", Some("fill")) => (
4835+ "width fill",
4836+ " (`children:flex 1` in a row, `children:width 100%` otherwise)",
4837+ ),
4838+ ("height", Some("fill")) => (
4839+ "height fill",
4840+ " (`children:flex 1` in a column, `children:height 100%` otherwise)",
4841+ ),
4842+ ("width", Some(_)) => (
4843+ "width shrink",
4844+ " (`children:flex-shrink 0` in a row, `children:width fit-content` otherwise)",
4845+ ),
4846+ ("height", Some(_)) => (
4847+ "height shrink",
4848+ " (`children:flex-shrink 0` in a column, `children:height fit-content` \
4849+ otherwise)",
4850+ ),
4851+ _ => (base, ""),
4852+ };
4853+ return fail(
4854+ ctx,
4855+ format!(
4856+ "'{}{}': `{}` places an element in its parent, and under `children:` that \
4857+ parent is this element: write `{}` on the children themselves, or the CSS \
4858+ you mean{}",
4859+ attr.key,
4860+ attr.value
4861+ .as_deref()
4862+ .map_or(String::new(), |v| format!(" {}", v.trim())),
4863+ word,
4864+ word,
4865+ css
4866+ ),
4867+ &attr.key,
4868+ None,
4869+ );
4870+ }
4871+ true
4872+}
4873+
4874+/// Check an attribute written as a style or a flag (not `key=value`): its
4875+/// prefix, its name, and, for a style, its value. A name htmlang doesn't
4876+/// know but CSS could have (`corner-shape`) is passed to the CSS as written,
4877+/// with a warning; custom properties (`--brand`) and vendor-prefixed ones
4878+/// (`-webkit-...`) without one. Anything that can't be written into the
4879+/// page is an error; returns false then, and the attribute is left out.
4880+fn check_attribute(
4881+ attr: &Attribute,
4882+ line: usize,
4883+ column: Option<usize>,
4884+ after_another: bool,
4885+ ctx: &mut ParseContext,
4886+) -> bool {
4887+ use crate::vocab;
4888+ let (prefixes, base) = vocab::split_prefixes(&attr.key);
4889+ let fail = |ctx: &mut ParseContext, code: &'static str, message: String, subject: &str| {
4890+ let diagnostic = Diagnostic::error(code, line, message).subject(subject);
4891+ let diagnostic = at_attribute(diagnostic, column, ctx);
4892+ ctx.diagnostics.push(diagnostic);
4893+ false
4894+ };
4895+
4896+ if !check_prefixes(attr, line, column, ctx) {
4897+ return false;
4898+ }
4899+ let prefixed = !prefixes.is_empty();
4900+ // `md:id=x`: `=` makes an HTML attribute, which has no states
4901+ if prefixed && let Some((name, _)) = base.split_once('=') {
4902+ return fail(
4903+ ctx,
4904+ code::INVALID_PREFIX,
4905+ format!(
4906+ "'{}': a prefix applies to a style, and `{}=` is an HTML attribute",
4907+ attr.key, name
4908+ ),
4909+ &attr.key,
4910+ );
4911+ }
4912+ let is_html_name = |name: &str| {
4913+ vocab::HTML_ATTRIBUTES.contains(&name)
4914+ || name.starts_with("aria-")
4915+ || name.starts_with("data-")
4916+ };
4917+
4918+ let Some(value) = &attr.value else {
4919+ // `inline` puts a file into the page as it compiles, which no
4920+ // state or media condition can undo
4921+ if base == "inline" && prefixed {
4922+ return fail(
4923+ ctx,
4924+ code::INVALID_PREFIX,
4925+ format!(
4926+ "'{}': `inline` puts the image's file into the page, which can't depend \
4927+ on a prefix",
4928+ attr.key
4929+ ),
4930+ &attr.key,
4931+ );
4932+ }
4933+ if vocab::HTMLANG_FLAGS.contains(&base) {
4934+ return true;
4935+ }
4936+ if vocab::BOOLEAN_HTML_ATTRS.contains(&base) {
4937+ if !prefixed {
4938+ return true;
18114939 }
4940+ return fail(
4941+ ctx,
4942+ code::INVALID_PREFIX,
4943+ format!(
4944+ "'{}': a prefix applies to a style, and '{}' is an HTML attribute",
4945+ attr.key, base
4946+ ),
4947+ &attr.key,
4948+ );
4949+ }
4950+ if vocab::is_style_attribute(base)
4951+ || vocab::is_custom_property(base)
4952+ || vocab::is_vendor_property(base)
4953+ {
4954+ return fail(
4955+ ctx,
4956+ code::MISSING_VALUE,
4957+ format!("'{}' needs a value: `{} VALUE`", attr.key, attr.key),
4958+ &attr.key,
4959+ );
18124960 }
4961+ if is_html_name(base) && !prefixed {
4962+ return fail(
4963+ ctx,
4964+ code::HTML_ATTRIBUTE_FORM,
4965+ format!(
4966+ "'{}' is an HTML attribute that isn't a flag: write `{}=VALUE`",
4967+ base, base
4968+ ),
4969+ base,
4970+ );
4971+ }
4972+ return unknown_attribute(attr, base, line, column, after_another, true, ctx);
4973+ };
4974+
4975+ if vocab::HTMLANG_FLAGS.contains(&base) {
4976+ return fail(
4977+ ctx,
4978+ code::INVALID_VALUE,
4979+ format!(
4980+ "'{}' is a flag and takes no value: write `{}` alone",
4981+ base, attr.key
4982+ ),
4983+ &attr.key,
4984+ );
4985+ }
4986+ if vocab::is_style_attribute(base)
4987+ || vocab::is_custom_property(base)
4988+ || vocab::is_vendor_property(base)
4989+ {
4990+ return check_css_value(attr, base, line, column, ctx);
4991+ }
4992+ if is_html_name(base) && !prefixed {
4993+ let diagnostic = Diagnostic::error(
4994+ code::HTML_ATTRIBUTE_FORM,
4995+ line,
4996+ format!(
4997+ "'{}' is an HTML attribute: write `{}={}`",
4998+ attr.key, attr.key, value
4999+ ),
5000+ )
5001+ .subject(attr.key.as_str());
5002+ let diagnostic = at_attribute(diagnostic, column, ctx);
5003+ ctx.diagnostics.push(diagnostic);
5004+ return false;
18135005 }
5006+ let passes = vocab::is_property_name(base);
5007+ unknown_attribute(attr, base, line, column, after_another, !passes, ctx)
5008+ && check_css_value(attr, base, line, column, ctx)
18145009}
18155010
1816−fn parse_attr_brackets(
1817− input: &str,
1818− line_num: usize,
5011+/// Whether an attribute of a bundle could pass a parameter to a function
5012+/// it is spliced into (`@let t [title Hello]`): a name without a prefix
5013+/// that isn't a style or a flag. Such a name is checked where the bundle is
5014+/// used.
5015+fn could_be_parameter(attr: &Attribute) -> bool {
5016+ use crate::vocab;
5017+ let key = attr.key.as_str();
5018+ let flag = attr.value.is_none()
5019+ && (vocab::HTMLANG_FLAGS.contains(&key) || vocab::BOOLEAN_HTML_ATTRS.contains(&key));
5020+ !attr.html
5021+ && !flag
5022+ && !vocab::is_style_attribute(key)
5023+ && key.starts_with(|c: char| c.is_alphabetic())
5024+ && key
5025+ .chars()
5026+ .all(|c| c.is_alphanumeric() || matches!(c, '-' | '_'))
5027+}
5028+
5029+/// At a call, a name close to one of the function's parameters is a
5030+/// misspelled parameter, not an attribute for its root: report it, and
5031+/// return true (it is left out).
5032+fn misspelled_parameter(
5033+ attr: &Attribute,
5034+ text_keys: &[String],
5035+ line: usize,
5036+ column: Option<usize>,
5037+ ctx: &mut ParseContext,
5038+) -> bool {
5039+ if text_keys.is_empty() || !could_be_parameter(attr) {
5040+ return false;
5041+ }
5042+ let params: Vec<&str> = text_keys.iter().map(String::as_str).collect();
5043+ let Some(closest) = suggest_closest(&attr.key, ¶ms) else {
5044+ return false;
5045+ };
5046+ let what = if ctx.in_page {
5047+ "@page word"
5048+ } else {
5049+ "parameter"
5050+ };
5051+ let diagnostic = Diagnostic::error(
5052+ code::UNKNOWN_ATTRIBUTE,
5053+ line,
5054+ format!(
5055+ "unknown {} '{}', did you mean '{}'?",
5056+ what, attr.key, closest
5057+ ),
5058+ )
5059+ .subject(attr.key.as_str())
5060+ .suggest(Some(closest));
5061+ let diagnostic = at_attribute(diagnostic, column, ctx);
5062+ ctx.diagnostics.push(diagnostic);
5063+ true
5064+}
5065+
5066+/// An attribute name htmlang doesn't know. A style whose name CSS could
5067+/// have goes to the CSS as written, with a warning; anything else (a flag,
5068+/// a name that isn't a word) is an error. Returns whether it is kept.
5069+fn unknown_attribute(
5070+ attr: &Attribute,
5071+ base: &str,
5072+ line: usize,
5073+ column: Option<usize>,
5074+ after_another: bool,
5075+ error: bool,
18195076 ctx: &mut ParseContext,
1820−) -> Result<(Vec<Attribute>, String), ParseError> {
1821− parse_attr_brackets_inner(input, line_num, ctx, true)
5077+) -> bool {
5078+ // `@td padding 8`: an element prefix without its colon
5079+ if let Some(name) = base.strip_prefix('@')
5080+ && crate::ast::ElementKind::from_name(name).is_some()
5081+ {
5082+ let example = match attr.value.as_deref() {
5083+ Some(value) => format!("{}:{}", attr.key, value.trim()),
5084+ None => format!("{}:padding 8", attr.key),
5085+ };
5086+ let diagnostic = Diagnostic::error(
5087+ code::UNKNOWN_ATTRIBUTE,
5088+ line,
5089+ format!(
5090+ "unknown attribute '{}': an element prefix ends in a colon, as in `{}`",
5091+ attr.key, example
5092+ ),
5093+ )
5094+ .subject(base);
5095+ let diagnostic = at_attribute(diagnostic, column, ctx);
5096+ ctx.diagnostics.push(diagnostic);
5097+ return false;
5098+ }
5099+ // `[card]` where `card` is a bundle: it is used as `$card`
5100+ if attr.value.is_none() && ctx.env.bundle(base).is_some() && base == attr.key {
5101+ ctx.used_defines.insert(base.to_string());
5102+ let diagnostic = Diagnostic::error(
5103+ code::UNKNOWN_ATTRIBUTE,
5104+ line,
5105+ format!(
5106+ "unknown attribute '{}': '{}' is an attribute bundle, used as `${}`",
5107+ base, base, base
5108+ ),
5109+ )
5110+ .subject(base)
5111+ .suggest(Some(format!("${}", base)));
5112+ let diagnostic = at_attribute(diagnostic, column, ctx);
5113+ ctx.diagnostics.push(diagnostic);
5114+ return false;
5115+ }
5116+ // `hover:title x`: an HTML attribute's name is not a suggestion for
5117+ // itself
5118+ let suggestion =
5119+ suggest_closest(base, &crate::vocab::all_attributes()).filter(|&closest| closest != base);
5120+ let mut message = match (&suggestion, error) {
5121+ (Some(closest), true) => {
5122+ format!(
5123+ "unknown attribute '{}', did you mean '{}'?",
5124+ attr.key, closest
5125+ )
5126+ }
5127+ (None, true) => format!("unknown attribute '{}'", attr.key),
5128+ (Some(closest), false) => format!(
5129+ "unknown CSS property '{}', did you mean '{}'? It is written to the CSS as it is",
5130+ base, closest
5131+ ),
5132+ (None, false) => format!(
5133+ "unknown CSS property '{}': it is written to the CSS as it is",
5134+ base
5135+ ),
5136+ };
5137+ // `box-shadow 0 1px red, 0 2px blue` or `font-family Inter,
5138+ // sans-serif`: the comma ended the attribute, and the rest of the
5139+ // value became one
5140+ let rest_of_a_value = !base.starts_with(|c: char| c.is_ascii_alphabetic() || c == '-')
5141+ || (suggestion.is_none() && attr.value.is_none() && after_another);
5142+ if rest_of_a_value && error {
5143+ if !message.ends_with('?') {
5144+ message.push('.');
5145+ }
5146+ message.push_str(" A comma separates attributes: to keep one in a value, write `\\,`");
5147+ }
5148+ let severity = if error {
5149+ Severity::Error
5150+ } else {
5151+ Severity::Warning
5152+ };
5153+ let diagnostic = Diagnostic::new(code::UNKNOWN_ATTRIBUTE, severity, line, message)
5154+ .subject(base)
5155+ .suggest(suggestion);
5156+ let diagnostic = at_attribute(diagnostic, column, ctx);
5157+ ctx.diagnostics.push(diagnostic);
5158+ !error
18225159}
18235160
1824−fn parse_attr_brackets_no_validate(
1825− input: &str,
5161+/// Evaluate the attributes of a list: bundles are spliced in, `if()`
5162+/// chooses, and variables fill values. A variable fills only the value it
5163+/// is written in: attributes come from bundles, never from text. With
5164+/// `validate`, unknown names and invalid values are reported. `text_keys`
5165+/// are a called function's parameters: their values are text rather than
5166+/// CSS, and they aren't checked as attributes.
5167+fn parse_attr_list(
5168+ tokens: &[syntax::Attr],
18265169 line_num: usize,
18275170 ctx: &mut ParseContext,
1828−) -> Result<(Vec<Attribute>, String), ParseError> {
1829− parse_attr_brackets_inner(input, line_num, ctx, false)
5171+ validate: bool,
5172+ text_keys: &[String],
5173+) -> Vec<Attribute> {
5174+ parse_attrs(tokens, line_num, ctx, validate, text_keys)
5175+ .into_iter()
5176+ .map(|(attr, _)| attr)
5177+ .collect()
18305178}
18315179
1832−fn parse_attr_brackets_inner(
1833− input: &str,
5180+/// [`parse_attr_list`], with the value of each attribute whose key is one
5181+/// of `text_keys` (a call's parameters) as a value with its type (see
5182+/// [`ParseContext::slot_value`]), so a parameter can get a list or a
5183+/// record.
5184+fn parse_attrs(
5185+ tokens: &[syntax::Attr],
18345186 line_num: usize,
18355187 ctx: &mut ParseContext,
18365188 validate: bool,
1837−) -> Result<(Vec<Attribute>, String), ParseError> {
1838− let mut depth = 0;
1839− let mut end_pos = 0;
1840−
1841− for (i, c) in input.char_indices() {
1842− match c {
1843− '[' => depth += 1,
1844− ']' => {
1845− depth -= 1;
1846− if depth == 0 {
1847− end_pos = i;
1848− break;
1849− }
1850− }
1851− _ => {}
1852− }
1853− }
1854−
1855− if depth != 0 {
1856− return Err(ParseError {
1857− line: line_num,
1858− message: "unclosed '[' in attribute list".to_string(),
1859− });
1860− }
1861−
1862− let attrs_inner = &input[1..end_pos];
1863− let remaining = input[end_pos + 1..].trim().to_string();
1864− let attrs = parse_attr_list(attrs_inner, line_num, ctx, validate);
1865−
1866− Ok((attrs, remaining))
5189+ text_keys: &[String],
5190+) -> Vec<(Attribute, Option<Value>)> {
5191+ let mut read = ReadAttrs::default();
5192+ read_attrs(tokens, "", line_num, ctx, validate, text_keys, &mut read);
5193+ read.attrs
18675194}
18685195
1869−fn is_valid_hex_color(s: &str) -> bool {
1870− if !s.starts_with('#') {
1871− return true; // Not a hex color, skip
1872− }
1873− let hex = &s[1..];
1874− matches!(hex.len(), 3 | 4 | 6 | 8) && hex.chars().all(|c| c.is_ascii_hexdigit())
5196+/// The attributes of a list read so far, and the keys written (for the
5197+/// duplicate check).
5198+#[derive(Default)]
5199+struct ReadAttrs {
5200+ attrs: Vec<(Attribute, Option<Value>)>,
5201+ seen_keys: Vec<(String, bool)>,
18755202}
18765203
1877−fn parse_attr_list(
1878− input: &str,
5204+/// [`parse_attrs`] for the attributes of `tokens`, each under the prefixes
5205+/// `prefix` (`md:` for those of `md:[...]`), which distribute over a
5206+/// group, a bundle and the branch an `if()` takes. Only styles take a
5207+/// prefix, so an HTML attribute there is an error.
5208+fn read_attrs(
5209+ tokens: &[syntax::Attr],
5210+ prefix: &str,
18795211 line_num: usize,
18805212 ctx: &mut ParseContext,
18815213 validate: bool,
1882−) -> Vec<Attribute> {
1883− let mut attrs = Vec::new();
1884− let mut seen_keys: Vec<String> = Vec::new();
1885−
1886− for part in split_commas(input) {
1887− let part = part.trim();
1888− // A whole attribute `if(cond, a, b)` is the chosen branch's text.
1889− let chosen;
1890− let part = match choose_if(part, ctx, line_num) {
1891− Some(branch) => {
1892− chosen = branch;
1893− chosen.as_str()
1894− }
1895− None => part,
5214+ text_keys: &[String],
5215+ out: &mut ReadAttrs,
5216+) {
5217+ let mut chosen = Vec::new();
5218+ choose_attrs(
5219+ tokens,
5220+ prefix,
5221+ line_num,
5222+ ctx,
5223+ validate,
5224+ text_keys,
5225+ &mut chosen,
5226+ );
5227+
5228+ for token in &chosen {
5229+ let line = if token.span.line == 0 {
5230+ line_num
5231+ } else {
5232+ token.span.line
18965233 };
1897− if part.is_empty() {
5234+ let (key, value, html) = (token.key.clone(), token.value.clone(), token.html);
5235+ let column = |at: usize| Some(token.span.column + at);
5236+
5237+ // `md:[...]`, `md:$card`, `md:if(...)`: the prefixes apply to each
5238+ // attribute there, and a prefix a parameter can't have
5239+ if let Some(prefixed) = &token.prefixed {
5240+ if let Some(inner) = group_prefix(token, prefixed, prefix, line, ctx) {
5241+ read_attrs(
5242+ prefixed.target.attrs(),
5243+ &inner,
5244+ line_num,
5245+ ctx,
5246+ validate,
5247+ text_keys,
5248+ out,
5249+ );
5250+ }
18985251 continue;
18995252 }
19005253
1901− // $define reference — expand attribute bundle
1902− if let Some(name) = part.strip_prefix('$')
1903− && let Some(define_attrs) = ctx.defines.get(name)
1904− {
1905− ctx.used_defines.insert(name.to_string());
1906− attrs.extend(define_attrs.clone());
5254+ // `$name` (or `${name}`) alone: an attribute bundle, spliced in
5255+ let bundle = key.strip_prefix('$').filter(|_| value.is_none() && !html);
5256+ let bundle = bundle.and_then(|after| match interp::reference(after, &ctx.env)? {
5257+ (interp::Reference::Var(name), len) if len == after.len() => Some(name),
5258+ _ => None,
5259+ });
5260+ if let Some(name) = bundle {
5261+ if let Some(define_attrs) = ctx.env.bundle(&name).cloned() {
5262+ ctx.used_defines.insert(name.clone());
5263+ for attr in define_attrs.iter() {
5264+ if !prefix.is_empty() {
5265+ let prefixed = Attribute {
5266+ key: format!("{}{}", prefix, attr.key),
5267+ ..attr.clone()
5268+ };
5269+ if prefixed_parameter(&prefixed, text_keys, line, column(0), validate, ctx)
5270+ {
5271+ continue;
5272+ }
5273+ if let Some(attr) =
5274+ prefixed_member(attr, prefix, &name, line, column(0), validate, ctx)
5275+ {
5276+ out.attrs.push((attr, None));
5277+ }
5278+ continue;
5279+ }
5280+ let attrs = &out.attrs;
5281+ // Checked here, where it is either a parameter or not
5282+ let checked_here = validate
5283+ && !ctx.in_bundle
5284+ && could_be_parameter(attr)
5285+ && !text_keys.contains(&attr.key);
5286+ if checked_here
5287+ && (misspelled_parameter(attr, text_keys, line, column(0), ctx)
5288+ || !check_attribute(attr, line, column(0), !attrs.is_empty(), ctx))
5289+ {
5290+ continue;
5291+ }
5292+ out.attrs.push((attr.clone(), None));
5293+ }
5294+ } else {
5295+ not_a_bundle(&name, line, column(0), ctx);
5296+ }
5297+ continue;
5298+ }
5299+ // A name never comes from a variable
5300+ if key.contains('$') {
5301+ track_var_refs(&key, &mut ctx.used_variables);
5302+ ctx.diagnostics.push(
5303+ Diagnostic::error(
5304+ code::ATTRIBUTE_FROM_VARIABLE,
5305+ line,
5306+ format!(
5307+ "'{}': an attribute's name can't come from a variable. A variable \
5308+ fills a value (`padding $size`), and whole attributes come from a \
5309+ bundle (`@let name [padding 8]`, used as `[$name]`)",
5310+ key
5311+ ),
5312+ )
5313+ .subject(key.as_str()),
5314+ );
19075315 continue;
19085316 }
19095317
1910− track_var_refs(part, &mut ctx.used_variables);
1911−
1912− // A value `if(cond, a, b)` picks `a` or `b` (free text) by `cond`;
1913− // an empty choice leaves the attribute out.
1914− let Some(part) = choose_if_value(part, ctx, line_num) else {
5318+ // Only a style has states: `md:[id=x]`, `md:id=x`
5319+ if html && (!prefix.is_empty() || !crate::vocab::split_prefixes(&key).0.is_empty()) {
5320+ let written = format!("{}{}", prefix, key);
5321+ let (name, _) = crate::vocab::split_prefixes(&written);
5322+ let diagnostic = Diagnostic::error(
5323+ code::INVALID_PREFIX,
5324+ line,
5325+ format!(
5326+ "'{}=': a prefix applies to a style, and `{}=` is an HTML attribute, \
5327+ which has no states",
5328+ written,
5329+ &written[name.concat().len()..]
5330+ ),
5331+ )
5332+ .subject(token.key.as_str());
5333+ let diagnostic = at_attribute(diagnostic, column(0), ctx);
5334+ ctx.diagnostics.push(diagnostic);
19155335 continue;
5336+ }
5337+ let key = if prefix.is_empty() {
5338+ key
5339+ } else {
5340+ format!("{}{}", prefix, key)
19165341 };
1917− let part = substitute_vars(&part, &ctx.variables);
19185342
1919− let attr = if let Some((key, value)) = split_html_attribute(&part) {
1920− Attribute {
1921− key: key.to_string(),
1922− value: Some(value.to_string()),
1923− html: true,
1924− }
1925− } else if let Some((key, value)) = part.split_once(' ') {
1926− let value = value.trim().to_string();
1927− Attribute {
1928− key: key.trim().to_string(),
1929− value: Some(value),
1930− html: false,
1931− }
5343+ // A value's variables are filled in. A style's value is CSS, where
5344+ // quoted text keeps its quotes; an HTML attribute's (and a
5345+ // parameter's) is text, where it loses them.
5346+ let sink = if html || text_keys.contains(&key) {
5347+ Sink::Text
19325348 } else {
1933− Attribute {
1934− key: part.to_string(),
1935− value: None,
1936− html: false,
5349+ Sink::Css
5350+ };
5351+ let mut filled = true;
5352+ let mut quoted = None;
5353+ let mut typed = None;
5354+ let value = match value {
5355+ None => None,
5356+ // A parameter's value keeps its type
5357+ Some(value) if !html && text_keys.contains(&key) => {
5358+ let at = column(token.raw.len() - value.len());
5359+ let (value, ok) = ctx.slot_value(&value, line, at);
5360+ filled = ok;
5361+ if let Value::Quoted(q) = &value {
5362+ quoted = Some(q.clone());
5363+ }
5364+ let text = value.to_string();
5365+ typed = Some(value);
5366+ Some(text)
5367+ }
5368+ Some(value) => {
5369+ let at = column(token.raw.len() - value.len());
5370+ let (text, is_quoted, ok) = ctx.fill_value(&value, line, at, sink);
5371+ filled = ok;
5372+ quoted = is_quoted;
5373+ Some(text)
19375374 }
19385375 };
5376+ let attr = Attribute {
5377+ key,
5378+ value,
5379+ html,
5380+ quoted,
5381+ };
5382+ // A value that couldn't be filled in is already reported, and a
5383+ // parameter's value is text for the function
5384+ let validate = validate && filled && !text_keys.contains(&attr.key);
19395385
1940− // Warn on duplicate attributes (compare full key so pseudo-class
1941− // variants like `border` and `hover:border` are not conflated)
5386+ // A duplicate is reported (compare the full key, so `border` and
5387+ // `hover:border` differ, and the form, so `width=800` and
5388+ // `width 200` do too), and the later one wins
19425389 if validate {
1943− if seen_keys.contains(&attr.key) {
1944− ctx.diagnostics.push(Diagnostic {
1945− line: line_num,
1946− column: None,
1947− message: format!("duplicate attribute '{}'", attr.key),
1948− severity: Severity::Warning,
1949− source_line: None,
1950− });
5390+ let seen = (normal_key(&attr.key), attr.html);
5391+ if out.seen_keys.contains(&seen) {
5392+ let message = if attr.html {
5393+ format!("duplicate attribute '{}='", attr.key)
5394+ } else {
5395+ format!("duplicate attribute '{}': the later one wins", attr.key)
5396+ };
5397+ let diagnostic = Diagnostic::warning(code::DUPLICATE_ATTRIBUTE, line, message)
5398+ .subject(attr.key.as_str());
5399+ let diagnostic = at_attribute(diagnostic, column(0), ctx);
5400+ ctx.diagnostics.push(diagnostic);
19515401 } else {
1952− seen_keys.push(attr.key.clone());
5402+ out.seen_keys.push(seen);
19535403 }
5404+ }
19545405
1955− // Color validation for hex colors
1956− if !attr.html
1957− && matches!(
1958− crate::vocab::base_attribute(&attr.key),
1959− "background" | "color"
1960− )
1961− && let Some(ref val) = attr.value
1962− && val.starts_with('#')
1963− && !is_valid_hex_color(val)
1964− {
1965− ctx.diagnostics.push(Diagnostic {
1966− line: line_num,
1967− column: None,
1968− message: format!("invalid hex color '{}'", val),
1969− severity: Severity::Warning,
1970− source_line: None,
1971− });
1972− }
5406+ if validate && misspelled_parameter(&attr, text_keys, line, column(0), ctx) {
5407+ continue;
5408+ }
5409+ if prefixed_parameter(&attr, text_keys, line, column(0), validate, ctx) {
5410+ continue;
5411+ }
5412+ if validate && attr.html && attr.key == "class" {
5413+ reserved_class(&attr, line, column(0), ctx);
5414+ }
5415+ // `padding=4`: a style written as an HTML attribute, which the
5416+ // browser ignores (`width=` and `height=` are real on some
5417+ // elements, see `validate_tree`)
5418+ if validate
5419+ && attr.html
5420+ && crate::vocab::is_style_attribute(&attr.key)
5421+ && !crate::vocab::HTML_ATTRIBUTES.contains(&attr.key.as_str())
5422+ {
5423+ let value = token.value.as_deref().unwrap_or("").trim();
5424+ let diagnostic = Diagnostic::warning(
5425+ code::HTML_ATTRIBUTE_FORM,
5426+ line,
5427+ format!(
5428+ "'{0}={1}' is an HTML attribute, but {0} is a style: write `{0} {1}`",
5429+ attr.key, value
5430+ ),
5431+ )
5432+ .subject(token.raw.as_str())
5433+ .suggest(Some(format!("{} {}", attr.key, value)));
5434+ let diagnostic = at_attribute(diagnostic, column(0), ctx);
5435+ ctx.diagnostics.push(diagnostic);
19735436 }
19745437
1975− // Warn on unknown attributes. `key=value` HTML attributes may use any
1976− // name; everything else must be a known style.
1977− if validate && !attr.html {
1978− let base_key = crate::vocab::base_attribute(attr.key.as_str());
1979− let is_boolean_html =
1980− attr.value.is_none() && crate::vocab::BOOLEAN_HTML_ATTRS.contains(&base_key);
1981− if is_boolean_html || crate::vocab::is_style_attribute(base_key) {
1982− validate_attr_value(&attr, line_num, ctx);
1983− } else if crate::vocab::HTML_ATTRIBUTES.contains(&base_key)
1984− || base_key.starts_with("aria-")
1985− || base_key.starts_with("data-")
1986− {
1987− ctx.diagnostics.push(Diagnostic {
1988− line: line_num,
1989− column: None,
1990− message: format!(
1991− "'{}' is an HTML attribute: write `{}={}`",
1992− attr.key,
1993− attr.key,
1994− attr.value.as_deref().unwrap_or("")
1995− ),
1996− severity: Severity::Warning,
1997− source_line: None,
1998− });
1999− } else {
2000− let suggestion = suggest_closest(base_key, &crate::vocab::all_attributes());
2001− let msg = match suggestion {
2002− Some(closest) => {
2003− format!(
2004− "unknown attribute '{}', did you mean '{}'?",
2005− attr.key, closest
2006− )
2007− }
2008− None => format!("unknown attribute '{}'", attr.key),
2009− };
2010− ctx.diagnostics.push(Diagnostic {
2011− line: line_num,
2012− column: None,
2013− message: msg,
2014− severity: Severity::Warning,
2015− source_line: None,
2016− });
2017− }
5438+ // A style or a flag: its name is checked, and what can't be
5439+ // written into the page is an error and left out
5440+ let checked = validate && !attr.html && !(ctx.in_bundle && could_be_parameter(&attr));
5441+ let after_another = !out.attrs.is_empty();
5442+ if checked && !check_attribute(&attr, line, column(0), after_another, ctx) {
5443+ continue;
20185444 }
20195445
2020− attrs.push(attr);
5446+ out.attrs.push((attr, typed));
20215447 }
2022−
2023− attrs
20245448}
20255449
2026−/// Split an HTML attribute written `key=value` (`alt=`, `type=email`,
2027−/// `aria-label=Close menu`). Returns `None` for style attributes.
2028−fn split_html_attribute(part: &str) -> Option<(&str, &str)> {
2029− let first_token = part.split(char::is_whitespace).next()?;
2030− let eq = first_token.find('=')?;
2031− let key = &part[..eq];
2032− let valid_key = key.starts_with(|c: char| c.is_ascii_alphabetic())
2033− && key
2034− .chars()
2035− .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'));
2036− valid_key.then(|| (key, part[eq + 1..].trim()))
5450+/// At a call, a parameter under prefixes (`md:title x`, `md:[title x]`):
5451+/// a parameter has one value, with no states, so it is reported (with
5452+/// `validate`) and left out; returns true then. A parameter named like a
5453+/// style (`color`) is a style under a prefix, for the root element.
5454+fn prefixed_parameter(
5455+ attr: &Attribute,
5456+ text_keys: &[String],
5457+ line: usize,
5458+ column: Option<usize>,
5459+ validate: bool,
5460+ ctx: &mut ParseContext,
5461+) -> bool {
5462+ let (prefixes, name) = crate::vocab::split_prefixes(&attr.key);
5463+ if attr.html
5464+ || prefixes.is_empty()
5465+ || !text_keys.iter().any(|k| k == name)
5466+ || crate::vocab::is_style_attribute(name)
5467+ {
5468+ return false;
5469+ }
5470+ if validate {
5471+ let what = if ctx.in_page {
5472+ "@page's own word"
5473+ } else {
5474+ "a parameter"
5475+ };
5476+ let diagnostic = Diagnostic::error(
5477+ code::INVALID_PREFIX,
5478+ line,
5479+ format!(
5480+ "'{}': `{}` is {}, which has one value, and a prefix applies to a style, \
5481+ which has states",
5482+ attr.key, name, what
5483+ ),
5484+ )
5485+ .subject(attr.key.as_str());
5486+ let diagnostic = at_attribute(diagnostic, column, ctx);
5487+ ctx.diagnostics.push(diagnostic);
5488+ }
5489+ true
20375490}
20385491
2039−fn split_commas(input: &str) -> Vec<&str> {
2040− let mut parts = Vec::new();
2041− let mut start = 0;
2042− let mut depth = 0;
2043− let mut in_quotes = false;
2044−
2045− for (i, c) in input.char_indices() {
2046− match c {
2047− '"' => in_quotes = !in_quotes,
2048− _ if in_quotes => {}
2049− '[' | '(' => depth += 1,
2050− ']' | ')' => depth -= 1,
2051− ',' if depth == 0 => {
2052− parts.push(&input[start..i]);
2053− start = i + 1;
2054− }
2055− _ => {}
5492+/// The prefixes of a prefixed group, bundle or `if()` inside `outer` (the
5493+/// prefixes of the groups it is in), when they are all known; else the
5494+/// unknown one is reported. Text after a group's `]` is an error too.
5495+fn group_prefix(
5496+ token: &syntax::Attr,
5497+ prefixed: &syntax::Prefixed,
5498+ outer: &str,
5499+ line: usize,
5500+ ctx: &mut ParseContext,
5501+) -> Option<String> {
5502+ let at = |ctx: &ParseContext, diagnostic: Diagnostic, span: syntax::Span| match &ctx
5503+ .current_source
5504+ {
5505+ (current, Some(text)) if span.line != 0 && *current == span.line => {
5506+ diagnostic.column(span.column).source(text.clone())
20565507 }
5508+ _ => diagnostic,
5509+ };
5510+ if let syntax::Branch::Group {
5511+ trailing: Some(trailing),
5512+ ..
5513+ } = &prefixed.target
5514+ {
5515+ let diagnostic = Diagnostic::error(
5516+ code::UNEXPECTED_ARGUMENT,
5517+ line,
5518+ format!(
5519+ "'{}' after the `]` of `{}[...]`: the prefixes apply to the attributes in the \
5520+ group, so it goes inside it",
5521+ trailing.raw, prefixed.prefix
5522+ ),
5523+ )
5524+ .subject(trailing.raw.as_str());
5525+ let diagnostic = at(ctx, diagnostic, trailing.span);
5526+ ctx.push_once(diagnostic);
5527+ }
5528+ let (known, rest) = crate::vocab::split_prefixes(&prefixed.prefix);
5529+ if !rest.is_empty() {
5530+ let problem = unknown_prefix(rest).unwrap_or_else(|| {
5531+ let written = rest.split_inclusive(':').next().unwrap_or(rest);
5532+ PrefixProblem {
5533+ message: format!("unknown prefix '{}'", written),
5534+ subject: written.to_string(),
5535+ suggestion: None,
5536+ }
5537+ });
5538+ let diagnostic = Diagnostic::error(code::UNKNOWN_PREFIX, line, problem.message)
5539+ .subject(problem.subject)
5540+ .suggest(problem.suggestion);
5541+ let diagnostic = at(ctx, diagnostic, token.span);
5542+ ctx.push_once(diagnostic);
5543+ return None;
20575544 }
2058− parts.push(&input[start..]);
2059− parts
5545+ Some(format!("{}{}", outer, known.concat()))
20605546}
20615547
2062−// ---------------------------------------------------------------------------
2063−// Chain splitting (the > operator)
2064−// ---------------------------------------------------------------------------
2065−
2066−fn split_chain(content: &str) -> Vec<String> {
2067− let mut segments = Vec::new();
2068− let mut current = String::new();
2069− let chars: Vec<char> = content.chars().collect();
2070− let mut i = 0;
2071− let mut bracket_depth = 0;
2072−
2073− while i < chars.len() {
2074− if chars[i] == '[' {
2075− bracket_depth += 1;
5548+/// An attribute of the bundle `bundle`, spliced in under `prefix`
5549+/// (`md:$card`): the same attribute with the prefixes in front, when it can
5550+/// take them. An HTML attribute can't; a style's prefixes are checked, as
5551+/// is a flag or a name that isn't a style (a bundle's parameter), which
5552+/// under a prefix are attributes like any other.
5553+fn prefixed_member(
5554+ attr: &Attribute,
5555+ prefix: &str,
5556+ bundle: &str,
5557+ line: usize,
5558+ column: Option<usize>,
5559+ validate: bool,
5560+ ctx: &mut ParseContext,
5561+) -> Option<Attribute> {
5562+ let key = format!("{}{}", prefix, attr.key);
5563+ if attr.html {
5564+ if validate {
5565+ let diagnostic = Diagnostic::error(
5566+ code::INVALID_PREFIX,
5567+ line,
5568+ format!(
5569+ "'{}${}': the bundle has `{}=`, an HTML attribute, and a prefix applies to \
5570+ styles, which have states",
5571+ prefix, bundle, attr.key
5572+ ),
5573+ )
5574+ .subject(format!("{}${}", prefix, bundle));
5575+ let diagnostic = at_attribute(diagnostic, column, ctx);
5576+ ctx.diagnostics.push(diagnostic);
20765577 }
2077− if chars[i] == ']' {
2078− bracket_depth -= 1;
5578+ return None;
5579+ }
5580+ let prefixed = Attribute {
5581+ key,
5582+ ..attr.clone()
5583+ };
5584+ if validate {
5585+ let fine = if attr.value.is_none() || could_be_parameter(attr) {
5586+ check_attribute(&prefixed, line, column, false, ctx)
5587+ } else {
5588+ check_prefixes(&prefixed, line, column, ctx)
5589+ };
5590+ if !fine {
5591+ return None;
20795592 }
5593+ }
5594+ Some(prefixed)
5595+}
20805596
2081− // Match " > @" outside brackets
2082− if bracket_depth == 0
2083− && i + 3 < chars.len()
2084− && chars[i] == ' '
2085− && chars[i + 1] == '>'
2086− && chars[i + 2] == ' '
2087− && chars[i + 3] == '@'
2088− {
2089− segments.push(current.trim().to_string());
2090− current = String::new();
2091− i += 3; // skip " > ", keep the "@"
2092− continue;
5597+/// `class=hl-x`: the `hl-` prefix is htmlang's, for its generated classes,
5598+/// whose rules would then apply to the element too. It goes into the page
5599+/// as written, so this is a warning.
5600+fn reserved_class(attr: &Attribute, line: usize, column: Option<usize>, ctx: &mut ParseContext) {
5601+ let classes = attr.value.as_deref().unwrap_or_default();
5602+ for class in classes.split_whitespace() {
5603+ if class.starts_with(crate::codegen::CLASS_PREFIX) {
5604+ let diagnostic = Diagnostic::warning(
5605+ code::INVALID_VALUE,
5606+ line,
5607+ format!(
5608+ "class '{}' starts with `{}`, which htmlang keeps for the classes it \
5609+ generates, so their styles could apply to this element: give it \
5610+ another name",
5611+ class,
5612+ crate::codegen::CLASS_PREFIX
5613+ ),
5614+ )
5615+ .subject(class);
5616+ let diagnostic = at_attribute(diagnostic, column, ctx);
5617+ ctx.diagnostics.push(diagnostic);
20935618 }
2094−
2095− current.push(chars[i]);
2096− i += 1;
20975619 }
5620+}
20985621
2099− if !current.trim().is_empty() {
2100− segments.push(current.trim().to_string());
5622+/// A style's key as the CSS reads it, for finding duplicates: its at-rule
5623+/// prefixes in one order (`dark:md:` is `md:dark:`), then its selector
5624+/// prefixes as written, whose order is the selector's.
5625+fn normal_key(key: &str) -> String {
5626+ let (prefixes, name) = crate::vocab::split_prefixes(key);
5627+ let mut at: Vec<(usize, &str)> = prefixes
5628+ .iter()
5629+ .filter_map(|p| crate::vocab::at_rule_rank(p).map(|rank| (rank, *p)))
5630+ .collect();
5631+ at.sort_unstable();
5632+ at.dedup();
5633+ let mut normal: String = at.iter().map(|(_, p)| *p).collect();
5634+ for prefix in prefixes
5635+ .iter()
5636+ .filter(|p| crate::vocab::at_rule_rank(p).is_none())
5637+ {
5638+ normal.push_str(prefix);
21015639 }
5640+ normal.push_str(name);
5641+ normal
5642+}
21025643
2103− segments
5644+/// `[$name]` where `$name` isn't an attribute bundle.
5645+fn not_a_bundle(name: &str, line: usize, column: Option<usize>, ctx: &mut ParseContext) {
5646+ track_var_refs(&format!("${}", name), &mut ctx.used_variables);
5647+ let is_value = interp::name_len(name) > 0 && interp::resolve(name, &ctx.env).is_some();
5648+ let diagnostic = if is_value {
5649+ Diagnostic::error(
5650+ code::ATTRIBUTE_FROM_VARIABLE,
5651+ line,
5652+ format!(
5653+ "'${}' is a value, not an attribute: attributes come from a bundle \
5654+ (`@let name [padding 8]`, used as `[$name]`), and a value fills an \
5655+ attribute's value (`padding ${}`)",
5656+ name, name
5657+ ),
5658+ )
5659+ .subject(name)
5660+ } else if ctx.env.function(name).is_some() {
5661+ ctx.used_functions.insert(name.to_string());
5662+ Diagnostic::error(
5663+ code::UNDEFINED_VARIABLE,
5664+ line,
5665+ format!(
5666+ "'${}' is a function, not an attribute bundle: it is called as an element, \
5667+ `@{}`",
5668+ name, name
5669+ ),
5670+ )
5671+ .subject(name)
5672+ } else {
5673+ let mut bundles = ctx.env.bundle_names();
5674+ bundles.sort_unstable();
5675+ let suggestion = suggest_closest(name, &bundles);
5676+ let message = match suggestion {
5677+ Some(closest) => format!(
5678+ "undefined attribute bundle '${}', did you mean '${}'?",
5679+ name, closest
5680+ ),
5681+ None => format!("undefined attribute bundle '${}'", name),
5682+ };
5683+ Diagnostic::error(code::UNDEFINED_VARIABLE, line, message)
5684+ .subject(name)
5685+ .suggest(suggestion)
5686+ };
5687+ let diagnostic = match (&ctx.current_source, column) {
5688+ ((current, Some(text)), Some(column)) if *current == line => {
5689+ diagnostic.column(column).source(text.clone())
5690+ }
5691+ _ => diagnostic,
5692+ };
5693+ ctx.diagnostics.push(diagnostic);
21045694}
21055695
21065696// ---------------------------------------------------------------------------
21075697// Text segment parsing (inline {...} elements)
21085698// ---------------------------------------------------------------------------
21095699
2110−/// Escapes in text: `\@`, `\$`, `\{`, `\--` and `\\` stand for the
2111−/// character(s) themselves. While a text is processed, each is a private-use
2112−/// placeholder, so it can't start a variable, an inline element or a line.
2113−const ESCAPES: &[(&str, char, &str)] = &[
2114− ("\\\\", '\u{E000}', "\\"),
2115− ("\\$", '\u{E001}', "$"),
2116− ("\\{", '\u{E002}', "{"),
2117− ("\\@", '\u{E003}', "@"),
2118− ("\\--", '\u{E004}', "--"),
2119−];
2120−
5700+/// While a slot is filled in, each escape (see [`syntax::ESCAPES`]) is a
5701+/// private-use placeholder, U+E000 plus its place in the table, so it
5702+/// can't start a variable, a quote or an inline element. Afterwards it
5703+/// becomes what it stands for.
21215704fn protect_escapes(text: &str) -> String {
21225705 if !text.contains('\\') {
21235706 return text.to_string();
21245707 }
2125− let mut out = text.to_string();
2126− for (escape, placeholder, _) in ESCAPES {
2127− out = out.replace(escape, &placeholder.to_string());
5708+ let mut out = String::with_capacity(text.len());
5709+ let mut i = 0;
5710+ while let Some(c) = text[i..].chars().next() {
5711+ let len = syntax::escape_len(&text[i..]);
5712+ if len == 0 {
5713+ out.push(c);
5714+ i += c.len_utf8();
5715+ continue;
5716+ }
5717+ let escape = &text[i..i + len];
5718+ let index = syntax::ESCAPES.iter().position(|e| *e == escape);
5719+ out.extend(index.and_then(|n| char::from_u32(0xE000 + n as u32)));
5720+ i += len;
21285721 }
21295722 out
21305723}
21315724
5725+/// The escape a placeholder stands for, as written (`\,`).
5726+fn escape_of(c: char) -> Option<&'static str> {
5727+ let index = (c as u32).checked_sub(0xE000)?;
5728+ syntax::ESCAPES.get(index as usize).copied()
5729+}
5730+
21325731fn restore_escapes(text: &str) -> String {
2133− let mut out = text.to_string();
2134− for (_, placeholder, literal) in ESCAPES {
2135− out = out.replace(*placeholder, literal);
5732+ text.chars()
5733+ .fold(String::with_capacity(text.len()), |mut out, c| {
5734+ match escape_of(c) {
5735+ // What the escape stands for: what follows the backslash
5736+ Some(escape) => out.push_str(&escape[1..]),
5737+ None => out.push(c),
5738+ }
5739+ out
5740+ })
5741+}
5742+
5743+/// Inside the quoted strings of a CSS value, `\"` and `\\` mean in CSS what
5744+/// they mean in htmlang, so they stay as written there.
5745+fn keep_css_string_escapes(protected: &str) -> String {
5746+ let mut out = String::with_capacity(protected.len());
5747+ let mut inside = false;
5748+ for c in protected.chars() {
5749+ match escape_of(c) {
5750+ Some(escape @ ("\\\"" | "\\\\")) if inside => out.push_str(escape),
5751+ _ => {
5752+ if c == '"' {
5753+ inside = !inside;
5754+ }
5755+ out.push(c);
5756+ }
5757+ }
21365758 }
21375759 out
21385760}
21395761
2140−fn parse_text_segments(input: &str, ctx: &mut ParseContext) -> Vec<TextSegment> {
5762+/// Evaluate text: fill in the variables of its plain runs and build its
5763+/// inline elements. Each run is one slot, so a value can't make markup.
5764+fn text_segments(text: &syntax::Text, ctx: &mut ParseContext) -> Vec<TextSegment> {
21415765 let mut segments = Vec::new();
2142− let mut current_text = String::new();
2143− let chars: Vec<char> = protect_escapes(input).chars().collect();
2144− let mut i = 0;
2145−
2146− while i < chars.len() {
2147− if chars[i] == '{' && i + 1 < chars.len() && chars[i + 1] == '@' {
2148− // Flush accumulated plain text
2149− if !current_text.is_empty() {
2150− segments.push(TextSegment::Plain(restore_escapes(&substitute_vars(
2151− ¤t_text,
2152− &ctx.variables,
2153− ))));
2154− current_text.clear();
2155− }
2156−
2157− // Find matching }
2158− let mut depth = 0;
2159− let start = i + 1; // after {
2160− i += 1;
2161− loop {
2162− if i >= chars.len() {
2163− break;
2164− }
2165− if chars[i] == '{' {
2166− depth += 1;
2167− } else if chars[i] == '}' {
2168− if depth == 0 {
2169− break;
2170− }
2171− depth -= 1;
2172− }
2173− i += 1;
5766+ // The plain text so far, and where it starts
5767+ let mut plain = String::new();
5768+ let mut start: Option<syntax::Span> = None;
5769+ let flush = |plain: &mut String,
5770+ start: &mut Option<syntax::Span>,
5771+ segments: &mut Vec<TextSegment>,
5772+ ctx: &mut ParseContext| {
5773+ if !plain.is_empty() {
5774+ let at = start.unwrap_or(text.span);
5775+ let filled = ctx.interpolate_text(plain, at.line, Some(at.column));
5776+ segments.push(TextSegment::Plain(filled));
5777+ plain.clear();
5778+ }
5779+ *start = None;
5780+ };
5781+ for segment in &text.segments {
5782+ match segment {
5783+ Segment::Plain { raw, span } => {
5784+ start.get_or_insert(*span);
5785+ plain.push_str(raw);
21745786 }
2175−
2176− let inner: String = chars[start..i].iter().collect();
2177− i += 1; // skip }
2178−
2179− match parse_single_element(&inner, ctx.current_line, ctx) {
2180− Ok(elem) => segments.push(TextSegment::Inline(elem)),
2181− Err(e) => {
2182− // Keep the braces as literal text, but flag what looks
2183− // like a mistyped inline element.
2184− if inner.trim_start().starts_with('@') {
2185− ctx.diagnostics.push(Diagnostic {
2186− line: ctx.current_line,
2187− column: None,
2188− message: e.message,
2189− severity: Severity::Warning,
2190− source_line: Some(input.to_string()),
2191− });
5787+ Segment::Inline(inline) => {
5788+ let line = ctx.current_line;
5789+ match resolve(&inline.head, inline.text.as_ref(), line, &text.raw, ctx) {
5790+ Ok(resolved) => {
5791+ if !inline.closed {
5792+ let d = Diagnostic::warning(
5793+ code::UNCLOSED_BRACKET,
5794+ inline.span.line,
5795+ format!(
5796+ "unclosed `{{`: the inline @{} runs to the end of the line. \
5797+ An inline element ends with `}}` (a brace that is text is \
5798+ written `\\{{`)",
5799+ inline.head.name
5800+ ),
5801+ );
5802+ let d = at_attribute(d, Some(inline.span.column), ctx);
5803+ ctx.push_once(d);
5804+ }
5805+ flush(&mut plain, &mut start, &mut segments, ctx);
5806+ // A function called inline gets no children: its
5807+ // content is the text after its attributes
5808+ match Evaluator.complete(resolved, Vec::new(), ctx) {
5809+ Ok(nodes) => segments.extend(inline_segments(nodes, line)),
5810+ Err(mut e) => {
5811+ e.source_line
5812+ .get_or_insert_with(|| text.raw.as_str().into());
5813+ ctx.diagnostics.push(e);
5814+ }
5815+ }
5816+ }
5817+ Err(mut e) => {
5818+ // A misspelled element is an error inline too (a
5819+ // brace that is text is written `\{`); the braces
5820+ // stay as written
5821+ e.source_line = Some(text.raw.as_str().into());
5822+ ctx.diagnostics.push(e);
5823+ start.get_or_insert(inline.span);
5824+ plain.push('{');
5825+ plain.push_str(&inline.raw);
5826+ if inline.closed {
5827+ plain.push('}');
5828+ }
21925829 }
2193− current_text.push('{');
2194− current_text.push_str(&inner);
2195− current_text.push('}');
21965830 }
21975831 }
2198− } else {
2199− current_text.push(chars[i]);
2200− i += 1;
22015832 }
22025833 }
5834+ flush(&mut plain, &mut start, &mut segments, ctx);
5835+ segments
5836+}
22035837
2204− if !current_text.is_empty() {
2205− segments.push(TextSegment::Plain(restore_escapes(&substitute_vars(
2206− ¤t_text,
2207− &ctx.variables,
2208− ))));
5838+/// The variable `raw` is, when it is exactly one `$name` or `${name}`.
5839+fn whole_reference(raw: &str, env: &Env) -> Option<String> {
5840+ let after = raw.trim().strip_prefix('$')?;
5841+ match interp::reference(after, env)? {
5842+ (interp::Reference::Var(path), len) if len == after.len() => Some(path),
5843+ _ => None,
22095844 }
2210−
2211− segments
22125845}
22135846
2214−/// The items of a text list: a range `A..B [step N]`, or comma-separated.
2215−fn text_list_items(list: &str) -> Vec<String> {
2216− if let Some((start, rest)) = list.split_once("..") {
2217− let (end, step) = match rest.split_once(" step ") {
2218− Some((end, step)) => (end.trim(), step.trim().parse::<i64>().unwrap_or(1).max(1)),
2219− None => (rest.trim(), 1),
5847+/// The attributes of `tokens` after each whole-attribute `if()` has
5848+/// chosen (see [`syntax::Choice`]), in order, into `out`. The branch not
5849+/// taken isn't evaluated; with `validate`, its attribute names are checked
5850+/// like code that doesn't run, under the prefixes `prefix` the `if()` is
5851+/// under (`hover:if(...)`).
5852+fn choose_attrs(
5853+ tokens: &[syntax::Attr],
5854+ prefix: &str,
5855+ line_num: usize,
5856+ ctx: &mut ParseContext,
5857+ validate: bool,
5858+ text_keys: &[String],
5859+ out: &mut Vec<syntax::Attr>,
5860+) {
5861+ for token in tokens {
5862+ let Some(choice) = &token.choice else {
5863+ out.push(token.clone());
5864+ continue;
5865+ };
5866+ let Some(condition) = choice_shape(token, choice, line_num, ctx) else {
5867+ continue;
22205868 };
2221− if let (Ok(start), Ok(end)) = (start.trim().parse::<i64>(), end.parse::<i64>()) {
2222− return numeric_range(start, end, step);
5869+ let taken = match condition.span.line {
5870+ 0 => ctx.condition(&condition.raw, line_num, None),
5871+ line => ctx.condition(&condition.raw, line, Some(condition.span.column)),
5872+ };
5873+ let (chosen, other) = match taken {
5874+ true => (choice.branches.first(), choice.branches.get(1)),
5875+ false => (choice.branches.get(1), choice.branches.first()),
5876+ };
5877+ if let Some(other) = other {
5878+ track_var_refs(&branch_text(other), &mut ctx.used_variables);
5879+ if validate {
5880+ check_branch(token, other, prefix, line_num, ctx, text_keys);
5881+ }
5882+ }
5883+ if let Some(branch) = chosen {
5884+ choose_attrs(
5885+ branch.attrs(),
5886+ prefix,
5887+ line_num,
5888+ ctx,
5889+ validate,
5890+ text_keys,
5891+ out,
5892+ );
22235893 }
22245894 }
2225− list.split(',')
2226− .map(|s| s.trim().to_string())
2227− .filter(|s| !s.is_empty())
2228− .collect()
22295895}
22305896
2231−/// Make `$target` (and `$target.key`, and nested lists) a copy of the list
2232−/// item stored under `source`.
2233−fn bind_item(vars: &mut HashMap<String, String>, source: &str, target: &str) {
2234− let under = |key: &str, name: &str| {
2235− key.strip_prefix(name)
2236− .is_some_and(|rest| rest.is_empty() || rest.starts_with(['.', '#']))
5897+/// Report what is wrong with the shape of `if()`: an empty condition, a
5898+/// number of branches other than one or two, text after a group's `]`.
5899+/// Returns the condition when the `if()` can be evaluated.
5900+fn choice_shape<'a>(
5901+ token: &syntax::Attr,
5902+ choice: &'a syntax::Choice,
5903+ line_num: usize,
5904+ ctx: &mut ParseContext,
5905+) -> Option<&'a syntax::Arg> {
5906+ let line = if token.span.line == 0 {
5907+ line_num
5908+ } else {
5909+ token.span.line
22375910 };
2238− vars.retain(|key, _| !under(key, target));
2239− let copies: Vec<(String, String)> = vars
2240− .iter()
2241− .filter(|(key, _)| under(key, source))
2242− .map(|(key, value)| (format!("{}{}", target, &key[source.len()..]), value.clone()))
2243− .collect();
2244− vars.extend(copies);
2245− // A record has no text of its own
2246− vars.entry(target.to_string()).or_default();
2247−}
2248−
2249−/// Inclusive integer range from `start` to `end` (counting down when
2250−/// `start > end`), stepping by `step`. Stops instead of overflowing.
2251−fn numeric_range(start: i64, end: i64, step: i64) -> Vec<String> {
2252− let mut items = Vec::new();
2253− let mut n = start;
2254− if start <= end {
2255− while n <= end {
2256− items.push(n.to_string());
2257− match n.checked_add(step) {
2258− Some(next) => n = next,
2259− None => break,
2260− }
5911+ // The line the column points into, when it is the one being evaluated
5912+ let source = |ctx: &ParseContext, diagnostic: Diagnostic, at: usize| match &ctx.current_source {
5913+ (current, Some(text)) if *current == at => diagnostic.source(text.clone()),
5914+ _ => diagnostic,
5915+ };
5916+ for branch in &choice.branches {
5917+ if let syntax::Branch::Group {
5918+ trailing: Some(trailing),
5919+ ..
5920+ } = branch
5921+ {
5922+ let diagnostic = source(
5923+ ctx,
5924+ Diagnostic::error(
5925+ code::UNEXPECTED_ARGUMENT,
5926+ trailing.span.line,
5927+ format!(
5928+ "'{}' after the `]` of a group in if(): a branch is one attribute, \
5929+ one `[group]` of attributes or one `$bundle`",
5930+ trailing.raw
5931+ ),
5932+ )
5933+ .column(trailing.span.column)
5934+ .subject(trailing.raw.as_str()),
5935+ trailing.span.line,
5936+ );
5937+ ctx.push_once(diagnostic);
22615938 }
2262− } else {
2263− while n >= end {
2264− items.push(n.to_string());
2265− match n.checked_sub(step) {
2266− Some(next) => n = next,
2267− None => break,
2268− }
5939+ }
5940+ match &choice.condition {
5941+ Some(condition) if (1..=2).contains(&choice.branches.len()) => Some(condition),
5942+ _ => {
5943+ let diagnostic = source(
5944+ ctx,
5945+ Diagnostic::error(
5946+ code::INVALID_EXPRESSION,
5947+ line,
5948+ format!(
5949+ "`{}`: if() takes a condition and one or two branches, \
5950+ `if(CONDITION, A, B)`",
5951+ token.raw
5952+ ),
5953+ )
5954+ .column(token.span.column),
5955+ line,
5956+ );
5957+ ctx.push_once(diagnostic);
5958+ None
22695959 }
22705960 }
2271− items
22725961}
22735962
2274−/// Evaluate `if(cond, a)` or `if(cond, a, b)` when it is all of `text`,
2275−/// returning the chosen branch (empty when `cond` fails and there is no `b`).
2276−fn choose_if(text: &str, ctx: &mut ParseContext, line: usize) -> Option<String> {
2277− let inner = text.strip_prefix("if(")?.strip_suffix(')')?;
2278− let args = split_if_args(inner);
2279− // `if(a) (b)` isn't one call
2280− if split_trailing_paren(inner) || !(2..=3).contains(&args.len()) {
2281− return None;
2282− }
2283− let branch = if ctx.condition(args[0].trim(), line) {
2284− args[1]
2285− } else {
2286− args.get(2).copied().unwrap_or("")
2287− };
2288− Some(branch.trim().to_string())
5963+/// A branch's text, for the names it uses.
5964+fn branch_text(branch: &syntax::Branch) -> String {
5965+ let raws: Vec<&str> = branch.attrs().iter().map(|a| a.raw.as_str()).collect();
5966+ raws.join(", ")
22895967}
22905968
2291−/// Whether the parentheses in `inner` close before its end, as in the
2292−/// inside of `if(a)(b)`.
2293−fn split_trailing_paren(inner: &str) -> bool {
2294− let mut depth = 0i32;
2295− let mut quote = None;
2296− for c in inner.chars() {
2297− match c {
2298− '"' | '\'' if quote == Some(c) => quote = None,
2299− '"' | '\'' if quote.is_none() => quote = Some(c),
2300− _ if quote.is_some() => {}
2301− '(' => depth += 1,
2302− ')' => {
2303− depth -= 1;
2304− if depth < 0 {
2305− return true;
2306− }
2307− }
2308− _ => {}
2309− }
2310− }
2311− false
5969+/// Check attributes that are never evaluated (in code that doesn't run,
5970+/// or the branch an `if()` didn't take), as far as they can be checked:
5971+/// names are, and literal values; a value with a variable depends on what
5972+/// the variable holds. Each branch of an `if()` is checked on its own.
5973+fn check_attrs(tokens: &[syntax::Attr], line: usize, ctx: &mut ParseContext, text_keys: &[String]) {
5974+ parse_attr_list(&literal_attrs(tokens), line, ctx, true, text_keys);
5975+ check_choices(tokens, "", line, ctx, text_keys);
23125976}
23135977
2314−/// Resolve a value written `if(cond, a, b)`: evaluate `cond` and keep the
2315−/// chosen branch's text, or `None` when the choice is empty. Other
2316−/// attributes are returned unchanged.
2317−fn choose_if_value(part: &str, ctx: &mut ParseContext, line: usize) -> Option<String> {
2318− let Some(pos) = part.find(['=', ' ']) else {
2319− return Some(part.to_string());
2320− };
2321− let (head, value) = part.split_at(pos + 1);
2322− match choose_if(value.trim(), ctx, line) {
2323− Some(branch) if branch.is_empty() => None,
2324− Some(branch) => Some(format!("{}{}", head, branch)),
2325− None => Some(part.to_string()),
5978+/// [`check_attrs`] for a branch of the `if()` `token`, under the prefixes
5979+/// `prefix` it is under: `hover:if($on, color red, [id=x])` checks
5980+/// `hover:[id=x]`, an error whichever branch is taken.
5981+fn check_branch(
5982+ token: &syntax::Attr,
5983+ branch: &syntax::Branch,
5984+ prefix: &str,
5985+ line: usize,
5986+ ctx: &mut ParseContext,
5987+ text_keys: &[String],
5988+) {
5989+ if prefix.is_empty() {
5990+ check_attrs(branch.attrs(), line, ctx, text_keys);
5991+ return;
23265992 }
5993+ let list = syntax::AttrList {
5994+ attrs: branch.attrs().to_vec(),
5995+ span: token.span,
5996+ closed: true,
5997+ };
5998+ let grouped = syntax::Attr {
5999+ key: prefix.to_string(),
6000+ value: None,
6001+ html: false,
6002+ raw: token.raw.clone(),
6003+ span: token.span,
6004+ choice: None,
6005+ prefixed: Some(Box::new(syntax::Prefixed {
6006+ prefix: prefix.to_string(),
6007+ prefix_span: token.span,
6008+ target: syntax::Branch::Group {
6009+ list,
6010+ trailing: None,
6011+ },
6012+ })),
6013+ };
6014+ check_attrs(std::slice::from_ref(&grouped), line, ctx, text_keys);
23276015}
23286016
2329−fn split_if_args(input: &str) -> Vec<&str> {
2330− let mut parts = Vec::new();
2331− let mut start = 0;
2332− let mut depth = 0;
2333− let mut quote = None;
2334− for (i, c) in input.char_indices() {
2335− match c {
2336− '"' | '\'' if quote == Some(c) => quote = None,
2337− '"' | '\'' if quote.is_none() => quote = Some(c),
2338− _ if quote.is_some() => {}
2339− '(' => depth += 1,
2340− ')' => depth -= 1,
2341− ',' if depth == 0 => {
2342− parts.push(&input[start..i]);
2343− start = i + 1;
6017+/// [`check_attrs`] for the branches of each `if()` of `tokens`, which are
6018+/// under the prefixes `prefix`, also inside a prefixed group or as a
6019+/// prefixed `if()`.
6020+fn check_choices(
6021+ tokens: &[syntax::Attr],
6022+ prefix: &str,
6023+ line: usize,
6024+ ctx: &mut ParseContext,
6025+ text_keys: &[String],
6026+) {
6027+ for token in tokens {
6028+ if let Some(choice) = &token.choice
6029+ && choice_shape(token, choice, line, ctx).is_some()
6030+ {
6031+ for branch in &choice.branches {
6032+ check_branch(token, branch, prefix, line, ctx, text_keys);
23446033 }
2345− _ => {}
6034+ }
6035+ if let Some(prefixed) = &token.prefixed {
6036+ let inner = format!("{}{}", prefix, prefixed.prefix);
6037+ check_choices(prefixed.target.attrs(), &inner, line, ctx, text_keys);
23466038 }
23476039 }
2348− parts.push(&input[start..]);
2349− parts
23506040}
23516041
23526042// ---------------------------------------------------------------------------
23536043// Post-parse validation (context-dependent warnings)
23546044// ---------------------------------------------------------------------------
23556045
2356−/// Attributes that only make sense on container elements (@row, @el, @el).
2357−const CONTAINER_ONLY_ATTRS: &[&str] = &[
2358− "spacing",
2359− "gap",
2360− "wrap",
2361− "grid-cols",
2362− "grid-rows",
2363− "container",
2364− "container-name",
2365− "container-type",
2366−];
2367−
23686046fn element_kind_name(kind: &ElementKind) -> String {
23696047 format!("@{}", kind.name())
23706048}
23716049
2372−fn is_container(kind: &ElementKind) -> bool {
2373− matches!(kind, ElementKind::Row | ElementKind::El)
2374− || kind.spec().is_some_and(|spec| spec.container)
6050+/// HTML elements whose start tag ends an open `<p>`: written inside a
6051+/// `@paragraph`, the browser moves them out of it. (`div` isn't here:
6052+/// inside text, htmlang writes its `<div>`s as `<span>`s.)
6053+#[rustfmt::skip]
6054+const ENDS_A_PARAGRAPH: &[&str] = &[
6055+ "address", "article", "aside", "blockquote", "dd", "details", "dialog", "dl", "dt",
6056+ "fieldset", "figcaption", "figure", "footer", "form", "h1", "h2", "h3", "h4", "h5", "h6",
6057+ "header", "hgroup", "hr", "li", "main", "menu", "nav", "ol", "p", "pre", "search",
6058+ "section", "summary", "table", "ul",
6059+];
6060+
6061+/// The HTML element `kind` is written as, if the browser would take it out
6062+/// of a `<p>`.
6063+fn ends_a_paragraph(kind: &ElementKind) -> Option<&'static str> {
6064+ let html = match kind {
6065+ ElementKind::Paragraph => "p",
6066+ ElementKind::Tag(spec) => spec.html,
6067+ _ => return None,
6068+ };
6069+ ENDS_A_PARAGRAPH.contains(&html).then_some(html)
23756070}
23766071
23776072/// Stricter checks for `htmlang lint`, on top of the diagnostics every
@@ -2381,132 +6076,171 @@ pub fn lint(nodes: &[Node]) -> Vec<Diagnostic> {
23816076 fn walk(nodes: &[Node], depth: usize, out: &mut Vec<Diagnostic>) {
23826077 for node in nodes {
23836078 let Node::Element(elem) = node else { continue };
2384− let mut warn = |message: String| {
2385− out.push(Diagnostic {
2386− line: elem.line_num,
2387− column: None,
2388− message,
2389− severity: Severity::Warning,
2390− source_line: None,
2391− })
6079+ let start = out.len();
6080+ let mut warn = |code: &'static str, message: String| {
6081+ out.push(Diagnostic::warning(code, elem.line_num, message))
23926082 };
23936083 if depth > 10 {
2394− warn(format!(
2395− "deeply nested element ({} levels): consider simplifying",
2396− depth
2397− ));
6084+ warn(
6085+ code::DEEP_NESTING,
6086+ format!(
6087+ "deeply nested element ({} levels): consider simplifying",
6088+ depth
6089+ ),
6090+ );
23986091 }
2399− if matches!(elem.kind, ElementKind::Row | ElementKind::El) && elem.children.is_empty() {
2400− warn(format!(
2401− "empty container (@{}) has no children",
2402− elem.kind.name()
2403− ));
6092+ // A function's body may draw with an empty element (a spacer,
6093+ // a dot): only one written in the page is flagged
6094+ if elem.kind.layout().is_container()
6095+ && elem.children.is_empty()
6096+ && elem.function.is_none()
6097+ {
6098+ warn(
6099+ code::EMPTY_CONTAINER,
6100+ format!("empty container (@{}) has no children", elem.kind.name()),
6101+ );
24046102 }
24056103 if elem.kind.is_tag("button") && !elem.attrs.iter().any(|a| a.key == "type") {
2406− warn("@button missing 'type' attribute (defaults to submit)".to_string());
6104+ warn(
6105+ code::MISSING_BUTTON_TYPE,
6106+ "@button missing 'type' attribute (defaults to submit)".to_string(),
6107+ );
24076108 }
6109+ in_function_body(elem, &mut out[start..]);
24086110 walk(&elem.children, depth + 1, out);
24096111 }
24106112 }
24116113 let mut out = Vec::new();
24126114 walk(nodes, 0, &mut out);
6115+ dedupe(&mut out);
24136116 out
24146117}
24156118
6119+/// `in_paragraph`: the nodes are inside a `@paragraph` (and not inside a
6120+/// `@button` in it, which the browser keeps whole).
24166121fn validate_tree(
24176122 nodes: &[Node],
24186123 parent_kind: Option<&ElementKind>,
6124+ in_paragraph: bool,
24196125 diagnostics: &mut Vec<Diagnostic>,
24206126) {
24216127 for node in nodes {
6128+ // An element inside a line of text (`{@kbd ...}`, an inline call)
6129+ // is checked like one on a line of its own
6130+ if let Node::Text(segments) = node {
6131+ let inline: Vec<Node> = segments
6132+ .iter()
6133+ .filter_map(|segment| match segment {
6134+ TextSegment::Inline(elem) => Some(Node::Element(elem.clone())),
6135+ _ => None,
6136+ })
6137+ .collect();
6138+ validate_tree(&inline, parent_kind, in_paragraph, diagnostics);
6139+ }
24226140 if let Node::Element(elem) = node {
6141+ let start = diagnostics.len();
6142+ dropped_by_the_element(elem, diagnostics);
6143+ if in_paragraph && let Some(html) = ends_a_paragraph(&elem.kind) {
6144+ diagnostics.push(
6145+ Diagnostic::warning(
6146+ code::BLOCK_IN_PARAGRAPH,
6147+ elem.line_num,
6148+ format!(
6149+ "{0} inside @paragraph: HTML ends a <p> before a <{1}>, so the \
6150+ browser moves the <{1}> out of the paragraph. Put {0} after the \
6151+ paragraph, or use @el, @row or @grid, which are laid out inline \
6152+ in text",
6153+ element_kind_name(&elem.kind),
6154+ html
6155+ ),
6156+ )
6157+ .subject(elem.kind.name()),
6158+ );
6159+ }
24236160 for attr in &elem.attrs {
24246161 let base = crate::vocab::base_attribute(&attr.key);
2425− if base == "width"
2426− && attr.value.as_deref() == Some("fill")
2427− && !matches!(parent_kind, Some(ElementKind::Row))
2428− {
2429− diagnostics.push(Diagnostic {
2430− line: elem.line_num,
2431− column: None,
2432− message: "'width fill' works best inside @row; using 100% as fallback"
2433− .to_string(),
2434− severity: Severity::Warning,
2435− source_line: None,
2436− });
2437− }
2438− if base == "height"
2439− && attr.value.as_deref() == Some("fill")
2440− && !parent_kind.is_some_and(ElementKind::is_column)
2441− {
2442− diagnostics.push(Diagnostic {
2443− line: elem.line_num,
2444− column: None,
2445− message: "'height fill' works best inside @el; using 100% as fallback"
2446− .to_string(),
2447− severity: Severity::Warning,
2448− source_line: None,
2449− });
2450− }
24516162
2452− // Container-only attributes on non-container elements
2453− if CONTAINER_ONLY_ATTRS.contains(&base) && !is_container(&elem.kind) {
2454− diagnostics.push(Diagnostic {
2455− line: elem.line_num,
2456− column: None,
2457− message: format!(
2458− "'{}' has no effect on {} (only works on @row, @el, @el)",
2459− base,
2460− element_kind_name(&elem.kind)
2461− ),
2462− severity: Severity::Warning,
2463− source_line: None,
2464− });
6163+ // htmlang's words for laying out children, on an element
6164+ // that doesn't lay out its children: left out (codegen)
6165+ if !attr.html
6166+ && crate::vocab::CONTAINER_ATTRIBUTES.contains(&base)
6167+ && !elem.kind.layout().is_container()
6168+ && !has_no_element(&elem.kind)
6169+ && !crate::vocab::split_prefixes(&attr.key)
6170+ .0
6171+ .contains(&"children:")
6172+ {
6173+ diagnostics.push(not_a_container(&elem.kind, elem.line_num, base));
24656174 }
24666175
24676176 // Form-specific: placeholder only on @input/@textarea
24686177 if base == "placeholder"
24696178 && !(elem.kind.is_tag("input") || elem.kind.is_tag("textarea"))
24706179 {
2471− diagnostics.push(Diagnostic {
2472− line: elem.line_num,
2473− column: None,
2474− message: format!(
6180+ diagnostics.push(Diagnostic::new(
6181+ code::NO_EFFECT,
6182+ Severity::Warning,
6183+ elem.line_num,
6184+ format!(
24756185 "'placeholder' has no effect on {} (only works on @input, @textarea)",
24766186 element_kind_name(&elem.kind)
24776187 ),
2478− severity: Severity::Warning,
2479− source_line: None,
2480− });
6188+ ));
24816189 }
24826190
2483− // 'for' only on @label
2484− if base == "for" && !elem.kind.is_tag("label") {
2485− diagnostics.push(Diagnostic {
2486− line: elem.line_num,
2487− column: None,
2488− message: format!(
2489− "'for' has no effect on {} (only works on @label)",
6191+ // 'for' only on @label and @output
6192+ if base == "for" && !(elem.kind.is_tag("label") || elem.kind.is_tag("output")) {
6193+ diagnostics.push(Diagnostic::new(
6194+ code::NO_EFFECT,
6195+ Severity::Warning,
6196+ elem.line_num,
6197+ format!(
6198+ "'for' has no effect on {} (only works on @label and @output)",
24906199 element_kind_name(&elem.kind)
24916200 ),
2492− severity: Severity::Warning,
2493− source_line: None,
2494− });
6201+ ));
6202+ }
6203+
6204+ // `width=` and `height=` are HTML attributes of media and
6205+ // embedded content only; elsewhere they are styles
6206+ if attr.html
6207+ && (base == "width" || base == "height")
6208+ && !matches!(elem.kind, ElementKind::Image)
6209+ && ![
6210+ "video", "canvas", "iframe", "embed", "object", "input", "source",
6211+ ]
6212+ .iter()
6213+ .any(|tag| elem.kind.is_tag(tag))
6214+ {
6215+ let value = attr.value.as_deref().unwrap_or("");
6216+ diagnostics.push(
6217+ Diagnostic::warning(
6218+ code::HTML_ATTRIBUTE_FORM,
6219+ elem.line_num,
6220+ format!(
6221+ "'{0}={1}' has no effect on {2}, which has no {0} attribute: \
6222+ the style is written `{0} {1}`",
6223+ base,
6224+ value,
6225+ element_kind_name(&elem.kind)
6226+ ),
6227+ )
6228+ .subject(format!("{}={}", base, value)),
6229+ );
24956230 }
24966231
24976232 // 'rows'/'cols' only on @textarea
24986233 if (base == "rows" || base == "cols") && !elem.kind.is_tag("textarea") {
2499− diagnostics.push(Diagnostic {
2500− line: elem.line_num,
2501− column: None,
2502− message: format!(
6234+ diagnostics.push(Diagnostic::new(
6235+ code::NO_EFFECT,
6236+ Severity::Warning,
6237+ elem.line_num,
6238+ format!(
25036239 "'{}' has no effect on {} (only works on @textarea)",
25046240 base,
25056241 element_kind_name(&elem.kind)
25066242 ),
2507− severity: Severity::Warning,
2508− source_line: None,
2509− });
6243+ ));
25106244 }
25116245
25126246 // Media-specific attributes only on @video/@audio
@@ -2521,38 +6255,35 @@ fn validate_tree(
25216255 | "preload"
25226256 ) && !matches!(elem.kind.name(), "video" | "audio")
25236257 {
2524− diagnostics.push(Diagnostic {
2525− line: elem.line_num,
2526− column: None,
2527− message: format!(
6258+ diagnostics.push(Diagnostic::new(
6259+ code::NO_EFFECT,
6260+ Severity::Warning,
6261+ elem.line_num,
6262+ format!(
25286263 "'{}' has no effect on {} (only works on @video, @audio)",
25296264 base,
25306265 element_kind_name(&elem.kind)
25316266 ),
2532− severity: Severity::Warning,
2533− source_line: None,
2534− });
6267+ ));
25356268 }
25366269 }
25376270 // Missing alt text on @image
25386271 if matches!(elem.kind, ElementKind::Image) && !elem.attrs.iter().any(|a| a.key == "alt")
25396272 {
2540− diagnostics.push(Diagnostic {
2541− line: elem.line_num,
2542− column: None,
2543− message: "@image missing 'alt' attribute (accessibility)".to_string(),
2544− severity: Severity::Warning,
2545− source_line: None,
2546− });
6273+ diagnostics.push(Diagnostic::new(
6274+ code::MISSING_ALT,
6275+ Severity::Warning,
6276+ elem.line_num,
6277+ "@image missing 'alt' attribute (accessibility)".to_string(),
6278+ ));
25476279 }
25486280 if elem.kind.is_tag("input") && !elem.attrs.iter().any(|a| a.key == "type") {
2549− diagnostics.push(Diagnostic {
2550− line: elem.line_num,
2551− column: None,
2552− message: "@input missing 'type' attribute (defaults to 'text')".to_string(),
2553− severity: Severity::Warning,
2554− source_line: None,
2555− });
6281+ diagnostics.push(Diagnostic::new(
6282+ code::MISSING_INPUT_TYPE,
6283+ Severity::Warning,
6284+ elem.line_num,
6285+ "@input missing 'type' attribute (defaults to 'text')".to_string(),
6286+ ));
25566287 }
25576288 if matches!(elem.kind, ElementKind::Link) {
25586289 // For @link, argument is the URL, not text content
@@ -2563,47 +6294,50 @@ fn validate_tree(
25636294 .iter()
25646295 .any(|a| a.key == "aria-label" || a.key == "title")
25656296 {
2566− diagnostics.push(Diagnostic {
2567− line: elem.line_num,
2568− column: None,
2569− message: "@link has no visible text or aria-label (accessibility)"
2570− .to_string(),
2571− severity: Severity::Warning,
2572− source_line: None,
2573− });
6297+ diagnostics.push(Diagnostic::new(
6298+ code::MISSING_LINK_TEXT,
6299+ Severity::Warning,
6300+ elem.line_num,
6301+ "@link has no visible text or aria-label (accessibility)".to_string(),
6302+ ));
25746303 }
25756304 }
25766305
2577− // Contrast ratio check for hex color pairs
2578− {
2579− let bg_color = elem
2580− .attrs
2581− .iter()
2582− .find(|a| crate::vocab::base_attribute(&a.key) == "background")
2583− .and_then(|a| a.value.as_deref());
2584− let fg_color = elem
2585− .attrs
2586− .iter()
2587− .find(|a| crate::vocab::base_attribute(&a.key) == "color")
2588− .and_then(|a| a.value.as_deref());
6306+ // Contrast ratio check for hex color pairs, each pair on the
6307+ // same elements: the element's own, or those an element prefix
6308+ // (`@td:`) picks out inside it
6309+ let inside = |key: &str| {
6310+ crate::vocab::split_prefixes(key)
6311+ .0
6312+ .into_iter()
6313+ .find_map(crate::vocab::element_prefix)
6314+ .map(str::to_string)
6315+ };
6316+ let mut targets: Vec<Option<String>> = Vec::new();
6317+ for attr in elem.attrs.iter().filter(|a| !a.html) {
6318+ let target = inside(&attr.key);
6319+ if !targets.contains(&target) {
6320+ targets.push(target);
6321+ }
6322+ }
6323+ for target in targets {
6324+ let color = |property: &str| {
6325+ elem.attrs
6326+ .iter()
6327+ .filter(|a| !a.html && inside(&a.key) == target)
6328+ .find(|a| crate::vocab::base_attribute(&a.key) == property)
6329+ .and_then(|a| a.value.as_deref())
6330+ };
6331+ let (bg_color, fg_color) = (color("background"), color("color"));
25896332 if let (Some(bg), Some(fg)) = (bg_color, fg_color)
2590− && let (Some(bg_rgb), Some(fg_rgb)) = (
2591− crate::expr::parse_hex_rgb(bg),
2592− crate::expr::parse_hex_rgb(fg),
2593− )
6333+ && let (Some(bg_rgb), Some(fg_rgb)) = (parse_hex_rgb(bg), parse_hex_rgb(fg))
25946334 {
25956335 let ratio = contrast_ratio(bg_rgb, fg_rgb);
25966336 if ratio < 4.5 {
2597− diagnostics.push(Diagnostic {
2598− line: elem.line_num,
2599− column: None,
2600− message: format!(
6337+ diagnostics.push(Diagnostic::new(code::LOW_CONTRAST, Severity::Warning, elem.line_num, format!(
26016338 "low contrast ratio {:.1}:1 between '{}' and '{}' (WCAG AA requires 4.5:1)",
26026339 ratio, fg, bg
2603− ),
2604− severity: Severity::Warning,
2605− source_line: None,
2606− });
6340+ )));
26076341 }
26086342 }
26096343 }
@@ -2618,43 +6352,34 @@ fn validate_tree(
26186352 let has_title = elem.attrs.iter().any(|a| a.key == "title");
26196353 let in_label = parent_kind.is_some_and(|k| k.is_tag("label"));
26206354 if !has_id && !has_aria_label && !has_title && !in_label {
2621− diagnostics.push(Diagnostic {
2622− line: elem.line_num,
2623− column: None,
2624− message: format!(
6355+ diagnostics.push(Diagnostic::new(code::MISSING_LABEL, Severity::Warning, elem.line_num, format!(
26256356 "{} should have an 'id' (with matching @label[for]), 'aria-label', or be wrapped in @label (accessibility)",
26266357 element_kind_name(&elem.kind)
2627− ),
2628− severity: Severity::Warning,
2629− source_line: None,
2630− });
6358+ )));
26316359 }
26326360 }
26336361
26346362 // @iframe should have title attribute
26356363 if elem.kind.is_tag("iframe") && !elem.attrs.iter().any(|a| a.key == "title") {
2636− diagnostics.push(Diagnostic {
2637− line: elem.line_num,
2638− column: None,
2639− message: "@iframe missing 'title' attribute (accessibility)".to_string(),
2640− severity: Severity::Warning,
2641− source_line: None,
2642− });
6364+ diagnostics.push(Diagnostic::new(
6365+ code::MISSING_TITLE,
6366+ Severity::Warning,
6367+ elem.line_num,
6368+ "@iframe missing 'title' attribute (accessibility)".to_string(),
6369+ ));
26436370 }
26446371
26456372 // @button should have accessible text
26466373 if elem.kind.is_tag("button") {
2647− let has_text = elem.argument.is_some() || !elem.children.is_empty();
6374+ let has_text = !elem.children.is_empty();
26486375 let has_aria = elem.attrs.iter().any(|a| a.key == "aria-label");
26496376 if !has_text && !has_aria {
2650− diagnostics.push(Diagnostic {
2651− line: elem.line_num,
2652− column: None,
2653− message: "@button has no text content or aria-label (accessibility)"
2654− .to_string(),
2655− severity: Severity::Warning,
2656− source_line: None,
2657− });
6377+ diagnostics.push(Diagnostic::new(
6378+ code::MISSING_BUTTON_TEXT,
6379+ Severity::Warning,
6380+ elem.line_num,
6381+ "@button has no text content or aria-label (accessibility)".to_string(),
6382+ ));
26586383 }
26596384 }
26606385
@@ -2667,16 +6392,15 @@ fn validate_tree(
26676392 let has_track = elem
26686393 .children
26696394 .iter()
2670− .any(|c| matches!(c, Node::Element(e) if e.kind.is_tag("source")));
6395+ .any(|c| matches!(c, Node::Element(e) if e.kind.is_tag("track")));
26716396 if !has_aria && !has_track {
2672− diagnostics.push(Diagnostic {
2673− line: elem.line_num,
2674− column: None,
2675− message: "@video should have aria-label or captions for accessibility"
6397+ diagnostics.push(Diagnostic::new(
6398+ code::MISSING_CAPTIONS,
6399+ Severity::Warning,
6400+ elem.line_num,
6401+ "@video should have aria-label or a captions @track for accessibility"
26766402 .to_string(),
2677− severity: Severity::Warning,
2678− source_line: None,
2679− });
6403+ ));
26806404 }
26816405 }
26826406
@@ -2686,20 +6410,204 @@ fn validate_tree(
26866410 && let Ok(n) = val.parse::<i32>()
26876411 && n > 0
26886412 {
2689− diagnostics.push(Diagnostic {
2690− line: elem.line_num,
2691− column: None,
2692− message: format!("tabindex {} is positive — avoid positive tabindex values as they disrupt natural tab order", n),
2693− severity: Severity::Warning,
2694− source_line: None,
2695− });
6413+ 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)));
26966414 }
6415+ in_function_body(elem, &mut diagnostics[start..]);
6416+
6417+ // An element that ends the <p> takes what is inside it out of
6418+ // the paragraph too, so only it is reported
6419+ let in_paragraph = elem.kind == ElementKind::Paragraph
6420+ || (in_paragraph
6421+ && ends_a_paragraph(&elem.kind).is_none()
6422+ && !elem.kind.is_tag("button"));
6423+ validate_tree(&elem.children, Some(&elem.kind), in_paragraph, diagnostics);
6424+ }
6425+ }
6426+}
6427+
6428+/// What an element has no place for in HTML, which would otherwise be
6429+/// left out of the page: attributes on `@fragment` (which has no element
6430+/// of its own), styles on `@script` (which isn't shown), a body under a
6431+/// `@script` that has a src (which the browser doesn't run), an element
6432+/// under a `@script` (whose body is code), and content in a void element
6433+/// such as `@input`.
6434+fn dropped_by_the_element(elem: &Element, diagnostics: &mut Vec<Diagnostic>) {
6435+ let name = elem.kind.name();
6436+ let keys = |attrs: Vec<&Attribute>| {
6437+ attrs
6438+ .iter()
6439+ .map(|a| format!("'{}'", a.key))
6440+ .collect::<Vec<_>>()
6441+ .join(", ")
6442+ };
6443+ let mut error = |code: &'static str, message: String| {
6444+ diagnostics.push(Diagnostic::error(code, elem.line_num, message).subject(name))
6445+ };
6446+ if elem.kind == ElementKind::Fragment && !elem.attrs.is_empty() {
6447+ error(
6448+ code::UNEXPECTED_ARGUMENT,
6449+ format!(
6450+ "@fragment has no element of its own to put attributes on, so {} would go \
6451+ nowhere: put them on its children, or use @el",
6452+ keys(elem.attrs.iter().collect())
6453+ ),
6454+ );
6455+ }
6456+ // The leading argument given twice: an attribute passed to the root
6457+ // of a function whose body gives the argument (written on one line,
6458+ // it is reported where it is read, and the attribute wins there)
6459+ if let Some(argument) = &elem.argument
6460+ && let Some(attr) = elem
6461+ .attrs
6462+ .iter()
6463+ .find(|a| a.html && elem.kind.arg().attributes().contains(&a.key.as_str()))
6464+ {
6465+ error(
6466+ code::DUPLICATE_ATTRIBUTE,
6467+ format!(
6468+ "@{} takes '{}' as its {}, and it also has {}={}: give it once",
6469+ name,
6470+ argument,
6471+ leading_name(&elem.kind),
6472+ attr.key,
6473+ attr.value.as_deref().unwrap_or("")
6474+ ),
6475+ );
6476+ }
6477+ if elem.kind.is_verbatim() {
6478+ let styles: Vec<&Attribute> = elem
6479+ .attrs
6480+ .iter()
6481+ .filter(|a| !a.html && !crate::vocab::BOOLEAN_HTML_ATTRS.contains(&a.key.as_str()))
6482+ .collect();
6483+ if !styles.is_empty() {
6484+ error(
6485+ code::UNEXPECTED_ARGUMENT,
6486+ format!(
6487+ "@{} isn't shown on the page, so its styles {} would go nowhere",
6488+ name,
6489+ keys(styles)
6490+ ),
6491+ );
6492+ }
6493+ let src = elem.argument.clone().or_else(|| {
6494+ elem.attrs
6495+ .iter()
6496+ .find(|a| a.html && a.key == "src")
6497+ .map(|a| a.value.clone().unwrap_or_default())
6498+ });
6499+ if let Some(src) = src
6500+ && !elem.children.is_empty()
6501+ {
6502+ error(
6503+ code::UNEXPECTED_CONTENT,
6504+ format!(
6505+ "@{0} has both a src ('{1}') and a body: the browser runs only the file, \
6506+ so the body would go nowhere. Put the code in {1}, or leave out the src",
6507+ name, src
6508+ ),
6509+ );
6510+ } else if let Some(Node::Element(child)) = elem
6511+ .children
6512+ .iter()
6513+ .find(|child| matches!(child, Node::Element(_)))
6514+ {
6515+ // `@script > @b x`: its body is code, not elements
6516+ error(
6517+ code::UNEXPECTED_CONTENT,
6518+ format!(
6519+ "@{} holds its code as the lines under it, kept as written, so @{} would \
6520+ go nowhere",
6521+ name,
6522+ child.kind.name()
6523+ ),
6524+ );
6525+ }
6526+ }
6527+ if elem.kind != ElementKind::Image && elem.attrs.iter().any(|a| !a.html && a.key == "inline") {
6528+ error(
6529+ code::UNEXPECTED_ARGUMENT,
6530+ format!(
6531+ "`inline` puts an image's file into the page, and @{} has none: it only \
6532+ works on @image",
6533+ name
6534+ ),
6535+ );
6536+ }
6537+ if elem.kind.layout() == Layout::Void && !elem.children.is_empty() {
6538+ error(
6539+ code::UNEXPECTED_CONTENT,
6540+ format!(
6541+ "@{} takes no content: it is an element without a closing tag, so its text \
6542+ and indented lines would go nowhere",
6543+ name
6544+ ),
6545+ );
6546+ }
6547+}
6548+
6549+/// `@fragment`, `@script`, `@children` and `@slot`, whose attributes are
6550+/// reported on their own (see `dropped_by_the_element`).
6551+fn has_no_element(kind: &ElementKind) -> bool {
6552+ matches!(
6553+ kind,
6554+ ElementKind::Fragment | ElementKind::Children | ElementKind::Slot(_)
6555+ ) || kind.is_verbatim()
6556+}
26976557
2698− validate_tree(&elem.children, Some(&elem.kind), diagnostics);
6558+/// htmlang's word `word` for laying out children (`spacing`, `wrap`,
6559+/// `grid-cols`, `grid-rows`) on an element that doesn't lay out its
6560+/// children: an error, and the word is left out.
6561+fn not_a_container(kind: &ElementKind, line: usize, word: &str) -> Diagnostic {
6562+ let name = element_kind_name(kind);
6563+ let (what, instead) = match kind.layout() {
6564+ Layout::Text => (
6565+ "is text, whose lines and children flow together with no gap between them",
6566+ "; to space the children out, put them in an @el or @row",
6567+ ),
6568+ Layout::Void => ("has no content to lay out", ""),
6569+ _ => (
6570+ "keeps HTML's own layout",
6571+ "; for a flex layout of your own, write CSS, such as `display flex, gap 8`",
6572+ ),
6573+ };
6574+ Diagnostic::error(
6575+ code::NO_EFFECT,
6576+ line,
6577+ format!(
6578+ "'{0}' can't go on {1}: {1} {2}. `{0}` works on a row, column or grid \
6579+ (@el, @row, @grid, @section, ...){3}",
6580+ word, name, what, instead
6581+ ),
6582+ )
6583+ .subject(word)
6584+}
6585+
6586+/// Diagnostics about an element a function's body wrote are reported at
6587+/// the call (see `belongs_to_call`); say which body the element is in.
6588+fn in_function_body(elem: &Element, diagnostics: &mut [Diagnostic]) {
6589+ if let Some(function) = &elem.function {
6590+ for d in diagnostics {
6591+ d.message = format!("{}\n in the body of @{}", d.message, function);
26996592 }
27006593 }
27016594}
27026595
6596+/// Report each diagnostic once: a line that runs many times (in a loop, in
6597+/// a function called from one place many times) reports its problems once.
6598+fn dedupe(diagnostics: &mut Vec<Diagnostic>) {
6599+ let mut seen = HashSet::new();
6600+ diagnostics.retain(|d| {
6601+ seen.insert((
6602+ d.code,
6603+ d.line,
6604+ d.column,
6605+ d.message.clone(),
6606+ d.severity as u8,
6607+ ))
6608+ });
6609+}
6610+
27036611fn relative_luminance(r: u8, g: u8, b: u8) -> f64 {
27046612 fn linearize(c: u8) -> f64 {
27056613 let s = c as f64 / 255.0;
@@ -2712,6 +6620,24 @@ fn relative_luminance(r: u8, g: u8, b: u8) -> f64 {
27126620 0.2126 * linearize(r) + 0.7152 * linearize(g) + 0.0722 * linearize(b)
27136621}
27146622
6623+/// The red, green and blue of a `#rgb` or `#rrggbb` colour.
6624+fn parse_hex_rgb(s: &str) -> Option<(u8, u8, u8)> {
6625+ let s = s.strip_prefix('#')?;
6626+ if !s.bytes().all(|b| b.is_ascii_hexdigit()) {
6627+ return None;
6628+ }
6629+ let channel = |i: usize, len: usize| u8::from_str_radix(&s[i..i + len], 16).ok();
6630+ match s.len() {
6631+ 3 => Some((
6632+ channel(0, 1)? * 17,
6633+ channel(1, 1)? * 17,
6634+ channel(2, 1)? * 17,
6635+ )),
6636+ 6 => Some((channel(0, 2)?, channel(2, 2)?, channel(4, 2)?)),
6637+ _ => None,
6638+ }
6639+}
6640+
27156641fn contrast_ratio(c1: (u8, u8, u8), c2: (u8, u8, u8)) -> f64 {
27166642 let l1 = relative_luminance(c1.0, c1.1, c1.2);
27176643 let l2 = relative_luminance(c2.0, c2.1, c2.2);
@@ -2719,70 +6645,48 @@ fn contrast_ratio(c1: (u8, u8, u8), c2: (u8, u8, u8)) -> f64 {
27196645 (lighter + 0.05) / (darker + 0.05)
27206646}
27216647
2722−// ---------------------------------------------------------------------------
2723−// Variable substitution
2724−// ---------------------------------------------------------------------------
2725−
2726−/// Interpolate `$name` variables and `${expr}` expressions into text.
2727−/// Undefined variables, and expressions that don't evaluate, are left as
2728−/// written so they show up in the output.
2729−fn substitute_vars(input: &str, vars: &HashMap<String, String>) -> String {
2730− if !input.contains('$') {
2731− return input.to_string();
2732− }
2733− let is_name_char = |c: char| c.is_alphanumeric() || matches!(c, '_' | '-' | '.');
2734− let mut result = String::with_capacity(input.len());
2735− let mut rest = input;
2736− while let Some(pos) = rest.find('$') {
2737− result.push_str(&rest[..pos]);
2738− let after = &rest[pos + 1..];
2739− if after.starts_with('{')
2740− && let Some(close) = matching_brace(after)
2741− {
2742− let source = &after[1..close];
2743− match crate::expr::eval(source, &|name: &str| lookup(vars, name)) {
2744− Ok(value) => result.push_str(&value.to_string()),
2745− Err(_) => result.push_str(&rest[pos..pos + 1 + close + 1]),
2746− }
2747− rest = &after[close + 1..];
2748− continue;
2749− }
2750− let mut end = after
2751− .find(|c: char| !is_name_char(c))
2752− .unwrap_or(after.len());
2753− while end > 0 && after[..end].ends_with('.') {
2754− end -= 1;
2755− }
2756− let name = &after[..end];
2757− match vars.get(name) {
2758− Some(value) if !name.is_empty() => result.push_str(value),
2759− _ => {
2760− result.push('$');
2761− result.push_str(name);
2762− }
2763− }
2764− rest = &after[end..];
2765− }
2766− result.push_str(rest);
2767− result
2768−}
2769−
27706648/// `@image [inline] icon.svg` becomes the SVG's markup, with `width`,
2771−/// `height`, `color` / `fill`, `class=` and `id=` applied to the `<svg>`
2772−/// tag. Other nodes are returned unchanged.
6649+/// `height`, `color` / `fill` and the HTML attributes (`class=`, `id=`,
6650+/// `aria-label=`, ...) applied to the `<svg>` tag; any other attribute is
6651+/// an error. Other nodes are returned unchanged.
27736652fn inline_svg(node: Node, line_num: usize, ctx: &mut ParseContext) -> Node {
27746653 let Node::Element(elem) = &node else {
27756654 return node;
27766655 };
2777− let is_inline_svg = elem.kind == ElementKind::Image
6656+ let inline = elem.kind == ElementKind::Image
27786657 && elem.attrs.iter().any(|a| a.key == "inline" && !a.html)
2779− && elem
2780− .argument
2781− .as_deref()
2782− .is_some_and(|src| src.ends_with(".svg"));
2783− if !is_inline_svg {
6658+ && elem.argument.as_deref().is_some_and(|src| !src.is_empty());
6659+ if !inline {
27846660 return node;
27856661 }
6662+ // A raster image: its file, read relative to this one, as a `data:` URI
6663+ if !elem
6664+ .argument
6665+ .as_deref()
6666+ .is_some_and(|src| src.ends_with(".svg"))
6667+ {
6668+ let Node::Element(mut elem) = node else {
6669+ return node;
6670+ };
6671+ let filename = elem.argument.clone().unwrap_or_default();
6672+ let resolved = ctx.resolve(&filename);
6673+ match std::fs::read(&resolved) {
6674+ Ok(data) => {
6675+ elem.argument = Some(crate::codegen::data_uri(&filename, &data));
6676+ ctx.included_files.push(resolved);
6677+ }
6678+ Err(e) => ctx.diagnostics.push(Diagnostic::new(
6679+ code::UNREADABLE_FILE,
6680+ Severity::Error,
6681+ line_num,
6682+ format!(
6683+ "cannot load image '{}' to put it into the page: {}",
6684+ filename, e
6685+ ),
6686+ )),
6687+ }
6688+ return Node::Element(elem);
6689+ }
27866690 let filename = elem.argument.clone().unwrap_or_default();
27876691 let resolved = match &ctx.base_path {
27886692 Some(base) => base.join(&filename),
@@ -2791,81 +6695,104 @@ fn inline_svg(node: Node, line_num: usize, ctx: &mut ParseContext) -> Node {
27916695 let mut svg = match std::fs::read_to_string(&resolved) {
27926696 Ok(text) => text.trim().to_string(),
27936697 Err(e) => {
2794− ctx.diagnostics.push(Diagnostic {
2795− line: line_num,
2796− column: None,
2797− message: format!("cannot load SVG '{}': {}", filename, e),
2798− severity: Severity::Error,
2799− source_line: None,
2800− });
6698+ ctx.diagnostics.push(Diagnostic::new(
6699+ code::UNREADABLE_FILE,
6700+ Severity::Error,
6701+ line_num,
6702+ format!("cannot load SVG '{}': {}", filename, e),
6703+ ));
28016704 return node;
28026705 }
28036706 };
28046707 ctx.included_files.push(resolved);
6708+ // The file's markup has no class of its own, so a style reaches it only
6709+ // as one of the root's attributes: anything else is reported, never
6710+ // left out silently
6711+ let mut left_out: Vec<String> = Vec::new();
6712+ // The styles go in the root's `style=`, where a length takes its unit
6713+ // and `var(--name)` works, as in any CSS
6714+ let mut style: Vec<String> = Vec::new();
28056715 for attr in &elem.attrs {
2806− let Some(value) = &attr.value else { continue };
2807− let target = match (attr.key.as_str(), attr.html) {
2808− ("width", false) | ("height", false) => attr.key.as_str(),
2809− ("color", false) | ("fill", false) => "fill",
2810− ("class", true) | ("id", true) => attr.key.as_str(),
2811− _ => continue,
6716+ let target = match (attr.key.as_str(), attr.html, &attr.value) {
6717+ ("inline", false, None) | ("src", true, _) => continue,
6718+ // `fill` and `shrink` are layout words, which need a class
6719+ ("width" | "height", false, Some(value))
6720+ if matches!(value.as_str(), "fill" | "shrink") =>
6721+ {
6722+ left_out.push(format!("{} {}", attr.key, value));
6723+ continue;
6724+ }
6725+ ("width" | "height", false, Some(value)) => {
6726+ let value = crate::vocab::with_px(&attr.key, value);
6727+ style.push(format!("{}:{}", attr.key, value));
6728+ continue;
6729+ }
6730+ ("color" | "fill", false, Some(value)) => {
6731+ style.push(format!("fill:{}", value));
6732+ continue;
6733+ }
6734+ ("style", true, Some(value)) => {
6735+ style.insert(0, value.trim().trim_end_matches(';').to_string());
6736+ continue;
6737+ }
6738+ ("alt", true, _) => {
6739+ left_out.push("alt".to_string());
6740+ continue;
6741+ }
6742+ (key, true, Some(_)) => key,
6743+ (key, false, None) if crate::vocab::BOOLEAN_HTML_ATTRS.contains(&key) => key,
6744+ _ => {
6745+ left_out.push(attr.key.clone());
6746+ continue;
6747+ }
28126748 };
2813− svg = set_svg_attr(&svg, target, value);
6749+ let value = attr.value.as_deref().unwrap_or("");
6750+ svg = set_svg_attr(&svg, target, &html_escape_md(value));
28146751 }
2815− Node::Raw(svg)
2816−}
2817−
2818−/// Index of the `}` matching the `{` that `s` starts with (skipping
2819−/// braces inside string literals).
2820−fn matching_brace(s: &str) -> Option<usize> {
2821− let mut depth = 0;
2822− let mut in_string = false;
2823− for (i, c) in s.char_indices() {
2824− match c {
2825− '"' => in_string = !in_string,
2826− _ if in_string => {}
2827− '{' => depth += 1,
2828− '}' => {
2829− depth -= 1;
2830− if depth == 0 {
2831− return Some(i);
2832− }
2833− }
2834− _ => {}
6752+ if !style.is_empty() {
6753+ // After the file's own `style=`, which stays: these come later, so
6754+ // they win where both set a property
6755+ let mut value = html_escape_md(&style.join(";"));
6756+ if let Some(own) = svg_attr_value(&svg, "style")
6757+ .map(|range| svg[range].trim().trim_end_matches(';').to_string())
6758+ .filter(|own| !own.is_empty())
6759+ {
6760+ value = format!("{};{}", own, value);
28356761 }
6762+ svg = set_svg_attr(&svg, "style", &value);
28366763 }
2837− None
6764+ if !left_out.is_empty() {
6765+ let alt = left_out.iter().any(|name| name == "alt");
6766+ let names = left_out
6767+ .iter()
6768+ .map(|name| format!("'{}'", name))
6769+ .collect::<Vec<_>>()
6770+ .join(", ");
6771+ let mut message = format!(
6772+ "{} 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=`, ...)",
6773+ names
6774+ );
6775+ if alt {
6776+ message.push_str("; an SVG has no alt text: name it with `aria-label=` and `role=img`");
6777+ }
6778+ ctx.diagnostics.push(Diagnostic::new(
6779+ code::UNEXPECTED_ARGUMENT,
6780+ Severity::Error,
6781+ line_num,
6782+ message,
6783+ ));
6784+ }
6785+ Node::Raw(svg)
28386786}
28396787
28406788// ---------------------------------------------------------------------------
28416789// Variable usage tracking
28426790// ---------------------------------------------------------------------------
28436791
2844−/// Scan a string for $name references and record them in the used set.
6792+/// Record the names a string refers to (by syntax) as used.
28456793fn track_var_refs(input: &str, used: &mut HashSet<String>) {
2846− if !input.contains('$') {
2847− return;
2848− }
2849− let chars: Vec<char> = input.chars().collect();
2850− let mut i = 0;
2851− while i < chars.len() {
2852− if chars[i] == '$'
2853− && i + 1 < chars.len()
2854− && (chars[i + 1].is_alphanumeric() || chars[i + 1] == '_' || chars[i + 1] == '-')
2855− {
2856− let start = i + 1;
2857− let mut end = start;
2858− while end < chars.len()
2859− && (chars[end].is_alphanumeric() || chars[end] == '-' || chars[end] == '_')
2860− {
2861− end += 1;
2862− }
2863− let name: String = chars[start..end].iter().collect();
2864− used.insert(name);
2865− i = end;
2866− } else {
2867− i += 1;
2868− }
6794+ if input.contains('$') {
6795+ used.extend(interp::names(input).into_iter().map(String::from));
28696796 }
28706797}
28716798
@@ -2873,49 +6800,63 @@ fn track_var_refs(input: &str, used: &mut HashSet<String>) {
28736800// Unused definition warnings
28746801// ---------------------------------------------------------------------------
28756802
2876−fn check_unused(ctx: &mut ParseContext) {
6803+/// Warn about definitions nothing uses, except `exported` ones (the
6804+/// definitions of a library, for the files that include it).
6805+fn check_unused(ctx: &mut ParseContext, exported: &HashSet<String>) {
28776806 // Check unused @let variables
28786807 for (name, &line) in &ctx.let_lines {
2879− if name.starts_with("--") {
2880− continue; // CSS vars are always used
6808+ if exported.contains(name) {
6809+ // A library's names are for other files (a custom property
6810+ // isn't a variable, so it is never listed here)
6811+ continue;
28816812 }
28826813 if !ctx.used_variables.contains(name) {
2883− ctx.diagnostics.push(Diagnostic {
2884− line,
2885− column: None,
2886− message: format!("unused variable '${}' (defined but never referenced)", name),
2887− severity: Severity::Warning,
2888− source_line: None,
2889− });
6814+ ctx.diagnostics.push(
6815+ Diagnostic::new(
6816+ code::UNUSED_VARIABLE,
6817+ Severity::Warning,
6818+ line,
6819+ format!("unused variable '${}' (defined but never referenced)", name),
6820+ )
6821+ .subject(name.as_str()),
6822+ );
28906823 }
28916824 }
28926825
2893− // Check unused attribute bundles (@let name [...])
6826+ // Check unused attribute bundles (@let name [...]). A `$name` in code
6827+ // that doesn't run (an `if()` branch or `@if` not taken) counts too.
28946828 for (name, &line) in &ctx.define_lines {
2895− if !ctx.used_defines.contains(name) {
2896− ctx.diagnostics.push(Diagnostic {
2897− line,
2898− column: None,
2899− message: format!(
2900− "unused attribute bundle '${}' (defined but never referenced)",
2901− name
2902− ),
2903− severity: Severity::Warning,
2904− source_line: None,
2905− });
6829+ if !ctx.used_defines.contains(name)
6830+ && !ctx.used_variables.contains(name)
6831+ && !exported.contains(name)
6832+ {
6833+ ctx.diagnostics.push(
6834+ Diagnostic::new(
6835+ code::UNUSED_BUNDLE,
6836+ Severity::Warning,
6837+ line,
6838+ format!(
6839+ "unused attribute bundle '${}' (defined but never referenced)",
6840+ name
6841+ ),
6842+ )
6843+ .subject(name.as_str()),
6844+ );
29066845 }
29076846 }
29086847
29096848 // Check unused functions (@let name ... with body)
29106849 for (name, &line) in &ctx.fn_lines {
2911− if !ctx.used_functions.contains(name) {
2912− ctx.diagnostics.push(Diagnostic {
2913− line,
2914− column: None,
2915− message: format!("unused function '@{}' (defined but never called)", name),
2916− severity: Severity::Warning,
2917− source_line: None,
2918− });
6850+ if !ctx.used_functions.contains(name) && !exported.contains(name) {
6851+ ctx.diagnostics.push(
6852+ Diagnostic::new(
6853+ code::UNUSED_FUNCTION,
6854+ Severity::Warning,
6855+ line,
6856+ format!("unused function '@{}' (defined but never called)", name),
6857+ )
6858+ .subject(name.as_str()),
6859+ );
29196860 }
29206861 }
29216862}
@@ -3001,34 +6942,6 @@ fn parse_json_with_error(input: &str) -> Result<JsonValue, String> {
30016942 }
30026943}
30036944
3004−/// Visit the lines of a block in source order, children after their line.
3005−fn for_each_line<'a>(block: &'a [Syntax], f: &mut impl FnMut(&'a Syntax)) {
3006− for node in block {
3007− f(node);
3008− if let Syntax::Line { children, .. } = node {
3009− for_each_line(children, f);
3010− }
3011− }
3012−}
3013−
3014−/// The text of a block whose lines are content, not htmlang (`@head`,
3015−/// `@style`, `@markdown`): each line trimmed, verbatim text as is.
3016−fn block_text(block: &[Syntax]) -> String {
3017− let mut text = String::new();
3018− for_each_line(block, &mut |node| match node {
3019− Syntax::Line { text: line, .. } => {
3020− text.push_str(line.trim());
3021− text.push('\n');
3022− }
3023− Syntax::Raw { text: raw, .. } => {
3024− text.push_str(raw);
3025− text.push('\n');
3026− }
3027− _ => {}
3028− });
3029− text
3030−}
3031−
30326945fn parse_json_value(chars: &[char], mut pos: usize) -> Option<(JsonValue, usize)> {
30336946 pos = skip_ws(chars, pos);
30346947 if pos >= chars.len() {
@@ -3209,75 +7122,21 @@ fn skip_ws(chars: &[char], mut pos: usize) -> usize {
32097122 pos
32107123}
32117124
3212−/// Flatten a JSON value into variable assignments.
3213−/// - Top-level object: each key becomes `prefix.key`
3214−/// - Top-level array: `prefix` becomes comma-separated, `prefix._count` set
3215−/// - Array of objects: each item becomes space-separated values for @each destructuring
3216−fn flatten_json(prefix: &str, value: &JsonValue, vars: &mut HashMap<String, String>) {
3217− match value {
3218− JsonValue::Str(s) => {
3219− vars.insert(prefix.to_string(), s.clone());
3220− }
3221− JsonValue::Number(n) => {
3222− vars.insert(prefix.to_string(), n.clone());
3223− }
3224− JsonValue::Bool(b) => {
3225− vars.insert(prefix.to_string(), b.to_string());
3226− }
3227− JsonValue::Null => {
3228− vars.insert(prefix.to_string(), String::new());
3229− }
3230− JsonValue::Object(pairs) => {
3231− for (key, val) in pairs {
3232− flatten_json(&format!("{}.{}", prefix, key), val, vars);
3233− }
3234− }
3235− JsonValue::Array(items) => {
3236− // A list: its length under `NAME#` (see `lookup`), its text
3237− // items joined as its value, and each item as `NAME.INDEX`
3238− vars.insert(format!("{}#", prefix), items.len().to_string());
3239− let text: Vec<String> = items
3240− .iter()
3241− .map(json_value_to_string)
3242− .filter(|s| !s.is_empty())
3243− .collect();
3244− vars.insert(prefix.to_string(), text.join(", "));
3245− // Also set indexed access: prefix.0, prefix.1, etc.
3246− for (i, item) in items.iter().enumerate() {
3247− flatten_json(&format!("{}.{}", prefix, i), item, vars);
3248− }
3249− }
3250− }
3251−}
3252−
3253−/// Resolve `$name` for an expression: a list if `name` was loaded from a
3254−/// JSON array, else its text.
3255−fn lookup(vars: &HashMap<String, String>, name: &str) -> Option<crate::expr::Value> {
3256− use crate::expr::Value;
3257− match vars
3258− .get(&format!("{}#", name))
3259− .and_then(|n| n.parse::<usize>().ok())
3260− {
3261− Some(len) => Some(Value::List(
3262− (0..len)
3263− .map(|i| {
3264− vars.get(&format!("{}.{}", name, i))
3265− .cloned()
3266− .unwrap_or_default()
3267− })
7125+/// A JSON value as an htmlang value: an object is a record, an array a
7126+/// list, a string text (never quoted text), `null` empty. A number keeps
7127+/// the text it is written with (`1.50`), and reads as a number.
7128+fn json_value(json: JsonValue) -> Value {
7129+ match json {
7130+ JsonValue::Null => Value::empty(),
7131+ JsonValue::Bool(b) => Value::Bool(b),
7132+ JsonValue::Number(n) | JsonValue::Str(n) => Value::Str(n),
7133+ JsonValue::Array(items) => Value::list(items.into_iter().map(json_value).collect()),
7134+ JsonValue::Object(pairs) => Value::Record(Rc::new(
7135+ pairs
7136+ .into_iter()
7137+ .map(|(key, value)| (key, json_value(value)))
32687138 .collect(),
32697139 )),
3270− None => vars.get(name).cloned().map(Value::Str),
3271− }
3272−}
3273−
3274−fn json_value_to_string(v: &JsonValue) -> String {
3275− match v {
3276− JsonValue::Str(s) => s.clone(),
3277− JsonValue::Number(n) => n.clone(),
3278− JsonValue::Bool(b) => b.to_string(),
3279− JsonValue::Null => String::new(),
3280− JsonValue::Array(_) | JsonValue::Object(_) => String::new(),
32817140 }
32827141}
32837142
@@ -3285,6 +7144,29 @@ fn json_value_to_string(v: &JsonValue) -> String {
32857144// SVG attribute injection helper
32867145// ---------------------------------------------------------------------------
32877146
7147+/// Where the root `<svg ...>` tag's `attr_name="..."` value is, as a byte
7148+/// range of `svg`. Only the opening tag is read, so a child's attribute is
7149+/// never found, and the name must follow whitespace, so `width` doesn't
7150+/// match `stroke-width`.
7151+fn svg_attr_value(svg: &str, attr_name: &str) -> Option<std::ops::Range<usize>> {
7152+ let tag_start = svg.find("<svg")?;
7153+ let tag_end = svg[tag_start..]
7154+ .find('>')
7155+ .map(|p| tag_start + p)
7156+ .unwrap_or(svg.len());
7157+ let tag = &svg[tag_start..tag_end];
7158+ let pattern = format!("{}=\"", attr_name);
7159+ let (pos, _) = tag.match_indices(&pattern).find(|(pos, _)| {
7160+ tag[..*pos]
7161+ .chars()
7162+ .next_back()
7163+ .is_some_and(char::is_whitespace)
7164+ })?;
7165+ let value_start = tag_start + pos + pattern.len();
7166+ let end = svg[value_start..tag_end].find('"')?;
7167+ Some(value_start..value_start + end)
7168+}
7169+
32887170fn set_svg_attr(svg: &str, attr_name: &str, value: &str) -> String {
32897171 // Only the opening <svg ...> tag is touched, so child attributes such as
32907172 // `stroke-width` are left alone.
@@ -3295,26 +7177,14 @@ fn set_svg_attr(svg: &str, attr_name: &str, value: &str) -> String {
32957177 .find('>')
32967178 .map(|p| tag_start + p)
32977179 .unwrap_or(svg.len());
3298− let tag = &svg[tag_start..tag_end];
32997180
3300− // Replace an existing attribute (must be preceded by whitespace so that
3301− // `width` doesn't match `stroke-width`).
3302− let pattern = format!("{}=\"", attr_name);
3303− let existing = tag.match_indices(&pattern).find(|(pos, _)| {
3304− tag[..*pos]
3305− .chars()
3306− .next_back()
3307− .is_some_and(char::is_whitespace)
3308− });
3309− if let Some((pos, _)) = existing {
3310− let value_start = tag_start + pos + pattern.len();
3311− if let Some(end) = svg[value_start..tag_end].find('"') {
3312− let mut result = String::with_capacity(svg.len());
3313− result.push_str(&svg[..value_start]);
3314− result.push_str(value);
3315− result.push_str(&svg[value_start + end..]);
3316− return result;
3317− }
7181+ // Replace an existing attribute
7182+ if let Some(existing) = svg_attr_value(svg, attr_name) {
7183+ let mut result = String::with_capacity(svg.len());
7184+ result.push_str(&svg[..existing.start]);
7185+ result.push_str(value);
7186+ result.push_str(&svg[existing.end..]);
7187+ return result;
33187188 }
33197189
33207190 // Otherwise inject it into the opening tag (before a self-closing `/`).
@@ -3637,7 +7507,10 @@ mod tests {
36377507 #[test]
36387508 fn parses_page_directive() {
36397509 let r = parse_ok("@page My Title\n");
3640− assert_eq!(r.document.page_title.as_deref(), Some("My Title"));
7510+ assert_eq!(
7511+ r.document.page.map(|p| p.title).as_deref(),
7512+ Some("My Title")
7513+ );
36417514 }
36427515
36437516 #[test]