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

feat(rome_js_analyze): new lint rule: useImportRestrictions #4700

Merged
merged 9 commits into from
Jul 21, 2023
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 19 additions & 19 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ rome_aria_metadata = { path = "./crates/rome_aria_metadata" }
rome_cli = { path = "./crates/rome_cli" }
rome_console = { version = "0.0.1", path = "./crates/rome_console" }
rome_control_flow = { path = "./crates/rome_control_flow" }
rome_css_factory = { path = "./crates/rome_css_factory" }
rome_css_parser = { path = "./crates/rome_css_parser" }
rome_css_syntax = { path = "./crates/rome_css_syntax" }
rome_deserialize = { version = "0.0.0", path = "./crates/rome_deserialize" }
rome_diagnostics = { version = "0.0.1", path = "./crates/rome_diagnostics" }
rome_diagnostics_categories = { version = "0.0.1", path = "./crates/rome_diagnostics_categories" }
Expand All @@ -51,9 +54,6 @@ rome_json_factory = { version = "0.0.1", path = "./crates/rome_json_fa
rome_json_formatter = { path = "./crates/rome_json_formatter" }
rome_json_parser = { path = "./crates/rome_json_parser" }
rome_json_syntax = { version = "0.0.1", path = "./crates/rome_json_syntax" }
rome_css_factory = { path = "./crates/rome_css_factory" }
rome_css_parser = { path = "./crates/rome_css_parser" }
rome_css_syntax = { path = "./crates/rome_css_syntax" }
rome_lsp = { path = "./crates/rome_lsp" }
rome_markup = { version = "0.0.1", path = "./crates/rome_markup" }
rome_migrate = { path = "./crates/rome_migrate" }
Expand All @@ -65,24 +65,24 @@ rome_text_size = { version = "0.0.1", path = "./crates/rome_text_si
tests_macros = { path = "./crates/tests_macros" }

# Crates needed in the workspace
ematipico marked this conversation as resolved.
Show resolved Hide resolved
bitflags = "2.3.1"
bpaf = { version = "0.9.2", features = ["derive"] }
countme = "3.0.1"
dashmap = "5.4.0"
indexmap = "1.9.3"
insta = "1.29.0"
lazy_static = "1.4.0"
quickcheck = "1.0.3"
quickcheck_macros = "1.0.0"
quickcheck = "1.0.3"
bitflags = "2.3.1"
bpaf = { version = "0.9.2", features = ["derive"] }
countme = "3.0.1"
dashmap = "5.4.0"
indexmap = "1.9.3"
insta = "1.29.0"
lazy_static = "1.4.0"
quote = { version = "1.0.28" }
rustc-hash = "1.1.0"
schemars = { version = "0.8.12" }
serde = { version = "1.0.163", features = ["derive"], default-features = false }
serde_json = "1.0.96"
smallvec = { version = "1.10.0", features = ["union", "const_new"] }
tracing = { version = "0.1.37", default-features = false, features = ["std"] }
quote = { version = "1.0.28" }
rustc-hash = "1.1.0"
schemars = { version = "0.8.12" }
serde = { version = "1.0.163", features = ["derive"], default-features = false }
serde_json = "1.0.96"
smallvec = { version = "1.10.0", features = ["union", "const_new"] }
tracing = { version = "0.1.37", default-features = false, features = ["std"] }
# pinning to version 1.18 to avoid multiple versions of windows-sys as dependency
tokio = { version = "~1.18.5" }
tokio = { version = "~1.18.5" }


[profile.dev.package.rome_wasm]
Expand Down
39 changes: 0 additions & 39 deletions crates/rome_analyze/CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -343,45 +343,6 @@ This allows the rule to be configured inside `rome.json` file like:
}
```

In this specific case, we don't want the configuration to replace all the standard React hooks configuration,
so to have more control on the deserialization of options, we can implement the trait `DeserializableRuleOptions`.

In the example below we also deserialize to a struct with a more user-friendly schema.

This code run only once when the analyzer is first called.

```rust,ignore

impl DeserializableRuleOptions for ReactExtensiveDependenciesOptions {
fn try_from(value: serde_json::Value) -> Result<Self, serde_json::Error> {
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct Options {
#[serde(default)]
hooks: Vec<(String, usize, usize)>,
#[serde(default)]
stables: HashSet<StableReactHookConfiguration>,
}

let options: Options = serde_json::from_value(value)?;

let mut default = ReactExtensiveDependenciesOptions::default();
for (k, closure_index, dependencies_index) in options.hooks.into_iter() {
default.hooks_config.insert(
k,
ReactHookConfiguration {
closure_index,
dependencies_index,
},
);
}
default.stable_config.extend(options.stables.into_iter());

Ok(default)
}
}
```

A rule can retrieve its option with:

```rust,ignore
Expand Down
2 changes: 1 addition & 1 deletion crates/rome_css_parser/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@ version = "0.0.1"

[dependencies]
rome_console = { workspace = true }
rome_css_syntax = { workspace = true }
rome_diagnostics = { workspace = true }
rome_js_unicode_table = { workspace = true }
rome_css_syntax = { workspace = true }
rome_parser = { workspace = true }
rome_rowan = { workspace = true }
tracing = { workspace = true }
Expand Down
1 change: 1 addition & 0 deletions crates/rome_diagnostics_categories/src/categories.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ define_categories! {
"lint/nursery/useGroupedTypeImport": "https://docs.rome.tools/lint/rules/useGroupedTypeImport",
"lint/nursery/useHeadingContent": "https://docs.rome.tools/lint/rules/useHeadingContent",
"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/useIsNan": "https://docs.rome.tools/lint/rules/useIsNan",
"lint/nursery/useLiteralEnumMembers": "https://docs.rome.tools/lint/rules/useLiteralEnumMembers",
Expand Down
2 changes: 2 additions & 0 deletions crates/rome_js_analyze/src/analyzers/nursery.rs

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

Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
use rome_analyze::{context::RuleContext, declare_rule, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_js_syntax::JsModuleSource;
use rome_rowan::{AstNode, SyntaxTokenText};

const INDEX_BASENAMES: &[&str] = &["index", "mod"];

const SOURCE_EXTENSIONS: &[&str] = &["js", "ts", "cjs", "cts", "mjs", "mts", "jsx", "tsx"];
ematipico marked this conversation as resolved.
Show resolved Hide resolved
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we consider .d.ts too? Genuine question, I don't know it :)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think it makes sense to be honest, since you can't import "some_file.d.ts".


declare_rule! {
/// Disallows package private imports.
///
/// This rules enforces the following restrictions:
///
/// ## Package private visibility
///
/// All exported symbols, such as types, functions or other things that may be exported, are
/// considered to be "package private". This means that modules that reside in the same
/// directory, as well as submodules of those "sibling" modules, are allowed to import them,
/// while any other modules that are further away in the file system are restricted from
/// importing them. A symbol's visibility may be extended by re-exporting from an index file.
///
/// Notes:
///
/// * This rule only applies to relative imports. External dependencies are exempted.
/// * This rule only applies to imports for JavaScript and TypeScript files. Imports for
/// resources such as images or CSS files are exempted.
///
/// Source: https://github.com/uhyo/eslint-plugin-import-access
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// // Attempt to import from `foo.js` from outside its `sub` module.
/// import { fooPackageVariable } from "./sub/foo.js";
///
/// // Attempt to import from `bar.ts` from outside its `aunt` module.
/// import { barPackageVariable } from "../aunt/bar.ts";
///
/// // Assumed to resolve to a JS/TS file.
/// import { fooPackageVariable } from "./sub/foo";
///
/// // If the `sub/foo` module is inaccessible, so is its index file.
/// import { fooPackageVariable } from "./sub/foo/index.js";
/// ```
///
/// ### Valid
///
/// ```js
/// // Imports within the same module are always allowed.
/// import { fooPackageVariable } from "./foo.js";
///
/// // Resources (anything other than JS/TS files) are exempt.
/// import { barResource } from "../aunt/bar.png";
///
/// // A parent index file is accessible like other modules.
/// import { internal } from "../../index.js";
///
/// // If the `sub` module is accessible, so is its index file.
/// import { subPackageVariable } from "./sub/index.js";
///
/// // Library imports are exempt.
/// import useAsync from "react-use/lib/useAsync";
/// ```
///
pub(crate) UseImportRestrictions {
version: "next",
name: "useImportRestrictions",
recommended: false,
}
}

impl Rule for UseImportRestrictions {
type Query = Ast<JsModuleSource>;
type State = ImportRestrictionsState;
type Signals = Option<Self::State>;
type Options = ();

fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let binding = ctx.query();
let Ok(path) = binding.inner_string_text() else {
return None;
};

get_restricted_import(&path)
}

fn diagnostic(ctx: &RuleContext<Self>, state: &Self::State) -> Option<RuleDiagnostic> {
let ImportRestrictionsState { path, suggestion } = state;

let diagnostic = RuleDiagnostic::new(
rule_category!(),
ctx.query().range(),
markup! {
"Importing package private symbols is prohibited from outside the module directory."
},
)
.note(markup! {
"Please import from "<Emphasis>{suggestion}</Emphasis>" instead "
"(you may need to re-export the symbol(s) from "<Emphasis>{path}</Emphasis>")."
});

Some(diagnostic)
}
}

pub(crate) struct ImportRestrictionsState {
/// The path that is being restricted.
path: String,

/// Suggestion from which to import instead.
suggestion: String,
}

fn get_restricted_import(module_path: &SyntaxTokenText) -> Option<ImportRestrictionsState> {
if !module_path.starts_with('.') {
return None;
}

let mut path_parts: Vec<&str> = module_path.text().split('/').collect();
arendjr marked this conversation as resolved.
Show resolved Hide resolved
let mut index_filename = None;

if let Some(extension) = get_extension(&path_parts) {
if !SOURCE_EXTENSIONS.contains(&extension) {
return None; // Resource files are exempt.
}

if let Some(basename) = get_basename(&path_parts) {
if INDEX_BASENAMES.contains(&basename) {
// We pop the index file because it shouldn't count as a path,
// component, but we store the file name so we can add it to
// both the reported path and the suggestion.
index_filename = path_parts.last().cloned();
path_parts.pop();
}
}
}

let is_restricted = path_parts
.iter()
.filter(|&&part| part != "." && part != "..")
.count()
> 1;
if !is_restricted {
return None;
}

let mut suggestion_parts = path_parts[..path_parts.len() - 1].to_vec();

// Push the index file if it exists. This makes sure the reported path
// matches the import path exactly.
if let Some(index_filename) = index_filename {
path_parts.push(index_filename);

// Assumes the user probably wants to use an index file that has the
// same name as the original.
suggestion_parts.push(index_filename);
}

Some(ImportRestrictionsState {
path: path_parts.join("/"),
suggestion: suggestion_parts.join("/"),
})
}

fn get_basename<'a>(path_parts: &'_ [&'a str]) -> Option<&'a str> {
path_parts.last().map(|&part| match part.find('.') {
Some(dot_index) if dot_index > 0 && dot_index < part.len() - 1 => &part[..dot_index],
_ => part,
})
}

fn get_extension<'a>(path_parts: &'_ [&'a str]) -> Option<&'a str> {
path_parts.last().and_then(|part| match part.find('.') {
Some(dot_index) if dot_index > 0 && dot_index < part.len() - 1 => {
Some(&part[dot_index + 1..])
}
_ => None,
})
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// Attempt to import from `foo.js` from outside its `sub` module.
import { fooPackageVariable } from "./sub/foo.js";

// Attempt to import from `bar.ts` from outside its `aunt` module.
import { barPackageVariable } from "../aunt/bar.ts";

// Assumed to resolve to a JS/TS file.
import { fooPackageVariable } from "./sub/foo";

// If the `sub/foo` module is inaccessible, so is its index file.
import { fooPackageVariable } from "./sub/foo/index.js";
Loading