Skip to content

Commit

Permalink
Fix: no-undefined warned on non-computed property keys (fixes #7964)
Browse files Browse the repository at this point in the history
  • Loading branch information
platinumazure committed Jan 28, 2017
1 parent 5ae6e00 commit 2794cf6
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 9 deletions.
35 changes: 29 additions & 6 deletions lib/rules/no-undefined.js
Expand Up @@ -21,15 +21,38 @@ module.exports = {

create(context) {

/**
* Returns true if an Identifier with name of "undefined" is in an
* acceptable location.
* @param {ASTNode} node The Identifer node to check.
* @returns {boolean} True if undefined is allowed here, false otherwise.
*/
function isValidUndefinedIdentifier(node) {
switch (node.parent.type) {
case "MemberExpression":

// foo.undefined is valid, foo[undefined] is not
return node === node.parent.property && !node.parent.computed;

case "Property":

// Only non-computed keys are valid here
return node === node.parent.key &&
!node.parent.computed;

default:
return false;
}
}

return {

Identifier(node) {
if (node.name === "undefined") {
const parent = context.getAncestors().pop();

if (!parent || parent.type !== "MemberExpression" || node !== parent.property || parent.computed) {
context.report({ node, message: "Unexpected use of undefined." });
}
if (node.name === "undefined" && !isValidUndefinedIdentifier(node)) {
context.report({
node,
message: "Unexpected use of undefined."
});
}
}
};
Expand Down
12 changes: 9 additions & 3 deletions tests/lib/rules/no-undefined.js
Expand Up @@ -18,7 +18,7 @@ const rule = require("../../../lib/rules/no-undefined"),

const errors = [{ message: "Unexpected use of undefined.", type: "Identifier" }];

const ruleTester = new RuleTester();
const ruleTester = new RuleTester({ parserOptions: { ecmaVersion: 6 } });

ruleTester.run("no-undefined", rule, {
valid: [
Expand All @@ -31,7 +31,11 @@ ruleTester.run("no-undefined", rule, {
"ndefined",
"a.undefined",
"this.undefined",
"global['undefined']"
"global['undefined']",

// https://github.com/eslint/eslint/issues/7964
"({ undefined: bar })",
"({ undefined: bar } = foo)"
],
invalid: [
{ code: "undefined", errors },
Expand All @@ -44,6 +48,8 @@ ruleTester.run("no-undefined", rule, {
{ code: "try {} catch(undefined) {}", errors },
{ code: "(function undefined(){}())", errors },
{ code: "undefined = true", errors },
{ code: "var undefined = true", errors }
{ code: "var undefined = true", errors },
{ code: "({ bar: undefined })", errors },
{ code: "({ bar: undefined } = foo)", errors }
]
});

0 comments on commit 2794cf6

Please sign in to comment.