id
int32 0
58k
| repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
sequence | docstring
stringlengths 4
11.8k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 86
226
|
---|---|---|---|---|---|---|---|---|---|---|---|
3,100 | eslint/eslint | lib/rules/no-dupe-class-members.js | getState | function getState(name, isStatic) {
const stateMap = stack[stack.length - 1];
const key = `$${name}`; // to avoid "__proto__".
if (!stateMap[key]) {
stateMap[key] = {
nonStatic: { init: false, get: false, set: false },
static: { init: false, get: false, set: false }
};
}
return stateMap[key][isStatic ? "static" : "nonStatic"];
} | javascript | function getState(name, isStatic) {
const stateMap = stack[stack.length - 1];
const key = `$${name}`; // to avoid "__proto__".
if (!stateMap[key]) {
stateMap[key] = {
nonStatic: { init: false, get: false, set: false },
static: { init: false, get: false, set: false }
};
}
return stateMap[key][isStatic ? "static" : "nonStatic"];
} | [
"function",
"getState",
"(",
"name",
",",
"isStatic",
")",
"{",
"const",
"stateMap",
"=",
"stack",
"[",
"stack",
".",
"length",
"-",
"1",
"]",
";",
"const",
"key",
"=",
"`",
"${",
"name",
"}",
"`",
";",
"// to avoid \"__proto__\".",
"if",
"(",
"!",
"stateMap",
"[",
"key",
"]",
")",
"{",
"stateMap",
"[",
"key",
"]",
"=",
"{",
"nonStatic",
":",
"{",
"init",
":",
"false",
",",
"get",
":",
"false",
",",
"set",
":",
"false",
"}",
",",
"static",
":",
"{",
"init",
":",
"false",
",",
"get",
":",
"false",
",",
"set",
":",
"false",
"}",
"}",
";",
"}",
"return",
"stateMap",
"[",
"key",
"]",
"[",
"isStatic",
"?",
"\"static\"",
":",
"\"nonStatic\"",
"]",
";",
"}"
] | Gets state of a given member name.
@param {string} name - A name of a member.
@param {boolean} isStatic - A flag which specifies that is a static member.
@returns {Object} A state of a given member name.
- retv.init {boolean} A flag which shows the name is declared as normal member.
- retv.get {boolean} A flag which shows the name is declared as getter.
- retv.set {boolean} A flag which shows the name is declared as setter. | [
"Gets",
"state",
"of",
"a",
"given",
"member",
"name",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-dupe-class-members.js#L42-L54 |
3,101 | eslint/eslint | lib/rules/prefer-object-spread.js | needsParens | function needsParens(node, sourceCode) {
const parent = node.parent;
switch (parent.type) {
case "VariableDeclarator":
case "ArrayExpression":
case "ReturnStatement":
case "CallExpression":
case "Property":
return false;
case "AssignmentExpression":
return parent.left === node && !isParenthesised(sourceCode, node);
default:
return !isParenthesised(sourceCode, node);
}
} | javascript | function needsParens(node, sourceCode) {
const parent = node.parent;
switch (parent.type) {
case "VariableDeclarator":
case "ArrayExpression":
case "ReturnStatement":
case "CallExpression":
case "Property":
return false;
case "AssignmentExpression":
return parent.left === node && !isParenthesised(sourceCode, node);
default:
return !isParenthesised(sourceCode, node);
}
} | [
"function",
"needsParens",
"(",
"node",
",",
"sourceCode",
")",
"{",
"const",
"parent",
"=",
"node",
".",
"parent",
";",
"switch",
"(",
"parent",
".",
"type",
")",
"{",
"case",
"\"VariableDeclarator\"",
":",
"case",
"\"ArrayExpression\"",
":",
"case",
"\"ReturnStatement\"",
":",
"case",
"\"CallExpression\"",
":",
"case",
"\"Property\"",
":",
"return",
"false",
";",
"case",
"\"AssignmentExpression\"",
":",
"return",
"parent",
".",
"left",
"===",
"node",
"&&",
"!",
"isParenthesised",
"(",
"sourceCode",
",",
"node",
")",
";",
"default",
":",
"return",
"!",
"isParenthesised",
"(",
"sourceCode",
",",
"node",
")",
";",
"}",
"}"
] | Helper that checks if the node needs parentheses to be valid JS.
The default is to wrap the node in parentheses to avoid parsing errors.
@param {ASTNode} node - The node that the rule warns on
@param {Object} sourceCode - in context sourcecode object
@returns {boolean} - Returns true if the node needs parentheses | [
"Helper",
"that",
"checks",
"if",
"the",
"node",
"needs",
"parentheses",
"to",
"be",
"valid",
"JS",
".",
"The",
"default",
"is",
"to",
"wrap",
"the",
"node",
"in",
"parentheses",
"to",
"avoid",
"parsing",
"errors",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/prefer-object-spread.js#L35-L50 |
3,102 | eslint/eslint | lib/rules/prefer-object-spread.js | getParenTokens | function getParenTokens(node, leftArgumentListParen, sourceCode) {
const parens = [sourceCode.getFirstToken(node), sourceCode.getLastToken(node)];
let leftNext = sourceCode.getTokenBefore(node);
let rightNext = sourceCode.getTokenAfter(node);
// Note: don't include the parens of the argument list.
while (
leftNext &&
rightNext &&
leftNext.range[0] > leftArgumentListParen.range[0] &&
isOpeningParenToken(leftNext) &&
isClosingParenToken(rightNext)
) {
parens.push(leftNext, rightNext);
leftNext = sourceCode.getTokenBefore(leftNext);
rightNext = sourceCode.getTokenAfter(rightNext);
}
return parens.sort((a, b) => a.range[0] - b.range[0]);
} | javascript | function getParenTokens(node, leftArgumentListParen, sourceCode) {
const parens = [sourceCode.getFirstToken(node), sourceCode.getLastToken(node)];
let leftNext = sourceCode.getTokenBefore(node);
let rightNext = sourceCode.getTokenAfter(node);
// Note: don't include the parens of the argument list.
while (
leftNext &&
rightNext &&
leftNext.range[0] > leftArgumentListParen.range[0] &&
isOpeningParenToken(leftNext) &&
isClosingParenToken(rightNext)
) {
parens.push(leftNext, rightNext);
leftNext = sourceCode.getTokenBefore(leftNext);
rightNext = sourceCode.getTokenAfter(rightNext);
}
return parens.sort((a, b) => a.range[0] - b.range[0]);
} | [
"function",
"getParenTokens",
"(",
"node",
",",
"leftArgumentListParen",
",",
"sourceCode",
")",
"{",
"const",
"parens",
"=",
"[",
"sourceCode",
".",
"getFirstToken",
"(",
"node",
")",
",",
"sourceCode",
".",
"getLastToken",
"(",
"node",
")",
"]",
";",
"let",
"leftNext",
"=",
"sourceCode",
".",
"getTokenBefore",
"(",
"node",
")",
";",
"let",
"rightNext",
"=",
"sourceCode",
".",
"getTokenAfter",
"(",
"node",
")",
";",
"// Note: don't include the parens of the argument list.",
"while",
"(",
"leftNext",
"&&",
"rightNext",
"&&",
"leftNext",
".",
"range",
"[",
"0",
"]",
">",
"leftArgumentListParen",
".",
"range",
"[",
"0",
"]",
"&&",
"isOpeningParenToken",
"(",
"leftNext",
")",
"&&",
"isClosingParenToken",
"(",
"rightNext",
")",
")",
"{",
"parens",
".",
"push",
"(",
"leftNext",
",",
"rightNext",
")",
";",
"leftNext",
"=",
"sourceCode",
".",
"getTokenBefore",
"(",
"leftNext",
")",
";",
"rightNext",
"=",
"sourceCode",
".",
"getTokenAfter",
"(",
"rightNext",
")",
";",
"}",
"return",
"parens",
".",
"sort",
"(",
"(",
"a",
",",
"b",
")",
"=>",
"a",
".",
"range",
"[",
"0",
"]",
"-",
"b",
".",
"range",
"[",
"0",
"]",
")",
";",
"}"
] | Get the parenthesis tokens of a given ObjectExpression node.
This incldues the braces of the object literal and enclosing parentheses.
@param {ASTNode} node The node to get.
@param {Token} leftArgumentListParen The opening paren token of the argument list.
@param {SourceCode} sourceCode The source code object to get tokens.
@returns {Token[]} The parenthesis tokens of the node. This is sorted by the location. | [
"Get",
"the",
"parenthesis",
"tokens",
"of",
"a",
"given",
"ObjectExpression",
"node",
".",
"This",
"incldues",
"the",
"braces",
"of",
"the",
"object",
"literal",
"and",
"enclosing",
"parentheses",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/prefer-object-spread.js#L77-L96 |
3,103 | eslint/eslint | lib/rules/prefer-object-spread.js | defineFixer | function defineFixer(node, sourceCode) {
return function *(fixer) {
const leftParen = sourceCode.getTokenAfter(node.callee, isOpeningParenToken);
const rightParen = sourceCode.getLastToken(node);
// Remove the callee `Object.assign`
yield fixer.remove(node.callee);
// Replace the parens of argument list to braces.
if (needsParens(node, sourceCode)) {
yield fixer.replaceText(leftParen, "({");
yield fixer.replaceText(rightParen, "})");
} else {
yield fixer.replaceText(leftParen, "{");
yield fixer.replaceText(rightParen, "}");
}
// Process arguments.
for (const argNode of node.arguments) {
const innerParens = getParenTokens(argNode, leftParen, sourceCode);
const left = innerParens.shift();
const right = innerParens.pop();
if (argNode.type === "ObjectExpression") {
const maybeTrailingComma = sourceCode.getLastToken(argNode, 1);
const maybeArgumentComma = sourceCode.getTokenAfter(right);
/*
* Make bare this object literal.
* And remove spaces inside of the braces for better formatting.
*/
for (const innerParen of innerParens) {
yield fixer.remove(innerParen);
}
const leftRange = [left.range[0], getEndWithSpaces(left, sourceCode)];
const rightRange = [
Math.max(getStartWithSpaces(right, sourceCode), leftRange[1]), // Ensure ranges don't overlap
right.range[1]
];
yield fixer.removeRange(leftRange);
yield fixer.removeRange(rightRange);
// Remove the comma of this argument if it's duplication.
if (
(argNode.properties.length === 0 || isCommaToken(maybeTrailingComma)) &&
isCommaToken(maybeArgumentComma)
) {
yield fixer.remove(maybeArgumentComma);
}
} else {
// Make spread.
if (argNeedsParens(argNode, sourceCode)) {
yield fixer.insertTextBefore(left, "...(");
yield fixer.insertTextAfter(right, ")");
} else {
yield fixer.insertTextBefore(left, "...");
}
}
}
};
} | javascript | function defineFixer(node, sourceCode) {
return function *(fixer) {
const leftParen = sourceCode.getTokenAfter(node.callee, isOpeningParenToken);
const rightParen = sourceCode.getLastToken(node);
// Remove the callee `Object.assign`
yield fixer.remove(node.callee);
// Replace the parens of argument list to braces.
if (needsParens(node, sourceCode)) {
yield fixer.replaceText(leftParen, "({");
yield fixer.replaceText(rightParen, "})");
} else {
yield fixer.replaceText(leftParen, "{");
yield fixer.replaceText(rightParen, "}");
}
// Process arguments.
for (const argNode of node.arguments) {
const innerParens = getParenTokens(argNode, leftParen, sourceCode);
const left = innerParens.shift();
const right = innerParens.pop();
if (argNode.type === "ObjectExpression") {
const maybeTrailingComma = sourceCode.getLastToken(argNode, 1);
const maybeArgumentComma = sourceCode.getTokenAfter(right);
/*
* Make bare this object literal.
* And remove spaces inside of the braces for better formatting.
*/
for (const innerParen of innerParens) {
yield fixer.remove(innerParen);
}
const leftRange = [left.range[0], getEndWithSpaces(left, sourceCode)];
const rightRange = [
Math.max(getStartWithSpaces(right, sourceCode), leftRange[1]), // Ensure ranges don't overlap
right.range[1]
];
yield fixer.removeRange(leftRange);
yield fixer.removeRange(rightRange);
// Remove the comma of this argument if it's duplication.
if (
(argNode.properties.length === 0 || isCommaToken(maybeTrailingComma)) &&
isCommaToken(maybeArgumentComma)
) {
yield fixer.remove(maybeArgumentComma);
}
} else {
// Make spread.
if (argNeedsParens(argNode, sourceCode)) {
yield fixer.insertTextBefore(left, "...(");
yield fixer.insertTextAfter(right, ")");
} else {
yield fixer.insertTextBefore(left, "...");
}
}
}
};
} | [
"function",
"defineFixer",
"(",
"node",
",",
"sourceCode",
")",
"{",
"return",
"function",
"*",
"(",
"fixer",
")",
"{",
"const",
"leftParen",
"=",
"sourceCode",
".",
"getTokenAfter",
"(",
"node",
".",
"callee",
",",
"isOpeningParenToken",
")",
";",
"const",
"rightParen",
"=",
"sourceCode",
".",
"getLastToken",
"(",
"node",
")",
";",
"// Remove the callee `Object.assign`",
"yield",
"fixer",
".",
"remove",
"(",
"node",
".",
"callee",
")",
";",
"// Replace the parens of argument list to braces.",
"if",
"(",
"needsParens",
"(",
"node",
",",
"sourceCode",
")",
")",
"{",
"yield",
"fixer",
".",
"replaceText",
"(",
"leftParen",
",",
"\"({\"",
")",
";",
"yield",
"fixer",
".",
"replaceText",
"(",
"rightParen",
",",
"\"})\"",
")",
";",
"}",
"else",
"{",
"yield",
"fixer",
".",
"replaceText",
"(",
"leftParen",
",",
"\"{\"",
")",
";",
"yield",
"fixer",
".",
"replaceText",
"(",
"rightParen",
",",
"\"}\"",
")",
";",
"}",
"// Process arguments.",
"for",
"(",
"const",
"argNode",
"of",
"node",
".",
"arguments",
")",
"{",
"const",
"innerParens",
"=",
"getParenTokens",
"(",
"argNode",
",",
"leftParen",
",",
"sourceCode",
")",
";",
"const",
"left",
"=",
"innerParens",
".",
"shift",
"(",
")",
";",
"const",
"right",
"=",
"innerParens",
".",
"pop",
"(",
")",
";",
"if",
"(",
"argNode",
".",
"type",
"===",
"\"ObjectExpression\"",
")",
"{",
"const",
"maybeTrailingComma",
"=",
"sourceCode",
".",
"getLastToken",
"(",
"argNode",
",",
"1",
")",
";",
"const",
"maybeArgumentComma",
"=",
"sourceCode",
".",
"getTokenAfter",
"(",
"right",
")",
";",
"/*\n * Make bare this object literal.\n * And remove spaces inside of the braces for better formatting.\n */",
"for",
"(",
"const",
"innerParen",
"of",
"innerParens",
")",
"{",
"yield",
"fixer",
".",
"remove",
"(",
"innerParen",
")",
";",
"}",
"const",
"leftRange",
"=",
"[",
"left",
".",
"range",
"[",
"0",
"]",
",",
"getEndWithSpaces",
"(",
"left",
",",
"sourceCode",
")",
"]",
";",
"const",
"rightRange",
"=",
"[",
"Math",
".",
"max",
"(",
"getStartWithSpaces",
"(",
"right",
",",
"sourceCode",
")",
",",
"leftRange",
"[",
"1",
"]",
")",
",",
"// Ensure ranges don't overlap",
"right",
".",
"range",
"[",
"1",
"]",
"]",
";",
"yield",
"fixer",
".",
"removeRange",
"(",
"leftRange",
")",
";",
"yield",
"fixer",
".",
"removeRange",
"(",
"rightRange",
")",
";",
"// Remove the comma of this argument if it's duplication.",
"if",
"(",
"(",
"argNode",
".",
"properties",
".",
"length",
"===",
"0",
"||",
"isCommaToken",
"(",
"maybeTrailingComma",
")",
")",
"&&",
"isCommaToken",
"(",
"maybeArgumentComma",
")",
")",
"{",
"yield",
"fixer",
".",
"remove",
"(",
"maybeArgumentComma",
")",
";",
"}",
"}",
"else",
"{",
"// Make spread.",
"if",
"(",
"argNeedsParens",
"(",
"argNode",
",",
"sourceCode",
")",
")",
"{",
"yield",
"fixer",
".",
"insertTextBefore",
"(",
"left",
",",
"\"...(\"",
")",
";",
"yield",
"fixer",
".",
"insertTextAfter",
"(",
"right",
",",
"\")\"",
")",
";",
"}",
"else",
"{",
"yield",
"fixer",
".",
"insertTextBefore",
"(",
"left",
",",
"\"...\"",
")",
";",
"}",
"}",
"}",
"}",
";",
"}"
] | Autofixes the Object.assign call to use an object spread instead.
@param {ASTNode|null} node - The node that the rule warns on, i.e. the Object.assign call
@param {string} sourceCode - sourceCode of the Object.assign call
@returns {Function} autofixer - replaces the Object.assign with a spread object. | [
"Autofixes",
"the",
"Object",
".",
"assign",
"call",
"to",
"use",
"an",
"object",
"spread",
"instead",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/prefer-object-spread.js#L149-L211 |
3,104 | eslint/eslint | lib/rules/space-before-function-paren.js | getConfigForFunction | function getConfigForFunction(node) {
if (node.type === "ArrowFunctionExpression") {
// Always ignore non-async functions and arrow functions without parens, e.g. async foo => bar
if (node.async && astUtils.isOpeningParenToken(sourceCode.getFirstToken(node, { skip: 1 }))) {
return overrideConfig.asyncArrow || baseConfig;
}
} else if (isNamedFunction(node)) {
return overrideConfig.named || baseConfig;
// `generator-star-spacing` should warn anonymous generators. E.g. `function* () {}`
} else if (!node.generator) {
return overrideConfig.anonymous || baseConfig;
}
return "ignore";
} | javascript | function getConfigForFunction(node) {
if (node.type === "ArrowFunctionExpression") {
// Always ignore non-async functions and arrow functions without parens, e.g. async foo => bar
if (node.async && astUtils.isOpeningParenToken(sourceCode.getFirstToken(node, { skip: 1 }))) {
return overrideConfig.asyncArrow || baseConfig;
}
} else if (isNamedFunction(node)) {
return overrideConfig.named || baseConfig;
// `generator-star-spacing` should warn anonymous generators. E.g. `function* () {}`
} else if (!node.generator) {
return overrideConfig.anonymous || baseConfig;
}
return "ignore";
} | [
"function",
"getConfigForFunction",
"(",
"node",
")",
"{",
"if",
"(",
"node",
".",
"type",
"===",
"\"ArrowFunctionExpression\"",
")",
"{",
"// Always ignore non-async functions and arrow functions without parens, e.g. async foo => bar",
"if",
"(",
"node",
".",
"async",
"&&",
"astUtils",
".",
"isOpeningParenToken",
"(",
"sourceCode",
".",
"getFirstToken",
"(",
"node",
",",
"{",
"skip",
":",
"1",
"}",
")",
")",
")",
"{",
"return",
"overrideConfig",
".",
"asyncArrow",
"||",
"baseConfig",
";",
"}",
"}",
"else",
"if",
"(",
"isNamedFunction",
"(",
"node",
")",
")",
"{",
"return",
"overrideConfig",
".",
"named",
"||",
"baseConfig",
";",
"// `generator-star-spacing` should warn anonymous generators. E.g. `function* () {}`",
"}",
"else",
"if",
"(",
"!",
"node",
".",
"generator",
")",
"{",
"return",
"overrideConfig",
".",
"anonymous",
"||",
"baseConfig",
";",
"}",
"return",
"\"ignore\"",
";",
"}"
] | Gets the config for a given function
@param {ASTNode} node The function node
@returns {string} "always", "never", or "ignore" | [
"Gets",
"the",
"config",
"for",
"a",
"given",
"function"
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/space-before-function-paren.js#L88-L104 |
3,105 | eslint/eslint | lib/rules/space-before-function-paren.js | checkFunction | function checkFunction(node) {
const functionConfig = getConfigForFunction(node);
if (functionConfig === "ignore") {
return;
}
const rightToken = sourceCode.getFirstToken(node, astUtils.isOpeningParenToken);
const leftToken = sourceCode.getTokenBefore(rightToken);
const hasSpacing = sourceCode.isSpaceBetweenTokens(leftToken, rightToken);
if (hasSpacing && functionConfig === "never") {
context.report({
node,
loc: leftToken.loc.end,
message: "Unexpected space before function parentheses.",
fix: fixer => fixer.removeRange([leftToken.range[1], rightToken.range[0]])
});
} else if (!hasSpacing && functionConfig === "always") {
context.report({
node,
loc: leftToken.loc.end,
message: "Missing space before function parentheses.",
fix: fixer => fixer.insertTextAfter(leftToken, " ")
});
}
} | javascript | function checkFunction(node) {
const functionConfig = getConfigForFunction(node);
if (functionConfig === "ignore") {
return;
}
const rightToken = sourceCode.getFirstToken(node, astUtils.isOpeningParenToken);
const leftToken = sourceCode.getTokenBefore(rightToken);
const hasSpacing = sourceCode.isSpaceBetweenTokens(leftToken, rightToken);
if (hasSpacing && functionConfig === "never") {
context.report({
node,
loc: leftToken.loc.end,
message: "Unexpected space before function parentheses.",
fix: fixer => fixer.removeRange([leftToken.range[1], rightToken.range[0]])
});
} else if (!hasSpacing && functionConfig === "always") {
context.report({
node,
loc: leftToken.loc.end,
message: "Missing space before function parentheses.",
fix: fixer => fixer.insertTextAfter(leftToken, " ")
});
}
} | [
"function",
"checkFunction",
"(",
"node",
")",
"{",
"const",
"functionConfig",
"=",
"getConfigForFunction",
"(",
"node",
")",
";",
"if",
"(",
"functionConfig",
"===",
"\"ignore\"",
")",
"{",
"return",
";",
"}",
"const",
"rightToken",
"=",
"sourceCode",
".",
"getFirstToken",
"(",
"node",
",",
"astUtils",
".",
"isOpeningParenToken",
")",
";",
"const",
"leftToken",
"=",
"sourceCode",
".",
"getTokenBefore",
"(",
"rightToken",
")",
";",
"const",
"hasSpacing",
"=",
"sourceCode",
".",
"isSpaceBetweenTokens",
"(",
"leftToken",
",",
"rightToken",
")",
";",
"if",
"(",
"hasSpacing",
"&&",
"functionConfig",
"===",
"\"never\"",
")",
"{",
"context",
".",
"report",
"(",
"{",
"node",
",",
"loc",
":",
"leftToken",
".",
"loc",
".",
"end",
",",
"message",
":",
"\"Unexpected space before function parentheses.\"",
",",
"fix",
":",
"fixer",
"=>",
"fixer",
".",
"removeRange",
"(",
"[",
"leftToken",
".",
"range",
"[",
"1",
"]",
",",
"rightToken",
".",
"range",
"[",
"0",
"]",
"]",
")",
"}",
")",
";",
"}",
"else",
"if",
"(",
"!",
"hasSpacing",
"&&",
"functionConfig",
"===",
"\"always\"",
")",
"{",
"context",
".",
"report",
"(",
"{",
"node",
",",
"loc",
":",
"leftToken",
".",
"loc",
".",
"end",
",",
"message",
":",
"\"Missing space before function parentheses.\"",
",",
"fix",
":",
"fixer",
"=>",
"fixer",
".",
"insertTextAfter",
"(",
"leftToken",
",",
"\" \"",
")",
"}",
")",
";",
"}",
"}"
] | Checks the parens of a function node
@param {ASTNode} node A function node
@returns {void} | [
"Checks",
"the",
"parens",
"of",
"a",
"function",
"node"
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/space-before-function-paren.js#L111-L137 |
3,106 | eslint/eslint | lib/rules/capitalized-comments.js | createRegExpForIgnorePatterns | function createRegExpForIgnorePatterns(normalizedOptions) {
Object.keys(normalizedOptions).forEach(key => {
const ignorePatternStr = normalizedOptions[key].ignorePattern;
if (ignorePatternStr) {
const regExp = RegExp(`^\\s*(?:${ignorePatternStr})`, "u");
normalizedOptions[key].ignorePatternRegExp = regExp;
}
});
} | javascript | function createRegExpForIgnorePatterns(normalizedOptions) {
Object.keys(normalizedOptions).forEach(key => {
const ignorePatternStr = normalizedOptions[key].ignorePattern;
if (ignorePatternStr) {
const regExp = RegExp(`^\\s*(?:${ignorePatternStr})`, "u");
normalizedOptions[key].ignorePatternRegExp = regExp;
}
});
} | [
"function",
"createRegExpForIgnorePatterns",
"(",
"normalizedOptions",
")",
"{",
"Object",
".",
"keys",
"(",
"normalizedOptions",
")",
".",
"forEach",
"(",
"key",
"=>",
"{",
"const",
"ignorePatternStr",
"=",
"normalizedOptions",
"[",
"key",
"]",
".",
"ignorePattern",
";",
"if",
"(",
"ignorePatternStr",
")",
"{",
"const",
"regExp",
"=",
"RegExp",
"(",
"`",
"\\\\",
"${",
"ignorePatternStr",
"}",
"`",
",",
"\"u\"",
")",
";",
"normalizedOptions",
"[",
"key",
"]",
".",
"ignorePatternRegExp",
"=",
"regExp",
";",
"}",
"}",
")",
";",
"}"
] | Creates a regular expression for each ignorePattern defined in the rule
options.
This is done in order to avoid invoking the RegExp constructor repeatedly.
@param {Object} normalizedOptions The normalized rule options.
@returns {void} | [
"Creates",
"a",
"regular",
"expression",
"for",
"each",
"ignorePattern",
"defined",
"in",
"the",
"rule",
"options",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/capitalized-comments.js#L89-L99 |
3,107 | eslint/eslint | lib/rules/capitalized-comments.js | isConsecutiveComment | function isConsecutiveComment(comment) {
const previousTokenOrComment = sourceCode.getTokenBefore(comment, { includeComments: true });
return Boolean(
previousTokenOrComment &&
["Block", "Line"].indexOf(previousTokenOrComment.type) !== -1
);
} | javascript | function isConsecutiveComment(comment) {
const previousTokenOrComment = sourceCode.getTokenBefore(comment, { includeComments: true });
return Boolean(
previousTokenOrComment &&
["Block", "Line"].indexOf(previousTokenOrComment.type) !== -1
);
} | [
"function",
"isConsecutiveComment",
"(",
"comment",
")",
"{",
"const",
"previousTokenOrComment",
"=",
"sourceCode",
".",
"getTokenBefore",
"(",
"comment",
",",
"{",
"includeComments",
":",
"true",
"}",
")",
";",
"return",
"Boolean",
"(",
"previousTokenOrComment",
"&&",
"[",
"\"Block\"",
",",
"\"Line\"",
"]",
".",
"indexOf",
"(",
"previousTokenOrComment",
".",
"type",
")",
"!==",
"-",
"1",
")",
";",
"}"
] | Determine if a comment follows another comment.
@param {ASTNode} comment The comment to check.
@returns {boolean} True if the comment follows a valid comment. | [
"Determine",
"if",
"a",
"comment",
"follows",
"another",
"comment",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/capitalized-comments.js#L188-L195 |
3,108 | eslint/eslint | lib/rules/capitalized-comments.js | isCommentValid | function isCommentValid(comment, options) {
// 1. Check for default ignore pattern.
if (DEFAULT_IGNORE_PATTERN.test(comment.value)) {
return true;
}
// 2. Check for custom ignore pattern.
const commentWithoutAsterisks = comment.value
.replace(/\*/gu, "");
if (options.ignorePatternRegExp && options.ignorePatternRegExp.test(commentWithoutAsterisks)) {
return true;
}
// 3. Check for inline comments.
if (options.ignoreInlineComments && isInlineComment(comment)) {
return true;
}
// 4. Is this a consecutive comment (and are we tolerating those)?
if (options.ignoreConsecutiveComments && isConsecutiveComment(comment)) {
return true;
}
// 5. Does the comment start with a possible URL?
if (MAYBE_URL.test(commentWithoutAsterisks)) {
return true;
}
// 6. Is the initial word character a letter?
const commentWordCharsOnly = commentWithoutAsterisks
.replace(WHITESPACE, "");
if (commentWordCharsOnly.length === 0) {
return true;
}
const firstWordChar = commentWordCharsOnly[0];
if (!LETTER_PATTERN.test(firstWordChar)) {
return true;
}
// 7. Check the case of the initial word character.
const isUppercase = firstWordChar !== firstWordChar.toLocaleLowerCase(),
isLowercase = firstWordChar !== firstWordChar.toLocaleUpperCase();
if (capitalize === "always" && isLowercase) {
return false;
}
if (capitalize === "never" && isUppercase) {
return false;
}
return true;
} | javascript | function isCommentValid(comment, options) {
// 1. Check for default ignore pattern.
if (DEFAULT_IGNORE_PATTERN.test(comment.value)) {
return true;
}
// 2. Check for custom ignore pattern.
const commentWithoutAsterisks = comment.value
.replace(/\*/gu, "");
if (options.ignorePatternRegExp && options.ignorePatternRegExp.test(commentWithoutAsterisks)) {
return true;
}
// 3. Check for inline comments.
if (options.ignoreInlineComments && isInlineComment(comment)) {
return true;
}
// 4. Is this a consecutive comment (and are we tolerating those)?
if (options.ignoreConsecutiveComments && isConsecutiveComment(comment)) {
return true;
}
// 5. Does the comment start with a possible URL?
if (MAYBE_URL.test(commentWithoutAsterisks)) {
return true;
}
// 6. Is the initial word character a letter?
const commentWordCharsOnly = commentWithoutAsterisks
.replace(WHITESPACE, "");
if (commentWordCharsOnly.length === 0) {
return true;
}
const firstWordChar = commentWordCharsOnly[0];
if (!LETTER_PATTERN.test(firstWordChar)) {
return true;
}
// 7. Check the case of the initial word character.
const isUppercase = firstWordChar !== firstWordChar.toLocaleLowerCase(),
isLowercase = firstWordChar !== firstWordChar.toLocaleUpperCase();
if (capitalize === "always" && isLowercase) {
return false;
}
if (capitalize === "never" && isUppercase) {
return false;
}
return true;
} | [
"function",
"isCommentValid",
"(",
"comment",
",",
"options",
")",
"{",
"// 1. Check for default ignore pattern.",
"if",
"(",
"DEFAULT_IGNORE_PATTERN",
".",
"test",
"(",
"comment",
".",
"value",
")",
")",
"{",
"return",
"true",
";",
"}",
"// 2. Check for custom ignore pattern.",
"const",
"commentWithoutAsterisks",
"=",
"comment",
".",
"value",
".",
"replace",
"(",
"/",
"\\*",
"/",
"gu",
",",
"\"\"",
")",
";",
"if",
"(",
"options",
".",
"ignorePatternRegExp",
"&&",
"options",
".",
"ignorePatternRegExp",
".",
"test",
"(",
"commentWithoutAsterisks",
")",
")",
"{",
"return",
"true",
";",
"}",
"// 3. Check for inline comments.",
"if",
"(",
"options",
".",
"ignoreInlineComments",
"&&",
"isInlineComment",
"(",
"comment",
")",
")",
"{",
"return",
"true",
";",
"}",
"// 4. Is this a consecutive comment (and are we tolerating those)?",
"if",
"(",
"options",
".",
"ignoreConsecutiveComments",
"&&",
"isConsecutiveComment",
"(",
"comment",
")",
")",
"{",
"return",
"true",
";",
"}",
"// 5. Does the comment start with a possible URL?",
"if",
"(",
"MAYBE_URL",
".",
"test",
"(",
"commentWithoutAsterisks",
")",
")",
"{",
"return",
"true",
";",
"}",
"// 6. Is the initial word character a letter?",
"const",
"commentWordCharsOnly",
"=",
"commentWithoutAsterisks",
".",
"replace",
"(",
"WHITESPACE",
",",
"\"\"",
")",
";",
"if",
"(",
"commentWordCharsOnly",
".",
"length",
"===",
"0",
")",
"{",
"return",
"true",
";",
"}",
"const",
"firstWordChar",
"=",
"commentWordCharsOnly",
"[",
"0",
"]",
";",
"if",
"(",
"!",
"LETTER_PATTERN",
".",
"test",
"(",
"firstWordChar",
")",
")",
"{",
"return",
"true",
";",
"}",
"// 7. Check the case of the initial word character.",
"const",
"isUppercase",
"=",
"firstWordChar",
"!==",
"firstWordChar",
".",
"toLocaleLowerCase",
"(",
")",
",",
"isLowercase",
"=",
"firstWordChar",
"!==",
"firstWordChar",
".",
"toLocaleUpperCase",
"(",
")",
";",
"if",
"(",
"capitalize",
"===",
"\"always\"",
"&&",
"isLowercase",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"capitalize",
"===",
"\"never\"",
"&&",
"isUppercase",
")",
"{",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}"
] | Check a comment to determine if it is valid for this rule.
@param {ASTNode} comment The comment node to process.
@param {Object} options The options for checking this comment.
@returns {boolean} True if the comment is valid, false otherwise. | [
"Check",
"a",
"comment",
"to",
"determine",
"if",
"it",
"is",
"valid",
"for",
"this",
"rule",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/capitalized-comments.js#L204-L260 |
3,109 | eslint/eslint | lib/rules/capitalized-comments.js | processComment | function processComment(comment) {
const options = normalizedOptions[comment.type],
commentValid = isCommentValid(comment, options);
if (!commentValid) {
const messageId = capitalize === "always"
? "unexpectedLowercaseComment"
: "unexpectedUppercaseComment";
context.report({
node: null, // Intentionally using loc instead
loc: comment.loc,
messageId,
fix(fixer) {
const match = comment.value.match(LETTER_PATTERN);
return fixer.replaceTextRange(
// Offset match.index by 2 to account for the first 2 characters that start the comment (// or /*)
[comment.range[0] + match.index + 2, comment.range[0] + match.index + 3],
capitalize === "always" ? match[0].toLocaleUpperCase() : match[0].toLocaleLowerCase()
);
}
});
}
} | javascript | function processComment(comment) {
const options = normalizedOptions[comment.type],
commentValid = isCommentValid(comment, options);
if (!commentValid) {
const messageId = capitalize === "always"
? "unexpectedLowercaseComment"
: "unexpectedUppercaseComment";
context.report({
node: null, // Intentionally using loc instead
loc: comment.loc,
messageId,
fix(fixer) {
const match = comment.value.match(LETTER_PATTERN);
return fixer.replaceTextRange(
// Offset match.index by 2 to account for the first 2 characters that start the comment (// or /*)
[comment.range[0] + match.index + 2, comment.range[0] + match.index + 3],
capitalize === "always" ? match[0].toLocaleUpperCase() : match[0].toLocaleLowerCase()
);
}
});
}
} | [
"function",
"processComment",
"(",
"comment",
")",
"{",
"const",
"options",
"=",
"normalizedOptions",
"[",
"comment",
".",
"type",
"]",
",",
"commentValid",
"=",
"isCommentValid",
"(",
"comment",
",",
"options",
")",
";",
"if",
"(",
"!",
"commentValid",
")",
"{",
"const",
"messageId",
"=",
"capitalize",
"===",
"\"always\"",
"?",
"\"unexpectedLowercaseComment\"",
":",
"\"unexpectedUppercaseComment\"",
";",
"context",
".",
"report",
"(",
"{",
"node",
":",
"null",
",",
"// Intentionally using loc instead",
"loc",
":",
"comment",
".",
"loc",
",",
"messageId",
",",
"fix",
"(",
"fixer",
")",
"{",
"const",
"match",
"=",
"comment",
".",
"value",
".",
"match",
"(",
"LETTER_PATTERN",
")",
";",
"return",
"fixer",
".",
"replaceTextRange",
"(",
"// Offset match.index by 2 to account for the first 2 characters that start the comment (// or /*)",
"[",
"comment",
".",
"range",
"[",
"0",
"]",
"+",
"match",
".",
"index",
"+",
"2",
",",
"comment",
".",
"range",
"[",
"0",
"]",
"+",
"match",
".",
"index",
"+",
"3",
"]",
",",
"capitalize",
"===",
"\"always\"",
"?",
"match",
"[",
"0",
"]",
".",
"toLocaleUpperCase",
"(",
")",
":",
"match",
"[",
"0",
"]",
".",
"toLocaleLowerCase",
"(",
")",
")",
";",
"}",
"}",
")",
";",
"}",
"}"
] | Process a comment to determine if it needs to be reported.
@param {ASTNode} comment The comment node to process.
@returns {void} | [
"Process",
"a",
"comment",
"to",
"determine",
"if",
"it",
"needs",
"to",
"be",
"reported",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/capitalized-comments.js#L268-L293 |
3,110 | eslint/eslint | lib/rules/consistent-return.js | isClassConstructor | function isClassConstructor(node) {
return node.type === "FunctionExpression" &&
node.parent &&
node.parent.type === "MethodDefinition" &&
node.parent.kind === "constructor";
} | javascript | function isClassConstructor(node) {
return node.type === "FunctionExpression" &&
node.parent &&
node.parent.type === "MethodDefinition" &&
node.parent.kind === "constructor";
} | [
"function",
"isClassConstructor",
"(",
"node",
")",
"{",
"return",
"node",
".",
"type",
"===",
"\"FunctionExpression\"",
"&&",
"node",
".",
"parent",
"&&",
"node",
".",
"parent",
".",
"type",
"===",
"\"MethodDefinition\"",
"&&",
"node",
".",
"parent",
".",
"kind",
"===",
"\"constructor\"",
";",
"}"
] | Checks whether a given node is a `constructor` method in an ES6 class
@param {ASTNode} node A node to check
@returns {boolean} `true` if the node is a `constructor` method | [
"Checks",
"whether",
"a",
"given",
"node",
"is",
"a",
"constructor",
"method",
"in",
"an",
"ES6",
"class"
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/consistent-return.js#L43-L48 |
3,111 | eslint/eslint | lib/rules/consistent-return.js | checkLastSegment | function checkLastSegment(node) {
let loc, name;
/*
* Skip if it expected no return value or unreachable.
* When unreachable, all paths are returned or thrown.
*/
if (!funcInfo.hasReturnValue ||
funcInfo.codePath.currentSegments.every(isUnreachable) ||
astUtils.isES5Constructor(node) ||
isClassConstructor(node)
) {
return;
}
// Adjust a location and a message.
if (node.type === "Program") {
// The head of program.
loc = { line: 1, column: 0 };
name = "program";
} else if (node.type === "ArrowFunctionExpression") {
// `=>` token
loc = context.getSourceCode().getTokenBefore(node.body, astUtils.isArrowToken).loc.start;
} else if (
node.parent.type === "MethodDefinition" ||
(node.parent.type === "Property" && node.parent.method)
) {
// Method name.
loc = node.parent.key.loc.start;
} else {
// Function name or `function` keyword.
loc = (node.id || node).loc.start;
}
if (!name) {
name = astUtils.getFunctionNameWithKind(node);
}
// Reports.
context.report({
node,
loc,
messageId: "missingReturn",
data: { name }
});
} | javascript | function checkLastSegment(node) {
let loc, name;
/*
* Skip if it expected no return value or unreachable.
* When unreachable, all paths are returned or thrown.
*/
if (!funcInfo.hasReturnValue ||
funcInfo.codePath.currentSegments.every(isUnreachable) ||
astUtils.isES5Constructor(node) ||
isClassConstructor(node)
) {
return;
}
// Adjust a location and a message.
if (node.type === "Program") {
// The head of program.
loc = { line: 1, column: 0 };
name = "program";
} else if (node.type === "ArrowFunctionExpression") {
// `=>` token
loc = context.getSourceCode().getTokenBefore(node.body, astUtils.isArrowToken).loc.start;
} else if (
node.parent.type === "MethodDefinition" ||
(node.parent.type === "Property" && node.parent.method)
) {
// Method name.
loc = node.parent.key.loc.start;
} else {
// Function name or `function` keyword.
loc = (node.id || node).loc.start;
}
if (!name) {
name = astUtils.getFunctionNameWithKind(node);
}
// Reports.
context.report({
node,
loc,
messageId: "missingReturn",
data: { name }
});
} | [
"function",
"checkLastSegment",
"(",
"node",
")",
"{",
"let",
"loc",
",",
"name",
";",
"/*\n * Skip if it expected no return value or unreachable.\n * When unreachable, all paths are returned or thrown.\n */",
"if",
"(",
"!",
"funcInfo",
".",
"hasReturnValue",
"||",
"funcInfo",
".",
"codePath",
".",
"currentSegments",
".",
"every",
"(",
"isUnreachable",
")",
"||",
"astUtils",
".",
"isES5Constructor",
"(",
"node",
")",
"||",
"isClassConstructor",
"(",
"node",
")",
")",
"{",
"return",
";",
"}",
"// Adjust a location and a message.",
"if",
"(",
"node",
".",
"type",
"===",
"\"Program\"",
")",
"{",
"// The head of program.",
"loc",
"=",
"{",
"line",
":",
"1",
",",
"column",
":",
"0",
"}",
";",
"name",
"=",
"\"program\"",
";",
"}",
"else",
"if",
"(",
"node",
".",
"type",
"===",
"\"ArrowFunctionExpression\"",
")",
"{",
"// `=>` token",
"loc",
"=",
"context",
".",
"getSourceCode",
"(",
")",
".",
"getTokenBefore",
"(",
"node",
".",
"body",
",",
"astUtils",
".",
"isArrowToken",
")",
".",
"loc",
".",
"start",
";",
"}",
"else",
"if",
"(",
"node",
".",
"parent",
".",
"type",
"===",
"\"MethodDefinition\"",
"||",
"(",
"node",
".",
"parent",
".",
"type",
"===",
"\"Property\"",
"&&",
"node",
".",
"parent",
".",
"method",
")",
")",
"{",
"// Method name.",
"loc",
"=",
"node",
".",
"parent",
".",
"key",
".",
"loc",
".",
"start",
";",
"}",
"else",
"{",
"// Function name or `function` keyword.",
"loc",
"=",
"(",
"node",
".",
"id",
"||",
"node",
")",
".",
"loc",
".",
"start",
";",
"}",
"if",
"(",
"!",
"name",
")",
"{",
"name",
"=",
"astUtils",
".",
"getFunctionNameWithKind",
"(",
"node",
")",
";",
"}",
"// Reports.",
"context",
".",
"report",
"(",
"{",
"node",
",",
"loc",
",",
"messageId",
":",
"\"missingReturn\"",
",",
"data",
":",
"{",
"name",
"}",
"}",
")",
";",
"}"
] | Checks whether of not the implicit returning is consistent if the last
code path segment is reachable.
@param {ASTNode} node - A program/function node to check.
@returns {void} | [
"Checks",
"whether",
"of",
"not",
"the",
"implicit",
"returning",
"is",
"consistent",
"if",
"the",
"last",
"code",
"path",
"segment",
"is",
"reachable",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/consistent-return.js#L95-L144 |
3,112 | eslint/eslint | lib/util/node-event-generator.js | countClassAttributes | function countClassAttributes(parsedSelector) {
switch (parsedSelector.type) {
case "child":
case "descendant":
case "sibling":
case "adjacent":
return countClassAttributes(parsedSelector.left) + countClassAttributes(parsedSelector.right);
case "compound":
case "not":
case "matches":
return parsedSelector.selectors.reduce((sum, childSelector) => sum + countClassAttributes(childSelector), 0);
case "attribute":
case "field":
case "nth-child":
case "nth-last-child":
return 1;
default:
return 0;
}
} | javascript | function countClassAttributes(parsedSelector) {
switch (parsedSelector.type) {
case "child":
case "descendant":
case "sibling":
case "adjacent":
return countClassAttributes(parsedSelector.left) + countClassAttributes(parsedSelector.right);
case "compound":
case "not":
case "matches":
return parsedSelector.selectors.reduce((sum, childSelector) => sum + countClassAttributes(childSelector), 0);
case "attribute":
case "field":
case "nth-child":
case "nth-last-child":
return 1;
default:
return 0;
}
} | [
"function",
"countClassAttributes",
"(",
"parsedSelector",
")",
"{",
"switch",
"(",
"parsedSelector",
".",
"type",
")",
"{",
"case",
"\"child\"",
":",
"case",
"\"descendant\"",
":",
"case",
"\"sibling\"",
":",
"case",
"\"adjacent\"",
":",
"return",
"countClassAttributes",
"(",
"parsedSelector",
".",
"left",
")",
"+",
"countClassAttributes",
"(",
"parsedSelector",
".",
"right",
")",
";",
"case",
"\"compound\"",
":",
"case",
"\"not\"",
":",
"case",
"\"matches\"",
":",
"return",
"parsedSelector",
".",
"selectors",
".",
"reduce",
"(",
"(",
"sum",
",",
"childSelector",
")",
"=>",
"sum",
"+",
"countClassAttributes",
"(",
"childSelector",
")",
",",
"0",
")",
";",
"case",
"\"attribute\"",
":",
"case",
"\"field\"",
":",
"case",
"\"nth-child\"",
":",
"case",
"\"nth-last-child\"",
":",
"return",
"1",
";",
"default",
":",
"return",
"0",
";",
"}",
"}"
] | Counts the number of class, pseudo-class, and attribute queries in this selector
@param {Object} parsedSelector An object (from esquery) describing the selector's matching behavior
@returns {number} The number of class, pseudo-class, and attribute queries in this selector | [
"Counts",
"the",
"number",
"of",
"class",
"pseudo",
"-",
"class",
"and",
"attribute",
"queries",
"in",
"this",
"selector"
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/util/node-event-generator.js#L86-L108 |
3,113 | eslint/eslint | lib/util/node-event-generator.js | countIdentifiers | function countIdentifiers(parsedSelector) {
switch (parsedSelector.type) {
case "child":
case "descendant":
case "sibling":
case "adjacent":
return countIdentifiers(parsedSelector.left) + countIdentifiers(parsedSelector.right);
case "compound":
case "not":
case "matches":
return parsedSelector.selectors.reduce((sum, childSelector) => sum + countIdentifiers(childSelector), 0);
case "identifier":
return 1;
default:
return 0;
}
} | javascript | function countIdentifiers(parsedSelector) {
switch (parsedSelector.type) {
case "child":
case "descendant":
case "sibling":
case "adjacent":
return countIdentifiers(parsedSelector.left) + countIdentifiers(parsedSelector.right);
case "compound":
case "not":
case "matches":
return parsedSelector.selectors.reduce((sum, childSelector) => sum + countIdentifiers(childSelector), 0);
case "identifier":
return 1;
default:
return 0;
}
} | [
"function",
"countIdentifiers",
"(",
"parsedSelector",
")",
"{",
"switch",
"(",
"parsedSelector",
".",
"type",
")",
"{",
"case",
"\"child\"",
":",
"case",
"\"descendant\"",
":",
"case",
"\"sibling\"",
":",
"case",
"\"adjacent\"",
":",
"return",
"countIdentifiers",
"(",
"parsedSelector",
".",
"left",
")",
"+",
"countIdentifiers",
"(",
"parsedSelector",
".",
"right",
")",
";",
"case",
"\"compound\"",
":",
"case",
"\"not\"",
":",
"case",
"\"matches\"",
":",
"return",
"parsedSelector",
".",
"selectors",
".",
"reduce",
"(",
"(",
"sum",
",",
"childSelector",
")",
"=>",
"sum",
"+",
"countIdentifiers",
"(",
"childSelector",
")",
",",
"0",
")",
";",
"case",
"\"identifier\"",
":",
"return",
"1",
";",
"default",
":",
"return",
"0",
";",
"}",
"}"
] | Counts the number of identifier queries in this selector
@param {Object} parsedSelector An object (from esquery) describing the selector's matching behavior
@returns {number} The number of identifier queries | [
"Counts",
"the",
"number",
"of",
"identifier",
"queries",
"in",
"this",
"selector"
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/util/node-event-generator.js#L115-L134 |
3,114 | eslint/eslint | lib/util/node-event-generator.js | compareSpecificity | function compareSpecificity(selectorA, selectorB) {
return selectorA.attributeCount - selectorB.attributeCount ||
selectorA.identifierCount - selectorB.identifierCount ||
(selectorA.rawSelector <= selectorB.rawSelector ? -1 : 1);
} | javascript | function compareSpecificity(selectorA, selectorB) {
return selectorA.attributeCount - selectorB.attributeCount ||
selectorA.identifierCount - selectorB.identifierCount ||
(selectorA.rawSelector <= selectorB.rawSelector ? -1 : 1);
} | [
"function",
"compareSpecificity",
"(",
"selectorA",
",",
"selectorB",
")",
"{",
"return",
"selectorA",
".",
"attributeCount",
"-",
"selectorB",
".",
"attributeCount",
"||",
"selectorA",
".",
"identifierCount",
"-",
"selectorB",
".",
"identifierCount",
"||",
"(",
"selectorA",
".",
"rawSelector",
"<=",
"selectorB",
".",
"rawSelector",
"?",
"-",
"1",
":",
"1",
")",
";",
"}"
] | Compares the specificity of two selector objects, with CSS-like rules.
@param {ASTSelector} selectorA An AST selector descriptor
@param {ASTSelector} selectorB Another AST selector descriptor
@returns {number}
a value less than 0 if selectorA is less specific than selectorB
a value greater than 0 if selectorA is more specific than selectorB
a value less than 0 if selectorA and selectorB have the same specificity, and selectorA <= selectorB alphabetically
a value greater than 0 if selectorA and selectorB have the same specificity, and selectorA > selectorB alphabetically | [
"Compares",
"the",
"specificity",
"of",
"two",
"selector",
"objects",
"with",
"CSS",
"-",
"like",
"rules",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/util/node-event-generator.js#L146-L150 |
3,115 | eslint/eslint | lib/rules/max-statements-per-line.js | reportFirstExtraStatementAndClear | function reportFirstExtraStatementAndClear() {
if (firstExtraStatement) {
context.report({
node: firstExtraStatement,
messageId: "exceed",
data: {
numberOfStatementsOnThisLine,
maxStatementsPerLine,
statements: numberOfStatementsOnThisLine === 1 ? "statement" : "statements"
}
});
}
firstExtraStatement = null;
} | javascript | function reportFirstExtraStatementAndClear() {
if (firstExtraStatement) {
context.report({
node: firstExtraStatement,
messageId: "exceed",
data: {
numberOfStatementsOnThisLine,
maxStatementsPerLine,
statements: numberOfStatementsOnThisLine === 1 ? "statement" : "statements"
}
});
}
firstExtraStatement = null;
} | [
"function",
"reportFirstExtraStatementAndClear",
"(",
")",
"{",
"if",
"(",
"firstExtraStatement",
")",
"{",
"context",
".",
"report",
"(",
"{",
"node",
":",
"firstExtraStatement",
",",
"messageId",
":",
"\"exceed\"",
",",
"data",
":",
"{",
"numberOfStatementsOnThisLine",
",",
"maxStatementsPerLine",
",",
"statements",
":",
"numberOfStatementsOnThisLine",
"===",
"1",
"?",
"\"statement\"",
":",
"\"statements\"",
"}",
"}",
")",
";",
"}",
"firstExtraStatement",
"=",
"null",
";",
"}"
] | Reports with the first extra statement, and clears it.
@returns {void} | [
"Reports",
"with",
"the",
"first",
"extra",
"statement",
"and",
"clears",
"it",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/max-statements-per-line.js#L67-L80 |
3,116 | eslint/eslint | lib/rules/max-statements-per-line.js | enterStatement | function enterStatement(node) {
const line = node.loc.start.line;
/*
* Skip to allow non-block statements if this is direct child of control statements.
* `if (a) foo();` is counted as 1.
* But `if (a) foo(); else foo();` should be counted as 2.
*/
if (SINGLE_CHILD_ALLOWED.test(node.parent.type) &&
node.parent.alternate !== node
) {
return;
}
// Update state.
if (line === lastStatementLine) {
numberOfStatementsOnThisLine += 1;
} else {
reportFirstExtraStatementAndClear();
numberOfStatementsOnThisLine = 1;
lastStatementLine = line;
}
// Reports if the node violated this rule.
if (numberOfStatementsOnThisLine === maxStatementsPerLine + 1) {
firstExtraStatement = firstExtraStatement || node;
}
} | javascript | function enterStatement(node) {
const line = node.loc.start.line;
/*
* Skip to allow non-block statements if this is direct child of control statements.
* `if (a) foo();` is counted as 1.
* But `if (a) foo(); else foo();` should be counted as 2.
*/
if (SINGLE_CHILD_ALLOWED.test(node.parent.type) &&
node.parent.alternate !== node
) {
return;
}
// Update state.
if (line === lastStatementLine) {
numberOfStatementsOnThisLine += 1;
} else {
reportFirstExtraStatementAndClear();
numberOfStatementsOnThisLine = 1;
lastStatementLine = line;
}
// Reports if the node violated this rule.
if (numberOfStatementsOnThisLine === maxStatementsPerLine + 1) {
firstExtraStatement = firstExtraStatement || node;
}
} | [
"function",
"enterStatement",
"(",
"node",
")",
"{",
"const",
"line",
"=",
"node",
".",
"loc",
".",
"start",
".",
"line",
";",
"/*\n * Skip to allow non-block statements if this is direct child of control statements.\n * `if (a) foo();` is counted as 1.\n * But `if (a) foo(); else foo();` should be counted as 2.\n */",
"if",
"(",
"SINGLE_CHILD_ALLOWED",
".",
"test",
"(",
"node",
".",
"parent",
".",
"type",
")",
"&&",
"node",
".",
"parent",
".",
"alternate",
"!==",
"node",
")",
"{",
"return",
";",
"}",
"// Update state.",
"if",
"(",
"line",
"===",
"lastStatementLine",
")",
"{",
"numberOfStatementsOnThisLine",
"+=",
"1",
";",
"}",
"else",
"{",
"reportFirstExtraStatementAndClear",
"(",
")",
";",
"numberOfStatementsOnThisLine",
"=",
"1",
";",
"lastStatementLine",
"=",
"line",
";",
"}",
"// Reports if the node violated this rule.",
"if",
"(",
"numberOfStatementsOnThisLine",
"===",
"maxStatementsPerLine",
"+",
"1",
")",
"{",
"firstExtraStatement",
"=",
"firstExtraStatement",
"||",
"node",
";",
"}",
"}"
] | Addresses a given node.
It updates the state of this rule, then reports the node if the node violated this rule.
@param {ASTNode} node - A node to check.
@returns {void} | [
"Addresses",
"a",
"given",
"node",
".",
"It",
"updates",
"the",
"state",
"of",
"this",
"rule",
"then",
"reports",
"the",
"node",
"if",
"the",
"node",
"violated",
"this",
"rule",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/max-statements-per-line.js#L99-L126 |
3,117 | eslint/eslint | lib/rules/max-statements-per-line.js | leaveStatement | function leaveStatement(node) {
const line = getActualLastToken(node).loc.end.line;
// Update state.
if (line !== lastStatementLine) {
reportFirstExtraStatementAndClear();
numberOfStatementsOnThisLine = 1;
lastStatementLine = line;
}
} | javascript | function leaveStatement(node) {
const line = getActualLastToken(node).loc.end.line;
// Update state.
if (line !== lastStatementLine) {
reportFirstExtraStatementAndClear();
numberOfStatementsOnThisLine = 1;
lastStatementLine = line;
}
} | [
"function",
"leaveStatement",
"(",
"node",
")",
"{",
"const",
"line",
"=",
"getActualLastToken",
"(",
"node",
")",
".",
"loc",
".",
"end",
".",
"line",
";",
"// Update state.",
"if",
"(",
"line",
"!==",
"lastStatementLine",
")",
"{",
"reportFirstExtraStatementAndClear",
"(",
")",
";",
"numberOfStatementsOnThisLine",
"=",
"1",
";",
"lastStatementLine",
"=",
"line",
";",
"}",
"}"
] | Updates the state of this rule with the end line of leaving node to check with the next statement.
@param {ASTNode} node - A node to check.
@returns {void} | [
"Updates",
"the",
"state",
"of",
"this",
"rule",
"with",
"the",
"end",
"line",
"of",
"leaving",
"node",
"to",
"check",
"with",
"the",
"next",
"statement",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/max-statements-per-line.js#L134-L143 |
3,118 | eslint/eslint | lib/rules/block-spacing.js | checkSpacingInsideBraces | function checkSpacingInsideBraces(node) {
// Gets braces and the first/last token of content.
const openBrace = getOpenBrace(node);
const closeBrace = sourceCode.getLastToken(node);
const firstToken = sourceCode.getTokenAfter(openBrace, { includeComments: true });
const lastToken = sourceCode.getTokenBefore(closeBrace, { includeComments: true });
// Skip if the node is invalid or empty.
if (openBrace.type !== "Punctuator" ||
openBrace.value !== "{" ||
closeBrace.type !== "Punctuator" ||
closeBrace.value !== "}" ||
firstToken === closeBrace
) {
return;
}
// Skip line comments for option never
if (!always && firstToken.type === "Line") {
return;
}
// Check.
if (!isValid(openBrace, firstToken)) {
context.report({
node,
loc: openBrace.loc.start,
messageId,
data: {
location: "after",
token: openBrace.value
},
fix(fixer) {
if (always) {
return fixer.insertTextBefore(firstToken, " ");
}
return fixer.removeRange([openBrace.range[1], firstToken.range[0]]);
}
});
}
if (!isValid(lastToken, closeBrace)) {
context.report({
node,
loc: closeBrace.loc.start,
messageId,
data: {
location: "before",
token: closeBrace.value
},
fix(fixer) {
if (always) {
return fixer.insertTextAfter(lastToken, " ");
}
return fixer.removeRange([lastToken.range[1], closeBrace.range[0]]);
}
});
}
} | javascript | function checkSpacingInsideBraces(node) {
// Gets braces and the first/last token of content.
const openBrace = getOpenBrace(node);
const closeBrace = sourceCode.getLastToken(node);
const firstToken = sourceCode.getTokenAfter(openBrace, { includeComments: true });
const lastToken = sourceCode.getTokenBefore(closeBrace, { includeComments: true });
// Skip if the node is invalid or empty.
if (openBrace.type !== "Punctuator" ||
openBrace.value !== "{" ||
closeBrace.type !== "Punctuator" ||
closeBrace.value !== "}" ||
firstToken === closeBrace
) {
return;
}
// Skip line comments for option never
if (!always && firstToken.type === "Line") {
return;
}
// Check.
if (!isValid(openBrace, firstToken)) {
context.report({
node,
loc: openBrace.loc.start,
messageId,
data: {
location: "after",
token: openBrace.value
},
fix(fixer) {
if (always) {
return fixer.insertTextBefore(firstToken, " ");
}
return fixer.removeRange([openBrace.range[1], firstToken.range[0]]);
}
});
}
if (!isValid(lastToken, closeBrace)) {
context.report({
node,
loc: closeBrace.loc.start,
messageId,
data: {
location: "before",
token: closeBrace.value
},
fix(fixer) {
if (always) {
return fixer.insertTextAfter(lastToken, " ");
}
return fixer.removeRange([lastToken.range[1], closeBrace.range[0]]);
}
});
}
} | [
"function",
"checkSpacingInsideBraces",
"(",
"node",
")",
"{",
"// Gets braces and the first/last token of content.",
"const",
"openBrace",
"=",
"getOpenBrace",
"(",
"node",
")",
";",
"const",
"closeBrace",
"=",
"sourceCode",
".",
"getLastToken",
"(",
"node",
")",
";",
"const",
"firstToken",
"=",
"sourceCode",
".",
"getTokenAfter",
"(",
"openBrace",
",",
"{",
"includeComments",
":",
"true",
"}",
")",
";",
"const",
"lastToken",
"=",
"sourceCode",
".",
"getTokenBefore",
"(",
"closeBrace",
",",
"{",
"includeComments",
":",
"true",
"}",
")",
";",
"// Skip if the node is invalid or empty.",
"if",
"(",
"openBrace",
".",
"type",
"!==",
"\"Punctuator\"",
"||",
"openBrace",
".",
"value",
"!==",
"\"{\"",
"||",
"closeBrace",
".",
"type",
"!==",
"\"Punctuator\"",
"||",
"closeBrace",
".",
"value",
"!==",
"\"}\"",
"||",
"firstToken",
"===",
"closeBrace",
")",
"{",
"return",
";",
"}",
"// Skip line comments for option never",
"if",
"(",
"!",
"always",
"&&",
"firstToken",
".",
"type",
"===",
"\"Line\"",
")",
"{",
"return",
";",
"}",
"// Check.",
"if",
"(",
"!",
"isValid",
"(",
"openBrace",
",",
"firstToken",
")",
")",
"{",
"context",
".",
"report",
"(",
"{",
"node",
",",
"loc",
":",
"openBrace",
".",
"loc",
".",
"start",
",",
"messageId",
",",
"data",
":",
"{",
"location",
":",
"\"after\"",
",",
"token",
":",
"openBrace",
".",
"value",
"}",
",",
"fix",
"(",
"fixer",
")",
"{",
"if",
"(",
"always",
")",
"{",
"return",
"fixer",
".",
"insertTextBefore",
"(",
"firstToken",
",",
"\" \"",
")",
";",
"}",
"return",
"fixer",
".",
"removeRange",
"(",
"[",
"openBrace",
".",
"range",
"[",
"1",
"]",
",",
"firstToken",
".",
"range",
"[",
"0",
"]",
"]",
")",
";",
"}",
"}",
")",
";",
"}",
"if",
"(",
"!",
"isValid",
"(",
"lastToken",
",",
"closeBrace",
")",
")",
"{",
"context",
".",
"report",
"(",
"{",
"node",
",",
"loc",
":",
"closeBrace",
".",
"loc",
".",
"start",
",",
"messageId",
",",
"data",
":",
"{",
"location",
":",
"\"before\"",
",",
"token",
":",
"closeBrace",
".",
"value",
"}",
",",
"fix",
"(",
"fixer",
")",
"{",
"if",
"(",
"always",
")",
"{",
"return",
"fixer",
".",
"insertTextAfter",
"(",
"lastToken",
",",
"\" \"",
")",
";",
"}",
"return",
"fixer",
".",
"removeRange",
"(",
"[",
"lastToken",
".",
"range",
"[",
"1",
"]",
",",
"closeBrace",
".",
"range",
"[",
"0",
"]",
"]",
")",
";",
"}",
"}",
")",
";",
"}",
"}"
] | Reports invalid spacing style inside braces.
@param {ASTNode} node - A BlockStatement/SwitchStatement node to get.
@returns {void} | [
"Reports",
"invalid",
"spacing",
"style",
"inside",
"braces",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/block-spacing.js#L80-L140 |
3,119 | eslint/eslint | lib/rules/multiline-comment-style.js | convertToStarredBlock | function convertToStarredBlock(firstComment, commentLinesList) {
const initialOffset = sourceCode.text.slice(firstComment.range[0] - firstComment.loc.start.column, firstComment.range[0]);
const starredLines = commentLinesList.map(line => `${initialOffset} *${line}`);
return `\n${starredLines.join("\n")}\n${initialOffset} `;
} | javascript | function convertToStarredBlock(firstComment, commentLinesList) {
const initialOffset = sourceCode.text.slice(firstComment.range[0] - firstComment.loc.start.column, firstComment.range[0]);
const starredLines = commentLinesList.map(line => `${initialOffset} *${line}`);
return `\n${starredLines.join("\n")}\n${initialOffset} `;
} | [
"function",
"convertToStarredBlock",
"(",
"firstComment",
",",
"commentLinesList",
")",
"{",
"const",
"initialOffset",
"=",
"sourceCode",
".",
"text",
".",
"slice",
"(",
"firstComment",
".",
"range",
"[",
"0",
"]",
"-",
"firstComment",
".",
"loc",
".",
"start",
".",
"column",
",",
"firstComment",
".",
"range",
"[",
"0",
"]",
")",
";",
"const",
"starredLines",
"=",
"commentLinesList",
".",
"map",
"(",
"line",
"=>",
"`",
"${",
"initialOffset",
"}",
"${",
"line",
"}",
"`",
")",
";",
"return",
"`",
"\\n",
"${",
"starredLines",
".",
"join",
"(",
"\"\\n\"",
")",
"}",
"\\n",
"${",
"initialOffset",
"}",
"`",
";",
"}"
] | Converts a comment into starred-block form
@param {Token} firstComment The first comment of the group being converted
@param {string[]} commentLinesList A list of lines to appear in the new starred-block comment
@returns {string} A representation of the comment value in starred-block form, excluding start and end markers | [
"Converts",
"a",
"comment",
"into",
"starred",
"-",
"block",
"form"
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/multiline-comment-style.js#L64-L69 |
3,120 | eslint/eslint | lib/rules/multiline-comment-style.js | convertToSeparateLines | function convertToSeparateLines(firstComment, commentLinesList) {
const initialOffset = sourceCode.text.slice(firstComment.range[0] - firstComment.loc.start.column, firstComment.range[0]);
const separateLines = commentLinesList.map(line => `// ${line.trim()}`);
return separateLines.join(`\n${initialOffset}`);
} | javascript | function convertToSeparateLines(firstComment, commentLinesList) {
const initialOffset = sourceCode.text.slice(firstComment.range[0] - firstComment.loc.start.column, firstComment.range[0]);
const separateLines = commentLinesList.map(line => `// ${line.trim()}`);
return separateLines.join(`\n${initialOffset}`);
} | [
"function",
"convertToSeparateLines",
"(",
"firstComment",
",",
"commentLinesList",
")",
"{",
"const",
"initialOffset",
"=",
"sourceCode",
".",
"text",
".",
"slice",
"(",
"firstComment",
".",
"range",
"[",
"0",
"]",
"-",
"firstComment",
".",
"loc",
".",
"start",
".",
"column",
",",
"firstComment",
".",
"range",
"[",
"0",
"]",
")",
";",
"const",
"separateLines",
"=",
"commentLinesList",
".",
"map",
"(",
"line",
"=>",
"`",
"${",
"line",
".",
"trim",
"(",
")",
"}",
"`",
")",
";",
"return",
"separateLines",
".",
"join",
"(",
"`",
"\\n",
"${",
"initialOffset",
"}",
"`",
")",
";",
"}"
] | Converts a comment into separate-line form
@param {Token} firstComment The first comment of the group being converted
@param {string[]} commentLinesList A list of lines to appear in the new starred-block comment
@returns {string} A representation of the comment value in separate-line form | [
"Converts",
"a",
"comment",
"into",
"separate",
"-",
"line",
"form"
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/multiline-comment-style.js#L77-L82 |
3,121 | eslint/eslint | lib/rules/multiline-comment-style.js | convertToBlock | function convertToBlock(firstComment, commentLinesList) {
const initialOffset = sourceCode.text.slice(firstComment.range[0] - firstComment.loc.start.column, firstComment.range[0]);
const blockLines = commentLinesList.map(line => line.trim());
return `/* ${blockLines.join(`\n${initialOffset} `)} */`;
} | javascript | function convertToBlock(firstComment, commentLinesList) {
const initialOffset = sourceCode.text.slice(firstComment.range[0] - firstComment.loc.start.column, firstComment.range[0]);
const blockLines = commentLinesList.map(line => line.trim());
return `/* ${blockLines.join(`\n${initialOffset} `)} */`;
} | [
"function",
"convertToBlock",
"(",
"firstComment",
",",
"commentLinesList",
")",
"{",
"const",
"initialOffset",
"=",
"sourceCode",
".",
"text",
".",
"slice",
"(",
"firstComment",
".",
"range",
"[",
"0",
"]",
"-",
"firstComment",
".",
"loc",
".",
"start",
".",
"column",
",",
"firstComment",
".",
"range",
"[",
"0",
"]",
")",
";",
"const",
"blockLines",
"=",
"commentLinesList",
".",
"map",
"(",
"line",
"=>",
"line",
".",
"trim",
"(",
")",
")",
";",
"return",
"`",
"${",
"blockLines",
".",
"join",
"(",
"`",
"\\n",
"${",
"initialOffset",
"}",
"`",
")",
"}",
"`",
";",
"}"
] | Converts a comment into bare-block form
@param {Token} firstComment The first comment of the group being converted
@param {string[]} commentLinesList A list of lines to appear in the new starred-block comment
@returns {string} A representation of the comment value in bare-block form | [
"Converts",
"a",
"comment",
"into",
"bare",
"-",
"block",
"form"
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/multiline-comment-style.js#L90-L95 |
3,122 | eslint/eslint | lib/rules/multiline-comment-style.js | isJSDoc | function isJSDoc(commentGroup) {
const lines = commentGroup[0].value.split(astUtils.LINEBREAK_MATCHER);
return commentGroup[0].type === "Block" &&
/^\*\s*$/u.test(lines[0]) &&
lines.slice(1, -1).every(line => /^\s* /u.test(line)) &&
/^\s*$/u.test(lines[lines.length - 1]);
} | javascript | function isJSDoc(commentGroup) {
const lines = commentGroup[0].value.split(astUtils.LINEBREAK_MATCHER);
return commentGroup[0].type === "Block" &&
/^\*\s*$/u.test(lines[0]) &&
lines.slice(1, -1).every(line => /^\s* /u.test(line)) &&
/^\s*$/u.test(lines[lines.length - 1]);
} | [
"function",
"isJSDoc",
"(",
"commentGroup",
")",
"{",
"const",
"lines",
"=",
"commentGroup",
"[",
"0",
"]",
".",
"value",
".",
"split",
"(",
"astUtils",
".",
"LINEBREAK_MATCHER",
")",
";",
"return",
"commentGroup",
"[",
"0",
"]",
".",
"type",
"===",
"\"Block\"",
"&&",
"/",
"^\\*\\s*$",
"/",
"u",
".",
"test",
"(",
"lines",
"[",
"0",
"]",
")",
"&&",
"lines",
".",
"slice",
"(",
"1",
",",
"-",
"1",
")",
".",
"every",
"(",
"line",
"=>",
"/",
"^\\s* ",
"/",
"u",
".",
"test",
"(",
"line",
")",
")",
"&&",
"/",
"^\\s*$",
"/",
"u",
".",
"test",
"(",
"lines",
"[",
"lines",
".",
"length",
"-",
"1",
"]",
")",
";",
"}"
] | Check a comment is JSDoc form
@param {Token[]} commentGroup A group of comments, containing either multiple line comments or a single block comment
@returns {boolean} if commentGroup is JSDoc form, return true | [
"Check",
"a",
"comment",
"is",
"JSDoc",
"form"
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/multiline-comment-style.js#L102-L109 |
3,123 | eslint/eslint | lib/code-path-analysis/code-path-analyzer.js | isIdentifierReference | function isIdentifierReference(node) {
const parent = node.parent;
switch (parent.type) {
case "LabeledStatement":
case "BreakStatement":
case "ContinueStatement":
case "ArrayPattern":
case "RestElement":
case "ImportSpecifier":
case "ImportDefaultSpecifier":
case "ImportNamespaceSpecifier":
case "CatchClause":
return false;
case "FunctionDeclaration":
case "FunctionExpression":
case "ArrowFunctionExpression":
case "ClassDeclaration":
case "ClassExpression":
case "VariableDeclarator":
return parent.id !== node;
case "Property":
case "MethodDefinition":
return (
parent.key !== node ||
parent.computed ||
parent.shorthand
);
case "AssignmentPattern":
return parent.key !== node;
default:
return true;
}
} | javascript | function isIdentifierReference(node) {
const parent = node.parent;
switch (parent.type) {
case "LabeledStatement":
case "BreakStatement":
case "ContinueStatement":
case "ArrayPattern":
case "RestElement":
case "ImportSpecifier":
case "ImportDefaultSpecifier":
case "ImportNamespaceSpecifier":
case "CatchClause":
return false;
case "FunctionDeclaration":
case "FunctionExpression":
case "ArrowFunctionExpression":
case "ClassDeclaration":
case "ClassExpression":
case "VariableDeclarator":
return parent.id !== node;
case "Property":
case "MethodDefinition":
return (
parent.key !== node ||
parent.computed ||
parent.shorthand
);
case "AssignmentPattern":
return parent.key !== node;
default:
return true;
}
} | [
"function",
"isIdentifierReference",
"(",
"node",
")",
"{",
"const",
"parent",
"=",
"node",
".",
"parent",
";",
"switch",
"(",
"parent",
".",
"type",
")",
"{",
"case",
"\"LabeledStatement\"",
":",
"case",
"\"BreakStatement\"",
":",
"case",
"\"ContinueStatement\"",
":",
"case",
"\"ArrayPattern\"",
":",
"case",
"\"RestElement\"",
":",
"case",
"\"ImportSpecifier\"",
":",
"case",
"\"ImportDefaultSpecifier\"",
":",
"case",
"\"ImportNamespaceSpecifier\"",
":",
"case",
"\"CatchClause\"",
":",
"return",
"false",
";",
"case",
"\"FunctionDeclaration\"",
":",
"case",
"\"FunctionExpression\"",
":",
"case",
"\"ArrowFunctionExpression\"",
":",
"case",
"\"ClassDeclaration\"",
":",
"case",
"\"ClassExpression\"",
":",
"case",
"\"VariableDeclarator\"",
":",
"return",
"parent",
".",
"id",
"!==",
"node",
";",
"case",
"\"Property\"",
":",
"case",
"\"MethodDefinition\"",
":",
"return",
"(",
"parent",
".",
"key",
"!==",
"node",
"||",
"parent",
".",
"computed",
"||",
"parent",
".",
"shorthand",
")",
";",
"case",
"\"AssignmentPattern\"",
":",
"return",
"parent",
".",
"key",
"!==",
"node",
";",
"default",
":",
"return",
"true",
";",
"}",
"}"
] | Checks that a given identifier node is a reference or not.
This is used to detect the first throwable node in a `try` block.
@param {ASTNode} node - An Identifier node to check.
@returns {boolean} `true` if the node is a reference. | [
"Checks",
"that",
"a",
"given",
"identifier",
"node",
"is",
"a",
"reference",
"or",
"not",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/code-path-analysis/code-path-analyzer.js#L96-L133 |
3,124 | eslint/eslint | lib/code-path-analysis/code-path-analyzer.js | leaveFromCurrentSegment | function leaveFromCurrentSegment(analyzer, node) {
const state = CodePath.getState(analyzer.codePath);
const currentSegments = state.currentSegments;
for (let i = 0; i < currentSegments.length; ++i) {
const currentSegment = currentSegments[i];
debug.dump(`onCodePathSegmentEnd ${currentSegment.id}`);
if (currentSegment.reachable) {
analyzer.emitter.emit(
"onCodePathSegmentEnd",
currentSegment,
node
);
}
}
state.currentSegments = [];
} | javascript | function leaveFromCurrentSegment(analyzer, node) {
const state = CodePath.getState(analyzer.codePath);
const currentSegments = state.currentSegments;
for (let i = 0; i < currentSegments.length; ++i) {
const currentSegment = currentSegments[i];
debug.dump(`onCodePathSegmentEnd ${currentSegment.id}`);
if (currentSegment.reachable) {
analyzer.emitter.emit(
"onCodePathSegmentEnd",
currentSegment,
node
);
}
}
state.currentSegments = [];
} | [
"function",
"leaveFromCurrentSegment",
"(",
"analyzer",
",",
"node",
")",
"{",
"const",
"state",
"=",
"CodePath",
".",
"getState",
"(",
"analyzer",
".",
"codePath",
")",
";",
"const",
"currentSegments",
"=",
"state",
".",
"currentSegments",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"currentSegments",
".",
"length",
";",
"++",
"i",
")",
"{",
"const",
"currentSegment",
"=",
"currentSegments",
"[",
"i",
"]",
";",
"debug",
".",
"dump",
"(",
"`",
"${",
"currentSegment",
".",
"id",
"}",
"`",
")",
";",
"if",
"(",
"currentSegment",
".",
"reachable",
")",
"{",
"analyzer",
".",
"emitter",
".",
"emit",
"(",
"\"onCodePathSegmentEnd\"",
",",
"currentSegment",
",",
"node",
")",
";",
"}",
"}",
"state",
".",
"currentSegments",
"=",
"[",
"]",
";",
"}"
] | Updates the current segment with empty.
This is called at the last of functions or the program.
@param {CodePathAnalyzer} analyzer - The instance.
@param {ASTNode} node - The current AST node.
@returns {void} | [
"Updates",
"the",
"current",
"segment",
"with",
"empty",
".",
"This",
"is",
"called",
"at",
"the",
"last",
"of",
"functions",
"or",
"the",
"program",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/code-path-analysis/code-path-analyzer.js#L206-L224 |
3,125 | eslint/eslint | lib/code-path-analysis/code-path-analyzer.js | preprocess | function preprocess(analyzer, node) {
const codePath = analyzer.codePath;
const state = CodePath.getState(codePath);
const parent = node.parent;
switch (parent.type) {
case "LogicalExpression":
if (
parent.right === node &&
isHandledLogicalOperator(parent.operator)
) {
state.makeLogicalRight();
}
break;
case "ConditionalExpression":
case "IfStatement":
/*
* Fork if this node is at `consequent`/`alternate`.
* `popForkContext()` exists at `IfStatement:exit` and
* `ConditionalExpression:exit`.
*/
if (parent.consequent === node) {
state.makeIfConsequent();
} else if (parent.alternate === node) {
state.makeIfAlternate();
}
break;
case "SwitchCase":
if (parent.consequent[0] === node) {
state.makeSwitchCaseBody(false, !parent.test);
}
break;
case "TryStatement":
if (parent.handler === node) {
state.makeCatchBlock();
} else if (parent.finalizer === node) {
state.makeFinallyBlock();
}
break;
case "WhileStatement":
if (parent.test === node) {
state.makeWhileTest(getBooleanValueIfSimpleConstant(node));
} else {
assert(parent.body === node);
state.makeWhileBody();
}
break;
case "DoWhileStatement":
if (parent.body === node) {
state.makeDoWhileBody();
} else {
assert(parent.test === node);
state.makeDoWhileTest(getBooleanValueIfSimpleConstant(node));
}
break;
case "ForStatement":
if (parent.test === node) {
state.makeForTest(getBooleanValueIfSimpleConstant(node));
} else if (parent.update === node) {
state.makeForUpdate();
} else if (parent.body === node) {
state.makeForBody();
}
break;
case "ForInStatement":
case "ForOfStatement":
if (parent.left === node) {
state.makeForInOfLeft();
} else if (parent.right === node) {
state.makeForInOfRight();
} else {
assert(parent.body === node);
state.makeForInOfBody();
}
break;
case "AssignmentPattern":
/*
* Fork if this node is at `right`.
* `left` is executed always, so it uses the current path.
* `popForkContext()` exists at `AssignmentPattern:exit`.
*/
if (parent.right === node) {
state.pushForkContext();
state.forkBypassPath();
state.forkPath();
}
break;
default:
break;
}
} | javascript | function preprocess(analyzer, node) {
const codePath = analyzer.codePath;
const state = CodePath.getState(codePath);
const parent = node.parent;
switch (parent.type) {
case "LogicalExpression":
if (
parent.right === node &&
isHandledLogicalOperator(parent.operator)
) {
state.makeLogicalRight();
}
break;
case "ConditionalExpression":
case "IfStatement":
/*
* Fork if this node is at `consequent`/`alternate`.
* `popForkContext()` exists at `IfStatement:exit` and
* `ConditionalExpression:exit`.
*/
if (parent.consequent === node) {
state.makeIfConsequent();
} else if (parent.alternate === node) {
state.makeIfAlternate();
}
break;
case "SwitchCase":
if (parent.consequent[0] === node) {
state.makeSwitchCaseBody(false, !parent.test);
}
break;
case "TryStatement":
if (parent.handler === node) {
state.makeCatchBlock();
} else if (parent.finalizer === node) {
state.makeFinallyBlock();
}
break;
case "WhileStatement":
if (parent.test === node) {
state.makeWhileTest(getBooleanValueIfSimpleConstant(node));
} else {
assert(parent.body === node);
state.makeWhileBody();
}
break;
case "DoWhileStatement":
if (parent.body === node) {
state.makeDoWhileBody();
} else {
assert(parent.test === node);
state.makeDoWhileTest(getBooleanValueIfSimpleConstant(node));
}
break;
case "ForStatement":
if (parent.test === node) {
state.makeForTest(getBooleanValueIfSimpleConstant(node));
} else if (parent.update === node) {
state.makeForUpdate();
} else if (parent.body === node) {
state.makeForBody();
}
break;
case "ForInStatement":
case "ForOfStatement":
if (parent.left === node) {
state.makeForInOfLeft();
} else if (parent.right === node) {
state.makeForInOfRight();
} else {
assert(parent.body === node);
state.makeForInOfBody();
}
break;
case "AssignmentPattern":
/*
* Fork if this node is at `right`.
* `left` is executed always, so it uses the current path.
* `popForkContext()` exists at `AssignmentPattern:exit`.
*/
if (parent.right === node) {
state.pushForkContext();
state.forkBypassPath();
state.forkPath();
}
break;
default:
break;
}
} | [
"function",
"preprocess",
"(",
"analyzer",
",",
"node",
")",
"{",
"const",
"codePath",
"=",
"analyzer",
".",
"codePath",
";",
"const",
"state",
"=",
"CodePath",
".",
"getState",
"(",
"codePath",
")",
";",
"const",
"parent",
"=",
"node",
".",
"parent",
";",
"switch",
"(",
"parent",
".",
"type",
")",
"{",
"case",
"\"LogicalExpression\"",
":",
"if",
"(",
"parent",
".",
"right",
"===",
"node",
"&&",
"isHandledLogicalOperator",
"(",
"parent",
".",
"operator",
")",
")",
"{",
"state",
".",
"makeLogicalRight",
"(",
")",
";",
"}",
"break",
";",
"case",
"\"ConditionalExpression\"",
":",
"case",
"\"IfStatement\"",
":",
"/*\n * Fork if this node is at `consequent`/`alternate`.\n * `popForkContext()` exists at `IfStatement:exit` and\n * `ConditionalExpression:exit`.\n */",
"if",
"(",
"parent",
".",
"consequent",
"===",
"node",
")",
"{",
"state",
".",
"makeIfConsequent",
"(",
")",
";",
"}",
"else",
"if",
"(",
"parent",
".",
"alternate",
"===",
"node",
")",
"{",
"state",
".",
"makeIfAlternate",
"(",
")",
";",
"}",
"break",
";",
"case",
"\"SwitchCase\"",
":",
"if",
"(",
"parent",
".",
"consequent",
"[",
"0",
"]",
"===",
"node",
")",
"{",
"state",
".",
"makeSwitchCaseBody",
"(",
"false",
",",
"!",
"parent",
".",
"test",
")",
";",
"}",
"break",
";",
"case",
"\"TryStatement\"",
":",
"if",
"(",
"parent",
".",
"handler",
"===",
"node",
")",
"{",
"state",
".",
"makeCatchBlock",
"(",
")",
";",
"}",
"else",
"if",
"(",
"parent",
".",
"finalizer",
"===",
"node",
")",
"{",
"state",
".",
"makeFinallyBlock",
"(",
")",
";",
"}",
"break",
";",
"case",
"\"WhileStatement\"",
":",
"if",
"(",
"parent",
".",
"test",
"===",
"node",
")",
"{",
"state",
".",
"makeWhileTest",
"(",
"getBooleanValueIfSimpleConstant",
"(",
"node",
")",
")",
";",
"}",
"else",
"{",
"assert",
"(",
"parent",
".",
"body",
"===",
"node",
")",
";",
"state",
".",
"makeWhileBody",
"(",
")",
";",
"}",
"break",
";",
"case",
"\"DoWhileStatement\"",
":",
"if",
"(",
"parent",
".",
"body",
"===",
"node",
")",
"{",
"state",
".",
"makeDoWhileBody",
"(",
")",
";",
"}",
"else",
"{",
"assert",
"(",
"parent",
".",
"test",
"===",
"node",
")",
";",
"state",
".",
"makeDoWhileTest",
"(",
"getBooleanValueIfSimpleConstant",
"(",
"node",
")",
")",
";",
"}",
"break",
";",
"case",
"\"ForStatement\"",
":",
"if",
"(",
"parent",
".",
"test",
"===",
"node",
")",
"{",
"state",
".",
"makeForTest",
"(",
"getBooleanValueIfSimpleConstant",
"(",
"node",
")",
")",
";",
"}",
"else",
"if",
"(",
"parent",
".",
"update",
"===",
"node",
")",
"{",
"state",
".",
"makeForUpdate",
"(",
")",
";",
"}",
"else",
"if",
"(",
"parent",
".",
"body",
"===",
"node",
")",
"{",
"state",
".",
"makeForBody",
"(",
")",
";",
"}",
"break",
";",
"case",
"\"ForInStatement\"",
":",
"case",
"\"ForOfStatement\"",
":",
"if",
"(",
"parent",
".",
"left",
"===",
"node",
")",
"{",
"state",
".",
"makeForInOfLeft",
"(",
")",
";",
"}",
"else",
"if",
"(",
"parent",
".",
"right",
"===",
"node",
")",
"{",
"state",
".",
"makeForInOfRight",
"(",
")",
";",
"}",
"else",
"{",
"assert",
"(",
"parent",
".",
"body",
"===",
"node",
")",
";",
"state",
".",
"makeForInOfBody",
"(",
")",
";",
"}",
"break",
";",
"case",
"\"AssignmentPattern\"",
":",
"/*\n * Fork if this node is at `right`.\n * `left` is executed always, so it uses the current path.\n * `popForkContext()` exists at `AssignmentPattern:exit`.\n */",
"if",
"(",
"parent",
".",
"right",
"===",
"node",
")",
"{",
"state",
".",
"pushForkContext",
"(",
")",
";",
"state",
".",
"forkBypassPath",
"(",
")",
";",
"state",
".",
"forkPath",
"(",
")",
";",
"}",
"break",
";",
"default",
":",
"break",
";",
"}",
"}"
] | Updates the code path due to the position of a given node in the parent node
thereof.
For example, if the node is `parent.consequent`, this creates a fork from the
current path.
@param {CodePathAnalyzer} analyzer - The instance.
@param {ASTNode} node - The current AST node.
@returns {void} | [
"Updates",
"the",
"code",
"path",
"due",
"to",
"the",
"position",
"of",
"a",
"given",
"node",
"in",
"the",
"parent",
"node",
"thereof",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/code-path-analysis/code-path-analyzer.js#L237-L338 |
3,126 | eslint/eslint | lib/code-path-analysis/code-path-analyzer.js | processCodePathToEnter | function processCodePathToEnter(analyzer, node) {
let codePath = analyzer.codePath;
let state = codePath && CodePath.getState(codePath);
const parent = node.parent;
switch (node.type) {
case "Program":
case "FunctionDeclaration":
case "FunctionExpression":
case "ArrowFunctionExpression":
if (codePath) {
// Emits onCodePathSegmentStart events if updated.
forwardCurrentToHead(analyzer, node);
debug.dumpState(node, state, false);
}
// Create the code path of this scope.
codePath = analyzer.codePath = new CodePath(
analyzer.idGenerator.next(),
codePath,
analyzer.onLooped
);
state = CodePath.getState(codePath);
// Emits onCodePathStart events.
debug.dump(`onCodePathStart ${codePath.id}`);
analyzer.emitter.emit("onCodePathStart", codePath, node);
break;
case "LogicalExpression":
if (isHandledLogicalOperator(node.operator)) {
state.pushChoiceContext(
node.operator,
isForkingByTrueOrFalse(node)
);
}
break;
case "ConditionalExpression":
case "IfStatement":
state.pushChoiceContext("test", false);
break;
case "SwitchStatement":
state.pushSwitchContext(
node.cases.some(isCaseNode),
astUtils.getLabel(node)
);
break;
case "TryStatement":
state.pushTryContext(Boolean(node.finalizer));
break;
case "SwitchCase":
/*
* Fork if this node is after the 2st node in `cases`.
* It's similar to `else` blocks.
* The next `test` node is processed in this path.
*/
if (parent.discriminant !== node && parent.cases[0] !== node) {
state.forkPath();
}
break;
case "WhileStatement":
case "DoWhileStatement":
case "ForStatement":
case "ForInStatement":
case "ForOfStatement":
state.pushLoopContext(node.type, astUtils.getLabel(node));
break;
case "LabeledStatement":
if (!astUtils.isBreakableStatement(node.body)) {
state.pushBreakContext(false, node.label.name);
}
break;
default:
break;
}
// Emits onCodePathSegmentStart events if updated.
forwardCurrentToHead(analyzer, node);
debug.dumpState(node, state, false);
} | javascript | function processCodePathToEnter(analyzer, node) {
let codePath = analyzer.codePath;
let state = codePath && CodePath.getState(codePath);
const parent = node.parent;
switch (node.type) {
case "Program":
case "FunctionDeclaration":
case "FunctionExpression":
case "ArrowFunctionExpression":
if (codePath) {
// Emits onCodePathSegmentStart events if updated.
forwardCurrentToHead(analyzer, node);
debug.dumpState(node, state, false);
}
// Create the code path of this scope.
codePath = analyzer.codePath = new CodePath(
analyzer.idGenerator.next(),
codePath,
analyzer.onLooped
);
state = CodePath.getState(codePath);
// Emits onCodePathStart events.
debug.dump(`onCodePathStart ${codePath.id}`);
analyzer.emitter.emit("onCodePathStart", codePath, node);
break;
case "LogicalExpression":
if (isHandledLogicalOperator(node.operator)) {
state.pushChoiceContext(
node.operator,
isForkingByTrueOrFalse(node)
);
}
break;
case "ConditionalExpression":
case "IfStatement":
state.pushChoiceContext("test", false);
break;
case "SwitchStatement":
state.pushSwitchContext(
node.cases.some(isCaseNode),
astUtils.getLabel(node)
);
break;
case "TryStatement":
state.pushTryContext(Boolean(node.finalizer));
break;
case "SwitchCase":
/*
* Fork if this node is after the 2st node in `cases`.
* It's similar to `else` blocks.
* The next `test` node is processed in this path.
*/
if (parent.discriminant !== node && parent.cases[0] !== node) {
state.forkPath();
}
break;
case "WhileStatement":
case "DoWhileStatement":
case "ForStatement":
case "ForInStatement":
case "ForOfStatement":
state.pushLoopContext(node.type, astUtils.getLabel(node));
break;
case "LabeledStatement":
if (!astUtils.isBreakableStatement(node.body)) {
state.pushBreakContext(false, node.label.name);
}
break;
default:
break;
}
// Emits onCodePathSegmentStart events if updated.
forwardCurrentToHead(analyzer, node);
debug.dumpState(node, state, false);
} | [
"function",
"processCodePathToEnter",
"(",
"analyzer",
",",
"node",
")",
"{",
"let",
"codePath",
"=",
"analyzer",
".",
"codePath",
";",
"let",
"state",
"=",
"codePath",
"&&",
"CodePath",
".",
"getState",
"(",
"codePath",
")",
";",
"const",
"parent",
"=",
"node",
".",
"parent",
";",
"switch",
"(",
"node",
".",
"type",
")",
"{",
"case",
"\"Program\"",
":",
"case",
"\"FunctionDeclaration\"",
":",
"case",
"\"FunctionExpression\"",
":",
"case",
"\"ArrowFunctionExpression\"",
":",
"if",
"(",
"codePath",
")",
"{",
"// Emits onCodePathSegmentStart events if updated.",
"forwardCurrentToHead",
"(",
"analyzer",
",",
"node",
")",
";",
"debug",
".",
"dumpState",
"(",
"node",
",",
"state",
",",
"false",
")",
";",
"}",
"// Create the code path of this scope.",
"codePath",
"=",
"analyzer",
".",
"codePath",
"=",
"new",
"CodePath",
"(",
"analyzer",
".",
"idGenerator",
".",
"next",
"(",
")",
",",
"codePath",
",",
"analyzer",
".",
"onLooped",
")",
";",
"state",
"=",
"CodePath",
".",
"getState",
"(",
"codePath",
")",
";",
"// Emits onCodePathStart events.",
"debug",
".",
"dump",
"(",
"`",
"${",
"codePath",
".",
"id",
"}",
"`",
")",
";",
"analyzer",
".",
"emitter",
".",
"emit",
"(",
"\"onCodePathStart\"",
",",
"codePath",
",",
"node",
")",
";",
"break",
";",
"case",
"\"LogicalExpression\"",
":",
"if",
"(",
"isHandledLogicalOperator",
"(",
"node",
".",
"operator",
")",
")",
"{",
"state",
".",
"pushChoiceContext",
"(",
"node",
".",
"operator",
",",
"isForkingByTrueOrFalse",
"(",
"node",
")",
")",
";",
"}",
"break",
";",
"case",
"\"ConditionalExpression\"",
":",
"case",
"\"IfStatement\"",
":",
"state",
".",
"pushChoiceContext",
"(",
"\"test\"",
",",
"false",
")",
";",
"break",
";",
"case",
"\"SwitchStatement\"",
":",
"state",
".",
"pushSwitchContext",
"(",
"node",
".",
"cases",
".",
"some",
"(",
"isCaseNode",
")",
",",
"astUtils",
".",
"getLabel",
"(",
"node",
")",
")",
";",
"break",
";",
"case",
"\"TryStatement\"",
":",
"state",
".",
"pushTryContext",
"(",
"Boolean",
"(",
"node",
".",
"finalizer",
")",
")",
";",
"break",
";",
"case",
"\"SwitchCase\"",
":",
"/*\n * Fork if this node is after the 2st node in `cases`.\n * It's similar to `else` blocks.\n * The next `test` node is processed in this path.\n */",
"if",
"(",
"parent",
".",
"discriminant",
"!==",
"node",
"&&",
"parent",
".",
"cases",
"[",
"0",
"]",
"!==",
"node",
")",
"{",
"state",
".",
"forkPath",
"(",
")",
";",
"}",
"break",
";",
"case",
"\"WhileStatement\"",
":",
"case",
"\"DoWhileStatement\"",
":",
"case",
"\"ForStatement\"",
":",
"case",
"\"ForInStatement\"",
":",
"case",
"\"ForOfStatement\"",
":",
"state",
".",
"pushLoopContext",
"(",
"node",
".",
"type",
",",
"astUtils",
".",
"getLabel",
"(",
"node",
")",
")",
";",
"break",
";",
"case",
"\"LabeledStatement\"",
":",
"if",
"(",
"!",
"astUtils",
".",
"isBreakableStatement",
"(",
"node",
".",
"body",
")",
")",
"{",
"state",
".",
"pushBreakContext",
"(",
"false",
",",
"node",
".",
"label",
".",
"name",
")",
";",
"}",
"break",
";",
"default",
":",
"break",
";",
"}",
"// Emits onCodePathSegmentStart events if updated.",
"forwardCurrentToHead",
"(",
"analyzer",
",",
"node",
")",
";",
"debug",
".",
"dumpState",
"(",
"node",
",",
"state",
",",
"false",
")",
";",
"}"
] | Updates the code path due to the type of a given node in entering.
@param {CodePathAnalyzer} analyzer - The instance.
@param {ASTNode} node - The current AST node.
@returns {void} | [
"Updates",
"the",
"code",
"path",
"due",
"to",
"the",
"type",
"of",
"a",
"given",
"node",
"in",
"entering",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/code-path-analysis/code-path-analyzer.js#L347-L435 |
3,127 | eslint/eslint | lib/code-path-analysis/code-path-analyzer.js | processCodePathToExit | function processCodePathToExit(analyzer, node) {
const codePath = analyzer.codePath;
const state = CodePath.getState(codePath);
let dontForward = false;
switch (node.type) {
case "IfStatement":
case "ConditionalExpression":
state.popChoiceContext();
break;
case "LogicalExpression":
if (isHandledLogicalOperator(node.operator)) {
state.popChoiceContext();
}
break;
case "SwitchStatement":
state.popSwitchContext();
break;
case "SwitchCase":
/*
* This is the same as the process at the 1st `consequent` node in
* `preprocess` function.
* Must do if this `consequent` is empty.
*/
if (node.consequent.length === 0) {
state.makeSwitchCaseBody(true, !node.test);
}
if (state.forkContext.reachable) {
dontForward = true;
}
break;
case "TryStatement":
state.popTryContext();
break;
case "BreakStatement":
forwardCurrentToHead(analyzer, node);
state.makeBreak(node.label && node.label.name);
dontForward = true;
break;
case "ContinueStatement":
forwardCurrentToHead(analyzer, node);
state.makeContinue(node.label && node.label.name);
dontForward = true;
break;
case "ReturnStatement":
forwardCurrentToHead(analyzer, node);
state.makeReturn();
dontForward = true;
break;
case "ThrowStatement":
forwardCurrentToHead(analyzer, node);
state.makeThrow();
dontForward = true;
break;
case "Identifier":
if (isIdentifierReference(node)) {
state.makeFirstThrowablePathInTryBlock();
dontForward = true;
}
break;
case "CallExpression":
case "MemberExpression":
case "NewExpression":
state.makeFirstThrowablePathInTryBlock();
break;
case "WhileStatement":
case "DoWhileStatement":
case "ForStatement":
case "ForInStatement":
case "ForOfStatement":
state.popLoopContext();
break;
case "AssignmentPattern":
state.popForkContext();
break;
case "LabeledStatement":
if (!astUtils.isBreakableStatement(node.body)) {
state.popBreakContext();
}
break;
default:
break;
}
// Emits onCodePathSegmentStart events if updated.
if (!dontForward) {
forwardCurrentToHead(analyzer, node);
}
debug.dumpState(node, state, true);
} | javascript | function processCodePathToExit(analyzer, node) {
const codePath = analyzer.codePath;
const state = CodePath.getState(codePath);
let dontForward = false;
switch (node.type) {
case "IfStatement":
case "ConditionalExpression":
state.popChoiceContext();
break;
case "LogicalExpression":
if (isHandledLogicalOperator(node.operator)) {
state.popChoiceContext();
}
break;
case "SwitchStatement":
state.popSwitchContext();
break;
case "SwitchCase":
/*
* This is the same as the process at the 1st `consequent` node in
* `preprocess` function.
* Must do if this `consequent` is empty.
*/
if (node.consequent.length === 0) {
state.makeSwitchCaseBody(true, !node.test);
}
if (state.forkContext.reachable) {
dontForward = true;
}
break;
case "TryStatement":
state.popTryContext();
break;
case "BreakStatement":
forwardCurrentToHead(analyzer, node);
state.makeBreak(node.label && node.label.name);
dontForward = true;
break;
case "ContinueStatement":
forwardCurrentToHead(analyzer, node);
state.makeContinue(node.label && node.label.name);
dontForward = true;
break;
case "ReturnStatement":
forwardCurrentToHead(analyzer, node);
state.makeReturn();
dontForward = true;
break;
case "ThrowStatement":
forwardCurrentToHead(analyzer, node);
state.makeThrow();
dontForward = true;
break;
case "Identifier":
if (isIdentifierReference(node)) {
state.makeFirstThrowablePathInTryBlock();
dontForward = true;
}
break;
case "CallExpression":
case "MemberExpression":
case "NewExpression":
state.makeFirstThrowablePathInTryBlock();
break;
case "WhileStatement":
case "DoWhileStatement":
case "ForStatement":
case "ForInStatement":
case "ForOfStatement":
state.popLoopContext();
break;
case "AssignmentPattern":
state.popForkContext();
break;
case "LabeledStatement":
if (!astUtils.isBreakableStatement(node.body)) {
state.popBreakContext();
}
break;
default:
break;
}
// Emits onCodePathSegmentStart events if updated.
if (!dontForward) {
forwardCurrentToHead(analyzer, node);
}
debug.dumpState(node, state, true);
} | [
"function",
"processCodePathToExit",
"(",
"analyzer",
",",
"node",
")",
"{",
"const",
"codePath",
"=",
"analyzer",
".",
"codePath",
";",
"const",
"state",
"=",
"CodePath",
".",
"getState",
"(",
"codePath",
")",
";",
"let",
"dontForward",
"=",
"false",
";",
"switch",
"(",
"node",
".",
"type",
")",
"{",
"case",
"\"IfStatement\"",
":",
"case",
"\"ConditionalExpression\"",
":",
"state",
".",
"popChoiceContext",
"(",
")",
";",
"break",
";",
"case",
"\"LogicalExpression\"",
":",
"if",
"(",
"isHandledLogicalOperator",
"(",
"node",
".",
"operator",
")",
")",
"{",
"state",
".",
"popChoiceContext",
"(",
")",
";",
"}",
"break",
";",
"case",
"\"SwitchStatement\"",
":",
"state",
".",
"popSwitchContext",
"(",
")",
";",
"break",
";",
"case",
"\"SwitchCase\"",
":",
"/*\n * This is the same as the process at the 1st `consequent` node in\n * `preprocess` function.\n * Must do if this `consequent` is empty.\n */",
"if",
"(",
"node",
".",
"consequent",
".",
"length",
"===",
"0",
")",
"{",
"state",
".",
"makeSwitchCaseBody",
"(",
"true",
",",
"!",
"node",
".",
"test",
")",
";",
"}",
"if",
"(",
"state",
".",
"forkContext",
".",
"reachable",
")",
"{",
"dontForward",
"=",
"true",
";",
"}",
"break",
";",
"case",
"\"TryStatement\"",
":",
"state",
".",
"popTryContext",
"(",
")",
";",
"break",
";",
"case",
"\"BreakStatement\"",
":",
"forwardCurrentToHead",
"(",
"analyzer",
",",
"node",
")",
";",
"state",
".",
"makeBreak",
"(",
"node",
".",
"label",
"&&",
"node",
".",
"label",
".",
"name",
")",
";",
"dontForward",
"=",
"true",
";",
"break",
";",
"case",
"\"ContinueStatement\"",
":",
"forwardCurrentToHead",
"(",
"analyzer",
",",
"node",
")",
";",
"state",
".",
"makeContinue",
"(",
"node",
".",
"label",
"&&",
"node",
".",
"label",
".",
"name",
")",
";",
"dontForward",
"=",
"true",
";",
"break",
";",
"case",
"\"ReturnStatement\"",
":",
"forwardCurrentToHead",
"(",
"analyzer",
",",
"node",
")",
";",
"state",
".",
"makeReturn",
"(",
")",
";",
"dontForward",
"=",
"true",
";",
"break",
";",
"case",
"\"ThrowStatement\"",
":",
"forwardCurrentToHead",
"(",
"analyzer",
",",
"node",
")",
";",
"state",
".",
"makeThrow",
"(",
")",
";",
"dontForward",
"=",
"true",
";",
"break",
";",
"case",
"\"Identifier\"",
":",
"if",
"(",
"isIdentifierReference",
"(",
"node",
")",
")",
"{",
"state",
".",
"makeFirstThrowablePathInTryBlock",
"(",
")",
";",
"dontForward",
"=",
"true",
";",
"}",
"break",
";",
"case",
"\"CallExpression\"",
":",
"case",
"\"MemberExpression\"",
":",
"case",
"\"NewExpression\"",
":",
"state",
".",
"makeFirstThrowablePathInTryBlock",
"(",
")",
";",
"break",
";",
"case",
"\"WhileStatement\"",
":",
"case",
"\"DoWhileStatement\"",
":",
"case",
"\"ForStatement\"",
":",
"case",
"\"ForInStatement\"",
":",
"case",
"\"ForOfStatement\"",
":",
"state",
".",
"popLoopContext",
"(",
")",
";",
"break",
";",
"case",
"\"AssignmentPattern\"",
":",
"state",
".",
"popForkContext",
"(",
")",
";",
"break",
";",
"case",
"\"LabeledStatement\"",
":",
"if",
"(",
"!",
"astUtils",
".",
"isBreakableStatement",
"(",
"node",
".",
"body",
")",
")",
"{",
"state",
".",
"popBreakContext",
"(",
")",
";",
"}",
"break",
";",
"default",
":",
"break",
";",
"}",
"// Emits onCodePathSegmentStart events if updated.",
"if",
"(",
"!",
"dontForward",
")",
"{",
"forwardCurrentToHead",
"(",
"analyzer",
",",
"node",
")",
";",
"}",
"debug",
".",
"dumpState",
"(",
"node",
",",
"state",
",",
"true",
")",
";",
"}"
] | Updates the code path due to the type of a given node in leaving.
@param {CodePathAnalyzer} analyzer - The instance.
@param {ASTNode} node - The current AST node.
@returns {void} | [
"Updates",
"the",
"code",
"path",
"due",
"to",
"the",
"type",
"of",
"a",
"given",
"node",
"in",
"leaving",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/code-path-analysis/code-path-analyzer.js#L444-L548 |
3,128 | eslint/eslint | lib/rules/operator-assignment.js | getOperatorToken | function getOperatorToken(node) {
return sourceCode.getFirstTokenBetween(node.left, node.right, token => token.value === node.operator);
} | javascript | function getOperatorToken(node) {
return sourceCode.getFirstTokenBetween(node.left, node.right, token => token.value === node.operator);
} | [
"function",
"getOperatorToken",
"(",
"node",
")",
"{",
"return",
"sourceCode",
".",
"getFirstTokenBetween",
"(",
"node",
".",
"left",
",",
"node",
".",
"right",
",",
"token",
"=>",
"token",
".",
"value",
"===",
"node",
".",
"operator",
")",
";",
"}"
] | Returns the operator token of an AssignmentExpression or BinaryExpression
@param {ASTNode} node An AssignmentExpression or BinaryExpression node
@returns {Token} The operator token in the node | [
"Returns",
"the",
"operator",
"token",
"of",
"an",
"AssignmentExpression",
"or",
"BinaryExpression"
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/operator-assignment.js#L123-L125 |
3,129 | eslint/eslint | lib/rules/operator-assignment.js | verify | function verify(node) {
if (node.operator !== "=" || node.right.type !== "BinaryExpression") {
return;
}
const left = node.left;
const expr = node.right;
const operator = expr.operator;
if (isCommutativeOperatorWithShorthand(operator) || isNonCommutativeOperatorWithShorthand(operator)) {
if (same(left, expr.left)) {
context.report({
node,
messageId: "replaced",
fix(fixer) {
if (canBeFixed(left)) {
const equalsToken = getOperatorToken(node);
const operatorToken = getOperatorToken(expr);
const leftText = sourceCode.getText().slice(node.range[0], equalsToken.range[0]);
const rightText = sourceCode.getText().slice(operatorToken.range[1], node.right.range[1]);
return fixer.replaceText(node, `${leftText}${expr.operator}=${rightText}`);
}
return null;
}
});
} else if (same(left, expr.right) && isCommutativeOperatorWithShorthand(operator)) {
/*
* This case can't be fixed safely.
* If `a` and `b` both have custom valueOf() behavior, then fixing `a = b * a` to `a *= b` would
* change the execution order of the valueOf() functions.
*/
context.report({
node,
messageId: "replaced"
});
}
}
} | javascript | function verify(node) {
if (node.operator !== "=" || node.right.type !== "BinaryExpression") {
return;
}
const left = node.left;
const expr = node.right;
const operator = expr.operator;
if (isCommutativeOperatorWithShorthand(operator) || isNonCommutativeOperatorWithShorthand(operator)) {
if (same(left, expr.left)) {
context.report({
node,
messageId: "replaced",
fix(fixer) {
if (canBeFixed(left)) {
const equalsToken = getOperatorToken(node);
const operatorToken = getOperatorToken(expr);
const leftText = sourceCode.getText().slice(node.range[0], equalsToken.range[0]);
const rightText = sourceCode.getText().slice(operatorToken.range[1], node.right.range[1]);
return fixer.replaceText(node, `${leftText}${expr.operator}=${rightText}`);
}
return null;
}
});
} else if (same(left, expr.right) && isCommutativeOperatorWithShorthand(operator)) {
/*
* This case can't be fixed safely.
* If `a` and `b` both have custom valueOf() behavior, then fixing `a = b * a` to `a *= b` would
* change the execution order of the valueOf() functions.
*/
context.report({
node,
messageId: "replaced"
});
}
}
} | [
"function",
"verify",
"(",
"node",
")",
"{",
"if",
"(",
"node",
".",
"operator",
"!==",
"\"=\"",
"||",
"node",
".",
"right",
".",
"type",
"!==",
"\"BinaryExpression\"",
")",
"{",
"return",
";",
"}",
"const",
"left",
"=",
"node",
".",
"left",
";",
"const",
"expr",
"=",
"node",
".",
"right",
";",
"const",
"operator",
"=",
"expr",
".",
"operator",
";",
"if",
"(",
"isCommutativeOperatorWithShorthand",
"(",
"operator",
")",
"||",
"isNonCommutativeOperatorWithShorthand",
"(",
"operator",
")",
")",
"{",
"if",
"(",
"same",
"(",
"left",
",",
"expr",
".",
"left",
")",
")",
"{",
"context",
".",
"report",
"(",
"{",
"node",
",",
"messageId",
":",
"\"replaced\"",
",",
"fix",
"(",
"fixer",
")",
"{",
"if",
"(",
"canBeFixed",
"(",
"left",
")",
")",
"{",
"const",
"equalsToken",
"=",
"getOperatorToken",
"(",
"node",
")",
";",
"const",
"operatorToken",
"=",
"getOperatorToken",
"(",
"expr",
")",
";",
"const",
"leftText",
"=",
"sourceCode",
".",
"getText",
"(",
")",
".",
"slice",
"(",
"node",
".",
"range",
"[",
"0",
"]",
",",
"equalsToken",
".",
"range",
"[",
"0",
"]",
")",
";",
"const",
"rightText",
"=",
"sourceCode",
".",
"getText",
"(",
")",
".",
"slice",
"(",
"operatorToken",
".",
"range",
"[",
"1",
"]",
",",
"node",
".",
"right",
".",
"range",
"[",
"1",
"]",
")",
";",
"return",
"fixer",
".",
"replaceText",
"(",
"node",
",",
"`",
"${",
"leftText",
"}",
"${",
"expr",
".",
"operator",
"}",
"${",
"rightText",
"}",
"`",
")",
";",
"}",
"return",
"null",
";",
"}",
"}",
")",
";",
"}",
"else",
"if",
"(",
"same",
"(",
"left",
",",
"expr",
".",
"right",
")",
"&&",
"isCommutativeOperatorWithShorthand",
"(",
"operator",
")",
")",
"{",
"/*\n * This case can't be fixed safely.\n * If `a` and `b` both have custom valueOf() behavior, then fixing `a = b * a` to `a *= b` would\n * change the execution order of the valueOf() functions.\n */",
"context",
".",
"report",
"(",
"{",
"node",
",",
"messageId",
":",
"\"replaced\"",
"}",
")",
";",
"}",
"}",
"}"
] | Ensures that an assignment uses the shorthand form where possible.
@param {ASTNode} node An AssignmentExpression node.
@returns {void} | [
"Ensures",
"that",
"an",
"assignment",
"uses",
"the",
"shorthand",
"form",
"where",
"possible",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/operator-assignment.js#L132-L171 |
3,130 | eslint/eslint | lib/rules/operator-assignment.js | prohibit | function prohibit(node) {
if (node.operator !== "=") {
context.report({
node,
messageId: "unexpected",
fix(fixer) {
if (canBeFixed(node.left)) {
const operatorToken = getOperatorToken(node);
const leftText = sourceCode.getText().slice(node.range[0], operatorToken.range[0]);
const newOperator = node.operator.slice(0, -1);
let rightText;
// If this change would modify precedence (e.g. `foo *= bar + 1` => `foo = foo * (bar + 1)`), parenthesize the right side.
if (
astUtils.getPrecedence(node.right) <= astUtils.getPrecedence({ type: "BinaryExpression", operator: newOperator }) &&
!astUtils.isParenthesised(sourceCode, node.right)
) {
rightText = `${sourceCode.text.slice(operatorToken.range[1], node.right.range[0])}(${sourceCode.getText(node.right)})`;
} else {
rightText = sourceCode.text.slice(operatorToken.range[1], node.range[1]);
}
return fixer.replaceText(node, `${leftText}= ${leftText}${newOperator}${rightText}`);
}
return null;
}
});
}
} | javascript | function prohibit(node) {
if (node.operator !== "=") {
context.report({
node,
messageId: "unexpected",
fix(fixer) {
if (canBeFixed(node.left)) {
const operatorToken = getOperatorToken(node);
const leftText = sourceCode.getText().slice(node.range[0], operatorToken.range[0]);
const newOperator = node.operator.slice(0, -1);
let rightText;
// If this change would modify precedence (e.g. `foo *= bar + 1` => `foo = foo * (bar + 1)`), parenthesize the right side.
if (
astUtils.getPrecedence(node.right) <= astUtils.getPrecedence({ type: "BinaryExpression", operator: newOperator }) &&
!astUtils.isParenthesised(sourceCode, node.right)
) {
rightText = `${sourceCode.text.slice(operatorToken.range[1], node.right.range[0])}(${sourceCode.getText(node.right)})`;
} else {
rightText = sourceCode.text.slice(operatorToken.range[1], node.range[1]);
}
return fixer.replaceText(node, `${leftText}= ${leftText}${newOperator}${rightText}`);
}
return null;
}
});
}
} | [
"function",
"prohibit",
"(",
"node",
")",
"{",
"if",
"(",
"node",
".",
"operator",
"!==",
"\"=\"",
")",
"{",
"context",
".",
"report",
"(",
"{",
"node",
",",
"messageId",
":",
"\"unexpected\"",
",",
"fix",
"(",
"fixer",
")",
"{",
"if",
"(",
"canBeFixed",
"(",
"node",
".",
"left",
")",
")",
"{",
"const",
"operatorToken",
"=",
"getOperatorToken",
"(",
"node",
")",
";",
"const",
"leftText",
"=",
"sourceCode",
".",
"getText",
"(",
")",
".",
"slice",
"(",
"node",
".",
"range",
"[",
"0",
"]",
",",
"operatorToken",
".",
"range",
"[",
"0",
"]",
")",
";",
"const",
"newOperator",
"=",
"node",
".",
"operator",
".",
"slice",
"(",
"0",
",",
"-",
"1",
")",
";",
"let",
"rightText",
";",
"// If this change would modify precedence (e.g. `foo *= bar + 1` => `foo = foo * (bar + 1)`), parenthesize the right side.",
"if",
"(",
"astUtils",
".",
"getPrecedence",
"(",
"node",
".",
"right",
")",
"<=",
"astUtils",
".",
"getPrecedence",
"(",
"{",
"type",
":",
"\"BinaryExpression\"",
",",
"operator",
":",
"newOperator",
"}",
")",
"&&",
"!",
"astUtils",
".",
"isParenthesised",
"(",
"sourceCode",
",",
"node",
".",
"right",
")",
")",
"{",
"rightText",
"=",
"`",
"${",
"sourceCode",
".",
"text",
".",
"slice",
"(",
"operatorToken",
".",
"range",
"[",
"1",
"]",
",",
"node",
".",
"right",
".",
"range",
"[",
"0",
"]",
")",
"}",
"${",
"sourceCode",
".",
"getText",
"(",
"node",
".",
"right",
")",
"}",
"`",
";",
"}",
"else",
"{",
"rightText",
"=",
"sourceCode",
".",
"text",
".",
"slice",
"(",
"operatorToken",
".",
"range",
"[",
"1",
"]",
",",
"node",
".",
"range",
"[",
"1",
"]",
")",
";",
"}",
"return",
"fixer",
".",
"replaceText",
"(",
"node",
",",
"`",
"${",
"leftText",
"}",
"${",
"leftText",
"}",
"${",
"newOperator",
"}",
"${",
"rightText",
"}",
"`",
")",
";",
"}",
"return",
"null",
";",
"}",
"}",
")",
";",
"}",
"}"
] | Warns if an assignment expression uses operator assignment shorthand.
@param {ASTNode} node An AssignmentExpression node.
@returns {void} | [
"Warns",
"if",
"an",
"assignment",
"expression",
"uses",
"operator",
"assignment",
"shorthand",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/operator-assignment.js#L178-L206 |
3,131 | eslint/eslint | lib/rules/function-paren-newline.js | validateArguments | function validateArguments(parens, elements) {
const leftParen = parens.leftParen;
const tokenAfterLeftParen = sourceCode.getTokenAfter(leftParen);
const hasLeftNewline = !astUtils.isTokenOnSameLine(leftParen, tokenAfterLeftParen);
const needsNewlines = shouldHaveNewlines(elements, hasLeftNewline);
for (let i = 0; i <= elements.length - 2; i++) {
const currentElement = elements[i];
const nextElement = elements[i + 1];
const hasNewLine = currentElement.loc.end.line !== nextElement.loc.start.line;
if (!hasNewLine && needsNewlines) {
context.report({
node: currentElement,
messageId: "expectedBetween",
fix: fixer => fixer.insertTextBefore(nextElement, "\n")
});
}
}
} | javascript | function validateArguments(parens, elements) {
const leftParen = parens.leftParen;
const tokenAfterLeftParen = sourceCode.getTokenAfter(leftParen);
const hasLeftNewline = !astUtils.isTokenOnSameLine(leftParen, tokenAfterLeftParen);
const needsNewlines = shouldHaveNewlines(elements, hasLeftNewline);
for (let i = 0; i <= elements.length - 2; i++) {
const currentElement = elements[i];
const nextElement = elements[i + 1];
const hasNewLine = currentElement.loc.end.line !== nextElement.loc.start.line;
if (!hasNewLine && needsNewlines) {
context.report({
node: currentElement,
messageId: "expectedBetween",
fix: fixer => fixer.insertTextBefore(nextElement, "\n")
});
}
}
} | [
"function",
"validateArguments",
"(",
"parens",
",",
"elements",
")",
"{",
"const",
"leftParen",
"=",
"parens",
".",
"leftParen",
";",
"const",
"tokenAfterLeftParen",
"=",
"sourceCode",
".",
"getTokenAfter",
"(",
"leftParen",
")",
";",
"const",
"hasLeftNewline",
"=",
"!",
"astUtils",
".",
"isTokenOnSameLine",
"(",
"leftParen",
",",
"tokenAfterLeftParen",
")",
";",
"const",
"needsNewlines",
"=",
"shouldHaveNewlines",
"(",
"elements",
",",
"hasLeftNewline",
")",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<=",
"elements",
".",
"length",
"-",
"2",
";",
"i",
"++",
")",
"{",
"const",
"currentElement",
"=",
"elements",
"[",
"i",
"]",
";",
"const",
"nextElement",
"=",
"elements",
"[",
"i",
"+",
"1",
"]",
";",
"const",
"hasNewLine",
"=",
"currentElement",
".",
"loc",
".",
"end",
".",
"line",
"!==",
"nextElement",
".",
"loc",
".",
"start",
".",
"line",
";",
"if",
"(",
"!",
"hasNewLine",
"&&",
"needsNewlines",
")",
"{",
"context",
".",
"report",
"(",
"{",
"node",
":",
"currentElement",
",",
"messageId",
":",
"\"expectedBetween\"",
",",
"fix",
":",
"fixer",
"=>",
"fixer",
".",
"insertTextBefore",
"(",
"nextElement",
",",
"\"\\n\"",
")",
"}",
")",
";",
"}",
"}",
"}"
] | Validates a list of arguments or parameters
@param {Object} parens An object with keys `leftParen` for the left paren token, and `rightParen` for the right paren token
@param {ASTNode[]} elements The arguments or parameters in the list
@returns {void} | [
"Validates",
"a",
"list",
"of",
"arguments",
"or",
"parameters"
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/function-paren-newline.js#L162-L181 |
3,132 | eslint/eslint | lib/rules/function-paren-newline.js | getParenTokens | function getParenTokens(node) {
switch (node.type) {
case "NewExpression":
if (!node.arguments.length && !(
astUtils.isOpeningParenToken(sourceCode.getLastToken(node, { skip: 1 })) &&
astUtils.isClosingParenToken(sourceCode.getLastToken(node))
)) {
// If the NewExpression does not have parens (e.g. `new Foo`), return null.
return null;
}
// falls through
case "CallExpression":
return {
leftParen: sourceCode.getTokenAfter(node.callee, astUtils.isOpeningParenToken),
rightParen: sourceCode.getLastToken(node)
};
case "FunctionDeclaration":
case "FunctionExpression": {
const leftParen = sourceCode.getFirstToken(node, astUtils.isOpeningParenToken);
const rightParen = node.params.length
? sourceCode.getTokenAfter(node.params[node.params.length - 1], astUtils.isClosingParenToken)
: sourceCode.getTokenAfter(leftParen);
return { leftParen, rightParen };
}
case "ArrowFunctionExpression": {
const firstToken = sourceCode.getFirstToken(node);
if (!astUtils.isOpeningParenToken(firstToken)) {
// If the ArrowFunctionExpression has a single param without parens, return null.
return null;
}
return {
leftParen: firstToken,
rightParen: sourceCode.getTokenBefore(node.body, astUtils.isClosingParenToken)
};
}
default:
throw new TypeError(`unexpected node with type ${node.type}`);
}
} | javascript | function getParenTokens(node) {
switch (node.type) {
case "NewExpression":
if (!node.arguments.length && !(
astUtils.isOpeningParenToken(sourceCode.getLastToken(node, { skip: 1 })) &&
astUtils.isClosingParenToken(sourceCode.getLastToken(node))
)) {
// If the NewExpression does not have parens (e.g. `new Foo`), return null.
return null;
}
// falls through
case "CallExpression":
return {
leftParen: sourceCode.getTokenAfter(node.callee, astUtils.isOpeningParenToken),
rightParen: sourceCode.getLastToken(node)
};
case "FunctionDeclaration":
case "FunctionExpression": {
const leftParen = sourceCode.getFirstToken(node, astUtils.isOpeningParenToken);
const rightParen = node.params.length
? sourceCode.getTokenAfter(node.params[node.params.length - 1], astUtils.isClosingParenToken)
: sourceCode.getTokenAfter(leftParen);
return { leftParen, rightParen };
}
case "ArrowFunctionExpression": {
const firstToken = sourceCode.getFirstToken(node);
if (!astUtils.isOpeningParenToken(firstToken)) {
// If the ArrowFunctionExpression has a single param without parens, return null.
return null;
}
return {
leftParen: firstToken,
rightParen: sourceCode.getTokenBefore(node.body, astUtils.isClosingParenToken)
};
}
default:
throw new TypeError(`unexpected node with type ${node.type}`);
}
} | [
"function",
"getParenTokens",
"(",
"node",
")",
"{",
"switch",
"(",
"node",
".",
"type",
")",
"{",
"case",
"\"NewExpression\"",
":",
"if",
"(",
"!",
"node",
".",
"arguments",
".",
"length",
"&&",
"!",
"(",
"astUtils",
".",
"isOpeningParenToken",
"(",
"sourceCode",
".",
"getLastToken",
"(",
"node",
",",
"{",
"skip",
":",
"1",
"}",
")",
")",
"&&",
"astUtils",
".",
"isClosingParenToken",
"(",
"sourceCode",
".",
"getLastToken",
"(",
"node",
")",
")",
")",
")",
"{",
"// If the NewExpression does not have parens (e.g. `new Foo`), return null.",
"return",
"null",
";",
"}",
"// falls through",
"case",
"\"CallExpression\"",
":",
"return",
"{",
"leftParen",
":",
"sourceCode",
".",
"getTokenAfter",
"(",
"node",
".",
"callee",
",",
"astUtils",
".",
"isOpeningParenToken",
")",
",",
"rightParen",
":",
"sourceCode",
".",
"getLastToken",
"(",
"node",
")",
"}",
";",
"case",
"\"FunctionDeclaration\"",
":",
"case",
"\"FunctionExpression\"",
":",
"{",
"const",
"leftParen",
"=",
"sourceCode",
".",
"getFirstToken",
"(",
"node",
",",
"astUtils",
".",
"isOpeningParenToken",
")",
";",
"const",
"rightParen",
"=",
"node",
".",
"params",
".",
"length",
"?",
"sourceCode",
".",
"getTokenAfter",
"(",
"node",
".",
"params",
"[",
"node",
".",
"params",
".",
"length",
"-",
"1",
"]",
",",
"astUtils",
".",
"isClosingParenToken",
")",
":",
"sourceCode",
".",
"getTokenAfter",
"(",
"leftParen",
")",
";",
"return",
"{",
"leftParen",
",",
"rightParen",
"}",
";",
"}",
"case",
"\"ArrowFunctionExpression\"",
":",
"{",
"const",
"firstToken",
"=",
"sourceCode",
".",
"getFirstToken",
"(",
"node",
")",
";",
"if",
"(",
"!",
"astUtils",
".",
"isOpeningParenToken",
"(",
"firstToken",
")",
")",
"{",
"// If the ArrowFunctionExpression has a single param without parens, return null.",
"return",
"null",
";",
"}",
"return",
"{",
"leftParen",
":",
"firstToken",
",",
"rightParen",
":",
"sourceCode",
".",
"getTokenBefore",
"(",
"node",
".",
"body",
",",
"astUtils",
".",
"isClosingParenToken",
")",
"}",
";",
"}",
"default",
":",
"throw",
"new",
"TypeError",
"(",
"`",
"${",
"node",
".",
"type",
"}",
"`",
")",
";",
"}",
"}"
] | Gets the left paren and right paren tokens of a node.
@param {ASTNode} node The node with parens
@returns {Object} An object with keys `leftParen` for the left paren token, and `rightParen` for the right paren token.
Can also return `null` if an expression has no parens (e.g. a NewExpression with no arguments, or an ArrowFunctionExpression
with a single parameter) | [
"Gets",
"the",
"left",
"paren",
"and",
"right",
"paren",
"tokens",
"of",
"a",
"node",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/function-paren-newline.js#L190-L238 |
3,133 | eslint/eslint | lib/rules/function-paren-newline.js | validateNode | function validateNode(node) {
const parens = getParenTokens(node);
if (parens) {
validateParens(parens, astUtils.isFunction(node) ? node.params : node.arguments);
if (multilineArgumentsOption) {
validateArguments(parens, astUtils.isFunction(node) ? node.params : node.arguments);
}
}
} | javascript | function validateNode(node) {
const parens = getParenTokens(node);
if (parens) {
validateParens(parens, astUtils.isFunction(node) ? node.params : node.arguments);
if (multilineArgumentsOption) {
validateArguments(parens, astUtils.isFunction(node) ? node.params : node.arguments);
}
}
} | [
"function",
"validateNode",
"(",
"node",
")",
"{",
"const",
"parens",
"=",
"getParenTokens",
"(",
"node",
")",
";",
"if",
"(",
"parens",
")",
"{",
"validateParens",
"(",
"parens",
",",
"astUtils",
".",
"isFunction",
"(",
"node",
")",
"?",
"node",
".",
"params",
":",
"node",
".",
"arguments",
")",
";",
"if",
"(",
"multilineArgumentsOption",
")",
"{",
"validateArguments",
"(",
"parens",
",",
"astUtils",
".",
"isFunction",
"(",
"node",
")",
"?",
"node",
".",
"params",
":",
"node",
".",
"arguments",
")",
";",
"}",
"}",
"}"
] | Validates the parentheses for a node
@param {ASTNode} node The node with parens
@returns {void} | [
"Validates",
"the",
"parentheses",
"for",
"a",
"node"
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/function-paren-newline.js#L245-L255 |
3,134 | eslint/eslint | lib/rules/no-unused-vars.js | getDefinedMessage | function getDefinedMessage(unusedVar) {
const defType = unusedVar.defs && unusedVar.defs[0] && unusedVar.defs[0].type;
let type;
let pattern;
if (defType === "CatchClause" && config.caughtErrorsIgnorePattern) {
type = "args";
pattern = config.caughtErrorsIgnorePattern.toString();
} else if (defType === "Parameter" && config.argsIgnorePattern) {
type = "args";
pattern = config.argsIgnorePattern.toString();
} else if (defType !== "Parameter" && config.varsIgnorePattern) {
type = "vars";
pattern = config.varsIgnorePattern.toString();
}
const additional = type ? ` Allowed unused ${type} must match ${pattern}.` : "";
return `'{{name}}' is defined but never used.${additional}`;
} | javascript | function getDefinedMessage(unusedVar) {
const defType = unusedVar.defs && unusedVar.defs[0] && unusedVar.defs[0].type;
let type;
let pattern;
if (defType === "CatchClause" && config.caughtErrorsIgnorePattern) {
type = "args";
pattern = config.caughtErrorsIgnorePattern.toString();
} else if (defType === "Parameter" && config.argsIgnorePattern) {
type = "args";
pattern = config.argsIgnorePattern.toString();
} else if (defType !== "Parameter" && config.varsIgnorePattern) {
type = "vars";
pattern = config.varsIgnorePattern.toString();
}
const additional = type ? ` Allowed unused ${type} must match ${pattern}.` : "";
return `'{{name}}' is defined but never used.${additional}`;
} | [
"function",
"getDefinedMessage",
"(",
"unusedVar",
")",
"{",
"const",
"defType",
"=",
"unusedVar",
".",
"defs",
"&&",
"unusedVar",
".",
"defs",
"[",
"0",
"]",
"&&",
"unusedVar",
".",
"defs",
"[",
"0",
"]",
".",
"type",
";",
"let",
"type",
";",
"let",
"pattern",
";",
"if",
"(",
"defType",
"===",
"\"CatchClause\"",
"&&",
"config",
".",
"caughtErrorsIgnorePattern",
")",
"{",
"type",
"=",
"\"args\"",
";",
"pattern",
"=",
"config",
".",
"caughtErrorsIgnorePattern",
".",
"toString",
"(",
")",
";",
"}",
"else",
"if",
"(",
"defType",
"===",
"\"Parameter\"",
"&&",
"config",
".",
"argsIgnorePattern",
")",
"{",
"type",
"=",
"\"args\"",
";",
"pattern",
"=",
"config",
".",
"argsIgnorePattern",
".",
"toString",
"(",
")",
";",
"}",
"else",
"if",
"(",
"defType",
"!==",
"\"Parameter\"",
"&&",
"config",
".",
"varsIgnorePattern",
")",
"{",
"type",
"=",
"\"vars\"",
";",
"pattern",
"=",
"config",
".",
"varsIgnorePattern",
".",
"toString",
"(",
")",
";",
"}",
"const",
"additional",
"=",
"type",
"?",
"`",
"${",
"type",
"}",
"${",
"pattern",
"}",
"`",
":",
"\"\"",
";",
"return",
"`",
"${",
"additional",
"}",
"`",
";",
"}"
] | Generate the warning message about the variable being
defined and unused, including the ignore pattern if configured.
@param {Variable} unusedVar - eslint-scope variable object.
@returns {string} The warning message to be used with this unused variable. | [
"Generate",
"the",
"warning",
"message",
"about",
"the",
"variable",
"being",
"defined",
"and",
"unused",
"including",
"the",
"ignore",
"pattern",
"if",
"configured",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-unused-vars.js#L109-L128 |
3,135 | eslint/eslint | lib/rules/no-unused-vars.js | hasRestSpreadSibling | function hasRestSpreadSibling(variable) {
if (config.ignoreRestSiblings) {
return variable.defs.some(def => {
const propertyNode = def.name.parent;
const patternNode = propertyNode.parent;
return (
propertyNode.type === "Property" &&
patternNode.type === "ObjectPattern" &&
REST_PROPERTY_TYPE.test(patternNode.properties[patternNode.properties.length - 1].type)
);
});
}
return false;
} | javascript | function hasRestSpreadSibling(variable) {
if (config.ignoreRestSiblings) {
return variable.defs.some(def => {
const propertyNode = def.name.parent;
const patternNode = propertyNode.parent;
return (
propertyNode.type === "Property" &&
patternNode.type === "ObjectPattern" &&
REST_PROPERTY_TYPE.test(patternNode.properties[patternNode.properties.length - 1].type)
);
});
}
return false;
} | [
"function",
"hasRestSpreadSibling",
"(",
"variable",
")",
"{",
"if",
"(",
"config",
".",
"ignoreRestSiblings",
")",
"{",
"return",
"variable",
".",
"defs",
".",
"some",
"(",
"def",
"=>",
"{",
"const",
"propertyNode",
"=",
"def",
".",
"name",
".",
"parent",
";",
"const",
"patternNode",
"=",
"propertyNode",
".",
"parent",
";",
"return",
"(",
"propertyNode",
".",
"type",
"===",
"\"Property\"",
"&&",
"patternNode",
".",
"type",
"===",
"\"ObjectPattern\"",
"&&",
"REST_PROPERTY_TYPE",
".",
"test",
"(",
"patternNode",
".",
"properties",
"[",
"patternNode",
".",
"properties",
".",
"length",
"-",
"1",
"]",
".",
"type",
")",
")",
";",
"}",
")",
";",
"}",
"return",
"false",
";",
"}"
] | Determines if a variable has a sibling rest property
@param {Variable} variable - eslint-scope variable object.
@returns {boolean} True if the variable is exported, false if not.
@private | [
"Determines",
"if",
"a",
"variable",
"has",
"a",
"sibling",
"rest",
"property"
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-unused-vars.js#L179-L194 |
3,136 | eslint/eslint | lib/rules/no-unused-vars.js | isSelfReference | function isSelfReference(ref, nodes) {
let scope = ref.from;
while (scope) {
if (nodes.indexOf(scope.block) >= 0) {
return true;
}
scope = scope.upper;
}
return false;
} | javascript | function isSelfReference(ref, nodes) {
let scope = ref.from;
while (scope) {
if (nodes.indexOf(scope.block) >= 0) {
return true;
}
scope = scope.upper;
}
return false;
} | [
"function",
"isSelfReference",
"(",
"ref",
",",
"nodes",
")",
"{",
"let",
"scope",
"=",
"ref",
".",
"from",
";",
"while",
"(",
"scope",
")",
"{",
"if",
"(",
"nodes",
".",
"indexOf",
"(",
"scope",
".",
"block",
")",
">=",
"0",
")",
"{",
"return",
"true",
";",
"}",
"scope",
"=",
"scope",
".",
"upper",
";",
"}",
"return",
"false",
";",
"}"
] | Determine if an identifier is referencing an enclosing function name.
@param {Reference} ref - The reference to check.
@param {ASTNode[]} nodes - The candidate function nodes.
@returns {boolean} True if it's a self-reference, false if not.
@private | [
"Determine",
"if",
"an",
"identifier",
"is",
"referencing",
"an",
"enclosing",
"function",
"name",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-unused-vars.js#L213-L225 |
3,137 | eslint/eslint | lib/rules/no-unused-vars.js | getFunctionDefinitions | function getFunctionDefinitions(variable) {
const functionDefinitions = [];
variable.defs.forEach(def => {
const { type, node } = def;
// FunctionDeclarations
if (type === "FunctionName") {
functionDefinitions.push(node);
}
// FunctionExpressions
if (type === "Variable" && node.init &&
(node.init.type === "FunctionExpression" || node.init.type === "ArrowFunctionExpression")) {
functionDefinitions.push(node.init);
}
});
return functionDefinitions;
} | javascript | function getFunctionDefinitions(variable) {
const functionDefinitions = [];
variable.defs.forEach(def => {
const { type, node } = def;
// FunctionDeclarations
if (type === "FunctionName") {
functionDefinitions.push(node);
}
// FunctionExpressions
if (type === "Variable" && node.init &&
(node.init.type === "FunctionExpression" || node.init.type === "ArrowFunctionExpression")) {
functionDefinitions.push(node.init);
}
});
return functionDefinitions;
} | [
"function",
"getFunctionDefinitions",
"(",
"variable",
")",
"{",
"const",
"functionDefinitions",
"=",
"[",
"]",
";",
"variable",
".",
"defs",
".",
"forEach",
"(",
"def",
"=>",
"{",
"const",
"{",
"type",
",",
"node",
"}",
"=",
"def",
";",
"// FunctionDeclarations",
"if",
"(",
"type",
"===",
"\"FunctionName\"",
")",
"{",
"functionDefinitions",
".",
"push",
"(",
"node",
")",
";",
"}",
"// FunctionExpressions",
"if",
"(",
"type",
"===",
"\"Variable\"",
"&&",
"node",
".",
"init",
"&&",
"(",
"node",
".",
"init",
".",
"type",
"===",
"\"FunctionExpression\"",
"||",
"node",
".",
"init",
".",
"type",
"===",
"\"ArrowFunctionExpression\"",
")",
")",
"{",
"functionDefinitions",
".",
"push",
"(",
"node",
".",
"init",
")",
";",
"}",
"}",
")",
";",
"return",
"functionDefinitions",
";",
"}"
] | Gets a list of function definitions for a specified variable.
@param {Variable} variable - eslint-scope variable object.
@returns {ASTNode[]} Function nodes.
@private | [
"Gets",
"a",
"list",
"of",
"function",
"definitions",
"for",
"a",
"specified",
"variable",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-unused-vars.js#L233-L251 |
3,138 | eslint/eslint | lib/rules/no-unused-vars.js | isInside | function isInside(inner, outer) {
return (
inner.range[0] >= outer.range[0] &&
inner.range[1] <= outer.range[1]
);
} | javascript | function isInside(inner, outer) {
return (
inner.range[0] >= outer.range[0] &&
inner.range[1] <= outer.range[1]
);
} | [
"function",
"isInside",
"(",
"inner",
",",
"outer",
")",
"{",
"return",
"(",
"inner",
".",
"range",
"[",
"0",
"]",
">=",
"outer",
".",
"range",
"[",
"0",
"]",
"&&",
"inner",
".",
"range",
"[",
"1",
"]",
"<=",
"outer",
".",
"range",
"[",
"1",
"]",
")",
";",
"}"
] | Checks the position of given nodes.
@param {ASTNode} inner - A node which is expected as inside.
@param {ASTNode} outer - A node which is expected as outside.
@returns {boolean} `true` if the `inner` node exists in the `outer` node.
@private | [
"Checks",
"the",
"position",
"of",
"given",
"nodes",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-unused-vars.js#L261-L266 |
3,139 | eslint/eslint | lib/rules/no-unused-vars.js | getRhsNode | function getRhsNode(ref, prevRhsNode) {
const id = ref.identifier;
const parent = id.parent;
const granpa = parent.parent;
const refScope = ref.from.variableScope;
const varScope = ref.resolved.scope.variableScope;
const canBeUsedLater = refScope !== varScope || astUtils.isInLoop(id);
/*
* Inherits the previous node if this reference is in the node.
* This is for `a = a + a`-like code.
*/
if (prevRhsNode && isInside(id, prevRhsNode)) {
return prevRhsNode;
}
if (parent.type === "AssignmentExpression" &&
granpa.type === "ExpressionStatement" &&
id === parent.left &&
!canBeUsedLater
) {
return parent.right;
}
return null;
} | javascript | function getRhsNode(ref, prevRhsNode) {
const id = ref.identifier;
const parent = id.parent;
const granpa = parent.parent;
const refScope = ref.from.variableScope;
const varScope = ref.resolved.scope.variableScope;
const canBeUsedLater = refScope !== varScope || astUtils.isInLoop(id);
/*
* Inherits the previous node if this reference is in the node.
* This is for `a = a + a`-like code.
*/
if (prevRhsNode && isInside(id, prevRhsNode)) {
return prevRhsNode;
}
if (parent.type === "AssignmentExpression" &&
granpa.type === "ExpressionStatement" &&
id === parent.left &&
!canBeUsedLater
) {
return parent.right;
}
return null;
} | [
"function",
"getRhsNode",
"(",
"ref",
",",
"prevRhsNode",
")",
"{",
"const",
"id",
"=",
"ref",
".",
"identifier",
";",
"const",
"parent",
"=",
"id",
".",
"parent",
";",
"const",
"granpa",
"=",
"parent",
".",
"parent",
";",
"const",
"refScope",
"=",
"ref",
".",
"from",
".",
"variableScope",
";",
"const",
"varScope",
"=",
"ref",
".",
"resolved",
".",
"scope",
".",
"variableScope",
";",
"const",
"canBeUsedLater",
"=",
"refScope",
"!==",
"varScope",
"||",
"astUtils",
".",
"isInLoop",
"(",
"id",
")",
";",
"/*\n * Inherits the previous node if this reference is in the node.\n * This is for `a = a + a`-like code.\n */",
"if",
"(",
"prevRhsNode",
"&&",
"isInside",
"(",
"id",
",",
"prevRhsNode",
")",
")",
"{",
"return",
"prevRhsNode",
";",
"}",
"if",
"(",
"parent",
".",
"type",
"===",
"\"AssignmentExpression\"",
"&&",
"granpa",
".",
"type",
"===",
"\"ExpressionStatement\"",
"&&",
"id",
"===",
"parent",
".",
"left",
"&&",
"!",
"canBeUsedLater",
")",
"{",
"return",
"parent",
".",
"right",
";",
"}",
"return",
"null",
";",
"}"
] | If a given reference is left-hand side of an assignment, this gets
the right-hand side node of the assignment.
In the following cases, this returns null.
- The reference is not the LHS of an assignment expression.
- The reference is inside of a loop.
- The reference is inside of a function scope which is different from
the declaration.
@param {eslint-scope.Reference} ref - A reference to check.
@param {ASTNode} prevRhsNode - The previous RHS node.
@returns {ASTNode|null} The RHS node or null.
@private | [
"If",
"a",
"given",
"reference",
"is",
"left",
"-",
"hand",
"side",
"of",
"an",
"assignment",
"this",
"gets",
"the",
"right",
"-",
"hand",
"side",
"node",
"of",
"the",
"assignment",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-unused-vars.js#L284-L308 |
3,140 | eslint/eslint | lib/rules/no-unused-vars.js | isReadForItself | function isReadForItself(ref, rhsNode) {
const id = ref.identifier;
const parent = id.parent;
const granpa = parent.parent;
return ref.isRead() && (
// self update. e.g. `a += 1`, `a++`
(// in RHS of an assignment for itself. e.g. `a = a + 1`
((
parent.type === "AssignmentExpression" &&
granpa.type === "ExpressionStatement" &&
parent.left === id
) ||
(
parent.type === "UpdateExpression" &&
granpa.type === "ExpressionStatement"
) || rhsNode &&
isInside(id, rhsNode) &&
!isInsideOfStorableFunction(id, rhsNode)))
);
} | javascript | function isReadForItself(ref, rhsNode) {
const id = ref.identifier;
const parent = id.parent;
const granpa = parent.parent;
return ref.isRead() && (
// self update. e.g. `a += 1`, `a++`
(// in RHS of an assignment for itself. e.g. `a = a + 1`
((
parent.type === "AssignmentExpression" &&
granpa.type === "ExpressionStatement" &&
parent.left === id
) ||
(
parent.type === "UpdateExpression" &&
granpa.type === "ExpressionStatement"
) || rhsNode &&
isInside(id, rhsNode) &&
!isInsideOfStorableFunction(id, rhsNode)))
);
} | [
"function",
"isReadForItself",
"(",
"ref",
",",
"rhsNode",
")",
"{",
"const",
"id",
"=",
"ref",
".",
"identifier",
";",
"const",
"parent",
"=",
"id",
".",
"parent",
";",
"const",
"granpa",
"=",
"parent",
".",
"parent",
";",
"return",
"ref",
".",
"isRead",
"(",
")",
"&&",
"(",
"// self update. e.g. `a += 1`, `a++`",
"(",
"// in RHS of an assignment for itself. e.g. `a = a + 1`",
"(",
"(",
"parent",
".",
"type",
"===",
"\"AssignmentExpression\"",
"&&",
"granpa",
".",
"type",
"===",
"\"ExpressionStatement\"",
"&&",
"parent",
".",
"left",
"===",
"id",
")",
"||",
"(",
"parent",
".",
"type",
"===",
"\"UpdateExpression\"",
"&&",
"granpa",
".",
"type",
"===",
"\"ExpressionStatement\"",
")",
"||",
"rhsNode",
"&&",
"isInside",
"(",
"id",
",",
"rhsNode",
")",
"&&",
"!",
"isInsideOfStorableFunction",
"(",
"id",
",",
"rhsNode",
")",
")",
")",
")",
";",
"}"
] | Checks whether a given reference is a read to update itself or not.
@param {eslint-scope.Reference} ref - A reference to check.
@param {ASTNode} rhsNode - The RHS node of the previous assignment.
@returns {boolean} The reference is a read to update itself.
@private | [
"Checks",
"whether",
"a",
"given",
"reference",
"is",
"a",
"read",
"to",
"update",
"itself",
"or",
"not",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-unused-vars.js#L394-L415 |
3,141 | eslint/eslint | lib/rules/no-unused-vars.js | isForInRef | function isForInRef(ref) {
let target = ref.identifier.parent;
// "for (var ...) { return; }"
if (target.type === "VariableDeclarator") {
target = target.parent.parent;
}
if (target.type !== "ForInStatement") {
return false;
}
// "for (...) { return; }"
if (target.body.type === "BlockStatement") {
target = target.body.body[0];
// "for (...) return;"
} else {
target = target.body;
}
// For empty loop body
if (!target) {
return false;
}
return target.type === "ReturnStatement";
} | javascript | function isForInRef(ref) {
let target = ref.identifier.parent;
// "for (var ...) { return; }"
if (target.type === "VariableDeclarator") {
target = target.parent.parent;
}
if (target.type !== "ForInStatement") {
return false;
}
// "for (...) { return; }"
if (target.body.type === "BlockStatement") {
target = target.body.body[0];
// "for (...) return;"
} else {
target = target.body;
}
// For empty loop body
if (!target) {
return false;
}
return target.type === "ReturnStatement";
} | [
"function",
"isForInRef",
"(",
"ref",
")",
"{",
"let",
"target",
"=",
"ref",
".",
"identifier",
".",
"parent",
";",
"// \"for (var ...) { return; }\"",
"if",
"(",
"target",
".",
"type",
"===",
"\"VariableDeclarator\"",
")",
"{",
"target",
"=",
"target",
".",
"parent",
".",
"parent",
";",
"}",
"if",
"(",
"target",
".",
"type",
"!==",
"\"ForInStatement\"",
")",
"{",
"return",
"false",
";",
"}",
"// \"for (...) { return; }\"",
"if",
"(",
"target",
".",
"body",
".",
"type",
"===",
"\"BlockStatement\"",
")",
"{",
"target",
"=",
"target",
".",
"body",
".",
"body",
"[",
"0",
"]",
";",
"// \"for (...) return;\"",
"}",
"else",
"{",
"target",
"=",
"target",
".",
"body",
";",
"}",
"// For empty loop body",
"if",
"(",
"!",
"target",
")",
"{",
"return",
"false",
";",
"}",
"return",
"target",
".",
"type",
"===",
"\"ReturnStatement\"",
";",
"}"
] | Determine if an identifier is used either in for-in loops.
@param {Reference} ref - The reference to check.
@returns {boolean} whether reference is used in the for-in loops
@private | [
"Determine",
"if",
"an",
"identifier",
"is",
"used",
"either",
"in",
"for",
"-",
"in",
"loops",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-unused-vars.js#L424-L452 |
3,142 | eslint/eslint | lib/rules/no-unused-vars.js | isAfterLastUsedArg | function isAfterLastUsedArg(variable) {
const def = variable.defs[0];
const params = context.getDeclaredVariables(def.node);
const posteriorParams = params.slice(params.indexOf(variable) + 1);
// If any used parameters occur after this parameter, do not report.
return !posteriorParams.some(v => v.references.length > 0 || v.eslintUsed);
} | javascript | function isAfterLastUsedArg(variable) {
const def = variable.defs[0];
const params = context.getDeclaredVariables(def.node);
const posteriorParams = params.slice(params.indexOf(variable) + 1);
// If any used parameters occur after this parameter, do not report.
return !posteriorParams.some(v => v.references.length > 0 || v.eslintUsed);
} | [
"function",
"isAfterLastUsedArg",
"(",
"variable",
")",
"{",
"const",
"def",
"=",
"variable",
".",
"defs",
"[",
"0",
"]",
";",
"const",
"params",
"=",
"context",
".",
"getDeclaredVariables",
"(",
"def",
".",
"node",
")",
";",
"const",
"posteriorParams",
"=",
"params",
".",
"slice",
"(",
"params",
".",
"indexOf",
"(",
"variable",
")",
"+",
"1",
")",
";",
"// If any used parameters occur after this parameter, do not report.",
"return",
"!",
"posteriorParams",
".",
"some",
"(",
"v",
"=>",
"v",
".",
"references",
".",
"length",
">",
"0",
"||",
"v",
".",
"eslintUsed",
")",
";",
"}"
] | Checks whether the given variable is after the last used parameter.
@param {eslint-scope.Variable} variable - The variable to check.
@returns {boolean} `true` if the variable is defined after the last
used parameter. | [
"Checks",
"whether",
"the",
"given",
"variable",
"is",
"after",
"the",
"last",
"used",
"parameter",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-unused-vars.js#L489-L496 |
3,143 | eslint/eslint | lib/rules/comma-spacing.js | report | function report(node, loc, otherNode) {
context.report({
node,
fix(fixer) {
if (options[loc]) {
if (loc === "before") {
return fixer.insertTextBefore(node, " ");
}
return fixer.insertTextAfter(node, " ");
}
let start, end;
const newText = "";
if (loc === "before") {
start = otherNode.range[1];
end = node.range[0];
} else {
start = node.range[1];
end = otherNode.range[0];
}
return fixer.replaceTextRange([start, end], newText);
},
messageId: options[loc] ? "missing" : "unexpected",
data: {
loc
}
});
} | javascript | function report(node, loc, otherNode) {
context.report({
node,
fix(fixer) {
if (options[loc]) {
if (loc === "before") {
return fixer.insertTextBefore(node, " ");
}
return fixer.insertTextAfter(node, " ");
}
let start, end;
const newText = "";
if (loc === "before") {
start = otherNode.range[1];
end = node.range[0];
} else {
start = node.range[1];
end = otherNode.range[0];
}
return fixer.replaceTextRange([start, end], newText);
},
messageId: options[loc] ? "missing" : "unexpected",
data: {
loc
}
});
} | [
"function",
"report",
"(",
"node",
",",
"loc",
",",
"otherNode",
")",
"{",
"context",
".",
"report",
"(",
"{",
"node",
",",
"fix",
"(",
"fixer",
")",
"{",
"if",
"(",
"options",
"[",
"loc",
"]",
")",
"{",
"if",
"(",
"loc",
"===",
"\"before\"",
")",
"{",
"return",
"fixer",
".",
"insertTextBefore",
"(",
"node",
",",
"\" \"",
")",
";",
"}",
"return",
"fixer",
".",
"insertTextAfter",
"(",
"node",
",",
"\" \"",
")",
";",
"}",
"let",
"start",
",",
"end",
";",
"const",
"newText",
"=",
"\"\"",
";",
"if",
"(",
"loc",
"===",
"\"before\"",
")",
"{",
"start",
"=",
"otherNode",
".",
"range",
"[",
"1",
"]",
";",
"end",
"=",
"node",
".",
"range",
"[",
"0",
"]",
";",
"}",
"else",
"{",
"start",
"=",
"node",
".",
"range",
"[",
"1",
"]",
";",
"end",
"=",
"otherNode",
".",
"range",
"[",
"0",
"]",
";",
"}",
"return",
"fixer",
".",
"replaceTextRange",
"(",
"[",
"start",
",",
"end",
"]",
",",
"newText",
")",
";",
"}",
",",
"messageId",
":",
"options",
"[",
"loc",
"]",
"?",
"\"missing\"",
":",
"\"unexpected\"",
",",
"data",
":",
"{",
"loc",
"}",
"}",
")",
";",
"}"
] | Reports a spacing error with an appropriate message.
@param {ASTNode} node The binary expression node to report.
@param {string} loc Is the error "before" or "after" the comma?
@param {ASTNode} otherNode The node at the left or right of `node`
@returns {void}
@private | [
"Reports",
"a",
"spacing",
"error",
"with",
"an",
"appropriate",
"message",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/comma-spacing.js#L74-L104 |
3,144 | eslint/eslint | lib/rules/comma-spacing.js | validateCommaItemSpacing | function validateCommaItemSpacing(tokens, reportItem) {
if (tokens.left && astUtils.isTokenOnSameLine(tokens.left, tokens.comma) &&
(options.before !== sourceCode.isSpaceBetweenTokens(tokens.left, tokens.comma))
) {
report(reportItem, "before", tokens.left);
}
if (tokens.right && astUtils.isClosingParenToken(tokens.right)) {
return;
}
if (tokens.right && !options.after && tokens.right.type === "Line") {
return;
}
if (tokens.right && astUtils.isTokenOnSameLine(tokens.comma, tokens.right) &&
(options.after !== sourceCode.isSpaceBetweenTokens(tokens.comma, tokens.right))
) {
report(reportItem, "after", tokens.right);
}
} | javascript | function validateCommaItemSpacing(tokens, reportItem) {
if (tokens.left && astUtils.isTokenOnSameLine(tokens.left, tokens.comma) &&
(options.before !== sourceCode.isSpaceBetweenTokens(tokens.left, tokens.comma))
) {
report(reportItem, "before", tokens.left);
}
if (tokens.right && astUtils.isClosingParenToken(tokens.right)) {
return;
}
if (tokens.right && !options.after && tokens.right.type === "Line") {
return;
}
if (tokens.right && astUtils.isTokenOnSameLine(tokens.comma, tokens.right) &&
(options.after !== sourceCode.isSpaceBetweenTokens(tokens.comma, tokens.right))
) {
report(reportItem, "after", tokens.right);
}
} | [
"function",
"validateCommaItemSpacing",
"(",
"tokens",
",",
"reportItem",
")",
"{",
"if",
"(",
"tokens",
".",
"left",
"&&",
"astUtils",
".",
"isTokenOnSameLine",
"(",
"tokens",
".",
"left",
",",
"tokens",
".",
"comma",
")",
"&&",
"(",
"options",
".",
"before",
"!==",
"sourceCode",
".",
"isSpaceBetweenTokens",
"(",
"tokens",
".",
"left",
",",
"tokens",
".",
"comma",
")",
")",
")",
"{",
"report",
"(",
"reportItem",
",",
"\"before\"",
",",
"tokens",
".",
"left",
")",
";",
"}",
"if",
"(",
"tokens",
".",
"right",
"&&",
"astUtils",
".",
"isClosingParenToken",
"(",
"tokens",
".",
"right",
")",
")",
"{",
"return",
";",
"}",
"if",
"(",
"tokens",
".",
"right",
"&&",
"!",
"options",
".",
"after",
"&&",
"tokens",
".",
"right",
".",
"type",
"===",
"\"Line\"",
")",
"{",
"return",
";",
"}",
"if",
"(",
"tokens",
".",
"right",
"&&",
"astUtils",
".",
"isTokenOnSameLine",
"(",
"tokens",
".",
"comma",
",",
"tokens",
".",
"right",
")",
"&&",
"(",
"options",
".",
"after",
"!==",
"sourceCode",
".",
"isSpaceBetweenTokens",
"(",
"tokens",
".",
"comma",
",",
"tokens",
".",
"right",
")",
")",
")",
"{",
"report",
"(",
"reportItem",
",",
"\"after\"",
",",
"tokens",
".",
"right",
")",
";",
"}",
"}"
] | Validates the spacing around a comma token.
@param {Object} tokens - The tokens to be validated.
@param {Token} tokens.comma The token representing the comma.
@param {Token} [tokens.left] The last token before the comma.
@param {Token} [tokens.right] The first token after the comma.
@param {Token|ASTNode} reportItem The item to use when reporting an error.
@returns {void}
@private | [
"Validates",
"the",
"spacing",
"around",
"a",
"comma",
"token",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/comma-spacing.js#L116-L136 |
3,145 | eslint/eslint | lib/rules/comma-spacing.js | addNullElementsToIgnoreList | function addNullElementsToIgnoreList(node) {
let previousToken = sourceCode.getFirstToken(node);
node.elements.forEach(element => {
let token;
if (element === null) {
token = sourceCode.getTokenAfter(previousToken);
if (astUtils.isCommaToken(token)) {
commaTokensToIgnore.push(token);
}
} else {
token = sourceCode.getTokenAfter(element);
}
previousToken = token;
});
} | javascript | function addNullElementsToIgnoreList(node) {
let previousToken = sourceCode.getFirstToken(node);
node.elements.forEach(element => {
let token;
if (element === null) {
token = sourceCode.getTokenAfter(previousToken);
if (astUtils.isCommaToken(token)) {
commaTokensToIgnore.push(token);
}
} else {
token = sourceCode.getTokenAfter(element);
}
previousToken = token;
});
} | [
"function",
"addNullElementsToIgnoreList",
"(",
"node",
")",
"{",
"let",
"previousToken",
"=",
"sourceCode",
".",
"getFirstToken",
"(",
"node",
")",
";",
"node",
".",
"elements",
".",
"forEach",
"(",
"element",
"=>",
"{",
"let",
"token",
";",
"if",
"(",
"element",
"===",
"null",
")",
"{",
"token",
"=",
"sourceCode",
".",
"getTokenAfter",
"(",
"previousToken",
")",
";",
"if",
"(",
"astUtils",
".",
"isCommaToken",
"(",
"token",
")",
")",
"{",
"commaTokensToIgnore",
".",
"push",
"(",
"token",
")",
";",
"}",
"}",
"else",
"{",
"token",
"=",
"sourceCode",
".",
"getTokenAfter",
"(",
"element",
")",
";",
"}",
"previousToken",
"=",
"token",
";",
"}",
")",
";",
"}"
] | Adds null elements of the given ArrayExpression or ArrayPattern node to the ignore list.
@param {ASTNode} node An ArrayExpression or ArrayPattern node.
@returns {void} | [
"Adds",
"null",
"elements",
"of",
"the",
"given",
"ArrayExpression",
"or",
"ArrayPattern",
"node",
"to",
"the",
"ignore",
"list",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/comma-spacing.js#L143-L161 |
3,146 | eslint/eslint | lib/rules/no-var.js | getEnclosingFunctionScope | function getEnclosingFunctionScope(scope) {
let currentScope = scope;
while (currentScope.type !== "function" && currentScope.type !== "global") {
currentScope = currentScope.upper;
}
return currentScope;
} | javascript | function getEnclosingFunctionScope(scope) {
let currentScope = scope;
while (currentScope.type !== "function" && currentScope.type !== "global") {
currentScope = currentScope.upper;
}
return currentScope;
} | [
"function",
"getEnclosingFunctionScope",
"(",
"scope",
")",
"{",
"let",
"currentScope",
"=",
"scope",
";",
"while",
"(",
"currentScope",
".",
"type",
"!==",
"\"function\"",
"&&",
"currentScope",
".",
"type",
"!==",
"\"global\"",
")",
"{",
"currentScope",
"=",
"currentScope",
".",
"upper",
";",
"}",
"return",
"currentScope",
";",
"}"
] | Finds the nearest function scope or global scope walking up the scope
hierarchy.
@param {eslint-scope.Scope} scope - The scope to traverse.
@returns {eslint-scope.Scope} a function scope or global scope containing the given
scope. | [
"Finds",
"the",
"nearest",
"function",
"scope",
"or",
"global",
"scope",
"walking",
"up",
"the",
"scope",
"hierarchy",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-var.js#L35-L42 |
3,147 | eslint/eslint | lib/rules/no-var.js | isLoopAssignee | function isLoopAssignee(node) {
return (node.parent.type === "ForOfStatement" || node.parent.type === "ForInStatement") &&
node === node.parent.left;
} | javascript | function isLoopAssignee(node) {
return (node.parent.type === "ForOfStatement" || node.parent.type === "ForInStatement") &&
node === node.parent.left;
} | [
"function",
"isLoopAssignee",
"(",
"node",
")",
"{",
"return",
"(",
"node",
".",
"parent",
".",
"type",
"===",
"\"ForOfStatement\"",
"||",
"node",
".",
"parent",
".",
"type",
"===",
"\"ForInStatement\"",
")",
"&&",
"node",
"===",
"node",
".",
"parent",
".",
"left",
";",
"}"
] | Checks whether the given node is the assignee of a loop.
@param {ASTNode} node - A VariableDeclaration node to check.
@returns {boolean} `true` if the declaration is assigned as part of loop
iteration. | [
"Checks",
"whether",
"the",
"given",
"node",
"is",
"the",
"assignee",
"of",
"a",
"loop",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-var.js#L65-L68 |
3,148 | eslint/eslint | lib/rules/no-var.js | getScopeNode | function getScopeNode(node) {
for (let currentNode = node; currentNode; currentNode = currentNode.parent) {
if (SCOPE_NODE_TYPE.test(currentNode.type)) {
return currentNode;
}
}
/* istanbul ignore next : unreachable */
return null;
} | javascript | function getScopeNode(node) {
for (let currentNode = node; currentNode; currentNode = currentNode.parent) {
if (SCOPE_NODE_TYPE.test(currentNode.type)) {
return currentNode;
}
}
/* istanbul ignore next : unreachable */
return null;
} | [
"function",
"getScopeNode",
"(",
"node",
")",
"{",
"for",
"(",
"let",
"currentNode",
"=",
"node",
";",
"currentNode",
";",
"currentNode",
"=",
"currentNode",
".",
"parent",
")",
"{",
"if",
"(",
"SCOPE_NODE_TYPE",
".",
"test",
"(",
"currentNode",
".",
"type",
")",
")",
"{",
"return",
"currentNode",
";",
"}",
"}",
"/* istanbul ignore next : unreachable */",
"return",
"null",
";",
"}"
] | Gets the scope node which directly contains a given node.
@param {ASTNode} node - A node to get. This is a `VariableDeclaration` or
an `Identifier`.
@returns {ASTNode} A scope node. This is one of `Program`, `BlockStatement`,
`SwitchStatement`, `ForStatement`, `ForInStatement`, and
`ForOfStatement`. | [
"Gets",
"the",
"scope",
"node",
"which",
"directly",
"contains",
"a",
"given",
"node",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-var.js#L91-L100 |
3,149 | eslint/eslint | lib/rules/no-var.js | isUsedFromOutsideOf | function isUsedFromOutsideOf(scopeNode) {
/**
* Checks whether a given reference is inside of the specified scope or not.
*
* @param {eslint-scope.Reference} reference - A reference to check.
* @returns {boolean} `true` if the reference is inside of the specified
* scope.
*/
function isOutsideOfScope(reference) {
const scope = scopeNode.range;
const id = reference.identifier.range;
return id[0] < scope[0] || id[1] > scope[1];
}
return function(variable) {
return variable.references.some(isOutsideOfScope);
};
} | javascript | function isUsedFromOutsideOf(scopeNode) {
/**
* Checks whether a given reference is inside of the specified scope or not.
*
* @param {eslint-scope.Reference} reference - A reference to check.
* @returns {boolean} `true` if the reference is inside of the specified
* scope.
*/
function isOutsideOfScope(reference) {
const scope = scopeNode.range;
const id = reference.identifier.range;
return id[0] < scope[0] || id[1] > scope[1];
}
return function(variable) {
return variable.references.some(isOutsideOfScope);
};
} | [
"function",
"isUsedFromOutsideOf",
"(",
"scopeNode",
")",
"{",
"/**\n * Checks whether a given reference is inside of the specified scope or not.\n *\n * @param {eslint-scope.Reference} reference - A reference to check.\n * @returns {boolean} `true` if the reference is inside of the specified\n * scope.\n */",
"function",
"isOutsideOfScope",
"(",
"reference",
")",
"{",
"const",
"scope",
"=",
"scopeNode",
".",
"range",
";",
"const",
"id",
"=",
"reference",
".",
"identifier",
".",
"range",
";",
"return",
"id",
"[",
"0",
"]",
"<",
"scope",
"[",
"0",
"]",
"||",
"id",
"[",
"1",
"]",
">",
"scope",
"[",
"1",
"]",
";",
"}",
"return",
"function",
"(",
"variable",
")",
"{",
"return",
"variable",
".",
"references",
".",
"some",
"(",
"isOutsideOfScope",
")",
";",
"}",
";",
"}"
] | Checks whether a given variable is used from outside of the specified scope.
@param {ASTNode} scopeNode - A scope node to check.
@returns {Function} The predicate function which checks whether a given
variable is used from outside of the specified scope. | [
"Checks",
"whether",
"a",
"given",
"variable",
"is",
"used",
"from",
"outside",
"of",
"the",
"specified",
"scope",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-var.js#L119-L138 |
3,150 | eslint/eslint | lib/rules/no-var.js | isOutsideOfScope | function isOutsideOfScope(reference) {
const scope = scopeNode.range;
const id = reference.identifier.range;
return id[0] < scope[0] || id[1] > scope[1];
} | javascript | function isOutsideOfScope(reference) {
const scope = scopeNode.range;
const id = reference.identifier.range;
return id[0] < scope[0] || id[1] > scope[1];
} | [
"function",
"isOutsideOfScope",
"(",
"reference",
")",
"{",
"const",
"scope",
"=",
"scopeNode",
".",
"range",
";",
"const",
"id",
"=",
"reference",
".",
"identifier",
".",
"range",
";",
"return",
"id",
"[",
"0",
"]",
"<",
"scope",
"[",
"0",
"]",
"||",
"id",
"[",
"1",
"]",
">",
"scope",
"[",
"1",
"]",
";",
"}"
] | Checks whether a given reference is inside of the specified scope or not.
@param {eslint-scope.Reference} reference - A reference to check.
@returns {boolean} `true` if the reference is inside of the specified
scope. | [
"Checks",
"whether",
"a",
"given",
"reference",
"is",
"inside",
"of",
"the",
"specified",
"scope",
"or",
"not",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-var.js#L128-L133 |
3,151 | eslint/eslint | lib/rules/no-var.js | hasReferenceInTDZ | function hasReferenceInTDZ(node) {
const initStart = node.range[0];
const initEnd = node.range[1];
return variable => {
const id = variable.defs[0].name;
const idStart = id.range[0];
const defaultValue = (id.parent.type === "AssignmentPattern" ? id.parent.right : null);
const defaultStart = defaultValue && defaultValue.range[0];
const defaultEnd = defaultValue && defaultValue.range[1];
return variable.references.some(reference => {
const start = reference.identifier.range[0];
const end = reference.identifier.range[1];
return !reference.init && (
start < idStart ||
(defaultValue !== null && start >= defaultStart && end <= defaultEnd) ||
(start >= initStart && end <= initEnd)
);
});
};
} | javascript | function hasReferenceInTDZ(node) {
const initStart = node.range[0];
const initEnd = node.range[1];
return variable => {
const id = variable.defs[0].name;
const idStart = id.range[0];
const defaultValue = (id.parent.type === "AssignmentPattern" ? id.parent.right : null);
const defaultStart = defaultValue && defaultValue.range[0];
const defaultEnd = defaultValue && defaultValue.range[1];
return variable.references.some(reference => {
const start = reference.identifier.range[0];
const end = reference.identifier.range[1];
return !reference.init && (
start < idStart ||
(defaultValue !== null && start >= defaultStart && end <= defaultEnd) ||
(start >= initStart && end <= initEnd)
);
});
};
} | [
"function",
"hasReferenceInTDZ",
"(",
"node",
")",
"{",
"const",
"initStart",
"=",
"node",
".",
"range",
"[",
"0",
"]",
";",
"const",
"initEnd",
"=",
"node",
".",
"range",
"[",
"1",
"]",
";",
"return",
"variable",
"=>",
"{",
"const",
"id",
"=",
"variable",
".",
"defs",
"[",
"0",
"]",
".",
"name",
";",
"const",
"idStart",
"=",
"id",
".",
"range",
"[",
"0",
"]",
";",
"const",
"defaultValue",
"=",
"(",
"id",
".",
"parent",
".",
"type",
"===",
"\"AssignmentPattern\"",
"?",
"id",
".",
"parent",
".",
"right",
":",
"null",
")",
";",
"const",
"defaultStart",
"=",
"defaultValue",
"&&",
"defaultValue",
".",
"range",
"[",
"0",
"]",
";",
"const",
"defaultEnd",
"=",
"defaultValue",
"&&",
"defaultValue",
".",
"range",
"[",
"1",
"]",
";",
"return",
"variable",
".",
"references",
".",
"some",
"(",
"reference",
"=>",
"{",
"const",
"start",
"=",
"reference",
".",
"identifier",
".",
"range",
"[",
"0",
"]",
";",
"const",
"end",
"=",
"reference",
".",
"identifier",
".",
"range",
"[",
"1",
"]",
";",
"return",
"!",
"reference",
".",
"init",
"&&",
"(",
"start",
"<",
"idStart",
"||",
"(",
"defaultValue",
"!==",
"null",
"&&",
"start",
">=",
"defaultStart",
"&&",
"end",
"<=",
"defaultEnd",
")",
"||",
"(",
"start",
">=",
"initStart",
"&&",
"end",
"<=",
"initEnd",
")",
")",
";",
"}",
")",
";",
"}",
";",
"}"
] | Creates the predicate function which checks whether a variable has their references in TDZ.
The predicate function would return `true`:
- if a reference is before the declarator. E.g. (var a = b, b = 1;)(var {a = b, b} = {};)
- if a reference is in the expression of their default value. E.g. (var {a = a} = {};)
- if a reference is in the expression of their initializer. E.g. (var a = a;)
@param {ASTNode} node - The initializer node of VariableDeclarator.
@returns {Function} The predicate function.
@private | [
"Creates",
"the",
"predicate",
"function",
"which",
"checks",
"whether",
"a",
"variable",
"has",
"their",
"references",
"in",
"TDZ",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-var.js#L153-L175 |
3,152 | eslint/eslint | lib/rules/no-var.js | hasSelfReferenceInTDZ | function hasSelfReferenceInTDZ(declarator) {
if (!declarator.init) {
return false;
}
const variables = context.getDeclaredVariables(declarator);
return variables.some(hasReferenceInTDZ(declarator.init));
} | javascript | function hasSelfReferenceInTDZ(declarator) {
if (!declarator.init) {
return false;
}
const variables = context.getDeclaredVariables(declarator);
return variables.some(hasReferenceInTDZ(declarator.init));
} | [
"function",
"hasSelfReferenceInTDZ",
"(",
"declarator",
")",
"{",
"if",
"(",
"!",
"declarator",
".",
"init",
")",
"{",
"return",
"false",
";",
"}",
"const",
"variables",
"=",
"context",
".",
"getDeclaredVariables",
"(",
"declarator",
")",
";",
"return",
"variables",
".",
"some",
"(",
"hasReferenceInTDZ",
"(",
"declarator",
".",
"init",
")",
")",
";",
"}"
] | Checks whether the variables which are defined by the given declarator node have their references in TDZ.
@param {ASTNode} declarator - The VariableDeclarator node to check.
@returns {boolean} `true` if one of the variables which are defined by the given declarator node have their references in TDZ. | [
"Checks",
"whether",
"the",
"variables",
"which",
"are",
"defined",
"by",
"the",
"given",
"declarator",
"node",
"have",
"their",
"references",
"in",
"TDZ",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-var.js#L205-L212 |
3,153 | eslint/eslint | lib/rules/no-var.js | report | function report(node) {
context.report({
node,
message: "Unexpected var, use let or const instead.",
fix(fixer) {
const varToken = sourceCode.getFirstToken(node, { filter: t => t.value === "var" });
return canFix(node)
? fixer.replaceText(varToken, "let")
: null;
}
});
} | javascript | function report(node) {
context.report({
node,
message: "Unexpected var, use let or const instead.",
fix(fixer) {
const varToken = sourceCode.getFirstToken(node, { filter: t => t.value === "var" });
return canFix(node)
? fixer.replaceText(varToken, "let")
: null;
}
});
} | [
"function",
"report",
"(",
"node",
")",
"{",
"context",
".",
"report",
"(",
"{",
"node",
",",
"message",
":",
"\"Unexpected var, use let or const instead.\"",
",",
"fix",
"(",
"fixer",
")",
"{",
"const",
"varToken",
"=",
"sourceCode",
".",
"getFirstToken",
"(",
"node",
",",
"{",
"filter",
":",
"t",
"=>",
"t",
".",
"value",
"===",
"\"var\"",
"}",
")",
";",
"return",
"canFix",
"(",
"node",
")",
"?",
"fixer",
".",
"replaceText",
"(",
"varToken",
",",
"\"let\"",
")",
":",
"null",
";",
"}",
"}",
")",
";",
"}"
] | Reports a given variable declaration node.
@param {ASTNode} node - A variable declaration node to report.
@returns {void} | [
"Reports",
"a",
"given",
"variable",
"declaration",
"node",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-var.js#L307-L320 |
3,154 | eslint/eslint | lib/rules/no-confusing-arrow.js | checkArrowFunc | function checkArrowFunc(node) {
const body = node.body;
if (isConditional(body) && !(allowParens && astUtils.isParenthesised(sourceCode, body))) {
context.report({
node,
messageId: "confusing",
fix(fixer) {
// if `allowParens` is not set to true dont bother wrapping in parens
return allowParens && fixer.replaceText(node.body, `(${sourceCode.getText(node.body)})`);
}
});
}
} | javascript | function checkArrowFunc(node) {
const body = node.body;
if (isConditional(body) && !(allowParens && astUtils.isParenthesised(sourceCode, body))) {
context.report({
node,
messageId: "confusing",
fix(fixer) {
// if `allowParens` is not set to true dont bother wrapping in parens
return allowParens && fixer.replaceText(node.body, `(${sourceCode.getText(node.body)})`);
}
});
}
} | [
"function",
"checkArrowFunc",
"(",
"node",
")",
"{",
"const",
"body",
"=",
"node",
".",
"body",
";",
"if",
"(",
"isConditional",
"(",
"body",
")",
"&&",
"!",
"(",
"allowParens",
"&&",
"astUtils",
".",
"isParenthesised",
"(",
"sourceCode",
",",
"body",
")",
")",
")",
"{",
"context",
".",
"report",
"(",
"{",
"node",
",",
"messageId",
":",
"\"confusing\"",
",",
"fix",
"(",
"fixer",
")",
"{",
"// if `allowParens` is not set to true dont bother wrapping in parens",
"return",
"allowParens",
"&&",
"fixer",
".",
"replaceText",
"(",
"node",
".",
"body",
",",
"`",
"${",
"sourceCode",
".",
"getText",
"(",
"node",
".",
"body",
")",
"}",
"`",
")",
";",
"}",
"}",
")",
";",
"}",
"}"
] | Reports if an arrow function contains an ambiguous conditional.
@param {ASTNode} node - A node to check and report.
@returns {void} | [
"Reports",
"if",
"an",
"arrow",
"function",
"contains",
"an",
"ambiguous",
"conditional",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-confusing-arrow.js#L65-L79 |
3,155 | eslint/eslint | lib/rules/max-nested-callbacks.js | checkFunction | function checkFunction(node) {
const parent = node.parent;
if (parent.type === "CallExpression") {
callbackStack.push(node);
}
if (callbackStack.length > THRESHOLD) {
const opts = { num: callbackStack.length, max: THRESHOLD };
context.report({ node, messageId: "exceed", data: opts });
}
} | javascript | function checkFunction(node) {
const parent = node.parent;
if (parent.type === "CallExpression") {
callbackStack.push(node);
}
if (callbackStack.length > THRESHOLD) {
const opts = { num: callbackStack.length, max: THRESHOLD };
context.report({ node, messageId: "exceed", data: opts });
}
} | [
"function",
"checkFunction",
"(",
"node",
")",
"{",
"const",
"parent",
"=",
"node",
".",
"parent",
";",
"if",
"(",
"parent",
".",
"type",
"===",
"\"CallExpression\"",
")",
"{",
"callbackStack",
".",
"push",
"(",
"node",
")",
";",
"}",
"if",
"(",
"callbackStack",
".",
"length",
">",
"THRESHOLD",
")",
"{",
"const",
"opts",
"=",
"{",
"num",
":",
"callbackStack",
".",
"length",
",",
"max",
":",
"THRESHOLD",
"}",
";",
"context",
".",
"report",
"(",
"{",
"node",
",",
"messageId",
":",
"\"exceed\"",
",",
"data",
":",
"opts",
"}",
")",
";",
"}",
"}"
] | Checks a given function node for too many callbacks.
@param {ASTNode} node The node to check.
@returns {void}
@private | [
"Checks",
"a",
"given",
"function",
"node",
"for",
"too",
"many",
"callbacks",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/max-nested-callbacks.js#L81-L93 |
3,156 | eslint/eslint | lib/rules/init-declarations.js | isInitialized | function isInitialized(node) {
const declaration = node.parent;
const block = declaration.parent;
if (isForLoop(block)) {
if (block.type === "ForStatement") {
return block.init === declaration;
}
return block.left === declaration;
}
return Boolean(node.init);
} | javascript | function isInitialized(node) {
const declaration = node.parent;
const block = declaration.parent;
if (isForLoop(block)) {
if (block.type === "ForStatement") {
return block.init === declaration;
}
return block.left === declaration;
}
return Boolean(node.init);
} | [
"function",
"isInitialized",
"(",
"node",
")",
"{",
"const",
"declaration",
"=",
"node",
".",
"parent",
";",
"const",
"block",
"=",
"declaration",
".",
"parent",
";",
"if",
"(",
"isForLoop",
"(",
"block",
")",
")",
"{",
"if",
"(",
"block",
".",
"type",
"===",
"\"ForStatement\"",
")",
"{",
"return",
"block",
".",
"init",
"===",
"declaration",
";",
"}",
"return",
"block",
".",
"left",
"===",
"declaration",
";",
"}",
"return",
"Boolean",
"(",
"node",
".",
"init",
")",
";",
"}"
] | Checks whether or not a given declarator node has its initializer.
@param {ASTNode} node - A declarator node to check.
@returns {boolean} `true` when the node has its initializer. | [
"Checks",
"whether",
"or",
"not",
"a",
"given",
"declarator",
"node",
"has",
"its",
"initializer",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/init-declarations.js#L28-L39 |
3,157 | eslint/eslint | lib/rules/new-cap.js | checkArray | function checkArray(obj, key, fallback) {
/* istanbul ignore if */
if (Object.prototype.hasOwnProperty.call(obj, key) && !Array.isArray(obj[key])) {
throw new TypeError(`${key}, if provided, must be an Array`);
}
return obj[key] || fallback;
} | javascript | function checkArray(obj, key, fallback) {
/* istanbul ignore if */
if (Object.prototype.hasOwnProperty.call(obj, key) && !Array.isArray(obj[key])) {
throw new TypeError(`${key}, if provided, must be an Array`);
}
return obj[key] || fallback;
} | [
"function",
"checkArray",
"(",
"obj",
",",
"key",
",",
"fallback",
")",
"{",
"/* istanbul ignore if */",
"if",
"(",
"Object",
".",
"prototype",
".",
"hasOwnProperty",
".",
"call",
"(",
"obj",
",",
"key",
")",
"&&",
"!",
"Array",
".",
"isArray",
"(",
"obj",
"[",
"key",
"]",
")",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"`",
"${",
"key",
"}",
"`",
")",
";",
"}",
"return",
"obj",
"[",
"key",
"]",
"||",
"fallback",
";",
"}"
] | Ensure that if the key is provided, it must be an array.
@param {Object} obj Object to check with `key`.
@param {string} key Object key to check on `obj`.
@param {*} fallback If obj[key] is not present, this will be returned.
@returns {string[]} Returns obj[key] if it's an Array, otherwise `fallback` | [
"Ensure",
"that",
"if",
"the",
"key",
"is",
"provided",
"it",
"must",
"be",
"an",
"array",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/new-cap.js#L36-L43 |
3,158 | eslint/eslint | lib/rules/new-cap.js | calculateCapIsNewExceptions | function calculateCapIsNewExceptions(config) {
let capIsNewExceptions = checkArray(config, "capIsNewExceptions", CAPS_ALLOWED);
if (capIsNewExceptions !== CAPS_ALLOWED) {
capIsNewExceptions = capIsNewExceptions.concat(CAPS_ALLOWED);
}
return capIsNewExceptions.reduce(invert, {});
} | javascript | function calculateCapIsNewExceptions(config) {
let capIsNewExceptions = checkArray(config, "capIsNewExceptions", CAPS_ALLOWED);
if (capIsNewExceptions !== CAPS_ALLOWED) {
capIsNewExceptions = capIsNewExceptions.concat(CAPS_ALLOWED);
}
return capIsNewExceptions.reduce(invert, {});
} | [
"function",
"calculateCapIsNewExceptions",
"(",
"config",
")",
"{",
"let",
"capIsNewExceptions",
"=",
"checkArray",
"(",
"config",
",",
"\"capIsNewExceptions\"",
",",
"CAPS_ALLOWED",
")",
";",
"if",
"(",
"capIsNewExceptions",
"!==",
"CAPS_ALLOWED",
")",
"{",
"capIsNewExceptions",
"=",
"capIsNewExceptions",
".",
"concat",
"(",
"CAPS_ALLOWED",
")",
";",
"}",
"return",
"capIsNewExceptions",
".",
"reduce",
"(",
"invert",
",",
"{",
"}",
")",
";",
"}"
] | Creates an object with the cap is new exceptions as its keys and true as their values.
@param {Object} config Rule configuration
@returns {Object} Object with cap is new exceptions. | [
"Creates",
"an",
"object",
"with",
"the",
"cap",
"is",
"new",
"exceptions",
"as",
"its",
"keys",
"and",
"true",
"as",
"their",
"values",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/new-cap.js#L61-L69 |
3,159 | eslint/eslint | lib/rules/new-cap.js | getCap | function getCap(str) {
const firstChar = str.charAt(0);
const firstCharLower = firstChar.toLowerCase();
const firstCharUpper = firstChar.toUpperCase();
if (firstCharLower === firstCharUpper) {
// char has no uppercase variant, so it's non-alphabetic
return "non-alpha";
}
if (firstChar === firstCharLower) {
return "lower";
}
return "upper";
} | javascript | function getCap(str) {
const firstChar = str.charAt(0);
const firstCharLower = firstChar.toLowerCase();
const firstCharUpper = firstChar.toUpperCase();
if (firstCharLower === firstCharUpper) {
// char has no uppercase variant, so it's non-alphabetic
return "non-alpha";
}
if (firstChar === firstCharLower) {
return "lower";
}
return "upper";
} | [
"function",
"getCap",
"(",
"str",
")",
"{",
"const",
"firstChar",
"=",
"str",
".",
"charAt",
"(",
"0",
")",
";",
"const",
"firstCharLower",
"=",
"firstChar",
".",
"toLowerCase",
"(",
")",
";",
"const",
"firstCharUpper",
"=",
"firstChar",
".",
"toUpperCase",
"(",
")",
";",
"if",
"(",
"firstCharLower",
"===",
"firstCharUpper",
")",
"{",
"// char has no uppercase variant, so it's non-alphabetic",
"return",
"\"non-alpha\"",
";",
"}",
"if",
"(",
"firstChar",
"===",
"firstCharLower",
")",
"{",
"return",
"\"lower\"",
";",
"}",
"return",
"\"upper\"",
";",
"}"
] | Returns the capitalization state of the string -
Whether the first character is uppercase, lowercase, or non-alphabetic
@param {string} str String
@returns {string} capitalization state: "non-alpha", "lower", or "upper" | [
"Returns",
"the",
"capitalization",
"state",
"of",
"the",
"string",
"-",
"Whether",
"the",
"first",
"character",
"is",
"uppercase",
"lowercase",
"or",
"non",
"-",
"alphabetic"
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/new-cap.js#L181-L197 |
3,160 | eslint/eslint | lib/rules/new-cap.js | isCapAllowed | function isCapAllowed(allowedMap, node, calleeName, pattern) {
const sourceText = sourceCode.getText(node.callee);
if (allowedMap[calleeName] || allowedMap[sourceText]) {
return true;
}
if (pattern && pattern.test(sourceText)) {
return true;
}
if (calleeName === "UTC" && node.callee.type === "MemberExpression") {
// allow if callee is Date.UTC
return node.callee.object.type === "Identifier" &&
node.callee.object.name === "Date";
}
return skipProperties && node.callee.type === "MemberExpression";
} | javascript | function isCapAllowed(allowedMap, node, calleeName, pattern) {
const sourceText = sourceCode.getText(node.callee);
if (allowedMap[calleeName] || allowedMap[sourceText]) {
return true;
}
if (pattern && pattern.test(sourceText)) {
return true;
}
if (calleeName === "UTC" && node.callee.type === "MemberExpression") {
// allow if callee is Date.UTC
return node.callee.object.type === "Identifier" &&
node.callee.object.name === "Date";
}
return skipProperties && node.callee.type === "MemberExpression";
} | [
"function",
"isCapAllowed",
"(",
"allowedMap",
",",
"node",
",",
"calleeName",
",",
"pattern",
")",
"{",
"const",
"sourceText",
"=",
"sourceCode",
".",
"getText",
"(",
"node",
".",
"callee",
")",
";",
"if",
"(",
"allowedMap",
"[",
"calleeName",
"]",
"||",
"allowedMap",
"[",
"sourceText",
"]",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"pattern",
"&&",
"pattern",
".",
"test",
"(",
"sourceText",
")",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"calleeName",
"===",
"\"UTC\"",
"&&",
"node",
".",
"callee",
".",
"type",
"===",
"\"MemberExpression\"",
")",
"{",
"// allow if callee is Date.UTC",
"return",
"node",
".",
"callee",
".",
"object",
".",
"type",
"===",
"\"Identifier\"",
"&&",
"node",
".",
"callee",
".",
"object",
".",
"name",
"===",
"\"Date\"",
";",
"}",
"return",
"skipProperties",
"&&",
"node",
".",
"callee",
".",
"type",
"===",
"\"MemberExpression\"",
";",
"}"
] | Check if capitalization is allowed for a CallExpression
@param {Object} allowedMap Object mapping calleeName to a Boolean
@param {ASTNode} node CallExpression node
@param {string} calleeName Capitalized callee name from a CallExpression
@param {Object} pattern RegExp object from options pattern
@returns {boolean} Returns true if the callee may be capitalized | [
"Check",
"if",
"capitalization",
"is",
"allowed",
"for",
"a",
"CallExpression"
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/new-cap.js#L207-L226 |
3,161 | eslint/eslint | lib/rules/new-cap.js | report | function report(node, messageId) {
let callee = node.callee;
if (callee.type === "MemberExpression") {
callee = callee.property;
}
context.report({ node, loc: callee.loc.start, messageId });
} | javascript | function report(node, messageId) {
let callee = node.callee;
if (callee.type === "MemberExpression") {
callee = callee.property;
}
context.report({ node, loc: callee.loc.start, messageId });
} | [
"function",
"report",
"(",
"node",
",",
"messageId",
")",
"{",
"let",
"callee",
"=",
"node",
".",
"callee",
";",
"if",
"(",
"callee",
".",
"type",
"===",
"\"MemberExpression\"",
")",
"{",
"callee",
"=",
"callee",
".",
"property",
";",
"}",
"context",
".",
"report",
"(",
"{",
"node",
",",
"loc",
":",
"callee",
".",
"loc",
".",
"start",
",",
"messageId",
"}",
")",
";",
"}"
] | Reports the given messageId for the given node. The location will be the start of the property or the callee.
@param {ASTNode} node CallExpression or NewExpression node.
@param {string} messageId The messageId to report.
@returns {void} | [
"Reports",
"the",
"given",
"messageId",
"for",
"the",
"given",
"node",
".",
"The",
"location",
"will",
"be",
"the",
"start",
"of",
"the",
"property",
"or",
"the",
"callee",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/new-cap.js#L234-L242 |
3,162 | eslint/eslint | lib/util/traverser.js | getVisitorKeys | function getVisitorKeys(visitorKeys, node) {
let keys = visitorKeys[node.type];
if (!keys) {
keys = vk.getKeys(node);
debug("Unknown node type \"%s\": Estimated visitor keys %j", node.type, keys);
}
return keys;
} | javascript | function getVisitorKeys(visitorKeys, node) {
let keys = visitorKeys[node.type];
if (!keys) {
keys = vk.getKeys(node);
debug("Unknown node type \"%s\": Estimated visitor keys %j", node.type, keys);
}
return keys;
} | [
"function",
"getVisitorKeys",
"(",
"visitorKeys",
",",
"node",
")",
"{",
"let",
"keys",
"=",
"visitorKeys",
"[",
"node",
".",
"type",
"]",
";",
"if",
"(",
"!",
"keys",
")",
"{",
"keys",
"=",
"vk",
".",
"getKeys",
"(",
"node",
")",
";",
"debug",
"(",
"\"Unknown node type \\\"%s\\\": Estimated visitor keys %j\"",
",",
"node",
".",
"type",
",",
"keys",
")",
";",
"}",
"return",
"keys",
";",
"}"
] | Get the visitor keys of a given node.
@param {Object} visitorKeys The map of visitor keys.
@param {ASTNode} node The node to get their visitor keys.
@returns {string[]} The visitor keys of the node. | [
"Get",
"the",
"visitor",
"keys",
"of",
"a",
"given",
"node",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/util/traverser.js#L43-L52 |
3,163 | eslint/eslint | lib/rules/yoda.js | looksLikeLiteral | function looksLikeLiteral(node) {
return (node.type === "UnaryExpression" &&
node.operator === "-" &&
node.prefix &&
node.argument.type === "Literal" &&
typeof node.argument.value === "number");
} | javascript | function looksLikeLiteral(node) {
return (node.type === "UnaryExpression" &&
node.operator === "-" &&
node.prefix &&
node.argument.type === "Literal" &&
typeof node.argument.value === "number");
} | [
"function",
"looksLikeLiteral",
"(",
"node",
")",
"{",
"return",
"(",
"node",
".",
"type",
"===",
"\"UnaryExpression\"",
"&&",
"node",
".",
"operator",
"===",
"\"-\"",
"&&",
"node",
".",
"prefix",
"&&",
"node",
".",
"argument",
".",
"type",
"===",
"\"Literal\"",
"&&",
"typeof",
"node",
".",
"argument",
".",
"value",
"===",
"\"number\"",
")",
";",
"}"
] | Determines whether a non-Literal node is a negative number that should be
treated as if it were a single Literal node.
@param {ASTNode} node Node to test.
@returns {boolean} True if the node is a negative number that looks like a
real literal and should be treated as such. | [
"Determines",
"whether",
"a",
"non",
"-",
"Literal",
"node",
"is",
"a",
"negative",
"number",
"that",
"should",
"be",
"treated",
"as",
"if",
"it",
"were",
"a",
"single",
"Literal",
"node",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/yoda.js#L52-L58 |
3,164 | eslint/eslint | lib/rules/prefer-reflect.js | report | function report(node, existing, substitute) {
context.report({
node,
message: "Avoid using {{existing}}, instead use {{substitute}}.",
data: {
existing,
substitute
}
});
} | javascript | function report(node, existing, substitute) {
context.report({
node,
message: "Avoid using {{existing}}, instead use {{substitute}}.",
data: {
existing,
substitute
}
});
} | [
"function",
"report",
"(",
"node",
",",
"existing",
",",
"substitute",
")",
"{",
"context",
".",
"report",
"(",
"{",
"node",
",",
"message",
":",
"\"Avoid using {{existing}}, instead use {{substitute}}.\"",
",",
"data",
":",
"{",
"existing",
",",
"substitute",
"}",
"}",
")",
";",
"}"
] | Reports the Reflect violation based on the `existing` and `substitute`
@param {Object} node The node that violates the rule.
@param {string} existing The existing method name that has been used.
@param {string} substitute The Reflect substitute that should be used.
@returns {void} | [
"Reports",
"the",
"Reflect",
"violation",
"based",
"on",
"the",
"existing",
"and",
"substitute"
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/prefer-reflect.js#L89-L98 |
3,165 | eslint/eslint | lib/rules/prefer-named-capture-group.js | checkRegex | function checkRegex(regex, node, uFlag) {
let ast;
try {
ast = parser.parsePattern(regex, 0, regex.length, uFlag);
} catch (_) {
// ignore regex syntax errors
return;
}
regexpp.visitRegExpAST(ast, {
onCapturingGroupEnter(group) {
if (!group.name) {
const locNode = node.type === "Literal" ? node : node.arguments[0];
context.report({
node,
messageId: "required",
loc: {
start: {
line: locNode.loc.start.line,
column: locNode.loc.start.column + group.start + 1
},
end: {
line: locNode.loc.start.line,
column: locNode.loc.start.column + group.end + 1
}
},
data: {
group: group.raw
}
});
}
}
});
} | javascript | function checkRegex(regex, node, uFlag) {
let ast;
try {
ast = parser.parsePattern(regex, 0, regex.length, uFlag);
} catch (_) {
// ignore regex syntax errors
return;
}
regexpp.visitRegExpAST(ast, {
onCapturingGroupEnter(group) {
if (!group.name) {
const locNode = node.type === "Literal" ? node : node.arguments[0];
context.report({
node,
messageId: "required",
loc: {
start: {
line: locNode.loc.start.line,
column: locNode.loc.start.column + group.start + 1
},
end: {
line: locNode.loc.start.line,
column: locNode.loc.start.column + group.end + 1
}
},
data: {
group: group.raw
}
});
}
}
});
} | [
"function",
"checkRegex",
"(",
"regex",
",",
"node",
",",
"uFlag",
")",
"{",
"let",
"ast",
";",
"try",
"{",
"ast",
"=",
"parser",
".",
"parsePattern",
"(",
"regex",
",",
"0",
",",
"regex",
".",
"length",
",",
"uFlag",
")",
";",
"}",
"catch",
"(",
"_",
")",
"{",
"// ignore regex syntax errors",
"return",
";",
"}",
"regexpp",
".",
"visitRegExpAST",
"(",
"ast",
",",
"{",
"onCapturingGroupEnter",
"(",
"group",
")",
"{",
"if",
"(",
"!",
"group",
".",
"name",
")",
"{",
"const",
"locNode",
"=",
"node",
".",
"type",
"===",
"\"Literal\"",
"?",
"node",
":",
"node",
".",
"arguments",
"[",
"0",
"]",
";",
"context",
".",
"report",
"(",
"{",
"node",
",",
"messageId",
":",
"\"required\"",
",",
"loc",
":",
"{",
"start",
":",
"{",
"line",
":",
"locNode",
".",
"loc",
".",
"start",
".",
"line",
",",
"column",
":",
"locNode",
".",
"loc",
".",
"start",
".",
"column",
"+",
"group",
".",
"start",
"+",
"1",
"}",
",",
"end",
":",
"{",
"line",
":",
"locNode",
".",
"loc",
".",
"start",
".",
"line",
",",
"column",
":",
"locNode",
".",
"loc",
".",
"start",
".",
"column",
"+",
"group",
".",
"end",
"+",
"1",
"}",
"}",
",",
"data",
":",
"{",
"group",
":",
"group",
".",
"raw",
"}",
"}",
")",
";",
"}",
"}",
"}",
")",
";",
"}"
] | Function to check regular expression.
@param {string} regex The regular expression to be check.
@param {ASTNode} node AST node which contains regular expression.
@param {boolean} uFlag Flag indicates whether unicode mode is enabled or not.
@returns {void} | [
"Function",
"to",
"check",
"regular",
"expression",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/prefer-named-capture-group.js#L58-L94 |
3,166 | eslint/eslint | lib/util/file-finder.js | normalizeDirectoryEntries | function normalizeDirectoryEntries(entries, directory, supportedConfigs) {
const fileHash = {};
entries.forEach(entry => {
if (supportedConfigs.indexOf(entry) >= 0) {
const resolvedEntry = path.resolve(directory, entry);
if (fs.statSync(resolvedEntry).isFile()) {
fileHash[entry] = resolvedEntry;
}
}
});
return fileHash;
} | javascript | function normalizeDirectoryEntries(entries, directory, supportedConfigs) {
const fileHash = {};
entries.forEach(entry => {
if (supportedConfigs.indexOf(entry) >= 0) {
const resolvedEntry = path.resolve(directory, entry);
if (fs.statSync(resolvedEntry).isFile()) {
fileHash[entry] = resolvedEntry;
}
}
});
return fileHash;
} | [
"function",
"normalizeDirectoryEntries",
"(",
"entries",
",",
"directory",
",",
"supportedConfigs",
")",
"{",
"const",
"fileHash",
"=",
"{",
"}",
";",
"entries",
".",
"forEach",
"(",
"entry",
"=>",
"{",
"if",
"(",
"supportedConfigs",
".",
"indexOf",
"(",
"entry",
")",
">=",
"0",
")",
"{",
"const",
"resolvedEntry",
"=",
"path",
".",
"resolve",
"(",
"directory",
",",
"entry",
")",
";",
"if",
"(",
"fs",
".",
"statSync",
"(",
"resolvedEntry",
")",
".",
"isFile",
"(",
")",
")",
"{",
"fileHash",
"[",
"entry",
"]",
"=",
"resolvedEntry",
";",
"}",
"}",
"}",
")",
";",
"return",
"fileHash",
";",
"}"
] | Create a hash of filenames from a directory listing
@param {string[]} entries Array of directory entries.
@param {string} directory Path to a current directory.
@param {string[]} supportedConfigs List of support filenames.
@returns {Object} Hashmap of filenames | [
"Create",
"a",
"hash",
"of",
"filenames",
"from",
"a",
"directory",
"listing"
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/util/file-finder.js#L42-L55 |
3,167 | eslint/eslint | lib/rules/no-empty-function.js | getKind | function getKind(node) {
const parent = node.parent;
let kind = "";
if (node.type === "ArrowFunctionExpression") {
return "arrowFunctions";
}
// Detects main kind.
if (parent.type === "Property") {
if (parent.kind === "get") {
return "getters";
}
if (parent.kind === "set") {
return "setters";
}
kind = parent.method ? "methods" : "functions";
} else if (parent.type === "MethodDefinition") {
if (parent.kind === "get") {
return "getters";
}
if (parent.kind === "set") {
return "setters";
}
if (parent.kind === "constructor") {
return "constructors";
}
kind = "methods";
} else {
kind = "functions";
}
// Detects prefix.
let prefix = "";
if (node.generator) {
prefix = "generator";
} else if (node.async) {
prefix = "async";
} else {
return kind;
}
return prefix + kind[0].toUpperCase() + kind.slice(1);
} | javascript | function getKind(node) {
const parent = node.parent;
let kind = "";
if (node.type === "ArrowFunctionExpression") {
return "arrowFunctions";
}
// Detects main kind.
if (parent.type === "Property") {
if (parent.kind === "get") {
return "getters";
}
if (parent.kind === "set") {
return "setters";
}
kind = parent.method ? "methods" : "functions";
} else if (parent.type === "MethodDefinition") {
if (parent.kind === "get") {
return "getters";
}
if (parent.kind === "set") {
return "setters";
}
if (parent.kind === "constructor") {
return "constructors";
}
kind = "methods";
} else {
kind = "functions";
}
// Detects prefix.
let prefix = "";
if (node.generator) {
prefix = "generator";
} else if (node.async) {
prefix = "async";
} else {
return kind;
}
return prefix + kind[0].toUpperCase() + kind.slice(1);
} | [
"function",
"getKind",
"(",
"node",
")",
"{",
"const",
"parent",
"=",
"node",
".",
"parent",
";",
"let",
"kind",
"=",
"\"\"",
";",
"if",
"(",
"node",
".",
"type",
"===",
"\"ArrowFunctionExpression\"",
")",
"{",
"return",
"\"arrowFunctions\"",
";",
"}",
"// Detects main kind.",
"if",
"(",
"parent",
".",
"type",
"===",
"\"Property\"",
")",
"{",
"if",
"(",
"parent",
".",
"kind",
"===",
"\"get\"",
")",
"{",
"return",
"\"getters\"",
";",
"}",
"if",
"(",
"parent",
".",
"kind",
"===",
"\"set\"",
")",
"{",
"return",
"\"setters\"",
";",
"}",
"kind",
"=",
"parent",
".",
"method",
"?",
"\"methods\"",
":",
"\"functions\"",
";",
"}",
"else",
"if",
"(",
"parent",
".",
"type",
"===",
"\"MethodDefinition\"",
")",
"{",
"if",
"(",
"parent",
".",
"kind",
"===",
"\"get\"",
")",
"{",
"return",
"\"getters\"",
";",
"}",
"if",
"(",
"parent",
".",
"kind",
"===",
"\"set\"",
")",
"{",
"return",
"\"setters\"",
";",
"}",
"if",
"(",
"parent",
".",
"kind",
"===",
"\"constructor\"",
")",
"{",
"return",
"\"constructors\"",
";",
"}",
"kind",
"=",
"\"methods\"",
";",
"}",
"else",
"{",
"kind",
"=",
"\"functions\"",
";",
"}",
"// Detects prefix.",
"let",
"prefix",
"=",
"\"\"",
";",
"if",
"(",
"node",
".",
"generator",
")",
"{",
"prefix",
"=",
"\"generator\"",
";",
"}",
"else",
"if",
"(",
"node",
".",
"async",
")",
"{",
"prefix",
"=",
"\"async\"",
";",
"}",
"else",
"{",
"return",
"kind",
";",
"}",
"return",
"prefix",
"+",
"kind",
"[",
"0",
"]",
".",
"toUpperCase",
"(",
")",
"+",
"kind",
".",
"slice",
"(",
"1",
")",
";",
"}"
] | Gets the kind of a given function node.
@param {ASTNode} node - A function node to get. This is one of
an ArrowFunctionExpression, a FunctionDeclaration, or a
FunctionExpression.
@returns {string} The kind of the function. This is one of "functions",
"arrowFunctions", "generatorFunctions", "asyncFunctions", "methods",
"generatorMethods", "asyncMethods", "getters", "setters", and
"constructors". | [
"Gets",
"the",
"kind",
"of",
"a",
"given",
"function",
"node",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-empty-function.js#L40-L85 |
3,168 | eslint/eslint | lib/rules/no-empty-function.js | reportIfEmpty | function reportIfEmpty(node) {
const kind = getKind(node);
const name = astUtils.getFunctionNameWithKind(node);
const innerComments = sourceCode.getTokens(node.body, {
includeComments: true,
filter: astUtils.isCommentToken
});
if (allowed.indexOf(kind) === -1 &&
node.body.type === "BlockStatement" &&
node.body.body.length === 0 &&
innerComments.length === 0
) {
context.report({
node,
loc: node.body.loc.start,
messageId: "unexpected",
data: { name }
});
}
} | javascript | function reportIfEmpty(node) {
const kind = getKind(node);
const name = astUtils.getFunctionNameWithKind(node);
const innerComments = sourceCode.getTokens(node.body, {
includeComments: true,
filter: astUtils.isCommentToken
});
if (allowed.indexOf(kind) === -1 &&
node.body.type === "BlockStatement" &&
node.body.body.length === 0 &&
innerComments.length === 0
) {
context.report({
node,
loc: node.body.loc.start,
messageId: "unexpected",
data: { name }
});
}
} | [
"function",
"reportIfEmpty",
"(",
"node",
")",
"{",
"const",
"kind",
"=",
"getKind",
"(",
"node",
")",
";",
"const",
"name",
"=",
"astUtils",
".",
"getFunctionNameWithKind",
"(",
"node",
")",
";",
"const",
"innerComments",
"=",
"sourceCode",
".",
"getTokens",
"(",
"node",
".",
"body",
",",
"{",
"includeComments",
":",
"true",
",",
"filter",
":",
"astUtils",
".",
"isCommentToken",
"}",
")",
";",
"if",
"(",
"allowed",
".",
"indexOf",
"(",
"kind",
")",
"===",
"-",
"1",
"&&",
"node",
".",
"body",
".",
"type",
"===",
"\"BlockStatement\"",
"&&",
"node",
".",
"body",
".",
"body",
".",
"length",
"===",
"0",
"&&",
"innerComments",
".",
"length",
"===",
"0",
")",
"{",
"context",
".",
"report",
"(",
"{",
"node",
",",
"loc",
":",
"node",
".",
"body",
".",
"loc",
".",
"start",
",",
"messageId",
":",
"\"unexpected\"",
",",
"data",
":",
"{",
"name",
"}",
"}",
")",
";",
"}",
"}"
] | Reports a given function node if the node matches the following patterns.
- Not allowed by options.
- The body is empty.
- The body doesn't have any comments.
@param {ASTNode} node - A function node to report. This is one of
an ArrowFunctionExpression, a FunctionDeclaration, or a
FunctionExpression.
@returns {void} | [
"Reports",
"a",
"given",
"function",
"node",
"if",
"the",
"node",
"matches",
"the",
"following",
"patterns",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-empty-function.js#L139-L159 |
3,169 | eslint/eslint | lib/rules/no-unused-labels.js | enterLabeledScope | function enterLabeledScope(node) {
scopeInfo = {
label: node.label.name,
used: false,
upper: scopeInfo
};
} | javascript | function enterLabeledScope(node) {
scopeInfo = {
label: node.label.name,
used: false,
upper: scopeInfo
};
} | [
"function",
"enterLabeledScope",
"(",
"node",
")",
"{",
"scopeInfo",
"=",
"{",
"label",
":",
"node",
".",
"label",
".",
"name",
",",
"used",
":",
"false",
",",
"upper",
":",
"scopeInfo",
"}",
";",
"}"
] | Adds a scope info to the stack.
@param {ASTNode} node - A node to add. This is a LabeledStatement.
@returns {void} | [
"Adds",
"a",
"scope",
"info",
"to",
"the",
"stack",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-unused-labels.js#L42-L48 |
3,170 | eslint/eslint | lib/rules/no-unused-labels.js | exitLabeledScope | function exitLabeledScope(node) {
if (!scopeInfo.used) {
context.report({
node: node.label,
messageId: "unused",
data: node.label,
fix(fixer) {
/*
* Only perform a fix if there are no comments between the label and the body. This will be the case
* when there is exactly one token/comment (the ":") between the label and the body.
*/
if (sourceCode.getTokenAfter(node.label, { includeComments: true }) ===
sourceCode.getTokenBefore(node.body, { includeComments: true })) {
return fixer.removeRange([node.range[0], node.body.range[0]]);
}
return null;
}
});
}
scopeInfo = scopeInfo.upper;
} | javascript | function exitLabeledScope(node) {
if (!scopeInfo.used) {
context.report({
node: node.label,
messageId: "unused",
data: node.label,
fix(fixer) {
/*
* Only perform a fix if there are no comments between the label and the body. This will be the case
* when there is exactly one token/comment (the ":") between the label and the body.
*/
if (sourceCode.getTokenAfter(node.label, { includeComments: true }) ===
sourceCode.getTokenBefore(node.body, { includeComments: true })) {
return fixer.removeRange([node.range[0], node.body.range[0]]);
}
return null;
}
});
}
scopeInfo = scopeInfo.upper;
} | [
"function",
"exitLabeledScope",
"(",
"node",
")",
"{",
"if",
"(",
"!",
"scopeInfo",
".",
"used",
")",
"{",
"context",
".",
"report",
"(",
"{",
"node",
":",
"node",
".",
"label",
",",
"messageId",
":",
"\"unused\"",
",",
"data",
":",
"node",
".",
"label",
",",
"fix",
"(",
"fixer",
")",
"{",
"/*\n * Only perform a fix if there are no comments between the label and the body. This will be the case\n * when there is exactly one token/comment (the \":\") between the label and the body.\n */",
"if",
"(",
"sourceCode",
".",
"getTokenAfter",
"(",
"node",
".",
"label",
",",
"{",
"includeComments",
":",
"true",
"}",
")",
"===",
"sourceCode",
".",
"getTokenBefore",
"(",
"node",
".",
"body",
",",
"{",
"includeComments",
":",
"true",
"}",
")",
")",
"{",
"return",
"fixer",
".",
"removeRange",
"(",
"[",
"node",
".",
"range",
"[",
"0",
"]",
",",
"node",
".",
"body",
".",
"range",
"[",
"0",
"]",
"]",
")",
";",
"}",
"return",
"null",
";",
"}",
"}",
")",
";",
"}",
"scopeInfo",
"=",
"scopeInfo",
".",
"upper",
";",
"}"
] | Removes the top of the stack.
At the same time, this reports the label if it's never used.
@param {ASTNode} node - A node to report. This is a LabeledStatement.
@returns {void} | [
"Removes",
"the",
"top",
"of",
"the",
"stack",
".",
"At",
"the",
"same",
"time",
"this",
"reports",
"the",
"label",
"if",
"it",
"s",
"never",
"used",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-unused-labels.js#L57-L80 |
3,171 | eslint/eslint | lib/rules/no-unused-labels.js | markAsUsed | function markAsUsed(node) {
if (!node.label) {
return;
}
const label = node.label.name;
let info = scopeInfo;
while (info) {
if (info.label === label) {
info.used = true;
break;
}
info = info.upper;
}
} | javascript | function markAsUsed(node) {
if (!node.label) {
return;
}
const label = node.label.name;
let info = scopeInfo;
while (info) {
if (info.label === label) {
info.used = true;
break;
}
info = info.upper;
}
} | [
"function",
"markAsUsed",
"(",
"node",
")",
"{",
"if",
"(",
"!",
"node",
".",
"label",
")",
"{",
"return",
";",
"}",
"const",
"label",
"=",
"node",
".",
"label",
".",
"name",
";",
"let",
"info",
"=",
"scopeInfo",
";",
"while",
"(",
"info",
")",
"{",
"if",
"(",
"info",
".",
"label",
"===",
"label",
")",
"{",
"info",
".",
"used",
"=",
"true",
";",
"break",
";",
"}",
"info",
"=",
"info",
".",
"upper",
";",
"}",
"}"
] | Marks the label of a given node as used.
@param {ASTNode} node - A node to mark. This is a BreakStatement or
ContinueStatement.
@returns {void} | [
"Marks",
"the",
"label",
"of",
"a",
"given",
"node",
"as",
"used",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-unused-labels.js#L89-L104 |
3,172 | eslint/eslint | lib/rules/padding-line-between-statements.js | isIIFEStatement | function isIIFEStatement(node) {
if (node.type === "ExpressionStatement") {
let call = node.expression;
if (call.type === "UnaryExpression") {
call = call.argument;
}
return call.type === "CallExpression" && astUtils.isFunction(call.callee);
}
return false;
} | javascript | function isIIFEStatement(node) {
if (node.type === "ExpressionStatement") {
let call = node.expression;
if (call.type === "UnaryExpression") {
call = call.argument;
}
return call.type === "CallExpression" && astUtils.isFunction(call.callee);
}
return false;
} | [
"function",
"isIIFEStatement",
"(",
"node",
")",
"{",
"if",
"(",
"node",
".",
"type",
"===",
"\"ExpressionStatement\"",
")",
"{",
"let",
"call",
"=",
"node",
".",
"expression",
";",
"if",
"(",
"call",
".",
"type",
"===",
"\"UnaryExpression\"",
")",
"{",
"call",
"=",
"call",
".",
"argument",
";",
"}",
"return",
"call",
".",
"type",
"===",
"\"CallExpression\"",
"&&",
"astUtils",
".",
"isFunction",
"(",
"call",
".",
"callee",
")",
";",
"}",
"return",
"false",
";",
"}"
] | Checks the given node is an expression statement of IIFE.
@param {ASTNode} node The node to check.
@returns {boolean} `true` if the node is an expression statement of IIFE.
@private | [
"Checks",
"the",
"given",
"node",
"is",
"an",
"expression",
"statement",
"of",
"IIFE",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/padding-line-between-statements.js#L91-L101 |
3,173 | eslint/eslint | lib/rules/padding-line-between-statements.js | isBlockLikeStatement | function isBlockLikeStatement(sourceCode, node) {
// do-while with a block is a block-like statement.
if (node.type === "DoWhileStatement" && node.body.type === "BlockStatement") {
return true;
}
/*
* IIFE is a block-like statement specially from
* JSCS#disallowPaddingNewLinesAfterBlocks.
*/
if (isIIFEStatement(node)) {
return true;
}
// Checks the last token is a closing brace of blocks.
const lastToken = sourceCode.getLastToken(node, astUtils.isNotSemicolonToken);
const belongingNode = lastToken && astUtils.isClosingBraceToken(lastToken)
? sourceCode.getNodeByRangeIndex(lastToken.range[0])
: null;
return Boolean(belongingNode) && (
belongingNode.type === "BlockStatement" ||
belongingNode.type === "SwitchStatement"
);
} | javascript | function isBlockLikeStatement(sourceCode, node) {
// do-while with a block is a block-like statement.
if (node.type === "DoWhileStatement" && node.body.type === "BlockStatement") {
return true;
}
/*
* IIFE is a block-like statement specially from
* JSCS#disallowPaddingNewLinesAfterBlocks.
*/
if (isIIFEStatement(node)) {
return true;
}
// Checks the last token is a closing brace of blocks.
const lastToken = sourceCode.getLastToken(node, astUtils.isNotSemicolonToken);
const belongingNode = lastToken && astUtils.isClosingBraceToken(lastToken)
? sourceCode.getNodeByRangeIndex(lastToken.range[0])
: null;
return Boolean(belongingNode) && (
belongingNode.type === "BlockStatement" ||
belongingNode.type === "SwitchStatement"
);
} | [
"function",
"isBlockLikeStatement",
"(",
"sourceCode",
",",
"node",
")",
"{",
"// do-while with a block is a block-like statement.",
"if",
"(",
"node",
".",
"type",
"===",
"\"DoWhileStatement\"",
"&&",
"node",
".",
"body",
".",
"type",
"===",
"\"BlockStatement\"",
")",
"{",
"return",
"true",
";",
"}",
"/*\n * IIFE is a block-like statement specially from\n * JSCS#disallowPaddingNewLinesAfterBlocks.\n */",
"if",
"(",
"isIIFEStatement",
"(",
"node",
")",
")",
"{",
"return",
"true",
";",
"}",
"// Checks the last token is a closing brace of blocks.",
"const",
"lastToken",
"=",
"sourceCode",
".",
"getLastToken",
"(",
"node",
",",
"astUtils",
".",
"isNotSemicolonToken",
")",
";",
"const",
"belongingNode",
"=",
"lastToken",
"&&",
"astUtils",
".",
"isClosingBraceToken",
"(",
"lastToken",
")",
"?",
"sourceCode",
".",
"getNodeByRangeIndex",
"(",
"lastToken",
".",
"range",
"[",
"0",
"]",
")",
":",
"null",
";",
"return",
"Boolean",
"(",
"belongingNode",
")",
"&&",
"(",
"belongingNode",
".",
"type",
"===",
"\"BlockStatement\"",
"||",
"belongingNode",
".",
"type",
"===",
"\"SwitchStatement\"",
")",
";",
"}"
] | Checks whether the given node is a block-like statement.
This checks the last token of the node is the closing brace of a block.
@param {SourceCode} sourceCode The source code to get tokens.
@param {ASTNode} node The node to check.
@returns {boolean} `true` if the node is a block-like statement.
@private | [
"Checks",
"whether",
"the",
"given",
"node",
"is",
"a",
"block",
"-",
"like",
"statement",
".",
"This",
"checks",
"the",
"last",
"token",
"of",
"the",
"node",
"is",
"the",
"closing",
"brace",
"of",
"a",
"block",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/padding-line-between-statements.js#L112-L137 |
3,174 | eslint/eslint | lib/rules/padding-line-between-statements.js | isDirective | function isDirective(node, sourceCode) {
return (
node.type === "ExpressionStatement" &&
(
node.parent.type === "Program" ||
(
node.parent.type === "BlockStatement" &&
astUtils.isFunction(node.parent.parent)
)
) &&
node.expression.type === "Literal" &&
typeof node.expression.value === "string" &&
!astUtils.isParenthesised(sourceCode, node.expression)
);
} | javascript | function isDirective(node, sourceCode) {
return (
node.type === "ExpressionStatement" &&
(
node.parent.type === "Program" ||
(
node.parent.type === "BlockStatement" &&
astUtils.isFunction(node.parent.parent)
)
) &&
node.expression.type === "Literal" &&
typeof node.expression.value === "string" &&
!astUtils.isParenthesised(sourceCode, node.expression)
);
} | [
"function",
"isDirective",
"(",
"node",
",",
"sourceCode",
")",
"{",
"return",
"(",
"node",
".",
"type",
"===",
"\"ExpressionStatement\"",
"&&",
"(",
"node",
".",
"parent",
".",
"type",
"===",
"\"Program\"",
"||",
"(",
"node",
".",
"parent",
".",
"type",
"===",
"\"BlockStatement\"",
"&&",
"astUtils",
".",
"isFunction",
"(",
"node",
".",
"parent",
".",
"parent",
")",
")",
")",
"&&",
"node",
".",
"expression",
".",
"type",
"===",
"\"Literal\"",
"&&",
"typeof",
"node",
".",
"expression",
".",
"value",
"===",
"\"string\"",
"&&",
"!",
"astUtils",
".",
"isParenthesised",
"(",
"sourceCode",
",",
"node",
".",
"expression",
")",
")",
";",
"}"
] | Check whether the given node is a directive or not.
@param {ASTNode} node The node to check.
@param {SourceCode} sourceCode The source code object to get tokens.
@returns {boolean} `true` if the node is a directive. | [
"Check",
"whether",
"the",
"given",
"node",
"is",
"a",
"directive",
"or",
"not",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/padding-line-between-statements.js#L145-L159 |
3,175 | eslint/eslint | lib/rules/padding-line-between-statements.js | isDirectivePrologue | function isDirectivePrologue(node, sourceCode) {
if (isDirective(node, sourceCode)) {
for (const sibling of node.parent.body) {
if (sibling === node) {
break;
}
if (!isDirective(sibling, sourceCode)) {
return false;
}
}
return true;
}
return false;
} | javascript | function isDirectivePrologue(node, sourceCode) {
if (isDirective(node, sourceCode)) {
for (const sibling of node.parent.body) {
if (sibling === node) {
break;
}
if (!isDirective(sibling, sourceCode)) {
return false;
}
}
return true;
}
return false;
} | [
"function",
"isDirectivePrologue",
"(",
"node",
",",
"sourceCode",
")",
"{",
"if",
"(",
"isDirective",
"(",
"node",
",",
"sourceCode",
")",
")",
"{",
"for",
"(",
"const",
"sibling",
"of",
"node",
".",
"parent",
".",
"body",
")",
"{",
"if",
"(",
"sibling",
"===",
"node",
")",
"{",
"break",
";",
"}",
"if",
"(",
"!",
"isDirective",
"(",
"sibling",
",",
"sourceCode",
")",
")",
"{",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] | Check whether the given node is a part of directive prologue or not.
@param {ASTNode} node The node to check.
@param {SourceCode} sourceCode The source code object to get tokens.
@returns {boolean} `true` if the node is a part of directive prologue. | [
"Check",
"whether",
"the",
"given",
"node",
"is",
"a",
"part",
"of",
"directive",
"prologue",
"or",
"not",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/padding-line-between-statements.js#L167-L180 |
3,176 | eslint/eslint | lib/rules/padding-line-between-statements.js | getActualLastToken | function getActualLastToken(sourceCode, node) {
const semiToken = sourceCode.getLastToken(node);
const prevToken = sourceCode.getTokenBefore(semiToken);
const nextToken = sourceCode.getTokenAfter(semiToken);
const isSemicolonLessStyle = Boolean(
prevToken &&
nextToken &&
prevToken.range[0] >= node.range[0] &&
astUtils.isSemicolonToken(semiToken) &&
semiToken.loc.start.line !== prevToken.loc.end.line &&
semiToken.loc.end.line === nextToken.loc.start.line
);
return isSemicolonLessStyle ? prevToken : semiToken;
} | javascript | function getActualLastToken(sourceCode, node) {
const semiToken = sourceCode.getLastToken(node);
const prevToken = sourceCode.getTokenBefore(semiToken);
const nextToken = sourceCode.getTokenAfter(semiToken);
const isSemicolonLessStyle = Boolean(
prevToken &&
nextToken &&
prevToken.range[0] >= node.range[0] &&
astUtils.isSemicolonToken(semiToken) &&
semiToken.loc.start.line !== prevToken.loc.end.line &&
semiToken.loc.end.line === nextToken.loc.start.line
);
return isSemicolonLessStyle ? prevToken : semiToken;
} | [
"function",
"getActualLastToken",
"(",
"sourceCode",
",",
"node",
")",
"{",
"const",
"semiToken",
"=",
"sourceCode",
".",
"getLastToken",
"(",
"node",
")",
";",
"const",
"prevToken",
"=",
"sourceCode",
".",
"getTokenBefore",
"(",
"semiToken",
")",
";",
"const",
"nextToken",
"=",
"sourceCode",
".",
"getTokenAfter",
"(",
"semiToken",
")",
";",
"const",
"isSemicolonLessStyle",
"=",
"Boolean",
"(",
"prevToken",
"&&",
"nextToken",
"&&",
"prevToken",
".",
"range",
"[",
"0",
"]",
">=",
"node",
".",
"range",
"[",
"0",
"]",
"&&",
"astUtils",
".",
"isSemicolonToken",
"(",
"semiToken",
")",
"&&",
"semiToken",
".",
"loc",
".",
"start",
".",
"line",
"!==",
"prevToken",
".",
"loc",
".",
"end",
".",
"line",
"&&",
"semiToken",
".",
"loc",
".",
"end",
".",
"line",
"===",
"nextToken",
".",
"loc",
".",
"start",
".",
"line",
")",
";",
"return",
"isSemicolonLessStyle",
"?",
"prevToken",
":",
"semiToken",
";",
"}"
] | Gets the actual last token.
If a semicolon is semicolon-less style's semicolon, this ignores it.
For example:
foo()
;[1, 2, 3].forEach(bar)
@param {SourceCode} sourceCode The source code to get tokens.
@param {ASTNode} node The node to get.
@returns {Token} The actual last token.
@private | [
"Gets",
"the",
"actual",
"last",
"token",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/padding-line-between-statements.js#L196-L210 |
3,177 | eslint/eslint | lib/rules/padding-line-between-statements.js | verifyForNever | function verifyForNever(context, _, nextNode, paddingLines) {
if (paddingLines.length === 0) {
return;
}
context.report({
node: nextNode,
message: "Unexpected blank line before this statement.",
fix(fixer) {
if (paddingLines.length >= 2) {
return null;
}
const prevToken = paddingLines[0][0];
const nextToken = paddingLines[0][1];
const start = prevToken.range[1];
const end = nextToken.range[0];
const text = context.getSourceCode().text
.slice(start, end)
.replace(PADDING_LINE_SEQUENCE, replacerToRemovePaddingLines);
return fixer.replaceTextRange([start, end], text);
}
});
} | javascript | function verifyForNever(context, _, nextNode, paddingLines) {
if (paddingLines.length === 0) {
return;
}
context.report({
node: nextNode,
message: "Unexpected blank line before this statement.",
fix(fixer) {
if (paddingLines.length >= 2) {
return null;
}
const prevToken = paddingLines[0][0];
const nextToken = paddingLines[0][1];
const start = prevToken.range[1];
const end = nextToken.range[0];
const text = context.getSourceCode().text
.slice(start, end)
.replace(PADDING_LINE_SEQUENCE, replacerToRemovePaddingLines);
return fixer.replaceTextRange([start, end], text);
}
});
} | [
"function",
"verifyForNever",
"(",
"context",
",",
"_",
",",
"nextNode",
",",
"paddingLines",
")",
"{",
"if",
"(",
"paddingLines",
".",
"length",
"===",
"0",
")",
"{",
"return",
";",
"}",
"context",
".",
"report",
"(",
"{",
"node",
":",
"nextNode",
",",
"message",
":",
"\"Unexpected blank line before this statement.\"",
",",
"fix",
"(",
"fixer",
")",
"{",
"if",
"(",
"paddingLines",
".",
"length",
">=",
"2",
")",
"{",
"return",
"null",
";",
"}",
"const",
"prevToken",
"=",
"paddingLines",
"[",
"0",
"]",
"[",
"0",
"]",
";",
"const",
"nextToken",
"=",
"paddingLines",
"[",
"0",
"]",
"[",
"1",
"]",
";",
"const",
"start",
"=",
"prevToken",
".",
"range",
"[",
"1",
"]",
";",
"const",
"end",
"=",
"nextToken",
".",
"range",
"[",
"0",
"]",
";",
"const",
"text",
"=",
"context",
".",
"getSourceCode",
"(",
")",
".",
"text",
".",
"slice",
"(",
"start",
",",
"end",
")",
".",
"replace",
"(",
"PADDING_LINE_SEQUENCE",
",",
"replacerToRemovePaddingLines",
")",
";",
"return",
"fixer",
".",
"replaceTextRange",
"(",
"[",
"start",
",",
"end",
"]",
",",
"text",
")",
";",
"}",
"}",
")",
";",
"}"
] | Check and report statements for `never` configuration.
This autofix removes blank lines between the given 2 statements.
However, if comments exist between 2 blank lines, it does not remove those
blank lines automatically.
@param {RuleContext} context The rule context to report.
@param {ASTNode} _ Unused. The previous node to check.
@param {ASTNode} nextNode The next node to check.
@param {Array<Token[]>} paddingLines The array of token pairs that blank
lines exist between the pair.
@returns {void}
@private | [
"Check",
"and",
"report",
"statements",
"for",
"never",
"configuration",
".",
"This",
"autofix",
"removes",
"blank",
"lines",
"between",
"the",
"given",
"2",
"statements",
".",
"However",
"if",
"comments",
"exist",
"between",
"2",
"blank",
"lines",
"it",
"does",
"not",
"remove",
"those",
"blank",
"lines",
"automatically",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/padding-line-between-statements.js#L248-L272 |
3,178 | eslint/eslint | lib/rules/padding-line-between-statements.js | verifyForAlways | function verifyForAlways(context, prevNode, nextNode, paddingLines) {
if (paddingLines.length > 0) {
return;
}
context.report({
node: nextNode,
message: "Expected blank line before this statement.",
fix(fixer) {
const sourceCode = context.getSourceCode();
let prevToken = getActualLastToken(sourceCode, prevNode);
const nextToken = sourceCode.getFirstTokenBetween(
prevToken,
nextNode,
{
includeComments: true,
/**
* Skip the trailing comments of the previous node.
* This inserts a blank line after the last trailing comment.
*
* For example:
*
* foo(); // trailing comment.
* // comment.
* bar();
*
* Get fixed to:
*
* foo(); // trailing comment.
*
* // comment.
* bar();
*
* @param {Token} token The token to check.
* @returns {boolean} `true` if the token is not a trailing comment.
* @private
*/
filter(token) {
if (astUtils.isTokenOnSameLine(prevToken, token)) {
prevToken = token;
return false;
}
return true;
}
}
) || nextNode;
const insertText = astUtils.isTokenOnSameLine(prevToken, nextToken)
? "\n\n"
: "\n";
return fixer.insertTextAfter(prevToken, insertText);
}
});
} | javascript | function verifyForAlways(context, prevNode, nextNode, paddingLines) {
if (paddingLines.length > 0) {
return;
}
context.report({
node: nextNode,
message: "Expected blank line before this statement.",
fix(fixer) {
const sourceCode = context.getSourceCode();
let prevToken = getActualLastToken(sourceCode, prevNode);
const nextToken = sourceCode.getFirstTokenBetween(
prevToken,
nextNode,
{
includeComments: true,
/**
* Skip the trailing comments of the previous node.
* This inserts a blank line after the last trailing comment.
*
* For example:
*
* foo(); // trailing comment.
* // comment.
* bar();
*
* Get fixed to:
*
* foo(); // trailing comment.
*
* // comment.
* bar();
*
* @param {Token} token The token to check.
* @returns {boolean} `true` if the token is not a trailing comment.
* @private
*/
filter(token) {
if (astUtils.isTokenOnSameLine(prevToken, token)) {
prevToken = token;
return false;
}
return true;
}
}
) || nextNode;
const insertText = astUtils.isTokenOnSameLine(prevToken, nextToken)
? "\n\n"
: "\n";
return fixer.insertTextAfter(prevToken, insertText);
}
});
} | [
"function",
"verifyForAlways",
"(",
"context",
",",
"prevNode",
",",
"nextNode",
",",
"paddingLines",
")",
"{",
"if",
"(",
"paddingLines",
".",
"length",
">",
"0",
")",
"{",
"return",
";",
"}",
"context",
".",
"report",
"(",
"{",
"node",
":",
"nextNode",
",",
"message",
":",
"\"Expected blank line before this statement.\"",
",",
"fix",
"(",
"fixer",
")",
"{",
"const",
"sourceCode",
"=",
"context",
".",
"getSourceCode",
"(",
")",
";",
"let",
"prevToken",
"=",
"getActualLastToken",
"(",
"sourceCode",
",",
"prevNode",
")",
";",
"const",
"nextToken",
"=",
"sourceCode",
".",
"getFirstTokenBetween",
"(",
"prevToken",
",",
"nextNode",
",",
"{",
"includeComments",
":",
"true",
",",
"/**\n * Skip the trailing comments of the previous node.\n * This inserts a blank line after the last trailing comment.\n *\n * For example:\n *\n * foo(); // trailing comment.\n * // comment.\n * bar();\n *\n * Get fixed to:\n *\n * foo(); // trailing comment.\n *\n * // comment.\n * bar();\n *\n * @param {Token} token The token to check.\n * @returns {boolean} `true` if the token is not a trailing comment.\n * @private\n */",
"filter",
"(",
"token",
")",
"{",
"if",
"(",
"astUtils",
".",
"isTokenOnSameLine",
"(",
"prevToken",
",",
"token",
")",
")",
"{",
"prevToken",
"=",
"token",
";",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}",
"}",
")",
"||",
"nextNode",
";",
"const",
"insertText",
"=",
"astUtils",
".",
"isTokenOnSameLine",
"(",
"prevToken",
",",
"nextToken",
")",
"?",
"\"\\n\\n\"",
":",
"\"\\n\"",
";",
"return",
"fixer",
".",
"insertTextAfter",
"(",
"prevToken",
",",
"insertText",
")",
";",
"}",
"}",
")",
";",
"}"
] | Check and report statements for `always` configuration.
This autofix inserts a blank line between the given 2 statements.
If the `prevNode` has trailing comments, it inserts a blank line after the
trailing comments.
@param {RuleContext} context The rule context to report.
@param {ASTNode} prevNode The previous node to check.
@param {ASTNode} nextNode The next node to check.
@param {Array<Token[]>} paddingLines The array of token pairs that blank
lines exist between the pair.
@returns {void}
@private | [
"Check",
"and",
"report",
"statements",
"for",
"always",
"configuration",
".",
"This",
"autofix",
"inserts",
"a",
"blank",
"line",
"between",
"the",
"given",
"2",
"statements",
".",
"If",
"the",
"prevNode",
"has",
"trailing",
"comments",
"it",
"inserts",
"a",
"blank",
"line",
"after",
"the",
"trailing",
"comments",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/padding-line-between-statements.js#L288-L342 |
3,179 | eslint/eslint | lib/rules/padding-line-between-statements.js | match | function match(node, type) {
let innerStatementNode = node;
while (innerStatementNode.type === "LabeledStatement") {
innerStatementNode = innerStatementNode.body;
}
if (Array.isArray(type)) {
return type.some(match.bind(null, innerStatementNode));
}
return StatementTypes[type].test(innerStatementNode, sourceCode);
} | javascript | function match(node, type) {
let innerStatementNode = node;
while (innerStatementNode.type === "LabeledStatement") {
innerStatementNode = innerStatementNode.body;
}
if (Array.isArray(type)) {
return type.some(match.bind(null, innerStatementNode));
}
return StatementTypes[type].test(innerStatementNode, sourceCode);
} | [
"function",
"match",
"(",
"node",
",",
"type",
")",
"{",
"let",
"innerStatementNode",
"=",
"node",
";",
"while",
"(",
"innerStatementNode",
".",
"type",
"===",
"\"LabeledStatement\"",
")",
"{",
"innerStatementNode",
"=",
"innerStatementNode",
".",
"body",
";",
"}",
"if",
"(",
"Array",
".",
"isArray",
"(",
"type",
")",
")",
"{",
"return",
"type",
".",
"some",
"(",
"match",
".",
"bind",
"(",
"null",
",",
"innerStatementNode",
")",
")",
";",
"}",
"return",
"StatementTypes",
"[",
"type",
"]",
".",
"test",
"(",
"innerStatementNode",
",",
"sourceCode",
")",
";",
"}"
] | Checks whether the given node matches the given type.
@param {ASTNode} node The statement node to check.
@param {string|string[]} type The statement type to check.
@returns {boolean} `true` if the statement node matched the type.
@private | [
"Checks",
"whether",
"the",
"given",
"node",
"matches",
"the",
"given",
"type",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/padding-line-between-statements.js#L520-L530 |
3,180 | eslint/eslint | lib/rules/padding-line-between-statements.js | getPaddingType | function getPaddingType(prevNode, nextNode) {
for (let i = configureList.length - 1; i >= 0; --i) {
const configure = configureList[i];
const matched =
match(prevNode, configure.prev) &&
match(nextNode, configure.next);
if (matched) {
return PaddingTypes[configure.blankLine];
}
}
return PaddingTypes.any;
} | javascript | function getPaddingType(prevNode, nextNode) {
for (let i = configureList.length - 1; i >= 0; --i) {
const configure = configureList[i];
const matched =
match(prevNode, configure.prev) &&
match(nextNode, configure.next);
if (matched) {
return PaddingTypes[configure.blankLine];
}
}
return PaddingTypes.any;
} | [
"function",
"getPaddingType",
"(",
"prevNode",
",",
"nextNode",
")",
"{",
"for",
"(",
"let",
"i",
"=",
"configureList",
".",
"length",
"-",
"1",
";",
"i",
">=",
"0",
";",
"--",
"i",
")",
"{",
"const",
"configure",
"=",
"configureList",
"[",
"i",
"]",
";",
"const",
"matched",
"=",
"match",
"(",
"prevNode",
",",
"configure",
".",
"prev",
")",
"&&",
"match",
"(",
"nextNode",
",",
"configure",
".",
"next",
")",
";",
"if",
"(",
"matched",
")",
"{",
"return",
"PaddingTypes",
"[",
"configure",
".",
"blankLine",
"]",
";",
"}",
"}",
"return",
"PaddingTypes",
".",
"any",
";",
"}"
] | Finds the last matched configure from configureList.
@param {ASTNode} prevNode The previous statement to match.
@param {ASTNode} nextNode The current statement to match.
@returns {Object} The tester of the last matched configure.
@private | [
"Finds",
"the",
"last",
"matched",
"configure",
"from",
"configureList",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/padding-line-between-statements.js#L540-L552 |
3,181 | eslint/eslint | lib/rules/padding-line-between-statements.js | getPaddingLineSequences | function getPaddingLineSequences(prevNode, nextNode) {
const pairs = [];
let prevToken = getActualLastToken(sourceCode, prevNode);
if (nextNode.loc.start.line - prevToken.loc.end.line >= 2) {
do {
const token = sourceCode.getTokenAfter(
prevToken,
{ includeComments: true }
);
if (token.loc.start.line - prevToken.loc.end.line >= 2) {
pairs.push([prevToken, token]);
}
prevToken = token;
} while (prevToken.range[0] < nextNode.range[0]);
}
return pairs;
} | javascript | function getPaddingLineSequences(prevNode, nextNode) {
const pairs = [];
let prevToken = getActualLastToken(sourceCode, prevNode);
if (nextNode.loc.start.line - prevToken.loc.end.line >= 2) {
do {
const token = sourceCode.getTokenAfter(
prevToken,
{ includeComments: true }
);
if (token.loc.start.line - prevToken.loc.end.line >= 2) {
pairs.push([prevToken, token]);
}
prevToken = token;
} while (prevToken.range[0] < nextNode.range[0]);
}
return pairs;
} | [
"function",
"getPaddingLineSequences",
"(",
"prevNode",
",",
"nextNode",
")",
"{",
"const",
"pairs",
"=",
"[",
"]",
";",
"let",
"prevToken",
"=",
"getActualLastToken",
"(",
"sourceCode",
",",
"prevNode",
")",
";",
"if",
"(",
"nextNode",
".",
"loc",
".",
"start",
".",
"line",
"-",
"prevToken",
".",
"loc",
".",
"end",
".",
"line",
">=",
"2",
")",
"{",
"do",
"{",
"const",
"token",
"=",
"sourceCode",
".",
"getTokenAfter",
"(",
"prevToken",
",",
"{",
"includeComments",
":",
"true",
"}",
")",
";",
"if",
"(",
"token",
".",
"loc",
".",
"start",
".",
"line",
"-",
"prevToken",
".",
"loc",
".",
"end",
".",
"line",
">=",
"2",
")",
"{",
"pairs",
".",
"push",
"(",
"[",
"prevToken",
",",
"token",
"]",
")",
";",
"}",
"prevToken",
"=",
"token",
";",
"}",
"while",
"(",
"prevToken",
".",
"range",
"[",
"0",
"]",
"<",
"nextNode",
".",
"range",
"[",
"0",
"]",
")",
";",
"}",
"return",
"pairs",
";",
"}"
] | Gets padding line sequences between the given 2 statements.
Comments are separators of the padding line sequences.
@param {ASTNode} prevNode The previous statement to count.
@param {ASTNode} nextNode The current statement to count.
@returns {Array<Token[]>} The array of token pairs.
@private | [
"Gets",
"padding",
"line",
"sequences",
"between",
"the",
"given",
"2",
"statements",
".",
"Comments",
"are",
"separators",
"of",
"the",
"padding",
"line",
"sequences",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/padding-line-between-statements.js#L563-L583 |
3,182 | eslint/eslint | lib/rules/padding-line-between-statements.js | verify | function verify(node) {
const parentType = node.parent.type;
const validParent =
astUtils.STATEMENT_LIST_PARENTS.has(parentType) ||
parentType === "SwitchStatement";
if (!validParent) {
return;
}
// Save this node as the current previous statement.
const prevNode = scopeInfo.prevNode;
// Verify.
if (prevNode) {
const type = getPaddingType(prevNode, node);
const paddingLines = getPaddingLineSequences(prevNode, node);
type.verify(context, prevNode, node, paddingLines);
}
scopeInfo.prevNode = node;
} | javascript | function verify(node) {
const parentType = node.parent.type;
const validParent =
astUtils.STATEMENT_LIST_PARENTS.has(parentType) ||
parentType === "SwitchStatement";
if (!validParent) {
return;
}
// Save this node as the current previous statement.
const prevNode = scopeInfo.prevNode;
// Verify.
if (prevNode) {
const type = getPaddingType(prevNode, node);
const paddingLines = getPaddingLineSequences(prevNode, node);
type.verify(context, prevNode, node, paddingLines);
}
scopeInfo.prevNode = node;
} | [
"function",
"verify",
"(",
"node",
")",
"{",
"const",
"parentType",
"=",
"node",
".",
"parent",
".",
"type",
";",
"const",
"validParent",
"=",
"astUtils",
".",
"STATEMENT_LIST_PARENTS",
".",
"has",
"(",
"parentType",
")",
"||",
"parentType",
"===",
"\"SwitchStatement\"",
";",
"if",
"(",
"!",
"validParent",
")",
"{",
"return",
";",
"}",
"// Save this node as the current previous statement.",
"const",
"prevNode",
"=",
"scopeInfo",
".",
"prevNode",
";",
"// Verify.",
"if",
"(",
"prevNode",
")",
"{",
"const",
"type",
"=",
"getPaddingType",
"(",
"prevNode",
",",
"node",
")",
";",
"const",
"paddingLines",
"=",
"getPaddingLineSequences",
"(",
"prevNode",
",",
"node",
")",
";",
"type",
".",
"verify",
"(",
"context",
",",
"prevNode",
",",
"node",
",",
"paddingLines",
")",
";",
"}",
"scopeInfo",
".",
"prevNode",
"=",
"node",
";",
"}"
] | Verify padding lines between the given node and the previous node.
@param {ASTNode} node The node to verify.
@returns {void}
@private | [
"Verify",
"padding",
"lines",
"between",
"the",
"given",
"node",
"and",
"the",
"previous",
"node",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/padding-line-between-statements.js#L592-L614 |
3,183 | eslint/eslint | lib/rules/dot-location.js | checkDotLocation | function checkDotLocation(obj, prop, node) {
const dot = sourceCode.getTokenBefore(prop);
const textBeforeDot = sourceCode.getText().slice(obj.range[1], dot.range[0]);
const textAfterDot = sourceCode.getText().slice(dot.range[1], prop.range[0]);
if (dot.type === "Punctuator" && dot.value === ".") {
if (onObject) {
if (!astUtils.isTokenOnSameLine(obj, dot)) {
const neededTextAfterObj = astUtils.isDecimalInteger(obj) ? " " : "";
context.report({
node,
loc: dot.loc.start,
messageId: "expectedDotAfterObject",
fix: fixer => fixer.replaceTextRange([obj.range[1], prop.range[0]], `${neededTextAfterObj}.${textBeforeDot}${textAfterDot}`)
});
}
} else if (!astUtils.isTokenOnSameLine(dot, prop)) {
context.report({
node,
loc: dot.loc.start,
messageId: "expectedDotBeforeProperty",
fix: fixer => fixer.replaceTextRange([obj.range[1], prop.range[0]], `${textBeforeDot}${textAfterDot}.`)
});
}
}
} | javascript | function checkDotLocation(obj, prop, node) {
const dot = sourceCode.getTokenBefore(prop);
const textBeforeDot = sourceCode.getText().slice(obj.range[1], dot.range[0]);
const textAfterDot = sourceCode.getText().slice(dot.range[1], prop.range[0]);
if (dot.type === "Punctuator" && dot.value === ".") {
if (onObject) {
if (!astUtils.isTokenOnSameLine(obj, dot)) {
const neededTextAfterObj = astUtils.isDecimalInteger(obj) ? " " : "";
context.report({
node,
loc: dot.loc.start,
messageId: "expectedDotAfterObject",
fix: fixer => fixer.replaceTextRange([obj.range[1], prop.range[0]], `${neededTextAfterObj}.${textBeforeDot}${textAfterDot}`)
});
}
} else if (!astUtils.isTokenOnSameLine(dot, prop)) {
context.report({
node,
loc: dot.loc.start,
messageId: "expectedDotBeforeProperty",
fix: fixer => fixer.replaceTextRange([obj.range[1], prop.range[0]], `${textBeforeDot}${textAfterDot}.`)
});
}
}
} | [
"function",
"checkDotLocation",
"(",
"obj",
",",
"prop",
",",
"node",
")",
"{",
"const",
"dot",
"=",
"sourceCode",
".",
"getTokenBefore",
"(",
"prop",
")",
";",
"const",
"textBeforeDot",
"=",
"sourceCode",
".",
"getText",
"(",
")",
".",
"slice",
"(",
"obj",
".",
"range",
"[",
"1",
"]",
",",
"dot",
".",
"range",
"[",
"0",
"]",
")",
";",
"const",
"textAfterDot",
"=",
"sourceCode",
".",
"getText",
"(",
")",
".",
"slice",
"(",
"dot",
".",
"range",
"[",
"1",
"]",
",",
"prop",
".",
"range",
"[",
"0",
"]",
")",
";",
"if",
"(",
"dot",
".",
"type",
"===",
"\"Punctuator\"",
"&&",
"dot",
".",
"value",
"===",
"\".\"",
")",
"{",
"if",
"(",
"onObject",
")",
"{",
"if",
"(",
"!",
"astUtils",
".",
"isTokenOnSameLine",
"(",
"obj",
",",
"dot",
")",
")",
"{",
"const",
"neededTextAfterObj",
"=",
"astUtils",
".",
"isDecimalInteger",
"(",
"obj",
")",
"?",
"\" \"",
":",
"\"\"",
";",
"context",
".",
"report",
"(",
"{",
"node",
",",
"loc",
":",
"dot",
".",
"loc",
".",
"start",
",",
"messageId",
":",
"\"expectedDotAfterObject\"",
",",
"fix",
":",
"fixer",
"=>",
"fixer",
".",
"replaceTextRange",
"(",
"[",
"obj",
".",
"range",
"[",
"1",
"]",
",",
"prop",
".",
"range",
"[",
"0",
"]",
"]",
",",
"`",
"${",
"neededTextAfterObj",
"}",
"${",
"textBeforeDot",
"}",
"${",
"textAfterDot",
"}",
"`",
")",
"}",
")",
";",
"}",
"}",
"else",
"if",
"(",
"!",
"astUtils",
".",
"isTokenOnSameLine",
"(",
"dot",
",",
"prop",
")",
")",
"{",
"context",
".",
"report",
"(",
"{",
"node",
",",
"loc",
":",
"dot",
".",
"loc",
".",
"start",
",",
"messageId",
":",
"\"expectedDotBeforeProperty\"",
",",
"fix",
":",
"fixer",
"=>",
"fixer",
".",
"replaceTextRange",
"(",
"[",
"obj",
".",
"range",
"[",
"1",
"]",
",",
"prop",
".",
"range",
"[",
"0",
"]",
"]",
",",
"`",
"${",
"textBeforeDot",
"}",
"${",
"textAfterDot",
"}",
"`",
")",
"}",
")",
";",
"}",
"}",
"}"
] | Reports if the dot between object and property is on the correct loccation.
@param {ASTNode} obj The object owning the property.
@param {ASTNode} prop The property of the object.
@param {ASTNode} node The corresponding node of the token.
@returns {void} | [
"Reports",
"if",
"the",
"dot",
"between",
"object",
"and",
"property",
"is",
"on",
"the",
"correct",
"loccation",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/dot-location.js#L55-L81 |
3,184 | eslint/eslint | lib/rules/nonblock-statement-body-position.js | validateStatement | function validateStatement(node, keywordName) {
const option = getOption(keywordName);
if (node.type === "BlockStatement" || option === "any") {
return;
}
const tokenBefore = sourceCode.getTokenBefore(node);
if (tokenBefore.loc.end.line === node.loc.start.line && option === "below") {
context.report({
node,
message: "Expected a linebreak before this statement.",
fix: fixer => fixer.insertTextBefore(node, "\n")
});
} else if (tokenBefore.loc.end.line !== node.loc.start.line && option === "beside") {
context.report({
node,
message: "Expected no linebreak before this statement.",
fix(fixer) {
if (sourceCode.getText().slice(tokenBefore.range[1], node.range[0]).trim()) {
return null;
}
return fixer.replaceTextRange([tokenBefore.range[1], node.range[0]], " ");
}
});
}
} | javascript | function validateStatement(node, keywordName) {
const option = getOption(keywordName);
if (node.type === "BlockStatement" || option === "any") {
return;
}
const tokenBefore = sourceCode.getTokenBefore(node);
if (tokenBefore.loc.end.line === node.loc.start.line && option === "below") {
context.report({
node,
message: "Expected a linebreak before this statement.",
fix: fixer => fixer.insertTextBefore(node, "\n")
});
} else if (tokenBefore.loc.end.line !== node.loc.start.line && option === "beside") {
context.report({
node,
message: "Expected no linebreak before this statement.",
fix(fixer) {
if (sourceCode.getText().slice(tokenBefore.range[1], node.range[0]).trim()) {
return null;
}
return fixer.replaceTextRange([tokenBefore.range[1], node.range[0]], " ");
}
});
}
} | [
"function",
"validateStatement",
"(",
"node",
",",
"keywordName",
")",
"{",
"const",
"option",
"=",
"getOption",
"(",
"keywordName",
")",
";",
"if",
"(",
"node",
".",
"type",
"===",
"\"BlockStatement\"",
"||",
"option",
"===",
"\"any\"",
")",
"{",
"return",
";",
"}",
"const",
"tokenBefore",
"=",
"sourceCode",
".",
"getTokenBefore",
"(",
"node",
")",
";",
"if",
"(",
"tokenBefore",
".",
"loc",
".",
"end",
".",
"line",
"===",
"node",
".",
"loc",
".",
"start",
".",
"line",
"&&",
"option",
"===",
"\"below\"",
")",
"{",
"context",
".",
"report",
"(",
"{",
"node",
",",
"message",
":",
"\"Expected a linebreak before this statement.\"",
",",
"fix",
":",
"fixer",
"=>",
"fixer",
".",
"insertTextBefore",
"(",
"node",
",",
"\"\\n\"",
")",
"}",
")",
";",
"}",
"else",
"if",
"(",
"tokenBefore",
".",
"loc",
".",
"end",
".",
"line",
"!==",
"node",
".",
"loc",
".",
"start",
".",
"line",
"&&",
"option",
"===",
"\"beside\"",
")",
"{",
"context",
".",
"report",
"(",
"{",
"node",
",",
"message",
":",
"\"Expected no linebreak before this statement.\"",
",",
"fix",
"(",
"fixer",
")",
"{",
"if",
"(",
"sourceCode",
".",
"getText",
"(",
")",
".",
"slice",
"(",
"tokenBefore",
".",
"range",
"[",
"1",
"]",
",",
"node",
".",
"range",
"[",
"0",
"]",
")",
".",
"trim",
"(",
")",
")",
"{",
"return",
"null",
";",
"}",
"return",
"fixer",
".",
"replaceTextRange",
"(",
"[",
"tokenBefore",
".",
"range",
"[",
"1",
"]",
",",
"node",
".",
"range",
"[",
"0",
"]",
"]",
",",
"\" \"",
")",
";",
"}",
"}",
")",
";",
"}",
"}"
] | Validates the location of a single-line statement
@param {ASTNode} node The single-line statement
@param {string} keywordName The applicable keyword name for the single-line statement
@returns {void} | [
"Validates",
"the",
"location",
"of",
"a",
"single",
"-",
"line",
"statement"
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/nonblock-statement-body-position.js#L70-L97 |
3,185 | eslint/eslint | lib/util/source-code-fixer.js | compareMessagesByFixRange | function compareMessagesByFixRange(a, b) {
return a.fix.range[0] - b.fix.range[0] || a.fix.range[1] - b.fix.range[1];
} | javascript | function compareMessagesByFixRange(a, b) {
return a.fix.range[0] - b.fix.range[0] || a.fix.range[1] - b.fix.range[1];
} | [
"function",
"compareMessagesByFixRange",
"(",
"a",
",",
"b",
")",
"{",
"return",
"a",
".",
"fix",
".",
"range",
"[",
"0",
"]",
"-",
"b",
".",
"fix",
".",
"range",
"[",
"0",
"]",
"||",
"a",
".",
"fix",
".",
"range",
"[",
"1",
"]",
"-",
"b",
".",
"fix",
".",
"range",
"[",
"1",
"]",
";",
"}"
] | Compares items in a messages array by range.
@param {Message} a The first message.
@param {Message} b The second message.
@returns {int} -1 if a comes before b, 1 if a comes after b, 0 if equal.
@private | [
"Compares",
"items",
"in",
"a",
"messages",
"array",
"by",
"range",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/util/source-code-fixer.js#L26-L28 |
3,186 | eslint/eslint | lib/util/source-code-fixer.js | attemptFix | function attemptFix(problem) {
const fix = problem.fix;
const start = fix.range[0];
const end = fix.range[1];
// Remain it as a problem if it's overlapped or it's a negative range
if (lastPos >= start || start > end) {
remainingMessages.push(problem);
return false;
}
// Remove BOM.
if ((start < 0 && end >= 0) || (start === 0 && fix.text.startsWith(BOM))) {
output = "";
}
// Make output to this fix.
output += text.slice(Math.max(0, lastPos), Math.max(0, start));
output += fix.text;
lastPos = end;
return true;
} | javascript | function attemptFix(problem) {
const fix = problem.fix;
const start = fix.range[0];
const end = fix.range[1];
// Remain it as a problem if it's overlapped or it's a negative range
if (lastPos >= start || start > end) {
remainingMessages.push(problem);
return false;
}
// Remove BOM.
if ((start < 0 && end >= 0) || (start === 0 && fix.text.startsWith(BOM))) {
output = "";
}
// Make output to this fix.
output += text.slice(Math.max(0, lastPos), Math.max(0, start));
output += fix.text;
lastPos = end;
return true;
} | [
"function",
"attemptFix",
"(",
"problem",
")",
"{",
"const",
"fix",
"=",
"problem",
".",
"fix",
";",
"const",
"start",
"=",
"fix",
".",
"range",
"[",
"0",
"]",
";",
"const",
"end",
"=",
"fix",
".",
"range",
"[",
"1",
"]",
";",
"// Remain it as a problem if it's overlapped or it's a negative range",
"if",
"(",
"lastPos",
">=",
"start",
"||",
"start",
">",
"end",
")",
"{",
"remainingMessages",
".",
"push",
"(",
"problem",
")",
";",
"return",
"false",
";",
"}",
"// Remove BOM.",
"if",
"(",
"(",
"start",
"<",
"0",
"&&",
"end",
">=",
"0",
")",
"||",
"(",
"start",
"===",
"0",
"&&",
"fix",
".",
"text",
".",
"startsWith",
"(",
"BOM",
")",
")",
")",
"{",
"output",
"=",
"\"\"",
";",
"}",
"// Make output to this fix.",
"output",
"+=",
"text",
".",
"slice",
"(",
"Math",
".",
"max",
"(",
"0",
",",
"lastPos",
")",
",",
"Math",
".",
"max",
"(",
"0",
",",
"start",
")",
")",
";",
"output",
"+=",
"fix",
".",
"text",
";",
"lastPos",
"=",
"end",
";",
"return",
"true",
";",
"}"
] | Try to use the 'fix' from a problem.
@param {Message} problem The message object to apply fixes from
@returns {boolean} Whether fix was successfully applied | [
"Try",
"to",
"use",
"the",
"fix",
"from",
"a",
"problem",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/util/source-code-fixer.js#L86-L107 |
3,187 | eslint/eslint | lib/util/source-code.js | looksLikeExport | function looksLikeExport(astNode) {
return astNode.type === "ExportDefaultDeclaration" || astNode.type === "ExportNamedDeclaration" ||
astNode.type === "ExportAllDeclaration" || astNode.type === "ExportSpecifier";
} | javascript | function looksLikeExport(astNode) {
return astNode.type === "ExportDefaultDeclaration" || astNode.type === "ExportNamedDeclaration" ||
astNode.type === "ExportAllDeclaration" || astNode.type === "ExportSpecifier";
} | [
"function",
"looksLikeExport",
"(",
"astNode",
")",
"{",
"return",
"astNode",
".",
"type",
"===",
"\"ExportDefaultDeclaration\"",
"||",
"astNode",
".",
"type",
"===",
"\"ExportNamedDeclaration\"",
"||",
"astNode",
".",
"type",
"===",
"\"ExportAllDeclaration\"",
"||",
"astNode",
".",
"type",
"===",
"\"ExportSpecifier\"",
";",
"}"
] | Check to see if its a ES6 export declaration.
@param {ASTNode} astNode An AST node.
@returns {boolean} whether the given node represents an export declaration.
@private | [
"Check",
"to",
"see",
"if",
"its",
"a",
"ES6",
"export",
"declaration",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/util/source-code.js#L51-L54 |
3,188 | eslint/eslint | lib/rules/no-trailing-spaces.js | getCommentLineNumbers | function getCommentLineNumbers(comments) {
const lines = new Set();
comments.forEach(comment => {
for (let i = comment.loc.start.line; i <= comment.loc.end.line; i++) {
lines.add(i);
}
});
return lines;
} | javascript | function getCommentLineNumbers(comments) {
const lines = new Set();
comments.forEach(comment => {
for (let i = comment.loc.start.line; i <= comment.loc.end.line; i++) {
lines.add(i);
}
});
return lines;
} | [
"function",
"getCommentLineNumbers",
"(",
"comments",
")",
"{",
"const",
"lines",
"=",
"new",
"Set",
"(",
")",
";",
"comments",
".",
"forEach",
"(",
"comment",
"=>",
"{",
"for",
"(",
"let",
"i",
"=",
"comment",
".",
"loc",
".",
"start",
".",
"line",
";",
"i",
"<=",
"comment",
".",
"loc",
".",
"end",
".",
"line",
";",
"i",
"++",
")",
"{",
"lines",
".",
"add",
"(",
"i",
")",
";",
"}",
"}",
")",
";",
"return",
"lines",
";",
"}"
] | Given a list of comment nodes, return the line numbers for those comments.
@param {Array} comments An array of comment nodes.
@returns {number[]} An array of line numbers containing comments. | [
"Given",
"a",
"list",
"of",
"comment",
"nodes",
"return",
"the",
"line",
"numbers",
"for",
"those",
"comments",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-trailing-spaces.js#L89-L99 |
3,189 | eslint/eslint | lib/rules/no-use-before-define.js | isOuterVariable | function isOuterVariable(variable, reference) {
return (
variable.defs[0].type === "Variable" &&
variable.scope.variableScope !== reference.from.variableScope
);
} | javascript | function isOuterVariable(variable, reference) {
return (
variable.defs[0].type === "Variable" &&
variable.scope.variableScope !== reference.from.variableScope
);
} | [
"function",
"isOuterVariable",
"(",
"variable",
",",
"reference",
")",
"{",
"return",
"(",
"variable",
".",
"defs",
"[",
"0",
"]",
".",
"type",
"===",
"\"Variable\"",
"&&",
"variable",
".",
"scope",
".",
"variableScope",
"!==",
"reference",
".",
"from",
".",
"variableScope",
")",
";",
"}"
] | Checks whether or not a given variable is a variable declaration in an upper function scope.
@param {eslint-scope.Variable} variable - A variable to check.
@param {eslint-scope.Reference} reference - A reference to check.
@returns {boolean} `true` if the variable is a variable declaration. | [
"Checks",
"whether",
"or",
"not",
"a",
"given",
"variable",
"is",
"a",
"variable",
"declaration",
"in",
"an",
"upper",
"function",
"scope",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-use-before-define.js#L67-L72 |
3,190 | eslint/eslint | lib/rules/no-use-before-define.js | isInRange | function isInRange(node, location) {
return node && node.range[0] <= location && location <= node.range[1];
} | javascript | function isInRange(node, location) {
return node && node.range[0] <= location && location <= node.range[1];
} | [
"function",
"isInRange",
"(",
"node",
",",
"location",
")",
"{",
"return",
"node",
"&&",
"node",
".",
"range",
"[",
"0",
"]",
"<=",
"location",
"&&",
"location",
"<=",
"node",
".",
"range",
"[",
"1",
"]",
";",
"}"
] | Checks whether or not a given location is inside of the range of a given node.
@param {ASTNode} node - An node to check.
@param {number} location - A location to check.
@returns {boolean} `true` if the location is inside of the range of the node. | [
"Checks",
"whether",
"or",
"not",
"a",
"given",
"location",
"is",
"inside",
"of",
"the",
"range",
"of",
"a",
"given",
"node",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-use-before-define.js#L81-L83 |
3,191 | eslint/eslint | lib/rules/no-use-before-define.js | isInInitializer | function isInInitializer(variable, reference) {
if (variable.scope !== reference.from) {
return false;
}
let node = variable.identifiers[0].parent;
const location = reference.identifier.range[1];
while (node) {
if (node.type === "VariableDeclarator") {
if (isInRange(node.init, location)) {
return true;
}
if (FOR_IN_OF_TYPE.test(node.parent.parent.type) &&
isInRange(node.parent.parent.right, location)
) {
return true;
}
break;
} else if (node.type === "AssignmentPattern") {
if (isInRange(node.right, location)) {
return true;
}
} else if (SENTINEL_TYPE.test(node.type)) {
break;
}
node = node.parent;
}
return false;
} | javascript | function isInInitializer(variable, reference) {
if (variable.scope !== reference.from) {
return false;
}
let node = variable.identifiers[0].parent;
const location = reference.identifier.range[1];
while (node) {
if (node.type === "VariableDeclarator") {
if (isInRange(node.init, location)) {
return true;
}
if (FOR_IN_OF_TYPE.test(node.parent.parent.type) &&
isInRange(node.parent.parent.right, location)
) {
return true;
}
break;
} else if (node.type === "AssignmentPattern") {
if (isInRange(node.right, location)) {
return true;
}
} else if (SENTINEL_TYPE.test(node.type)) {
break;
}
node = node.parent;
}
return false;
} | [
"function",
"isInInitializer",
"(",
"variable",
",",
"reference",
")",
"{",
"if",
"(",
"variable",
".",
"scope",
"!==",
"reference",
".",
"from",
")",
"{",
"return",
"false",
";",
"}",
"let",
"node",
"=",
"variable",
".",
"identifiers",
"[",
"0",
"]",
".",
"parent",
";",
"const",
"location",
"=",
"reference",
".",
"identifier",
".",
"range",
"[",
"1",
"]",
";",
"while",
"(",
"node",
")",
"{",
"if",
"(",
"node",
".",
"type",
"===",
"\"VariableDeclarator\"",
")",
"{",
"if",
"(",
"isInRange",
"(",
"node",
".",
"init",
",",
"location",
")",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"FOR_IN_OF_TYPE",
".",
"test",
"(",
"node",
".",
"parent",
".",
"parent",
".",
"type",
")",
"&&",
"isInRange",
"(",
"node",
".",
"parent",
".",
"parent",
".",
"right",
",",
"location",
")",
")",
"{",
"return",
"true",
";",
"}",
"break",
";",
"}",
"else",
"if",
"(",
"node",
".",
"type",
"===",
"\"AssignmentPattern\"",
")",
"{",
"if",
"(",
"isInRange",
"(",
"node",
".",
"right",
",",
"location",
")",
")",
"{",
"return",
"true",
";",
"}",
"}",
"else",
"if",
"(",
"SENTINEL_TYPE",
".",
"test",
"(",
"node",
".",
"type",
")",
")",
"{",
"break",
";",
"}",
"node",
"=",
"node",
".",
"parent",
";",
"}",
"return",
"false",
";",
"}"
] | Checks whether or not a given reference is inside of the initializers of a given variable.
This returns `true` in the following cases:
var a = a
var [a = a] = list
var {a = a} = obj
for (var a in a) {}
for (var a of a) {}
@param {Variable} variable - A variable to check.
@param {Reference} reference - A reference to check.
@returns {boolean} `true` if the reference is inside of the initializers. | [
"Checks",
"whether",
"or",
"not",
"a",
"given",
"reference",
"is",
"inside",
"of",
"the",
"initializers",
"of",
"a",
"given",
"variable",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-use-before-define.js#L100-L131 |
3,192 | eslint/eslint | lib/rules/no-use-before-define.js | findVariablesInScope | function findVariablesInScope(scope) {
scope.references.forEach(reference => {
const variable = reference.resolved;
/*
* Skips when the reference is:
* - initialization's.
* - referring to an undefined variable.
* - referring to a global environment variable (there're no identifiers).
* - located preceded by the variable (except in initializers).
* - allowed by options.
*/
if (reference.init ||
!variable ||
variable.identifiers.length === 0 ||
(variable.identifiers[0].range[1] < reference.identifier.range[1] && !isInInitializer(variable, reference)) ||
!isForbidden(variable, reference)
) {
return;
}
// Reports.
context.report({
node: reference.identifier,
message: "'{{name}}' was used before it was defined.",
data: reference.identifier
});
});
scope.childScopes.forEach(findVariablesInScope);
} | javascript | function findVariablesInScope(scope) {
scope.references.forEach(reference => {
const variable = reference.resolved;
/*
* Skips when the reference is:
* - initialization's.
* - referring to an undefined variable.
* - referring to a global environment variable (there're no identifiers).
* - located preceded by the variable (except in initializers).
* - allowed by options.
*/
if (reference.init ||
!variable ||
variable.identifiers.length === 0 ||
(variable.identifiers[0].range[1] < reference.identifier.range[1] && !isInInitializer(variable, reference)) ||
!isForbidden(variable, reference)
) {
return;
}
// Reports.
context.report({
node: reference.identifier,
message: "'{{name}}' was used before it was defined.",
data: reference.identifier
});
});
scope.childScopes.forEach(findVariablesInScope);
} | [
"function",
"findVariablesInScope",
"(",
"scope",
")",
"{",
"scope",
".",
"references",
".",
"forEach",
"(",
"reference",
"=>",
"{",
"const",
"variable",
"=",
"reference",
".",
"resolved",
";",
"/*\n * Skips when the reference is:\n * - initialization's.\n * - referring to an undefined variable.\n * - referring to a global environment variable (there're no identifiers).\n * - located preceded by the variable (except in initializers).\n * - allowed by options.\n */",
"if",
"(",
"reference",
".",
"init",
"||",
"!",
"variable",
"||",
"variable",
".",
"identifiers",
".",
"length",
"===",
"0",
"||",
"(",
"variable",
".",
"identifiers",
"[",
"0",
"]",
".",
"range",
"[",
"1",
"]",
"<",
"reference",
".",
"identifier",
".",
"range",
"[",
"1",
"]",
"&&",
"!",
"isInInitializer",
"(",
"variable",
",",
"reference",
")",
")",
"||",
"!",
"isForbidden",
"(",
"variable",
",",
"reference",
")",
")",
"{",
"return",
";",
"}",
"// Reports.",
"context",
".",
"report",
"(",
"{",
"node",
":",
"reference",
".",
"identifier",
",",
"message",
":",
"\"'{{name}}' was used before it was defined.\"",
",",
"data",
":",
"reference",
".",
"identifier",
"}",
")",
";",
"}",
")",
";",
"scope",
".",
"childScopes",
".",
"forEach",
"(",
"findVariablesInScope",
")",
";",
"}"
] | Finds and validates all variables in a given scope.
@param {Scope} scope The scope object.
@returns {void}
@private | [
"Finds",
"and",
"validates",
"all",
"variables",
"in",
"a",
"given",
"scope",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-use-before-define.js#L196-L226 |
3,193 | eslint/eslint | lib/rules/semi-style.js | isLastChild | function isLastChild(node) {
const t = node.parent.type;
if (t === "IfStatement" && node.parent.consequent === node && node.parent.alternate) { // before `else` keyword.
return true;
}
if (t === "DoWhileStatement") { // before `while` keyword.
return true;
}
const nodeList = getChildren(node.parent);
return nodeList !== null && nodeList[nodeList.length - 1] === node; // before `}` or etc.
} | javascript | function isLastChild(node) {
const t = node.parent.type;
if (t === "IfStatement" && node.parent.consequent === node && node.parent.alternate) { // before `else` keyword.
return true;
}
if (t === "DoWhileStatement") { // before `while` keyword.
return true;
}
const nodeList = getChildren(node.parent);
return nodeList !== null && nodeList[nodeList.length - 1] === node; // before `}` or etc.
} | [
"function",
"isLastChild",
"(",
"node",
")",
"{",
"const",
"t",
"=",
"node",
".",
"parent",
".",
"type",
";",
"if",
"(",
"t",
"===",
"\"IfStatement\"",
"&&",
"node",
".",
"parent",
".",
"consequent",
"===",
"node",
"&&",
"node",
".",
"parent",
".",
"alternate",
")",
"{",
"// before `else` keyword.",
"return",
"true",
";",
"}",
"if",
"(",
"t",
"===",
"\"DoWhileStatement\"",
")",
"{",
"// before `while` keyword.",
"return",
"true",
";",
"}",
"const",
"nodeList",
"=",
"getChildren",
"(",
"node",
".",
"parent",
")",
";",
"return",
"nodeList",
"!==",
"null",
"&&",
"nodeList",
"[",
"nodeList",
".",
"length",
"-",
"1",
"]",
"===",
"node",
";",
"// before `}` or etc.",
"}"
] | Check whether a given node is the last statement in the parent block.
@param {Node} node A node to check.
@returns {boolean} `true` if the node is the last statement in the parent block. | [
"Check",
"whether",
"a",
"given",
"node",
"is",
"the",
"last",
"statement",
"in",
"the",
"parent",
"block",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/semi-style.js#L52-L64 |
3,194 | eslint/eslint | lib/rules/semi-style.js | check | function check(semiToken, expected) {
const prevToken = sourceCode.getTokenBefore(semiToken);
const nextToken = sourceCode.getTokenAfter(semiToken);
const prevIsSameLine = !prevToken || astUtils.isTokenOnSameLine(prevToken, semiToken);
const nextIsSameLine = !nextToken || astUtils.isTokenOnSameLine(semiToken, nextToken);
if ((expected === "last" && !prevIsSameLine) || (expected === "first" && !nextIsSameLine)) {
context.report({
loc: semiToken.loc,
message: "Expected this semicolon to be at {{pos}}.",
data: {
pos: (expected === "last")
? "the end of the previous line"
: "the beginning of the next line"
},
fix(fixer) {
if (prevToken && nextToken && sourceCode.commentsExistBetween(prevToken, nextToken)) {
return null;
}
const start = prevToken ? prevToken.range[1] : semiToken.range[0];
const end = nextToken ? nextToken.range[0] : semiToken.range[1];
const text = (expected === "last") ? ";\n" : "\n;";
return fixer.replaceTextRange([start, end], text);
}
});
}
} | javascript | function check(semiToken, expected) {
const prevToken = sourceCode.getTokenBefore(semiToken);
const nextToken = sourceCode.getTokenAfter(semiToken);
const prevIsSameLine = !prevToken || astUtils.isTokenOnSameLine(prevToken, semiToken);
const nextIsSameLine = !nextToken || astUtils.isTokenOnSameLine(semiToken, nextToken);
if ((expected === "last" && !prevIsSameLine) || (expected === "first" && !nextIsSameLine)) {
context.report({
loc: semiToken.loc,
message: "Expected this semicolon to be at {{pos}}.",
data: {
pos: (expected === "last")
? "the end of the previous line"
: "the beginning of the next line"
},
fix(fixer) {
if (prevToken && nextToken && sourceCode.commentsExistBetween(prevToken, nextToken)) {
return null;
}
const start = prevToken ? prevToken.range[1] : semiToken.range[0];
const end = nextToken ? nextToken.range[0] : semiToken.range[1];
const text = (expected === "last") ? ";\n" : "\n;";
return fixer.replaceTextRange([start, end], text);
}
});
}
} | [
"function",
"check",
"(",
"semiToken",
",",
"expected",
")",
"{",
"const",
"prevToken",
"=",
"sourceCode",
".",
"getTokenBefore",
"(",
"semiToken",
")",
";",
"const",
"nextToken",
"=",
"sourceCode",
".",
"getTokenAfter",
"(",
"semiToken",
")",
";",
"const",
"prevIsSameLine",
"=",
"!",
"prevToken",
"||",
"astUtils",
".",
"isTokenOnSameLine",
"(",
"prevToken",
",",
"semiToken",
")",
";",
"const",
"nextIsSameLine",
"=",
"!",
"nextToken",
"||",
"astUtils",
".",
"isTokenOnSameLine",
"(",
"semiToken",
",",
"nextToken",
")",
";",
"if",
"(",
"(",
"expected",
"===",
"\"last\"",
"&&",
"!",
"prevIsSameLine",
")",
"||",
"(",
"expected",
"===",
"\"first\"",
"&&",
"!",
"nextIsSameLine",
")",
")",
"{",
"context",
".",
"report",
"(",
"{",
"loc",
":",
"semiToken",
".",
"loc",
",",
"message",
":",
"\"Expected this semicolon to be at {{pos}}.\"",
",",
"data",
":",
"{",
"pos",
":",
"(",
"expected",
"===",
"\"last\"",
")",
"?",
"\"the end of the previous line\"",
":",
"\"the beginning of the next line\"",
"}",
",",
"fix",
"(",
"fixer",
")",
"{",
"if",
"(",
"prevToken",
"&&",
"nextToken",
"&&",
"sourceCode",
".",
"commentsExistBetween",
"(",
"prevToken",
",",
"nextToken",
")",
")",
"{",
"return",
"null",
";",
"}",
"const",
"start",
"=",
"prevToken",
"?",
"prevToken",
".",
"range",
"[",
"1",
"]",
":",
"semiToken",
".",
"range",
"[",
"0",
"]",
";",
"const",
"end",
"=",
"nextToken",
"?",
"nextToken",
".",
"range",
"[",
"0",
"]",
":",
"semiToken",
".",
"range",
"[",
"1",
"]",
";",
"const",
"text",
"=",
"(",
"expected",
"===",
"\"last\"",
")",
"?",
"\";\\n\"",
":",
"\"\\n;\"",
";",
"return",
"fixer",
".",
"replaceTextRange",
"(",
"[",
"start",
",",
"end",
"]",
",",
"text",
")",
";",
"}",
"}",
")",
";",
"}",
"}"
] | Check the given semicolon token.
@param {Token} semiToken The semicolon token to check.
@param {"first"|"last"} expected The expected location to check.
@returns {void} | [
"Check",
"the",
"given",
"semicolon",
"token",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/semi-style.js#L91-L119 |
3,195 | eslint/eslint | lib/rules/no-extra-parens.js | ruleApplies | function ruleApplies(node) {
if (node.type === "JSXElement" || node.type === "JSXFragment") {
const isSingleLine = node.loc.start.line === node.loc.end.line;
switch (IGNORE_JSX) {
// Exclude this JSX element from linting
case "all":
return false;
// Exclude this JSX element if it is multi-line element
case "multi-line":
return isSingleLine;
// Exclude this JSX element if it is single-line element
case "single-line":
return !isSingleLine;
// Nothing special to be done for JSX elements
case "none":
break;
// no default
}
}
return ALL_NODES || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression";
} | javascript | function ruleApplies(node) {
if (node.type === "JSXElement" || node.type === "JSXFragment") {
const isSingleLine = node.loc.start.line === node.loc.end.line;
switch (IGNORE_JSX) {
// Exclude this JSX element from linting
case "all":
return false;
// Exclude this JSX element if it is multi-line element
case "multi-line":
return isSingleLine;
// Exclude this JSX element if it is single-line element
case "single-line":
return !isSingleLine;
// Nothing special to be done for JSX elements
case "none":
break;
// no default
}
}
return ALL_NODES || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression";
} | [
"function",
"ruleApplies",
"(",
"node",
")",
"{",
"if",
"(",
"node",
".",
"type",
"===",
"\"JSXElement\"",
"||",
"node",
".",
"type",
"===",
"\"JSXFragment\"",
")",
"{",
"const",
"isSingleLine",
"=",
"node",
".",
"loc",
".",
"start",
".",
"line",
"===",
"node",
".",
"loc",
".",
"end",
".",
"line",
";",
"switch",
"(",
"IGNORE_JSX",
")",
"{",
"// Exclude this JSX element from linting",
"case",
"\"all\"",
":",
"return",
"false",
";",
"// Exclude this JSX element if it is multi-line element",
"case",
"\"multi-line\"",
":",
"return",
"isSingleLine",
";",
"// Exclude this JSX element if it is single-line element",
"case",
"\"single-line\"",
":",
"return",
"!",
"isSingleLine",
";",
"// Nothing special to be done for JSX elements",
"case",
"\"none\"",
":",
"break",
";",
"// no default",
"}",
"}",
"return",
"ALL_NODES",
"||",
"node",
".",
"type",
"===",
"\"FunctionExpression\"",
"||",
"node",
".",
"type",
"===",
"\"ArrowFunctionExpression\"",
";",
"}"
] | Determines if this rule should be enforced for a node given the current configuration.
@param {ASTNode} node - The node to be checked.
@returns {boolean} True if the rule should be enforced for this node.
@private | [
"Determines",
"if",
"this",
"rule",
"should",
"be",
"enforced",
"for",
"a",
"node",
"given",
"the",
"current",
"configuration",
"."
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-extra-parens.js#L90-L117 |
3,196 | eslint/eslint | lib/rules/no-extra-parens.js | isNewExpressionWithParens | function isNewExpressionWithParens(newExpression) {
const lastToken = sourceCode.getLastToken(newExpression);
const penultimateToken = sourceCode.getTokenBefore(lastToken);
return newExpression.arguments.length > 0 || astUtils.isOpeningParenToken(penultimateToken) && astUtils.isClosingParenToken(lastToken);
} | javascript | function isNewExpressionWithParens(newExpression) {
const lastToken = sourceCode.getLastToken(newExpression);
const penultimateToken = sourceCode.getTokenBefore(lastToken);
return newExpression.arguments.length > 0 || astUtils.isOpeningParenToken(penultimateToken) && astUtils.isClosingParenToken(lastToken);
} | [
"function",
"isNewExpressionWithParens",
"(",
"newExpression",
")",
"{",
"const",
"lastToken",
"=",
"sourceCode",
".",
"getLastToken",
"(",
"newExpression",
")",
";",
"const",
"penultimateToken",
"=",
"sourceCode",
".",
"getTokenBefore",
"(",
"lastToken",
")",
";",
"return",
"newExpression",
".",
"arguments",
".",
"length",
">",
"0",
"||",
"astUtils",
".",
"isOpeningParenToken",
"(",
"penultimateToken",
")",
"&&",
"astUtils",
".",
"isClosingParenToken",
"(",
"lastToken",
")",
";",
"}"
] | Determines if a constructor function is newed-up with parens
@param {ASTNode} newExpression - The NewExpression node to be checked.
@returns {boolean} True if the constructor is called with parens.
@private | [
"Determines",
"if",
"a",
"constructor",
"function",
"is",
"newed",
"-",
"up",
"with",
"parens"
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-extra-parens.js#L190-L195 |
3,197 | eslint/eslint | lib/rules/no-extra-parens.js | requiresLeadingSpace | function requiresLeadingSpace(node) {
const leftParenToken = sourceCode.getTokenBefore(node);
const tokenBeforeLeftParen = sourceCode.getTokenBefore(node, 1);
const firstToken = sourceCode.getFirstToken(node);
return tokenBeforeLeftParen &&
tokenBeforeLeftParen.range[1] === leftParenToken.range[0] &&
leftParenToken.range[1] === firstToken.range[0] &&
!astUtils.canTokensBeAdjacent(tokenBeforeLeftParen, firstToken);
} | javascript | function requiresLeadingSpace(node) {
const leftParenToken = sourceCode.getTokenBefore(node);
const tokenBeforeLeftParen = sourceCode.getTokenBefore(node, 1);
const firstToken = sourceCode.getFirstToken(node);
return tokenBeforeLeftParen &&
tokenBeforeLeftParen.range[1] === leftParenToken.range[0] &&
leftParenToken.range[1] === firstToken.range[0] &&
!astUtils.canTokensBeAdjacent(tokenBeforeLeftParen, firstToken);
} | [
"function",
"requiresLeadingSpace",
"(",
"node",
")",
"{",
"const",
"leftParenToken",
"=",
"sourceCode",
".",
"getTokenBefore",
"(",
"node",
")",
";",
"const",
"tokenBeforeLeftParen",
"=",
"sourceCode",
".",
"getTokenBefore",
"(",
"node",
",",
"1",
")",
";",
"const",
"firstToken",
"=",
"sourceCode",
".",
"getFirstToken",
"(",
"node",
")",
";",
"return",
"tokenBeforeLeftParen",
"&&",
"tokenBeforeLeftParen",
".",
"range",
"[",
"1",
"]",
"===",
"leftParenToken",
".",
"range",
"[",
"0",
"]",
"&&",
"leftParenToken",
".",
"range",
"[",
"1",
"]",
"===",
"firstToken",
".",
"range",
"[",
"0",
"]",
"&&",
"!",
"astUtils",
".",
"canTokensBeAdjacent",
"(",
"tokenBeforeLeftParen",
",",
"firstToken",
")",
";",
"}"
] | Determines whether a node should be preceded by an additional space when removing parens
@param {ASTNode} node node to evaluate; must be surrounded by parentheses
@returns {boolean} `true` if a space should be inserted before the node
@private | [
"Determines",
"whether",
"a",
"node",
"should",
"be",
"preceded",
"by",
"an",
"additional",
"space",
"when",
"removing",
"parens"
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-extra-parens.js#L262-L271 |
3,198 | eslint/eslint | lib/rules/no-extra-parens.js | requiresTrailingSpace | function requiresTrailingSpace(node) {
const nextTwoTokens = sourceCode.getTokensAfter(node, { count: 2 });
const rightParenToken = nextTwoTokens[0];
const tokenAfterRightParen = nextTwoTokens[1];
const tokenBeforeRightParen = sourceCode.getLastToken(node);
return rightParenToken && tokenAfterRightParen &&
!sourceCode.isSpaceBetweenTokens(rightParenToken, tokenAfterRightParen) &&
!astUtils.canTokensBeAdjacent(tokenBeforeRightParen, tokenAfterRightParen);
} | javascript | function requiresTrailingSpace(node) {
const nextTwoTokens = sourceCode.getTokensAfter(node, { count: 2 });
const rightParenToken = nextTwoTokens[0];
const tokenAfterRightParen = nextTwoTokens[1];
const tokenBeforeRightParen = sourceCode.getLastToken(node);
return rightParenToken && tokenAfterRightParen &&
!sourceCode.isSpaceBetweenTokens(rightParenToken, tokenAfterRightParen) &&
!astUtils.canTokensBeAdjacent(tokenBeforeRightParen, tokenAfterRightParen);
} | [
"function",
"requiresTrailingSpace",
"(",
"node",
")",
"{",
"const",
"nextTwoTokens",
"=",
"sourceCode",
".",
"getTokensAfter",
"(",
"node",
",",
"{",
"count",
":",
"2",
"}",
")",
";",
"const",
"rightParenToken",
"=",
"nextTwoTokens",
"[",
"0",
"]",
";",
"const",
"tokenAfterRightParen",
"=",
"nextTwoTokens",
"[",
"1",
"]",
";",
"const",
"tokenBeforeRightParen",
"=",
"sourceCode",
".",
"getLastToken",
"(",
"node",
")",
";",
"return",
"rightParenToken",
"&&",
"tokenAfterRightParen",
"&&",
"!",
"sourceCode",
".",
"isSpaceBetweenTokens",
"(",
"rightParenToken",
",",
"tokenAfterRightParen",
")",
"&&",
"!",
"astUtils",
".",
"canTokensBeAdjacent",
"(",
"tokenBeforeRightParen",
",",
"tokenAfterRightParen",
")",
";",
"}"
] | Determines whether a node should be followed by an additional space when removing parens
@param {ASTNode} node node to evaluate; must be surrounded by parentheses
@returns {boolean} `true` if a space should be inserted after the node
@private | [
"Determines",
"whether",
"a",
"node",
"should",
"be",
"followed",
"by",
"an",
"additional",
"space",
"when",
"removing",
"parens"
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-extra-parens.js#L279-L288 |
3,199 | eslint/eslint | lib/rules/no-extra-parens.js | doesMemberExpressionContainCallExpression | function doesMemberExpressionContainCallExpression(node) {
let currentNode = node.object;
let currentNodeType = node.object.type;
while (currentNodeType === "MemberExpression") {
currentNode = currentNode.object;
currentNodeType = currentNode.type;
}
return currentNodeType === "CallExpression";
} | javascript | function doesMemberExpressionContainCallExpression(node) {
let currentNode = node.object;
let currentNodeType = node.object.type;
while (currentNodeType === "MemberExpression") {
currentNode = currentNode.object;
currentNodeType = currentNode.type;
}
return currentNodeType === "CallExpression";
} | [
"function",
"doesMemberExpressionContainCallExpression",
"(",
"node",
")",
"{",
"let",
"currentNode",
"=",
"node",
".",
"object",
";",
"let",
"currentNodeType",
"=",
"node",
".",
"object",
".",
"type",
";",
"while",
"(",
"currentNodeType",
"===",
"\"MemberExpression\"",
")",
"{",
"currentNode",
"=",
"currentNode",
".",
"object",
";",
"currentNodeType",
"=",
"currentNode",
".",
"type",
";",
"}",
"return",
"currentNodeType",
"===",
"\"CallExpression\"",
";",
"}"
] | Check if a member expression contains a call expression
@param {ASTNode} node MemberExpression node to evaluate
@returns {boolean} true if found, false if not | [
"Check",
"if",
"a",
"member",
"expression",
"contains",
"a",
"call",
"expression"
] | bc0819c94aad14f7fad3cbc2338ea15658b0f272 | https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-extra-parens.js#L355-L365 |
Subsets and Splits