Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add eslint/no-obj-calls #508

Merged
merged 7 commits into from
Jul 3, 2023
Merged
Show file tree
Hide file tree
Changes from 3 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
1 change: 1 addition & 0 deletions crates/oxc_linter/src/rules.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ oxc_macros::declare_all_lint_rules! {
eslint::no_inner_declarations,
eslint::no_mixed_operators,
eslint::no_new_symbol,
eslint::no_obj_calls,
eslint::no_prototype_builtins,
eslint::no_self_assign,
eslint::no_self_compare,
Expand Down
206 changes: 206 additions & 0 deletions crates/oxc_linter/src/rules/eslint/no_obj_calls.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,206 @@
use oxc_ast::{
ast::{Expression, IdentifierReference, MemberExpression},
AstKind,
};
use oxc_diagnostics::{
miette::{self, Diagnostic},
thiserror::Error,
};
use oxc_macros::declare_oxc_lint;
use oxc_semantic::{AstNode, ScopeId};
use oxc_span::{Atom, Span};

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

const GLOBAL_THIS: &str = "globalThis";
const NON_CALLABLE_GLOBALS: [&str; 5] = ["Atomics", "Intl", "JSON", "Math", "Reflect"];

#[derive(Debug, Error, Diagnostic)]
#[error("eslint(no-obj-calls): Disallow calling some global objects as functions")]
#[diagnostic(severity(error), help("{0} is not a function."))]
struct NoObjCallsDiagnostic(Atom, #[label] pub Span);

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NoObjCalls;

impl Default for NoObjCalls {
fn default() -> Self {
Self
}
}

declare_oxc_lint! {
/// ### What it does
/// Disallow calling some global objects as functions
///
/// ### Why is this bad?
/// Some global objects are not intended to be called as functions.
/// Calling them as functions will usually result in a TypeError being thrown.
///
/// ### Example
/// ```javascript
/// // Bad
/// let math = Math();
/// let newMath = new Math();
///
/// let json = JSON();
/// let newJson = new JSON();
///
/// let atomics = Atomics();
/// let newAtomics = new Atomics();
///
/// let intl = Intl();
/// let newIntl = new Intl();
///
/// let reflect = Reflect();
/// let newReflect = new Reflect();
///
/// // Good
/// let area = r => 2 * Math.PI * r * r;
/// let object = JSON.parse("{}");
/// let first = Atomics.load(sharedArray, 0);
/// let segmenterFrom = Intl.Segmenter("fr", { granularity: "word" });
/// ```
NoObjCalls,
correctness,
}

fn is_global_obj<'a>(str: &impl PartialEq<&'a str>) -> bool {
NON_CALLABLE_GLOBALS.iter().any(|&n| str == &n)
}

fn global_this_member(expr: &oxc_allocator::Box<'_, MemberExpression<'_>>) -> Option<Atom> {
if let Expression::Identifier(static_ident) = expr.object() &&
static_ident.name == GLOBAL_THIS &&
let Some(static_member) = expr.static_property_name() {
return Some(static_member.into())
} else {
return None
}
}

fn resolve_global_binding<'a, 'b: 'a>(
ident: &oxc_allocator::Box<'a, IdentifierReference>,
scope_id: ScopeId,
ctx: &LintContext<'a>,
) -> Option<Atom> {
if ctx.semantic().is_reference_to_global_variable(ident) {
return Some(ident.name.clone());
} else {
let scope = ctx.scopes();
Boshen marked this conversation as resolved.
Show resolved Hide resolved
let nodes = ctx.nodes();
let symbols = ctx.symbols();
if let Some(binding_id) = scope.get_binding(scope_id, &ident.name) {
let decl = nodes.get_node(symbols.get_declaration(binding_id));
let decl_scope = decl.scope_id();
match decl.kind() {
AstKind::VariableDeclarator(&ref parent_decl) => {
match &parent_decl.init {
// handles "let a = JSON; let b = a; a();"
Some(Expression::Identifier(parent_ident)) => {
return resolve_global_binding(&parent_ident, decl_scope, ctx);
}
// handles "let a = globalThis.JSON; let b = a; a();"
Some(Expression::MemberExpression(parent_expr)) => {
return global_this_member(parent_expr);
}
_ => None,
}
}
_ => {
return None;
}
}
} else {
panic!("No binding id found, but this IdentifierReference is not a global");
}
}
}

impl Rule for NoObjCalls {
fn run<'a>(&self, node: &AstNode<'a>, ctx: &LintContext<'a>) {
let (callee, span) = match node.kind() {
AstKind::NewExpression(expr) => (&expr.callee, expr.span),
AstKind::CallExpression(expr) => (&expr.callee, expr.span),

_ => return,
};

match callee {
Expression::Identifier(ident) => {
// handle new Math(), Math(), etc
if let Some(top_level_reference) = resolve_global_binding(&ident, node.scope_id(), ctx) &&
is_global_obj(&top_level_reference) {
ctx.diagnostic(NoObjCallsDiagnostic(ident.name.clone(), span));
return;
}
}

Expression::MemberExpression(expr) => {
// handle new globalThis.Math(), globalThis.Math(), etc
if let Some(global_member) = global_this_member(expr) &&
is_global_obj(&global_member)
{
ctx.diagnostic(NoObjCallsDiagnostic(global_member, span));
return
}
}
_ => return,
};
}
}

