feat(es/lints): Implement no-debugger rule (#3398)

This commit is contained in:
Artur 2022-01-30 06:33:46 +03:00 committed by GitHub
parent 7de339530c
commit 9dec9236f7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 81 additions and 1 deletions

View File

@ -0,0 +1,7 @@
{
"jsc": {
"lints": {
"noDebugger": ["error"]
}
}
}

View File

@ -0,0 +1,5 @@
function f() {
debugger;
}
debugger;

View File

@ -0,0 +1,12 @@
error: Unexpected 'debugger' statement
|
2 | debugger;
| ^^^^^^^^^
error: Unexpected 'debugger' statement
|
5 | debugger;
| ^^^^^^^^^

View File

@ -2,7 +2,7 @@ use crate::rules::no_console::NoConsoleConfig;
use serde::{Deserialize, Serialize};
use std::fmt::Debug;
#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum LintRuleReaction {
Off,
@ -38,4 +38,7 @@ impl<T: Debug + Clone + Serialize + Default> RuleConfig<T> {
pub struct LintConfig {
#[serde(default)]
pub no_console: RuleConfig<NoConsoleConfig>,
#[serde(default)]
pub no_debugger: RuleConfig<()>,
}

View File

@ -7,6 +7,7 @@ mod const_assign;
mod duplicate_bindings;
mod duplicate_exports;
pub mod no_console;
mod no_debugger;
pub fn all(lint_config: &LintConfig, top_level_ctxt: SyntaxContext) -> Vec<Box<dyn Rule>> {
let mut rules = vec![
@ -20,6 +21,8 @@ pub fn all(lint_config: &LintConfig, top_level_ctxt: SyntaxContext) -> Vec<Box<d
top_level_ctxt,
));
rules.extend(no_debugger::no_debugger(&lint_config.no_debugger));
rules
}

View File

@ -0,0 +1,50 @@
use crate::{
config::{LintRuleReaction, RuleConfig},
rule::{visitor_rule, Rule},
};
use serde::{Deserialize, Serialize};
use swc_common::{collections::AHashSet, errors::HANDLER, Span, SyntaxContext};
use swc_ecma_ast::*;
use swc_ecma_visit::{noop_visit_type, Visit};
const MESSAGE: &str = "Unexpected 'debugger' statement";
pub fn no_debugger(config: &RuleConfig<()>) -> Option<Box<dyn Rule>> {
let rule_reaction = config.get_rule_reaction();
match rule_reaction {
LintRuleReaction::Off => None,
_ => Some(visitor_rule(NoDebugger::new(*rule_reaction))),
}
}
#[derive(Debug, Default)]
struct NoDebugger {
expected_reaction: LintRuleReaction,
}
impl NoDebugger {
fn new(expected_reaction: LintRuleReaction) -> Self {
Self { expected_reaction }
}
fn check(&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 NoDebugger {
noop_visit_type!();
fn visit_debugger_stmt(&mut self, debugger_stmt: &DebuggerStmt) {
self.check(debugger_stmt.span);
}
}