From 0ed55a576e6f12c2d86506d5f1297f0de2c7f11b Mon Sep 17 00:00:00 2001 From: Shahryar Tavakkoli Date: Sat, 31 Oct 2026 22:27:03 +0100 Subject: [PATCH 1/7] feat: validate_block/2 checks a rule's contents, and every validation error carries its line and column `IgniterCss.Validation` gains `errors`, a list of `IgniterCss.Diagnostic` (message, 1-based line and column, byte offset, and the text it is about), read from Biome's own parse diagnostics. Its message names the first. `validate_block/2` reads a body as the contents of one rule, the way an editor for a single element takes it, and places every error in that body. A `}` that closes the block early is an error there, though what follows it may parse. Both now leave out errors Biome 0.5.8 raises against valid CSS: a `:` in a custom property's value (`--x: a:b`), a legacy `progid:` filter, and a run of stray `;`. Each is found in the CST and kept only while its brackets close. Both report an `@import`, `@charset` or `@namespace` written inside a block, which Biome parses without an error. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- lib/igniter_css.ex | 41 +++- lib/igniter_css/native.ex | 1 + lib/igniter_css/structs.ex | 29 ++- native/igniter_css/Cargo.lock | 1 + native/igniter_css/Cargo.toml | 3 + native/igniter_css/src/analyze.rs | 336 +++++++++++++++++++++++++++--- native/igniter_css/src/atoms.rs | 1 + native/igniter_css/src/ctx.rs | 38 ++++ native/igniter_css/src/locate.rs | 157 ++++++++++++++ native/igniter_css/src/nif.rs | 70 ++++++- test/igniter_css_test.exs | 52 +++++ 12 files changed, 684 insertions(+), 47 deletions(-) diff --git a/README.md b/README.md index b805a8c..d4db9aa 100644 --- a/README.md +++ b/README.md @@ -114,7 +114,7 @@ Callers get Igniter's normal diff preview and confirmation flow. **Queries** — read-only: `has_rule?/3`, `has_declaration?/4`, `has_at_rule?/3`, `get_declaration/4`, `get_rule_declarations/3`, `get_at_rules/4`, `list_selectors/2`, `analyze/2`, -`validate/2`, `extract_colors/2`, `extract_media_queries/2`, +`validate/2`, `validate_block/2`, `extract_colors/2`, `extract_media_queries/2`, `extract_animations/2`. **Whole-file transforms** (`IgniterCss.Transform`) — `minify/2`, `beautify/2`, diff --git a/lib/igniter_css.ex b/lib/igniter_css.ex index 81dadd0..620243b 100644 --- a/lib/igniter_css.ex +++ b/lib/igniter_css.ex @@ -502,10 +502,40 @@ defmodule IgniterCss do """ @spec validate(String.t(), opts()) :: {:ok, Validation.t()} | {:error, Validation.t()} def validate(source, opts \\ []) do - case Native.validate_nif(source, ParseOpts.new(opts)) do - {:ok, _fun, validation} -> {:ok, validation} - {:error, _fun, validation} -> {:error, validation} - end + Native.validate_nif(source, ParseOpts.new(opts)) |> validation() + end + + @doc """ + Is `body` valid as the contents of one rule's block? + + What an editor that styles one element takes: declarations, nested rules + such as `&:hover { … }`, and at-rules such as `@media (…) { … }` or Tailwind's + `@apply`. It is read as the parser reads a block, by putting it inside one, + and every error is placed by line and column in `body` itself. + + On top of what `validate/2` checks, a `}` that closes the block the body is + written in is an error, though what follows it may parse: in a stylesheet, + everything after it would be outside the block. + + Returns `{:ok, %IgniterCss.Validation{}}` or `{:error, %IgniterCss.Validation{}}`. + + iex> {:ok, v} = IgniterCss.validate_block("padding: 4px;\\n&:hover { color: red; }") + iex> v.errors + [] + + iex> {:error, v} = IgniterCss.validate_block("gap: 1px;\\ncolor: red background: blue;") + iex> [%IgniterCss.Diagnostic{line: 2, column: 22, text: ": blue"}] = v.errors + iex> v.valid + false + + iex> {:error, v} = IgniterCss.validate_block("gap: 1px; } body { display: none; ") + iex> [%IgniterCss.Diagnostic{line: 1, column: 11, text: "}"}] = v.errors + iex> v.valid + false + """ + @spec validate_block(String.t(), opts()) :: {:ok, Validation.t()} | {:error, Validation.t()} + def validate_block(body, opts \\ []) do + Native.validate_block_nif(body, ParseOpts.new(opts)) |> validation() end @doc """ @@ -542,4 +572,7 @@ defmodule IgniterCss do defp unwrap({:ok, _fun, value}), do: {:ok, value} defp unwrap({:error, _fun, reason}), do: {:error, reason} + + defp validation({:ok, _fun, validation}), do: {:ok, validation} + defp validation({:error, _fun, validation}), do: {:error, validation} end diff --git a/lib/igniter_css/native.ex b/lib/igniter_css/native.ex index c4cf5e9..47ef333 100644 --- a/lib/igniter_css/native.ex +++ b/lib/igniter_css/native.ex @@ -91,6 +91,7 @@ defmodule IgniterCss.Native do def analyze_nif(_source, _opts), do: error() def get_at_rules_nif(_source, _name, _matching, _opts), do: error() def validate_nif(_source, _opts), do: error() + def validate_block_nif(_body, _opts), do: error() def extract_colors_nif(_source, _opts), do: error() def extract_media_queries_nif(_source, _opts), do: error() def extract_animations_nif(_source, _opts), do: error() diff --git a/lib/igniter_css/structs.ex b/lib/igniter_css/structs.ex index 3bb1424..12bd1ce 100644 --- a/lib/igniter_css/structs.ex +++ b/lib/igniter_css/structs.ex @@ -111,16 +111,41 @@ defmodule IgniterCss.Validation do checks before touching a file. A stylesheet that round-trips but has diagnostics is still patchable; one that does not round-trip is not, and `IgniterCss` will refuse rather than risk a wrong edit. + + `errors` is the verdict, each placed by line and column: the parser's errors + less the ones it raises against valid CSS, such as a `:` in a custom + property's value. `diagnostics` counts what the parser raised before that. """ @type t :: %__MODULE__{ valid: boolean(), diagnostics: non_neg_integer(), round_trips: boolean(), - message: String.t() + message: String.t(), + errors: [IgniterCss.Diagnostic.t()] + } + + defstruct valid: false, diagnostics: 0, round_trips: false, message: "", errors: [] +end + +defmodule IgniterCss.Diagnostic do + @moduledoc """ + One reason CSS is not valid, placed in the text that was checked. + + `line` and `column` are 1-based, the column counted in characters. `offset` is + the byte offset of `text`, the part of the source the error is about; `text` + is empty when the error is about the end of the source. + """ + + @type t :: %__MODULE__{ + message: String.t(), + line: pos_integer(), + column: pos_integer(), + offset: non_neg_integer(), + text: String.t() } - defstruct valid: false, diagnostics: 0, round_trips: false, message: "" + defstruct message: "", line: 1, column: 1, offset: 0, text: "" end defmodule IgniterCss.AtRule do diff --git a/native/igniter_css/Cargo.lock b/native/igniter_css/Cargo.lock index 761829a..bd4a74e 100644 --- a/native/igniter_css/Cargo.lock +++ b/native/igniter_css/Cargo.lock @@ -473,6 +473,7 @@ version = "1.1.1" dependencies = [ "biome_css_parser", "biome_css_syntax", + "biome_diagnostics", "biome_rowan", "proptest", "rustler", diff --git a/native/igniter_css/Cargo.toml b/native/igniter_css/Cargo.toml index 48d80ee..a8a33c2 100644 --- a/native/igniter_css/Cargo.toml +++ b/native/igniter_css/Cargo.toml @@ -36,6 +36,9 @@ crate-type = ["cdylib", "rlib"] biome_css_parser = "=0.5.8" biome_css_syntax = "=0.5.8" biome_rowan = "=0.5.8" +# Already in the graph through biome_css_parser; named here only for the +# `Diagnostic` trait, which is how a parse error gives up its span. +biome_diagnostics = "=0.5.8" rustler = "=0.38.0" [dev-dependencies] diff --git a/native/igniter_css/src/analyze.rs b/native/igniter_css/src/analyze.rs index 082661c..2167ca8 100644 --- a/native/igniter_css/src/analyze.rs +++ b/native/igniter_css/src/analyze.rs @@ -6,11 +6,12 @@ //! can violate the diff-minimality constraint -- these are the queries the //! Elixir side uses to report on a stylesheet. -use crate::ctx::{ParseCtx, ParseOptions}; +use crate::ctx::{ParseCtx, ParseError, ParseOptions}; use crate::error::Result; use crate::locate::{ - all_comments, at_rule_body, declaration_lists, declarations_in_block, find_all_at_rules, - find_all_rules, find_at_rules_named, find_top_level_rules, DeclRef, + all_comments, at_rule_body, closing_brace, declaration_lists, declarations_in_block, + find_all_at_rules, find_all_rules, find_at_rules_named, find_top_level_rules, + in_free_form_value, is_stray_semicolon, misplaced_at_rules, DeclRef, }; use crate::ops::at_rule::normalize_target_needle; use crate::ops::query; @@ -634,9 +635,118 @@ pub fn analyze(source: &str, options: ParseOptions) -> Result { #[derive(Debug, Clone, PartialEq, Eq)] pub struct Validation { pub valid: bool, + /// How many diagnostics the parser raised, before any of them is set aside + /// as an error it raises against valid CSS. `errors` is the verdict. pub diagnostics: usize, pub round_trips: bool, pub message: String, + pub errors: Vec, +} + +/// One reason a stylesheet or a block is not valid, placed in the text the +/// caller handed over. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Diagnostic { + pub message: String, + /// 1-based. + pub line: usize, + /// 1-based, counted in characters from the start of the line. + pub column: usize, + /// Byte offset of the start of `text`. + pub offset: usize, + /// The text the error is about; empty when it is about the end of the text. + pub text: String, +} + +impl Validation { + fn refused(message: String) -> Self { + Validation { + valid: false, + diagnostics: 0, + round_trips: false, + errors: vec![Diagnostic { + message: message.clone(), + line: 1, + column: 1, + offset: 0, + text: String::new(), + }], + message, + } + } + + fn of(ctx: &ParseCtx, errors: Vec) -> Self { + let round_trips = ctx.round_trips(); + let message = if !round_trips { + "the parser did not reproduce the input byte for byte; refusing to patch this file" + .to_string() + } else { + match errors.as_slice() { + [] => "CSS is valid".to_string(), + [first, ..] => format!( + "CSS parsed with {} diagnostic(s); the first is at line {}, column {}: {}", + errors.len(), + first.line, + first.column, + first.message + ), + } + }; + Validation { + valid: round_trips && errors.is_empty(), + diagnostics: ctx.diagnostics_count(), + round_trips, + message, + errors, + } + } +} + +/// What is wrong with a parse, in source order: the parser's own errors less +/// the ones it raises against valid CSS, and the at-rules written inside a +/// block that are valid only at the top level of a stylesheet. +fn errors(ctx: &ParseCtx) -> Vec { + let mut errors: Vec = ctx + .errors() + .into_iter() + .filter(|e| { + !in_free_form_value(ctx, e.start, e.end) && !is_stray_semicolon(ctx, e.start, e.end) + }) + .collect(); + errors.extend( + misplaced_at_rules(ctx) + .into_iter() + .map(|(name, start, end)| ParseError { + message: format!("`@{name}` is valid only at the top level of a stylesheet"), + start, + end, + }), + ); + errors.sort_by_key(|e| (e.start, e.end)); + errors +} + +/// `error` placed in `text`, whose first byte is at `shift` in the parsed +/// source. A range that reaches past either end of `text` is clamped to it. +fn placed(text: &str, shift: usize, error: &ParseError) -> Diagnostic { + let clamp = |at: usize| { + let mut at = at.saturating_sub(shift).min(text.len()); + while !text.is_char_boundary(at) { + at -= 1; + } + at + }; + let start = clamp(error.start); + let end = clamp(error.end).max(start); + let line_start = text[..start].rfind('\n').map_or(0, |i| i + 1); + + Diagnostic { + message: error.message.clone(), + line: text[..start].matches('\n').count() + 1, + column: text[line_start..start].chars().count() + 1, + offset: start, + text: text[start..end].to_string(), + } } /// Is this CSS understood well enough to patch? @@ -644,44 +754,81 @@ pub struct Validation { /// "Valid" here means: the parser reproduced the input byte for byte **and** /// raised no errors. The round-trip half is the one that actually matters for /// safety -- it is what every codemod checks before touching a file. +/// +/// The errors are the parser's, less the ones Biome 0.5.8 raises against valid +/// CSS (see `in_free_form_value` and `is_stray_semicolon`), plus an `@import`, +/// `@charset` or `@namespace` written inside a block, which it does not raise. pub fn validate(source: &str, options: ParseOptions) -> Validation { if let Err(e) = crate::ctx::check_nesting(source) { - return Validation { - valid: false, - diagnostics: 0, - round_trips: false, - message: e.to_string(), - }; + return Validation::refused(e.to_string()); } let ctx = match ParseCtx::try_new(source, options) { Ok(c) => c, - Err(e) => { - return Validation { - valid: false, - diagnostics: 0, - round_trips: false, - message: e.to_string(), - } - } + Err(e) => return Validation::refused(e.to_string()), }; - let round_trips = ctx.round_trips(); - let diagnostics = ctx.diagnostics_count(); - let has_errors = ctx.has_errors(); - let valid = round_trips && !has_errors; - let message = if !round_trips { - "the parser did not reproduce the input byte for byte; refusing to patch this file" - .to_string() - } else if has_errors { - format!("CSS parsed with {diagnostics} diagnostic(s)") + // Offsets are into the source without its byte-order mark, which no editor + // shows as a column. + let bom = if ctx.has_bom() { + crate::ctx::BOM.len() } else { - "CSS is valid".to_string() + 0 }; - Validation { - valid, - diagnostics, - round_trips, - message, + let errors = errors(&ctx) + .iter() + .map(|e| { + let mut d = placed(ctx.source(), 0, e); + d.offset += bom; + d + }) + .collect(); + Validation::of(&ctx, errors) +} + +/// The rule a block is read inside, its body on lines of its own: a body that +/// ends in a `//` comment, where those are read as comments, cannot then +/// comment out the closing brace. +const BLOCK_OPEN: &str = ".block {\n"; +const BLOCK_CLOSE: &str = "\n}\n"; + +/// Is `body` valid as the contents of one rule's block: declarations, nested +/// rules and at-rules, what an editor gives a single element? +/// +/// Read as the parser reads a block, by putting it inside one, with every +/// error placed in `body` itself. On top of `validate/2`'s checks, a `}` in +/// `body` that closes the block it was put in is an error: everything after it +/// would be outside that block, at the top level of whatever stylesheet the +/// body is written into, and still parse. +pub fn validate_block(body: &str, options: ParseOptions) -> Validation { + if let Err(e) = crate::ctx::check_nesting(body) { + return Validation::refused(e.to_string()); + } + let source = format!("{BLOCK_OPEN}{body}{BLOCK_CLOSE}"); + let ctx = match ParseCtx::try_new(&source, options) { + Ok(c) => c, + Err(e) => return Validation::refused(e.to_string()), + }; + + let mut found = errors(&ctx); + let body_end = BLOCK_OPEN.len() + body.len(); + let closed_early = find_top_level_rules(&ctx) + .first() + .and_then(closing_brace) + .filter(|&at| at < body_end); + if let Some(at) = closed_early { + found.push(ParseError { + message: "this `}` closes the block it is written in; everything after it is outside" + .to_string(), + start: at, + end: at + 1, + }); + found.sort_by_key(|e| (e.start, e.end)); } + + let errors = found + .iter() + .map(|e| placed(body, BLOCK_OPEN.len(), e)) + .collect(); + Validation::of(&ctx, errors) } #[cfg(test)] @@ -1002,6 +1149,131 @@ mod tests { assert!(validate("", opts()).valid); } + #[test] + fn an_error_is_placed_by_line_and_column() { + let v = validate(".a {\n color: red\n background: blue;\n}\n", opts()); + assert!(!v.valid); + let first = &v.errors[0]; + assert_eq!((first.line, first.column), (3, 13)); + assert_eq!(first.text, ": blue"); + assert!(v.message.contains("line 3, column 13"), "{}", v.message); + } + + #[test] + fn a_column_counts_characters_not_bytes() { + let v = validate(".é { content: \"ü\" color: red; }", opts()); + // `: red` is the 24th character and the 26th byte. + assert_eq!((v.errors[0].column, v.errors[0].offset), (24, 25)); + } + + // Biome 0.5.8 refuses a `:` in a value; a custom property's value may hold + // one, and Bootstrap 3 ships `progid:` filters. + #[test] + fn a_colon_in_a_free_form_value_is_valid() { + for src in [ + ".a { --x: a:b; }", + ".a { --x: [a:b]; }", + ".a { --x: a:b !important; }", + ".a { filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#80000000'); }", + ".a { -ms-filter: PROGID:DXImageTransform.Microsoft.Alpha(Opacity=80); }", + ] { + let v = validate(src, opts()); + assert!(v.valid, "{src}: {:?}", v.errors); + assert!( + v.diagnostics > 0, + "{src} no longer trips the parser; drop the exemption" + ); + } + } + + #[test] + fn a_colon_in_an_ordinary_value_is_not() { + assert!(!validate(".a { color: red color: blue; }", opts()).valid); + assert!(!validate(".a { --x: a:(b; }", opts()).valid); + } + + #[test] + fn stray_semicolons_are_nothing() { + assert!(validate(".a { color: red;;; gap: 1px }", opts()).valid); + } + + #[test] + fn an_import_inside_a_block_is_invalid() { + let v = validate(".a { @import \"x.css\"; }", opts()); + assert!(!v.valid); + assert_eq!(v.errors[0].text, "@import \"x.css\";"); + assert!(validate("@import \"x.css\";\n.a {}\n", opts()).valid); + } + + // -- blocks ------------------------------------------------------------- + + #[test] + fn a_block_takes_declarations_nesting_and_tailwind() { + for body in [ + "padding: 20px;\n\n&:hover {\n transform: translateY(-2px);\n}", + "@media (max-width: 900px) { padding: 12px; }", + "@supports (display: grid) { display: grid }", + "@container card (min-width: 400px) { color: red }", + "@layer base { color: red }", + "@apply hover:bg-red-500 md:p-4;", + "&:hover { @apply hover:underline md:p-2; }", + "content: \"}\"; color: red", + "/* } */\ngap: 1px;", + "& .w-\\[10px\\] { gap: 1px; }", + "body { display: none; }", + "", + ] { + let v = validate_block(body, opts()); + assert!(v.valid, "{body:?}: {:?}", v.errors); + } + } + + #[test] + fn a_block_error_is_placed_in_the_body() { + let v = validate_block("gap: 1px;\ncolor: red background: blue;", opts()); + assert_eq!(v.errors.len(), 1); + assert_eq!((v.errors[0].line, v.errors[0].column), (2, 22)); + assert_eq!(v.errors[0].offset, 31); + assert_eq!(v.errors[0].text, ": blue"); + } + + #[test] + fn a_block_closed_by_its_own_body_is_invalid() { + for (body, column) in [ + ("gap: 1px; } body { display: none; ", 11), + ("} &:hover { gap: 1px; }", 1), + ("--x: a:b }", 10), + ] { + let v = validate_block(body, opts()); + assert!(!v.valid, "{body:?}"); + let early = v + .errors + .iter() + .find(|e| e.message.contains("closes the block")) + .unwrap_or_else(|| panic!("{body:?}: {:?}", v.errors)); + assert_eq!( + (early.line, early.column, early.text.as_str()), + (1, column, "}") + ); + } + } + + #[test] + fn a_block_left_open_is_invalid_at_its_end() { + let v = validate_block("&:hover { gap: 1px;", opts()); + assert!(!v.valid); + let last = v.errors.last().unwrap(); + assert_eq!((last.line, last.column, last.text.as_str()), (1, 20, "")); + } + + #[test] + fn a_comment_or_string_left_open_is_invalid() { + assert!(!validate_block("/* never closed\ngap: 1px;", opts()).valid); + assert!(!validate_block("content: \"abc\ncolor: red;", opts()).valid); + assert!(!validate_block("width: calc(1px + 2px;", opts()).valid); + assert!(!validate_block("&[data-open { gap: 1px; }", opts()).valid); + } + #[test] fn tailwind_v4_validates() { let src = "@import \"tailwindcss\";\n@theme {\n --color-x: red;\n}\n@utility tab-4 {\n tab-size: 4;\n}\n"; diff --git a/native/igniter_css/src/atoms.rs b/native/igniter_css/src/atoms.rs index 7718b74..d12d2b2 100644 --- a/native/igniter_css/src/atoms.rs +++ b/native/igniter_css/src/atoms.rs @@ -38,6 +38,7 @@ rustler::atoms! { analyze_nif, get_at_rules_nif, validate_nif, + validate_block_nif, extract_colors_nif, extract_media_queries_nif, extract_animations_nif, diff --git a/native/igniter_css/src/ctx.rs b/native/igniter_css/src/ctx.rs index 0acd76e..686bb83 100644 --- a/native/igniter_css/src/ctx.rs +++ b/native/igniter_css/src/ctx.rs @@ -11,6 +11,7 @@ use biome_css_parser::{parse_css, CssParse, CssParserOptions}; use biome_css_syntax::{CssSyntaxKind, CssSyntaxNode}; +use biome_diagnostics::Diagnostic; use biome_rowan::TextRange; use std::collections::BTreeMap; @@ -77,6 +78,14 @@ pub fn check_nesting(source: &str) -> crate::error::Result<()> { Ok(()) } +/// One error the parser raised: what it said, and the byte range it is about. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ParseError { + pub message: String, + pub start: usize, + pub end: usize, +} + #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Newline { Lf, @@ -209,6 +218,35 @@ impl ParseCtx { self.parse.has_errors() } + /// Every error the parser raised, with the bytes it points at, in source + /// order. + /// + /// Biome reports an error without a span only for a whole-file problem; + /// that one is pinned to the end of the file, where the reader ran out. + pub fn errors(&self) -> Vec { + let end = self.source.len(); + let mut errors: Vec = self + .parse + .diagnostics() + .iter() + .filter(|d| d.is_error()) + .map(|d| { + let (start, stop) = d + .location() + .span + .map(|r| (usize::from(r.start()), usize::from(r.end()))) + .unwrap_or((end, end)); + ParseError { + message: d.message.to_string(), + start: start.min(end), + end: stop.clamp(start.min(end), end), + } + }) + .collect(); + errors.sort_by_key(|e| (e.start, e.end)); + errors + } + /// The parse is lossless by construction, but assert it before we let any /// codemod compute offsets against it. If this ever fails, the byte-range /// design's foundation is gone and we must refuse to patch rather than diff --git a/native/igniter_css/src/locate.rs b/native/igniter_css/src/locate.rs index 9bed28d..48db4b2 100644 --- a/native/igniter_css/src/locate.rs +++ b/native/igniter_css/src/locate.rs @@ -839,6 +839,163 @@ pub fn all_comments(ctx: &ParseCtx) -> Vec<(usize, usize, String)> { out } +// --------------------------------------------------------------------------- +// Errors the parser raises against valid CSS, and errors it does not raise +// --------------------------------------------------------------------------- + +/// Byte offset of the `}` that closes `rule`'s own block, or `None` when the +/// block is never closed. +pub fn closing_brace(rule: &RuleRef) -> Option { + let block = block_child(&rule.node)?; + block + .children_with_tokens() + .filter_map(|e| e.into_token()) + .find(|t| t.kind() == CssSyntaxKind::R_CURLY) + .map(|t| usize::from(t.text_trimmed_range().start())) +} + +/// The smallest node whose range covers `start..end`. +fn covering_node(ctx: &ParseCtx, start: usize, end: usize) -> Option { + let start = u32::try_from(start).ok()?; + let end = u32::try_from(end).ok()?; + let range = TextRange::new(start.into(), end.into()); + if !ctx.syntax().text_range().contains_range(range) { + return None; + } + match ctx.syntax().covering_element(range) { + biome_rowan::SyntaxElement::Node(node) => Some(node), + biome_rowan::SyntaxElement::Token(token) => token.parent(), + } +} + +/// Is `start..end` inside a declaration value whose grammar is any run of +/// tokens, where Biome 0.5.8 raises an error the specification does not? +/// +/// * A custom property's value, `--x: a:b`: CSS Custom Properties takes any +/// tokens there, a `:` included. Biome reads it as an ordinary value and +/// refuses the colon. +/// * A legacy `progid:` filter, `filter: progid:DXImageTransform…(…)`, which old +/// Internet Explorer read and vendored stylesheets such as Bootstrap 3 still +/// carry. +/// +/// Only while every `(`, `[` and `{` in the value is closed inside it. The +/// specification reads an open one to its match, braces included, so it +/// swallows everything after it; Biome ends the declaration at the next `;` +/// instead, and the value would look harmless here when it is not. +pub fn in_free_form_value(ctx: &ParseCtx, start: usize, end: usize) -> bool { + let Some(node) = covering_node(ctx, start, end) else { + return false; + }; + let Some(property) = node.ancestors().find(|n| { + matches!( + n.kind(), + CssSyntaxKind::CSS_GENERIC_PROPERTY | CssSyntaxKind::CSS_BOGUS_PROPERTY + ) + }) else { + return false; + }; + let Some(colon) = property + .children_with_tokens() + .filter_map(|e| e.into_token()) + .find(|t| t.kind() == CssSyntaxKind::COLON) + else { + return false; + }; + let value_start = usize::from(colon.text_trimmed_range().end()); + if start < value_start { + return false; + } + + let value: Vec<_> = property + .descendants_tokens(Direction::Next) + .filter(|t| usize::from(t.text_trimmed_range().start()) >= value_start) + .collect(); + let custom = property + .first_child() + .is_some_and(|name| name.kind() == CssSyntaxKind::CSS_DASHED_IDENTIFIER); + let progid = matches!( + value.as_slice(), + [first, second, ..] + if first.text_trimmed().eq_ignore_ascii_case("progid") + && second.kind() == CssSyntaxKind::COLON + ); + + (custom || progid) && brackets_close(&value) +} + +/// Does every `(`, `[` and `{` among `tokens` meet its own closer, in order? +fn brackets_close(tokens: &[biome_rowan::SyntaxToken]) -> bool { + let mut open: Vec = Vec::new(); + for token in tokens { + match token.kind() { + CssSyntaxKind::L_PAREN => open.push(CssSyntaxKind::R_PAREN), + CssSyntaxKind::L_BRACK => open.push(CssSyntaxKind::R_BRACK), + CssSyntaxKind::L_CURLY => open.push(CssSyntaxKind::R_CURLY), + kind @ (CssSyntaxKind::R_PAREN | CssSyntaxKind::R_BRACK | CssSyntaxKind::R_CURLY) + if open.pop() != Some(kind) => + { + return false + } + _ => {} + } + } + open.is_empty() +} + +/// Is `start..end` a `;` the parser refused as an item of a block? +/// +/// CSS Syntax skips a `;` among a block's contents however many stand +/// together. Biome 0.5.8 takes one empty declaration (`a;;`) and raises an +/// error on the next (`a;;;`). +pub fn is_stray_semicolon(ctx: &ParseCtx, start: usize, end: usize) -> bool { + let Some(node) = covering_node(ctx, start, end) else { + return false; + }; + let in_block = node.parent().is_some_and(|p| { + matches!( + p.kind(), + CssSyntaxKind::CSS_DECLARATION_OR_RULE_LIST + | CssSyntaxKind::CSS_DECLARATION_LIST + | CssSyntaxKind::CSS_DECLARATION_OR_AT_RULE_LIST + ) + }); + is_bogus(node.kind()) + && in_block + && node + .descendants_tokens(Direction::Next) + .all(|t| t.kind() == CssSyntaxKind::SEMICOLON) +} + +/// At-rules that are valid only at the top level of a stylesheet, written +/// inside a block instead, as `(name, start, end)`. +/// +/// Biome 0.5.8 parses `.a { @import "x.css"; }` without an error, though CSS +/// Cascade and CSS Nesting make it invalid there, and Tailwind refuses to build +/// a stylesheet that does it. +pub fn misplaced_at_rules(ctx: &ParseCtx) -> Vec<(String, usize, usize)> { + ctx.syntax() + .descendants() + .filter_map(|n| { + let name = match n.kind() { + CssSyntaxKind::CSS_IMPORT_AT_RULE => "import", + CssSyntaxKind::CSS_CHARSET_AT_RULE => "charset", + CssSyntaxKind::CSS_NAMESPACE_AT_RULE => "namespace", + _ => return None, + }; + let at_rule = n.parent()?; + let top_level = at_rule.parent().is_some_and(|list| { + list.parent() + .is_some_and(|p| p.kind() == CssSyntaxKind::CSS_ROOT) + }); + if top_level { + return None; + } + let (start, end) = trimmed(&at_rule); + Some((name.to_string(), start, end)) + }) + .collect() +} + #[cfg(test)] mod tests { use super::*; diff --git a/native/igniter_css/src/nif.rs b/native/igniter_css/src/nif.rs index 27e39bf..ef30c72 100644 --- a/native/igniter_css/src/nif.rs +++ b/native/igniter_css/src/nif.rs @@ -120,6 +120,41 @@ pub struct ExValidation { pub diagnostics: usize, pub round_trips: bool, pub message: String, + pub errors: Vec, +} + +impl From for ExValidation { + fn from(v: analyze::Validation) -> Self { + ExValidation { + valid: v.valid, + diagnostics: v.diagnostics, + round_trips: v.round_trips, + message: v.message, + errors: v.errors.into_iter().map(ExDiagnostic::from).collect(), + } + } +} + +#[derive(NifStruct, Debug, Clone)] +#[module = "IgniterCss.Diagnostic"] +pub struct ExDiagnostic { + pub message: String, + pub line: usize, + pub column: usize, + pub offset: usize, + pub text: String, +} + +impl From for ExDiagnostic { + fn from(d: analyze::Diagnostic) -> Self { + ExDiagnostic { + message: d.message, + line: d.line, + column: d.column, + offset: d.offset, + text: d.text, + } + } } #[derive(NifStruct, Debug, Clone)] @@ -533,15 +568,34 @@ fn analyze_nif(env: Env, source: String, opts: ExParseOpts) -> NifResult { #[rustler::nif(schedule = "DirtyCpu")] fn validate_nif(env: Env, source: String, opts: ExParseOpts) -> NifResult { - let v = analyze::validate(&source, opts.into()); - let status = if v.valid { atoms::ok() } else { atoms::error() }; - let payload = ExValidation { - valid: v.valid, - diagnostics: v.diagnostics, - round_trips: v.round_trips, - message: v.message, + respond_validation( + env, + atoms::validate_nif(), + analyze::validate(&source, opts.into()), + ) +} + +#[rustler::nif(schedule = "DirtyCpu")] +fn validate_block_nif(env: Env, body: String, opts: ExParseOpts) -> NifResult { + respond_validation( + env, + atoms::validate_block_nif(), + analyze::validate_block(&body, opts.into()), + ) +} + +/// `{:ok | :error, fun, %IgniterCss.Validation{}}`: the details either way. +fn respond_validation( + env: Env, + fun: rustler::types::atom::Atom, + validation: analyze::Validation, +) -> NifResult { + let status = if validation.valid { + atoms::ok() + } else { + atoms::error() }; - encode_response(env, status, atoms::validate_nif(), payload) + encode_response(env, status, fun, ExValidation::from(validation)) } #[rustler::nif(schedule = "DirtyCpu")] diff --git a/test/igniter_css_test.exs b/test/igniter_css_test.exs index c8ee6ad..0b63ce2 100644 --- a/test/igniter_css_test.exs +++ b/test/igniter_css_test.exs @@ -635,6 +635,58 @@ defmodule IgniterCssTest do end end + describe "validate/2 errors" do + test "each is placed by line and column" do + assert {:error, %{errors: [error]}} = + IgniterCss.validate(".a {\n color: red\n background: blue;\n}\n") + + assert %IgniterCss.Diagnostic{line: 3, column: 13, text: ": blue"} = error + end + + test "a colon in a custom property or a progid filter is not one" do + assert {:ok, %{errors: []}} = IgniterCss.validate(".a { --x: a:b; }") + + assert {:ok, %{errors: []}} = + IgniterCss.validate( + ".a { filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=80); }" + ) + end + end + + describe "validate_block/2" do + test "takes declarations, nesting, at-rules and @apply" do + for body <- [ + "padding: 20px;\n\n&:hover {\n transform: translateY(-2px);\n}", + "@media (max-width: 900px) { padding: 12px; }", + "@apply hover:bg-red-500 md:p-4;", + ~s|content: "}"; color: red|, + "--x: a:b;", + "" + ] do + assert {:ok, %{valid: true, errors: []}} = IgniterCss.validate_block(body), body + end + end + + test "places an error in the body, not in the rule it is read inside" do + assert {:error, %{errors: [error | _rest]}} = + IgniterCss.validate_block("gap: 1px;\ncolor crimson") + + assert %IgniterCss.Diagnostic{line: 2, column: 14} = error + end + + test "refuses a } that closes the block early, even when the rest parses" do + assert {:error, %{errors: [error]}} = + IgniterCss.validate_block("gap: 1px; } body { display: none; ") + + assert %IgniterCss.Diagnostic{line: 1, column: 11, offset: 10, text: "}"} = error + end + + test "refuses an @import, which is valid only at the top level" do + assert {:error, %{errors: [%{text: ~s|@import "x.css";|}]}} = + IgniterCss.validate_block(~s|@import "x.css";|) + end + end + describe "extract_*" do test "extracts colours by selector" do assert {:ok, [{".a", ["color: #333"]}, {".b", ["background: rgba(0,0,0,.5)"]}]} = From 7c0a346be2bac46c5df1864fdba0a26fb98e57ce Mon Sep 17 00:00:00 2001 From: Shahryar Tavakkoli Date: Sun, 1 Nov 2026 01:35:36 +0100 Subject: [PATCH 2/7] feat: list_at_rules/2 and remove_at_rules/3 reach at-rules at any depth, ones the parser could not place included `list_at_rules/2` returns every at-rule in the file as `IgniterCss.AtRule`, in source order: nested in `@media`, `@layer`, a rule or another at-rule's block, and where Biome could not place one, such as an `@import` inside `@font-face` or a keyframe. Biome keeps that one as bogus tokens, but Tailwind still imports the file it names, so it is read from the tokens after its `@` up to the `;` or block that ends it. An `@` counts only where a statement starts (first, or after `;`, `{` or `}`), so one in a string, a comment or `url(@x.png)` starts nothing. `remove_at_rules/3` removes, wherever they are, the at-rules written exactly as ones `list_at_rules/2` returned, with the comments they own. Matched on the text, so a second run changes nothing; one inside another being removed goes with it, and braces that do not balance are refused. Co-Authored-By: Claude Opus 5.5 --- README.md | 3 +- lib/igniter_css.ex | 47 ++++++++++ lib/igniter_css/native.ex | 2 + native/igniter_css/src/analyze.rs | 125 ++++++++++++++++++++----- native/igniter_css/src/atoms.rs | 2 + native/igniter_css/src/locate.rs | 128 +++++++++++++++++++++++++- native/igniter_css/src/nif.rs | 53 ++++++++--- native/igniter_css/src/ops/at_rule.rs | 90 +++++++++++++++++- test/at_rules_test.exs | 66 +++++++++++++ 9 files changed, 476 insertions(+), 40 deletions(-) diff --git a/README.md b/README.md index d4db9aa..05e9075 100644 --- a/README.md +++ b/README.md @@ -103,6 +103,7 @@ Callers get Igniter's normal diff preview and confirmation flow. | | | |---|---| | `ensure_at_rule/3`, `remove_at_rule/4` | `@import`, `@plugin`, `@source`, `@layer`, … | +| `remove_at_rules/3` | at-rules `list_at_rules/2` found, at any depth | | `ensure_at_rule_block/5`, `ensure_at_rule_declarations/5`, `remove_at_rule_declarations/5` | at-rule blocks: a whole body, or only the declarations you own in a shared one such as `@theme` | | `add_import/4`, `remove_import/3` | `@import` convenience wrappers | | `ensure_rule/4`, `remove_rule/3` | whole rules | @@ -112,7 +113,7 @@ Callers get Igniter's normal diff preview and confirmation flow. | `sort_properties/2`, `remove_duplicates/2` | tidying, by moving and deleting whole lines | **Queries** — read-only: `has_rule?/3`, `has_declaration?/4`, `has_at_rule?/3`, -`get_declaration/4`, `get_rule_declarations/3`, `get_at_rules/4`, +`get_declaration/4`, `get_rule_declarations/3`, `get_at_rules/4`, `list_at_rules/2`, `list_selectors/2`, `analyze/2`, `validate/2`, `validate_block/2`, `extract_colors/2`, `extract_media_queries/2`, `extract_animations/2`. diff --git a/lib/igniter_css.ex b/lib/igniter_css.ex index 620243b..bd3375a 100644 --- a/lib/igniter_css.ex +++ b/lib/igniter_css.ex @@ -245,6 +245,53 @@ defmodule IgniterCss do Native.get_at_rules_nif(source, name, matching, ParseOpts.new(opts)) |> unwrap() end + @doc """ + Every at-rule in the file, as `IgniterCss.AtRule` structs in source order, + wherever it is: nested in `@media`, `@layer`, a rule or another at-rule's + block, and where the parser could not place one, such as an `@import` inside + `@font-face` or a keyframe. Biome keeps that one as bogus tokens, but a reader + with a looser grammar, Tailwind for one, still acts on it, so it is here too, + running from its `@` to the `;` or the block that ends it. + + An `@` inside a string, a comment or a `url()` starts nothing. The name keeps + any escape as written (`@\\69mport` is named `\\69mport`). + + For a caller that must know everything a stylesheet asks for, such as one + that keeps a build tool from reading files; the codemods stay top-level. + + iex> css = ~s|@media print {\\n @import "a.css";\\n}\\n@font-face { @plugin "p"; }\\n| + iex> {:ok, rules} = IgniterCss.list_at_rules(css) + iex> Enum.map(rules, &{&1.name, &1.target}) + [{"media", nil}, {"import", "a.css"}, {"font-face", nil}, {"plugin", "p"}] + """ + @spec list_at_rules(String.t(), opts()) :: + {:ok, [IgniterCss.AtRule.t()]} | {:error, String.t()} + def list_at_rules(source, opts \\ []) do + Native.list_at_rules_nif(source, ParseOpts.new(opts)) |> unwrap() + end + + @doc """ + Remove, wherever it is, every at-rule written exactly as one of `at_rules`: + at-rules `list_at_rules/2` returned for this `source`, read with the same + `opts`. One inside another being removed goes with it, and the comments a + removed at-rule owns go too, as with `remove_at_rule/4`. + + Matched on the at-rule's text, so a second run on the output finds nothing + and reports `changed: false`. + + iex> css = ~s|@media print {\\n @import "a.css";\\n .a { color: red; }\\n}\\n| + iex> {:ok, rules} = IgniterCss.list_at_rules(css) + iex> {:ok, out} = IgniterCss.remove_at_rules(css, Enum.filter(rules, &(&1.name == "import"))) + iex> out.source + ~s|@media print {\\n .a { color: red; }\\n}\\n| + """ + @spec remove_at_rules(String.t(), [IgniterCss.AtRule.t()], opts()) :: result() + def remove_at_rules(source, at_rules, opts \\ []) when is_list(at_rules) do + source + |> Native.remove_at_rules_nif(Enum.map(at_rules, & &1.text), ParseOpts.new(opts)) + |> unwrap() + end + @doc """ Add an `@import`, building the line for you. diff --git a/lib/igniter_css/native.ex b/lib/igniter_css/native.ex index 47ef333..dbe9843 100644 --- a/lib/igniter_css/native.ex +++ b/lib/igniter_css/native.ex @@ -49,6 +49,7 @@ defmodule IgniterCss.Native do do: error() def remove_at_rule_nif(_source, _name, _matching, _opts), do: error() + def remove_at_rules_nif(_source, _texts, _opts), do: error() def has_at_rule_nif(_source, _line, _opts), do: error() def add_import_nif(_source, _url, _media, _opts), do: error() def remove_import_nif(_source, _url, _opts), do: error() @@ -90,6 +91,7 @@ defmodule IgniterCss.Native do def analyze_nif(_source, _opts), do: error() def get_at_rules_nif(_source, _name, _matching, _opts), do: error() + def list_at_rules_nif(_source, _opts), do: error() def validate_nif(_source, _opts), do: error() def validate_block_nif(_body, _opts), do: error() def extract_colors_nif(_source, _opts), do: error() diff --git a/native/igniter_css/src/analyze.rs b/native/igniter_css/src/analyze.rs index 2167ca8..1ce38db 100644 --- a/native/igniter_css/src/analyze.rs +++ b/native/igniter_css/src/analyze.rs @@ -10,8 +10,9 @@ use crate::ctx::{ParseCtx, ParseError, ParseOptions}; use crate::error::Result; use crate::locate::{ all_comments, at_rule_body, closing_brace, declaration_lists, declarations_in_block, - find_all_at_rules, find_all_rules, find_at_rules_named, find_top_level_rules, - in_free_form_value, is_stray_semicolon, misplaced_at_rules, DeclRef, + find_all_at_rules, find_all_rules, find_at_rules_named, find_every_at_rule, + find_top_level_rules, in_free_form_value, is_stray_semicolon, misplaced_at_rules, AtRuleRef, + DeclRef, }; use crate::ops::at_rule::normalize_target_needle; use crate::ops::query; @@ -479,6 +480,29 @@ pub struct AtRule { pub body: Option, } +fn read_at_rule(ctx: &ParseCtx, at: &AtRuleRef) -> AtRule { + AtRule { + name: at.name.clone(), + prelude: at.prelude.clone(), + target: at.target.clone(), + has_block: at.has_block, + declarations: at_rule_body(at) + .filter(|_| at.placed) + .map(|block| { + declarations_in_block(ctx, &block) + .iter() + .map(|d| (d.property.clone(), d.value_raw.trim().to_string())) + .collect() + }) + .unwrap_or_default(), + text: ctx.source()[at.start..at.end].to_string(), + body: match (at.body_open, at.body_close) { + (Some(open), Some(close)) => Some(ctx.source()[open..close].to_string()), + _ => None, + }, + } +} + /// Every **top-level** at-rule named `name`, optionally narrowed to those /// `matching` names -- see [`crate::locate::AtRuleRef::matches`]. /// @@ -498,25 +522,22 @@ pub fn get_at_rules( Ok(find_at_rules_named(ctx, &wanted) .iter() .filter(|at| at.matches(want.as_deref())) - .map(|at| AtRule { - name: at.name.clone(), - prelude: at.prelude.clone(), - target: at.target.clone(), - has_block: at.has_block, - declarations: at_rule_body(at) - .map(|block| { - declarations_in_block(ctx, &block) - .iter() - .map(|d| (d.property.clone(), d.value_raw.trim().to_string())) - .collect() - }) - .unwrap_or_default(), - text: ctx.source()[at.start..at.end].to_string(), - body: match (at.body_open, at.body_close) { - (Some(open), Some(close)) => Some(ctx.source()[open..close].to_string()), - _ => None, - }, - }) + .map(|at| read_at_rule(ctx, at)) + .collect()) + }) +} + +/// Every at-rule in the file, in source order, wherever it is: nested in +/// `@media`, `@layer`, a rule or another at-rule's block, or where the parser +/// could not place one -- see [`crate::locate::find_every_at_rule`]. +/// +/// For a caller that has to know everything a stylesheet asks for, such as one +/// that keeps a build tool from reading files, rather than for a codemod. +pub fn list_at_rules(source: &str, options: ParseOptions) -> Result> { + query(source, options, |ctx| { + Ok(find_every_at_rule(ctx) + .iter() + .map(|at| read_at_rule(ctx, at)) .collect()) }) } @@ -933,6 +954,68 @@ mod tests { .contains("/* keeps daisyUI off our own .btn */")); } + fn listed(src: &str) -> Vec<(String, Option)> { + list_at_rules(src, ParseOptions::strict()) + .unwrap() + .into_iter() + .map(|at| (at.name, at.target)) + .collect() + } + + fn named(name: &str, target: &str) -> (String, Option) { + (name.to_string(), Some(target.to_string())) + } + + #[test] + fn lists_every_at_rule_at_any_depth_in_source_order() { + let src = "@import \"a.css\";\n@media print {\n @import \"b.css\";\n .a { &:hover { @source \"../c\"; } }\n}\n@layer base { @plugin \"d\"; }\n"; + assert_eq!( + listed(src), + vec![ + named("import", "a.css"), + ("media".to_string(), None), + named("import", "b.css"), + named("source", "../c"), + ("layer".to_string(), None), + named("plugin", "d"), + ] + ); + } + + #[test] + fn lists_an_at_rule_the_parser_could_not_place() { + // CSS has no at-rule inside `@font-face` or a keyframe, so Biome keeps + // these as bogus tokens. Tailwind still imports the file. + let found = list_at_rules( + "@font-face { src: x; @import \"../x.css\"; font-family: a; }", + ParseOptions::strict(), + ) + .unwrap(); + assert_eq!(found[1].name, "import"); + assert_eq!(found[1].target.as_deref(), Some("../x.css")); + assert_eq!(found[1].text, "@import \"../x.css\";"); + assert!(found[1].declarations.is_empty()); + + assert_eq!( + listed("@keyframes k { from { @plugin \"p\" { a: b } color: red } }"), + vec![("keyframes".to_string(), None), named("plugin", "p")] + ); + } + + #[test] + fn an_at_sign_in_a_string_a_comment_or_a_value_starts_nothing() { + let src = + "/* @import \"a\"; */ .a { content: \"@import 'b';\"; background: url(@import.png); }"; + assert!(listed(src).is_empty()); + assert!(listed(".a { b: c @import \"x\"; }").is_empty()); + } + + #[test] + fn a_listed_name_keeps_its_case_folded_and_its_escape_as_written() { + assert_eq!(listed("@IMPORT \"a\";"), vec![named("import", "a")]); + assert_eq!(listed("@\\69mport \"a\";"), vec![named("\\69mport", "a")]); + } + #[test] fn an_absent_at_rule_is_an_empty_list_not_an_error() { assert!(get_at_rules(".a { color: red; }\n", "plugin", None, opts()) diff --git a/native/igniter_css/src/atoms.rs b/native/igniter_css/src/atoms.rs index d12d2b2..7199676 100644 --- a/native/igniter_css/src/atoms.rs +++ b/native/igniter_css/src/atoms.rs @@ -14,6 +14,7 @@ rustler::atoms! { ensure_at_rule_declarations_nif, remove_at_rule_declarations_nif, remove_at_rule_nif, + remove_at_rules_nif, has_at_rule_nif, add_import_nif, remove_import_nif, @@ -37,6 +38,7 @@ rustler::atoms! { analyze_nif, get_at_rules_nif, + list_at_rules_nif, validate_nif, validate_block_nif, extract_colors_nif, diff --git a/native/igniter_css/src/locate.rs b/native/igniter_css/src/locate.rs index 48db4b2..55b1def 100644 --- a/native/igniter_css/src/locate.rs +++ b/native/igniter_css/src/locate.rs @@ -13,7 +13,7 @@ //! pick one, because guessing produces surprising diffs. use crate::ctx::{is_bogus, ParseCtx}; -use biome_css_syntax::{CssSyntaxKind, CssSyntaxNode}; +use biome_css_syntax::{CssSyntaxKind, CssSyntaxNode, CssSyntaxToken}; use biome_rowan::{Direction, TextRange}; // --------------------------------------------------------------------------- @@ -72,6 +72,9 @@ pub struct AtRuleRef { /// Present only when `has_block`. pub body_open: Option, pub body_close: Option, + /// False for an `@` the parser could not place in an at-rule -- see + /// [`find_every_at_rule`]. Its `node` is then the one the `@` sits in. + pub placed: bool, } impl AtRuleRef { @@ -466,6 +469,111 @@ fn at_rule_ref_from(node: &CssSyntaxNode, ctx: &ParseCtx) -> Option { has_block, body_open, body_close, + placed: true, + }) +} + +/// The at-rule an `@` starts where the parser could not place one, read from +/// the tokens that follow it: the name written against the `@`, then up to the +/// `;` that ends it or the `}` that closes its block. A `}` closing the block +/// the `@` sits in ends it first. +/// +/// `None` for an `@` with no name against it, or one that does not start a +/// statement -- first in the file or after a `;`, `{` or `}`, comments aside -- +/// because after anything else it is part of a selector or a value +/// (`url(@x.png)`), as every reader of CSS takes it. +fn stray_at_rule_ref(ctx: &ParseCtx, at: &CssSyntaxToken) -> Option { + let starts_statement = at.prev_token().is_none_or(|token| { + matches!( + token.kind(), + CssSyntaxKind::SEMICOLON | CssSyntaxKind::L_CURLY | CssSyntaxKind::R_CURLY + ) + }); + if !starts_statement { + return None; + } + let (start, at_end) = range_to_pair(at.text_trimmed_range()); + let name_token = at.next_token()?; + let (name_start, name_end) = range_to_pair(name_token.text_trimmed_range()); + if name_start != at_end || name_token.kind() == CssSyntaxKind::EOF { + return None; + } + + let mut end = name_end; + let mut depth = 0usize; + let mut prelude_end = None; + let mut body_open = None; + let mut body_close = None; + let mut target = None; + let mut prelude_norm = Vec::new(); + let mut cursor = name_token.next_token(); + + while let Some(token) = cursor { + let (token_start, token_end) = range_to_pair(token.text_trimmed_range()); + match token.kind() { + CssSyntaxKind::EOF => break, + CssSyntaxKind::SEMICOLON if depth == 0 => { + prelude_end.get_or_insert(token_start); + end = token_end; + break; + } + CssSyntaxKind::L_CURLY => { + if depth == 0 { + prelude_end.get_or_insert(token_start); + body_open = Some(token_end); + } + depth += 1; + end = token_end; + } + CssSyntaxKind::R_CURLY if depth == 0 => break, + CssSyntaxKind::R_CURLY => { + depth -= 1; + end = token_end; + if depth == 0 { + body_close = Some(token_start); + break; + } + } + kind => { + if prelude_end.is_none() { + if target.is_none() { + target = match kind { + CssSyntaxKind::CSS_STRING_LITERAL => { + Some(unquote(token.text_trimmed())) + } + CssSyntaxKind::CSS_URL_VALUE_RAW_LITERAL => { + Some(token.text_trimmed().trim().to_string()) + } + _ => None, + }; + } + prelude_norm.push(token.text_trimmed().to_string()); + } + end = token_end; + } + } + cursor = token.next_token(); + } + + let prelude_end = prelude_end.unwrap_or(end); + Some(AtRuleRef { + node: at.parent()?, + name: name_token.text_trimmed().trim().to_lowercase(), + prelude: ctx + .source() + .get(name_end..prelude_end.max(name_end)) + .unwrap_or("") + .trim() + .to_string(), + prelude_norm: prelude_norm.join(" "), + target, + start, + end, + has_block: body_open.is_some(), + body_open, + // An unclosed block runs to the end of the at-rule's text. + body_close: body_open.map(|_| body_close.unwrap_or(end)), + placed: false, }) } @@ -574,6 +682,24 @@ pub fn find_all_at_rules(ctx: &ParseCtx) -> Vec { .collect() } +/// Every at-rule in the file, in source order: each one [`find_all_at_rules`] +/// finds, at any depth, and each `@` the parser could not place in an at-rule, +/// such as an `@import` inside `@font-face` or a keyframe. Biome keeps those as +/// bogus tokens, but a reader with a looser grammar -- Tailwind, for one -- still +/// acts on them, so a caller deciding what a stylesheet may ask for has to see +/// them too. An `@` inside a string, a comment or a `url()` is part of that +/// token and starts nothing. +pub fn find_every_at_rule(ctx: &ParseCtx) -> Vec { + ctx.syntax() + .descendants_tokens(Direction::Next) + .filter(|token| token.kind() == CssSyntaxKind::AT) + .filter_map(|at| match at.parent() { + Some(node) if node.kind() == CssSyntaxKind::CSS_AT_RULE => at_rule_ref_from(&node, ctx), + _ => stray_at_rule_ref(ctx, &at), + }) + .collect() +} + /// Top-level at-rules with the given (lowercase, no `@`) name. pub fn find_at_rules_named(ctx: &ParseCtx, name: &str) -> Vec { let want = name.trim_start_matches('@').to_lowercase(); diff --git a/native/igniter_css/src/nif.rs b/native/igniter_css/src/nif.rs index ef30c72..a7baf0d 100644 --- a/native/igniter_css/src/nif.rs +++ b/native/igniter_css/src/nif.rs @@ -169,6 +169,20 @@ pub struct ExAtRule { pub body: Option, } +impl From for ExAtRule { + fn from(a: analyze::AtRule) -> Self { + ExAtRule { + name: a.name, + prelude: a.prelude, + target: a.target, + has_block: a.has_block, + declarations: a.declarations, + text: a.text, + body: a.body, + } + } +} + #[derive(NifStruct, Debug, Clone)] #[module = "IgniterCss.Animation"] pub struct ExAnimation { @@ -675,19 +689,32 @@ fn get_at_rules_nif( respond!( env, atoms::get_at_rules_nif(), - analyze::get_at_rules(&source, &name, matching.as_deref(), opts.into()).map(|list| { - list.into_iter() - .map(|a| ExAtRule { - name: a.name, - prelude: a.prelude, - target: a.target, - has_block: a.has_block, - declarations: a.declarations, - text: a.text, - body: a.body, - }) - .collect::>() - }) + analyze::get_at_rules(&source, &name, matching.as_deref(), opts.into()) + .map(|list| list.into_iter().map(ExAtRule::from).collect::>()) + ) +} + +#[rustler::nif(schedule = "DirtyCpu")] +fn list_at_rules_nif(env: Env, source: String, opts: ExParseOpts) -> NifResult { + respond!( + env, + atoms::list_at_rules_nif(), + analyze::list_at_rules(&source, opts.into()) + .map(|list| list.into_iter().map(ExAtRule::from).collect::>()) + ) +} + +#[rustler::nif(schedule = "DirtyCpu")] +fn remove_at_rules_nif( + env: Env, + source: String, + texts: Vec, + opts: ExParseOpts, +) -> NifResult { + respond!( + env, + atoms::remove_at_rules_nif(), + at_rule::remove_at_rules(&source, &texts, opts.into()).map(ExOutcome::from) ) } diff --git a/native/igniter_css/src/ops/at_rule.rs b/native/igniter_css/src/ops/at_rule.rs index c477bc1..9cc6fc9 100644 --- a/native/igniter_css/src/ops/at_rule.rs +++ b/native/igniter_css/src/ops/at_rule.rs @@ -12,15 +12,15 @@ use crate::ctx::{ParseCtx, ParseOptions}; use crate::edit::Edit; use crate::error::{CssError, Result}; use crate::locate::{ - at_rule_block_rule, declarations_in, find_at_rules_named, find_top_level_at_rules, - find_top_level_rules, non_declaration_items, normalize_property, top_level_nodes, - top_of_file_anchor, value_norm, AtRuleRef, DeclRef, + at_rule_block_rule, declarations_in, find_at_rules_named, find_every_at_rule, + find_top_level_at_rules, find_top_level_rules, non_declaration_items, normalize_property, + top_level_nodes, top_of_file_anchor, value_norm, AtRuleRef, DeclRef, }; use crate::ops::rule::append_all_to_body; use crate::ops::{reindent, run, validate_snippet, Outcome}; use crate::trivia::{absorb_surrounding_blank_line, comment_ranges, deletion_span}; use biome_css_syntax::CssSyntaxKind; -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; /// At-rules that must appear before any style rule, in this order. const PROLOGUE_FIRST: &[&str] = &["charset", "import", "use", "namespace"]; @@ -215,6 +215,38 @@ pub fn remove_at_rule( }) } +/// Remove every at-rule, wherever it is, whose text is exactly one of `texts` +/// -- the `text` of at-rules [`crate::analyze::list_at_rules`] returned, read +/// with the same options, ones the parser could not place included. One inside +/// another being removed goes with it, and comments it owns go as they do for +/// [`remove_at_rule`]. Matched on the text rather than a position, so running +/// it again on its own output finds nothing and changes nothing. +pub fn remove_at_rules(source: &str, texts: &[String], options: ParseOptions) -> Result { + let texts: HashSet<&str> = texts.iter().map(String::as_str).collect(); + + run(source, options, |ctx| { + let comments = comment_ranges(ctx); + let mut edits: Vec = Vec::new(); + // In source order, so a span inside or touching the last one widens it + // rather than overlapping it. + for at in find_every_at_rule(ctx) { + if !texts.contains(&ctx.source()[at.start..at.end]) { + continue; + } + let span = + absorb_surrounding_blank_line(ctx, deletion_span(ctx, &comments, at.start, at.end)); + match edits.last_mut() { + Some(last) if span.start <= last.end => { + last.start = last.start.min(span.start); + last.end = last.end.max(span.end); + } + _ => edits.push(Edit::delete(span.start, span.end)), + } + } + Ok(edits) + }) +} + /// `@import` convenience wrapper: builds the line and delegates. pub fn add_import( source: &str, @@ -1535,6 +1567,56 @@ mod tests { } } + fn remove_listed(src: &str, names: &[&str]) -> Outcome { + let texts: Vec = crate::analyze::list_at_rules(src, ParseOptions::strict()) + .unwrap() + .into_iter() + .filter(|at| names.contains(&at.name.as_str())) + .map(|at| at.text) + .collect(); + remove_at_rules(src, &texts, ParseOptions::strict()).unwrap() + } + + #[test] + fn removes_listed_at_rules_wherever_they_are() { + let src = "@import \"a.css\";\n@media print {\n @import \"b.css\";\n .a { color: red; }\n}\n.b { &:hover { @source \"../c\"; } }\n@font-face { src: x; @import \"d.css\"; font-family: a; }\n.e { color: blue; }\n"; + let out = remove_listed(src, &["import", "source"]); + assert_eq!( + out.source, + "@media print {\n .a { color: red; }\n}\n.b { &:hover { } }\n@font-face { src: x; font-family: a; }\n.e { color: blue; }\n" + ); + assert!(out.changed); + // Matched on the text, so a second run finds nothing to remove. + assert!(!remove_listed(&out.source, &["import", "source"]).changed); + } + + #[test] + fn an_at_rule_inside_one_being_removed_goes_with_it() { + let src = "@plugin \"p\" { @import \"x\"; }\n.a { color: red; }\n"; + assert_eq!( + remove_listed(src, &["plugin", "import"]).source, + ".a { color: red; }\n" + ); + } + + #[test] + fn removes_every_copy_of_a_listed_text_and_nothing_else() { + let src = "@import \"x\";\n.a { @import \"x\"; }\n@import \"y\";\n"; + let texts = vec!["@import \"x\";".to_string()]; + assert_eq!( + remove_at_rules(src, &texts, ParseOptions::strict()) + .unwrap() + .source, + ".a { }\n@import \"y\";\n" + ); + } + + #[test] + fn removing_at_rules_from_unbalanced_braces_is_refused() { + let texts = vec!["@import \"x\";".to_string()]; + assert!(remove_at_rules(".a { @import \"x\";", &texts, ParseOptions::strict()).is_err()); + } + #[test] fn a_caller_supplied_needle_is_unquoted() { assert_eq!(normalize_target_needle("a.css"), "a.css"); diff --git a/test/at_rules_test.exs b/test/at_rules_test.exs index 0905a50..43959cc 100644 --- a/test/at_rules_test.exs +++ b/test/at_rules_test.exs @@ -554,4 +554,70 @@ defmodule IgniterCss.AtRulesTest do assert prefix == "d-" end end + + describe "list_at_rules/2 and remove_at_rules/3" do + # A build tool that reads files is told what to read by at-rules anywhere in + # the sheet, and a looser grammar than Biome's still acts on one the parser + # could not place: Tailwind imports the file named inside `@font-face`. + @nested """ + @import "https://fonts.example.test/a.css"; + @media print { + @import "../private.css"; + .a { color: red; } + } + .b { &:hover { @source "../notes"; } } + @font-face { src: x; @import "../font.css"; font-family: a; } + /* @import "../comment.css"; */ + .c { content: "@import 'string.css'"; background: url(@import.png); } + """ + + defp local?(%IgniterCss.AtRule{name: "import", target: "https://" <> _}), do: false + defp local?(%IgniterCss.AtRule{name: name}), do: name in ~w(import source) + + test "lists every at-rule, nested or unplaced, and none in a comment, a string or a url()" do + assert {:ok, rules} = IgniterCss.list_at_rules(@nested, allow_wrong_line_comments: false) + + assert Enum.map(rules, &{&1.name, &1.target}) == [ + {"import", "https://fonts.example.test/a.css"}, + {"media", nil}, + {"import", "../private.css"}, + {"source", "../notes"}, + {"font-face", nil}, + {"import", "../font.css"} + ] + end + + test "removes the ones a caller picked, wherever they are, and only those" do + opts = [allow_wrong_line_comments: false] + {:ok, rules} = IgniterCss.list_at_rules(@nested, opts) + + assert {:ok, out} = IgniterCss.remove_at_rules(@nested, Enum.filter(rules, &local?/1), opts) + assert out.changed + refute out.source =~ "private.css" + refute out.source =~ "../notes" + refute out.source =~ "font.css" + assert out.source =~ ~s|@import "https://fonts.example.test/a.css";| + assert out.source =~ "font-family: a;" + assert out.source =~ ~s|/* @import "../comment.css"; */| + assert out.source =~ "url(@import.png)" + + # Matched on the text, so the same list removes nothing the second time. + assert {:ok, %{changed: false}} = + IgniterCss.remove_at_rules(out.source, Enum.filter(rules, &local?/1), opts) + end + + test "names an escaped at-rule as written, and folds its case" do + assert {:ok, [escaped, upper]} = + IgniterCss.list_at_rules(~s|@\\69mport "a.css";\n@IMPORT "b.css";|) + + assert escaped.name == "\\69mport" + assert upper.name == "import" + end + + test "refuses to remove from braces that do not balance" do + css = ~s|.a { @import "x.css";| + {:ok, rules} = IgniterCss.list_at_rules(css) + assert {:error, _reason} = IgniterCss.remove_at_rules(css, rules) + end + end end From e1476a810bc1312cfa79f1a7b3c643084551ee61 Mon Sep 17 00:00:00 2001 From: Shahryar Tavakkoli Date: Sun, 1 Nov 2026 02:22:05 +0100 Subject: [PATCH 3/7] fix: validate_block/2 places an error that reaches the block's end on what the author wrote No error points into the block a body is read inside or names its `}`. A declaration with no `:`, which Biome reads as a nested rule (`color crimson;`), is one error on that text: "Expected a `:` after the property name `color`". Another statement the body ends in the middle of is one error on it ("Expected a `{` after the selector `&:hover`", "This declaration is not finished"), and a block left open is one error where its `}` is missing, naming the `{` it lacks. Messages igniter_css writes quote in backticks. Co-Authored-By: Claude Opus 5.5 --- lib/igniter_css.ex | 10 ++ native/igniter_css/src/analyze.rs | 204 ++++++++++++++++++++++++++++-- native/igniter_css/src/locate.rs | 157 ++++++++++++++++++++++- test/igniter_css_test.exs | 34 ++++- 4 files changed, 386 insertions(+), 19 deletions(-) diff --git a/lib/igniter_css.ex b/lib/igniter_css.ex index bd3375a..d726464 100644 --- a/lib/igniter_css.ex +++ b/lib/igniter_css.ex @@ -564,6 +564,11 @@ defmodule IgniterCss do written in is an error, though what follows it may parse: in a stylesheet, everything after it would be outside the block. + No error points past the body or names the block it is put in. A body that + ends in the middle of a statement has one error on that statement, and one + that leaves a block open has one where its `}` is missing. A declaration + with no `:`, which the parser reads as a nested rule, is named as one. + Returns `{:ok, %IgniterCss.Validation{}}` or `{:error, %IgniterCss.Validation{}}`. iex> {:ok, v} = IgniterCss.validate_block("padding: 4px;\\n&:hover { color: red; }") @@ -575,6 +580,11 @@ defmodule IgniterCss do iex> v.valid false + iex> {:error, v} = IgniterCss.validate_block("gap: 1px;\\ncolor crimson") + iex> [%IgniterCss.Diagnostic{line: 2, column: 1, text: "color crimson", message: message}] = v.errors + iex> message + "Expected a `:` after the property name `color`" + iex> {:error, v} = IgniterCss.validate_block("gap: 1px; } body { display: none; ") iex> [%IgniterCss.Diagnostic{line: 1, column: 11, text: "}"}] = v.errors iex> v.valid diff --git a/native/igniter_css/src/analyze.rs b/native/igniter_css/src/analyze.rs index 1ce38db..2a0c2b9 100644 --- a/native/igniter_css/src/analyze.rs +++ b/native/igniter_css/src/analyze.rs @@ -11,8 +11,8 @@ use crate::error::Result; use crate::locate::{ all_comments, at_rule_body, closing_brace, declaration_lists, declarations_in_block, find_all_at_rules, find_all_rules, find_at_rules_named, find_every_at_rule, - find_top_level_rules, in_free_form_value, is_stray_semicolon, misplaced_at_rules, AtRuleRef, - DeclRef, + find_top_level_rules, in_free_form_value, is_stray_semicolon, misplaced_at_rules, + misread_rules, opening_brace, statement_before, AtRuleRef, DeclRef, Statement, StatementKind, }; use crate::ops::at_rule::normalize_target_needle; use crate::ops::query; @@ -759,17 +759,47 @@ fn placed(text: &str, shift: usize, error: &ParseError) -> Diagnostic { }; let start = clamp(error.start); let end = clamp(error.end).max(start); - let line_start = text[..start].rfind('\n').map_or(0, |i| i + 1); + let (line, column) = line_and_column(text, start); Diagnostic { message: error.message.clone(), - line: text[..start].matches('\n').count() + 1, - column: text[line_start..start].chars().count() + 1, + line, + column, offset: start, text: text[start..end].to_string(), } } +/// 1-based line and column of byte `at` in `text`, the column in characters. +fn line_and_column(text: &str, at: usize) -> (usize, usize) { + let line_start = text[..at].rfind('\n').map_or(0, |i| i + 1); + ( + text[..at].matches('\n').count() + 1, + text[line_start..at].chars().count() + 1, + ) +} + +/// The one error for a statement left unfinished, saying what it lacks. +fn unfinished(source: &str, statement: &Statement) -> ParseError { + let message = match &statement.kind { + StatementKind::Rule { + property: Some(name), + } => format!("Expected a `:` after the property name `{name}`"), + StatementKind::Rule { property: None } => format!( + "Expected a `{{` after the selector `{}`", + &source[statement.start..statement.end] + ), + StatementKind::AtRule(name) => format!("This `@{name}` rule is not finished"), + StatementKind::Declaration => "This declaration is not finished".to_string(), + StatementKind::Other => "This statement is not finished".to_string(), + }; + ParseError { + message, + start: statement.start, + end: statement.end, + } +} + /// Is this CSS understood well enough to patch? /// /// "Valid" here means: the parser reproduced the input byte for byte **and** @@ -819,6 +849,14 @@ const BLOCK_CLOSE: &str = "\n}\n"; /// `body` that closes the block it was put in is an error: everything after it /// would be outside that block, at the top level of whatever stylesheet the /// body is written into, and still parse. +/// +/// No error points into or names the block the body is put in. A declaration +/// with no `:`, which Biome reads as a rule and raises selector errors +/// against, is one error on what the author wrote. The errors Biome raises +/// past the body's end come from the body ending in the middle of something: +/// a block it opens and leaves open is one error at its end, a statement it +/// leaves unfinished one error on that statement, and they go when an error +/// in the body already runs past its end or a `}` closes the block early. pub fn validate_block(body: &str, options: ParseOptions) -> Validation { if let Err(e) = crate::ctx::check_nesting(body) { return Validation::refused(e.to_string()); @@ -830,25 +868,53 @@ pub fn validate_block(body: &str, options: ParseOptions) -> Validation { }; let mut found = errors(&ctx); - let body_end = BLOCK_OPEN.len() + body.len(); + let body_start = BLOCK_OPEN.len(); + let body_end = body_start + body.len(); let closed_early = find_top_level_rules(&ctx) .first() .and_then(closing_brace) .filter(|&at| at < body_end); if let Some(at) = closed_early { found.push(ParseError { - message: "this `}` closes the block it is written in; everything after it is outside" + message: "This `}` closes the block it is written in; everything after it is outside" .to_string(), start: at, end: at + 1, }); - found.sort_by_key(|e| (e.start, e.end)); } - let errors = found - .iter() - .map(|e| placed(body, BLOCK_OPEN.len(), e)) - .collect(); + for (rule, reach) in misread_rules(&ctx, body_end) { + found.retain(|e| e.start < rule.start || e.start >= reach); + found.push(unfinished(&source, &rule)); + } + + if found.iter().any(|e| e.start >= body_end) { + let explained = + closed_early.is_some() || found.iter().any(|e| e.start < body_end && e.end > body_end); + if explained { + found.retain(|e| e.start < body_end); + } else if let Some(open) = + opening_brace(&ctx, body_end + 1).filter(|&open| open >= body_start) + { + let (line, column) = line_and_column(body, open - body_start); + found.retain(|e| e.start < body_end); + found.push(ParseError { + message: format!( + "Expected a `}}` to close the `{{` on line {line}, column {column}" + ), + start: body_end, + end: body_end, + }); + } else if let Some(statement) = + statement_before(&ctx, body_end).filter(|s| s.start >= body_start) + { + found.retain(|e| e.start < statement.start); + found.push(unfinished(&source, &statement)); + } + } + found.sort_by_key(|e| (e.start, e.end)); + + let errors = found.iter().map(|e| placed(body, body_start, e)).collect(); Validation::of(&ctx, errors) } @@ -1349,6 +1415,120 @@ mod tests { assert_eq!((last.line, last.column, last.text.as_str()), (1, 20, "")); } + fn only_error(body: &str) -> (usize, usize, String, String) { + let v = validate_block(body, opts()); + assert!(!v.valid, "{body:?}"); + assert_eq!(v.errors.len(), 1, "{body:?}: {:?}", v.errors); + let e = &v.errors[0]; + (e.line, e.column, e.text.clone(), e.message.clone()) + } + + fn row( + line: usize, + column: usize, + text: &str, + message: &str, + ) -> (usize, usize, String, String) { + (line, column, text.to_string(), message.to_string()) + } + + // Biome reads `color crimson` as a nested rule, the block's own `}` and + // everything after it up to a `{` included, and raises selector errors + // there and past the body's end. + #[test] + fn a_declaration_with_no_colon_is_one_error_on_what_was_written() { + let missing = "Expected a `:` after the property name `color`"; + for (body, at) in [ + ("color crimson", (1, 1)), + ("color crimson;", (1, 1)), + ("color crimson /* c */ ", (1, 1)), + ("gap: 1px;\ncolor crimson", (2, 1)), + ("gap: 1px;\ncolor crimson;\nmargin: 0;", (2, 1)), + ("gap: 1px;\r\n color crimson", (2, 3)), + ("color crimson; &:hover { gap: 1px }", (1, 1)), + ("&:hover { color crimson; }", (1, 11)), + ] { + assert_eq!( + only_error(body), + row(at.0, at.1, "color crimson", missing), + "{body:?}" + ); + } + assert_eq!( + only_error("width 10px !important"), + row( + 1, + 1, + "width 10px !important", + "Expected a `:` after the property name `width`" + ) + ); + } + + #[test] + fn an_unfinished_statement_is_one_error_on_what_was_written() { + for (body, expected) in [ + ( + "gap: 1px;\n&:hover", + row( + 2, + 1, + "&:hover", + "Expected a `{` after the selector `&:hover`", + ), + ), + ( + "div > span", + row( + 1, + 1, + "div > span", + "Expected a `{` after the selector `div > span`", + ), + ), + ( + "@media (min-width: 1px)", + row( + 1, + 1, + "@media (min-width: 1px)", + "This `@media` rule is not finished", + ), + ), + ( + "gap: 1px;\ncolor: var(--x", + row(2, 1, "color: var(--x", "This declaration is not finished"), + ), + ] { + assert_eq!(only_error(body), expected, "{body:?}"); + } + } + + #[test] + fn a_block_left_open_is_one_error_naming_its_brace() { + for (body, at, message) in [ + ( + "&:hover { gap: 1px;", + (1, 20), + "Expected a `}` to close the `{` on line 1, column 9", + ), + ( + "gap: 1px;\n&:hover {\n &:focus { gap: 1px; }", + (3, 24), + "Expected a `}` to close the `{` on line 2, column 9", + ), + ] { + assert_eq!(only_error(body), row(at.0, at.1, "", message), "{body:?}"); + } + } + + #[test] + fn an_error_running_past_the_end_explains_the_rest() { + let (_, _, _, message) = only_error("/* never closed\ngap: 1px;"); + assert_eq!(message, "Unterminated block comment"); + assert_eq!(only_error("background: url(x").2, "x"); + } + #[test] fn a_comment_or_string_left_open_is_invalid() { assert!(!validate_block("/* never closed\ngap: 1px;", opts()).valid); diff --git a/native/igniter_css/src/locate.rs b/native/igniter_css/src/locate.rs index 55b1def..b47a69a 100644 --- a/native/igniter_css/src/locate.rs +++ b/native/igniter_css/src/locate.rs @@ -14,7 +14,7 @@ use crate::ctx::{is_bogus, ParseCtx}; use biome_css_syntax::{CssSyntaxKind, CssSyntaxNode, CssSyntaxToken}; -use biome_rowan::{Direction, TextRange}; +use biome_rowan::{Direction, TextRange, TextSize}; // --------------------------------------------------------------------------- // References @@ -168,10 +168,13 @@ pub fn at_rule_body(at: &AtRuleRef) -> Option { } fn block_child(node: &CssSyntaxNode) -> Option { - node.children().find(|c| { - c.first_token() - .is_some_and(|t| t.kind() == CssSyntaxKind::L_CURLY) - }) + node.children().find(is_block) +} + +/// Does `node` open with `{`? +fn is_block(node: &CssSyntaxNode) -> bool { + node.first_token() + .is_some_and(|t| t.kind() == CssSyntaxKind::L_CURLY) } fn block_bounds(block: &CssSyntaxNode) -> Option<(usize, usize)> { @@ -1122,6 +1125,150 @@ pub fn misplaced_at_rules(ctx: &ParseCtx) -> Vec<(String, usize, usize)> { .collect() } +// --------------------------------------------------------------------------- +// Statements left unfinished +// --------------------------------------------------------------------------- + +/// What a statement in a block is, enough to say what it lacks. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum StatementKind { + Declaration, + /// A rule. `property` is the name its selector starts with when that reads + /// as a declaration with no `:`, which Biome parses as a rule. + Rule { + property: Option, + }, + /// An at-rule, with its name as written. + AtRule(String), + Other, +} + +/// A declaration, rule or at-rule written in a block, as far as the author +/// wrote it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Statement { + pub kind: StatementKind, + pub start: usize, + /// End of its last token before the limit it was read to. A rule ends + /// before the first `;` in its selector, where the author ended it. + pub end: usize, +} + +/// Is `node` an item of a block: something written between a `{` and its `}`? +fn is_statement(node: &CssSyntaxNode) -> bool { + node.parent() + .and_then(|list| list.parent()) + .is_some_and(|block| is_block(&block)) +} + +/// The name a rule's selector starts with, when nothing but a space or its end +/// follows: `color crimson`, `width 10px`. That is a declaration whose `:` is +/// missing; an `&`, `.a`, `[x]`, `:hover` or `>` against the name makes it a +/// selector. +fn property_name(rule: &CssSyntaxNode) -> Option { + let name = rule.first_token()?; + let type_selector = name.parent()?.parent()?; + let compound = type_selector.parent()?; + let bare = type_selector.kind() == CssSyntaxKind::CSS_TYPE_SELECTOR + && compound.text_trimmed_range() == type_selector.text_trimmed_range() + && compound + .next_sibling_or_token() + .is_none_or(|next| next.kind() == CssSyntaxKind::CSS_SPACE_LITERAL); + bare.then(|| name.text_trimmed().to_string()) +} + +/// `node`, a statement, read up to `limit`. +fn statement(node: &CssSyntaxNode, limit: usize) -> Statement { + let kind = match node.kind() { + CssSyntaxKind::CSS_NESTED_QUALIFIED_RULE | CssSyntaxKind::CSS_QUALIFIED_RULE => { + StatementKind::Rule { + property: property_name(node), + } + } + CssSyntaxKind::CSS_AT_RULE => match node.first_token().and_then(|at| at.next_token()) { + Some(name) if usize::from(name.text_trimmed_range().start()) < limit => { + StatementKind::AtRule(name.text_trimmed().to_string()) + } + _ => StatementKind::Other, + }, + kind if is_declaration_item(kind) => StatementKind::Declaration, + _ => StatementKind::Other, + }; + // A rule as written is its selector: Biome reads every token up to the + // next `{` into it, past any `;`. + let rule = matches!(kind, StatementKind::Rule { .. }); + let written = if rule { node.first_child() } else { None }; + let start = trimmed(node).0; + let end = written + .as_ref() + .unwrap_or(node) + .descendants_tokens(Direction::Next) + .take_while(|t| { + usize::from(t.text_trimmed_range().start()) < limit + && !(rule && t.kind() == CssSyntaxKind::SEMICOLON) + }) + .filter(|t| t.kind() != CssSyntaxKind::CSS_SPACE_LITERAL) + .last() + .map_or(start, |t| usize::from(t.text_trimmed_range().end())); + Statement { kind, start, end } +} + +/// Nested rules whose selector cannot be one: it holds a `;`, or no `{` +/// follows it. That is how Biome reads a declaration with no `:`, such as +/// `color crimson;`, together with everything after it up to the next `{`, or +/// to the end of the text when there is none. Each comes with the offset +/// where that reading stops, and is read as written up to `limit`. +pub fn misread_rules(ctx: &ParseCtx, limit: usize) -> Vec<(Statement, usize)> { + ctx.syntax() + .descendants() + .filter(|n| n.kind() == CssSyntaxKind::CSS_NESTED_QUALIFIED_RULE) + .filter_map(|rule| { + let reach = block_child(&rule).map(|block| trimmed(&block).0); + let semicolon = rule + .first_child()? + .descendants_tokens(Direction::Next) + .any(|t| t.kind() == CssSyntaxKind::SEMICOLON); + (semicolon || reach.is_none()) + .then(|| (statement(&rule, limit), reach.unwrap_or(usize::MAX))) + }) + .collect() +} + +/// Byte offset of the `{` whose block the `}` at `at` closes. `None` when no +/// `}` token starts there, or Biome read that one into a selector, a value or +/// an at-rule's prelude instead. +pub fn opening_brace(ctx: &ParseCtx, at: usize) -> Option { + let offset = TextSize::from(u32::try_from(at).ok()?); + if !ctx.syntax().text_range().contains(offset) { + return None; + } + let close = ctx.syntax().token_at_offset(offset).right_biased()?; + if close.kind() != CssSyntaxKind::R_CURLY + || usize::from(close.text_trimmed_range().start()) != at + { + return None; + } + let block = close.parent().filter(is_block)?; + block + .first_token() + .map(|open| usize::from(open.text_trimmed_range().start())) +} + +/// The innermost statement holding the last token that starts before +/// `limit`, read up to `limit`. +pub fn statement_before(ctx: &ParseCtx, limit: usize) -> Option { + let offset = TextSize::from(u32::try_from(limit.checked_sub(1)?).ok()?); + if !ctx.syntax().text_range().contains(offset) { + return None; + } + let mut last = ctx.syntax().token_at_offset(offset).left_biased()?; + while usize::from(last.text_trimmed_range().start()) >= limit { + last = last.prev_token()?; + } + let node = last.ancestors().find(is_statement)?; + Some(statement(&node, limit)) +} + #[cfg(test)] mod tests { use super::*; diff --git a/test/igniter_css_test.exs b/test/igniter_css_test.exs index 0b63ce2..89f5729 100644 --- a/test/igniter_css_test.exs +++ b/test/igniter_css_test.exs @@ -668,10 +668,40 @@ defmodule IgniterCssTest do end test "places an error in the body, not in the rule it is read inside" do - assert {:error, %{errors: [error | _rest]}} = + assert {:error, %{errors: [error]}} = IgniterCss.validate_block("gap: 1px;\ncolor crimson") - assert %IgniterCss.Diagnostic{line: 2, column: 14} = error + assert %IgniterCss.Diagnostic{line: 2, column: 1, offset: 10, text: "color crimson"} = + error + end + + test "names a declaration with no `:`, however it ends" do + for {body, line} <- [ + {"color crimson", 1}, + {"color crimson;", 1}, + {"gap: 1px;\ncolor crimson", 2}, + {"gap: 1px;\ncolor crimson;\nmargin: 0;", 2} + ] do + assert {:error, %{errors: [error]}} = IgniterCss.validate_block(body), body + + assert %IgniterCss.Diagnostic{ + line: ^line, + column: 1, + text: "color crimson", + message: "Expected a `:` after the property name `color`" + } = error + end + end + + test "places a block left open where its } is missing" do + assert {:error, %{errors: [error]}} = IgniterCss.validate_block("&:hover { gap: 1px;") + + assert %IgniterCss.Diagnostic{ + line: 1, + column: 20, + text: "", + message: "Expected a `}` to close the `{` on line 1, column 9" + } = error end test "refuses a } that closes the block early, even when the rest parses" do From 734e380f41fd17333d3900a1d3411ac639483030 Mon Sep 17 00:00:00 2001 From: Shahryar Tavakkoli Date: Sun, 1 Nov 2026 02:32:11 +0100 Subject: [PATCH 4/7] fix: validate/2 and validate_block/2 accept an at-rule with no `;` written last in a block CSS Syntax ends an at-rule with no block at the `}` of the block it is in, and Tailwind takes `.a { @apply p-4 }`. Biome 0.5.8 reads that `}`, and what follows up to a `;` or `{`, into the at-rule's prelude. That `}` is found in the CST, the text is parsed again with a `;` before it, one at a time in source order, and errors are placed back in the text as given. Only for a prelude on one line, with its brackets closed and no `:` followed by a space: `@apply p-4` then `color: red`, or `@apply p-4 gap: 1px`, is another statement with its `;` missing and stays an error. Co-Authored-By: Claude Opus 5.5 --- lib/igniter_css/structs.ex | 3 +- native/igniter_css/src/analyze.rs | 221 +++++++++++++++++++++++++----- native/igniter_css/src/locate.rs | 43 ++++++ test/igniter_css_test.exs | 15 ++ 4 files changed, 249 insertions(+), 33 deletions(-) diff --git a/lib/igniter_css/structs.ex b/lib/igniter_css/structs.ex index 12bd1ce..6e33935 100644 --- a/lib/igniter_css/structs.ex +++ b/lib/igniter_css/structs.ex @@ -114,7 +114,8 @@ defmodule IgniterCss.Validation do `errors` is the verdict, each placed by line and column: the parser's errors less the ones it raises against valid CSS, such as a `:` in a custom - property's value. `diagnostics` counts what the parser raised before that. + property's value or an `@apply` with no `;` written last in a block. + `diagnostics` counts what the parser raised before that. """ @type t :: %__MODULE__{ diff --git a/native/igniter_css/src/analyze.rs b/native/igniter_css/src/analyze.rs index 2a0c2b9..d99313d 100644 --- a/native/igniter_css/src/analyze.rs +++ b/native/igniter_css/src/analyze.rs @@ -9,10 +9,11 @@ use crate::ctx::{ParseCtx, ParseError, ParseOptions}; use crate::error::Result; use crate::locate::{ - all_comments, at_rule_body, closing_brace, declaration_lists, declarations_in_block, - find_all_at_rules, find_all_rules, find_at_rules_named, find_every_at_rule, - find_top_level_rules, in_free_form_value, is_stray_semicolon, misplaced_at_rules, - misread_rules, opening_brace, statement_before, AtRuleRef, DeclRef, Statement, StatementKind, + all_comments, at_rule_body, at_rule_ended_by_its_block, closing_brace, declaration_lists, + declarations_in_block, find_all_at_rules, find_all_rules, find_at_rules_named, + find_every_at_rule, find_top_level_rules, in_free_form_value, is_stray_semicolon, + misplaced_at_rules, misread_rules, opening_brace, statement_before, AtRuleRef, DeclRef, + Statement, StatementKind, }; use crate::ops::at_rule::normalize_target_needle; use crate::ops::query; @@ -696,8 +697,8 @@ impl Validation { } } - fn of(ctx: &ParseCtx, errors: Vec) -> Self { - let round_trips = ctx.round_trips(); + fn of(reading: &Reading, errors: Vec) -> Self { + let round_trips = reading.round_trips; let message = if !round_trips { "the parser did not reproduce the input byte for byte; refusing to patch this file" .to_string() @@ -715,7 +716,7 @@ impl Validation { }; Validation { valid: round_trips && errors.is_empty(), - diagnostics: ctx.diagnostics_count(), + diagnostics: reading.diagnostics, round_trips, message, errors, @@ -723,6 +724,79 @@ impl Validation { } } +/// A stylesheet parsed as CSS Syntax reads an at-rule written last in a block +/// with no block of its own and no `;`, `.a { @apply p-4 }`: ended by the `}` +/// that closes the block. Biome 0.5.8 reads that `}`, and what follows up to a +/// `;` or a `{`, into the at-rule's prelude (see `at_rule_ended_by_its_block`), +/// so the text is parsed again with a `;` before the `}`, which CSS Syntax +/// reads the same way. One at a time, in source order: until then, a parse +/// misreads everything after the first one. +struct Reading { + /// The parse errors are read from. + ctx: ParseCtx, + /// Where each `;` was put, as offsets in `ctx`'s text, ascending. + inserted: Vec, + /// Whether the text as given round-trips, and how many diagnostics the + /// parser raised on it. + round_trips: bool, + diagnostics: usize, +} + +impl Reading { + fn new(source: &str, options: ParseOptions) -> Result { + let mut ctx = ParseCtx::try_new(source, options)?; + let (round_trips, diagnostics) = (ctx.round_trips(), ctx.diagnostics_count()); + let bom = if ctx.has_bom() { crate::ctx::BOM } else { "" }; + let mut inserted: Vec = Vec::new(); + // Each `}` gets one `;` at most, so this ends. + while let Some(at) = + at_rule_ended_by_its_block(&ctx).filter(|&at| !inserted.iter().any(|&q| q + 1 == at)) + { + let text = format!("{bom}{};{}", &ctx.source()[..at], &ctx.source()[at..]); + let Ok(next) = ParseCtx::try_new(&text, options) else { + break; + }; + for q in inserted.iter_mut().filter(|q| **q >= at) { + *q += 1; + } + inserted.push(at); + inserted.sort_unstable(); + ctx = next; + } + Ok(Reading { + ctx, + inserted, + round_trips, + diagnostics, + }) + } + + /// Offset in the given text of `at` in the parsed one. + fn given(&self, at: usize) -> usize { + at - self.inserted.iter().filter(|&&q| q < at).count() + } + + /// Offset in the parsed text of the byte at `at` in the given one. + fn parsed(&self, at: usize) -> usize { + // The `k`th `;`, counting from 0, went before byte `q - k` of the given text. + at + self + .inserted + .iter() + .enumerate() + .filter(|&(k, &q)| q - k <= at) + .count() + } + + /// `error`, read from the parsed text, placed in the given one. + fn given_error(&self, error: &ParseError) -> ParseError { + ParseError { + message: error.message.clone(), + start: self.given(error.start), + end: self.given(error.end), + } + } +} + /// What is wrong with a parse, in source order: the parser's own errors less /// the ones it raises against valid CSS, and the at-rules written inside a /// block that are valid only at the top level of a stylesheet. @@ -807,32 +881,30 @@ fn unfinished(source: &str, statement: &Statement) -> ParseError { /// safety -- it is what every codemod checks before touching a file. /// /// The errors are the parser's, less the ones Biome 0.5.8 raises against valid -/// CSS (see `in_free_form_value` and `is_stray_semicolon`), plus an `@import`, -/// `@charset` or `@namespace` written inside a block, which it does not raise. +/// CSS (see `in_free_form_value`, `is_stray_semicolon` and `Reading`), plus an +/// `@import`, `@charset` or `@namespace` written inside a block, which it does +/// not raise. pub fn validate(source: &str, options: ParseOptions) -> Validation { if let Err(e) = crate::ctx::check_nesting(source) { return Validation::refused(e.to_string()); } - let ctx = match ParseCtx::try_new(source, options) { - Ok(c) => c, + let reading = match Reading::new(source, options) { + Ok(r) => r, Err(e) => return Validation::refused(e.to_string()), }; // Offsets are into the source without its byte-order mark, which no editor // shows as a column. - let bom = if ctx.has_bom() { - crate::ctx::BOM.len() - } else { - 0 - }; - let errors = errors(&ctx) + let given = source.strip_prefix(crate::ctx::BOM).unwrap_or(source); + let bom = source.len() - given.len(); + let errors = errors(&reading.ctx) .iter() .map(|e| { - let mut d = placed(ctx.source(), 0, e); + let mut d = placed(given, 0, &reading.given_error(e)); d.offset += bom; d }) .collect(); - Validation::of(&ctx, errors) + Validation::of(&reading, errors) } /// The rule a block is read inside, its body on lines of its own: a body that @@ -862,15 +934,19 @@ pub fn validate_block(body: &str, options: ParseOptions) -> Validation { return Validation::refused(e.to_string()); } let source = format!("{BLOCK_OPEN}{body}{BLOCK_CLOSE}"); - let ctx = match ParseCtx::try_new(&source, options) { - Ok(c) => c, + let reading = match Reading::new(&source, options) { + Ok(r) => r, Err(e) => return Validation::refused(e.to_string()), }; + // Offsets below are in the parsed text, which may hold a `;` the body + // does not; errors are placed in the body once read back. + let ctx = &reading.ctx; - let mut found = errors(&ctx); + let mut found = errors(ctx); let body_start = BLOCK_OPEN.len(); - let body_end = body_start + body.len(); - let closed_early = find_top_level_rules(&ctx) + let body_end = reading.parsed(body_start + body.len()); + let block_close = reading.parsed(body_start + body.len() + 1); + let closed_early = find_top_level_rules(ctx) .first() .and_then(closing_brace) .filter(|&at| at < body_end); @@ -883,9 +959,9 @@ pub fn validate_block(body: &str, options: ParseOptions) -> Validation { }); } - for (rule, reach) in misread_rules(&ctx, body_end) { + for (rule, reach) in misread_rules(ctx, body_end) { found.retain(|e| e.start < rule.start || e.start >= reach); - found.push(unfinished(&source, &rule)); + found.push(unfinished(ctx.source(), &rule)); } if found.iter().any(|e| e.start >= body_end) { @@ -894,9 +970,9 @@ pub fn validate_block(body: &str, options: ParseOptions) -> Validation { if explained { found.retain(|e| e.start < body_end); } else if let Some(open) = - opening_brace(&ctx, body_end + 1).filter(|&open| open >= body_start) + opening_brace(ctx, block_close).filter(|&open| open >= body_start) { - let (line, column) = line_and_column(body, open - body_start); + let (line, column) = line_and_column(body, reading.given(open) - body_start); found.retain(|e| e.start < body_end); found.push(ParseError { message: format!( @@ -906,16 +982,19 @@ pub fn validate_block(body: &str, options: ParseOptions) -> Validation { end: body_end, }); } else if let Some(statement) = - statement_before(&ctx, body_end).filter(|s| s.start >= body_start) + statement_before(ctx, body_end).filter(|s| s.start >= body_start) { found.retain(|e| e.start < statement.start); - found.push(unfinished(&source, &statement)); + found.push(unfinished(ctx.source(), &statement)); } } found.sort_by_key(|e| (e.start, e.end)); - let errors = found.iter().map(|e| placed(body, body_start, e)).collect(); - Validation::of(&ctx, errors) + let errors = found + .iter() + .map(|e| placed(body, body_start, &reading.given_error(e))) + .collect(); + Validation::of(&reading, errors) } #[cfg(test)] @@ -1529,6 +1608,84 @@ mod tests { assert_eq!(only_error("background: url(x").2, "x"); } + // CSS Syntax ends an at-rule with no block at the `}` of the block it is + // written in; Biome 0.5.8 reads that `}`, and what follows, into its prelude. + #[test] + fn an_at_rule_last_in_a_block_needs_no_semicolon() { + for src in [ + ".a { @apply p-4 }", + ".a { @apply hover:bg-red-500 md:p-4 /* c */ }", + ".a { @apply p-4 }\n.b { color: red; }", + ".a { @apply p-4 } .b { &:hover { @apply p-2 } }", + "@media print { .a { @apply p-4 } }", + ] { + let v = validate(src, opts()); + assert!(v.valid, "{src}: {:?}", v.errors); + assert!( + v.diagnostics > 0, + "{src} no longer trips the parser; drop `Reading`" + ); + } + for body in [ + "@apply p-4", + "padding: 4px;\n@apply p-4", + "&:hover { @apply p-4 }", + ] { + let v = validate_block(body, opts()); + assert!(v.valid, "{body:?}: {:?}", v.errors); + } + } + + #[test] + fn an_error_after_an_at_rule_ended_by_its_block_keeps_its_place() { + let v = validate( + "\u{feff}.a { @apply p-4 }\n.b { color: red background: blue; }", + opts(), + ); + assert_eq!(v.errors.len(), 1, "{:?}", v.errors); + let e = &v.errors[0]; + assert_eq!( + (e.line, e.column, e.offset, e.text.as_str()), + (2, 27, 47, ": blue") + ); + + let (line, column, text, _) = + only_error("&:hover { @apply p-4 }\ncolor: red background: blue;"); + assert_eq!((line, column, text.as_str()), (2, 22, ": blue")); + assert_eq!( + only_error("&:hover { gap: 1px; @apply p-4"), + row( + 1, + 31, + "", + "Expected a `}` to close the `{` on line 1, column 9" + ) + ); + } + + #[test] + fn an_at_rule_running_into_another_statement_is_still_an_error() { + for body in [ + "@apply p-4\ncolor: red", + "@apply p-4 gap: 1px", + "@apply\np-4", + ] { + assert_eq!( + only_error(body).3, + "This `@apply` rule is not finished", + "{body:?}" + ); + } + for src in [ + ".a { @apply p-4\n color: red }", + ".a { @apply }", + ".a { @apply foo(a }", + ".a { @media print }", + ] { + assert!(!validate(src, opts()).valid, "{src}"); + } + } + #[test] fn a_comment_or_string_left_open_is_invalid() { assert!(!validate_block("/* never closed\ngap: 1px;", opts()).valid); diff --git a/native/igniter_css/src/locate.rs b/native/igniter_css/src/locate.rs index b47a69a..498fb57 100644 --- a/native/igniter_css/src/locate.rs +++ b/native/igniter_css/src/locate.rs @@ -1095,6 +1095,49 @@ pub fn is_stray_semicolon(ctx: &ParseCtx, start: usize, end: usize) -> bool { .all(|t| t.kind() == CssSyntaxKind::SEMICOLON) } +/// Byte offset of the first `}` Biome read into an at-rule's prelude where CSS +/// Syntax ends the at-rule with it: one written last in a block, with no block +/// of its own and no `;`, such as `.a { @apply p-4 }`. That `}` closes the +/// block the at-rule is in; Biome 0.5.8 reads on to the next `;` or `{`, and +/// misreads everything up to there. +/// +/// Only for a prelude on one line with its brackets closed and no `:` with a +/// space after it. One that runs onto a new line before the `}`, `@apply p-4` +/// then `color: red`, or holds a `:` the way a declaration does, `@apply p-4 +/// gap: 1px`, holds what reads as another statement with its `;` missing, and +/// stays an error. A class name such as `md:p-4` has no space after its `:`. +pub fn at_rule_ended_by_its_block(ctx: &ParseCtx) -> Option { + let prelude = ctx + .syntax() + .descendants() + .filter(|n| n.kind() == CssSyntaxKind::CSS_UNKNOWN_AT_RULE_COMPONENT_LIST) + .find(|n| { + n.children_with_tokens() + .any(|e| e.kind() == CssSyntaxKind::R_CURLY) + })?; + prelude + .parent()? + .parent() + .filter(|n| n.kind() == CssSyntaxKind::CSS_AT_RULE && is_statement(n))?; + let tokens: Vec<_> = prelude.descendants_tokens(Direction::Next).collect(); + let close = tokens + .iter() + .position(|t| t.kind() == CssSyntaxKind::R_CURLY)?; + let before = &tokens[..close]; + let one_line = !before.is_empty() && !before.iter().any(|t| t.has_leading_newline()); + let declaration = before.iter().any(|t| { + t.kind() == CssSyntaxKind::COLON + && t.trailing_trivia() + .pieces() + .any(|piece| piece.is_whitespace()) + }); + (one_line + && !declaration + && brackets_close(before) + && tokens[close].parent().as_ref() == Some(&prelude)) + .then(|| usize::from(tokens[close].text_trimmed_range().start())) +} + /// At-rules that are valid only at the top level of a stylesheet, written /// inside a block instead, as `(name, start, end)`. /// diff --git a/test/igniter_css_test.exs b/test/igniter_css_test.exs index 89f5729..d9c44f4 100644 --- a/test/igniter_css_test.exs +++ b/test/igniter_css_test.exs @@ -693,6 +693,21 @@ defmodule IgniterCssTest do end end + test "accepts an at-rule with no `;` written last in a block" do + for body <- ["@apply p-4", "padding: 4px;\n@apply p-4", "&:hover { @apply p-4 }"] do + assert {:ok, %{valid: true, errors: []}} = IgniterCss.validate_block(body), body + end + + assert {:ok, %{valid: true}} = IgniterCss.validate(".a { @apply p-4 }\n.b { color: red; }") + end + + test "still refuses an @apply that runs into another statement without a `;`" do + assert {:error, %{errors: [%{line: 1, column: 1, text: "@apply p-4\ncolor: red"}]}} = + IgniterCss.validate_block("@apply p-4\ncolor: red") + + assert {:error, _} = IgniterCss.validate_block("@apply p-4 gap: 1px") + end + test "places a block left open where its } is missing" do assert {:error, %{errors: [error]}} = IgniterCss.validate_block("&:hover { gap: 1px;") From 9b5733068673cdc1ef0c3d605bbb72852958edc9 Mon Sep 17 00:00:00 2001 From: Shahryar Tavakkoli Date: Sun, 1 Nov 2026 04:51:00 +0100 Subject: [PATCH 5/7] fix: validate_block/2 keeps a string's missing closing quote, and its messages quote the author's text on one line MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A string with no closing quote in a selector, `&[data-x="a` then `b"] { … }`, is Biome's "Missing closing quote" at that quote again. The lexer ends the string at the line's end and Biome reads the rest, the block included, as one rule with no `{`; that rule is no longer reported as "Expected a `{` after the selector …". A token the lexer could not read keeps its own error in a rule read as a declaration with no `:` and in a statement the body ends in; one after a misread rule's `;` keeps its error next to that one. A message igniter_css writes quotes the author's text with a line break in it as `\n` (or `\r`), as `text` reads when inspected, and the validation summary does the same with the first error's message. Co-Authored-By: Claude Opus 5.5 --- lib/igniter_css.ex | 5 +- native/igniter_css/src/analyze.rs | 93 +++++++++++++++++++++++++++++-- native/igniter_css/src/locate.rs | 34 +++++++++-- test/igniter_css_test.exs | 24 ++++++++ 4 files changed, 147 insertions(+), 9 deletions(-) diff --git a/lib/igniter_css.ex b/lib/igniter_css.ex index d726464..f270ba5 100644 --- a/lib/igniter_css.ex +++ b/lib/igniter_css.ex @@ -567,7 +567,10 @@ defmodule IgniterCss do No error points past the body or names the block it is put in. A body that ends in the middle of a statement has one error on that statement, and one that leaves a block open has one where its `}` is missing. A declaration - with no `:`, which the parser reads as a nested rule, is named as one. + with no `:`, which the parser reads as a nested rule, is named as one. A + string with no closing quote keeps the parser's own error, whatever it + misreads after it. A message quotes the author's text on one line, a line + break in it written `\\n`. Returns `{:ok, %IgniterCss.Validation{}}` or `{:error, %IgniterCss.Validation{}}`. diff --git a/native/igniter_css/src/analyze.rs b/native/igniter_css/src/analyze.rs index d99313d..8c0c274 100644 --- a/native/igniter_css/src/analyze.rs +++ b/native/igniter_css/src/analyze.rs @@ -710,7 +710,7 @@ impl Validation { errors.len(), first.line, first.column, - first.message + one_line(&first.message) ), } }; @@ -853,6 +853,12 @@ fn line_and_column(text: &str, at: usize) -> (usize, usize) { ) } +/// `message` on one line: a line break in the author's text it quotes reads +/// `\r` or `\n`, as it does in an inspected string. +fn one_line(message: &str) -> String { + message.replace('\r', "\\r").replace('\n', "\\n") +} + /// The one error for a statement left unfinished, saying what it lacks. fn unfinished(source: &str, statement: &Statement) -> ParseError { let message = match &statement.kind { @@ -868,7 +874,7 @@ fn unfinished(source: &str, statement: &Statement) -> ParseError { StatementKind::Other => "This statement is not finished".to_string(), }; ParseError { - message, + message: one_line(&message), start: statement.start, end: statement.end, } @@ -929,6 +935,9 @@ const BLOCK_CLOSE: &str = "\n}\n"; /// a block it opens and leaves open is one error at its end, a statement it /// leaves unfinished one error on that statement, and they go when an error /// in the body already runs past its end or a `}` closes the block early. +/// A token the lexer could not read, such as a string with no closing quote, +/// keeps its own error: what Biome misreads after it is not put down to a +/// missing `:`, `{` or end. A message quotes the author's text on one line. pub fn validate_block(body: &str, options: ParseOptions) -> Validation { if let Err(e) = crate::ctx::check_nesting(body) { return Validation::refused(e.to_string()); @@ -984,8 +993,17 @@ pub fn validate_block(body: &str, options: ParseOptions) -> Validation { } else if let Some(statement) = statement_before(ctx, body_end).filter(|s| s.start >= body_start) { - found.retain(|e| e.start < statement.start); - found.push(unfinished(ctx.source(), &statement)); + // A token in it the lexer could not read explains the rest, while + // its own error is still there to say so. + let unread = statement + .unread + .is_some_and(|at| found.iter().any(|e| e.start >= at && e.start < body_end)); + if unread { + found.retain(|e| e.start < body_end); + } else { + found.retain(|e| e.start < statement.start); + found.push(unfinished(ctx.source(), &statement)); + } } } found.sort_by_key(|e| (e.start, e.end)); @@ -1608,6 +1626,73 @@ mod tests { assert_eq!(only_error("background: url(x").2, "x"); } + // The lexer ends a string with no closing quote at the line's end; Biome + // then reads the rest of the selector, its block included, as one rule + // with no `{`. + #[test] + fn a_string_left_open_keeps_its_own_error() { + let quote = "Missing closing quote"; + for (body, at, text) in [ + ("&[data-x=\"a\nb\"] { gap: 1px; }", (1, 10), "\"a"), + ("&[data-x='a\nb'] { gap: 1px; }", (1, 10), "'a"), + ("&[x=\"a\nb\"] {\n gap: 1px;\n}", (1, 5), "\"a"), + ("@media (x: \"a", (1, 12), "\"a"), + ("--x: [\"abc", (1, 7), "\"abc"), + ] { + let v = validate_block(body, opts()); + assert!(!v.valid, "{body:?}"); + let e = &v.errors[0]; + assert_eq!( + (e.line, e.column, e.text.as_str(), e.message.as_str()), + (at.0, at.1, text, quote), + "{body:?}: {:?}", + v.errors + ); + assert!( + v.errors.iter().all(|e| e.message == quote), + "{body:?}: {:?}", + v.errors + ); + } + + let v = validate_block("color crimson;\n&[data-x=\"a\nb\"] { gap: 1px; }", opts()); + let found: Vec<_> = v + .errors + .iter() + .map(|e| (e.line, e.column, e.message.as_str())) + .collect(); + assert_eq!( + found, + [ + (1, 1, "Expected a `:` after the property name `color`"), + (2, 10, quote), + (3, 2, quote) + ] + ); + } + + #[test] + fn a_message_quotes_the_authors_text_on_one_line() { + assert_eq!( + only_error("&:hover\n.b"), + row( + 1, + 1, + "&:hover\n.b", + "Expected a `{` after the selector `&:hover\\n.b`" + ) + ); + assert_eq!( + only_error("gap: 1px;\r\n&:hover\r\n.b").3, + "Expected a `{` after the selector `&:hover\\r\\n.b`" + ); + + // Biome quotes what it found, a string's escaped line break included. + let v = validate_block("\"a\\\nb\" { gap: 1px; }", opts()); + assert!(v.errors[0].message.contains('\n'), "{:?}", v.errors); + assert!(!v.message.contains('\n'), "{}", v.message); + } + // CSS Syntax ends an at-rule with no block at the `}` of the block it is // written in; Biome 0.5.8 reads that `}`, and what follows, into its prelude. #[test] diff --git a/native/igniter_css/src/locate.rs b/native/igniter_css/src/locate.rs index 498fb57..56c37f6 100644 --- a/native/igniter_css/src/locate.rs +++ b/native/igniter_css/src/locate.rs @@ -1195,6 +1195,9 @@ pub struct Statement { /// End of its last token before the limit it was read to. A rule ends /// before the first `;` in its selector, where the author ended it. pub end: usize, + /// Start of the first token in it before the limit that the lexer could + /// not read, such as a string with no closing quote. + pub unread: Option, } /// Is `node` an item of a block: something written between a `{` and its `}`? @@ -1253,7 +1256,17 @@ fn statement(node: &CssSyntaxNode, limit: usize) -> Statement { .filter(|t| t.kind() != CssSyntaxKind::CSS_SPACE_LITERAL) .last() .map_or(start, |t| usize::from(t.text_trimmed_range().end())); - Statement { kind, start, end } + let unread = node + .descendants_tokens(Direction::Next) + .take_while(|t| usize::from(t.text_trimmed_range().start()) < limit) + .find(|t| t.kind() == CssSyntaxKind::ERROR_TOKEN) + .map(|t| usize::from(t.text_trimmed_range().start())); + Statement { + kind, + start, + end, + unread, + } } /// Nested rules whose selector cannot be one: it holds a `;`, or no `{` @@ -1261,18 +1274,31 @@ fn statement(node: &CssSyntaxNode, limit: usize) -> Statement { /// `color crimson;`, together with everything after it up to the next `{`, or /// to the end of the text when there is none. Each comes with the offset /// where that reading stops, and is read as written up to `limit`. +/// +/// A token the lexer could not read, such as a string with no closing quote, +/// is what Biome misread the rest from: a rule with one in what the author +/// wrote is not listed, and one after its `;` stops the reading there. pub fn misread_rules(ctx: &ParseCtx, limit: usize) -> Vec<(Statement, usize)> { ctx.syntax() .descendants() .filter(|n| n.kind() == CssSyntaxKind::CSS_NESTED_QUALIFIED_RULE) .filter_map(|rule| { - let reach = block_child(&rule).map(|block| trimmed(&block).0); + let block = block_child(&rule).map(|block| trimmed(&block).0); let semicolon = rule .first_child()? .descendants_tokens(Direction::Next) .any(|t| t.kind() == CssSyntaxKind::SEMICOLON); - (semicolon || reach.is_none()) - .then(|| (statement(&rule, limit), reach.unwrap_or(usize::MAX))) + if !semicolon && block.is_some() { + return None; + } + let read = statement(&rule, limit); + if read.unread.is_some_and(|at| at < read.end) { + return None; + } + let reach = block + .unwrap_or(usize::MAX) + .min(read.unread.unwrap_or(usize::MAX)); + Some((read, reach)) }) .collect() } diff --git a/test/igniter_css_test.exs b/test/igniter_css_test.exs index d9c44f4..362f799 100644 --- a/test/igniter_css_test.exs +++ b/test/igniter_css_test.exs @@ -708,6 +708,30 @@ defmodule IgniterCssTest do assert {:error, _} = IgniterCss.validate_block("@apply p-4 gap: 1px") end + test "keeps a string's missing closing quote over what the parser misreads after it" do + assert {:error, %{errors: [error | _]}} = + IgniterCss.validate_block(~s|&[data-x="a\nb"] { gap: 1px; }|) + + assert %IgniterCss.Diagnostic{ + line: 1, + column: 10, + text: ~s|"a|, + message: "Missing closing quote" + } = error + end + + test "quotes the author's text in its own messages on one line" do + assert {:error, %{errors: [error], message: message}} = + IgniterCss.validate_block("&:hover\n.b") + + assert %IgniterCss.Diagnostic{ + text: "&:hover\n.b", + message: "Expected a `{` after the selector `&:hover\\n.b`" + } = error + + refute message =~ "\n" + end + test "places a block left open where its } is missing" do assert {:error, %{errors: [error]}} = IgniterCss.validate_block("&:hover { gap: 1px;") From 590057bed7c321ac57534c79319118029a948660 Mon Sep 17 00:00:00 2001 From: Shahryar Tavakkoli Date: Sun, 1 Nov 2026 05:27:40 +0100 Subject: [PATCH 6/7] fix: validate/2 and validate_block/2 refuse a string left open in a custom property, and a misread rule's text ends at its block's `}` A custom property's value still takes any run of tokens, a `:` included, but not a string the lexer could not end: `--x: "abc` is Biome's "Missing closing quote" on `"abc`, as CSS Syntax reads it as a bad string. The string is found as an error token in the CST that opens with a quote and spans the error. A declaration with no `:` written last in a block, `&:hover { color navy }`, is named on `color navy`: the `}` Biome reads into its selector closes the block it is in and is no longer part of the error's text. Co-Authored-By: Claude Opus 5.5 --- native/igniter_css/src/analyze.rs | 24 ++++++++++++++++++++++++ native/igniter_css/src/locate.rs | 31 +++++++++++++++++++++++++++++-- test/igniter_css_test.exs | 19 +++++++++++++++++++ 3 files changed, 72 insertions(+), 2 deletions(-) diff --git a/native/igniter_css/src/analyze.rs b/native/igniter_css/src/analyze.rs index 8c0c274..9e6d8b3 100644 --- a/native/igniter_css/src/analyze.rs +++ b/native/igniter_css/src/analyze.rs @@ -1544,6 +1544,8 @@ mod tests { ("gap: 1px;\r\n color crimson", (2, 3)), ("color crimson; &:hover { gap: 1px }", (1, 1)), ("&:hover { color crimson; }", (1, 11)), + ("&:hover { color crimson }", (1, 11)), + ("@media print { color crimson }", (1, 16)), ] { assert_eq!( only_error(body), @@ -1671,6 +1673,28 @@ mod tests { ); } + // A custom property takes any run of tokens, a `:` included, but a string + // its line leaves open is a bad string to CSS Syntax, which none takes. + #[test] + fn a_string_left_open_in_a_custom_property_is_refused() { + let quote = "Missing closing quote"; + assert_eq!(only_error("--x: \"abc"), row(1, 6, "\"abc", quote)); + assert_eq!( + only_error("--x: a:b;\n--y: 'abc;\ngap: 1px;"), + row(2, 6, "'abc;", quote) + ); + + let v = validate(".a { --x: \"abc\n}", opts()); + assert_eq!(v.errors.len(), 1, "{:?}", v.errors); + let e = &v.errors[0]; + assert_eq!( + (e.line, e.column, e.text.as_str(), e.message.as_str()), + (1, 11, "\"abc", quote) + ); + + assert!(validate_block("--x: a:b; --y: \"a:b\";", opts()).valid); + } + #[test] fn a_message_quotes_the_authors_text_on_one_line() { assert_eq!( diff --git a/native/igniter_css/src/locate.rs b/native/igniter_css/src/locate.rs index 56c37f6..7c3c82e 100644 --- a/native/igniter_css/src/locate.rs +++ b/native/igniter_css/src/locate.rs @@ -997,6 +997,27 @@ fn covering_node(ctx: &ParseCtx, start: usize, end: usize) -> Option bool { + let (Ok(start), Ok(end)) = (u32::try_from(start), u32::try_from(end)) else { + return false; + }; + let range = TextRange::new(start.into(), end.into()); + if !ctx.syntax().text_range().contains_range(range) { + return false; + } + match ctx.syntax().covering_element(range) { + biome_rowan::SyntaxElement::Token(token) => { + token.kind() == CssSyntaxKind::ERROR_TOKEN + && token.text_trimmed_range() == range + && token.text_trimmed().starts_with(['"', '\'']) + } + biome_rowan::SyntaxElement::Node(_) => false, + } +} + /// Is `start..end` inside a declaration value whose grammar is any run of /// tokens, where Biome 0.5.8 raises an error the specification does not? /// @@ -1011,7 +1032,12 @@ fn covering_node(ctx: &ParseCtx, start: usize, end: usize) -> Option bool { + if is_open_string(ctx, start, end) { + return false; + } let Some(node) = covering_node(ctx, start, end) else { return false; }; @@ -1193,7 +1219,8 @@ pub struct Statement { pub kind: StatementKind, pub start: usize, /// End of its last token before the limit it was read to. A rule ends - /// before the first `;` in its selector, where the author ended it. + /// before the first `;` or `}` in its selector, where the author ended it + /// or the block it is in ends. pub end: usize, /// Start of the first token in it before the limit that the lexer could /// not read, such as a string with no closing quote. @@ -1251,7 +1278,7 @@ fn statement(node: &CssSyntaxNode, limit: usize) -> Statement { .descendants_tokens(Direction::Next) .take_while(|t| { usize::from(t.text_trimmed_range().start()) < limit - && !(rule && t.kind() == CssSyntaxKind::SEMICOLON) + && !(rule && matches!(t.kind(), CssSyntaxKind::SEMICOLON | CssSyntaxKind::R_CURLY)) }) .filter(|t| t.kind() != CssSyntaxKind::CSS_SPACE_LITERAL) .last() diff --git a/test/igniter_css_test.exs b/test/igniter_css_test.exs index 362f799..61e31ed 100644 --- a/test/igniter_css_test.exs +++ b/test/igniter_css_test.exs @@ -691,6 +691,25 @@ defmodule IgniterCssTest do message: "Expected a `:` after the property name `color`" } = error end + + assert {:error, %{errors: [%{line: 1, column: 11, text: "color crimson"}]}} = + IgniterCss.validate_block("&:hover { color crimson }") + end + + test "refuses a string left open in a custom property, which takes a `:`" do + assert {:error, %{errors: [error]}} = IgniterCss.validate_block(~s|--x: "abc|) + + assert %IgniterCss.Diagnostic{ + line: 1, + column: 6, + text: ~s|"abc|, + message: "Missing closing quote" + } = error + + assert {:error, %{errors: [%{column: 11, message: "Missing closing quote"}]}} = + IgniterCss.validate(~s|.a { --x: "abc\n}|) + + assert {:ok, _} = IgniterCss.validate_block("--x: a:b;") end test "accepts an at-rule with no `;` written last in a block" do From fd8c94f98411738ad9a88b27e2aa8e02eca8697a Mon Sep 17 00:00:00 2001 From: Shahryar Tavakkoli Date: Sun, 1 Nov 2026 05:52:44 +0100 Subject: [PATCH 7/7] fix: an at-rule with no block ends at its block's `}` as CSS Syntax reads it, an `@` with no name starts none, and a line ends at `\r` too * An at-rule written last in a block with no `;` ends at the block's `}` whenever that `}` is outside the prelude's brackets, as CSS Syntax reads it: `.a { @apply p-4 gap: 1px }`, `.a { @foo (min-width: 1px) }` and `.a { @apply foo(a: b) }` are valid, and a prelude spanning lines is too. What the prelude says is the at-rule's to check (Tailwind for `@apply`). `@apply foo(a }` still runs on, its `}` inside the `(`. * An `@` the parser could not place starts an at-rule only when an identifier or a keyword Biome lexes as one is written against it. `.a { @; color: red; }` lists nothing, and `remove_at_rules/3` keeps `color: red;`. * An error's line and column are Biome's own (`SourceFile::location`), so a line ends at `\n`, `\r\n` or `\r`. * Bogus nodes are told apart with Biome's `SyntaxKind::is_bogus`, all 19 of its kinds, not a copy of 8. Co-Authored-By: Claude Opus 5.5 --- native/igniter_css/src/analyze.rs | 62 ++++++++++++++++----------- native/igniter_css/src/ctx.rs | 16 ------- native/igniter_css/src/locate.rs | 38 ++++++---------- native/igniter_css/src/ops/at_rule.rs | 15 +++++++ test/at_rules_test.exs | 13 ++++++ test/igniter_css_test.exs | 17 ++++++-- 6 files changed, 92 insertions(+), 69 deletions(-) diff --git a/native/igniter_css/src/analyze.rs b/native/igniter_css/src/analyze.rs index 9e6d8b3..1d39849 100644 --- a/native/igniter_css/src/analyze.rs +++ b/native/igniter_css/src/analyze.rs @@ -18,7 +18,8 @@ use crate::locate::{ use crate::ops::at_rule::normalize_target_needle; use crate::ops::query; use biome_css_syntax::{CssSyntaxKind, CssSyntaxNode}; -use biome_rowan::Direction; +use biome_diagnostics::{display::SourceFile, SourceCode}; +use biome_rowan::{Direction, TextSize}; use std::collections::{BTreeMap, BTreeSet}; /// A block of declarations together with the text that introduced it -- a @@ -844,13 +845,17 @@ fn placed(text: &str, shift: usize, error: &ParseError) -> Diagnostic { } } -/// 1-based line and column of byte `at` in `text`, the column in characters. +/// 1-based line and column of byte `at` in `text`, the column in characters, +/// as Biome counts them: a line ends at `\n`, `\r\n` or `\r`. fn line_and_column(text: &str, at: usize) -> (usize, usize) { - let line_start = text[..at].rfind('\n').map_or(0, |i| i + 1); - ( - text[..at].matches('\n').count() + 1, - text[line_start..at].chars().count() + 1, - ) + let file = SourceFile::new(SourceCode { + text, + line_starts: None, + }); + TextSize::try_from(at) + .ok() + .and_then(|at| file.location(at).ok()) + .map_or((1, 1), |l| (l.line_number.get(), l.column_number.get())) } /// `message` on one line: a line break in the author's text it quotes reads @@ -1403,6 +1408,10 @@ mod tests { assert_eq!((first.line, first.column), (3, 13)); assert_eq!(first.text, ": blue"); assert!(v.message.contains("line 3, column 13"), "{}", v.message); + + // A line ends at `\r` too, as Biome reads it. + let v = validate(".a {\r color: red\r background: blue;\r}\r", opts()); + assert_eq!((v.errors[0].line, v.errors[0].column), (3, 13)); } #[test] @@ -1542,6 +1551,7 @@ mod tests { ("gap: 1px;\ncolor crimson", (2, 1)), ("gap: 1px;\ncolor crimson;\nmargin: 0;", (2, 1)), ("gap: 1px;\r\n color crimson", (2, 3)), + ("gap: 1px;\r color crimson", (2, 3)), ("color crimson; &:hover { gap: 1px }", (1, 1)), ("&:hover { color crimson; }", (1, 11)), ("&:hover { color crimson }", (1, 11)), @@ -1616,6 +1626,11 @@ mod tests { (3, 24), "Expected a `}` to close the `{` on line 2, column 9", ), + ( + "gap: 1px;\r&:hover {\r &:focus { gap: 1px; }", + (3, 24), + "Expected a `}` to close the `{` on line 2, column 9", + ), ] { assert_eq!(only_error(body), row(at.0, at.1, "", message), "{body:?}"); } @@ -1727,6 +1742,11 @@ mod tests { ".a { @apply p-4 }\n.b { color: red; }", ".a { @apply p-4 } .b { &:hover { @apply p-2 } }", "@media print { .a { @apply p-4 } }", + ".a { @apply p-4\n color: red }", + ".a { @apply p-4 gap: 1px }", + ".a { @foo (min-width: 1px) }", + ".a { @apply foo(a: b) }", + ".a { @apply }", ] { let v = validate(src, opts()); assert!(v.valid, "{src}: {:?}", v.errors); @@ -1739,6 +1759,8 @@ mod tests { "@apply p-4", "padding: 4px;\n@apply p-4", "&:hover { @apply p-4 }", + "@apply p-4\ncolor: red", + "@apply p-4 gap: 1px", ] { let v = validate_block(body, opts()); assert!(v.valid, "{body:?}: {:?}", v.errors); @@ -1772,25 +1794,15 @@ mod tests { ); } + // A `}` inside a bracket is part of that bracket's block, and an at-rule + // Biome knows the grammar of, `@media`, still needs a block of its own. #[test] - fn an_at_rule_running_into_another_statement_is_still_an_error() { - for body in [ - "@apply p-4\ncolor: red", - "@apply p-4 gap: 1px", - "@apply\np-4", - ] { - assert_eq!( - only_error(body).3, - "This `@apply` rule is not finished", - "{body:?}" - ); - } - for src in [ - ".a { @apply p-4\n color: red }", - ".a { @apply }", - ".a { @apply foo(a }", - ".a { @media print }", - ] { + fn an_at_rule_its_block_does_not_end_is_still_an_error() { + assert_eq!( + only_error("@apply foo(a"), + row(1, 1, "@apply foo(a", "This `@apply` rule is not finished") + ); + for src in [".a { @apply foo(a }", ".a { @media print }"] { assert!(!validate(src, opts()).valid, "{src}"); } } diff --git a/native/igniter_css/src/ctx.rs b/native/igniter_css/src/ctx.rs index 686bb83..47c7ea4 100644 --- a/native/igniter_css/src/ctx.rs +++ b/native/igniter_css/src/ctx.rs @@ -425,22 +425,6 @@ pub fn is_comment_kind(kind: biome_rowan::TriviaPieceKind) -> bool { ) } -/// Kinds that represent a rule Biome could not understand. They still carry -/// their original source text, which is exactly why we can patch around them. -pub fn is_bogus(kind: CssSyntaxKind) -> bool { - matches!( - kind, - CssSyntaxKind::CSS_BOGUS - | CssSyntaxKind::CSS_BOGUS_RULE - | CssSyntaxKind::CSS_BOGUS_AT_RULE - | CssSyntaxKind::CSS_BOGUS_BLOCK - | CssSyntaxKind::CSS_BOGUS_DECLARATION_ITEM - | CssSyntaxKind::CSS_BOGUS_PROPERTY - | CssSyntaxKind::CSS_BOGUS_PROPERTY_VALUE - | CssSyntaxKind::CSS_BOGUS_SELECTOR - ) -} - #[cfg(test)] mod tests { use super::*; diff --git a/native/igniter_css/src/locate.rs b/native/igniter_css/src/locate.rs index 7c3c82e..657fc86 100644 --- a/native/igniter_css/src/locate.rs +++ b/native/igniter_css/src/locate.rs @@ -12,9 +12,9 @@ //! * more than one match is `MatchResult::Ambiguous` -- we error, we do not //! pick one, because guessing produces surprising diffs. -use crate::ctx::{is_bogus, ParseCtx}; +use crate::ctx::ParseCtx; use biome_css_syntax::{CssSyntaxKind, CssSyntaxNode, CssSyntaxToken}; -use biome_rowan::{Direction, TextRange, TextSize}; +use biome_rowan::{Direction, SyntaxKind, TextRange, TextSize}; // --------------------------------------------------------------------------- // References @@ -481,7 +481,8 @@ fn at_rule_ref_from(node: &CssSyntaxNode, ctx: &ParseCtx) -> Option { /// `;` that ends it or the `}` that closes its block. A `}` closing the block /// the `@` sits in ends it first. /// -/// `None` for an `@` with no name against it, or one that does not start a +/// `None` for an `@` with no name against it -- an identifier or a keyword +/// Biome lexes as one, not `;` or `(` -- or one that does not start a /// statement -- first in the file or after a `;`, `{` or `}`, comments aside -- /// because after anything else it is part of a selector or a value /// (`url(@x.png)`), as every reader of CSS takes it. @@ -498,7 +499,9 @@ fn stray_at_rule_ref(ctx: &ParseCtx, at: &CssSyntaxToken) -> Option { let (start, at_end) = range_to_pair(at.text_trimmed_range()); let name_token = at.next_token()?; let (name_start, name_end) = range_to_pair(name_token.text_trimmed_range()); - if name_start != at_end || name_token.kind() == CssSyntaxKind::EOF { + let named = + name_token.kind() == CssSyntaxKind::IDENT || name_token.kind().is_contextual_keyword(); + if name_start != at_end || !named { return None; } @@ -902,7 +905,7 @@ pub fn top_of_file_anchor(ctx: &ParseCtx) -> usize { // that appear before the first rule. let first_rule_start = top_level_nodes(ctx) .iter() - .filter(|n| !is_bogus(n.kind())) + .filter(|n| !n.kind().is_bogus()) .map(|n| usize::from(n.text_trimmed_range().start())) .find(|start| *start >= anchor); @@ -1114,7 +1117,7 @@ pub fn is_stray_semicolon(ctx: &ParseCtx, start: usize, end: usize) -> bool { | CssSyntaxKind::CSS_DECLARATION_OR_AT_RULE_LIST ) }); - is_bogus(node.kind()) + node.kind().is_bogus() && in_block && node .descendants_tokens(Direction::Next) @@ -1127,11 +1130,9 @@ pub fn is_stray_semicolon(ctx: &ParseCtx, start: usize, end: usize) -> bool { /// block the at-rule is in; Biome 0.5.8 reads on to the next `;` or `{`, and /// misreads everything up to there. /// -/// Only for a prelude on one line with its brackets closed and no `:` with a -/// space after it. One that runs onto a new line before the `}`, `@apply p-4` -/// then `color: red`, or holds a `:` the way a declaration does, `@apply p-4 -/// gap: 1px`, holds what reads as another statement with its `;` missing, and -/// stays an error. A class name such as `md:p-4` has no space after its `:`. +/// Only for a `}` outside every bracket in the prelude: in `@apply foo(a }` it +/// is part of the `(`'s block, and the at-rule runs on past it. What the +/// prelude says, `@apply p-4 gap: 1px` included, is the at-rule's to check. pub fn at_rule_ended_by_its_block(ctx: &ParseCtx) -> Option { let prelude = ctx .syntax() @@ -1149,19 +1150,8 @@ pub fn at_rule_ended_by_its_block(ctx: &ParseCtx) -> Option { let close = tokens .iter() .position(|t| t.kind() == CssSyntaxKind::R_CURLY)?; - let before = &tokens[..close]; - let one_line = !before.is_empty() && !before.iter().any(|t| t.has_leading_newline()); - let declaration = before.iter().any(|t| { - t.kind() == CssSyntaxKind::COLON - && t.trailing_trivia() - .pieces() - .any(|piece| piece.is_whitespace()) - }); - (one_line - && !declaration - && brackets_close(before) - && tokens[close].parent().as_ref() == Some(&prelude)) - .then(|| usize::from(tokens[close].text_trimmed_range().start())) + (brackets_close(&tokens[..close]) && tokens[close].parent().as_ref() == Some(&prelude)) + .then(|| usize::from(tokens[close].text_trimmed_range().start())) } /// At-rules that are valid only at the top level of a stylesheet, written diff --git a/native/igniter_css/src/ops/at_rule.rs b/native/igniter_css/src/ops/at_rule.rs index 9cc6fc9..7ae9acf 100644 --- a/native/igniter_css/src/ops/at_rule.rs +++ b/native/igniter_css/src/ops/at_rule.rs @@ -1611,6 +1611,21 @@ mod tests { ); } + // An `@` with no name against it starts no at-rule, so nothing after it is + // listed as one, or removed with it. The texts are what was listed before. + #[test] + fn an_at_sign_with_no_name_is_not_an_at_rule() { + for (src, text) in [ + (".a { @; color: red; }\n", "@; color: red;"), + (".a { @(x); color: red; }\n", "@(x);"), + ] { + let listed = crate::analyze::list_at_rules(src, ParseOptions::strict()).unwrap(); + assert!(listed.is_empty(), "{src}: {listed:?}"); + let out = remove_at_rules(src, &[text.to_string()], ParseOptions::strict()).unwrap(); + assert_eq!(out.source, src); + } + } + #[test] fn removing_at_rules_from_unbalanced_braces_is_refused() { let texts = vec!["@import \"x\";".to_string()]; diff --git a/test/at_rules_test.exs b/test/at_rules_test.exs index 43959cc..e2af9b5 100644 --- a/test/at_rules_test.exs +++ b/test/at_rules_test.exs @@ -614,6 +614,19 @@ defmodule IgniterCss.AtRulesTest do assert upper.name == "import" end + # Before, `@;` was listed as an at-rule named `;` that ran on to `color: red;`. + test "an @ with no name against it starts no at-rule, so nothing goes with it" do + for {css, text} <- [ + {".a { @; color: red; }", "@; color: red;"}, + {".a { @(x); color: red; }", "@(x);"} + ] do + assert {:ok, []} = IgniterCss.list_at_rules(css) + + assert {:ok, %{changed: false, source: ^css}} = + IgniterCss.remove_at_rules(css, [%IgniterCss.AtRule{text: text}]) + end + end + test "refuses to remove from braces that do not balance" do css = ~s|.a { @import "x.css";| {:ok, rules} = IgniterCss.list_at_rules(css) diff --git a/test/igniter_css_test.exs b/test/igniter_css_test.exs index 61e31ed..ffa5f2c 100644 --- a/test/igniter_css_test.exs +++ b/test/igniter_css_test.exs @@ -720,11 +720,20 @@ defmodule IgniterCssTest do assert {:ok, %{valid: true}} = IgniterCss.validate(".a { @apply p-4 }\n.b { color: red; }") end - test "still refuses an @apply that runs into another statement without a `;`" do - assert {:error, %{errors: [%{line: 1, column: 1, text: "@apply p-4\ncolor: red"}]}} = - IgniterCss.validate_block("@apply p-4\ncolor: red") + test "reads an at-rule's prelude up to the } of its block, as CSS Syntax does" do + for body <- ["@apply p-4\ncolor: red", "@apply p-4 gap: 1px"] do + assert {:ok, %{valid: true}} = IgniterCss.validate_block(body), body + end + + assert {:ok, %{valid: true}} = IgniterCss.validate(".a { @foo (min-width: 1px) }") + + assert {:error, %{errors: [%{line: 1, column: 1, text: "@apply foo(a"}]}} = + IgniterCss.validate_block("@apply foo(a") + end - assert {:error, _} = IgniterCss.validate_block("@apply p-4 gap: 1px") + test "counts a line ended by \\r alone" do + assert {:error, %{errors: [%{line: 2, column: 1, text: "color crimson"}]}} = + IgniterCss.validate_block("gap: 1px;\rcolor crimson") end test "keeps a string's missing closing quote over what the parser misreads after it" do