#[test]
fn test_ref() {
use crate::tester::Tester;
let pass = vec![(
"let j = JSON;
function foo() {
let j = x => x;
return x();
}",
None,
)];
let fail = vec![
("let j = JSON; j();", None),
("let a = JSON; let b = a; let c = b; b();", None),
("let m = globalThis.Math; new m();", None),
];

Tester::new(NoObjCalls::NAME, pass, fail).test();
}

#[test]
fn test() {
use crate::tester::Tester;
// see: https://github.com/eslint/eslint/blob/main/tests/lib/rules/no-obj-calls.js

let pass = vec![
("const m = Math;", None),
("let m = foo.Math();", None),
("JSON.parse(\"{}\")", None),
("Math.PI * 2 * (r * r)", None),
("bar.Atomic(foo)", None),
];

let fail = vec![
("let newObj = new JSON();", None),
("let obj = JSON();", None),
("let obj = globalThis.JSON()", None),
("new JSON", None),
("const foo = x => new JSON()", None),
("let newObj = new Math();", None),
("let obj = Math();", None),
("let obj = new Math().foo;", None),
("let obj = new globalThis.Math()", None),
("let newObj = new Atomics();", None),
("let obj = Atomics();", None),
("let newObj = new Intl();", None),
("let obj = Intl();", None),
("let newObj = new Reflect();", None),
("let obj = Reflect();", None),
("function() { JSON.parse(Atomics()) }", None),
];

Tester::new(NoObjCalls::NAME, pass, fail).test_and_snapshot();
}
117 changes: 117 additions & 0 deletions crates/oxc_linter/src/snapshots/no_obj_calls.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
---
source: crates/oxc_linter/src/tester.rs
expression: no_obj_calls
---
× eslint(no-obj-calls): Disallow calling some global objects as functions
╭─[no_obj_calls.tsx:1:1]
1 │ let newObj = new JSON();
· ──────────
╰────
help: JSON is not a function.

× eslint(no-obj-calls): Disallow calling some global objects as functions
╭─[no_obj_calls.tsx:1:1]
1 │ let obj = JSON();
· ──────
╰────
help: JSON is not a function.

× eslint(no-obj-calls): Disallow calling some global objects as functions
╭─[no_obj_calls.tsx:1:1]
1 │ let obj = globalThis.JSON()
· ─────────────────
╰────
help: JSON is not a function.

× eslint(no-obj-calls): Disallow calling some global objects as functions
╭─[no_obj_calls.tsx:1:1]
1 │ new JSON
· ────────
╰────
help: JSON is not a function.

× eslint(no-obj-calls): Disallow calling some global objects as functions
╭─[no_obj_calls.tsx:1:1]
1 │ const foo = x => new JSON()
· ──────────
╰────
help: JSON is not a function.

× eslint(no-obj-calls): Disallow calling some global objects as functions
╭─[no_obj_calls.tsx:1:1]
1 │ let newObj = new Math();
· ──────────
╰────
help: Math is not a function.

× eslint(no-obj-calls): Disallow calling some global objects as functions
╭─[no_obj_calls.tsx:1:1]
1 │ let obj = Math();
· ──────
╰────
help: Math is not a function.

× eslint(no-obj-calls): Disallow calling some global objects as functions
╭─[no_obj_calls.tsx:1:1]
1 │ let obj = new Math().foo;
· ──────────
╰────
help: Math is not a function.

× eslint(no-obj-calls): Disallow calling some global objects as functions
╭─[no_obj_calls.tsx:1:1]
1 │ let obj = new globalThis.Math()
· ─────────────────────
╰────
help: Math is not a function.

× eslint(no-obj-calls): Disallow calling some global objects as functions
╭─[no_obj_calls.tsx:1:1]
1 │ let newObj = new Atomics();
· ─────────────
╰────
help: Atomics is not a function.

× eslint(no-obj-calls): Disallow calling some global objects as functions
╭─[no_obj_calls.tsx:1:1]
1 │ let obj = Atomics();
· ─────────
╰────
help: Atomics is not a function.

× eslint(no-obj-calls): Disallow calling some global objects as functions
╭─[no_obj_calls.tsx:1:1]
1 │ let newObj = new Intl();
· ──────────
╰────
help: Intl is not a function.

× eslint(no-obj-calls): Disallow calling some global objects as functions
╭─[no_obj_calls.tsx:1:1]
1 │ let obj = Intl();
· ──────
╰────
help: Intl is not a function.

× eslint(no-obj-calls): Disallow calling some global objects as functions
╭─[no_obj_calls.tsx:1:1]
1 │ let newObj = new Reflect();
· ─────────────
╰────
help: Reflect is not a function.

× eslint(no-obj-calls): Disallow calling some global objects as functions
╭─[no_obj_calls.tsx:1:1]
1 │ let obj = Reflect();
· ─────────
╰────
help: Reflect is not a function.

× eslint(no-obj-calls): Disallow calling some global objects as functions
╭─[no_obj_calls.tsx:1:1]
1 │ function() { JSON.parse(Atomics()) }
· ─────────
╰────
help: Atomics is not a function.