Skip to content
This repository has been archived by the owner on Aug 31, 2023. It is now read-only.

Commit

Permalink
feat(rome_js_analyze): analyzer metadata (#4368)
Browse files Browse the repository at this point in the history
  • Loading branch information
ematipico authored Apr 12, 2023
1 parent 802bf8b commit 0133f40
Show file tree
Hide file tree
Showing 23 changed files with 330 additions and 125 deletions.
4 changes: 3 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,15 @@
+ import "module" with {}
```
- Fix an issue where JSON formatter does not respect `lineWidth` for arrays [#4351](https://github.com/rome/tools/issues/4351)

### Linter

#### Other changes

- Code actions are formatted using Rome's formatter. If the formatter is disabled,
the code action is not formatted.
- Fixed an issue that [`useShorthandArrayType`](https://docs.rome.tools/lint/rules/useShorthandArrayType) rule did not handle nested ReadonlyArray types correctly and erroneously reported TsObjectType [#4354](https://github.com/rome/tools/issues/4353)
- Fixed an issue that [`useShorthandArrayType`](https://docs.rome.tools/lint/rules/useShorthandArrayType) rule did not handle nested ReadonlyArray types correctly and erroneously reported TsObjectType [#4354](https://github.com/rome/tools/issues/4353).
- [`noUndeclaredVariables`](https://docs.rome.tools/lint/rules/noUndeclaredVariables) detects globals based on the file type.

- Fix an issue when `noUndeclaredVariables` incorrectly identifies `AggregateError` as an undeclared variable. [#4365](https://github.com/rome/tools/issues/4365)
#### New rules
Expand Down
16 changes: 16 additions & 0 deletions crates/rome_analyze/src/context.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use crate::{registry::RuleRoot, FromServices, Queryable, Rule, RuleKey, ServiceBag};
use rome_diagnostics::{Error, Result};
use std::ops::Deref;
use std::path::Path;

type RuleQueryResult<R> = <<R as Rule>::Query as Queryable>::Output;
type RuleServiceBag<R> = <<R as Rule>::Query as Queryable>::Services;
Expand All @@ -17,6 +18,7 @@ where
bag: &'a ServiceBag,
services: RuleServiceBag<R>,
globals: &'a [&'a str],
file_path: &'a Path,
}

impl<'a, R> RuleContext<'a, R>
Expand All @@ -28,6 +30,7 @@ where
root: &'a RuleRoot<R>,
services: &'a ServiceBag,
globals: &'a [&'a str],
file_path: &'a Path,
) -> Result<Self, Error> {
let rule_key = RuleKey::rule::<R>();
Ok(Self {
Expand All @@ -36,6 +39,7 @@ where
bag: services,
services: FromServices::from_services(&rule_key, services)?,
globals,
file_path,
})
}

Expand Down Expand Up @@ -97,6 +101,18 @@ where
pub fn is_global(&self, text: &str) -> bool {
self.globals.contains(&text)
}

/// Returns the source type of the current file
pub fn source_type<T: 'static>(&self) -> &T {
self.bag
.get_service::<T>()
.expect("Source type is not registered")
}

/// The file path of the current file
pub fn file_path(&self) -> &Path {
self.file_path
}
}

impl<'a, R> Deref for RuleContext<'a, R>
Expand Down
7 changes: 7 additions & 0 deletions crates/rome_analyze/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use std::cmp::Ordering;
use std::collections::{BTreeMap, BinaryHeap};
use std::fmt::{Debug, Display, Formatter};
use std::ops;
use std::path::Path;

mod categories;
pub mod context;
Expand Down Expand Up @@ -77,6 +78,7 @@ pub struct AnalyzerContext<'a, L: Language> {
pub services: ServiceBag,
pub range: Option<TextRange>,
pub globals: &'a [&'a str],
pub file_path: &'a Path,
}

impl<'analyzer, L, Matcher, Break, Diag> Analyzer<'analyzer, L, Matcher, Break, Diag>
Expand Down Expand Up @@ -142,6 +144,7 @@ where
range: ctx.range,
globals: ctx.globals,
apply_suppression_comment,
file_path: ctx.file_path,
};

// The first phase being run will inspect the tokens and parse the
Expand Down Expand Up @@ -220,6 +223,8 @@ struct PhaseRunner<'analyzer, 'phase, L: Language, Matcher, Break, Diag> {
range: Option<TextRange>,
/// Options passed to the analyzer
globals: &'phase [&'phase str],
/// The [Path] of the current file
file_path: &'phase Path,
}

/// Single entry for a suppression comment in the `line_suppressions` buffer
Expand Down Expand Up @@ -279,6 +284,7 @@ where
signal_queue: &mut self.signal_queue,
apply_suppression_comment: self.apply_suppression_comment,
globals: self.globals,
file_path: self.file_path,
};

visitor.visit(&node_event, ctx);
Expand All @@ -304,6 +310,7 @@ where
signal_queue: &mut self.signal_queue,
apply_suppression_comment: self.apply_suppression_comment,
globals: self.globals,
file_path: self.file_path,
};

visitor.visit(&event, ctx);
Expand Down
4 changes: 4 additions & 0 deletions crates/rome_analyze/src/matcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use crate::{
SuppressionCommentEmitter,
};
use rome_rowan::{Language, TextRange};
use std::path::Path;
use std::{
any::{Any, TypeId},
cmp::Ordering,
Expand All @@ -27,6 +28,7 @@ pub struct MatchQueryParams<'phase, 'query, L: Language> {
pub signal_queue: &'query mut BinaryHeap<SignalEntry<'phase, L>>,
pub apply_suppression_comment: SuppressionCommentEmitter<L>,
pub globals: &'phase [&'phase str],
pub file_path: &'phase Path,
}

/// Wrapper type for a [QueryMatch]
Expand Down Expand Up @@ -197,6 +199,7 @@ where
#[cfg(test)]
mod tests {
use std::convert::Infallible;
use std::path::Path;

use rome_diagnostics::{category, DiagnosticExt};
use rome_diagnostics::{Diagnostic, Severity};
Expand Down Expand Up @@ -381,6 +384,7 @@ mod tests {
range: None,
services: ServiceBag::default(),
globals: &[],
file_path: Path::new(""),
};

let result: Option<Never> = analyzer.run(ctx);
Expand Down
13 changes: 9 additions & 4 deletions crates/rome_analyze/src/options.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
use crate::RuleKey;
use serde::Deserialize;
use std::collections::HashMap;
use std::fmt::Debug;
use std::path::PathBuf;

/// A convenient new type data structure to store the options that belong to a rule
#[derive(Debug, Clone, Deserialize)]
#[derive(Debug, Default, Deserialize)]
pub struct RuleOptions(String);

impl RuleOptions {
Expand All @@ -19,7 +21,7 @@ impl RuleOptions {
}

/// A convenient new type data structure to insert and get rules
#[derive(Debug, Clone, Default)]
#[derive(Debug, Default)]
pub struct AnalyzerRules(HashMap<RuleKey, RuleOptions>);

impl AnalyzerRules {
Expand All @@ -35,7 +37,7 @@ impl AnalyzerRules {
}

/// A data structured derived from the `rome.json` file
#[derive(Debug, Clone, Default)]
#[derive(Debug, Default)]
pub struct AnalyzerConfiguration {
/// A list of rules and their options
pub rules: AnalyzerRules,
Expand All @@ -47,8 +49,11 @@ pub struct AnalyzerConfiguration {
}

/// A set of information useful to the analyzer infrastructure
#[derive(Debug, Clone, Default)]
#[derive(Debug, Default)]
pub struct AnalyzerOptions {
/// A data structured derived from the [`rome.json`] file
pub configuration: AnalyzerConfiguration,

/// The file that is being analyzed
pub file_path: PathBuf,
}
17 changes: 11 additions & 6 deletions crates/rome_analyze/src/registry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -426,12 +426,16 @@ impl<L: Language + Default> RegistryRule<L> {
// if the query doesn't match
let query_result = params.query.downcast_ref().unwrap();
let query_result = <R::Query as Queryable>::unwrap_match(params.services, query_result);
let ctx =
match RuleContext::new(&query_result, params.root, params.services, params.globals)
{
Ok(ctx) => ctx,
Err(error) => return Err(error),
};
let ctx = match RuleContext::new(
&query_result,
params.root,
params.services,
params.globals,
params.file_path,
) {
Ok(ctx) => ctx,
Err(error) => return Err(error),
};

for result in R::run(&ctx) {
let text_range =
Expand All @@ -446,6 +450,7 @@ impl<L: Language + Default> RegistryRule<L> {
params.services,
params.apply_suppression_comment,
params.globals,
params.file_path,
));

params.signal_queue.push(SignalEntry {
Expand Down
23 changes: 20 additions & 3 deletions crates/rome_analyze/src/signals.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ use rome_rowan::{BatchMutation, Language};
use std::borrow::Cow;
use std::iter::FusedIterator;
use std::marker::PhantomData;
use std::path::Path;
use std::vec::IntoIter;

/// Event raised by the analyzer when a [Rule](crate::Rule)
Expand Down Expand Up @@ -245,6 +246,7 @@ pub(crate) struct RuleSignal<'phase, R: Rule> {
apply_suppression_comment: SuppressionCommentEmitter<RuleLanguage<R>>,
/// A list of strings that are considered "globals" inside the analyzer
globals: &'phase [&'phase str],
file_path: &'phase Path,
}

impl<'phase, R> RuleSignal<'phase, R>
Expand All @@ -260,6 +262,7 @@ where
<<R as Rule>::Query as Queryable>::Language,
>,
globals: &'phase [&'phase str],
file_path: &'phase Path,
) -> Self {
Self {
root,
Expand All @@ -268,6 +271,7 @@ where
services,
apply_suppression_comment,
globals,
file_path,
}
}
}
Expand All @@ -277,14 +281,27 @@ where
R: Rule + 'static,
{
fn diagnostic(&self) -> Option<AnalyzerDiagnostic> {
let ctx =
RuleContext::new(&self.query_result, self.root, self.services, self.globals).ok()?;
let ctx = RuleContext::new(
&self.query_result,
self.root,
self.services,
self.globals,
self.file_path,
)
.ok()?;

R::diagnostic(&ctx, &self.state).map(AnalyzerDiagnostic::from)
}

fn actions(&self) -> AnalyzerActionIter<RuleLanguage<R>> {
let ctx = RuleContext::new(&self.query_result, self.root, self.services, self.globals).ok();
let ctx = RuleContext::new(
&self.query_result,
self.root,
self.services,
self.globals,
self.file_path,
)
.ok();
if let Some(ctx) = ctx {
let mut actions = Vec::new();
if let Some(action) = R::action(&ctx, &self.state) {
Expand Down
2 changes: 2 additions & 0 deletions crates/rome_analyze/src/syntax.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ mod tests {
AstNode, SyntaxNode,
};
use std::convert::Infallible;
use std::path::Path;

use crate::{
matcher::MatchQueryParams, registry::Phases, Analyzer, AnalyzerContext, AnalyzerSignal,
Expand Down Expand Up @@ -165,6 +166,7 @@ mod tests {
range: None,
services: ServiceBag::default(),
globals: &[],
file_path: Path::new(""),
};

let result: Option<Never> = analyzer.run(ctx);
Expand Down
3 changes: 3 additions & 0 deletions crates/rome_analyze/src/visitor.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use std::collections::BinaryHeap;
use std::path::Path;

use rome_rowan::{AstNode, Language, SyntaxNode, TextRange, WalkEvent};

Expand All @@ -18,6 +19,7 @@ pub struct VisitorContext<'phase, 'query, L: Language> {
pub(crate) signal_queue: &'query mut BinaryHeap<SignalEntry<'phase, L>>,
pub apply_suppression_comment: SuppressionCommentEmitter<L>,
pub globals: &'phase [&'phase str],
pub file_path: &'phase Path,
}

impl<'phase, 'query, L: Language> VisitorContext<'phase, 'query, L> {
Expand All @@ -30,6 +32,7 @@ impl<'phase, 'query, L: Language> VisitorContext<'phase, 'query, L> {
signal_queue: self.signal_queue,
apply_suppression_comment: self.apply_suppression_comment,
globals: self.globals,
file_path: self.file_path,
})
}
}
Expand Down
Loading

0 comments on commit 0133f40

Please sign in to comment.