@@ -1,193 +1,89 @@
11use std::collections::{HashMap, HashSet};
2+use std::fmt;
23use std::path::{Path, PathBuf};
3−use std::rc::Rc;
44
55use crate::ast::*;
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};
116
127// ---------------------------------------------------------------------------
138// Public types
149// ---------------------------------------------------------------------------
1510
11+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12+pub enum Severity {
13+ Error,
14+ Warning,
15+ Info,
16+ Help,
17+}
18+
19+#[derive(Debug, Clone)]
20+pub struct Diagnostic {
21+ pub line: usize,
22+ pub column: Option<usize>,
23+ pub message: String,
24+ pub severity: Severity,
25+ pub source_line: Option<String>,
26+}
27+
1628pub struct ParseResult {
1729 pub document: Document,
1830 pub diagnostics: Vec<Diagnostic>,
1931 pub included_files: Vec<PathBuf>,
2032}
2133
22−/// An error that stops one line from being evaluated.
23−type ParseError = Diagnostic;
24−
25−// ---------------------------------------------------------------------------
26−// Internal types
27−// ---------------------------------------------------------------------------
28−
29−#[derive(Clone)]
30−struct FnDef {
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.
34+#[derive(Debug)]
35+struct ParseError {
3636 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`: its class (`hl-fn-NAME-HASH`), and the
48− /// stylesheet nested under it, written into the page once the function
49− /// is called (see `Document::scoped_css`).
50− scoped: Option<(String, String)>,
51− /// What was visible where it was defined: its body and its defaults
52− /// see this, plus its parameters.
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,
37+ message: String,
5938}
6039
61−impl FnDef {
62− fn is_param(&self, name: &str) -> bool {
63− self.params.iter().any(|p| p.name == name)
40+impl fmt::Display for ParseError {
41+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
42+ write!(f, "line {}: {}", self.line, self.message)
6443 }
6544}
6645
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−}
46+// ---------------------------------------------------------------------------
47+// Internal types
48+// ---------------------------------------------------------------------------
7549
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>>>,
50+#[derive(Clone)]
51+enum LineContent {
52+ Normal(String),
53+ Raw(String),
8554}
8655
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− }
56+#[derive(Clone)]
57+struct Line {
58+ indent: usize,
59+ content: LineContent,
60+ line_num: usize,
16161}
16262
163−impl interp::Scope for Env {
164− fn get(&self, name: &str) -> Option<Value> {
165− self.value(name).cloned()
166− }
63+#[derive(Clone)]
64+struct FnDef {
65+ params: Vec<String>,
66+ defaults: HashMap<String, String>,
67+ body_lines: Vec<Line>,
16768}
16869
16970struct ParseContext {
17071 /// Source line currently being parsed, for diagnostics raised deep
17172 /// inside helpers that don't take a line number.
17273 current_line: usize,
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>,
74+ /// Functions whose body has a scoped @style block.
75+ scoped_functions: std::collections::HashSet<String>,
76+ page_title: Option<String>,
77+ lang: Option<String>,
78+ favicon: Option<String>,
17779 meta_tags: Vec<(String, String)>,
17880 head_blocks: Vec<String>,
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>>,
81+ variables: HashMap<String, String>,
82+ defines: HashMap<String, Vec<Attribute>>,
83+ functions: HashMap<String, FnDef>,
84+ keyframes: Vec<(String, String)>,
18785 css_vars: Vec<(String, String)>,
18886 custom_css: Vec<String>,
189− /// The scoped `@style` of each function called so far
190− scoped_css: Vec<String>,
19187 og_tags: Vec<(String, String)>,
19288 diagnostics: Vec<Diagnostic>,
19389 base_path: Option<PathBuf>,
@@ -207,550 +103,44 @@ struct ParseContext {
207103 fn_lines: HashMap<String, usize>,
208104 /// Line numbers of attribute bundle definitions (name -> line)
209105 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
106+ /// Canonical URL
107+ canonical: Option<String>,
108+ /// Base URL for relative links
109+ base_url: Option<String>,
110+ /// Track @import paths for circular dependency detection
111+ import_stack: Vec<PathBuf>,
295112}
296113
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− })
114+struct Parser {
115+ lines: Vec<Line>,
116+ pos: usize,
320117}
321118
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−
326−/// Evaluates a syntax tree (see `syntax.rs`) into the document's nodes.
327−struct Evaluator;
328−
329119impl ParseContext {
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> {
120+ /// Evaluate an expression (see `expr.rs`), reporting errors at `line`.
121+ fn eval(&mut self, src: &str, line: usize) -> Option<crate::expr::Value> {
343122 track_var_refs(src, &mut self.used_variables);
344− match crate::expr::eval(src, &self.env) {
123+ let vars = &self.variables;
124+ let resolve = |name: &str| vars.get(name).cloned();
125+ let result = crate::expr::eval(src, &resolve);
126+ match result {
345127 Ok(value) => Some(value),
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− }
128+ Err(message) => {
129+ self.diagnostics.push(Diagnostic {
130+ line,
131+ column: None,
132+ message: format!("invalid expression: {}", message),
133+ severity: Severity::Error,
134+ source_line: Some(src.to_string()),
135+ });
354136 None
355137 }
356138 }
357139 }
358140
359141 /// Evaluate a condition; an invalid one is reported and counts as false.
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− }
142+ fn condition(&mut self, src: &str, line: usize) -> bool {
143+ self.eval(src, line).is_some_and(|value| value.truthy())
754144 }
755145}
756146
@@ -759,19 +149,15 @@ impl ParseContext {
759149const PRELUDE: &str = include_str!("std.hl");
760150
761151fn load_prelude(ctx: &mut ParseContext) {
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;
152+ let mut prelude = Parser {
153+ lines: preprocess(PRELUDE),
154+ pos: 0,
155+ };
156+ let _ = prelude.parse_children(0, ctx);
770157 // Library definitions aren't the file's own: never report them unused.
771158 ctx.fn_lines.clear();
772159 ctx.define_lines.clear();
773160 ctx.let_lines.clear();
774− ctx.env.push();
775161}
776162
777163pub fn parse(input: &str) -> ParseResult {
@@ -779,18 +165,22 @@ pub fn parse(input: &str) -> ParseResult {
779165}
780166
781167pub fn parse_with_base(input: &str, base_path: Option<&Path>) -> ParseResult {
168+ let lines = preprocess(input);
169+ let mut parser = Parser { lines, pos: 0 };
782170 let mut ctx = ParseContext {
783171 current_line: 0,
784− page: None,
785− page_at: None,
172+ scoped_functions: std::collections::HashSet::new(),
173+ page_title: None,
174+ lang: None,
175+ favicon: None,
786176 meta_tags: Vec::new(),
787177 head_blocks: Vec::new(),
788− head_at: None,
789− env: Env::default(),
790− defined_functions: HashMap::new(),
178+ variables: HashMap::new(),
179+ defines: HashMap::new(),
180+ functions: HashMap::new(),
181+ keyframes: Vec::new(),
791182 css_vars: Vec::new(),
792183 custom_css: Vec::new(),
793− scoped_css: Vec::new(),
794184 og_tags: Vec::new(),
795185 diagnostics: Vec::new(),
796186 base_path: base_path.map(|p| p.to_path_buf()),
@@ -804,85 +194,30 @@ pub fn parse_with_base(input: &str, base_path: Option<&Path>) -> ParseResult {
804194 let_lines: HashMap::new(),
805195 fn_lines: HashMap::new(),
806196 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,
197+ canonical: None,
198+ base_url: None,
199+ import_stack: Vec::new(),
819200 };
820201 load_prelude(&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− }
202+ let nodes = parser.parse_children(0, &mut ctx);
203+ validate_tree(&nodes, None, &mut ctx.diagnostics);
204+ check_unused(&mut ctx);
875205 ParseResult {
876206 document: Document {
877− page: ctx.page,
207+ page_title: ctx.page_title,
208+ lang: ctx.lang,
209+ favicon: ctx.favicon,
878210 meta_tags: ctx.meta_tags,
879211 head_blocks: ctx.head_blocks,
880− variables,
881− defines,
212+ variables: ctx.variables,
213+ defines: ctx.defines,
214+ keyframes: ctx.keyframes,
882215 css_vars: ctx.css_vars,
883216 custom_css: ctx.custom_css,
884− scoped_css: ctx.scoped_css,
885217 og_tags: ctx.og_tags,
218+ canonical: ctx.canonical,
219+ base_url: ctx.base_url,
220+ preload_hints: collect_image_preload_hints(&nodes),
886221 nodes,
887222 },
888223 diagnostics: ctx.diagnostics,
@@ -890,878 +225,1311 @@ pub fn parse_with_base(input: &str, base_path: Option<&Path>) -> ParseResult {
890225 }
891226}
892227
893−// ---------------------------------------------------------------------------
894−// Code that never runs: an untaken branch, an uncalled function, a loop over
895−// an empty list
896−// ---------------------------------------------------------------------------
228+/// Scan nodes for @image elements and generate preload hints for early images.
229+fn collect_image_preload_hints(nodes: &[Node]) -> Vec<crate::ast::PreloadHint> {
230+ let mut hints = Vec::new();
231+ // Only preload the first few images (above-the-fold heuristic)
232+ collect_images_recursive(nodes, &mut hints, 3);
233+ hints
234+}
897235
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();
236+fn collect_images_recursive(nodes: &[Node], hints: &mut Vec<crate::ast::PreloadHint>, max: usize) {
907237 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());
911− }
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;
238+ if hints.len() >= max {
239+ return;
922240 }
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;
241+ if let Node::Element(elem) = node {
242+ if elem.kind == ElementKind::Image
243+ && let Some(ref src) = elem.argument
244+ && !src.is_empty()
245+ && !src.starts_with("data:")
246+ && !src.starts_with('#')
247+ {
248+ hints.push(crate::ast::PreloadHint {
249+ href: src.clone(),
250+ as_type: "image".to_string(),
251+ crossorigin: false,
252+ });
253+ }
254+ collect_images_recursive(&elem.children, hints, max);
929255 }
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);
936256 }
937257}
938258
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− }
259+// ---------------------------------------------------------------------------
260+// Preprocessing: strip comments/blanks, collapse @raw blocks
261+// ---------------------------------------------------------------------------
262+
263+fn preprocess(input: &str) -> Vec<Line> {
264+ let raw_lines: Vec<&str> = input.lines().collect();
265+ let mut lines = Vec::new();
266+ let mut i = 0;
267+
268+ while i < raw_lines.len() {
269+ let line = raw_lines[i];
270+ let trimmed = line.trim();
271+
272+ if trimmed.is_empty() || trimmed.starts_with("--") {
273+ i += 1;
274+ continue;
955275 }
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);
959− }
960− ctx.trees = trees;
961−}
962276
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);
277+ let indent = line.len() - line.trim_start().len();
278+
279+ // Inline `@markdown` and `@script` blocks keep their bodies verbatim:
280+ // in Markdown, blank lines separate paragraphs, `---` is a rule (not
281+ // a comment) and code indentation matters; in JavaScript, newlines,
282+ // `{...}` and `$` must reach the output untouched.
283+ let verbatim_body = trimmed == "@markdown"
284+ || trimmed == "@script"
285+ || trimmed.starts_with("@script ")
286+ || trimmed.starts_with("@script[");
287+ if verbatim_body {
288+ lines.push(Line {
289+ indent,
290+ content: LineContent::Normal(trimmed.to_string()),
291+ line_num: i + 1,
292+ });
293+ let body_start = i + 1;
294+ let mut body_end = body_start;
295+ let mut j = body_start;
296+ while j < raw_lines.len() {
297+ let l = raw_lines[j];
298+ if l.trim().is_empty() {
299+ j += 1;
300+ continue;
973301 }
974− check_unevaluated_content(node, element, ctx);
975− if let Some(text) = &element.text {
976− check_inline_heads(text, line, ctx);
302+ if l.len() - l.trim_start().len() <= indent {
303+ break;
977304 }
305+ j += 1;
306+ body_end = j;
978307 }
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− },
987− ..
988− }) => {
989− let words: Vec<String> = crate::vocab::PAGE_WORDS
308+ let body = &raw_lines[body_start..body_end];
309+ let body_indent = body
310+ .iter()
311+ .filter(|l| !l.trim().is_empty())
312+ .map(|l| l.len() - l.trim_start().len())
313+ .min()
314+ .unwrap_or(0);
315+ if !body.is_empty() {
316+ let text: Vec<&str> = body
990317 .iter()
991− .map(|w| w.to_string())
318+ .map(|l| l.get(body_indent..).unwrap_or("").trim_end())
992319 .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);
320+ lines.push(Line {
321+ indent: indent + 1,
322+ content: LineContent::Raw(text.join("\n")),
323+ line_num: body_start + 1,
324+ });
325+ }
326+ i = body_end.max(body_start);
327+ continue;
328+ }
329+
330+ // Handle @raw """..."""
331+ if let Some(raw_rest) = trimmed.strip_prefix("@raw") {
332+ let after_raw = raw_rest.trim_start();
333+ if let Some(after_open) = after_raw.strip_prefix("\"\"\"") {
334+ // Single-line: @raw """content"""
335+ if after_open.ends_with("\"\"\"") && after_open.len() >= 3 {
336+ let content = &after_open[..after_open.len() - 3];
337+ lines.push(Line {
338+ indent,
339+ content: LineContent::Raw(content.to_string()),
340+ line_num: i + 1,
341+ });
342+ i += 1;
343+ continue;
344+ }
345+
346+ // Multiline: collect until closing """
347+ let mut raw_content = String::new();
348+ if !after_open.is_empty() {
349+ raw_content.push_str(after_open);
350+ raw_content.push('\n');
351+ }
352+ i += 1;
353+ while i < raw_lines.len() {
354+ if raw_lines[i].trim() == "\"\"\"" {
355+ i += 1;
356+ break;
357+ }
358+ raw_content.push_str(raw_lines[i]);
359+ raw_content.push('\n');
360+ i += 1;
361+ }
362+
363+ lines.push(Line {
364+ indent,
365+ content: LineContent::Raw(raw_content.trim_end_matches('\n').to_string()),
366+ line_num: i,
367+ });
368+ continue;
997369 }
998− _ => {}
999370 }
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());
371+
372+ // Join continuation lines for multi-line attribute brackets
373+ let first_line_num = i + 1;
374+ let mut full = trimmed.to_string();
375+ while open_attr_depth(&full) > 0 && i + 1 < raw_lines.len() {
376+ i += 1;
377+ let next = raw_lines[i].trim();
378+ if next.is_empty() || next.starts_with("--") {
379+ continue;
380+ }
381+ full.push(' ');
382+ full.push_str(next);
1003383 }
384+
385+ lines.push(Line {
386+ indent,
387+ content: LineContent::Normal(full),
388+ line_num: first_line_num,
389+ });
390+ i += 1;
1004391 }
1005− for child in &node.children {
1006− check_unevaluated_node(child, ctx);
1007− }
1008−}
1009392
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−}
1050−
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));
393+ lines
394+}
395+
396+/// Bracket depth left open at the end of `line`, counting only attribute
397+/// lists: a `[` that starts the line or follows an `@name` token (optionally
398+/// with one more word, as in `@let name [`). Brackets in text content, such
399+/// as `@text [bold] Use [ to open`, are ignored.
400+fn open_attr_depth(line: &str) -> i32 {
401+ if !line.starts_with('@') && !line.starts_with('[') {
402+ return 0;
403+ }
404+ let bytes = line.as_bytes();
405+ let mut depth: i32 = 0;
406+ for (i, &b) in bytes.iter().enumerate() {
407+ match b {
408+ b'[' if depth > 0 => depth += 1,
409+ b'[' => {
410+ // Is this the start of an attribute list?
411+ let before = line[..i].trim_end();
412+ let last_directive = before
413+ .rsplit([']', '>'])
414+ .next()
415+ .unwrap_or("")
416+ .trim();
417+ let tokens: Vec<&str> = last_directive.split_whitespace().collect();
418+ let starts_list = match tokens.as_slice() {
419+ [] => before.is_empty() || before.ends_with('>'),
420+ [name] => name.starts_with('@'),
421+ [name, _] => name.starts_with('@'),
422+ _ => false,
423+ };
424+ if starts_list {
425+ depth = 1;
426+ } else if before.ends_with(']') {
427+ // Text after a closed attribute list: stop scanning.
428+ return 0;
1088429 }
1089430 }
431+ b']' if depth > 0 => depth -= 1,
432+ _ => {}
1090433 }
1091434 }
435+ depth
1092436}
1093437
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);
1106− }
1107− }
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− }
1125− }
1126− }
1127−}
438+// ---------------------------------------------------------------------------
439+// Parser
440+// ---------------------------------------------------------------------------
1128441
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);
442+impl Parser {
443+ fn parse_children(&mut self, min_indent: usize, ctx: &mut ParseContext) -> Vec<Node> {
444+ let mut nodes = Vec::new();
445+
446+ while self.pos < self.lines.len() {
447+ let indent = self.lines[self.pos].indent;
448+ if indent < min_indent {
449+ break;
1162450 }
1163− a
1164− })
1165− .chain(groups)
1166− .collect()
1167−}
1168451
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));
452+ match self.parse_line(ctx) {
453+ Ok(Some(new_nodes)) => nodes.extend(new_nodes),
454+ Ok(None) => {}
455+ Err(e) => {
456+ // Error recovery: record the diagnostic and continue parsing
457+ // to report multiple errors in a single pass
458+ let source = if self.pos > 0 && self.pos <= self.lines.len() {
459+ match &self.lines[self.pos.saturating_sub(1)].content {
460+ LineContent::Normal(s) => Some(s.clone()),
461+ LineContent::Raw(s) => Some(s.clone()),
462+ }
463+ } else {
464+ None
465+ };
466+ ctx.diagnostics.push(Diagnostic {
467+ line: e.line,
468+ column: None,
469+ message: e.message,
470+ severity: Severity::Error,
471+ source_line: source,
472+ });
473+ // Skip forward past any deeper-indented children of the errored line
474+ while self.pos < self.lines.len() && self.lines[self.pos].indent > indent {
475+ self.pos += 1;
476+ }
477+ }
478+ }
1191479 }
1192− }
1193−}
1194480
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;
1209− }
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());
481+ nodes
1222482 }
1223− reported
1224−}
1225483
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);
1232− }
484+ fn parse_line(&mut self, ctx: &mut ParseContext) -> Result<Option<Vec<Node>>, ParseError> {
485+ let line_num = self.lines[self.pos].line_num;
486+ ctx.current_line = line_num;
487+ if let LineContent::Normal(text) = &self.lines[self.pos].content
488+ && let Some(filter) = old_filter_syntax(text)
489+ {
490+ ctx.diagnostics.push(Diagnostic {
491+ line: line_num,
492+ column: None,
493+ message: format!(
494+ "`${}|{}` filters are functions now: write `${{{}(${})}}` (run `htmlang upgrade`)",
495+ filter.0, filter.1, filter.1, filter.0
496+ ),
497+ severity: Severity::Warning,
498+ source_line: Some(text.clone()),
499+ });
1233500 }
1234− }
1235−}
1236−
1237−// ---------------------------------------------------------------------------
1238−// Evaluation
1239−// ---------------------------------------------------------------------------
501+ let current_indent = self.lines[self.pos].indent;
1240502
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;
503+ // Handle raw content
504+ if let LineContent::Raw(s) = &self.lines[self.pos].content {
505+ let content = s.clone();
506+ self.pos += 1;
507+ return Ok(Some(vec![Node::Raw(content)]));
1252508 }
1253− let condition = match node.directive().map(|d| &d.args) {
1254− Some(DirectiveArgs::Else { condition }) => condition.is_some(),
1255− _ => break,
509+
510+ // Normal content — clone to release borrow. Raw is already handled
511+ // above; a let-else pattern avoids a panic path if new LineContent
512+ // variants are added in the future.
513+ let LineContent::Normal(content) = &self.lines[self.pos].content else {
514+ return Err(ParseError {
515+ line: line_num,
516+ message: "internal: unexpected line content variant".to_string(),
517+ });
1256518 };
1257− if condition && !is_if {
1258− break;
1259− }
1260− branches.push(node);
1261− next = i;
1262− if !condition {
1263− break;
519+ let content = content.clone();
520+ self.pos += 1;
521+
522+ // --- Directives ---
523+
524+ // Removed syntax gets a pointer to its replacement — unless the
525+ // name is a user function (e.g. `@let divider`).
526+ if content.starts_with('@')
527+ && !ctx.functions.contains_key(extract_element_name(&content))
528+ && let Some(hint) = removed_syntax_hint(&content)
529+ {
530+ return Err(ParseError {
531+ line: line_num,
532+ message: hint,
533+ });
1264534 }
1265− }
1266− (branches, next)
1267−}
1268535
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;
1278− }
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)
536+ // @page [lang en, favicon /f.png, canonical URL, base URL] Title
537+ if let Some(rest) = content.strip_prefix("@page ") {
538+ let rest = rest.trim_start();
539+ let title = if rest.starts_with('[') {
540+ let (attrs, title) = parse_attr_brackets_no_validate(rest, line_num, ctx)?;
541+ for attr in attrs {
542+ let value = attr.value.unwrap_or_default();
543+ match attr.key.as_str() {
544+ "lang" => ctx.lang = Some(value),
545+ "favicon" => ctx.favicon = Some(value),
546+ "canonical" => ctx.canonical = Some(value),
547+ "base" => ctx.base_url = Some(value),
548+ other => ctx.diagnostics.push(Diagnostic {
549+ line: line_num,
550+ column: None,
551+ message: format!(
552+ "unknown @page attribute '{}' (expected lang, favicon, canonical or base)",
553+ other
554+ ),
555+ severity: Severity::Warning,
556+ source_line: Some(content.clone()),
557+ }),
1287558 }
1288559 }
1289− // Reported as a syntax error
1290− Some("else") => {
1291− ctx.visited.insert(node.id);
1292− Ok(None)
1293− }
1294− _ => self.eval(node, ctx),
560+ title
561+ } else {
562+ rest.to_string()
1295563 };
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− }
1305− }
564+ ctx.page_title = Some(substitute_vars(title.trim(), &ctx.variables));
565+ return Ok(None);
1306566 }
1307− nodes
1308− }
1309567
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− }
1318568
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− )
569+ if let Some(rest) = content.strip_prefix("@let ") {
570+ let rest = rest.trim();
571+
572+ // A `"""` value opens a multi-line string, whose indented lines
573+ // are its content — not a function body.
574+ let opens_triple_quote = rest.split_once(' ').is_some_and(|(_, v)| {
575+ let v = v.trim();
576+ v.strip_prefix("= ").unwrap_or(v).trim_start().starts_with("\"\"\"")
577+ });
578+ // Check if next lines are indented (function/component definition)
579+ let has_body = !opens_triple_quote
580+ && self.pos < self.lines.len()
581+ && self.lines[self.pos].indent > current_indent;
582+
583+ if has_body {
584+ // Function definition: @let name $param1 $param2=default
585+ let parts: Vec<&str> = rest.split_whitespace().collect();
586+ if parts.is_empty() {
587+ return Err(ParseError {
588+ line: line_num,
589+ message: "@let with body requires a name".to_string(),
590+ });
591+ }
592+ let name = parts[0].to_string();
593+ let mut params = Vec::new();
594+ let mut defaults = HashMap::new();
595+ for part in &parts[1..] {
596+ let part = part.strip_prefix('$').unwrap_or(part);
597+ if let Some((param_name, default_val)) = part.split_once('=') {
598+ params.push(param_name.to_string());
599+ defaults.insert(param_name.to_string(), default_val.to_string());
600+ } else {
601+ params.push(part.to_string());
602+ }
1343603 }
1344− Some(DirectiveArgs::Else { condition: None }) => true,
1345− // A syntax error, already reported
1346− _ => false,
1347− };
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− }
1354604
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);
605+ // Collect body lines (all lines indented deeper than @let)
606+ let mut body_lines = Vec::new();
607+ while self.pos < self.lines.len() && self.lines[self.pos].indent > current_indent {
608+ body_lines.push(self.lines[self.pos].clone());
609+ self.pos += 1;
1381610 }
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− }
1394611
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),
1412− };
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
1427− ),
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);
612+ // An @style block at the top of the body is scoped to the
613+ // function: its rules apply inside a `.hl-NAME` wrapper.
614+ let (body_lines, style_lines) = split_style_block(body_lines);
615+ if !style_lines.is_empty() {
616+ let scope_class = format!("hl-{}", name);
617+ let scoped_css: String = style_lines
618+ .iter()
619+ .filter_map(|line| match &line.content {
620+ LineContent::Normal(s) if !s.trim().is_empty() => {
621+ Some(format!(".{} {}\n", scope_class, s.trim()))
622+ }
623+ _ => None,
624+ })
625+ .collect();
626+ if !scoped_css.is_empty() {
627+ ctx.custom_css.push(scoped_css);
628+ }
629+ ctx.scoped_functions.insert(name.clone());
1435630 }
1436− Ok(None)
631+
632+ ctx.fn_lines.entry(name.clone()).or_insert(line_num);
633+ ctx.functions.insert(
634+ name,
635+ FnDef {
636+ params,
637+ defaults,
638+ body_lines,
639+ },
640+ );
641+ return Ok(None);
1437642 }
1438643
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);
644+ if let Some((name, value)) = rest.split_once(' ') {
645+ let value = value.trim();
646+ // `@let name = EXPR` computes its value (see expr.rs); any
647+ // other value is literal text with `$var` interpolation.
648+ if let Some(expression) = value.strip_prefix('=') {
649+ let value = ctx
650+ .eval(expression.trim(), line_num)
651+ .map(|v| v.to_string())
652+ .unwrap_or_default();
653+ if name.starts_with("--") {
654+ ctx.css_vars.push((name.to_string(), value.clone()));
1477655 }
656+ ctx.variables.insert(name.to_string(), value);
657+ ctx.let_lines.entry(name.to_string()).or_insert(line_num);
658+ return Ok(None);
1478659 }
1479− Ok(None)
1480− }
1481660
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− );
661+ // Attribute bundle: @let name [attr1, attr2, ...]
662+ if value.starts_with('[') {
663+ let (attrs, _) = parse_attr_brackets(value, line_num, ctx)?;
664+ ctx.defines.insert(name.to_string(), attrs);
665+ ctx.define_lines.entry(name.to_string()).or_insert(line_num);
1493666 return Ok(None);
667+ }
668+
669+ // Multi-line @let with triple quotes: @let name """..."""
670+ let value_str;
671+ let value = if let Some(after_open) = value.strip_prefix("\"\"\"") {
672+ if after_open.ends_with("\"\"\"") && after_open.len() >= 3 {
673+ // Single-line triple-quote: @let name """value"""
674+ value_str = after_open[..after_open.len() - 3].to_string();
675+ value_str.as_str()
676+ } else {
677+ // Multi-line: collect indented body lines until closing """
678+ let mut lines_buf = String::new();
679+ if !after_open.is_empty() {
680+ lines_buf.push_str(after_open);
681+ lines_buf.push('\n');
682+ }
683+ while self.pos < self.lines.len() {
684+ match &self.lines[self.pos].content {
685+ LineContent::Normal(s) if s.trim() == "\"\"\"" => {
686+ self.pos += 1;
687+ break;
688+ }
689+ LineContent::Normal(s) => {
690+ lines_buf.push_str(s);
691+ lines_buf.push('\n');
692+ }
693+ LineContent::Raw(s) => {
694+ lines_buf.push_str(s);
695+ lines_buf.push('\n');
696+ }
697+ }
698+ self.pos += 1;
699+ }
700+ value_str = lines_buf.trim_end_matches('\n').to_string();
701+ value_str.as_str()
702+ }
703+ } else if value.starts_with('"') && value.ends_with('"') && value.len() >= 2 {
704+ // Support quoted string interpolation: @let greeting "Hello $name"
705+ &value[1..value.len() - 1]
706+ } else {
707+ value
1494708 };
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);
709+ track_var_refs(value, &mut ctx.used_variables);
710+ let value = substitute_vars(value, &ctx.variables);
711+ if name.starts_with("--") {
712+ // CSS custom property
713+ ctx.css_vars.push((name.to_string(), value.clone()));
1507714 }
1508− ctx.head_at.get_or_insert(line_num);
1509− Ok(None)
715+ ctx.variables.insert(name.to_string(), value);
716+ ctx.let_lines.entry(name.to_string()).or_insert(line_num);
1510717 }
718+ return Ok(None);
719+ }
1511720
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);
721+ // @meta NAME VALUE; `og:` names become Open Graph property tags
722+ if let Some(rest) = content.strip_prefix("@meta ") {
723+ let rest = rest.trim();
724+ if let Some((name, value)) = rest.split_once(' ') {
725+ let value = substitute_vars(value.trim(), &ctx.variables);
726+ match name.trim().strip_prefix("og:") {
727+ Some(property) => ctx.og_tags.push((property.to_string(), value)),
728+ None => ctx.meta_tags.push((name.trim().to_string(), value)),
1517729 }
1518− Ok(None)
1519730 }
731+ return Ok(None);
732+ }
1520733
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− ));
734+
735+ if content == "@head" || content.starts_with("@head ") {
736+ // Collect indented body lines as raw head content
737+ let mut head_content = String::new();
738+ while self.pos < self.lines.len() && self.lines[self.pos].indent > current_indent {
739+ match &self.lines[self.pos].content {
740+ LineContent::Normal(s) => {
741+ head_content.push_str(s.trim());
742+ head_content.push('\n');
743+ }
744+ LineContent::Raw(s) => {
745+ head_content.push_str(s);
746+ head_content.push('\n');
747+ }
1534748 }
1535− if !text.trim().is_empty() {
1536− ctx.custom_css.push(text.trim().to_string());
749+ self.pos += 1;
750+ }
751+ let trimmed = head_content.trim().to_string();
752+ if !trimmed.is_empty() {
753+ ctx.head_blocks.push(trimmed);
754+ }
755+ return Ok(None);
756+ }
757+
758+ // --- @style block (raw CSS) ---
759+ if content.trim() == "@style" {
760+ let mut style_content = String::new();
761+ while self.pos < self.lines.len() && self.lines[self.pos].indent > current_indent {
762+ match &self.lines[self.pos].content {
763+ LineContent::Normal(s) => {
764+ style_content.push_str(s.trim());
765+ style_content.push('\n');
766+ }
767+ LineContent::Raw(s) => {
768+ style_content.push_str(s);
769+ style_content.push('\n');
770+ }
1537771 }
1538− Ok(None)
772+ self.pos += 1;
1539773 }
774+ let trimmed = style_content.trim().to_string();
775+ if !trimmed.is_empty() {
776+ ctx.custom_css.push(trimmed);
777+ }
778+ return Ok(None);
779+ }
1540780
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))]));
781+
782+ // --- @markdown block or file (convert markdown to HTML) ---
783+ if content.trim() == "@markdown" || content.trim().starts_with("@markdown ") {
784+ let arg = content.trim().strip_prefix("@markdown").unwrap().trim();
785+ if arg.is_empty() {
786+ // Inline markdown block: indented children
787+ let mut md_lines = Vec::new();
788+ while self.pos < self.lines.len() && self.lines[self.pos].indent > current_indent {
789+ match &self.lines[self.pos].content {
790+ LineContent::Normal(s) => md_lines.push(s.clone()),
791+ LineContent::Raw(s) => md_lines.extend(s.lines().map(String::from)),
792+ }
793+ self.pos += 1;
794+ }
795+ let html = markdown_to_html(&md_lines);
796+ return Ok(Some(vec![Node::Raw(html)]));
797+ } else {
798+ // External markdown file: @markdown file.md
799+ let filename = substitute_vars(arg, &ctx.variables);
800+ let resolved = match &ctx.base_path {
801+ Some(base) => base.join(&filename),
802+ None => PathBuf::from(&filename),
1549803 };
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,
1554− Err(e) => {
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− );
1563− return Ok(None);
804+ let md_text = if let Some(cached) = ctx.file_cache.get(&resolved) {
805+ cached.clone()
806+ } else {
807+ match std::fs::read_to_string(&resolved) {
808+ Ok(text) => {
809+ ctx.file_cache.insert(resolved.clone(), text.clone());
810+ text
811+ }
812+ Err(e) => {
813+ ctx.diagnostics.push(Diagnostic {
814+ line: line_num,
815+ column: None,
816+ message: format!("cannot read markdown '{}': {}", filename, e),
817+ severity: Severity::Error,
818+ source_line: Some(content.clone()),
819+ });
820+ return Ok(None);
821+ }
1564822 }
1565823 };
1566824 ctx.included_files.push(resolved);
1567825 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))]))
826+ let html = markdown_to_html(&md_lines);
827+ return Ok(Some(vec![Node::Raw(html)]));
1569828 }
829+ }
830+
1570831
1571− ("include", DirectiveArgs::Text(Some(path))) => {
1572− self.eval_include(node.id, path, line_num, content, ctx)
1573− }
1574832
1575− ("data", DirectiveArgs::Data { name, source, .. }) => {
1576− self.eval_data(name, source, line_num, content, ctx);
1577− Ok(None)
833+ // --- @assert directive (compile-time assertions) ---
834+
835+ if let Some(rest) = content.strip_prefix("@assert ") {
836+ let rest = rest.trim();
837+ if !ctx.condition(rest, line_num) {
838+ ctx.diagnostics.push(Diagnostic {
839+ line: line_num,
840+ column: None,
841+ message: format!("assertion failed: {}", rest),
842+ severity: Severity::Error,
843+ source_line: Some(content.clone()),
844+ });
1578845 }
846+ return Ok(None);
847+ }
1579848
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())]))
849+ if let Some(rest) = content.strip_prefix("@include ") {
850+ let rest = rest.trim();
851+ let (filename, alias) = if let Some((file_part, alias_part)) = rest.rsplit_once(" as ")
852+ {
853+ (
854+ file_part.trim().to_string(),
855+ Some(alias_part.trim().to_string()),
856+ )
857+ } else {
858+ (rest.to_string(), None)
859+ };
860+ // Strip quotes from filename
861+ let filename =
862+ if filename.starts_with('"') && filename.ends_with('"') && filename.len() >= 2 {
863+ filename[1..filename.len() - 1].to_string()
864+ } else {
865+ filename
866+ };
867+ let filename = substitute_vars(&filename, &ctx.variables);
868+
869+ // Glob support: if filename contains *, expand to multiple imports
870+ if filename.contains('*') {
871+ let base_dir = match &ctx.base_path {
872+ Some(base) => base.clone(),
873+ None => PathBuf::from("."),
874+ };
875+ let pattern_path = Path::new(&filename);
876+ let (glob_dir, glob_pattern) = match pattern_path.parent() {
877+ Some(dir) if !dir.as_os_str().is_empty() => (
878+ base_dir.join(dir),
879+ pattern_path
880+ .file_name()
881+ .unwrap_or_default()
882+ .to_string_lossy()
883+ .to_string(),
884+ ),
885+ _ => (base_dir.clone(), filename.clone()),
886+ };
887+ let matched_files = match std::fs::read_dir(&glob_dir) {
888+ Ok(entries) => {
889+ let mut files: Vec<PathBuf> = entries
890+ .flatten()
891+ .filter(|e| {
892+ let name = e.file_name().to_string_lossy().to_string();
893+ glob_match(&glob_pattern, &name)
894+ })
895+ .map(|e| e.path())
896+ .collect();
897+ files.sort();
898+ files
899+ }
900+ Err(e) => {
901+ ctx.diagnostics.push(Diagnostic {
902+ line: line_num,
903+ column: None,
904+ message: format!(
905+ "cannot read directory for glob '{}': {}",
906+ filename, e
907+ ),
908+ severity: Severity::Error,
909+ source_line: Some(content.clone()),
910+ });
911+ return Ok(None);
912+ }
913+ };
914+ if matched_files.is_empty() {
915+ ctx.diagnostics.push(Diagnostic {
916+ line: line_num,
917+ column: None,
918+ message: format!("no files matched glob pattern '{}'", filename),
919+ severity: Severity::Warning,
920+ source_line: Some(content.clone()),
921+ });
922+ return Ok(None);
923+ }
924+ let mut matched_nodes = Vec::new();
925+ for file_path in matched_files {
926+ let rel_name = file_path
927+ .strip_prefix(&base_dir)
928+ .unwrap_or(&file_path)
929+ .to_string_lossy()
930+ .to_string();
931+ // Synthesize an @include line for each matched file
932+ let import_line = match &alias {
933+ Some(pfx) => {
934+ let stem = file_path
935+ .file_stem()
936+ .unwrap_or_default()
937+ .to_string_lossy()
938+ .to_string();
939+ format!("@include \"{}\" as {}.{}", rel_name, pfx, stem)
940+ }
941+ None => format!("@include \"{}\"", rel_name),
942+ };
943+ let synth_lines = preprocess(&import_line);
944+ let mut synth_parser = Parser {
945+ lines: synth_lines,
946+ pos: 0,
947+ };
948+ matched_nodes.extend(synth_parser.parse_children(0, ctx));
949+ }
950+ return Ok(Some(matched_nodes));
1585951 }
1586952
1587− // A header with a syntax error (reported), or a directive
1588− // without its argument
1589− _ => Ok(None),
1590− }
1591− }
953+ let resolved = match &ctx.base_path {
954+ Some(base) => base.join(&filename),
955+ None => PathBuf::from(&filename),
956+ };
1592957
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!(
958+ if ctx.include_stack.contains(&resolved) || ctx.import_stack.contains(&resolved) {
959+ let cycle_chain = format_include_chain(&ctx.import_stack);
960+ ctx.diagnostics.push(Diagnostic {
961+ line: line_num,
962+ column: None,
963+ message: format!(
1616964 "circular include '{}' (cycle: {} → {})",
1617965 filename, cycle_chain, filename
1618966 ),
1619− )
1620− .source(content),
1621− );
1622− return Ok(None);
1623− }
1624−
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− );
967+ severity: Severity::Error,
968+ source_line: Some(content.clone()),
969+ });
1636970 return Ok(None);
1637971 }
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);
1675− }
1676972
1677− ctx.base_path = saved_base;
1678− ctx.include_stack.pop();
1679− Ok(Some(included_nodes))
1680− }
973+ let imported_text = if let Some(cached) = ctx.file_cache.get(&resolved) {
974+ cached.clone()
975+ } else {
976+ match std::fs::read_to_string(&resolved) {
977+ Ok(text) => {
978+ ctx.file_cache.insert(resolved.clone(), text.clone());
979+ text
980+ }
981+ Err(e) => {
982+ ctx.diagnostics.push(Diagnostic {
983+ line: line_num,
984+ column: None,
985+ message: format!("cannot include '{}': {}", filename, e),
986+ severity: Severity::Error,
987+ source_line: Some(content.clone()),
988+ });
989+ return Ok(None);
990+ }
991+ }
992+ };
1681993
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),
994+ ctx.included_files.push(resolved.clone());
995+ ctx.include_stack.push(resolved.clone());
996+ ctx.import_stack.push(resolved.clone());
997+ let saved_base = ctx.base_path.clone();
998+ ctx.base_path = resolved.parent().map(|p| p.to_path_buf());
999+
1000+ let diag_count_before = ctx.diagnostics.len();
1001+ let mut included_nodes = Vec::new();
1002+
1003+ if let Some(ref prefix) = alias {
1004+ // Snapshot just the *key sets* before parsing — much cheaper
1005+ // than cloning the full HashMaps, since we only need to know
1006+ // which definitions are new afterwards.
1007+ let fn_keys_before: std::collections::HashSet<String> =
1008+ ctx.functions.keys().cloned().collect();
1009+ let define_keys_before: std::collections::HashSet<String> =
1010+ ctx.defines.keys().cloned().collect();
1011+ let var_keys_before: std::collections::HashSet<String> =
1012+ ctx.variables.keys().cloned().collect();
1013+
1014+ let imported_lines = preprocess(&imported_text);
1015+ let mut imported_parser = Parser {
1016+ lines: imported_lines,
1017+ pos: 0,
1018+ };
1019+ let _discarded_nodes = imported_parser.parse_children(0, ctx);
1020+
1021+ // Remove newly added entries and re-insert them under the prefix.
1022+ let new_fn_keys: Vec<String> = ctx
1023+ .functions
1024+ .keys()
1025+ .filter(|k| !fn_keys_before.contains(*k))
1026+ .cloned()
1027+ .collect();
1028+ for name in new_fn_keys {
1029+ if let Some(def) = ctx.functions.remove(&name) {
1030+ ctx.functions.insert(format!("{}.{}", prefix, name), def);
1031+ }
1032+ }
1033+ let new_define_keys: Vec<String> = ctx
1034+ .defines
1035+ .keys()
1036+ .filter(|k| !define_keys_before.contains(*k))
1037+ .cloned()
1038+ .collect();
1039+ for name in new_define_keys {
1040+ if let Some(attrs) = ctx.defines.remove(&name) {
1041+ ctx.defines.insert(format!("{}.{}", prefix, name), attrs);
1042+ }
1043+ }
1044+ let new_var_keys: Vec<String> = ctx
1045+ .variables
1046+ .keys()
1047+ .filter(|k| !var_keys_before.contains(*k))
1048+ .cloned()
1049+ .collect();
1050+ for name in new_var_keys {
1051+ if let Some(val) = ctx.variables.remove(&name)
1052+ && !name.starts_with("__")
1053+ {
1054+ ctx.variables.insert(format!("{}.{}", prefix, name), val);
1055+ }
1056+ }
1057+ } else {
1058+ let included_lines = preprocess(&imported_text);
1059+ let mut included_parser = Parser {
1060+ lines: included_lines,
1061+ pos: 0,
1062+ };
1063+ included_nodes = included_parser.parse_children(0, ctx);
1064+ }
1065+
1066+ // Annotate new diagnostics with import chain
1067+ let import_chain = format_include_chain(&ctx.include_stack);
1068+ for d in &mut ctx.diagnostics[diag_count_before..] {
1069+ d.message = format!("{}\n in {}", d.message, import_chain);
1070+ }
1071+
1072+ ctx.base_path = saved_base;
1073+ ctx.include_stack.pop();
1074+ ctx.import_stack.pop();
1075+ return Ok(Some(included_nodes));
1076+ }
1077+
1078+
1079+
1080+ // --- @data (load JSON file into variables) ---
1081+
1082+ // @data file.json top-level keys become variables
1083+ // @data $name file.json values as $name.key
1084+ // @data $name dir/*.json each file as $name.STEM.key; $name
1085+ // lists the stems, $name._count counts them
1086+ // @data $name env:NAME [DEFAULT] an environment variable
1087+ if let Some(rest) = content.strip_prefix("@data ") {
1088+ let rest = rest.trim();
1089+ let (prefix, filename) = match rest.strip_prefix('$') {
1090+ Some(named) => match named.split_once(char::is_whitespace) {
1091+ Some((name, source)) => (name.to_string(), source.trim().to_string()),
1092+ None => {
1093+ return Err(ParseError {
1094+ line: line_num,
1095+ message: "@data requires: @data $name SOURCE or @data file.json"
1096+ .to_string(),
1097+ });
1098+ }
1099+ },
1100+ None => (String::new(), rest.to_string()),
17001101 };
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!(
1102+
1103+ if let Some(env) = filename.strip_prefix("env:") {
1104+ let (var, default) = match env.split_once(char::is_whitespace) {
1105+ Some((var, default)) => (var, Some(default.trim())),
1106+ None => (env, None),
1107+ };
1108+ if prefix.is_empty() {
1109+ return Err(ParseError {
1110+ line: line_num,
1111+ message: format!("@data env:{} needs a name: @data $name env:{}", var, var),
1112+ });
1113+ }
1114+ let value = std::env::var(var)
1115+ .ok()
1116+ .or_else(|| default.map(|d| substitute_vars(d, &ctx.variables)));
1117+ if value.is_none() {
1118+ ctx.diagnostics.push(Diagnostic {
1119+ line: line_num,
1120+ column: None,
1121+ message: format!(
17111122 "environment variable '{}' is not set and has no default",
17121123 var
17131124 ),
1714− )
1715− .source(content),
1716− );
1125+ severity: Severity::Warning,
1126+ source_line: Some(content.clone()),
1127+ });
1128+ }
1129+ ctx.variables.insert(prefix, value.unwrap_or_default());
1130+ return Ok(None);
17171131 }
1718− ctx.bind(&prefix, Value::Str(value.unwrap_or_default()));
1719− return;
1720− }
17211132
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));
1133+ let filename = substitute_vars(&filename, &ctx.variables);
17271134 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))
1135+ if prefix.is_empty() {
1136+ return Err(ParseError {
1137+ line: line_num,
1138+ message: format!("@data {} needs a name: @data $name {}", filename, filename),
1139+ });
17361140 }
1141+ self.load_data_glob(&prefix, &filename, line_num, &content, ctx);
1142+ return Ok(None);
1143+ }
1144+
1145+ let filename = substitute_vars(&filename, &ctx.variables);
1146+ let resolved = match &ctx.base_path {
1147+ Some(base) => base.join(&filename),
1148+ None => PathBuf::from(&filename),
1149+ };
1150+
1151+ let json_text = match std::fs::read_to_string(&resolved) {
1152+ Ok(text) => text,
17371153 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;
1154+ ctx.diagnostics.push(Diagnostic {
1155+ line: line_num,
1156+ column: None,
1157+ message: format!("cannot load data '{}': {}", filename, e),
1158+ severity: Severity::Error,
1159+ source_line: Some(content.clone()),
1160+ });
1161+ return Ok(None);
1162+ }
1163+ };
1164+
1165+ match parse_json_with_error(&json_text) {
1166+ Ok(json) => {
1167+ if prefix.is_empty() {
1168+ // No prefix: top-level object keys become variables directly
1169+ if let JsonValue::Object(pairs) = &json {
1170+ for (key, val) in pairs {
1171+ let mut sub = HashMap::new();
1172+ flatten_json(key, val, &mut sub);
1173+ for (k, v) in sub {
1174+ ctx.variables.insert(k, v);
1175+ }
1176+ }
1177+ } else {
1178+ ctx.diagnostics.push(Diagnostic {
1179+ line: line_num,
1180+ column: None,
1181+ message: "@data without prefix requires a JSON object at top level"
1182+ .to_string(),
1183+ severity: Severity::Error,
1184+ source_line: Some(content.clone()),
1185+ });
1186+ }
1187+ } else {
1188+ let mut sub = HashMap::new();
1189+ flatten_json(&prefix, &json, &mut sub);
1190+ for (k, v) in sub {
1191+ ctx.variables.insert(k, v);
1192+ }
1193+ }
1194+ }
1195+ Err(detail) => {
1196+ ctx.diagnostics.push(Diagnostic {
1197+ line: line_num,
1198+ column: None,
1199+ message: format!("invalid JSON in '{}': {}", filename, detail),
1200+ severity: Severity::Error,
1201+ source_line: Some(content.clone()),
1202+ });
17471203 }
17481204 }
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− ),
1205+
1206+ ctx.included_files.push(resolved);
1207+ return Ok(None);
1208+ }
1209+
1210+
1211+ // --- @if / @else ---
1212+
1213+ if let Some(rest) = content.strip_prefix("@if ") {
1214+ let result = ctx.condition(rest.trim(), line_num);
1215+
1216+ // Collect then-body lines
1217+ let mut then_lines = Vec::new();
1218+ while self.pos < self.lines.len() && self.lines[self.pos].indent > current_indent {
1219+ then_lines.push(self.lines[self.pos].clone());
1220+ self.pos += 1;
1221+ }
1222+
1223+ // Build branches: [(condition_result, body_lines), ...]
1224+ let mut branches: Vec<(bool, Vec<Line>)> = vec![(result, then_lines)];
1225+
1226+ // Check for @else if / @else chains at same indent
1227+ loop {
1228+ if self.pos >= self.lines.len() || self.lines[self.pos].indent != current_indent {
1229+ break;
1230+ }
1231+ if let LineContent::Normal(ref s) = self.lines[self.pos].content {
1232+ let trimmed = s.trim();
1233+ if let Some(else_if_cond) = trimmed.strip_prefix("@else if ") {
1234+ self.pos += 1; // consume @else if
1235+ let cond_result =
1236+ ctx.condition(else_if_cond.trim(), self.lines[self.pos - 1].line_num);
1237+ let mut body = Vec::new();
1238+ while self.pos < self.lines.len()
1239+ && self.lines[self.pos].indent > current_indent
1240+ {
1241+ body.push(self.lines[self.pos].clone());
1242+ self.pos += 1;
1243+ }
1244+ branches.push((cond_result, body));
1245+ } else if trimmed == "@else" {
1246+ self.pos += 1; // consume @else
1247+ let mut body = Vec::new();
1248+ while self.pos < self.lines.len()
1249+ && self.lines[self.pos].indent > current_indent
1250+ {
1251+ body.push(self.lines[self.pos].clone());
1252+ self.pos += 1;
1253+ }
1254+ // @else is always true (fallback)
1255+ branches.push((true, body));
1256+ break;
1257+ } else {
1258+ break;
1259+ }
1260+ } else {
1261+ break;
1262+ }
1263+ }
1264+
1265+ // Pick the first branch whose condition is true
1266+ let body_lines = branches
1267+ .into_iter()
1268+ .find(|(cond, _)| *cond)
1269+ .map(|(_, lines)| lines)
1270+ .unwrap_or_default();
1271+
1272+ if body_lines.is_empty() {
1273+ return Ok(None);
1274+ }
1275+
1276+ let min_indent = body_lines.iter().map(|l| l.indent).min().unwrap_or(0);
1277+ let adjusted: Vec<Line> = body_lines
1278+ .iter()
1279+ .map(|l| Line {
1280+ indent: l.indent - min_indent,
1281+ content: l.content.clone(),
1282+ line_num: l.line_num,
1283+ })
1284+ .collect();
1285+
1286+ // Scope variables: @let inside @if doesn't leak out
1287+ let saved_vars = ctx.variables.clone();
1288+ let mut body_parser = Parser {
1289+ lines: adjusted,
1290+ pos: 0,
1291+ };
1292+ let nodes = body_parser.parse_children(0, ctx);
1293+ ctx.variables = saved_vars;
1294+ return Ok(Some(nodes));
1295+ }
1296+
1297+
1298+ if content.trim() == "@else" || content.trim().starts_with("@else if ") {
1299+ return Err(ParseError {
1300+ line: line_num,
1301+ message: "@else without matching @if".to_string(),
1302+ });
1303+ }
1304+
1305+ // --- @each loop ---
1306+
1307+ if let Some(rest) = content.strip_prefix("@each ") {
1308+ let rest = rest.trim();
1309+ // Support: @each $var in list OR @each $var, $index in list
1310+ // OR @each $name, $url in Alice /alice, Bob /bob (destructuring)
1311+ let (var_names, list_str) = if let Some((before_in, after_in)) = rest.split_once(" in ")
1312+ {
1313+ let before_in = before_in.trim();
1314+ let vars: Vec<String> = before_in
1315+ .split(',')
1316+ .map(|v| v.trim().strip_prefix('$').unwrap_or(v.trim()).to_string())
1317+ .collect();
1318+ (vars, after_in.trim().to_string())
1319+ } else {
1320+ return Err(ParseError {
1321+ line: line_num,
1322+ message: "@each requires: @each $var in list".to_string(),
1323+ });
1324+ };
1325+ let var_name = var_names[0].clone();
1326+ let index_var = var_names.get(1).cloned();
1327+
1328+ if list_str.trim_end().ends_with(']') && list_str.contains("[page ") {
1329+ return Err(ParseError {
1330+ line: line_num,
1331+ message: "@each pagination (`[page N]`) was removed: split the list or \
1332+ filter it with @if"
1333+ .to_string(),
1334+ });
1335+ }
1336+ track_var_refs(&list_str, &mut ctx.used_variables);
1337+ let list_str = substitute_vars(&list_str, &ctx.variables);
1338+ // Support range syntax: @each $i in 1..5 or @each $i in 0..100 step 10
1339+ let items: Vec<String> = if let Some((start_s, rest)) = list_str.split_once("..") {
1340+ let (end_s, step) = if let Some((e, s)) = rest.split_once(" step ") {
1341+ (e.trim(), s.trim().parse::<i64>().unwrap_or(1).max(1))
1342+ } else {
1343+ (rest.trim(), 1i64)
1344+ };
1345+ if let (Ok(start), Ok(end)) = (start_s.trim().parse::<i64>(), end_s.parse::<i64>())
1346+ {
1347+ numeric_range(start, end, step)
1348+ } else {
1349+ list_str
1350+ .split(',')
1351+ .map(|s| s.trim().to_string())
1352+ .filter(|s| !s.is_empty())
1353+ .collect()
1354+ }
1355+ } else {
1356+ list_str
1357+ .split(',')
1358+ .map(|s| s.trim().to_string())
1359+ .filter(|s| !s.is_empty())
1360+ .collect()
1361+ };
1362+
1363+ // Collect body lines
1364+ let mut body_lines = Vec::new();
1365+ while self.pos < self.lines.len() && self.lines[self.pos].indent > current_indent {
1366+ body_lines.push(self.lines[self.pos].clone());
1367+ self.pos += 1;
1368+ }
1369+
1370+ // Check for @else block (empty-state fallback)
1371+ let mut else_lines = Vec::new();
1372+ if self.pos < self.lines.len()
1373+ && self.lines[self.pos].indent == current_indent
1374+ && let LineContent::Normal(ref s) = self.lines[self.pos].content
1375+ && s.trim() == "@else"
1376+ {
1377+ self.pos += 1; // consume @else
1378+ while self.pos < self.lines.len() && self.lines[self.pos].indent > current_indent {
1379+ else_lines.push(self.lines[self.pos].clone());
1380+ self.pos += 1;
1381+ }
1382+ }
1383+
1384+ if body_lines.is_empty() {
1385+ return Ok(None);
1386+ }
1387+
1388+ // If list is empty, render @else body
1389+ if items.is_empty() {
1390+ if else_lines.is_empty() {
1391+ return Ok(None);
1392+ }
1393+ let min_indent = else_lines.iter().map(|l| l.indent).min().unwrap_or(0);
1394+ let adjusted: Vec<Line> = else_lines
1395+ .iter()
1396+ .map(|l| Line {
1397+ indent: l.indent - min_indent,
1398+ content: l.content.clone(),
1399+ line_num: l.line_num,
1400+ })
1401+ .collect();
1402+ let mut body_parser = Parser {
1403+ lines: adjusted,
1404+ pos: 0,
1405+ };
1406+ let saved_vars = ctx.variables.clone();
1407+ let nodes = body_parser.parse_children(0, ctx);
1408+ ctx.variables = saved_vars;
1409+ return Ok(Some(nodes));
1410+ }
1411+
1412+ let min_indent = body_lines.iter().map(|l| l.indent).min().unwrap_or(0);
1413+ let adjusted: Vec<Line> = body_lines
1414+ .iter()
1415+ .map(|l| Line {
1416+ indent: l.indent - min_indent,
1417+ content: l.content.clone(),
1418+ line_num: l.line_num,
1419+ })
1420+ .collect();
1421+
1422+ let saved_vars = ctx.variables.clone();
1423+ let mut all_nodes = Vec::new();
1424+
1425+ let has_extra_vars = var_names.len() > 2
1426+ || (var_names.len() == 2 && items.first().is_some_and(|it| it.contains(' ')));
1427+
1428+ for (i, item) in items.iter().enumerate() {
1429+ // Always expose $_index for the current iteration
1430+ ctx.variables.insert("_index".to_string(), i.to_string());
1431+ if has_extra_vars {
1432+ // Destructuring: split item by spaces and assign to each variable
1433+ let parts: Vec<&str> = item.splitn(var_names.len(), ' ').collect();
1434+ for (vi, vn) in var_names.iter().enumerate() {
1435+ let val = parts.get(vi).unwrap_or(&"").to_string();
1436+ ctx.variables.insert(vn.clone(), val);
1437+ }
1438+ } else {
1439+ ctx.variables.insert(var_name.clone(), item.clone());
1440+ if let Some(ref idx_name) = index_var {
1441+ ctx.variables.insert(idx_name.clone(), i.to_string());
1442+ }
1443+ }
1444+ let mut body_parser = Parser {
1445+ lines: adjusted.clone(),
1446+ pos: 0,
1447+ };
1448+ let nodes = body_parser.parse_children(0, ctx);
1449+ all_nodes.extend(nodes);
1450+ }
1451+
1452+ ctx.variables = saved_vars;
1453+ return Ok(Some(all_nodes));
1454+ }
1455+
1456+
1457+
1458+ // --- @warn / @debug ---
1459+
1460+ if let Some(rest) = content.strip_prefix("@warn ") {
1461+ let msg = substitute_vars(rest.trim(), &ctx.variables);
1462+ ctx.diagnostics.push(Diagnostic {
1463+ line: line_num,
1464+ column: None,
1465+ message: msg,
1466+ severity: Severity::Warning,
1467+ source_line: Some(content.clone()),
1468+ });
1469+ return Ok(None);
1470+ }
1471+
1472+
1473+ // --- @keyframes directive ---
1474+
1475+ if let Some(rest) = content.strip_prefix("@keyframes ") {
1476+ let name = rest.trim().to_string();
1477+ if name.is_empty() {
1478+ return Err(ParseError {
1479+ line: line_num,
1480+ message: "@keyframes requires a name".to_string(),
1481+ });
1482+ }
1483+ // Collect body lines (indented deeper)
1484+ let mut body = String::new();
1485+ while self.pos < self.lines.len() && self.lines[self.pos].indent > current_indent {
1486+ if let LineContent::Normal(ref s) = self.lines[self.pos].content {
1487+ let trimmed = s.trim();
1488+ // Support htmlang-style: from [opacity 0] / to [opacity 1] / 50% [transform scale(1.5)]
1489+ if let Some(kf_css) = parse_keyframe_line(trimmed) {
1490+ body.push_str(&kf_css);
1491+ } else {
1492+ body.push_str(trimmed);
1493+ }
1494+ }
1495+ self.pos += 1;
1496+ }
1497+ ctx.keyframes.push((name, body));
1498+ return Ok(None);
1499+ }
1500+
1501+
1502+
1503+ // --- Function call ---
1504+
1505+ if content.starts_with('@') {
1506+ let name = extract_element_name(&content);
1507+ if ctx.functions.contains_key(name) {
1508+ ctx.used_functions.insert(name.to_string());
1509+ let nodes = self.expand_fn_call(name, &content, current_indent, line_num, ctx)?;
1510+ return Ok(Some(nodes));
1511+ }
1512+ }
1513+
1514+ // --- Elements ---
1515+
1516+ if content.starts_with('@') || content.starts_with('[') {
1517+ let node = self.parse_element_line(&content, current_indent, line_num, ctx)?;
1518+ return Ok(Some(vec![inline_svg(node, line_num, ctx)]));
17601519 }
1520+
1521+ // --- Bare text ---
1522+
1523+ let var_warnings =
1524+ check_undefined_vars(&content, &ctx.variables, line_num, current_indent);
1525+ ctx.diagnostics.extend(var_warnings);
1526+ track_var_refs(&content, &mut ctx.used_variables);
1527+ let segments = parse_text_segments(&content, ctx);
1528+ Ok(Some(vec![Node::Text(segments)]))
17611529 }
17621530
1763− /// `@data $name dir/*.json`: a list with one record per matching file
1764− /// (in name order), whose `file` is the file's name without extension.
1531+ /// `@data $name dir/*.json`: load every matching file as
1532+ /// `$name.STEM.key`, list the stems in `$name` and count them.
17651533 fn load_data_glob(
17661534 &mut self,
17671535 name: &str,
@@ -1791,20 +1559,18 @@ impl Evaluator {
17911559 })
17921560 .collect(),
17931561 Err(e) => {
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− );
1562+ ctx.diagnostics.push(Diagnostic {
1563+ line: line_num,
1564+ column: None,
1565+ message: format!("cannot read directory for '{}': {}", pattern, e),
1566+ severity: Severity::Error,
1567+ source_line: Some(content.to_string()),
1568+ });
18031569 return;
18041570 }
18051571 };
18061572 files.sort();
1807− let mut records = Vec::new();
1573+ let mut stems = Vec::new();
18081574 for file in files {
18091575 let stem = file
18101576 .file_stem()
@@ -1814,454 +1580,135 @@ impl Evaluator {
18141580 let text = match std::fs::read_to_string(&file) {
18151581 Ok(text) => text,
18161582 Err(e) => {
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− );
1583+ ctx.diagnostics.push(Diagnostic {
1584+ line: line_num,
1585+ column: None,
1586+ message: format!("cannot load data '{}': {}", file.display(), e),
1587+ severity: Severity::Error,
1588+ source_line: Some(content.to_string()),
1589+ });
18261590 continue;
18271591 }
18281592 };
18291593 match parse_json_with_error(&text) {
1830− Ok(JsonValue::Object(mut pairs)) => {
1831− if !pairs.iter().any(|(key, _)| key == "file") {
1832− pairs.push(("file".to_string(), JsonValue::Str(stem)));
1833− }
1834− records.push(JsonValue::Object(pairs));
1594+ Ok(json) => {
1595+ let mut vars = HashMap::new();
1596+ flatten_json(&format!("{}.{}", name, stem), &json, &mut vars);
1597+ ctx.variables.extend(vars);
1598+ stems.push(stem);
18351599 }
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− ),
1600+ Err(detail) => ctx.diagnostics.push(Diagnostic {
1601+ line: line_num,
1602+ column: None,
1603+ message: format!("invalid JSON in '{}': {}", file.display(), detail),
1604+ severity: Severity::Error,
1605+ source_line: Some(content.to_string()),
1606+ }),
18541607 }
18551608 ctx.included_files.push(file);
18561609 }
1857− ctx.bind(name, json_value(JsonValue::Array(records)));
1610+ ctx.variables
1611+ .insert(format!("{}._count", name), stems.len().to_string());
1612+ ctx.variables.insert(name.to_string(), stems.join(", "));
18581613 }
18591614
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.
1865− fn eval_each(
1615+ fn expand_fn_call(
18661616 &mut self,
1867− node: &syntax::Node,
1868− empty_branch: Option<&syntax::Node>,
1617+ name: &str,
1618+ content: &str,
1619+ current_indent: usize,
1620+ line_num: usize,
18691621 ctx: &mut ParseContext,
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);
1874− }
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())
1897− }
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
1622+ ) -> Result<Vec<Node>, ParseError> {
1623+ // Recursive function cycle detection
1624+ if ctx.fn_call_stack.contains(&name.to_string()) {
1625+ return Err(ParseError {
1626+ line: line_num,
1627+ message: format!(
1628+ "recursive function call to @{} (call stack: {})",
1629+ name,
1630+ ctx.fn_call_stack.join(" -> ")
19081631 ),
1909− ctx,
1910− )
1911− .suggest(Some(inner));
1912− ctx.push_once(diagnostic);
1632+ });
19131633 }
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);
1929− Vec::new()
1634+ ctx.fn_call_stack.push(name.to_string());
1635+
1636+ // Parse [param value, ...] arguments
1637+ let rest = &content[1 + name.len()..];
1638+ let rest = rest.trim_start();
1639+
1640+ let (args, trailing_text) = if rest.starts_with('[') {
1641+ parse_attr_brackets_no_validate(rest, line_num, ctx)?
1642+ } else {
1643+ (Vec::new(), rest.to_string())
1644+ };
1645+
1646+ // Clone function definition (releases borrow on ctx). If the function is
1647+ // missing (shouldn't normally happen — callers check ctx.functions.contains_key
1648+ // first — but we avoid panicking on malformed state).
1649+ let fn_def = match ctx.functions.get(name) {
1650+ Some(def) => def.clone(),
1651+ None => {
1652+ ctx.fn_call_stack.pop();
1653+ return Err(ParseError {
1654+ line: line_num,
1655+ message: format!("undefined function @{}", name),
1656+ });
19301657 }
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],
19351658 };
19361659
1937− if body.iter().all(syntax::Node::is_trivia) {
1938− return Ok(Some(Vec::new()));
1939− }
1940− if items.is_empty() {
1941− return Ok(Some(self.eval_scoped(empty, ctx)));
1942− }
1943− let mut nodes = Vec::new();
1944− for (i, value) in items.into_iter().enumerate() {
1945− ctx.env.push();
1946− ctx.bind(item, value);
1947− if let Some(index) = index {
1948− ctx.bind(index, Value::Num(i as f64));
1660+ // Parse caller's children, separating named slots from default children
1661+ let all_caller_children = self.parse_children(current_indent + 1, ctx);
1662+ let mut slot_contents: HashMap<String, Vec<Node>> = HashMap::new();
1663+ let mut caller_children = Vec::new();
1664+ for child in all_caller_children {
1665+ if let Node::Element(ref elem) = child
1666+ && let ElementKind::Slot(ref slot_name) = elem.kind
1667+ && !slot_name.is_empty()
1668+ {
1669+ slot_contents
1670+ .entry(slot_name.clone())
1671+ .or_default()
1672+ .extend(elem.children.clone());
1673+ continue;
19491674 }
1950− nodes.extend(self.eval_block(body, ctx));
1951− ctx.env.pop();
1675+ caller_children.push(child);
1676+ }
1677+ // Text after the call, as in `@badge [color red] New`, is content:
1678+ // it goes first among the caller's children.
1679+ let trailing_text = trailing_text.trim();
1680+ if !trailing_text.is_empty() {
1681+ caller_children.insert(0, Node::Text(parse_text_segments(trailing_text, ctx)));
19521682 }
1953− Ok(Some(nodes))
1954− }
19551683
1956− fn define_function(
1957− &mut self,
1958− name: &str,
1959− params: &[syntax::Param],
1960− node: &syntax::Node,
1961− ctx: &mut ParseContext,
1962− ) {
1963− let line_num = node.span.line;
1964− let body = &node.children;
1965− // An @style block at the top of the body is scoped to the
1966− // function: its rules apply inside a `.hl-fn-NAME-HASH` wrapper (a
1967− // generated class never has a second `-`, so the two can't meet).
1968− // The hash is the stylesheet's, so two functions of one name with
1969− // two stylesheets, in two files, don't style each other's elements
1970− // in a page that has both. It is written into the page when the
1971− // function is called.
1972− let (style, body): (Vec<&syntax::Node>, Vec<&syntax::Node>) =
1973− body.iter().partition(|node| node.is_directive("style"));
1974− let scoped = (!style.is_empty()).then(|| {
1975− let css: String = style
1976− .iter()
1977− .map(|node| {
1978− ctx.visited.insert(node.id);
1979− verbatim_content(node)
1684+ // Save variable state, inject function parameters
1685+ let saved_vars = ctx.variables.clone();
1686+ let mut consumed = vec![false; args.len()];
1687+ for (i, param) in fn_def.params.iter().enumerate() {
1688+ let named = args.iter().position(|a| a.key == *param);
1689+ // Positional fallback, unless that argument is named for a
1690+ // different parameter.
1691+ let positional = args
1692+ .get(i)
1693+ .filter(|a| !fn_def.params.contains(&a.key) && a.value.is_some())
1694+ .map(|_| i);
1695+ let value = named
1696+ .filter(|&j| args[j].value.is_some())
1697+ .or(positional)
1698+ .and_then(|j| {
1699+ consumed[j] = true;
1700+ args[j].value.clone()
19801701 })
1981− .collect();
1982− let digits = crate::codegen::CLASS_DIGITS;
1983− let hash = crate::codegen::hash_digits(crate::codegen::stable_hash(&css), digits);
1984− let class = format!("hl-fn-{}-{}", name, hash);
1985− // Nested under the scope class, so any CSS works (multi-line
1986− // rules, at-rules)
1987− let css = if css.trim().is_empty() {
1988− String::new()
1989− } else {
1990− format!(".{} {{\n{}}}", class, css)
1991− };
1992− (class, css)
1993− });
1994−
1995− // A default is filled in only when a call leaves its parameter
1996− // out, so the names in it count as used here
1997− for default in params.iter().filter_map(|p| p.default.as_ref()) {
1998− track_var_refs(default, &mut ctx.used_variables);
1999− }
2000− ctx.fn_lines.entry(name.to_string()).or_insert(line_num);
2001− let wraps_itself = ElementKind::from_name(name).is_some()
2002− && body.iter().any(|node| calls_unguarded(node, name));
2003− if wraps_itself {
2004− ctx.push_once(
2005− Diagnostic::error(
2006− code::RECURSIVE_CALL,
2007− line_num,
2008− format!(
2009− "@{0} in the body of `@let @{0}` calls the function itself, not the \
2010− element @{0}, so it would never stop: give the function another name \
2011− (such as @site-{0})",
2012− name
2013− ),
2014− )
2015− .subject(name),
2016− );
2017− }
2018− for node in &body {
2019− node.walk(&mut |node| {
2020− if let Some(d) = marker_in_text(node) {
2021− ctx.push_once(d);
2022− }
2023− });
2024− }
2025− let body: Vec<syntax::Node> = body.into_iter().cloned().collect();
2026− let (slots, has_children) = declared_slots(&body, ctx);
2027− let function = Rc::new(FnDef {
2028− params: params.to_vec(),
2029− line: line_num,
2030− source: ctx.current_source.1.clone(),
2031− node: node.id,
2032− body,
2033− file: ctx.current_file.clone(),
2034− slots,
2035− has_children,
2036− scoped,
2037− env: ctx.env.clone(),
2038− wraps_itself,
2039− });
2040− ctx.defined_functions
2041− .insert(name.to_string(), function.clone());
2042− ctx.env.define(name, Binding::Function(function));
2043− }
2044−
2045− /// An element line: a chain of elements and function calls, the last of
2046− /// which gets the indented children.
2047− fn eval_element(
2048− &mut self,
2049− node: &syntax::Node,
2050− element: &syntax::ElementLine,
2051− ctx: &mut ParseContext,
2052− ) -> Result<Vec<Node>, ParseError> {
2053− // An unclosed attribute list is a syntax error, already reported
2054− if element
2055− .chain
2056− .iter()
2057− .any(|h| h.attrs.as_ref().is_some_and(|a| !a.closed))
2058− {
2059− return Ok(Vec::new());
2060− }
2061− let line_num = node.span.line;
2062− let last = element.chain.len() - 1;
2063− // Each head is read where it is written, left to right. The
2064− // children belong to the last one, so the chain is built right to
2065− // left, each link wrapping the next.
2066− let mut links = Vec::new();
2067− for (i, head) in element.chain.iter().enumerate() {
2068− let text = if i == last {
2069− element.text.as_ref()
2070− } else {
2071− None
2072− };
2073− links.push(resolve(head, text, line_num, &node.source, ctx)?);
2074− }
2075− let calls: Vec<Option<(String, Rc<FnDef>)>> = links
2076− .iter()
2077− .map(|link| match link {
2078− Resolved::Call(call) => Some((call.name.clone(), call.function.clone())),
2079− Resolved::Element(_) => None,
2080− })
2081− .collect();
2082− let mut current = self.eval_scoped(&node.children, ctx);
2083− // After the lines under the call ran, so the files they include
2084− // are read
2085− check_fillers(node, element, &calls, ctx);
2086− for link in links.into_iter().rev() {
2087− current = self.complete(link, current, ctx)?;
2088− }
2089− Ok(current)
2090− }
2091−
2092− /// Give a resolved `@name` its children: an element holds them, and a
2093− /// function's body puts them where its `@children` is.
2094− fn complete(
2095− &mut self,
2096− resolved: Resolved,
2097− children: Vec<Node>,
2098− ctx: &mut ParseContext,
2099− ) -> Result<Vec<Node>, ParseError> {
2100− match resolved {
2101− Resolved::Element(mut element) => {
2102− element.children.extend(children);
2103− let line = element.line_num;
2104− Ok(vec![inline_svg(Node::Element(element), line, ctx)])
2105− }
2106− Resolved::Call(call) => self.expand_fn_call(*call, children, ctx),
2107− }
2108− }
2109−
2110− fn expand_fn_call(
2111− &mut self,
2112− call: Call,
2113− all_caller_children: Vec<Node>,
2114− ctx: &mut ParseContext,
2115− ) -> Result<Vec<Node>, ParseError> {
2116− let Call {
2117− name,
2118− function: fn_def,
2119− args,
2120− values,
2121− text: trailing_text,
2122− written_form,
2123− written_keys,
2124− line: line_num,
2125− name_at,
2126− source: content,
2127− } = call;
2128− let (name, content) = (name.as_str(), content.as_str());
2129−
2130− // Separate the caller's `@slot NAME` blocks from its other
2131− // children. A block for a slot the function doesn't declare was
2132− // reported where it is written (see `check_fillers`), like one
2133− // without a name.
2134− let mut slot_contents: HashMap<String, Vec<Node>> = HashMap::new();
2135− let mut caller_children = Vec::new();
2136− for child in all_caller_children {
2137− if let Node::Element(elem) = child {
2138− match elem.kind {
2139− ElementKind::Slot(slot_name) => {
2140− slot_contents
2141− .entry(slot_name)
2142− .or_default()
2143− .extend(elem.children);
2144− }
2145− kind => caller_children.push(Node::Element(Element { kind, ..elem })),
2146− }
2147− continue;
2148− }
2149− caller_children.push(child);
2150− }
2151− // Text after the call, as in `@card [color red] New`, is content:
2152− // it goes first among the caller's children, and like them it is
2153− // evaluated where the call is written.
2154− if let Some(text) = &trailing_text {
2155− caller_children.insert(0, Node::Text(text_segments(text, ctx)));
2156− }
2157− // Content goes where the body's `@children` is: without one, it
2158− // would be dropped
2159− if !fn_def.has_children && !caller_children.is_empty() {
2160− let (column, text) = match &name_at {
2161− Some((column, text)) => (Some(*column), text.as_str()),
2162− None => (None, content),
2163− };
2164− ctx.push_once(no_children(name, line_num, column).source(text));
2165− }
2166−
2167− if fn_def.wraps_itself {
2168− return Ok(Vec::new());
2169− }
2170− // Only the body is inside the call, so a function may appear in the
2171− // content its caller passes it. A function may call itself, under
2172− // a condition that stops it; one that doesn't stop goes too deep.
2173− if ctx.too_deep {
2174− return Ok(Vec::new());
2175− }
2176− if ctx.fn_call_stack.len() >= MAX_CALL_DEPTH {
2177− ctx.too_deep = true;
2178− return Err(too_deep(name, &ctx.fn_call_stack, line_num).source(content));
2179− }
2180− let caller = (
2181− ctx.current_line,
2182− ctx.current_source.clone(),
2183− ctx.current_node,
2184− );
2185− ctx.fn_call_stack.push(name.to_string());
2186−
2187− // The body runs where the function is defined: it sees what was
2188− // visible there, the function itself (so it can call itself), and
2189− // its parameters, bound by name in the order they are declared. A
2190− // default is filled in at the call, seeing the same, with the
2191− // parameters before it.
2192− let caller_env = std::mem::replace(&mut ctx.env, fn_def.env.clone());
2193− ctx.env.push();
2194− ctx.env.define(name, Binding::Function(fn_def.clone()));
2195− let mut consumed = vec![false; args.len()];
2196− for param in &fn_def.params {
2197− let mut passed = None;
2198− for (j, arg) in args.iter().enumerate() {
2199− if arg.key != param.name {
2200− continue;
2201− }
2202− consumed[j] = true;
2203− // The later one wins, as for any attribute: one written
2204− // after a bundle overrides it, and only one written twice
2205− // in the call's own list is reported
2206− if passed.is_some() && written_keys.iter().filter(|k| **k == param.name).count() > 1
2207− {
2208− ctx.push_once(
2209− Diagnostic::warning(
2210− code::DUPLICATE_ATTRIBUTE,
2211− line_num,
2212− format!(
2213− "parameter '{}' of @{} is passed twice: the later one wins",
2214− param.name, name
2215− ),
2216− )
2217− .source(content)
2218− .subject(param.name.as_str()),
2219− );
2220− }
2221− // Written `name=value` in the call's own list is reported
2222− // as written; this is one from a bundle
2223− if arg.html && !written_form.contains(&arg.key) {
2224− let value = arg.value.as_deref().unwrap_or("");
2225− ctx.push_once(parameter_form(name, &arg.key, value, line_num).source(content));
2226− }
2227− passed = Some(j);
2228− }
2229− let value = match passed {
2230− // A parameter's name alone is true: `@post-card [featured]`
2231− Some(j) if args[j].value.is_none() => Value::Bool(true),
2232− // What the call passed, with its type: a record, a list,
2233− // quoted text
2234− Some(j) => values[j].clone().unwrap_or_else(|| {
2235− let arg = &args[j];
2236− match &arg.quoted {
2237− Some(quoted) => Value::Quoted(quoted.clone()),
2238− None => Value::Str(arg.value.clone().unwrap_or_default()),
2239− }
2240− }),
2241− None => match ¶m.default {
2242− Some(default) => {
2243− let before = ctx.diagnostics.len();
2244− let value = fill_default(&fn_def, param, default, ctx);
2245− point_at_call(ctx, before, &fn_def, name, line_num, content);
2246− value
2247− }
2248− None => {
2249− let (column, text) = match &name_at {
2250− Some((column, text)) => (Some(*column), text.as_str()),
2251− None => (None, content),
2252− };
2253− ctx.push_once(
2254− missing_parameter(name, ¶m.name, line_num, column).source(text),
2255− );
2256− Value::empty()
2257− }
2258− },
2259− };
2260− ctx.bind(¶m.name, value);
1702+ .or_else(|| fn_def.defaults.get(param).cloned())
1703+ .unwrap_or_default();
1704+ if let Some(j) = named {
1705+ consumed[j] = true;
1706+ }
1707+ ctx.variables.insert(param.clone(), value);
22611708 }
22621709 // Arguments that aren't parameters are attributes for the
22631710 // function's root element, so a function can be styled like an
2264− // element: `@card [background red] New`.
1711+ // element: `@badge [background red] New`.
22651712 let forwarded: Vec<Attribute> = args
22661713 .iter()
22671714 .zip(&consumed)
@@ -2269,1435 +1716,245 @@ impl Evaluator {
22691716 .map(|(a, _)| a.clone())
22701717 .collect();
22711718
2272− // Evaluate the body with the parameters in scope, as lines of the
2273− // file that defines the function
2274− let caller_file = std::mem::replace(&mut ctx.current_file, fn_def.file.clone());
2275− let before = ctx.diagnostics.len();
2276− let mut body_nodes = self.eval_block(&fn_def.body, ctx);
2277− ctx.current_file = caller_file;
2278− point_at_call(ctx, before, &fn_def, name, line_num, content);
2279−
2280− // Back to the caller's names and call stack
2281− ctx.env = caller_env;
2282− ctx.fn_call_stack.pop();
2283− if ctx.fn_call_stack.is_empty() {
2284− ctx.too_deep = false;
2285− }
2286− (ctx.current_line, ctx.current_source, ctx.current_node) = caller;
2287−
2288− // What the body wrote is the call's
2289− belongs_to_call(&mut body_nodes, name, line_num);
2290−
2291− // Replace @children with caller's children and @slot with slot content
2292− let mut result_nodes =
2293− replace_children_and_slots(body_nodes, &caller_children, &slot_contents);
2294−
2295− // Attributes that aren't parameters style the function's root
2296− // element, and a scoped @style's class goes on it too.
2297− let scope_class = fn_def.scoped.as_ref().map(|(class, _)| class.clone());
2298− if !forwarded.is_empty() || scope_class.is_some() {
2299− let mut roots = result_nodes.iter_mut().filter_map(|n| match n {
2300− Node::Element(e) => Some(e),
2301− _ => None,
2302− });
2303− let root = match (roots.next(), roots.next()) {
2304− (Some(root), None) => Some(root),
2305− _ => None,
2306− };
2307− let mut problems = Vec::new();
2308− match root {
2309− Some(root) => {
2310− // A call's `class=` adds to the root's own classes
2311− for attr in forwarded {
2312− let existing = (attr.html && attr.key == "class")
2313− .then(|| root.attrs.iter_mut().find(|a| a.html && a.key == "class"))
2314− .flatten();
2315− match existing {
2316− Some(class) => {
2317− let mut value = class.value.take().unwrap_or_default();
2318− for name in attr.value.as_deref().unwrap_or("").split_whitespace() {
2319− if !value.split_whitespace().any(|c| c == name) {
2320− value.push(' ');
2321− value.push_str(name);
2322− }
2323− }
2324− class.value = Some(value.trim().to_string());
2325− }
2326− None => root.attrs.push(attr),
2327− }
2328− }
2329− // The scoped `@style` goes into the page once, when the
2330− // function is first called
2331− if let Some((_, css)) = &fn_def.scoped
2332− && !css.is_empty()
2333− && !ctx.scoped_css.contains(css)
2334− {
2335− ctx.scoped_css.push(css.clone());
2336− }
2337− if let Some(class) = scope_class {
2338− match root.attrs.iter_mut().find(|a| a.html && a.key == "class") {
2339− Some(attr) => {
2340− let existing = attr.value.take().unwrap_or_default();
2341− attr.value =
2342− Some(format!("{} {}", existing, class).trim().to_string());
2343− }
2344− None => root.attrs.push(Attribute {
2345− key: "class".to_string(),
2346− value: Some(class),
2347− html: true,
2348− quoted: None,
2349− }),
2350− }
2351− }
2352− }
2353− None => {
2354− if !forwarded.is_empty() {
2355− problems.push(format!(
2356− "attributes {} on @{} are not parameters, and its body has no single \
2357− root element to receive them",
2358− forwarded
2359− .iter()
2360− .map(|a| format!("'{}'", a.key))
2361− .collect::<Vec<_>>()
2362− .join(", "),
2363− name
2364− ));
2365− }
2366− if scope_class.is_some() {
2367− problems.push(format!(
2368− "@{} has a scoped @style, but its body has no single root element \
2369− to scope it to",
2370− name
2371− ));
2372− }
2373− }
2374− }
2375− for message in problems {
2376− ctx.diagnostics.push(
2377− Diagnostic::error(code::NO_SINGLE_ROOT, line_num, message)
2378− .source(content)
2379− .subject(name),
2380− );
2381− }
2382− }
2383−
2384− Ok(result_nodes)
2385− }
2386−}
2387−
2388−/// A `@name` read where it is written: a built-in element, or a call.
2389−enum Resolved {
2390− Element(Element),
2391− Call(Box<Call>),
2392−}
2393−
2394−/// A call of a function, with its arguments evaluated where it is written.
2395−struct Call {
2396− name: String,
2397− function: Rc<FnDef>,
2398− args: Vec<Attribute>,
2399− /// The value of each argument that passes a parameter, with its type
2400− /// (see [`ParseContext::slot_value`]), in the order of `args`.
2401− values: Vec<Option<Value>>,
2402− /// Text after the attributes, which is content.
2403− text: Option<syntax::Text>,
2404− /// Parameters written `name=value`, already reported.
2405− written_form: Vec<String>,
2406− /// The keys written in the call's own list, not from a bundle.
2407− written_keys: Vec<String>,
2408− line: usize,
2409− /// The column of the call's name and the line it is on, for a missing
2410− /// parameter.
2411− name_at: Option<(usize, String)>,
2412− /// The line as written, for diagnostics.
2413− source: String,
2414−}
2415−
2416−/// What `@name` is where it is written: a call of the function `name`
2417−/// when one is defined, else the built-in element. A whole line, each link
2418−/// of a chain and an inline element in text all resolve here.
2419−fn resolve(
2420− head: &syntax::Head,
2421− text: Option<&syntax::Text>,
2422− line: usize,
2423− source: &str,
2424− ctx: &mut ParseContext,
2425−) -> Result<Resolved, ParseError> {
2426− let Some(function) = ctx.env.function(&head.name).cloned() else {
2427− return parse_single_element(head, text, line, ctx).map(Resolved::Element);
2428− };
2429− ctx.used_functions.insert(head.name.clone());
2430− let params: Vec<String> = function.params.iter().map(|p| p.name.clone()).collect();
2431− let written = head.attrs.as_ref().map_or(&[][..], |list| &list.attrs[..]);
2432− let written_form = written_parameter_forms(&head.name, &function, written, line, ctx);
2433− let written_keys = written.iter().map(|a| a.key.clone()).collect();
2434− // Parameters are bound by name; every other attribute goes to the
2435− // root element, and is checked like any attribute
2436− let (args, values) = parse_attrs(written, line, ctx, true, ¶ms)
2437− .into_iter()
2438− .unzip();
2439− let name_at = name_column(head, line).zip(match &ctx.current_source {
2440− (current, Some(text)) if *current == line => Some(text.clone()),
2441− _ => None,
2442− });
2443− Ok(Resolved::Call(Box::new(Call {
2444− name: head.name.clone(),
2445− function,
2446− args,
2447− values,
2448− text: text.cloned(),
2449− written_form,
2450− written_keys,
2451− line,
2452− name_at,
2453− source: source.to_string(),
2454− })))
2455−}
2456−
2457−/// A line of another file (the standard library, an included file) means
2458−/// nothing in this one: the problems reported since `before` while
2459−/// evaluating the function (its body, a default) are moved to the call.
2460−fn point_at_call(
2461− ctx: &mut ParseContext,
2462− before: usize,
2463− function: &FnDef,
2464− name: &str,
2465− line: usize,
2466− source: &str,
2467−) {
2468− if function.file == ctx.current_file {
2469− return;
2470− }
2471− let defined_in = function
2472− .file
2473− .as_deref()
2474− .unwrap_or("the file being compiled");
2475− for d in &mut ctx.diagnostics[before..] {
2476− d.message = format!(
2477− "{}\n in @{} (line {} of {})",
2478− d.message, name, d.line, defined_in
2479− );
2480− d.line = line;
2481− d.column = None;
2482− d.subject = None;
2483− d.suggestion = None;
2484− d.source_line = Some(source.into());
2485− }
2486−}
2487−
2488−/// A call nested deeper than [`MAX_CALL_DEPTH`].
2489−fn too_deep(name: &str, stack: &[String], line: usize) -> Diagnostic {
2490− let message = if stack.iter().any(|n| n == name) {
2491− format!(
2492− "recursive function call to @{} goes more than {} calls deep: a function that \
2493− calls itself needs a condition that stops it (`@if`)",
2494− name, MAX_CALL_DEPTH
2495− )
2496− } else {
2497− format!(
2498− "function calls nest more than {} deep at @{} (starting with {})",
2499− MAX_CALL_DEPTH,
2500− name,
2501− stack
2502− .iter()
2503− .take(3)
2504− .map(|n| format!("@{}", n))
2505− .collect::<Vec<_>>()
2506− .join(" → ")
2507− )
2508− };
2509− Diagnostic::error(code::RECURSIVE_CALL, line, message).subject(name)
2510−}
2511−
2512−/// Mark what a function's body wrote as the call's: it gets the call's
2513−/// line, so what is reported about it points at the call, and the name of
2514−/// the function, unless a call inside the body already claimed it.
2515−fn belongs_to_call(nodes: &mut [Node], function: &str, line: usize) {
2516− fn claim(element: &mut Element, function: &str, line: usize) {
2517− element.line_num = line;
2518− element.function.get_or_insert_with(|| function.to_string());
2519− belongs_to_call(&mut element.children, function, line);
2520− }
2521− for node in nodes {
2522− match node {
2523− Node::Element(element) => claim(element, function, line),
2524− Node::Text(segments) => {
2525− for segment in segments {
2526− if let TextSegment::Inline(element) = segment {
2527− claim(element, function, line);
2528− }
2529− }
2530− }
2531− Node::Raw(_) => {}
2532− }
2533− }
2534−}
2535−
2536−/// What an inline `{@name ...}` stands for in its line of text: an
2537−/// element; the text of a function whose body is text; or, for a body with
2538−/// several roots, its nodes as a fragment.
2539−fn inline_segments(mut nodes: Vec<Node>, line: usize) -> Vec<TextSegment> {
2540− if let [Node::Element(_)] = nodes.as_slice()
2541− && let Some(Node::Element(element)) = nodes.pop()
2542− {
2543− return vec![TextSegment::Inline(element)];
2544− }
2545− if nodes.iter().all(|n| matches!(n, Node::Text(_))) {
2546− let mut segments = Vec::new();
2547− for node in nodes {
2548− if let Node::Text(run) = node {
2549− if !segments.is_empty() {
2550− segments.push(TextSegment::Plain(" ".to_string()));
2551− }
2552− segments.extend(run);
2553− }
2554− }
2555− return segments;
2556− }
2557− vec![TextSegment::Inline(Element {
2558− kind: ElementKind::Fragment,
2559− attrs: Vec::new(),
2560− argument: None,
2561− children: nodes,
2562− line_num: line,
2563− function: None,
2564− })]
2565−}
2566−
2567−/// Fill in the default of a parameter that a call leaves out, like the
2568−/// value of an attribute passed for it: variables are filled in, one
2569−/// `$name` keeps its type and one `"..."` is quoted text. It sees what the
2570−/// body sees: the names visible where the function is defined, and the
2571−/// parameters before it. Its problems are reported at the definition, once.
2572−fn fill_default(
2573− fn_def: &FnDef,
2574− param: &syntax::Param,
2575− default: &str,
2576− ctx: &mut ParseContext,
2577−) -> Value {
2578− // A default that uses a later parameter is an error in the
2579− // definition; the later one isn't bound yet, so don't report it again
2580− let later = fn_def
2581− .params
2582− .iter()
2583− .skip_while(|p| p.name != param.name)
2584− .skip(1);
2585− let names = interp::names(default);
2586− if later.clone().any(|p| names.contains(&p.name.as_str())) {
2587− return Value::empty();
2588− }
2589− let line = param.span.line;
2590− let at_head = line == fn_def.line && fn_def.source.is_some();
2591− let column =
2592− at_head.then(|| param.span.column + (param.span.end - param.span.start) - default.len());
2593− let caller = (
2594− std::mem::replace(
2595− &mut ctx.current_source,
2596− (fn_def.line, fn_def.source.clone()),
2597− ),
2598− std::mem::replace(&mut ctx.current_node, fn_def.node),
2599− );
2600− let (value, _) = ctx.slot_value(default, line, column);
2601− (ctx.current_source, ctx.current_node) = caller;
2602− value
2603−}
2604−
2605−/// Read `@page`'s attribute list and title. The page is the root element,
2606−/// and its attributes are checked like any element's: `key=value` (and a
2607−/// bare boolean HTML attribute) go on `<html>`, styles on `<body>`, and
2608−/// `favicon FILE` is its one word of htmlang's own.
2609−fn read_page(
2610− attrs: Option<&syntax::AttrList>,
2611− title: Option<&syntax::Arg>,
2612− line: usize,
2613− ctx: &mut ParseContext,
2614−) -> Page {
2615− let mut page = Page::default();
2616− if let Some(list) = attrs {
2617− let words: Vec<String> = crate::vocab::PAGE_WORDS
1719+ // Normalize body indentation so it parses from indent 0
1720+ let min_indent = fn_def
1721+ .body_lines
26181722 .iter()
2619− .map(|w| w.to_string())
2620− .collect();
2621− ctx.in_page = true;
2622− let read = parse_attr_list(&list.attrs, line, ctx, true, &words);
2623− ctx.in_page = false;
2624− // How many of each name have been read, to find where the next
2625− // one is written
2626− let mut seen: HashMap<String, usize> = HashMap::new();
2627− for attr in read {
2628− let boolean = attr.value.is_none() && crate::vocab::is_html_flag(&attr.key);
2629− // Where it is written, when it is written in the list itself
2630− let nth = seen.entry(attr.key.clone()).or_default();
2631− let column = list
2632− .attrs
2633− .iter()
2634− .filter(|token| token.key == attr.key)
2635− .nth(*nth)
2636− .map(|token| token.span.column);
2637− *nth += 1;
2638− let value = attr
2639− .quoted
2640− .as_ref()
2641− .map(|q| q.text.clone())
2642− .or(attr.value.clone());
2643− if !check_page_attr(&attr.key, attr.html, value.as_deref(), line, column, ctx) {
2644− continue;
2645− }
2646− if words.contains(&attr.key) {
2647− if page.favicon.is_some() {
2648− let diagnostic = Diagnostic::warning(
2649− code::DUPLICATE_ATTRIBUTE,
2650− line,
2651− "duplicate attribute 'favicon': the later one wins".to_string(),
2652− )
2653− .subject("favicon");
2654− ctx.diagnostics.push(at_attribute(diagnostic, column, ctx));
2655− }
2656− // The file itself goes into the page when it can be read
2657− // (relative to the file); otherwise it is linked
2658− page.favicon = value.map(|path| match std::fs::read(ctx.resolve(&path)) {
2659− Ok(data) => crate::codegen::data_uri(&path, &data),
2660− Err(_) => path,
2661− });
2662− } else if attr.html || boolean {
2663− page.html_attrs.push(attr);
2664− } else {
2665− page.styles.push(attr);
2666− }
2667− }
2668− }
2669− page.title = match title {
2670− Some(title) => ctx.interpolate_text(&title.raw, title.span.line, Some(title.span.column)),
2671− None => String::new(),
2672− };
2673− page
2674−}
2675−
2676−/// `@page`'s own rules for one of its attributes, checked where the
2677−/// `@page` runs and where it doesn't (a layout that isn't called): its
2678−/// word is written `favicon FILE`, and `inline` belongs to `@image`.
2679−/// Returns whether the attribute can be used (a `favicon` with its file,
2680−/// or any other attribute but `inline`).
2681−fn check_page_attr(
2682− key: &str,
2683− html: bool,
2684− value: Option<&str>,
2685− line: usize,
2686− column: Option<usize>,
2687− ctx: &mut ParseContext,
2688−) -> bool {
2689− let report = |ctx: &mut ParseContext, diagnostic: Diagnostic| {
2690− let diagnostic = at_attribute(diagnostic, column, ctx);
2691− ctx.diagnostics.push(diagnostic);
2692− };
2693− if crate::vocab::PAGE_WORDS.contains(&key) {
2694− if html {
2695− report(
2696− ctx,
2697− Diagnostic::error(
2698− code::PARAMETER_FORM,
2699− line,
2700− format!(
2701− "'{0}' is @page's own word, not an HTML attribute: write `{0} {1}`",
2702− key,
2703− value.filter(|v| !v.is_empty()).unwrap_or("FILE")
2704− ),
2705− )
2706− .subject(format!("{}=", key))
2707− .suggest(Some(format!("{} ", key))),
2708− );
2709− }
2710− if value.is_none_or(|v| v.trim().is_empty()) {
2711− report(
2712− ctx,
2713− Diagnostic::error(
2714− code::MISSING_VALUE,
2715− line,
2716− format!("'{0}' needs its file: `{0} favicon.png`", key),
2717− )
2718− .subject(key),
2719− );
2720− return false;
2721− }
2722− return true;
2723− }
2724− if !html && crate::vocab::base_attribute(key) == "inline" {
2725− report(
2726− ctx,
2727− Diagnostic::error(
2728− code::UNEXPECTED_ARGUMENT,
2729− line,
2730− "`inline` puts an image's file into the page, and @page has none: it only \
2731− goes on @image"
2732− .to_string(),
2733− )
2734− .subject("inline"),
2735− );
2736− return false;
2737− }
2738− true
2739−}
2740−
2741−/// A parameter passed `name=value`, the form of an HTML attribute.
2742−fn parameter_form(function: &str, key: &str, value: &str, line: usize) -> Diagnostic {
2743− Diagnostic::error(
2744− code::PARAMETER_FORM,
2745− line,
2746− format!(
2747− "'{}' is a parameter of @{}: parameters are written `name value`, so write `{} {}`",
2748− key, function, key, value
2749− ),
2750− )
2751− .subject(format!("{}=", key))
2752− .suggest(Some(format!("{} ", key)))
2753−}
2754−
2755−/// A call that leaves out a parameter without a default.
2756−fn missing_parameter(
2757− function: &str,
2758− param: &str,
2759− line: usize,
2760− column: Option<usize>,
2761−) -> Diagnostic {
2762− let diagnostic = Diagnostic::error(
2763− code::MISSING_PARAMETER,
2764− line,
2765− format!(
2766− "@{} needs '{}': the parameter has no default, so pass it as `{} VALUE`",
2767− function, param, param
2768− ),
2769− )
2770− .subject(param);
2771− match column {
2772− Some(column) => diagnostic.column(column),
2773− None => diagnostic,
2774− }
2775−}
2776−
2777−/// The column of a call's `@name`, when it is on the call's line.
2778−fn name_column(head: &syntax::Head, line: usize) -> Option<usize> {
2779− (head.name_span.line == line).then_some(head.name_span.column)
2780−}
2781−
2782−/// Define `$name`, or, for `--name`, the CSS custom property on `:root`
2783−/// (which gets quoted text with its quotes, and is read with
2784−/// `var(--name)`, never as a variable). `@let name.field value` gives the
2785−/// record `$name` that field (or the list `$name` a new item at that
2786−/// index), as a new value in this block.
2787−fn set_variable(name: &str, value: Value, line_num: usize, ctx: &mut ParseContext) {
2788− if name.starts_with("--") {
2789− let css = value
2790− .quoted_css()
2791− .map_or_else(|| value.to_string(), str::to_string);
2792− let at_line = |diagnostic: Diagnostic, ctx: &ParseContext| match &ctx.current_source {
2793− (current, Some(text)) if *current == line_num => diagnostic.source(text.clone()),
2794− _ => diagnostic,
2795− };
2796− // `:root` is one place for the whole page: a declaration inside a
2797− // block (an element, a loop, a function's body) would not be
2798− // kept to it, and each run would replace the last
2799− if ctx.env.frames.len() > FILE_FRAMES {
2800− let diagnostic = Diagnostic::error(
2801− code::INVALID_DEFINITION,
2802− line_num,
2803− format!(
2804− "`@let {name}` declares {name} on :root, for the whole page, so it goes at \
2805− the top level of the file: to set it on an element and what is inside \
2806− it, write `[{name} value]` on that element"
2807− ),
2808− )
2809− .subject(name);
2810− ctx.push_once(at_line(diagnostic, ctx));
2811− return;
2812− }
2813− match css_breakout(&css) {
2814− Some(reason) => {
2815− let diagnostic = Diagnostic::error(
2816− code::INVALID_VALUE,
2817− line_num,
2818− format!(
2819− "the value of '{}' has {}: `{}` can't be written into the page's CSS",
2820− name, reason, css
2821− ),
2822− )
2823− .subject(css.as_str());
2824− ctx.push_once(at_line(diagnostic, ctx));
2825− }
2826− None => match ctx.css_vars.iter_mut().find(|(n, _)| n == name) {
2827− Some(declared) => {
2828− let diagnostic = Diagnostic::warning(
2829− code::DUPLICATE_ATTRIBUTE,
2830− line_num,
2831− format!(
2832− "{name} is declared again: :root has one value for the whole page, \
2833− so every element gets this one, also above this line (a theme \
2834− redefines a token on an element: `[dark:{name} {css}]`)"
2835− ),
2836− )
2837− .subject(name);
2838− declared.1 = css;
2839− ctx.push_once(at_line(diagnostic, ctx));
2840− }
2841− None => ctx.css_vars.push((name.to_string(), css)),
2842− },
2843− }
2844− return;
2845− }
2846− let mut path = name.split('.');
2847− let root = path.next().unwrap_or(name);
2848− let fields: Vec<&str> = path.collect();
2849− let value = match fields.is_empty() {
2850− true => value,
2851− false => match with_field(ctx.env.value(root).cloned(), root, &fields, value) {
2852− Ok(value) => value,
2853− Err(message) => {
2854− let diagnostic =
2855− Diagnostic::error(code::INVALID_DEFINITION, line_num, message).subject(name);
2856− let diagnostic = match &ctx.current_source {
2857− (current, Some(text)) if *current == line_num => {
2858− diagnostic.source(text.clone())
2859− }
2860− _ => diagnostic,
2861− };
2862− ctx.push_once(diagnostic);
2863− // Reported: the name keeps what it held
2864− ctx.let_lines.entry(root.to_string()).or_insert(line_num);
2865− return;
2866− }
2867− },
2868− };
2869− ctx.bind(root, value);
2870− ctx.let_lines.entry(root.to_string()).or_insert(line_num);
2871−}
2872−
2873−/// `value` (the value of `$name`) with the field at `path` set to `new`:
2874−/// a record's field, or the item of a list at an index it has. A name
2875−/// without a value, or one whose value is empty (a field a record doesn't
2876−/// have), becomes a record; any other value has no fields to set.
2877−fn with_field(
2878− value: Option<Value>,
2879− name: &str,
2880− path: &[&str],
2881− new: Value,
2882−) -> Result<Value, String> {
2883− let Some((field, rest)) = path.split_first() else {
2884− return Ok(new);
2885− };
2886− let inner = format!("{}.{}", name, field);
2887− match value {
2888− Some(Value::Record(fields)) => {
2889− let mut fields = fields.as_ref().clone();
2890− match fields.iter().position(|(key, _)| key == field) {
2891− Some(i) => {
2892− let old = std::mem::replace(&mut fields[i].1, Value::empty());
2893− fields[i].1 = with_field(Some(old), &inner, rest, new)?;
2894− }
2895− None => fields.push((field.to_string(), with_field(None, &inner, rest, new)?)),
2896− }
2897− Ok(Value::Record(Rc::new(fields)))
2898− }
2899− Some(Value::List(list)) => {
2900− let count = list.items.len();
2901− let Some(i) = field.parse::<usize>().ok().filter(|&i| i < count) else {
2902− return Err(format!(
2903− "`${}` is {}, so `.{}` isn't one of its items (they are `.0` to `.{}`)",
2904− name,
2905− Value::List(list).describe(),
2906− field,
2907− count.saturating_sub(1)
2908− ));
2909− };
2910− let mut items = list.items.as_ref().clone();
2911− let old = std::mem::replace(&mut items[i], Value::empty());
2912− items[i] = with_field(Some(old), &inner, rest, new)?;
2913− // Its items changed, so it no longer prints as written
2914− Ok(Value::list(items))
2915− }
2916− None => Ok(Value::Record(Rc::new(vec![(
2917− field.to_string(),
2918− with_field(None, &inner, rest, new)?,
2919− )]))),
2920− Some(value) if value.to_string().is_empty() => with_field(None, name, path, new),
2921− Some(value) => Err(format!(
2922− "`@let {}.{}` sets a field of a record, but `${}` is {} (`{}`), which has no fields",
2923− name,
2924− path.join("."),
2925− name,
2926− value.describe(),
2927− value
2928− )),
2929− }
2930−}
2931−
2932−/// What a verbatim directive holds (`@head`, `@style`, `@raw`): the rest
2933−/// of its line (`@style .a { color: red }`), or else its indented block.
2934−/// The two together are a syntax error, reported by the tree; the line
2935−/// wins.
2936−fn verbatim_content(node: &syntax::Node) -> String {
2937− match node.directive().map(|d| &d.args) {
2938− Some(DirectiveArgs::Text(Some(line))) => format!("{}\n", line.raw),
2939− _ => verbatim_text(&node.children),
2940− }
2941−}
2942−
2943−/// The text of a verbatim body (`@head`, `@style`, `@markdown`, `@raw`).
2944−fn verbatim_text(children: &[syntax::Node]) -> String {
2945− let mut text = String::new();
2946− for child in children {
2947− if let NodeKind::Verbatim(body) = &child.kind {
2948− text.push_str(&body.text);
2949− text.push('\n');
2950− }
2951− }
2952− text
2953−}
2954−
2955−// ---------------------------------------------------------------------------
2956−// @children replacement
2957−// ---------------------------------------------------------------------------
2958−
2959−fn replace_children_and_slots(
2960− nodes: Vec<Node>,
2961− caller_children: &[Node],
2962− slot_contents: &HashMap<String, Vec<Node>>,
2963−) -> Vec<Node> {
2964− let mut result = Vec::new();
2965− for node in nodes {
2966− match node {
2967− Node::Element(elem) if elem.kind == ElementKind::Children => {
2968− if caller_children.is_empty() && !elem.children.is_empty() {
2969− // Use @children's own children as default/fallback content
2970− result.extend(elem.children);
2971− } else {
2972− result.extend(caller_children.iter().cloned());
2973− }
2974− }
2975− Node::Element(elem) if matches!(&elem.kind, ElementKind::Slot(name) if !name.is_empty()) =>
2976− {
2977− if let ElementKind::Slot(ref name) = elem.kind {
2978− if let Some(content) = slot_contents.get(name) {
2979− result.extend(content.iter().cloned());
2980− }
2981− // If no content provided for this slot, use the slot's own children as default
2982− else if !elem.children.is_empty() {
2983− result.extend(elem.children);
2984− }
2985− }
2986− }
2987− Node::Element(mut elem) => {
2988− elem.children =
2989− replace_children_and_slots(elem.children, caller_children, slot_contents);
2990− result.push(Node::Element(elem));
2991− }
2992− other => result.push(other),
2993− }
2994− }
2995− result
2996−}
2997−
2998−// ---------------------------------------------------------------------------
2999−// Where @slot and @children are written
3000−// ---------------------------------------------------------------------------
3001−
3002−/// The files each `@include` line brought in, by the line's node id, with
3003−/// the include chain that leads to each.
3004−type IncludedBy = HashMap<usize, Vec<(Rc<Tree>, String)>>;
3005−
3006−/// The lines of the files an `@include` line brings in, and the include
3007−/// chain of each (for diagnostics).
3008−type Included<'a, 'f> = &'f dyn Fn(&syntax::Node) -> Vec<(&'a [syntax::Node], Option<&'a str>)>;
3009−
3010−/// Whether `name` is a function here: defined so far, or anywhere in the
3011−/// file and the files it includes.
3012−fn is_function(name: &str, ctx: &ParseContext) -> bool {
3013− ctx.env.function(name).is_some() || ctx.namespace.contains(name)
3014−}
3015−
3016−/// Whether `name` is one slot name: letters, digits, `-` and `_`,
3017−/// starting with a letter (like a function's name).
3018−fn is_slot_name(name: &str) -> bool {
3019− name.chars().next().is_some_and(char::is_alphabetic)
3020− && name
3021− .chars()
3022− .all(|c| c.is_alphanumeric() || c == '-' || c == '_')
3023−}
3024−
3025−/// What a `@slot` or `@children` line is written in.
3026−#[derive(Clone, Copy)]
3027−enum Place<'a> {
3028− /// The top of a file or of a function's body, or a built-in element
3029− /// (by its name).
3030− Element(Option<&'a str>),
3031− /// A call: its content.
3032− Call,
3033−}
3034−
3035−/// Where a line is, for [`slot_uses`].
3036−#[derive(Clone, Copy)]
3037−struct At<'a> {
3038− /// Inside a function's body.
3039− body: bool,
3040− place: Place<'a>,
3041− /// Outside a body: the call (and its line) whose content it is in.
3042− call: Option<(&'a str, usize)>,
3043− /// The include chain of the file it is in, when that isn't the file
3044− /// being compiled.
3045− file: Option<&'a str>,
3046−}
3047−
3048−impl At<'_> {
3049− /// The top of a file, or of a function's body.
3050− fn top(body: bool) -> Self {
3051− At {
3052− body,
3053− place: Place::Element(None),
3054− call: None,
3055− file: None,
3056− }
3057− }
3058−}
3059−
3060−/// What [`slot_uses`] knows about the names and files it walks.
3061−struct Scan<'a, 'f> {
3062− is_function: &'f dyn Fn(&str) -> bool,
3063− included: Included<'a, 'f>,
3064− /// Visit the bodies of the functions defined in the lines too.
3065− into_lets: bool,
3066−}
3067−
3068−/// A `@slot` or `@children` written in a file, and where.
3069−struct SlotUse<'a> {
3070− node: &'a syntax::Node,
3071− head: &'a syntax::Head,
3072− /// The text after it, which is a slot's name; `None` when it isn't
3073− /// the last head of its chain.
3074− text: Option<&'a syntax::Text>,
3075− /// Written inline in a line of text, `{@slot x}`.
3076− inline: bool,
3077− at: At<'a>,
3078−}
3079−
3080−impl SlotUse<'_> {
3081− fn is_slot(&self) -> bool {
3082− self.head.name == "slot"
3083− }
3084−
3085− /// The slot's name as written.
3086− fn name(&self) -> &str {
3087− self.text.map_or("", |t| t.raw.trim())
3088− }
3089−
3090− /// A `@slot NAME` that marks a place in a function's body (not one
3091− /// that fills a slot of a call).
3092− fn declares(&self) -> bool {
3093− self.is_slot() && !self.inline && !matches!(self.at.place, Place::Call)
3094− }
3095−}
3096−
3097−/// Where each `@slot` and `@children` in `block` is written. A `@slot`
3098−/// directly under a call (under its `@if`, `@else` and `@each` too) fills
3099−/// one of its slots; anywhere else in a function's body it declares one.
3100−/// An included file's lines are where its `@include` is.
3101−fn slot_uses<'a>(
3102− block: &'a [syntax::Node],
3103− at: At<'a>,
3104− scan: &Scan<'a, '_>,
3105− out: &mut Vec<SlotUse<'a>>,
3106−) {
3107− fn inline<'a>(
3108− text: &'a syntax::Text,
3109− node: &'a syntax::Node,
3110− at: At<'a>,
3111− scan: &Scan<'a, '_>,
3112− out: &mut Vec<SlotUse<'a>>,
3113− ) {
3114− for segment in &text.segments {
3115− if let Segment::Inline(inline_element) = segment {
3116− let head = &inline_element.head;
3117− if matches!(head.name.as_str(), "slot" | "children")
3118− && !(scan.is_function)(&head.name)
3119− {
3120− out.push(SlotUse {
3121− node,
3122− head,
3123− text: inline_element.text.as_ref(),
3124− inline: true,
3125− at,
3126− });
3127− }
3128− if let Some(text) = &inline_element.text {
3129− inline(text, node, at, scan, out);
3130− }
3131− }
3132− }
3133− }
3134− for node in block {
3135− match &node.kind {
3136− NodeKind::Directive(directive) => match &directive.args {
3137− DirectiveArgs::Let(def) if matches!(def.form, LetForm::Function(_)) => {
3138− if scan.into_lets {
3139− let top = At {
3140− file: at.file,
3141− ..At::top(true)
3142− };
3143− slot_uses(&node.children, top, scan, out);
3144− }
3145− }
3146− // A value's body is an error of its own
3147− DirectiveArgs::Let(_) => {}
3148− _ if directive.spec.body == BodyKind::Verbatim => {}
3149− // `@if`, `@else` and `@each` put their lines in place, and
3150− // `@include` its file's; the lines under a directive that
3151− // takes no body are its siblings
3152− _ => {
3153− for (lines, file) in (scan.included)(node) {
3154− slot_uses(lines, At { file, ..at }, scan, out);
3155− }
3156− slot_uses(&node.children, at, scan, out);
3157− }
3158− },
3159− NodeKind::Element(line) => {
3160− let mut at = at;
3161− let last = line.chain.len() - 1;
3162− for (i, head) in line.chain.iter().enumerate() {
3163− let text = if i == last { line.text.as_ref() } else { None };
3164− let function = (scan.is_function)(&head.name);
3165− if !function && matches!(head.name.as_str(), "slot" | "children") {
3166− out.push(SlotUse {
3167− node,
3168− head,
3169− text,
3170− inline: false,
3171− at,
3172− });
3173− } else if let Some(text) = text {
3174− inline(text, node, at, scan, out);
3175− }
3176− if function {
3177− at.place = Place::Call;
3178− if !at.body {
3179− at.call = Some((&head.name, node.span.line));
3180− }
3181− } else {
3182− at.place = Place::Element(Some(&head.name));
3183− }
3184− }
3185− slot_uses(&node.children, at, scan, out);
3186− }
3187− NodeKind::Text(text) => {
3188− inline(text, node, at, scan, out);
3189− slot_uses(&node.children, at, scan, out);
3190− }
3191− NodeKind::Blank | NodeKind::Comment | NodeKind::Verbatim(_) => {}
3192− }
3193− }
3194−}
3195−
3196−/// The slots a function's body declares, and whether it has a
3197−/// `@children`, when it is defined. The files its `@include` lines bring
3198−/// in count too: they are read now, since they run only at a call.
3199−fn declared_slots(body: &[syntax::Node], ctx: &mut ParseContext) -> (Vec<String>, bool) {
3200− let mut files = HashMap::new();
3201− read_includes(
3202− body,
3203− ctx.base_path.clone(),
3204− &mut Vec::new(),
3205− ctx,
3206− &mut files,
3207− );
3208− let included = |node: &syntax::Node| match files.get(&node.id) {
3209− Some(tree) => vec![(&tree.nodes[..], None)],
3210− None => Vec::new(),
3211− };
3212− let is_function = |name: &str| is_function(name, ctx);
3213− slots_of(body, &is_function, &included)
3214−}
3215−
3216−/// Read and parse the files the `@include` lines in `nodes` bring in (by
3217−/// a literal path, relative to `base`), and the files those include, by
3218−/// the node id of each `@include` line.
3219−fn read_includes(
3220− nodes: &[syntax::Node],
3221− base: Option<PathBuf>,
3222− stack: &mut Vec<PathBuf>,
3223− ctx: &mut ParseContext,
3224− files: &mut HashMap<usize, Rc<Tree>>,
3225−) {
3226− let mut includes = Vec::new();
3227− for node in nodes {
3228− node.walk(&mut |node| {
3229− if let Some(DirectiveArgs::Text(Some(path))) = node.directive().map(|d| &d.args)
3230− && node.is_directive("include")
3231− {
3232− includes.push((node.id, path.raw.clone()));
3233− }
3234− });
3235− }
3236− for (id, path) in includes {
3237− let path = path.trim_matches('"');
3238− if path.contains('$') {
3239− continue;
3240− }
3241− let resolved = match &base {
3242− Some(base) => base.join(path),
3243− None => PathBuf::from(path),
3244− };
3245− if stack.contains(&resolved) {
3246− continue;
3247− }
3248− let Ok(text) = ctx.read_file(&resolved) else {
3249− continue;
1723+ .map(|l| l.indent)
1724+ .min()
1725+ .unwrap_or(0);
1726+ let adjusted: Vec<Line> = fn_def
1727+ .body_lines
1728+ .iter()
1729+ .map(|l| Line {
1730+ indent: l.indent - min_indent,
1731+ content: l.content.clone(),
1732+ line_num: l.line_num,
1733+ })
1734+ .collect();
1735+
1736+ // Parse body with params in scope
1737+ let mut body_parser = Parser {
1738+ lines: adjusted,
1739+ pos: 0,
32501740 };
3251− let tree = ctx.parse_tree(&text);
3252− stack.push(resolved.clone());
3253− let parent = resolved.parent().map(Path::to_path_buf);
3254− read_includes(&tree.nodes, parent, stack, ctx, files);
3255− stack.pop();
3256− files.insert(id, tree);
3257− }
3258−}
1741+ let body_nodes = body_parser.parse_children(0, ctx);
32591742
3260−/// The slots a function's body declares (`@slot NAME`, in order), and
3261−/// whether it has a `@children` for the content of a call. A `@slot`
3262−/// directly under a call in the body fills that call's slot instead, so
3263−/// `is_function` says which names are functions. The files the body
3264−/// includes aren't read.
3265−pub fn function_slots(
3266− body: &[syntax::Node],
3267− is_function: &dyn Fn(&str) -> bool,
3268−) -> (Vec<String>, bool) {
3269− slots_of(body, is_function, &|_| Vec::new())
3270−}
1743+ // Restore variables and call stack
1744+ ctx.variables = saved_vars;
1745+ ctx.fn_call_stack.pop();
32711746
3272−fn slots_of<'a>(
3273− body: &'a [syntax::Node],
3274− is_function: &dyn Fn(&str) -> bool,
3275− included: Included<'a, '_>,
3276−) -> (Vec<String>, bool) {
3277− let scan = Scan {
3278− is_function,
3279− included,
3280− into_lets: false,
3281− };
3282− let mut uses = Vec::new();
3283− slot_uses(body, At::top(true), &scan, &mut uses);
3284− let mut slots: Vec<String> = Vec::new();
3285− for slot in uses.iter().filter(|u| u.declares()) {
3286− let name = slot.name();
3287− if is_slot_name(name) && !slots.iter().any(|s| s == name) {
3288− slots.push(name.to_string());
1747+ // Replace @children with caller's children and @slot with slot content
1748+ let mut result_nodes =
1749+ replace_children_and_slots(body_nodes, &caller_children, &slot_contents);
1750+
1751+ if !forwarded.is_empty() {
1752+ let mut roots = result_nodes.iter_mut().filter_map(|n| match n {
1753+ Node::Element(e) => Some(e),
1754+ _ => None,
1755+ });
1756+ match (roots.next(), roots.next()) {
1757+ (Some(root), None) => root.attrs.extend(forwarded),
1758+ _ => ctx.diagnostics.push(Diagnostic {
1759+ line: line_num,
1760+ column: None,
1761+ message: format!(
1762+ "attributes {} on @{} are not parameters, and its body has no single \
1763+ root element to receive them",
1764+ forwarded
1765+ .iter()
1766+ .map(|a| format!("'{}'", a.key))
1767+ .collect::<Vec<_>>()
1768+ .join(", "),
1769+ name
1770+ ),
1771+ severity: Severity::Warning,
1772+ source_line: Some(content.to_string()),
1773+ }),
1774+ }
32891775 }
3290− }
3291− let has_children = uses.iter().any(|u| !u.is_slot() && !u.inline);
3292− (slots, has_children)
3293−}
32941776
3295−/// The line as written, indented, when it is one physical line, so a
3296−/// column points into it.
3297−fn written_line(node: &syntax::Node) -> String {
3298− match node.line_count <= 1 {
3299− true => format!("{}{}", " ".repeat(node.indent), node.source),
3300− false => node.source.clone(),
3301− }
3302−}
1777+ // A function with a scoped @style wraps its output in the scope class
1778+ if ctx.scoped_functions.contains(name) {
1779+ let wrapper = Element {
1780+ kind: ElementKind::El,
1781+ attrs: vec![Attribute {
1782+ key: "class".to_string(),
1783+ value: Some(format!("hl-{}", name)),
1784+ html: true,
1785+ }],
1786+ argument: None,
1787+ children: result_nodes,
1788+ line_num,
1789+ };
1790+ result_nodes = vec![Node::Element(wrapper)];
1791+ }
33031792
3304−/// The lines of the files an `@include` line brought in when it ran, from
3305−/// `included_by`.
3306−fn ran_includes<'a>(
3307− included_by: &'a IncludedBy,
3308− node: &syntax::Node,
3309−) -> Vec<(&'a [syntax::Node], Option<&'a str>)> {
3310− match included_by.get(&node.id) {
3311− Some(files) => files
3312− .iter()
3313− .map(|(tree, chain)| (&tree.nodes[..], Some(chain.as_str())))
3314− .collect(),
3315− None => Vec::new(),
1793+ Ok(result_nodes)
33161794 }
3317−}
33181795
3319−/// Check where every `@slot` and `@children` of the file and the files it
3320−/// includes is written, whether or not it runs: a slot has one name, a
3321−/// function's body marks places with them, and a call fills its slots
3322−/// with `@slot` blocks directly under it. An included file's lines are
3323−/// where its `@include` is (in a body, under a call), so an `@include`
3324−/// that never ran leaves its file unchecked.
3325−fn check_slot_places(ctx: &mut ParseContext) {
3326− let trees = std::mem::take(&mut ctx.trees);
3327− let included_by = ctx.included_by.clone();
3328− let is_function = |name: &str| is_function(name, ctx);
3329− let scan = Scan {
3330− is_function: &is_function,
3331− included: &|node| ran_includes(&included_by, node),
3332− into_lets: true,
3333− };
3334− let mut uses = Vec::new();
3335− for (tree, _) in trees.iter().filter(|(_, chain)| chain.is_none()) {
3336− slot_uses(&tree.nodes, At::top(false), &scan, &mut uses);
3337− }
3338− let found: Vec<Diagnostic> = uses
3339− .iter()
3340− .filter_map(|slot| {
3341− let mut d = slot_problem(slot)?;
3342− if d.column.is_none() {
3343− d = d.column(slot.head.name_span.column);
3344− }
3345− d = d.source(written_line(slot.node));
3346− if let Some(file) = slot.at.file {
3347− d.message = format!("{}\n in {}", d.message, file);
3348− }
3349− Some(d)
3350− })
3351− .collect();
3352− ctx.diagnostics.extend(found);
3353− ctx.trees = trees;
3354−}
1796+ fn parse_element_line(
1797+ &mut self,
1798+ content: &str,
1799+ current_indent: usize,
1800+ line_num: usize,
1801+ ctx: &mut ParseContext,
1802+ ) -> Result<Node, ParseError> {
1803+ let segments = split_chain(content);
33551804
3356−/// What is wrong with a `@slot` or `@children` where it is written.
3357−fn slot_problem(slot: &SlotUse) -> Option<Diagnostic> {
3358− let line = slot.node.span.line;
3359− let what = if slot.is_slot() {
3360− match slot.name() {
3361− "" => "@slot".to_string(),
3362− name => format!("@slot {}", name),
3363− }
3364− } else {
3365− "@children".to_string()
3366− };
3367− if slot.inline {
3368− return Some(Diagnostic::error(
3369− code::MISPLACED_SLOT,
3370− line,
3371− format!(
3372− "{} goes on a line of its own: inline in text it marks and fills nothing",
3373− what
3374− ),
3375− ));
3376− }
3377− if let Some(list) = &slot.head.attrs {
3378− return Some(
3379− Diagnostic::error(
3380− code::UNEXPECTED_ARGUMENT,
3381− line,
3382− format!(
3383− "{} takes no attributes: it is replaced by content, so style the \
3384− element around it",
3385− what
3386− ),
3387− )
3388− .column(list.span.column),
3389− );
3390− }
3391− if slot.is_slot() {
3392− let name = slot.name();
3393− if name.is_empty() {
3394− return Some(Diagnostic::error(
3395− code::MISSING_ARGUMENT,
3396− line,
3397− "@slot needs a name: `@slot footer` (the caller's content without a \
3398− name goes where `@children` is)"
3399− .to_string(),
3400− ));
3401− }
3402− if !is_slot_name(name) {
3403− let joined = name.split_whitespace().collect::<Vec<_>>().join("-");
3404− let suggestion = is_slot_name(&joined).then_some(joined);
3405− let column = slot.text.map(|t| t.span.column);
3406− let d = Diagnostic::error(
3407− code::INVALID_SLOT_NAME,
3408− line,
3409− format!(
3410− "'{}' is not a slot name: a slot's name is one word of letters, digits, \
3411− `-` and `_`, starting with a letter, and its content goes on the lines \
3412− under it",
3413− name
3414− ),
3415− )
3416− .subject(name)
3417− .suggest(suggestion);
3418− return Some(match column {
3419− Some(column) => d.column(column),
3420− None => d,
3421− });
1805+ // Parse each segment into an Element
1806+ let mut elements: Vec<Element> = Vec::new();
1807+ for seg in &segments {
1808+ let elem = parse_single_element(seg.trim(), line_num, ctx)?;
1809+ elements.push(elem);
34221810 }
3423− if matches!(slot.at.place, Place::Call) || slot.at.body {
3424− return None;
1811+
1812+ // Parse indented children (belong to the innermost element)
1813+ let children = self.parse_children(current_indent + 1, ctx);
1814+
1815+ // Build chain right-to-left: rightmost gets children, each wraps the next
1816+ let mut current_children = children;
1817+ for mut elem in elements.into_iter().rev() {
1818+ elem.children.extend(current_children);
1819+ current_children = vec![Node::Element(elem)];
34251820 }
3426− let message = match (slot.at.call, slot.at.place) {
3427− (Some((call, call_line)), Place::Element(Some(element))) => format!(
3428− "{} is inside @{}, so it fills nothing: a @slot block that fills a slot of \
3429− @{} (line {}) goes directly under the call",
3430− what, element, call, call_line
3431− ),
3432− _ => format!(
3433− "{} is outside a function's body: `@slot NAME` marks a place in a body \
3434− (`@let @name`), and directly under a call it fills one",
3435− what
3436− ),
3437− };
3438− return Some(Diagnostic::error(code::MISPLACED_SLOT, line, message));
3439− }
3440− if slot.at.body {
3441− return None;
3442− }
3443− let message = match slot.at.call {
3444− Some((call, _)) => format!(
3445− "@children is outside a function's body, so it stands for nothing: the content \
3446− for @{} is written directly under the call",
3447− call
3448− ),
3449− None => "@children is outside a function's body: it marks where a body puts the \
3450− content of each call"
3451− .to_string(),
3452− };
3453− Some(Diagnostic::error(code::MISPLACED_SLOT, line, message))
3454−}
34551821
3456−/// A `@slot NAME` block that fills a slot of a call.
3457−struct Filler<'a> {
3458− node: &'a syntax::Node,
3459− text: &'a syntax::Text,
3460− /// The include chain of the file it is in, when that isn't the file
3461− /// being compiled.
3462− file: Option<&'a str>,
1822+ current_children.into_iter().next().ok_or(ParseError {
1823+ line: line_num,
1824+ message: "element chain produced no nodes (this is a parser bug)".to_string(),
1825+ })
1826+ }
34631827}
34641828
3465−/// Whether `@slot` is the built-in element here, and not a function
3466−/// defined so far that took its name.
3467−fn slot_is_built_in(ctx: &ParseContext) -> bool {
3468− ctx.env.function("slot").is_none()
3469−}
1829+// ---------------------------------------------------------------------------
1830+// @children replacement
1831+// ---------------------------------------------------------------------------
34701832
3471−/// The `@slot NAME` blocks directly under a call, in `block` (under its
3472−/// `@if`, `@else` and `@each` too, and in the files its `@include` lines
3473−/// brought in).
3474−fn fillers<'a>(
3475− block: &'a [syntax::Node],
3476− file: Option<&'a str>,
3477− included: &'a IncludedBy,
3478− out: &mut Vec<Filler<'a>>,
3479−) {
3480− for node in block {
3481− match &node.kind {
3482− NodeKind::Directive(directive)
3483− if matches!(directive.name(), "if" | "else" | "each") =>
3484− {
3485− fillers(&node.children, file, included, out);
3486− }
3487− NodeKind::Directive(directive) if directive.name() == "include" => {
3488− for (lines, file) in ran_includes(included, node) {
3489− fillers(lines, file, included, out);
1833+fn replace_children_and_slots(
1834+ nodes: Vec<Node>,
1835+ caller_children: &[Node],
1836+ slot_contents: &HashMap<String, Vec<Node>>,
1837+) -> Vec<Node> {
1838+ let mut result = Vec::new();
1839+ for node in nodes {
1840+ match node {
1841+ Node::Element(elem) if elem.kind == ElementKind::Children => {
1842+ if caller_children.is_empty() && !elem.children.is_empty() {
1843+ // Use @children's own children as default/fallback content
1844+ result.extend(elem.children);
1845+ } else {
1846+ result.extend(caller_children.iter().cloned());
34901847 }
34911848 }
3492− NodeKind::Element(line) if line.chain.len() == 1 && line.chain[0].name == "slot" => {
3493− if let Some(text) = &line.text {
3494− out.push(Filler { node, text, file });
1849+ Node::Element(elem) if matches!(&elem.kind, ElementKind::Slot(name) if !name.is_empty()) =>
1850+ {
1851+ if let ElementKind::Slot(ref name) = elem.kind {
1852+ if let Some(content) = slot_contents.get(name) {
1853+ result.extend(content.iter().cloned());
1854+ }
1855+ // If no content provided for this slot, use the slot's own children as default
1856+ else if !elem.children.is_empty() {
1857+ result.extend(elem.children);
1858+ }
34951859 }
34961860 }
3497− _ => {}
3498− }
3499− }
3500−}
3501−
3502−/// Whether `block`, the lines under a call, holds content other than
3503−/// `@slot` blocks (under `@if`, `@else` and `@each` too): text, an
3504−/// element, raw HTML, Markdown or an included file. For code that doesn't
3505−/// run.
3506−fn holds_content(block: &[syntax::Node], ctx: &ParseContext) -> bool {
3507− block.iter().any(|node| match &node.kind {
3508− NodeKind::Directive(directive) => match directive.name() {
3509− "if" | "else" | "each" => holds_content(&node.children, ctx),
3510− name => matches!(name, "raw" | "markdown" | "include"),
3511− },
3512− NodeKind::Element(line) => {
3513− line.chain[0].name != "slot" || !slot_is_built_in(ctx) || line.chain.len() > 1
3514− }
3515− NodeKind::Text(_) => true,
3516− _ => false,
3517− })
3518−}
3519−
3520−/// Check the `@slot NAME` blocks passed to each call of a line against
3521−/// the slots its function declares. `calls` has the function of each head
3522−/// of the chain that is a call.
3523−fn check_fillers(
3524− node: &syntax::Node,
3525− element: &syntax::ElementLine,
3526− calls: &[Option<(String, Rc<FnDef>)>],
3527− ctx: &mut ParseContext,
3528−) {
3529− if !slot_is_built_in(ctx) {
3530− return;
3531− }
3532− let included = ctx.included_by.clone();
3533− let last = element.chain.len() - 1;
3534− for (i, call) in calls.iter().enumerate() {
3535− let Some((name, function)) = call else {
3536− continue;
3537− };
3538− let mut found = Vec::new();
3539− if i == last {
3540− fillers(&node.children, None, &included, &mut found);
3541− } else if i + 1 == last
3542− && element.chain[last].name == "slot"
3543− && let Some(text) = &element.text
3544− {
3545− // `@card > @slot footer`
3546− found.push(Filler {
3547− node,
3548− text,
3549− file: None,
3550− });
3551− }
3552− for filler in found {
3553− let slot = filler.text.raw.trim();
3554− if !is_slot_name(slot) || function.slots.iter().any(|s| s == slot) {
3555− continue;
3556− }
3557− let mut d = unknown_slot(name, slot, &function.slots, filler.text.span.line)
3558− .column(filler.text.span.column)
3559− .source(written_line(filler.node));
3560− if let Some(file) = filler.file {
3561− d.message = format!("{}\n in {}", d.message, file);
1861+ Node::Element(mut elem) => {
1862+ elem.children =
1863+ replace_children_and_slots(elem.children, caller_children, slot_contents);
1864+ result.push(Node::Element(elem));
35621865 }
3563− ctx.push_once(d);
1866+ other => result.push(other),
35641867 }
35651868 }
3566−}
3567−
3568−/// A `@slot NAME` block for a slot the function doesn't declare.
3569−fn unknown_slot(function: &str, slot: &str, slots: &[String], line: usize) -> Diagnostic {
3570− let candidates: Vec<&str> = slots.iter().map(String::as_str).collect();
3571− let suggestion = suggest_closest(slot, &candidates);
3572− let message = match (slots.is_empty(), suggestion) {
3573− (true, _) => format!(
3574− "@{} has no slot '{}': its body declares no slots (`@slot NAME`)",
3575− function, slot
3576− ),
3577− (false, Some(close)) => format!(
3578− "@{} has no slot '{}', did you mean '{}'? (its slots: {})",
3579− function,
3580− slot,
3581− close,
3582− slots.join(", ")
3583− ),
3584− (false, None) => format!(
3585− "@{} has no slot '{}' (its slots: {})",
3586− function,
3587− slot,
3588− slots.join(", ")
3589− ),
3590− };
3591− Diagnostic::error(code::UNKNOWN_SLOT, line, message)
3592− .subject(slot)
3593− .suggest(suggestion)
3594−}
3595−
3596−/// Content passed to a function whose body has no `@children`.
3597−fn no_children(function: &str, line: usize, column: Option<usize>) -> Diagnostic {
3598− let d = Diagnostic::error(
3599− code::UNEXPECTED_CONTENT,
3600− line,
3601− format!(
3602− "@{0} takes no content: its body has no `@children`, so the text and lines \
3603− passed to it would be dropped (pass text as a parameter, `@{0} [name value]`, \
3604− or add `@children` to the body)",
3605− function
3606− ),
3607− )
3608− .subject(function);
3609− match column {
3610− Some(column) => d.column(column),
3611− None => d,
3612− }
1869+ result
36131870}
36141871
36151872// ---------------------------------------------------------------------------
36161873// Element parsing
36171874// ---------------------------------------------------------------------------
36181875
3619−/// Build the element for `@name [attrs] text` (on its own line, in a chain,
3620−/// or inline in text).
1876+fn extract_element_name(content: &str) -> &str {
1877+ let without_at = &content[1..];
1878+ match without_at.find([' ', '[']) {
1879+ Some(i) => &without_at[..i],
1880+ None => without_at,
1881+ }
1882+}
1883+
36211884fn parse_single_element(
3622− head: &syntax::Head,
3623− text: Option<&syntax::Text>,
1885+ content: &str,
36241886 line_num: usize,
36251887 ctx: &mut ParseContext,
36261888) -> Result<Element, ParseError> {
3627− let kind = parse_element_kind(&head.name, line_num, ctx)?;
3628− let mut attrs = head.attrs.as_ref().map_or_else(Vec::new, |list| {
3629− parse_attr_list(&list.attrs, line_num, ctx, true, &[])
3630− });
3631−
3632− // The leading argument: for an element whose row names a leading
3633− // attribute (`@link`'s href, `@image`'s src, `@form`'s action, ...),
3634− // the first token of the text fills it, split before anything is
3635− // filled in, and the rest is content (an error on an element without
3636− // content). `@slot`'s whole text is its name. Any other element's text
3637− // is content, parsed like any line of text, as in `@el [padding 8]
3638− // Hello` or `@h2 Meet {@text htmlang}`; its layout decides how it
3639− // combines with the lines under it.
3640− let mut children = Vec::new();
3641− let mut argument = None;
3642− let leading = kind.arg().attributes();
3643− match text {
3644− Some(text) if !leading.is_empty() => {
3645− let (token, rest) = text.split_leading();
3646− let given = attrs
3647− .iter()
3648− .find(|a| a.html && leading.contains(&a.key.as_str()))
3649− .map(|a| (a.key.clone(), a.value.clone().unwrap_or_default()));
3650− if let Some((key, value)) = given {
3651− // The attribute wins; the text is content, as if the
3652− // element had no leading argument
3653− ctx.push_once(leading_twice(&kind, &token, &key, &value, text, ctx));
3654− if !takes_no_text(&kind) {
3655− children.push(Node::Text(text_segments(text, ctx)));
3656− }
3657− } else if let Some(d) = bad_leading_token(&kind, &token, &text.raw, ctx) {
3658− // Nothing is taken as the argument; the line is content
3659− ctx.push_once(d);
3660− if !takes_no_text(&kind) {
3661− children.push(Node::Text(text_segments(text, ctx)));
3662− }
3663− } else {
3664− let column = Some(token.span.column);
3665− if let Some(d) = text_as_url(&kind, &token, ctx) {
3666− ctx.push_once(d);
3667− }
3668− argument = Some(
3669− ctx.fill_value(&token.raw, text.span.line, column, Sink::Text)
3670− .0,
3671− );
3672− if let Some(rest) = rest {
3673− if let Some(d) = chain_after_argument(&kind, &token.raw, &rest, ctx) {
3674− ctx.push_once(d);
3675− }
3676− if takes_no_text(&kind) {
3677− let d = after_the_leading_argument(&kind, &token.raw, &rest);
3678− let d = at_attribute(d, Some(rest.span.column), ctx);
3679− ctx.push_once(d);
3680− } else {
3681− children.push(Node::Text(text_segments(&rest, ctx)));
1889+ let (kind, rest) = if content.starts_with('[') {
1890+ // Implicit @el
1891+ (ElementKind::El, content.to_string())
1892+ } else if let Some(without_at) = content.strip_prefix('@') {
1893+ match without_at.find([' ', '[']) {
1894+ Some(i) => {
1895+ let kind_str = &without_at[..i];
1896+ let rest = if without_at.as_bytes()[i] == b'[' {
1897+ without_at[i..].to_string()
1898+ } else {
1899+ without_at[i + 1..].to_string()
1900+ };
1901+ match parse_element_kind(kind_str, line_num) {
1902+ Ok(kind) => (kind, rest),
1903+ Err(mut e) => {
1904+ // Also suggest user-defined functions
1905+ if let Some(fn_suggestion) = suggest_fn_name(kind_str, ctx) {
1906+ e.message =
1907+ format!("{}, or did you mean @{}?", e.message, fn_suggestion);
1908+ }
1909+ return Err(e);
36821910 }
36831911 }
36841912 }
1913+ None => match parse_element_kind(without_at, line_num) {
1914+ Ok(kind) => (kind, String::new()),
1915+ Err(mut e) => {
1916+ if let Some(fn_suggestion) = suggest_fn_name(without_at, ctx) {
1917+ e.message = format!("{}, or did you mean @{}?", e.message, fn_suggestion);
1918+ }
1919+ return Err(e);
1920+ }
1921+ },
36851922 }
3686− Some(text) if matches!(kind, ElementKind::Slot(_)) => {
3687− argument =
3688− Some(ctx.interpolate_text(&text.raw, text.span.line, Some(text.span.column)));
3689− }
3690− Some(text) => children.push(Node::Text(text_segments(text, ctx))),
3691− // `@link [href=/about]`: the attribute is the leading argument, so
3692− // both forms compile the same (`@image [src=a.svg, inline]`). Not
3693− // for `@source`, whose attribute depends on where it is.
3694− None if leading.len() == 1 => {
3695− if let Some(i) = attrs.iter().position(|a| a.html && a.key == leading[0]) {
3696− argument = Some(attrs.remove(i).value.unwrap_or_default());
3697− }
1923+ } else {
1924+ return Err(ParseError {
1925+ line: line_num,
1926+ message: format!("expected @element or [attrs], got: {}", content),
1927+ });
1928+ };
1929+
1930+ // Parse optional [attrs]
1931+ let (attrs, rest) = if rest.starts_with('[') {
1932+ parse_attr_brackets(&rest, line_num, ctx)?
1933+ } else {
1934+ (Vec::new(), rest)
1935+ };
1936+
1937+ let rest = rest.trim().to_string();
1938+ track_var_refs(&rest, &mut ctx.used_variables);
1939+
1940+ // For @link, first token of rest is URL, remainder is inline text
1941+ let mut children = Vec::new();
1942+ let argument = if rest.is_empty() {
1943+ None
1944+ } else if kind == ElementKind::Link {
1945+ let rest_sub = substitute_vars(&rest, &ctx.variables);
1946+ if let Some((url, text)) = rest_sub.split_once(' ') {
1947+ let text = text.trim();
1948+ if !text.is_empty() {
1949+ children.push(Node::Text(parse_text_segments(text, ctx)));
1950+ }
1951+ Some(url.to_string())
1952+ } else {
1953+ Some(rest_sub)
36981954 }
3699− None => {}
3700− }
1955+ } else {
1956+ Some(substitute_vars(&rest, &ctx.variables))
1957+ };
37011958
37021959 // For @slot, the argument is the slot name
37031960 let kind = if let ElementKind::Slot(_) = kind {
@@ -3706,352 +1963,201 @@ fn parse_single_element(
37061963 kind
37071964 };
37081965
1966+ // Every other element treats its argument as leading text content, as
1967+ // in `@el [padding 8] Hello` or `@paragraph Read {@link /more more}`.
1968+ let argument = match argument {
1969+ Some(_) if !argument_is_special(&kind) && !renders_argument_as_text(&kind) => {
1970+ children.insert(0, Node::Text(parse_text_segments(&rest, ctx)));
1971+ None
1972+ }
1973+ other => other,
1974+ };
1975+
37091976 Ok(Element {
37101977 kind,
37111978 attrs,
37121979 argument,
37131980 children,
37141981 line_num,
3715− function: None,
37161982 })
37171983}
37181984
3719−/// Whether `node` or a line inside it calls `@name` outside any `@if`
3720−/// (in a chain, or inline in text).
3721−fn calls_unguarded(node: &syntax::Node, name: &str) -> bool {
3722− if node.is_directive("if") || node.is_directive("else") {
3723− return false;
3724− }
3725− let text_calls = |text: &syntax::Text| {
3726− text.segments
3727− .iter()
3728− .any(|s| matches!(s, Segment::Inline(inline) if inline.head.name == name))
3729− };
3730− let here = match &node.kind {
3731− NodeKind::Element(element) => {
3732− element.chain.iter().any(|head| head.name == name)
3733− || element.text.as_ref().is_some_and(text_calls)
3734− }
3735− NodeKind::Text(text) => text_calls(text),
3736− _ => false,
3737− };
3738− here || node
3739− .children
3740− .iter()
3741− .any(|child| calls_unguarded(child, name))
3742−}
3743−
3744−/// `@td [padding 8] @children`: `@children` and `@slot NAME` mark where a
3745−/// call's content goes only on a line of their own; after an element's
3746−/// attributes, or in a verbatim body, they are text.
3747−fn marker_in_text(node: &syntax::Node) -> Option<Diagnostic> {
3748− let is_marker = |text: &str| {
3749− let text = text.trim();
3750− text == "@children" || text == "@slot" || text.starts_with("@slot ")
3751− };
3752− let mut line = node.span.line;
3753− let mut source = written_line(node);
3754− let (marker, message) = match &node.kind {
3755− NodeKind::Element(element) => {
3756− let text = element.text.as_ref()?;
3757− if !is_marker(&text.raw) {
3758− return None;
3759− }
3760− let name = &element.chain.last()?.name;
3761− let marker = text.raw.trim().to_string();
3762− let message = format!(
3763− "`{marker}` after @{name}'s attributes is text: it marks where a call's content \
3764− goes only on a line of its own, so write it on the next line, indented under \
3765− @{name}"
3766− );
3767− (marker, message)
3768− }
3769− NodeKind::Verbatim(verbatim) if verbatim.escaped => {
3770− let (i, written) = verbatim
3771− .text
3772− .lines()
3773− .enumerate()
3774− .find(|(_, l)| is_marker(l))?;
3775− let marker = written.trim().to_string();
3776− line += i;
3777− source = written.to_string();
3778− let message = format!(
3779− "`{marker}` in a verbatim body is text: the body is written as it is, so it can't \
3780− hold a call's content (pass the text as a parameter instead)"
3781− );
3782− (marker, message)
3783− }
3784− _ => return None,
3785− };
3786− Some(
3787− Diagnostic::error(code::MISPLACED_SLOT, line, message)
3788− .subject(marker)
3789− .source(source),
3790− )
3791−}
3792−
3793−/// A first word that can't be a leading argument: an inline element
3794−/// (`@link {@b x} y`), or a quote that isn't closed (`@link "a b`).
3795−fn bad_leading_token(
3796− kind: &ElementKind,
3797− token: &syntax::Arg,
3798− text: &str,
3799− ctx: &ParseContext,
3800−) -> Option<Diagnostic> {
3801− let what = leading_name(kind);
3802− let name = kind.name();
3803− let message = if token.raw.starts_with("{@") {
3804− format!(
3805− "@{0} takes its {1} first, before any text: write `@{0} VALUE {2}`, or give it as \
3806− `[{1}=VALUE]`",
3807− name,
3808− what,
3809− text.trim()
3810− )
3811− } else if token.raw.starts_with('"') && syntax::quoted_string(&token.raw).is_none() {
3812− format!(
3813− "@{}'s {} starts with a `\"` that isn't closed: close it (`\"...\"`), or write \
3814− `\\\"` for a quote in the value",
3815− name, what
3816− )
3817− } else {
3818− return None;
3819− };
3820− let d = Diagnostic::error(code::UNEXPECTED_ARGUMENT, token.span.line, message)
3821− .subject(token.raw.clone());
3822− Some(at_attribute(d, Some(token.span.column), ctx))
3823−}
1985+/// Elements whose argument is not text content: a URL, a source, an action,
1986+/// or a slot name.
1987+fn argument_is_special(kind: &ElementKind) -> bool {
1988+ matches!(
1989+ kind,
1990+ ElementKind::Link | ElementKind::Image | ElementKind::Script | ElementKind::Slot(_)
1991+ ) || kind
1992+ .spec()
1993+ .is_some_and(|spec| matches!(spec.arg, TagArg::Attr(_)))
1994+}
1995+
1996+/// The directive names (without `@`) the parser recognizes, for tools such
1997+/// as the language server.
1998+pub fn known_directives() -> &'static [&'static str] {
1999+ KNOWN_DIRECTIVES
2000+}
2001+
2002+const KNOWN_DIRECTIVES: &[&str] = &[
2003+ "page",
2004+ "let",
2005+ "include",
2006+ "raw",
2007+ "keyframes",
2008+ "if",
2009+ "else",
2010+ "each",
2011+ "meta",
2012+ "head",
2013+ "style",
2014+ "warn",
2015+ "assert",
2016+ "markdown",
2017+ "data",
2018+];
38242019
3825−/// A first word taken as a URL that reads as text: a word with a capital
3826−/// and nothing a URL or a file name has, as in `@link [hx-get=/panel] Open
3827−/// panel`, whose href would be `Open`. It still is (a relative URL can be
3828−/// such a word), with a warning.
3829−fn text_as_url(kind: &ElementKind, token: &syntax::Arg, ctx: &ParseContext) -> Option<Diagnostic> {
3830− const URLS: &[&str] = &["href", "src", "srcset", "action", "data"];
3831− let word = token.raw.as_str();
3832− let reads_as_text = word.starts_with(char::is_uppercase)
3833− && !word.contains([
3834− '/', '.', ':', '#', '?', '=', '&', '%', '~', '$', '{', '\\', '"',
3835− ]);
3836− if !reads_as_text || !kind.arg().attributes().iter().any(|a| URLS.contains(a)) {
3837− return None;
2020+fn parse_element_kind(s: &str, line_num: usize) -> Result<ElementKind, ParseError> {
2021+ if let Some(kind) = ElementKind::from_name(s) {
2022+ return Ok(kind);
38382023 }
3839− let name = kind.name();
3840− let attr = leading_name(kind);
3841− let text = if takes_no_text(kind) {
3842− String::new()
3843− } else {
3844− format!(": write the {attr} before the text, or put the text on the lines under it")
3845− };
3846− let message = format!(
3847− "@{name} takes '{word}', its first word, as its {attr}{text}. A relative URL that \
3848− starts with a capital is written `./{word}`"
3849− );
3850− let d = Diagnostic::warning(code::TEXT_AS_URL, token.span.line, message).subject(word);
3851− Some(at_attribute(d, Some(token.span.column), ctx))
3852−}
3853−
3854−/// `@link /a > @image logo.png`: a `>` chains only after an element's
3855−/// name or its `[attributes]`, so after a leading argument it is text.
3856−/// Said when what follows names an element or a function.
3857−fn chain_after_argument(
3858− kind: &ElementKind,
3859− token: &str,
3860− rest: &syntax::Text,
3861− ctx: &ParseContext,
3862−) -> Option<Diagnostic> {
3863− let after = rest.raw.strip_prefix('>')?;
3864− let name_start = after.trim_start().strip_prefix('@')?;
3865− if after.len() == after.trim_start().len() {
3866− return None;
2024+ if let Some(hint) = removed_syntax_hint(&format!("@{}", s)) {
2025+ return Err(ParseError {
2026+ line: line_num,
2027+ message: hint,
2028+ });
38672029 }
3868− let name: String = name_start
3869− .chars()
3870− .take_while(|c| c.is_ascii_alphanumeric() || *c == '-')
2030+ let all_known: Vec<&str> = ElementKind::all_names()
2031+ .chain(KNOWN_DIRECTIVES.iter().copied())
38712032 .collect();
3872− if ElementKind::from_name(&name).is_none() && ctx.env.function(&name).is_none() {
3873− return None;
3874− }
3875− let attr = leading_name(kind);
3876− let d = Diagnostic::warning(
3877− code::UNEXPECTED_ARGUMENT,
3878− rest.span.line,
3879− format!(
3880− "`{}` after @{}'s {} is text, not a chain: `>` chains after an element's name or \
3881− its [attributes], so write `@{} [{}={}] {}`",
3882− rest.raw.trim_end(),
3883− kind.name(),
3884− attr,
3885− kind.name(),
3886− attr,
3887− token,
3888− rest.raw.trim_end()
3889− ),
3890− )
3891− .subject(rest.raw.trim_end());
3892− Some(at_attribute(d, Some(rest.span.column), ctx))
3893−}
3894−
3895−/// A leading argument given twice, as the first token and as its
3896−/// attribute: `@link [href=/a] About`.
3897−fn leading_twice(
3898− kind: &ElementKind,
3899− token: &syntax::Arg,
3900− key: &str,
3901− value: &str,
3902− text: &syntax::Text,
3903− ctx: &ParseContext,
3904−) -> Diagnostic {
3905− let name = kind.name();
3906− let what = leading_name(kind);
3907− // The value as one token: quoted when it is empty or has a space in it
3908− let value = if !value.is_empty() && syntax::leading_token_len(value) == value.len() {
3909− value.to_string()
3910− } else {
3911− format!("\"{}\"", value.replace('\\', "\\\\").replace('"', "\\\""))
2033+ let message = match suggest_closest(s, &all_known) {
2034+ Some(closest) => format!("unknown element @{}, did you mean @{}?", s, closest),
2035+ None => format!("unknown element @{}", s),
39122036 };
3913− let written = if takes_no_text(kind) {
3914− format!("@{} {}", name, value)
3915− } else {
3916− format!("@{} {} {}", name, value, text.raw)
3917− };
3918− let d = Diagnostic::error(
3919− code::DUPLICATE_ATTRIBUTE,
3920− text.span.line,
3921− format!(
3922− "@{} takes its first word '{}' as its {}, and it also has {}=: give it once, \
3923− as `{}`",
3924− name, token.raw, what, key, written
3925− ),
3926− )
3927− .subject(token.raw.clone());
3928− at_attribute(d, Some(token.span.column), ctx)
3929−}
3930−
3931−/// The attribute an element's leading argument fills, for messages.
3932−fn leading_name(kind: &ElementKind) -> &'static str {
3933− match kind.arg() {
3934− TagArg::Source => "srcset in @picture or src elsewhere",
3935− arg => arg.attribute(false).unwrap_or("argument"),
3936− }
2037+ Err(ParseError {
2038+ line: line_num,
2039+ message,
2040+ })
39372041}
39382042
3939−/// Whether text after an element's leading argument has nowhere to go:
3940−/// an element without content (`@image`, `@source`, ...), or `@optgroup`,
3941−/// which holds only `@option` lines, so `@optgroup Citrus fruits` would
3942−/// otherwise make `Citrus` the label and drop `fruits`.
3943−fn takes_no_text(kind: &ElementKind) -> bool {
3944− kind.layout() == Layout::Void || kind.is_tag("optgroup")
3945−}
2043+/// Directives and element names removed when the language was simplified,
2044+/// with what replaces each. `htmlang upgrade` rewrites all of them.
2045+const REMOVED_SYNTAX: &[(&str, &str)] = &[
2046+ ("@fn", "use `@let name $param` with an indented body"),
2047+ ("@define", "use `@let name [attributes]`"),
2048+ ("@mixin", "use `@let name [attributes]`"),
2049+ ("@unless", "use `@if not <condition>`"),
2050+ ("@for", "use `@each $i in 1..10`"),
2051+ ("@repeat", "use `@each $_ in 1..N`"),
2052+ (
2053+ "@switch",
2054+ "use `@match`, with `@let __switch [...]` inside a case for its attributes",
2055+ ),
2056+ ("@use", "use `@include`"),
2057+ (
2058+ "@import",
2059+ "use `@include` (a file with only definitions emits no content)",
2060+ ),
2061+ ("@with", "use `@let alias $source`"),
2062+ (
2063+ "@layout",
2064+ "make the layout a function (`@let layout` with `@children`) and call it",
2065+ ),
2066+ (
2067+ "@extends",
2068+ "make the layout a function (`@let layout` with `@children` and `@slot`), \
2069+ `@include` its file and call it",
2070+ ),
2071+ ("@scope", "write the `@scope` rule in an `@style` block"),
2072+ (
2073+ "@starting-style",
2074+ "write the `@starting-style` rule in an `@style` block",
2075+ ),
2076+ ("@css-property", "write an `@property` rule in an `@style` block"),
2077+ ("@lang", "use `@page [lang ...] Title`"),
2078+ ("@favicon", "use `@page [favicon ...] Title`"),
2079+ ("@canonical", "use `@page [canonical ...] Title`"),
2080+ ("@base", "use `@page [base ...] Title`"),
2081+ ("@og", "use `@meta og:NAME VALUE`"),
2082+ ("@debug", "use `@warn`"),
2083+ ("@svg", "use `@image [inline] file.svg`"),
2084+ ("@match", "use `@if $x == a` / `@else if $x == b` / `@else`"),
2085+ ("@case", "use `@if $x == a` / `@else if $x == b` / `@else`"),
2086+ ("@default", "use `@else` in an `@if` chain"),
2087+ ("@theme", "use a `@let --name value` line per token"),
2088+ (
2089+ "@json-ld",
2090+ "put a `<script type=\"application/ld+json\">` in `@head`",
2091+ ),
2092+ ("@font-face", "write the `@font-face` rule in an `@style` block"),
2093+ (
2094+ "@manifest",
2095+ "write a manifest.json file and link it from `@head`",
2096+ ),
2097+ ("@breakpoint", "write the media query in an `@style` block"),
2098+ ("@deprecated", "remove it"),
2099+ (
2100+ "@collection",
2101+ "use `@data $name dir/*.json` (each file becomes `$name.STEM.key`)",
2102+ ),
2103+ ("@env", "use `@data $name env:NAME [default]`"),
2104+ (
2105+ "@fetch",
2106+ "download the data before building and use `@data $name file.json`",
2107+ ),
2108+ (
2109+ "@translations",
2110+ "put each locale's strings in a JSON file and use `@data $t locales/$lang.json`",
2111+ ),
2112+ ("@defer", "remove it: the content is already in the page"),
2113+ ("@log", "use `@warn`"),
2114+ (
2115+ "@component",
2116+ "use `@let`: an `@style` block in a function body is scoped to it",
2117+ ),
2118+ ("@col", "use `@column`"),
2119+ ("@p", "use `@paragraph`"),
2120+ ("@img", "use `@image`"),
2121+ ("@li", "use `@item`"),
2122+ ("@btn", "use `@button`"),
2123+ ("@ul", "use `@list`"),
2124+ ("@divider", "use `@hr`"),
2125+ ("@opt", "use `@option`"),
2126+];
39462127
3947−/// Text after the leading argument of an element without content:
3948−/// `@image logo.png Our logo`.
3949−fn after_the_leading_argument(kind: &ElementKind, token: &str, rest: &syntax::Text) -> Diagnostic {
3950− let name = kind.name();
3951− let attr = leading_name(kind);
3952− let alt = if matches!(kind, ElementKind::Image) || kind.is_tag("area") {
3953− " For a text alternative, write `alt=...`."
3954− } else {
3955− ""
3956− };
3957− let holds = if kind.layout() == Layout::Void {
3958− "it has no content"
3959− } else {
3960− "it holds only the elements on the lines under it"
3961− };
3962− let bare = syntax::quoted_string(token).unwrap_or(token);
3963− Diagnostic::error(
3964− code::UNEXPECTED_ARGUMENT,
3965− rest.span.line,
3966− format!(
3967− "@{0} takes one word after its attributes, its {1} ('{2}'), and {5}, so '{3}' \
3968− would go nowhere. A value with a space in it is quoted: `\"{6} {3}\"`.{4}",
3969− name, attr, token, rest.raw, alt, holds, bare
3970− ),
3971− )
3972− .subject(rest.raw.clone())
2128+/// Attributes that became standard-library bundles or plain CSS.
2129+fn removed_attribute_hint(name: &str) -> Option<&'static str> {
2130+ match name {
2131+ "skeleton" => Some("use the `$skeleton` bundle"),
2132+ "no-scrollbar" => Some("use the `$no-scrollbar` bundle"),
2133+ "gradient" => Some("use `background linear-gradient(...)`"),
2134+ "animate" => Some("use `animation`"),
2135+ "inset-area" => Some("use `position-area`"),
2136+ "gap-x" => Some("use `column-gap`"),
2137+ "gap-y" => Some("use `row-gap`"),
2138+ "shadow" => Some("use `box-shadow`"),
2139+ "blur" => Some("use `filter blur(...)`"),
2140+ "backdrop-blur" => Some("use `backdrop-filter blur(...)`"),
2141+ "truncate" => Some("use the `$truncate` bundle"),
2142+ "critical" => Some("remove it"),
2143+ "grid" => Some("use `@grid`, or `display grid`"),
2144+ _ => None,
2145+ }
39732146}
39742147
3975−/// The element named `name`, or an "unknown element" error that suggests
3976−/// the closest element, directive or function.
3977−fn parse_element_kind(
3978− name: &str,
3979− line_num: usize,
3980− ctx: &mut ParseContext,
3981−) -> Result<ElementKind, ParseError> {
3982− if let Some(kind) = ElementKind::from_name(name) {
3983− return Ok(kind);
3984− }
3985− // A known name in a place it can't go: say why instead of suggesting
3986− // the name itself.
3987− let misplaced = if crate::ast::directive(name).is_some() {
3988− Some(format!(
3989− "unknown element @{}: @{} is a directive, which goes at the start of its own line",
3990− name, name
3991− ))
3992− } else if ctx.env.bundle(name).is_some() {
3993− Some(format!(
3994− "unknown element @{}: '{}' is an attribute bundle, used as `[${}]` \
3995− (a function is defined with `@let @{}`)",
3996− name, name, name, name
3997− ))
3998− } else if ctx.env.value(name).is_some() {
3999− Some(format!(
4000− "unknown element @{}: '{}' is a value, used as `${}` \
4001− (a function is defined with `@let @{}`)",
4002− name, name, name, name
4003− ))
4004− } else if ctx.namespace.contains(name) {
4005− ctx.used_functions.insert(name.to_string());
4006− Some(format!(
4007− "unknown element @{}: the function @{} isn't visible here. A definition is \
4008− visible from its line to the end of its block, and a function's body sees what \
4009− is defined above the function, so define @{} above this line, outside the block \
4010− it is in",
4011− name, name, name
4012− ))
4013− } else if matches!(name, "svg" | "math" | "template") {
2148+/// If `content` starts with removed syntax, the error message for it.
2149+fn removed_syntax_hint(content: &str) -> Option<String> {
2150+ let trimmed = content.trim_start();
2151+ REMOVED_SYNTAX.iter().find_map(|(name, replacement)| {
2152+ let rest = trimmed.strip_prefix(name)?;
2153+ if !(rest.is_empty() || rest.starts_with([' ', '['])) {
2154+ return None;
2155+ }
40142156 Some(format!(
4015− "unknown element @{}: htmlang doesn't write <{}>; put its markup in the page with \
4016− @raw{}",
4017− name,
4018− name,
4019− if name == "svg" {
4020− " (or an SVG file with `@image [inline] file.svg`)"
4021− } else {
4022− ""
4023− }
2157+ "`{}` was removed: {} (run `htmlang upgrade` to rewrite it automatically)",
2158+ name, replacement
40242159 ))
4025− } else {
4026− None
4027− };
4028− if let Some(message) = misplaced {
4029− return Err(Diagnostic::error(code::UNKNOWN_ELEMENT, line_num, message).subject(name));
4030− }
4031− let all_known: Vec<&str> = ElementKind::all_names()
4032− .chain(DIRECTIVES.iter().map(|d| d.name))
4033− .collect();
4034− // An HTML element htmlang writes under its own name (`@a` is `@link`).
4035− let written_otherwise = crate::ast::HTML_NAMES_WRITTEN_OTHERWISE
4036− .iter()
4037− .find(|(html, _)| *html == name)
4038− .map(|(_, htmlang)| *htmlang);
4039− let closest = written_otherwise.or_else(|| suggest_closest(name, &all_known));
4040− let mut message = match (closest, written_otherwise) {
4041− (Some(closest), Some(_)) => format!(
4042− "unknown element @{}, did you mean @{}? (@{} writes <{}>)",
4043− name, closest, closest, name
4044− ),
4045− (Some(closest), None) => format!("unknown element @{}, did you mean @{}?", name, closest),
4046− (None, _) => format!("unknown element @{}", name),
4047− };
4048− let function = suggest_fn_name(name, ctx);
4049− if let Some(function) = &function {
4050− message = format!("{}, or did you mean @{}?", message, function);
4051− }
4052− Err(Diagnostic::error(code::UNKNOWN_ELEMENT, line_num, message)
4053− .subject(name)
4054− .suggest(closest.map(str::to_string).or(function)))
2160+ })
40552161}
40562162
40572163/// Format include/import stack as a readable chain for error messages.
@@ -4122,37 +2228,34 @@ fn suggest_closest<'a>(input: &str, candidates: &[&'a str]) -> Option<&'a str> {
41222228 best
41232229}
41242230
4125−/// Suggest the closest user-defined function name for typos, from the
4126−/// functions defined so far and those defined anywhere in the file.
2231+/// Suggest the closest user-defined function name for typos.
41272232fn suggest_fn_name(input: &str, ctx: &ParseContext) -> Option<String> {
41282233 let input_chars: Vec<char> = input.chars().collect();
41292234 let max_allowed = 2usize.min(input_chars.len().saturating_sub(1));
4130− let mut best: Option<(usize, &String)> = None;
4131− let visible: Vec<&String> = ctx.defined_functions.keys().collect();
4132− for name in visible.into_iter().chain(ctx.namespace.iter()) {
2235+ let mut best: Option<String> = None;
2236+ let mut best_dist = usize::MAX;
2237+ for name in ctx.functions.keys() {
41332238 let nlen = name.chars().count();
41342239 if nlen.abs_diff(input_chars.len()) > max_allowed {
41352240 continue;
41362241 }
41372242 let name_chars: Vec<char> = name.chars().collect();
41382243 let dist = levenshtein_bounded(&input_chars, &name_chars, max_allowed);
4139− if dist <= max_allowed && best.is_none_or(|b| (dist, name) < b) {
4140− best = Some((dist, name));
2244+ if dist < best_dist && dist <= max_allowed {
2245+ best_dist = dist;
2246+ best = Some(name.clone());
41412247 }
41422248 }
4143− best.map(|(_, name)| name.clone())
2249+ best
41442250}
41452251
41462252/// Suggest the closest variable name for undefined `$var` references.
4147−fn suggest_var_name(input: &str, vars: &[&str]) -> Option<String> {
2253+fn suggest_var_name(input: &str, vars: &HashMap<String, String>) -> Option<String> {
41482254 let input_chars: Vec<char> = input.chars().collect();
41492255 let max_allowed = 2usize.min(input_chars.len().saturating_sub(1));
41502256 let mut best: Option<String> = None;
41512257 let mut best_dist = usize::MAX;
4152− let mut vars = vars.to_vec();
4153− // The same answer every time, whatever the order of the names
4154− vars.sort_unstable();
4155− for name in vars {
2258+ for name in vars.keys() {
41562259 let nlen = name.chars().count();
41572260 if nlen.abs_diff(input_chars.len()) > max_allowed {
41582261 continue;
@@ -4161,1988 +2264,986 @@ fn suggest_var_name(input: &str, vars: &[&str]) -> Option<String> {
41612264 let dist = levenshtein_bounded(&input_chars, &name_chars, max_allowed);
41622265 if dist < best_dist && dist <= max_allowed {
41632266 best_dist = dist;
4164− best = Some(name.to_string());
2267+ best = Some(name.clone());
41652268 }
41662269 }
41672270 best
41682271}
41692272
4170−// ---------------------------------------------------------------------------
4171−// Attribute parsing
4172−// ---------------------------------------------------------------------------
4173−
4174−/// The quoted strings of a CSS value, without their quotes.
4175−fn css_strings(value: &str) -> Vec<&str> {
4176− let mut strings = Vec::new();
4177− let mut start = None;
4178− let mut escaped = false;
4179− for (i, c) in value.char_indices() {
4180− match (c, start) {
4181− _ if escaped => escaped = false,
4182− ('\\', Some(_)) => escaped = true,
4183− ('"', None) => start = Some(i + 1),
4184− ('"', Some(from)) => {
4185− strings.push(&value[from..i]);
4186− start = None;
2273+/// Check for undefined `$var` references and return "did you mean?" diagnostics.
2274+/// `indent` is the line's leading whitespace, which `input` has had trimmed;
2275+/// reported columns and source lines include it.
2276+fn check_undefined_vars(
2277+ input: &str,
2278+ vars: &HashMap<String, String>,
2279+ line_num: usize,
2280+ indent: usize,
2281+) -> Vec<Diagnostic> {
2282+ let mut warnings = Vec::new();
2283+ if !input.contains('$') {
2284+ return warnings;
2285+ }
2286+ let chars: Vec<char> = input.chars().collect();
2287+ let mut i = 0;
2288+ while i < chars.len() {
2289+ if chars[i] == '$'
2290+ && i + 1 < chars.len()
2291+ && (chars[i + 1].is_alphanumeric() || chars[i + 1] == '_' || chars[i + 1] == '-')
2292+ {
2293+ let col = i;
2294+ let start = i + 1;
2295+ let mut end = start;
2296+ while end < chars.len()
2297+ && (chars[end].is_alphanumeric()
2298+ || chars[end] == '-'
2299+ || chars[end] == '_'
2300+ || chars[end] == '.')
2301+ {
2302+ end += 1;
41872303 }
4188− _ => {}
2304+ while end > start && chars[end - 1] == '.' {
2305+ end -= 1;
2306+ }
2307+ let name: String = chars[start..end].iter().collect();
2308+ if !name.is_empty()
2309+ && !vars.contains_key(&name)
2310+ && let Some(closest) = suggest_var_name(&name, vars)
2311+ {
2312+ warnings.push(Diagnostic {
2313+ line: line_num,
2314+ column: Some(indent + col),
2315+ message: format!(
2316+ "undefined variable '${}', did you mean '${}'?",
2317+ name, closest
2318+ ),
2319+ severity: Severity::Warning,
2320+ source_line: Some(format!("{}{}", " ".repeat(indent), input)),
2321+ });
2322+ }
2323+ i = end;
2324+ } else {
2325+ i += 1;
41892326 }
41902327 }
4191− strings
2328+ warnings
41922329}
41932330
4194−/// An `if(...)` in a CSS value that isn't CSS's if(): CSS writes each
4195−/// branch `CONDITION: VALUE`, so an if() without a `:` is something else.
4196−/// Quoted CSS strings are text, not calls.
4197−fn not_css_if(value: &str) -> Option<&str> {
4198− let mut quote = None;
4199− let mut prev = None;
4200− let mut chars = value.char_indices();
4201− while let Some((at, c)) = chars.next() {
4202− match quote {
4203− Some(_) if c == '\\' => {
4204− chars.next();
2331+// ---------------------------------------------------------------------------
2332+// Attribute parsing
2333+// ---------------------------------------------------------------------------
2334+
2335+/// Attributes that expect purely numeric values (px-based) or values with CSS units.
2336+const NUMERIC_ATTRS: &[&str] = &[
2337+ "spacing",
2338+ "gap",
2339+ "padding",
2340+ "padding-x",
2341+ "padding-y",
2342+ "padding-top",
2343+ "padding-bottom",
2344+ "padding-left",
2345+ "padding-right",
2346+ "min-width",
2347+ "max-width",
2348+ "min-height",
2349+ "max-height",
2350+ "rounded",
2351+ "size",
2352+ "column-gap",
2353+ "row-gap",
2354+ "top",
2355+ "right",
2356+ "bottom",
2357+ "left",
2358+ "letter-spacing",
2359+];
2360+
2361+const CSS_UNIT_SUFFIXES: &[&str] = &[
2362+ "px", "%", "rem", "em", "vh", "vw", "vmin", "vmax", "dvh", "svh", "lvh", "ch", "ex", "cm",
2363+ "mm", "in", "pt", "pc", "fr",
2364+];
2365+
2366+fn has_css_unit(value: &str) -> bool {
2367+ CSS_UNIT_SUFFIXES.iter().any(|u| value.ends_with(u))
2368+ || value.starts_with("var(")
2369+ || value.starts_with("calc(")
2370+ || value.starts_with("clamp(")
2371+ || value.starts_with("min(")
2372+ || value.starts_with("max(")
2373+}
2374+
2375+/// Attributes that accept numeric OR keyword values.
2376+const NUMERIC_OR_KEYWORD_ATTRS: &[&str] = &["width", "height"];
2377+const SIZE_KEYWORDS: &[&str] = &["fill", "shrink"];
2378+
2379+fn validate_attr_value(attr: &Attribute, line_num: usize, ctx: &mut ParseContext) {
2380+ let base_key = crate::vocab::base_attribute(attr.key.as_str());
2381+
2382+ if let Some(val) = &attr.value {
2383+ if NUMERIC_ATTRS.contains(&base_key) {
2384+ // All space-separated parts must be numeric or have a CSS unit
2385+ for part in val.split_whitespace() {
2386+ if part.parse::<f64>().is_err() && !has_css_unit(part) {
2387+ ctx.diagnostics.push(Diagnostic {
2388+ line: line_num,
2389+ column: None,
2390+ message: format!(
2391+ "'{}' expects a numeric value (with optional unit), got '{}'",
2392+ attr.key, val
2393+ ),
2394+ severity: Severity::Warning,
2395+ source_line: None,
2396+ });
2397+ return;
2398+ }
42052399 }
4206− Some(q) if c == q => quote = None,
4207− Some(_) => {}
4208− None if matches!(c, '"' | '\'') => quote = Some(c),
4209− None => {
4210− let word_before =
4211− prev.is_some_and(|p: char| p.is_alphanumeric() || matches!(p, '-' | '_'));
4212− if !word_before && value[at..].starts_with("if(") {
4213− let mut depth = 0;
4214− let close = value[at + 2..].char_indices().find_map(|(i, c)| {
4215− match c {
4216− '(' => depth += 1,
4217− ')' => depth -= 1,
4218− _ => {}
4219− }
4220− (depth == 0).then_some(at + 2 + i)
2400+ } else if NUMERIC_OR_KEYWORD_ATTRS.contains(&base_key) {
2401+ let is_keyword = SIZE_KEYWORDS.contains(&val.as_str());
2402+ let is_numeric = val.parse::<f64>().is_ok();
2403+ let has_unit = has_css_unit(val);
2404+ if !is_keyword && !is_numeric && !has_unit {
2405+ ctx.diagnostics.push(Diagnostic {
2406+ line: line_num,
2407+ column: None,
2408+ message: format!(
2409+ "'{}' expects a number or one of [{}], got '{}'",
2410+ attr.key,
2411+ SIZE_KEYWORDS.join(", "),
2412+ val
2413+ ),
2414+ severity: Severity::Warning,
2415+ source_line: None,
2416+ });
2417+ }
2418+ } else if base_key == "opacity" {
2419+ if let Ok(v) = val.parse::<f64>() {
2420+ if !(0.0..=1.0).contains(&v) {
2421+ ctx.diagnostics.push(Diagnostic {
2422+ line: line_num,
2423+ column: None,
2424+ message: format!("'opacity' should be between 0 and 1, got '{}'", val),
2425+ severity: Severity::Warning,
2426+ source_line: None,
42212427 });
4222− let end = close.map_or(value.len(), |c| c + 1);
4223− if !value[at + 3..end].contains(':') {
4224− return Some(&value[at..end]);
4225− }
42262428 }
2429+ } else {
2430+ ctx.diagnostics.push(Diagnostic {
2431+ line: line_num,
2432+ column: None,
2433+ message: format!("'opacity' expects a numeric value, got '{}'", val),
2434+ severity: Severity::Warning,
2435+ source_line: None,
2436+ });
42272437 }
4228− }
4229− prev = Some(c);
4230− }
4231− None
4232−}
4233−
4234−/// Why a CSS value can't be written into a rule as it is, whatever it
4235−/// means: a `;` (outside parentheses, where CSS's own `if()` uses it), a
4236−/// `{` or a `}` would end the declaration or the rule, and an unclosed
4237−/// quote or parenthesis would run on into the rules after it. Quoted
4238−/// strings are text, and a backslash escapes the character after it, as
4239−/// in CSS. A `</style` anywhere, even in a string, would end the page's
4240−/// `<style>` element and start HTML.
4241−fn css_breakout(value: &str) -> Option<&'static str> {
4242− if value.to_ascii_lowercase().contains("</style") {
4243− return Some("a `</style`, which would end the page's style element");
4244− }
4245− let mut quote = None;
4246− let mut depth = 0usize;
4247− let mut chars = value.chars();
4248− while let Some(c) = chars.next() {
4249− match (quote, c) {
4250− (_, '\\') => {
4251− chars.next();
2438+ } else if base_key == "z-index" {
2439+ if val.parse::<i32>().is_err() {
2440+ ctx.diagnostics.push(Diagnostic {
2441+ line: line_num,
2442+ column: None,
2443+ message: format!("'z-index' expects an integer, got '{}'", val),
2444+ severity: Severity::Warning,
2445+ source_line: None,
2446+ });
42522447 }
4253− (Some(q), c) if c == q => quote = None,
4254− (Some(_), _) => {}
4255− (None, '"' | '\'') => quote = Some(c),
4256− (None, '(') => depth += 1,
4257− (None, ')') if depth == 0 => return Some("a `)` that closes nothing"),
4258− (None, ')') => depth -= 1,
4259− (None, ';') if depth == 0 => return Some("a `;`, which would end the declaration"),
4260− (None, '{' | '}') => return Some("a `{` or `}`, which would end the CSS rule"),
4261− _ => {}
4262− }
4263− }
4264− match (quote, depth) {
4265− (Some('"'), _) => Some("a `\"` that isn't closed"),
4266− (Some(_), _) => Some("a `'` that isn't closed"),
4267− (None, 0) => None,
4268− (None, _) => Some("a `(` that isn't closed"),
4269− }
4270−}
4271−
4272−/// The hex colors of a CSS value that don't have 3, 4, 6 or 8 hex
4273−/// digits. A `#` word in a CSS value is a color, except inside `url(...)`
4274−/// and quoted strings.
4275−fn bad_hex_colors(value: &str) -> Vec<&str> {
4276− let mut bad = Vec::new();
4277− let mut quote = None;
4278− let mut in_url = 0usize;
4279− let mut depth = 0usize;
4280− let mut chars = value.char_indices().peekable();
4281− while let Some((at, c)) = chars.next() {
4282− match (quote, c) {
4283− (_, '\\') => {
4284− chars.next();
2448+ } else if base_key == "display" {
2449+ const DISPLAY_VALUES: &[&str] = &[
2450+ "none",
2451+ "block",
2452+ "inline",
2453+ "inline-block",
2454+ "flex",
2455+ "inline-flex",
2456+ "grid",
2457+ "inline-grid",
2458+ "table",
2459+ "table-row",
2460+ "table-cell",
2461+ "contents",
2462+ "flow-root",
2463+ "list-item",
2464+ ];
2465+ if !DISPLAY_VALUES.contains(&val.as_str()) && !val.starts_with("var(") {
2466+ let suggestion = suggest_closest(val, DISPLAY_VALUES);
2467+ let msg = match suggestion {
2468+ Some(s) => format!("unknown display value '{}', did you mean '{}'?", val, s),
2469+ None => format!("unknown display value '{}'", val),
2470+ };
2471+ ctx.diagnostics.push(Diagnostic {
2472+ line: line_num,
2473+ column: None,
2474+ message: msg,
2475+ severity: Severity::Warning,
2476+ source_line: None,
2477+ });
42852478 }
4286− (Some(q), c) if c == q => quote = None,
4287− (Some(_), _) => {}
4288− (None, '"' | '\'') => quote = Some(c),
4289− (None, '(') => {
4290− depth += 1;
4291− if value[..at].ends_with("url") && in_url == 0 {
4292− in_url = depth;
4293− }
2479+ } else if base_key == "position" {
2480+ const POSITION_VALUES: &[&str] = &["static", "relative", "absolute", "fixed", "sticky"];
2481+ if !POSITION_VALUES.contains(&val.as_str()) && !val.starts_with("var(") {
2482+ let suggestion = suggest_closest(val, POSITION_VALUES);
2483+ let msg = match suggestion {
2484+ Some(s) => format!("unknown position value '{}', did you mean '{}'?", val, s),
2485+ None => format!("unknown position value '{}'", val),
2486+ };
2487+ ctx.diagnostics.push(Diagnostic {
2488+ line: line_num,
2489+ column: None,
2490+ message: msg,
2491+ severity: Severity::Warning,
2492+ source_line: None,
2493+ });
42942494 }
4295− (None, ')') => {
4296− if in_url == depth {
4297− in_url = 0;
4298− }
4299− depth = depth.saturating_sub(1);
2495+ } else if base_key == "overflow" || base_key == "overflow-x" || base_key == "overflow-y" {
2496+ const OVERFLOW_VALUES: &[&str] = &["visible", "hidden", "scroll", "auto", "clip"];
2497+ if !OVERFLOW_VALUES.contains(&val.as_str()) && !val.starts_with("var(") {
2498+ let suggestion = suggest_closest(val, OVERFLOW_VALUES);
2499+ let msg = match suggestion {
2500+ Some(s) => format!("unknown overflow value '{}', did you mean '{}'?", val, s),
2501+ None => format!("unknown overflow value '{}'", val),
2502+ };
2503+ ctx.diagnostics.push(Diagnostic {
2504+ line: line_num,
2505+ column: None,
2506+ message: msg,
2507+ severity: Severity::Warning,
2508+ source_line: None,
2509+ });
43002510 }
4301− (None, '#') if in_url == 0 => {
4302− let end = value[at + 1..]
4303− .find(|c: char| !(c.is_alphanumeric() || c == '-' || c == '_'))
4304− .map_or(value.len(), |n| at + 1 + n);
4305− let hex = &value[at + 1..end];
4306− if !(matches!(hex.len(), 3 | 4 | 6 | 8)
4307− && hex.chars().all(|c| c.is_ascii_hexdigit()))
4308− {
4309− bad.push(&value[at..end]);
4310− }
2511+ } else if base_key == "text-align" {
2512+ const TEXT_ALIGN_VALUES: &[&str] =
2513+ &["left", "right", "center", "justify", "start", "end"];
2514+ if !TEXT_ALIGN_VALUES.contains(&val.as_str()) && !val.starts_with("var(") {
2515+ let suggestion = suggest_closest(val, TEXT_ALIGN_VALUES);
2516+ let msg = match suggestion {
2517+ Some(s) => format!("unknown text-align value '{}', did you mean '{}'?", val, s),
2518+ None => format!("unknown text-align value '{}'", val),
2519+ };
2520+ ctx.diagnostics.push(Diagnostic {
2521+ line: line_num,
2522+ column: None,
2523+ message: msg,
2524+ severity: Severity::Warning,
2525+ source_line: None,
2526+ });
43112527 }
4312− _ => {}
4313− }
4314− }
4315− bad
4316−}
4317−
4318−/// A diagnostic about an attribute, with its column and source line when
4319−/// it is on the line being evaluated.
4320−fn at_attribute(diagnostic: Diagnostic, column: Option<usize>, ctx: &ParseContext) -> Diagnostic {
4321− match (&ctx.current_source, column) {
4322− ((current, Some(text)), Some(column)) if *current == diagnostic.line => {
4323− diagnostic.column(column).source(text.clone())
4324− }
4325− _ => diagnostic,
4326− }
4327−}
4328−
4329−/// Check a style's value. Values go to the CSS as written, so only what
4330−/// can't be wrong in any CSS is checked: a value that would break out of
4331−/// its rule is an error (and it is left out); a hex color without 3, 4, 6
4332−/// or 8 digits, an `if()` that isn't CSS's and a quoted font stack are
4333−/// warnings. Returns whether the value can be written.
4334−fn check_css_value(
4335− attr: &Attribute,
4336− base: &str,
4337− line: usize,
4338− column: Option<usize>,
4339− ctx: &mut ParseContext,
4340−) -> bool {
4341− let Some(value) = &attr.value else {
4342− return true;
4343− };
4344− if let Some(reason) = css_breakout(value) {
4345− let diagnostic = Diagnostic::error(
4346− code::INVALID_VALUE,
4347− line,
4348− format!(
4349− "the value of '{}' has {}: `{}` can't be written into the page's CSS",
4350− attr.key, reason, value
4351− ),
4352− )
4353− .subject(value.as_str());
4354− ctx.diagnostics.push(at_attribute(diagnostic, column, ctx));
4355− return false;
4356− }
4357− if crate::vocab::is_custom_property(base) {
4358− return true;
4359− }
4360−
4361− let warn = |ctx: &mut ParseContext, diagnostic: Diagnostic| {
4362− let diagnostic = at_attribute(diagnostic, column, ctx);
4363− ctx.diagnostics.push(diagnostic);
4364− };
4365− // In CSS, a quoted font-family is one family, commas and all
4366− if base == "font-family"
4367− && let Some(family) = css_strings(value).into_iter().find(|s| s.contains(','))
4368− {
4369− let stack = family
4370− .split(',')
4371− .map(str::trim)
4372− .collect::<Vec<_>>()
4373− .join("\\, ");
4374− warn(
4375− ctx,
4376− Diagnostic::warning(
4377− code::INVALID_VALUE,
4378− line,
4379− format!(
4380− "font-family \"{}\" is one family, whose name has a comma in it: \
4381− for a font stack, write `font-family {}`",
4382− family, stack
4383− ),
4384− )
4385− .subject(format!("\"{}\"", family))
4386− .suggest(Some(stack)),
4387− );
4388− }
4389− if let Some(call) = not_css_if(value) {
4390− warn(
4391− ctx,
4392− Diagnostic::warning(
4393− code::INVALID_VALUE,
4394− line,
4395− format!(
4396− "'{}' is not CSS's if(), whose branches are written \
4397− `if(CONDITION: VALUE; else: VALUE)`",
4398− call
4399− ),
4400− )
4401− .subject(call),
4402− );
4403− }
4404− for color in bad_hex_colors(value) {
4405− warn(
4406− ctx,
4407− Diagnostic::warning(
4408− code::INVALID_COLOR,
4409− line,
4410− format!(
4411− "invalid hex color '{}': a hex color has 3, 4, 6 or 8 hex digits",
4412− color
4413− ),
4414− )
4415− .subject(color),
4416− );
4417− }
4418− true
4419−}
4420−
4421−/// An unknown prefix: the message, the text it is about, and what to write
4422−/// instead, when something is close enough.
4423−struct PrefixProblem {
4424− message: String,
4425− subject: String,
4426− suggestion: Option<String>,
4427−}
4428−
4429−/// What is wrong with the prefix `rest` starts with, when the known
4430−/// prefixes are already split off it and what is left still starts with
4431−/// one: a word and a `:` (`hovr:`), or a word and a parenthesised argument
4432−/// and a `:` (`nth-chld(2):`). Selector prefixes are CSS's pseudo-classes
4433−/// and pseudo-elements under their CSS names, so an unknown one gets the
4434−/// closest name as a suggestion. Only names with the same first letter are
4435−/// suggested: `odd:` is two edits from `md:`, which it doesn't mean.
4436−fn unknown_prefix(rest: &str) -> Option<PrefixProblem> {
4437− use crate::vocab::{self, Pseudo};
4438− let name_len = rest.find(|c: char| !(c.is_ascii_alphanumeric() || c == '-'))?;
4439− let name = &rest[..name_len];
4440− if name.is_empty() {
4441− return None;
4442− }
4443− if rest[name_len..].starts_with('(') {
4444− // `name(...):`: a pseudo-class with an argument
4445− let close = vocab::closing_paren(rest, name_len)?;
4446− if !rest[close + 1..].starts_with(':') {
4447− return None;
4448− }
4449− let written = &rest[..close + 2];
4450− if matches!(vocab::pseudo(name), Some(Pseudo::Class | Pseudo::Element)) {
4451− let bare = format!("{}:", name);
4452− return Some(PrefixProblem {
4453− message: format!(
4454− "'{}': `{}` takes no argument: write `{}`",
4455− written,
4456− vocab::pseudo_selector(&bare).unwrap_or_default(),
4457− bare
4458− ),
4459− subject: written.to_string(),
4460− suggestion: Some(bare),
4461− });
4462− }
4463− let functional: Vec<&str> = vocab::functional_pseudos()
4464− .into_iter()
4465− .filter(|p| p.chars().next() == name.chars().next())
4466− .collect();
4467− let suggestion = suggest_closest(name, &functional)
4468− .filter(|&closest| closest != name)
4469− .map(|closest| format!("{}(", closest));
4470− let written = format!("{}(", name);
4471− let message = match &suggestion {
4472− Some(closest) => format!("unknown prefix '{}', did you mean '{}'?", written, closest),
4473− None => format!("unknown prefix '{}'", written),
4474− };
4475− return Some(PrefixProblem {
4476− message,
4477− subject: written,
4478− suggestion,
4479− });
4480− }
4481− if !rest[name_len..].starts_with(':') {
4482− return None;
4483− }
4484− let written = &rest[..name_len + 1];
4485− // `has:`: its argument is missing
4486− if vocab::pseudo(name) == Some(Pseudo::Function) {
4487− return Some(PrefixProblem {
4488− message: format!(
4489− "'{}': `:{}()` takes an argument, in parentheses, as in CSS: `{}(...):`",
4490− written, name, name
4491− ),
4492− subject: written.to_string(),
4493− suggestion: None,
4494− });
4495− }
4496− let prefixes = vocab::all_prefixes();
4497− let candidates: Vec<&str> = prefixes
4498− .iter()
4499− .map(String::as_str)
4500− .filter(|p| p.chars().next() == written.chars().next())
4501− .collect();
4502− // The closest name that starts with the same letter (`hvoer:` →
4503− // `hover:`), else the first that starts with the word written and a `-`
4504− // (`first:` → `first-child:`)
4505− let suggestion = suggest_closest(written, &candidates)
4506− .or_else(|| {
4507− let longer = format!("{}-", name);
4508− candidates.iter().copied().find(|p| p.starts_with(&longer))
4509− })
4510− .filter(|&closest| closest != written)
4511− .map(str::to_string);
4512− let message = match &suggestion {
4513− Some(closest) => format!("unknown prefix '{}', did you mean '{}'?", written, closest),
4514− None => format!("unknown prefix '{}'", written),
4515− };
4516− Some(PrefixProblem {
4517− message,
4518− subject: written.to_string(),
4519− suggestion,
4520− })
4521−}
4522−
4523−/// Check an attribute's element prefix (`@td:padding 8`), when it has one:
4524−/// it names a built-in element that has an HTML tag of its own (not a
4525−/// function, and not `@el`, whose `<div>` other elements write too), there
4526−/// is one, not with `children:`, and what it styles is a CSS property, not
4527−/// one of htmlang's words, which compile against each element's layout and
4528−/// its parent's. Returns false, after reporting, when the attribute can't
4529−/// be written.
4530−fn check_element_prefixes(
4531− attr: &Attribute,
4532− prefixes: &[&str],
4533− base: &str,
4534− line: usize,
4535− column: Option<usize>,
4536− ctx: &mut ParseContext,
4537−) -> bool {
4538− use crate::ast::ElementKind;
4539− use crate::vocab;
4540− let elements: Vec<&str> = prefixes
4541− .iter()
4542− .copied()
4543− .filter(|p| vocab::element_prefix(p).is_some())
4544− .collect();
4545− let Some(&prefix) = elements.first() else {
4546− return true;
4547− };
4548− let fail = |ctx: &mut ParseContext,
4549− code: &'static str,
4550− message: String,
4551− subject: &str,
4552− suggestion: Option<String>| {
4553− let diagnostic = Diagnostic::error(code, line, message)
4554− .subject(subject)
4555− .suggest(suggestion);
4556− let diagnostic = at_attribute(diagnostic, column, ctx);
4557− ctx.diagnostics.push(diagnostic);
4558− false
4559− };
4560− let name = vocab::element_prefix(prefix).unwrap_or_default();
4561− if is_function(name, ctx) {
4562− return fail(
4563− ctx,
4564− code::INVALID_PREFIX,
4565− format!(
4566− "'{}': @{} is a function, and `{}` would pick elements out by their HTML tag, \
4567− which a function doesn't have: style what @{} writes in its body, or pass it \
4568− attributes",
4569− attr.key, name, prefix, name
4570− ),
4571− prefix,
4572− None,
4573− );
4574− }
4575− match ElementKind::from_name(name) {
4576− None => {
4577− let own: Vec<&str> = ElementKind::all_names()
4578− .filter(|n| ElementKind::from_name(n).is_some_and(|k| k.own_tag().is_some()))
4579− .collect();
4580− // An HTML name htmlang writes under another (`@a:` is `@link:`)
4581− let (written_otherwise, shared) = match crate::ast::HTML_NAMES_WRITTEN_OTHERWISE
4582− .iter()
4583− .find(|(html, _)| *html == name)
2528+ } else if base_key == "cursor" {
2529+ const CURSOR_VALUES: &[&str] = &[
2530+ "auto",
2531+ "default",
2532+ "none",
2533+ "pointer",
2534+ "wait",
2535+ "text",
2536+ "move",
2537+ "not-allowed",
2538+ "crosshair",
2539+ "grab",
2540+ "grabbing",
2541+ "help",
2542+ "progress",
2543+ "col-resize",
2544+ "row-resize",
2545+ "n-resize",
2546+ "s-resize",
2547+ "e-resize",
2548+ "w-resize",
2549+ "zoom-in",
2550+ "zoom-out",
2551+ "context-menu",
2552+ "cell",
2553+ "copy",
2554+ "alias",
2555+ "no-drop",
2556+ ];
2557+ if !CURSOR_VALUES.contains(&val.as_str())
2558+ && !val.starts_with("url(")
2559+ && !val.starts_with("var(")
45842560 {
4585− Some((_, htmlang)) if own.contains(htmlang) => (Some(*htmlang), false),
4586− Some(_) => (None, true),
4587− None => (None, false),
4588− };
4589− // `@each:`, `@markdown:`: a directive, which is no element
4590− if crate::ast::directive(name).is_some() {
4591− return fail(
4592− ctx,
4593− code::UNKNOWN_PREFIX,
4594− format!(
4595− "unknown element @{} in '{}': @{} is a directive, and an element \
4596− prefix names an element with an HTML tag of its own, such as `@td:`",
4597− name, prefix, name
4598− ),
4599− prefix,
4600− None,
4601− );
2561+ let suggestion = suggest_closest(val, CURSOR_VALUES);
2562+ let msg = match suggestion {
2563+ Some(s) => format!("unknown cursor value '{}', did you mean '{}'?", val, s),
2564+ None => format!("unknown cursor value '{}'", val),
2565+ };
2566+ ctx.diagnostics.push(Diagnostic {
2567+ line: line_num,
2568+ column: None,
2569+ message: msg,
2570+ severity: Severity::Warning,
2571+ source_line: None,
2572+ });
46022573 }
4603− // `@div:`, `@span:`: several elements write it
4604− if shared {
4605− return fail(
4606− ctx,
4607− code::UNKNOWN_PREFIX,
4608− format!(
4609− "unknown element @{} in '{}': htmlang writes <{}> for several \
4610− elements, so no element prefix picks it out",
4611− name, prefix, name
2574+ } else if base_key == "font-weight" {
2575+ const WEIGHT_VALUES: &[&str] = &[
2576+ "normal", "bold", "bolder", "lighter", "100", "200", "300", "400", "500", "600",
2577+ "700", "800", "900",
2578+ ];
2579+ if !WEIGHT_VALUES.contains(&val.as_str()) && !val.starts_with("var(") {
2580+ ctx.diagnostics.push(Diagnostic {
2581+ line: line_num,
2582+ column: None,
2583+ message: format!(
2584+ "'font-weight' expects a weight keyword or number 100-900, got '{}'",
2585+ val
46122586 ),
4613− prefix,
4614− None,
4615− );
2587+ severity: Severity::Warning,
2588+ source_line: None,
2589+ });
46162590 }
4617− // A name with the same first letter first (`@tdd:` is `@td:`)
4618− let same_letter: Vec<&str> = own
4619− .iter()
4620− .copied()
4621− .filter(|n| n.chars().next() == name.chars().next())
4622− .collect();
4623− let closest = written_otherwise
4624− .or_else(|| suggest_closest(name, &same_letter))
4625− .or_else(|| suggest_closest(name, &own));
4626− let message = match (closest, written_otherwise) {
4627− (Some(closest), Some(_)) => format!(
4628− "unknown element @{} in '{}', did you mean '@{}:'? (@{} writes <{}>)",
4629− name, prefix, closest, closest, name
4630− ),
4631− (Some(closest), None) => format!(
4632− "unknown element @{} in '{}', did you mean '@{}:'?",
4633− name, prefix, closest
4634− ),
4635− (None, _) => format!("unknown element @{} in '{}'", name, prefix),
4636− };
4637− let suggestion = closest.map(|c| format!("@{}:", c));
4638− fail(ctx, code::UNKNOWN_PREFIX, message, prefix, suggestion)
4639− }
4640− Some(kind) if kind.own_tag().is_none() => {
4641− let reason = match kind.tag() {
4642− None => format!(
4643− "@{} writes no element of its own, so there is nothing for `{}` to style",
4644− name, prefix
4645− ),
4646− Some(_) if kind.is_verbatim() => {
4647− format!("@{} isn't shown, so there is nothing to style", name)
4648− }
4649− Some("span") => format!(
4650− "@{} writes a <span>, as every line of text in a row or column does, so \
4651− `{}` can't pick it out",
4652− name, prefix
4653− ),
4654− Some(tag) => {
4655− let others: Vec<String> = ElementKind::all_names()
4656− .filter(|n| {
4657− *n != name
4658− && ElementKind::from_name(n).and_then(|k| k.tag()) == Some(tag)
4659− })
4660− .map(|n| format!("@{}", n))
4661− .collect();
4662− let others = match others.split_last() {
4663− Some((last, [])) => last.clone(),
4664− Some((last, rest)) => format!("{} and {}", rest.join(", "), last),
4665− None => String::new(),
2591+ } else if base_key == "color" || base_key == "background" {
2592+ // Validate named CSS colors (only if not hex, rgb, hsl, var, etc.)
2593+ if !val.starts_with('#')
2594+ && !val.starts_with("rgb")
2595+ && !val.starts_with("hsl")
2596+ && !val.starts_with("var(")
2597+ && !val.starts_with("linear-gradient")
2598+ && !val.starts_with("radial-gradient")
2599+ && !val.starts_with("conic-gradient")
2600+ && !val.starts_with("oklch")
2601+ && !val.starts_with("oklab")
2602+ && !val.starts_with("color(")
2603+ && !val.starts_with("light-dark(")
2604+ && !val.contains("url(")
2605+ && !val.contains(' ')
2606+ // skip shorthand multi-value
2607+ {
2608+ const NAMED_COLORS: &[&str] = &[
2609+ "transparent",
2610+ "currentcolor",
2611+ "inherit",
2612+ "initial",
2613+ "unset",
2614+ "black",
2615+ "white",
2616+ "red",
2617+ "green",
2618+ "blue",
2619+ "yellow",
2620+ "orange",
2621+ "purple",
2622+ "pink",
2623+ "brown",
2624+ "gray",
2625+ "grey",
2626+ "cyan",
2627+ "magenta",
2628+ "lime",
2629+ "olive",
2630+ "navy",
2631+ "teal",
2632+ "aqua",
2633+ "fuchsia",
2634+ "maroon",
2635+ "silver",
2636+ "coral",
2637+ "salmon",
2638+ "tomato",
2639+ "crimson",
2640+ "firebrick",
2641+ "darkred",
2642+ "indigo",
2643+ "violet",
2644+ "plum",
2645+ "orchid",
2646+ "thistle",
2647+ "lavender",
2648+ "gold",
2649+ "khaki",
2650+ "wheat",
2651+ "tan",
2652+ "sienna",
2653+ "chocolate",
2654+ "peru",
2655+ "beige",
2656+ "ivory",
2657+ "linen",
2658+ "snow",
2659+ "seashell",
2660+ "mintcream",
2661+ "skyblue",
2662+ "steelblue",
2663+ "royalblue",
2664+ "dodgerblue",
2665+ "cornflowerblue",
2666+ "slategray",
2667+ "slategrey",
2668+ "dimgray",
2669+ "dimgrey",
2670+ "lightgray",
2671+ "lightgrey",
2672+ "darkgray",
2673+ "darkgrey",
2674+ "gainsboro",
2675+ "whitesmoke",
2676+ ];
2677+ if !NAMED_COLORS.contains(&val.to_lowercase().as_str()) {
2678+ let lower = val.to_lowercase();
2679+ let suggestion = suggest_closest(&lower, NAMED_COLORS);
2680+ let msg = match suggestion {
2681+ Some(s) => format!("unknown color '{}', did you mean '{}'?", val, s),
2682+ None => format!("unknown color '{}'", val),
46662683 };
4667− format!(
4668− "@{} writes a <{}>, as {} do, so `{}` can't pick it out",
4669− name, tag, others, prefix
4670− )
2684+ ctx.diagnostics.push(Diagnostic {
2685+ line: line_num,
2686+ column: None,
2687+ message: msg,
2688+ severity: Severity::Warning,
2689+ source_line: None,
2690+ });
46712691 }
4672− };
4673− fail(
4674− ctx,
4675− code::INVALID_PREFIX,
4676− format!(
4677− "'{}': {}. Give those elements their styles themselves, or a bundle \
4678− (`@let name [...]`, used as `[$name]`)",
4679− attr.key, reason
4680− ),
4681− prefix,
4682− None,
4683− )
4684− }
4685− Some(_) if elements.len() > 1 => fail(
4686− ctx,
4687− code::INVALID_PREFIX,
4688− format!(
4689− "'{}': a style takes one element prefix, which styles every such element \
4690− inside this one, at any depth",
4691− attr.key
4692− ),
4693− &attr.key,
4694− None,
4695− ),
4696− Some(_) if prefixes.contains(&vocab::CHILDREN) => fail(
4697− ctx,
4698− code::INVALID_PREFIX,
4699− format!(
4700− "'{}': `children:` and `{}` each say which elements the style is for: write \
4701− one of them",
4702− attr.key, prefix
4703− ),
4704− &attr.key,
4705− None,
4706− ),
4707− Some(_) if vocab::is_htmlang_word(base, attr.value.as_deref()) => {
4708− let value = attr.value.as_deref().map(str::trim);
4709− let css = match (base, value) {
4710− ("spacing", _) => " (`gap`)",
4711− ("wrap", _) => " (`flex-wrap wrap`)",
4712− ("grid-cols", _) => " (`grid-template-columns`)",
4713− ("grid-rows", _) => " (`grid-template-rows`)",
4714− ("col-span", _) => " (`grid-column span N`)",
4715− ("row-span", _) => " (`grid-row span N`)",
4716− ("width", Some("fill")) => " (`flex 1` in a row, `width 100%` otherwise)",
4717− ("height", Some("fill")) => " (`flex 1` in a column, `height 100%` otherwise)",
4718− ("width", _) => " (`flex-shrink 0` in a row, `width fit-content` otherwise)",
4719− ("height", _) => " (`flex-shrink 0` in a column, `height fit-content` otherwise)",
4720− ("center-x", _) => " (`margin-inline auto`)",
4721− ("center-y", _) => " (`margin-block auto`)",
4722− _ => "",
4723− };
4724− let word = match value {
4725− Some(v) if matches!(base, "width" | "height") => format!("{} {}", base, v),
4726− _ => base.to_string(),
4727− };
4728− fail(
4729− ctx,
4730− code::INVALID_PREFIX,
4731− format!(
4732− "'{}': `{}` is one of htmlang's layout words, which compile against each \
4733− element's layout and its parent's, and `{}` styles elements whose \
4734− parents it doesn't know: write `{}` on the elements themselves, or the \
4735− CSS you mean{}",
4736− attr.key, word, prefix, word, css
4737− ),
4738− &attr.key,
4739− None,
4740− )
2692+ }
47412693 }
4742− Some(_) => true,
47432694 }
47442695}
47452696
4746−/// Check an attribute's prefixes: each is known, their selector prefixes
4747−/// read left to right with a pseudo-element (`before:`) last, the argument
4748−/// of `has(...)` or `nth-child(...)` can be written into the CSS, and a word that
4749−/// places an element in its parent (`width fill`, `center-x`, `align-*`)
4750−/// isn't under `children:`, whose styles go on the children. Media,
4751−/// container and width prefixes go anywhere. Returns false, after
4752−/// reporting, when the attribute can't be written.
4753−fn check_prefixes(
4754− attr: &Attribute,
4755− line: usize,
4756− column: Option<usize>,
2697+fn parse_attr_brackets(
2698+ input: &str,
2699+ line_num: usize,
47572700 ctx: &mut ParseContext,
4758−) -> bool {
4759− use crate::vocab;
4760− let (prefixes, base) = vocab::split_prefixes(&attr.key);
4761− let fail =
4762− |ctx: &mut ParseContext, message: String, subject: &str, suggestion: Option<String>| {
4763− let diagnostic = Diagnostic::error(code::INVALID_PREFIX, line, message)
4764− .subject(subject)
4765− .suggest(suggestion);
4766− let diagnostic = at_attribute(diagnostic, column, ctx);
4767− ctx.diagnostics.push(diagnostic);
4768− false
4769− };
2701+) -> Result<(Vec<Attribute>, String), ParseError> {
2702+ parse_attr_brackets_inner(input, line_num, ctx, true)
2703+}
47702704
4771− if let Some(problem) = unknown_prefix(base) {
4772− let diagnostic = Diagnostic::error(code::UNKNOWN_PREFIX, line, problem.message)
4773− .subject(problem.subject)
4774− .suggest(problem.suggestion);
4775− let diagnostic = at_attribute(diagnostic, column, ctx);
4776− ctx.diagnostics.push(diagnostic);
4777− return false;
4778− }
4779− if !check_element_prefixes(attr, &prefixes, base, line, column, ctx) {
4780− return false;
4781− }
4782− // The argument of `has(...)` or `nth-child(...)` goes into the CSS as
4783− // written
4784− for prefix in &prefixes {
4785− if let Some(reason) = css_breakout(prefix.trim_end_matches(':')) {
4786− return fail(
4787− ctx,
4788− format!(
4789− "the prefix '{}' has {}: it can't be written into the page's CSS",
4790− prefix, reason
4791− ),
4792− prefix,
4793− None,
4794− );
4795− }
4796− }
4797− // `nth-child():` or `has( ):`: CSS has no pseudo-class with an empty
4798− // argument
4799− let empty_argument = |prefix: &str| {
4800− prefix
4801− .strip_suffix("):")
4802− .and_then(|p| p.split_once('('))
4803− .is_some_and(|(_, argument)| argument.trim().is_empty())
4804− };
4805− if let Some(empty) = prefixes.iter().find(|p| empty_argument(p)) {
4806− return fail(
4807− ctx,
4808− format!(
4809− "'{}': `:{}()` takes an argument between its parentheses, as in CSS",
4810− attr.key,
4811− vocab::pseudo_name(empty)
4812− ),
4813− empty,
4814− None,
4815− );
4816− }
4817− // A pseudo-element is the last selector prefix: CSS has no
4818− // `::before:hover`
4819− let selectors: Vec<&str> = prefixes
4820− .iter()
4821− .copied()
4822− .filter(|p| vocab::at_rule_rank(p).is_none())
4823− .collect();
4824− // Only one: an element has one `::before`, which has no `::after`
4825− let elements: Vec<&str> = selectors
4826− .iter()
4827− .copied()
4828− .filter(|p| vocab::is_pseudo_element(p))
4829− .collect();
4830− if elements.len() > 1 {
4831− return fail(
4832− ctx,
4833− format!(
4834− "'{}': `{}` and `{}` each select a pseudo-element, and a style applies to one \
4835− of them",
4836− attr.key, elements[0], elements[1]
4837− ),
4838− &attr.key,
4839− None,
4840− );
4841− }
4842− if let Some(at) = selectors.iter().position(|p| vocab::is_pseudo_element(p))
4843− && at + 1 < selectors.len()
4844− {
4845− let element = selectors[at];
4846− // The same prefixes, with the pseudo-element moved after the other
4847− // selector prefixes
4848− let mut order: Vec<&str> = prefixes.iter().copied().filter(|p| *p != element).collect();
4849− let last_selector = order
4850− .iter()
4851− .rposition(|p| vocab::at_rule_rank(p).is_none())
4852− .map_or(order.len(), |i| i + 1);
4853− order.insert(last_selector, element);
4854− let fixed = format!("{}{}", order.concat(), base);
4855− return fail(
4856− ctx,
4857− format!(
4858− "'{}': `{}` selects a pseudo-element, which comes after the other selector \
4859− prefixes, as in CSS: write `{}`",
4860− attr.key, element, fixed
4861− ),
4862− &attr.key,
4863− Some(fixed),
4864− );
4865− }
4866− // Under `children:` the styles go on the children, whose parent is this
4867− // element: a word that places an element in its parent can't say where
4868− if prefixes.contains(&"children:") && vocab::places_in_parent(base, attr.value.as_deref()) {
4869− // The CSS of `fill` and `shrink` depends on the direction: along
4870− // it, they are flex properties
4871− let (word, css) = match (base, attr.value.as_deref().map(str::trim)) {
4872− ("width", Some("fill")) => (
4873− "width fill",
4874− " (`children:flex 1` in a row, `children:width 100%` otherwise)",
4875− ),
4876− ("height", Some("fill")) => (
4877− "height fill",
4878− " (`children:flex 1` in a column, `children:height 100%` otherwise)",
4879− ),
4880− ("width", Some(_)) => (
4881− "width shrink",
4882− " (`children:flex-shrink 0` in a row, `children:width fit-content` otherwise)",
4883− ),
4884− ("height", Some(_)) => (
4885− "height shrink",
4886− " (`children:flex-shrink 0` in a column, `children:height fit-content` \
4887− otherwise)",
4888− ),
4889− _ => (base, ""),
4890− };
4891− return fail(
4892− ctx,
4893− format!(
4894− "'{}{}': `{}` places an element in its parent, and under `children:` that \
4895− parent is this element: write `{}` on the children themselves, or the CSS \
4896− you mean{}",
4897− attr.key,
4898− attr.value
4899− .as_deref()
4900− .map_or(String::new(), |v| format!(" {}", v.trim())),
4901− word,
4902− word,
4903− css
4904− ),
4905− &attr.key,
4906− None,
4907− );
4908− }
4909− true
2705+fn parse_attr_brackets_no_validate(
2706+ input: &str,
2707+ line_num: usize,
2708+ ctx: &mut ParseContext,
2709+) -> Result<(Vec<Attribute>, String), ParseError> {
2710+ parse_attr_brackets_inner(input, line_num, ctx, false)
49102711}
49112712
4912−/// Check an attribute written as a style or a flag (not `key=value`): its
4913−/// prefix, its name, and, for a style, its value. A name htmlang doesn't
4914−/// know but CSS could have (`corner-shape`) is passed to the CSS as written,
4915−/// with a warning; custom properties (`--brand`) and vendor-prefixed ones
4916−/// (`-webkit-...`) without one. Anything that can't be written into the
4917−/// page is an error; returns false then, and the attribute is left out.
4918−fn check_attribute(
4919− attr: &Attribute,
4920− line: usize,
4921− column: Option<usize>,
4922− before: Option<&Attribute>,
2713+fn parse_attr_brackets_inner(
2714+ input: &str,
2715+ line_num: usize,
49232716 ctx: &mut ParseContext,
4924−) -> bool {
4925− use crate::vocab;
4926− let (prefixes, base) = vocab::split_prefixes(&attr.key);
4927− let fail = |ctx: &mut ParseContext, code: &'static str, message: String, subject: &str| {
4928− let diagnostic = Diagnostic::error(code, line, message).subject(subject);
4929− let diagnostic = at_attribute(diagnostic, column, ctx);
4930− ctx.diagnostics.push(diagnostic);
4931− false
4932− };
2717+ validate: bool,
2718+) -> Result<(Vec<Attribute>, String), ParseError> {
2719+ let mut depth = 0;
2720+ let mut end_pos = 0;
49332721
4934− if !check_prefixes(attr, line, column, ctx) {
4935− return false;
4936− }
4937− let prefixed = !prefixes.is_empty();
4938− // `md:id=x`: `=` makes an HTML attribute, which has no states
4939− if prefixed && let Some((name, _)) = base.split_once('=') {
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, name
4946− ),
4947− &attr.key,
4948− );
4949− }
4950− let Some(value) = &attr.value else {
4951− // `inline` puts a file into the page as it compiles, which no
4952− // state or media condition can undo
4953− if base == "inline" && prefixed {
4954− return fail(
4955− ctx,
4956− code::INVALID_PREFIX,
4957− format!(
4958− "'{}': `inline` puts the image's file into the page, which can't depend \
4959− on a prefix",
4960− attr.key
4961− ),
4962− &attr.key,
4963− );
4964− }
4965− if vocab::HTMLANG_FLAGS.contains(&base) {
4966− return true;
4967− }
4968− if vocab::is_html_flag(base) {
4969− if !prefixed {
4970− return true;
2722+ for (i, c) in input.char_indices() {
2723+ match c {
2724+ '[' => depth += 1,
2725+ ']' => {
2726+ depth -= 1;
2727+ if depth == 0 {
2728+ end_pos = i;
2729+ break;
2730+ }
49712731 }
4972− return fail(
4973− ctx,
4974− code::INVALID_PREFIX,
4975− format!(
4976− "'{}': a prefix applies to a style, and '{}' is an HTML attribute",
4977− attr.key, base
4978− ),
4979− &attr.key,
4980− );
4981− }
4982− if vocab::is_style_attribute(base)
4983− || vocab::is_custom_property(base)
4984− || vocab::is_vendor_property(base)
4985− {
4986− return fail(
4987− ctx,
4988− code::MISSING_VALUE,
4989− format!("'{}' needs a value: `{} VALUE`", attr.key, attr.key),
4990− &attr.key,
4991− );
4992− }
4993− if vocab::is_html_attribute(base) && !prefixed {
4994− return fail(
4995− ctx,
4996− code::HTML_ATTRIBUTE_FORM,
4997− format!(
4998− "'{}' is an HTML attribute that isn't a flag: write `{}=VALUE`",
4999− base, base
5000− ),
5001− base,
5002− );
2732+ _ => {}
50032733 }
5004− return unknown_attribute(attr, base, line, column, before, true, ctx);
5005− };
5006−
5007− if vocab::HTMLANG_FLAGS.contains(&base) {
5008− return fail(
5009− ctx,
5010− code::INVALID_VALUE,
5011− format!(
5012− "'{}' is a flag and takes no value: write `{}` alone",
5013− base, attr.key
5014− ),
5015− &attr.key,
5016− );
5017− }
5018− if vocab::is_style_attribute(base)
5019− || vocab::is_custom_property(base)
5020− || vocab::is_vendor_property(base)
5021− {
5022− return check_css_value(attr, base, line, column, ctx);
50232734 }
5024− if vocab::is_html_attribute(base) && !prefixed {
5025− let diagnostic = Diagnostic::error(
5026− code::HTML_ATTRIBUTE_FORM,
5027− line,
5028− format!(
5029− "'{}' is an HTML attribute: write `{}={}`",
5030− attr.key, attr.key, value
5031− ),
5032− )
5033− .subject(attr.key.as_str());
5034− let diagnostic = at_attribute(diagnostic, column, ctx);
5035− ctx.diagnostics.push(diagnostic);
5036− return false;
2735+
2736+ if depth != 0 {
2737+ return Err(ParseError {
2738+ line: line_num,
2739+ message: "unclosed '[' in attribute list".to_string(),
2740+ });
50372741 }
5038− let passes = vocab::is_property_name(base);
5039− unknown_attribute(attr, base, line, column, before, !passes, ctx)
5040− && check_css_value(attr, base, line, column, ctx)
5041−}
50422742
5043−/// Whether an attribute of a bundle could pass a parameter to a function
5044−/// it is spliced into (`@let t [title Hello]`): a name without a prefix
5045−/// that isn't a style or a flag. Such a name is checked where the bundle is
5046−/// used.
5047−fn could_be_parameter(attr: &Attribute) -> bool {
5048− use crate::vocab;
5049− let key = attr.key.as_str();
5050− let flag =
5051− attr.value.is_none() && (vocab::HTMLANG_FLAGS.contains(&key) || vocab::is_html_flag(key));
5052− !attr.html
5053− && !flag
5054− && !vocab::is_style_attribute(key)
5055− && key.starts_with(|c: char| c.is_alphabetic())
5056− && key
5057− .chars()
5058− .all(|c| c.is_alphanumeric() || matches!(c, '-' | '_'))
5059−}
2743+ let attrs_inner = &input[1..end_pos];
2744+ let remaining = input[end_pos + 1..].trim().to_string();
2745+ let attrs = parse_attr_list(attrs_inner, line_num, ctx, validate);
50602746
5061−/// At a call, a name close to one of the function's parameters is a
5062−/// misspelled parameter, not an attribute for its root: report it, and
5063−/// return true (it is left out).
5064−fn misspelled_parameter(
5065− attr: &Attribute,
5066− text_keys: &[String],
5067− line: usize,
5068− column: Option<usize>,
5069− ctx: &mut ParseContext,
5070−) -> bool {
5071− if text_keys.is_empty() || !could_be_parameter(attr) {
5072− return false;
5073− }
5074− let params: Vec<&str> = text_keys.iter().map(String::as_str).collect();
5075− let Some(closest) = suggest_closest(&attr.key, ¶ms) else {
5076− return false;
5077− };
5078− let what = if ctx.in_page {
5079− "@page word"
5080− } else {
5081− "parameter"
5082− };
5083− let diagnostic = Diagnostic::error(
5084− code::UNKNOWN_ATTRIBUTE,
5085− line,
5086− format!(
5087− "unknown {} '{}', did you mean '{}'?",
5088− what, attr.key, closest
5089− ),
5090− )
5091− .subject(attr.key.as_str())
5092− .suggest(Some(closest));
5093− let diagnostic = at_attribute(diagnostic, column, ctx);
5094− ctx.diagnostics.push(diagnostic);
5095− true
2747+ Ok((attrs, remaining))
50962748}
50972749
5098−/// An attribute name htmlang doesn't know. A style whose name CSS could
5099−/// have goes to the CSS as written, with a warning; anything else (a flag,
5100−/// a name that isn't a word) is an error. Returns whether it is kept.
5101−fn unknown_attribute(
5102− attr: &Attribute,
5103− base: &str,
5104− line: usize,
5105− column: Option<usize>,
5106− before: Option<&Attribute>,
5107− error: bool,
5108− ctx: &mut ParseContext,
5109−) -> bool {
5110− // `@td padding 8`: an element prefix without its colon
5111− if let Some(name) = base.strip_prefix('@')
5112− && crate::ast::ElementKind::from_name(name).is_some()
5113− {
5114− let example = match attr.value.as_deref() {
5115− Some(value) => format!("{}:{}", attr.key, value.trim()),
5116− None => format!("{}:padding 8", attr.key),
5117− };
5118− let diagnostic = Diagnostic::error(
5119− code::UNKNOWN_ATTRIBUTE,
5120− line,
5121− format!(
5122− "unknown attribute '{}': an element prefix ends in a colon, as in `{}`",
5123− attr.key, example
5124− ),
5125− )
5126− .subject(base);
5127− let diagnostic = at_attribute(diagnostic, column, ctx);
5128− ctx.diagnostics.push(diagnostic);
5129− return false;
5130− }
5131− // `[card]` where `card` is a bundle: it is used as `$card`
5132− if attr.value.is_none() && ctx.env.bundle(base).is_some() && base == attr.key {
5133− ctx.used_defines.insert(base.to_string());
5134− let diagnostic = Diagnostic::error(
5135− code::UNKNOWN_ATTRIBUTE,
5136− line,
5137− format!(
5138− "unknown attribute '{}': '{}' is an attribute bundle, used as `${}`",
5139− base, base, base
5140− ),
5141− )
5142− .subject(base)
5143− .suggest(Some(format!("${}", base)));
5144− let diagnostic = at_attribute(diagnostic, column, ctx);
5145− ctx.diagnostics.push(diagnostic);
5146− return false;
5147− }
5148− // `hover:title x`: an HTML attribute's name is not a suggestion for
5149− // itself
5150− let suggestion =
5151− suggest_closest(base, &crate::vocab::all_attributes()).filter(|&closest| closest != base);
5152− // `hx-trigger=load, every 2s`: right after a `key=value`, a name that
5153− // isn't close to one htmlang knows is the rest of that value, which
5154− // the comma ended. It is left out.
5155− let cut = before.filter(|b| b.html && b.value.is_some());
5156− let rest = match &attr.value {
5157− Some(value) => format!("{} {}", attr.key, value),
5158− None => attr.key.clone(),
5159− };
5160− let joined = cut.map(|cut| {
5161− let value = cut.value.as_deref().unwrap_or("");
5162− (
5163− format!("{}={}", cut.key, value),
5164− format!("{}={}\\, {}", cut.key, value, rest),
5165− )
5166− });
5167− if let (Some((cut, joined)), None) = (&joined, suggestion) {
5168− let diagnostic = Diagnostic::error(
5169− code::SPLIT_VALUE,
5170− line,
5171− format!(
5172− "unknown attribute '{}' after `{}`: if '{}' is the rest of its value, the comma \
5173− ended it. To keep a comma in a value, write `\\,`: `{}`",
5174− base, cut, rest, joined
5175− ),
5176− )
5177− .subject(base);
5178− let diagnostic = at_attribute(diagnostic, column, ctx);
5179− ctx.diagnostics.push(diagnostic);
5180− return false;
2750+fn is_valid_hex_color(s: &str) -> bool {
2751+ if !s.starts_with('#') {
2752+ return true; // Not a hex color, skip
51812753 }
5182− let mut message = match (&suggestion, error) {
5183− (Some(closest), true) => {
5184− format!(
5185− "unknown attribute '{}', did you mean '{}'?",
5186− attr.key, closest
5187− )
5188− }
5189− (None, true) => format!("unknown attribute '{}'", attr.key),
5190− (Some(closest), false) => format!(
5191− "unknown CSS property '{}', did you mean '{}'? It is written to the CSS as it is",
5192− base, closest
5193− ),
5194− (None, false) => format!(
5195− "unknown CSS property '{}': it is written to the CSS as it is",
5196− base
5197− ),
5198− };
5199− // `box-shadow 0 1px red, 0 2px blue` or `font-family Inter,
5200− // sans-serif`: the comma ended the attribute, and the rest of the
5201− // value became one
5202− let rest_of_a_value = !base.starts_with(|c: char| c.is_ascii_alphabetic() || c == '-')
5203− || (suggestion.is_none() && attr.value.is_none() && before.is_some());
5204− if joined.is_some() || (rest_of_a_value && error) {
5205− if !message.ends_with('?') {
5206− message.push('.');
5207− }
5208− match &joined {
5209− Some((cut, joined)) => message.push_str(&format!(
5210− " If it is the rest of `{}`, the comma ended it: write `{}`",
5211− cut, joined
5212− )),
5213− None => message
5214− .push_str(" A comma separates attributes: to keep one in a value, write `\\,`"),
5215− }
5216− }
5217− let severity = if error {
5218− Severity::Error
5219− } else {
5220− Severity::Warning
5221− };
5222− let diagnostic = Diagnostic::new(code::UNKNOWN_ATTRIBUTE, severity, line, message)
5223− .subject(base)
5224− .suggest(suggestion);
5225− let diagnostic = at_attribute(diagnostic, column, ctx);
5226− ctx.diagnostics.push(diagnostic);
5227− !error
2754+ let hex = &s[1..];
2755+ matches!(hex.len(), 3 | 4 | 6 | 8) && hex.chars().all(|c| c.is_ascii_hexdigit())
52282756}
52292757
5230−/// Evaluate the attributes of a list: bundles are spliced in, `if()`
5231−/// chooses, and variables fill values. A variable fills only the value it
5232−/// is written in: attributes come from bundles, never from text. With
5233−/// `validate`, unknown names and invalid values are reported. `text_keys`
5234−/// are a called function's parameters: their values are text rather than
5235−/// CSS, and they aren't checked as attributes.
52362758fn parse_attr_list(
5237− tokens: &[syntax::Attr],
2759+ input: &str,
52382760 line_num: usize,
52392761 ctx: &mut ParseContext,
52402762 validate: bool,
5241− text_keys: &[String],
52422763) -> Vec<Attribute> {
5243− parse_attrs(tokens, line_num, ctx, validate, text_keys)
5244− .into_iter()
5245− .map(|(attr, _)| attr)
5246− .collect()
5247−}
5248−
5249−/// [`parse_attr_list`], with the value of each attribute whose key is one
5250−/// of `text_keys` (a call's parameters) as a value with its type (see
5251−/// [`ParseContext::slot_value`]), so a parameter can get a list or a
5252−/// record.
5253−fn parse_attrs(
5254− tokens: &[syntax::Attr],
5255− line_num: usize,
5256− ctx: &mut ParseContext,
5257− validate: bool,
5258− text_keys: &[String],
5259−) -> Vec<(Attribute, Option<Value>)> {
5260− let mut read = ReadAttrs::default();
5261− read_attrs(tokens, "", line_num, ctx, validate, text_keys, &mut read);
5262− read.attrs
5263−}
5264−
5265−/// The attributes of a list read so far, and the keys written (for the
5266−/// duplicate check).
5267−#[derive(Default)]
5268−struct ReadAttrs {
5269− attrs: Vec<(Attribute, Option<Value>)>,
5270− seen_keys: Vec<(String, bool)>,
5271−}
5272−
5273−/// [`parse_attrs`] for the attributes of `tokens`, each under the prefixes
5274−/// `prefix` (`md:` for those of `md:[...]`), which distribute over a
5275−/// group, a bundle and the branch an `if()` takes. Only styles take a
5276−/// prefix, so an HTML attribute there is an error.
5277−fn read_attrs(
5278− tokens: &[syntax::Attr],
5279− prefix: &str,
5280− line_num: usize,
5281− ctx: &mut ParseContext,
5282− validate: bool,
5283− text_keys: &[String],
5284− out: &mut ReadAttrs,
5285−) {
5286− let mut chosen = Vec::new();
5287− choose_attrs(
5288− tokens,
5289− prefix,
5290− line_num,
5291− ctx,
5292− validate,
5293− text_keys,
5294− &mut chosen,
5295− );
5296−
5297− for token in &chosen {
5298− let line = if token.span.line == 0 {
5299− line_num
5300− } else {
5301− token.span.line
2764+ let mut attrs = Vec::new();
2765+ let mut seen_keys: Vec<String> = Vec::new();
2766+
2767+ for part in split_commas(input) {
2768+ let part = part.trim();
2769+ // A whole attribute `if(cond, a, b)` is the chosen branch's text.
2770+ let chosen;
2771+ let part = match choose_if(part, ctx, line_num) {
2772+ Some(branch) => {
2773+ chosen = branch;
2774+ chosen.as_str()
2775+ }
2776+ None => part,
53022777 };
5303− let (key, value, html) = (token.key.clone(), token.value.clone(), token.html);
5304− let column = |at: usize| Some(token.span.column + at);
5305−
5306− // `md:[...]`, `md:$card`, `md:if(...)`: the prefixes apply to each
5307− // attribute there, and a prefix a parameter can't have
5308− if let Some(prefixed) = &token.prefixed {
5309− if let Some(inner) = group_prefix(token, prefixed, prefix, line, ctx) {
5310− read_attrs(
5311− prefixed.target.attrs(),
5312− &inner,
5313− line_num,
5314− ctx,
5315− validate,
5316− text_keys,
5317− out,
5318− );
5319− }
2778+ if part.is_empty() {
53202779 continue;
53212780 }
53222781
5323− // `$name` (or `${name}`) alone: an attribute bundle, spliced in
5324− let bundle = key.strip_prefix('$').filter(|_| value.is_none() && !html);
5325− let bundle = bundle.and_then(|after| match interp::reference(after, &ctx.env)? {
5326− (interp::Reference::Var(name), len) if len == after.len() => Some(name),
5327− _ => None,
5328− });
5329− if let Some(name) = bundle {
5330− if let Some(define_attrs) = ctx.env.bundle(&name).cloned() {
5331− ctx.used_defines.insert(name.clone());
5332− for attr in define_attrs.iter() {
5333− if !prefix.is_empty() {
5334− let prefixed = Attribute {
5335− key: format!("{}{}", prefix, attr.key),
5336− ..attr.clone()
5337− };
5338− if prefixed_parameter(&prefixed, text_keys, line, column(0), validate, ctx)
5339− {
5340− continue;
5341− }
5342− if let Some(attr) =
5343− prefixed_member(attr, prefix, &name, line, column(0), validate, ctx)
5344− {
5345− out.attrs.push((attr, None));
5346− }
5347− continue;
5348− }
5349− let attrs = &out.attrs;
5350− // Checked here, where it is either a parameter or not
5351− let checked_here = validate
5352− && !ctx.in_bundle
5353− && could_be_parameter(attr)
5354− && !text_keys.contains(&attr.key);
5355− if checked_here
5356− && (misspelled_parameter(attr, text_keys, line, column(0), ctx)
5357− || !check_attribute(
5358− attr,
5359− line,
5360− column(0),
5361− attrs.last().map(|(a, _)| a),
5362− ctx,
5363− ))
5364− {
5365− continue;
5366− }
5367− out.attrs.push((attr.clone(), None));
5368− }
5369− } else {
5370− not_a_bundle(&name, line, column(0), ctx);
5371− }
5372− continue;
5373− }
5374− // A name never comes from a variable
5375− if key.contains('$') {
5376− track_var_refs(&key, &mut ctx.used_variables);
5377− ctx.diagnostics.push(
5378− Diagnostic::error(
5379− code::ATTRIBUTE_FROM_VARIABLE,
5380− line,
5381− format!(
5382− "'{}': an attribute's name can't come from a variable. A variable \
5383− fills a value (`padding $size`), and whole attributes come from a \
5384− bundle (`@let name [padding 8]`, used as `[$name]`)",
5385− key
5386− ),
5387− )
5388− .subject(key.as_str()),
5389− );
2782+ // $define reference — expand attribute bundle
2783+ if let Some(name) = part.strip_prefix('$')
2784+ && let Some(define_attrs) = ctx.defines.get(name)
2785+ {
2786+ ctx.used_defines.insert(name.to_string());
2787+ attrs.extend(define_attrs.clone());
53902788 continue;
53912789 }
53922790
5393− // Only a style has states: `md:[id=x]`, `md:id=x`
5394− if html && (!prefix.is_empty() || !crate::vocab::split_prefixes(&key).0.is_empty()) {
5395− let written = format!("{}{}", prefix, key);
5396− let (name, _) = crate::vocab::split_prefixes(&written);
5397− let diagnostic = Diagnostic::error(
5398− code::INVALID_PREFIX,
5399− line,
5400− format!(
5401− "'{}=': a prefix applies to a style, and `{}=` is an HTML attribute, \
5402− which has no states",
5403− written,
5404− &written[name.concat().len()..]
2791+ track_var_refs(part, &mut ctx.used_variables);
2792+
2793+ if let Some((attr, condition)) = split_trailing_if(part) {
2794+ ctx.diagnostics.push(Diagnostic {
2795+ line: line_num,
2796+ column: None,
2797+ message: format!(
2798+ "`KEY if CONDITION` was removed: write `if({}, {})`",
2799+ condition, attr
54052800 ),
5406− )
5407− .subject(token.key.as_str());
5408− let diagnostic = at_attribute(diagnostic, column(0), ctx);
5409− ctx.diagnostics.push(diagnostic);
2801+ severity: Severity::Error,
2802+ source_line: None,
2803+ });
54102804 continue;
54112805 }
5412− let key = if prefix.is_empty() {
5413− key
5414− } else {
5415− format!("{}{}", prefix, key)
2806+ // A value `if(cond, a, b)` picks `a` or `b` (free text) by `cond`;
2807+ // an empty choice leaves the attribute out.
2808+ let Some(part) = choose_if_value(part, ctx, line_num) else {
2809+ continue;
54162810 };
2811+ let part = substitute_vars(&part, &ctx.variables);
54172812
5418− // A value's variables are filled in. A style's value is CSS, where
5419− // quoted text keeps its quotes; an HTML attribute's (and a
5420− // parameter's) is text, where it loses them.
5421− let sink = if html || text_keys.contains(&key) {
5422− Sink::Text
5423− } else {
5424− Sink::Css
5425− };
5426− let mut filled = true;
5427− let mut quoted = None;
5428− let mut typed = None;
5429− let value = match value {
5430− None => None,
5431− // A parameter's value keeps its type
5432− Some(value) if !html && text_keys.contains(&key) => {
5433− let at = column(token.raw.len() - value.len());
5434− let (value, ok) = ctx.slot_value(&value, line, at);
5435− filled = ok;
5436− if let Value::Quoted(q) = &value {
5437− quoted = Some(q.clone());
5438− }
5439− let text = value.to_string();
5440− typed = Some(value);
5441− Some(text)
2813+ let attr = if let Some((key, value)) = split_html_attribute(&part) {
2814+ Attribute {
2815+ key: key.to_string(),
2816+ value: Some(value.to_string()),
2817+ html: true,
54422818 }
5443− Some(value) => {
5444− let at = column(token.raw.len() - value.len());
5445− let (text, is_quoted, ok) = ctx.fill_value(&value, line, at, sink);
5446− filled = ok;
5447− quoted = is_quoted;
5448− Some(text)
2819+ } else if let Some((key, value)) = part.split_once(' ') {
2820+ let value = value.trim().to_string();
2821+ Attribute {
2822+ key: key.trim().to_string(),
2823+ value: Some(value),
2824+ html: false,
2825+ }
2826+ } else {
2827+ Attribute {
2828+ key: part.to_string(),
2829+ value: None,
2830+ html: false,
54492831 }
54502832 };
5451− let attr = Attribute {
5452− key,
5453− value,
5454− html,
5455− quoted,
5456− };
5457− // A value that couldn't be filled in is already reported, and a
5458− // parameter's value is text for the function
5459− let validate = validate && filled && !text_keys.contains(&attr.key);
54602833
5461− // A duplicate is reported (compare the full key, so `border` and
5462− // `hover:border` differ, and the form, so `width=800` and
5463− // `width 200` do too), and the later one wins
2834+ // Warn on duplicate attributes (compare full key so pseudo-class
2835+ // variants like `border` and `hover:border` are not conflated)
54642836 if validate {
5465− let seen = (normal_key(&attr.key), attr.html);
5466− if out.seen_keys.contains(&seen) {
5467− let written = if attr.html { "=" } else { "" };
5468− let message = format!(
5469− "duplicate attribute '{}{}': the later one wins",
5470− attr.key, written
5471− );
5472− let diagnostic = Diagnostic::warning(code::DUPLICATE_ATTRIBUTE, line, message)
5473− .subject(attr.key.as_str());
5474− let diagnostic = at_attribute(diagnostic, column(0), ctx);
5475− ctx.diagnostics.push(diagnostic);
2837+ if seen_keys.contains(&attr.key) {
2838+ ctx.diagnostics.push(Diagnostic {
2839+ line: line_num,
2840+ column: None,
2841+ message: format!("duplicate attribute '{}'", attr.key),
2842+ severity: Severity::Warning,
2843+ source_line: None,
2844+ });
54762845 } else {
5477− out.seen_keys.push(seen);
2846+ seen_keys.push(attr.key.clone());
54782847 }
5479− }
54802848
5481− if validate && misspelled_parameter(&attr, text_keys, line, column(0), ctx) {
5482− continue;
5483− }
5484− if prefixed_parameter(&attr, text_keys, line, column(0), validate, ctx) {
5485− continue;
5486− }
5487− if validate && attr.html && attr.key == "class" {
5488− reserved_class(&attr, line, column(0), ctx);
5489− }
5490− // `padding=4`: a style written as an HTML attribute, which the
5491− // browser ignores (`width=` and `height=` are real on some
5492− // elements, see `validate_tree`)
5493− if validate
5494− && attr.html
5495− && crate::vocab::is_style_attribute(&attr.key)
5496− && !crate::vocab::HTML_ATTRIBUTES.contains(&attr.key.as_str())
5497− {
5498− let value = token.value.as_deref().unwrap_or("").trim();
5499− let diagnostic = Diagnostic::warning(
5500− code::HTML_ATTRIBUTE_FORM,
5501− line,
5502− format!(
5503− "'{0}={1}' is an HTML attribute, but {0} is a style: write `{0} {1}`",
5504− attr.key, value
5505− ),
5506− )
5507− .subject(token.raw.as_str())
5508− .suggest(Some(format!("{} {}", attr.key, value)));
5509− let diagnostic = at_attribute(diagnostic, column(0), ctx);
5510− ctx.diagnostics.push(diagnostic);
2849+ // Color validation for hex colors
2850+ if !attr.html
2851+ && matches!(crate::vocab::base_attribute(&attr.key), "background" | "color")
2852+ && let Some(ref val) = attr.value
2853+ && val.starts_with('#')
2854+ && !is_valid_hex_color(val)
2855+ {
2856+ ctx.diagnostics.push(Diagnostic {
2857+ line: line_num,
2858+ column: None,
2859+ message: format!("invalid hex color '{}'", val),
2860+ severity: Severity::Warning,
2861+ source_line: None,
2862+ });
2863+ }
55112864 }
55122865
5513− // A style or a flag: its name is checked, and what can't be
5514− // written into the page is an error and left out
5515− let checked = validate && !attr.html && !(ctx.in_bundle && could_be_parameter(&attr));
5516− let before = out.attrs.last().map(|(a, _)| a);
5517− if checked && !check_attribute(&attr, line, column(0), before, ctx) {
5518− continue;
2866+ // Warn on unknown attributes. `key=value` HTML attributes may use any
2867+ // name; everything else must be a known style.
2868+ if validate && !attr.html {
2869+ let base_key = crate::vocab::base_attribute(attr.key.as_str());
2870+ let is_boolean_html =
2871+ attr.value.is_none() && crate::vocab::BOOLEAN_HTML_ATTRS.contains(&base_key);
2872+ // A removed attribute that shares its name with a CSS property
2873+ // (bare `grid`) still gets its hint.
2874+ let removed = removed_attribute_hint(base_key)
2875+ .filter(|_| attr.value.is_none() || !crate::vocab::is_css_property(base_key));
2876+ if let Some(hint) = removed {
2877+ ctx.diagnostics.push(Diagnostic {
2878+ line: line_num,
2879+ column: None,
2880+ message: format!(
2881+ "attribute '{}' was removed: {} (run `htmlang upgrade`)",
2882+ base_key, hint
2883+ ),
2884+ severity: Severity::Warning,
2885+ source_line: None,
2886+ });
2887+ } else if is_boolean_html || crate::vocab::is_style_attribute(base_key) {
2888+ validate_attr_value(&attr, line_num, ctx);
2889+ } else if crate::vocab::HTML_ATTRIBUTES.contains(&base_key)
2890+ || base_key.starts_with("aria-")
2891+ || base_key.starts_with("data-")
2892+ {
2893+ ctx.diagnostics.push(Diagnostic {
2894+ line: line_num,
2895+ column: None,
2896+ message: format!(
2897+ "'{}' is an HTML attribute: write `{}={}` (run `htmlang upgrade`)",
2898+ attr.key,
2899+ attr.key,
2900+ attr.value.as_deref().unwrap_or("")
2901+ ),
2902+ severity: Severity::Warning,
2903+ source_line: None,
2904+ });
2905+ } else {
2906+ let suggestion = suggest_closest(base_key, &crate::vocab::all_attributes());
2907+ let msg = match suggestion {
2908+ Some(closest) => {
2909+ format!(
2910+ "unknown attribute '{}', did you mean '{}'?",
2911+ attr.key, closest
2912+ )
2913+ }
2914+ None => format!("unknown attribute '{}'", attr.key),
2915+ };
2916+ ctx.diagnostics.push(Diagnostic {
2917+ line: line_num,
2918+ column: None,
2919+ message: msg,
2920+ severity: Severity::Warning,
2921+ source_line: None,
2922+ });
2923+ }
55192924 }
55202925
5521− out.attrs.push((attr, typed));
2926+ attrs.push(attr);
55222927 }
2928+
2929+ attrs
55232930}
55242931
5525−/// At a call, a parameter under prefixes (`md:title x`, `md:[title x]`):
5526−/// a parameter has one value, with no states, so it is reported (with
5527−/// `validate`) and left out; returns true then. A parameter named like a
5528−/// style (`color`) is a style under a prefix, for the root element.
5529−fn prefixed_parameter(
5530− attr: &Attribute,
5531− text_keys: &[String],
5532− line: usize,
5533− column: Option<usize>,
5534− validate: bool,
5535− ctx: &mut ParseContext,
5536−) -> bool {
5537− let (prefixes, name) = crate::vocab::split_prefixes(&attr.key);
5538− if attr.html
5539− || prefixes.is_empty()
5540− || !text_keys.iter().any(|k| k == name)
5541− || crate::vocab::is_style_attribute(name)
5542− {
5543− return false;
5544− }
5545− if validate {
5546− let what = if ctx.in_page {
5547− "@page's own word"
5548− } else {
5549− "a parameter"
5550− };
5551− let diagnostic = Diagnostic::error(
5552− code::INVALID_PREFIX,
5553− line,
5554− format!(
5555− "'{}': `{}` is {}, which has one value, and a prefix applies to a style, \
5556− which has states",
5557− attr.key, name, what
5558− ),
5559− )
5560− .subject(attr.key.as_str());
5561− let diagnostic = at_attribute(diagnostic, column, ctx);
5562− ctx.diagnostics.push(diagnostic);
5563− }
5564− true
2932+/// Split an HTML attribute written `key=value` (`alt=`, `type=email`,
2933+/// `aria-label=Close menu`). Returns `None` for style attributes.
2934+fn split_html_attribute(part: &str) -> Option<(&str, &str)> {
2935+ let first_token = part.split(char::is_whitespace).next()?;
2936+ let eq = first_token.find('=')?;
2937+ let key = &part[..eq];
2938+ let valid_key = key.starts_with(|c: char| c.is_ascii_alphabetic())
2939+ && key
2940+ .chars()
2941+ .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'));
2942+ valid_key.then(|| (key, part[eq + 1..].trim()))
55652943}
55662944
5567−/// The prefixes of a prefixed group, bundle or `if()` inside `outer` (the
5568−/// prefixes of the groups it is in), when they are all known; else the
5569−/// unknown one is reported. Text after a group's `]` is an error too.
5570−fn group_prefix(
5571− token: &syntax::Attr,
5572− prefixed: &syntax::Prefixed,
5573− outer: &str,
5574− line: usize,
5575− ctx: &mut ParseContext,
5576−) -> Option<String> {
5577− let at = |ctx: &ParseContext, diagnostic: Diagnostic, span: syntax::Span| match &ctx
5578− .current_source
5579− {
5580− (current, Some(text)) if span.line != 0 && *current == span.line => {
5581− diagnostic.column(span.column).source(text.clone())
5582− }
5583− _ => diagnostic,
5584− };
5585− if let syntax::Branch::Group {
5586− trailing: Some(trailing),
5587− ..
5588− } = &prefixed.target
5589− {
5590− let diagnostic = Diagnostic::error(
5591− code::UNEXPECTED_ARGUMENT,
5592− line,
5593− format!(
5594− "'{}' after the `]` of `{}[...]`: the prefixes apply to the attributes in the \
5595− group, so it goes inside it",
5596− trailing.raw, prefixed.prefix
5597− ),
5598− )
5599− .subject(trailing.raw.as_str());
5600− let diagnostic = at(ctx, diagnostic, trailing.span);
5601− ctx.push_once(diagnostic);
5602− }
5603− let (known, rest) = crate::vocab::split_prefixes(&prefixed.prefix);
5604− if !rest.is_empty() {
5605− let problem = unknown_prefix(rest).unwrap_or_else(|| {
5606− let written = rest.split_inclusive(':').next().unwrap_or(rest);
5607− PrefixProblem {
5608− message: format!("unknown prefix '{}'", written),
5609− subject: written.to_string(),
5610− suggestion: None,
2945+fn split_commas(input: &str) -> Vec<&str> {
2946+ let mut parts = Vec::new();
2947+ let mut start = 0;
2948+ let mut depth = 0;
2949+ let mut in_quotes = false;
2950+
2951+ for (i, c) in input.char_indices() {
2952+ match c {
2953+ '"' => in_quotes = !in_quotes,
2954+ _ if in_quotes => {}
2955+ '[' | '(' => depth += 1,
2956+ ']' | ')' => depth -= 1,
2957+ ',' if depth == 0 => {
2958+ parts.push(&input[start..i]);
2959+ start = i + 1;
56112960 }
5612− });
5613− let diagnostic = Diagnostic::error(code::UNKNOWN_PREFIX, line, problem.message)
5614− .subject(problem.subject)
5615− .suggest(problem.suggestion);
5616− let diagnostic = at(ctx, diagnostic, token.span);
5617− ctx.push_once(diagnostic);
5618− return None;
2961+ _ => {}
2962+ }
56192963 }
5620− Some(format!("{}{}", outer, known.concat()))
2964+ parts.push(&input[start..]);
2965+ parts
56212966}
56222967
5623−/// An attribute of the bundle `bundle`, spliced in under `prefix`
5624−/// (`md:$card`): the same attribute with the prefixes in front, when it can
5625−/// take them. An HTML attribute can't; a style's prefixes are checked, as
5626−/// is a flag or a name that isn't a style (a bundle's parameter), which
5627−/// under a prefix are attributes like any other.
5628−fn prefixed_member(
5629− attr: &Attribute,
5630− prefix: &str,
5631− bundle: &str,
5632− line: usize,
5633− column: Option<usize>,
5634− validate: bool,
5635− ctx: &mut ParseContext,
5636−) -> Option<Attribute> {
5637− let key = format!("{}{}", prefix, attr.key);
5638− if attr.html {
5639− if validate {
5640− let diagnostic = Diagnostic::error(
5641− code::INVALID_PREFIX,
5642− line,
5643− format!(
5644− "'{}${}': the bundle has `{}=`, an HTML attribute, and a prefix applies to \
5645− styles, which have states",
5646− prefix, bundle, attr.key
5647− ),
5648− )
5649− .subject(format!("{}${}", prefix, bundle));
5650− let diagnostic = at_attribute(diagnostic, column, ctx);
5651− ctx.diagnostics.push(diagnostic);
2968+// ---------------------------------------------------------------------------
2969+// Chain splitting (the > operator)
2970+// ---------------------------------------------------------------------------
2971+
2972+fn split_chain(content: &str) -> Vec<String> {
2973+ let mut segments = Vec::new();
2974+ let mut current = String::new();
2975+ let chars: Vec<char> = content.chars().collect();
2976+ let mut i = 0;
2977+ let mut bracket_depth = 0;
2978+
2979+ while i < chars.len() {
2980+ if chars[i] == '[' {
2981+ bracket_depth += 1;
56522982 }
5653− return None;
5654− }
5655− let prefixed = Attribute {
5656− key,
5657− ..attr.clone()
5658− };
5659− if validate {
5660− let fine = if attr.value.is_none() || could_be_parameter(attr) {
5661− check_attribute(&prefixed, line, column, None, ctx)
5662− } else {
5663− check_prefixes(&prefixed, line, column, ctx)
5664− };
5665− if !fine {
5666− return None;
2983+ if chars[i] == ']' {
2984+ bracket_depth -= 1;
56672985 }
5668− }
5669− Some(prefixed)
5670−}
56712986
5672−/// `class=hl-x`: the `hl-` prefix is htmlang's, for its generated classes,
5673−/// whose rules would then apply to the element too. It goes into the page
5674−/// as written, so this is a warning.
5675−fn reserved_class(attr: &Attribute, line: usize, column: Option<usize>, ctx: &mut ParseContext) {
5676− let classes = attr.value.as_deref().unwrap_or_default();
5677− for class in classes.split_whitespace() {
5678− if class.starts_with(crate::codegen::CLASS_PREFIX) {
5679− let diagnostic = Diagnostic::warning(
5680− code::INVALID_VALUE,
5681− line,
5682− format!(
5683− "class '{}' starts with `{}`, which htmlang keeps for the classes it \
5684− generates, so their styles could apply to this element: give it \
5685− another name",
5686− class,
5687− crate::codegen::CLASS_PREFIX
5688− ),
5689− )
5690− .subject(class);
5691− let diagnostic = at_attribute(diagnostic, column, ctx);
5692− ctx.diagnostics.push(diagnostic);
2987+ // Match " > @" outside brackets
2988+ if bracket_depth == 0
2989+ && i + 3 < chars.len()
2990+ && chars[i] == ' '
2991+ && chars[i + 1] == '>'
2992+ && chars[i + 2] == ' '
2993+ && chars[i + 3] == '@'
2994+ {
2995+ segments.push(current.trim().to_string());
2996+ current = String::new();
2997+ i += 3; // skip " > ", keep the "@"
2998+ continue;
56932999 }
3000+
3001+ current.push(chars[i]);
3002+ i += 1;
56943003 }
5695−}
56963004
5697−/// A style's key as the CSS reads it, for finding duplicates: its at-rule
5698−/// prefixes in one order (`dark:md:` is `md:dark:`), then its selector
5699−/// prefixes as written, whose order is the selector's.
5700−fn normal_key(key: &str) -> String {
5701− let (prefixes, name) = crate::vocab::split_prefixes(key);
5702− let mut at: Vec<(usize, &str)> = prefixes
5703− .iter()
5704− .filter_map(|p| crate::vocab::at_rule_rank(p).map(|rank| (rank, *p)))
5705− .collect();
5706− at.sort_unstable();
5707− at.dedup();
5708− let mut normal: String = at.iter().map(|(_, p)| *p).collect();
5709− for prefix in prefixes
5710− .iter()
5711− .filter(|p| crate::vocab::at_rule_rank(p).is_none())
5712− {
5713− normal.push_str(prefix);
3005+ if !current.trim().is_empty() {
3006+ segments.push(current.trim().to_string());
57143007 }
5715− normal.push_str(name);
5716− normal
5717−}
57183008
5719−/// `[$name]` where `$name` isn't an attribute bundle.
5720−fn not_a_bundle(name: &str, line: usize, column: Option<usize>, ctx: &mut ParseContext) {
5721− track_var_refs(&format!("${}", name), &mut ctx.used_variables);
5722− let is_value = interp::name_len(name) > 0 && interp::resolve(name, &ctx.env).is_some();
5723− let diagnostic = if is_value {
5724− Diagnostic::error(
5725− code::ATTRIBUTE_FROM_VARIABLE,
5726− line,
5727− format!(
5728− "'${}' is a value, not an attribute: attributes come from a bundle \
5729− (`@let name [padding 8]`, used as `[$name]`), and a value fills an \
5730− attribute's value (`padding ${}`)",
5731− name, name
5732− ),
5733− )
5734− .subject(name)
5735− } else if ctx.env.function(name).is_some() {
5736− ctx.used_functions.insert(name.to_string());
5737− Diagnostic::error(
5738− code::UNDEFINED_VARIABLE,
5739− line,
5740− format!(
5741− "'${}' is a function, not an attribute bundle: it is called as an element, \
5742− `@{}`",
5743− name, name
5744− ),
5745− )
5746− .subject(name)
5747− } else {
5748− let mut bundles = ctx.env.bundle_names();
5749− bundles.sort_unstable();
5750− let suggestion = suggest_closest(name, &bundles);
5751− let message = match suggestion {
5752− Some(closest) => format!(
5753− "undefined attribute bundle '${}', did you mean '${}'?",
5754− name, closest
5755− ),
5756− None => format!("undefined attribute bundle '${}'", name),
5757− };
5758− Diagnostic::error(code::UNDEFINED_VARIABLE, line, message)
5759− .subject(name)
5760− .suggest(suggestion)
5761− };
5762− let diagnostic = match (&ctx.current_source, column) {
5763− ((current, Some(text)), Some(column)) if *current == line => {
5764− diagnostic.column(column).source(text.clone())
5765− }
5766− _ => diagnostic,
5767− };
5768− ctx.diagnostics.push(diagnostic);
3009+ segments
57693010}
57703011
57713012// ---------------------------------------------------------------------------
57723013// Text segment parsing (inline {...} elements)
57733014// ---------------------------------------------------------------------------
57743015
5775−/// While a slot is filled in, each escape (see [`syntax::ESCAPES`]) is a
5776−/// private-use placeholder, U+E000 plus its place in the table, so it
5777−/// can't start a variable, a quote or an inline element. Afterwards it
5778−/// becomes what it stands for.
5779−fn protect_escapes(text: &str) -> String {
5780− if !text.contains('\\') {
5781− return text.to_string();
5782− }
5783− let mut out = String::with_capacity(text.len());
3016+fn parse_text_segments(input: &str, ctx: &mut ParseContext) -> Vec<TextSegment> {
3017+ let mut segments = Vec::new();
3018+ let mut current_text = String::new();
3019+ let chars: Vec<char> = input.chars().collect();
57843020 let mut i = 0;
5785− while let Some(c) = text[i..].chars().next() {
5786− let len = syntax::escape_len(&text[i..]);
5787− if len == 0 {
5788− out.push(c);
5789− i += c.len_utf8();
5790− continue;
5791− }
5792− let escape = &text[i..i + len];
5793− let index = syntax::ESCAPES.iter().position(|e| *e == escape);
5794− out.extend(index.and_then(|n| char::from_u32(0xE000 + n as u32)));
5795− i += len;
5796− }
5797− out
5798−}
5799−
5800−/// The escape a placeholder stands for, as written (`\,`).
5801−fn escape_of(c: char) -> Option<&'static str> {
5802− let index = (c as u32).checked_sub(0xE000)?;
5803− syntax::ESCAPES.get(index as usize).copied()
5804−}
5805−
5806−fn restore_escapes(text: &str) -> String {
5807− text.chars()
5808− .fold(String::with_capacity(text.len()), |mut out, c| {
5809− match escape_of(c) {
5810− // What the escape stands for: what follows the backslash
5811− Some(escape) => out.push_str(&escape[1..]),
5812− None => out.push(c),
5813− }
5814− out
5815− })
5816−}
58173021
5818−/// Inside the quoted strings of a CSS value, `\"` and `\\` mean in CSS what
5819−/// they mean in htmlang, so they stay as written there.
5820−fn keep_css_string_escapes(protected: &str) -> String {
5821− let mut out = String::with_capacity(protected.len());
5822− let mut inside = false;
5823− for c in protected.chars() {
5824− match escape_of(c) {
5825− Some(escape @ ("\\\"" | "\\\\")) if inside => out.push_str(escape),
5826− _ => {
5827− if c == '"' {
5828− inside = !inside;
3022+ while i < chars.len() {
3023+ if chars[i] == '{' && i + 1 < chars.len() && chars[i + 1] == '@' {
3024+ // Flush accumulated plain text
3025+ if !current_text.is_empty() {
3026+ segments.push(TextSegment::Plain(substitute_vars(
3027+ ¤t_text,
3028+ &ctx.variables,
3029+ )));
3030+ current_text.clear();
3031+ }
3032+
3033+ // Find matching }
3034+ let mut depth = 0;
3035+ let start = i + 1; // after {
3036+ i += 1;
3037+ loop {
3038+ if i >= chars.len() {
3039+ break;
58293040 }
5830− out.push(c);
3041+ if chars[i] == '{' {
3042+ depth += 1;
3043+ } else if chars[i] == '}' {
3044+ if depth == 0 {
3045+ break;
3046+ }
3047+ depth -= 1;
3048+ }
3049+ i += 1;
58313050 }
5832− }
5833− }
5834− out
5835−}
58363051
5837−/// Evaluate text: fill in the variables of its plain runs and build its
5838−/// inline elements. Each run is one slot, so a value can't make markup.
5839−fn text_segments(text: &syntax::Text, ctx: &mut ParseContext) -> Vec<TextSegment> {
5840− let mut segments = Vec::new();
5841− // The plain text so far, and where it starts
5842− let mut plain = String::new();
5843− let mut start: Option<syntax::Span> = None;
5844− let flush = |plain: &mut String,
5845− start: &mut Option<syntax::Span>,
5846− segments: &mut Vec<TextSegment>,
5847− ctx: &mut ParseContext| {
5848− if !plain.is_empty() {
5849− let at = start.unwrap_or(text.span);
5850− let filled = ctx.interpolate_text(plain, at.line, Some(at.column));
5851− segments.push(TextSegment::Plain(filled));
5852− plain.clear();
5853− }
5854− *start = None;
5855− };
5856− for segment in &text.segments {
5857− match segment {
5858− Segment::Plain { raw, span } => {
5859− start.get_or_insert(*span);
5860− plain.push_str(raw);
5861− }
5862− Segment::Inline(inline) => {
5863− let line = ctx.current_line;
5864− match resolve(&inline.head, inline.text.as_ref(), line, &text.raw, ctx) {
5865− Ok(resolved) => {
5866− if !inline.closed {
5867− let d = Diagnostic::warning(
5868− code::UNCLOSED_BRACKET,
5869− inline.span.line,
5870− format!(
5871− "unclosed `{{`: the inline @{} runs to the end of the line. \
5872− An inline element ends with `}}` (a brace that is text is \
5873− written `\\{{`)",
5874− inline.head.name
5875− ),
5876− );
5877− let d = at_attribute(d, Some(inline.span.column), ctx);
5878− ctx.push_once(d);
5879− }
5880− flush(&mut plain, &mut start, &mut segments, ctx);
5881− // A function called inline gets no children: its
5882− // content is the text after its attributes
5883− match Evaluator.complete(resolved, Vec::new(), ctx) {
5884− Ok(nodes) => segments.extend(inline_segments(nodes, line)),
5885− Err(mut e) => {
5886− e.source_line
5887− .get_or_insert_with(|| text.raw.as_str().into());
5888− ctx.diagnostics.push(e);
5889− }
5890− }
5891− }
5892− Err(mut e) => {
5893− // A misspelled element is an error inline too (a
5894− // brace that is text is written `\{`); the braces
5895− // stay as written
5896− e.source_line = Some(text.raw.as_str().into());
5897− ctx.diagnostics.push(e);
5898− start.get_or_insert(inline.span);
5899− plain.push('{');
5900− plain.push_str(&inline.raw);
5901− if inline.closed {
5902− plain.push('}');
5903− }
3052+ let inner: String = chars[start..i].iter().collect();
3053+ i += 1; // skip }
3054+
3055+ match parse_single_element(&inner, ctx.current_line, ctx) {
3056+ Ok(elem) => segments.push(TextSegment::Inline(elem)),
3057+ Err(e) => {
3058+ // Keep the braces as literal text, but flag what looks
3059+ // like a mistyped inline element.
3060+ if inner.trim_start().starts_with('@') {
3061+ ctx.diagnostics.push(Diagnostic {
3062+ line: ctx.current_line,
3063+ column: None,
3064+ message: e.message,
3065+ severity: Severity::Warning,
3066+ source_line: Some(input.to_string()),
3067+ });
59043068 }
3069+ current_text.push('{');
3070+ current_text.push_str(&inner);
3071+ current_text.push('}');
59053072 }
59063073 }
3074+ } else {
3075+ current_text.push(chars[i]);
3076+ i += 1;
59073077 }
59083078 }
5909− flush(&mut plain, &mut start, &mut segments, ctx);
5910− segments
5911−}
59123079
5913−/// The variable `raw` is, when it is exactly one `$name` or `${name}`.
5914−fn whole_reference(raw: &str, env: &Env) -> Option<String> {
5915− let after = raw.trim().strip_prefix('$')?;
5916− match interp::reference(after, env)? {
5917− (interp::Reference::Var(path), len) if len == after.len() => Some(path),
5918− _ => None,
3080+ if !current_text.is_empty() {
3081+ segments.push(TextSegment::Plain(substitute_vars(
3082+ ¤t_text,
3083+ &ctx.variables,
3084+ )));
59193085 }
3086+
3087+ segments
59203088}
59213089
5922−/// The attributes of `tokens` after each whole-attribute `if()` has
5923−/// chosen (see [`syntax::Choice`]), in order, into `out`. The branch not
5924−/// taken isn't evaluated; with `validate`, its attribute names are checked
5925−/// like code that doesn't run, under the prefixes `prefix` the `if()` is
5926−/// under (`hover:if(...)`).
5927−fn choose_attrs(
5928− tokens: &[syntax::Attr],
5929− prefix: &str,
5930− line_num: usize,
5931− ctx: &mut ParseContext,
5932− validate: bool,
5933− text_keys: &[String],
5934− out: &mut Vec<syntax::Attr>,
5935−) {
5936− for token in tokens {
5937− let Some(choice) = &token.choice else {
5938− out.push(token.clone());
5939− continue;
5940− };
5941− let Some(condition) = choice_shape(token, choice, line_num, ctx) else {
5942− continue;
5943− };
5944− let taken = match condition.span.line {
5945− 0 => ctx.condition(&condition.raw, line_num, None),
5946− line => ctx.condition(&condition.raw, line, Some(condition.span.column)),
5947− };
5948− let (chosen, other) = match taken {
5949− true => (choice.branches.first(), choice.branches.get(1)),
5950− false => (choice.branches.get(1), choice.branches.first()),
5951− };
5952− if let Some(other) = other {
5953− track_var_refs(&branch_text(other), &mut ctx.used_variables);
5954− if validate {
5955− check_branch(token, other, prefix, line_num, ctx, text_keys);
3090+// ---------------------------------------------------------------------------
3091+// Variable substitution
3092+// ---------------------------------------------------------------------------
3093+
3094+// ---------------------------------------------------------------------------
3095+// Condition evaluation for @if
3096+// ---------------------------------------------------------------------------
3097+
3098+/// Inclusive integer range from `start` to `end` (counting down when
3099+/// `start > end`), stepping by `step`. Stops instead of overflowing.
3100+fn numeric_range(start: i64, end: i64, step: i64) -> Vec<String> {
3101+ let mut items = Vec::new();
3102+ let mut n = start;
3103+ if start <= end {
3104+ while n <= end {
3105+ items.push(n.to_string());
3106+ match n.checked_add(step) {
3107+ Some(next) => n = next,
3108+ None => break,
59563109 }
59573110 }
5958− if let Some(branch) = chosen {
5959− choose_attrs(
5960− branch.attrs(),
5961− prefix,
5962− line_num,
5963− ctx,
5964− validate,
5965− text_keys,
5966− out,
5967− );
3111+ } else {
3112+ while n >= end {
3113+ items.push(n.to_string());
3114+ match n.checked_sub(step) {
3115+ Some(next) => n = next,
3116+ None => break,
3117+ }
59683118 }
59693119 }
3120+ items
59703121}
59713122
5972−/// Report what is wrong with the shape of `if()`: an empty condition, a
5973−/// number of branches other than one or two, text after a group's `]`.
5974−/// Returns the condition when the `if()` can be evaluated.
5975−fn choice_shape<'a>(
5976− token: &syntax::Attr,
5977− choice: &'a syntax::Choice,
5978− line_num: usize,
5979− ctx: &mut ParseContext,
5980−) -> Option<&'a syntax::Arg> {
5981− let line = if token.span.line == 0 {
5982− line_num
5983− } else {
5984− token.span.line
5985− };
5986− // The line the column points into, when it is the one being evaluated
5987− let source = |ctx: &ParseContext, diagnostic: Diagnostic, at: usize| match &ctx.current_source {
5988− (current, Some(text)) if *current == at => diagnostic.source(text.clone()),
5989− _ => diagnostic,
5990− };
5991− for branch in &choice.branches {
5992− if let syntax::Branch::Group {
5993− trailing: Some(trailing),
5994− ..
5995− } = branch
5996− {
5997− let diagnostic = source(
5998− ctx,
5999− Diagnostic::error(
6000− code::UNEXPECTED_ARGUMENT,
6001− trailing.span.line,
6002− format!(
6003− "'{}' after the `]` of a group in if(): a branch is one attribute, \
6004− one `[group]` of attributes or one `$bundle`",
6005− trailing.raw
6006− ),
6007− )
6008− .column(trailing.span.column)
6009− .subject(trailing.raw.as_str()),
6010− trailing.span.line,
6011− );
6012− ctx.push_once(diagnostic);
6013− }
6014− }
6015− match &choice.condition {
6016− Some(condition) if (1..=2).contains(&choice.branches.len()) => Some(condition),
6017− _ => {
6018− let diagnostic = source(
6019− ctx,
6020− Diagnostic::error(
6021− code::INVALID_EXPRESSION,
6022− line,
6023− format!(
6024− "`{}`: if() takes a condition and one or two branches, \
6025− `if(CONDITION, A, B)`",
6026− token.raw
6027− ),
6028− )
6029− .column(token.span.column),
6030− line,
6031− );
6032− ctx.push_once(diagnostic);
6033− None
3123+
3124+
3125+/// Find a leftover `key if condition` (ignoring ` if ` inside parentheses
3126+/// or quotes), to point at `if()`.
3127+fn split_trailing_if(part: &str) -> Option<(&str, &str)> {
3128+ let mut depth = 0;
3129+ let mut quote = None;
3130+ for (i, c) in part.char_indices() {
3131+ match c {
3132+ '"' | '\'' if quote == Some(c) => quote = None,
3133+ '"' | '\'' if quote.is_none() => quote = Some(c),
3134+ _ if quote.is_some() => {}
3135+ '(' => depth += 1,
3136+ ')' => depth -= 1,
3137+ _ if depth == 0 && part[i..].starts_with(" if ") => {
3138+ return Some((&part[..i], part[i + 4..].trim()));
3139+ }
3140+ _ => {}
60343141 }
60353142 }
3143+ None
60363144}
60373145
6038−/// A branch's text, for the names it uses.
6039−fn branch_text(branch: &syntax::Branch) -> String {
6040− let raws: Vec<&str> = branch.attrs().iter().map(|a| a.raw.as_str()).collect();
6041− raws.join(", ")
3146+/// Evaluate `if(cond, a)` or `if(cond, a, b)` when it is all of `text`,
3147+/// returning the chosen branch (empty when `cond` fails and there is no `b`).
3148+fn choose_if(text: &str, ctx: &mut ParseContext, line: usize) -> Option<String> {
3149+ let inner = text.strip_prefix("if(")?.strip_suffix(')')?;
3150+ let args = split_if_args(inner);
3151+ // `if(a) (b)` isn't one call
3152+ if split_trailing_paren(inner) || !(2..=3).contains(&args.len()) {
3153+ return None;
3154+ }
3155+ let branch = if ctx.condition(args[0].trim(), line) {
3156+ args[1]
3157+ } else {
3158+ args.get(2).copied().unwrap_or("")
3159+ };
3160+ Some(branch.trim().to_string())
60423161}
60433162
6044−/// Check attributes that are never evaluated (in code that doesn't run,
6045−/// or the branch an `if()` didn't take), as far as they can be checked:
6046−/// names are, and literal values; a value with a variable depends on what
6047−/// the variable holds. Each branch of an `if()` is checked on its own.
6048−fn check_attrs(tokens: &[syntax::Attr], line: usize, ctx: &mut ParseContext, text_keys: &[String]) {
6049− parse_attr_list(&literal_attrs(tokens), line, ctx, true, text_keys);
6050− check_choices(tokens, "", line, ctx, text_keys);
3163+/// Whether the parentheses in `inner` close before its end, as in the
3164+/// inside of `if(a)(b)`.
3165+fn split_trailing_paren(inner: &str) -> bool {
3166+ let mut depth = 0i32;
3167+ let mut quote = None;
3168+ for c in inner.chars() {
3169+ match c {
3170+ '"' | '\'' if quote == Some(c) => quote = None,
3171+ '"' | '\'' if quote.is_none() => quote = Some(c),
3172+ _ if quote.is_some() => {}
3173+ '(' => depth += 1,
3174+ ')' => {
3175+ depth -= 1;
3176+ if depth < 0 {
3177+ return true;
3178+ }
3179+ }
3180+ _ => {}
3181+ }
3182+ }
3183+ false
60513184}
60523185
6053−/// [`check_attrs`] for a branch of the `if()` `token`, under the prefixes
6054−/// `prefix` it is under: `hover:if($on, color red, [id=x])` checks
6055−/// `hover:[id=x]`, an error whichever branch is taken.
6056−fn check_branch(
6057− token: &syntax::Attr,
6058− branch: &syntax::Branch,
6059− prefix: &str,
6060− line: usize,
6061− ctx: &mut ParseContext,
6062− text_keys: &[String],
6063−) {
6064− if prefix.is_empty() {
6065− check_attrs(branch.attrs(), line, ctx, text_keys);
6066− return;
6067− }
6068− let list = syntax::AttrList {
6069− attrs: branch.attrs().to_vec(),
6070− span: token.span,
6071− closed: true,
6072− quoted_close: None,
6073− };
6074− let grouped = syntax::Attr {
6075− key: prefix.to_string(),
6076− value: None,
6077− html: false,
6078− raw: token.raw.clone(),
6079− span: token.span,
6080− choice: None,
6081− prefixed: Some(Box::new(syntax::Prefixed {
6082− prefix: prefix.to_string(),
6083− prefix_span: token.span,
6084− target: syntax::Branch::Group {
6085− list,
6086− trailing: None,
6087− },
6088− })),
3186+/// Resolve a value written `if(cond, a, b)`: evaluate `cond` and keep the
3187+/// chosen branch's text, or `None` when the choice is empty. Other
3188+/// attributes are returned unchanged.
3189+fn choose_if_value(part: &str, ctx: &mut ParseContext, line: usize) -> Option<String> {
3190+ let Some(pos) = part.find(['=', ' ']) else {
3191+ return Some(part.to_string());
60893192 };
6090− check_attrs(std::slice::from_ref(&grouped), line, ctx, text_keys);
3193+ let (head, value) = part.split_at(pos + 1);
3194+ match choose_if(value.trim(), ctx, line) {
3195+ Some(branch) if branch.is_empty() => None,
3196+ Some(branch) => Some(format!("{}{}", head, branch)),
3197+ None => Some(part.to_string()),
3198+ }
60913199}
60923200
6093−/// [`check_attrs`] for the branches of each `if()` of `tokens`, which are
6094−/// under the prefixes `prefix`, also inside a prefixed group or as a
6095−/// prefixed `if()`.
6096−fn check_choices(
6097− tokens: &[syntax::Attr],
6098− prefix: &str,
6099− line: usize,
6100− ctx: &mut ParseContext,
6101− text_keys: &[String],
6102−) {
6103− for token in tokens {
6104− if let Some(choice) = &token.choice
6105− && choice_shape(token, choice, line, ctx).is_some()
6106− {
6107− for branch in &choice.branches {
6108− check_branch(token, branch, prefix, line, ctx, text_keys);
3201+fn split_if_args(input: &str) -> Vec<&str> {
3202+ let mut parts = Vec::new();
3203+ let mut start = 0;
3204+ let mut depth = 0;
3205+ let mut quote = None;
3206+ for (i, c) in input.char_indices() {
3207+ match c {
3208+ '"' | '\'' if quote == Some(c) => quote = None,
3209+ '"' | '\'' if quote.is_none() => quote = Some(c),
3210+ _ if quote.is_some() => {}
3211+ '(' => depth += 1,
3212+ ')' => depth -= 1,
3213+ ',' if depth == 0 => {
3214+ parts.push(&input[start..i]);
3215+ start = i + 1;
61093216 }
6110− }
6111− if let Some(prefixed) = &token.prefixed {
6112− let inner = format!("{}{}", prefix, prefixed.prefix);
6113− check_choices(prefixed.target.attrs(), &inner, line, ctx, text_keys);
3217+ _ => {}
61143218 }
61153219 }
3220+ parts.push(&input[start..]);
3221+ parts
61163222}
61173223
61183224// ---------------------------------------------------------------------------
61193225// Post-parse validation (context-dependent warnings)
61203226// ---------------------------------------------------------------------------
61213227
3228+/// Attributes that only make sense on container elements (@row, @column, @el).
3229+const CONTAINER_ONLY_ATTRS: &[&str] = &[
3230+ "spacing",
3231+ "gap",
3232+ "wrap",
3233+ "grid-cols",
3234+ "grid-rows",
3235+ "container",
3236+ "container-name",
3237+ "container-type",
3238+];
3239+
61223240fn element_kind_name(kind: &ElementKind) -> String {
61233241 format!("@{}", kind.name())
61243242}
61253243
6126−/// HTML elements whose start tag ends an open `<p>`: written inside a
6127−/// `@paragraph`, the browser moves them out of it. (`div` isn't here:
6128−/// inside text, htmlang writes its `<div>`s as `<span>`s.)
6129−#[rustfmt::skip]
6130−const ENDS_A_PARAGRAPH: &[&str] = &[
6131− "address", "article", "aside", "blockquote", "dd", "details", "dialog", "dl", "dt",
6132− "fieldset", "figcaption", "figure", "footer", "form", "h1", "h2", "h3", "h4", "h5", "h6",
6133− "header", "hgroup", "hr", "li", "main", "menu", "nav", "ol", "p", "pre", "search",
6134− "section", "summary", "table", "ul",
6135−];
6136−
6137−/// The HTML element `kind` is written as, if the browser would take it out
6138−/// of a `<p>`.
6139−fn ends_a_paragraph(kind: &ElementKind) -> Option<&'static str> {
6140− let html = match kind {
6141− ElementKind::Paragraph => "p",
6142− ElementKind::Tag(spec) => spec.html,
6143− _ => return None,
6144− };
6145− ENDS_A_PARAGRAPH.contains(&html).then_some(html)
3244+fn is_container(kind: &ElementKind) -> bool {
3245+ matches!(kind, ElementKind::Row | ElementKind::Column | ElementKind::El)
3246+ || kind.spec().is_some_and(|spec| spec.container)
61463247}
61473248
61483249/// Stricter checks for `htmlang lint`, on top of the diagnostics every
@@ -6152,171 +3253,147 @@ pub fn lint(nodes: &[Node]) -> Vec<Diagnostic> {
61523253 fn walk(nodes: &[Node], depth: usize, out: &mut Vec<Diagnostic>) {
61533254 for node in nodes {
61543255 let Node::Element(elem) = node else { continue };
6155− let start = out.len();
6156− let mut warn = |code: &'static str, message: String| {
6157− out.push(Diagnostic::warning(code, elem.line_num, message))
3256+ let mut warn = |message: String| {
3257+ out.push(Diagnostic {
3258+ line: elem.line_num,
3259+ column: None,
3260+ message,
3261+ severity: Severity::Warning,
3262+ source_line: None,
3263+ })
61583264 };
61593265 if depth > 10 {
6160− warn(
6161− code::DEEP_NESTING,
6162− format!(
6163− "deeply nested element ({} levels): consider simplifying",
6164− depth
6165− ),
6166− );
3266+ warn(format!(
3267+ "deeply nested element ({} levels): consider simplifying",
3268+ depth
3269+ ));
61673270 }
6168− // A function's body may draw with an empty element (a spacer,
6169− // a dot): only one written in the page is flagged
6170− if elem.kind.layout().is_container()
3271+ if matches!(elem.kind, ElementKind::Row | ElementKind::Column | ElementKind::El)
61713272 && elem.children.is_empty()
6172− && elem.function.is_none()
61733273 {
6174− warn(
6175− code::EMPTY_CONTAINER,
6176− format!("empty container (@{}) has no children", elem.kind.name()),
6177− );
3274+ warn(format!("empty container (@{}) has no children", elem.kind.name()));
61783275 }
61793276 if elem.kind.is_tag("button") && !elem.attrs.iter().any(|a| a.key == "type") {
6180− warn(
6181− code::MISSING_BUTTON_TYPE,
6182− "@button missing 'type' attribute (defaults to submit)".to_string(),
6183− );
3277+ warn("@button missing 'type' attribute (defaults to submit)".to_string());
61843278 }
6185− in_function_body(elem, &mut out[start..]);
61863279 walk(&elem.children, depth + 1, out);
61873280 }
61883281 }
61893282 let mut out = Vec::new();
61903283 walk(nodes, 0, &mut out);
6191− dedupe(&mut out);
61923284 out
61933285}
61943286
6195−/// `in_paragraph`: the nodes are inside a `@paragraph` (and not inside a
6196−/// `@button` in it, which the browser keeps whole).
3287+
61973288fn validate_tree(
61983289 nodes: &[Node],
61993290 parent_kind: Option<&ElementKind>,
6200− in_paragraph: bool,
62013291 diagnostics: &mut Vec<Diagnostic>,
62023292) {
62033293 for node in nodes {
6204− // An element inside a line of text (`{@kbd ...}`, an inline call)
6205− // is checked like one on a line of its own
6206− if let Node::Text(segments) = node {
6207− let inline: Vec<Node> = segments
6208− .iter()
6209− .filter_map(|segment| match segment {
6210− TextSegment::Inline(elem) => Some(Node::Element(elem.clone())),
6211− _ => None,
6212− })
6213− .collect();
6214− validate_tree(&inline, parent_kind, in_paragraph, diagnostics);
6215− }
62163294 if let Node::Element(elem) = node {
6217− let start = diagnostics.len();
6218− dropped_by_the_element(elem, diagnostics);
6219− if in_paragraph && let Some(html) = ends_a_paragraph(&elem.kind) {
6220− diagnostics.push(
6221− Diagnostic::warning(
6222− code::BLOCK_IN_PARAGRAPH,
6223− elem.line_num,
6224− format!(
6225− "{0} inside @paragraph: HTML ends a <p> before a <{1}>, so the \
6226− browser moves the <{1}> out of the paragraph. Put {0} after the \
6227− paragraph, or use @el, @row or @grid, which are laid out inline \
6228− in text",
6229− element_kind_name(&elem.kind),
6230− html
6231− ),
6232− )
6233− .subject(elem.kind.name()),
6234− );
6235− }
62363295 for attr in &elem.attrs {
62373296 let base = crate::vocab::base_attribute(&attr.key);
3297+ if base == "width"
3298+ && attr.value.as_deref() == Some("fill")
3299+ && !matches!(parent_kind, Some(ElementKind::Row))
3300+ {
3301+ diagnostics.push(Diagnostic {
3302+ line: elem.line_num,
3303+ column: None,
3304+ message: "'width fill' works best inside @row; using 100% as fallback"
3305+ .to_string(),
3306+ severity: Severity::Warning,
3307+ source_line: None,
3308+ });
3309+ }
3310+ if base == "height"
3311+ && attr.value.as_deref() == Some("fill")
3312+ && !matches!(parent_kind, Some(ElementKind::Column))
3313+ {
3314+ diagnostics.push(Diagnostic {
3315+ line: elem.line_num,
3316+ column: None,
3317+ message: "'height fill' works best inside @column; using 100% as fallback"
3318+ .to_string(),
3319+ severity: Severity::Warning,
3320+ source_line: None,
3321+ });
3322+ }
62383323
6239− // htmlang's words for laying out children, on an element
6240− // that doesn't lay out its children: left out (codegen)
6241− if !attr.html
6242− && crate::vocab::CONTAINER_ATTRIBUTES.contains(&base)
6243− && !elem.kind.layout().is_container()
6244− && !has_no_element(&elem.kind)
6245− && !crate::vocab::split_prefixes(&attr.key)
6246− .0
6247− .contains(&"children:")
6248− {
6249− diagnostics.push(not_a_container(&elem.kind, elem.line_num, base));
3324+ // Container-only attributes on non-container elements
3325+ if CONTAINER_ONLY_ATTRS.contains(&base) && !is_container(&elem.kind) {
3326+ diagnostics.push(Diagnostic {
3327+ line: elem.line_num,
3328+ column: None,
3329+ message: format!(
3330+ "'{}' has no effect on {} (only works on @row, @column, @el)",
3331+ base,
3332+ element_kind_name(&elem.kind)
3333+ ),
3334+ severity: Severity::Warning,
3335+ source_line: None,
3336+ });
62503337 }
62513338
62523339 // Form-specific: placeholder only on @input/@textarea
62533340 if base == "placeholder"
62543341 && !(elem.kind.is_tag("input") || elem.kind.is_tag("textarea"))
62553342 {
6256− diagnostics.push(Diagnostic::new(
6257− code::NO_EFFECT,
6258− Severity::Warning,
6259− elem.line_num,
6260− format!(
3343+ diagnostics.push(Diagnostic {
3344+ line: elem.line_num,
3345+ column: None,
3346+ message: format!(
62613347 "'placeholder' has no effect on {} (only works on @input, @textarea)",
62623348 element_kind_name(&elem.kind)
62633349 ),
6264− ));
3350+ severity: Severity::Warning,
3351+ source_line: None,
3352+ });
62653353 }
62663354
6267− // 'for' only on @label and @output
6268− if base == "for" && !(elem.kind.is_tag("label") || elem.kind.is_tag("output")) {
6269− diagnostics.push(Diagnostic::new(
6270− code::NO_EFFECT,
6271− Severity::Warning,
6272− elem.line_num,
6273− format!(
6274− "'for' has no effect on {} (only works on @label and @output)",
3355+ // 'for' only on @label
3356+ if base == "for" && !elem.kind.is_tag("label") {
3357+ diagnostics.push(Diagnostic {
3358+ line: elem.line_num,
3359+ column: None,
3360+ message: format!(
3361+ "'for' has no effect on {} (only works on @label)",
62753362 element_kind_name(&elem.kind)
62763363 ),
6277− ));
6278− }
6279−
6280− // `width=` and `height=` are HTML attributes of media and
6281− // embedded content only; elsewhere they are styles
6282− if attr.html
6283− && (base == "width" || base == "height")
6284− && !matches!(elem.kind, ElementKind::Image)
6285− && ![
6286− "video", "canvas", "iframe", "embed", "object", "input", "source",
6287− ]
6288− .iter()
6289− .any(|tag| elem.kind.is_tag(tag))
6290− {
6291− let value = attr.value.as_deref().unwrap_or("");
6292− diagnostics.push(
6293− Diagnostic::warning(
6294− code::HTML_ATTRIBUTE_FORM,
6295− elem.line_num,
6296− format!(
6297− "'{0}={1}' has no effect on {2}, which has no {0} attribute: \
6298− the style is written `{0} {1}`",
6299− base,
6300− value,
6301− element_kind_name(&elem.kind)
6302− ),
6303− )
6304− .subject(format!("{}={}", base, value)),
6305− );
3364+ severity: Severity::Warning,
3365+ source_line: None,
3366+ });
63063367 }
63073368
63083369 // 'rows'/'cols' only on @textarea
6309− if (base == "rows" || base == "cols") && !elem.kind.is_tag("textarea") {
6310− diagnostics.push(Diagnostic::new(
6311− code::NO_EFFECT,
6312− Severity::Warning,
6313− elem.line_num,
6314− format!(
3370+ if (base == "rows" || base == "cols") && !elem.kind.is_tag("textarea")
3371+ {
3372+ diagnostics.push(Diagnostic {
3373+ line: elem.line_num,
3374+ column: None,
3375+ message: format!(
63153376 "'{}' has no effect on {} (only works on @textarea)",
63163377 base,
63173378 element_kind_name(&elem.kind)
63183379 ),
6319− ));
3380+ severity: Severity::Warning,
3381+ source_line: None,
3382+ });
3383+ }
3384+
3385+ // 'ordered' only on @list
3386+ if base == "ordered" && !elem.kind.is_tag("list") {
3387+ diagnostics.push(Diagnostic {
3388+ line: elem.line_num,
3389+ column: None,
3390+ message: format!(
3391+ "'ordered' has no effect on {} (only works on @list)",
3392+ element_kind_name(&elem.kind)
3393+ ),
3394+ severity: Severity::Warning,
3395+ source_line: None,
3396+ });
63203397 }
63213398
63223399 // Media-specific attributes only on @video/@audio
@@ -6331,35 +3408,40 @@ fn validate_tree(
63313408 | "preload"
63323409 ) && !matches!(elem.kind.name(), "video" | "audio")
63333410 {
6334− diagnostics.push(Diagnostic::new(
6335− code::NO_EFFECT,
6336− Severity::Warning,
6337− elem.line_num,
6338− format!(
3411+ diagnostics.push(Diagnostic {
3412+ line: elem.line_num,
3413+ column: None,
3414+ message: format!(
63393415 "'{}' has no effect on {} (only works on @video, @audio)",
63403416 base,
63413417 element_kind_name(&elem.kind)
63423418 ),
6343− ));
3419+ severity: Severity::Warning,
3420+ source_line: None,
3421+ });
63443422 }
63453423 }
63463424 // Missing alt text on @image
63473425 if matches!(elem.kind, ElementKind::Image) && !elem.attrs.iter().any(|a| a.key == "alt")
63483426 {
6349− diagnostics.push(Diagnostic::new(
6350− code::MISSING_ALT,
6351− Severity::Warning,
6352− elem.line_num,
6353− "@image missing 'alt' attribute (accessibility)".to_string(),
6354− ));
3427+ diagnostics.push(Diagnostic {
3428+ line: elem.line_num,
3429+ column: None,
3430+ message: "@image missing 'alt' attribute (accessibility)".to_string(),
3431+ severity: Severity::Warning,
3432+ source_line: None,
3433+ });
63553434 }
6356− if elem.kind.is_tag("input") && !elem.attrs.iter().any(|a| a.key == "type") {
6357− diagnostics.push(Diagnostic::new(
6358− code::MISSING_INPUT_TYPE,
6359− Severity::Warning,
6360− elem.line_num,
6361− "@input missing 'type' attribute (defaults to 'text')".to_string(),
6362− ));
3435+ if elem.kind.is_tag("input")
3436+ && !elem.attrs.iter().any(|a| a.key == "type")
3437+ {
3438+ diagnostics.push(Diagnostic {
3439+ line: elem.line_num,
3440+ column: None,
3441+ message: "@input missing 'type' attribute (defaults to 'text')".to_string(),
3442+ severity: Severity::Warning,
3443+ source_line: None,
3444+ });
63633445 }
63643446 if matches!(elem.kind, ElementKind::Link) {
63653447 // For @link, argument is the URL, not text content
@@ -6370,50 +3452,44 @@ fn validate_tree(
63703452 .iter()
63713453 .any(|a| a.key == "aria-label" || a.key == "title")
63723454 {
6373− diagnostics.push(Diagnostic::new(
6374− code::MISSING_LINK_TEXT,
6375− Severity::Warning,
6376− elem.line_num,
6377− "@link has no visible text or aria-label (accessibility)".to_string(),
6378− ));
3455+ diagnostics.push(Diagnostic {
3456+ line: elem.line_num,
3457+ column: None,
3458+ message: "@link has no visible text or aria-label (accessibility)"
3459+ .to_string(),
3460+ severity: Severity::Warning,
3461+ source_line: None,
3462+ });
63793463 }
63803464 }
63813465
6382− // Contrast ratio check for hex color pairs, each pair on the
6383− // same elements: the element's own, or those an element prefix
6384− // (`@td:`) picks out inside it
6385− let inside = |key: &str| {
6386− crate::vocab::split_prefixes(key)
6387− .0
6388− .into_iter()
6389− .find_map(crate::vocab::element_prefix)
6390− .map(str::to_string)
6391− };
6392− let mut targets: Vec<Option<String>> = Vec::new();
6393− for attr in elem.attrs.iter().filter(|a| !a.html) {
6394− let target = inside(&attr.key);
6395− if !targets.contains(&target) {
6396− targets.push(target);
6397− }
6398− }
6399− for target in targets {
6400− let color = |property: &str| {
6401− elem.attrs
6402− .iter()
6403− .filter(|a| !a.html && inside(&a.key) == target)
6404− .find(|a| crate::vocab::base_attribute(&a.key) == property)
6405− .and_then(|a| a.value.as_deref())
6406− };
6407− let (bg_color, fg_color) = (color("background"), color("color"));
3466+ // Contrast ratio check for hex color pairs
3467+ {
3468+ let bg_color = elem
3469+ .attrs
3470+ .iter()
3471+ .find(|a| crate::vocab::base_attribute(&a.key) == "background")
3472+ .and_then(|a| a.value.as_deref());
3473+ let fg_color = elem
3474+ .attrs
3475+ .iter()
3476+ .find(|a| crate::vocab::base_attribute(&a.key) == "color")
3477+ .and_then(|a| a.value.as_deref());
64083478 if let (Some(bg), Some(fg)) = (bg_color, fg_color)
6409− && let (Some(bg_rgb), Some(fg_rgb)) = (parse_hex_rgb(bg), parse_hex_rgb(fg))
3479+ && let (Some(bg_rgb), Some(fg_rgb)) = (crate::expr::parse_hex_rgb(bg), crate::expr::parse_hex_rgb(fg))
64103480 {
64113481 let ratio = contrast_ratio(bg_rgb, fg_rgb);
64123482 if ratio < 4.5 {
6413− diagnostics.push(Diagnostic::new(code::LOW_CONTRAST, Severity::Warning, elem.line_num, format!(
3483+ diagnostics.push(Diagnostic {
3484+ line: elem.line_num,
3485+ column: None,
3486+ message: format!(
64143487 "low contrast ratio {:.1}:1 between '{}' and '{}' (WCAG AA requires 4.5:1)",
64153488 ratio, fg, bg
6416− )));
3489+ ),
3490+ severity: Severity::Warning,
3491+ source_line: None,
3492+ });
64173493 }
64183494 }
64193495 }
@@ -6428,34 +3504,45 @@ fn validate_tree(
64283504 let has_title = elem.attrs.iter().any(|a| a.key == "title");
64293505 let in_label = parent_kind.is_some_and(|k| k.is_tag("label"));
64303506 if !has_id && !has_aria_label && !has_title && !in_label {
6431− diagnostics.push(Diagnostic::new(code::MISSING_LABEL, Severity::Warning, elem.line_num, format!(
3507+ diagnostics.push(Diagnostic {
3508+ line: elem.line_num,
3509+ column: None,
3510+ message: format!(
64323511 "{} should have an 'id' (with matching @label[for]), 'aria-label', or be wrapped in @label (accessibility)",
64333512 element_kind_name(&elem.kind)
6434− )));
3513+ ),
3514+ severity: Severity::Warning,
3515+ source_line: None,
3516+ });
64353517 }
64363518 }
64373519
64383520 // @iframe should have title attribute
6439− if elem.kind.is_tag("iframe") && !elem.attrs.iter().any(|a| a.key == "title") {
6440− diagnostics.push(Diagnostic::new(
6441− code::MISSING_TITLE,
6442− Severity::Warning,
6443− elem.line_num,
6444− "@iframe missing 'title' attribute (accessibility)".to_string(),
6445− ));
3521+ if elem.kind.is_tag("iframe")
3522+ && !elem.attrs.iter().any(|a| a.key == "title")
3523+ {
3524+ diagnostics.push(Diagnostic {
3525+ line: elem.line_num,
3526+ column: None,
3527+ message: "@iframe missing 'title' attribute (accessibility)".to_string(),
3528+ severity: Severity::Warning,
3529+ source_line: None,
3530+ });
64463531 }
64473532
64483533 // @button should have accessible text
64493534 if elem.kind.is_tag("button") {
6450− let has_text = !elem.children.is_empty();
3535+ let has_text = elem.argument.is_some() || !elem.children.is_empty();
64513536 let has_aria = elem.attrs.iter().any(|a| a.key == "aria-label");
64523537 if !has_text && !has_aria {
6453− diagnostics.push(Diagnostic::new(
6454− code::MISSING_BUTTON_TEXT,
6455− Severity::Warning,
6456− elem.line_num,
6457− "@button has no text content or aria-label (accessibility)".to_string(),
6458− ));
3538+ diagnostics.push(Diagnostic {
3539+ line: elem.line_num,
3540+ column: None,
3541+ message: "@button has no text content or aria-label (accessibility)"
3542+ .to_string(),
3543+ severity: Severity::Warning,
3544+ source_line: None,
3545+ });
64593546 }
64603547 }
64613548
@@ -6468,15 +3555,16 @@ fn validate_tree(
64683555 let has_track = elem
64693556 .children
64703557 .iter()
6471− .any(|c| matches!(c, Node::Element(e) if e.kind.is_tag("track")));
3558+ .any(|c| matches!(c, Node::Element(e) if e.kind.is_tag("source")));
64723559 if !has_aria && !has_track {
6473− diagnostics.push(Diagnostic::new(
6474− code::MISSING_CAPTIONS,
6475− Severity::Warning,
6476− elem.line_num,
6477− "@video should have aria-label or a captions @track for accessibility"
3560+ diagnostics.push(Diagnostic {
3561+ line: elem.line_num,
3562+ column: None,
3563+ message: "@video should have aria-label or captions for accessibility"
64783564 .to_string(),
6479− ));
3565+ severity: Severity::Warning,
3566+ source_line: None,
3567+ });
64803568 }
64813569 }
64823570
@@ -6486,204 +3574,20 @@ fn validate_tree(
64863574 && let Ok(n) = val.parse::<i32>()
64873575 && n > 0
64883576 {
6489− diagnostics.push(Diagnostic::new(code::POSITIVE_TABINDEX, Severity::Warning, elem.line_num, format!("tabindex {} is positive — avoid positive tabindex values as they disrupt natural tab order", n)));
3577+ diagnostics.push(Diagnostic {
3578+ line: elem.line_num,
3579+ column: None,
3580+ message: format!("tabindex {} is positive — avoid positive tabindex values as they disrupt natural tab order", n),
3581+ severity: Severity::Warning,
3582+ source_line: None,
3583+ });
64903584 }
6491− in_function_body(elem, &mut diagnostics[start..]);
6492−
6493− // An element that ends the <p> takes what is inside it out of
6494− // the paragraph too, so only it is reported
6495− let in_paragraph = elem.kind == ElementKind::Paragraph
6496− || (in_paragraph
6497− && ends_a_paragraph(&elem.kind).is_none()
6498− && !elem.kind.is_tag("button"));
6499− validate_tree(&elem.children, Some(&elem.kind), in_paragraph, diagnostics);
6500− }
6501− }
6502−}
6503−
6504−/// What an element has no place for in HTML, which would otherwise be
6505−/// left out of the page: attributes on `@fragment` (which has no element
6506−/// of its own), styles on `@script` (which isn't shown), a body under a
6507−/// `@script` that has a src (which the browser doesn't run), an element
6508−/// under a `@script` (whose body is code), and content in a void element
6509−/// such as `@input`.
6510−fn dropped_by_the_element(elem: &Element, diagnostics: &mut Vec<Diagnostic>) {
6511− let name = elem.kind.name();
6512− let keys = |attrs: Vec<&Attribute>| {
6513− attrs
6514− .iter()
6515− .map(|a| format!("'{}'", a.key))
6516− .collect::<Vec<_>>()
6517− .join(", ")
6518− };
6519− let mut error = |code: &'static str, message: String| {
6520− diagnostics.push(Diagnostic::error(code, elem.line_num, message).subject(name))
6521− };
6522− if elem.kind == ElementKind::Fragment && !elem.attrs.is_empty() {
6523− error(
6524− code::UNEXPECTED_ARGUMENT,
6525− format!(
6526− "@fragment has no element of its own to put attributes on, so {} would go \
6527− nowhere: put them on its children, or use @el",
6528− keys(elem.attrs.iter().collect())
6529− ),
6530− );
6531− }
6532− // The leading argument given twice: an attribute passed to the root
6533− // of a function whose body gives the argument (written on one line,
6534− // it is reported where it is read, and the attribute wins there)
6535− if let Some(argument) = &elem.argument
6536− && let Some(attr) = elem
6537− .attrs
6538− .iter()
6539− .find(|a| a.html && elem.kind.arg().attributes().contains(&a.key.as_str()))
6540− {
6541− error(
6542− code::DUPLICATE_ATTRIBUTE,
6543− format!(
6544− "@{} takes '{}' as its {}, and it also has {}={}: give it once",
6545− name,
6546− argument,
6547− leading_name(&elem.kind),
6548− attr.key,
6549− attr.value.as_deref().unwrap_or("")
6550− ),
6551− );
6552− }
6553− if elem.kind.is_verbatim() {
6554− let styles: Vec<&Attribute> = elem
6555− .attrs
6556− .iter()
6557− .filter(|a| !a.html && !crate::vocab::is_html_flag(&a.key))
6558− .collect();
6559− if !styles.is_empty() {
6560− error(
6561− code::UNEXPECTED_ARGUMENT,
6562− format!(
6563− "@{} isn't shown on the page, so its styles {} would go nowhere",
6564− name,
6565− keys(styles)
6566− ),
6567− );
6568− }
6569− let src = elem.argument.clone().or_else(|| {
6570− elem.attrs
6571− .iter()
6572− .find(|a| a.html && a.key == "src")
6573− .map(|a| a.value.clone().unwrap_or_default())
6574− });
6575− if let Some(src) = src
6576− && !elem.children.is_empty()
6577− {
6578− error(
6579− code::UNEXPECTED_CONTENT,
6580− format!(
6581− "@{0} has both a src ('{1}') and a body: the browser runs only the file, \
6582− so the body would go nowhere. Put the code in {1}, or leave out the src",
6583− name, src
6584− ),
6585− );
6586− } else if let Some(Node::Element(child)) = elem
6587− .children
6588− .iter()
6589− .find(|child| matches!(child, Node::Element(_)))
6590− {
6591− // `@script > @b x`: its body is code, not elements
6592− error(
6593− code::UNEXPECTED_CONTENT,
6594− format!(
6595− "@{} holds its code as the lines under it, kept as written, so @{} would \
6596− go nowhere",
6597− name,
6598− child.kind.name()
6599− ),
6600− );
6601− }
6602− }
6603− if elem.kind != ElementKind::Image && elem.attrs.iter().any(|a| !a.html && a.key == "inline") {
6604− error(
6605− code::UNEXPECTED_ARGUMENT,
6606− format!(
6607− "`inline` puts an image's file into the page, and @{} has none: it only \
6608− works on @image",
6609− name
6610− ),
6611− );
6612− }
6613− if elem.kind.layout() == Layout::Void && !elem.children.is_empty() {
6614− error(
6615− code::UNEXPECTED_CONTENT,
6616− format!(
6617− "@{} takes no content: it is an element without a closing tag, so its text \
6618− and indented lines would go nowhere",
6619− name
6620− ),
6621− );
6622− }
6623−}
6624−
6625−/// `@fragment`, `@script`, `@children` and `@slot`, whose attributes are
6626−/// reported on their own (see `dropped_by_the_element`).
6627−fn has_no_element(kind: &ElementKind) -> bool {
6628− matches!(
6629− kind,
6630− ElementKind::Fragment | ElementKind::Children | ElementKind::Slot(_)
6631− ) || kind.is_verbatim()
6632−}
6633−
6634−/// htmlang's word `word` for laying out children (`spacing`, `wrap`,
6635−/// `grid-cols`, `grid-rows`) on an element that doesn't lay out its
6636−/// children: an error, and the word is left out.
6637−fn not_a_container(kind: &ElementKind, line: usize, word: &str) -> Diagnostic {
6638− let name = element_kind_name(kind);
6639− let (what, instead) = match kind.layout() {
6640− Layout::Text => (
6641− "is text, whose lines and children flow together with no gap between them",
6642− "; to space the children out, put them in an @el or @row",
6643− ),
6644− Layout::Void => ("has no content to lay out", ""),
6645− _ => (
6646− "keeps HTML's own layout",
6647− "; for a flex layout of your own, write CSS, such as `display flex, gap 8`",
6648− ),
6649− };
6650− Diagnostic::error(
6651− code::NO_EFFECT,
6652− line,
6653− format!(
6654− "'{0}' can't go on {1}: {1} {2}. `{0}` works on a row, column or grid \
6655− (@el, @row, @grid, @section, ...){3}",
6656− word, name, what, instead
6657− ),
6658− )
6659− .subject(word)
6660−}
66613585
6662−/// Diagnostics about an element a function's body wrote are reported at
6663−/// the call (see `belongs_to_call`); say which body the element is in.
6664−fn in_function_body(elem: &Element, diagnostics: &mut [Diagnostic]) {
6665− if let Some(function) = &elem.function {
6666− for d in diagnostics {
6667− d.message = format!("{}\n in the body of @{}", d.message, function);
3586+ validate_tree(&elem.children, Some(&elem.kind), diagnostics);
66683587 }
66693588 }
66703589}
66713590
6672−/// Report each diagnostic once: a line that runs many times (in a loop, in
6673−/// a function called from one place many times) reports its problems once.
6674−fn dedupe(diagnostics: &mut Vec<Diagnostic>) {
6675− let mut seen = HashSet::new();
6676− diagnostics.retain(|d| {
6677− seen.insert((
6678− d.code,
6679− d.line,
6680− d.column,
6681− d.message.clone(),
6682− d.severity as u8,
6683− ))
6684− });
6685−}
6686−
66873591fn relative_luminance(r: u8, g: u8, b: u8) -> f64 {
66883592 fn linearize(c: u8) -> f64 {
66893593 let s = c as f64 / 255.0;
@@ -6696,24 +3600,6 @@ fn relative_luminance(r: u8, g: u8, b: u8) -> f64 {
66963600 0.2126 * linearize(r) + 0.7152 * linearize(g) + 0.0722 * linearize(b)
66973601}
66983602
6699−/// The red, green and blue of a `#rgb` or `#rrggbb` colour.
6700−fn parse_hex_rgb(s: &str) -> Option<(u8, u8, u8)> {
6701− let s = s.strip_prefix('#')?;
6702− if !s.bytes().all(|b| b.is_ascii_hexdigit()) {
6703− return None;
6704− }
6705− let channel = |i: usize, len: usize| u8::from_str_radix(&s[i..i + len], 16).ok();
6706− match s.len() {
6707− 3 => Some((
6708− channel(0, 1)? * 17,
6709− channel(1, 1)? * 17,
6710− channel(2, 1)? * 17,
6711− )),
6712− 6 => Some((channel(0, 2)?, channel(2, 2)?, channel(4, 2)?)),
6713− _ => None,
6714− }
6715−}
6716−
67173603fn contrast_ratio(c1: (u8, u8, u8), c2: (u8, u8, u8)) -> f64 {
67183604 let l1 = relative_luminance(c1.0, c1.1, c1.2);
67193605 let l2 = relative_luminance(c2.0, c2.1, c2.2);
@@ -6721,48 +3607,66 @@ fn contrast_ratio(c1: (u8, u8, u8), c2: (u8, u8, u8)) -> f64 {
67213607 (lighter + 0.05) / (darker + 0.05)
67223608}
67233609
3610+// ---------------------------------------------------------------------------
3611+// Variable substitution
3612+// ---------------------------------------------------------------------------
3613+
3614+/// Interpolate `$name` variables and `${expr}` expressions into text.
3615+/// Undefined variables, and expressions that don't evaluate, are left as
3616+/// written so they show up in the output.
3617+fn substitute_vars(input: &str, vars: &HashMap<String, String>) -> String {
3618+ if !input.contains('$') {
3619+ return input.to_string();
3620+ }
3621+ let is_name_char = |c: char| c.is_alphanumeric() || matches!(c, '_' | '-' | '.');
3622+ let mut result = String::with_capacity(input.len());
3623+ let mut rest = input;
3624+ while let Some(pos) = rest.find('$') {
3625+ result.push_str(&rest[..pos]);
3626+ let after = &rest[pos + 1..];
3627+ if after.starts_with('{')
3628+ && let Some(close) = matching_brace(after)
3629+ {
3630+ let source = &after[1..close];
3631+ let resolve = |name: &str| vars.get(name).cloned();
3632+ match crate::expr::eval(source, &resolve) {
3633+ Ok(value) => result.push_str(&value.to_string()),
3634+ Err(_) => result.push_str(&rest[pos..pos + 1 + close + 1]),
3635+ }
3636+ rest = &after[close + 1..];
3637+ continue;
3638+ }
3639+ let mut end = after.find(|c: char| !is_name_char(c)).unwrap_or(after.len());
3640+ while end > 0 && after[..end].ends_with('.') {
3641+ end -= 1;
3642+ }
3643+ let name = &after[..end];
3644+ match vars.get(name) {
3645+ Some(value) if !name.is_empty() => result.push_str(value),
3646+ _ => {
3647+ result.push('$');
3648+ result.push_str(name);
3649+ }
3650+ }
3651+ rest = &after[end..];
3652+ }
3653+ result.push_str(rest);
3654+ result
3655+}
3656+
67243657/// `@image [inline] icon.svg` becomes the SVG's markup, with `width`,
6725−/// `height`, `color` / `fill` and the HTML attributes (`class=`, `id=`,
6726−/// `aria-label=`, ...) applied to the `<svg>` tag; any other attribute is
6727−/// an error. Other nodes are returned unchanged.
3658+/// `height`, `color` / `fill`, `class=` and `id=` applied to the `<svg>`
3659+/// tag. Other nodes are returned unchanged.
67283660fn inline_svg(node: Node, line_num: usize, ctx: &mut ParseContext) -> Node {
67293661 let Node::Element(elem) = &node else {
67303662 return node;
67313663 };
6732− let inline = elem.kind == ElementKind::Image
3664+ let is_inline_svg = elem.kind == ElementKind::Image
67333665 && elem.attrs.iter().any(|a| a.key == "inline" && !a.html)
6734− && elem.argument.as_deref().is_some_and(|src| !src.is_empty());
6735− if !inline {
3666+ && elem.argument.as_deref().is_some_and(|src| src.ends_with(".svg"));
3667+ if !is_inline_svg {
67363668 return node;
67373669 }
6738− // A raster image: its file, read relative to this one, as a `data:` URI
6739− if !elem
6740− .argument
6741− .as_deref()
6742− .is_some_and(|src| src.ends_with(".svg"))
6743− {
6744− let Node::Element(mut elem) = node else {
6745− return node;
6746− };
6747− let filename = elem.argument.clone().unwrap_or_default();
6748− let resolved = ctx.resolve(&filename);
6749− match std::fs::read(&resolved) {
6750− Ok(data) => {
6751− elem.argument = Some(crate::codegen::data_uri(&filename, &data));
6752− ctx.included_files.push(resolved);
6753− }
6754− Err(e) => ctx.diagnostics.push(Diagnostic::new(
6755− code::UNREADABLE_FILE,
6756− Severity::Error,
6757− line_num,
6758− format!(
6759− "cannot load image '{}' to put it into the page: {}",
6760− filename, e
6761− ),
6762− )),
6763− }
6764− return Node::Element(elem);
6765− }
67663670 let filename = elem.argument.clone().unwrap_or_default();
67673671 let resolved = match &ctx.base_path {
67683672 Some(base) => base.join(&filename),
@@ -6771,104 +3675,145 @@ fn inline_svg(node: Node, line_num: usize, ctx: &mut ParseContext) -> Node {
67713675 let mut svg = match std::fs::read_to_string(&resolved) {
67723676 Ok(text) => text.trim().to_string(),
67733677 Err(e) => {
6774− ctx.diagnostics.push(Diagnostic::new(
6775− code::UNREADABLE_FILE,
6776− Severity::Error,
6777− line_num,
6778− format!("cannot load SVG '{}': {}", filename, e),
6779− ));
3678+ ctx.diagnostics.push(Diagnostic {
3679+ line: line_num,
3680+ column: None,
3681+ message: format!("cannot load SVG '{}': {}", filename, e),
3682+ severity: Severity::Error,
3683+ source_line: None,
3684+ });
67803685 return node;
67813686 }
67823687 };
67833688 ctx.included_files.push(resolved);
6784− // The file's markup has no class of its own, so a style reaches it only
6785− // as one of the root's attributes: anything else is reported, never
6786− // left out silently
6787− let mut left_out: Vec<String> = Vec::new();
6788− // The styles go in the root's `style=`, where a length takes its unit
6789− // and `var(--name)` works, as in any CSS
6790− let mut style: Vec<String> = Vec::new();
67913689 for attr in &elem.attrs {
6792− let target = match (attr.key.as_str(), attr.html, &attr.value) {
6793− ("inline", false, None) | ("src", true, _) => continue,
6794− // `fill` and `shrink` are layout words, which need a class
6795− ("width" | "height", false, Some(value))
6796− if matches!(value.as_str(), "fill" | "shrink") =>
6797− {
6798− left_out.push(format!("{} {}", attr.key, value));
6799− continue;
6800− }
6801− ("width" | "height", false, Some(value)) => {
6802− let value = crate::vocab::with_px(&attr.key, value);
6803− style.push(format!("{}:{}", attr.key, value));
6804− continue;
6805− }
6806− ("color" | "fill", false, Some(value)) => {
6807− style.push(format!("fill:{}", value));
6808− continue;
6809− }
6810− ("style", true, Some(value)) => {
6811− style.insert(0, value.trim().trim_end_matches(';').to_string());
6812− continue;
6813− }
6814− ("alt", true, _) => {
6815− left_out.push("alt".to_string());
6816− continue;
6817− }
6818− (key, true, Some(_)) => key,
6819− (key, false, None) if crate::vocab::is_html_flag(key) => key,
6820− _ => {
6821− left_out.push(attr.key.clone());
6822− continue;
6823− }
3690+ let Some(value) = &attr.value else { continue };
3691+ let target = match (attr.key.as_str(), attr.html) {
3692+ ("width", false) | ("height", false) => attr.key.as_str(),
3693+ ("color", false) | ("fill", false) => "fill",
3694+ ("class", true) | ("id", true) => attr.key.as_str(),
3695+ _ => continue,
68243696 };
6825− let value = attr.value.as_deref().unwrap_or("");
6826− svg = set_svg_attr(&svg, target, &html_escape_md(value));
3697+ svg = set_svg_attr(&svg, target, value);
68273698 }
6828− if !style.is_empty() {
6829− // After the file's own `style=`, which stays: these come later, so
6830− // they win where both set a property
6831− let mut value = html_escape_md(&style.join(";"));
6832− if let Some(own) = svg_attr_value(&svg, "style")
6833− .map(|range| svg[range].trim().trim_end_matches(';').to_string())
6834− .filter(|own| !own.is_empty())
6835− {
6836− value = format!("{};{}", own, value);
3699+ Node::Raw(svg)
3700+}
3701+
3702+/// The first `$name|filter` (old filter syntax) in `text`, as (name, filter).
3703+fn old_filter_syntax(text: &str) -> Option<(String, String)> {
3704+ const FILTERS: &[&str] = &[
3705+ "uppercase", "lowercase", "capitalize", "trim", "length", "reverse", "truncate",
3706+ "replace", "default", "lighten", "darken", "alpha", "mix",
3707+ ];
3708+ let mut rest = text;
3709+ while let Some(pos) = rest.find('$') {
3710+ let after = &rest[pos + 1..];
3711+ let end = after
3712+ .find(|c: char| !(c.is_alphanumeric() || matches!(c, '_' | '-' | '.')))
3713+ .unwrap_or(after.len());
3714+ if let Some(filter) = after[end..].strip_prefix('|') {
3715+ let name_end = filter.find(|c: char| !c.is_ascii_alphabetic()).unwrap_or(filter.len());
3716+ if end > 0 && FILTERS.contains(&&filter[..name_end]) {
3717+ return Some((after[..end].to_string(), filter[..name_end].to_string()));
3718+ }
68373719 }
6838− svg = set_svg_attr(&svg, "style", &value);
3720+ rest = &after[end..];
68393721 }
6840− if !left_out.is_empty() {
6841− let alt = left_out.iter().any(|name| name == "alt");
6842− let names = left_out
6843− .iter()
6844− .map(|name| format!("'{}'", name))
6845− .collect::<Vec<_>>()
6846− .join(", ");
6847− let mut message = format!(
6848− "{} can't go on an inline SVG: `@image [inline]` puts the file's own markup into the page, which takes `width` and `height` as lengths, `color` or `fill` (as its fill) and HTML attributes (`class=`, `aria-label=`, ...)",
6849− names
6850− );
6851− if alt {
6852− message.push_str("; an SVG has no alt text: name it with `aria-label=` and `role=img`");
3722+ None
3723+}
3724+
3725+/// Index of the `}` matching the `{` that `s` starts with (skipping
3726+/// braces inside string literals).
3727+fn matching_brace(s: &str) -> Option<usize> {
3728+ let mut depth = 0;
3729+ let mut in_string = false;
3730+ for (i, c) in s.char_indices() {
3731+ match c {
3732+ '"' => in_string = !in_string,
3733+ _ if in_string => {}
3734+ '{' => depth += 1,
3735+ '}' => {
3736+ depth -= 1;
3737+ if depth == 0 {
3738+ return Some(i);
3739+ }
3740+ }
3741+ _ => {}
68533742 }
6854− ctx.diagnostics.push(Diagnostic::new(
6855− code::UNEXPECTED_ARGUMENT,
6856− Severity::Error,
6857− line_num,
6858− message,
6859− ));
68603743 }
6861− Node::Raw(svg)
3744+ None
3745+}
3746+
3747+/// Parse a keyframe line in htmlang syntax: `from [opacity 0]` / `50% [transform scale(1.5)]`
3748+fn parse_keyframe_line(line: &str) -> Option<String> {
3749+ let (selector, rest) = if let Some(rest) = line.strip_prefix("from") {
3750+ ("from", rest.trim())
3751+ } else if let Some(rest) = line.strip_prefix("to") {
3752+ ("to", rest.trim())
3753+ } else if let Some(pct_end) = line.find('%') {
3754+ let rest = line[pct_end + 1..].trim();
3755+ let selector = &line[..pct_end + 1];
3756+ (selector, rest)
3757+ } else {
3758+ return None;
3759+ };
3760+
3761+ if !rest.starts_with('[') || !rest.ends_with(']') {
3762+ return None;
3763+ }
3764+
3765+ let inner = &rest[1..rest.len() - 1];
3766+ // Parse comma-separated key-value pairs into CSS
3767+ let mut css = String::new();
3768+ for part in split_commas(inner) {
3769+ let part = part.trim();
3770+ if part.is_empty() {
3771+ continue;
3772+ }
3773+ if let Some((key, value)) = part.split_once(' ') {
3774+ css.push_str(key.trim());
3775+ css.push(':');
3776+ css.push_str(value.trim());
3777+ css.push(';');
3778+ }
3779+ }
3780+
3781+ if css.is_empty() {
3782+ return None;
3783+ }
3784+
3785+ Some(format!("{}{{{}}}", selector, css))
68623786}
68633787
68643788// ---------------------------------------------------------------------------
68653789// Variable usage tracking
68663790// ---------------------------------------------------------------------------
68673791
6868−/// Record the names a string refers to (by syntax) as used.
3792+/// Scan a string for $name references and record them in the used set.
68693793fn track_var_refs(input: &str, used: &mut HashSet<String>) {
6870− if input.contains('$') {
6871− used.extend(interp::names(input).into_iter().map(String::from));
3794+ if !input.contains('$') {
3795+ return;
3796+ }
3797+ let chars: Vec<char> = input.chars().collect();
3798+ let mut i = 0;
3799+ while i < chars.len() {
3800+ if chars[i] == '$'
3801+ && i + 1 < chars.len()
3802+ && (chars[i + 1].is_alphanumeric() || chars[i + 1] == '_' || chars[i + 1] == '-')
3803+ {
3804+ let start = i + 1;
3805+ let mut end = start;
3806+ while end < chars.len()
3807+ && (chars[end].is_alphanumeric() || chars[end] == '-' || chars[end] == '_')
3808+ {
3809+ end += 1;
3810+ }
3811+ let name: String = chars[start..end].iter().collect();
3812+ used.insert(name);
3813+ i = end;
3814+ } else {
3815+ i += 1;
3816+ }
68723817 }
68733818}
68743819
@@ -6876,63 +3821,49 @@ fn track_var_refs(input: &str, used: &mut HashSet<String>) {
68763821// Unused definition warnings
68773822// ---------------------------------------------------------------------------
68783823
6879−/// Warn about definitions nothing uses, except `exported` ones (the
6880−/// definitions of a library, for the files that include it).
6881−fn check_unused(ctx: &mut ParseContext, exported: &HashSet<String>) {
3824+fn check_unused(ctx: &mut ParseContext) {
68823825 // Check unused @let variables
68833826 for (name, &line) in &ctx.let_lines {
6884− if exported.contains(name) {
6885− // A library's names are for other files (a custom property
6886− // isn't a variable, so it is never listed here)
6887− continue;
3827+ if name.starts_with("--") {
3828+ continue; // CSS vars are always used
68883829 }
68893830 if !ctx.used_variables.contains(name) {
6890− ctx.diagnostics.push(
6891− Diagnostic::new(
6892− code::UNUSED_VARIABLE,
6893− Severity::Warning,
6894− line,
6895− format!("unused variable '${}' (defined but never referenced)", name),
6896− )
6897− .subject(name.as_str()),
6898− );
3831+ ctx.diagnostics.push(Diagnostic {
3832+ line,
3833+ column: None,
3834+ message: format!("unused variable '${}' (defined but never referenced)", name),
3835+ severity: Severity::Warning,
3836+ source_line: None,
3837+ });
68993838 }
69003839 }
69013840
6902− // Check unused attribute bundles (@let name [...]). A `$name` in code
6903− // that doesn't run (an `if()` branch or `@if` not taken) counts too.
3841+ // Check unused attribute bundles (@let name [...])
69043842 for (name, &line) in &ctx.define_lines {
6905− if !ctx.used_defines.contains(name)
6906− && !ctx.used_variables.contains(name)
6907− && !exported.contains(name)
6908− {
6909− ctx.diagnostics.push(
6910− Diagnostic::new(
6911− code::UNUSED_BUNDLE,
6912− Severity::Warning,
6913− line,
6914− format!(
6915− "unused attribute bundle '${}' (defined but never referenced)",
6916− name
6917− ),
6918− )
6919− .subject(name.as_str()),
6920− );
3843+ if !ctx.used_defines.contains(name) {
3844+ ctx.diagnostics.push(Diagnostic {
3845+ line,
3846+ column: None,
3847+ message: format!(
3848+ "unused attribute bundle '${}' (defined but never referenced)",
3849+ name
3850+ ),
3851+ severity: Severity::Warning,
3852+ source_line: None,
3853+ });
69213854 }
69223855 }
69233856
69243857 // Check unused functions (@let name ... with body)
69253858 for (name, &line) in &ctx.fn_lines {
6926− if !ctx.used_functions.contains(name) && !exported.contains(name) {
6927− ctx.diagnostics.push(
6928− Diagnostic::new(
6929− code::UNUSED_FUNCTION,
6930− Severity::Warning,
6931− line,
6932− format!("unused function '@{}' (defined but never called)", name),
6933− )
6934− .subject(name.as_str()),
6935− );
3859+ if !ctx.used_functions.contains(name) {
3860+ ctx.diagnostics.push(Diagnostic {
3861+ line,
3862+ column: None,
3863+ message: format!("unused function '@{}' (defined but never called)", name),
3864+ severity: Severity::Warning,
3865+ source_line: None,
3866+ });
69363867 }
69373868 }
69383869}
@@ -7018,6 +3949,28 @@ fn parse_json_with_error(input: &str) -> Result<JsonValue, String> {
70183949 }
70193950}
70203951
3952+/// Split a function body into its content and an @style block at the
3953+/// body's top level (the block's CSS lines, without the `@style` line).
3954+fn split_style_block(body: Vec<Line>) -> (Vec<Line>, Vec<Line>) {
3955+ let top = body.iter().map(|l| l.indent).min().unwrap_or(0);
3956+ let mut content = Vec::new();
3957+ let mut style = Vec::new();
3958+ let mut in_style = false;
3959+ for line in body {
3960+ let is_style_header =
3961+ line.indent == top && matches!(&line.content, LineContent::Normal(s) if s.trim() == "@style");
3962+ if is_style_header {
3963+ in_style = true;
3964+ } else if in_style && line.indent > top {
3965+ style.push(line);
3966+ } else {
3967+ in_style = false;
3968+ content.push(line);
3969+ }
3970+ }
3971+ (content, style)
3972+}
3973+
70213974fn parse_json_value(chars: &[char], mut pos: usize) -> Option<(JsonValue, usize)> {
70223975 pos = skip_ws(chars, pos);
70233976 if pos >= chars.len() {
@@ -7198,21 +4151,75 @@ fn skip_ws(chars: &[char], mut pos: usize) -> usize {
71984151 pos
71994152}
72004153
7201−/// A JSON value as an htmlang value: an object is a record, an array a
7202−/// list, a string text (never quoted text), `null` empty. A number keeps
7203−/// the text it is written with (`1.50`), and reads as a number.
7204−fn json_value(json: JsonValue) -> Value {
7205− match json {
7206− JsonValue::Null => Value::empty(),
7207− JsonValue::Bool(b) => Value::Bool(b),
7208− JsonValue::Number(n) | JsonValue::Str(n) => Value::Str(n),
7209− JsonValue::Array(items) => Value::list(items.into_iter().map(json_value).collect()),
7210− JsonValue::Object(pairs) => Value::Record(Rc::new(
7211− pairs
7212− .into_iter()
7213− .map(|(key, value)| (key, json_value(value)))
7214− .collect(),
7215− )),
4154+/// Flatten a JSON value into variable assignments.
4155+/// - Top-level object: each key becomes `prefix.key`
4156+/// - Top-level array: `prefix` becomes comma-separated, `prefix._count` set
4157+/// - Array of objects: each item becomes space-separated values for @each destructuring
4158+fn flatten_json(prefix: &str, value: &JsonValue, vars: &mut HashMap<String, String>) {
4159+ match value {
4160+ JsonValue::Str(s) => {
4161+ vars.insert(prefix.to_string(), s.clone());
4162+ }
4163+ JsonValue::Number(n) => {
4164+ vars.insert(prefix.to_string(), n.clone());
4165+ }
4166+ JsonValue::Bool(b) => {
4167+ vars.insert(prefix.to_string(), b.to_string());
4168+ }
4169+ JsonValue::Null => {
4170+ vars.insert(prefix.to_string(), String::new());
4171+ }
4172+ JsonValue::Object(pairs) => {
4173+ for (key, val) in pairs {
4174+ flatten_json(&format!("{}.{}", prefix, key), val, vars);
4175+ }
4176+ }
4177+ JsonValue::Array(items) => {
4178+ vars.insert(format!("{}._count", prefix), items.len().to_string());
4179+ // Check if all items are objects with the same keys
4180+ let all_objects = items.iter().all(|v| matches!(v, JsonValue::Object(_)));
4181+ if all_objects && !items.is_empty() {
4182+ // Collect keys from first object for destructuring
4183+ if let JsonValue::Object(first_pairs) = &items[0] {
4184+ let keys: Vec<String> = first_pairs.iter().map(|(k, _)| k.clone()).collect();
4185+ vars.insert(format!("{}._keys", prefix), keys.join(","));
4186+ }
4187+ // Each item becomes space-separated values, items comma-separated
4188+ let csv: Vec<String> = items
4189+ .iter()
4190+ .map(|item| {
4191+ if let JsonValue::Object(pairs) = item {
4192+ pairs
4193+ .iter()
4194+ .map(|(_, v)| json_value_to_string(v))
4195+ .collect::<Vec<_>>()
4196+ .join(" ")
4197+ } else {
4198+ json_value_to_string(item)
4199+ }
4200+ })
4201+ .collect();
4202+ vars.insert(prefix.to_string(), csv.join(","));
4203+ } else {
4204+ // Primitive array: comma-separated
4205+ let csv: Vec<String> = items.iter().map(json_value_to_string).collect();
4206+ vars.insert(prefix.to_string(), csv.join(","));
4207+ }
4208+ // Also set indexed access: prefix.0, prefix.1, etc.
4209+ for (i, item) in items.iter().enumerate() {
4210+ flatten_json(&format!("{}.{}", prefix, i), item, vars);
4211+ }
4212+ }
4213+ }
4214+}
4215+
4216+fn json_value_to_string(v: &JsonValue) -> String {
4217+ match v {
4218+ JsonValue::Str(s) => s.clone(),
4219+ JsonValue::Number(n) => n.clone(),
4220+ JsonValue::Bool(b) => b.to_string(),
4221+ JsonValue::Null => String::new(),
4222+ JsonValue::Array(_) | JsonValue::Object(_) => String::new(),
72164223 }
72174224}
72184225
@@ -7220,29 +4227,6 @@ fn json_value(json: JsonValue) -> Value {
72204227// SVG attribute injection helper
72214228// ---------------------------------------------------------------------------
72224229
7223−/// Where the root `<svg ...>` tag's `attr_name="..."` value is, as a byte
7224−/// range of `svg`. Only the opening tag is read, so a child's attribute is
7225−/// never found, and the name must follow whitespace, so `width` doesn't
7226−/// match `stroke-width`.
7227−fn svg_attr_value(svg: &str, attr_name: &str) -> Option<std::ops::Range<usize>> {
7228− let tag_start = svg.find("<svg")?;
7229− let tag_end = svg[tag_start..]
7230− .find('>')
7231− .map(|p| tag_start + p)
7232− .unwrap_or(svg.len());
7233− let tag = &svg[tag_start..tag_end];
7234− let pattern = format!("{}=\"", attr_name);
7235− let (pos, _) = tag.match_indices(&pattern).find(|(pos, _)| {
7236− tag[..*pos]
7237− .chars()
7238− .next_back()
7239− .is_some_and(char::is_whitespace)
7240− })?;
7241− let value_start = tag_start + pos + pattern.len();
7242− let end = svg[value_start..tag_end].find('"')?;
7243− Some(value_start..value_start + end)
7244−}
7245−
72464230fn set_svg_attr(svg: &str, attr_name: &str, value: &str) -> String {
72474231 // Only the opening <svg ...> tag is touched, so child attributes such as
72484232 // `stroke-width` are left alone.
@@ -7253,14 +4237,26 @@ fn set_svg_attr(svg: &str, attr_name: &str, value: &str) -> String {
72534237 .find('>')
72544238 .map(|p| tag_start + p)
72554239 .unwrap_or(svg.len());
4240+ let tag = &svg[tag_start..tag_end];
72564241
7257− // Replace an existing attribute
7258− if let Some(existing) = svg_attr_value(svg, attr_name) {
7259− let mut result = String::with_capacity(svg.len());
7260− result.push_str(&svg[..existing.start]);
7261− result.push_str(value);
7262− result.push_str(&svg[existing.end..]);
7263− return result;
4242+ // Replace an existing attribute (must be preceded by whitespace so that
4243+ // `width` doesn't match `stroke-width`).
4244+ let pattern = format!("{}=\"", attr_name);
4245+ let existing = tag.match_indices(&pattern).find(|(pos, _)| {
4246+ tag[..*pos]
4247+ .chars()
4248+ .next_back()
4249+ .is_some_and(char::is_whitespace)
4250+ });
4251+ if let Some((pos, _)) = existing {
4252+ let value_start = tag_start + pos + pattern.len();
4253+ if let Some(end) = svg[value_start..tag_end].find('"') {
4254+ let mut result = String::with_capacity(svg.len());
4255+ result.push_str(&svg[..value_start]);
4256+ result.push_str(value);
4257+ result.push_str(&svg[value_start + end..]);
4258+ return result;
4259+ }
72644260 }
72654261
72664262 // Otherwise inject it into the opening tag (before a self-closing `/`).
@@ -7583,10 +4579,7 @@ mod tests {
75834579 #[test]
75844580 fn parses_page_directive() {
75854581 let r = parse_ok("@page My Title\n");
7586− assert_eq!(
7587− r.document.page.map(|p| p.title).as_deref(),
7588− Some("My Title")
7589− );
4582+ assert_eq!(r.document.page_title.as_deref(), Some("My Title"));
75904583 }
75914584
75924585 #[test]