Skip to content

Commit

Permalink
feat: new no-new-native-nonconstructor rule (#16368)
Browse files Browse the repository at this point in the history
* feat: add `no-new-noconstructor` rule

* docs: add docs for `no-new-noconstructor`

* fix: pass constructor name to message

* docs: add `related_rules`

* chore: add new rule

* fix: rename `noconstructor` -> `nonconstructor`

* fix: set `recommended: false`

* fix: rename `no-new-nonconstructor` -> `no-new-native-nonconstructor`

* docs: fix correct example

* Update docs/src/rules/no-new-native-nonconstructor.md

Co-authored-by: Milos Djermanovic <milos.djermanovic@gmail.com>

* docs: update links

* docs: address reviews

* fix: `no constructor` -> `non-constructor`

* Apply suggestions from code review

Co-authored-by: Nicholas C. Zakas <nicholas@humanwhocodes.com>

Co-authored-by: Milos Djermanovic <milos.djermanovic@gmail.com>
Co-authored-by: Nicholas C. Zakas <nicholas@humanwhocodes.com>
Co-authored-by: Brandon Mills <btmills@users.noreply.github.com>
  • Loading branch information
4 people committed Nov 6, 2022
1 parent 978799b commit f14587c
Show file tree
Hide file tree
Showing 6 changed files with 221 additions and 0 deletions.
14 changes: 14 additions & 0 deletions docs/src/_data/further_reading_links.json
Expand Up @@ -705,5 +705,19 @@
"logo": "https://github.com/fluidicon.png",
"title": "GitHub - tc39/proposal-class-static-block: ECMAScript class static initialization blocks",
"description": "ECMAScript class static initialization blocks. Contribute to tc39/proposal-class-static-block development by creating an account on GitHub."
},
"https://tc39.es/ecma262/#sec-symbol-constructor": {
"domain": "tc39.es",
"url": "https://tc39.es/ecma262/#sec-symbol-constructor",
"logo": "https://tc39.es/ecma262/img/favicon.ico",
"title": "ECMAScript® 2023 Language Specification",
"description": null
},
"https://tc39.es/ecma262/#sec-bigint-constructor": {
"domain": "tc39.es",
"url": "https://tc39.es/ecma262/#sec-bigint-constructor",
"logo": "https://tc39.es/ecma262/img/favicon.ico",
"title": "ECMAScript® 2023 Language Specification",
"description": null
}
}
73 changes: 73 additions & 0 deletions docs/src/rules/no-new-native-nonconstructor.md
@@ -0,0 +1,73 @@
---
title: no-new-native-nonconstructor
layout: doc
rule_type: problem
related_rules:
- no-obj-calls
further_reading:
- https://tc39.es/ecma262/#sec-symbol-constructor
- https://tc39.es/ecma262/#sec-bigint-constructor
---



It is a convention in JavaScript that global variables beginning with an uppercase letter typically represent classes that can be instantiated using the `new` operator, such as `new Array` and `new Map`. Confusingly, JavaScript also provides some global variables that begin with an uppercase letter that cannot be called using the `new` operator and will throw an error if you attempt to do so. These are typically functions that are related to data types and are easy to mistake for classes. Consider the following example:

