Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: create biome_css_analyze crate #1462

Merged
merged 4 commits into from
Jan 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
19 changes: 19 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions crates/biome_analyze/src/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -138,9 +138,9 @@ impl AnalyzerDiagnostic {
}
}

#[derive(Debug, Diagnostic)]
#[derive(Debug, Diagnostic, Clone)]
#[diagnostic(severity = Warning)]
pub(crate) struct SuppressionDiagnostic {
pub struct SuppressionDiagnostic {
#[category]
category: &'static Category,
#[location(span)]
Expand Down
2 changes: 1 addition & 1 deletion crates/biome_analyze/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ pub use crate::categories::{
ActionCategory, RefactorKind, RuleCategories, RuleCategory, SourceActionKind,
};
pub use crate::diagnostics::AnalyzerDiagnostic;
use crate::diagnostics::SuppressionDiagnostic;
pub use crate::diagnostics::SuppressionDiagnostic;
pub use crate::matcher::{InspectMatcher, MatchQueryParams, QueryMatcher, RuleKey, SignalEntry};
pub use crate::options::{AnalyzerConfiguration, AnalyzerOptions, AnalyzerRules};
pub use crate::query::{AddVisitor, QueryKey, QueryMatch, Queryable};
Expand Down
33 changes: 33 additions & 0 deletions crates/biome_css_analyze/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
[package]
authors.workspace = true
categories.workspace = true
description = "Biome's CSS linter"
edition.workspace = true
homepage.workspace = true
keywords.workspace = true
license.workspace = true
name = "biome_css_analyze"
repository.workspace = true
version = "0.4.0"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
biome_analyze = { workspace = true }
biome_console = { workspace = true }
biome_css_syntax = { workspace = true }
biome_diagnostics = { workspace = true }
biome_rowan = { workspace = true }
lazy_static = { workspace = true }
rustc-hash = { workspace = true }

[dev-dependencies]
biome_css_factory = { path = "../biome_css_factory" }
biome_css_parser = { path = "../biome_css_parser" }
biome_service = { path = "../biome_service" }
biome_test_utils = { path = "../biome_test_utils" }
insta = { workspace = true, features = ["glob"] }
tests_macros = { path = "../tests_macros" }

[lints]
workspace = true
4 changes: 4 additions & 0 deletions crates/biome_css_analyze/src/analyzers.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
//! Generated file, do not edit by hand, see `xtask/codegen`

pub(crate) mod nursery;
::biome_analyze::declare_category! { pub (crate) Analyzers { kind : Lint , groups : [self :: nursery :: Nursery ,] } }
14 changes: 14 additions & 0 deletions crates/biome_css_analyze/src/analyzers/nursery.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
//! Generated file, do not edit by hand, see `xtask/codegen`

use biome_analyze::declare_group;

pub(crate) mod noop;

declare_group! {
pub (crate) Nursery {
name : "nursery" ,
rules : [
self :: noop :: Noop ,
]
}
}
21 changes: 21 additions & 0 deletions crates/biome_css_analyze/src/analyzers/nursery/noop.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
use biome_analyze::{context::RuleContext, declare_rule, Ast, Rule};
use biome_css_syntax::CssColor;

declare_rule! {
/// Noop rule
pub(crate) Noop {
version: "next",
name: "noop",
}
}

impl Rule for Noop {
type Query = Ast<CssColor>;
type State = ();
type Signals = Option<Self::State>;
type Options = ();

fn run(_: &RuleContext<Self>) -> Option<Self::State> {
None
}
}
161 changes: 161 additions & 0 deletions crates/biome_css_analyze/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
mod analyzers;
mod registry;

pub use crate::registry::visit_registry;
use biome_analyze::{
AnalysisFilter, AnalyzerOptions, AnalyzerSignal, ControlFlow, LanguageRoot, MatchQueryParams,
MetadataRegistry, RuleRegistry, SuppressionDiagnostic, SuppressionKind,
};
use biome_css_syntax::CssLanguage;
use biome_diagnostics::Error;

/// Return the static [MetadataRegistry] for the JSON analyzer rules
pub fn metadata() -> &'static MetadataRegistry {
lazy_static::lazy_static! {
static ref METADATA: MetadataRegistry = {
let mut metadata = MetadataRegistry::default();
visit_registry(&mut metadata);
metadata
};
}

&METADATA
}

/// Run the analyzer on the provided `root`: this process will use the given `filter`
/// to selectively restrict analysis to specific rules / a specific source range,
/// then call `emit_signal` when an analysis rule emits a diagnostic or action
pub fn analyze<'a, F, B>(
root: &LanguageRoot<CssLanguage>,
filter: AnalysisFilter,
options: &'a AnalyzerOptions,
emit_signal: F,
) -> (Option<B>, Vec<Error>)
where
F: FnMut(&dyn AnalyzerSignal<CssLanguage>) -> ControlFlow<B> + 'a,
B: 'a,
{
analyze_with_inspect_matcher(root, filter, |_| {}, options, emit_signal)
}

