diff --git a/README.md b/README.md index b805a8c..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,9 +113,9 @@ 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`, `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..f270ba5 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. @@ -502,10 +549,53 @@ 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. + + 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. 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{}}`. + + 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;\\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 + 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 +632,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..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,7 +91,9 @@ 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() 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..6e33935 100644 --- a/lib/igniter_css/structs.ex +++ b/lib/igniter_css/structs.ex @@ -111,16 +111,42 @@ 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 or an `@apply` with no `;` written last in a block. + `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..1d39849 100644 --- a/native/igniter_css/src/analyze.rs +++ b/native/igniter_css/src/analyze.rs @@ -6,16 +6,20 @@ //! 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, 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; 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 @@ -478,6 +482,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`]. /// @@ -497,25 +524,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()) }) } @@ -634,9 +658,231 @@ 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(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() + } 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, + one_line(&first.message) + ), + } + }; + Validation { + valid: round_trips && errors.is_empty(), + diagnostics: reading.diagnostics, + round_trips, + message, + errors, + } + } +} + +/// 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. +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, column) = line_and_column(text, start); + + Diagnostic { + message: error.message.clone(), + line, + column, + offset: start, + text: text[start..end].to_string(), + } +} + +/// 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 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 +/// `\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 { + 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: one_line(&message), + start: statement.start, + end: statement.end, + } } /// Is this CSS understood well enough to patch? @@ -644,44 +890,134 @@ 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`, `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 { - 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(), - } - } + let reading = match Reading::new(source, options) { + Ok(r) => r, + 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)") - } else { - "CSS is valid".to_string() + // Offsets are into the source without its byte-order mark, which no editor + // shows as a column. + 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(given, 0, &reading.given_error(e)); + d.offset += bom; + d + }) + .collect(); + Validation::of(&reading, 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. +/// +/// 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. +/// 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()); + } + let source = format!("{BLOCK_OPEN}{body}{BLOCK_CLOSE}"); + let reading = match Reading::new(&source, options) { + Ok(r) => r, + Err(e) => return Validation::refused(e.to_string()), }; - Validation { - valid, - diagnostics, - round_trips, - message, + // 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 body_start = BLOCK_OPEN.len(); + 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); + 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, + }); + } + + for (rule, reach) in misread_rules(ctx, body_end) { + found.retain(|e| e.start < rule.start || e.start >= reach); + found.push(unfinished(ctx.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, block_close).filter(|&open| 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!( + "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) + { + // 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)); + + let errors = found + .iter() + .map(|e| placed(body, body_start, &reading.given_error(e))) + .collect(); + Validation::of(&reading, errors) } #[cfg(test)] @@ -786,6 +1122,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()) @@ -1002,6 +1400,421 @@ 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); + + // 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] + 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, "")); + } + + 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)), + ("gap: 1px;\r 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), + 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", + ), + ( + "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:?}"); + } + } + + #[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"); + } + + // 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) + ] + ); + } + + // 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!( + 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] + 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 } }", + ".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); + 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 }", + "@apply p-4\ncolor: red", + "@apply p-4 gap: 1px", + ] { + 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" + ) + ); + } + + // 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_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}"); + } + } + + #[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..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,7 +38,9 @@ rustler::atoms! { analyze_nif, get_at_rules_nif, + list_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..47c7ea4 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 @@ -387,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 9bed28d..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 biome_css_syntax::{CssSyntaxKind, CssSyntaxNode}; -use biome_rowan::{Direction, TextRange}; +use crate::ctx::ParseCtx; +use biome_css_syntax::{CssSyntaxKind, CssSyntaxNode, CssSyntaxToken}; +use biome_rowan::{Direction, SyntaxKind, TextRange, TextSize}; // --------------------------------------------------------------------------- // References @@ -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 { @@ -165,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)> { @@ -466,6 +472,114 @@ 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 -- 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. +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()); + let named = + name_token.kind() == CssSyntaxKind::IDENT || name_token.kind().is_contextual_keyword(); + if name_start != at_end || !named { + 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 +688,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(); @@ -773,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); @@ -839,6 +971,390 @@ 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` a string the lexer could not end, `"abc` with its line or +/// the text ending before the closing quote? CSS Syntax reads it as a bad +/// string, which ends the declaration it is in as invalid. +fn is_open_string(ctx: &ParseCtx, start: usize, end: usize) -> 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? +/// +/// * 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. +/// +/// Never for a string left open (see `is_open_string`), which no value takes. +pub fn in_free_form_value(ctx: &ParseCtx, start: usize, end: usize) -> bool { + if is_open_string(ctx, start, end) { + return false; + } + 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 + ) + }); + node.kind().is_bogus() + && in_block + && node + .descendants_tokens(Direction::Next) + .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 `}` 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() + .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)?; + (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 +/// 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() +} + +// --------------------------------------------------------------------------- +// 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 `;` 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. + pub unread: Option, +} + +/// 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 && matches!(t.kind(), CssSyntaxKind::SEMICOLON | CssSyntaxKind::R_CURLY)) + }) + .filter(|t| t.kind() != CssSyntaxKind::CSS_SPACE_LITERAL) + .last() + .map_or(start, |t| usize::from(t.text_trimmed_range().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 `{` +/// 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`. +/// +/// 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 block = block_child(&rule).map(|block| trimmed(&block).0); + let semicolon = rule + .first_child()? + .descendants_tokens(Direction::Next) + .any(|t| t.kind() == CssSyntaxKind::SEMICOLON); + 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() +} + +/// 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/native/igniter_css/src/nif.rs b/native/igniter_css/src/nif.rs index 27e39bf..a7baf0d 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)] @@ -134,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 { @@ -533,15 +582,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")] @@ -621,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..7ae9acf 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,71 @@ 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" + ); + } + + // 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()]; + 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..e2af9b5 100644 --- a/test/at_rules_test.exs +++ b/test/at_rules_test.exs @@ -554,4 +554,83 @@ 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 + + # 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) + assert {:error, _reason} = IgniterCss.remove_at_rules(css, rules) + end + end end diff --git a/test/igniter_css_test.exs b/test/igniter_css_test.exs index c8ee6ad..ffa5f2c 100644 --- a/test/igniter_css_test.exs +++ b/test/igniter_css_test.exs @@ -635,6 +635,155 @@ 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]}} = + IgniterCss.validate_block("gap: 1px;\ncolor crimson") + + 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 + + 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 + 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 "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 + + 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 + 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;") + + 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 + 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)"]}]} =