```js
// throws a TypeError
let foo = new Symbol("foo");

// throws a TypeError
let result = new BigInt(9007199254740991);

Both `new Symbol` and `new BigInt` throw a type error because they are functions and not classes. It is easy to make this mistake by assuming the uppercase letters indicate classes.

## Rule Details

This rule is aimed at preventing the accidental calling of native JavaScript global functions with the `new` operator. These functions are:

* `Symbol`
* `BigInt`

## Examples

Examples of **incorrect** code for this rule:

::: incorrect

```js
/*eslint no-new-native-nonconstructor: "error"*/
/*eslint-env es2022*/
var foo = new Symbol('foo');
var bar = new BigInt(9007199254740991);
```

:::

Examples of **correct** code for this rule:

::: correct

```js
/*eslint no-new-native-nonconstructor: "error"*/
/*eslint-env es2022*/
var foo = Symbol('foo');
var bar = BigInt(9007199254740991);
// Ignores shadowed Symbol.
function baz(Symbol) {
const qux = new Symbol("baz");
}
function quux(BigInt) {
const corge = new BigInt(9007199254740991);
}
```

:::

## When Not To Use It

This rule should not be used in ES3/5 environments.
1 change: 1 addition & 0 deletions lib/rules/index.js
Expand Up @@ -168,6 +168,7 @@ module.exports = new LazyLoadingRuleMap(Object.entries({
"no-nested-ternary": () => require("./no-nested-ternary"),
"no-new": () => require("./no-new"),
"no-new-func": () => require("./no-new-func"),
"no-new-native-nonconstructor": () => require("./no-new-native-nonconstructor"),
"no-new-object": () => require("./no-new-object"),
"no-new-require": () => require("./no-new-require"),
"no-new-symbol": () => require("./no-new-symbol"),
Expand Down
64 changes: 64 additions & 0 deletions lib/rules/no-new-native-nonconstructor.js
@@ -0,0 +1,64 @@
/**
* @fileoverview Rule to disallow use of the new operator with global non-constructor functions
* @author Sosuke Suzuki
*/

"use strict";

//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------

const nonConstructorGlobalFunctionNames = ["Symbol", "BigInt"];

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------

/** @type {import('../shared/types').Rule} */
module.exports = {
meta: {
type: "problem",

docs: {
description: "Disallow `new` operators with global non-constructor functions",
recommended: false,
url: "https://eslint.org/docs/rules/no-new-native-nonconstructor"
},

schema: [],

messages: {
noNewNonconstructor: "`{{name}}` cannot be called as a constructor."
}
},

create(context) {

return {
"Program:exit"() {
const globalScope = context.getScope();

for (const nonConstructorName of nonConstructorGlobalFunctionNames) {
const variable = globalScope.set.get(nonConstructorName);

if (variable && variable.defs.length === 0) {
variable.references.forEach(ref => {
const node = ref.identifier;
const parent = node.parent;

if (parent && parent.type === "NewExpression" && parent.callee === node) {
context.report({
node,
messageId: "noNewNonconstructor",
data: { name: nonConstructorName }
});
}
});
}
}
}
};

}
};
68 changes: 68 additions & 0 deletions tests/lib/rules/no-new-native-nonconstructor.js
@@ -0,0 +1,68 @@
/**
* @fileoverview Tests for the no-new-native-nonconstructor rule
* @author Sosuke Suzuki
*/

"use strict";

//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------

const rule = require("../../../lib/rules/no-new-native-nonconstructor"),
{ RuleTester } = require("../../../lib/rule-tester");

//------------------------------------------------------------------------------
// Tests
//------------------------------------------------------------------------------

const ruleTester = new RuleTester({ env: { es2022: true } });

ruleTester.run("no-new-native-nonconstructor", rule, {
valid: [

// Symbol
"var foo = Symbol('foo');",
"function bar(Symbol) { var baz = new Symbol('baz');}",
"function Symbol() {} new Symbol();",
"new foo(Symbol);",
"new foo(bar, Symbol);",

// BigInt
"var foo = BigInt(9007199254740991);",
"function bar(BigInt) { var baz = new BigInt(9007199254740991);}",
"function BigInt() {} new BigInt();",
"new foo(BigInt);",
"new foo(bar, BigInt);"
],
invalid: [

// Symbol
{
code: "var foo = new Symbol('foo');",
errors: [{
message: "`Symbol` cannot be called as a constructor."
}]
},
{
code: "function bar() { return function Symbol() {}; } var baz = new Symbol('baz');",
errors: [{
message: "`Symbol` cannot be called as a constructor."
}]
},

// BigInt
{
code: "var foo = new BigInt(9007199254740991);",
errors: [{
message: "`BigInt` cannot be called as a constructor."
}]
},
{
code: "function bar() { return function BigInt() {}; } var baz = new BigInt(9007199254740991);",
errors: [{
message: "`BigInt` cannot be called as a constructor."
}]
}
]
});
1 change: 1 addition & 0 deletions tools/rule-types.json
Expand Up @@ -155,6 +155,7 @@
"no-nested-ternary": "suggestion",
"no-new": "suggestion",
"no-new-func": "suggestion",
"no-new-native-nonconstructor": "problem",
"no-new-object": "suggestion",
"no-new-require": "suggestion",
"no-new-symbol": "problem",
Expand Down

0 comments on commit f14587c

Please sign in to comment.