/// Run the analyzer on the provided `root`: this process will use the given `filter`
/// to selectively restrict analysis to specific rules / a specific source range,
/// then call `emit_signal` when an analysis rule emits a diagnostic or action.
/// Additionally, this function takes a `inspect_matcher` function that can be
/// used to inspect the "query matches" emitted by the analyzer before they are
/// processed by the lint rules registry
pub fn analyze_with_inspect_matcher<'a, V, F, B>(
root: &LanguageRoot<CssLanguage>,
filter: AnalysisFilter,
inspect_matcher: V,
options: &'a AnalyzerOptions,
mut emit_signal: F,
) -> (Option<B>, Vec<Error>)
where
V: FnMut(&MatchQueryParams<CssLanguage>) + 'a,
F: FnMut(&dyn AnalyzerSignal<CssLanguage>) -> ControlFlow<B> + 'a,
B: 'a,
{
fn parse_linter_suppression_comment(
_text: &str,
) -> Vec<Result<SuppressionKind, SuppressionDiagnostic>> {
vec![]
}
let mut registry = RuleRegistry::builder(&filter, root);
visit_registry(&mut registry);

let (registry, services, diagnostics, visitors) = registry.build();

// Bail if we can't parse a rule option
if !diagnostics.is_empty() {
return (None, diagnostics);
}

let mut analyzer = biome_analyze::Analyzer::new(
metadata(),
biome_analyze::InspectMatcher::new(registry, inspect_matcher),
parse_linter_suppression_comment,
|_| {},
&mut emit_signal,
);

for ((phase, _), visitor) in visitors {
analyzer.add_visitor(phase, visitor);
}

(
analyzer.run(biome_analyze::AnalyzerContext {
root: root.clone(),
range: filter.range,
services,
options,
}),
diagnostics,
)
}

#[cfg(test)]
mod tests {
use biome_analyze::{AnalyzerOptions, Never, RuleFilter};
use biome_console::fmt::{Formatter, Termcolor};
use biome_console::{markup, Markup};
use biome_css_parser::{parse_css, CssParserOptions};
use biome_css_syntax::TextRange;
use biome_diagnostics::termcolor::NoColor;
use biome_diagnostics::{Diagnostic, DiagnosticExt, PrintDiagnostic, Severity};
use std::slice;

use crate::{analyze, AnalysisFilter, ControlFlow};

#[ignore]
#[test]
fn quick_test() {
fn markup_to_string(markup: Markup) -> String {
let mut buffer = Vec::new();
let mut write = Termcolor(NoColor::new(&mut buffer));
let mut fmt = Formatter::new(&mut write);
fmt.write_markup(markup).unwrap();

String::from_utf8(buffer).unwrap()
}

const SOURCE: &str = r#".something {}
"#;

let parsed = parse_css(SOURCE, CssParserOptions::default());

let mut error_ranges: Vec<TextRange> = Vec::new();
let rule_filter = RuleFilter::Rule("nursery", "noDuplicateKeys");
let options = AnalyzerOptions::default();
analyze(
&parsed.tree(),
AnalysisFilter {
enabled_rules: Some(slice::from_ref(&rule_filter)),
..AnalysisFilter::default()
},
&options,
|signal| {
if let Some(diag) = signal.diagnostic() {
error_ranges.push(diag.location().span.unwrap());
let error = diag
.with_severity(Severity::Warning)
.with_file_path("ahahah")
.with_file_source_code(SOURCE);
let text = markup_to_string(markup! {
{PrintDiagnostic::verbose(&error)}
});
eprintln!("{text}");
}

for action in signal.actions() {
let new_code = action.mutation.commit();
eprintln!("{new_code}");
}

ControlFlow::<Never>::Continue(())
},
);

assert_eq!(error_ranges.as_slice(), &[]);
}
}
7 changes: 7 additions & 0 deletions crates/biome_css_analyze/src/registry.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
//! Generated file, do not edit by hand, see `xtask/codegen`

use biome_analyze::RegistryVisitor;
use biome_css_syntax::CssLanguage;
pub fn visit_registry<V: RegistryVisitor<CssLanguage>>(registry: &mut V) {
registry.record_category::<crate::analyzers::Analyzers>();
}
Loading