repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/fuzz/fuzz_targets/rome_format_module.rs
fuzz/fuzz_targets/rome_format_module.rs
#![cfg_attr(not(feature = "rome_all"), no_main)] #[path = "rome_common.rs"] mod rome_common; use libfuzzer_sys::Corpus; use rome_js_syntax::JsFileSource; pub fn do_fuzz(case: &[u8]) -> Corpus { let parse_type = JsFileSource::js_module(); rome_common::fuzz_js_formatter_with_source_type(case, parse_type) } #[cfg(not(feature = "rome_all"))] libfuzzer_sys::fuzz_target!(|case: &[u8]| -> Corpus { do_fuzz(case) });
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/fuzz/fuzz_targets/rome_parse_module.rs
fuzz/fuzz_targets/rome_parse_module.rs
#![cfg_attr(not(feature = "rome_all"), no_main)] #[path = "rome_common.rs"] mod rome_common; use libfuzzer_sys::Corpus; use rome_js_syntax::JsFileSource; pub fn do_fuzz(case: &[u8]) -> Corpus { let parse_type = JsFileSource::js_module(); rome_common::fuzz_js_parser_with_source_type(case, parse_type) } #[cfg(not(feature = "rome_all"))] libfuzzer_sys::fuzz_target!(|case: &[u8]| -> Corpus { do_fuzz(case) });
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/fuzz/fuzz_targets/rome_parse_d_ts.rs
fuzz/fuzz_targets/rome_parse_d_ts.rs
#![cfg_attr(not(feature = "rome_all"), no_main)] #[path = "rome_common.rs"] mod rome_common; use libfuzzer_sys::Corpus; use rome_js_syntax::JsFileSource; pub fn do_fuzz(case: &[u8]) -> Corpus { let parse_type = JsFileSource::d_ts(); rome_common::fuzz_js_parser_with_source_type(case, parse_type) } #[cfg(not(feature = "rome_all"))] libfuzzer_sys::fuzz_target!(|case: &[u8]| -> Corpus { do_fuzz(case) });
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/fuzz/fuzz_targets/rome_format_script.rs
fuzz/fuzz_targets/rome_format_script.rs
#![cfg_attr(not(feature = "rome_all"), no_main)] #[path = "rome_common.rs"] mod rome_common; use libfuzzer_sys::Corpus; use rome_js_syntax::JsFileSource; pub fn do_fuzz(case: &[u8]) -> Corpus { let parse_type = JsFileSource::js_script(); rome_common::fuzz_js_formatter_with_source_type(case, parse_type) } #[cfg(not(feature = "rome_all"))] libfuzzer_sys::fuzz_target!(|case: &[u8]| -> Corpus { do_fuzz(case) });
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/fuzz/fuzz_targets/rome_format_typescript.rs
fuzz/fuzz_targets/rome_format_typescript.rs
#![cfg_attr(not(feature = "rome_all"), no_main)] #[path = "rome_common.rs"] mod rome_common; use libfuzzer_sys::Corpus; use rome_js_syntax::JsFileSource; pub fn do_fuzz(case: &[u8]) -> Corpus { let parse_type = JsFileSource::ts(); rome_common::fuzz_js_formatter_with_source_type(case, parse_type) } #[cfg(not(feature = "rome_all"))] libfuzzer_sys::fuzz_target!(|case: &[u8]| -> Corpus { do_fuzz(case) });
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/fuzz/fuzz_targets/rome_parse_all.rs
fuzz/fuzz_targets/rome_parse_all.rs
#![no_main] mod rome_parse_d_ts; mod rome_parse_jsx; mod rome_parse_module; mod rome_parse_script; mod rome_parse_tsx; mod rome_parse_typescript; use libfuzzer_sys::{fuzz_target, Corpus}; fn do_fuzz(data: &[u8]) -> Corpus { let mut keep = Corpus::Reject; if let Corpus::Keep = rome_parse_d_ts::do_fuzz(data) { keep = Corpus::Keep; } if let Corpus::Keep = rome_parse_jsx::do_fuzz(data) { keep = Corpus::Keep; } if let Corpus::Keep = rome_parse_module::do_fuzz(data) { keep = Corpus::Keep; } if let Corpus::Keep = rome_parse_script::do_fuzz(data) { keep = Corpus::Keep; } if let Corpus::Keep = rome_parse_tsx::do_fuzz(data) { keep = Corpus::Keep; } if let Corpus::Keep = rome_parse_typescript::do_fuzz(data) { keep = Corpus::Keep; } keep } fuzz_target!(|case: &[u8]| -> Corpus { do_fuzz(case) });
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/fuzz/fuzz_targets/rome_parse_script.rs
fuzz/fuzz_targets/rome_parse_script.rs
#![cfg_attr(not(feature = "rome_all"), no_main)] #[path = "rome_common.rs"] mod rome_common; use libfuzzer_sys::Corpus; use rome_js_syntax::JsFileSource; pub fn do_fuzz(case: &[u8]) -> Corpus { let parse_type = JsFileSource::js_script(); rome_common::fuzz_js_parser_with_source_type(case, parse_type) } #[cfg(not(feature = "rome_all"))] libfuzzer_sys::fuzz_target!(|case: &[u8]| -> Corpus { do_fuzz(case) });
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/fuzz/fuzz_targets/rome_format_jsx.rs
fuzz/fuzz_targets/rome_format_jsx.rs
#![cfg_attr(not(feature = "rome_all"), no_main)] #[path = "rome_common.rs"] mod rome_common; use libfuzzer_sys::Corpus; use rome_js_syntax::JsFileSource; pub fn do_fuzz(case: &[u8]) -> Corpus { let parse_type = JsFileSource::jsx(); rome_common::fuzz_js_formatter_with_source_type(case, parse_type) } #[cfg(not(feature = "rome_all"))] libfuzzer_sys::fuzz_target!(|case: &[u8]| -> Corpus { do_fuzz(case) });
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/fuzz/fuzz_targets/rome_common.rs
fuzz/fuzz_targets/rome_common.rs
//! Common functionality between different fuzzers. Look here if you need to inspect implementation //! details for the fuzzer harnesses! #![allow(dead_code)] use libfuzzer_sys::Corpus; use rome_analyze::{AnalysisFilter, AnalyzerOptions, ControlFlow, RuleFilter}; use rome_diagnostics::Diagnostic; use rome_formatter::format_node; use rome_js_analyze::analyze; use rome_js_formatter::context::JsFormatOptions; use rome_js_formatter::JsFormatLanguage; use rome_js_parser::parse; use rome_js_syntax::JsFileSource; use rome_json_formatter::context::JsonFormatOptions; use rome_json_formatter::JsonFormatLanguage; use rome_json_parser::parse_json; use rome_service::Rules; use similar::TextDiff; use std::fmt::{Display, Formatter}; pub fn fuzz_js_parser_with_source_type(data: &[u8], source: JsFileSource) -> Corpus { let Ok(code1) = std::str::from_utf8(data) else { return Corpus::Reject; }; let parse1 = parse(code1, source); if !parse1.has_errors() { let syntax1 = parse1.syntax(); let code2 = syntax1.to_string(); assert_eq!(code1, code2, "unparse output differed"); } Corpus::Keep } static mut ANALYSIS_RULES: Option<Rules> = None; static mut ANALYSIS_RULE_FILTERS: Option<Vec<RuleFilter>> = None; static mut ANALYSIS_OPTIONS: Option<AnalyzerOptions> = None; struct DiagnosticDescriptionExtractor<'a, D> { diagnostic: &'a D, } impl<'a, D> DiagnosticDescriptionExtractor<'a, D> { pub fn new(diagnostic: &'a D) -> Self { Self { diagnostic } } } impl<'a, D> Display for DiagnosticDescriptionExtractor<'a, D> where D: Diagnostic, { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { self.diagnostic.description(f) } } pub fn fuzz_js_formatter_with_source_type(data: &[u8], source: JsFileSource) -> Corpus { let Ok(code1) = std::str::from_utf8(data) else { return Corpus::Reject; }; // TODO: replace with OnceLock when upgrading to 1.70 let rule_filters = if let Some(rules) = unsafe { ANALYSIS_RULE_FILTERS.as_ref() } { rules } else { let rules = unsafe { ANALYSIS_RULES.get_or_insert_with(|| Rules { all: Some(true), ..Default::default() }) }; let rules = rules.as_enabled_rules().into_iter().collect::<Vec<_>>(); unsafe { ANALYSIS_RULE_FILTERS = Some(rules); ANALYSIS_RULE_FILTERS.as_ref().unwrap_unchecked() } }; let options = unsafe { ANALYSIS_OPTIONS.get_or_insert_with(AnalyzerOptions::default) }; let parse1 = parse(code1, source); if !parse1.has_errors() { let language = JsFormatLanguage::new(JsFormatOptions::new(source)); let tree1 = parse1.tree(); let mut linter_errors = Vec::new(); let _ = analyze( &tree1, AnalysisFilter::from_enabled_rules(Some(rule_filters)), options, source, |e| -> ControlFlow<()> { if let Some(diagnostic) = e.diagnostic() { linter_errors .push(DiagnosticDescriptionExtractor::new(&diagnostic).to_string()); } ControlFlow::Continue(()) }, ); let syntax1 = parse1.syntax(); if let Ok(formatted1) = format_node(&syntax1, language.clone()) { if let Ok(printed1) = formatted1.print() { let code2 = printed1.as_code(); let parse2 = parse(code2, source); assert!( !parse2.has_errors(), "formatter introduced errors:\n{}", TextDiff::from_lines(code1, code2) .unified_diff() .header("original code", "formatted") ); let tree2 = parse2.tree(); let (maybe_diagnostic, _) = analyze( &tree2, AnalysisFilter::from_enabled_rules(Some(rule_filters)), options, source, |e| { if let Some(diagnostic) = e.diagnostic() { let new_error = DiagnosticDescriptionExtractor::new(&diagnostic).to_string(); if let Some(idx) = linter_errors.iter().position(|e| *e == new_error) { linter_errors.remove(idx); } else { return ControlFlow::Break(new_error); } } ControlFlow::Continue(()) }, ); if let Some(diagnostic) = maybe_diagnostic { panic!( "formatter introduced linter failure: {} (expected one of: {})\n{}", diagnostic, linter_errors.join(", "), TextDiff::from_lines(code1, code2) .unified_diff() .header("original code", "formatted") ); } let syntax2 = parse2.syntax(); let formatted2 = format_node(&syntax2, language) .expect("formatted code could not be reformatted"); let printed2 = formatted2 .print() .expect("reformatted code could not be printed"); let code3 = printed2.as_code(); assert_eq!( code2, code3, "format results differ:\n{}", TextDiff::from_lines(code2, code3) .unified_diff() .header("formatted", "reformatted") ) } } } Corpus::Keep } pub fn fuzz_json_parser(data: &[u8]) -> Corpus { let Ok(code1) = std::str::from_utf8(data) else { return Corpus::Reject; }; let parse1 = parse_json(code1); if !parse1.has_errors() { let syntax1 = parse1.syntax(); let code2 = syntax1.to_string(); assert_eq!(code1, code2, "unparse output differed"); } Corpus::Keep } pub fn fuzz_json_formatter(data: &[u8]) -> Corpus { let Ok(code1) = std::str::from_utf8(data) else { return Corpus::Reject; }; let parse1 = parse_json(code1); if !parse1.has_errors() { let language = JsonFormatLanguage::new(JsonFormatOptions::default()); let syntax1 = parse1.syntax(); if let Ok(formatted1) = format_node(&syntax1, language.clone()) { if let Ok(printed1) = formatted1.print() { let code2 = printed1.as_code(); let parse2 = parse_json(code2); assert!( !parse2.has_errors(), "formatter introduced errors:\n{}", TextDiff::from_lines(code1, code2) .unified_diff() .header("original code", "formatted") ); let syntax2 = parse2.syntax(); let formatted2 = format_node(&syntax2, language) .expect("formatted code could not be reformatted"); let printed2 = formatted2 .print() .expect("reformatted code could not be printed"); assert_eq!( code2, printed2.as_code(), "format results differ:\n{}", TextDiff::from_lines(code1, code2) .unified_diff() .header("formatted", "reformatted") ) } } } Corpus::Keep }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/fuzz/fuzz_targets/rome_format_tsx.rs
fuzz/fuzz_targets/rome_format_tsx.rs
#![cfg_attr(not(feature = "rome_all"), no_main)] #[path = "rome_common.rs"] mod rome_common; use libfuzzer_sys::Corpus; use rome_js_syntax::JsFileSource; pub fn do_fuzz(case: &[u8]) -> Corpus { let parse_type = JsFileSource::tsx(); rome_common::fuzz_js_formatter_with_source_type(case, parse_type) } #[cfg(not(feature = "rome_all"))] libfuzzer_sys::fuzz_target!(|case: &[u8]| -> Corpus { do_fuzz(case) });
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/fuzz/fuzz_targets/rome_parse_tsx.rs
fuzz/fuzz_targets/rome_parse_tsx.rs
#![cfg_attr(not(feature = "rome_all"), no_main)] #[path = "rome_common.rs"] mod rome_common; use libfuzzer_sys::Corpus; use rome_js_syntax::JsFileSource; pub fn do_fuzz(case: &[u8]) -> Corpus { let parse_type = JsFileSource::tsx(); rome_common::fuzz_js_parser_with_source_type(case, parse_type) } #[cfg(not(feature = "rome_all"))] libfuzzer_sys::fuzz_target!(|case: &[u8]| -> Corpus { do_fuzz(case) });
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/fuzz/fuzz_targets/rome_parse_json.rs
fuzz/fuzz_targets/rome_parse_json.rs
#![cfg_attr(not(feature = "rome_all"), no_main)] #[path = "rome_common.rs"] mod rome_common; use libfuzzer_sys::Corpus; pub fn do_fuzz(case: &[u8]) -> Corpus { rome_common::fuzz_json_parser(case) } #[cfg(not(feature = "rome_all"))] libfuzzer_sys::fuzz_target!(|case: &[u8]| -> Corpus { do_fuzz(case) });
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_json_analyze/src/diagnostics.rs
crates/rome_json_analyze/src/diagnostics.rs
use rome_diagnostics::Diagnostic; #[derive(Clone, Debug, PartialEq, Eq, Diagnostic)] #[diagnostic(category = "suppressions/parse")] pub struct SuppressionDiagnostic {}
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_json_analyze/src/lib.rs
crates/rome_json_analyze/src/lib.rs
mod analyzers; mod diagnostics; mod registry; use crate::diagnostics::SuppressionDiagnostic; pub use crate::registry::visit_registry; use rome_analyze::{ AnalysisFilter, AnalyzerOptions, AnalyzerSignal, ControlFlow, LanguageRoot, MatchQueryParams, MetadataRegistry, RuleRegistry, SuppressionKind, }; use rome_diagnostics::Error; use rome_json_syntax::JsonLanguage; /// 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<JsonLanguage>, filter: AnalysisFilter, options: &'a AnalyzerOptions, emit_signal: F, ) -> (Option<B>, Vec<Error>) where F: FnMut(&dyn AnalyzerSignal<JsonLanguage>) -> 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<JsonLanguage>, filter: AnalysisFilter, inspect_matcher: V, options: &'a AnalyzerOptions, mut emit_signal: F, ) -> (Option<B>, Vec<Error>) where V: FnMut(&MatchQueryParams<JsonLanguage>) + 'a, F: FnMut(&dyn AnalyzerSignal<JsonLanguage>) -> 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 = rome_analyze::Analyzer::new( metadata(), rome_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(rome_analyze::AnalyzerContext { root: root.clone(), range: filter.range, services, options, }), diagnostics, ) } #[cfg(test)] mod tests { use rome_analyze::{AnalyzerOptions, Never, RuleFilter}; use rome_console::fmt::{Formatter, Termcolor}; use rome_console::{markup, Markup}; use rome_diagnostics::termcolor::NoColor; use rome_diagnostics::{Diagnostic, DiagnosticExt, PrintDiagnostic, Severity}; use rome_json_parser::{parse_json, JsonParserOptions}; use rome_json_syntax::TextRange; 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#"{ "foo": "", "foo": "", "foo": "", "bar": "", "bar": "" } "#; let parsed = parse_json(SOURCE, JsonParserOptions::default()); let mut error_ranges: Vec<TextRange> = Vec::new(); let rule_filter = RuleFilter::Rule("nursery", "noDuplicateKeys"); let options = AnalyzerOptions::default(); analyze( &parsed.tree().value().unwrap(), 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(), &[]); } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_json_analyze/src/registry.rs
crates/rome_json_analyze/src/registry.rs
//! Generated file, do not edit by hand, see `xtask/codegen` use rome_analyze::RegistryVisitor; use rome_json_syntax::JsonLanguage; pub fn visit_registry<V: RegistryVisitor<JsonLanguage>>(registry: &mut V) { registry.record_category::<crate::analyzers::Analyzers>(); }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_json_analyze/src/analyzers.rs
crates/rome_json_analyze/src/analyzers.rs
//! Generated file, do not edit by hand, see `xtask/codegen` pub(crate) mod nursery; ::rome_analyze::declare_category! { pub (crate) Analyzers { kind : Lint , groups : [self :: nursery :: Nursery ,] } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_json_analyze/src/analyzers/nursery.rs
crates/rome_json_analyze/src/analyzers/nursery.rs
//! Generated file, do not edit by hand, see `xtask/codegen` use rome_analyze::declare_group; pub(crate) mod no_duplicate_json_keys; declare_group! { pub (crate) Nursery { name : "nursery" , rules : [ self :: no_duplicate_json_keys :: NoDuplicateJsonKeys , ] } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_json_analyze/src/analyzers/nursery/no_duplicate_json_keys.rs
crates/rome_json_analyze/src/analyzers/nursery/no_duplicate_json_keys.rs
use rome_analyze::{context::RuleContext, declare_rule, Ast, Rule, RuleDiagnostic}; use rome_console::markup; use rome_json_syntax::{JsonMemberName, JsonObjectValue, TextRange}; use rome_rowan::{AstNode, AstSeparatedList}; use std::collections::HashMap; declare_rule! { /// Disallow two keys with the same name inside a JSON object. /// /// ## Examples /// /// ### Invalid /// /// ```json,expect_diagnostic /// { /// "title": "New title", /// "title": "Second title" /// } /// ``` /// /// ### Valid /// /// ```json /// { /// "title": "New title", /// "secondTitle": "Second title" /// } /// ``` pub(crate) NoDuplicateJsonKeys { version: "next", name: "noDuplicateJsonKeys", recommended: true, } } pub(crate) struct DuplicatedKeys { /// The fist key, which should be the correct one original_key: JsonMemberName, /// The ranges where the duplicated keys are found duplicated_keys: Vec<TextRange>, } impl Rule for NoDuplicateJsonKeys { type Query = Ast<JsonObjectValue>; type State = DuplicatedKeys; type Signals = Option<Self::State>; type Options = (); fn run(ctx: &RuleContext<Self>) -> Self::Signals { let query = ctx.query(); let mut names = HashMap::<String, Vec<TextRange>>::new(); let mut original_key = None; for (index, member) in query.json_member_list().iter().flatten().enumerate() { let name = member.name().ok()?; if index == 0 { original_key = Some(name.clone()); } let text = name.inner_string_text().ok()?; if let Some(ranges) = names.get_mut(text.text()) { ranges.push(name.range()); } else { names.insert(text.text().to_string(), vec![]); } } let duplicated_keys: Vec<_> = names .into_values() .filter(|ranges| !ranges.is_empty()) .flatten() .collect(); if !duplicated_keys.is_empty() { let Some(original_key) = original_key else { return None}; return Some(DuplicatedKeys { original_key, duplicated_keys, }); } None } fn diagnostic(_ctx: &RuleContext<Self>, state: &Self::State) -> Option<RuleDiagnostic> { let DuplicatedKeys { duplicated_keys, original_key, } = state; let mut diagnostic = RuleDiagnostic::new( rule_category!(), original_key.range(), markup! { "The key "<Emphasis>{{original_key.inner_string_text().ok()?.text()}}</Emphasis>" was already declared." }, ); for range in duplicated_keys { diagnostic = diagnostic.detail( range, markup! { "This where a duplicated key was declared again." }, ); } Some(diagnostic.note( markup! { "If a key is defined multiple times, only the last definition takes effect. Previous definitions are ignored." }, )) } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_json_analyze/tests/spec_tests.rs
crates/rome_json_analyze/tests/spec_tests.rs
use rome_analyze::{AnalysisFilter, AnalyzerAction, ControlFlow, Never, RuleFilter}; use rome_diagnostics::advice::CodeSuggestionAdvice; use rome_diagnostics::{DiagnosticExt, Severity}; use rome_json_parser::{parse_json, JsonParserOptions}; use rome_json_syntax::JsonLanguage; use rome_rowan::AstNode; use rome_test_utils::{ assert_errors_are_absent, code_fix_to_string, create_analyzer_options, diagnostic_to_string, has_bogus_nodes_or_empty_slots, parse_test_path, register_leak_checker, write_analyzer_snapshot, }; use std::{ffi::OsStr, fs::read_to_string, path::Path, slice}; tests_macros::gen_tests! {"tests/specs/**/*.{json}", crate::run_test, "module"} fn run_test(input: &'static str, _: &str, _: &str, _: &str) { register_leak_checker(); let input_file = Path::new(input); let file_name = input_file.file_name().and_then(OsStr::to_str).unwrap(); let (group, rule) = parse_test_path(input_file); if rule == "specs" || rule == "suppression" { panic!("the test file must be placed in the {rule}/<group-name>/<rule-name>/ directory"); } if group == "specs" || group == "suppression" { panic!("the test file must be placed in the {group}/{rule}/<rule-name>/ directory"); } if rome_json_analyze::metadata() .find_rule(group, rule) .is_none() { panic!("could not find rule {group}/{rule}"); } let rule_filter = RuleFilter::Rule(group, rule); let filter = AnalysisFilter { enabled_rules: Some(slice::from_ref(&rule_filter)), ..AnalysisFilter::default() }; let mut snapshot = String::new(); let input_code = read_to_string(input_file) .unwrap_or_else(|err| panic!("failed to read {:?}: {:?}", input_file, err)); let quantity_diagnostics = analyze_and_snap(&mut snapshot, &input_code, filter, file_name, input_file); insta::with_settings!({ prepend_module_to_snapshot => false, snapshot_path => input_file.parent().unwrap(), }, { insta::assert_snapshot!(file_name, snapshot, file_name); }); if input_code.contains("/* should not generate diagnostics */") && quantity_diagnostics > 0 { panic!("This test should not generate diagnostics"); } } pub(crate) fn analyze_and_snap( snapshot: &mut String, input_code: &str, filter: AnalysisFilter, file_name: &str, input_file: &Path, ) -> usize { let parsed = parse_json(input_code, JsonParserOptions::default()); let root = parsed.tree(); let mut diagnostics = Vec::new(); let mut code_fixes = Vec::new(); let options = create_analyzer_options(input_file, &mut diagnostics); let (_, errors) = rome_json_analyze::analyze(&root.value().unwrap(), filter, &options, |event| { if let Some(mut diag) = event.diagnostic() { for action in event.actions() { if !action.is_suppression() { check_code_action(input_file, input_code, &action); diag = diag.add_code_suggestion(CodeSuggestionAdvice::from(action)); } } let error = diag.with_severity(Severity::Warning); diagnostics.push(diagnostic_to_string(file_name, input_code, error)); return ControlFlow::Continue(()); } for action in event.actions() { if !action.is_suppression() { check_code_action(input_file, input_code, &action); code_fixes.push(code_fix_to_string(input_code, action)); } } ControlFlow::<Never>::Continue(()) }); for error in errors { diagnostics.push(diagnostic_to_string(file_name, input_code, error)); } write_analyzer_snapshot( snapshot, input_code, diagnostics.as_slice(), code_fixes.as_slice(), ); diagnostics.len() } fn check_code_action(path: &Path, source: &str, action: &AnalyzerAction<JsonLanguage>) { let (_, text_edit) = action.mutation.as_text_edits().unwrap_or_default(); let output = text_edit.new_string(source); let new_tree = action.mutation.clone().commit(); // Checks that applying the text edits returned by the BatchMutation // returns the same code as printing the modified syntax tree assert_eq!(new_tree.to_string(), output); if has_bogus_nodes_or_empty_slots(&new_tree) { panic!( "modified tree has bogus nodes or empty slots:\n{new_tree:#?} \n\n {}", new_tree ) } // Checks the returned tree contains no missing children node if format!("{new_tree:?}").contains("missing (required)") { panic!("modified tree has missing children:\n{new_tree:#?}") } // Re-parse the modified code and panic if the resulting tree has syntax errors let re_parse = parse_json(&output, JsonParserOptions::default()); assert_errors_are_absent(re_parse.tree().syntax(), re_parse.diagnostics(), path); }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_diagnostics_macros/src/lib.rs
crates/rome_diagnostics_macros/src/lib.rs
use proc_macro::TokenStream; use proc_macro_error::*; use syn::{parse_macro_input, DeriveInput}; mod generate; mod parse; #[proc_macro_derive( Diagnostic, attributes( diagnostic, severity, category, description, message, advice, verbose_advice, location, tags, source ) )] #[proc_macro_error] pub fn derive_diagnostic(input: TokenStream) -> TokenStream { let input = parse_macro_input!(input as DeriveInput); let input = parse::DeriveInput::parse(input); let tokens = generate::generate_diagnostic(input); if false { panic!("{tokens}"); } TokenStream::from(tokens) }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_diagnostics_macros/src/parse.rs
crates/rome_diagnostics_macros/src/parse.rs
use proc_macro2::{Ident, TokenStream}; use proc_macro_error::*; use quote::{quote, ToTokens}; use syn::{ parse::{discouraged::Speculative, Error, Parse, ParseStream, Parser, Result}, punctuated::Punctuated, spanned::Spanned, token::Paren, Generics, Token, }; pub(crate) struct DeriveInput { pub(crate) ident: Ident, pub(crate) generics: Generics, pub(crate) severity: Option<StaticOrDynamic<Ident>>, pub(crate) category: Option<StaticOrDynamic<syn::LitStr>>, pub(crate) description: Option<StaticOrDynamic<StringOrMarkup>>, pub(crate) message: Option<StaticOrDynamic<StringOrMarkup>>, pub(crate) advices: Vec<TokenStream>, pub(crate) verbose_advices: Vec<TokenStream>, pub(crate) location: Vec<(TokenStream, LocationField)>, pub(crate) tags: Option<StaticOrDynamic<Punctuated<Ident, Token![|]>>>, pub(crate) source: Option<TokenStream>, } impl DeriveInput { pub(crate) fn parse(input: syn::DeriveInput) -> Self { let mut result = Self { ident: input.ident, generics: input.generics, severity: None, category: None, description: None, message: None, advices: Vec::new(), verbose_advices: Vec::new(), location: Vec::new(), tags: None, source: None, }; for attr in input.attrs { if attr.path.is_ident("diagnostic") { let tokens = attr.tokens.into(); let attrs = match DiagnosticAttrs::parse.parse(tokens) { Ok(attrs) => attrs, Err(err) => abort!( err.span(), "failed to parse \"diagnostic\" attribute: {}", err ), }; for item in attrs.attrs { match item { DiagnosticAttr::Severity(attr) => { result.severity = Some(StaticOrDynamic::Static(attr.value)); } DiagnosticAttr::Category(attr) => { result.category = Some(StaticOrDynamic::Static(attr.value)); } DiagnosticAttr::Message(MessageAttr::SingleString { value, .. }) => { let value = StringOrMarkup::from(value); result.description = Some(StaticOrDynamic::Static(value.clone())); result.message = Some(StaticOrDynamic::Static(value)); } DiagnosticAttr::Message(MessageAttr::SingleMarkup { markup, .. }) => { let value = StringOrMarkup::from(markup); result.description = Some(StaticOrDynamic::Static(value.clone())); result.message = Some(StaticOrDynamic::Static(value)); } DiagnosticAttr::Message(MessageAttr::Split(attr)) => { for item in attr.attrs { match item { SplitMessageAttr::Description { value, .. } => { result.description = Some(StaticOrDynamic::Static(value.into())); } SplitMessageAttr::Message { markup, .. } => { result.message = Some(StaticOrDynamic::Static(markup.into())); } } } } DiagnosticAttr::Tags(attr) => { result.tags = Some(StaticOrDynamic::Static(attr.tags)); } } } continue; } } let data = match input.data { syn::Data::Struct(data) => data, syn::Data::Enum(data) => abort!( data.enum_token.span(), "enums are not supported by the Diagnostic derive macro" ), syn::Data::Union(data) => abort!( data.union_token.span(), "unions are not supported by the Diagnostic derive macro" ), }; for (index, field) in data.fields.into_iter().enumerate() { let ident = match field.ident { Some(ident) => quote! { #ident }, None => quote! { #index }, }; for attr in field.attrs { if attr.path.is_ident("category") { result.category = Some(StaticOrDynamic::Dynamic(ident.clone())); continue; } if attr.path.is_ident("severity") { result.severity = Some(StaticOrDynamic::Dynamic(ident.clone())); continue; } if attr.path.is_ident("description") { result.description = Some(StaticOrDynamic::Dynamic(ident.clone())); continue; } if attr.path.is_ident("message") { result.message = Some(StaticOrDynamic::Dynamic(ident.clone())); continue; } if attr.path.is_ident("advice") { result.advices.push(ident.clone()); continue; } if attr.path.is_ident("verbose_advice") { result.verbose_advices.push(ident.clone()); continue; } if attr.path.is_ident("location") { let tokens = attr.tokens.into(); let attr = match LocationAttr::parse.parse(tokens) { Ok(attr) => attr, Err(err) => abort!( err.span(), "failed to parse \"location\" attribute: {}", err ), }; result.location.push((ident.clone(), attr.field)); continue; } if attr.path.is_ident("tags") { result.tags = Some(StaticOrDynamic::Dynamic(ident.clone())); continue; } if attr.path.is_ident("source") { result.source = Some(ident.clone()); continue; } } } result } } pub(crate) enum StaticOrDynamic<S> { Static(S), Dynamic(TokenStream), } #[derive(Clone)] pub(crate) enum StringOrMarkup { String(syn::LitStr), Markup(TokenStream), } impl From<syn::LitStr> for StringOrMarkup { fn from(value: syn::LitStr) -> Self { Self::String(value) } } impl From<TokenStream> for StringOrMarkup { fn from(value: TokenStream) -> Self { Self::Markup(value) } } struct DiagnosticAttrs { _paren_token: syn::token::Paren, attrs: Punctuated<DiagnosticAttr, Token![,]>, } impl Parse for DiagnosticAttrs { fn parse(input: ParseStream) -> Result<Self> { let content; Ok(Self { _paren_token: syn::parenthesized!(content in input), attrs: content.parse_terminated(DiagnosticAttr::parse)?, }) } } enum DiagnosticAttr { Severity(SeverityAttr), Category(CategoryAttr), Message(MessageAttr), Tags(TagsAttr), } impl Parse for DiagnosticAttr { fn parse(input: ParseStream) -> Result<Self> { let name: Ident = input.parse()?; if name == "severity" { return Ok(Self::Severity(input.parse()?)); } if name == "category" { return Ok(Self::Category(input.parse()?)); } if name == "message" { return Ok(Self::Message(input.parse()?)); } if name == "tags" { return Ok(Self::Tags(input.parse()?)); } Err(Error::new_spanned(name, "unknown attribute")) } } struct SeverityAttr { _eq_token: Token![=], value: Ident, } impl Parse for SeverityAttr { fn parse(input: ParseStream) -> Result<Self> { Ok(Self { _eq_token: input.parse()?, value: input.parse()?, }) } } struct CategoryAttr { _eq_token: Token![=], value: syn::LitStr, } impl Parse for CategoryAttr { fn parse(input: ParseStream) -> Result<Self> { Ok(Self { _eq_token: input.parse()?, value: input.parse()?, }) } } enum MessageAttr { SingleString { _eq_token: Token![=], value: syn::LitStr, }, SingleMarkup { _paren_token: Paren, markup: TokenStream, }, Split(SplitMessageAttrs), } impl Parse for MessageAttr { fn parse(input: ParseStream) -> Result<Self> { let lookahead = input.lookahead1(); if lookahead.peek(Token![=]) { return Ok(Self::SingleString { _eq_token: input.parse()?, value: input.parse()?, }); } let fork = input.fork(); if let Ok(attr) = fork.parse() { input.advance_to(&fork); return Ok(Self::Split(attr)); } let content; Ok(Self::SingleMarkup { _paren_token: syn::parenthesized!(content in input), markup: content.parse()?, }) } } struct SplitMessageAttrs { _paren_token: syn::token::Paren, attrs: Punctuated<SplitMessageAttr, Token![,]>, } impl Parse for SplitMessageAttrs { fn parse(input: ParseStream) -> Result<Self> { let content; Ok(Self { _paren_token: syn::parenthesized!(content in input), attrs: content.parse_terminated(SplitMessageAttr::parse)?, }) } } enum SplitMessageAttr { Description { _eq_token: Token![=], value: syn::LitStr, }, Message { _paren_token: Paren, markup: TokenStream, }, } impl Parse for SplitMessageAttr { fn parse(input: ParseStream) -> Result<Self> { let name: Ident = input.parse()?; if name == "description" { return Ok(Self::Description { _eq_token: input.parse()?, value: input.parse()?, }); } if name == "message" { let content; return Ok(Self::Message { _paren_token: syn::parenthesized!(content in input), markup: content.parse()?, }); } Err(Error::new_spanned(name, "unknown attribute")) } } struct TagsAttr { _paren_token: Paren, tags: Punctuated<Ident, Token![|]>, } impl Parse for TagsAttr { fn parse(input: ParseStream) -> Result<Self> { let content; Ok(Self { _paren_token: syn::parenthesized!(content in input), tags: content.parse_terminated(Ident::parse)?, }) } } struct LocationAttr { _paren_token: Paren, field: LocationField, } pub(crate) enum LocationField { Resource(Ident), Span(Ident), SourceCode(Ident), } impl Parse for LocationAttr { fn parse(input: ParseStream) -> Result<Self> { let content; let _paren_token = syn::parenthesized!(content in input); let ident: Ident = content.parse()?; let field = if ident == "resource" { LocationField::Resource(ident) } else if ident == "span" { LocationField::Span(ident) } else if ident == "source_code" { LocationField::SourceCode(ident) } else { return Err(Error::new_spanned(ident, "unknown location field")); }; Ok(Self { _paren_token, field, }) } } impl ToTokens for LocationField { fn to_tokens(&self, tokens: &mut TokenStream) { match self { LocationField::Resource(ident) => ident.to_tokens(tokens), LocationField::Span(ident) => ident.to_tokens(tokens), LocationField::SourceCode(ident) => ident.to_tokens(tokens), } } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_diagnostics_macros/src/generate.rs
crates/rome_diagnostics_macros/src/generate.rs
use proc_macro2::{Ident, Span, TokenStream}; use proc_macro_error::*; use quote::quote; use crate::parse::{DeriveInput, StaticOrDynamic, StringOrMarkup}; pub(crate) fn generate_diagnostic(input: DeriveInput) -> TokenStream { let category = generate_category(&input); let severity = generate_severity(&input); let description = generate_description(&input); let message = generate_message(&input); let advices = generate_advices(&input); let verbose_advices = generate_verbose_advices(&input); let location = generate_location(&input); let tags = generate_tags(&input); let source = generate_source(&input); let generic_params = if !input.generics.params.is_empty() { let lt_token = &input.generics.lt_token; let params = &input.generics.params; let gt_token = &input.generics.gt_token; quote! { #lt_token #params #gt_token } } else { quote!() }; let ident = input.ident; let generics = input.generics; quote! { impl #generic_params rome_diagnostics::Diagnostic for #ident #generics { #category #severity #description #message #advices #verbose_advices #location #tags #source } } } fn generate_category(input: &DeriveInput) -> TokenStream { let category = match &input.category { Some(StaticOrDynamic::Static(value)) => quote! { rome_diagnostics::category!(#value) }, Some(StaticOrDynamic::Dynamic(value)) => quote! { self.#value }, None => return quote!(), }; quote! { fn category(&self) -> Option<&'static rome_diagnostics::Category> { Some(#category) } } } fn generate_severity(input: &DeriveInput) -> TokenStream { let severity = match &input.severity { Some(StaticOrDynamic::Static(value)) => quote! { rome_diagnostics::Severity::#value }, Some(StaticOrDynamic::Dynamic(value)) => quote! { self.#value }, None => return quote!(), }; quote! { fn severity(&self) -> rome_diagnostics::Severity { #severity } } } fn generate_description(input: &DeriveInput) -> TokenStream { let description = match &input.description { Some(StaticOrDynamic::Static(StringOrMarkup::String(value))) => { let mut format_string = String::new(); let mut format_params = Vec::new(); let input = value.value(); let mut input = input.as_str(); while let Some(idx) = input.find('{') { let (before, after) = input.split_at(idx); format_string.push_str(before); let after = &after[1..]; format_string.push('{'); if let Some(after) = after.strip_prefix('{') { input = after; continue; } let end = match after.find([':', '}']) { Some(end) => end, None => abort!(value.span(), "failed to parse format string"), }; let (ident, after) = after.split_at(end); let ident = Ident::new(ident, Span::call_site()); format_params.push(quote! { self.#ident }); input = after; } if !input.is_empty() { format_string.push_str(input); } if format_params.is_empty() { quote! { fmt.write_str(#format_string) } } else { quote! { fmt.write_fmt(::std::format_args!(#format_string, #( #format_params ),*)) } } } Some(StaticOrDynamic::Static(StringOrMarkup::Markup(markup))) => quote! { let mut buffer = Vec::new(); let write = rome_diagnostics::termcolor::NoColor::new(&mut buffer); let mut write = rome_diagnostics::console::fmt::Termcolor(write); let mut write = rome_diagnostics::console::fmt::Formatter::new(&mut write); use rome_diagnostics::console as rome_console; write.write_markup(&rome_diagnostics::console::markup!{ #markup }) .map_err(|_| ::std::fmt::Error)?; fmt.write_str(::std::str::from_utf8(&buffer).map_err(|_| ::std::fmt::Error)?) }, Some(StaticOrDynamic::Dynamic(value)) => quote! { fmt.write_fmt(::std::format_args!("{}", self.#value)) }, None => return quote!(), }; quote! { fn description(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { #description } } } fn generate_message(input: &DeriveInput) -> TokenStream { let message = match &input.message { Some(StaticOrDynamic::Static(StringOrMarkup::String(value))) => quote! { fmt.write_str(#value) }, Some(StaticOrDynamic::Static(StringOrMarkup::Markup(markup))) => quote! { use rome_diagnostics::console as rome_console; fmt.write_markup(rome_diagnostics::console::markup!{ #markup }) }, Some(StaticOrDynamic::Dynamic(value)) => quote! { rome_diagnostics::console::fmt::Display::fmt(&self.#value, fmt) }, None => return quote!(), }; quote! { fn message(&self, fmt: &mut rome_diagnostics::console::fmt::Formatter<'_>) -> ::std::io::Result<()> { #message } } } fn generate_advices(input: &DeriveInput) -> TokenStream { if input.advices.is_empty() { return quote!(); } let advices = input.advices.iter(); quote! { fn advices(&self, visitor: &mut dyn rome_diagnostics::Visit) -> ::std::io::Result<()> { #( rome_diagnostics::Advices::record(&self.#advices, visitor)?; )* Ok(()) } } } fn generate_verbose_advices(input: &DeriveInput) -> TokenStream { if input.verbose_advices.is_empty() { return quote!(); } let verbose_advices = input.verbose_advices.iter(); quote! { fn verbose_advices(&self, visitor: &mut dyn rome_diagnostics::Visit) -> ::std::io::Result<()> { #( rome_diagnostics::Advices::record(&self.#verbose_advices, visitor)?; )* Ok(()) } } } fn generate_location(input: &DeriveInput) -> TokenStream { if input.location.is_empty() { return quote!(); } let field = input.location.iter().map(|(field, _)| field); let method = input.location.iter().map(|(_, method)| method); quote! { fn location(&self) -> rome_diagnostics::Location<'_> { rome_diagnostics::Location::builder() #( .#method(&self.#field) )* .build() } } } fn generate_tags(input: &DeriveInput) -> TokenStream { let tags = match &input.tags { Some(StaticOrDynamic::Static(value)) => { let values = value.iter(); quote! { #( rome_diagnostics::DiagnosticTags::#values )|* } } Some(StaticOrDynamic::Dynamic(value)) => quote! { self.#value }, None => return quote!(), }; quote! { fn tags(&self) -> rome_diagnostics::DiagnosticTags { #tags } } } fn generate_source(input: &DeriveInput) -> TokenStream { match &input.source { Some(value) => quote! { fn source(&self) -> Option<&dyn rome_diagnostics::Diagnostic> { self.#value.as_deref() } }, None => quote!(), } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_css_syntax/src/lib.rs
crates/rome_css_syntax/src/lib.rs
#[macro_use] mod generated; mod syntax_node; pub use self::generated::*; pub use rome_rowan::{ SyntaxNodeText, TextLen, TextRange, TextSize, TokenAtOffset, TriviaPieceKind, WalkEvent, }; pub use syntax_node::*; use crate::CssSyntaxKind::*; use rome_rowan::RawSyntaxKind; impl From<u16> for CssSyntaxKind { fn from(d: u16) -> CssSyntaxKind { assert!(d <= (CssSyntaxKind::__LAST as u16)); unsafe { std::mem::transmute::<u16, CssSyntaxKind>(d) } } } impl From<CssSyntaxKind> for u16 { fn from(k: CssSyntaxKind) -> u16 { k as u16 } } impl CssSyntaxKind { pub fn is_trivia(self) -> bool { matches!( self, CssSyntaxKind::NEWLINE | CssSyntaxKind::WHITESPACE | CssSyntaxKind::COMMENT ) } /// Returns `true` for any contextual (await) or non-contextual keyword #[inline] pub const fn is_keyword(self) -> bool { true } /// Returns `true` for contextual keywords (excluding strict mode contextual keywords) #[inline] pub const fn is_contextual_keyword(self) -> bool { (self as u16) >= (ALICEBLUE_KW as u16) && (self as u16) <= (CSS_SELECTOR as u16) } /// Returns true for all non-contextual keywords (includes future reserved keywords) #[inline] pub const fn is_non_contextual_keyword(self) -> bool { self.is_keyword() && !self.is_contextual_keyword() } } impl rome_rowan::SyntaxKind for CssSyntaxKind { const TOMBSTONE: Self = CssSyntaxKind::TOMBSTONE; const EOF: Self = EOF; fn is_bogus(&self) -> bool { matches!(self, CSS_BOGUS) } fn to_bogus(&self) -> Self { todo!() } #[inline] fn to_raw(&self) -> RawSyntaxKind { RawSyntaxKind(*self as u16) } #[inline] fn from_raw(raw: RawSyntaxKind) -> Self { Self::from(raw.0) } fn is_root(&self) -> bool { matches!(self, CSS_ROOT) } #[inline] fn is_list(&self) -> bool { CssSyntaxKind::is_list(*self) } fn to_string(&self) -> Option<&'static str> { CssSyntaxKind::to_string(self) } } impl TryFrom<CssSyntaxKind> for TriviaPieceKind { type Error = (); fn try_from(value: CssSyntaxKind) -> Result<Self, Self::Error> { if value.is_trivia() { match value { CssSyntaxKind::NEWLINE => Ok(TriviaPieceKind::Newline), CssSyntaxKind::WHITESPACE => Ok(TriviaPieceKind::Whitespace), CssSyntaxKind::COMMENT => Ok(TriviaPieceKind::SingleLineComment), CssSyntaxKind::MULTILINE_COMMENT => Ok(TriviaPieceKind::MultiLineComment), _ => unreachable!("Not Trivia"), } } else { Err(()) } } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_css_syntax/src/syntax_node.rs
crates/rome_css_syntax/src/syntax_node.rs
//! This module defines the Concrete Syntax Tree used by Rome. //! //! The tree is entirely lossless, whitespace, comments, and errors are preserved. //! It also provides traversal methods including parent, children, and siblings of nodes. //! //! This is a simple wrapper around the `rowan` crate which does most of the heavy lifting and is language agnostic. use crate::{CssRoot, CssSyntaxKind}; use rome_rowan::Language; #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] pub struct CssLanguage; impl Language for CssLanguage { type Kind = CssSyntaxKind; type Root = CssRoot; } pub type CssSyntaxNode = rome_rowan::SyntaxNode<CssLanguage>; pub type CssSyntaxToken = rome_rowan::SyntaxToken<CssLanguage>; pub type CssSyntaxElement = rome_rowan::SyntaxElement<CssLanguage>; pub type CssSyntaxNodeChildren = rome_rowan::SyntaxNodeChildren<CssLanguage>; pub type CssSyntaxElementChildren = rome_rowan::SyntaxElementChildren<CssLanguage>; pub type CssSyntaxList = rome_rowan::SyntaxList<CssLanguage>;
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_css_syntax/src/generated.rs
crates/rome_css_syntax/src/generated.rs
#[rustfmt::skip] pub(super) mod nodes; #[rustfmt::skip] pub(super) mod nodes_mut; #[rustfmt::skip] pub mod macros; #[macro_use] pub mod kind; pub use kind::*; pub use nodes::*;
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_css_syntax/src/generated/nodes_mut.rs
crates/rome_css_syntax/src/generated/nodes_mut.rs
//! Generated file, do not edit by hand, see `xtask/codegen` use crate::{generated::nodes::*, CssSyntaxToken as SyntaxToken}; use rome_rowan::AstNode; use std::iter::once; impl CssAnyFunction { pub fn with_css_simple_function(self, element: CssSimpleFunction) -> Self { Self::unwrap_cast( self.syntax .splice_slots(0usize..=0usize, once(Some(element.into_syntax().into()))), ) } } impl CssAtKeyframes { pub fn with_at_token(self, element: SyntaxToken) -> Self { Self::unwrap_cast( self.syntax .splice_slots(0usize..=0usize, once(Some(element.into()))), ) } pub fn with_keyframes_token(self, element: SyntaxToken) -> Self { Self::unwrap_cast( self.syntax .splice_slots(1usize..=1usize, once(Some(element.into()))), ) } pub fn with_name(self, element: CssIdentifier) -> Self { Self::unwrap_cast( self.syntax .splice_slots(2usize..=2usize, once(Some(element.into_syntax().into()))), ) } pub fn with_css_string(self, element: CssString) -> Self { Self::unwrap_cast( self.syntax .splice_slots(3usize..=3usize, once(Some(element.into_syntax().into()))), ) } pub fn with_body(self, element: CssAtKeyframesBody) -> Self { Self::unwrap_cast( self.syntax .splice_slots(4usize..=4usize, once(Some(element.into_syntax().into()))), ) } } impl CssAtKeyframesBody { pub fn with_l_curly_token(self, element: SyntaxToken) -> Self { Self::unwrap_cast( self.syntax .splice_slots(0usize..=0usize, once(Some(element.into()))), ) } pub fn with_items(self, element: CssAtKeyframesItemList) -> Self { Self::unwrap_cast( self.syntax .splice_slots(1usize..=1usize, once(Some(element.into_syntax().into()))), ) } pub fn with_r_curly_token(self, element: SyntaxToken) -> Self { Self::unwrap_cast( self.syntax .splice_slots(2usize..=2usize, once(Some(element.into()))), ) } } impl CssAtMedia { pub fn with_at_token(self, element: SyntaxToken) -> Self { Self::unwrap_cast( self.syntax .splice_slots(0usize..=0usize, once(Some(element.into()))), ) } pub fn with_media_token(self, element: SyntaxToken) -> Self { Self::unwrap_cast( self.syntax .splice_slots(1usize..=1usize, once(Some(element.into()))), ) } pub fn with_query_list(self, element: CssAtMediaQueryList) -> Self { Self::unwrap_cast( self.syntax .splice_slots(2usize..=2usize, once(Some(element.into_syntax().into()))), ) } pub fn with_l_curly_token(self, element: SyntaxToken) -> Self { Self::unwrap_cast( self.syntax .splice_slots(3usize..=3usize, once(Some(element.into()))), ) } pub fn with_body(self, element: AnyCssRule) -> Self { Self::unwrap_cast( self.syntax .splice_slots(4usize..=4usize, once(Some(element.into_syntax().into()))), ) } pub fn with_r_curly_token(self, element: SyntaxToken) -> Self { Self::unwrap_cast( self.syntax .splice_slots(5usize..=5usize, once(Some(element.into()))), ) } } impl CssAtMediaQuery { pub fn with_condition_token(self, element: SyntaxToken) -> Self { Self::unwrap_cast( self.syntax .splice_slots(0usize..=0usize, once(Some(element.into()))), ) } pub fn with_or_token(self, element: SyntaxToken) -> Self { Self::unwrap_cast( self.syntax .splice_slots(1usize..=1usize, once(Some(element.into()))), ) } pub fn with_only_token(self, element: Option<SyntaxToken>) -> Self { Self::unwrap_cast( self.syntax .splice_slots(2usize..=2usize, once(element.map(|element| element.into()))), ) } pub fn with_ty(self, element: AnyCssAtMediaQueryType) -> Self { Self::unwrap_cast( self.syntax .splice_slots(3usize..=3usize, once(Some(element.into_syntax().into()))), ) } pub fn with_consequent(self, element: Option<CssAtMediaQueryConsequent>) -> Self { Self::unwrap_cast(self.syntax.splice_slots( 4usize..=4usize, once(element.map(|element| element.into_syntax().into())), )) } } impl CssAtMediaQueryConsequent { pub fn with_and_token(self, element: SyntaxToken) -> Self { Self::unwrap_cast( self.syntax .splice_slots(0usize..=0usize, once(Some(element.into()))), ) } pub fn with_condition_token(self, element: Option<SyntaxToken>) -> Self { Self::unwrap_cast( self.syntax .splice_slots(1usize..=1usize, once(element.map(|element| element.into()))), ) } pub fn with_ty(self, element: AnyCssAtMediaQueryType) -> Self { Self::unwrap_cast( self.syntax .splice_slots(2usize..=2usize, once(Some(element.into_syntax().into()))), ) } } impl CssAtMediaQueryFeature { pub fn with_l_paren_token(self, element: SyntaxToken) -> Self { Self::unwrap_cast( self.syntax .splice_slots(0usize..=0usize, once(Some(element.into()))), ) } pub fn with_feature(self, element: AnyCssAtMediaQueryFeatureType) -> Self { Self::unwrap_cast( self.syntax .splice_slots(1usize..=1usize, once(Some(element.into_syntax().into()))), ) } pub fn with_r_paren_token(self, element: SyntaxToken) -> Self { Self::unwrap_cast( self.syntax .splice_slots(2usize..=2usize, once(Some(element.into()))), ) } } impl CssAtMediaQueryFeatureBoolean { pub fn with_css_identifier(self, element: CssIdentifier) -> Self { Self::unwrap_cast( self.syntax .splice_slots(0usize..=0usize, once(Some(element.into_syntax().into()))), ) } } impl CssAtMediaQueryFeatureCompare { pub fn with_name(self, element: CssIdentifier) -> Self { Self::unwrap_cast( self.syntax .splice_slots(0usize..=0usize, once(Some(element.into_syntax().into()))), ) } pub fn with_range(self, element: CssAtMediaQueryRange) -> Self { Self::unwrap_cast( self.syntax .splice_slots(1usize..=1usize, once(Some(element.into_syntax().into()))), ) } pub fn with_value(self, element: AnyCssValue) -> Self { Self::unwrap_cast( self.syntax .splice_slots(2usize..=2usize, once(Some(element.into_syntax().into()))), ) } } impl CssAtMediaQueryFeaturePlain { pub fn with_name(self, element: CssIdentifier) -> Self { Self::unwrap_cast( self.syntax .splice_slots(0usize..=0usize, once(Some(element.into_syntax().into()))), ) } pub fn with_colon_token(self, element: SyntaxToken) -> Self { Self::unwrap_cast( self.syntax .splice_slots(1usize..=1usize, once(Some(element.into()))), ) } pub fn with_value(self, element: AnyCssValue) -> Self { Self::unwrap_cast( self.syntax .splice_slots(2usize..=2usize, once(Some(element.into_syntax().into()))), ) } } impl CssAtMediaQueryFeatureRange { pub fn with_first_value(self, element: AnyCssValue) -> Self { Self::unwrap_cast( self.syntax .splice_slots(0usize..=0usize, once(Some(element.into_syntax().into()))), ) } pub fn with_first_range(self, element: CssAtMediaQueryRange) -> Self { Self::unwrap_cast( self.syntax .splice_slots(1usize..=1usize, once(Some(element.into_syntax().into()))), ) } pub fn with_name(self, element: CssIdentifier) -> Self { Self::unwrap_cast( self.syntax .splice_slots(2usize..=2usize, once(Some(element.into_syntax().into()))), ) } pub fn with_second_value(self, element: AnyCssValue) -> Self { Self::unwrap_cast( self.syntax .splice_slots(3usize..=3usize, once(Some(element.into_syntax().into()))), ) } pub fn with_second_range(self, element: CssAtMediaQueryRange) -> Self { Self::unwrap_cast( self.syntax .splice_slots(4usize..=4usize, once(Some(element.into_syntax().into()))), ) } } impl CssAtMediaQueryRange { pub fn with_r_angle_token(self, element: SyntaxToken) -> Self { Self::unwrap_cast( self.syntax .splice_slots(0usize..=0usize, once(Some(element.into()))), ) } pub fn with_l_angle_token(self, element: SyntaxToken) -> Self { Self::unwrap_cast( self.syntax .splice_slots(1usize..=1usize, once(Some(element.into()))), ) } pub fn with_greater_than_equal_token(self, element: SyntaxToken) -> Self { Self::unwrap_cast( self.syntax .splice_slots(2usize..=2usize, once(Some(element.into()))), ) } pub fn with_less_than_equal_token(self, element: SyntaxToken) -> Self { Self::unwrap_cast( self.syntax .splice_slots(3usize..=3usize, once(Some(element.into()))), ) } } impl CssAttribute { pub fn with_l_brack_token(self, element: SyntaxToken) -> Self { Self::unwrap_cast( self.syntax .splice_slots(0usize..=0usize, once(Some(element.into()))), ) } pub fn with_attribute_name(self, element: CssAttributeName) -> Self { Self::unwrap_cast( self.syntax .splice_slots(1usize..=1usize, once(Some(element.into_syntax().into()))), ) } pub fn with_attribute_meta(self, element: Option<CssAttributeMeta>) -> Self { Self::unwrap_cast(self.syntax.splice_slots( 2usize..=2usize, once(element.map(|element| element.into_syntax().into())), )) } pub fn with_r_brack_token(self, element: SyntaxToken) -> Self { Self::unwrap_cast( self.syntax .splice_slots(3usize..=3usize, once(Some(element.into()))), ) } } impl CssAttributeMatcher { pub fn with_matcher_type_token(self, element: SyntaxToken) -> Self { Self::unwrap_cast( self.syntax .splice_slots(0usize..=0usize, once(Some(element.into()))), ) } pub fn with_exactly_or_hyphen_token(self, element: SyntaxToken) -> Self { Self::unwrap_cast( self.syntax .splice_slots(1usize..=1usize, once(Some(element.into()))), ) } pub fn with_prefix_token(self, element: SyntaxToken) -> Self { Self::unwrap_cast( self.syntax .splice_slots(2usize..=2usize, once(Some(element.into()))), ) } pub fn with_suffix_token(self, element: SyntaxToken) -> Self { Self::unwrap_cast( self.syntax .splice_slots(3usize..=3usize, once(Some(element.into()))), ) } pub fn with_times_assign_token(self, element: SyntaxToken) -> Self { Self::unwrap_cast( self.syntax .splice_slots(4usize..=4usize, once(Some(element.into()))), ) } pub fn with_eq_token(self, element: SyntaxToken) -> Self { Self::unwrap_cast( self.syntax .splice_slots(5usize..=5usize, once(Some(element.into()))), ) } pub fn with_matcher_name(self, element: CssString) -> Self { Self::unwrap_cast( self.syntax .splice_slots(6usize..=6usize, once(Some(element.into_syntax().into()))), ) } pub fn with_css_identifier(self, element: CssIdentifier) -> Self { Self::unwrap_cast( self.syntax .splice_slots(7usize..=7usize, once(Some(element.into_syntax().into()))), ) } } impl CssAttributeMeta { pub fn with_attribute_matcher(self, element: Option<CssAttributeMatcher>) -> Self { Self::unwrap_cast(self.syntax.splice_slots( 0usize..=0usize, once(element.map(|element| element.into_syntax().into())), )) } pub fn with_attribute_modifier(self, element: Option<CssAttributeModifier>) -> Self { Self::unwrap_cast(self.syntax.splice_slots( 1usize..=1usize, once(element.map(|element| element.into_syntax().into())), )) } } impl CssAttributeModifier { pub fn with_i_token(self, element: SyntaxToken) -> Self { Self::unwrap_cast( self.syntax .splice_slots(0usize..=0usize, once(Some(element.into()))), ) } } impl CssAttributeName { pub fn with_css_string(self, element: CssString) -> Self { Self::unwrap_cast( self.syntax .splice_slots(0usize..=0usize, once(Some(element.into_syntax().into()))), ) } } impl CssAttributeSelectorPattern { pub fn with_name(self, element: CssIdentifier) -> Self { Self::unwrap_cast( self.syntax .splice_slots(0usize..=0usize, once(Some(element.into_syntax().into()))), ) } pub fn with_attribute_list(self, element: CssAttributeList) -> Self { Self::unwrap_cast( self.syntax .splice_slots(1usize..=1usize, once(Some(element.into_syntax().into()))), ) } } impl CssBlock { pub fn with_l_curly_token(self, element: SyntaxToken) -> Self { Self::unwrap_cast( self.syntax .splice_slots(0usize..=0usize, once(Some(element.into()))), ) } pub fn with_declaration_list(self, element: CssDeclarationList) -> Self { Self::unwrap_cast( self.syntax .splice_slots(1usize..=1usize, once(Some(element.into_syntax().into()))), ) } pub fn with_r_curly_token(self, element: SyntaxToken) -> Self { Self::unwrap_cast( self.syntax .splice_slots(2usize..=2usize, once(Some(element.into()))), ) } } impl CssClassSelectorPattern { pub fn with_dot_token(self, element: SyntaxToken) -> Self { Self::unwrap_cast( self.syntax .splice_slots(0usize..=0usize, once(Some(element.into()))), ) } pub fn with_name(self, element: CssIdentifier) -> Self { Self::unwrap_cast( self.syntax .splice_slots(1usize..=1usize, once(Some(element.into_syntax().into()))), ) } } impl CssCombinatorSelectorPattern { pub fn with_left(self, element: AnyCssSelectorPattern) -> Self { Self::unwrap_cast( self.syntax .splice_slots(0usize..=0usize, once(Some(element.into_syntax().into()))), ) } pub fn with_combinator_token(self, element: SyntaxToken) -> Self { Self::unwrap_cast( self.syntax .splice_slots(1usize..=1usize, once(Some(element.into()))), ) } pub fn with_plus_token(self, element: SyntaxToken) -> Self { Self::unwrap_cast( self.syntax .splice_slots(2usize..=2usize, once(Some(element.into()))), ) } pub fn with_bitwise_not_token(self, element: SyntaxToken) -> Self { Self::unwrap_cast( self.syntax .splice_slots(3usize..=3usize, once(Some(element.into()))), ) } pub fn with_css_space_literal_token(self, element: SyntaxToken) -> Self { Self::unwrap_cast( self.syntax .splice_slots(4usize..=4usize, once(Some(element.into()))), ) } pub fn with_right(self, element: AnyCssSelectorPattern) -> Self { Self::unwrap_cast( self.syntax .splice_slots(5usize..=5usize, once(Some(element.into_syntax().into()))), ) } } impl CssCustomProperty { pub fn with_value_token(self, element: SyntaxToken) -> Self { Self::unwrap_cast( self.syntax .splice_slots(0usize..=0usize, once(Some(element.into()))), ) } } impl CssDeclaration { pub fn with_name(self, element: CssIdentifier) -> Self { Self::unwrap_cast( self.syntax .splice_slots(0usize..=0usize, once(Some(element.into_syntax().into()))), ) } pub fn with_css_custom_property(self, element: CssCustomProperty) -> Self { Self::unwrap_cast( self.syntax .splice_slots(1usize..=1usize, once(Some(element.into_syntax().into()))), ) } pub fn with_colon_token(self, element: SyntaxToken) -> Self { Self::unwrap_cast( self.syntax .splice_slots(2usize..=2usize, once(Some(element.into()))), ) } pub fn with_value(self, element: AnyCssValue) -> Self { Self::unwrap_cast( self.syntax .splice_slots(3usize..=3usize, once(Some(element.into_syntax().into()))), ) } pub fn with_important(self, element: Option<CssDeclarationImportant>) -> Self { Self::unwrap_cast(self.syntax.splice_slots( 4usize..=4usize, once(element.map(|element| element.into_syntax().into())), )) } } impl CssDeclarationImportant { pub fn with_excl_token(self, element: SyntaxToken) -> Self { Self::unwrap_cast( self.syntax .splice_slots(0usize..=0usize, once(Some(element.into()))), ) } pub fn with_important_token(self, element: SyntaxToken) -> Self { Self::unwrap_cast( self.syntax .splice_slots(1usize..=1usize, once(Some(element.into()))), ) } } impl CssDimension { pub fn with_value(self, element: CssNumber) -> Self { Self::unwrap_cast( self.syntax .splice_slots(0usize..=0usize, once(Some(element.into_syntax().into()))), ) } pub fn with_unit(self, element: CssIdentifier) -> Self { Self::unwrap_cast( self.syntax .splice_slots(1usize..=1usize, once(Some(element.into_syntax().into()))), ) } } impl CssIdSelectorPattern { pub fn with_hash_token(self, element: SyntaxToken) -> Self { Self::unwrap_cast( self.syntax .splice_slots(0usize..=0usize, once(Some(element.into()))), ) } pub fn with_name(self, element: CssIdentifier) -> Self { Self::unwrap_cast( self.syntax .splice_slots(1usize..=1usize, once(Some(element.into_syntax().into()))), ) } } impl CssIdentifier { pub fn with_value_token(self, element: SyntaxToken) -> Self { Self::unwrap_cast( self.syntax .splice_slots(0usize..=0usize, once(Some(element.into()))), ) } } impl CssKeyframesBlock { pub fn with_selectors(self, element: CssKeyframesSelectorList) -> Self { Self::unwrap_cast( self.syntax .splice_slots(0usize..=0usize, once(Some(element.into_syntax().into()))), ) } pub fn with_l_curly_token(self, element: SyntaxToken) -> Self { Self::unwrap_cast( self.syntax .splice_slots(1usize..=1usize, once(Some(element.into()))), ) } pub fn with_declarations(self, element: CssDeclarationList) -> Self { Self::unwrap_cast( self.syntax .splice_slots(2usize..=2usize, once(Some(element.into_syntax().into()))), ) } pub fn with_r_curly_token(self, element: SyntaxToken) -> Self { Self::unwrap_cast( self.syntax .splice_slots(3usize..=3usize, once(Some(element.into()))), ) } } impl CssKeyframesSelector { pub fn with_from_token(self, element: SyntaxToken) -> Self { Self::unwrap_cast( self.syntax .splice_slots(0usize..=0usize, once(Some(element.into()))), ) } pub fn with_to_token(self, element: SyntaxToken) -> Self { Self::unwrap_cast( self.syntax .splice_slots(1usize..=1usize, once(Some(element.into()))), ) } pub fn with_css_percentage(self, element: CssPercentage) -> Self { Self::unwrap_cast( self.syntax .splice_slots(2usize..=2usize, once(Some(element.into_syntax().into()))), ) } } impl CssNumber { pub fn with_value_token(self, element: SyntaxToken) -> Self { Self::unwrap_cast( self.syntax .splice_slots(0usize..=0usize, once(Some(element.into()))), ) } } impl CssParameter { pub fn with_any_css_value(self, element: AnyCssValue) -> Self { Self::unwrap_cast( self.syntax .splice_slots(0usize..=0usize, once(Some(element.into_syntax().into()))), ) } } impl CssPercentage { pub fn with_value(self, element: CssNumber) -> Self { Self::unwrap_cast( self.syntax .splice_slots(0usize..=0usize, once(Some(element.into_syntax().into()))), ) } pub fn with_reminder_token(self, element: SyntaxToken) -> Self { Self::unwrap_cast( self.syntax .splice_slots(1usize..=1usize, once(Some(element.into()))), ) } } impl CssPseudoClassSelectorPattern { pub fn with_colon_token(self, element: SyntaxToken) -> Self { Self::unwrap_cast( self.syntax .splice_slots(0usize..=0usize, once(Some(element.into()))), ) } pub fn with_name(self, element: CssIdentifier) -> Self { Self::unwrap_cast( self.syntax .splice_slots(1usize..=1usize, once(Some(element.into_syntax().into()))), ) } pub fn with_parameters(self, element: Option<CssPseudoClassSelectorPatternParameters>) -> Self { Self::unwrap_cast(self.syntax.splice_slots( 2usize..=2usize, once(element.map(|element| element.into_syntax().into())), )) } } impl CssPseudoClassSelectorPatternParameters { pub fn with_l_paren_token(self, element: SyntaxToken) -> Self { Self::unwrap_cast( self.syntax .splice_slots(0usize..=0usize, once(Some(element.into()))), ) } pub fn with_parameter(self, element: AnyCssValue) -> Self { Self::unwrap_cast( self.syntax .splice_slots(1usize..=1usize, once(Some(element.into_syntax().into()))), ) } pub fn with_r_paren_token(self, element: SyntaxToken) -> Self { Self::unwrap_cast( self.syntax .splice_slots(2usize..=2usize, once(Some(element.into()))), ) } } impl CssRatio { pub fn with_numerator(self, element: CssNumber) -> Self { Self::unwrap_cast( self.syntax .splice_slots(0usize..=0usize, once(Some(element.into_syntax().into()))), ) } pub fn with_denominator(self, element: CssNumber) -> Self { Self::unwrap_cast( self.syntax .splice_slots(1usize..=1usize, once(Some(element.into_syntax().into()))), ) } } impl CssRoot { pub fn with_rules(self, element: CssRuleList) -> Self { Self::unwrap_cast( self.syntax .splice_slots(0usize..=0usize, once(Some(element.into_syntax().into()))), ) } pub fn with_eof_token(self, element: SyntaxToken) -> Self { Self::unwrap_cast( self.syntax .splice_slots(1usize..=1usize, once(Some(element.into()))), ) } } impl CssRule { pub fn with_prelude(self, element: CssSelectorList) -> Self { Self::unwrap_cast( self.syntax .splice_slots(0usize..=0usize, once(Some(element.into_syntax().into()))), ) } pub fn with_block(self, element: CssBlock) -> Self { Self::unwrap_cast( self.syntax .splice_slots(1usize..=1usize, once(Some(element.into_syntax().into()))), ) } } impl CssSelector { pub fn with_pattern_list(self, element: CssAnySelectorPatternList) -> Self { Self::unwrap_cast( self.syntax .splice_slots(0usize..=0usize, once(Some(element.into_syntax().into()))), ) } } impl CssSimpleFunction { pub fn with_name(self, element: CssIdentifier) -> Self { Self::unwrap_cast( self.syntax .splice_slots(0usize..=0usize, once(Some(element.into_syntax().into()))), ) } pub fn with_l_paren_token(self, element: SyntaxToken) -> Self { Self::unwrap_cast( self.syntax .splice_slots(1usize..=1usize, once(Some(element.into()))), ) } pub fn with_items(self, element: CssParameterList) -> Self { Self::unwrap_cast( self.syntax .splice_slots(2usize..=2usize, once(Some(element.into_syntax().into()))), ) } pub fn with_r_paren_token(self, element: SyntaxToken) -> Self { Self::unwrap_cast( self.syntax .splice_slots(3usize..=3usize, once(Some(element.into()))), ) } } impl CssString { pub fn with_value_token(self, element: SyntaxToken) -> Self { Self::unwrap_cast( self.syntax .splice_slots(0usize..=0usize, once(Some(element.into()))), ) } } impl CssTypeSelectorPattern { pub fn with_ident(self, element: CssIdentifier) -> Self { Self::unwrap_cast( self.syntax .splice_slots(0usize..=0usize, once(Some(element.into_syntax().into()))), ) } } impl CssUniversalSelectorPattern { pub fn with_star_token(self, element: SyntaxToken) -> Self { Self::unwrap_cast( self.syntax .splice_slots(0usize..=0usize, once(Some(element.into()))), ) } } impl CssVarFunction { pub fn with_var_token(self, element: SyntaxToken) -> Self { Self::unwrap_cast( self.syntax .splice_slots(0usize..=0usize, once(Some(element.into()))), ) } pub fn with_l_paren_token(self, element: SyntaxToken) -> Self { Self::unwrap_cast( self.syntax .splice_slots(1usize..=1usize, once(Some(element.into()))), ) } pub fn with_property(self, element: CssCustomProperty) -> Self { Self::unwrap_cast( self.syntax .splice_slots(2usize..=2usize, once(Some(element.into_syntax().into()))), ) } pub fn with_value(self, element: Option<CssVarFunctionValue>) -> Self { Self::unwrap_cast(self.syntax.splice_slots( 3usize..=3usize, once(element.map(|element| element.into_syntax().into())), )) } pub fn with_r_paren_token(self, element: SyntaxToken) -> Self { Self::unwrap_cast( self.syntax .splice_slots(4usize..=4usize, once(Some(element.into()))), ) } } impl CssVarFunctionValue { pub fn with_comma_token(self, element: SyntaxToken) -> Self { Self::unwrap_cast( self.syntax .splice_slots(0usize..=0usize, once(Some(element.into()))), ) } pub fn with_value(self, element: CssIdentifier) -> Self { Self::unwrap_cast( self.syntax .splice_slots(1usize..=1usize, once(Some(element.into_syntax().into()))), ) } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_css_syntax/src/generated/kind.rs
crates/rome_css_syntax/src/generated/kind.rs
//! Generated file, do not edit by hand, see `xtask/codegen` #![allow(clippy::all)] #![allow(bad_style, missing_docs, unreachable_pub)] #[doc = r" The kind of syntax node, e.g. `IDENT`, `FUNCTION_KW`, or `FOR_STMT`."] #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] #[repr(u16)] pub enum CssSyntaxKind { #[doc(hidden)] TOMBSTONE, #[doc = r" Marks the end of the file.May have trivia attached"] EOF, SEMICOLON, COMMA, L_PAREN, R_PAREN, L_CURLY, R_CURLY, L_BRACK, R_BRACK, L_ANGLE, R_ANGLE, TILDE, HASH, AMP, PIPE, PLUS, STAR, SLASH, CARET, PERCENT, DOT, COLON, EQ, BANG, NEQ, MINUS, LTEQ, GTEQ, PLUSEQ, PIPEEQ, AMPEQ, CARETEQ, SLASHEQ, STAREQ, PERCENTEQ, AT, DOLLAR_EQ, TILDE_EQ, CDC, CDO, ALICEBLUE_KW, ANTIQUEWHITE_KW, AQUA_KW, AQUAMARINE_KW, AZURE_KW, BEIGE_KW, BISQUE_KW, BLACK_KW, BLANCHEDALMOND_KW, BLUE_KW, BLUEVIOLET_KW, BROWN_KW, BURLYWOOD_KW, CADETBLUE_KW, CHARTREUSE_KW, CHOCOLATE_KW, CORAL_KW, CORNFLOWERBLUE_KW, CORNSILK_KW, CRIMSON_KW, CYAN_KW, DARKBLUE_KW, DARKCYAN_KW, DARKGOLDENROD_KW, DARKGRAY_KW, DARKGREEN_KW, DARKKHAKI_KW, DARKMAGENTA_KW, DARKOLIVEGREEN_KW, DARKORANGE_KW, DARKORCHID_KW, DARKRED_KW, DARKSALMON_KW, DARKSEAGREEN_KW, DARKSLATEBLUE_KW, DARKSLATEGRAY_KW, DARKTURQUOISE_KW, DARKVIOLET_KW, DEEPPINK_KW, DEEPSKYBLUE_KW, DIMGRAY_KW, DODGERBLUE_KW, FIREBRICK_KW, FLORALWHITE_KW, FORESTGREEN_KW, FUCHSIA_KW, GAINSBORO_KW, GHOSTWHITE_KW, GOLD_KW, GOLDENROD_KW, GRAY_KW, GREEN_KW, GREENYELLOW_KW, HONEYDEW_KW, HOTPINK_KW, INDIANRED_KW, INDIGO_KW, IVORY_KW, KHAKI_KW, LAVENDER_KW, LAVENDERBLUSH_KW, LAWNGREEN_KW, LEMONCHIFFON_KW, LIGHTBLUE_KW, LIGHTCORAL_KW, LIGHTCYAN_KW, LIGHTGOLDENRODYELLOW_KW, LIGHTGREEN_KW, LIGHTGREY_KW, LIGHTPINK_KW, LIGHTSALMON_KW, LIGHTSEAGREEN_KW, LIGHTSKYBLUE_KW, LIGHTSLATEGRAY_KW, LIGHTSTEELBLUE_KW, LIGHTYELLOW_KW, LIME_KW, LIMEGREEN_KW, LINEN_KW, MAGENTA_KW, MAROON_KW, MEDIUMAQUAMARINE_KW, MEDIUMBLUE_KW, MEDIUMORCHID_KW, MEDIUMPURPLE_KW, MEDIUMSEAGREEN_KW, MEDIUMSLATEBLUE_KW, MEDIUMSPRINGGREEN_KW, MEDIUMTURQUOISE_KW, MEDIUMVIOLETRED_KW, MIDNIGHTBLUE_KW, MINTCREAM_KW, MISTYROSE_KW, MOCCASIN_KW, NAVAJOWHITE_KW, NAVY_KW, NAVYBLUE_KW, OLDLACE_KW, OLIVE_KW, OLIVEDRAB_KW, ORANGE_KW, ORANGERED_KW, ORCHID_KW, PALEGOLDENROD_KW, PALEGREEN_KW, PALETURQUOISE_KW, PALEVIOLETRED_KW, PAPAYAWHIP_KW, PEACHPUFF_KW, PERU_KW, PINK_KW, PLUM_KW, POWDERBLUE_KW, PURPLE_KW, RED_KW, ROSYBROWN_KW, ROYALBLUE_KW, SADDLEBROWN_KW, SALMON_KW, SANDYBROWN_KW, SEAGREEN_KW, SEASHELL_KW, SIENNA_KW, SILVER_KW, SKYBLUE_KW, SLATEBLUE_KW, SLATEGRAY_KW, SNOW_KW, SPRINGGREEN_KW, STEELBLUE_KW, TAN_KW, TEAL_KW, THISTLE_KW, TOMATO_KW, TURQUOISE_KW, VIOLET_KW, WHEAT_KW, WHITE_KW, WHITESMOKE_KW, YELLOW_KW, YELLOWGREEN_KW, MEDIA_KW, KEYFRAMES_KW, NOT_KW, AND_KW, ONLY_KW, OR_KW, I_KW, IMPORTANT_KW, FROM_KW, TO_KW, VAR_KW, CSS_STRING_LITERAL, CSS_NUMBER_LITERAL, CSS_CUSTOM_PROPERTY, CSS_SPACE_LITERAL, ERROR_TOKEN, IDENT, NEWLINE, WHITESPACE, COMMENT, MULTILINE_COMMENT, CSS_ROOT, CSS_RULE_LIST, CSS_ID_SELECTOR_PATTERN, CSS_RULE, CSS_SELECTOR_LIST, CSS_SELECTOR, CSS_ANY_FUNCTION, CSS_AT_KEYFRAMES, CSS_AT_KEYFRAMES_BODY, CSS_AT_MEDIA, CSS_AT_MEDIA_QUERY, CSS_AT_MEDIA_QUERY_CONSEQUENT, CSS_AT_MEDIA_QUERY_FEATURE, CSS_AT_MEDIA_QUERY_FEATURE_BOOLEAN, CSS_AT_MEDIA_QUERY_FEATURE_COMPARE, CSS_AT_MEDIA_QUERY_FEATURE_PLAIN, CSS_AT_MEDIA_QUERY_FEATURE_RANGE, CSS_AT_MEDIA_QUERY_RANGE, CSS_ATTRIBUTE, CSS_ATTRIBUTE_MATCHER, CSS_ATTRIBUTE_META, CSS_ATTRIBUTE_MODIFIER, CSS_ATTRIBUTE_NAME, CSS_ATTRIBUTE_SELECTOR_PATTERN, CSS_BLOCK, CSS_CLASS_SELECTOR_PATTERN, CSS_COMBINATOR_SELECTOR_PATTERN, CSS_DECLARATION, CSS_DIMENSION, CSS_IDENTIFIER, CSS_KEYFRAMES_BLOCK, CSS_KEYFRAMES_SELECTOR, CSS_NUMBER, CSS_PARAMETER, CSS_PERCENTAGE, CSS_PSEUDO_CLASS_SELECTOR_PATTERN, CSS_PSEUDO_CLASS_SELECTOR_PATTERN_PARAMETERS, CSS_RATIO, CSS_SIMPLE_FUNCTION, CSS_STRING, CSS_TYPE_SELECTOR_PATTERN, CSS_UNIVERSAL_SELECTOR_PATTERN, CSS_VAR_FUNCTION, CSS_VAR_FUNCTION_VALUE, CSS_ANY_SELECTOR_PATTERN_LIST, CSS_AT_KEYFRAMES_ITEM_LIST, CSS_AT_MEDIA_QUERY_LIST, CSS_ATTRIBUTE_LIST, CSS_DECLARATION_LIST, CSS_KEYFRAMES_SELECTOR_LIST, CSS_PARAMETER_LIST, CSS_DECLARATION_IMPORTANT, CSS_BOGUS, #[doc(hidden)] __LAST, } use self::CssSyntaxKind::*; impl CssSyntaxKind { pub const fn is_punct(self) -> bool { match self { SEMICOLON | COMMA | L_PAREN | R_PAREN | L_CURLY | R_CURLY | L_BRACK | R_BRACK | L_ANGLE | R_ANGLE | TILDE | HASH | AMP | PIPE | PLUS | STAR | SLASH | CARET | PERCENT | DOT | COLON | EQ | BANG | NEQ | MINUS | LTEQ | GTEQ | PLUSEQ | PIPEEQ | AMPEQ | CARETEQ | SLASHEQ | STAREQ | PERCENTEQ | AT | DOLLAR_EQ | TILDE_EQ | CDC | CDO => true, _ => false, } } pub const fn is_literal(self) -> bool { match self { CSS_STRING_LITERAL | CSS_NUMBER_LITERAL | CSS_CUSTOM_PROPERTY | CSS_SPACE_LITERAL => { true } _ => false, } } pub const fn is_list(self) -> bool { match self { CSS_RULE_LIST | CSS_SELECTOR_LIST | CSS_ANY_SELECTOR_PATTERN_LIST | CSS_AT_KEYFRAMES_ITEM_LIST | CSS_AT_MEDIA_QUERY_LIST | CSS_ATTRIBUTE_LIST | CSS_DECLARATION_LIST | CSS_KEYFRAMES_SELECTOR_LIST | CSS_PARAMETER_LIST => true, _ => false, } } pub fn from_keyword(ident: &str) -> Option<CssSyntaxKind> { let kw = match ident { "aliceblue" => ALICEBLUE_KW, "antiquewhite" => ANTIQUEWHITE_KW, "aqua" => AQUA_KW, "aquamarine" => AQUAMARINE_KW, "azure" => AZURE_KW, "beige" => BEIGE_KW, "bisque" => BISQUE_KW, "black" => BLACK_KW, "blanchedalmond" => BLANCHEDALMOND_KW, "blue" => BLUE_KW, "blueviolet" => BLUEVIOLET_KW, "brown" => BROWN_KW, "burlywood" => BURLYWOOD_KW, "cadetblue" => CADETBLUE_KW, "chartreuse" => CHARTREUSE_KW, "chocolate" => CHOCOLATE_KW, "coral" => CORAL_KW, "cornflowerblue" => CORNFLOWERBLUE_KW, "cornsilk" => CORNSILK_KW, "crimson" => CRIMSON_KW, "cyan" => CYAN_KW, "darkblue" => DARKBLUE_KW, "darkcyan" => DARKCYAN_KW, "darkgoldenrod" => DARKGOLDENROD_KW, "darkgray" => DARKGRAY_KW, "darkgreen" => DARKGREEN_KW, "darkkhaki" => DARKKHAKI_KW, "darkmagenta" => DARKMAGENTA_KW, "darkolivegreen" => DARKOLIVEGREEN_KW, "darkorange" => DARKORANGE_KW, "darkorchid" => DARKORCHID_KW, "darkred" => DARKRED_KW, "darksalmon" => DARKSALMON_KW, "darkseagreen" => DARKSEAGREEN_KW, "darkslateblue" => DARKSLATEBLUE_KW, "darkslategray" => DARKSLATEGRAY_KW, "darkturquoise" => DARKTURQUOISE_KW, "darkviolet" => DARKVIOLET_KW, "deeppink" => DEEPPINK_KW, "deepskyblue" => DEEPSKYBLUE_KW, "dimgray" => DIMGRAY_KW, "dodgerblue" => DODGERBLUE_KW, "firebrick" => FIREBRICK_KW, "floralwhite" => FLORALWHITE_KW, "forestgreen" => FORESTGREEN_KW, "fuchsia" => FUCHSIA_KW, "gainsboro" => GAINSBORO_KW, "ghostwhite" => GHOSTWHITE_KW, "gold" => GOLD_KW, "goldenrod" => GOLDENROD_KW, "gray" => GRAY_KW, "green" => GREEN_KW, "greenyellow" => GREENYELLOW_KW, "honeydew" => HONEYDEW_KW, "hotpink" => HOTPINK_KW, "indianred" => INDIANRED_KW, "indigo" => INDIGO_KW, "ivory" => IVORY_KW, "khaki" => KHAKI_KW, "lavender" => LAVENDER_KW, "lavenderblush" => LAVENDERBLUSH_KW, "lawngreen" => LAWNGREEN_KW, "lemonchiffon" => LEMONCHIFFON_KW, "lightblue" => LIGHTBLUE_KW, "lightcoral" => LIGHTCORAL_KW, "lightcyan" => LIGHTCYAN_KW, "lightgoldenrodyellow" => LIGHTGOLDENRODYELLOW_KW, "lightgreen" => LIGHTGREEN_KW, "lightgrey" => LIGHTGREY_KW, "lightpink" => LIGHTPINK_KW, "lightsalmon" => LIGHTSALMON_KW, "lightseagreen" => LIGHTSEAGREEN_KW, "lightskyblue" => LIGHTSKYBLUE_KW, "lightslategray" => LIGHTSLATEGRAY_KW, "lightsteelblue" => LIGHTSTEELBLUE_KW, "lightyellow" => LIGHTYELLOW_KW, "lime" => LIME_KW, "limegreen" => LIMEGREEN_KW, "linen" => LINEN_KW, "magenta" => MAGENTA_KW, "maroon" => MAROON_KW, "mediumaquamarine" => MEDIUMAQUAMARINE_KW, "mediumblue" => MEDIUMBLUE_KW, "mediumorchid" => MEDIUMORCHID_KW, "mediumpurple" => MEDIUMPURPLE_KW, "mediumseagreen" => MEDIUMSEAGREEN_KW, "mediumslateblue" => MEDIUMSLATEBLUE_KW, "mediumspringgreen" => MEDIUMSPRINGGREEN_KW, "mediumturquoise" => MEDIUMTURQUOISE_KW, "mediumvioletred" => MEDIUMVIOLETRED_KW, "midnightblue" => MIDNIGHTBLUE_KW, "mintcream" => MINTCREAM_KW, "mistyrose" => MISTYROSE_KW, "moccasin" => MOCCASIN_KW, "navajowhite" => NAVAJOWHITE_KW, "navy" => NAVY_KW, "navyblue" => NAVYBLUE_KW, "oldlace" => OLDLACE_KW, "olive" => OLIVE_KW, "olivedrab" => OLIVEDRAB_KW, "orange" => ORANGE_KW, "orangered" => ORANGERED_KW, "orchid" => ORCHID_KW, "palegoldenrod" => PALEGOLDENROD_KW, "palegreen" => PALEGREEN_KW, "paleturquoise" => PALETURQUOISE_KW, "palevioletred" => PALEVIOLETRED_KW, "papayawhip" => PAPAYAWHIP_KW, "peachpuff" => PEACHPUFF_KW, "peru" => PERU_KW, "pink" => PINK_KW, "plum" => PLUM_KW, "powderblue" => POWDERBLUE_KW, "purple" => PURPLE_KW, "red" => RED_KW, "rosybrown" => ROSYBROWN_KW, "royalblue" => ROYALBLUE_KW, "saddlebrown" => SADDLEBROWN_KW, "salmon" => SALMON_KW, "sandybrown" => SANDYBROWN_KW, "seagreen" => SEAGREEN_KW, "seashell" => SEASHELL_KW, "sienna" => SIENNA_KW, "silver" => SILVER_KW, "skyblue" => SKYBLUE_KW, "slateblue" => SLATEBLUE_KW, "slategray" => SLATEGRAY_KW, "snow" => SNOW_KW, "springgreen" => SPRINGGREEN_KW, "steelblue" => STEELBLUE_KW, "tan" => TAN_KW, "teal" => TEAL_KW, "thistle" => THISTLE_KW, "tomato" => TOMATO_KW, "turquoise" => TURQUOISE_KW, "violet" => VIOLET_KW, "wheat" => WHEAT_KW, "white" => WHITE_KW, "whitesmoke" => WHITESMOKE_KW, "yellow" => YELLOW_KW, "yellowgreen" => YELLOWGREEN_KW, "media" => MEDIA_KW, "keyframes" => KEYFRAMES_KW, "not" => NOT_KW, "and" => AND_KW, "only" => ONLY_KW, "or" => OR_KW, "i" => I_KW, "important" => IMPORTANT_KW, "from" => FROM_KW, "to" => TO_KW, "var" => VAR_KW, _ => return None, }; Some(kw) } pub const fn to_string(&self) -> Option<&'static str> { let tok = match self { SEMICOLON => ";", COMMA => ",", L_PAREN => "(", R_PAREN => ")", L_CURLY => "{", R_CURLY => "}", L_BRACK => "[", R_BRACK => "]", L_ANGLE => "<", R_ANGLE => ">", TILDE => "~", HASH => "#", AMP => "&", PIPE => "|", PLUS => "+", STAR => "*", SLASH => "/", CARET => "^", PERCENT => "%", DOT => ".", COLON => ":", EQ => "=", BANG => "!", NEQ => "!=", MINUS => "-", LTEQ => "<=", GTEQ => ">=", PLUSEQ => "+=", PIPEEQ => "|=", AMPEQ => "&=", CARETEQ => "^=", SLASHEQ => "/=", STAREQ => "*=", PERCENTEQ => "%=", AT => "@", DOLLAR_EQ => "$=", TILDE_EQ => "~=", CDC => "-->", CDO => "<!--", ALICEBLUE_KW => "aliceblue", ANTIQUEWHITE_KW => "antiquewhite", AQUA_KW => "aqua", AQUAMARINE_KW => "aquamarine", AZURE_KW => "azure", BEIGE_KW => "beige", BISQUE_KW => "bisque", BLACK_KW => "black", BLANCHEDALMOND_KW => "blanchedalmond", BLUE_KW => "blue", BLUEVIOLET_KW => "blueviolet", BROWN_KW => "brown", BURLYWOOD_KW => "burlywood", CADETBLUE_KW => "cadetblue", CHARTREUSE_KW => "chartreuse", CHOCOLATE_KW => "chocolate", CORAL_KW => "coral", CORNFLOWERBLUE_KW => "cornflowerblue", CORNSILK_KW => "cornsilk", CRIMSON_KW => "crimson", CYAN_KW => "cyan", DARKBLUE_KW => "darkblue", DARKCYAN_KW => "darkcyan", DARKGOLDENROD_KW => "darkgoldenrod", DARKGRAY_KW => "darkgray", DARKGREEN_KW => "darkgreen", DARKKHAKI_KW => "darkkhaki", DARKMAGENTA_KW => "darkmagenta", DARKOLIVEGREEN_KW => "darkolivegreen", DARKORANGE_KW => "darkorange", DARKORCHID_KW => "darkorchid", DARKRED_KW => "darkred", DARKSALMON_KW => "darksalmon", DARKSEAGREEN_KW => "darkseagreen", DARKSLATEBLUE_KW => "darkslateblue", DARKSLATEGRAY_KW => "darkslategray", DARKTURQUOISE_KW => "darkturquoise", DARKVIOLET_KW => "darkviolet", DEEPPINK_KW => "deeppink", DEEPSKYBLUE_KW => "deepskyblue", DIMGRAY_KW => "dimgray", DODGERBLUE_KW => "dodgerblue", FIREBRICK_KW => "firebrick", FLORALWHITE_KW => "floralwhite", FORESTGREEN_KW => "forestgreen", FUCHSIA_KW => "fuchsia", GAINSBORO_KW => "gainsboro", GHOSTWHITE_KW => "ghostwhite", GOLD_KW => "gold", GOLDENROD_KW => "goldenrod", GRAY_KW => "gray", GREEN_KW => "green", GREENYELLOW_KW => "greenyellow", HONEYDEW_KW => "honeydew", HOTPINK_KW => "hotpink", INDIANRED_KW => "indianred", INDIGO_KW => "indigo", IVORY_KW => "ivory", KHAKI_KW => "khaki", LAVENDER_KW => "lavender", LAVENDERBLUSH_KW => "lavenderblush", LAWNGREEN_KW => "lawngreen", LEMONCHIFFON_KW => "lemonchiffon", LIGHTBLUE_KW => "lightblue", LIGHTCORAL_KW => "lightcoral", LIGHTCYAN_KW => "lightcyan", LIGHTGOLDENRODYELLOW_KW => "lightgoldenrodyellow", LIGHTGREEN_KW => "lightgreen", LIGHTGREY_KW => "lightgrey", LIGHTPINK_KW => "lightpink", LIGHTSALMON_KW => "lightsalmon", LIGHTSEAGREEN_KW => "lightseagreen", LIGHTSKYBLUE_KW => "lightskyblue", LIGHTSLATEGRAY_KW => "lightslategray", LIGHTSTEELBLUE_KW => "lightsteelblue", LIGHTYELLOW_KW => "lightyellow", LIME_KW => "lime", LIMEGREEN_KW => "limegreen", LINEN_KW => "linen", MAGENTA_KW => "magenta", MAROON_KW => "maroon", MEDIUMAQUAMARINE_KW => "mediumaquamarine", MEDIUMBLUE_KW => "mediumblue", MEDIUMORCHID_KW => "mediumorchid", MEDIUMPURPLE_KW => "mediumpurple", MEDIUMSEAGREEN_KW => "mediumseagreen", MEDIUMSLATEBLUE_KW => "mediumslateblue", MEDIUMSPRINGGREEN_KW => "mediumspringgreen", MEDIUMTURQUOISE_KW => "mediumturquoise", MEDIUMVIOLETRED_KW => "mediumvioletred", MIDNIGHTBLUE_KW => "midnightblue", MINTCREAM_KW => "mintcream", MISTYROSE_KW => "mistyrose", MOCCASIN_KW => "moccasin", NAVAJOWHITE_KW => "navajowhite", NAVY_KW => "navy", NAVYBLUE_KW => "navyblue", OLDLACE_KW => "oldlace", OLIVE_KW => "olive", OLIVEDRAB_KW => "olivedrab", ORANGE_KW => "orange", ORANGERED_KW => "orangered", ORCHID_KW => "orchid", PALEGOLDENROD_KW => "palegoldenrod", PALEGREEN_KW => "palegreen", PALETURQUOISE_KW => "paleturquoise", PALEVIOLETRED_KW => "palevioletred", PAPAYAWHIP_KW => "papayawhip", PEACHPUFF_KW => "peachpuff", PERU_KW => "peru", PINK_KW => "pink", PLUM_KW => "plum", POWDERBLUE_KW => "powderblue", PURPLE_KW => "purple", RED_KW => "red", ROSYBROWN_KW => "rosybrown", ROYALBLUE_KW => "royalblue", SADDLEBROWN_KW => "saddlebrown", SALMON_KW => "salmon", SANDYBROWN_KW => "sandybrown", SEAGREEN_KW => "seagreen", SEASHELL_KW => "seashell", SIENNA_KW => "sienna", SILVER_KW => "silver", SKYBLUE_KW => "skyblue", SLATEBLUE_KW => "slateblue", SLATEGRAY_KW => "slategray", SNOW_KW => "snow", SPRINGGREEN_KW => "springgreen", STEELBLUE_KW => "steelblue", TAN_KW => "tan", TEAL_KW => "teal", THISTLE_KW => "thistle", TOMATO_KW => "tomato", TURQUOISE_KW => "turquoise", VIOLET_KW => "violet", WHEAT_KW => "wheat", WHITE_KW => "white", WHITESMOKE_KW => "whitesmoke", YELLOW_KW => "yellow", YELLOWGREEN_KW => "yellowgreen", MEDIA_KW => "media", KEYFRAMES_KW => "keyframes", NOT_KW => "not", AND_KW => "and", ONLY_KW => "only", OR_KW => "or", I_KW => "i", IMPORTANT_KW => "important", FROM_KW => "from", TO_KW => "to", VAR_KW => "var", CSS_STRING_LITERAL => "string literal", _ => return None, }; Some(tok) } } #[doc = r" Utility macro for creating a SyntaxKind through simple macro syntax"] #[macro_export] macro_rules ! T { [;] => { $ crate :: CssSyntaxKind :: SEMICOLON } ; [,] => { $ crate :: CssSyntaxKind :: COMMA } ; ['('] => { $ crate :: CssSyntaxKind :: L_PAREN } ; [')'] => { $ crate :: CssSyntaxKind :: R_PAREN } ; ['{'] => { $ crate :: CssSyntaxKind :: L_CURLY } ; ['}'] => { $ crate :: CssSyntaxKind :: R_CURLY } ; ['['] => { $ crate :: CssSyntaxKind :: L_BRACK } ; [']'] => { $ crate :: CssSyntaxKind :: R_BRACK } ; [<] => { $ crate :: CssSyntaxKind :: L_ANGLE } ; [>] => { $ crate :: CssSyntaxKind :: R_ANGLE } ; [~] => { $ crate :: CssSyntaxKind :: TILDE } ; [#] => { $ crate :: CssSyntaxKind :: HASH } ; [&] => { $ crate :: CssSyntaxKind :: AMP } ; [|] => { $ crate :: CssSyntaxKind :: PIPE } ; [+] => { $ crate :: CssSyntaxKind :: PLUS } ; [*] => { $ crate :: CssSyntaxKind :: STAR } ; [/] => { $ crate :: CssSyntaxKind :: SLASH } ; [^] => { $ crate :: CssSyntaxKind :: CARET } ; [%] => { $ crate :: CssSyntaxKind :: PERCENT } ; [.] => { $ crate :: CssSyntaxKind :: DOT } ; [:] => { $ crate :: CssSyntaxKind :: COLON } ; [=] => { $ crate :: CssSyntaxKind :: EQ } ; [!] => { $ crate :: CssSyntaxKind :: BANG } ; [!=] => { $ crate :: CssSyntaxKind :: NEQ } ; [-] => { $ crate :: CssSyntaxKind :: MINUS } ; [<=] => { $ crate :: CssSyntaxKind :: LTEQ } ; [>=] => { $ crate :: CssSyntaxKind :: GTEQ } ; [+=] => { $ crate :: CssSyntaxKind :: PLUSEQ } ; [|=] => { $ crate :: CssSyntaxKind :: PIPEEQ } ; [&=] => { $ crate :: CssSyntaxKind :: AMPEQ } ; [^=] => { $ crate :: CssSyntaxKind :: CARETEQ } ; [/=] => { $ crate :: CssSyntaxKind :: SLASHEQ } ; [*=] => { $ crate :: CssSyntaxKind :: STAREQ } ; [%=] => { $ crate :: CssSyntaxKind :: PERCENTEQ } ; [@] => { $ crate :: CssSyntaxKind :: AT } ; ["$="] => { $ crate :: CssSyntaxKind :: DOLLAR_EQ } ; [~=] => { $ crate :: CssSyntaxKind :: TILDE_EQ } ; [-->] => { $ crate :: CssSyntaxKind :: CDC } ; [<!--] => { $ crate :: CssSyntaxKind :: CDO } ; [aliceblue] => { $ crate :: CssSyntaxKind :: ALICEBLUE_KW } ; [antiquewhite] => { $ crate :: CssSyntaxKind :: ANTIQUEWHITE_KW } ; [aqua] => { $ crate :: CssSyntaxKind :: AQUA_KW } ; [aquamarine] => { $ crate :: CssSyntaxKind :: AQUAMARINE_KW } ; [azure] => { $ crate :: CssSyntaxKind :: AZURE_KW } ; [beige] => { $ crate :: CssSyntaxKind :: BEIGE_KW } ; [bisque] => { $ crate :: CssSyntaxKind :: BISQUE_KW } ; [black] => { $ crate :: CssSyntaxKind :: BLACK_KW } ; [blanchedalmond] => { $ crate :: CssSyntaxKind :: BLANCHEDALMOND_KW } ; [blue] => { $ crate :: CssSyntaxKind :: BLUE_KW } ; [blueviolet] => { $ crate :: CssSyntaxKind :: BLUEVIOLET_KW } ; [brown] => { $ crate :: CssSyntaxKind :: BROWN_KW } ; [burlywood] => { $ crate :: CssSyntaxKind :: BURLYWOOD_KW } ; [cadetblue] => { $ crate :: CssSyntaxKind :: CADETBLUE_KW } ; [chartreuse] => { $ crate :: CssSyntaxKind :: CHARTREUSE_KW } ; [chocolate] => { $ crate :: CssSyntaxKind :: CHOCOLATE_KW } ; [coral] => { $ crate :: CssSyntaxKind :: CORAL_KW } ; [cornflowerblue] => { $ crate :: CssSyntaxKind :: CORNFLOWERBLUE_KW } ; [cornsilk] => { $ crate :: CssSyntaxKind :: CORNSILK_KW } ; [crimson] => { $ crate :: CssSyntaxKind :: CRIMSON_KW } ; [cyan] => { $ crate :: CssSyntaxKind :: CYAN_KW } ; [darkblue] => { $ crate :: CssSyntaxKind :: DARKBLUE_KW } ; [darkcyan] => { $ crate :: CssSyntaxKind :: DARKCYAN_KW } ; [darkgoldenrod] => { $ crate :: CssSyntaxKind :: DARKGOLDENROD_KW } ; [darkgray] => { $ crate :: CssSyntaxKind :: DARKGRAY_KW } ; [darkgreen] => { $ crate :: CssSyntaxKind :: DARKGREEN_KW } ; [darkkhaki] => { $ crate :: CssSyntaxKind :: DARKKHAKI_KW } ; [darkmagenta] => { $ crate :: CssSyntaxKind :: DARKMAGENTA_KW } ; [darkolivegreen] => { $ crate :: CssSyntaxKind :: DARKOLIVEGREEN_KW } ; [darkorange] => { $ crate :: CssSyntaxKind :: DARKORANGE_KW } ; [darkorchid] => { $ crate :: CssSyntaxKind :: DARKORCHID_KW } ; [darkred] => { $ crate :: CssSyntaxKind :: DARKRED_KW } ; [darksalmon] => { $ crate :: CssSyntaxKind :: DARKSALMON_KW } ; [darkseagreen] => { $ crate :: CssSyntaxKind :: DARKSEAGREEN_KW } ; [darkslateblue] => { $ crate :: CssSyntaxKind :: DARKSLATEBLUE_KW } ; [darkslategray] => { $ crate :: CssSyntaxKind :: DARKSLATEGRAY_KW } ; [darkturquoise] => { $ crate :: CssSyntaxKind :: DARKTURQUOISE_KW } ; [darkviolet] => { $ crate :: CssSyntaxKind :: DARKVIOLET_KW } ; [deeppink] => { $ crate :: CssSyntaxKind :: DEEPPINK_KW } ; [deepskyblue] => { $ crate :: CssSyntaxKind :: DEEPSKYBLUE_KW } ; [dimgray] => { $ crate :: CssSyntaxKind :: DIMGRAY_KW } ; [dodgerblue] => { $ crate :: CssSyntaxKind :: DODGERBLUE_KW } ; [firebrick] => { $ crate :: CssSyntaxKind :: FIREBRICK_KW } ; [floralwhite] => { $ crate :: CssSyntaxKind :: FLORALWHITE_KW } ; [forestgreen] => { $ crate :: CssSyntaxKind :: FORESTGREEN_KW } ; [fuchsia] => { $ crate :: CssSyntaxKind :: FUCHSIA_KW } ; [gainsboro] => { $ crate :: CssSyntaxKind :: GAINSBORO_KW } ; [ghostwhite] => { $ crate :: CssSyntaxKind :: GHOSTWHITE_KW } ; [gold] => { $ crate :: CssSyntaxKind :: GOLD_KW } ; [goldenrod] => { $ crate :: CssSyntaxKind :: GOLDENROD_KW } ; [gray] => { $ crate :: CssSyntaxKind :: GRAY_KW } ; [green] => { $ crate :: CssSyntaxKind :: GREEN_KW } ; [greenyellow] => { $ crate :: CssSyntaxKind :: GREENYELLOW_KW } ; [honeydew] => { $ crate :: CssSyntaxKind :: HONEYDEW_KW } ; [hotpink] => { $ crate :: CssSyntaxKind :: HOTPINK_KW } ; [indianred] => { $ crate :: CssSyntaxKind :: INDIANRED_KW } ; [indigo] => { $ crate :: CssSyntaxKind :: INDIGO_KW } ; [ivory] => { $ crate :: CssSyntaxKind :: IVORY_KW } ; [khaki] => { $ crate :: CssSyntaxKind :: KHAKI_KW } ; [lavender] => { $ crate :: CssSyntaxKind :: LAVENDER_KW } ; [lavenderblush] => { $ crate :: CssSyntaxKind :: LAVENDERBLUSH_KW } ; [lawngreen] => { $ crate :: CssSyntaxKind :: LAWNGREEN_KW } ; [lemonchiffon] => { $ crate :: CssSyntaxKind :: LEMONCHIFFON_KW } ; [lightblue] => { $ crate :: CssSyntaxKind :: LIGHTBLUE_KW } ; [lightcoral] => { $ crate :: CssSyntaxKind :: LIGHTCORAL_KW } ; [lightcyan] => { $ crate :: CssSyntaxKind :: LIGHTCYAN_KW } ; [lightgoldenrodyellow] => { $ crate :: CssSyntaxKind :: LIGHTGOLDENRODYELLOW_KW } ; [lightgreen] => { $ crate :: CssSyntaxKind :: LIGHTGREEN_KW } ; [lightgrey] => { $ crate :: CssSyntaxKind :: LIGHTGREY_KW } ; [lightpink] => { $ crate :: CssSyntaxKind :: LIGHTPINK_KW } ; [lightsalmon] => { $ crate :: CssSyntaxKind :: LIGHTSALMON_KW } ; [lightseagreen] => { $ crate :: CssSyntaxKind :: LIGHTSEAGREEN_KW } ; [lightskyblue] => { $ crate :: CssSyntaxKind :: LIGHTSKYBLUE_KW } ; [lightslategray] => { $ crate :: CssSyntaxKind :: LIGHTSLATEGRAY_KW } ; [lightsteelblue] => { $ crate :: CssSyntaxKind :: LIGHTSTEELBLUE_KW } ; [lightyellow] => { $ crate :: CssSyntaxKind :: LIGHTYELLOW_KW } ; [lime] => { $ crate :: CssSyntaxKind :: LIME_KW } ; [limegreen] => { $ crate :: CssSyntaxKind :: LIMEGREEN_KW } ; [linen] => { $ crate :: CssSyntaxKind :: LINEN_KW } ; [magenta] => { $ crate :: CssSyntaxKind :: MAGENTA_KW } ; [maroon] => { $ crate :: CssSyntaxKind :: MAROON_KW } ; [mediumaquamarine] => { $ crate :: CssSyntaxKind :: MEDIUMAQUAMARINE_KW } ; [mediumblue] => { $ crate :: CssSyntaxKind :: MEDIUMBLUE_KW } ; [mediumorchid] => { $ crate :: CssSyntaxKind :: MEDIUMORCHID_KW } ; [mediumpurple] => { $ crate :: CssSyntaxKind :: MEDIUMPURPLE_KW } ; [mediumseagreen] => { $ crate :: CssSyntaxKind :: MEDIUMSEAGREEN_KW } ; [mediumslateblue] => { $ crate :: CssSyntaxKind :: MEDIUMSLATEBLUE_KW } ; [mediumspringgreen] => { $ crate :: CssSyntaxKind :: MEDIUMSPRINGGREEN_KW } ; [mediumturquoise] => { $ crate :: CssSyntaxKind :: MEDIUMTURQUOISE_KW } ; [mediumvioletred] => { $ crate :: CssSyntaxKind :: MEDIUMVIOLETRED_KW } ; [midnightblue] => { $ crate :: CssSyntaxKind :: MIDNIGHTBLUE_KW } ; [mintcream] => { $ crate :: CssSyntaxKind :: MINTCREAM_KW } ; [mistyrose] => { $ crate :: CssSyntaxKind :: MISTYROSE_KW } ; [moccasin] => { $ crate :: CssSyntaxKind :: MOCCASIN_KW } ; [navajowhite] => { $ crate :: CssSyntaxKind :: NAVAJOWHITE_KW } ; [navy] => { $ crate :: CssSyntaxKind :: NAVY_KW } ; [navyblue] => { $ crate :: CssSyntaxKind :: NAVYBLUE_KW } ; [oldlace] => { $ crate :: CssSyntaxKind :: OLDLACE_KW } ; [olive] => { $ crate :: CssSyntaxKind :: OLIVE_KW } ; [olivedrab] => { $ crate :: CssSyntaxKind :: OLIVEDRAB_KW } ; [orange] => { $ crate :: CssSyntaxKind :: ORANGE_KW } ; [orangered] => { $ crate :: CssSyntaxKind :: ORANGERED_KW } ; [orchid] => { $ crate :: CssSyntaxKind :: ORCHID_KW } ; [palegoldenrod] => { $ crate :: CssSyntaxKind :: PALEGOLDENROD_KW } ; [palegreen] => { $ crate :: CssSyntaxKind :: PALEGREEN_KW } ; [paleturquoise] => { $ crate :: CssSyntaxKind :: PALETURQUOISE_KW } ; [palevioletred] => { $ crate :: CssSyntaxKind :: PALEVIOLETRED_KW } ; [papayawhip] => { $ crate :: CssSyntaxKind :: PAPAYAWHIP_KW } ; [peachpuff] => { $ crate :: CssSyntaxKind :: PEACHPUFF_KW } ; [peru] => { $ crate :: CssSyntaxKind :: PERU_KW } ; [pink] => { $ crate :: CssSyntaxKind :: PINK_KW } ; [plum] => { $ crate :: CssSyntaxKind :: PLUM_KW } ; [powderblue] => { $ crate :: CssSyntaxKind :: POWDERBLUE_KW } ; [purple] => { $ crate :: CssSyntaxKind :: PURPLE_KW } ; [red] => { $ crate :: CssSyntaxKind :: RED_KW } ; [rosybrown] => { $ crate :: CssSyntaxKind :: ROSYBROWN_KW } ; [royalblue] => { $ crate :: CssSyntaxKind :: ROYALBLUE_KW } ; [saddlebrown] => { $ crate :: CssSyntaxKind :: SADDLEBROWN_KW } ; [salmon] => { $ crate :: CssSyntaxKind :: SALMON_KW } ; [sandybrown] => { $ crate :: CssSyntaxKind :: SANDYBROWN_KW } ; [seagreen] => { $ crate :: CssSyntaxKind :: SEAGREEN_KW } ; [seashell] => { $ crate :: CssSyntaxKind :: SEASHELL_KW } ; [sienna] => { $ crate :: CssSyntaxKind :: SIENNA_KW } ; [silver] => { $ crate :: CssSyntaxKind :: SILVER_KW } ; [skyblue] => { $ crate :: CssSyntaxKind :: SKYBLUE_KW } ; [slateblue] => { $ crate :: CssSyntaxKind :: SLATEBLUE_KW } ; [slategray] => { $ crate :: CssSyntaxKind :: SLATEGRAY_KW } ; [snow] => { $ crate :: CssSyntaxKind :: SNOW_KW } ; [springgreen] => { $ crate :: CssSyntaxKind :: SPRINGGREEN_KW } ; [steelblue] => { $ crate :: CssSyntaxKind :: STEELBLUE_KW } ; [tan] => { $ crate :: CssSyntaxKind :: TAN_KW } ; [teal] => { $ crate :: CssSyntaxKind :: TEAL_KW } ; [thistle] => { $ crate :: CssSyntaxKind :: THISTLE_KW } ; [tomato] => { $ crate :: CssSyntaxKind :: TOMATO_KW } ; [turquoise] => { $ crate :: CssSyntaxKind :: TURQUOISE_KW } ; [violet] => { $ crate :: CssSyntaxKind :: VIOLET_KW } ; [wheat] => { $ crate :: CssSyntaxKind :: WHEAT_KW } ; [white] => { $ crate :: CssSyntaxKind :: WHITE_KW } ; [whitesmoke] => { $ crate :: CssSyntaxKind :: WHITESMOKE_KW } ; [yellow] => { $ crate :: CssSyntaxKind :: YELLOW_KW } ; [yellowgreen] => { $ crate :: CssSyntaxKind :: YELLOWGREEN_KW } ; [media] => { $ crate :: CssSyntaxKind :: MEDIA_KW } ; [keyframes] => { $ crate :: CssSyntaxKind :: KEYFRAMES_KW } ; [not] => { $ crate :: CssSyntaxKind :: NOT_KW } ; [and] => { $ crate :: CssSyntaxKind :: AND_KW } ; [only] => { $ crate :: CssSyntaxKind :: ONLY_KW } ; [or] => { $ crate :: CssSyntaxKind :: OR_KW } ; [i] => { $ crate :: CssSyntaxKind :: I_KW } ; [important] => { $ crate :: CssSyntaxKind :: IMPORTANT_KW } ; [from] => { $ crate :: CssSyntaxKind :: FROM_KW } ; [to] => { $ crate :: CssSyntaxKind :: TO_KW } ; [var] => { $ crate :: CssSyntaxKind :: VAR_KW } ; [ident] => { $ crate :: CssSyntaxKind :: IDENT } ; [EOF] => { $ crate :: CssSyntaxKind :: EOF } ; [#] => { $ crate :: CssSyntaxKind :: HASH } ; }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_css_syntax/src/generated/macros.rs
crates/rome_css_syntax/src/generated/macros.rs
//! Generated file, do not edit by hand, see `xtask/codegen` #[doc = r" Reconstruct an AstNode from a SyntaxNode"] #[doc = r""] #[doc = r" This macros performs a match over the [kind](rome_rowan::SyntaxNode::kind)"] #[doc = r" of the provided [rome_rowan::SyntaxNode] and constructs the appropriate"] #[doc = r" AstNode type for it, then execute the provided expression over it."] #[doc = r""] #[doc = r" # Examples"] #[doc = r""] #[doc = r" ```ignore"] #[doc = r" map_syntax_node!(syntax_node, node => node.format())"] #[doc = r" ```"] #[macro_export] macro_rules! map_syntax_node { ($ node : expr , $ pattern : pat => $ body : expr) => { match $node { node => match $crate::CssSyntaxNode::kind(&node) { $crate::CssSyntaxKind::CSS_ANY_FUNCTION => { let $pattern = unsafe { $crate::CssAnyFunction::new_unchecked(node) }; $body } $crate::CssSyntaxKind::CSS_AT_KEYFRAMES => { let $pattern = unsafe { $crate::CssAtKeyframes::new_unchecked(node) }; $body } $crate::CssSyntaxKind::CSS_AT_KEYFRAMES_BODY => { let $pattern = unsafe { $crate::CssAtKeyframesBody::new_unchecked(node) }; $body } $crate::CssSyntaxKind::CSS_AT_MEDIA => { let $pattern = unsafe { $crate::CssAtMedia::new_unchecked(node) }; $body } $crate::CssSyntaxKind::CSS_AT_MEDIA_QUERY => { let $pattern = unsafe { $crate::CssAtMediaQuery::new_unchecked(node) }; $body } $crate::CssSyntaxKind::CSS_AT_MEDIA_QUERY_CONSEQUENT => { let $pattern = unsafe { $crate::CssAtMediaQueryConsequent::new_unchecked(node) }; $body } $crate::CssSyntaxKind::CSS_AT_MEDIA_QUERY_FEATURE => { let $pattern = unsafe { $crate::CssAtMediaQueryFeature::new_unchecked(node) }; $body } $crate::CssSyntaxKind::CSS_AT_MEDIA_QUERY_FEATURE_BOOLEAN => { let $pattern = unsafe { $crate::CssAtMediaQueryFeatureBoolean::new_unchecked(node) }; $body } $crate::CssSyntaxKind::CSS_AT_MEDIA_QUERY_FEATURE_COMPARE => { let $pattern = unsafe { $crate::CssAtMediaQueryFeatureCompare::new_unchecked(node) }; $body } $crate::CssSyntaxKind::CSS_AT_MEDIA_QUERY_FEATURE_PLAIN => { let $pattern = unsafe { $crate::CssAtMediaQueryFeaturePlain::new_unchecked(node) }; $body } $crate::CssSyntaxKind::CSS_AT_MEDIA_QUERY_FEATURE_RANGE => { let $pattern = unsafe { $crate::CssAtMediaQueryFeatureRange::new_unchecked(node) }; $body } $crate::CssSyntaxKind::CSS_AT_MEDIA_QUERY_RANGE => { let $pattern = unsafe { $crate::CssAtMediaQueryRange::new_unchecked(node) }; $body } $crate::CssSyntaxKind::CSS_ATTRIBUTE => { let $pattern = unsafe { $crate::CssAttribute::new_unchecked(node) }; $body } $crate::CssSyntaxKind::CSS_ATTRIBUTE_MATCHER => { let $pattern = unsafe { $crate::CssAttributeMatcher::new_unchecked(node) }; $body } $crate::CssSyntaxKind::CSS_ATTRIBUTE_META => { let $pattern = unsafe { $crate::CssAttributeMeta::new_unchecked(node) }; $body } $crate::CssSyntaxKind::CSS_ATTRIBUTE_MODIFIER => { let $pattern = unsafe { $crate::CssAttributeModifier::new_unchecked(node) }; $body } $crate::CssSyntaxKind::CSS_ATTRIBUTE_NAME => { let $pattern = unsafe { $crate::CssAttributeName::new_unchecked(node) }; $body } $crate::CssSyntaxKind::CSS_ATTRIBUTE_SELECTOR_PATTERN => { let $pattern = unsafe { $crate::CssAttributeSelectorPattern::new_unchecked(node) }; $body } $crate::CssSyntaxKind::CSS_BLOCK => { let $pattern = unsafe { $crate::CssBlock::new_unchecked(node) }; $body } $crate::CssSyntaxKind::CSS_CLASS_SELECTOR_PATTERN => { let $pattern = unsafe { $crate::CssClassSelectorPattern::new_unchecked(node) }; $body } $crate::CssSyntaxKind::CSS_COMBINATOR_SELECTOR_PATTERN => { let $pattern = unsafe { $crate::CssCombinatorSelectorPattern::new_unchecked(node) }; $body } $crate::CssSyntaxKind::CSS_CUSTOM_PROPERTY => { let $pattern = unsafe { $crate::CssCustomProperty::new_unchecked(node) }; $body } $crate::CssSyntaxKind::CSS_DECLARATION => { let $pattern = unsafe { $crate::CssDeclaration::new_unchecked(node) }; $body } $crate::CssSyntaxKind::CSS_DECLARATION_IMPORTANT => { let $pattern = unsafe { $crate::CssDeclarationImportant::new_unchecked(node) }; $body } $crate::CssSyntaxKind::CSS_DIMENSION => { let $pattern = unsafe { $crate::CssDimension::new_unchecked(node) }; $body } $crate::CssSyntaxKind::CSS_ID_SELECTOR_PATTERN => { let $pattern = unsafe { $crate::CssIdSelectorPattern::new_unchecked(node) }; $body } $crate::CssSyntaxKind::CSS_IDENTIFIER => { let $pattern = unsafe { $crate::CssIdentifier::new_unchecked(node) }; $body } $crate::CssSyntaxKind::CSS_KEYFRAMES_BLOCK => { let $pattern = unsafe { $crate::CssKeyframesBlock::new_unchecked(node) }; $body } $crate::CssSyntaxKind::CSS_KEYFRAMES_SELECTOR => { let $pattern = unsafe { $crate::CssKeyframesSelector::new_unchecked(node) }; $body } $crate::CssSyntaxKind::CSS_NUMBER => { let $pattern = unsafe { $crate::CssNumber::new_unchecked(node) }; $body } $crate::CssSyntaxKind::CSS_PARAMETER => { let $pattern = unsafe { $crate::CssParameter::new_unchecked(node) }; $body } $crate::CssSyntaxKind::CSS_PERCENTAGE => { let $pattern = unsafe { $crate::CssPercentage::new_unchecked(node) }; $body } $crate::CssSyntaxKind::CSS_PSEUDO_CLASS_SELECTOR_PATTERN => { let $pattern = unsafe { $crate::CssPseudoClassSelectorPattern::new_unchecked(node) }; $body } $crate::CssSyntaxKind::CSS_PSEUDO_CLASS_SELECTOR_PATTERN_PARAMETERS => { let $pattern = unsafe { $crate::CssPseudoClassSelectorPatternParameters::new_unchecked(node) }; $body } $crate::CssSyntaxKind::CSS_RATIO => { let $pattern = unsafe { $crate::CssRatio::new_unchecked(node) }; $body } $crate::CssSyntaxKind::CSS_ROOT => { let $pattern = unsafe { $crate::CssRoot::new_unchecked(node) }; $body } $crate::CssSyntaxKind::CSS_RULE => { let $pattern = unsafe { $crate::CssRule::new_unchecked(node) }; $body } $crate::CssSyntaxKind::CSS_SELECTOR => { let $pattern = unsafe { $crate::CssSelector::new_unchecked(node) }; $body } $crate::CssSyntaxKind::CSS_SIMPLE_FUNCTION => { let $pattern = unsafe { $crate::CssSimpleFunction::new_unchecked(node) }; $body } $crate::CssSyntaxKind::CSS_STRING => { let $pattern = unsafe { $crate::CssString::new_unchecked(node) }; $body } $crate::CssSyntaxKind::CSS_TYPE_SELECTOR_PATTERN => { let $pattern = unsafe { $crate::CssTypeSelectorPattern::new_unchecked(node) }; $body } $crate::CssSyntaxKind::CSS_UNIVERSAL_SELECTOR_PATTERN => { let $pattern = unsafe { $crate::CssUniversalSelectorPattern::new_unchecked(node) }; $body } $crate::CssSyntaxKind::CSS_VAR_FUNCTION => { let $pattern = unsafe { $crate::CssVarFunction::new_unchecked(node) }; $body } $crate::CssSyntaxKind::CSS_VAR_FUNCTION_VALUE => { let $pattern = unsafe { $crate::CssVarFunctionValue::new_unchecked(node) }; $body } $crate::CssSyntaxKind::CSS_BOGUS => { let $pattern = unsafe { $crate::CssBogus::new_unchecked(node) }; $body } $crate::CssSyntaxKind::CSS_ANY_SELECTOR_PATTERN_LIST => { let $pattern = unsafe { $crate::CssAnySelectorPatternList::new_unchecked(node) }; $body } $crate::CssSyntaxKind::CSS_AT_KEYFRAMES_ITEM_LIST => { let $pattern = unsafe { $crate::CssAtKeyframesItemList::new_unchecked(node) }; $body } $crate::CssSyntaxKind::CSS_AT_MEDIA_QUERY_LIST => { let $pattern = unsafe { $crate::CssAtMediaQueryList::new_unchecked(node) }; $body } $crate::CssSyntaxKind::CSS_ATTRIBUTE_LIST => { let $pattern = unsafe { $crate::CssAttributeList::new_unchecked(node) }; $body } $crate::CssSyntaxKind::CSS_DECLARATION_LIST => { let $pattern = unsafe { $crate::CssDeclarationList::new_unchecked(node) }; $body } $crate::CssSyntaxKind::CSS_KEYFRAMES_SELECTOR_LIST => { let $pattern = unsafe { $crate::CssKeyframesSelectorList::new_unchecked(node) }; $body } $crate::CssSyntaxKind::CSS_PARAMETER_LIST => { let $pattern = unsafe { $crate::CssParameterList::new_unchecked(node) }; $body } $crate::CssSyntaxKind::CSS_RULE_LIST => { let $pattern = unsafe { $crate::CssRuleList::new_unchecked(node) }; $body } $crate::CssSyntaxKind::CSS_SELECTOR_LIST => { let $pattern = unsafe { $crate::CssSelectorList::new_unchecked(node) }; $body } _ => unreachable!(), }, } }; } pub(crate) use map_syntax_node;
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_css_syntax/src/generated/nodes.rs
crates/rome_css_syntax/src/generated/nodes.rs
//! Generated file, do not edit by hand, see `xtask/codegen` #![allow(clippy::enum_variant_names)] #![allow(clippy::match_like_matches_macro)] use crate::{ macros::map_syntax_node, CssLanguage as Language, CssSyntaxElement as SyntaxElement, CssSyntaxElementChildren as SyntaxElementChildren, CssSyntaxKind::{self as SyntaxKind, *}, CssSyntaxList as SyntaxList, CssSyntaxNode as SyntaxNode, CssSyntaxToken as SyntaxToken, }; use rome_rowan::{support, AstNode, RawSyntaxKind, SyntaxKindSet, SyntaxResult}; #[allow(unused)] use rome_rowan::{ AstNodeList, AstNodeListIterator, AstSeparatedList, AstSeparatedListNodesIterator, }; #[cfg(feature = "serde")] use serde::ser::SerializeSeq; #[cfg(feature = "serde")] use serde::{Serialize, Serializer}; use std::fmt::{Debug, Formatter}; #[derive(Clone, PartialEq, Eq, Hash)] pub struct CssAnyFunction { pub(crate) syntax: SyntaxNode, } impl CssAnyFunction { #[doc = r" Create an AstNode from a SyntaxNode without checking its kind"] #[doc = r""] #[doc = r" # Safety"] #[doc = r" This function must be guarded with a call to [AstNode::can_cast]"] #[doc = r" or a match on [SyntaxNode::kind]"] #[inline] pub const unsafe fn new_unchecked(syntax: SyntaxNode) -> Self { Self { syntax } } pub fn as_fields(&self) -> CssAnyFunctionFields { CssAnyFunctionFields { css_simple_function: self.css_simple_function(), } } pub fn css_simple_function(&self) -> SyntaxResult<CssSimpleFunction> { support::required_node(&self.syntax, 0usize) } } #[cfg(feature = "serde")] impl Serialize for CssAnyFunction { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { self.as_fields().serialize(serializer) } } #[cfg_attr(feature = "serde", derive(Serialize))] pub struct CssAnyFunctionFields { pub css_simple_function: SyntaxResult<CssSimpleFunction>, } #[derive(Clone, PartialEq, Eq, Hash)] pub struct CssAtKeyframes { pub(crate) syntax: SyntaxNode, } impl CssAtKeyframes { #[doc = r" Create an AstNode from a SyntaxNode without checking its kind"] #[doc = r""] #[doc = r" # Safety"] #[doc = r" This function must be guarded with a call to [AstNode::can_cast]"] #[doc = r" or a match on [SyntaxNode::kind]"] #[inline] pub const unsafe fn new_unchecked(syntax: SyntaxNode) -> Self { Self { syntax } } pub fn as_fields(&self) -> CssAtKeyframesFields { CssAtKeyframesFields { at_token: self.at_token(), keyframes_token: self.keyframes_token(), name: self.name(), css_string: self.css_string(), body: self.body(), } } pub fn at_token(&self) -> SyntaxResult<SyntaxToken> { support::required_token(&self.syntax, 0usize) } pub fn keyframes_token(&self) -> SyntaxResult<SyntaxToken> { support::required_token(&self.syntax, 1usize) } pub fn name(&self) -> SyntaxResult<CssIdentifier> { support::required_node(&self.syntax, 2usize) } pub fn css_string(&self) -> SyntaxResult<CssString> { support::required_node(&self.syntax, 3usize) } pub fn body(&self) -> SyntaxResult<CssAtKeyframesBody> { support::required_node(&self.syntax, 4usize) } } #[cfg(feature = "serde")] impl Serialize for CssAtKeyframes { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { self.as_fields().serialize(serializer) } } #[cfg_attr(feature = "serde", derive(Serialize))] pub struct CssAtKeyframesFields { pub at_token: SyntaxResult<SyntaxToken>, pub keyframes_token: SyntaxResult<SyntaxToken>, pub name: SyntaxResult<CssIdentifier>, pub css_string: SyntaxResult<CssString>, pub body: SyntaxResult<CssAtKeyframesBody>, } #[derive(Clone, PartialEq, Eq, Hash)] pub struct CssAtKeyframesBody { pub(crate) syntax: SyntaxNode, } impl CssAtKeyframesBody { #[doc = r" Create an AstNode from a SyntaxNode without checking its kind"] #[doc = r""] #[doc = r" # Safety"] #[doc = r" This function must be guarded with a call to [AstNode::can_cast]"] #[doc = r" or a match on [SyntaxNode::kind]"] #[inline] pub const unsafe fn new_unchecked(syntax: SyntaxNode) -> Self { Self { syntax } } pub fn as_fields(&self) -> CssAtKeyframesBodyFields { CssAtKeyframesBodyFields { l_curly_token: self.l_curly_token(), items: self.items(), r_curly_token: self.r_curly_token(), } } pub fn l_curly_token(&self) -> SyntaxResult<SyntaxToken> { support::required_token(&self.syntax, 0usize) } pub fn items(&self) -> CssAtKeyframesItemList { support::list(&self.syntax, 1usize) } pub fn r_curly_token(&self) -> SyntaxResult<SyntaxToken> { support::required_token(&self.syntax, 2usize) } } #[cfg(feature = "serde")] impl Serialize for CssAtKeyframesBody { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { self.as_fields().serialize(serializer) } } #[cfg_attr(feature = "serde", derive(Serialize))] pub struct CssAtKeyframesBodyFields { pub l_curly_token: SyntaxResult<SyntaxToken>, pub items: CssAtKeyframesItemList, pub r_curly_token: SyntaxResult<SyntaxToken>, } #[derive(Clone, PartialEq, Eq, Hash)] pub struct CssAtMedia { pub(crate) syntax: SyntaxNode, } impl CssAtMedia { #[doc = r" Create an AstNode from a SyntaxNode without checking its kind"] #[doc = r""] #[doc = r" # Safety"] #[doc = r" This function must be guarded with a call to [AstNode::can_cast]"] #[doc = r" or a match on [SyntaxNode::kind]"] #[inline] pub const unsafe fn new_unchecked(syntax: SyntaxNode) -> Self { Self { syntax } } pub fn as_fields(&self) -> CssAtMediaFields { CssAtMediaFields { at_token: self.at_token(), media_token: self.media_token(), query_list: self.query_list(), l_curly_token: self.l_curly_token(), body: self.body(), r_curly_token: self.r_curly_token(), } } pub fn at_token(&self) -> SyntaxResult<SyntaxToken> { support::required_token(&self.syntax, 0usize) } pub fn media_token(&self) -> SyntaxResult<SyntaxToken> { support::required_token(&self.syntax, 1usize) } pub fn query_list(&self) -> CssAtMediaQueryList { support::list(&self.syntax, 2usize) } pub fn l_curly_token(&self) -> SyntaxResult<SyntaxToken> { support::required_token(&self.syntax, 3usize) } pub fn body(&self) -> SyntaxResult<AnyCssRule> { support::required_node(&self.syntax, 4usize) } pub fn r_curly_token(&self) -> SyntaxResult<SyntaxToken> { support::required_token(&self.syntax, 5usize) } } #[cfg(feature = "serde")] impl Serialize for CssAtMedia { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { self.as_fields().serialize(serializer) } } #[cfg_attr(feature = "serde", derive(Serialize))] pub struct CssAtMediaFields { pub at_token: SyntaxResult<SyntaxToken>, pub media_token: SyntaxResult<SyntaxToken>, pub query_list: CssAtMediaQueryList, pub l_curly_token: SyntaxResult<SyntaxToken>, pub body: SyntaxResult<AnyCssRule>, pub r_curly_token: SyntaxResult<SyntaxToken>, } #[derive(Clone, PartialEq, Eq, Hash)] pub struct CssAtMediaQuery { pub(crate) syntax: SyntaxNode, } impl CssAtMediaQuery { #[doc = r" Create an AstNode from a SyntaxNode without checking its kind"] #[doc = r""] #[doc = r" # Safety"] #[doc = r" This function must be guarded with a call to [AstNode::can_cast]"] #[doc = r" or a match on [SyntaxNode::kind]"] #[inline] pub const unsafe fn new_unchecked(syntax: SyntaxNode) -> Self { Self { syntax } } pub fn as_fields(&self) -> CssAtMediaQueryFields { CssAtMediaQueryFields { condition_token: self.condition_token(), or_token: self.or_token(), only_token: self.only_token(), ty: self.ty(), consequent: self.consequent(), } } pub fn condition_token(&self) -> SyntaxResult<SyntaxToken> { support::required_token(&self.syntax, 0usize) } pub fn or_token(&self) -> SyntaxResult<SyntaxToken> { support::required_token(&self.syntax, 1usize) } pub fn only_token(&self) -> Option<SyntaxToken> { support::token(&self.syntax, 2usize) } pub fn ty(&self) -> SyntaxResult<AnyCssAtMediaQueryType> { support::required_node(&self.syntax, 3usize) } pub fn consequent(&self) -> Option<CssAtMediaQueryConsequent> { support::node(&self.syntax, 4usize) } } #[cfg(feature = "serde")] impl Serialize for CssAtMediaQuery { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { self.as_fields().serialize(serializer) } } #[cfg_attr(feature = "serde", derive(Serialize))] pub struct CssAtMediaQueryFields { pub condition_token: SyntaxResult<SyntaxToken>, pub or_token: SyntaxResult<SyntaxToken>, pub only_token: Option<SyntaxToken>, pub ty: SyntaxResult<AnyCssAtMediaQueryType>, pub consequent: Option<CssAtMediaQueryConsequent>, } #[derive(Clone, PartialEq, Eq, Hash)] pub struct CssAtMediaQueryConsequent { pub(crate) syntax: SyntaxNode, } impl CssAtMediaQueryConsequent { #[doc = r" Create an AstNode from a SyntaxNode without checking its kind"] #[doc = r""] #[doc = r" # Safety"] #[doc = r" This function must be guarded with a call to [AstNode::can_cast]"] #[doc = r" or a match on [SyntaxNode::kind]"] #[inline] pub const unsafe fn new_unchecked(syntax: SyntaxNode) -> Self { Self { syntax } } pub fn as_fields(&self) -> CssAtMediaQueryConsequentFields { CssAtMediaQueryConsequentFields { and_token: self.and_token(), condition_token: self.condition_token(), ty: self.ty(), } } pub fn and_token(&self) -> SyntaxResult<SyntaxToken> { support::required_token(&self.syntax, 0usize) } pub fn condition_token(&self) -> Option<SyntaxToken> { support::token(&self.syntax, 1usize) } pub fn ty(&self) -> SyntaxResult<AnyCssAtMediaQueryType> { support::required_node(&self.syntax, 2usize) } } #[cfg(feature = "serde")] impl Serialize for CssAtMediaQueryConsequent { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { self.as_fields().serialize(serializer) } } #[cfg_attr(feature = "serde", derive(Serialize))] pub struct CssAtMediaQueryConsequentFields { pub and_token: SyntaxResult<SyntaxToken>, pub condition_token: Option<SyntaxToken>, pub ty: SyntaxResult<AnyCssAtMediaQueryType>, } #[derive(Clone, PartialEq, Eq, Hash)] pub struct CssAtMediaQueryFeature { pub(crate) syntax: SyntaxNode, } impl CssAtMediaQueryFeature { #[doc = r" Create an AstNode from a SyntaxNode without checking its kind"] #[doc = r""] #[doc = r" # Safety"] #[doc = r" This function must be guarded with a call to [AstNode::can_cast]"] #[doc = r" or a match on [SyntaxNode::kind]"] #[inline] pub const unsafe fn new_unchecked(syntax: SyntaxNode) -> Self { Self { syntax } } pub fn as_fields(&self) -> CssAtMediaQueryFeatureFields { CssAtMediaQueryFeatureFields { l_paren_token: self.l_paren_token(), feature: self.feature(), r_paren_token: self.r_paren_token(), } } pub fn l_paren_token(&self) -> SyntaxResult<SyntaxToken> { support::required_token(&self.syntax, 0usize) } pub fn feature(&self) -> SyntaxResult<AnyCssAtMediaQueryFeatureType> { support::required_node(&self.syntax, 1usize) } pub fn r_paren_token(&self) -> SyntaxResult<SyntaxToken> { support::required_token(&self.syntax, 2usize) } } #[cfg(feature = "serde")] impl Serialize for CssAtMediaQueryFeature { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { self.as_fields().serialize(serializer) } } #[cfg_attr(feature = "serde", derive(Serialize))] pub struct CssAtMediaQueryFeatureFields { pub l_paren_token: SyntaxResult<SyntaxToken>, pub feature: SyntaxResult<AnyCssAtMediaQueryFeatureType>, pub r_paren_token: SyntaxResult<SyntaxToken>, } #[derive(Clone, PartialEq, Eq, Hash)] pub struct CssAtMediaQueryFeatureBoolean { pub(crate) syntax: SyntaxNode, } impl CssAtMediaQueryFeatureBoolean { #[doc = r" Create an AstNode from a SyntaxNode without checking its kind"] #[doc = r""] #[doc = r" # Safety"] #[doc = r" This function must be guarded with a call to [AstNode::can_cast]"] #[doc = r" or a match on [SyntaxNode::kind]"] #[inline] pub const unsafe fn new_unchecked(syntax: SyntaxNode) -> Self { Self { syntax } } pub fn as_fields(&self) -> CssAtMediaQueryFeatureBooleanFields { CssAtMediaQueryFeatureBooleanFields { css_identifier: self.css_identifier(), } } pub fn css_identifier(&self) -> SyntaxResult<CssIdentifier> { support::required_node(&self.syntax, 0usize) } } #[cfg(feature = "serde")] impl Serialize for CssAtMediaQueryFeatureBoolean { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { self.as_fields().serialize(serializer) } } #[cfg_attr(feature = "serde", derive(Serialize))] pub struct CssAtMediaQueryFeatureBooleanFields { pub css_identifier: SyntaxResult<CssIdentifier>, } #[derive(Clone, PartialEq, Eq, Hash)] pub struct CssAtMediaQueryFeatureCompare { pub(crate) syntax: SyntaxNode, } impl CssAtMediaQueryFeatureCompare { #[doc = r" Create an AstNode from a SyntaxNode without checking its kind"] #[doc = r""] #[doc = r" # Safety"] #[doc = r" This function must be guarded with a call to [AstNode::can_cast]"] #[doc = r" or a match on [SyntaxNode::kind]"] #[inline] pub const unsafe fn new_unchecked(syntax: SyntaxNode) -> Self { Self { syntax } } pub fn as_fields(&self) -> CssAtMediaQueryFeatureCompareFields { CssAtMediaQueryFeatureCompareFields { name: self.name(), range: self.range(), value: self.value(), } } pub fn name(&self) -> SyntaxResult<CssIdentifier> { support::required_node(&self.syntax, 0usize) } pub fn range(&self) -> SyntaxResult<CssAtMediaQueryRange> { support::required_node(&self.syntax, 1usize) } pub fn value(&self) -> SyntaxResult<AnyCssValue> { support::required_node(&self.syntax, 2usize) } } #[cfg(feature = "serde")] impl Serialize for CssAtMediaQueryFeatureCompare { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { self.as_fields().serialize(serializer) } } #[cfg_attr(feature = "serde", derive(Serialize))] pub struct CssAtMediaQueryFeatureCompareFields { pub name: SyntaxResult<CssIdentifier>, pub range: SyntaxResult<CssAtMediaQueryRange>, pub value: SyntaxResult<AnyCssValue>, } #[derive(Clone, PartialEq, Eq, Hash)] pub struct CssAtMediaQueryFeaturePlain { pub(crate) syntax: SyntaxNode, } impl CssAtMediaQueryFeaturePlain { #[doc = r" Create an AstNode from a SyntaxNode without checking its kind"] #[doc = r""] #[doc = r" # Safety"] #[doc = r" This function must be guarded with a call to [AstNode::can_cast]"] #[doc = r" or a match on [SyntaxNode::kind]"] #[inline] pub const unsafe fn new_unchecked(syntax: SyntaxNode) -> Self { Self { syntax } } pub fn as_fields(&self) -> CssAtMediaQueryFeaturePlainFields { CssAtMediaQueryFeaturePlainFields { name: self.name(), colon_token: self.colon_token(), value: self.value(), } } pub fn name(&self) -> SyntaxResult<CssIdentifier> { support::required_node(&self.syntax, 0usize) } pub fn colon_token(&self) -> SyntaxResult<SyntaxToken> { support::required_token(&self.syntax, 1usize) } pub fn value(&self) -> SyntaxResult<AnyCssValue> { support::required_node(&self.syntax, 2usize) } } #[cfg(feature = "serde")] impl Serialize for CssAtMediaQueryFeaturePlain { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { self.as_fields().serialize(serializer) } } #[cfg_attr(feature = "serde", derive(Serialize))] pub struct CssAtMediaQueryFeaturePlainFields { pub name: SyntaxResult<CssIdentifier>, pub colon_token: SyntaxResult<SyntaxToken>, pub value: SyntaxResult<AnyCssValue>, } #[derive(Clone, PartialEq, Eq, Hash)] pub struct CssAtMediaQueryFeatureRange { pub(crate) syntax: SyntaxNode, } impl CssAtMediaQueryFeatureRange { #[doc = r" Create an AstNode from a SyntaxNode without checking its kind"] #[doc = r""] #[doc = r" # Safety"] #[doc = r" This function must be guarded with a call to [AstNode::can_cast]"] #[doc = r" or a match on [SyntaxNode::kind]"] #[inline] pub const unsafe fn new_unchecked(syntax: SyntaxNode) -> Self { Self { syntax } } pub fn as_fields(&self) -> CssAtMediaQueryFeatureRangeFields { CssAtMediaQueryFeatureRangeFields { first_value: self.first_value(), first_range: self.first_range(), name: self.name(), second_value: self.second_value(), second_range: self.second_range(), } } pub fn first_value(&self) -> SyntaxResult<AnyCssValue> { support::required_node(&self.syntax, 0usize) } pub fn first_range(&self) -> SyntaxResult<CssAtMediaQueryRange> { support::required_node(&self.syntax, 1usize) } pub fn name(&self) -> SyntaxResult<CssIdentifier> { support::required_node(&self.syntax, 2usize) } pub fn second_value(&self) -> SyntaxResult<AnyCssValue> { support::required_node(&self.syntax, 3usize) } pub fn second_range(&self) -> SyntaxResult<CssAtMediaQueryRange> { support::required_node(&self.syntax, 4usize) } } #[cfg(feature = "serde")] impl Serialize for CssAtMediaQueryFeatureRange { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { self.as_fields().serialize(serializer) } } #[cfg_attr(feature = "serde", derive(Serialize))] pub struct CssAtMediaQueryFeatureRangeFields { pub first_value: SyntaxResult<AnyCssValue>, pub first_range: SyntaxResult<CssAtMediaQueryRange>, pub name: SyntaxResult<CssIdentifier>, pub second_value: SyntaxResult<AnyCssValue>, pub second_range: SyntaxResult<CssAtMediaQueryRange>, } #[derive(Clone, PartialEq, Eq, Hash)] pub struct CssAtMediaQueryRange { pub(crate) syntax: SyntaxNode, } impl CssAtMediaQueryRange { #[doc = r" Create an AstNode from a SyntaxNode without checking its kind"] #[doc = r""] #[doc = r" # Safety"] #[doc = r" This function must be guarded with a call to [AstNode::can_cast]"] #[doc = r" or a match on [SyntaxNode::kind]"] #[inline] pub const unsafe fn new_unchecked(syntax: SyntaxNode) -> Self { Self { syntax } } pub fn as_fields(&self) -> CssAtMediaQueryRangeFields { CssAtMediaQueryRangeFields { r_angle_token: self.r_angle_token(), l_angle_token: self.l_angle_token(), greater_than_equal_token: self.greater_than_equal_token(), less_than_equal_token: self.less_than_equal_token(), } } pub fn r_angle_token(&self) -> SyntaxResult<SyntaxToken> { support::required_token(&self.syntax, 0usize) } pub fn l_angle_token(&self) -> SyntaxResult<SyntaxToken> { support::required_token(&self.syntax, 1usize) } pub fn greater_than_equal_token(&self) -> SyntaxResult<SyntaxToken> { support::required_token(&self.syntax, 2usize) } pub fn less_than_equal_token(&self) -> SyntaxResult<SyntaxToken> { support::required_token(&self.syntax, 3usize) } } #[cfg(feature = "serde")] impl Serialize for CssAtMediaQueryRange { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { self.as_fields().serialize(serializer) } } #[cfg_attr(feature = "serde", derive(Serialize))] pub struct CssAtMediaQueryRangeFields { pub r_angle_token: SyntaxResult<SyntaxToken>, pub l_angle_token: SyntaxResult<SyntaxToken>, pub greater_than_equal_token: SyntaxResult<SyntaxToken>, pub less_than_equal_token: SyntaxResult<SyntaxToken>, } #[derive(Clone, PartialEq, Eq, Hash)] pub struct CssAttribute { pub(crate) syntax: SyntaxNode, } impl CssAttribute { #[doc = r" Create an AstNode from a SyntaxNode without checking its kind"] #[doc = r""] #[doc = r" # Safety"] #[doc = r" This function must be guarded with a call to [AstNode::can_cast]"] #[doc = r" or a match on [SyntaxNode::kind]"] #[inline] pub const unsafe fn new_unchecked(syntax: SyntaxNode) -> Self { Self { syntax } } pub fn as_fields(&self) -> CssAttributeFields { CssAttributeFields { l_brack_token: self.l_brack_token(), attribute_name: self.attribute_name(), attribute_meta: self.attribute_meta(), r_brack_token: self.r_brack_token(), } } pub fn l_brack_token(&self) -> SyntaxResult<SyntaxToken> { support::required_token(&self.syntax, 0usize) } pub fn attribute_name(&self) -> SyntaxResult<CssAttributeName> { support::required_node(&self.syntax, 1usize) } pub fn attribute_meta(&self) -> Option<CssAttributeMeta> { support::node(&self.syntax, 2usize) } pub fn r_brack_token(&self) -> SyntaxResult<SyntaxToken> { support::required_token(&self.syntax, 3usize) } } #[cfg(feature = "serde")] impl Serialize for CssAttribute { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { self.as_fields().serialize(serializer) } } #[cfg_attr(feature = "serde", derive(Serialize))] pub struct CssAttributeFields { pub l_brack_token: SyntaxResult<SyntaxToken>, pub attribute_name: SyntaxResult<CssAttributeName>, pub attribute_meta: Option<CssAttributeMeta>, pub r_brack_token: SyntaxResult<SyntaxToken>, } #[derive(Clone, PartialEq, Eq, Hash)] pub struct CssAttributeMatcher { pub(crate) syntax: SyntaxNode, } impl CssAttributeMatcher { #[doc = r" Create an AstNode from a SyntaxNode without checking its kind"] #[doc = r""] #[doc = r" # Safety"] #[doc = r" This function must be guarded with a call to [AstNode::can_cast]"] #[doc = r" or a match on [SyntaxNode::kind]"] #[inline] pub const unsafe fn new_unchecked(syntax: SyntaxNode) -> Self { Self { syntax } } pub fn as_fields(&self) -> CssAttributeMatcherFields { CssAttributeMatcherFields { matcher_type_token: self.matcher_type_token(), exactly_or_hyphen_token: self.exactly_or_hyphen_token(), prefix_token: self.prefix_token(), suffix_token: self.suffix_token(), times_assign_token: self.times_assign_token(), eq_token: self.eq_token(), matcher_name: self.matcher_name(), css_identifier: self.css_identifier(), } } pub fn matcher_type_token(&self) -> SyntaxResult<SyntaxToken> { support::required_token(&self.syntax, 0usize) } pub fn exactly_or_hyphen_token(&self) -> SyntaxResult<SyntaxToken> { support::required_token(&self.syntax, 1usize) } pub fn prefix_token(&self) -> SyntaxResult<SyntaxToken> { support::required_token(&self.syntax, 2usize) } pub fn suffix_token(&self) -> SyntaxResult<SyntaxToken> { support::required_token(&self.syntax, 3usize) } pub fn times_assign_token(&self) -> SyntaxResult<SyntaxToken> { support::required_token(&self.syntax, 4usize) } pub fn eq_token(&self) -> SyntaxResult<SyntaxToken> { support::required_token(&self.syntax, 5usize) } pub fn matcher_name(&self) -> SyntaxResult<CssString> { support::required_node(&self.syntax, 6usize) } pub fn css_identifier(&self) -> SyntaxResult<CssIdentifier> { support::required_node(&self.syntax, 7usize) } } #[cfg(feature = "serde")] impl Serialize for CssAttributeMatcher { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { self.as_fields().serialize(serializer) } } #[cfg_attr(feature = "serde", derive(Serialize))] pub struct CssAttributeMatcherFields { pub matcher_type_token: SyntaxResult<SyntaxToken>, pub exactly_or_hyphen_token: SyntaxResult<SyntaxToken>, pub prefix_token: SyntaxResult<SyntaxToken>, pub suffix_token: SyntaxResult<SyntaxToken>, pub times_assign_token: SyntaxResult<SyntaxToken>, pub eq_token: SyntaxResult<SyntaxToken>, pub matcher_name: SyntaxResult<CssString>, pub css_identifier: SyntaxResult<CssIdentifier>, } #[derive(Clone, PartialEq, Eq, Hash)] pub struct CssAttributeMeta { pub(crate) syntax: SyntaxNode, } impl CssAttributeMeta { #[doc = r" Create an AstNode from a SyntaxNode without checking its kind"] #[doc = r""] #[doc = r" # Safety"] #[doc = r" This function must be guarded with a call to [AstNode::can_cast]"] #[doc = r" or a match on [SyntaxNode::kind]"] #[inline] pub const unsafe fn new_unchecked(syntax: SyntaxNode) -> Self { Self { syntax } } pub fn as_fields(&self) -> CssAttributeMetaFields { CssAttributeMetaFields { attribute_matcher: self.attribute_matcher(), attribute_modifier: self.attribute_modifier(), } } pub fn attribute_matcher(&self) -> Option<CssAttributeMatcher> { support::node(&self.syntax, 0usize) } pub fn attribute_modifier(&self) -> Option<CssAttributeModifier> { support::node(&self.syntax, 1usize) } } #[cfg(feature = "serde")] impl Serialize for CssAttributeMeta { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { self.as_fields().serialize(serializer) } } #[cfg_attr(feature = "serde", derive(Serialize))] pub struct CssAttributeMetaFields { pub attribute_matcher: Option<CssAttributeMatcher>, pub attribute_modifier: Option<CssAttributeModifier>, } #[derive(Clone, PartialEq, Eq, Hash)] pub struct CssAttributeModifier { pub(crate) syntax: SyntaxNode, } impl CssAttributeModifier { #[doc = r" Create an AstNode from a SyntaxNode without checking its kind"] #[doc = r""] #[doc = r" # Safety"] #[doc = r" This function must be guarded with a call to [AstNode::can_cast]"] #[doc = r" or a match on [SyntaxNode::kind]"] #[inline] pub const unsafe fn new_unchecked(syntax: SyntaxNode) -> Self { Self { syntax } } pub fn as_fields(&self) -> CssAttributeModifierFields { CssAttributeModifierFields { i_token: self.i_token(), } } pub fn i_token(&self) -> SyntaxResult<SyntaxToken> { support::required_token(&self.syntax, 0usize) } } #[cfg(feature = "serde")] impl Serialize for CssAttributeModifier { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { self.as_fields().serialize(serializer) } } #[cfg_attr(feature = "serde", derive(Serialize))] pub struct CssAttributeModifierFields { pub i_token: SyntaxResult<SyntaxToken>, } #[derive(Clone, PartialEq, Eq, Hash)] pub struct CssAttributeName { pub(crate) syntax: SyntaxNode, } impl CssAttributeName { #[doc = r" Create an AstNode from a SyntaxNode without checking its kind"] #[doc = r""] #[doc = r" # Safety"] #[doc = r" This function must be guarded with a call to [AstNode::can_cast]"] #[doc = r" or a match on [SyntaxNode::kind]"] #[inline] pub const unsafe fn new_unchecked(syntax: SyntaxNode) -> Self { Self { syntax } } pub fn as_fields(&self) -> CssAttributeNameFields { CssAttributeNameFields { css_string: self.css_string(), } } pub fn css_string(&self) -> SyntaxResult<CssString> { support::required_node(&self.syntax, 0usize) } } #[cfg(feature = "serde")] impl Serialize for CssAttributeName { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { self.as_fields().serialize(serializer) } } #[cfg_attr(feature = "serde", derive(Serialize))] pub struct CssAttributeNameFields { pub css_string: SyntaxResult<CssString>, } #[derive(Clone, PartialEq, Eq, Hash)] pub struct CssAttributeSelectorPattern { pub(crate) syntax: SyntaxNode, } impl CssAttributeSelectorPattern { #[doc = r" Create an AstNode from a SyntaxNode without checking its kind"] #[doc = r""] #[doc = r" # Safety"] #[doc = r" This function must be guarded with a call to [AstNode::can_cast]"] #[doc = r" or a match on [SyntaxNode::kind]"] #[inline] pub const unsafe fn new_unchecked(syntax: SyntaxNode) -> Self { Self { syntax } } pub fn as_fields(&self) -> CssAttributeSelectorPatternFields { CssAttributeSelectorPatternFields { name: self.name(), attribute_list: self.attribute_list(), } } pub fn name(&self) -> SyntaxResult<CssIdentifier> { support::required_node(&self.syntax, 0usize) } pub fn attribute_list(&self) -> CssAttributeList { support::list(&self.syntax, 1usize) } } #[cfg(feature = "serde")] impl Serialize for CssAttributeSelectorPattern { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { self.as_fields().serialize(serializer) } } #[cfg_attr(feature = "serde", derive(Serialize))] pub struct CssAttributeSelectorPatternFields { pub name: SyntaxResult<CssIdentifier>, pub attribute_list: CssAttributeList, } #[derive(Clone, PartialEq, Eq, Hash)] pub struct CssBlock { pub(crate) syntax: SyntaxNode, } impl CssBlock { #[doc = r" Create an AstNode from a SyntaxNode without checking its kind"] #[doc = r""] #[doc = r" # Safety"] #[doc = r" This function must be guarded with a call to [AstNode::can_cast]"] #[doc = r" or a match on [SyntaxNode::kind]"] #[inline] pub const unsafe fn new_unchecked(syntax: SyntaxNode) -> Self { Self { syntax } } pub fn as_fields(&self) -> CssBlockFields { CssBlockFields { l_curly_token: self.l_curly_token(), declaration_list: self.declaration_list(), r_curly_token: self.r_curly_token(), } } pub fn l_curly_token(&self) -> SyntaxResult<SyntaxToken> { support::required_token(&self.syntax, 0usize) } pub fn declaration_list(&self) -> CssDeclarationList { support::list(&self.syntax, 1usize) } pub fn r_curly_token(&self) -> SyntaxResult<SyntaxToken> { support::required_token(&self.syntax, 2usize) } } #[cfg(feature = "serde")] impl Serialize for CssBlock { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { self.as_fields().serialize(serializer) } } #[cfg_attr(feature = "serde", derive(Serialize))] pub struct CssBlockFields { pub l_curly_token: SyntaxResult<SyntaxToken>, pub declaration_list: CssDeclarationList, pub r_curly_token: SyntaxResult<SyntaxToken>, } #[derive(Clone, PartialEq, Eq, Hash)] pub struct CssClassSelectorPattern { pub(crate) syntax: SyntaxNode, } impl CssClassSelectorPattern { #[doc = r" Create an AstNode from a SyntaxNode without checking its kind"] #[doc = r""] #[doc = r" # Safety"] #[doc = r" This function must be guarded with a call to [AstNode::can_cast]"] #[doc = r" or a match on [SyntaxNode::kind]"] #[inline] pub const unsafe fn new_unchecked(syntax: SyntaxNode) -> Self { Self { syntax } } pub fn as_fields(&self) -> CssClassSelectorPatternFields { CssClassSelectorPatternFields { dot_token: self.dot_token(), name: self.name(), } } pub fn dot_token(&self) -> SyntaxResult<SyntaxToken> { support::required_token(&self.syntax, 0usize) } pub fn name(&self) -> SyntaxResult<CssIdentifier> { support::required_node(&self.syntax, 1usize) } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
true
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_diagnostics_categories/build.rs
crates/rome_diagnostics_categories/build.rs
use quote::{format_ident, quote}; use std::{env, fs, io, path::PathBuf}; macro_rules! define_categories { ( $( $name_link:literal : $link:literal, )* ; $( $name:literal , )* ) => { const CATEGORIES: &[(&str, Option<&str>)] = &[ $( ($name_link, Some($link)), )* $( ($name, None), )* ]; }; } include!("src/categories.rs"); pub fn main() -> io::Result<()> { let mut metadata = Vec::with_capacity(CATEGORIES.len()); let mut macro_arms = Vec::with_capacity(CATEGORIES.len()); let mut parse_arms = Vec::with_capacity(CATEGORIES.len()); let mut enum_variants = Vec::with_capacity(CATEGORIES.len()); let mut concat_macro_arms = Vec::with_capacity(CATEGORIES.len()); for (name, link) in CATEGORIES { let meta_name = name.replace('/', "_").to_uppercase(); let meta_ident = format_ident!("{meta_name}"); let link = if let Some(link) = link { quote! { Some(#link) } } else { quote! { None } }; metadata.push(quote! { pub static #meta_ident: crate::Category = crate::Category { name: #name, link: #link, }; }); macro_arms.push(quote! { (#name) => { &$crate::registry::#meta_ident }; }); parse_arms.push(quote! { #name => Ok(&crate::registry::#meta_ident), }); enum_variants.push(*name); let parts = name.split('/'); concat_macro_arms.push(quote! { ( #( #parts ),* ) => { &$crate::registry::#meta_ident }; }); } let tokens = quote! { impl FromStr for &'static Category { type Err = (); fn from_str(name: &str) -> Result<Self, ()> { match name { #( #parse_arms )* _ => Err(()), } } } #[cfg(feature = "schemars")] impl schemars::JsonSchema for &'static Category { fn schema_name() -> String { String::from("Category") } fn json_schema(_gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema { schemars::schema::Schema::Object(schemars::schema::SchemaObject { instance_type: Some(schemars::schema::InstanceType::String.into()), enum_values: Some(vec![#( #enum_variants.into() ),*]), ..Default::default() }) } } /// The `category!` macro can be used to statically lookup a category /// by name from the registry /// /// # Example /// /// ``` /// # use rome_diagnostics_categories::{Category, category}; /// let category: &'static Category = category!("internalError/io"); /// assert_eq!(category.name(), "internalError/io"); /// assert_eq!(category.link(), None); /// ``` #[macro_export] macro_rules! category { #( #macro_arms )* ( $name:literal ) => { compile_error!(concat!("Unregistered diagnostic category \"", $name, "\", please add it to \"crates/rome_diagnostics_categories/src/categories.rs\"")) }; ( $( $parts:tt )* ) => { compile_error!(concat!("Invalid diagnostic category `", stringify!($( $parts )*), "`, expected a single string literal")) }; } /// The `category_concat!` macro is a variant of `category!` using a /// slightly different syntax, for use in the `declare_group` and /// `declare_rule` macros in the analyzer #[macro_export] macro_rules! category_concat { #( #concat_macro_arms )* ( @compile_error $( $parts:tt )* ) => { compile_error!(concat!("Unregistered diagnostic category \"", $( $parts, )* "\", please add it to \"crates/rome_diagnostics_categories/src/categories.rs\"")) }; ( $( $parts:tt ),* ) => { $crate::category_concat!( @compile_error $( $parts )"/"* ) }; ( $( $parts:tt )* ) => { compile_error!(concat!("Invalid diagnostic category `", stringify!($( $parts )*), "`, expected a comma-separated list of string literals")) }; } pub mod registry { #( #metadata )* } }; let out_dir = env::var("OUT_DIR").unwrap(); fs::write( PathBuf::from(out_dir).join("categories.rs"), tokens.to_string(), )?; Ok(()) }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_diagnostics_categories/src/lib.rs
crates/rome_diagnostics_categories/src/lib.rs
use std::{ hash::{Hash, Hasher}, str::FromStr, }; /// Metadata for a diagnostic category /// /// This type cannot be instantiated outside of the `rome_diagnostics_categories` /// crate, which serves as a registry for all known diagnostic categories /// (currently this registry is fully static and generated at compile time) #[derive(Debug)] pub struct Category { name: &'static str, link: Option<&'static str>, } impl Category { /// Return the name of this category pub fn name(&self) -> &'static str { self.name } /// Return the hyperlink associated with this category if it has one /// /// This will generally be a link to the documentation page for diagnostics /// with this category pub fn link(&self) -> Option<&'static str> { self.link } } impl Eq for Category {} impl PartialEq for Category { fn eq(&self, other: &Self) -> bool { self.name == other.name } } impl Hash for Category { fn hash<H: Hasher>(&self, state: &mut H) { self.name.hash(state); } } #[cfg(feature = "serde")] impl serde::Serialize for &'static Category { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { self.name().serialize(serializer) } } #[cfg(feature = "serde")] struct CategoryVisitor; #[cfg(feature = "serde")] fn deserialize_parse<E: serde::de::Error>(code: &str) -> Result<&'static Category, E> { code.parse().map_err(|()| { serde::de::Error::custom(format_args!("failed to deserialize category from {code}")) }) } #[cfg(feature = "serde")] impl<'de> serde::de::Visitor<'de> for CategoryVisitor { type Value = &'static Category; fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { formatter.write_str("a borrowed string") } fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: serde::de::Error, { deserialize_parse(v) } fn visit_borrowed_str<E>(self, v: &'de str) -> Result<Self::Value, E> where E: serde::de::Error, { deserialize_parse(v) } fn visit_string<E>(self, v: String) -> Result<Self::Value, E> where E: serde::de::Error, { deserialize_parse(&v) } } #[cfg(feature = "serde")] impl<'de> serde::Deserialize<'de> for &'static Category { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { deserializer.deserialize_str(CategoryVisitor) } } // Import the code generated by the build script from the content of `src/categories.rs` include!(concat!(env!("OUT_DIR"), "/categories.rs"));
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_diagnostics_categories/src/categories.rs
crates/rome_diagnostics_categories/src/categories.rs
// This file contains the list of all diagnostic categories for the Rome // toolchain // // The `define_categories` macro is preprocessed in the build script for the // crate in order to generate the static registry. The body of the macro // consists of a list of key-value pairs defining the categories that have an // associated hyperlink, then a list of string literals defining the remaining // categories without a link. define_categories! { // Lint categories // a11y "lint/a11y/noAccessKey": "https://docs.rome.tools/lint/rules/noAccessKey", "lint/a11y/noAutofocus": "https://docs.rome.tools/lint/rules/noAutofocus", "lint/a11y/noBlankTarget": "https://docs.rome.tools/lint/rules/noBlankTarget", "lint/a11y/noDistractingElements": "https://docs.rome.tools/lint/rules/noDistractingElements", "lint/a11y/noHeaderScope": "https://docs.rome.tools/lint/rules/noHeaderScope", "lint/a11y/noNoninteractiveElementToInteractiveRole": "https://docs.rome.tools/lint/rules/noNoninteractiveElementToInteractiveRole", "lint/a11y/noPositiveTabindex": "https://docs.rome.tools/lint/rules/noPositiveTabindex", "lint/a11y/noRedundantAlt": "https://docs.rome.tools/lint/rules/noRedundantAlt", "lint/a11y/noSvgWithoutTitle": "https://docs.rome.tools/lint/rules/noSvgWithoutTitle", "lint/a11y/useAltText": "https://docs.rome.tools/lint/rules/useAltText", "lint/a11y/useAnchorContent": "https://docs.rome.tools/lint/rules/useAnchorContent", "lint/a11y/useAriaPropsForRole": "https://docs.rome.tools/lint/rules/useAriaPropsForRole", "lint/a11y/useButtonType": "https://docs.rome.tools/lint/rules/useButtonType", "lint/a11y/useHeadingContent": "https://docs.rome.tools/lint/rules/useHeadingContent", "lint/a11y/useHtmlLang": "https://docs.rome.tools/lint/rules/useHtmlLang", "lint/a11y/useIframeTitle": "https://docs.rome.tools/lint/rules/useIframeTitle", "lint/a11y/useKeyWithClickEvents": "https://docs.rome.tools/lint/rules/useKeyWithClickEvents", "lint/a11y/useKeyWithMouseEvents": "https://docs.rome.tools/lint/rules/useKeyWithMouseEvents", "lint/a11y/useMediaCaption": "https://docs.rome.tools/lint/rules/useMediaCaption", "lint/a11y/useValidAnchor": "https://docs.rome.tools/lint/rules/useValidAnchor", "lint/a11y/useValidAriaProps":"https://docs.rome.tools/lint/rules/useValidAriaProps", "lint/a11y/useValidLang":"https://docs.rome.tools/lint/rules/useValidLang", // complexity "lint/complexity/noExtraBooleanCast": "https://docs.rome.tools/lint/rules/noExtraBooleanCast", "lint/complexity/noForEach": "https://docs.rome.tools/lint/rules/noForEach", "lint/complexity/noMultipleSpacesInRegularExpressionLiterals": "https://docs.rome.tools/lint/rules/noMultipleSpacesInRegularExpressionLiterals", "lint/complexity/noUselessCatch": "https://docs.rome.tools/lint/rules/noUselessCatch", "lint/complexity/noUselessConstructor": "https://docs.rome.tools/lint/rules/noUselessConstructor", "lint/complexity/noUselessFragments": "https://docs.rome.tools/lint/rules/noUselessFragments", "lint/complexity/noUselessLabel":"https://docs.rome.tools/lint/rules/noUselessLabel", "lint/complexity/noUselessRename": "https://docs.rome.tools/lint/rules/noUselessRename", "lint/complexity/noUselessSwitchCase": "https://docs.rome.tools/lint/rules/noUselessSwitchCase", "lint/complexity/noUselessTypeConstraint": "https://docs.rome.tools/lint/rules/noUselessTypeConstraint", "lint/complexity/noWith": "https://docs.rome.tools/lint/rules/noWith", "lint/complexity/useFlatMap": "https://docs.rome.tools/lint/rules/useFlatMap", "lint/complexity/useLiteralKeys": "https://docs.rome.tools/lint/rules/useLiteralKeys", "lint/complexity/useOptionalChain": "https://docs.rome.tools/lint/rules/useOptionalChain", "lint/complexity/useSimpleNumberKeys": "https://docs.rome.tools/lint/rules/useSimpleNumberKeys", "lint/complexity/useSimplifiedLogicExpression": "https://docs.rome.tools/lint/rules/useSimplifiedLogicExpression", // correctness "lint/correctness/noChildrenProp": "https://docs.rome.tools/lint/rules/noChildrenProp", "lint/correctness/noConstAssign": "https://docs.rome.tools/lint/rules/noConstAssign", "lint/correctness/noConstructorReturn": "https://docs.rome.tools/lint/rules/noConstructorReturn", "lint/correctness/noEmptyPattern": "https://docs.rome.tools/lint/rules/noEmptyPattern", "lint/correctness/noGlobalObjectCalls": "https://docs.rome.tools/lint/rules/noGlobalObjectCalls", "lint/correctness/noInnerDeclarations": "https://docs.rome.tools/lint/rules/noInnerDeclarations", "lint/correctness/noInvalidConstructorSuper": "https://docs.rome.tools/lint/rules/noInvalidConstructorSuper", "lint/correctness/useIsNan": "https://docs.rome.tools/lint/rules/useIsNan", "lint/correctness/noNewSymbol": "https://docs.rome.tools/lint/rules/noNewSymbol", "lint/correctness/noPrecisionLoss": "https://docs.rome.tools/lint/rules/noPrecisionLoss", "lint/correctness/noRenderReturnValue": "https://docs.rome.tools/lint/rules/noRenderReturnValue", "lint/correctness/noSetterReturn": "https://docs.rome.tools/lint/rules/noSetterReturn", "lint/correctness/noStringCaseMismatch": "https://docs.rome.tools/lint/rules/noStringCaseMismatch", "lint/correctness/noSwitchDeclarations": "https://docs.rome.tools/lint/rules/noSwitchDeclarations", "lint/correctness/noUndeclaredVariables": "https://docs.rome.tools/lint/rules/noUndeclaredVariables", "lint/correctness/noUnnecessaryContinue": "https://docs.rome.tools/lint/rules/noUnnecessaryContinue", "lint/correctness/noUnreachable": "https://docs.rome.tools/lint/rules/noUnreachable", "lint/correctness/noUnreachableSuper": "https://rome.tools/docs/lint/rules/noUnreachableSuper", "lint/correctness/noUnsafeFinally": "https://docs.rome.tools/lint/rules/noUnsafeFinally", "lint/correctness/noUnsafeOptionalChaining": "https://docs.rome.tools/lint/rules/noUnsafeOptionalChaining", "lint/correctness/noUnusedLabels": "https://docs.rome.tools/lint/rules/noUnusedLabels", "lint/correctness/noUnusedVariables": "https://docs.rome.tools/lint/rules/noUnusedVariables", "lint/correctness/noVoidElementsWithChildren": "https://docs.rome.tools/lint/rules/noVoidElementsWithChildren", "lint/correctness/noVoidTypeReturn": "https://docs.rome.tools/lint/rules/noVoidTypeReturn", "lint/correctness/useValidForDirection": "https://docs.rome.tools/lint/rules/useValidForDirection", "lint/correctness/useYield": "https://docs.rome.tools/lint/rules/useYield", // nursery "lint/nursery/noAccumulatingSpread": "https://docs.rome.tools/lint/rules/noAccumulatingSpread", "lint/nursery/noAriaUnsupportedElements": "https://docs.rome.tools/lint/rules/noAriaUnsupportedElements", "lint/nursery/noBannedTypes":"https://docs.rome.tools/lint/rules/noBannedTypes", "lint/nursery/noConfusingArrow": "https://docs.rome.tools/lint/rules/noConfusingArrow", "lint/nursery/noConstantCondition": "https://docs.rome.tools/lint/rules/noConstantCondition", "lint/nursery/noControlCharactersInRegex": "https://docs.rome.tools/lint/rules/noControlCharactersInRegex", "lint/nursery/noDuplicateJsonKeys": "https://docs.rome.tools/lint/rules/noDuplicateJsonKeys", "lint/nursery/noExcessiveComplexity": "https://docs.rome.tools/lint/rules/noExcessiveComplexity", "lint/nursery/noFallthroughSwitchClause": "https://docs.rome.tools/lint/rules/noFallthroughSwitchClause", "lint/nursery/noGlobalIsFinite": "https://docs.rome.tools/lint/rules/noGlobalIsFinite", "lint/nursery/noGlobalIsNan": "https://docs.rome.tools/lint/rules/noGlobalIsNan", "lint/nursery/noNoninteractiveTabindex": "https://docs.rome.tools/lint/rules/noNoninteractiveTabindex", "lint/nursery/noNonoctalDecimalEscape": "https://docs.rome.tools/lint/rules/noNonoctalDecimalEscape", "lint/nursery/noRedundantRoles": "https://docs.rome.tools/lint/rules/noRedundantRoles", "lint/nursery/noSelfAssign": "https://docs.rome.tools/lint/rules/noSelfAssign", "lint/nursery/noStaticOnlyClass": "https://docs.rome.tools/lint/rules/noStaticOnlyClass", "lint/nursery/noUnsafeDeclarationMerging": "https://docs.rome.tools/lint/rules/noUnsafeDeclarationMerging", "lint/nursery/noUselessEmptyExport": "https://docs.rome.tools/lint/rules/noUselessEmptyExport", "lint/nursery/noVoid": "https://docs.rome.tools/lint/rules/noVoid", "lint/nursery/useAriaPropTypes": "https://docs.rome.tools/lint/rules/useAriaPropTypes", "lint/nursery/useArrowFunction": "https://docs.rome.tools/lint/rules/useArrowFunction", "lint/nursery/useExhaustiveDependencies": "https://docs.rome.tools/lint/rules/useExhaustiveDependencies", "lint/nursery/useGroupedTypeImport": "https://docs.rome.tools/lint/rules/useGroupedTypeImport", "lint/nursery/useHookAtTopLevel": "https://docs.rome.tools/lint/rules/useHookAtTopLevel", "lint/nursery/useImportRestrictions": "https://docs.rome.tools/lint/rules/useImportRestrictions", "lint/nursery/useIsArray": "https://docs.rome.tools/lint/rules/useIsArray", "lint/nursery/useLiteralEnumMembers": "https://docs.rome.tools/lint/rules/useLiteralEnumMembers", "lint/nursery/useNamingConvention": "https://docs.rome.tools/lint/rules/useNamingConvention", // nursery end // performance "lint/performance/noDelete": "https://docs.rome.tools/lint/rules/noDelete", // security "lint/security/noDangerouslySetInnerHtml": "https://docs.rome.tools/lint/rules/noDangerouslySetInnerHtml", "lint/security/noDangerouslySetInnerHtmlWithChildren": "https://docs.rome.tools/lint/rules/noDangerouslySetInnerHtmlWithChildren", // style "lint/style/noArguments": "https://docs.rome.tools/lint/rules/noArguments", "lint/style/noCommaOperator": "https://docs.rome.tools/lint/rules/noCommaOperator", "lint/style/noImplicitBoolean": "https://docs.rome.tools/lint/rules/noImplicitBoolean", "lint/style/noInferrableTypes": "https://docs.rome.tools/lint/rules/noInferrableTypes", "lint/style/noNamespace": "https://docs.rome.tools/lint/rules/noNamespace", "lint/style/noNegationElse": "https://docs.rome.tools/lint/rules/noNegationElse", "lint/style/noNonNullAssertion": "https://docs.rome.tools/lint/rules/noNonNullAssertion", "lint/style/noParameterAssign": "https://docs.rome.tools/lint/rules/noParameterAssign", "lint/style/noParameterProperties": "https://docs.rome.tools/lint/rules/noParameterProperties", "lint/style/noRestrictedGlobals": "https://docs.rome.tools/lint/rules/noRestrictedGlobals", "lint/style/noShoutyConstants": "https://docs.rome.tools/lint/rules/noShoutyConstants", "lint/style/noUnusedTemplateLiteral": "https://docs.rome.tools/lint/rules/noUnusedTemplateLiteral", "lint/style/noVar": "https://docs.rome.tools/lint/rules/noVar", "lint/style/useBlockStatements": "https://docs.rome.tools/lint/rules/useBlockStatements", "lint/style/useConst":"https://docs.rome.tools/lint/rules/useConst", "lint/style/useDefaultParameterLast":"https://docs.rome.tools/lint/rules/useDefaultParameterLast", "lint/style/useEnumInitializers":"https://docs.rome.tools/lint/rules/useEnumInitializers", "lint/style/useExponentiationOperator": "https://docs.rome.tools/lint/rules/useExponentiationOperator", "lint/style/useFragmentSyntax": "https://docs.rome.tools/lint/rules/useFragmentSyntax", "lint/style/useNumericLiterals": "https://docs.rome.tools/lint/rules/useNumericLiterals", "lint/style/useSelfClosingElements": "https://docs.rome.tools/lint/rules/useSelfClosingElements", "lint/style/useShorthandArrayType": "https://docs.rome.tools/lint/rules/useShorthandArrayType", "lint/style/useSingleCaseStatement": "https://docs.rome.tools/lint/rules/useSingleCaseStatement", "lint/style/useSingleVarDeclarator": "https://docs.rome.tools/lint/rules/useSingleVarDeclarator", "lint/style/useTemplate": "https://docs.rome.tools/lint/rules/useTemplate", "lint/style/useWhile": "https://docs.rome.tools/lint/rules/useWhile", // suspicious "lint/suspicious/noArrayIndexKey": "https://docs.rome.tools/lint/rules/noArrayIndexKey", "lint/suspicious/noAssignInExpressions": "https://docs.rome.tools/lint/rules/noAssignInExpressions", "lint/suspicious/noAsyncPromiseExecutor": "https://docs.rome.tools/lint/rules/noAsyncPromiseExecutor", "lint/suspicious/noCatchAssign": "https://docs.rome.tools/lint/rules/noCatchAssign", "lint/suspicious/noClassAssign": "https://docs.rome.tools/lint/rules/noClassAssign", "lint/suspicious/noCommentText": "https://docs.rome.tools/lint/rules/noCommentText", "lint/suspicious/noCompareNegZero": "https://docs.rome.tools/lint/rules/noCompareNegZero", "lint/suspicious/noConfusingLabels": "https://docs.rome.tools/lint/rules/noConfusingLabels", "lint/suspicious/noConsoleLog": "https://docs.rome.tools/lint/rules/noConsoleLog", "lint/suspicious/noConstEnum": "https://docs.rome.tools/lint/rules/noConstEnum", "lint/suspicious/noDebugger": "https://docs.rome.tools/lint/rules/noDebugger", "lint/suspicious/noDoubleEquals": "https://docs.rome.tools/lint/rules/noDoubleEquals", "lint/suspicious/noDuplicateCase": "https://docs.rome.tools/lint/rules/noDuplicateCase", "lint/suspicious/noDuplicateClassMembers": "https://docs.rome.tools/lint/rules/noDuplicateClassMembers", "lint/suspicious/noDuplicateJsxProps": "https://docs.rome.tools/lint/rules/noDuplicateJsxProps", "lint/suspicious/noDuplicateObjectKeys":"https://docs.rome.tools/lint/rules/noDuplicateObjectKeys", "lint/suspicious/noDuplicateParameters": "https://docs.rome.tools/lint/rules/noDuplicateParameters", "lint/suspicious/noEmptyInterface": "https://docs.rome.tools/lint/rules/noEmptyInterface", "lint/suspicious/noExplicitAny": "https://docs.rome.tools/lint/rules/noExplicitAny", "lint/suspicious/noExtraNonNullAssertion":"https://docs.rome.tools/lint/rules/noExtraNonNullAssertion", "lint/suspicious/noFunctionAssign": "https://docs.rome.tools/lint/rules/noFunctionAssign", "lint/suspicious/noImportAssign": "https://docs.rome.tools/lint/rules/noImportAssign", "lint/suspicious/noLabelVar": "https://docs.rome.tools/lint/rules/noLabelVar", "lint/suspicious/noPrototypeBuiltins": "https://docs.rome.tools/lint/rules/noPrototypeBuiltins", "lint/suspicious/noRedeclare": "https://docs.rome.tools/lint/rules/noRedeclare", "lint/suspicious/noRedundantUseStrict": "https://docs.rome.tools/lint/rules/noRedundantUseStrict", "lint/suspicious/noSelfCompare": "https://docs.rome.tools/lint/rules/noSelfCompare", "lint/suspicious/noShadowRestrictedNames": "https://docs.rome.tools/lint/rules/noShadowRestrictedNames", "lint/suspicious/noSparseArray": "https://docs.rome.tools/lint/rules/noSparseArray", "lint/suspicious/noUnsafeNegation": "https://docs.rome.tools/lint/rules/noUnsafeNegation", "lint/suspicious/useDefaultSwitchClauseLast":"https://docs.rome.tools/lint/rules/useDefaultSwitchClauseLast", "lint/suspicious/useNamespaceKeyword": "https://docs.rome.tools/lint/rules/useNamespaceKeyword", "lint/suspicious/useValidTypeof": "https://docs.rome.tools/lint/rules/useValidTypeof", ; // General categories "files/missingHandler", "format", "check", "ci", "configuration", "organizeImports", "migrate", "deserialize", "internalError/io", "internalError/fs", "internalError/panic", // parse categories "parse", "parse/noSuperWithoutExtends", "parse/noDuplicatePrivateClassMembers", // Lint groups "lint", "lint/a11y", "lint/complexity", "lint/correctness", "lint/nursery", "lint/performance", "lint/security", "lint/style", "lint/suspicious", // Suppression comments "suppressions/parse", "suppressions/unknownGroup", "suppressions/unknownRule", "suppressions/unused", "suppressions/deprecatedSyntax", // Used in tests and examples "args/fileNotFound", "flags/invalid", "semanticTests", }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_lsp/src/diagnostics.rs
crates/rome_lsp/src/diagnostics.rs
use crate::utils::into_lsp_error; use anyhow::Error; use rome_service::WorkspaceError; use std::fmt::{Display, Formatter}; use tower_lsp::lsp_types::MessageType; #[derive(Debug)] pub enum LspError { WorkspaceError(WorkspaceError), Anyhow(anyhow::Error), } impl From<WorkspaceError> for LspError { fn from(value: WorkspaceError) -> Self { Self::WorkspaceError(value) } } impl From<anyhow::Error> for LspError { fn from(value: Error) -> Self { Self::Anyhow(value) } } impl Display for LspError { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { LspError::WorkspaceError(err) => { write!(f, "{}", err) } LspError::Anyhow(err) => { write!(f, "{}", err) } } } } /// Receives an error coming from a LSP query, and converts it into a JSON-RPC error. /// /// It accepts a `Client`, so contextual messages are sent to the user. pub(crate) async fn handle_lsp_error<T>( err: LspError, client: &tower_lsp::Client, ) -> Result<Option<T>, tower_lsp::jsonrpc::Error> { match err { LspError::WorkspaceError(err) => match err { // diagnostics that shouldn't raise an hard error, but send a message to the user WorkspaceError::FormatWithErrorsDisabled(_) | WorkspaceError::FileIgnored(_) | WorkspaceError::FileTooLarge(_) => { let message = format!("{}", err); client.show_message(MessageType::WARNING, message).await; Ok(None) } _ => Err(into_lsp_error(err)), }, LspError::Anyhow(err) => Err(into_lsp_error(err)), } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_lsp/src/lib.rs
crates/rome_lsp/src/lib.rs
mod capabilities; mod converters; mod diagnostics; mod documents; mod extension_settings; mod handlers; mod requests; mod server; mod session; mod utils; pub use crate::extension_settings::WorkspaceSettings; pub use crate::server::{LSPServer, ServerConnection, ServerFactory};
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_lsp/src/documents.rs
crates/rome_lsp/src/documents.rs
use crate::converters::line_index::LineIndex; /// Represents an open [`textDocument`]. Can be cheaply cloned. /// /// [`textDocument`]: https://microsoft.github.io/language-server-protocol/specifications/specification-3-17/#textDocumentItem #[derive(Clone)] pub(crate) struct Document { pub(crate) version: i32, pub(crate) line_index: LineIndex, } impl Document { pub(crate) fn new(version: i32, text: &str) -> Self { Self { version, line_index: LineIndex::new(text), } } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_lsp/src/handlers.rs
crates/rome_lsp/src/handlers.rs
pub(crate) mod analysis; pub(crate) mod formatting; pub(crate) mod rename; pub(crate) mod text_document;
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_lsp/src/session.rs
crates/rome_lsp/src/session.rs
use crate::converters::{negotiated_encoding, PositionEncoding, WideEncoding}; use crate::documents::Document; use crate::extension_settings::ExtensionSettings; use crate::extension_settings::CONFIGURATION_SECTION; use crate::utils; use anyhow::Result; use futures::stream::futures_unordered::FuturesUnordered; use futures::StreamExt; use rome_analyze::RuleCategories; use rome_console::markup; use rome_fs::{FileSystem, OsFileSystem, RomePath}; use rome_service::workspace::{ FeatureName, FeaturesBuilder, PullDiagnosticsParams, SupportsFeatureParams, }; use rome_service::workspace::{RageEntry, RageParams, RageResult, UpdateSettingsParams}; use rome_service::{load_config, ConfigurationBasePath, Workspace}; use rome_service::{DynRef, WorkspaceError}; use serde_json::Value; use std::collections::HashMap; use std::path::PathBuf; use std::sync::atomic::AtomicU8; use std::sync::atomic::Ordering; use std::sync::Arc; use std::sync::RwLock; use tokio::sync::Notify; use tokio::sync::OnceCell; use tower_lsp::lsp_types; use tower_lsp::lsp_types::Registration; use tower_lsp::lsp_types::Unregistration; use tower_lsp::lsp_types::Url; use tracing::{error, info, warn}; pub(crate) struct ClientInformation { /// The name of the client pub(crate) name: String, /// The version of the client pub(crate) version: Option<String>, } /// Key, uniquely identifying a LSP session. #[derive(Clone, Copy, Eq, PartialEq, Hash, Debug)] pub(crate) struct SessionKey(pub u64); /// Represents the state of an LSP server session. pub(crate) struct Session { /// The unique key identifying this session. pub(crate) key: SessionKey, /// The LSP client for this session. pub(crate) client: tower_lsp::Client, /// The parameters provided by the client in the "initialize" request initialize_params: OnceCell<InitializeParams>, /// The settings of the Rome extension (under the `rome` namespace) pub(crate) extension_settings: RwLock<ExtensionSettings>, pub(crate) workspace: Arc<dyn Workspace>, configuration_status: AtomicU8, /// File system to read files inside the workspace pub(crate) fs: DynRef<'static, dyn FileSystem>, documents: RwLock<HashMap<lsp_types::Url, Document>>, pub(crate) cancellation: Arc<Notify>, } /// The parameters provided by the client in the "initialize" request struct InitializeParams { /// The capabilities provided by the client as part of [`lsp_types::InitializeParams`] client_capabilities: lsp_types::ClientCapabilities, client_information: Option<ClientInformation>, root_uri: Option<Url>, } #[repr(u8)] enum ConfigurationStatus { /// The configuration file was properly loaded Loaded = 0, /// The configuration file does not exist Missing = 1, /// The configuration file exists but could not be loaded Error = 2, } impl TryFrom<u8> for ConfigurationStatus { type Error = (); fn try_from(value: u8) -> Result<Self, ()> { match value { 0 => Ok(Self::Loaded), 1 => Ok(Self::Missing), 2 => Ok(Self::Error), _ => Err(()), } } } pub(crate) type SessionHandle = Arc<Session>; /// Holds the set of capabilities supported by the Language Server /// instance and whether they are enabled or not #[derive(Default)] pub(crate) struct CapabilitySet { registry: HashMap<&'static str, (&'static str, CapabilityStatus)>, } /// Represents whether a capability is enabled or not, optionally holding the /// configuration associated with the capability pub(crate) enum CapabilityStatus { Enable(Option<Value>), Disable, } impl CapabilitySet { /// Insert a capability in the set pub(crate) fn add_capability( &mut self, id: &'static str, method: &'static str, status: CapabilityStatus, ) { self.registry.insert(id, (method, status)); } } impl Session { pub(crate) fn new( key: SessionKey, client: tower_lsp::Client, workspace: Arc<dyn Workspace>, cancellation: Arc<Notify>, ) -> Self { let documents = Default::default(); let config = RwLock::new(ExtensionSettings::new()); Self { key, client, initialize_params: OnceCell::default(), workspace, configuration_status: AtomicU8::new(ConfigurationStatus::Missing as u8), documents, extension_settings: config, fs: DynRef::Owned(Box::new(OsFileSystem)), cancellation, } } /// Initialize this session instance with the incoming initialization parameters from the client pub(crate) fn initialize( &self, client_capabilities: lsp_types::ClientCapabilities, client_information: Option<ClientInformation>, root_uri: Option<Url>, ) { let result = self.initialize_params.set(InitializeParams { client_capabilities, client_information, root_uri, }); if let Err(err) = result { error!("Failed to initialize session: {err}"); } } /// Register a set of capabilities with the client pub(crate) async fn register_capabilities(&self, capabilities: CapabilitySet) { let mut registrations = Vec::new(); let mut unregistrations = Vec::new(); let mut register_methods = String::new(); let mut unregister_methods = String::new(); for (id, (method, status)) in capabilities.registry { unregistrations.push(Unregistration { id: id.to_string(), method: method.to_string(), }); if !unregister_methods.is_empty() { unregister_methods.push_str(", "); } unregister_methods.push_str(method); if let CapabilityStatus::Enable(register_options) = status { registrations.push(Registration { id: id.to_string(), method: method.to_string(), register_options, }); if !register_methods.is_empty() { register_methods.push_str(", "); } register_methods.push_str(method); } } if let Err(e) = self.client.unregister_capability(unregistrations).await { error!( "Error unregistering {unregister_methods:?} capabilities: {}", e ); } else { info!("Unregister capabilities {unregister_methods:?}"); } if let Err(e) = self.client.register_capability(registrations).await { error!("Error registering {register_methods:?} capabilities: {}", e); } else { info!("Register capabilities {register_methods:?}"); } } /// Get a [`Document`] matching the provided [`lsp_types::Url`] /// /// If document does not exist, result is [SessionError::DocumentNotFound] pub(crate) fn document(&self, url: &lsp_types::Url) -> Result<Document, WorkspaceError> { self.documents .read() .unwrap() .get(url) .cloned() .ok_or_else(WorkspaceError::not_found) } /// Set the [`Document`] for the provided [`lsp_types::Url`] /// /// Used by [`handlers::text_document] to synchronize documents with the client. pub(crate) fn insert_document(&self, url: lsp_types::Url, document: Document) { self.documents.write().unwrap().insert(url, document); } /// Remove the [`Document`] matching the provided [`lsp_types::Url`] pub(crate) fn remove_document(&self, url: &lsp_types::Url) { self.documents.write().unwrap().remove(url); } pub(crate) fn file_path(&self, url: &lsp_types::Url) -> Result<RomePath> { let mut path_to_file = match url.to_file_path() { Err(_) => { // If we can't create a path, it's probably because the file doesn't exist. // It can be a newly created file that it's not on disk PathBuf::from(url.path()) } Ok(path) => path, }; let relative_path = self.initialize_params.get().and_then(|initialize_params| { let root_uri = initialize_params.root_uri.as_ref()?; let root_path = root_uri.to_file_path().ok()?; path_to_file.strip_prefix(&root_path).ok() }); if let Some(relative_path) = relative_path { path_to_file = relative_path.into(); } Ok(RomePath::new(path_to_file)) } /// Computes diagnostics for the file matching the provided url and publishes /// them to the client. Called from [`handlers::text_document`] when a file's /// contents changes. #[tracing::instrument(level = "debug", skip_all, fields(url = display(&url), diagnostic_count), err)] pub(crate) async fn update_diagnostics(&self, url: lsp_types::Url) -> Result<()> { let rome_path = self.file_path(&url)?; let doc = self.document(&url)?; let file_features = self.workspace.file_features(SupportsFeatureParams { feature: FeaturesBuilder::new() .with_linter() .with_organize_imports() .build(), path: rome_path.clone(), })?; let diagnostics = if self.is_linting_and_formatting_disabled() { tracing::trace!("Linting disabled because Rome configuration is missing and `requireConfiguration` is true."); vec![] } else if !file_features.supports_for(&FeatureName::Lint) && !file_features.supports_for(&FeatureName::OrganizeImports) { tracing::trace!("linting and import sorting are not supported: {file_features:?}"); // Sending empty vector clears published diagnostics vec![] } else { let mut categories = RuleCategories::SYNTAX; if file_features.supports_for(&FeatureName::Lint) { categories |= RuleCategories::LINT } if file_features.supports_for(&FeatureName::OrganizeImports) { categories |= RuleCategories::ACTION } let result = self.workspace.pull_diagnostics(PullDiagnosticsParams { path: rome_path, categories, max_diagnostics: u64::MAX, })?; tracing::trace!("rome diagnostics: {:#?}", result.diagnostics); let result = result .diagnostics .into_iter() .filter_map(|d| { match utils::diagnostic_to_lsp( d, &url, &doc.line_index, self.position_encoding(), ) { Ok(diag) => Some(diag), Err(err) => { tracing::error!("failed to convert diagnostic to LSP: {err:?}"); None } } }) .collect(); tracing::trace!("lsp diagnostics: {:#?}", result); result }; tracing::Span::current().record("diagnostic_count", diagnostics.len()); self.client .publish_diagnostics(url, diagnostics, Some(doc.version)) .await; Ok(()) } /// Updates diagnostics for every [`Document`] in this [`Session`] pub(crate) async fn update_all_diagnostics(&self) { let mut futures: FuturesUnordered<_> = self .documents .read() .unwrap() .keys() .map(|url| self.update_diagnostics(url.clone())) .collect(); while let Some(result) = futures.next().await { if let Err(e) = result { error!("Error while updating diagnostics: {}", e); } } } /// True if the client supports dynamic registration of "workspace/didChangeConfiguration" requests pub(crate) fn can_register_did_change_configuration(&self) -> bool { self.initialize_params .get() .and_then(|c| c.client_capabilities.workspace.as_ref()) .and_then(|c| c.did_change_configuration) .and_then(|c| c.dynamic_registration) == Some(true) } /// Returns the base path of the workspace on the filesystem if it has one pub(crate) fn base_path(&self) -> Option<PathBuf> { let initialize_params = self.initialize_params.get()?; let root_uri = initialize_params.root_uri.as_ref()?; match root_uri.to_file_path() { Ok(base_path) => Some(base_path), Err(()) => { error!( "The Workspace root URI {root_uri:?} could not be parsed as a filesystem path" ); None } } } /// Returns a reference to the client informations for this session pub(crate) fn client_information(&self) -> Option<&ClientInformation> { self.initialize_params.get()?.client_information.as_ref() } /// This function attempts to read the `rome.json` configuration file from /// the root URI and update the workspace settings accordingly #[tracing::instrument(level = "debug", skip(self))] pub(crate) async fn load_workspace_settings(&self) { let base_path = match self.base_path() { None => ConfigurationBasePath::default(), Some(path) => ConfigurationBasePath::Lsp(path), }; let status = match load_config(&self.fs, base_path) { Ok(Some(payload)) => { let (configuration, diagnostics) = payload.deserialized.consume(); if !diagnostics.is_empty() { warn!("The deserialization of the configuration resulted in errors. Rome will use its defaults where possible."); } info!("Loaded workspace settings: {configuration:#?}"); let result = self .workspace .update_settings(UpdateSettingsParams { configuration }); if let Err(error) = result { error!("Failed to set workspace settings: {}", error); ConfigurationStatus::Error } else { ConfigurationStatus::Loaded } } Ok(None) => { // Ignore, load_config already logs an error in this case ConfigurationStatus::Missing } Err(err) => { error!("Couldn't load the workspace settings, reason:\n {}", err); ConfigurationStatus::Error } }; self.set_configuration_status(status); } /// Requests "workspace/configuration" from client and updates Session config #[tracing::instrument(level = "debug", skip(self))] pub(crate) async fn load_extension_settings(&self) { let item = lsp_types::ConfigurationItem { scope_uri: None, section: Some(String::from(CONFIGURATION_SECTION)), }; let client_configurations = match self.client.configuration(vec![item]).await { Ok(client_configurations) => client_configurations, Err(err) => { error!("Couldn't read configuration from the client: {err}"); return; } }; let client_configuration = client_configurations.into_iter().next(); if let Some(client_configuration) = client_configuration { info!("Loaded client configuration: {client_configuration:#?}"); let mut config = self.extension_settings.write().unwrap(); if let Err(err) = config.set_workspace_settings(client_configuration) { error!("Couldn't set client configuration: {}", err); } } else { info!("Client did not return any configuration"); } } /// Broadcast a shutdown signal to all active connections pub(crate) fn broadcast_shutdown(&self) { self.cancellation.notify_one(); } pub(crate) fn failsafe_rage(&self, params: RageParams) -> RageResult { match self.workspace.rage(params) { Ok(result) => result, Err(err) => { let entries = vec![ RageEntry::section("Workspace"), RageEntry::markup(markup! { <Error>"\u{2716} Rage command failed:"</Error> {&format!("{err}")} }), ]; RageResult { entries } } } } fn configuration_status(&self) -> ConfigurationStatus { self.configuration_status .load(Ordering::Relaxed) .try_into() .unwrap() } fn set_configuration_status(&self, status: ConfigurationStatus) { self.configuration_status .store(status as u8, Ordering::Relaxed); } pub(crate) fn is_linting_and_formatting_disabled(&self) -> bool { match self.configuration_status() { ConfigurationStatus::Loaded => false, ConfigurationStatus::Missing => self .extension_settings .read() .unwrap() .requires_configuration(), ConfigurationStatus::Error => true, } } pub fn position_encoding(&self) -> PositionEncoding { self.initialize_params .get() .map(|params| negotiated_encoding(&params.client_capabilities)) .unwrap_or(PositionEncoding::Wide(WideEncoding::Utf16)) } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_lsp/src/utils.rs
crates/rome_lsp/src/utils.rs
use crate::converters::line_index::LineIndex; use crate::converters::{from_proto, to_proto, PositionEncoding}; use anyhow::{ensure, Context, Result}; use rome_analyze::ActionCategory; use rome_console::fmt::Termcolor; use rome_console::fmt::{self, Formatter}; use rome_console::MarkupBuf; use rome_diagnostics::termcolor::NoColor; use rome_diagnostics::{ Applicability, {Diagnostic, DiagnosticTags, Location, PrintDescription, Severity, Visit}, }; use rome_rowan::TextSize; use rome_service::workspace::CodeAction; use rome_text_edit::{CompressedOp, DiffOp, TextEdit}; use std::any::Any; use std::collections::HashMap; use std::fmt::{Debug, Display}; use std::ops::Range; use std::{io, mem}; use tower_lsp::jsonrpc::Error as LspError; use tower_lsp::lsp_types; use tower_lsp::lsp_types::{self as lsp, CodeDescription, Url}; use tracing::error; pub(crate) fn text_edit( line_index: &LineIndex, diff: TextEdit, position_encoding: PositionEncoding, ) -> Result<Vec<lsp::TextEdit>> { let mut result: Vec<lsp::TextEdit> = Vec::new(); let mut offset = TextSize::from(0); for op in diff.iter() { match op { CompressedOp::DiffOp(DiffOp::Equal { range }) => { offset += range.len(); } CompressedOp::DiffOp(DiffOp::Insert { range }) => { let start = to_proto::position(line_index, offset, position_encoding)?; // Merge with a previous delete operation if possible let last_edit = result.last_mut().filter(|text_edit| { text_edit.range.end == start && text_edit.new_text.is_empty() }); if let Some(last_edit) = last_edit { last_edit.new_text = diff.get_text(*range).to_string(); } else { result.push(lsp::TextEdit { range: lsp::Range::new(start, start), new_text: diff.get_text(*range).to_string(), }); } } CompressedOp::DiffOp(DiffOp::Delete { range }) => { let start = to_proto::position(line_index, offset, position_encoding)?; offset += range.len(); let end = to_proto::position(line_index, offset, position_encoding)?; result.push(lsp::TextEdit { range: lsp::Range::new(start, end), new_text: String::new(), }); } CompressedOp::EqualLines { line_count } => { let mut line_col = line_index .line_col(offset) .expect("diff length is overflowing the line count in the original file"); line_col.line += line_count.get() + 1; line_col.col = 0; // SAFETY: This should only happen if `line_index` wasn't built // from the same string as the old revision of `diff` let new_offset = line_index .offset(line_col) .expect("diff length is overflowing the line count in the original file"); offset = new_offset; } } } Ok(result) } pub(crate) fn code_fix_to_lsp( url: &lsp::Url, line_index: &LineIndex, position_encoding: PositionEncoding, diagnostics: &[lsp::Diagnostic], action: CodeAction, ) -> Result<lsp::CodeAction> { // Mark diagnostics emitted by the same rule as resolved by this action let diagnostics: Vec<_> = action .rule_name .as_ref() .filter(|_| action.category.matches("quickfix")) .map(|(group_name, rule_name)| { diagnostics .iter() .filter_map(|d| { let code = d.code.as_ref()?; let code = match code { lsp::NumberOrString::String(code) => code.as_str(), lsp::NumberOrString::Number(_) => return None, }; let code = code.strip_prefix("lint/")?; let code = code.strip_prefix(group_name.as_ref())?; let code = code.strip_prefix('/')?; if code == rule_name { Some(d.clone()) } else { None } }) .collect() }) .unwrap_or_default(); let kind = action.category.to_str(); let mut kind = kind.into_owned(); if !matches!(action.category, ActionCategory::Source(_)) { if let Some((group, rule)) = action.rule_name { kind.push('.'); kind.push_str(group.as_ref()); kind.push('.'); kind.push_str(rule.as_ref()); } } let suggestion = action.suggestion; let mut changes = HashMap::new(); let edits = text_edit(line_index, suggestion.suggestion, position_encoding)?; changes.insert(url.clone(), edits); let edit = lsp::WorkspaceEdit { changes: Some(changes), document_changes: None, change_annotations: None, }; let is_preferred = matches!(action.category, ActionCategory::Source(_)) || matches!(suggestion.applicability, Applicability::Always) && !action.category.matches("quickfix.suppressRule"); Ok(lsp::CodeAction { title: print_markup(&suggestion.msg), kind: Some(lsp::CodeActionKind::from(kind)), diagnostics: if !diagnostics.is_empty() { Some(diagnostics) } else { None }, edit: Some(edit), command: None, is_preferred: is_preferred.then_some(true), disabled: None, data: None, }) } /// Convert an [rome_diagnostics::Diagnostic] to a [lsp::Diagnostic], using the span /// of the diagnostic's primary label as the diagnostic range. /// Requires a [LineIndex] to convert a byte offset range to the line/col range /// expected by LSP. pub(crate) fn diagnostic_to_lsp<D: Diagnostic>( diagnostic: D, url: &lsp::Url, line_index: &LineIndex, position_encoding: PositionEncoding, ) -> Result<lsp::Diagnostic> { let location = diagnostic.location(); let span = location.span.context("diagnostic location has no span")?; let span = to_proto::range(line_index, span, position_encoding) .context("failed to convert diagnostic span to LSP range")?; let severity = match diagnostic.severity() { Severity::Fatal | Severity::Error => lsp::DiagnosticSeverity::ERROR, Severity::Warning => lsp::DiagnosticSeverity::WARNING, Severity::Information => lsp::DiagnosticSeverity::INFORMATION, Severity::Hint => lsp::DiagnosticSeverity::HINT, }; let code = diagnostic .category() .map(|category| lsp::NumberOrString::String(category.name().to_string())); let code_description = diagnostic .category() .and_then(|category| category.link()) .and_then(|link| { let href = Url::parse(link).ok()?; Some(CodeDescription { href }) }); let message = PrintDescription(&diagnostic).to_string(); ensure!(!message.is_empty(), "diagnostic description is empty"); let mut related_information = None; let mut visitor = RelatedInformationVisitor { url, line_index, position_encoding, related_information: &mut related_information, }; diagnostic.advices(&mut visitor).unwrap(); let tags = diagnostic.tags(); let tags = { let mut result = Vec::new(); if tags.contains(DiagnosticTags::UNNECESSARY_CODE) { result.push(lsp::DiagnosticTag::UNNECESSARY); } if tags.contains(DiagnosticTags::DEPRECATED_CODE) { result.push(lsp::DiagnosticTag::DEPRECATED); } if !result.is_empty() { Some(result) } else { None } }; let mut diagnostic = lsp::Diagnostic::new( span, Some(severity), code, Some("rome".into()), message, related_information, tags, ); diagnostic.code_description = code_description; Ok(diagnostic) } struct RelatedInformationVisitor<'a> { url: &'a lsp::Url, line_index: &'a LineIndex, position_encoding: PositionEncoding, related_information: &'a mut Option<Vec<lsp::DiagnosticRelatedInformation>>, } impl Visit for RelatedInformationVisitor<'_> { fn record_frame(&mut self, location: Location<'_>) -> io::Result<()> { let span = match location.span { Some(span) => span, None => return Ok(()), }; let range = match to_proto::range(self.line_index, span, self.position_encoding) { Ok(range) => range, Err(_) => return Ok(()), }; let related_information = self.related_information.get_or_insert_with(Vec::new); related_information.push(lsp::DiagnosticRelatedInformation { location: lsp::Location { uri: self.url.clone(), range, }, message: String::new(), }); Ok(()) } } /// Convert a piece of markup into a String fn print_markup(markup: &MarkupBuf) -> String { let mut message = Termcolor(NoColor::new(Vec::new())); fmt::Display::fmt(markup, &mut Formatter::new(&mut message)) // SAFETY: Writing to a memory buffer should never fail .unwrap(); // SAFETY: Printing uncolored markup never generates non UTF-8 byte sequences String::from_utf8(message.0.into_inner()).unwrap() } /// Helper to create a [tower_lsp::jsonrpc::Error] from a message pub(crate) fn into_lsp_error(msg: impl Display + Debug) -> LspError { let mut error = LspError::internal_error(); error!("Error: {}", msg); error.message = msg.to_string(); error.data = Some(format!("{msg:?}").into()); error } pub(crate) fn panic_to_lsp_error(err: Box<dyn Any + Send>) -> LspError { let mut error = LspError::internal_error(); match err.downcast::<String>() { Ok(msg) => { error.message = *msg; } Err(err) => match err.downcast::<&str>() { Ok(msg) => { error.message = msg.to_string(); } Err(_) => { error.message = String::from("Rome encountered an unknown error"); } }, } error } pub(crate) fn apply_document_changes( position_encoding: PositionEncoding, current_content: String, mut content_changes: Vec<lsp_types::TextDocumentContentChangeEvent>, ) -> String { // Skip to the last full document change, as it invalidates all previous changes anyways. let mut start = content_changes .iter() .rev() .position(|change| change.range.is_none()) .map(|idx| content_changes.len() - idx - 1) .unwrap_or(0); let mut text: String = match content_changes.get_mut(start) { // peek at the first content change as an optimization Some(lsp_types::TextDocumentContentChangeEvent { range: None, text, .. }) => { let text = mem::take(text); start += 1; // The only change is a full document update if start == content_changes.len() { return text; } text } Some(_) => current_content, // we received no content changes None => return current_content, }; let mut line_index = LineIndex::new(&text); // The changes we got must be applied sequentially, but can cross lines so we // have to keep our line index updated. // Some clients (e.g. Code) sort the ranges in reverse. As an optimization, we // remember the last valid line in the index and only rebuild it if needed. let mut index_valid = u32::MAX; for change in content_changes { // The None case can't happen as we have handled it above already if let Some(range) = change.range { if index_valid <= range.end.line { line_index = LineIndex::new(&text); } index_valid = range.start.line; if let Ok(range) = from_proto::text_range(&line_index, range, position_encoding) { text.replace_range(Range::<usize>::from(range), &change.text); } } } text } #[cfg(test)] mod tests { use super::apply_document_changes; use crate::converters::line_index::LineIndex; use crate::converters::{PositionEncoding, WideEncoding}; use rome_text_edit::TextEdit; use tower_lsp::lsp_types as lsp; use tower_lsp::lsp_types::{Position, Range, TextDocumentContentChangeEvent}; #[test] fn test_diff_1() { const OLD: &str = "line 1 old line 2 line 3 line 4 line 5 line 6 line 7 old"; const NEW: &str = "line 1 new line 2 line 3 line 4 line 5 line 6 line 7 new"; let line_index = LineIndex::new(OLD); let diff = TextEdit::from_unicode_words(OLD, NEW); let text_edit = super::text_edit(&line_index, diff, PositionEncoding::Utf8).unwrap(); assert_eq!( text_edit.as_slice(), &[ lsp::TextEdit { range: lsp::Range { start: lsp::Position { line: 0, character: 7, }, end: lsp::Position { line: 0, character: 10, }, }, new_text: String::from("new"), }, lsp::TextEdit { range: lsp::Range { start: lsp::Position { line: 6, character: 7 }, end: lsp::Position { line: 6, character: 10 } }, new_text: String::from("new"), }, ] ); } #[test] fn test_diff_2() { const OLD: &str = "console.log(\"Variable: \" + variable);"; const NEW: &str = "console.log(`Variable: ${variable}`);"; let line_index = LineIndex::new(OLD); let diff = TextEdit::from_unicode_words(OLD, NEW); let text_edit = super::text_edit(&line_index, diff, PositionEncoding::Utf8).unwrap(); assert_eq!( text_edit.as_slice(), &[ lsp::TextEdit { range: lsp::Range { start: lsp::Position { line: 0, character: 12, }, end: lsp::Position { line: 0, character: 13, }, }, new_text: String::from("`"), }, lsp::TextEdit { range: lsp::Range { start: lsp::Position { line: 0, character: 23 }, end: lsp::Position { line: 0, character: 27 } }, new_text: String::from("${"), }, lsp::TextEdit { range: lsp::Range { start: lsp::Position { line: 0, character: 35 }, end: lsp::Position { line: 0, character: 35 } }, new_text: String::from("}`"), }, ] ); } #[test] fn test_range_formatting() { let encoding = PositionEncoding::Wide(WideEncoding::Utf16); let input = "(\"Jan 1, 2018\u{2009}–\u{2009}Jan 1, 2019\");\n(\"Jan 1, 2018\u{2009}–\u{2009}Jan 1, 2019\");\nisSpreadAssignment;\n".to_string(); let change = TextDocumentContentChangeEvent { range: Some(Range::new(Position::new(0, 30), Position::new(1, 0))), range_length: Some(1), text: "".to_string(), }; let output = apply_document_changes(encoding, input, vec![change]); let expected = "(\"Jan 1, 2018\u{2009}–\u{2009}Jan 1, 2019\");(\"Jan 1, 2018\u{2009}–\u{2009}Jan 1, 2019\");\nisSpreadAssignment;\n"; assert_eq!(output, expected); } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_lsp/src/server.rs
crates/rome_lsp/src/server.rs
use crate::capabilities::server_capabilities; use crate::diagnostics::{handle_lsp_error, LspError}; use crate::requests::syntax_tree::{SyntaxTreePayload, SYNTAX_TREE_REQUEST}; use crate::session::{ CapabilitySet, CapabilityStatus, ClientInformation, Session, SessionHandle, SessionKey, }; use crate::utils::{into_lsp_error, panic_to_lsp_error}; use crate::{handlers, requests}; use futures::future::ready; use futures::FutureExt; use rome_console::markup; use rome_diagnostics::panic::PanicError; use rome_fs::CONFIG_NAME; use rome_service::workspace::{RageEntry, RageParams, RageResult}; use rome_service::{workspace, Workspace}; use serde_json::json; use std::collections::HashMap; use std::panic::RefUnwindSafe; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::{Arc, Mutex}; use tokio::io::{AsyncRead, AsyncWrite}; use tokio::sync::Notify; use tokio::task::spawn_blocking; use tower_lsp::jsonrpc::Result as LspResult; use tower_lsp::{lsp_types::*, ClientSocket}; use tower_lsp::{LanguageServer, LspService, Server}; use tracing::{error, info, trace, warn}; pub struct LSPServer { session: SessionHandle, /// Map of all sessions connected to the same [ServerFactory] as this [LSPServer]. sessions: Sessions, /// If this is true the server will broadcast a shutdown signal once the /// last client disconnected stop_on_disconnect: bool, /// This shared flag is set to true once at least one sessions has been /// initialized on this server instance is_initialized: Arc<AtomicBool>, } impl RefUnwindSafe for LSPServer {} impl LSPServer { fn new( session: SessionHandle, sessions: Sessions, stop_on_disconnect: bool, is_initialized: Arc<AtomicBool>, ) -> Self { Self { session, sessions, stop_on_disconnect, is_initialized, } } async fn syntax_tree_request(&self, params: SyntaxTreePayload) -> LspResult<String> { trace!( "Calling method: {}\n with params: {:?}", SYNTAX_TREE_REQUEST, &params ); let url = params.text_document.uri; requests::syntax_tree::syntax_tree(&self.session, &url).map_err(into_lsp_error) } #[tracing::instrument(skip(self), name = "rome/rage", level = "debug")] async fn rage(&self, params: RageParams) -> LspResult<RageResult> { let mut entries = vec![ RageEntry::section("Server"), RageEntry::pair("Version", rome_service::VERSION), RageEntry::pair("Name", env!("CARGO_PKG_NAME")), RageEntry::pair("CPU Architecture", std::env::consts::ARCH), RageEntry::pair("OS", std::env::consts::OS), ]; let RageResult { entries: workspace_entries, } = self.session.failsafe_rage(params); entries.extend(workspace_entries); if let Ok(sessions) = self.sessions.lock() { if sessions.len() > 1 { entries.push(RageEntry::markup( markup!("\n"<Underline><Emphasis>"Other Active Server Workspaces:"</Emphasis></Underline>"\n"), )); for (key, session) in sessions.iter() { if &self.session.key == key { // Already printed above continue; } let RageResult { entries: workspace_entries, } = session.failsafe_rage(params); entries.extend(workspace_entries); if let Some(information) = session.client_information() { entries.push(RageEntry::pair("Client Name", &information.name)); if let Some(version) = &information.version { entries.push(RageEntry::pair("Client Version", version)) } } } } } Ok(RageResult { entries }) } async fn setup_capabilities(&self) { let mut capabilities = CapabilitySet::default(); capabilities.add_capability( "rome_did_change_extension_settings", "workspace/didChangeConfiguration", if self.session.can_register_did_change_configuration() { CapabilityStatus::Enable(None) } else { CapabilityStatus::Disable }, ); capabilities.add_capability( "rome_did_change_workspace_settings", "workspace/didChangeWatchedFiles", if let Some(base_path) = self.session.base_path() { CapabilityStatus::Enable(Some(json!(DidChangeWatchedFilesRegistrationOptions { watchers: vec![FileSystemWatcher { glob_pattern: GlobPattern::String(format!( "{}/rome.json", base_path.display() )), kind: Some(WatchKind::all()), }], }))) } else { CapabilityStatus::Disable }, ); capabilities.add_capability( "rome_formatting", "textDocument/formatting", if self.session.is_linting_and_formatting_disabled() { CapabilityStatus::Disable } else { CapabilityStatus::Enable(None) }, ); capabilities.add_capability( "rome_range_formatting", "textDocument/rangeFormatting", if self.session.is_linting_and_formatting_disabled() { CapabilityStatus::Disable } else { CapabilityStatus::Enable(None) }, ); capabilities.add_capability( "rome_on_type_formatting", "textDocument/onTypeFormatting", if self.session.is_linting_and_formatting_disabled() { CapabilityStatus::Disable } else { CapabilityStatus::Enable(Some(json!(DocumentOnTypeFormattingRegistrationOptions { document_selector: None, first_trigger_character: String::from("}"), more_trigger_character: Some(vec![String::from("]"), String::from(")")]), }))) }, ); let rename = { let config = self.session.extension_settings.read().ok(); config.and_then(|x| x.settings.rename).unwrap_or(false) }; capabilities.add_capability( "rome_rename", "textDocument/rename", if rename { CapabilityStatus::Enable(None) } else { CapabilityStatus::Disable }, ); self.session.register_capabilities(capabilities).await; } async fn map_op_error<T>( &self, result: Result<Result<Option<T>, LspError>, PanicError>, ) -> LspResult<Option<T>> { match result { Ok(result) => match result { Ok(result) => Ok(result), Err(err) => handle_lsp_error(err, &self.session.client).await, }, Err(err) => Err(into_lsp_error(err)), } } } #[tower_lsp::async_trait] impl LanguageServer for LSPServer { // The `root_path` field is deprecated, but we still read it so we can print a warning about it #[allow(deprecated)] #[tracing::instrument( level = "debug", skip_all, fields( root_uri = params.root_uri.as_ref().map(display), capabilities = debug(&params.capabilities), client_info = params.client_info.as_ref().map(debug), root_path = params.root_path, workspace_folders = params.workspace_folders.as_ref().map(debug), ) )] async fn initialize(&self, params: InitializeParams) -> LspResult<InitializeResult> { info!("Starting Rome Language Server..."); self.is_initialized.store(true, Ordering::Relaxed); let server_capabilities = server_capabilities(&params.capabilities); self.session.initialize( params.capabilities, params.client_info.map(|client_info| ClientInformation { name: client_info.name, version: client_info.version, }), params.root_uri, ); if params.root_path.is_some() { warn!("The Rome Server was initialized with the deprecated `root_path` parameter: this is not supported, use `root_uri` instead"); } if params.workspace_folders.is_some() { warn!("The Rome Server was initialized with the `workspace_folders` parameter: this is unsupported at the moment, use `root_uri` instead"); } // let init = InitializeResult { capabilities: server_capabilities, server_info: Some(ServerInfo { name: String::from(env!("CARGO_PKG_NAME")), version: Some(rome_service::VERSION.to_string()), }), }; Ok(init) } #[tracing::instrument(level = "debug", skip(self))] async fn initialized(&self, params: InitializedParams) { let _ = params; info!("Attempting to load the configuration from 'rome.json' file"); futures::join!( self.session.load_extension_settings(), self.session.load_workspace_settings() ); let msg = format!("Server initialized with PID: {}", std::process::id()); self.session .client .log_message(MessageType::INFO, msg) .await; self.setup_capabilities().await; // Diagnostics are disabled by default, so update them after fetching workspace config self.session.update_all_diagnostics().await; } async fn shutdown(&self) -> LspResult<()> { Ok(()) } /// Called when the user changed the editor settings. #[tracing::instrument(level = "debug", skip(self))] async fn did_change_configuration(&self, params: DidChangeConfigurationParams) { let _ = params; self.session.load_extension_settings().await; self.setup_capabilities().await; self.session.update_all_diagnostics().await; } #[tracing::instrument(level = "debug", skip(self))] async fn did_change_watched_files(&self, params: DidChangeWatchedFilesParams) { let file_paths = params .changes .iter() .map(|change| change.uri.to_file_path()); for file_path in file_paths { match file_path { Ok(file_path) => { let base_path = self.session.base_path(); if let Some(base_path) = base_path { let possible_rome_json = file_path.strip_prefix(&base_path); if let Ok(possible_rome_json) = possible_rome_json { if possible_rome_json.display().to_string() == CONFIG_NAME { self.session.load_workspace_settings().await; self.setup_capabilities().await; self.session.update_all_diagnostics().await; // for now we are only interested to the configuration file, // so it's OK to exist the loop break; } } } } Err(_) => { error!("The Workspace root URI {file_path:?} could not be parsed as a filesystem path"); continue; } } } } async fn did_open(&self, params: DidOpenTextDocumentParams) { handlers::text_document::did_open(&self.session, params) .await .ok(); } async fn did_change(&self, params: DidChangeTextDocumentParams) { handlers::text_document::did_change(&self.session, params) .await .ok(); } async fn did_close(&self, params: DidCloseTextDocumentParams) { handlers::text_document::did_close(&self.session, params) .await .ok(); } async fn code_action(&self, params: CodeActionParams) -> LspResult<Option<CodeActionResponse>> { rome_diagnostics::panic::catch_unwind(move || { handlers::analysis::code_actions(&self.session, params).map_err(into_lsp_error) }) .map_err(into_lsp_error)? } async fn formatting( &self, params: DocumentFormattingParams, ) -> LspResult<Option<Vec<TextEdit>>> { let result = rome_diagnostics::panic::catch_unwind(move || { handlers::formatting::format(&self.session, params) }); self.map_op_error(result).await } async fn range_formatting( &self, params: DocumentRangeFormattingParams, ) -> LspResult<Option<Vec<TextEdit>>> { let result = rome_diagnostics::panic::catch_unwind(move || { handlers::formatting::format_range(&self.session, params) }); self.map_op_error(result).await } async fn on_type_formatting( &self, params: DocumentOnTypeFormattingParams, ) -> LspResult<Option<Vec<TextEdit>>> { let result = rome_diagnostics::panic::catch_unwind(move || { handlers::formatting::format_on_type(&self.session, params) }); self.map_op_error(result).await } async fn rename(&self, params: RenameParams) -> LspResult<Option<WorkspaceEdit>> { rome_diagnostics::panic::catch_unwind(move || { let rename_enabled = self .session .extension_settings .read() .ok() .and_then(|config| config.settings.rename) .unwrap_or(false); if rename_enabled { handlers::rename::rename(&self.session, params).map_err(into_lsp_error) } else { Ok(None) } }) .map_err(into_lsp_error)? } } impl Drop for LSPServer { fn drop(&mut self) { if let Ok(mut sessions) = self.sessions.lock() { let _removed = sessions.remove(&self.session.key); debug_assert!(_removed.is_some(), "Session did not exist."); if self.stop_on_disconnect && sessions.is_empty() && self.is_initialized.load(Ordering::Relaxed) { self.session.cancellation.notify_one(); } } } } /// Map of active sessions connected to a [ServerFactory]. type Sessions = Arc<Mutex<HashMap<SessionKey, SessionHandle>>>; /// Helper method for wrapping a [Workspace] method in a `custom_method` for /// the [LSPServer] macro_rules! workspace_method { ( $builder:ident, $method:ident ) => { $builder = $builder.custom_method( concat!("rome/", stringify!($method)), |server: &LSPServer, params| { let span = tracing::trace_span!(concat!("rome/", stringify!($method)), params = ?params).or_current(); let workspace = server.session.workspace.clone(); let result = spawn_blocking(move || { let _guard = span.entered(); workspace.$method(params) }); result.map(move |result| { // The type of `result` is `Result<Result<R, RomeError>, JoinError>`, // where the inner result is the return value of `$method` while the // outer one is added by `spawn_blocking` to catch panics or // cancellations of the task match result { Ok(Ok(result)) => Ok(result), Ok(Err(err)) => Err(into_lsp_error(err)), Err(err) => match err.try_into_panic() { Ok(err) => Err(panic_to_lsp_error(err)), Err(err) => Err(into_lsp_error(err)), }, } }) }, ); }; } /// Factory data structure responsible for creating [ServerConnection] handles /// for each incoming connection accepted by the server #[derive(Default)] pub struct ServerFactory { /// Synchronisation primitive used to broadcast a shutdown signal to all /// active connections cancellation: Arc<Notify>, /// Optional [Workspace] instance shared between all clients. Currently /// this field is always [None] (meaning each connection will get its own /// workspace) until we figure out how to handle concurrent access to the /// same workspace from multiple client workspace: Option<Arc<dyn Workspace>>, /// The sessions of the connected clients indexed by session key. sessions: Sessions, /// Session key generator. Stores the key of the next session. next_session_key: AtomicU64, /// If this is true the server will broadcast a shutdown signal once the /// last client disconnected stop_on_disconnect: bool, /// This shared flag is set to true once at least one sessions has been /// initialized on this server instance is_initialized: Arc<AtomicBool>, } impl ServerFactory { pub fn new(stop_on_disconnect: bool) -> Self { Self { cancellation: Arc::default(), workspace: None, sessions: Sessions::default(), next_session_key: AtomicU64::new(0), stop_on_disconnect, is_initialized: Arc::default(), } } /// Create a new [ServerConnection] from this factory pub fn create(&self) -> ServerConnection { let workspace = self .workspace .clone() .unwrap_or_else(workspace::server_sync); let session_key = SessionKey(self.next_session_key.fetch_add(1, Ordering::Relaxed)); let mut builder = LspService::build(move |client| { let session = Session::new(session_key, client, workspace, self.cancellation.clone()); let handle = Arc::new(session); let mut sessions = self.sessions.lock().unwrap(); sessions.insert(session_key, handle.clone()); LSPServer::new( handle, self.sessions.clone(), self.stop_on_disconnect, self.is_initialized.clone(), ) }); builder = builder.custom_method(SYNTAX_TREE_REQUEST, LSPServer::syntax_tree_request); // "shutdown" is not part of the Workspace API builder = builder.custom_method("rome/shutdown", |server: &LSPServer, (): ()| { info!("Sending shutdown signal"); server.session.broadcast_shutdown(); ready(Ok(Some(()))) }); builder = builder.custom_method("rome/rage", LSPServer::rage); workspace_method!(builder, file_features); workspace_method!(builder, is_path_ignored); workspace_method!(builder, update_settings); workspace_method!(builder, open_file); workspace_method!(builder, get_syntax_tree); workspace_method!(builder, get_control_flow_graph); workspace_method!(builder, get_formatter_ir); workspace_method!(builder, change_file); workspace_method!(builder, get_file_content); workspace_method!(builder, close_file); workspace_method!(builder, pull_diagnostics); workspace_method!(builder, pull_actions); workspace_method!(builder, format_file); workspace_method!(builder, format_range); workspace_method!(builder, format_on_type); workspace_method!(builder, fix_file); workspace_method!(builder, rename); workspace_method!(builder, organize_imports); let (service, socket) = builder.finish(); ServerConnection { socket, service } } /// Return a handle to the cancellation token for this server process pub fn cancellation(&self) -> Arc<Notify> { self.cancellation.clone() } } /// Handle type created by the server for each incoming connection pub struct ServerConnection { socket: ClientSocket, service: LspService<LSPServer>, } impl ServerConnection { /// Destructure a connection into its inner service instance and socket pub fn into_inner(self) -> (LspService<LSPServer>, ClientSocket) { (self.service, self.socket) } /// Accept an incoming connection and run the server async I/O loop to /// completion pub async fn accept<I, O>(self, stdin: I, stdout: O) where I: AsyncRead + Unpin, O: AsyncWrite, { Server::new(stdin, stdout, self.socket) .serve(self.service) .await; } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_lsp/src/extension_settings.rs
crates/rome_lsp/src/extension_settings.rs
use serde::{Deserialize, Serialize}; use serde_json::{Error, Value}; use tracing::trace; pub(crate) const CONFIGURATION_SECTION: &str = "rome"; #[derive(Debug, Default, Clone, Deserialize, Serialize, PartialEq, Eq)] #[serde(rename_all = "camelCase")] /// The settings applied to the workspace by the LSP pub struct WorkspaceSettings { /// Unstable features enabled #[serde(default)] pub unstable: bool, /// Enable rename capability pub rename: Option<bool>, /// Only run Rome if a `rome.json` configuration file exists. pub require_configuration: Option<bool>, } /// The `rome.*` extension settings #[derive(Debug)] pub(crate) struct ExtensionSettings { pub(crate) settings: WorkspaceSettings, } impl ExtensionSettings { pub(crate) fn new() -> Self { Self { settings: WorkspaceSettings::default(), } } pub(crate) fn set_workspace_settings(&mut self, value: Value) -> Result<(), Error> { let workspace_settings = serde_json::from_value(value)?; self.settings = workspace_settings; trace!( "Correctly stored the settings coming from the client: {:?}", self.settings ); Ok(()) } pub(crate) fn requires_configuration(&self) -> bool { self.settings.require_configuration.unwrap_or_default() } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_lsp/src/capabilities.rs
crates/rome_lsp/src/capabilities.rs
use crate::converters::{negotiated_encoding, PositionEncoding, WideEncoding}; use tower_lsp::lsp_types::{ ClientCapabilities, CodeActionProviderCapability, PositionEncodingKind, ServerCapabilities, TextDocumentSyncCapability, TextDocumentSyncKind, }; /// The capabilities to send from server as part of [`InitializeResult`] /// /// [`InitializeResult`]: lspower::lsp::InitializeResult pub(crate) fn server_capabilities(capabilities: &ClientCapabilities) -> ServerCapabilities { ServerCapabilities { position_encoding: Some(match negotiated_encoding(capabilities) { PositionEncoding::Utf8 => PositionEncodingKind::UTF8, PositionEncoding::Wide(wide) => match wide { WideEncoding::Utf16 => PositionEncodingKind::UTF16, WideEncoding::Utf32 => PositionEncodingKind::UTF32, }, }), text_document_sync: Some(TextDocumentSyncCapability::Kind( TextDocumentSyncKind::INCREMENTAL, )), code_action_provider: Some(CodeActionProviderCapability::Simple(true)), rename_provider: None, ..Default::default() } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_lsp/src/converters/to_proto.rs
crates/rome_lsp/src/converters/to_proto.rs
use crate::converters::line_index::LineIndex; use crate::converters::PositionEncoding; use anyhow::{Context, Result}; use rome_rowan::{TextRange, TextSize}; use tower_lsp::lsp_types; /// The function is used to convert TextSize to a LSP position. pub(crate) fn position( line_index: &LineIndex, offset: TextSize, position_encoding: PositionEncoding, ) -> Result<lsp_types::Position> { let line_col = line_index .line_col(offset) .with_context(|| format!("could not convert offset {offset:?} into a line-column index"))?; let position = match position_encoding { PositionEncoding::Utf8 => lsp_types::Position::new(line_col.line, line_col.col), PositionEncoding::Wide(enc) => { let line_col = line_index .to_wide(enc, line_col) .with_context(|| format!("could not convert {line_col:?} into wide line column"))?; lsp_types::Position::new(line_col.line, line_col.col) } }; Ok(position) } /// The function is used to convert TextRange to a LSP range. pub(crate) fn range( line_index: &LineIndex, range: TextRange, position_encoding: PositionEncoding, ) -> Result<lsp_types::Range> { let start = position(line_index, range.start(), position_encoding)?; let end = position(line_index, range.end(), position_encoding)?; Ok(lsp_types::Range::new(start, end)) }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_lsp/src/converters/line_index.rs
crates/rome_lsp/src/converters/line_index.rs
//! `LineIndex` maps flat `TextSize` offsets into `(Line, Column)` //! representation. use std::collections::HashMap; use std::mem; use crate::converters::{LineCol, WideChar, WideEncoding, WideLineCol}; use rome_rowan::TextSize; #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) struct LineIndex { /// Offset the beginning of each line, zero-based. pub(crate) newlines: Vec<TextSize>, /// List of non-ASCII characters on each line. pub(crate) line_wide_chars: HashMap<u32, Vec<WideChar>>, } impl LineIndex { pub fn new(text: &str) -> LineIndex { let mut line_wide_chars = HashMap::default(); let mut wide_chars = Vec::new(); let mut newlines = vec![TextSize::from(0)]; let mut current_col = TextSize::from(0); let mut line = 0; for (offset, char) in text.char_indices() { let char_size = TextSize::of(char); if char == '\n' { // SAFETY: the conversion from `usize` to `TextSize` can fail if `offset` // is larger than 2^32. We don't support such large files. let char_offset = TextSize::try_from(offset).expect("TextSize overflow"); newlines.push(char_offset + char_size); // Save any utf-16 characters seen in the previous line if !wide_chars.is_empty() { line_wide_chars.insert(line, mem::take(&mut wide_chars)); } // Prepare for processing the next line current_col = TextSize::from(0); line += 1; continue; } if !char.is_ascii() { wide_chars.push(WideChar { start: current_col, end: current_col + char_size, }); } current_col += char_size; } // Save any utf-16 characters seen in the last line if !wide_chars.is_empty() { line_wide_chars.insert(line, wide_chars); } LineIndex { newlines, line_wide_chars, } } /// Return the number of lines in the index, clamped to [u32::MAX] pub(crate) fn len(&self) -> u32 { self.newlines.len().try_into().unwrap_or(u32::MAX) } pub fn line_col(&self, offset: TextSize) -> Option<LineCol> { let line = self.newlines.partition_point(|&it| it <= offset) - 1; let line_start_offset = self.newlines.get(line)?; let col = offset - line_start_offset; Some(LineCol { line: u32::try_from(line).ok()?, col: col.into(), }) } pub fn offset(&self, line_col: LineCol) -> Option<TextSize> { self.newlines .get(line_col.line as usize) .map(|offset| offset + TextSize::from(line_col.col)) } pub fn to_wide(&self, enc: WideEncoding, line_col: LineCol) -> Option<WideLineCol> { let col = self.utf8_to_wide_col(enc, line_col.line, line_col.col.into()); Some(WideLineCol { line: line_col.line, col: u32::try_from(col).ok()?, }) } pub fn to_utf8(&self, enc: WideEncoding, line_col: WideLineCol) -> LineCol { let col = self.wide_to_utf8_col(enc, line_col.line, line_col.col); LineCol { line: line_col.line, col: col.into(), } } fn utf8_to_wide_col(&self, enc: WideEncoding, line: u32, col: TextSize) -> usize { let mut res: usize = col.into(); if let Some(wide_chars) = self.line_wide_chars.get(&line) { for c in wide_chars { if c.end <= col { res -= usize::from(c.len()) - c.wide_len(enc); } else { // From here on, all utf16 characters come *after* the character we are mapping, // so we don't need to take them into account break; } } } res } fn wide_to_utf8_col(&self, enc: WideEncoding, line: u32, mut col: u32) -> TextSize { if let Some(wide_chars) = self.line_wide_chars.get(&line) { for c in wide_chars { if col > u32::from(c.start) { col += u32::from(c.len()) - c.wide_len(enc) as u32; } else { // From here on, all utf16 characters come *after* the character we are mapping, // so we don't need to take them into account break; } } } col.into() } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_lsp/src/converters/mod.rs
crates/rome_lsp/src/converters/mod.rs
use rome_rowan::TextSize; use tower_lsp::lsp_types::{ClientCapabilities, PositionEncodingKind}; pub(crate) mod from_proto; pub(crate) mod line_index; pub(crate) mod to_proto; pub(crate) fn negotiated_encoding(capabilities: &ClientCapabilities) -> PositionEncoding { let client_encodings = match &capabilities.general { Some(general) => general.position_encodings.as_deref().unwrap_or_default(), None => &[], }; for enc in client_encodings { if enc == &PositionEncodingKind::UTF8 { return PositionEncoding::Utf8; } else if enc == &PositionEncodingKind::UTF32 { return PositionEncoding::Wide(WideEncoding::Utf32); } // NB: intentionally prefer just about anything else to utf-16. } PositionEncoding::Wide(WideEncoding::Utf16) } #[derive(Clone, Copy, Debug)] pub enum PositionEncoding { Utf8, Wide(WideEncoding), } #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum WideEncoding { Utf16, Utf32, } #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub(crate) struct LineCol { /// Zero-based pub(crate) line: u32, /// Zero-based utf8 offset pub(crate) col: u32, } /// Deliberately not a generic type and different from `LineCol`. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct WideLineCol { /// Zero-based pub line: u32, /// Zero-based pub col: u32, } #[derive(Clone, Debug, Hash, PartialEq, Eq)] pub(crate) struct WideChar { /// Start offset of a character inside a line, zero-based pub(crate) start: TextSize, /// End offset of a character inside a line, zero-based pub(crate) end: TextSize, } impl WideChar { /// Returns the length in 8-bit UTF-8 code units. fn len(&self) -> TextSize { self.end - self.start } /// Returns the length in UTF-16 or UTF-32 code units. fn wide_len(&self, enc: WideEncoding) -> usize { match enc { WideEncoding::Utf16 => { if self.len() == TextSize::from(4) { 2 } else { 1 } } WideEncoding::Utf32 => 1, } } } #[cfg(test)] mod tests { use crate::converters::from_proto::offset; use crate::converters::line_index::LineIndex; use crate::converters::to_proto::position; use crate::converters::WideEncoding::{Utf16, Utf32}; use crate::converters::{LineCol, PositionEncoding, WideEncoding}; use rome_rowan::TextSize; use tower_lsp::lsp_types::Position; macro_rules! check_conversion { ($line_index:ident : $position:expr => $text_size:expr ) => { let position_encoding = PositionEncoding::Wide(WideEncoding::Utf16); let offset = offset(&$line_index, $position, position_encoding).ok(); assert_eq!(offset, Some($text_size)); let position = position(&$line_index, offset.unwrap(), position_encoding).ok(); assert_eq!(position, Some($position)); }; } #[test] fn empty_string() { let line_index = LineIndex::new(""); check_conversion!(line_index: Position { line: 0, character: 0 } => TextSize::from(0)); } #[test] fn empty_line() { let line_index = LineIndex::new("\n\n"); check_conversion!(line_index: Position { line: 1, character: 0 } => TextSize::from(1)); } #[test] fn line_end() { let line_index = LineIndex::new("abc\ndef\nghi"); check_conversion!(line_index: Position { line: 1, character: 3 } => TextSize::from(7)); } #[test] fn out_of_bounds_line() { let line_index = LineIndex::new("abcde\nfghij\n"); let offset = line_index.offset(LineCol { line: 5, col: 0 }); assert!(offset.is_none()); } #[test] fn unicode() { let line_index = LineIndex::new("'Jan 1, 2018 – Jan 1, 2019'"); check_conversion!(line_index: Position { line: 0, character: 0 } => TextSize::from(0)); check_conversion!(line_index: Position { line: 0, character: 1 } => TextSize::from(1)); check_conversion!(line_index: Position { line: 0, character: 12 } => TextSize::from(12)); check_conversion!(line_index: Position { line: 0, character: 13 } => TextSize::from(15)); check_conversion!(line_index: Position { line: 0, character: 14 } => TextSize::from(18)); check_conversion!(line_index: Position { line: 0, character: 15 } => TextSize::from(21)); check_conversion!(line_index: Position { line: 0, character: 26 } => TextSize::from(32)); check_conversion!(line_index: Position { line: 0, character: 27 } => TextSize::from(33)); } #[ignore] #[test] fn test_every_chars() { let text: String = { let mut chars: Vec<char> = ((0 as char)..char::MAX).collect(); chars.extend("\n".repeat(chars.len() / 16).chars()); chars.into_iter().collect() }; let line_index = LineIndex::new(&text); let mut lin_col = LineCol { line: 0, col: 0 }; let mut col_utf16 = 0; let mut col_utf32 = 0; for (offset, c) in text.char_indices() { let got_offset = line_index.offset(lin_col).unwrap(); assert_eq!(usize::from(got_offset), offset); let got_lin_col = line_index.line_col(got_offset).unwrap(); assert_eq!(got_lin_col, lin_col); for enc in [Utf16, Utf32] { let wide_lin_col = line_index.to_wide(enc, lin_col).unwrap(); let got_lin_col = line_index.to_utf8(enc, wide_lin_col); assert_eq!(got_lin_col, lin_col); let want_col = match enc { Utf16 => col_utf16, Utf32 => col_utf32, }; assert_eq!(wide_lin_col.col, want_col) } if c == '\n' { lin_col.line += 1; lin_col.col = 0; col_utf16 = 0; col_utf32 = 0; } else { lin_col.col += c.len_utf8() as u32; col_utf16 += c.len_utf16() as u32; col_utf32 += 1; } } } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_lsp/src/converters/from_proto.rs
crates/rome_lsp/src/converters/from_proto.rs
use crate::converters::line_index::LineIndex; use crate::converters::{LineCol, PositionEncoding, WideLineCol}; use anyhow::{Context, Result}; use rome_rowan::{TextRange, TextSize}; use tower_lsp::lsp_types; /// The function is used to convert a LSP position to TextSize. pub(crate) fn offset( line_index: &LineIndex, position: lsp_types::Position, position_encoding: PositionEncoding, ) -> Result<TextSize> { let line_col = match position_encoding { PositionEncoding::Utf8 => LineCol { line: position.line, col: position.character, }, PositionEncoding::Wide(enc) => { let line_col = WideLineCol { line: position.line, col: position.character, }; line_index.to_utf8(enc, line_col) } }; line_index .offset(line_col) .with_context(|| format!("position {position:?} is out of range")) } /// The function is used to convert a LSP range to TextRange. pub(crate) fn text_range( line_index: &LineIndex, range: lsp_types::Range, position_encoding: PositionEncoding, ) -> Result<TextRange> { let start = offset(line_index, range.start, position_encoding)?; let end = offset(line_index, range.end, position_encoding)?; Ok(TextRange::new(start, end)) }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_lsp/src/requests/syntax_tree.rs
crates/rome_lsp/src/requests/syntax_tree.rs
use crate::session::Session; use anyhow::Result; use rome_service::workspace::GetSyntaxTreeParams; use serde::{Deserialize, Serialize}; use tower_lsp::lsp_types::{TextDocumentIdentifier, Url}; use tracing::info; pub const SYNTAX_TREE_REQUEST: &str = "rome_lsp/syntaxTree"; #[derive(Deserialize, Serialize, Debug)] #[serde(rename_all = "camelCase")] pub struct SyntaxTreePayload { pub text_document: TextDocumentIdentifier, } pub(crate) fn syntax_tree(session: &Session, url: &Url) -> Result<String> { info!("Showing syntax tree"); let rome_path = session.file_path(url)?; let syntax_tree = session .workspace .get_syntax_tree(GetSyntaxTreeParams { path: rome_path })?; Ok(syntax_tree.ast) }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_lsp/src/requests/mod.rs
crates/rome_lsp/src/requests/mod.rs
pub(crate) mod syntax_tree;
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_lsp/src/handlers/rename.rs
crates/rome_lsp/src/handlers/rename.rs
use std::collections::HashMap; use crate::converters::from_proto; use crate::{session::Session, utils}; use anyhow::{Context, Result}; use tower_lsp::lsp_types::{RenameParams, WorkspaceEdit}; use tracing::trace; #[tracing::instrument(level = "debug", skip(session), err)] pub(crate) fn rename(session: &Session, params: RenameParams) -> Result<Option<WorkspaceEdit>> { let url = params.text_document_position.text_document.uri; let rome_path = session.file_path(&url)?; trace!("Renaming..."); let doc = session.document(&url)?; let position_encoding = session.position_encoding(); let cursor_range = from_proto::offset( &doc.line_index, params.text_document_position.position, position_encoding, ) .with_context(|| { format!( "failed to access position {:?} in document {url}", params.text_document_position.position ) })?; let result = session .workspace .rename(rome_service::workspace::RenameParams { path: rome_path, symbol_at: cursor_range, new_name: params.new_name, })?; let mut changes = HashMap::new(); changes.insert( url, utils::text_edit(&doc.line_index, result.indels, position_encoding)?, ); let workspace_edit = WorkspaceEdit { changes: Some(changes), document_changes: None, change_annotations: None, }; Ok(Some(workspace_edit)) }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_lsp/src/handlers/analysis.rs
crates/rome_lsp/src/handlers/analysis.rs
use crate::converters::from_proto; use crate::converters::line_index::LineIndex; use crate::session::Session; use crate::utils; use anyhow::{Context, Result}; use rome_analyze::{ActionCategory, SourceActionKind}; use rome_fs::RomePath; use rome_service::workspace::{ FeatureName, FeaturesBuilder, FixFileMode, FixFileParams, PullActionsParams, SupportsFeatureParams, }; use rome_service::WorkspaceError; use std::borrow::Cow; use std::collections::HashMap; use tower_lsp::lsp_types::{ self as lsp, CodeActionKind, CodeActionOrCommand, CodeActionParams, CodeActionResponse, }; use tracing::debug; const FIX_ALL_CATEGORY: ActionCategory = ActionCategory::Source(SourceActionKind::FixAll); fn fix_all_kind() -> CodeActionKind { match FIX_ALL_CATEGORY.to_str() { Cow::Borrowed(kind) => CodeActionKind::from(kind), Cow::Owned(kind) => CodeActionKind::from(kind), } } /// Queries the [`AnalysisServer`] for code actions of the file matching its path /// /// If the AnalysisServer has no matching file, results in error. #[tracing::instrument(level = "debug", skip_all, fields(uri = display(&params.text_document.uri), range = debug(params.range), only = debug(&params.context.only), diagnostics = debug(&params.context.diagnostics)), err)] pub(crate) fn code_actions( session: &Session, params: CodeActionParams, ) -> Result<Option<CodeActionResponse>> { let url = params.text_document.uri.clone(); let rome_path = session.file_path(&url)?; let file_features = &session.workspace.file_features(SupportsFeatureParams { path: rome_path, feature: FeaturesBuilder::new() .with_linter() .with_organize_imports() .build(), })?; if !file_features.supports_for(&FeatureName::Lint) && !file_features.supports_for(&FeatureName::OrganizeImports) { debug!("Linter and organize imports are both disabled"); return Ok(Some(Vec::new())); } let mut has_fix_all = false; let mut filters = Vec::new(); if let Some(filter) = &params.context.only { for kind in filter { let kind = kind.as_str(); if FIX_ALL_CATEGORY.matches(kind) { has_fix_all = true; } filters.push(kind); } } let url = params.text_document.uri.clone(); let rome_path = session.file_path(&url)?; let doc = session.document(&url)?; let position_encoding = session.position_encoding(); let diagnostics = params.context.diagnostics; let cursor_range = from_proto::text_range(&doc.line_index, params.range, position_encoding) .with_context(|| { format!( "failed to access range {:?} in document {url} {:?}", params.range, &doc.line_index, ) })?; let result = match session.workspace.pull_actions(PullActionsParams { path: rome_path.clone(), range: cursor_range, }) { Ok(result) => result, Err(err) => { return if matches!(err, WorkspaceError::FileIgnored(_)) { Ok(Some(Vec::new())) } else { Err(err.into()) } } }; debug!("Pull actions result: {:?}", result); // Generate an additional code action to apply all safe fixes on the // document if the action category "source.fixAll" was explicitly requested // by the language client let fix_all = if has_fix_all { fix_all(session, &url, rome_path, &doc.line_index, &diagnostics)? } else { None }; let mut has_fixes = false; let mut actions: Vec<_> = result .actions .into_iter() .filter_map(|action| { if action.category.matches("source.organizeImports.rome") && !file_features.supports_for(&FeatureName::OrganizeImports) { return None; } // Remove actions that do not match the categories requested by the // language client let matches_filters = filters.iter().any(|filter| action.category.matches(filter)); if !filters.is_empty() && !matches_filters { return None; } let action = utils::code_fix_to_lsp( &url, &doc.line_index, position_encoding, &diagnostics, action, ) .ok()?; has_fixes |= action.diagnostics.is_some(); Some(CodeActionOrCommand::CodeAction(action)) }) .chain(fix_all) .collect(); // If any actions is marked as fixing a diagnostic, hide other actions // that do not fix anything (refactor opportunities) to reduce noise if has_fixes { actions.retain(|action| { if let CodeActionOrCommand::CodeAction(action) = action { action.kind.as_ref() == Some(&fix_all_kind()) || action.diagnostics.is_some() } else { true } }); } debug!("Suggested actions: \n{:?}", &actions); Ok(Some(actions)) } /// Generate a "fix all" code action for the given document #[tracing::instrument(level = "debug", skip(session), err)] fn fix_all( session: &Session, url: &lsp::Url, rome_path: RomePath, line_index: &LineIndex, diagnostics: &[lsp::Diagnostic], ) -> Result<Option<CodeActionOrCommand>, WorkspaceError> { let should_format = session .workspace .file_features(SupportsFeatureParams { path: rome_path.clone(), feature: vec![FeatureName::Format], })? .supports_for(&FeatureName::Format); let fixed = session.workspace.fix_file(FixFileParams { path: rome_path, fix_file_mode: FixFileMode::SafeFixes, should_format, })?; if fixed.actions.is_empty() { return Ok(None); } let diagnostics = diagnostics .iter() .filter_map(|d| { let code = d.code.as_ref()?; let code = match code { lsp::NumberOrString::String(code) => code.as_str(), lsp::NumberOrString::Number(_) => return None, }; let code = code.strip_prefix("lint/")?; let position_encoding = session.position_encoding(); let diag_range = from_proto::text_range(line_index, d.range, position_encoding).ok()?; let has_matching_rule = fixed.actions.iter().any(|action| { let Some((group_name, rule_name)) = &action.rule_name else { return false }; let Some(code) = code.strip_prefix(group_name.as_ref()) else { return false }; let Some(code) = code.strip_prefix('/') else { return false }; code == rule_name && action.range.intersect(diag_range).is_some() }); if has_matching_rule { Some(d.clone()) } else { None } }) .collect(); let mut changes = HashMap::new(); changes.insert( url.clone(), vec![lsp::TextEdit { range: lsp::Range { start: lsp::Position::new(0, 0), end: lsp::Position::new(line_index.len(), 0), }, new_text: fixed.code, }], ); let edit = lsp::WorkspaceEdit { changes: Some(changes), document_changes: None, change_annotations: None, }; Ok(Some(CodeActionOrCommand::CodeAction(lsp::CodeAction { title: String::from("Fix all auto-fixable issues"), kind: Some(fix_all_kind()), diagnostics: Some(diagnostics), edit: Some(edit), command: None, is_preferred: Some(true), disabled: None, data: None, }))) }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_lsp/src/handlers/text_document.rs
crates/rome_lsp/src/handlers/text_document.rs
use anyhow::Result; use rome_service::workspace::{ ChangeFileParams, CloseFileParams, GetFileContentParams, Language, OpenFileParams, }; use tower_lsp::lsp_types; use tracing::{error, field}; use crate::utils::apply_document_changes; use crate::{documents::Document, session::Session}; /// Handler for `textDocument/didOpen` LSP notification #[tracing::instrument(level = "debug", skip(session), err)] pub(crate) async fn did_open( session: &Session, params: lsp_types::DidOpenTextDocumentParams, ) -> Result<()> { let url = params.text_document.uri; let version = params.text_document.version; let content = params.text_document.text; let language_hint = Language::from_language_id(&params.text_document.language_id); let rome_path = session.file_path(&url)?; let doc = Document::new(version, &content); session.workspace.open_file(OpenFileParams { path: rome_path, version, content, language_hint, })?; session.insert_document(url.clone(), doc); if let Err(err) = session.update_diagnostics(url).await { error!("Failed to update diagnostics: {}", err); } Ok(()) } /// Handler for `textDocument/didChange` LSP notification #[tracing::instrument(level = "debug", skip_all, fields(url = field::display(&params.text_document.uri), version = params.text_document.version), err)] pub(crate) async fn did_change( session: &Session, params: lsp_types::DidChangeTextDocumentParams, ) -> Result<()> { let url = params.text_document.uri; let version = params.text_document.version; let rome_path = session.file_path(&url)?; let old_text = session.workspace.get_file_content(GetFileContentParams { path: rome_path.clone(), })?; tracing::trace!("old document: {:?}", old_text); tracing::trace!("content changes: {:?}", params.content_changes); let text = apply_document_changes( session.position_encoding(), old_text, params.content_changes, ); tracing::trace!("new document: {:?}", text); session.insert_document(url.clone(), Document::new(version, &text)); session.workspace.change_file(ChangeFileParams { path: rome_path, version, content: text, })?; if let Err(err) = session.update_diagnostics(url).await { error!("Failed to update diagnostics: {}", err); } Ok(()) } /// Handler for `textDocument/didClose` LSP notification #[tracing::instrument(level = "debug", skip(session), err)] pub(crate) async fn did_close( session: &Session, params: lsp_types::DidCloseTextDocumentParams, ) -> Result<()> { let url = params.text_document.uri; let rome_path = session.file_path(&url)?; session .workspace .close_file(CloseFileParams { path: rome_path })?; session.remove_document(&url); let diagnostics = vec![]; let version = None; session .client .publish_diagnostics(url, diagnostics, version) .await; Ok(()) }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_lsp/src/handlers/formatting.rs
crates/rome_lsp/src/handlers/formatting.rs
use crate::converters::{from_proto, to_proto}; use crate::diagnostics::LspError; use crate::session::Session; use anyhow::Context; use rome_service::workspace::{FormatFileParams, FormatOnTypeParams, FormatRangeParams}; use tower_lsp::lsp_types::*; use tracing::debug; #[tracing::instrument(level = "debug", skip(session), err)] pub(crate) fn format( session: &Session, params: DocumentFormattingParams, ) -> Result<Option<Vec<TextEdit>>, LspError> { let url = params.text_document.uri; let rome_path = session.file_path(&url)?; let doc = session.document(&url)?; debug!("Formatting..."); let printed = session .workspace .format_file(FormatFileParams { path: rome_path })?; let num_lines: u32 = doc.line_index.len(); let range = Range { start: Position::default(), end: Position { line: num_lines, character: 0, }, }; let edits = vec![TextEdit { range, new_text: printed.into_code(), }]; Ok(Some(edits)) } #[tracing::instrument(level = "debug", skip(session), err)] pub(crate) fn format_range( session: &Session, params: DocumentRangeFormattingParams, ) -> Result<Option<Vec<TextEdit>>, LspError> { let url = params.text_document.uri; let rome_path = session.file_path(&url)?; let doc = session.document(&url)?; let position_encoding = session.position_encoding(); let format_range = from_proto::text_range(&doc.line_index, params.range, position_encoding) .with_context(|| { format!( "failed to convert range {:?} in document {url}", params.range.end ) })?; let formatted = session.workspace.format_range(FormatRangeParams { path: rome_path, range: format_range, })?; // Recalculate the actual range that was reformatted from the formatter result let formatted_range = match formatted.range() { Some(range) => { let position_encoding = session.position_encoding(); to_proto::range(&doc.line_index, range, position_encoding)? } None => Range { start: Position::default(), end: Position { line: doc.line_index.len(), character: 0, }, }, }; Ok(Some(vec![TextEdit { range: formatted_range, new_text: formatted.into_code(), }])) } #[tracing::instrument(level = "debug", skip(session), err)] pub(crate) fn format_on_type( session: &Session, params: DocumentOnTypeFormattingParams, ) -> Result<Option<Vec<TextEdit>>, LspError> { let url = params.text_document_position.text_document.uri; let position = params.text_document_position.position; let rome_path = session.file_path(&url)?; let doc = session.document(&url)?; let position_encoding = session.position_encoding(); let offset = from_proto::offset(&doc.line_index, position, position_encoding) .with_context(|| format!("failed to access position {position:?} in document {url}"))?; let formatted = session.workspace.format_on_type(FormatOnTypeParams { path: rome_path, offset, })?; // Recalculate the actual range that was reformatted from the formatter result let formatted_range = match formatted.range() { Some(range) => { let position_encoding = session.position_encoding(); let start_loc = to_proto::position(&doc.line_index, range.start(), position_encoding)?; let end_loc = to_proto::position(&doc.line_index, range.end(), position_encoding)?; Range { start: start_loc, end: end_loc, } } None => Range { start: Position::default(), end: Position { line: doc.line_index.len(), character: 0, }, }, }; Ok(Some(vec![TextEdit { range: formatted_range, new_text: formatted.into_code(), }])) }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_lsp/tests/server.rs
crates/rome_lsp/tests/server.rs
use anyhow::bail; use anyhow::Context; use anyhow::Error; use anyhow::Result; use futures::channel::mpsc::{channel, Sender}; use futures::Sink; use futures::SinkExt; use futures::Stream; use futures::StreamExt; use rome_fs::RomePath; use rome_lsp::LSPServer; use rome_lsp::ServerFactory; use rome_lsp::WorkspaceSettings; use rome_service::workspace::GetSyntaxTreeResult; use rome_service::workspace::{GetFileContentParams, GetSyntaxTreeParams}; use serde::de::DeserializeOwned; use serde::Serialize; use serde_json::{from_value, to_value}; use std::any::type_name; use std::collections::HashMap; use std::fmt::Display; use std::slice; use std::time::Duration; use tokio::time::sleep; use tower::timeout::Timeout; use tower::{Service, ServiceExt}; use tower_lsp::jsonrpc; use tower_lsp::jsonrpc::Response; use tower_lsp::lsp_types as lsp; use tower_lsp::lsp_types::DidChangeTextDocumentParams; use tower_lsp::lsp_types::DidCloseTextDocumentParams; use tower_lsp::lsp_types::DidOpenTextDocumentParams; use tower_lsp::lsp_types::DocumentFormattingParams; use tower_lsp::lsp_types::FormattingOptions; use tower_lsp::lsp_types::InitializeResult; use tower_lsp::lsp_types::InitializedParams; use tower_lsp::lsp_types::Position; use tower_lsp::lsp_types::PublishDiagnosticsParams; use tower_lsp::lsp_types::Range; use tower_lsp::lsp_types::TextDocumentContentChangeEvent; use tower_lsp::lsp_types::TextDocumentIdentifier; use tower_lsp::lsp_types::TextDocumentItem; use tower_lsp::lsp_types::TextEdit; use tower_lsp::lsp_types::VersionedTextDocumentIdentifier; use tower_lsp::lsp_types::WorkDoneProgressParams; use tower_lsp::lsp_types::{ClientCapabilities, CodeDescription, Url}; use tower_lsp::LspService; use tower_lsp::{jsonrpc::Request, lsp_types::InitializeParams}; /// Statically build an [lsp::Url] instance that points to the file at `$path` /// within the workspace. The filesystem path contained in the return URI is /// guaranteed to be a valid path for the underlying operating system, but /// doesn't have to refer to an existing file on the host machine. macro_rules! url { ($path:literal) => { if cfg!(windows) { lsp::Url::parse(concat!("file:///z%3A/workspace/", $path)).unwrap() } else { lsp::Url::parse(concat!("file:///workspace/", $path)).unwrap() } }; } struct Server { service: Timeout<LspService<LSPServer>>, } impl Server { fn new(service: LspService<LSPServer>) -> Self { Self { service: Timeout::new(service, Duration::from_secs(1)), } } async fn notify<P>(&mut self, method: &'static str, params: P) -> Result<()> where P: Serialize, { self.service .ready() .await .map_err(Error::msg) .context("ready() returned an error")? .call( Request::build(method) .params(to_value(&params).context("failed to serialize params")?) .finish(), ) .await .map_err(Error::msg) .context("call() returned an error") .and_then(|res| { if let Some(res) = res { bail!("shutdown returned {:?}", res) } else { Ok(()) } }) } async fn request<P, R>( &mut self, method: &'static str, id: &'static str, params: P, ) -> Result<Option<R>> where P: Serialize, R: DeserializeOwned, { self.service .ready() .await .map_err(Error::msg) .context("ready() returned an error")? .call( Request::build(method) .id(id) .params(to_value(&params).context("failed to serialize params")?) .finish(), ) .await .map_err(Error::msg) .context("call() returned an error")? .map(|res| { let (_, body) = res.into_parts(); let body = body.with_context(|| format!("response to {method:?} contained an error"))?; from_value(body.clone()).with_context(|| { format!( "failed to deserialize type {} from response {body:?}", type_name::<R>() ) }) }) .transpose() } /// Basic implementation of the `initialize` request for tests // The `root_path` field is deprecated, but we still need to specify it #[allow(deprecated)] async fn initialize(&mut self) -> Result<()> { let _res: InitializeResult = self .request( "initialize", "_init", InitializeParams { process_id: None, root_path: None, root_uri: Some(url!("")), initialization_options: None, capabilities: ClientCapabilities::default(), trace: None, workspace_folders: None, client_info: None, locale: None, }, ) .await? .context("initialize returned None")?; Ok(()) } /// Basic implementation of the `initialized` notification for tests async fn initialized(&mut self) -> Result<()> { self.notify("initialized", InitializedParams {}).await } /// Basic implementation of the `shutdown` notification for tests async fn shutdown(&mut self) -> Result<()> { self.service .ready() .await .map_err(Error::msg) .context("ready() returned an error")? .call(Request::build("shutdown").finish()) .await .map_err(Error::msg) .context("call() returned an error") .and_then(|res| { if let Some(res) = res { bail!("shutdown returned {:?}", res) } else { Ok(()) } }) } async fn open_document(&mut self, text: impl Display) -> Result<()> { self.notify( "textDocument/didOpen", DidOpenTextDocumentParams { text_document: TextDocumentItem { uri: url!("document.js"), language_id: String::from("javascript"), version: 0, text: text.to_string(), }, }, ) .await } /// Opens a document with given contents and given name. The name must contain the extension too async fn open_named_document( &mut self, text: impl Display, document_name: Url, language: impl Display, ) -> Result<()> { self.notify( "textDocument/didOpen", DidOpenTextDocumentParams { text_document: TextDocumentItem { uri: document_name, language_id: language.to_string(), version: 0, text: text.to_string(), }, }, ) .await } async fn change_document( &mut self, version: i32, content_changes: Vec<TextDocumentContentChangeEvent>, ) -> Result<()> { self.notify( "textDocument/didChange", DidChangeTextDocumentParams { text_document: VersionedTextDocumentIdentifier { uri: url!("document.js"), version, }, content_changes, }, ) .await } async fn close_document(&mut self) -> Result<()> { self.notify( "textDocument/didClose", DidCloseTextDocumentParams { text_document: TextDocumentIdentifier { uri: url!("document.js"), }, }, ) .await } /// Basic implementation of the `rome/shutdown` request for tests async fn rome_shutdown(&mut self) -> Result<()> { self.request::<_, ()>("rome/shutdown", "_rome_shutdown", ()) .await? .context("rome/shutdown returned None")?; Ok(()) } } /// Number of notifications buffered by the server-to-client channel before it starts blocking the current task const CHANNEL_BUFFER_SIZE: usize = 8; #[derive(Debug, PartialEq, Eq)] enum ServerNotification { PublishDiagnostics(PublishDiagnosticsParams), } /// Basic handler for requests and notifications coming from the server for tests async fn client_handler<I, O>( mut stream: I, mut sink: O, mut notify: Sender<ServerNotification>, ) -> Result<()> where // This function has to be generic as `RequestStream` and `ResponseSink` // are not exported from `tower_lsp` and cannot be named in the signature I: Stream<Item = Request> + Unpin, O: Sink<Response> + Unpin, { while let Some(req) = stream.next().await { if req.method() == "textDocument/publishDiagnostics" { let params = req.params().expect("invalid request"); let diagnostics = from_value(params.clone()).expect("invalid params"); let notification = ServerNotification::PublishDiagnostics(diagnostics); match notify.send(notification).await { Ok(_) => continue, Err(_) => break, } } let id = match req.id() { Some(id) => id, None => continue, }; let res = match req.method() { "workspace/configuration" => { let settings = WorkspaceSettings { ..WorkspaceSettings::default() }; let result = to_value(slice::from_ref(&settings)).context("failed to serialize settings")?; Response::from_ok(id.clone(), result) } _ => Response::from_error(id.clone(), jsonrpc::Error::method_not_found()), }; sink.send(res).await.ok(); } Ok(()) } #[tokio::test] async fn basic_lifecycle() -> Result<()> { let factory = ServerFactory::default(); let (service, client) = factory.create().into_inner(); let (stream, sink) = client.split(); let mut server = Server::new(service); let (sender, _) = channel(CHANNEL_BUFFER_SIZE); let reader = tokio::spawn(client_handler(stream, sink, sender)); server.initialize().await?; server.initialized().await?; server.shutdown().await?; reader.abort(); Ok(()) } #[tokio::test] async fn document_lifecycle() -> Result<()> { let factory = ServerFactory::default(); let (service, client) = factory.create().into_inner(); let (stream, sink) = client.split(); let mut server = Server::new(service); let (sender, _) = channel(CHANNEL_BUFFER_SIZE); let reader = tokio::spawn(client_handler(stream, sink, sender)); server.initialize().await?; server.initialized().await?; server .open_document("first_line();\nsecond_line();\nthird_line();") .await?; server .change_document( 1, vec![ TextDocumentContentChangeEvent { range: Some(Range { start: Position { line: 2, character: 6, }, end: Position { line: 2, character: 10, }, }), range_length: None, text: String::from("statement"), }, TextDocumentContentChangeEvent { range: Some(Range { start: Position { line: 1, character: 7, }, end: Position { line: 1, character: 11, }, }), range_length: None, text: String::from("statement"), }, TextDocumentContentChangeEvent { range: Some(Range { start: Position { line: 0, character: 6, }, end: Position { line: 0, character: 10, }, }), range_length: None, text: String::from("statement"), }, ], ) .await?; let res: GetSyntaxTreeResult = server .request( "rome/get_syntax_tree", "get_syntax_tree", GetSyntaxTreeParams { path: RomePath::new("document.js"), }, ) .await? .expect("get_syntax_tree returned None"); const EXPECTED: &str = "0: JS_MODULE@0..57 0: (empty) 1: JS_DIRECTIVE_LIST@0..0 2: JS_MODULE_ITEM_LIST@0..57 0: JS_EXPRESSION_STATEMENT@0..18 0: JS_CALL_EXPRESSION@0..17 0: JS_IDENTIFIER_EXPRESSION@0..15 0: JS_REFERENCE_IDENTIFIER@0..15 0: IDENT@0..15 \"first_statement\" [] [] 1: (empty) 2: (empty) 3: JS_CALL_ARGUMENTS@15..17 0: L_PAREN@15..16 \"(\" [] [] 1: JS_CALL_ARGUMENT_LIST@16..16 2: R_PAREN@16..17 \")\" [] [] 1: SEMICOLON@17..18 \";\" [] [] 1: JS_EXPRESSION_STATEMENT@18..38 0: JS_CALL_EXPRESSION@18..37 0: JS_IDENTIFIER_EXPRESSION@18..35 0: JS_REFERENCE_IDENTIFIER@18..35 0: IDENT@18..35 \"second_statement\" [Newline(\"\\n\")] [] 1: (empty) 2: (empty) 3: JS_CALL_ARGUMENTS@35..37 0: L_PAREN@35..36 \"(\" [] [] 1: JS_CALL_ARGUMENT_LIST@36..36 2: R_PAREN@36..37 \")\" [] [] 1: SEMICOLON@37..38 \";\" [] [] 2: JS_EXPRESSION_STATEMENT@38..57 0: JS_CALL_EXPRESSION@38..56 0: JS_IDENTIFIER_EXPRESSION@38..54 0: JS_REFERENCE_IDENTIFIER@38..54 0: IDENT@38..54 \"third_statement\" [Newline(\"\\n\")] [] 1: (empty) 2: (empty) 3: JS_CALL_ARGUMENTS@54..56 0: L_PAREN@54..55 \"(\" [] [] 1: JS_CALL_ARGUMENT_LIST@55..55 2: R_PAREN@55..56 \")\" [] [] 1: SEMICOLON@56..57 \";\" [] [] 3: EOF@57..57 \"\" [] [] "; assert_eq!(res.cst, EXPECTED); server.close_document().await?; server.shutdown().await?; reader.abort(); Ok(()) } #[tokio::test] async fn document_no_extension() -> Result<()> { let factory = ServerFactory::default(); let (service, client) = factory.create().into_inner(); let (stream, sink) = client.split(); let mut server = Server::new(service); let (sender, _) = channel(CHANNEL_BUFFER_SIZE); let reader = tokio::spawn(client_handler(stream, sink, sender)); server.initialize().await?; server.initialized().await?; server .notify( "textDocument/didOpen", DidOpenTextDocumentParams { text_document: TextDocumentItem { uri: url!("document"), language_id: String::from("javascript"), version: 0, text: String::from("statement()"), }, }, ) .await?; let res: Option<Vec<TextEdit>> = server .request( "textDocument/formatting", "formatting", DocumentFormattingParams { text_document: TextDocumentIdentifier { uri: url!("document"), }, options: FormattingOptions { tab_size: 4, insert_spaces: false, properties: HashMap::default(), trim_trailing_whitespace: None, insert_final_newline: None, trim_final_newlines: None, }, work_done_progress_params: WorkDoneProgressParams { work_done_token: None, }, }, ) .await? .context("formatting returned None")?; let edits = res.context("formatting did not return an edit list")?; assert!(!edits.is_empty(), "formatting returned an empty edit list"); server .notify( "textDocument/didClose", DidCloseTextDocumentParams { text_document: TextDocumentIdentifier { uri: url!("document"), }, }, ) .await?; server.shutdown().await?; reader.abort(); Ok(()) } #[tokio::test] async fn pull_diagnostics() -> Result<()> { let factory = ServerFactory::default(); let (service, client) = factory.create().into_inner(); let (stream, sink) = client.split(); let mut server = Server::new(service); let (sender, mut receiver) = channel(CHANNEL_BUFFER_SIZE); let reader = tokio::spawn(client_handler(stream, sink, sender)); server.initialize().await?; server.initialized().await?; server.open_document("if(a == b) {}").await?; let notification = tokio::select! { msg = receiver.next() => msg, _ = sleep(Duration::from_secs(1)) => { panic!("timed out waiting for the server to send diagnostics") } }; assert_eq!( notification, Some(ServerNotification::PublishDiagnostics( PublishDiagnosticsParams { uri: url!("document.js"), version: Some(0), diagnostics: vec![lsp::Diagnostic { range: lsp::Range { start: lsp::Position { line: 0, character: 5, }, end: lsp::Position { line: 0, character: 7, }, }, severity: Some(lsp::DiagnosticSeverity::ERROR), code: Some(lsp::NumberOrString::String(String::from( "lint/suspicious/noDoubleEquals", ))), code_description: Some(CodeDescription { href: Url::parse("https://docs.rome.tools/lint/rules/noDoubleEquals") .unwrap() }), source: Some(String::from("rome")), message: String::from( "Use === instead of ==.\n== is only allowed when comparing against `null`", ), related_information: Some(vec![lsp::DiagnosticRelatedInformation { location: lsp::Location { uri: url!("document.js"), range: lsp::Range { start: lsp::Position { line: 0, character: 5, }, end: lsp::Position { line: 0, character: 7, }, }, }, message: String::new(), }]), tags: None, data: None, }], } )) ); server.close_document().await?; server.shutdown().await?; reader.abort(); Ok(()) } fn fixable_diagnostic(line: u32) -> Result<lsp::Diagnostic> { Ok(lsp::Diagnostic { range: lsp::Range { start: lsp::Position { line, character: 3 }, end: lsp::Position { line, character: 11, }, }, severity: Some(lsp::DiagnosticSeverity::ERROR), code: Some(lsp::NumberOrString::String(String::from( "lint/suspicious/noCompareNegZero", ))), code_description: None, source: Some(String::from("rome")), message: String::from("Do not use the === operator to compare against -0."), related_information: None, tags: None, data: None, }) } #[tokio::test] async fn pull_quick_fixes() -> Result<()> { let factory = ServerFactory::default(); let (service, client) = factory.create().into_inner(); let (stream, sink) = client.split(); let mut server = Server::new(service); let (sender, _) = channel(CHANNEL_BUFFER_SIZE); let reader = tokio::spawn(client_handler(stream, sink, sender)); server.initialize().await?; server.initialized().await?; server.open_document("if(a === -0) {}").await?; let res: lsp::CodeActionResponse = server .request( "textDocument/codeAction", "pull_code_actions", lsp::CodeActionParams { text_document: lsp::TextDocumentIdentifier { uri: url!("document.js"), }, range: lsp::Range { start: lsp::Position { line: 0, character: 6, }, end: lsp::Position { line: 0, character: 6, }, }, context: lsp::CodeActionContext { diagnostics: vec![fixable_diagnostic(0)?], only: Some(vec![lsp::CodeActionKind::QUICKFIX]), ..Default::default() }, work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token: None, }, partial_result_params: lsp::PartialResultParams { partial_result_token: None, }, }, ) .await? .context("codeAction returned None")?; let mut changes = HashMap::default(); changes.insert( url!("document.js"), vec![lsp::TextEdit { range: lsp::Range { start: lsp::Position { line: 0, character: 9, }, end: lsp::Position { line: 0, character: 10, }, }, new_text: String::new(), }], ); let expected_code_action = lsp::CodeActionOrCommand::CodeAction(lsp::CodeAction { title: String::from("Replace -0 with 0"), kind: Some(lsp::CodeActionKind::new( "quickfix.rome.suspicious.noCompareNegZero", )), diagnostics: Some(vec![fixable_diagnostic(0)?]), edit: Some(lsp::WorkspaceEdit { changes: Some(changes), document_changes: None, change_annotations: None, }), command: None, is_preferred: Some(true), disabled: None, data: None, }); let mut suppression_changes = HashMap::default(); suppression_changes.insert( url!("document.js"), vec![lsp::TextEdit { range: lsp::Range { start: lsp::Position { line: 0, character: 0, }, end: lsp::Position { line: 0, character: 0, }, }, new_text: String::from( "// rome-ignore lint/suspicious/noCompareNegZero: <explanation>\n", ), }], ); let expected_suppression_action = lsp::CodeActionOrCommand::CodeAction(lsp::CodeAction { title: String::from("Suppress rule lint/suspicious/noCompareNegZero"), kind: Some(lsp::CodeActionKind::new( "quickfix.suppressRule.rome.suspicious.noCompareNegZero", )), diagnostics: Some(vec![fixable_diagnostic(0)?]), edit: Some(lsp::WorkspaceEdit { changes: Some(suppression_changes), document_changes: None, change_annotations: None, }), command: None, is_preferred: None, disabled: None, data: None, }); assert_eq!(res, vec![expected_code_action, expected_suppression_action]); server.close_document().await?; server.shutdown().await?; reader.abort(); Ok(()) } #[tokio::test] async fn pull_diagnostics_for_rome_json() -> Result<()> { let factory = ServerFactory::default(); let (service, client) = factory.create().into_inner(); let (stream, sink) = client.split(); let mut server = Server::new(service); let (sender, mut receiver) = channel(CHANNEL_BUFFER_SIZE); let reader = tokio::spawn(client_handler(stream, sink, sender)); server.initialize().await?; server.initialized().await?; let incorrect_config = r#"{ "formatter": { "indentStyle": "magic" } }"#; server .open_named_document(incorrect_config, url!("rome.json"), "json") .await?; let notification = tokio::select! { msg = receiver.next() => msg, _ = sleep(Duration::from_secs(1)) => { panic!("timed out waiting for the server to send diagnostics") } }; assert_eq!( notification, Some(ServerNotification::PublishDiagnostics( PublishDiagnosticsParams { uri: url!("rome.json"), version: Some(0), diagnostics: vec![lsp::Diagnostic { range: lsp::Range { start: lsp::Position { line: 2, character: 27, }, end: lsp::Position { line: 2, character: 34, }, }, severity: Some(lsp::DiagnosticSeverity::ERROR), code: Some(lsp::NumberOrString::String(String::from("deserialize",))), code_description: None, source: Some(String::from("rome")), message: String::from("Found an unknown value `magic`.",), related_information: None, tags: None, data: None, }], } )) ); server.close_document().await?; server.shutdown().await?; reader.abort(); Ok(()) } #[tokio::test] async fn no_code_actions_for_ignored_json_files() -> Result<()> { let factory = ServerFactory::default(); let (service, client) = factory.create().into_inner(); let (stream, sink) = client.split(); let mut server = Server::new(service); let (sender, mut receiver) = channel(CHANNEL_BUFFER_SIZE); let reader = tokio::spawn(client_handler(stream, sink, sender)); server.initialize().await?; server.initialized().await?; let incorrect_config = r#"{ "name": "test" }"#; server .open_named_document( incorrect_config, url!("./node_modules/preact/package.json"), "json", ) .await?; let notification = tokio::select! { msg = receiver.next() => msg, _ = sleep(Duration::from_secs(1)) => { panic!("timed out waiting for the server to send diagnostics") } }; assert_eq!( notification, Some(ServerNotification::PublishDiagnostics( PublishDiagnosticsParams { uri: url!("./node_modules/preact/package.json"), version: Some(0), diagnostics: vec![], } )) ); let res: lsp::CodeActionResponse = server .request( "textDocument/codeAction", "pull_code_actions", lsp::CodeActionParams { text_document: lsp::TextDocumentIdentifier { uri: url!("./node_modules/preact/package.json"), }, range: lsp::Range { start: lsp::Position { line: 0, character: 7, }, end: lsp::Position { line: 0, character: 7, }, }, context: lsp::CodeActionContext { diagnostics: vec![], ..Default::default() }, work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token: None, }, partial_result_params: lsp::PartialResultParams { partial_result_token: None, }, }, ) .await? .context("codeAction returned None")?; assert_eq!(res, vec![]); server.close_document().await?; server.shutdown().await?; reader.abort(); Ok(()) } #[tokio::test] async fn pull_refactors() -> Result<()> { let factory = ServerFactory::default(); let (service, client) = factory.create().into_inner(); let (stream, sink) = client.split(); let mut server = Server::new(service); let (sender, _) = channel(CHANNEL_BUFFER_SIZE); let reader = tokio::spawn(client_handler(stream, sink, sender)); server.initialize().await?; server.initialized().await?; server .open_document("let variable = \"value\"; func(variable);") .await?; let res: lsp::CodeActionResponse = server .request( "textDocument/codeAction", "pull_code_actions", lsp::CodeActionParams { text_document: lsp::TextDocumentIdentifier { uri: url!("document.js"), }, range: lsp::Range { start: lsp::Position { line: 0, character: 7, }, end: lsp::Position { line: 0, character: 7, }, }, context: lsp::CodeActionContext { diagnostics: vec![], only: Some(vec![lsp::CodeActionKind::REFACTOR]), ..Default::default() }, work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token: None, }, partial_result_params: lsp::PartialResultParams { partial_result_token: None, }, }, ) .await? .context("codeAction returned None")?; let mut changes = HashMap::default(); changes.insert( url!("document.js"), vec![ lsp::TextEdit { range: lsp::Range { start: lsp::Position { line: 0, character: 0, }, end: lsp::Position { line: 0, character: 15, }, }, new_text: String::from("func("), }, lsp::TextEdit { range: lsp::Range { start: lsp::Position { line: 0, character: 22, }, end: lsp::Position { line: 0, character: 37, }, }, new_text: String::new(), }, ], ); let _expected_action = lsp::CodeActionOrCommand::CodeAction(lsp::CodeAction { title: String::from("Inline variable"), kind: Some(lsp::CodeActionKind::new( "refactor.inline.rome.correctness.inlineVariable", )), diagnostics: None, edit: Some(lsp::WorkspaceEdit { changes: Some(changes), document_changes: None, change_annotations: None, }), command: None,
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
true
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_wasm/build.rs
crates/rome_wasm/build.rs
use std::{env, fs, io, path::PathBuf}; use quote::{format_ident, quote}; use rome_js_factory::syntax::JsFileSource; use rome_js_factory::{ make, syntax::{AnyJsDeclaration, AnyJsModuleItem, AnyJsStatement}, }; use rome_js_formatter::{context::JsFormatOptions, format_node}; use rome_rowan::AstNode; use rome_service::workspace_types::{generate_type, methods, ModuleQueue}; fn main() -> io::Result<()> { let methods = methods(); let mut items = Vec::new(); let mut queue = ModuleQueue::default(); for method in &methods { generate_type(&mut items, &mut queue, &method.params); generate_type(&mut items, &mut queue, &method.result); } let module = make::js_module( make::js_directive_list(None), make::js_module_item_list(items.into_iter().map(|(decl, _)| { AnyJsModuleItem::AnyJsStatement(match decl { AnyJsDeclaration::JsClassDeclaration(decl) => { AnyJsStatement::JsClassDeclaration(decl) } AnyJsDeclaration::JsFunctionDeclaration(decl) => { AnyJsStatement::JsFunctionDeclaration(decl) } AnyJsDeclaration::JsVariableDeclaration(decl) => { AnyJsStatement::JsVariableStatement(make::js_variable_statement(decl).build()) } AnyJsDeclaration::TsDeclareFunctionDeclaration(decl) => { AnyJsStatement::TsDeclareFunctionDeclaration(decl) } AnyJsDeclaration::TsEnumDeclaration(decl) => { AnyJsStatement::TsEnumDeclaration(decl) } AnyJsDeclaration::TsExternalModuleDeclaration(decl) => { AnyJsStatement::TsExternalModuleDeclaration(decl) } AnyJsDeclaration::TsGlobalDeclaration(decl) => { AnyJsStatement::TsGlobalDeclaration(decl) } AnyJsDeclaration::TsImportEqualsDeclaration(decl) => { AnyJsStatement::TsImportEqualsDeclaration(decl) } AnyJsDeclaration::TsInterfaceDeclaration(decl) => { AnyJsStatement::TsInterfaceDeclaration(decl) } AnyJsDeclaration::TsModuleDeclaration(decl) => { AnyJsStatement::TsModuleDeclaration(decl) } AnyJsDeclaration::TsTypeAliasDeclaration(decl) => { AnyJsStatement::TsTypeAliasDeclaration(decl) } }) })), make::eof(), ) .build(); // Wasm-bindgen will paste the generated TS code as-is into the final .d.ts file, // ensure it looks good by running it through the formatter let formatted = format_node(JsFormatOptions::new(JsFileSource::ts()), module.syntax()).unwrap(); let printed = formatted.print().unwrap(); let definitions = printed.into_code(); // Generate wasm-bindgen extern type imports for all the types defined in the TS code let types = queue.visited().iter().map(|name| { let ident = format_ident!("I{name}"); quote! { #[wasm_bindgen(typescript_type = #name)] #[allow(non_camel_case_types)] pub type #ident; } }); let tokens = quote! { #[wasm_bindgen(typescript_custom_section)] const TS_TYPEDEFS: &'static str = #definitions; #[wasm_bindgen] extern "C" { #( #types )* } }; let out_dir = env::var("OUT_DIR").unwrap(); fs::write( PathBuf::from(out_dir).join("ts_types.rs"), tokens.to_string(), )?; Ok(()) }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_wasm/src/lib.rs
crates/rome_wasm/src/lib.rs
use js_sys::Error; use wasm_bindgen::prelude::*; use rome_service::workspace::{ self, ChangeFileParams, CloseFileParams, FixFileParams, FormatFileParams, FormatOnTypeParams, FormatRangeParams, GetControlFlowGraphParams, GetFileContentParams, GetFormatterIRParams, GetSyntaxTreeParams, OrganizeImportsParams, PullActionsParams, PullDiagnosticsParams, RenameParams, UpdateSettingsParams, }; use rome_service::workspace::{OpenFileParams, SupportsFeatureParams}; mod utils; pub use crate::utils::DiagnosticPrinter; use crate::utils::{into_error, set_panic_hook}; #[wasm_bindgen(start)] pub fn main() { set_panic_hook(); } include!(concat!(env!("OUT_DIR"), "/ts_types.rs")); #[wasm_bindgen] pub struct Workspace { inner: Box<dyn workspace::Workspace>, } #[wasm_bindgen] impl Workspace { #[wasm_bindgen(constructor)] #[allow(clippy::new_without_default)] pub fn new() -> Workspace { Workspace { inner: workspace::server(), } } #[wasm_bindgen(js_name = fileFeatures)] pub fn file_features( &self, params: ISupportsFeatureParams, ) -> Result<ISupportsFeatureResult, Error> { let params: SupportsFeatureParams = serde_wasm_bindgen::from_value(params.into()).map_err(into_error)?; let result = self.inner.file_features(params).map_err(into_error)?; to_value(&result) .map(ISupportsFeatureResult::from) .map_err(into_error) } #[wasm_bindgen(js_name = updateSettings)] pub fn update_settings(&self, params: IUpdateSettingsParams) -> Result<(), Error> { let params: UpdateSettingsParams = serde_wasm_bindgen::from_value(params.into()).map_err(into_error)?; self.inner.update_settings(params).map_err(into_error) } #[wasm_bindgen(js_name = openFile)] pub fn open_file(&self, params: IOpenFileParams) -> Result<(), Error> { let params: OpenFileParams = serde_wasm_bindgen::from_value(params.into()).map_err(into_error)?; self.inner.open_file(params).map_err(into_error) } #[wasm_bindgen(js_name = getFileContent)] pub fn get_file_content(&self, params: IGetFileContentParams) -> Result<String, Error> { let params: GetFileContentParams = serde_wasm_bindgen::from_value(params.into()).map_err(into_error)?; self.inner.get_file_content(params).map_err(into_error) } #[wasm_bindgen(js_name = getSyntaxTree)] pub fn get_syntax_tree( &self, params: IGetSyntaxTreeParams, ) -> Result<IGetSyntaxTreeResult, Error> { let params: GetSyntaxTreeParams = serde_wasm_bindgen::from_value(params.into()).map_err(into_error)?; let result = self.inner.get_syntax_tree(params).map_err(into_error)?; to_value(&result) .map(IGetSyntaxTreeResult::from) .map_err(into_error) } #[wasm_bindgen(js_name = getControlFlowGraph)] pub fn get_control_flow_graph( &self, params: IGetControlFlowGraphParams, ) -> Result<String, Error> { let params: GetControlFlowGraphParams = serde_wasm_bindgen::from_value(params.into()).map_err(into_error)?; self.inner .get_control_flow_graph(params) .map_err(into_error) } #[wasm_bindgen(js_name = getFormatterIr)] pub fn get_formatter_ir(&self, params: IGetFormatterIRParams) -> Result<String, Error> { let params: GetFormatterIRParams = serde_wasm_bindgen::from_value(params.into()).map_err(into_error)?; self.inner.get_formatter_ir(params).map_err(into_error) } #[wasm_bindgen(js_name = changeFile)] pub fn change_file(&self, params: IChangeFileParams) -> Result<(), Error> { let params: ChangeFileParams = serde_wasm_bindgen::from_value(params.into()).map_err(into_error)?; self.inner.change_file(params).map_err(into_error) } #[wasm_bindgen(js_name = closeFile)] pub fn close_file(&self, params: ICloseFileParams) -> Result<(), Error> { let params: CloseFileParams = serde_wasm_bindgen::from_value(params.into()).map_err(into_error)?; self.inner.close_file(params).map_err(into_error) } #[wasm_bindgen(js_name = pullDiagnostics)] pub fn pull_diagnostics( &self, params: IPullDiagnosticsParams, ) -> Result<IPullDiagnosticsResult, Error> { let params: PullDiagnosticsParams = serde_wasm_bindgen::from_value(params.into()).map_err(into_error)?; let result = self.inner.pull_diagnostics(params).map_err(into_error)?; to_value(&result) .map(IPullDiagnosticsResult::from) .map_err(into_error) } #[wasm_bindgen(js_name = pullActions)] pub fn pull_actions(&self, params: IPullActionsParams) -> Result<IPullActionsResult, Error> { let params: PullActionsParams = serde_wasm_bindgen::from_value(params.into()).map_err(into_error)?; let result = self.inner.pull_actions(params).map_err(into_error)?; to_value(&result) .map(IPullActionsResult::from) .map_err(into_error) } #[wasm_bindgen(js_name = formatFile)] pub fn format_file(&self, params: IFormatFileParams) -> Result<JsValue, Error> { let params: FormatFileParams = serde_wasm_bindgen::from_value(params.into()).map_err(into_error)?; let result = self.inner.format_file(params).map_err(into_error)?; to_value(&result).map_err(into_error) } #[wasm_bindgen(js_name = formatRange)] pub fn format_range(&self, params: IFormatRangeParams) -> Result<JsValue, Error> { let params: FormatRangeParams = serde_wasm_bindgen::from_value(params.into()).map_err(into_error)?; let result = self.inner.format_range(params).map_err(into_error)?; to_value(&result).map_err(into_error) } #[wasm_bindgen(js_name = formatOnType)] pub fn format_on_type(&self, params: IFormatOnTypeParams) -> Result<JsValue, Error> { let params: FormatOnTypeParams = serde_wasm_bindgen::from_value(params.into()).map_err(into_error)?; let result = self.inner.format_on_type(params).map_err(into_error)?; to_value(&result).map_err(into_error) } #[wasm_bindgen(js_name = fixFile)] pub fn fix_file(&self, params: IFixFileParams) -> Result<IFixFileResult, Error> { let params: FixFileParams = serde_wasm_bindgen::from_value(params.into()).map_err(into_error)?; let result = self.inner.fix_file(params).map_err(into_error)?; to_value(&result) .map(IFixFileResult::from) .map_err(into_error) } #[wasm_bindgen(js_name = organizeImports)] pub fn organize_imports( &self, params: IOrganizeImportsParams, ) -> Result<IOrganizeImportsResult, Error> { let params: OrganizeImportsParams = serde_wasm_bindgen::from_value(params.into()).map_err(into_error)?; let result = self.inner.organize_imports(params).map_err(into_error)?; to_value(&result) .map(IOrganizeImportsResult::from) .map_err(into_error) } pub fn rename(&self, params: IRenameParams) -> Result<IRenameResult, Error> { let params: RenameParams = serde_wasm_bindgen::from_value(params.into()).map_err(into_error)?; let result = self.inner.rename(params).map_err(into_error)?; to_value(&result) .map(IRenameResult::from) .map_err(into_error) } } fn to_value<T: serde::ser::Serialize + ?Sized>( value: &T, ) -> Result<JsValue, serde_wasm_bindgen::Error> { value.serialize(&serde_wasm_bindgen::Serializer::new().serialize_missing_as_null(true)) }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_wasm/src/utils.rs
crates/rome_wasm/src/utils.rs
use std::fmt::Display; use js_sys::Error; use wasm_bindgen::prelude::*; use rome_console::fmt::HTML; use rome_console::{fmt::Formatter, markup}; use rome_diagnostics::serde::Diagnostic; use rome_diagnostics::{DiagnosticExt, LineIndexBuf, PrintDiagnostic, SourceCode}; use super::IDiagnostic; pub(crate) fn set_panic_hook() { // When the `console_error_panic_hook` feature is enabled, we can call the // `set_panic_hook` function at least once during initialization, and then // we will get better error messages if our code ever panics. // // For more details see // https://github.com/rustwasm/console_error_panic_hook#readme #[cfg(feature = "console_error_panic_hook")] console_error_panic_hook::set_once(); } #[wasm_bindgen] pub struct DiagnosticPrinter { file_name: String, file_source: SourceCode<String, LineIndexBuf>, buffer: Vec<u8>, } #[wasm_bindgen] impl DiagnosticPrinter { #[wasm_bindgen(constructor)] pub fn new(file_name: String, file_source: String) -> Self { let line_starts = LineIndexBuf::from_source_text(&file_source); Self { file_name, file_source: SourceCode { text: file_source, line_starts: Some(line_starts), }, buffer: Vec::new(), } } pub fn print_simple(&mut self, diagnostic: IDiagnostic) -> Result<(), Error> { self.print(diagnostic, |err| PrintDiagnostic::simple(err)) } pub fn print_verbose(&mut self, diagnostic: IDiagnostic) -> Result<(), Error> { self.print(diagnostic, |err| PrintDiagnostic::verbose(err)) } fn print( &mut self, diagnostic: IDiagnostic, printer: fn(&rome_diagnostics::Error) -> PrintDiagnostic<rome_diagnostics::Error>, ) -> Result<(), Error> { let diag: Diagnostic = serde_wasm_bindgen::from_value(diagnostic.into()).map_err(into_error)?; let err = diag .with_file_path(&self.file_name) .with_file_source_code(&self.file_source); let mut html = HTML(&mut self.buffer); Formatter::new(&mut html) .write_markup(markup!({ printer(&err) })) .map_err(into_error)?; Ok(()) } pub fn finish(self) -> Result<String, Error> { String::from_utf8(self.buffer).map_err(into_error) } } pub(crate) fn into_error<E: Display>(err: E) -> Error { Error::new(&err.to_string()) }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_wasm/tests/web.rs
crates/rome_wasm/tests/web.rs
//! Test suite for the Web and headless browsers. #![cfg(target_arch = "wasm32")] extern crate wasm_bindgen_test; use wasm_bindgen_test::*; wasm_bindgen_test_configure!(run_in_browser); #[wasm_bindgen_test] fn pass() { assert_eq!(1 + 1, 2); }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/lib.rs
crates/rome_js_analyze/src/lib.rs
use crate::suppression_action::apply_suppression_comment; use rome_analyze::{ AnalysisFilter, Analyzer, AnalyzerContext, AnalyzerOptions, AnalyzerSignal, ControlFlow, InspectMatcher, LanguageRoot, MatchQueryParams, MetadataRegistry, RuleAction, RuleRegistry, SuppressionKind, }; use rome_aria::{AriaProperties, AriaRoles}; use rome_diagnostics::{category, Diagnostic, Error as DiagnosticError}; use rome_js_syntax::suppression::SuppressionDiagnostic; use rome_js_syntax::{suppression::parse_suppression_comment, JsFileSource, JsLanguage}; use serde::{Deserialize, Serialize}; use std::sync::Arc; use std::{borrow::Cow, error::Error}; mod analyzers; mod aria_analyzers; mod aria_services; mod assists; mod ast_utils; mod control_flow; pub mod globals; pub mod options; mod react; mod registry; mod semantic_analyzers; mod semantic_services; mod suppression_action; mod syntax; pub mod utils; pub use crate::control_flow::ControlFlowGraph; pub use crate::registry::visit_registry; pub(crate) type JsRuleAction = RuleAction<JsLanguage>; /// Return the static [MetadataRegistry] for the JS 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. /// 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<JsLanguage>, filter: AnalysisFilter, inspect_matcher: V, options: &'a AnalyzerOptions, source_type: JsFileSource, mut emit_signal: F, ) -> (Option<B>, Vec<DiagnosticError>) where V: FnMut(&MatchQueryParams<JsLanguage>) + 'a, F: FnMut(&dyn AnalyzerSignal<JsLanguage>) -> ControlFlow<B> + 'a, B: 'a, { fn parse_linter_suppression_comment( text: &str, ) -> Vec<Result<SuppressionKind, SuppressionDiagnostic>> { let mut result = Vec::new(); for comment in parse_suppression_comment(text) { let categories = match comment { Ok(comment) => comment.categories, Err(err) => { result.push(Err(err)); continue; } }; for (key, value) in categories { if key == category!("lint") { if let Some(value) = value { result.push(Ok(SuppressionKind::MaybeLegacy(value))); } else { result.push(Ok(SuppressionKind::Everything)); } } else { let category = key.name(); if let Some(rule) = category.strip_prefix("lint/") { result.push(Ok(SuppressionKind::Rule(rule))); } } } } result } let mut registry = RuleRegistry::builder(&filter, root); visit_registry(&mut registry); let (registry, mut services, diagnostics, visitors) = registry.build(); // Bail if we can't parse a rule option if !diagnostics.is_empty() { return (None, diagnostics); } let mut analyzer = Analyzer::new( metadata(), InspectMatcher::new(registry, inspect_matcher), parse_linter_suppression_comment, apply_suppression_comment, &mut emit_signal, ); for ((phase, _), visitor) in visitors { analyzer.add_visitor(phase, visitor); } services.insert_service(Arc::new(AriaRoles::default())); services.insert_service(Arc::new(AriaProperties::default())); services.insert_service(source_type); ( analyzer.run(AnalyzerContext { root: root.clone(), range: filter.range, services, options, }), diagnostics, ) } /// 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<JsLanguage>, filter: AnalysisFilter, options: &'a AnalyzerOptions, source_type: JsFileSource, emit_signal: F, ) -> (Option<B>, Vec<DiagnosticError>) where F: FnMut(&dyn AnalyzerSignal<JsLanguage>) -> ControlFlow<B> + 'a, B: 'a, { analyze_with_inspect_matcher(root, filter, |_| {}, options, source_type, emit_signal) } #[cfg(test)] mod tests { use rome_analyze::options::RuleOptions; use rome_analyze::{AnalyzerOptions, Never, RuleCategories, RuleFilter, RuleKey}; use rome_console::fmt::{Formatter, Termcolor}; use rome_console::{markup, Markup}; use rome_diagnostics::category; use rome_diagnostics::termcolor::NoColor; use rome_diagnostics::{Diagnostic, DiagnosticExt, PrintDiagnostic, Severity}; use rome_js_parser::{parse, JsParserOptions}; use rome_js_syntax::{JsFileSource, TextRange, TextSize}; use std::slice; use crate::semantic_analyzers::nursery::use_exhaustive_dependencies::{Hooks, HooksOptions}; 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#"a[f].c = a[f].c;"#; let parsed = parse(SOURCE, JsFileSource::tsx(), JsParserOptions::default()); let mut error_ranges: Vec<TextRange> = Vec::new(); let mut options = AnalyzerOptions::default(); let hook = Hooks { name: "myEffect".to_string(), closure_index: Some(0), dependencies_index: Some(1), }; let rule_filter = RuleFilter::Rule("nursery", "noSelfAssign"); options.configuration.rules.push_rule( RuleKey::new("nursery", "useHookAtTopLevel"), RuleOptions::new(HooksOptions { hooks: vec![hook] }), ); analyze( &parsed.tree(), AnalysisFilter { enabled_rules: Some(slice::from_ref(&rule_filter)), ..AnalysisFilter::default() }, &options, JsFileSource::tsx(), |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(), &[]); } #[test] fn suppression() { const SOURCE: &str = " function checkSuppressions1(a, b) { a == b; // rome-ignore lint/suspicious:whole group a == b; // rome-ignore lint/suspicious/noDoubleEquals: single rule a == b; /* rome-ignore lint/style/useWhile: multiple block comments */ /* rome-ignore lint/suspicious/noDoubleEquals: multiple block comments */ a == b; // rome-ignore lint/style/useWhile: multiple line comments // rome-ignore lint/suspicious/noDoubleEquals: multiple line comments a == b; a == b; } // rome-ignore lint/suspicious/noDoubleEquals: do not suppress warning for the whole function function checkSuppressions2(a, b) { a == b; } function checkSuppressions3(a, b) { a == b; // rome-ignore lint(suspicious): whole group a == b; // rome-ignore lint(suspicious/noDoubleEquals): single rule a == b; /* rome-ignore lint(style/useWhile): multiple block comments */ /* rome-ignore lint(suspicious/noDoubleEquals): multiple block comments */ a == b; // rome-ignore lint(style/useWhile): multiple line comments // rome-ignore lint(suspicious/noDoubleEquals): multiple line comments a == b; a == b; } // rome-ignore lint(suspicious/noDoubleEquals): do not suppress warning for the whole function function checkSuppressions4(a, b) { a == b; } function checkSuppressions5() { // rome-ignore format explanation // rome-ignore format(: // rome-ignore (value): explanation // rome-ignore unknown: explanation } "; let parsed = parse( SOURCE, JsFileSource::js_module(), JsParserOptions::default(), ); let mut lint_ranges: Vec<TextRange> = Vec::new(); let mut parse_ranges: Vec<TextRange> = Vec::new(); let mut warn_ranges: Vec<TextRange> = Vec::new(); let options = AnalyzerOptions::default(); analyze( &parsed.tree(), AnalysisFilter::default(), &options, JsFileSource::js_module(), |signal| { if let Some(diag) = signal.diagnostic() { let span = diag.get_span(); let error = diag .with_severity(Severity::Warning) .with_file_path("example.js") .with_file_source_code(SOURCE); let code = error.category().unwrap(); if code == category!("lint/suspicious/noDoubleEquals") { lint_ranges.push(span.unwrap()); } if code == category!("suppressions/parse") { parse_ranges.push(span.unwrap()); } if code == category!("suppressions/deprecatedSyntax") { assert!(signal.actions().len() > 0); warn_ranges.push(span.unwrap()); } } ControlFlow::<Never>::Continue(()) }, ); assert_eq!( lint_ranges.as_slice(), &[ TextRange::new(TextSize::from(67), TextSize::from(69)), TextRange::new(TextSize::from(635), TextSize::from(637)), TextRange::new(TextSize::from(828), TextSize::from(830)), TextRange::new(TextSize::from(915), TextSize::from(917)), TextRange::new(TextSize::from(1490), TextSize::from(1492)), TextRange::new(TextSize::from(1684), TextSize::from(1686)), ] ); assert_eq!( parse_ranges.as_slice(), &[ TextRange::new(TextSize::from(1787), TextSize::from(1798)), TextRange::new(TextSize::from(1837), TextSize::from(1838)), TextRange::new(TextSize::from(1870), TextSize::from(1871)), TextRange::new(TextSize::from(1922), TextSize::from(1929)), ] ); assert_eq!( warn_ranges.as_slice(), &[ TextRange::new(TextSize::from(937), TextSize::from(981)), TextRange::new(TextSize::from(1022), TextSize::from(1081)), TextRange::new(TextSize::from(1122), TextSize::from(1185)), TextRange::new(TextSize::from(1186), TextSize::from(1260)), TextRange::new(TextSize::from(1301), TextSize::from(1360)), TextRange::new(TextSize::from(1377), TextSize::from(1447)), TextRange::new(TextSize::from(1523), TextSize::from(1617)), ] ); } #[test] fn suppression_syntax() { const SOURCE: &str = " // rome-ignore lint/suspicious/noDoubleEquals: single rule a == b; "; let parsed = parse( SOURCE, JsFileSource::js_module(), JsParserOptions::default(), ); let filter = AnalysisFilter { categories: RuleCategories::SYNTAX, ..AnalysisFilter::default() }; let options = AnalyzerOptions::default(); analyze( &parsed.tree(), filter, &options, JsFileSource::js_module(), |signal| { if let Some(diag) = signal.diagnostic() { let code = diag.category().unwrap(); if code != category!("suppressions/unused") { panic!("unexpected diagnostic {code:?}"); } } ControlFlow::<Never>::Continue(()) }, ); } } /// Series of errors encountered when running rules on a file #[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)] pub enum RuleError { /// The rule with the specified name replaced the root of the file with a node that is not a valid root for that language. ReplacedRootWithNonRootError { rule_name: Option<(Cow<'static, str>, Cow<'static, str>)>, }, } impl Diagnostic for RuleError {} impl std::fmt::Display for RuleError { fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result { match self { RuleError::ReplacedRootWithNonRootError { rule_name: Some((group, rule)), } => { std::write!( fmt, "the rule '{group}/{rule}' replaced the root of the file with a non-root node." ) } RuleError::ReplacedRootWithNonRootError { rule_name: None } => { std::write!( fmt, "a code action replaced the root of the file with a non-root node." ) } } } } impl rome_console::fmt::Display for RuleError { fn fmt(&self, fmt: &mut rome_console::fmt::Formatter) -> std::io::Result<()> { match self { RuleError::ReplacedRootWithNonRootError { rule_name: Some((group, rule)), } => { std::write!( fmt, "the rule '{group}/{rule}' replaced the root of the file with a non-root node." ) } RuleError::ReplacedRootWithNonRootError { rule_name: None } => { std::write!( fmt, "a code action replaced the root of the file with a non-root node." ) } } } } impl Error for RuleError {}
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/semantic_analyzers.rs
crates/rome_js_analyze/src/semantic_analyzers.rs
//! Generated file, do not edit by hand, see `xtask/codegen` pub(crate) mod a11y; pub(crate) mod complexity; pub(crate) mod correctness; pub(crate) mod nursery; pub(crate) mod security; pub(crate) mod style; pub(crate) mod suspicious; ::rome_analyze::declare_category! { pub (crate) SemanticAnalyzers { kind : Lint , groups : [self :: a11y :: A11y , self :: complexity :: Complexity , self :: correctness :: Correctness , self :: nursery :: Nursery , self :: security :: Security , self :: style :: Style , self :: suspicious :: Suspicious ,] } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/aria_services.rs
crates/rome_js_analyze/src/aria_services.rs
use rome_analyze::{ AddVisitor, FromServices, MissingServicesDiagnostic, Phase, Phases, QueryKey, Queryable, RuleKey, ServiceBag, SyntaxVisitor, }; use rome_aria::iso::{countries, is_valid_country, is_valid_language, languages}; use rome_aria::{AriaProperties, AriaRoles}; use rome_js_syntax::{AnyJsRoot, AnyJsxAttribute, JsLanguage, JsSyntaxNode, JsxAttributeList}; use rome_rowan::AstNode; use std::collections::HashMap; use std::sync::Arc; #[derive(Debug, Clone)] pub(crate) struct AriaServices { pub(crate) roles: Arc<AriaRoles>, pub(crate) properties: Arc<AriaProperties>, } impl AriaServices { pub fn aria_roles(&self) -> &AriaRoles { &self.roles } pub fn aria_properties(&self) -> &AriaProperties { &self.properties } pub fn is_valid_iso_language(&self, language: &str) -> bool { is_valid_language(language) } pub fn is_valid_iso_country(&self, country: &str) -> bool { is_valid_country(country) } pub fn iso_country_list(&self) -> &'static [&'static str] { countries() } pub fn iso_language_list(&self) -> &'static [&'static str] { languages() } /// Parses a [JsxAttributeList] and extracts the names and values of each [JsxAttribute], /// returning them as a [HashMap]. Attributes with no specified value are given a value of "true". /// If an attribute has multiple values, each value is stored as a separate item in the /// [HashMap] under the same attribute name. Returns [None] if the parsing fails. pub fn extract_attributes( &self, attribute_list: &JsxAttributeList, ) -> Option<HashMap<String, Vec<String>>> { let mut defined_attributes: HashMap<String, Vec<String>> = HashMap::new(); for attribute in attribute_list { if let AnyJsxAttribute::JsxAttribute(attr) = attribute { let name = attr.name().ok()?.syntax().text_trimmed().to_string(); // handle an attribute without values e.g. `<img aria-hidden />` let Some(initializer) = attr.initializer() else { defined_attributes.entry(name).or_insert(vec!["true".to_string()]); continue }; let initializer = initializer.value().ok()?; let static_value = initializer.as_static_value()?; // handle multiple values e.g. `<div class="wrapper document">` let values = static_value.text().split(' '); let values = values.map(|s| s.to_string()).collect::<Vec<String>>(); defined_attributes.entry(name).or_insert(values); } } Some(defined_attributes) } } #[cfg(test)] mod tests { use crate::aria_services::AriaServices; use rome_aria::{AriaProperties, AriaRoles}; use rome_js_factory::make::{ ident, jsx_attribute, jsx_attribute_initializer_clause, jsx_attribute_list, jsx_name, jsx_string, jsx_string_literal, token, }; use rome_js_syntax::{AnyJsxAttribute, AnyJsxAttributeName, AnyJsxAttributeValue, T}; use std::sync::Arc; #[test] fn test_extract_attributes() { // Assume attributes of `<div class="wrapper document" role="article"></div>` let attribute_list = jsx_attribute_list(vec![ AnyJsxAttribute::JsxAttribute( jsx_attribute(AnyJsxAttributeName::JsxName(jsx_name(ident("class")))) .with_initializer(jsx_attribute_initializer_clause( token(T![=]), AnyJsxAttributeValue::JsxString(jsx_string(jsx_string_literal( "wrapper document", ))), )) .build(), ), AnyJsxAttribute::JsxAttribute( jsx_attribute(AnyJsxAttributeName::JsxName(jsx_name(ident("role")))) .with_initializer(jsx_attribute_initializer_clause( token(T![=]), AnyJsxAttributeValue::JsxString(jsx_string(jsx_string_literal("article"))), )) .build(), ), ]); let services = AriaServices { roles: Arc::new(AriaRoles {}), properties: Arc::new(AriaProperties {}), }; let attribute_name_to_values = services.extract_attributes(&attribute_list).unwrap(); assert_eq!( attribute_name_to_values.get("class").unwrap(), &vec!["wrapper".to_string(), "document".to_string()] ); assert_eq!( attribute_name_to_values.get("role").unwrap(), &vec!["article".to_string()] ) } } impl FromServices for AriaServices { fn from_services( rule_key: &RuleKey, services: &ServiceBag, ) -> Result<Self, MissingServicesDiagnostic> { let roles: &Arc<AriaRoles> = services .get_service() .ok_or_else(|| MissingServicesDiagnostic::new(rule_key.rule_name(), &["AriaRoles"]))?; let properties: &Arc<AriaProperties> = services.get_service().ok_or_else(|| { MissingServicesDiagnostic::new(rule_key.rule_name(), &["AriaProperties"]) })?; Ok(Self { roles: roles.clone(), properties: properties.clone(), }) } } impl Phase for AriaServices { fn phase() -> Phases { Phases::Syntax } } /// Query type usable by lint rules **that uses the semantic model** to match on specific [AstNode] types #[derive(Clone)] pub(crate) struct Aria<N>(pub N); impl<N> Queryable for Aria<N> where N: AstNode<Language = JsLanguage> + 'static, { type Input = JsSyntaxNode; type Output = N; type Language = JsLanguage; type Services = AriaServices; fn build_visitor(analyzer: &mut impl AddVisitor<JsLanguage>, _: &AnyJsRoot) { analyzer.add_visitor(Phases::Syntax, SyntaxVisitor::default); } fn key() -> QueryKey<Self::Language> { QueryKey::Syntax(N::KIND_SET) } fn unwrap_match(_: &ServiceBag, node: &Self::Input) -> Self::Output { N::unwrap_cast(node.clone()) } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/aria_analyzers.rs
crates/rome_js_analyze/src/aria_analyzers.rs
//! Generated file, do not edit by hand, see `xtask/codegen` pub(crate) mod a11y; pub(crate) mod nursery; ::rome_analyze::declare_category! { pub (crate) AriaAnalyzers { kind : Lint , groups : [self :: a11y :: A11y , self :: nursery :: Nursery ,] } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/suppression_action.rs
crates/rome_js_analyze/src/suppression_action.rs
use crate::utils::batch::JsBatchMutation; use rome_analyze::SuppressionCommentEmitterPayload; use rome_js_factory::make::{jsx_expression_child, jsx_ident, jsx_text, token}; use rome_js_syntax::jsx_ext::AnyJsxElement; use rome_js_syntax::{ AnyJsxChild, JsLanguage, JsSyntaxKind, JsSyntaxToken, JsxChildList, JsxElement, JsxOpeningElement, JsxSelfClosingElement, JsxText, TextRange, T, }; use rome_rowan::{AstNode, TokenAtOffset, TriviaPieceKind}; /// Considering that the detection of suppression comments in the linter is "line based", the function starts /// querying the node covered by the text range of the diagnostic, until it finds the first token that has a newline /// among its leading trivia. /// /// There are some edge cases: /// - JSX elements might have newlines in their content; /// - JS templates are an exception to the rule. JS templates might contain expressions inside their /// content, and those expressions can contain diagnostics. The function uses the token `${` as boundary /// and tries to place the suppression comment after it; pub(crate) fn apply_suppression_comment(payload: SuppressionCommentEmitterPayload<JsLanguage>) { let SuppressionCommentEmitterPayload { token_offset, mutation, suppression_text, diagnostic_text_range, } = payload; // retrieve the most suited, most left token where the diagnostics was emitted let original_token = get_token_from_offset(token_offset, diagnostic_text_range); // considering that our suppression system works via lines, we need to look for the first newline, // so we can place the comment there let apply_suppression = original_token .as_ref() .map(|original_token| find_token_to_apply_suppression(original_token.clone())); if let Some(apply_suppression) = apply_suppression { let ApplySuppression { token_to_apply_suppression, token_has_trailing_comments, should_insert_leading_newline, } = apply_suppression; // we check if the token that has the newline is inside a JSX element: JsxOpeningElement or JsxSelfClosingElement let current_jsx_element = token_to_apply_suppression.parent().and_then(|parent| { if AnyJsxElement::can_cast(parent.kind()) || JsxText::can_cast(parent.kind()) { Some(parent) } else { None } }); // When inside a JSX element, we have to apply different logics when applying suppression comments. // Newlines are inside JsxText. if let Some(current_jsx_element) = current_jsx_element { // quick check is the element is inside a list if current_jsx_element .parent() .map(|p| JsxChildList::can_cast(p.kind())) .unwrap_or_default() { let jsx_comment = jsx_expression_child( token(T!['{']).with_trailing_trivia([( TriviaPieceKind::SingleLineComment, format!("/* {}: <explanation> */", suppression_text).as_str(), )]), token(T!['}']), ) .build(); if let Some(current_element) = JsxOpeningElement::cast_ref(&current_jsx_element) { let parent = current_element.parent::<JsxElement>(); if let Some(parent) = parent { mutation.add_jsx_elements_before_element( &parent.into(), [AnyJsxChild::JsxExpressionChild(jsx_comment)], ); } } else if let Some(current_element) = JsxSelfClosingElement::cast_ref(&current_jsx_element) { mutation.add_jsx_elements_before_element( &AnyJsxChild::JsxSelfClosingElement(current_element), [AnyJsxChild::JsxExpressionChild(jsx_comment)], ); } else if let Some(current_element) = JsxText::cast_ref(&current_jsx_element) { // We want to add an additional JsxText to keep the indentation let indentation_text = make_indentation_from_jsx_element(&current_element); mutation.add_jsx_elements_after_element( &AnyJsxChild::JsxText(current_element), [ AnyJsxChild::JsxExpressionChild(jsx_comment), AnyJsxChild::JsxText(indentation_text), ], ); } } else { let mut new_token = token_to_apply_suppression.clone(); if !should_insert_leading_newline { new_token = new_token.with_leading_trivia([ (TriviaPieceKind::Newline, "\n"), ( TriviaPieceKind::SingleLineComment, format!("// {}: <explanation>", suppression_text).as_str(), ), (TriviaPieceKind::Newline, "\n"), ]) } else { new_token = new_token.with_leading_trivia([ ( TriviaPieceKind::SingleLineComment, format!("// {}: <explanation>", suppression_text).as_str(), ), (TriviaPieceKind::Newline, "\n"), ]) }; mutation.replace_token_transfer_trivia(token_to_apply_suppression, new_token); } } else { let mut new_token = token_to_apply_suppression.clone(); if !should_insert_leading_newline { if token_has_trailing_comments { new_token = new_token.with_trailing_trivia([ (TriviaPieceKind::Newline, "\n"), ( TriviaPieceKind::SingleLineComment, format!("// {}: <explanation>", suppression_text).as_str(), ), (TriviaPieceKind::Newline, "\n"), ]) } else { new_token = new_token.with_leading_trivia([ (TriviaPieceKind::Newline, "\n"), ( TriviaPieceKind::SingleLineComment, format!("// {}: <explanation>", suppression_text).as_str(), ), (TriviaPieceKind::Newline, "\n"), ]) } } else if token_has_trailing_comments { new_token = new_token.with_trailing_trivia([ ( TriviaPieceKind::SingleLineComment, format!("// {}: <explanation>", suppression_text).as_str(), ), (TriviaPieceKind::Newline, "\n"), ]) } else { new_token = new_token.with_leading_trivia([ ( TriviaPieceKind::SingleLineComment, format!("// {}: <explanation>", suppression_text).as_str(), ), (TriviaPieceKind::Newline, "\n"), ]) }; mutation.replace_token_transfer_trivia(token_to_apply_suppression, new_token); } } } /// Convenient type to store useful information struct ApplySuppression { /// If the token is following by trailing comments token_has_trailing_comments: bool, /// The token to apply attach the suppression token_to_apply_suppression: JsSyntaxToken, /// If the suppression should have a leading newline should_insert_leading_newline: bool, } /// It checks if the current token has leading trivia newline. If not, it /// it peeks the previous token and recursively call itself. /// /// Due to the nature of JSX, sometimes the current token might contain text that contains /// some newline. In case that happens, we choose that token. /// /// Due to the nature of JavaScript templates, we also check if the tokens we browse are /// `${` and if so, we stop there. fn find_token_to_apply_suppression(token: JsSyntaxToken) -> ApplySuppression { let mut apply_suppression = ApplySuppression { token_has_trailing_comments: false, token_to_apply_suppression: token.clone(), should_insert_leading_newline: false, }; let mut current_token = token; let mut should_insert_leading_newline = loop { let trivia = current_token.leading_trivia(); // There are some tokens that might contains newlines in their tokens, only // few nodes matches this criteria. If the token is inside one of those nodes, // then we check its content. let nodes_that_might_contain_newlines = current_token .parent() .map(|node| { matches!( node.kind(), JsSyntaxKind::JSX_TEXT | JsSyntaxKind::JS_STRING_LITERAL | JsSyntaxKind::TEMPLATE_CHUNK ) }) .unwrap_or_default(); if current_token .trailing_trivia() .pieces() .any(|trivia| trivia.kind().is_multiline_comment()) { break true; } else if trivia.pieces().any(|trivia| trivia.is_newline()) || (nodes_that_might_contain_newlines && current_token.text_trimmed().contains(['\n', '\r'])) { break false; } else if matches!(current_token.kind(), JsSyntaxKind::DOLLAR_CURLY) { if let Some(next_token) = current_token.next_token() { current_token = next_token; break false; } } else if let Some(token) = current_token.prev_token() { current_token = token; } else { break true; } }; // If the flag has been set to `true`, it means we are at the beginning of the file. if !should_insert_leading_newline { // Still, if there's a a multiline comment, we want to try to attach the suppression comment // to the existing multiline comment without newlines. should_insert_leading_newline = current_token .leading_trivia() .pieces() .all(|piece| !piece.kind().is_multiline_comment()); } apply_suppression.should_insert_leading_newline = should_insert_leading_newline; apply_suppression.token_has_trailing_comments = current_token .trailing_trivia() .pieces() .any(|trivia| trivia.kind().is_multiline_comment()); apply_suppression.token_to_apply_suppression = current_token; apply_suppression } /// Finds the first token, starting with the current token and traversing backwards, /// until if find one that has has a leading newline trivia. /// /// Sometimes, the offset is between tokens, we need to decide which one to take. /// /// For example: /// ```jsx /// function f() { /// return <div /// ><img /> {/* <--- diagnostic emitted in this line */} /// </div> /// } /// ``` /// /// In these case it's best to peek the right token, because it belongs to the node where error actually occurred, /// and becomes easier to add the suppression comment. fn get_token_from_offset( token_offset: TokenAtOffset<JsSyntaxToken>, diagnostic_text_range: &TextRange, ) -> Option<JsSyntaxToken> { match token_offset { TokenAtOffset::None => None, TokenAtOffset::Single(token) => Some(token), TokenAtOffset::Between(left_token, right_token) => { let chosen_token = if right_token.text_range().start() == diagnostic_text_range.start() { right_token } else { left_token }; Some(chosen_token) } } } /// Creates a new [JsxText], where its content are the computed spaces from `current_element`. /// /// This new element will serve as trailing "newline" for the suppression comment. fn make_indentation_from_jsx_element(current_element: &JsxText) -> JsxText { if let Ok(text) = current_element.value_token() { let chars = text.text().chars(); let mut newlines = 0; let mut spaces = 0; let mut string_found = false; for char in chars { if char == '\"' { if string_found { string_found = false; } else { string_found = true; continue; } } if string_found { continue; } if matches!(char, '\r' | '\n') { newlines += 1; } if matches!(char, ' ') && newlines == 1 && !string_found { spaces += 1; } } let content = format!("\n{}", " ".repeat(spaces)); jsx_text(jsx_ident(content.as_str())) } else { jsx_text(jsx_ident("\n")) } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/semantic_services.rs
crates/rome_js_analyze/src/semantic_services.rs
use rome_analyze::{ AddVisitor, FromServices, MissingServicesDiagnostic, Phase, Phases, QueryKey, QueryMatch, Queryable, RuleKey, ServiceBag, SyntaxVisitor, Visitor, VisitorContext, VisitorFinishContext, }; use rome_js_semantic::{SemanticEventExtractor, SemanticModel, SemanticModelBuilder}; use rome_js_syntax::{AnyJsRoot, JsLanguage, JsSyntaxNode, TextRange, WalkEvent}; use rome_rowan::{AstNode, SyntaxNode}; pub struct SemanticServices { model: SemanticModel, } impl SemanticServices { pub fn model(&self) -> &SemanticModel { &self.model } } impl FromServices for SemanticServices { fn from_services( rule_key: &RuleKey, services: &ServiceBag, ) -> Result<Self, MissingServicesDiagnostic> { let model: &SemanticModel = services.get_service().ok_or_else(|| { MissingServicesDiagnostic::new(rule_key.rule_name(), &["SemanticModel"]) })?; Ok(Self { model: model.clone(), }) } } impl Phase for SemanticServices { fn phase() -> Phases { Phases::Semantic } } /// The [SemanticServices] types can be used as a queryable to get an instance /// of the whole [SemanticModel] without matching on a specific AST node impl Queryable for SemanticServices { type Input = SemanticModelEvent; type Output = SemanticModel; type Language = JsLanguage; type Services = Self; fn build_visitor(analyzer: &mut impl AddVisitor<JsLanguage>, root: &AnyJsRoot) { analyzer.add_visitor(Phases::Syntax, || SemanticModelBuilderVisitor::new(root)); analyzer.add_visitor(Phases::Semantic, || SemanticModelVisitor); } fn unwrap_match(services: &ServiceBag, _: &SemanticModelEvent) -> Self::Output { services .get_service::<SemanticModel>() .expect("SemanticModel service is not registered") .clone() } } /// Query type usable by lint rules **that uses the semantic model** to match on specific [AstNode] types #[derive(Clone)] pub struct Semantic<N>(pub N); impl<N> Queryable for Semantic<N> where N: AstNode<Language = JsLanguage> + 'static, { type Input = JsSyntaxNode; type Output = N; type Language = JsLanguage; type Services = SemanticServices; fn build_visitor(analyzer: &mut impl AddVisitor<JsLanguage>, root: &AnyJsRoot) { analyzer.add_visitor(Phases::Syntax, || SemanticModelBuilderVisitor::new(root)); analyzer.add_visitor(Phases::Semantic, SyntaxVisitor::default); } fn key() -> QueryKey<Self::Language> { QueryKey::Syntax(N::KIND_SET) } fn unwrap_match(_: &ServiceBag, node: &Self::Input) -> Self::Output { N::unwrap_cast(node.clone()) } } struct SemanticModelBuilderVisitor { extractor: SemanticEventExtractor, builder: SemanticModelBuilder, } impl SemanticModelBuilderVisitor { fn new(root: &AnyJsRoot) -> Self { Self { extractor: SemanticEventExtractor::default(), builder: SemanticModelBuilder::new(root.clone()), } } } impl Visitor for SemanticModelBuilderVisitor { type Language = JsLanguage; fn visit( &mut self, event: &WalkEvent<SyntaxNode<JsLanguage>>, _ctx: VisitorContext<JsLanguage>, ) { match event { WalkEvent::Enter(node) => { self.builder.push_node(node); self.extractor.enter(node); } WalkEvent::Leave(node) => { self.extractor.leave(node); } } while let Some(e) = self.extractor.pop() { self.builder.push_event(e); } } fn finish(self: Box<Self>, ctx: VisitorFinishContext<JsLanguage>) { let model = self.builder.build(); ctx.services.insert_service(model); } } pub struct SemanticModelVisitor; pub struct SemanticModelEvent(TextRange); impl QueryMatch for SemanticModelEvent { fn text_range(&self) -> TextRange { self.0 } } impl Visitor for SemanticModelVisitor { type Language = JsLanguage; fn visit( &mut self, event: &WalkEvent<SyntaxNode<JsLanguage>>, mut ctx: VisitorContext<JsLanguage>, ) { let root = match event { WalkEvent::Enter(node) => { if node.parent().is_some() { return; } node } WalkEvent::Leave(_) => return, }; let text_range = root.text_range(); ctx.match_query(SemanticModelEvent(text_range)); } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/syntax.rs
crates/rome_js_analyze/src/syntax.rs
//! Generated file, do not edit by hand, see `xtask/codegen` pub(crate) mod nursery; ::rome_analyze::declare_category! { pub (crate) Syntax { kind : Syntax , groups : [self :: nursery :: Nursery ,] } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/ast_utils.rs
crates/rome_js_analyze/src/ast_utils.rs
use rome_js_syntax::{JsLanguage, JsSyntaxNode, JsSyntaxToken, TriviaPieceKind}; use rome_rowan::{AstNode, TriviaPiece}; /// Add any leading and trailing trivia from given source node to the token. /// /// Adds whitespace trivia if needed for safe replacement of source node. pub fn token_with_source_trivia<T>(token: JsSyntaxToken, source: &T) -> JsSyntaxToken where T: AstNode<Language = JsLanguage>, { let mut text = String::new(); let node = source.syntax(); let mut leading = vec![]; let mut trailing = vec![]; add_leading_trivia(&mut leading, &mut text, node); text.push_str(token.text()); add_trailing_trivia(&mut trailing, &mut text, node); JsSyntaxToken::new_detached(token.kind(), &text, leading, trailing) } fn add_leading_trivia(trivia: &mut Vec<TriviaPiece>, text: &mut String, node: &JsSyntaxNode) { let Some(token) = node.first_token() else { return }; for t in token.leading_trivia().pieces() { text.push_str(t.text()); trivia.push(TriviaPiece::new(t.kind(), t.text_len())); } if !trivia.is_empty() { return; } let Some(token) = token.prev_token() else { return }; if !token.kind().is_punct() && token.trailing_trivia().pieces().next().is_none() { text.push(' '); trivia.push(TriviaPiece::new(TriviaPieceKind::Whitespace, 1)); } } fn add_trailing_trivia(trivia: &mut Vec<TriviaPiece>, text: &mut String, node: &JsSyntaxNode) { let Some(token) = node.last_token() else { return }; for t in token.trailing_trivia().pieces() { text.push_str(t.text()); trivia.push(TriviaPiece::new(t.kind(), t.text_len())); } if !trivia.is_empty() { return; } let Some(token) = token.next_token() else { return }; if !token.kind().is_punct() && token.leading_trivia().pieces().next().is_none() { text.push(' '); trivia.push(TriviaPiece::new(TriviaPieceKind::Whitespace, 1)); } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/assists.rs
crates/rome_js_analyze/src/assists.rs
//! Generated file, do not edit by hand, see `xtask/codegen` pub(crate) mod correctness; ::rome_analyze::declare_category! { pub (crate) Assists { kind : Action , groups : [self :: correctness :: Correctness ,] } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/utils.rs
crates/rome_js_analyze/src/utils.rs
use rome_js_factory::make; use rome_js_syntax::{ inner_string_text, AnyJsStatement, JsLanguage, JsModuleItemList, JsStatementList, JsSyntaxNode, JsVariableDeclaration, JsVariableDeclarator, JsVariableDeclaratorList, JsVariableStatement, T, }; use rome_rowan::{AstNode, AstSeparatedList, BatchMutation, Direction, WalkEvent}; use std::borrow::Cow; use std::iter; pub mod batch; pub mod case; pub mod escape; pub mod rename; #[cfg(test)] pub mod tests; #[derive(Debug, PartialEq)] pub(crate) enum EscapeError { EscapeAtEndOfString, InvalidEscapedChar(char), } struct InterpretEscapedString<'a> { s: std::str::Chars<'a>, } impl<'a> Iterator for InterpretEscapedString<'a> { type Item = Result<char, EscapeError>; fn next(&mut self) -> Option<Self::Item> { self.s.next().map(|c| match c { '\\' => match self.s.next() { None => Err(EscapeError::EscapeAtEndOfString), Some('n') => Ok('\n'), Some('\\') => Ok('\\'), Some(c) => Err(EscapeError::InvalidEscapedChar(c)), }, c => Ok(c), }) } } /// unescape /// pub(crate) fn escape_string(s: &str) -> Result<String, EscapeError> { (InterpretEscapedString { s: s.chars() }).collect() } pub trait ToCamelCase { /// Return the camel case form of the input parameter. /// If it is already in camel case, nothing is done. /// /// This method do not address abbreviations and acronyms. fn to_camel_case(&self) -> Cow<str>; } impl ToCamelCase for str { fn to_camel_case(&self) -> Cow<str> { to_camel_case(self) } } /// Return the camel case form of the input parameter. /// If it is already in camel case, nothing is done. /// /// This method do not address abbreviations and acronyms. pub fn to_camel_case(input: &str) -> Cow<str> { pub enum ForceNext { Uppercase, Lowercase, } let mut force_next = None; let mut chars = input.char_indices(); let mut last_i = input.len() - 1; while let Some((i, chr)) = chars.next() { if i == 0 && chr.is_uppercase() { chars = input.char_indices(); force_next = Some(ForceNext::Lowercase); last_i = i; break; } if !chr.is_alphanumeric() { if i == 0 { force_next = Some(ForceNext::Lowercase); } else { force_next = Some(ForceNext::Uppercase); } last_i = i; break; } } if last_i >= (input.len() - 1) { Cow::Borrowed(input) } else { let mut output = Vec::with_capacity(input.len()); output.extend_from_slice(input[..last_i].as_bytes()); //SAFETY: bytes were already inside a valid &str let mut output = unsafe { String::from_utf8_unchecked(output) }; for (_, chr) in chars { if !chr.is_alphanumeric() { force_next = Some(ForceNext::Uppercase); continue; } match force_next { Some(ForceNext::Uppercase) => { output.extend(chr.to_uppercase()); } Some(ForceNext::Lowercase) => { output.extend(chr.to_lowercase()); } None => { output.push(chr); } } force_next = None; } Cow::Owned(output) } } /// Utility function to remove a statement node from a syntax tree, by either /// removing the node from its parent if said parent is a statement list or /// module item list, or by replacing the statement node with an empty statement pub(crate) fn remove_statement<N>(mutation: &mut BatchMutation<JsLanguage>, node: &N) -> Option<()> where N: AstNode<Language = JsLanguage> + Into<AnyJsStatement>, { let parent = node.syntax().parent()?; if JsStatementList::can_cast(parent.kind()) || JsModuleItemList::can_cast(parent.kind()) { mutation.remove_node(node.clone()); } else { mutation.replace_node( node.clone().into(), AnyJsStatement::JsEmptyStatement(make::js_empty_statement(make::token(T![;]))), ); } Some(()) } /// Removes the declarator, and: /// 1 - removes the statement if the declaration only has one declarator; /// 2 - removes commas around the declarator to keep the declaration list valid. pub(crate) fn remove_declarator( batch: &mut BatchMutation<JsLanguage>, declarator: &JsVariableDeclarator, ) -> Option<()> { let list = declarator.parent::<JsVariableDeclaratorList>()?; let declaration = list.parent::<JsVariableDeclaration>()?; if list.syntax_list().len() == 1 { let statement = declaration.parent::<JsVariableStatement>()?; batch.remove_node(statement); } else { let mut elements = list.elements(); // Find the declarator we want to remove // remove its trailing comma, if there is one let mut previous_element = None; for element in elements.by_ref() { if let Ok(node) = element.node() { if node == declarator { batch.remove_node(node.clone()); if let Some(comma) = element.trailing_separator().ok().flatten() { batch.remove_token(comma.clone()); } break; } } previous_element = Some(element); } // if it is the last declarator of the list // removes the comma before this element let is_last = elements.next().is_none(); if is_last { if let Some(element) = previous_element { if let Some(comma) = element.trailing_separator().ok().flatten() { batch.remove_token(comma.clone()); } } } } Some(()) } /// Verifies that both nodes are equal by checking their descendants (nodes included) kinds /// and tokens (same kind and inner token text). pub(crate) fn is_node_equal(a_node: &JsSyntaxNode, b_node: &JsSyntaxNode) -> bool { let a_tree = a_node.preorder_with_tokens(Direction::Next); let b_tree = b_node.preorder_with_tokens(Direction::Next); for (a_child, b_child) in iter::zip(a_tree, b_tree) { let a_event = match a_child { WalkEvent::Enter(event) => event, WalkEvent::Leave(event) => event, }; let b_event = match b_child { WalkEvent::Enter(event) => event, WalkEvent::Leave(event) => event, }; if a_event.kind() != b_event.kind() { return false; } let a_token = a_event.as_token(); let b_token = b_event.as_token(); match (a_token, b_token) { // both are nodes (None, None) => continue, // one of them is a node (None, Some(_)) | (Some(_), None) => return false, // both are tokens (Some(a), Some(b)) => { if inner_string_text(a) != inner_string_text(b) { return false; } continue; } } } true } #[test] fn ok_to_camel_case() { assert_eq!(to_camel_case("camelCase"), Cow::Borrowed("camelCase")); assert_eq!( to_camel_case("longCamelCase"), Cow::Borrowed("longCamelCase") ); assert!(matches!( to_camel_case("CamelCase"), Cow::Owned(s) if s.as_str() == "camelCase" )); assert!(matches!( to_camel_case("_camelCase"), Cow::Owned(s) if s.as_str() == "camelCase" )); assert!(matches!( to_camel_case("_camelCase_"), Cow::Owned(s) if s.as_str() == "camelCase" )); assert!(matches!( to_camel_case("_camel_Case_"), Cow::Owned(s) if s.as_str() == "camelCase" )); assert!(matches!( to_camel_case("_camel_case_"), Cow::Owned(s) if s.as_str() == "camelCase" )); assert!(matches!( to_camel_case("_camel_case"), Cow::Owned(s) if s.as_str() == "camelCase" )); assert!(matches!( to_camel_case("camel_case"), Cow::Owned(s) if s.as_str() == "camelCase" )); assert!(matches!( to_camel_case("LongCamelCase"), Cow::Owned(s) if s.as_str() == "longCamelCase" )); assert!(matches!( to_camel_case("long_camel_case"), Cow::Owned(s) if s.as_str() == "longCamelCase" )); }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/registry.rs
crates/rome_js_analyze/src/registry.rs
//! Generated file, do not edit by hand, see `xtask/codegen` use rome_analyze::RegistryVisitor; use rome_js_syntax::JsLanguage; pub fn visit_registry<V: RegistryVisitor<JsLanguage>>(registry: &mut V) { registry.record_category::<crate::analyzers::Analyzers>(); registry.record_category::<crate::semantic_analyzers::SemanticAnalyzers>(); registry.record_category::<crate::aria_analyzers::AriaAnalyzers>(); registry.record_category::<crate::assists::Assists>(); registry.record_category::<crate::syntax::Syntax>(); }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/options.rs
crates/rome_js_analyze/src/options.rs
//! This module contains the rules that have options use crate::analyzers::nursery::no_excessive_complexity::{complexity_options, ComplexityOptions}; use crate::semantic_analyzers::nursery::use_exhaustive_dependencies::{ hooks_options, HooksOptions, }; use crate::semantic_analyzers::nursery::use_naming_convention::{ naming_convention_options, NamingConventionOptions, }; use crate::semantic_analyzers::style::no_restricted_globals::{ restricted_globals_options, RestrictedGlobalsOptions, }; use bpaf::Bpaf; use rome_analyze::options::RuleOptions; use rome_analyze::RuleKey; use rome_deserialize::json::VisitJsonNode; use rome_deserialize::{DeserializationDiagnostic, VisitNode}; use rome_json_syntax::{AnyJsonValue, JsonLanguage, JsonMemberName, JsonObjectValue}; use rome_rowan::AstNode; #[cfg(feature = "schemars")] use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use std::str::FromStr; #[derive(Default, Deserialize, Serialize, Debug, Clone, Bpaf)] #[cfg_attr(feature = "schemars", derive(JsonSchema))] #[serde(rename_all = "camelCase", deny_unknown_fields, untagged)] pub enum PossibleOptions { /// Options for `noExcessiveComplexity` rule Complexity(#[bpaf(external(complexity_options), hide)] ComplexityOptions), /// Options for `useExhaustiveDependencies` and `useHookAtTopLevel` rule Hooks(#[bpaf(external(hooks_options), hide)] HooksOptions), /// Options for `useNamingConvention` rule NamingConvention(#[bpaf(external(naming_convention_options), hide)] NamingConventionOptions), /// Options for `noRestrictedGlobals` rule RestrictedGlobals(#[bpaf(external(restricted_globals_options), hide)] RestrictedGlobalsOptions), /// No options available #[default] NoOptions, } impl FromStr for PossibleOptions { type Err = (); fn from_str(_s: &str) -> Result<Self, Self::Err> { Ok(Self::NoOptions) } } impl PossibleOptions { pub fn extract_option(&self, rule_key: &RuleKey) -> RuleOptions { match rule_key.rule_name() { "noExcessiveComplexity" => { let options = match self { PossibleOptions::Complexity(options) => options.clone(), _ => ComplexityOptions::default(), }; RuleOptions::new(options) } "useExhaustiveDependencies" | "useHookAtTopLevel" => { let options = match self { PossibleOptions::Hooks(options) => options.clone(), _ => HooksOptions::default(), }; RuleOptions::new(options) } "useNamingConvention" => { let options = match self { PossibleOptions::NamingConvention(options) => options.clone(), _ => NamingConventionOptions::default(), }; RuleOptions::new(options) } "noRestrictedGlobals" => { let options = match self { PossibleOptions::RestrictedGlobals(options) => options.clone(), _ => RestrictedGlobalsOptions::default(), }; RuleOptions::new(options) } // TODO: review error _ => panic!("This rule {:?} doesn't have options", rule_key), } } } impl PossibleOptions { pub fn map_to_rule_options( &mut self, value: &AnyJsonValue, name: &str, rule_name: &str, diagnostics: &mut Vec<DeserializationDiagnostic>, ) -> Option<()> { let value = JsonObjectValue::cast_ref(value.syntax()).or_else(|| { diagnostics.push(DeserializationDiagnostic::new_incorrect_type_for_value( name, "object", value.range(), )); None })?; for element in value.json_member_list() { let element = element.ok()?; let key = element.name().ok()?; let value = element.value().ok()?; let name = key.inner_string_text().ok()?; self.validate_key(&key, rule_name, diagnostics)?; match name.text() { "hooks" => { let mut options = HooksOptions::default(); self.map_to_array(&value, &name, &mut options, diagnostics)?; *self = PossibleOptions::Hooks(options); } "maxAllowedComplexity" => { let mut options = ComplexityOptions::default(); options.visit_map(key.syntax(), value.syntax(), diagnostics)?; *self = PossibleOptions::Complexity(options); } "strictCase" | "enumMemberCase" => { let mut options = match self { PossibleOptions::NamingConvention(options) => options.clone(), _ => NamingConventionOptions::default(), }; options.visit_map(key.syntax(), value.syntax(), diagnostics)?; *self = PossibleOptions::NamingConvention(options); } "deniedGlobals" => { let mut options = match self { PossibleOptions::RestrictedGlobals(options) => options.clone(), _ => RestrictedGlobalsOptions::default(), }; options.visit_map(key.syntax(), value.syntax(), diagnostics)?; *self = PossibleOptions::RestrictedGlobals(options); } _ => (), } } Some(()) } pub fn validate_key( &mut self, node: &JsonMemberName, rule_name: &str, diagnostics: &mut Vec<DeserializationDiagnostic>, ) -> Option<()> { let key_name = node.inner_string_text().ok()?; let key_name = key_name.text(); match rule_name { "useExhaustiveDependencies" | "useHookAtTopLevel" => { if key_name != "hooks" { diagnostics.push(DeserializationDiagnostic::new_unknown_key( key_name, node.range(), &["hooks"], )); } } "useNamingConvention" => { if !matches!(key_name, "strictCase" | "enumMemberCase") { diagnostics.push(DeserializationDiagnostic::new_unknown_key( key_name, node.range(), &["strictCase", "enumMemberCase"], )); } } "noExcessiveComplexity" => { if !matches!(key_name, "maxAllowedComplexity") { diagnostics.push(DeserializationDiagnostic::new_unknown_key( key_name, node.range(), &["maxAllowedComplexity"], )); } } "noRestrictedGlobals" => { if !matches!(key_name, "deniedGlobals") { diagnostics.push(DeserializationDiagnostic::new_unknown_key( key_name, node.range(), &["deniedGlobals"], )); } } _ => {} } Some(()) } } impl VisitJsonNode for PossibleOptions {} impl VisitNode<JsonLanguage> for PossibleOptions {}
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers.rs
crates/rome_js_analyze/src/analyzers.rs
//! Generated file, do not edit by hand, see `xtask/codegen` pub(crate) mod a11y; pub(crate) mod complexity; pub(crate) mod correctness; pub(crate) mod nursery; pub(crate) mod performance; pub(crate) mod style; pub(crate) mod suspicious; ::rome_analyze::declare_category! { pub (crate) Analyzers { kind : Lint , groups : [self :: a11y :: A11y , self :: complexity :: Complexity , self :: correctness :: Correctness , self :: nursery :: Nursery , self :: performance :: Performance , self :: style :: Style , self :: suspicious :: Suspicious ,] } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/react.rs
crates/rome_js_analyze/src/react.rs
//! A series of AST utilities to work with the React library pub mod hooks; use rome_js_semantic::{Binding, SemanticModel}; use rome_js_syntax::{ AnyJsCallArgument, AnyJsExpression, AnyJsMemberExpression, AnyJsNamedImportSpecifier, JsCallExpression, JsIdentifierBinding, JsImport, JsImportNamedClause, JsNamedImportSpecifierList, JsNamedImportSpecifiers, JsObjectExpression, JsPropertyObjectMember, JsxMemberName, JsxReferenceIdentifier, }; use rome_rowan::{AstNode, AstSeparatedList}; /// A trait to share common logic among data structures that "mimic" react APIs pub(crate) trait ReactApiCall { /// It scans the current props and returns the property that matches the passed name fn find_prop_by_name(&self, prop_name: &str) -> Option<JsPropertyObjectMember>; } /// A convenient data structure that returns the three arguments of the [React.createElement] call /// ///[React.createElement]: https://reactjs.org/docs/react-api.html#createelement pub(crate) struct ReactCreateElementCall { /// The type of the react element pub(crate) element_type: AnyJsCallArgument, /// Optional props pub(crate) props: Option<JsObjectExpression>, /// Optional children pub(crate) children: Option<AnyJsExpression>, } impl ReactCreateElementCall { /// Checks if the current node is a possible `createElement` call. /// /// There are two cases: /// /// First case /// ```js /// React.createElement() /// ``` /// We check if the node is a static member expression with the specific members. Also, if `React` /// has been imported in the current scope, we make sure that the binding `React` has been imported /// from the `"react"` module. /// /// Second case /// /// ```js /// createElement() /// ``` /// /// The logic of this second case is very similar to the previous one, simply the node that we have /// to inspect is different. pub(crate) fn from_call_expression( call_expression: &JsCallExpression, model: &SemanticModel, ) -> Option<Self> { let callee = call_expression.callee().ok()?; let is_react_create_element = is_react_call_api(callee, model, ReactLibrary::React, "createElement"); if is_react_create_element { let arguments = call_expression.arguments().ok()?.args(); // React.createElement() should not be processed if !arguments.is_empty() { let mut iter = arguments.iter(); let first_argument = if let Some(first_argument) = iter.next() { first_argument.ok()? } else { return None; }; let second_argument = iter.next() .and_then(|argument| argument.ok()) .and_then(|argument| { argument .as_any_js_expression()? .as_js_object_expression() .cloned() }); let third_argument = iter .next() .and_then(|argument| argument.ok()) .and_then(|argument| argument.as_any_js_expression().cloned()); Some(ReactCreateElementCall { element_type: first_argument, props: second_argument, children: third_argument, }) } else { None } } else { None } } } impl ReactApiCall for ReactCreateElementCall { /// It scans the current props and returns the property that matches the passed name fn find_prop_by_name(&self, prop_name: &str) -> Option<JsPropertyObjectMember> { self.props.as_ref().and_then(|props| { let members = props.members(); members.iter().find_map(|member| { let member = member.ok()?; let property = member.as_js_property_object_member()?; let property_name = property.name().ok()?; let property_name = property_name.as_js_literal_member_name()?; if property_name.name().ok()? == prop_name { Some(property.clone()) } else { None } }) }) } } #[derive(Debug, Clone, Copy)] pub(crate) enum ReactLibrary { React, ReactDOM, } impl ReactLibrary { const fn import_name(self) -> &'static str { match self { ReactLibrary::React => "react", ReactLibrary::ReactDOM => "react-dom", } } const fn global_name(self) -> &'static str { match self { ReactLibrary::React => "React", ReactLibrary::ReactDOM => "ReactDOM", } } } /// List of valid [`React` API] /// /// [`React` API]: https://reactjs.org/docs/react-api.html const VALID_REACT_API: [&str; 29] = [ "Component", "PureComponent", "memo", "createElement", "cloneElement", "createFactory", "isValidElement", "Fragment", "createRef", "forwardRef", "lazy", "Suspense", "startTransition", "Children", "useEffect", "useLayoutEffect", "useInsertionEffect", "useCallback", "useMemo", "useImperativeHandle", "useState", "useContext", "useReducer", "useRef", "useDebugValue", "useDeferredValue", "useTransition", "useId", "useSyncExternalStore", ]; /// Checks if the current [JsCallExpression] is a potential [`React` API]. /// The function has accepts a `api_name` to check against /// /// [`React` API]: https://reactjs.org/docs/react-api.html pub(crate) fn is_react_call_api( expression: AnyJsExpression, model: &SemanticModel, lib: ReactLibrary, api_name: &str, ) -> bool { if matches!(lib, ReactLibrary::React) { // we bail straight away if the API doesn't exists in React debug_assert!(VALID_REACT_API.contains(&api_name)); } let expr = expression.omit_parentheses(); if let Some(callee) = AnyJsMemberExpression::cast_ref(expr.syntax()) { let Some(object) = callee.object().ok() else { return false }; let Some(reference) = object.omit_parentheses().as_js_reference_identifier() else { return false }; let Some(member_name) = callee.member_name() else { return false }; if member_name.text() != api_name { return false; } return match model.binding(&reference) { Some(decl) => is_react_export(decl, lib), None => reference.has_name(lib.global_name()), }; } if let Some(ident) = expr.as_js_reference_identifier() { return model .binding(&ident) .and_then(|it| is_named_react_export(it, lib, api_name)) .unwrap_or(false); } false } /// Checks if the node `JsxMemberName` is a react fragment. /// /// e.g. `<React.Fragment>` is a fragment, but no `<React.StrictMode>`. /// /// In case the `React` is a valid reference, the function checks if it is exported from the /// `"react"` library pub(crate) fn jsx_member_name_is_react_fragment( member_name: &JsxMemberName, model: &SemanticModel, ) -> Option<bool> { let object = member_name.object().ok()?; let member = member_name.member().ok()?; let object = object.as_jsx_reference_identifier()?; if member.value_token().ok()?.text_trimmed() != "Fragment" { return Some(false); } let lib = ReactLibrary::React; match model.binding(object) { Some(declaration) => Some(is_react_export(declaration, lib)), None => Some(object.value_token().ok()?.text_trimmed() == lib.global_name()), } } /// Checks if the node `JsxReferenceIdentifier` is a react fragment. /// /// e.g. `<Fragment>` is a fragment /// /// In case the `Fragment` is a valid reference, the function checks if it is exported from the /// `"react"` library pub(crate) fn jsx_reference_identifier_is_fragment( name: &JsxReferenceIdentifier, model: &SemanticModel, ) -> Option<bool> { match model.binding(name) { Some(reference) => is_named_react_export(reference, ReactLibrary::React, "Fragment"), None => { let value_token = name.value_token().ok()?; let is_fragment = value_token.text_trimmed() == "Fragment"; Some(is_fragment) } } } fn is_react_export(binding: Binding, lib: ReactLibrary) -> bool { binding .syntax() .ancestors() .find_map(|ancestor| JsImport::cast_ref(&ancestor)) .and_then(|js_import| js_import.source_is(lib.import_name()).ok()) .unwrap_or(false) } fn is_named_react_export(binding: Binding, lib: ReactLibrary, name: &str) -> Option<bool> { let ident = JsIdentifierBinding::cast_ref(binding.syntax())?; let import_specifier = ident.parent::<AnyJsNamedImportSpecifier>()?; let name_token = match &import_specifier { AnyJsNamedImportSpecifier::JsNamedImportSpecifier(named_import) => { named_import.name().ok()?.value().ok()? } AnyJsNamedImportSpecifier::JsShorthandNamedImportSpecifier(_) => ident.name_token().ok()?, AnyJsNamedImportSpecifier::JsBogusNamedImportSpecifier(_) => { return Some(false); } }; if name_token.text_trimmed() != name { return Some(false); } let import_specifier_list = import_specifier.parent::<JsNamedImportSpecifierList>()?; let import_specifiers = import_specifier_list.parent::<JsNamedImportSpecifiers>()?; let import_clause = import_specifiers.parent::<JsImportNamedClause>()?; let import = import_clause.parent::<JsImport>()?; import.source_is(lib.import_name()).ok() }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/control_flow.rs
crates/rome_js_analyze/src/control_flow.rs
use rome_analyze::QueryMatch; use rome_analyze::{AddVisitor, Phases, Queryable, ServiceBag}; use rome_js_syntax::AnyJsRoot; use rome_js_syntax::JsLanguage; use rome_js_syntax::TextRange; pub type JsControlFlowGraph = rome_control_flow::ControlFlowGraph<JsLanguage>; pub(crate) type BasicBlock = rome_control_flow::BasicBlock<JsLanguage>; pub(crate) type FunctionBuilder = rome_control_flow::builder::FunctionBuilder<JsLanguage>; mod nodes; mod visitor; pub(crate) use self::visitor::make_visitor; pub(crate) use self::visitor::AnyJsControlFlowRoot; pub struct ControlFlowGraph { pub graph: JsControlFlowGraph, } impl QueryMatch for ControlFlowGraph { fn text_range(&self) -> TextRange { self.graph.node.text_trimmed_range() } } impl Queryable for ControlFlowGraph { type Input = ControlFlowGraph; type Output = JsControlFlowGraph; type Language = JsLanguage; type Services = (); fn build_visitor(analyzer: &mut impl AddVisitor<JsLanguage>, _: &AnyJsRoot) { analyzer.add_visitor(Phases::Syntax, make_visitor); } fn unwrap_match(_: &ServiceBag, query: &ControlFlowGraph) -> Self::Output { query.graph.clone() } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/semantic_analyzers/complexity.rs
crates/rome_js_analyze/src/semantic_analyzers/complexity.rs
//! Generated file, do not edit by hand, see `xtask/codegen` use rome_analyze::declare_group; pub(crate) mod no_useless_fragments; declare_group! { pub (crate) Complexity { name : "complexity" , rules : [ self :: no_useless_fragments :: NoUselessFragments , ] } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/semantic_analyzers/security.rs
crates/rome_js_analyze/src/semantic_analyzers/security.rs
//! Generated file, do not edit by hand, see `xtask/codegen` use rome_analyze::declare_group; pub(crate) mod no_dangerously_set_inner_html; pub(crate) mod no_dangerously_set_inner_html_with_children; declare_group! { pub (crate) Security { name : "security" , rules : [ self :: no_dangerously_set_inner_html :: NoDangerouslySetInnerHtml , self :: no_dangerously_set_inner_html_with_children :: NoDangerouslySetInnerHtmlWithChildren , ] } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/semantic_analyzers/a11y.rs
crates/rome_js_analyze/src/semantic_analyzers/a11y.rs
//! Generated file, do not edit by hand, see `xtask/codegen` use rome_analyze::declare_group; pub(crate) mod no_positive_tabindex; pub(crate) mod use_button_type; declare_group! { pub (crate) A11y { name : "a11y" , rules : [ self :: no_positive_tabindex :: NoPositiveTabindex , self :: use_button_type :: UseButtonType , ] } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/semantic_analyzers/correctness.rs
crates/rome_js_analyze/src/semantic_analyzers/correctness.rs
//! Generated file, do not edit by hand, see `xtask/codegen` use rome_analyze::declare_group; pub(crate) mod no_children_prop; pub(crate) mod no_const_assign; pub(crate) mod no_global_object_calls; pub(crate) mod no_new_symbol; pub(crate) mod no_render_return_value; pub(crate) mod no_undeclared_variables; pub(crate) mod no_unused_variables; pub(crate) mod no_void_elements_with_children; pub(crate) mod use_is_nan; declare_group! { pub (crate) Correctness { name : "correctness" , rules : [ self :: no_children_prop :: NoChildrenProp , self :: no_const_assign :: NoConstAssign , self :: no_global_object_calls :: NoGlobalObjectCalls , self :: no_new_symbol :: NoNewSymbol , self :: no_render_return_value :: NoRenderReturnValue , self :: no_undeclared_variables :: NoUndeclaredVariables , self :: no_unused_variables :: NoUnusedVariables , self :: no_void_elements_with_children :: NoVoidElementsWithChildren , self :: use_is_nan :: UseIsNan , ] } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/semantic_analyzers/style.rs
crates/rome_js_analyze/src/semantic_analyzers/style.rs
//! Generated file, do not edit by hand, see `xtask/codegen` use rome_analyze::declare_group; pub(crate) mod no_arguments; pub(crate) mod no_parameter_assign; pub(crate) mod no_restricted_globals; pub(crate) mod no_shouty_constants; pub(crate) mod no_var; pub(crate) mod use_const; pub(crate) mod use_fragment_syntax; declare_group! { pub (crate) Style { name : "style" , rules : [ self :: no_arguments :: NoArguments , self :: no_parameter_assign :: NoParameterAssign , self :: no_restricted_globals :: NoRestrictedGlobals , self :: no_shouty_constants :: NoShoutyConstants , self :: no_var :: NoVar , self :: use_const :: UseConst , self :: use_fragment_syntax :: UseFragmentSyntax , ] } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/semantic_analyzers/nursery.rs
crates/rome_js_analyze/src/semantic_analyzers/nursery.rs
//! Generated file, do not edit by hand, see `xtask/codegen` use rome_analyze::declare_group; pub(crate) mod no_accumulating_spread; pub(crate) mod no_banned_types; pub(crate) mod no_constant_condition; pub(crate) mod no_global_is_finite; pub(crate) mod no_global_is_nan; pub(crate) mod no_unsafe_declaration_merging; pub(crate) mod use_exhaustive_dependencies; pub(crate) mod use_hook_at_top_level; pub(crate) mod use_is_array; pub(crate) mod use_naming_convention; declare_group! { pub (crate) Nursery { name : "nursery" , rules : [ self :: no_accumulating_spread :: NoAccumulatingSpread , self :: no_banned_types :: NoBannedTypes , self :: no_constant_condition :: NoConstantCondition , self :: no_global_is_finite :: NoGlobalIsFinite , self :: no_global_is_nan :: NoGlobalIsNan , self :: no_unsafe_declaration_merging :: NoUnsafeDeclarationMerging , self :: use_exhaustive_dependencies :: UseExhaustiveDependencies , self :: use_hook_at_top_level :: UseHookAtTopLevel , self :: use_is_array :: UseIsArray , self :: use_naming_convention :: UseNamingConvention , ] } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/semantic_analyzers/suspicious.rs
crates/rome_js_analyze/src/semantic_analyzers/suspicious.rs
//! Generated file, do not edit by hand, see `xtask/codegen` use rome_analyze::declare_group; pub(crate) mod no_array_index_key; pub(crate) mod no_catch_assign; pub(crate) mod no_class_assign; pub(crate) mod no_console_log; pub(crate) mod no_duplicate_parameters; pub(crate) mod no_function_assign; pub(crate) mod no_import_assign; pub(crate) mod no_label_var; pub(crate) mod no_redeclare; declare_group! { pub (crate) Suspicious { name : "suspicious" , rules : [ self :: no_array_index_key :: NoArrayIndexKey , self :: no_catch_assign :: NoCatchAssign , self :: no_class_assign :: NoClassAssign , self :: no_console_log :: NoConsoleLog , self :: no_duplicate_parameters :: NoDuplicateParameters , self :: no_function_assign :: NoFunctionAssign , self :: no_import_assign :: NoImportAssign , self :: no_label_var :: NoLabelVar , self :: no_redeclare :: NoRedeclare , ] } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/semantic_analyzers/a11y/no_positive_tabindex.rs
crates/rome_js_analyze/src/semantic_analyzers/a11y/no_positive_tabindex.rs
use crate::react::{ReactApiCall, ReactCreateElementCall}; use crate::semantic_services::Semantic; use rome_analyze::context::RuleContext; use rome_analyze::{declare_rule, Rule, RuleDiagnostic}; use rome_console::markup; use rome_js_semantic::SemanticModel; use rome_js_syntax::jsx_ext::AnyJsxElement; use rome_js_syntax::{ AnyJsxAttributeValue, JsCallExpression, JsNumberLiteralExpression, JsPropertyObjectMember, JsStringLiteralExpression, JsUnaryExpression, JsxAttribute, TextRange, }; use rome_rowan::{declare_node_union, AstNode}; declare_rule! { /// Prevent the usage of positive integers on `tabIndex` property /// /// Avoid positive `tabIndex` property values to synchronize the flow of the page with keyboard tab order. /// ## Accessibility guidelines /// /// [WCAG 2.4.3](https://www.w3.org/WAI/WCAG21/Understanding/focus-order) /// /// ## Examples /// /// ### Invalid /// /// ```jsx,expect_diagnostic /// <div tabIndex={1}>foo</div> /// ``` /// /// ```jsx,expect_diagnostic /// <div tabIndex={"1"} /> /// ``` /// /// ```js,expect_diagnostic /// React.createElement("div", { tabIndex: 1 }) /// ``` /// /// ### Valid /// /// ```jsx /// <div tabIndex="0" /> /// ``` /// /// ```js /// React.createElement("div", { tabIndex: -1 }) /// ``` pub(crate) NoPositiveTabindex { version: "10.0.0", name: "noPositiveTabindex", recommended: true, } } declare_node_union! { pub(crate) TabindexProp = JsxAttribute | JsPropertyObjectMember } declare_node_union! { pub(crate) NoPositiveTabindexQuery = AnyJsxElement | JsCallExpression } declare_node_union! { /// Subset of expressions supported by this rule. /// /// ## Examples /// /// - `JsStringLiteralExpression` &mdash; `"5"` /// - `JsNumberLiteralExpression` &mdash; `5` /// - `JsUnaryExpression` &mdash; `+5` | `-5` /// pub(crate) AnyNumberLikeExpression = JsStringLiteralExpression | JsNumberLiteralExpression | JsUnaryExpression } impl NoPositiveTabindexQuery { fn find_tabindex_attribute(&self, model: &SemanticModel) -> Option<TabindexProp> { match self { NoPositiveTabindexQuery::AnyJsxElement(jsx) => jsx .find_attribute_by_name("tabIndex") .map(TabindexProp::from), NoPositiveTabindexQuery::JsCallExpression(expression) => { let react_create_element = ReactCreateElementCall::from_call_expression(expression, model)?; react_create_element .find_prop_by_name("tabIndex") .map(TabindexProp::from) } } } } impl AnyNumberLikeExpression { /// Returns the value of a number-like expression; it returns the expression /// text for literal expressions. However, for unary expressions, it only /// returns the value for signed numeric expressions. pub(crate) fn value(&self) -> Option<String> { match self { AnyNumberLikeExpression::JsStringLiteralExpression(string_literal) => { return Some(string_literal.inner_string_text().ok()?.to_string()); } AnyNumberLikeExpression::JsNumberLiteralExpression(number_literal) => { return Some(number_literal.value_token().ok()?.to_string()); } AnyNumberLikeExpression::JsUnaryExpression(unary_expression) => { if unary_expression.is_signed_numeric_literal().ok()? { return Some(unary_expression.text()); } } } None } } impl Rule for NoPositiveTabindex { type Query = Semantic<NoPositiveTabindexQuery>; type State = TextRange; type Signals = Option<Self::State>; type Options = (); fn run(ctx: &RuleContext<Self>) -> Self::Signals { let node = ctx.query(); let model = ctx.model(); let tabindex_attribute = node.find_tabindex_attribute(model)?; match tabindex_attribute { TabindexProp::JsxAttribute(jsx_attribute) => { let jsx_any_attribute_value = jsx_attribute.initializer()?.value().ok()?; if !attribute_has_valid_tabindex(&jsx_any_attribute_value)? { return Some(jsx_any_attribute_value.syntax().text_trimmed_range()); } } TabindexProp::JsPropertyObjectMember(js_object_member) => { let expression = js_object_member.value().ok()?; let expression_syntax_node = expression.syntax(); let expression_value = AnyNumberLikeExpression::cast_ref(expression_syntax_node)?.value()?; if !is_tabindex_valid(&expression_value) { return Some(expression_syntax_node.text_trimmed_range()); } } } None } fn diagnostic(_ctx: &RuleContext<Self>, state: &Self::State) -> Option<RuleDiagnostic> { let diagnostic = RuleDiagnostic::new( rule_category!(), state, markup!{"Avoid positive values for the "<Emphasis>"tabIndex"</Emphasis>" prop."}.to_owned(), ) .note( markup!{ "Elements with a positive "<Emphasis>"tabIndex"</Emphasis>" override natural page content order. This causes elements without a positive tab index to come last when navigating using a keyboard." }.to_owned(), ); Some(diagnostic) } } /// Verify that a JSX attribute value has a valid tab index, meaning it is not positive. fn attribute_has_valid_tabindex(jsx_any_attribute_value: &AnyJsxAttributeValue) -> Option<bool> { match jsx_any_attribute_value { AnyJsxAttributeValue::JsxString(jsx_string) => { let value = jsx_string.inner_string_text().ok()?.to_string(); Some(is_tabindex_valid(&value)) } AnyJsxAttributeValue::JsxExpressionAttributeValue(value) => { let expression = value.expression().ok()?; let expression_value = AnyNumberLikeExpression::cast_ref(expression.syntax())?.value()?; Some(is_tabindex_valid(&expression_value)) } _ => None, } } /// Verify if number string is an integer less than equal zero. Non-integer numbers /// are considered valid. fn is_tabindex_valid(number_like_string: &str) -> bool { let number_string_result = number_like_string.trim().parse::<i32>(); match number_string_result { Ok(number) => number <= 0, Err(_) => true, } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/semantic_analyzers/a11y/use_button_type.rs
crates/rome_js_analyze/src/semantic_analyzers/a11y/use_button_type.rs
use crate::react::{ReactApiCall, ReactCreateElementCall}; use crate::semantic_services::Semantic; use rome_analyze::{context::RuleContext, declare_rule, Rule, RuleDiagnostic}; use rome_console::markup; use rome_js_syntax::{ AnyJsxElementName, JsCallExpression, JsxAttribute, JsxOpeningElement, JsxSelfClosingElement, TextRange, }; use rome_rowan::{declare_node_union, AstNode}; declare_rule! { /// Enforces the usage of the attribute `type` for the element `button` /// /// ## Examples /// /// ### Invalid /// /// ```jsx,expect_diagnostic /// <button>Do something</button> /// ``` /// /// ```jsx,expect_diagnostic /// <button type="incorrectType">Do something</button> /// ``` /// /// ```js,expect_diagnostic /// React.createElement('button'); /// ``` /// /// ## Valid /// /// ```jsx /// <> /// <button type="button">Do something</button> /// <button type={buttonType}>Do something</button> /// </> /// ``` pub(crate) UseButtonType { version: "0.10.0", name: "useButtonType", recommended: true, } } const ALLOWED_BUTTON_TYPES: [&str; 3] = ["submit", "button", "reset"]; declare_node_union! { pub(crate) UseButtonTypeQuery = JsxSelfClosingElement | JsxOpeningElement | JsCallExpression } pub(crate) struct UseButtonTypeState { range: TextRange, missing_prop: bool, } impl Rule for UseButtonType { type Query = Semantic<UseButtonTypeQuery>; type State = UseButtonTypeState; type Signals = Option<Self::State>; type Options = (); fn run(ctx: &RuleContext<Self>) -> Self::Signals { let node = ctx.query(); match node { UseButtonTypeQuery::JsxSelfClosingElement(element) => { let name = element.name().ok()?; if !is_button(&name)? { return None; } let type_attribute = element.find_attribute_by_name("type").ok()?; let Some(attribute) = type_attribute else { return Some(UseButtonTypeState { range: element.range(), missing_prop: true, }); }; inspect_jsx_type_attribute(attribute) } UseButtonTypeQuery::JsxOpeningElement(element) => { let name = element.name().ok()?; if !is_button(&name)? { return None; } let type_attribute = element.find_attribute_by_name("type").ok()?; let Some(attribute) = type_attribute else { return Some(UseButtonTypeState { range: element.range(), missing_prop: true, }); }; inspect_jsx_type_attribute(attribute) } UseButtonTypeQuery::JsCallExpression(call_expression) => { let model = ctx.model(); let react_create_element = ReactCreateElementCall::from_call_expression(call_expression, model)?; // first argument needs to be a string let first_argument = react_create_element .element_type .as_any_js_expression()? .as_any_js_literal_expression()? .as_js_string_literal_expression()?; if first_argument.inner_string_text().ok()?.text() == "button" { return if let Some(props) = react_create_element.props.as_ref() { let type_member = react_create_element.find_prop_by_name("type"); if let Some(member) = type_member { let property_value = member.value().ok()?; let Some(value) = property_value .as_any_js_literal_expression()? .as_js_string_literal_expression() else { return Some(UseButtonTypeState { range: property_value.range(), missing_prop: false, }); }; if !ALLOWED_BUTTON_TYPES.contains(&&*value.inner_string_text().ok()?) { return Some(UseButtonTypeState { range: value.range(), missing_prop: false, }); } } // if we are here, it means that we haven't found the property "type" and // we have to return a diagnostic Some(UseButtonTypeState { range: props.range(), missing_prop: false, }) } else { Some(UseButtonTypeState { range: first_argument.range(), missing_prop: true, }) }; } None } } } fn diagnostic(_ctx: &RuleContext<Self>, state: &Self::State) -> Option<RuleDiagnostic> { let message = if state.missing_prop { (markup! { "Provide an explicit "<Emphasis>"type"</Emphasis>" prop for the "<Emphasis>"button"</Emphasis>" element." }).to_owned() } else { (markup!{ "Provide a valid "<Emphasis>"type"</Emphasis>" prop for the "<Emphasis>"button"</Emphasis>" element." }).to_owned() }; Some(RuleDiagnostic::new(rule_category!(), state.range, message ) .note(markup! { "The default "<Emphasis>"type"</Emphasis>" of a button is "<Emphasis>"submit"</Emphasis>", which causes the submission of a form when placed inside a `form` element. " "This is likely not the behaviour that you want inside a React application." }) .note( markup! { "Allowed button types are: "<Emphasis>"submit"</Emphasis>", "<Emphasis>"button"</Emphasis>" or "<Emphasis>"reset"</Emphasis>"" } )) } } fn inspect_jsx_type_attribute(attribute: JsxAttribute) -> Option<UseButtonTypeState> { let Some(initializer) = attribute.initializer() else { return Some(UseButtonTypeState { range: attribute.range(), missing_prop: false, }); }; let value = initializer.value().ok()?; let Some(value) = value.as_jsx_string() else { // computed value return None; }; if ALLOWED_BUTTON_TYPES.contains(&&*value.inner_string_text().ok()?) { return None; } Some(UseButtonTypeState { range: value.range(), missing_prop: false, }) } /// Checks whether the current element is a button /// /// Case sensitive is important, `<button>` is different from `<Button>` fn is_button(name: &AnyJsxElementName) -> Option<bool> { // case sensitive is important, <button> is different from <Button> Some(match name { AnyJsxElementName::JsxName(name) => { let name = name.value_token().ok()?; name.text_trimmed() == "button" } _ => false, }) }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/semantic_analyzers/suspicious/no_array_index_key.rs
crates/rome_js_analyze/src/semantic_analyzers/suspicious/no_array_index_key.rs
use crate::react::{is_react_call_api, ReactLibrary}; use crate::semantic_services::Semantic; use rome_analyze::context::RuleContext; use rome_analyze::{declare_rule, Rule, RuleDiagnostic}; use rome_console::markup; use rome_js_syntax::{ AnyJsFunction, AnyJsMemberExpression, JsCallArgumentList, JsCallArguments, JsCallExpression, JsFormalParameter, JsIdentifierBinding, JsObjectExpression, JsObjectMemberList, JsParameterList, JsParameters, JsPropertyObjectMember, JsReferenceIdentifier, JsxAttribute, }; use rome_rowan::{declare_node_union, AstNode}; declare_rule! { /// Discourage the usage of Array index in keys. /// /// > We don’t recommend using indexes for keys if the order of items may change. /// This can negatively impact performance and may cause issues with component state. /// Check out Robin Pokorny’s article for an /// [in-depth explanation on the negative impacts of using an index as a key](https://robinpokorny.com/blog/index-as-a-key-is-an-anti-pattern/). /// If you choose not to assign an explicit key to list items then React will default to using indexes as keys. /// /// Source [React documentation](https://reactjs.org/docs/lists-and-keys.html#keys) /// /// ## Examples /// /// ### Invalid /// /// ```jsx,expect_diagnostic /// something.forEach((Element, index) => { /// <Component key={index} >foo</Component> /// }); /// ``` /// /// ```jsx,expect_diagnostic /// React.Children.map(this.props.children, (child, index) => ( /// React.cloneElement(child, { key: index }) /// )) /// ``` pub(crate) NoArrayIndexKey { version: "0.10.0", name: "noArrayIndexKey", recommended: true, } } declare_node_union! { pub(crate) NoArrayIndexKeyQuery = JsxAttribute | JsPropertyObjectMember } impl NoArrayIndexKeyQuery { const fn is_property_object_member(&self) -> bool { matches!(self, NoArrayIndexKeyQuery::JsPropertyObjectMember(_)) } fn is_key_property(&self) -> Option<bool> { Some(match self { NoArrayIndexKeyQuery::JsxAttribute(attribute) => { let attribute_name = attribute.name().ok()?; let name = attribute_name.as_jsx_name()?; let name_token = name.value_token().ok()?; name_token.text_trimmed() == "key" } NoArrayIndexKeyQuery::JsPropertyObjectMember(object_member) => { let object_member_name = object_member.name().ok()?; let name = object_member_name.as_js_literal_member_name()?; let name = name.value().ok()?; name.text_trimmed() == "key" } }) } /// Extracts the reference from the possible invalid prop fn as_js_reference_identifier(&self) -> Option<JsReferenceIdentifier> { match self { NoArrayIndexKeyQuery::JsxAttribute(attribute) => attribute .initializer()? .value() .ok()? .as_jsx_expression_attribute_value()? .expression() .ok()? .as_js_identifier_expression()? .name() .ok(), NoArrayIndexKeyQuery::JsPropertyObjectMember(object_member) => object_member .value() .ok()? .as_js_identifier_expression()? .name() .ok(), } } } pub(crate) struct NoArrayIndexKeyState { /// The incorrect prop incorrect_prop: JsReferenceIdentifier, /// Where the incorrect prop was defined binding_origin: JsIdentifierBinding, } impl Rule for NoArrayIndexKey { type Query = Semantic<NoArrayIndexKeyQuery>; type State = NoArrayIndexKeyState; type Signals = Option<Self::State>; type Options = (); fn run(ctx: &RuleContext<Self>) -> Self::Signals { let node = ctx.query(); if !node.is_key_property()? { return None; } let model = ctx.model(); let reference = node.as_js_reference_identifier()?; // Given the reference identifier retrieved from the key property, // find the declaration and ensure it resolves to the parameter of a function, // and navigate up to the closest call expression let parameter = model .binding(&reference) .and_then(|declaration| declaration.syntax().parent()) .and_then(JsFormalParameter::cast)?; let function = parameter .parent::<JsParameterList>() .and_then(|list| list.parent::<JsParameters>()) .and_then(|parameters| parameters.parent::<AnyJsFunction>())?; let call_expression = function .parent::<JsCallArgumentList>() .and_then(|arguments| arguments.parent::<JsCallArguments>()) .and_then(|arguments| arguments.parent::<JsCallExpression>())?; // Check if the caller is an array method and the parameter is the array index of that method let is_array_method_index = is_array_method_index(&parameter, &call_expression)?; if !is_array_method_index { return None; } if node.is_property_object_member() { let object_expression = node .parent::<JsObjectMemberList>() .and_then(|list| list.parent::<JsObjectExpression>())?; // Check if the object expression is passed to a `React.cloneElement` call let call_expression = object_expression .parent::<JsCallArgumentList>() .and_then(|list| list.parent::<JsCallArguments>()) .and_then(|arguments| arguments.parent::<JsCallExpression>())?; let callee = call_expression.callee().ok()?; if is_react_call_api(callee, model, ReactLibrary::React, "cloneElement") { let binding = parameter.binding().ok()?; let binding_origin = binding.as_any_js_binding()?.as_js_identifier_binding()?; Some(NoArrayIndexKeyState { binding_origin: binding_origin.clone(), incorrect_prop: reference, }) } else { None } } else { let binding = parameter.binding().ok()?; let binding_origin = binding.as_any_js_binding()?.as_js_identifier_binding()?; Some(NoArrayIndexKeyState { binding_origin: binding_origin.clone(), incorrect_prop: reference, }) } } fn diagnostic(_ctx: &RuleContext<Self>, state: &Self::State) -> Option<RuleDiagnostic> { let NoArrayIndexKeyState { binding_origin: incorrect_key, incorrect_prop, } = state; let diagnostic = RuleDiagnostic::new( rule_category!(), incorrect_prop.syntax().text_trimmed_range(), markup! {"Avoid using the index of an array as key property in an element."}, ) .detail( incorrect_key.syntax().text_trimmed_range(), markup! {"This is the source of the key value."}, ).note( markup! {"The order of the items may change, and this also affects performances and component state."} ).note( markup! { "Check the "<Hyperlink href="https://reactjs.org/docs/lists-and-keys.html#keys">"React documentation"</Hyperlink>". " } ); Some(diagnostic) } } /// Given a parameter and a call expression, it navigates the `callee` of the call /// and check if the method called by this function belongs to an array method /// and if the parameter is an array index /// /// ```js /// Array.map((_, index) => { /// return <Component key={index} /> /// }) /// ``` /// /// Given this example, the input node is the `index` and `Array.map(...)` call and we navigate to /// retrieve the name `map` and we check if it belongs to an `Array.prototype` method. fn is_array_method_index( parameter: &JsFormalParameter, call_expression: &JsCallExpression, ) -> Option<bool> { let member_expression = AnyJsMemberExpression::cast_ref(call_expression.callee().ok()?.syntax())?; let name = member_expression.member_name()?; let name = name.text(); if matches!( name, "map" | "flatMap" | "from" | "forEach" | "filter" | "some" | "every" | "find" | "findIndex" ) { Some(parameter.syntax().index() == 2) } else if matches!(name, "reduce" | "reduceRight") { Some(parameter.syntax().index() == 4) } else { None } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/semantic_analyzers/suspicious/no_label_var.rs
crates/rome_js_analyze/src/semantic_analyzers/suspicious/no_label_var.rs
use crate::{semantic_services::Semantic, JsRuleAction}; use rome_analyze::{context::RuleContext, declare_rule, Rule, RuleDiagnostic}; use rome_console::markup; use rome_js_syntax::{JsLabeledStatement, JsSyntaxNode, JsSyntaxToken}; use rome_rowan::AstNode; declare_rule! { /// Disallow labels that share a name with a variable /// /// ## Examples /// /// ### Invalid /// /// ```js,expect_diagnostic /// const x1 = "test"; /// x1: expr; /// ``` /// /// ### Valid /// /// ```js /// const x = "test"; /// z: expr; /// ``` pub(crate) NoLabelVar { version: "0.7.0", name: "noLabelVar", recommended: true, } } impl Rule for NoLabelVar { type Query = Semantic<JsLabeledStatement>; /// The first element of the tuple is the name of the binding, the second element of the tuple is the label name type State = (JsSyntaxNode, JsSyntaxToken); type Signals = Option<Self::State>; type Options = (); fn run(ctx: &RuleContext<Self>) -> Option<Self::State> { let label_statement = ctx.query(); let label_token = label_statement.label_token().ok()?; let name = label_token.text_trimmed(); let model = ctx.model(); // We search each scope from current scope until the global scope // if we find a binding that has its name equal to label name, then we found a `LabelVar` issue. for scope in model.scope(label_statement.syntax()).ancestors() { if let Some(binding) = scope.get_binding(name) { return Some((binding.syntax().clone(), label_token)); } } None } fn diagnostic(_: &RuleContext<Self>, state: &Self::State) -> Option<RuleDiagnostic> { let (binding_syntax_node, label_token) = state; let name = label_token.text_trimmed(); Some(RuleDiagnostic::new(rule_category!(), label_token.text_trimmed_range(), markup! { "Do not use the "<Emphasis>{name}</Emphasis>" variable name as a label" }, ) .detail(binding_syntax_node.text_trimmed_range(), markup! { "The variable is declared here" },) .note(markup! {"Creating a label with the same name as an in-scope variable leads to confusion."})) } fn action(_: &RuleContext<Self>, _: &Self::State) -> Option<JsRuleAction> { None } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/semantic_analyzers/suspicious/no_catch_assign.rs
crates/rome_js_analyze/src/semantic_analyzers/suspicious/no_catch_assign.rs
use crate::semantic_services::Semantic; use rome_analyze::{context::RuleContext, declare_rule, Rule, RuleDiagnostic}; use rome_console::markup; use rome_js_semantic::ReferencesExtensions; use rome_js_syntax::{JsCatchClause, JsSyntaxNode}; use rome_rowan::AstNode; declare_rule! { /// Disallow reassigning exceptions in catch clauses. /// /// Assignment to a `catch` parameter can be misleading and confusing. /// It is often unintended and indicative of a programmer error. /// /// Source: https://eslint.org/docs/latest/rules/no-ex-assign /// /// ## Examples /// /// ### Invalid /// /// ```js,expect_diagnostic /// try { /// /// } catch (e) { /// e; /// e = 10; /// } /// ``` /// /// ### Valid /// /// ```js /// try { /// /// } catch (e) { /// let e = 10; /// e = 100; /// } /// ``` pub(crate) NoCatchAssign { version: "0.7.0", name: "noCatchAssign", recommended: true, } } impl Rule for NoCatchAssign { // Why use [JsCatchClause] instead of [JsIdentifierAssignment] ? // Because this could reduce search range. // We only compare the declaration of [JsCatchClause] with all descent // [JsIdentifierAssignment] of its body. type Query = Semantic<JsCatchClause>; // The first element of `State` is the reassignment of catch parameter, // the second element of `State` is the declaration of catch clause. type State = (JsSyntaxNode, JsSyntaxNode); type Signals = Vec<Self::State>; type Options = (); fn run(ctx: &RuleContext<Self>) -> Vec<Self::State> { let catch_clause = ctx.query(); let model = ctx.model(); catch_clause .declaration() .and_then(|decl| { let catch_binding = decl.binding().ok()?; // Only [JsIdentifierBinding] is allowed to use `model.all_references` now, // so there's need to make sure this is a [JsIdentifierBinding]. let identifier_binding = catch_binding .as_any_js_binding()? .as_js_identifier_binding()?; let catch_binding_syntax = catch_binding.syntax(); let mut invalid_assignment = vec![]; for reference in identifier_binding.all_writes(model) { invalid_assignment .push((reference.syntax().clone(), catch_binding_syntax.clone())); } Some(invalid_assignment) }) .unwrap_or_default() } fn diagnostic(_ctx: &RuleContext<Self>, state: &Self::State) -> Option<RuleDiagnostic> { let (assignment, catch_binding_syntax) = state; Some( RuleDiagnostic::new( rule_category!(), assignment.text_trimmed_range(), markup! { "Reassigning a "<Emphasis>"catch parameter"</Emphasis>" is confusing." }, ) .detail( catch_binding_syntax.text_trimmed_range(), markup! { "The "<Emphasis>"catch parameter"</Emphasis>" is declared here:" }, ) .note("Use a local variable instead."), ) } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/semantic_analyzers/suspicious/no_class_assign.rs
crates/rome_js_analyze/src/semantic_analyzers/suspicious/no_class_assign.rs
use rome_analyze::context::RuleContext; use rome_analyze::{declare_rule, Rule, RuleDiagnostic}; use rome_console::markup; use rome_js_semantic::{Reference, ReferencesExtensions}; use rome_js_syntax::AnyJsClass; use crate::semantic_services::Semantic; declare_rule! { /// Disallow reassigning class members. /// /// A class declaration creates a variable that we can modify, however, the modification is a mistake in most cases. /// /// ## Examples /// /// ### Invalid /// /// ```js,expect_diagnostic /// class A {} /// A = 0; /// ``` /// /// ```js,expect_diagnostic /// A = 0; /// class A {} /// ``` /// /// ```js,expect_diagnostic /// class A { /// b() { /// A = 0; /// } /// } /// ``` /// /// ```js,expect_diagnostic /// let A = class A { /// b() { /// A = 0; /// // `let A` is shadowed by the class name. /// } /// } /// ``` /// /// ### Valid /// /// ```js /// let A = class A {} /// A = 0; // A is a variable. /// ``` /// /// ```js /// let A = class { /// b() { /// A = 0; // A is a variable. /// } /// } /// ``` /// /// ```js /// class A { /// b(A) { /// A = 0; // A is a parameter. /// } /// } /// ``` /// pub(crate) NoClassAssign { version: "12.0.0", name: "noClassAssign", recommended: true, } } impl Rule for NoClassAssign { type Query = Semantic<AnyJsClass>; type State = Reference; type Signals = Vec<Self::State>; type Options = (); fn run(ctx: &RuleContext<Self>) -> Self::Signals { let node = ctx.query(); let model = ctx.model(); if let Ok(Some(id)) = node.id() { if let Some(id_binding) = id.as_js_identifier_binding() { return id_binding.all_writes(model).collect(); } } Vec::new() } fn diagnostic(ctx: &RuleContext<Self>, reference: &Self::State) -> Option<RuleDiagnostic> { let binding = ctx .query() .id() .ok()?? .as_js_identifier_binding()? .name_token() .ok()?; let class_name = binding.text_trimmed(); Some( RuleDiagnostic::new( rule_category!(), reference.syntax().text_trimmed_range(), markup! {"'"{class_name}"' is a class."}, ) .detail( binding.text_trimmed_range(), markup! {"'"{class_name}"' is defined here."}, ), ) } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/semantic_analyzers/suspicious/no_function_assign.rs
crates/rome_js_analyze/src/semantic_analyzers/suspicious/no_function_assign.rs
use crate::semantic_services::Semantic; use rome_analyze::{context::RuleContext, declare_rule, Rule, RuleDiagnostic}; use rome_console::markup; use rome_js_semantic::{Reference, ReferencesExtensions}; use rome_js_syntax::{JsFunctionDeclaration, JsIdentifierBinding}; use rome_rowan::AstNode; declare_rule! { /// Disallow reassigning function declarations. /// /// ## Examples /// /// ### Invalid /// /// ```js,expect_diagnostic /// function foo() { }; /// foo = bar; /// ``` /// /// ```js,expect_diagnostic /// function foo() { /// foo = bar; /// } /// ``` /// /// ```js,expect_diagnostic /// foo = bar; /// function foo() { }; /// ``` /// /// ```js,expect_diagnostic /// [foo] = bar; /// function foo() { }; /// ``` /// /// ```js,expect_diagnostic /// ({ x: foo = 0 } = bar); /// function foo() { }; /// ``` /// /// ```js,expect_diagnostic /// function foo() { /// [foo] = bar; /// } /// ``` /// ```js,expect_diagnostic /// (function () { /// ({ x: foo = 0 } = bar); /// function foo() { }; /// })(); /// ``` /// /// ## Valid /// /// ```js /// function foo() { /// var foo = bar; /// } /// ``` /// /// ```js /// function foo(foo) { /// foo = bar; /// } /// ``` /// /// ```js /// function foo() { /// var foo; /// foo = bar; /// } /// ``` /// /// ```js /// var foo = () => {}; /// foo = bar; /// ``` /// /// ```js /// var foo = function() {}; /// foo = bar; /// ``` /// /// ```js /// var foo = function() { /// foo = bar; /// }; /// ``` /// /// ```js /// import bar from 'bar'; /// function foo() { /// var foo = bar; /// } /// ``` pub(crate) NoFunctionAssign { version: "0.7.0", name: "noFunctionAssign", recommended: true, } } pub struct State { id: JsIdentifierBinding, all_writes: Vec<Reference>, } impl Rule for NoFunctionAssign { type Query = Semantic<JsFunctionDeclaration>; type State = State; type Signals = Option<Self::State>; type Options = (); fn run(ctx: &RuleContext<Self>) -> Option<Self::State> { let declaration = ctx.query(); let model = ctx.model(); let id = declaration.id().ok()?; let id = id.as_js_identifier_binding()?; let all_writes: Vec<Reference> = id.all_writes(model).collect(); if all_writes.is_empty() { None } else { Some(State { id: id.clone(), all_writes, }) } } fn diagnostic(_: &RuleContext<Self>, state: &Self::State) -> Option<RuleDiagnostic> { let mut diag = RuleDiagnostic::new( rule_category!(), state.id.syntax().text_trimmed_range(), markup! { "Do not reassign a function declaration." }, ); let mut hoisted_quantity = 0; for reference in state.all_writes.iter() { let node = reference.syntax(); diag = diag.detail(node.text_trimmed_range(), "Reassigned here."); hoisted_quantity += i32::from(reference.is_using_hoisted_declaration()); } let diag = if hoisted_quantity > 0 { diag.note( markup! {"Reassignment happens here because the function declaration is hoisted."}, ) } else { diag }; let diag = diag.note(markup! {"Use a local variable instead."}); Some(diag) } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/semantic_analyzers/suspicious/no_duplicate_parameters.rs
crates/rome_js_analyze/src/semantic_analyzers/suspicious/no_duplicate_parameters.rs
use rome_analyze::{context::RuleContext, declare_rule, Ast, Rule, RuleDiagnostic}; use rome_console::markup; use rome_js_syntax::parameter_ext::{AnyJsParameterList, AnyJsParameters, AnyParameter}; use rome_js_syntax::{ AnyJsArrayBindingPatternElement, AnyJsBinding, AnyJsBindingPattern, AnyJsObjectBindingPatternMember, JsIdentifierBinding, }; use rome_rowan::AstNode; use rustc_hash::FxHashSet; declare_rule! { /// Disallow duplicate function parameter name. /// /// If more than one parameter has the same name in a function definition, /// the last occurrence overrides the preceding occurrences. /// A duplicated name might be a typing error. /// /// Source: https://eslint.org/docs/latest/rules/no-dupe-args /// /// ## Examples /// /// ### Invalid /// /// ```js,expect_diagnostic /// var f = function(a, b, b) {} /// ``` /// /// ```js,expect_diagnostic /// function b(a, b, b) {} /// ``` /// /// ### Valid /// /// ```js /// function i(i, b, c) {} /// var j = function (j, b, c) {}; /// function k({ k, b }, { c, d }) {} /// function l([, l]) {} /// function foo([[a, b], [c, d]]) {} /// ``` pub(crate) NoDuplicateParameters { version: "0.9.0", name: "noDuplicateParameters", recommended: true, } } impl Rule for NoDuplicateParameters { type Query = Ast<AnyJsParameters>; type State = JsIdentifierBinding; type Signals = Option<Self::State>; type Options = (); fn run(ctx: &RuleContext<Self>) -> Option<Self::State> { let parameters = ctx.query(); let list = match parameters { AnyJsParameters::JsParameters(parameters) => { AnyJsParameterList::from(parameters.items()) } AnyJsParameters::JsConstructorParameters(parameters) => { AnyJsParameterList::from(parameters.parameters()) } }; let mut set = FxHashSet::default(); // Traversing the parameters of the function in preorder and checking for duplicates, list.iter().find_map(|parameter| { let parameter = parameter.ok()?; traverse_parameter(parameter, &mut set) }) } fn diagnostic(_: &RuleContext<Self>, state: &Self::State) -> Option<RuleDiagnostic> { let binding_syntax_node = state; Some( RuleDiagnostic::new( rule_category!(), binding_syntax_node.syntax().text_trimmed_range(), markup! { "Duplicate parameter name." }, ) .note("The parameter overrides a preceding parameter by using the same name."), ) } } /// Traverse the parameter recursively and check if it is duplicated. /// Return `Some(JsIdentifierBinding)` if it is duplicated. fn traverse_parameter( parameter: AnyParameter, tracked_bindings: &mut FxHashSet<String>, ) -> Option<JsIdentifierBinding> { parameter .binding() .and_then(|binding| traverse_binding(binding, tracked_bindings)) } /// Traverse a [JsAnyBindingPattern] in preorder and check if the name of [JsIdentifierBinding] has seem before. /// If true then add the [JsIdentifierBinding] to the [duplicated_arguments]. /// If false then add the [JsIdentifierBinding] to the [tracked_bindings], mark it name as seen. /// If it is not a [JsIdentifierBinding] then recursively call [traverse_binding] on its children. fn traverse_binding( binding: AnyJsBindingPattern, tracked_bindings: &mut FxHashSet<String>, ) -> Option<JsIdentifierBinding> { match binding { AnyJsBindingPattern::AnyJsBinding(inner_binding) => match inner_binding { AnyJsBinding::JsIdentifierBinding(id_binding) => { if track_binding(&id_binding, tracked_bindings) { return Some(id_binding); } } AnyJsBinding::JsBogusBinding(_) => {} }, AnyJsBindingPattern::JsArrayBindingPattern(inner_binding) => { return inner_binding.elements().into_iter().find_map(|element| { let element = element.ok()?; match element { AnyJsArrayBindingPatternElement::AnyJsBindingPattern(pattern) => { traverse_binding(pattern, tracked_bindings) } AnyJsArrayBindingPatternElement::JsArrayBindingPatternRestElement( binding_rest, ) => { let binding_pattern = binding_rest.pattern().ok()?; traverse_binding(binding_pattern, tracked_bindings) } AnyJsArrayBindingPatternElement::JsArrayHole(_) => None, AnyJsArrayBindingPatternElement::JsBindingPatternWithDefault( binding_with_default, ) => { let pattern = binding_with_default.pattern().ok()?; traverse_binding(pattern, tracked_bindings) } } }) } AnyJsBindingPattern::JsObjectBindingPattern(pattern) => { return pattern.properties().into_iter().find_map(|prop| { let prop = prop.ok()?; match prop { AnyJsObjectBindingPatternMember::JsObjectBindingPatternProperty(pattern) => { let pattern = pattern.pattern().ok()?; traverse_binding(pattern, tracked_bindings) } AnyJsObjectBindingPatternMember::JsObjectBindingPatternRest(rest) => { let pattern = rest.binding().ok()?; match pattern { AnyJsBinding::JsIdentifierBinding(binding) => { track_binding(&binding, tracked_bindings).then_some(binding) } AnyJsBinding::JsBogusBinding(_) => None, } } AnyJsObjectBindingPatternMember::JsObjectBindingPatternShorthandProperty( shorthand_binding, ) => match shorthand_binding.identifier().ok()? { AnyJsBinding::JsIdentifierBinding(id_binding) => { track_binding(&id_binding, tracked_bindings).then_some(id_binding) } AnyJsBinding::JsBogusBinding(_) => None, }, AnyJsObjectBindingPatternMember::JsBogusBinding(_) => None, } }) } } None } #[inline] /// If the name of binding has been seen in set, then we push the `JsIdentifierBinding` into `identifier_vec`. /// Else we mark the name of binding as seen. fn track_binding( id_binding: &JsIdentifierBinding, tracked_bindings: &mut FxHashSet<String>, ) -> bool { let binding_text = id_binding.text(); if tracked_bindings.contains(&binding_text) { true } else { tracked_bindings.insert(binding_text); false } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/semantic_analyzers/suspicious/no_redeclare.rs
crates/rome_js_analyze/src/semantic_analyzers/suspicious/no_redeclare.rs
use crate::semantic_services::SemanticServices; use rome_analyze::declare_rule; use rome_analyze::{context::RuleContext, Rule, RuleDiagnostic}; use rome_console::markup; use rome_js_semantic::Scope; use rome_js_syntax::binding_ext::AnyJsBindingDeclaration; use rome_js_syntax::{ AnyTsType, TextRange, TsIndexSignatureParameter, TsIndexSignatureTypeMember, TsTypeMemberList, }; use rome_rowan::AstNode; use std::collections::HashMap; declare_rule! { /// Disallow variable, function, class, and type redeclarations in the same scope. /// /// Source: https://typescript-eslint.io/rules/no-redeclare /// /// ## Examples /// /// ### Invalid /// /// ```js,expect_diagnostic /// var a = 3; /// var a = 10; /// ``` /// /// ```js,expect_diagnostic /// let a = 3; /// let a = 10; /// ``` /// /// ```js,expect_diagnostic /// function f() {} /// function f() {} /// ``` /// /// ```js,expect_diagnostic /// class C { /// static { /// var c = 3; /// var c = 10; /// } /// } /// ``` /// /// ```ts,expect_diagnostic /// type Person = { name: string; } /// class Person { name: string; } /// ``` /// /// ### Valid /// /// ```js /// var a = 3; /// a = 10; /// ``` /// /// ```ts /// class Foo { /// bar(a: A); /// bar(a: A, b: B); /// bar(a: A, b: B) {} /// } /// ``` pub(crate) NoRedeclare { version: "12.0.0", name: "noRedeclare", recommended: true, } } #[derive(Debug)] pub(crate) struct Redeclaration { name: String, declaration: TextRange, redeclaration: TextRange, } impl Rule for NoRedeclare { type Query = SemanticServices; type State = Redeclaration; type Signals = Vec<Redeclaration>; type Options = (); fn run(ctx: &RuleContext<Self>) -> Self::Signals { let mut redeclarations = Vec::default(); for scope in ctx.query().scopes() { check_redeclarations_in_single_scope(&scope, &mut redeclarations); } redeclarations } fn diagnostic(_ctx: &RuleContext<Self>, state: &Self::State) -> Option<RuleDiagnostic> { let Redeclaration { name, declaration, redeclaration, } = state; let diag = RuleDiagnostic::new( rule_category!(), redeclaration, markup! { "Shouldn't redeclare '"{ name }"'. Consider to delete it or rename it." }, ) .detail( declaration, markup! { "'"{ name }"' is defined here:" }, ); Some(diag) } } fn check_redeclarations_in_single_scope(scope: &Scope, redeclarations: &mut Vec<Redeclaration>) { let mut declarations = HashMap::<String, (TextRange, AnyJsBindingDeclaration)>::default(); for binding in scope.bindings() { let id_binding = binding.tree(); // We consider only binding of a declaration // This allows to skip function parameters, methods, ... if let Some(decl) = id_binding.declaration() { let name = id_binding.text(); if let Some((first_text_range, first_decl)) = declarations.get(&name) { // Do not report: // - mergeable declarations. // e.g. a `function` and a `namespace` // - when both are parameter-like. // A parameter can override a previous parameter. // - when index signature parameters have the different type annotation or are not in the same type member if !(first_decl.is_mergeable(&decl) || first_decl.is_parameter_like() && decl.is_parameter_like()) { match (first_decl, &decl) { ( AnyJsBindingDeclaration::TsIndexSignatureParameter(first), AnyJsBindingDeclaration::TsIndexSignatureParameter(second), ) => { if are_index_signature_params_same_type_and_member(first, second) { redeclarations.push(Redeclaration { name, declaration: *first_text_range, redeclaration: id_binding.syntax().text_trimmed_range(), }) } } _ => redeclarations.push(Redeclaration { name, declaration: *first_text_range, redeclaration: id_binding.syntax().text_trimmed_range(), }), } } } else { declarations.insert(name, (id_binding.syntax().text_trimmed_range(), decl)); } } } } /// Checks if the both `TsIndexSignatureParameter` have the same type annotation and are in the same type member fn are_index_signature_params_same_type_and_member( first: &TsIndexSignatureParameter, second: &TsIndexSignatureParameter, ) -> bool { let are_same_index_signature_type_annotations = are_same_index_signature_type_annotations(first, second); let (Some(first), Some(second)) = (first.parent::<TsIndexSignatureTypeMember>(), second.parent::<TsIndexSignatureTypeMember>()) else { return false }; are_same_index_signature_type_annotations.unwrap_or(false) && are_same_type_members(&first, &second).unwrap_or(false) } /// Checks if the both `TsIndexSignatureParameter` have the same type annotation fn are_same_index_signature_type_annotations( first: &TsIndexSignatureParameter, second: &TsIndexSignatureParameter, ) -> Option<bool> { let first_ts_type = first.type_annotation().ok()?.ty().ok()?; let second_ts_type = second.type_annotation().ok()?.ty().ok()?; match (first_ts_type, second_ts_type) { (AnyTsType::TsStringType(_), AnyTsType::TsStringType(_)) => Some(true), (AnyTsType::TsNumberType(_), AnyTsType::TsNumberType(_)) => Some(true), (AnyTsType::TsSymbolType(_), AnyTsType::TsSymbolType(_)) => Some(true), _ => None, } } fn are_same_type_members( first: &TsIndexSignatureTypeMember, second: &TsIndexSignatureTypeMember, ) -> Option<bool> { let first_parent = first.parent::<TsTypeMemberList>()?; let second_parent = second.parent::<TsTypeMemberList>()?; Some(first_parent == second_parent) }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/semantic_analyzers/suspicious/no_import_assign.rs
crates/rome_js_analyze/src/semantic_analyzers/suspicious/no_import_assign.rs
use crate::semantic_services::Semantic; use rome_analyze::{context::RuleContext, declare_rule, Rule, RuleDiagnostic}; use rome_console::markup; use rome_js_semantic::ReferencesExtensions; use rome_js_syntax::{ JsDefaultImportSpecifier, JsIdentifierAssignment, JsIdentifierBinding, JsImportDefaultClause, JsImportNamespaceClause, JsNamedImportSpecifier, JsNamespaceImportSpecifier, JsShorthandNamedImportSpecifier, }; use rome_rowan::{declare_node_union, AstNode}; declare_rule! { /// Disallow assigning to imported bindings /// /// ## Examples /// /// ### Invalid /// /// ```js,expect_diagnostic /// import x from "y"; /// x = 1; /// ``` /// ```js,expect_diagnostic /// import y from "y"; /// [y] = 1; /// ``` /// ```js,expect_diagnostic /// import z from "y"; /// ({ z } = 1); /// ``` /// ```js,expect_diagnostic /// import a from "y"; /// [...a] = 1; /// ``` /// ```js,expect_diagnostic /// import b from "y"; /// ({ ...b } = 1); /// ``` /// ```js,expect_diagnostic /// import c from "y"; /// for (c in y) {}; /// ``` /// /// ```js,expect_diagnostic /// import d from "y"; /// d += 1; /// ``` /// ```js,expect_diagnostic /// import * as e from "y"; /// e = 1; /// ``` pub(crate) NoImportAssign { version: "0.9.0", name: "noImportAssign", recommended: true, } } impl Rule for NoImportAssign { type Query = Semantic<AnyJsImportLike>; /// The first element of the tuple is the invalid `JsIdentifierAssignment`, the second element of the tuple is the imported `JsIdentifierBinding`. type State = (JsIdentifierAssignment, JsIdentifierBinding); type Signals = Vec<Self::State>; type Options = (); fn run(ctx: &RuleContext<Self>) -> Vec<Self::State> { let label_statement = ctx.query(); let mut invalid_assign_list = vec![]; let local_name_binding = match label_statement { // `import xx from 'y'` AnyJsImportLike::JsImportDefaultClause(clause) => clause.local_name().ok(), // `import * as xxx from 'y'` AnyJsImportLike::JsImportNamespaceClause(clause) => clause.local_name().ok(), // `import {x as xx} from 'y'` // ^^^^^^^ AnyJsImportLike::JsNamedImportSpecifier(specifier) => specifier.local_name().ok(), // `import {x} from 'y'` // ^ AnyJsImportLike::JsShorthandNamedImportSpecifier(specifier) => { specifier.local_name().ok() } // `import a, * as b from 'y'` // ^^^^^^ AnyJsImportLike::JsNamespaceImportSpecifier(specifier) => specifier.local_name().ok(), // `import a, * as b from 'y'` // ^ AnyJsImportLike::JsDefaultImportSpecifier(specifier) => specifier.local_name().ok(), }; local_name_binding .and_then(|binding| { let ident_binding = binding.as_js_identifier_binding()?; let model = ctx.model(); for reference in ident_binding.all_writes(model) { invalid_assign_list.push(( JsIdentifierAssignment::cast(reference.syntax().clone())?, ident_binding.clone(), )); } Some(invalid_assign_list) }) .unwrap_or_default() } fn diagnostic(_: &RuleContext<Self>, state: &Self::State) -> Option<RuleDiagnostic> { let (invalid_assign, import_binding) = state; let name = invalid_assign.syntax().text_trimmed(); Some( RuleDiagnostic::new( rule_category!(), invalid_assign.syntax().text_trimmed_range(), markup! { "The imported variable "<Emphasis>{name.to_string()}</Emphasis>" is read-only" }, ) .note(markup! {"Use a local variable instead of reassigning an import."}) .detail( import_binding.syntax().text_trimmed_range(), markup! { "The variable is imported here" }, ), ) } } declare_node_union! { pub(crate) AnyJsImportLike = JsImportDefaultClause | JsImportNamespaceClause | JsNamedImportSpecifier | JsShorthandNamedImportSpecifier | JsNamespaceImportSpecifier | JsDefaultImportSpecifier }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/semantic_analyzers/suspicious/no_console_log.rs
crates/rome_js_analyze/src/semantic_analyzers/suspicious/no_console_log.rs
use crate::semantic_services::Semantic; use rome_analyze::{context::RuleContext, declare_rule, Rule, RuleDiagnostic}; use rome_console::markup; use rome_js_syntax::{global_identifier, AnyJsMemberExpression, JsCallExpression}; use rome_rowan::AstNode; declare_rule! { /// Disallow the use of `console.log` /// /// ## Examples /// /// ### Invalid /// /// ```js,expect_diagnostic /// console.log() /// ``` /// /// ## Valid /// /// ```js /// console.info("info"); /// console.warn("warn"); /// console.error("error"); /// console.assert(true); /// console.table(["foo", "bar"]); /// const console = { log() {} }; /// console.log(); /// ``` /// pub(crate) NoConsoleLog { version: "12.1.0", name: "noConsoleLog", recommended: false, } } impl Rule for NoConsoleLog { type Query = Semantic<JsCallExpression>; type State = (); type Signals = Option<Self::State>; type Options = (); fn run(ctx: &RuleContext<Self>) -> Self::Signals { let call_expression = ctx.query(); let model = ctx.model(); let callee = call_expression.callee().ok()?; let member_expression = AnyJsMemberExpression::cast_ref(callee.syntax())?; if member_expression.member_name()?.text() != "log" { return None; } let object = member_expression.object().ok()?; let (reference, name) = global_identifier(&object)?; if name.text() != "console" { return None; } model.binding(&reference).is_none().then_some(()) } fn diagnostic(ctx: &RuleContext<Self>, _: &Self::State) -> Option<RuleDiagnostic> { let node = ctx.query(); Some( RuleDiagnostic::new( rule_category!(), node.syntax().text_trimmed_range(), markup! { "Don't use "<Emphasis>"console.log"</Emphasis> }, ) .note(markup! { <Emphasis>"console.log"</Emphasis>" is usually a tool for debugging and you don't want to have that in production." }), ) } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/semantic_analyzers/style/no_arguments.rs
crates/rome_js_analyze/src/semantic_analyzers/style/no_arguments.rs
use crate::semantic_services::SemanticServices; use rome_analyze::{context::RuleContext, declare_rule, Rule, RuleDiagnostic}; use rome_console::markup; use rome_js_syntax::TextRange; declare_rule! { /// Disallow the use of ```arguments``` /// /// ## Examples /// /// ### Invalid /// /// ```js,expect_diagnostic /// function f() { /// console.log(arguments); /// } /// ``` /// /// ### Valid /// /// ```cjs /// function f() { /// let arguments = 1; /// console.log(arguments); /// } /// ``` pub(crate) NoArguments { version: "0.7.0", name: "noArguments", recommended: true, } } impl Rule for NoArguments { type Query = SemanticServices; type State = TextRange; type Signals = Vec<Self::State>; type Options = (); fn run(ctx: &RuleContext<Self>) -> Self::Signals { let model = ctx.query(); let mut found_arguments = vec![]; for unresolved_reference in model.all_unresolved_references() { let name = unresolved_reference.syntax().text_trimmed(); if name == "arguments" { let range = unresolved_reference.range(); found_arguments.push(*range); } } found_arguments } fn diagnostic(_: &RuleContext<Self>, range: &Self::State) -> Option<RuleDiagnostic> { Some(RuleDiagnostic::new(rule_category!(), range, markup! { "Use the "<Emphasis>"rest parameters"</Emphasis>" instead of "<Emphasis>"arguments"</Emphasis>"." }, ).note(markup! {<Emphasis>"arguments"</Emphasis>" does not have "<Emphasis>"Array.prototype"</Emphasis>" methods and can be inconvenient to use."})) } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/semantic_analyzers/style/no_parameter_assign.rs
crates/rome_js_analyze/src/semantic_analyzers/style/no_parameter_assign.rs
use crate::semantic_services::Semantic; use rome_analyze::{context::RuleContext, declare_rule, Rule, RuleDiagnostic}; use rome_console::markup; use rome_js_semantic::{AllBindingWriteReferencesIter, Reference, ReferencesExtensions}; use rome_js_syntax::{AnyJsBinding, AnyJsBindingPattern, AnyJsFormalParameter, AnyJsParameter}; use rome_rowan::AstNode; declare_rule! { /// Disallow reassigning `function` parameters. /// /// Assignment to a `function` parameters can be misleading and confusing, /// as modifying parameters will also mutate the `arguments` object. /// It is often unintended and indicative of a programmer error. /// /// Source: https://eslint.org/docs/latest/rules/no-param-reassign /// /// In contrast to the _ESLint_ rule, this rule cannot be configured to report /// assignments to a property of a parameter. /// /// ## Examples /// /// ### Invalid /// /// ```js,expect_diagnostic /// function f(param) { /// param = 13; /// } /// ``` /// /// ```js,expect_diagnostic /// function f(param) { /// param++; /// } /// ``` /// /// ```js,expect_diagnostic /// function f(param) { /// for (param of arr) {} /// } /// ``` /// /// ```ts,expect_diagnostic /// class C { /// constructor(readonly prop: number) { /// prop++ /// } /// } /// ``` /// /// ## Valid /// /// ```js /// function f(param) { /// let local = param; /// } /// ``` /// pub(crate) NoParameterAssign { version: "12.0.0", name: "noParameterAssign", recommended: true, } } impl Rule for NoParameterAssign { type Query = Semantic<AnyJsParameter>; type State = Reference; type Signals = AllBindingWriteReferencesIter; type Options = (); fn run(ctx: &RuleContext<Self>) -> Self::Signals { let param = ctx.query(); let model = ctx.model(); if let Some(AnyJsBindingPattern::AnyJsBinding(AnyJsBinding::JsIdentifierBinding(binding))) = binding_of(param) { return binding.all_writes(model); } // Empty iterator that conforms to `AllBindingWriteReferencesIter` type. std::iter::successors(None, |_| None) } fn diagnostic(ctx: &RuleContext<Self>, reference: &Self::State) -> Option<RuleDiagnostic> { let param = ctx.query(); Some( RuleDiagnostic::new( rule_category!(), reference.syntax().text_trimmed_range(), markup! { "Reassigning a "<Emphasis>"function parameter"</Emphasis>" is confusing." }, ) .detail( param.syntax().text_trimmed_range(), markup! { "The "<Emphasis>"parameter"</Emphasis>" is declared here:" }, ) .note(markup! { "Use a local variable instead." }), ) } } fn binding_of(param: &AnyJsParameter) -> Option<AnyJsBindingPattern> { match param { AnyJsParameter::AnyJsFormalParameter(formal_param) => match &formal_param { AnyJsFormalParameter::JsBogusParameter(_) => None, AnyJsFormalParameter::JsFormalParameter(param) => param.binding().ok(), }, AnyJsParameter::JsRestParameter(param) => param.binding().ok(), AnyJsParameter::TsThisParameter(_) => None, } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/semantic_analyzers/style/no_shouty_constants.rs
crates/rome_js_analyze/src/semantic_analyzers/style/no_shouty_constants.rs
use crate::{semantic_services::Semantic, utils::batch::JsBatchMutation, JsRuleAction}; use rome_analyze::{context::RuleContext, declare_rule, ActionCategory, Rule, RuleDiagnostic}; use rome_console::markup; use rome_diagnostics::Applicability; use rome_js_factory::make::{js_literal_member_name, js_property_object_member}; use rome_js_semantic::{Reference, ReferencesExtensions}; use rome_js_syntax::{ AnyJsExpression, AnyJsLiteralExpression, AnyJsObjectMemberName, JsIdentifierBinding, JsIdentifierExpression, JsReferenceIdentifier, JsShorthandPropertyObjectMember, JsStringLiteralExpression, JsSyntaxKind, JsVariableDeclaration, JsVariableDeclarator, JsVariableDeclaratorList, }; use rome_rowan::{AstNode, BatchMutationExt, SyntaxNodeCast, SyntaxToken}; declare_rule! { /// Disallow the use of constants which its value is the upper-case version of its name. /// /// ## Examples /// /// ### Invalid /// /// ```js,expect_diagnostic /// const FOO = "FOO"; /// console.log(FOO); /// ``` /// /// ### Valid /// /// ```js /// let FOO = "FOO"; /// console.log(FOO); /// ``` /// /// ```js /// export const FOO = "FOO"; /// console.log(FOO); /// ``` /// /// ```js /// function f(FOO = "FOO") { /// return FOO; /// } /// ``` /// pub(crate) NoShoutyConstants { version: "0.7.0", name: "noShoutyConstants", recommended: false, } } /// Check for /// a = "a" (true) /// a = "b" (false) fn is_id_and_string_literal_inner_text_equal( declarator: &JsVariableDeclarator, ) -> Option<(JsIdentifierBinding, JsStringLiteralExpression)> { let id = declarator.id().ok()?; let id = id.as_any_js_binding()?.as_js_identifier_binding()?; let name = id.name_token().ok()?; let id_text = name.text_trimmed(); let expression = declarator.initializer()?.expression().ok()?; let literal = expression .as_any_js_literal_expression()? .as_js_string_literal_expression()?; let literal_text = literal.inner_string_text().ok()?; if id_text.len() != literal_text.text().len() { return None; } for (from_id, from_literal) in id_text.chars().zip(literal_text.chars()) { if from_id != from_literal || from_id.is_lowercase() { return None; } } Some((id.clone(), literal.clone())) } pub struct State { literal: JsStringLiteralExpression, reference: Reference, } impl Rule for NoShoutyConstants { type Query = Semantic<JsVariableDeclarator>; type State = State; type Signals = Option<Self::State>; type Options = (); fn run(ctx: &RuleContext<Self>) -> Option<Self::State> { let declarator = ctx.query(); let declaration = declarator .parent::<JsVariableDeclaratorList>()? .parent::<JsVariableDeclaration>()?; if declaration.is_const() { if let Some((binding, literal)) = is_id_and_string_literal_inner_text_equal(declarator) { let model = ctx.model(); if model.is_exported(&binding) { return None; } if binding.all_references(model).count() > 1 { return None; } return Some(State { literal, reference: binding.all_references(model).next()?, }); } } None } fn diagnostic(ctx: &RuleContext<Self>, state: &Self::State) -> Option<RuleDiagnostic> { let declarator = ctx.query(); let mut diag = RuleDiagnostic::new( rule_category!(), declarator.syntax().text_trimmed_range(), markup! { "Redundant constant declaration." }, ); let node = state.reference.syntax(); diag = diag.detail(node.text_trimmed_range(), "Used here."); let diag = diag.note( markup! {"You should avoid declaring constants with a string that's the same value as the variable name. It introduces a level of unnecessary indirection when it's only two additional characters to inline."}, ); Some(diag) } fn action(ctx: &RuleContext<Self>, state: &Self::State) -> Option<JsRuleAction> { let root = ctx.root(); let literal = AnyJsLiteralExpression::JsStringLiteralExpression(state.literal.clone()); let mut batch = root.begin(); batch.remove_js_variable_declarator(ctx.query()); if let Some(node) = state .reference .syntax() .parent()? .cast::<JsIdentifierExpression>() { batch.replace_node( AnyJsExpression::JsIdentifierExpression(node), AnyJsExpression::AnyJsLiteralExpression(literal), ); } else if let Some(node) = state .reference .syntax() .parent()? .cast::<JsShorthandPropertyObjectMember>() { // for replacing JsShorthandPropertyObjectMember let new_element = js_property_object_member( AnyJsObjectMemberName::JsLiteralMemberName(js_literal_member_name( SyntaxToken::new_detached( JsSyntaxKind::JS_LITERAL_MEMBER_NAME, JsReferenceIdentifier::cast_ref(state.reference.syntax())? .value_token() .ok()? .text(), [], [], ), )), SyntaxToken::new_detached(JsSyntaxKind::COLON, ":", [], []), AnyJsExpression::AnyJsLiteralExpression(literal), ); batch.replace_element(node.into_syntax().into(), new_element.into_syntax().into()); } else { return None; } Some(JsRuleAction { category: ActionCategory::QuickFix, applicability: Applicability::MaybeIncorrect, message: markup! { "Use the constant value directly" }.to_owned(), mutation: batch, }) } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/semantic_analyzers/style/use_const.rs
crates/rome_js_analyze/src/semantic_analyzers/style/use_const.rs
use crate::{semantic_services::Semantic, JsRuleAction}; use rome_analyze::{context::RuleContext, declare_rule, ActionCategory, Rule, RuleDiagnostic}; use rome_console::markup; use rome_diagnostics::Applicability; use rome_js_factory::make; use rome_js_semantic::{ReferencesExtensions, Scope, SemanticModel, SemanticScopeExtensions}; use rome_js_syntax::*; use rome_rowan::{declare_node_union, AstNode, BatchMutationExt}; declare_rule! { /// Require `const` declarations for variables that are never reassigned after declared. /// /// ## Examples /// /// ### Invalid /// /// ```js,expect_diagnostic /// let a = 3; /// console.log(a); /// ``` /// /// ```js,expect_diagnostic /// // `a` is redefined (not reassigned) on each loop step. /// for (let a of [1, 2, 3]) { /// console.log(a); /// } /// ``` /// /// ```js,expect_diagnostic /// // `a` is redefined (not reassigned) on each loop step. /// for (let a in [1, 2, 3]) { /// console.log(a); /// } /// ``` /// /// ```js,expect_diagnostic /// let a = 3; /// { /// let a = 4; /// a = 2; /// } /// ``` /// /// ## Valid /// /// ```js /// let a = 2; /// a = 3; /// console.log(a); /// ``` /// /// ```js /// let a = 1, b = 2; /// b = 3; /// ``` pub(crate) UseConst { version: "11.0.0", name: "useConst", recommended: true, } } declare_node_union! { pub(crate) VariableDeclaration = JsVariableDeclaration | JsForVariableDeclaration } declare_node_union! { pub(crate) DestructuringHost = JsVariableDeclarator | JsAssignmentExpression } pub(crate) struct ConstBindings { pub can_be_const: Vec<JsIdentifierBinding>, pub can_fix: bool, } enum ConstCheckResult { Fix, Report, } impl Rule for UseConst { type Query = Semantic<VariableDeclaration>; type State = ConstBindings; type Signals = Option<Self::State>; type Options = (); fn run(ctx: &RuleContext<Self>) -> Self::Signals { let declaration = ctx.query(); let model = ctx.model(); // Not a let declaration or inside a for-loop init if !declaration.is_let() || declaration.parent::<JsForStatement>().is_some() { return None; } ConstBindings::new(declaration, model) } fn diagnostic(ctx: &RuleContext<Self>, state: &Self::State) -> Option<RuleDiagnostic> { let declaration = ctx.query(); let kind = declaration.kind_token()?; let title = if state.can_be_const.len() == 1 { "This 'let' declares a variable which is never re-assigned." } else { "This 'let' declares some variables which are never re-assigned." }; let mut diag = RuleDiagnostic::new(rule_category!(), kind.text_trimmed_range(), title); for binding in state.can_be_const.iter() { let binding = binding.name_token().ok()?; diag = diag.detail( binding.text_trimmed_range(), markup! { "'"{ binding.text_trimmed() }"' is never re-assigned." }, ); } Some(diag) } fn action(ctx: &RuleContext<Self>, state: &Self::State) -> Option<JsRuleAction> { let declaration = ctx.query(); if state.can_fix { let mut batch = ctx.root().begin(); batch.replace_token( declaration.kind_token()?, make::token(JsSyntaxKind::CONST_KW), ); Some(JsRuleAction { category: ActionCategory::QuickFix, applicability: Applicability::MaybeIncorrect, message: markup! { "Use 'const' instead." }.to_owned(), mutation: batch, }) } else { None } } } impl ConstBindings { pub fn new(declaration: &VariableDeclaration, model: &SemanticModel) -> Option<Self> { let mut state = Self { can_be_const: Vec::new(), can_fix: true, }; let in_for_in_or_of_loop = matches!( declaration, VariableDeclaration::JsForVariableDeclaration(..) ); let mut bindings = 0; declaration.for_each_binding(|binding, declarator| { bindings += 1; let has_initializer = declarator.initializer().is_some(); let fix = check_binding_can_be_const(&binding, in_for_in_or_of_loop, has_initializer, model); match fix { Some(ConstCheckResult::Fix) => state.can_be_const.push(binding), Some(ConstCheckResult::Report) => { state.can_be_const.push(binding); state.can_fix = false; } None => state.can_fix = false, } }); // Only flag if all bindings can be const if state.can_be_const.len() != bindings { None } else { Some(state) } } } /// Check if a binding can be const fn check_binding_can_be_const( binding: &JsIdentifierBinding, in_for_in_or_of_loop: bool, has_initializer: bool, model: &SemanticModel, ) -> Option<ConstCheckResult> { let mut writes = binding.all_writes(model); // In a for-in or for-of loop or if it has an initializer if in_for_in_or_of_loop || has_initializer { return if writes.next().is_none() { Some(ConstCheckResult::Fix) } else { None }; } // If no initializer and one assignment in same scope let write = match (writes.next(), writes.next()) { (Some(v), None) if v.scope() == binding.scope(model) => v, _ => return None, }; let host = write .syntax() .ancestors() .find_map(DestructuringHost::cast)?; if host.has_member_expr_assignment() || host.has_outer_variables(write.scope()) { return None; } if host.can_become_variable_declaration()? { Some(ConstCheckResult::Report) } else { None } } impl VariableDeclaration { pub fn for_each_declarator(&self, f: impl FnMut(JsVariableDeclarator)) { match self { VariableDeclaration::JsVariableDeclaration(x) => x .declarators() .into_iter() .filter_map(Result::ok) .for_each(f), VariableDeclaration::JsForVariableDeclaration(x) => { x.declarator().into_iter().for_each(f) } } } pub fn for_each_binding(&self, mut f: impl FnMut(JsIdentifierBinding, &JsVariableDeclarator)) { self.for_each_declarator(|declarator| { if let Ok(pattern) = declarator.id() { with_binding_pat_identifiers(pattern, &mut |binding| { f(binding, &declarator); false }); } }); } pub fn kind_token(&self) -> Option<JsSyntaxToken> { match self { Self::JsVariableDeclaration(x) => x.kind().ok(), Self::JsForVariableDeclaration(x) => x.kind_token().ok(), } } pub fn is_let(&self) -> bool { match self { Self::JsVariableDeclaration(it) => it.is_let(), Self::JsForVariableDeclaration(it) => it.is_let(), } } pub fn is_var(&self) -> bool { match self { Self::JsVariableDeclaration(it) => it.is_var(), Self::JsForVariableDeclaration(it) => it.is_var(), } } } /// Visit [JsIdentifierBinding] in the given [JsAnyBindingPattern]. /// /// Traversal stops if the given function returns true. pub(crate) fn with_binding_pat_identifiers( pat: AnyJsBindingPattern, f: &mut impl FnMut(JsIdentifierBinding) -> bool, ) -> bool { match pat { AnyJsBindingPattern::AnyJsBinding(id) => with_binding_identifier(id, f), AnyJsBindingPattern::JsArrayBindingPattern(p) => with_array_binding_pat_identifiers(p, f), AnyJsBindingPattern::JsObjectBindingPattern(p) => with_object_binding_pat_identifiers(p, f), } } fn with_object_binding_pat_identifiers( pat: JsObjectBindingPattern, f: &mut impl FnMut(JsIdentifierBinding) -> bool, ) -> bool { pat.properties() .into_iter() .filter_map(Result::ok) .any(|it| { use AnyJsObjectBindingPatternMember as P; match it { P::JsObjectBindingPatternProperty(p) => p .pattern() .map_or(false, |it| with_binding_pat_identifiers(it, f)), P::JsObjectBindingPatternRest(p) => p .binding() .map_or(false, |it| with_binding_identifier(it, f)), P::JsObjectBindingPatternShorthandProperty(p) => p .identifier() .map_or(false, |it| with_binding_identifier(it, f)), P::JsBogusBinding(_) => false, } }) } fn with_array_binding_pat_identifiers( pat: JsArrayBindingPattern, f: &mut impl FnMut(JsIdentifierBinding) -> bool, ) -> bool { pat.elements().into_iter().filter_map(Result::ok).any(|it| { use AnyJsArrayBindingPatternElement as P; match it { P::AnyJsBindingPattern(p) => with_binding_pat_identifiers(p, f), P::JsArrayBindingPatternRestElement(p) => p .pattern() .map_or(false, |it| with_binding_pat_identifiers(it, f)), P::JsArrayHole(_) => false, P::JsBindingPatternWithDefault(p) => p .pattern() .map_or(false, |it| with_binding_pat_identifiers(it, f)), } }) } fn with_binding_identifier( binding: AnyJsBinding, f: &mut impl FnMut(JsIdentifierBinding) -> bool, ) -> bool { match binding { AnyJsBinding::JsIdentifierBinding(id) => f(id), AnyJsBinding::JsBogusBinding(_) => false, } } impl DestructuringHost { fn can_become_variable_declaration(&self) -> Option<bool> { match self { Self::JsVariableDeclarator(_) => Some(true), Self::JsAssignmentExpression(e) => { let mut parent = e.syntax().parent()?; while parent.kind() == JsSyntaxKind::JS_PARENTHESIZED_EXPRESSION { parent = parent.parent()?; } if parent.kind() == JsSyntaxKind::JS_EXPRESSION_STATEMENT { parent = parent.parent()?; Some( parent.kind() == JsSyntaxKind::JS_STATEMENT_LIST || parent.kind() == JsSyntaxKind::JS_MODULE_ITEM_LIST, ) } else { // example: while(a = b) {} None } } } } fn has_member_expr_assignment(&self) -> bool { match self { Self::JsAssignmentExpression(it) => { it.left().map_or(false, has_member_expr_in_assign_pat) } _ => false, } } fn has_outer_variables(&self, scope: Scope) -> bool { match self { Self::JsVariableDeclarator(it) => it .id() .map_or(false, |pat| has_outer_variables_in_binding_pat(pat, scope)), Self::JsAssignmentExpression(it) => it .left() .map_or(false, |pat| has_outer_variables_in_assign_pat(pat, &scope)), } } } fn has_outer_variables_in_binding_pat(pat: AnyJsBindingPattern, scope: Scope) -> bool { with_binding_pat_identifiers(pat, &mut |it| is_outer_variable_in_binding(it, &scope)) } fn is_outer_variable_in_binding(binding: JsIdentifierBinding, scope: &Scope) -> bool { binding .name_token() .map_or(false, |name| is_binding_in_outer_scopes(scope, name)) } fn has_member_expr_in_assign_pat(pat: AnyJsAssignmentPattern) -> bool { use AnyJsAssignmentPattern as P; match pat { P::AnyJsAssignment(p) => is_member_expr_assignment(p), P::JsArrayAssignmentPattern(p) => has_member_expr_in_array_pat(p), P::JsObjectAssignmentPattern(p) => has_member_expr_in_object_assign_pat(p), } } fn has_member_expr_in_object_assign_pat(pat: JsObjectAssignmentPattern) -> bool { pat.properties() .into_iter() .filter_map(Result::ok) .any(|it| { use AnyJsObjectAssignmentPatternMember as P; match it { P::JsObjectAssignmentPatternProperty(p) => { p.pattern().map_or(false, has_member_expr_in_assign_pat) } P::JsObjectAssignmentPatternRest(p) => { p.target().map_or(false, is_member_expr_assignment) } P::JsObjectAssignmentPatternShorthandProperty(_) | P::JsBogusAssignment(_) => false, } }) } fn has_member_expr_in_array_pat(pat: JsArrayAssignmentPattern) -> bool { pat.elements() .into_iter() .filter_map(Result::ok) .any(|it| it.pattern().map_or(false, has_member_expr_in_assign_pat)) } fn is_member_expr_assignment(mut assignment: AnyJsAssignment) -> bool { use AnyJsAssignment::*; while let JsParenthesizedAssignment(p) = assignment { if let Ok(p) = p.assignment() { assignment = p } else { return false; } } matches!( assignment, JsComputedMemberAssignment(_) | JsStaticMemberAssignment(_) ) } fn has_outer_variables_in_assign_pat(pat: AnyJsAssignmentPattern, scope: &Scope) -> bool { use AnyJsAssignmentPattern as P; match pat { P::AnyJsAssignment(p) => is_outer_variable_in_assignment(p, scope), P::JsArrayAssignmentPattern(p) => has_outer_variables_in_object_assign_pat(p, scope), P::JsObjectAssignmentPattern(p) => has_outer_variables_in_array_assign_pat(p, scope), } } fn has_outer_variables_in_array_assign_pat(pat: JsObjectAssignmentPattern, scope: &Scope) -> bool { pat.properties() .into_iter() .filter_map(Result::ok) .any(|it| { use AnyJsObjectAssignmentPatternMember as P; match it { P::JsObjectAssignmentPatternProperty(p) => p .pattern() .map_or(false, |it| has_outer_variables_in_assign_pat(it, scope)), P::JsObjectAssignmentPatternRest(p) => p .target() .map_or(false, |it| is_outer_variable_in_assignment(it, scope)), P::JsObjectAssignmentPatternShorthandProperty(p) => p .identifier() .map_or(false, |it| is_outer_ident_in_assignment(it, scope)), P::JsBogusAssignment(_) => false, } }) } fn has_outer_variables_in_object_assign_pat(pat: JsArrayAssignmentPattern, scope: &Scope) -> bool { pat.elements().into_iter().filter_map(Result::ok).any(|it| { it.pattern() .map_or(false, |p| has_outer_variables_in_assign_pat(p, scope)) }) } fn is_outer_variable_in_assignment(e: AnyJsAssignment, scope: &Scope) -> bool { match e { AnyJsAssignment::JsIdentifierAssignment(it) => is_outer_ident_in_assignment(it, scope), _ => false, } } fn is_outer_ident_in_assignment(assignment: JsIdentifierAssignment, scope: &Scope) -> bool { assignment .name_token() .map_or(false, |name| is_binding_in_outer_scopes(scope, name)) } fn is_binding_in_outer_scopes(scope: &Scope, name: JsSyntaxToken) -> bool { let text = name.text_trimmed(); scope .ancestors() .skip(1) // Skip current scope .any(|scope| scope.get_binding(text).is_some()) }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/semantic_analyzers/style/use_fragment_syntax.rs
crates/rome_js_analyze/src/semantic_analyzers/style/use_fragment_syntax.rs
use crate::react::{jsx_member_name_is_react_fragment, jsx_reference_identifier_is_fragment}; use crate::semantic_services::Semantic; use crate::JsRuleAction; use rome_analyze::context::RuleContext; use rome_analyze::{declare_rule, ActionCategory, Rule, RuleDiagnostic}; use rome_console::markup; use rome_diagnostics::Applicability; use rome_js_factory::make::{ jsx_child_list, jsx_closing_fragment, jsx_fragment, jsx_opening_fragment, }; use rome_js_syntax::{AnyJsxElementName, JsxElement}; use rome_rowan::{AstNode, AstNodeList, BatchMutationExt}; declare_rule! { /// This rule enforces the use of `<>...</>` over `<Fragment>...</Fragment>`. /// /// The shorthand fragment syntax saves keystrokes and is only inapplicable when keys are required. /// /// ## Examples /// /// ### Invalid /// /// ```js,expect_diagnostic /// <Fragment>child</Fragment> /// ``` /// /// ```js,expect_diagnostic /// <React.Fragment>child</React.Fragment> /// ``` pub(crate) UseFragmentSyntax { version: "0.10.0", name: "useFragmentSyntax", recommended: false, } } impl Rule for UseFragmentSyntax { type Query = Semantic<JsxElement>; type State = (); type Signals = Option<Self::State>; type Options = (); fn run(ctx: &RuleContext<Self>) -> Self::Signals { let node = ctx.query(); let model = ctx.model(); let opening_element = node.opening_element().ok()?; let name = opening_element.name().ok()?; let maybe_invalid = match name { AnyJsxElementName::JsxMemberName(member_name) => { jsx_member_name_is_react_fragment(&member_name, model)? } AnyJsxElementName::JsxReferenceIdentifier(identifier) => { jsx_reference_identifier_is_fragment(&identifier, model)? } AnyJsxElementName::JsxName(_) | AnyJsxElementName::JsxNamespaceName(_) => false, }; if maybe_invalid && opening_element.attributes().is_empty() { return Some(()); } None } fn action(ctx: &RuleContext<Self>, _state: &Self::State) -> Option<JsRuleAction> { let node = ctx.query(); let mut mutation = ctx.root().begin(); let list = jsx_child_list(node.children()); let opening_element = node.opening_element().ok()?; let closing_element = node.closing_element().ok()?; let fragment = jsx_fragment( jsx_opening_fragment( opening_element.l_angle_token().ok()?, opening_element.r_angle_token().ok()?, ), list, jsx_closing_fragment( closing_element.l_angle_token().ok()?, closing_element.slash_token().ok()?, closing_element.r_angle_token().ok()?, ), ); mutation.replace_element( node.clone().into_syntax().into(), fragment.into_syntax().into(), ); Some(JsRuleAction { mutation, message: (markup! { "Replace "<Emphasis>"<Fragment>"</Emphasis>" with the fragment syntax" }) .to_owned(), applicability: Applicability::MaybeIncorrect, category: ActionCategory::QuickFix, }) } fn diagnostic(ctx: &RuleContext<Self>, _state: &Self::State) -> Option<RuleDiagnostic> { let node = ctx.query(); Some( RuleDiagnostic::new( rule_category!(), node.syntax().text_trimmed_range(), markup! { "Use shorthand syntax for Fragment elements instead of standard syntax." }, ) .note(markup! { "Shorthand fragment syntax saves keystrokes and is only inapplicable when keys are required." }), ) } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/semantic_analyzers/style/no_restricted_globals.rs
crates/rome_js_analyze/src/semantic_analyzers/style/no_restricted_globals.rs
use crate::semantic_services::SemanticServices; use bpaf::Bpaf; use rome_analyze::context::RuleContext; use rome_analyze::{declare_rule, Rule, RuleDiagnostic}; use rome_console::markup; use rome_deserialize::json::{has_only_known_keys, VisitJsonNode}; use rome_deserialize::{DeserializationDiagnostic, VisitNode}; use rome_js_semantic::{Binding, BindingExtensions}; use rome_js_syntax::{ JsIdentifierAssignment, JsReferenceIdentifier, JsxReferenceIdentifier, TextRange, }; use rome_json_syntax::JsonLanguage; use rome_rowan::{declare_node_union, AstNode, SyntaxNode}; use serde::{Deserialize, Serialize}; use std::str::FromStr; declare_rule! { /// This rule allows you to specify global variable names that you don’t want to use in your application. /// /// > Disallowing usage of specific global variables can be useful if you want to allow a set of /// global variables by enabling an environment, but still want to disallow some of those. /// /// ## Examples /// /// ### Invalid /// /// ```js,expect_diagnostic /// console.log(event) /// ``` /// /// ### Valid /// ```js /// function f(event) { /// console.log(event) /// } /// ``` /// ## Options /// /// Use the options to specify additional globals that you want to restrict in your /// source code. /// /// ```json /// { /// "//": "...", /// "options": { /// "deniedGlobals": ["$", "MooTools"] /// } /// } /// ``` /// /// In the example above, the rule will emit a diagnostics if tried to use `$` or `MooTools` without /// creating a local variable. /// pub(crate) NoRestrictedGlobals { version: "0.10.0", name: "noRestrictedGlobals", recommended: false, } } declare_node_union! { pub(crate) AnyIdentifier = JsReferenceIdentifier | JsIdentifierAssignment | JsxReferenceIdentifier } const RESTRICTED_GLOBALS: [&str; 2] = ["event", "error"]; /// Options for the rule `noRestrictedGlobals`. #[derive(Default, Deserialize, Serialize, Debug, Clone, Bpaf)] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct RestrictedGlobalsOptions { /// A list of names that should trigger the rule #[serde(skip_serializing_if = "Option::is_none")] #[bpaf(hide, argument::<String>("NUM"), many, optional)] denied_globals: Option<Vec<String>>, } impl RestrictedGlobalsOptions { pub const KNOWN_KEYS: &'static [&'static str] = &["deniedGlobals"]; } // Required by [Bpaf]. impl FromStr for RestrictedGlobalsOptions { type Err = &'static str; fn from_str(_s: &str) -> Result<Self, Self::Err> { // WARNING: should not be used. Ok(Self::default()) } } impl VisitJsonNode for RestrictedGlobalsOptions {} impl VisitNode<JsonLanguage> for RestrictedGlobalsOptions { fn visit_member_name( &mut self, node: &SyntaxNode<JsonLanguage>, diagnostics: &mut Vec<DeserializationDiagnostic>, ) -> Option<()> { has_only_known_keys(node, Self::KNOWN_KEYS, diagnostics) } fn visit_map( &mut self, key: &SyntaxNode<JsonLanguage>, value: &SyntaxNode<JsonLanguage>, diagnostics: &mut Vec<DeserializationDiagnostic>, ) -> Option<()> { let (name, value) = self.get_key_and_value(key, value, diagnostics)?; let name_text = name.text(); if name_text == "deniedGlobals" { self.denied_globals = self.map_to_array_of_strings(&value, name_text, diagnostics); } Some(()) } } impl Rule for NoRestrictedGlobals { type Query = SemanticServices; type State = (TextRange, String); type Signals = Vec<Self::State>; type Options = RestrictedGlobalsOptions; fn run(ctx: &RuleContext<Self>) -> Self::Signals { let model = ctx.model(); let options = ctx.options(); let unresolved_reference_nodes = model .all_unresolved_references() .map(|reference| reference.syntax().clone()); let global_references_nodes = model .all_global_references() .map(|reference| reference.syntax().clone()); unresolved_reference_nodes .chain(global_references_nodes) .filter_map(|node| { let node = AnyIdentifier::unwrap_cast(node); let (token, binding) = match node { AnyIdentifier::JsReferenceIdentifier(node) => { (node.value_token(), node.binding(model)) } AnyIdentifier::JsxReferenceIdentifier(node) => { (node.value_token(), node.binding(model)) } AnyIdentifier::JsIdentifierAssignment(node) => { (node.name_token(), node.binding(model)) } }; let token = token.ok()?; let text = token.text_trimmed(); let denied_globals = if let Some(denied_globals) = options.denied_globals.as_ref() { denied_globals.iter().map(AsRef::as_ref).collect::<Vec<_>>() } else { vec![] }; is_restricted(text, binding, denied_globals.as_slice()) .map(|text| (token.text_trimmed_range(), text)) }) .collect() } fn diagnostic(_ctx: &RuleContext<Self>, (span, text): &Self::State) -> Option<RuleDiagnostic> { Some( RuleDiagnostic::new( rule_category!(), *span, markup! { "Do not use the global variable "<Emphasis>{text}</Emphasis>"." }, ) .note(markup! { "Use a local variable instead." }), ) } } fn is_restricted(name: &str, binding: Option<Binding>, denied_globals: &[&str]) -> Option<String> { if binding.is_none() && (RESTRICTED_GLOBALS.contains(&name) || denied_globals.contains(&name)) { Some(name.to_string()) } else { None } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/semantic_analyzers/style/no_var.rs
crates/rome_js_analyze/src/semantic_analyzers/style/no_var.rs
use crate::{control_flow::AnyJsControlFlowRoot, semantic_services::Semantic, JsRuleAction}; use rome_analyze::{context::RuleContext, declare_rule, ActionCategory, Rule, RuleDiagnostic}; use rome_console::markup; use rome_diagnostics::Applicability; use rome_js_factory::make; use rome_js_syntax::{JsModule, JsScript, JsSyntaxKind}; use rome_rowan::{AstNode, BatchMutationExt}; use super::use_const::{ConstBindings, VariableDeclaration}; declare_rule! { /// Disallow the use of `var` /// /// ECMAScript 6 allows programmers to create variables with block scope instead of function scope using the let and const keywords. /// /// Block scope is common in many other programming languages and helps programmers avoid mistakes. /// /// Source: https://eslint.org/docs/latest/rules/no-var /// /// ## Examples /// /// ### Invalid /// /// ```js,expect_diagnostic /// var foo = 1; /// ``` /// /// ### Valid /// /// ```js /// const foo = 1; /// let bar = 1; ///``` pub(crate) NoVar { version: "11.0.0", name: "noVar", recommended: true, } } impl Rule for NoVar { type Query = Semantic<VariableDeclaration>; type State = (); type Signals = Option<Self::State>; type Options = (); fn run(ctx: &RuleContext<Self>) -> Self::Signals { let declaration = ctx.query(); declaration.is_var().then_some(()) } fn diagnostic(ctx: &RuleContext<Self>, _state: &Self::State) -> Option<RuleDiagnostic> { let declaration = ctx.query(); let var_scope = declaration .syntax() .ancestors() .find(|x| AnyJsControlFlowRoot::can_cast(x.kind()))?; let contextual_note = if JsScript::can_cast(var_scope.kind()) { markup! { "A variable declared with "<Emphasis>"var"</Emphasis>" in the global scope pollutes the global object." } } else if JsModule::can_cast(var_scope.kind()) { markup! { "A variable declared with "<Emphasis>"var"</Emphasis>" is accessible in the whole module. Thus, the variable can be accessed before its initialization and outside the block where it is declared." } } else { markup! { "A variable declared with "<Emphasis>"var"</Emphasis>" is accessible in the whole body of the function. Thus, the variable can be accessed before its initialization and outside the block where it is declared." } }; Some(RuleDiagnostic::new( rule_category!(), declaration.range(), markup! { "Use "<Emphasis>"let"</Emphasis>" or "<Emphasis>"const"</Emphasis>" instead of "<Emphasis>"var"</Emphasis>"." }, ).note(contextual_note).note( markup! { "See "<Hyperlink href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var">"MDN web docs"</Hyperlink>" for more details." } )) } fn action(ctx: &RuleContext<Self>, _: &Self::State) -> Option<JsRuleAction> { let declaration = ctx.query(); let model = ctx.model(); let maybe_const = ConstBindings::new(declaration, model); // When a `var` is initialized and re-assigned `maybe_const` is `None`. // In this case we fall back to `let`. // Otherwise, we check if the `var` can be "fixed" to a `const`. let replacing_token_kind = if maybe_const.filter(|x| x.can_fix).is_some() { JsSyntaxKind::CONST_KW } else { JsSyntaxKind::LET_KW }; let mut mutation = ctx.root().begin(); mutation.replace_token(declaration.kind_token()?, make::token(replacing_token_kind)); Some(JsRuleAction { category: ActionCategory::QuickFix, applicability: Applicability::MaybeIncorrect, message: markup! { "Use '"<Emphasis>{replacing_token_kind.to_string()?}</Emphasis>"' instead." }.to_owned(), mutation, }) } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/semantic_analyzers/complexity/no_useless_fragments.rs
crates/rome_js_analyze/src/semantic_analyzers/complexity/no_useless_fragments.rs
use crate::react::{jsx_member_name_is_react_fragment, jsx_reference_identifier_is_fragment}; use crate::semantic_services::Semantic; use crate::JsRuleAction; use rome_analyze::context::RuleContext; use rome_analyze::{declare_rule, ActionCategory, Rule, RuleDiagnostic}; use rome_console::markup; use rome_diagnostics::Applicability; use rome_js_factory::make::{ident, js_expression_statement, jsx_string, jsx_tag_expression}; use rome_js_syntax::{ AnyJsxChild, AnyJsxElementName, AnyJsxTag, JsLanguage, JsParenthesizedExpression, JsSyntaxKind, JsxChildList, JsxElement, JsxFragment, JsxTagExpression, }; use rome_rowan::{declare_node_union, AstNode, AstNodeList, BatchMutation, BatchMutationExt}; declare_rule! { /// Disallow unnecessary fragments /// /// ## Examples /// /// ### Invalid /// /// ```jsx,expect_diagnostic /// <> /// foo /// </> /// ``` /// /// ```jsx,expect_diagnostic /// <React.Fragment> /// foo /// </React.Fragment> /// ``` /// /// ```jsx,expect_diagnostic /// <> /// <>foo</> /// <SomeComponent /> /// </> /// ``` /// /// ```jsx,expect_diagnostic /// <></> /// ``` pub(crate) NoUselessFragments { version: "0.10.0", name: "noUselessFragments", recommended: true, } } #[derive(Debug)] pub(crate) enum NoUselessFragmentsState { Empty, Child(AnyJsxChild), } declare_node_union! { pub(crate) NoUselessFragmentsQuery = JsxFragment | JsxElement } impl NoUselessFragmentsQuery { fn replace_node(&self, mutation: &mut BatchMutation<JsLanguage>, new_node: AnyJsxChild) { match self { NoUselessFragmentsQuery::JsxFragment(fragment) => { let old_node = AnyJsxChild::JsxFragment(fragment.clone()); mutation.replace_node(old_node, new_node); } NoUselessFragmentsQuery::JsxElement(element) => { let old_node = AnyJsxChild::JsxElement(element.clone()); mutation.replace_node(old_node, new_node); } } } fn remove_node_from_list(&self, mutation: &mut BatchMutation<JsLanguage>) { match self { NoUselessFragmentsQuery::JsxFragment(fragment) => { let old_node = AnyJsxChild::JsxFragment(fragment.clone()); mutation.remove_node(old_node); } NoUselessFragmentsQuery::JsxElement(element) => { let old_node = AnyJsxChild::JsxElement(element.clone()); mutation.remove_node(old_node); } } } fn children(&self) -> JsxChildList { match self { NoUselessFragmentsQuery::JsxFragment(element) => element.children(), NoUselessFragmentsQuery::JsxElement(element) => element.children(), } } } impl Rule for NoUselessFragments { type Query = Semantic<NoUselessFragmentsQuery>; type State = NoUselessFragmentsState; type Signals = Option<Self::State>; type Options = (); fn run(ctx: &RuleContext<Self>) -> Self::Signals { let node = ctx.query(); let model = ctx.model(); match node { NoUselessFragmentsQuery::JsxFragment(fragment) => { let parents_where_fragments_must_be_preserved = node .syntax() .parent() .map(|parent| match JsxTagExpression::try_cast(parent) { Ok(parent) => parent .syntax() .parent() .and_then(|parent| { if let Some(parenthesized_expression) = JsParenthesizedExpression::cast_ref(&parent) { parenthesized_expression.syntax().parent() } else { Some(parent) } }) .map(|parent| { matches!( parent.kind(), JsSyntaxKind::JS_RETURN_STATEMENT | JsSyntaxKind::JS_INITIALIZER_CLAUSE | JsSyntaxKind::JS_CONDITIONAL_EXPRESSION | JsSyntaxKind::JS_ARROW_FUNCTION_EXPRESSION | JsSyntaxKind::JS_FUNCTION_EXPRESSION | JsSyntaxKind::JS_FUNCTION_DECLARATION | JsSyntaxKind::JS_PROPERTY_OBJECT_MEMBER ) }) .unwrap_or(false), Err(_) => false, }) .unwrap_or(false); let child_list = fragment.children(); if !parents_where_fragments_must_be_preserved { match child_list.first() { Some(first) if child_list.len() == 1 => { Some(NoUselessFragmentsState::Child(first)) } None => Some(NoUselessFragmentsState::Empty), _ => None, } } else { None } } NoUselessFragmentsQuery::JsxElement(element) => { let opening_element = element.opening_element().ok()?; let name = opening_element.name().ok()?; let is_valid_react_fragment = match name { AnyJsxElementName::JsxMemberName(member_name) => { jsx_member_name_is_react_fragment(&member_name, model)? } AnyJsxElementName::JsxReferenceIdentifier(identifier) => { jsx_reference_identifier_is_fragment(&identifier, model)? } AnyJsxElementName::JsxName(_) | AnyJsxElementName::JsxNamespaceName(_) => false, }; if is_valid_react_fragment { let child_list = element.children(); // The `Fragment` component supports only the "key" prop and react emits a warning for not supported props. // We assume that the user knows - and fixed - that and only care about the prop that is actually supported. let attribute_key = opening_element .attributes() .into_iter() .find_map(|attribute| { let attribute = attribute.as_jsx_attribute()?; let attribute_name = attribute.name().ok()?; let attribute_name = attribute_name.as_jsx_name()?; if attribute_name.value_token().ok()?.text_trimmed() == "key" { Some(()) } else { None } }); if attribute_key.is_none() { return match child_list.first() { Some(first) if child_list.len() == 1 => { Some(NoUselessFragmentsState::Child(first)) } None => Some(NoUselessFragmentsState::Empty), _ => None, }; } } None } } } fn action(ctx: &RuleContext<Self>, state: &Self::State) -> Option<JsRuleAction> { let node = ctx.query(); let mut mutation = ctx.root().begin(); let is_in_list = node .syntax() .parent() .map_or(false, |parent| JsxChildList::can_cast(parent.kind())); if is_in_list { let new_child = match state { NoUselessFragmentsState::Empty => None, NoUselessFragmentsState::Child(child) => Some(child.clone()), }; if let Some(new_child) = new_child { node.replace_node(&mut mutation, new_child); } else { node.remove_node_from_list(&mut mutation); } } else if let Some(parent) = node.parent::<JsxTagExpression>() { let parent = parent.syntax().parent()?; let child = node.children().first(); if let Some(child) = child { let new_node = match child { AnyJsxChild::JsxElement(node) => Some( jsx_tag_expression(AnyJsxTag::JsxElement(node)) .syntax() .clone(), ), AnyJsxChild::JsxFragment(node) => Some( jsx_tag_expression(AnyJsxTag::JsxFragment(node)) .syntax() .clone(), ), AnyJsxChild::JsxSelfClosingElement(node) => Some( jsx_tag_expression(AnyJsxTag::JsxSelfClosingElement(node)) .syntax() .clone(), ), AnyJsxChild::JsxText(text) => { let new_value = format!("\"{}\"", text.value_token().ok()?); Some(jsx_string(ident(&new_value)).syntax().clone()) } AnyJsxChild::JsxExpressionChild(child) => { child.expression().map(|expression| { js_expression_statement(expression).build().syntax().clone() }) } // can't apply a code action because it will create invalid syntax // for example `<>{...foo}</>` would become `{...foo}` which would produce // a syntax error AnyJsxChild::JsxSpreadChild(_) => return None, }; if let Some(new_node) = new_node { mutation.replace_element(parent.into(), new_node.into()); } else { mutation.remove_element(parent.into()); } } else { mutation.remove_element(parent.into()); } } Some(JsRuleAction { category: ActionCategory::QuickFix, applicability: Applicability::MaybeIncorrect, message: markup! { "Remove the Fragment" }.to_owned(), mutation, }) } fn diagnostic(ctx: &RuleContext<Self>, _state: &Self::State) -> Option<RuleDiagnostic> { let node = ctx.query(); Some(RuleDiagnostic::new( rule_category!(), node.syntax().text_trimmed_range(), markup! { "Avoid using unnecessary "<Emphasis>"Fragment"</Emphasis>"." }, )) } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/semantic_analyzers/correctness/no_unused_variables.rs
crates/rome_js_analyze/src/semantic_analyzers/correctness/no_unused_variables.rs
use crate::JsRuleAction; use crate::{semantic_services::Semantic, utils::rename::RenameSymbolExtensions}; use rome_analyze::{context::RuleContext, declare_rule, ActionCategory, Rule, RuleDiagnostic}; use rome_console::markup; use rome_diagnostics::Applicability; use rome_js_semantic::{ReferencesExtensions, SemanticScopeExtensions}; use rome_js_syntax::{ binding_ext::{AnyJsBindingDeclaration, AnyJsIdentifierBinding, JsAnyParameterParentFunction}, JsClassExpression, JsFunctionDeclaration, JsFunctionExpression, JsSyntaxKind, JsSyntaxNode, JsVariableDeclarator, }; use rome_rowan::{AstNode, BatchMutationExt}; declare_rule! { /// Disallow unused variables. /// /// There are two exceptions to this rule: /// 1. variables that starts with underscore, ex: `let _something;` /// 2. the `React` variable; /// /// The pattern of having an underscore as prefix of a name of variable is a very diffuse /// pattern among programmers, and Rome decided to follow it. /// /// Importing the `React` variable was a mandatory pattern until some time ago: /// /// For the time being this rule will ignore it, but this **might change in the future releases**. /// /// ## Examples /// /// ### Invalid /// /// ```js,expect_diagnostic /// const a = 4; /// ``` /// /// ```js,expect_diagnostic /// let a = 4; /// ``` /// /// ```js,expect_diagnostic /// function foo() { /// }; /// ``` /// /// ```js,expect_diagnostic /// function foo(myVar) { /// console.log('foo'); /// } /// foo(); /// ``` /// /// ```js,expect_diagnostic /// const foo = () => { /// }; /// ``` /// /// ```js,expect_diagnostic /// function foo() { /// foo(); /// } /// ``` /// /// ```js,expect_diagnostic /// const foo = () => { /// foo(); /// console.log(this); /// }; /// ``` /// /// # Valid /// /// ```js /// function foo(b) { /// console.log(b) /// }; /// foo(); /// ``` /// /// ```js /// function foo(_unused) { /// }; /// foo(); /// ``` /// /// ```jsx /// import React from 'react'; /// function foo() { /// return <div />; /// }; /// foo(); /// ``` /// /// ```ts /// function used_overloaded(): number; /// function used_overloaded(s: string): string; /// function used_overloaded(s?: string) { /// return s; /// } /// used_overloaded(); /// ``` pub(crate) NoUnusedVariables { version: "0.9.0", name: "noUnusedVariables", recommended: false, } } /// Suggestion if the bindnig is unused #[derive(Copy, Clone)] pub enum SuggestedFix { /// No suggestion will be given NoSuggestion, /// Suggest to prefix the name of the binding with underscore PrefixUnderscore, } fn is_function_that_is_ok_parameter_not_be_used( parent_function: Option<JsAnyParameterParentFunction>, ) -> bool { matches!( parent_function, Some( // bindings in signatures are ok to not be used JsAnyParameterParentFunction::TsMethodSignatureClassMember(_) | JsAnyParameterParentFunction::TsCallSignatureTypeMember(_) | JsAnyParameterParentFunction::TsConstructSignatureTypeMember(_) | JsAnyParameterParentFunction::TsConstructorSignatureClassMember(_) | JsAnyParameterParentFunction::TsMethodSignatureTypeMember(_) | JsAnyParameterParentFunction::TsSetterSignatureClassMember(_) | JsAnyParameterParentFunction::TsSetterSignatureTypeMember(_) // bindings in function types are ok to not be used | JsAnyParameterParentFunction::TsFunctionType(_) // binding in declare are ok to not be used | JsAnyParameterParentFunction::TsDeclareFunctionDeclaration(_) ) ) } fn is_ambient_context(node: &JsSyntaxNode) -> bool { node.ancestors() .any(|x| x.kind() == JsSyntaxKind::TS_DECLARE_STATEMENT) } fn suggestion_for_binding(binding: &AnyJsIdentifierBinding) -> Option<SuggestedFix> { if binding.is_under_object_pattern_binding()? { Some(SuggestedFix::NoSuggestion) } else { Some(SuggestedFix::PrefixUnderscore) } } // It is ok in some Typescripts constructs for a parameter to be unused. // Returning None means is ok to be unused fn suggested_fix_if_unused(binding: &AnyJsIdentifierBinding) -> Option<SuggestedFix> { match binding.declaration()? { // ok to not be used AnyJsBindingDeclaration::TsIndexSignatureParameter(_) | AnyJsBindingDeclaration::TsDeclareFunctionDeclaration(_) | AnyJsBindingDeclaration::JsClassExpression(_) | AnyJsBindingDeclaration::JsFunctionExpression(_) => None, // Some parameters are ok to not be used AnyJsBindingDeclaration::TsPropertyParameter(_) => None, AnyJsBindingDeclaration::JsFormalParameter(parameter) => { let is_binding_ok = is_function_that_is_ok_parameter_not_be_used(parameter.parent_function()); if !is_binding_ok { suggestion_for_binding(binding) } else { None } } AnyJsBindingDeclaration::JsRestParameter(parameter) => { let is_binding_ok = is_function_that_is_ok_parameter_not_be_used(parameter.parent_function()); if !is_binding_ok { suggestion_for_binding(binding) } else { None } } // declarations need to be check if they are under `declare` node @ AnyJsBindingDeclaration::JsVariableDeclarator(_) => { let is_binding_ok = is_ambient_context(node.syntax()); if !is_binding_ok { suggestion_for_binding(binding) } else { None } } node @ AnyJsBindingDeclaration::TsTypeAliasDeclaration(_) | node @ AnyJsBindingDeclaration::JsClassDeclaration(_) | node @ AnyJsBindingDeclaration::JsFunctionDeclaration(_) | node @ AnyJsBindingDeclaration::TsInterfaceDeclaration(_) | node @ AnyJsBindingDeclaration::TsEnumDeclaration(_) | node @ AnyJsBindingDeclaration::TsModuleDeclaration(_) | node @ AnyJsBindingDeclaration::TsImportEqualsDeclaration(_) => { if is_ambient_context(node.syntax()) { None } else { Some(SuggestedFix::NoSuggestion) } } // Bindings under unknown parameter are never ok to be unused AnyJsBindingDeclaration::JsBogusParameter(_) => Some(SuggestedFix::NoSuggestion), // Bindings under catch are never ok to be unused AnyJsBindingDeclaration::JsCatchDeclaration(_) => Some(SuggestedFix::PrefixUnderscore), // Imports are never ok to be unused AnyJsBindingDeclaration::JsImportDefaultClause(_) | AnyJsBindingDeclaration::JsImportNamespaceClause(_) | AnyJsBindingDeclaration::JsShorthandNamedImportSpecifier(_) | AnyJsBindingDeclaration::JsNamedImportSpecifier(_) | AnyJsBindingDeclaration::JsBogusNamedImportSpecifier(_) | AnyJsBindingDeclaration::JsDefaultImportSpecifier(_) | AnyJsBindingDeclaration::JsNamespaceImportSpecifier(_) => { Some(SuggestedFix::NoSuggestion) } // exports with binding are ok to be unused AnyJsBindingDeclaration::JsClassExportDefaultDeclaration(_) | AnyJsBindingDeclaration::JsFunctionExportDefaultDeclaration(_) | AnyJsBindingDeclaration::TsDeclareFunctionExportDefaultDeclaration(_) => { Some(SuggestedFix::NoSuggestion) } } } impl Rule for NoUnusedVariables { type Query = Semantic<AnyJsIdentifierBinding>; type State = SuggestedFix; type Signals = Option<Self::State>; type Options = (); fn run(ctx: &RuleContext<Self>) -> Option<Self::State> { let binding = ctx.query(); let name = match binding { AnyJsIdentifierBinding::JsIdentifierBinding(binding) => binding.name_token().ok()?, AnyJsIdentifierBinding::TsIdentifierBinding(binding) => binding.name_token().ok()?, AnyJsIdentifierBinding::TsTypeParameterName(binding) => binding.ident_token().ok()?, }; let name = name.token_text_trimmed(); let name = name.text(); // Old code import React but do not used directly // only indirectly after transpiling JSX. if name.starts_with('_') || name == "React" { return None; } // Ignore expressions if binding.parent::<JsFunctionExpression>().is_some() || binding.parent::<JsClassExpression>().is_some() { return None; } let Some(suggestion) = suggested_fix_if_unused(binding) else { return None; }; let model = ctx.model(); if model.is_exported(binding) { return None; } let all_references = binding.all_references(model); if all_references.count() == 0 { Some(suggestion) } else { // We need to check if all uses of this binding are somehow recursive let function_declaration_scope = binding .parent::<JsFunctionDeclaration>() .map(|declaration| declaration.scope(model)); let declarator = binding.parent::<JsVariableDeclarator>(); let mut references_outside = 0; for r in binding.all_references(model) { let reference_scope = r.scope(); // If this binding is a function, and all its references are "inside" this // function, we can safely say that this function is not used if function_declaration_scope .as_ref() .map(|s| s.is_ancestor_of(&reference_scope)) .unwrap_or(false) { continue; } // Another possibility is if all its references are "inside" the same declaration if let Some(declarator) = declarator.as_ref() { let node = declarator.syntax(); if r.syntax().ancestors().any(|n| n == *node) { continue; } } references_outside += 1; break; } if references_outside == 0 { Some(suggestion) } else { None } } } fn diagnostic(ctx: &RuleContext<Self>, _: &Self::State) -> Option<RuleDiagnostic> { let binding = ctx.query(); let symbol_type = match binding.syntax().parent().unwrap().kind() { JsSyntaxKind::JS_FORMAL_PARAMETER => "parameter", JsSyntaxKind::JS_FUNCTION_DECLARATION => "function", JsSyntaxKind::JS_CLASS_DECLARATION => "class", JsSyntaxKind::TS_INTERFACE_DECLARATION => "interface", JsSyntaxKind::TS_TYPE_ALIAS_DECLARATION => "type alias", _ => "variable", }; let diag = RuleDiagnostic::new( rule_category!(), binding.syntax().text_trimmed_range(), markup! { "This " {symbol_type} " is unused." }, ); let diag = diag.note( markup! {"Unused variables usually are result of incomplete refactoring, typos and other source of bugs."}, ); Some(diag) } fn action(ctx: &RuleContext<Self>, suggestion: &Self::State) -> Option<JsRuleAction> { match suggestion { SuggestedFix::NoSuggestion => None, SuggestedFix::PrefixUnderscore => { let binding = ctx.query(); let mut mutation = ctx.root().begin(); let name = match binding { AnyJsIdentifierBinding::JsIdentifierBinding(binding) => { binding.name_token().ok()? } AnyJsIdentifierBinding::TsIdentifierBinding(binding) => { binding.name_token().ok()? } AnyJsIdentifierBinding::TsTypeParameterName(binding) => { binding.ident_token().ok()? } }; let name_trimmed = name.text_trimmed(); let new_name = format!("_{}", name_trimmed); let model = ctx.model(); mutation.rename_node_declaration(model, binding.clone(), &new_name); Some(JsRuleAction { mutation, category: ActionCategory::QuickFix, applicability: Applicability::MaybeIncorrect, message: markup! { "If this is intentional, prepend "<Emphasis>{name_trimmed}</Emphasis>" with an underscore." } .to_owned(), }) } } } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/semantic_analyzers/correctness/use_is_nan.rs
crates/rome_js_analyze/src/semantic_analyzers/correctness/use_is_nan.rs
use rome_analyze::context::RuleContext; use rome_analyze::{declare_rule, Rule, RuleDiagnostic}; use rome_js_semantic::SemanticModel; use rome_js_syntax::{ global_identifier, AnyJsExpression, AnyJsMemberExpression, JsBinaryExpression, JsCaseClause, JsSwitchStatement, TextRange, }; use rome_rowan::{declare_node_union, AstNode}; use crate::semantic_services::Semantic; declare_rule! { /// Require calls to `isNaN()` when checking for `NaN`. /// /// In JavaScript, `NaN` is a special value of the `Number` type. /// It’s used to represent any of the "not-a-number" values represented by the double-precision 64-bit format as specified by the IEEE Standard for Binary Floating-Point Arithmetic. /// /// Because `NaN` is unique in JavaScript by not being equal to anything, including itself, the results of comparisons to `NaN` are confusing: /// - `NaN` === `NaN` or `NaN` == `NaN` evaluate to false /// - `NaN` !== `NaN` or `NaN` != `NaN` evaluate to true /// /// Therefore, use `Number.isNaN()` or global `isNaN()` functions to test whether a value is `NaN`. /// /// Note that `Number.isNaN()` and `isNaN()` [have not the same behavior](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN#description). /// When the argument to `isNaN()` is not a number, the value is first coerced to a number. /// `Number.isNaN()` does not perform this coercion. /// Therefore, it is a more reliable way to test whether a value is `NaN`. /// /// Source: [use-isnan](https://eslint.org/docs/latest/rules/use-isnan). /// /// ## Examples /// /// ### Invalid /// /// ```js,expect_diagnostic /// 123 == NaN /// ``` /// /// ```js,expect_diagnostic /// 123 != NaN /// ``` /// /// ```js,expect_diagnostic /// switch(foo) { case (NaN): break; } /// ``` /// /// ```js,expect_diagnostic /// Number.NaN == "abc" /// ``` /// /// ### Valid /// /// ```js /// if (Number.isNaN(123) !== true) {} /// /// foo(Number.NaN / 2) /// /// switch(foo) {} /// ``` /// pub(crate) UseIsNan { version: "12.0.0", name: "useIsNan", recommended: true, } } declare_node_union! { pub(crate) UseIsNanQuery = JsBinaryExpression | JsCaseClause | JsSwitchStatement } enum Message { BinaryExpression, CaseClause, SwitchCase, } pub struct RuleState { range: TextRange, message_id: Message, } impl Message { fn as_str(&self) -> &str { match self { Self::BinaryExpression => "Use the Number.isNaN function to compare with NaN.", Self::CaseClause => "'case NaN' can never match. Use Number.isNaN before the switch.", Self::SwitchCase => "'switch(NaN)' can never match a case clause. Use Number.isNaN instead of the switch." } } } impl Rule for UseIsNan { type Query = Semantic<UseIsNanQuery>; type State = RuleState; type Signals = Option<Self::State>; type Options = (); fn run(ctx: &RuleContext<Self>) -> Self::Signals { let node = ctx.query(); let model = ctx.model(); match node { UseIsNanQuery::JsBinaryExpression(bin_expr) => { if bin_expr.is_comparison_operator() && (has_nan(bin_expr.left().ok()?, model) || has_nan(bin_expr.right().ok()?, model)) { return Some(RuleState { message_id: Message::BinaryExpression, range: bin_expr.range(), }); } } UseIsNanQuery::JsCaseClause(case_clause) => { let test = case_clause.test().ok()?; let range = test.range(); if has_nan(test, model) { return Some(RuleState { message_id: Message::CaseClause, range, }); } } UseIsNanQuery::JsSwitchStatement(switch_stmt) => { let discriminant = switch_stmt.discriminant().ok()?; let range = discriminant.range(); if has_nan(discriminant, model) { return Some(RuleState { message_id: Message::SwitchCase, range, }); } } } None } fn diagnostic(_: &RuleContext<Self>, state: &Self::State) -> Option<RuleDiagnostic> { Some(RuleDiagnostic::new( rule_category!(), state.range, state.message_id.as_str(), )) } } /// Checks whether an expression has `NaN`, `Number.NaN`, or `Number['NaN']`. fn has_nan(expr: AnyJsExpression, model: &SemanticModel) -> bool { (|| { let expr = expr.omit_parentheses(); let reference = if let Some((reference, name)) = global_identifier(&expr) { if name.text() != "NaN" { return None; } reference } else { let member_expr = AnyJsMemberExpression::cast_ref(expr.syntax())?; if member_expr.member_name()?.text() != "NaN" { return None; } let member_object = member_expr.object().ok()?.omit_parentheses(); let (reference, name) = global_identifier(&member_object.omit_parentheses())?; if name.text() != "Number" { return None; } reference }; model.binding(&reference).is_none().then_some(()) })() .is_some() }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false
rome/tools
https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/semantic_analyzers/correctness/no_render_return_value.rs
crates/rome_js_analyze/src/semantic_analyzers/correctness/no_render_return_value.rs
use crate::react::{is_react_call_api, ReactLibrary}; use crate::semantic_services::Semantic; use rome_analyze::context::RuleContext; use rome_analyze::{declare_rule, Rule, RuleDiagnostic}; use rome_console::markup; use rome_js_syntax::{JsCallExpression, JsExpressionStatement}; use rome_rowan::AstNode; declare_rule! { /// Prevent the usage of the return value of `React.render`. /// /// > `ReactDOM.render()` currently returns a reference to the root `ReactComponent` instance. However, using this return value is legacy /// and should be avoided because future versions of React may render components asynchronously in some cases. /// If you need a reference to the root `ReactComponent` instance, the preferred solution is to attach a [callback ref](https://reactjs.org/docs/refs-and-the-dom.html#callback-refs) /// to the root element. /// /// Source: [ReactDOM documentation](https://facebook.github.io/react/docs/react-dom.html#render) /// /// ## Examples /// /// ### Invalid /// /// ```jsx,expect_diagnostic /// const foo = ReactDOM.render(<div />, document.body); /// ``` /// /// ### Valid /// /// ```jsx /// ReactDOM.render(<div />, document.body); /// ``` pub(crate) NoRenderReturnValue { version: "0.10.0", name: "noRenderReturnValue", recommended: true, } } impl Rule for NoRenderReturnValue { type Query = Semantic<JsCallExpression>; type State = (); type Signals = Option<Self::State>; type Options = (); fn run(ctx: &RuleContext<Self>) -> Self::Signals { let node = ctx.query(); let callee = node.callee().ok()?; let model = ctx.model(); if is_react_call_api(callee, model, ReactLibrary::ReactDOM, "render") { let parent = node.syntax().parent()?; if !JsExpressionStatement::can_cast(parent.kind()) { return Some(()); } } None } fn diagnostic(ctx: &RuleContext<Self>, _state: &Self::State) -> Option<RuleDiagnostic> { let node = ctx.query(); Some(RuleDiagnostic::new(rule_category!(), node.syntax().text_trimmed_range(), markup! { "Do not depend on the value returned by the function "<Emphasis>"ReactDOM.render()"</Emphasis>"." }, ).note(markup! { "The returned value is legacy and future versions of react might return that value asynchronously." " Check the "<Hyperlink href="https://facebook.github.io/react/docs/react-dom.html#render">"React documentation"</Hyperlink>" for more information." }) ) } }
rust
MIT
392d188a49d70e495f13b1bb08cd7d9c43690f9b
2026-01-04T15:38:12.578592Z
false