feat(es/lints): Implement no-var (#4485)

This commit is contained in:
Artur 2022-04-30 10:25:35 +03:00 committed by GitHub
parent 88103cc8ec
commit 17f237d3ba
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 79 additions and 1 deletions

View File

@ -0,0 +1,9 @@
{
"jsc": {
"lints": {
"no-var": [
"error"
]
}
}
}

View File

@ -0,0 +1,4 @@
var a = 1;
let b = 1;
const c = 1;

View File

@ -0,0 +1,6 @@
x Unexpected var, use let or const instead
,----
1 | var a = 1;
: ^^^^^^^^^^
`----

View File

@ -165,6 +165,10 @@ pub struct LintConfig {
#[serde(default, alias = "noObjCalls")]
pub no_obj_calls: RuleConfig<()>,
#[cfg(feature = "non_critical_lints")]
#[serde(default, alias = "noVar")]
pub no_var: RuleConfig<()>,
#[cfg(feature = "non_critical_lints")]
#[serde(default, alias = "noThrowLiteral")]
pub no_throw_literal: RuleConfig<()>,

View File

@ -32,6 +32,7 @@ pub(crate) mod non_critical_lints {
pub mod no_restricted_syntax;
pub mod no_throw_literal;
pub mod no_use_before_define;
pub mod no_var;
pub mod prefer_regex_literals;
pub mod quotes;
pub mod radix;
@ -159,7 +160,9 @@ pub fn all(lint_params: LintParams) -> Vec<Box<dyn Rule>> {
rules.extend(no_throw_literal::no_throw_literal(
&lint_config.no_throw_literal,
))
));
rules.extend(no_var::no_var(&lint_config.no_var));
}
rules

View File

@ -0,0 +1,52 @@
use swc_common::{errors::HANDLER, Span};
use swc_ecma_ast::*;
use swc_ecma_visit::{Visit, VisitWith};
use crate::{
config::{LintRuleReaction, RuleConfig},
rule::{visitor_rule, Rule},
};
const MESSAGE: &str = "Unexpected var, use let or const instead";
pub fn no_var(config: &RuleConfig<()>) -> Option<Box<dyn Rule>> {
let rule_reaction = config.get_rule_reaction();
match rule_reaction {
LintRuleReaction::Off => None,
_ => Some(visitor_rule(NoVar::new(rule_reaction))),
}
}
#[derive(Debug, Default)]
struct NoVar {
expected_reaction: LintRuleReaction,
}
impl NoVar {
fn new(expected_reaction: LintRuleReaction) -> Self {
Self { expected_reaction }
}
fn emit_error(&self, span: Span) {
HANDLER.with(|handler| match self.expected_reaction {
LintRuleReaction::Error => {
handler.struct_span_err(span, MESSAGE).emit();
}
LintRuleReaction::Warning => {
handler.struct_span_warn(span, MESSAGE).emit();
}
_ => {}
});
}
}
impl Visit for NoVar {
fn visit_var_decl(&mut self, var_decl: &VarDecl) {
if let VarDeclKind::Var = var_decl.kind {
self.emit_error(var_decl.span);
}
var_decl.visit_children_with(self);
}
}