Skip to content

Commit

Permalink
Merge branch 'main' into feat/vitest-prefer-each
Browse files Browse the repository at this point in the history
  • Loading branch information
DonIsaac authored Aug 26, 2024
2 parents 053676e + ce454cf commit 6dd8374
Show file tree
Hide file tree
Showing 29 changed files with 1,646 additions and 1,298 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: taiki-e/checkout-action@v1
- uses: crate-ci/typos@v1.23.6
- uses: crate-ci/typos@v1.24.1
with:
files: .

Expand Down Expand Up @@ -189,7 +189,7 @@ jobs:
with:
restore-cache: false
if: steps.filter.outputs.src == 'true'
- uses: cargo-bins/cargo-binstall@v1.10.2
- uses: cargo-bins/cargo-binstall@v1.10.3
if: steps.filter.outputs.src == 'true'
- run: cargo binstall --no-confirm cargo-shear@1
if: steps.filter.outputs.src == 'true'
Expand Down
9 changes: 8 additions & 1 deletion Cargo.lock

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

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,7 @@ seq-macro = "0.3.5"
serde = "1.0.206"
serde_json = "1.0.124"
serde-wasm-bindgen = "0.6.5"
simdutf8 = { version = "0.1.4", features = ["aarch64_neon"] }
similar = "2.6.0"
syn = { version = "2.0.74", default-features = false }
tempfile = "3.12.0"
Expand Down
1 change: 1 addition & 0 deletions crates/oxc_ast/src/ast/js.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2265,6 +2265,7 @@ pub enum AccessorPropertyType {
#[derive(Debug, Hash)]
#[generate_derive(CloneIn, GetSpan, GetSpanMut)]
#[cfg_attr(feature = "serialize", derive(Serialize, Tsify))]
#[serde(rename_all = "camelCase")]
pub struct AccessorProperty<'a> {
pub r#type: AccessorPropertyType,
#[serde(flatten)]
Expand Down
2 changes: 1 addition & 1 deletion crates/oxc_ast/src/ast/ts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -358,7 +358,7 @@ pub struct TSIntersectionType<'a> {
#[derive(Debug, Hash)]
#[generate_derive(CloneIn, GetSpan, GetSpanMut)]
#[cfg_attr(feature = "serialize", derive(Serialize, Tsify))]
#[serde(tag = "type")]
#[serde(tag = "type", rename_all = "camelCase")]
pub struct TSParenthesizedType<'a> {
#[serde(flatten)]
pub span: Span,
Expand Down
12 changes: 8 additions & 4 deletions crates/oxc_codegen/examples/codegen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,19 @@ fn main() -> std::io::Result<()> {
let path = Path::new(&name);
let source_text = std::fs::read_to_string(path)?;
let source_type = SourceType::from_path(path).unwrap();
let allocator = Allocator::default();

let Some(ret) = parse(&allocator, &source_text, source_type) else { return Ok(()) };
let mut allocator = Allocator::default();

let printed = {
let Some(ret) = parse(&allocator, &source_text, source_type) else { return Ok(()) };
codegen(&source_text, &ret, minify)
};
println!("First time:");
let printed = codegen(&source_text, &ret, minify);
println!("{printed}");

if twice {
// Reset the allocator as we don't need the first AST any more
allocator.reset();

let Some(ret) = parse(&allocator, &printed, source_type) else { return Ok(()) };
println!("Second time:");
let printed = codegen(&printed, &ret, minify);
Expand Down
11 changes: 6 additions & 5 deletions crates/oxc_codegen/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -412,11 +412,12 @@ impl<'a> Codegen<'a> {
}

fn print_list<T: Gen>(&mut self, items: &[T], ctx: Context) {
for (index, item) in items.iter().enumerate() {
if index != 0 {
self.print_comma();
self.print_soft_space();
}
let mut iter = items.iter();
let Some(item) = iter.next() else { return };
item.gen(self, ctx);
for item in iter {
self.print_comma();
self.print_soft_space();
item.gen(self, ctx);
}
}
Expand Down
1 change: 1 addition & 0 deletions crates/oxc_linter/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ once_cell = { workspace = true }
memchr = { workspace = true }
json-strip-comments = { workspace = true }
schemars = { workspace = true, features = ["indexmap2"] }
simdutf8 = { workspace = true }

[dev-dependencies]
insta = { workspace = true }
Expand Down
6 changes: 4 additions & 2 deletions crates/oxc_linter/src/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@ pub use self::{
settings::{jsdoc::JSDocPluginSettings, OxlintSettings},
};
use crate::{
rules::RuleEnum, utils::is_jest_rule_adapted_to_vitest, AllowWarnDeny, RuleWithSeverity,
rules::RuleEnum,
utils::{is_jest_rule_adapted_to_vitest, read_to_string},
AllowWarnDeny, RuleWithSeverity,
};

/// Oxlint Configuration File
Expand Down Expand Up @@ -68,7 +70,7 @@ impl OxlintConfig {
///
/// * Parse Failure
pub fn from_file(path: &Path) -> Result<Self, OxcDiagnostic> {
let mut string = std::fs::read_to_string(path).map_err(|e| {
let mut string = read_to_string(path).map_err(|e| {
OxcDiagnostic::error(format!("Failed to parse config {path:?} with error {e:?}"))
})?;

Expand Down
37 changes: 18 additions & 19 deletions crates/oxc_linter/src/rules/eslint/no_redeclare.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use oxc_ast::{
use oxc_diagnostics::OxcDiagnostic;
use oxc_macros::declare_oxc_lint;
use oxc_span::Span;
use oxc_syntax::symbol::SymbolId;

use crate::{context::LintContext, rule::Rule};

Expand Down Expand Up @@ -56,33 +57,31 @@ impl Rule for NoRedeclare {
Self { built_in_globals }
}

fn run_once(&self, ctx: &LintContext) {
fn run_on_symbol(&self, symbol_id: SymbolId, ctx: &LintContext) {
let symbol_table = ctx.semantic().symbols();

for symbol_id in ctx.symbols().iter() {
let decl = symbol_table.get_declaration(symbol_id);
let symbol_name = symbol_table.get_name(symbol_id);
match ctx.nodes().kind(decl) {
AstKind::VariableDeclarator(var) => {
if let BindingPatternKind::BindingIdentifier(ident) = &var.id.kind {
if symbol_name == ident.name.as_str() {
for span in ctx.symbols().get_redeclarations(symbol_id) {
self.report_diagnostic(ctx, *span, ident);
}
let decl_node_id = symbol_table.get_declaration(symbol_id);
match ctx.nodes().kind(decl_node_id) {
AstKind::VariableDeclarator(var) => {
if let BindingPatternKind::BindingIdentifier(ident) = &var.id.kind {
let symbol_name = symbol_table.get_name(symbol_id);
if symbol_name == ident.name.as_str() {
for span in ctx.symbols().get_redeclarations(symbol_id) {
self.report_diagnostic(ctx, *span, ident);
}
}
}
AstKind::FormalParameter(param) => {
if let BindingPatternKind::BindingIdentifier(ident) = &param.pattern.kind {
if symbol_name == ident.name.as_str() {
for span in ctx.symbols().get_redeclarations(symbol_id) {
self.report_diagnostic(ctx, *span, ident);
}
}
AstKind::FormalParameter(param) => {
if let BindingPatternKind::BindingIdentifier(ident) = &param.pattern.kind {
let symbol_name = symbol_table.get_name(symbol_id);
if symbol_name == ident.name.as_str() {
for span in ctx.symbols().get_redeclarations(symbol_id) {
self.report_diagnostic(ctx, *span, ident);
}
}
}
_ => {}
}
_ => {}
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,26 @@ impl NoUnusedVars {
return fixer.noop();
}

let Some(AstKind::VariableDeclaration(declaration)) =
symbol.nodes().parent_node(decl_id).map(AstNode::kind)
else {
panic!("VariableDeclarator nodes should always be direct children of VariableDeclaration nodes");
let Some(parent) = symbol.nodes().parent_node(decl_id).map(AstNode::kind) else {
#[cfg(debug_assertions)]
panic!("VariableDeclarator nodes should always have a parent node");
#[cfg(not(debug_assertions))]
return fixer.noop();
};
let (span, declarations) = match parent {
AstKind::VariableDeclaration(decl) => (decl.span, &decl.declarations),
AstKind::UsingDeclaration(decl) => {
if decl.is_await {
return fixer.noop();
}
(decl.span, &decl.declarations)
}
_ => {
#[cfg(debug_assertions)]
panic!("VariableDeclarator nodes should always be direct children of VariableDeclaration or UsingDeclaration nodes");
#[cfg(not(debug_assertions))]
return fixer.noop();
}
};

// `true` even if references aren't considered a usage.
Expand All @@ -48,18 +64,16 @@ impl NoUnusedVars {
// for `let x = 1;` or `const { x } = obj; the whole declaration can
// be removed, but for `const { x, y } = obj;` or `let x = 1, y = 2`
// we need to keep the other declarations
let has_neighbors = declaration.declarations.len() > 1;
debug_assert!(!declaration.declarations.is_empty());
let has_neighbors = declarations.len() > 1;
debug_assert!(!declarations.is_empty());
let binding_info = symbol.get_binding_info(&decl.id.kind);

match binding_info {
BindingInfo::SingleDestructure | BindingInfo::NotDestructure => {
if has_neighbors {
return symbol
.delete_from_list(fixer, &declaration.declarations, decl)
.dangerously();
return symbol.delete_from_list(fixer, declarations, decl).dangerously();
}
return fixer.delete(declaration).dangerously();
return fixer.delete_range(span).dangerously();
}
BindingInfo::MultiDestructure(mut span, is_object, is_last) => {
let source_after = &fixer.source_text()[(span.end as usize)..];
Expand Down
10 changes: 10 additions & 0 deletions crates/oxc_linter/src/rules/eslint/no_unused_vars/tests/oxc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -370,6 +370,16 @@ fn test_vars_catch() {
.test_and_snapshot();
}

#[test]
fn test_vars_using() {
let pass = vec![("using a = 1; console.log(a)", None)];

let fail = vec![("using a = 1;", None)];

Tester::new(NoUnusedVars::NAME, pass, fail)
.with_snapshot_suffix("oxc-vars-using")
.test_and_snapshot();
}
#[test]
fn test_functions() {
let pass = vec![
Expand Down
27 changes: 21 additions & 6 deletions crates/oxc_linter/src/rules/jest/prefer_to_have_length.rs
Original file line number Diff line number Diff line change
Expand Up @@ -144,12 +144,14 @@ impl PreferToHaveLength {

ctx.diagnostic_with_fix(use_to_have_length(matcher.span), |fixer| {
let code = Self::build_code(fixer, static_mem_expr, kind, property_name);
let end = if call_expr.arguments.len() > 0 {
call_expr.arguments.first().unwrap().span().start
} else {
matcher.span.end
};
fixer.replace(Span::new(call_expr.span.start, end - 1), code)
let offset = u32::try_from(
fixer
.source_range(Span::new(matcher.span.end, call_expr.span().end))
.find('(')
.unwrap(),
)
.unwrap();
fixer.replace(Span::new(call_expr.span.start, matcher.span.end + offset), code)
});
}

Expand Down Expand Up @@ -217,6 +219,10 @@ fn tests() {
"expect((meta.get('pages') as YArray<unknown>).length).toBe((originalMeta.get('pages') as YArray<unknown>).length);",
None
),
(
"expect(assetTypeContainer.getElementsByTagName('time').length).toEqual(
0,
);", None)
];

let fix = vec![
Expand Down Expand Up @@ -247,6 +253,15 @@ fn tests() {
"expect((meta.get('pages') as YArray<unknown>)).toHaveLength((originalMeta.get('pages') as YArray<unknown>).length);",
None
),
(
"expect(assetTypeContainer.getElementsByTagName('time').length).toEqual(
0,
);",
"expect(assetTypeContainer.getElementsByTagName('time')).toHaveLength(
0,
);",
None
)
];

Tester::new(PreferToHaveLength::NAME, pass, fail)
Expand Down
33 changes: 28 additions & 5 deletions crates/oxc_linter/src/rules/unicorn/prefer_set_size.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ use oxc_diagnostics::OxcDiagnostic;
use oxc_macros::declare_oxc_lint;
use oxc_span::Span;

use crate::{ast_util::get_declaration_of_variable, context::LintContext, rule::Rule, AstNode};
use crate::{
ast_util::get_declaration_of_variable, context::LintContext, fixer::Fix, rule::Rule, AstNode,
};

fn prefer_set_size_diagnostic(span0: Span) -> OxcDiagnostic {
OxcDiagnostic::warn(
Expand Down Expand Up @@ -38,7 +40,7 @@ declare_oxc_lint!(
/// ```
PreferSetSize,
correctness,
pending
fix
);

impl Rule for PreferSetSize {
Expand Down Expand Up @@ -68,13 +70,22 @@ impl Rule for PreferSetSize {
return;
};

let maybe_set = &spread_element.argument.without_parenthesized();
let maybe_set = &spread_element.argument.get_inner_expression();

if !is_set(maybe_set, ctx) {
return;
}

ctx.diagnostic(prefer_set_size_diagnostic(span));
ctx.diagnostic_with_fix(prefer_set_size_diagnostic(span), |_fixer| {
vec![
// remove [...
Fix::delete(Span::new(array_expr.span.start, spread_element.span.start + 3)),
// remove everything after the end of the spread element (including the `]` )
Fix::delete(Span::new(spread_element.span.end, array_expr.span.end)),
// replace .length with .size
Fix::new("size", span),
]
});
}
}

Expand Down Expand Up @@ -157,5 +168,17 @@ fn test() {
r"[...new /* comment */ Set(array)].length",
];

Tester::new(PreferSetSize::NAME, pass, fail).test_and_snapshot();
let fix = vec![
(r"[...new Set(array)].length", r"new Set(array).size"),
(r"[...new Set(array),].length", r"new Set(array).size"),
(r"[...(( new Set(array) ))].length", r"(( new Set(array) )).size"),
(r"[...(( new Set(array as foo) ))].length", r"(( new Set(array as foo) )).size"),
(r"[...(( new Set(array) as foo ))].length", r"(( new Set(array) as foo )).size"),
(
r"[...(( new Set(array) as foo ) ) ] .length;",
r"(( new Set(array) as foo ) ) .size;",
),
];

Tester::new(PreferSetSize::NAME, pass, fail).expect_fix(fix).test_and_snapshot();
}
Loading

0 comments on commit 6dd8374

Please sign in to comment.