Skip to content
Open
Changes from all 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
71 changes: 71 additions & 0 deletions crates/oxc_linter/src/rules/eslint/no_unassigned_vars.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,14 @@ declare_oxc_lint!(
///
/// Disallow let or var variables that are read but never assigned.
///
/// #### Ignored Files
/// This rule ignores `.svelte` and `.vue` files entirely. Oxlint only parses the
/// `<script>` blocks of these files, so a binding that the template assigns looks
/// like it is never assigned. In Svelte the template writes through
/// `bind:this={el}` and `bind:value={x}`; in Vue a `<script setup>` `let` is a
/// `setup-let` binding that `v-model="x"` and inline handlers such as
/// `@click="x = 1"` assign to directly.
///
/// ### Why is this bad?
///
/// This rule flags let or var declarations that are never assigned a value but are still read or used in the code.
Expand Down Expand Up @@ -103,6 +111,11 @@ impl Rule for NoUnassignedVars {
ctx.diagnostic(no_unassigned_vars_diagnostic(ident.span, ident.name.as_str()));
}
}

fn should_run(&self, ctx: &crate::context::ContextHost) -> bool {
// ignore svelte/vue: their templates can assign a binding, which we can't see.
!ctx.file_extension().is_some_and(|ext| ext == "svelte" || ext == "vue")
}
}

#[test]
Expand Down Expand Up @@ -160,3 +173,61 @@ fn test() {

Tester::new(NoUnassignedVars::NAME, NoUnassignedVars::PLUGIN, pass, fail).test_and_snapshot();
}

#[test]
fn test_svelte() {
use crate::tester::Tester;

// The markup is stripped before linting; it documents the template-side write
// (`bind:this`, `bind:value`) that makes these bindings assigned in reality.
let pass = vec![
"<script lang=\"ts\">
let dialog: HTMLDialogElement;
function openDialog() { dialog.showModal(); }
</script>
<dialog bind:this={dialog}></dialog>",
"<script>
let value;
log(value);
</script>
<input bind:value />",
// Both blocks of a two-script component are linted; neither may report.
"<script module>
let shared;
log(shared);
</script>
<script>
let value;
log(value);
</script>
<input bind:value />",
];

Tester::new(NoUnassignedVars::NAME, NoUnassignedVars::PLUGIN, pass, vec![])
.change_rule_path("test.svelte")
.test();
}

#[test]
fn test_vue() {
use crate::tester::Tester;

// A `<script setup>` `let` is a `setup-let` binding: `v-model` and inline handlers
// compile to direct assignments to it, so the script alone cannot see the write.
let pass = vec![
"<script setup>
let msg;
log(msg);
</script>
<template><input v-model=\"msg\" /></template>",
"<script setup>
let count;
log(count);
</script>
<template><button @click=\"count = 1\">go</button></template>",
];

Tester::new(NoUnassignedVars::NAME, NoUnassignedVars::PLUGIN, pass, vec![])
.change_rule_path("test.vue")
.test();
}
Loading