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
list | docstring
stringlengths 4
11.8k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 86
226
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
eslint/eslint
|
lib/rules/prefer-const.js
|
canBecomeVariableDeclaration
|
function canBecomeVariableDeclaration(identifier) {
let node = identifier.parent;
while (PATTERN_TYPE.test(node.type)) {
node = node.parent;
}
return (
node.type === "VariableDeclarator" ||
(
node.type === "AssignmentExpression" &&
node.parent.type === "ExpressionStatement" &&
DECLARATION_HOST_TYPE.test(node.parent.parent.type)
)
);
}
|
javascript
|
function canBecomeVariableDeclaration(identifier) {
let node = identifier.parent;
while (PATTERN_TYPE.test(node.type)) {
node = node.parent;
}
return (
node.type === "VariableDeclarator" ||
(
node.type === "AssignmentExpression" &&
node.parent.type === "ExpressionStatement" &&
DECLARATION_HOST_TYPE.test(node.parent.parent.type)
)
);
}
|
[
"function",
"canBecomeVariableDeclaration",
"(",
"identifier",
")",
"{",
"let",
"node",
"=",
"identifier",
".",
"parent",
";",
"while",
"(",
"PATTERN_TYPE",
".",
"test",
"(",
"node",
".",
"type",
")",
")",
"{",
"node",
"=",
"node",
".",
"parent",
";",
"}",
"return",
"(",
"node",
".",
"type",
"===",
"\"VariableDeclarator\"",
"||",
"(",
"node",
".",
"type",
"===",
"\"AssignmentExpression\"",
"&&",
"node",
".",
"parent",
".",
"type",
"===",
"\"ExpressionStatement\"",
"&&",
"DECLARATION_HOST_TYPE",
".",
"test",
"(",
"node",
".",
"parent",
".",
"parent",
".",
"type",
")",
")",
")",
";",
"}"
] |
Checks whether a given Identifier node becomes a VariableDeclaration or not.
@param {ASTNode} identifier - An Identifier node to check.
@returns {boolean} `true` if the node can become a VariableDeclaration.
|
[
"Checks",
"whether",
"a",
"given",
"Identifier",
"node",
"becomes",
"a",
"VariableDeclaration",
"or",
"not",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/prefer-const.js#L34-L49
|
train
|
eslint/eslint
|
lib/rules/prefer-const.js
|
isOuterVariableInDestructing
|
function isOuterVariableInDestructing(name, initScope) {
if (initScope.through.find(ref => ref.resolved && ref.resolved.name === name)) {
return true;
}
const variable = astUtils.getVariableByName(initScope, name);
if (variable !== null) {
return variable.defs.some(def => def.type === "Parameter");
}
return false;
}
|
javascript
|
function isOuterVariableInDestructing(name, initScope) {
if (initScope.through.find(ref => ref.resolved && ref.resolved.name === name)) {
return true;
}
const variable = astUtils.getVariableByName(initScope, name);
if (variable !== null) {
return variable.defs.some(def => def.type === "Parameter");
}
return false;
}
|
[
"function",
"isOuterVariableInDestructing",
"(",
"name",
",",
"initScope",
")",
"{",
"if",
"(",
"initScope",
".",
"through",
".",
"find",
"(",
"ref",
"=>",
"ref",
".",
"resolved",
"&&",
"ref",
".",
"resolved",
".",
"name",
"===",
"name",
")",
")",
"{",
"return",
"true",
";",
"}",
"const",
"variable",
"=",
"astUtils",
".",
"getVariableByName",
"(",
"initScope",
",",
"name",
")",
";",
"if",
"(",
"variable",
"!==",
"null",
")",
"{",
"return",
"variable",
".",
"defs",
".",
"some",
"(",
"def",
"=>",
"def",
".",
"type",
"===",
"\"Parameter\"",
")",
";",
"}",
"return",
"false",
";",
"}"
] |
Checks if an property or element is from outer scope or function parameters
in destructing pattern.
@param {string} name - A variable name to be checked.
@param {eslint-scope.Scope} initScope - A scope to start find.
@returns {boolean} Indicates if the variable is from outer scope or function parameters.
|
[
"Checks",
"if",
"an",
"property",
"or",
"element",
"is",
"from",
"outer",
"scope",
"or",
"function",
"parameters",
"in",
"destructing",
"pattern",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/prefer-const.js#L59-L72
|
train
|
eslint/eslint
|
lib/rules/prefer-const.js
|
hasMemberExpressionAssignment
|
function hasMemberExpressionAssignment(node) {
switch (node.type) {
case "ObjectPattern":
return node.properties.some(prop => {
if (prop) {
/*
* Spread elements have an argument property while
* others have a value property. Because different
* parsers use different node types for spread elements,
* we just check if there is an argument property.
*/
return hasMemberExpressionAssignment(prop.argument || prop.value);
}
return false;
});
case "ArrayPattern":
return node.elements.some(element => {
if (element) {
return hasMemberExpressionAssignment(element);
}
return false;
});
case "AssignmentPattern":
return hasMemberExpressionAssignment(node.left);
case "MemberExpression":
return true;
// no default
}
return false;
}
|
javascript
|
function hasMemberExpressionAssignment(node) {
switch (node.type) {
case "ObjectPattern":
return node.properties.some(prop => {
if (prop) {
/*
* Spread elements have an argument property while
* others have a value property. Because different
* parsers use different node types for spread elements,
* we just check if there is an argument property.
*/
return hasMemberExpressionAssignment(prop.argument || prop.value);
}
return false;
});
case "ArrayPattern":
return node.elements.some(element => {
if (element) {
return hasMemberExpressionAssignment(element);
}
return false;
});
case "AssignmentPattern":
return hasMemberExpressionAssignment(node.left);
case "MemberExpression":
return true;
// no default
}
return false;
}
|
[
"function",
"hasMemberExpressionAssignment",
"(",
"node",
")",
"{",
"switch",
"(",
"node",
".",
"type",
")",
"{",
"case",
"\"ObjectPattern\"",
":",
"return",
"node",
".",
"properties",
".",
"some",
"(",
"prop",
"=>",
"{",
"if",
"(",
"prop",
")",
"{",
"return",
"hasMemberExpressionAssignment",
"(",
"prop",
".",
"argument",
"||",
"prop",
".",
"value",
")",
";",
"}",
"return",
"false",
";",
"}",
")",
";",
"case",
"\"ArrayPattern\"",
":",
"return",
"node",
".",
"elements",
".",
"some",
"(",
"element",
"=>",
"{",
"if",
"(",
"element",
")",
"{",
"return",
"hasMemberExpressionAssignment",
"(",
"element",
")",
";",
"}",
"return",
"false",
";",
"}",
")",
";",
"case",
"\"AssignmentPattern\"",
":",
"return",
"hasMemberExpressionAssignment",
"(",
"node",
".",
"left",
")",
";",
"case",
"\"MemberExpression\"",
":",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] |
Determines if a destructuring assignment node contains
any MemberExpression nodes. This is used to determine if a
variable that is only written once using destructuring can be
safely converted into a const declaration.
@param {ASTNode} node The ObjectPattern or ArrayPattern node to check.
@returns {boolean} True if the destructuring pattern contains
a MemberExpression, false if not.
|
[
"Determines",
"if",
"a",
"destructuring",
"assignment",
"node",
"contains",
"any",
"MemberExpression",
"nodes",
".",
"This",
"is",
"used",
"to",
"determine",
"if",
"a",
"variable",
"that",
"is",
"only",
"written",
"once",
"using",
"destructuring",
"can",
"be",
"safely",
"converted",
"into",
"a",
"const",
"declaration",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/prefer-const.js#L109-L146
|
train
|
eslint/eslint
|
lib/rules/prefer-const.js
|
getIdentifierIfShouldBeConst
|
function getIdentifierIfShouldBeConst(variable, ignoreReadBeforeAssign) {
if (variable.eslintUsed && variable.scope.type === "global") {
return null;
}
// Finds the unique WriteReference.
let writer = null;
let isReadBeforeInit = false;
const references = variable.references;
for (let i = 0; i < references.length; ++i) {
const reference = references[i];
if (reference.isWrite()) {
const isReassigned = (
writer !== null &&
writer.identifier !== reference.identifier
);
if (isReassigned) {
return null;
}
const destructuringHost = getDestructuringHost(reference);
if (destructuringHost !== null && destructuringHost.left !== void 0) {
const leftNode = destructuringHost.left;
let hasOuterVariables = false,
hasNonIdentifiers = false;
if (leftNode.type === "ObjectPattern") {
const properties = leftNode.properties;
hasOuterVariables = properties
.filter(prop => prop.value)
.map(prop => prop.value.name)
.some(name => isOuterVariableInDestructing(name, variable.scope));
hasNonIdentifiers = hasMemberExpressionAssignment(leftNode);
} else if (leftNode.type === "ArrayPattern") {
const elements = leftNode.elements;
hasOuterVariables = elements
.map(element => element && element.name)
.some(name => isOuterVariableInDestructing(name, variable.scope));
hasNonIdentifiers = hasMemberExpressionAssignment(leftNode);
}
if (hasOuterVariables || hasNonIdentifiers) {
return null;
}
}
writer = reference;
} else if (reference.isRead() && writer === null) {
if (ignoreReadBeforeAssign) {
return null;
}
isReadBeforeInit = true;
}
}
/*
* If the assignment is from a different scope, ignore it.
* If the assignment cannot change to a declaration, ignore it.
*/
const shouldBeConst = (
writer !== null &&
writer.from === variable.scope &&
canBecomeVariableDeclaration(writer.identifier)
);
if (!shouldBeConst) {
return null;
}
if (isReadBeforeInit) {
return variable.defs[0].name;
}
return writer.identifier;
}
|
javascript
|
function getIdentifierIfShouldBeConst(variable, ignoreReadBeforeAssign) {
if (variable.eslintUsed && variable.scope.type === "global") {
return null;
}
// Finds the unique WriteReference.
let writer = null;
let isReadBeforeInit = false;
const references = variable.references;
for (let i = 0; i < references.length; ++i) {
const reference = references[i];
if (reference.isWrite()) {
const isReassigned = (
writer !== null &&
writer.identifier !== reference.identifier
);
if (isReassigned) {
return null;
}
const destructuringHost = getDestructuringHost(reference);
if (destructuringHost !== null && destructuringHost.left !== void 0) {
const leftNode = destructuringHost.left;
let hasOuterVariables = false,
hasNonIdentifiers = false;
if (leftNode.type === "ObjectPattern") {
const properties = leftNode.properties;
hasOuterVariables = properties
.filter(prop => prop.value)
.map(prop => prop.value.name)
.some(name => isOuterVariableInDestructing(name, variable.scope));
hasNonIdentifiers = hasMemberExpressionAssignment(leftNode);
} else if (leftNode.type === "ArrayPattern") {
const elements = leftNode.elements;
hasOuterVariables = elements
.map(element => element && element.name)
.some(name => isOuterVariableInDestructing(name, variable.scope));
hasNonIdentifiers = hasMemberExpressionAssignment(leftNode);
}
if (hasOuterVariables || hasNonIdentifiers) {
return null;
}
}
writer = reference;
} else if (reference.isRead() && writer === null) {
if (ignoreReadBeforeAssign) {
return null;
}
isReadBeforeInit = true;
}
}
/*
* If the assignment is from a different scope, ignore it.
* If the assignment cannot change to a declaration, ignore it.
*/
const shouldBeConst = (
writer !== null &&
writer.from === variable.scope &&
canBecomeVariableDeclaration(writer.identifier)
);
if (!shouldBeConst) {
return null;
}
if (isReadBeforeInit) {
return variable.defs[0].name;
}
return writer.identifier;
}
|
[
"function",
"getIdentifierIfShouldBeConst",
"(",
"variable",
",",
"ignoreReadBeforeAssign",
")",
"{",
"if",
"(",
"variable",
".",
"eslintUsed",
"&&",
"variable",
".",
"scope",
".",
"type",
"===",
"\"global\"",
")",
"{",
"return",
"null",
";",
"}",
"let",
"writer",
"=",
"null",
";",
"let",
"isReadBeforeInit",
"=",
"false",
";",
"const",
"references",
"=",
"variable",
".",
"references",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"references",
".",
"length",
";",
"++",
"i",
")",
"{",
"const",
"reference",
"=",
"references",
"[",
"i",
"]",
";",
"if",
"(",
"reference",
".",
"isWrite",
"(",
")",
")",
"{",
"const",
"isReassigned",
"=",
"(",
"writer",
"!==",
"null",
"&&",
"writer",
".",
"identifier",
"!==",
"reference",
".",
"identifier",
")",
";",
"if",
"(",
"isReassigned",
")",
"{",
"return",
"null",
";",
"}",
"const",
"destructuringHost",
"=",
"getDestructuringHost",
"(",
"reference",
")",
";",
"if",
"(",
"destructuringHost",
"!==",
"null",
"&&",
"destructuringHost",
".",
"left",
"!==",
"void",
"0",
")",
"{",
"const",
"leftNode",
"=",
"destructuringHost",
".",
"left",
";",
"let",
"hasOuterVariables",
"=",
"false",
",",
"hasNonIdentifiers",
"=",
"false",
";",
"if",
"(",
"leftNode",
".",
"type",
"===",
"\"ObjectPattern\"",
")",
"{",
"const",
"properties",
"=",
"leftNode",
".",
"properties",
";",
"hasOuterVariables",
"=",
"properties",
".",
"filter",
"(",
"prop",
"=>",
"prop",
".",
"value",
")",
".",
"map",
"(",
"prop",
"=>",
"prop",
".",
"value",
".",
"name",
")",
".",
"some",
"(",
"name",
"=>",
"isOuterVariableInDestructing",
"(",
"name",
",",
"variable",
".",
"scope",
")",
")",
";",
"hasNonIdentifiers",
"=",
"hasMemberExpressionAssignment",
"(",
"leftNode",
")",
";",
"}",
"else",
"if",
"(",
"leftNode",
".",
"type",
"===",
"\"ArrayPattern\"",
")",
"{",
"const",
"elements",
"=",
"leftNode",
".",
"elements",
";",
"hasOuterVariables",
"=",
"elements",
".",
"map",
"(",
"element",
"=>",
"element",
"&&",
"element",
".",
"name",
")",
".",
"some",
"(",
"name",
"=>",
"isOuterVariableInDestructing",
"(",
"name",
",",
"variable",
".",
"scope",
")",
")",
";",
"hasNonIdentifiers",
"=",
"hasMemberExpressionAssignment",
"(",
"leftNode",
")",
";",
"}",
"if",
"(",
"hasOuterVariables",
"||",
"hasNonIdentifiers",
")",
"{",
"return",
"null",
";",
"}",
"}",
"writer",
"=",
"reference",
";",
"}",
"else",
"if",
"(",
"reference",
".",
"isRead",
"(",
")",
"&&",
"writer",
"===",
"null",
")",
"{",
"if",
"(",
"ignoreReadBeforeAssign",
")",
"{",
"return",
"null",
";",
"}",
"isReadBeforeInit",
"=",
"true",
";",
"}",
"}",
"const",
"shouldBeConst",
"=",
"(",
"writer",
"!==",
"null",
"&&",
"writer",
".",
"from",
"===",
"variable",
".",
"scope",
"&&",
"canBecomeVariableDeclaration",
"(",
"writer",
".",
"identifier",
")",
")",
";",
"if",
"(",
"!",
"shouldBeConst",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"isReadBeforeInit",
")",
"{",
"return",
"variable",
".",
"defs",
"[",
"0",
"]",
".",
"name",
";",
"}",
"return",
"writer",
".",
"identifier",
";",
"}"
] |
Gets an identifier node of a given variable.
If the initialization exists or one or more reading references exist before
the first assignment, the identifier node is the node of the declaration.
Otherwise, the identifier node is the node of the first assignment.
If the variable should not change to const, this function returns null.
- If the variable is reassigned.
- If the variable is never initialized nor assigned.
- If the variable is initialized in a different scope from the declaration.
- If the unique assignment of the variable cannot change to a declaration.
e.g. `if (a) b = 1` / `return (b = 1)`
- If the variable is declared in the global scope and `eslintUsed` is `true`.
`/*exported foo` directive comment makes such variables. This rule does not
warn such variables because this rule cannot distinguish whether the
exported variables are reassigned or not.
@param {eslint-scope.Variable} variable - A variable to get.
@param {boolean} ignoreReadBeforeAssign -
The value of `ignoreReadBeforeAssign` option.
@returns {ASTNode|null}
An Identifier node if the variable should change to const.
Otherwise, null.
|
[
"Gets",
"an",
"identifier",
"node",
"of",
"a",
"given",
"variable",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/prefer-const.js#L173-L258
|
train
|
eslint/eslint
|
lib/rules/prefer-const.js
|
findUp
|
function findUp(node, type, shouldStop) {
if (!node || shouldStop(node)) {
return null;
}
if (node.type === type) {
return node;
}
return findUp(node.parent, type, shouldStop);
}
|
javascript
|
function findUp(node, type, shouldStop) {
if (!node || shouldStop(node)) {
return null;
}
if (node.type === type) {
return node;
}
return findUp(node.parent, type, shouldStop);
}
|
[
"function",
"findUp",
"(",
"node",
",",
"type",
",",
"shouldStop",
")",
"{",
"if",
"(",
"!",
"node",
"||",
"shouldStop",
"(",
"node",
")",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"node",
".",
"type",
"===",
"type",
")",
"{",
"return",
"node",
";",
"}",
"return",
"findUp",
"(",
"node",
".",
"parent",
",",
"type",
",",
"shouldStop",
")",
";",
"}"
] |
Finds the nearest parent of node with a given type.
@param {ASTNode} node – The node to search from.
@param {string} type – The type field of the parent node.
@param {Function} shouldStop – a predicate that returns true if the traversal should stop, and false otherwise.
@returns {ASTNode} The closest ancestor with the specified type; null if no such ancestor exists.
|
[
"Finds",
"the",
"nearest",
"parent",
"of",
"node",
"with",
"a",
"given",
"type",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/prefer-const.js#L317-L325
|
train
|
eslint/eslint
|
lib/rules/prefer-const.js
|
checkGroup
|
function checkGroup(nodes) {
const nodesToReport = nodes.filter(Boolean);
if (nodes.length && (shouldMatchAnyDestructuredVariable || nodesToReport.length === nodes.length)) {
const varDeclParent = findUp(nodes[0], "VariableDeclaration", parentNode => parentNode.type.endsWith("Statement"));
const isVarDecParentNull = varDeclParent === null;
if (!isVarDecParentNull && varDeclParent.declarations.length > 0) {
const firstDeclaration = varDeclParent.declarations[0];
if (firstDeclaration.init) {
const firstDecParent = firstDeclaration.init.parent;
/*
* First we check the declaration type and then depending on
* if the type is a "VariableDeclarator" or its an "ObjectPattern"
* we compare the name from the first identifier, if the names are different
* we assign the new name and reset the count of reportCount and nodeCount in
* order to check each block for the number of reported errors and base our fix
* based on comparing nodes.length and nodesToReport.length.
*/
if (firstDecParent.type === "VariableDeclarator") {
if (firstDecParent.id.name !== name) {
name = firstDecParent.id.name;
reportCount = 0;
}
if (firstDecParent.id.type === "ObjectPattern") {
if (firstDecParent.init.name !== name) {
name = firstDecParent.init.name;
reportCount = 0;
}
}
}
}
}
let shouldFix = varDeclParent &&
// Don't do a fix unless the variable is initialized (or it's in a for-in or for-of loop)
(varDeclParent.parent.type === "ForInStatement" || varDeclParent.parent.type === "ForOfStatement" || varDeclParent.declarations[0].init) &&
/*
* If options.destructuring is "all", then this warning will not occur unless
* every assignment in the destructuring should be const. In that case, it's safe
* to apply the fix.
*/
nodesToReport.length === nodes.length;
if (!isVarDecParentNull && varDeclParent.declarations && varDeclParent.declarations.length !== 1) {
if (varDeclParent && varDeclParent.declarations && varDeclParent.declarations.length >= 1) {
/*
* Add nodesToReport.length to a count, then comparing the count to the length
* of the declarations in the current block.
*/
reportCount += nodesToReport.length;
shouldFix = shouldFix && (reportCount === varDeclParent.declarations.length);
}
}
nodesToReport.forEach(node => {
context.report({
node,
messageId: "useConst",
data: node,
fix: shouldFix ? fixer => fixer.replaceText(sourceCode.getFirstToken(varDeclParent), "const") : null
});
});
}
}
|
javascript
|
function checkGroup(nodes) {
const nodesToReport = nodes.filter(Boolean);
if (nodes.length && (shouldMatchAnyDestructuredVariable || nodesToReport.length === nodes.length)) {
const varDeclParent = findUp(nodes[0], "VariableDeclaration", parentNode => parentNode.type.endsWith("Statement"));
const isVarDecParentNull = varDeclParent === null;
if (!isVarDecParentNull && varDeclParent.declarations.length > 0) {
const firstDeclaration = varDeclParent.declarations[0];
if (firstDeclaration.init) {
const firstDecParent = firstDeclaration.init.parent;
/*
* First we check the declaration type and then depending on
* if the type is a "VariableDeclarator" or its an "ObjectPattern"
* we compare the name from the first identifier, if the names are different
* we assign the new name and reset the count of reportCount and nodeCount in
* order to check each block for the number of reported errors and base our fix
* based on comparing nodes.length and nodesToReport.length.
*/
if (firstDecParent.type === "VariableDeclarator") {
if (firstDecParent.id.name !== name) {
name = firstDecParent.id.name;
reportCount = 0;
}
if (firstDecParent.id.type === "ObjectPattern") {
if (firstDecParent.init.name !== name) {
name = firstDecParent.init.name;
reportCount = 0;
}
}
}
}
}
let shouldFix = varDeclParent &&
// Don't do a fix unless the variable is initialized (or it's in a for-in or for-of loop)
(varDeclParent.parent.type === "ForInStatement" || varDeclParent.parent.type === "ForOfStatement" || varDeclParent.declarations[0].init) &&
/*
* If options.destructuring is "all", then this warning will not occur unless
* every assignment in the destructuring should be const. In that case, it's safe
* to apply the fix.
*/
nodesToReport.length === nodes.length;
if (!isVarDecParentNull && varDeclParent.declarations && varDeclParent.declarations.length !== 1) {
if (varDeclParent && varDeclParent.declarations && varDeclParent.declarations.length >= 1) {
/*
* Add nodesToReport.length to a count, then comparing the count to the length
* of the declarations in the current block.
*/
reportCount += nodesToReport.length;
shouldFix = shouldFix && (reportCount === varDeclParent.declarations.length);
}
}
nodesToReport.forEach(node => {
context.report({
node,
messageId: "useConst",
data: node,
fix: shouldFix ? fixer => fixer.replaceText(sourceCode.getFirstToken(varDeclParent), "const") : null
});
});
}
}
|
[
"function",
"checkGroup",
"(",
"nodes",
")",
"{",
"const",
"nodesToReport",
"=",
"nodes",
".",
"filter",
"(",
"Boolean",
")",
";",
"if",
"(",
"nodes",
".",
"length",
"&&",
"(",
"shouldMatchAnyDestructuredVariable",
"||",
"nodesToReport",
".",
"length",
"===",
"nodes",
".",
"length",
")",
")",
"{",
"const",
"varDeclParent",
"=",
"findUp",
"(",
"nodes",
"[",
"0",
"]",
",",
"\"VariableDeclaration\"",
",",
"parentNode",
"=>",
"parentNode",
".",
"type",
".",
"endsWith",
"(",
"\"Statement\"",
")",
")",
";",
"const",
"isVarDecParentNull",
"=",
"varDeclParent",
"===",
"null",
";",
"if",
"(",
"!",
"isVarDecParentNull",
"&&",
"varDeclParent",
".",
"declarations",
".",
"length",
">",
"0",
")",
"{",
"const",
"firstDeclaration",
"=",
"varDeclParent",
".",
"declarations",
"[",
"0",
"]",
";",
"if",
"(",
"firstDeclaration",
".",
"init",
")",
"{",
"const",
"firstDecParent",
"=",
"firstDeclaration",
".",
"init",
".",
"parent",
";",
"if",
"(",
"firstDecParent",
".",
"type",
"===",
"\"VariableDeclarator\"",
")",
"{",
"if",
"(",
"firstDecParent",
".",
"id",
".",
"name",
"!==",
"name",
")",
"{",
"name",
"=",
"firstDecParent",
".",
"id",
".",
"name",
";",
"reportCount",
"=",
"0",
";",
"}",
"if",
"(",
"firstDecParent",
".",
"id",
".",
"type",
"===",
"\"ObjectPattern\"",
")",
"{",
"if",
"(",
"firstDecParent",
".",
"init",
".",
"name",
"!==",
"name",
")",
"{",
"name",
"=",
"firstDecParent",
".",
"init",
".",
"name",
";",
"reportCount",
"=",
"0",
";",
"}",
"}",
"}",
"}",
"}",
"let",
"shouldFix",
"=",
"varDeclParent",
"&&",
"(",
"varDeclParent",
".",
"parent",
".",
"type",
"===",
"\"ForInStatement\"",
"||",
"varDeclParent",
".",
"parent",
".",
"type",
"===",
"\"ForOfStatement\"",
"||",
"varDeclParent",
".",
"declarations",
"[",
"0",
"]",
".",
"init",
")",
"&&",
"nodesToReport",
".",
"length",
"===",
"nodes",
".",
"length",
";",
"if",
"(",
"!",
"isVarDecParentNull",
"&&",
"varDeclParent",
".",
"declarations",
"&&",
"varDeclParent",
".",
"declarations",
".",
"length",
"!==",
"1",
")",
"{",
"if",
"(",
"varDeclParent",
"&&",
"varDeclParent",
".",
"declarations",
"&&",
"varDeclParent",
".",
"declarations",
".",
"length",
">=",
"1",
")",
"{",
"reportCount",
"+=",
"nodesToReport",
".",
"length",
";",
"shouldFix",
"=",
"shouldFix",
"&&",
"(",
"reportCount",
"===",
"varDeclParent",
".",
"declarations",
".",
"length",
")",
";",
"}",
"}",
"nodesToReport",
".",
"forEach",
"(",
"node",
"=>",
"{",
"context",
".",
"report",
"(",
"{",
"node",
",",
"messageId",
":",
"\"useConst\"",
",",
"data",
":",
"node",
",",
"fix",
":",
"shouldFix",
"?",
"fixer",
"=>",
"fixer",
".",
"replaceText",
"(",
"sourceCode",
".",
"getFirstToken",
"(",
"varDeclParent",
")",
",",
"\"const\"",
")",
":",
"null",
"}",
")",
";",
"}",
")",
";",
"}",
"}"
] |
Reports given identifier nodes if all of the nodes should be declared
as const.
The argument 'nodes' is an array of Identifier nodes.
This node is the result of 'getIdentifierIfShouldBeConst()', so it's
nullable. In simple declaration or assignment cases, the length of
the array is 1. In destructuring cases, the length of the array can
be 2 or more.
@param {(eslint-scope.Reference|null)[]} nodes -
References which are grouped by destructuring to report.
@returns {void}
|
[
"Reports",
"given",
"identifier",
"nodes",
"if",
"all",
"of",
"the",
"nodes",
"should",
"be",
"declared",
"as",
"const",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/prefer-const.js#L382-L457
|
train
|
eslint/eslint
|
lib/rules/object-shorthand.js
|
isConstructor
|
function isConstructor(name) {
const match = CTOR_PREFIX_REGEX.exec(name);
// Not a constructor if name has no characters apart from '_', '$' and digits e.g. '_', '$$', '_8'
if (!match) {
return false;
}
const firstChar = name.charAt(match.index);
return firstChar === firstChar.toUpperCase();
}
|
javascript
|
function isConstructor(name) {
const match = CTOR_PREFIX_REGEX.exec(name);
// Not a constructor if name has no characters apart from '_', '$' and digits e.g. '_', '$$', '_8'
if (!match) {
return false;
}
const firstChar = name.charAt(match.index);
return firstChar === firstChar.toUpperCase();
}
|
[
"function",
"isConstructor",
"(",
"name",
")",
"{",
"const",
"match",
"=",
"CTOR_PREFIX_REGEX",
".",
"exec",
"(",
"name",
")",
";",
"if",
"(",
"!",
"match",
")",
"{",
"return",
"false",
";",
"}",
"const",
"firstChar",
"=",
"name",
".",
"charAt",
"(",
"match",
".",
"index",
")",
";",
"return",
"firstChar",
"===",
"firstChar",
".",
"toUpperCase",
"(",
")",
";",
"}"
] |
Determines if the first character of the name is a capital letter.
@param {string} name The name of the node to evaluate.
@returns {boolean} True if the first character of the property name is a capital letter, false if not.
@private
|
[
"Determines",
"if",
"the",
"first",
"character",
"of",
"the",
"name",
"is",
"a",
"capital",
"letter",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/object-shorthand.js#L124-L135
|
train
|
eslint/eslint
|
lib/rules/object-shorthand.js
|
makeFunctionShorthand
|
function makeFunctionShorthand(fixer, node) {
const firstKeyToken = node.computed
? sourceCode.getFirstToken(node, astUtils.isOpeningBracketToken)
: sourceCode.getFirstToken(node.key);
const lastKeyToken = node.computed
? sourceCode.getFirstTokenBetween(node.key, node.value, astUtils.isClosingBracketToken)
: sourceCode.getLastToken(node.key);
const keyText = sourceCode.text.slice(firstKeyToken.range[0], lastKeyToken.range[1]);
let keyPrefix = "";
if (sourceCode.commentsExistBetween(lastKeyToken, node.value)) {
return null;
}
if (node.value.async) {
keyPrefix += "async ";
}
if (node.value.generator) {
keyPrefix += "*";
}
if (node.value.type === "FunctionExpression") {
const functionToken = sourceCode.getTokens(node.value).find(token => token.type === "Keyword" && token.value === "function");
const tokenBeforeParams = node.value.generator ? sourceCode.getTokenAfter(functionToken) : functionToken;
return fixer.replaceTextRange(
[firstKeyToken.range[0], node.range[1]],
keyPrefix + keyText + sourceCode.text.slice(tokenBeforeParams.range[1], node.value.range[1])
);
}
const arrowToken = sourceCode.getTokenBefore(node.value.body, { filter: token => token.value === "=>" });
const tokenBeforeArrow = sourceCode.getTokenBefore(arrowToken);
const hasParensAroundParameters = tokenBeforeArrow.type === "Punctuator" && tokenBeforeArrow.value === ")";
const oldParamText = sourceCode.text.slice(sourceCode.getFirstToken(node.value, node.value.async ? 1 : 0).range[0], tokenBeforeArrow.range[1]);
const newParamText = hasParensAroundParameters ? oldParamText : `(${oldParamText})`;
return fixer.replaceTextRange(
[firstKeyToken.range[0], node.range[1]],
keyPrefix + keyText + newParamText + sourceCode.text.slice(arrowToken.range[1], node.value.range[1])
);
}
|
javascript
|
function makeFunctionShorthand(fixer, node) {
const firstKeyToken = node.computed
? sourceCode.getFirstToken(node, astUtils.isOpeningBracketToken)
: sourceCode.getFirstToken(node.key);
const lastKeyToken = node.computed
? sourceCode.getFirstTokenBetween(node.key, node.value, astUtils.isClosingBracketToken)
: sourceCode.getLastToken(node.key);
const keyText = sourceCode.text.slice(firstKeyToken.range[0], lastKeyToken.range[1]);
let keyPrefix = "";
if (sourceCode.commentsExistBetween(lastKeyToken, node.value)) {
return null;
}
if (node.value.async) {
keyPrefix += "async ";
}
if (node.value.generator) {
keyPrefix += "*";
}
if (node.value.type === "FunctionExpression") {
const functionToken = sourceCode.getTokens(node.value).find(token => token.type === "Keyword" && token.value === "function");
const tokenBeforeParams = node.value.generator ? sourceCode.getTokenAfter(functionToken) : functionToken;
return fixer.replaceTextRange(
[firstKeyToken.range[0], node.range[1]],
keyPrefix + keyText + sourceCode.text.slice(tokenBeforeParams.range[1], node.value.range[1])
);
}
const arrowToken = sourceCode.getTokenBefore(node.value.body, { filter: token => token.value === "=>" });
const tokenBeforeArrow = sourceCode.getTokenBefore(arrowToken);
const hasParensAroundParameters = tokenBeforeArrow.type === "Punctuator" && tokenBeforeArrow.value === ")";
const oldParamText = sourceCode.text.slice(sourceCode.getFirstToken(node.value, node.value.async ? 1 : 0).range[0], tokenBeforeArrow.range[1]);
const newParamText = hasParensAroundParameters ? oldParamText : `(${oldParamText})`;
return fixer.replaceTextRange(
[firstKeyToken.range[0], node.range[1]],
keyPrefix + keyText + newParamText + sourceCode.text.slice(arrowToken.range[1], node.value.range[1])
);
}
|
[
"function",
"makeFunctionShorthand",
"(",
"fixer",
",",
"node",
")",
"{",
"const",
"firstKeyToken",
"=",
"node",
".",
"computed",
"?",
"sourceCode",
".",
"getFirstToken",
"(",
"node",
",",
"astUtils",
".",
"isOpeningBracketToken",
")",
":",
"sourceCode",
".",
"getFirstToken",
"(",
"node",
".",
"key",
")",
";",
"const",
"lastKeyToken",
"=",
"node",
".",
"computed",
"?",
"sourceCode",
".",
"getFirstTokenBetween",
"(",
"node",
".",
"key",
",",
"node",
".",
"value",
",",
"astUtils",
".",
"isClosingBracketToken",
")",
":",
"sourceCode",
".",
"getLastToken",
"(",
"node",
".",
"key",
")",
";",
"const",
"keyText",
"=",
"sourceCode",
".",
"text",
".",
"slice",
"(",
"firstKeyToken",
".",
"range",
"[",
"0",
"]",
",",
"lastKeyToken",
".",
"range",
"[",
"1",
"]",
")",
";",
"let",
"keyPrefix",
"=",
"\"\"",
";",
"if",
"(",
"sourceCode",
".",
"commentsExistBetween",
"(",
"lastKeyToken",
",",
"node",
".",
"value",
")",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"node",
".",
"value",
".",
"async",
")",
"{",
"keyPrefix",
"+=",
"\"async \"",
";",
"}",
"if",
"(",
"node",
".",
"value",
".",
"generator",
")",
"{",
"keyPrefix",
"+=",
"\"*\"",
";",
"}",
"if",
"(",
"node",
".",
"value",
".",
"type",
"===",
"\"FunctionExpression\"",
")",
"{",
"const",
"functionToken",
"=",
"sourceCode",
".",
"getTokens",
"(",
"node",
".",
"value",
")",
".",
"find",
"(",
"token",
"=>",
"token",
".",
"type",
"===",
"\"Keyword\"",
"&&",
"token",
".",
"value",
"===",
"\"function\"",
")",
";",
"const",
"tokenBeforeParams",
"=",
"node",
".",
"value",
".",
"generator",
"?",
"sourceCode",
".",
"getTokenAfter",
"(",
"functionToken",
")",
":",
"functionToken",
";",
"return",
"fixer",
".",
"replaceTextRange",
"(",
"[",
"firstKeyToken",
".",
"range",
"[",
"0",
"]",
",",
"node",
".",
"range",
"[",
"1",
"]",
"]",
",",
"keyPrefix",
"+",
"keyText",
"+",
"sourceCode",
".",
"text",
".",
"slice",
"(",
"tokenBeforeParams",
".",
"range",
"[",
"1",
"]",
",",
"node",
".",
"value",
".",
"range",
"[",
"1",
"]",
")",
")",
";",
"}",
"const",
"arrowToken",
"=",
"sourceCode",
".",
"getTokenBefore",
"(",
"node",
".",
"value",
".",
"body",
",",
"{",
"filter",
":",
"token",
"=>",
"token",
".",
"value",
"===",
"\"=>\"",
"}",
")",
";",
"const",
"tokenBeforeArrow",
"=",
"sourceCode",
".",
"getTokenBefore",
"(",
"arrowToken",
")",
";",
"const",
"hasParensAroundParameters",
"=",
"tokenBeforeArrow",
".",
"type",
"===",
"\"Punctuator\"",
"&&",
"tokenBeforeArrow",
".",
"value",
"===",
"\")\"",
";",
"const",
"oldParamText",
"=",
"sourceCode",
".",
"text",
".",
"slice",
"(",
"sourceCode",
".",
"getFirstToken",
"(",
"node",
".",
"value",
",",
"node",
".",
"value",
".",
"async",
"?",
"1",
":",
"0",
")",
".",
"range",
"[",
"0",
"]",
",",
"tokenBeforeArrow",
".",
"range",
"[",
"1",
"]",
")",
";",
"const",
"newParamText",
"=",
"hasParensAroundParameters",
"?",
"oldParamText",
":",
"`",
"${",
"oldParamText",
"}",
"`",
";",
"return",
"fixer",
".",
"replaceTextRange",
"(",
"[",
"firstKeyToken",
".",
"range",
"[",
"0",
"]",
",",
"node",
".",
"range",
"[",
"1",
"]",
"]",
",",
"keyPrefix",
"+",
"keyText",
"+",
"newParamText",
"+",
"sourceCode",
".",
"text",
".",
"slice",
"(",
"arrowToken",
".",
"range",
"[",
"1",
"]",
",",
"node",
".",
"value",
".",
"range",
"[",
"1",
"]",
")",
")",
";",
"}"
] |
Fixes a FunctionExpression node by making it into a shorthand property.
@param {SourceCodeFixer} fixer The fixer object
@param {ASTNode} node A `Property` node that has a `FunctionExpression` or `ArrowFunctionExpression` as its value
@returns {Object} A fix for this node
|
[
"Fixes",
"a",
"FunctionExpression",
"node",
"by",
"making",
"it",
"into",
"a",
"shorthand",
"property",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/object-shorthand.js#L237-L278
|
train
|
eslint/eslint
|
lib/rules/object-shorthand.js
|
enterFunction
|
function enterFunction() {
lexicalScopeStack.unshift(new Set());
context.getScope().variables.filter(variable => variable.name === "arguments").forEach(variable => {
variable.references.map(ref => ref.identifier).forEach(identifier => argumentsIdentifiers.add(identifier));
});
}
|
javascript
|
function enterFunction() {
lexicalScopeStack.unshift(new Set());
context.getScope().variables.filter(variable => variable.name === "arguments").forEach(variable => {
variable.references.map(ref => ref.identifier).forEach(identifier => argumentsIdentifiers.add(identifier));
});
}
|
[
"function",
"enterFunction",
"(",
")",
"{",
"lexicalScopeStack",
".",
"unshift",
"(",
"new",
"Set",
"(",
")",
")",
";",
"context",
".",
"getScope",
"(",
")",
".",
"variables",
".",
"filter",
"(",
"variable",
"=>",
"variable",
".",
"name",
"===",
"\"arguments\"",
")",
".",
"forEach",
"(",
"variable",
"=>",
"{",
"variable",
".",
"references",
".",
"map",
"(",
"ref",
"=>",
"ref",
".",
"identifier",
")",
".",
"forEach",
"(",
"identifier",
"=>",
"argumentsIdentifiers",
".",
"add",
"(",
"identifier",
")",
")",
";",
"}",
")",
";",
"}"
] |
Enters a function. This creates a new lexical identifier scope, so a new Set of arrow functions is pushed onto the stack.
Also, this marks all `arguments` identifiers so that they can be detected later.
@returns {void}
|
[
"Enters",
"a",
"function",
".",
"This",
"creates",
"a",
"new",
"lexical",
"identifier",
"scope",
"so",
"a",
"new",
"Set",
"of",
"arrow",
"functions",
"is",
"pushed",
"onto",
"the",
"stack",
".",
"Also",
"this",
"marks",
"all",
"arguments",
"identifiers",
"so",
"that",
"they",
"can",
"be",
"detected",
"later",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/object-shorthand.js#L321-L326
|
train
|
eslint/eslint
|
lib/rules/radix.js
|
isParseIntMethod
|
function isParseIntMethod(node) {
return (
node.type === "MemberExpression" &&
!node.computed &&
node.property.type === "Identifier" &&
node.property.name === "parseInt"
);
}
|
javascript
|
function isParseIntMethod(node) {
return (
node.type === "MemberExpression" &&
!node.computed &&
node.property.type === "Identifier" &&
node.property.name === "parseInt"
);
}
|
[
"function",
"isParseIntMethod",
"(",
"node",
")",
"{",
"return",
"(",
"node",
".",
"type",
"===",
"\"MemberExpression\"",
"&&",
"!",
"node",
".",
"computed",
"&&",
"node",
".",
"property",
".",
"type",
"===",
"\"Identifier\"",
"&&",
"node",
".",
"property",
".",
"name",
"===",
"\"parseInt\"",
")",
";",
"}"
] |
Checks whether a given node is a MemberExpression of `parseInt` method or not.
@param {ASTNode} node - A node to check.
@returns {boolean} `true` if the node is a MemberExpression of `parseInt`
method.
|
[
"Checks",
"whether",
"a",
"given",
"node",
"is",
"a",
"MemberExpression",
"of",
"parseInt",
"method",
"or",
"not",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/radix.js#L38-L45
|
train
|
eslint/eslint
|
lib/rules/radix.js
|
isValidRadix
|
function isValidRadix(radix) {
return !(
(radix.type === "Literal" && typeof radix.value !== "number") ||
(radix.type === "Identifier" && radix.name === "undefined")
);
}
|
javascript
|
function isValidRadix(radix) {
return !(
(radix.type === "Literal" && typeof radix.value !== "number") ||
(radix.type === "Identifier" && radix.name === "undefined")
);
}
|
[
"function",
"isValidRadix",
"(",
"radix",
")",
"{",
"return",
"!",
"(",
"(",
"radix",
".",
"type",
"===",
"\"Literal\"",
"&&",
"typeof",
"radix",
".",
"value",
"!==",
"\"number\"",
")",
"||",
"(",
"radix",
".",
"type",
"===",
"\"Identifier\"",
"&&",
"radix",
".",
"name",
"===",
"\"undefined\"",
")",
")",
";",
"}"
] |
Checks whether a given node is a valid value of radix or not.
The following values are invalid.
- A literal except numbers.
- undefined.
@param {ASTNode} radix - A node of radix to check.
@returns {boolean} `true` if the node is valid.
|
[
"Checks",
"whether",
"a",
"given",
"node",
"is",
"a",
"valid",
"value",
"of",
"radix",
"or",
"not",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/radix.js#L58-L63
|
train
|
eslint/eslint
|
lib/rules/radix.js
|
checkArguments
|
function checkArguments(node) {
const args = node.arguments;
switch (args.length) {
case 0:
context.report({
node,
message: "Missing parameters."
});
break;
case 1:
if (mode === MODE_ALWAYS) {
context.report({
node,
message: "Missing radix parameter."
});
}
break;
default:
if (mode === MODE_AS_NEEDED && isDefaultRadix(args[1])) {
context.report({
node,
message: "Redundant radix parameter."
});
} else if (!isValidRadix(args[1])) {
context.report({
node,
message: "Invalid radix parameter."
});
}
break;
}
}
|
javascript
|
function checkArguments(node) {
const args = node.arguments;
switch (args.length) {
case 0:
context.report({
node,
message: "Missing parameters."
});
break;
case 1:
if (mode === MODE_ALWAYS) {
context.report({
node,
message: "Missing radix parameter."
});
}
break;
default:
if (mode === MODE_AS_NEEDED && isDefaultRadix(args[1])) {
context.report({
node,
message: "Redundant radix parameter."
});
} else if (!isValidRadix(args[1])) {
context.report({
node,
message: "Invalid radix parameter."
});
}
break;
}
}
|
[
"function",
"checkArguments",
"(",
"node",
")",
"{",
"const",
"args",
"=",
"node",
".",
"arguments",
";",
"switch",
"(",
"args",
".",
"length",
")",
"{",
"case",
"0",
":",
"context",
".",
"report",
"(",
"{",
"node",
",",
"message",
":",
"\"Missing parameters.\"",
"}",
")",
";",
"break",
";",
"case",
"1",
":",
"if",
"(",
"mode",
"===",
"MODE_ALWAYS",
")",
"{",
"context",
".",
"report",
"(",
"{",
"node",
",",
"message",
":",
"\"Missing radix parameter.\"",
"}",
")",
";",
"}",
"break",
";",
"default",
":",
"if",
"(",
"mode",
"===",
"MODE_AS_NEEDED",
"&&",
"isDefaultRadix",
"(",
"args",
"[",
"1",
"]",
")",
")",
"{",
"context",
".",
"report",
"(",
"{",
"node",
",",
"message",
":",
"\"Redundant radix parameter.\"",
"}",
")",
";",
"}",
"else",
"if",
"(",
"!",
"isValidRadix",
"(",
"args",
"[",
"1",
"]",
")",
")",
"{",
"context",
".",
"report",
"(",
"{",
"node",
",",
"message",
":",
"\"Invalid radix parameter.\"",
"}",
")",
";",
"}",
"break",
";",
"}",
"}"
] |
Checks the arguments of a given CallExpression node and reports it if it
offends this rule.
@param {ASTNode} node - A CallExpression node to check.
@returns {void}
|
[
"Checks",
"the",
"arguments",
"of",
"a",
"given",
"CallExpression",
"node",
"and",
"reports",
"it",
"if",
"it",
"offends",
"this",
"rule",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/radix.js#L107-L141
|
train
|
eslint/eslint
|
lib/rules/no-this-before-super.js
|
setInvalid
|
function setInvalid(node) {
const segments = funcInfo.codePath.currentSegments;
for (let i = 0; i < segments.length; ++i) {
const segment = segments[i];
if (segment.reachable) {
segInfoMap[segment.id].invalidNodes.push(node);
}
}
}
|
javascript
|
function setInvalid(node) {
const segments = funcInfo.codePath.currentSegments;
for (let i = 0; i < segments.length; ++i) {
const segment = segments[i];
if (segment.reachable) {
segInfoMap[segment.id].invalidNodes.push(node);
}
}
}
|
[
"function",
"setInvalid",
"(",
"node",
")",
"{",
"const",
"segments",
"=",
"funcInfo",
".",
"codePath",
".",
"currentSegments",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"segments",
".",
"length",
";",
"++",
"i",
")",
"{",
"const",
"segment",
"=",
"segments",
"[",
"i",
"]",
";",
"if",
"(",
"segment",
".",
"reachable",
")",
"{",
"segInfoMap",
"[",
"segment",
".",
"id",
"]",
".",
"invalidNodes",
".",
"push",
"(",
"node",
")",
";",
"}",
"}",
"}"
] |
Sets a given node as invalid.
@param {ASTNode} node - A node to set as invalid. This is one of
a ThisExpression and a Super.
@returns {void}
|
[
"Sets",
"a",
"given",
"node",
"as",
"invalid",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-this-before-super.js#L106-L116
|
train
|
eslint/eslint
|
lib/rules/no-this-before-super.js
|
setSuperCalled
|
function setSuperCalled() {
const segments = funcInfo.codePath.currentSegments;
for (let i = 0; i < segments.length; ++i) {
const segment = segments[i];
if (segment.reachable) {
segInfoMap[segment.id].superCalled = true;
}
}
}
|
javascript
|
function setSuperCalled() {
const segments = funcInfo.codePath.currentSegments;
for (let i = 0; i < segments.length; ++i) {
const segment = segments[i];
if (segment.reachable) {
segInfoMap[segment.id].superCalled = true;
}
}
}
|
[
"function",
"setSuperCalled",
"(",
")",
"{",
"const",
"segments",
"=",
"funcInfo",
".",
"codePath",
".",
"currentSegments",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"segments",
".",
"length",
";",
"++",
"i",
")",
"{",
"const",
"segment",
"=",
"segments",
"[",
"i",
"]",
";",
"if",
"(",
"segment",
".",
"reachable",
")",
"{",
"segInfoMap",
"[",
"segment",
".",
"id",
"]",
".",
"superCalled",
"=",
"true",
";",
"}",
"}",
"}"
] |
Sets the current segment as `super` was called.
@returns {void}
|
[
"Sets",
"the",
"current",
"segment",
"as",
"super",
"was",
"called",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-this-before-super.js#L122-L132
|
train
|
eslint/eslint
|
lib/util/report-translator.js
|
assertValidNodeInfo
|
function assertValidNodeInfo(descriptor) {
if (descriptor.node) {
assert(typeof descriptor.node === "object", "Node must be an object");
} else {
assert(descriptor.loc, "Node must be provided when reporting error if location is not provided");
}
}
|
javascript
|
function assertValidNodeInfo(descriptor) {
if (descriptor.node) {
assert(typeof descriptor.node === "object", "Node must be an object");
} else {
assert(descriptor.loc, "Node must be provided when reporting error if location is not provided");
}
}
|
[
"function",
"assertValidNodeInfo",
"(",
"descriptor",
")",
"{",
"if",
"(",
"descriptor",
".",
"node",
")",
"{",
"assert",
"(",
"typeof",
"descriptor",
".",
"node",
"===",
"\"object\"",
",",
"\"Node must be an object\"",
")",
";",
"}",
"else",
"{",
"assert",
"(",
"descriptor",
".",
"loc",
",",
"\"Node must be provided when reporting error if location is not provided\"",
")",
";",
"}",
"}"
] |
Asserts that either a loc or a node was provided, and the node is valid if it was provided.
@param {MessageDescriptor} descriptor A descriptor to validate
@returns {void}
@throws AssertionError if neither a node nor a loc was provided, or if the node is not an object
|
[
"Asserts",
"that",
"either",
"a",
"loc",
"or",
"a",
"node",
"was",
"provided",
"and",
"the",
"node",
"is",
"valid",
"if",
"it",
"was",
"provided",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/util/report-translator.js#L92-L98
|
train
|
eslint/eslint
|
lib/util/report-translator.js
|
normalizeReportLoc
|
function normalizeReportLoc(descriptor) {
if (descriptor.loc) {
if (descriptor.loc.start) {
return descriptor.loc;
}
return { start: descriptor.loc, end: null };
}
return descriptor.node.loc;
}
|
javascript
|
function normalizeReportLoc(descriptor) {
if (descriptor.loc) {
if (descriptor.loc.start) {
return descriptor.loc;
}
return { start: descriptor.loc, end: null };
}
return descriptor.node.loc;
}
|
[
"function",
"normalizeReportLoc",
"(",
"descriptor",
")",
"{",
"if",
"(",
"descriptor",
".",
"loc",
")",
"{",
"if",
"(",
"descriptor",
".",
"loc",
".",
"start",
")",
"{",
"return",
"descriptor",
".",
"loc",
";",
"}",
"return",
"{",
"start",
":",
"descriptor",
".",
"loc",
",",
"end",
":",
"null",
"}",
";",
"}",
"return",
"descriptor",
".",
"node",
".",
"loc",
";",
"}"
] |
Normalizes a MessageDescriptor to always have a `loc` with `start` and `end` properties
@param {MessageDescriptor} descriptor A descriptor for the report from a rule.
@returns {{start: Location, end: (Location|null)}} An updated location that infers the `start` and `end` properties
from the `node` of the original descriptor, or infers the `start` from the `loc` of the original descriptor.
|
[
"Normalizes",
"a",
"MessageDescriptor",
"to",
"always",
"have",
"a",
"loc",
"with",
"start",
"and",
"end",
"properties"
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/util/report-translator.js#L106-L114
|
train
|
eslint/eslint
|
lib/util/report-translator.js
|
compareFixesByRange
|
function compareFixesByRange(a, b) {
return a.range[0] - b.range[0] || a.range[1] - b.range[1];
}
|
javascript
|
function compareFixesByRange(a, b) {
return a.range[0] - b.range[0] || a.range[1] - b.range[1];
}
|
[
"function",
"compareFixesByRange",
"(",
"a",
",",
"b",
")",
"{",
"return",
"a",
".",
"range",
"[",
"0",
"]",
"-",
"b",
".",
"range",
"[",
"0",
"]",
"||",
"a",
".",
"range",
"[",
"1",
"]",
"-",
"b",
".",
"range",
"[",
"1",
"]",
";",
"}"
] |
Compares items in a fixes array by range.
@param {Fix} a The first message.
@param {Fix} 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",
"fixes",
"array",
"by",
"range",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/util/report-translator.js#L123-L125
|
train
|
eslint/eslint
|
lib/util/report-translator.js
|
mergeFixes
|
function mergeFixes(fixes, sourceCode) {
if (fixes.length === 0) {
return null;
}
if (fixes.length === 1) {
return fixes[0];
}
fixes.sort(compareFixesByRange);
const originalText = sourceCode.text;
const start = fixes[0].range[0];
const end = fixes[fixes.length - 1].range[1];
let text = "";
let lastPos = Number.MIN_SAFE_INTEGER;
for (const fix of fixes) {
assert(fix.range[0] >= lastPos, "Fix objects must not be overlapped in a report.");
if (fix.range[0] >= 0) {
text += originalText.slice(Math.max(0, start, lastPos), fix.range[0]);
}
text += fix.text;
lastPos = fix.range[1];
}
text += originalText.slice(Math.max(0, start, lastPos), end);
return { range: [start, end], text };
}
|
javascript
|
function mergeFixes(fixes, sourceCode) {
if (fixes.length === 0) {
return null;
}
if (fixes.length === 1) {
return fixes[0];
}
fixes.sort(compareFixesByRange);
const originalText = sourceCode.text;
const start = fixes[0].range[0];
const end = fixes[fixes.length - 1].range[1];
let text = "";
let lastPos = Number.MIN_SAFE_INTEGER;
for (const fix of fixes) {
assert(fix.range[0] >= lastPos, "Fix objects must not be overlapped in a report.");
if (fix.range[0] >= 0) {
text += originalText.slice(Math.max(0, start, lastPos), fix.range[0]);
}
text += fix.text;
lastPos = fix.range[1];
}
text += originalText.slice(Math.max(0, start, lastPos), end);
return { range: [start, end], text };
}
|
[
"function",
"mergeFixes",
"(",
"fixes",
",",
"sourceCode",
")",
"{",
"if",
"(",
"fixes",
".",
"length",
"===",
"0",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"fixes",
".",
"length",
"===",
"1",
")",
"{",
"return",
"fixes",
"[",
"0",
"]",
";",
"}",
"fixes",
".",
"sort",
"(",
"compareFixesByRange",
")",
";",
"const",
"originalText",
"=",
"sourceCode",
".",
"text",
";",
"const",
"start",
"=",
"fixes",
"[",
"0",
"]",
".",
"range",
"[",
"0",
"]",
";",
"const",
"end",
"=",
"fixes",
"[",
"fixes",
".",
"length",
"-",
"1",
"]",
".",
"range",
"[",
"1",
"]",
";",
"let",
"text",
"=",
"\"\"",
";",
"let",
"lastPos",
"=",
"Number",
".",
"MIN_SAFE_INTEGER",
";",
"for",
"(",
"const",
"fix",
"of",
"fixes",
")",
"{",
"assert",
"(",
"fix",
".",
"range",
"[",
"0",
"]",
">=",
"lastPos",
",",
"\"Fix objects must not be overlapped in a report.\"",
")",
";",
"if",
"(",
"fix",
".",
"range",
"[",
"0",
"]",
">=",
"0",
")",
"{",
"text",
"+=",
"originalText",
".",
"slice",
"(",
"Math",
".",
"max",
"(",
"0",
",",
"start",
",",
"lastPos",
")",
",",
"fix",
".",
"range",
"[",
"0",
"]",
")",
";",
"}",
"text",
"+=",
"fix",
".",
"text",
";",
"lastPos",
"=",
"fix",
".",
"range",
"[",
"1",
"]",
";",
"}",
"text",
"+=",
"originalText",
".",
"slice",
"(",
"Math",
".",
"max",
"(",
"0",
",",
"start",
",",
"lastPos",
")",
",",
"end",
")",
";",
"return",
"{",
"range",
":",
"[",
"start",
",",
"end",
"]",
",",
"text",
"}",
";",
"}"
] |
Merges the given fixes array into one.
@param {Fix[]} fixes The fixes to merge.
@param {SourceCode} sourceCode The source code object to get the text between fixes.
@returns {{text: string, range: number[]}} The merged fixes
|
[
"Merges",
"the",
"given",
"fixes",
"array",
"into",
"one",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/util/report-translator.js#L133-L161
|
train
|
eslint/eslint
|
lib/util/report-translator.js
|
normalizeFixes
|
function normalizeFixes(descriptor, sourceCode) {
if (typeof descriptor.fix !== "function") {
return null;
}
// @type {null | Fix | Fix[] | IterableIterator<Fix>}
const fix = descriptor.fix(ruleFixer);
// Merge to one.
if (fix && Symbol.iterator in fix) {
return mergeFixes(Array.from(fix), sourceCode);
}
return fix;
}
|
javascript
|
function normalizeFixes(descriptor, sourceCode) {
if (typeof descriptor.fix !== "function") {
return null;
}
// @type {null | Fix | Fix[] | IterableIterator<Fix>}
const fix = descriptor.fix(ruleFixer);
// Merge to one.
if (fix && Symbol.iterator in fix) {
return mergeFixes(Array.from(fix), sourceCode);
}
return fix;
}
|
[
"function",
"normalizeFixes",
"(",
"descriptor",
",",
"sourceCode",
")",
"{",
"if",
"(",
"typeof",
"descriptor",
".",
"fix",
"!==",
"\"function\"",
")",
"{",
"return",
"null",
";",
"}",
"const",
"fix",
"=",
"descriptor",
".",
"fix",
"(",
"ruleFixer",
")",
";",
"if",
"(",
"fix",
"&&",
"Symbol",
".",
"iterator",
"in",
"fix",
")",
"{",
"return",
"mergeFixes",
"(",
"Array",
".",
"from",
"(",
"fix",
")",
",",
"sourceCode",
")",
";",
"}",
"return",
"fix",
";",
"}"
] |
Gets one fix object from the given descriptor.
If the descriptor retrieves multiple fixes, this merges those to one.
@param {MessageDescriptor} descriptor The report descriptor.
@param {SourceCode} sourceCode The source code object to get text between fixes.
@returns {({text: string, range: number[]}|null)} The fix for the descriptor
|
[
"Gets",
"one",
"fix",
"object",
"from",
"the",
"given",
"descriptor",
".",
"If",
"the",
"descriptor",
"retrieves",
"multiple",
"fixes",
"this",
"merges",
"those",
"to",
"one",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/util/report-translator.js#L170-L183
|
train
|
eslint/eslint
|
lib/util/report-translator.js
|
createProblem
|
function createProblem(options) {
const problem = {
ruleId: options.ruleId,
severity: options.severity,
message: options.message,
line: options.loc.start.line,
column: options.loc.start.column + 1,
nodeType: options.node && options.node.type || null
};
/*
* If this isn’t in the conditional, some of the tests fail
* because `messageId` is present in the problem object
*/
if (options.messageId) {
problem.messageId = options.messageId;
}
if (options.loc.end) {
problem.endLine = options.loc.end.line;
problem.endColumn = options.loc.end.column + 1;
}
if (options.fix) {
problem.fix = options.fix;
}
return problem;
}
|
javascript
|
function createProblem(options) {
const problem = {
ruleId: options.ruleId,
severity: options.severity,
message: options.message,
line: options.loc.start.line,
column: options.loc.start.column + 1,
nodeType: options.node && options.node.type || null
};
/*
* If this isn’t in the conditional, some of the tests fail
* because `messageId` is present in the problem object
*/
if (options.messageId) {
problem.messageId = options.messageId;
}
if (options.loc.end) {
problem.endLine = options.loc.end.line;
problem.endColumn = options.loc.end.column + 1;
}
if (options.fix) {
problem.fix = options.fix;
}
return problem;
}
|
[
"function",
"createProblem",
"(",
"options",
")",
"{",
"const",
"problem",
"=",
"{",
"ruleId",
":",
"options",
".",
"ruleId",
",",
"severity",
":",
"options",
".",
"severity",
",",
"message",
":",
"options",
".",
"message",
",",
"line",
":",
"options",
".",
"loc",
".",
"start",
".",
"line",
",",
"column",
":",
"options",
".",
"loc",
".",
"start",
".",
"column",
"+",
"1",
",",
"nodeType",
":",
"options",
".",
"node",
"&&",
"options",
".",
"node",
".",
"type",
"||",
"null",
"}",
";",
"if",
"(",
"options",
".",
"messageId",
")",
"{",
"problem",
".",
"messageId",
"=",
"options",
".",
"messageId",
";",
"}",
"if",
"(",
"options",
".",
"loc",
".",
"end",
")",
"{",
"problem",
".",
"endLine",
"=",
"options",
".",
"loc",
".",
"end",
".",
"line",
";",
"problem",
".",
"endColumn",
"=",
"options",
".",
"loc",
".",
"end",
".",
"column",
"+",
"1",
";",
"}",
"if",
"(",
"options",
".",
"fix",
")",
"{",
"problem",
".",
"fix",
"=",
"options",
".",
"fix",
";",
"}",
"return",
"problem",
";",
"}"
] |
Creates information about the report from a descriptor
@param {Object} options Information about the problem
@param {string} options.ruleId Rule ID
@param {(0|1|2)} options.severity Rule severity
@param {(ASTNode|null)} options.node Node
@param {string} options.message Error message
@param {string} [options.messageId] The error message ID.
@param {{start: SourceLocation, end: (SourceLocation|null)}} options.loc Start and end location
@param {{text: string, range: (number[]|null)}} options.fix The fix object
@returns {function(...args): ReportInfo} Function that returns information about the report
|
[
"Creates",
"information",
"about",
"the",
"report",
"from",
"a",
"descriptor"
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/util/report-translator.js#L197-L225
|
train
|
eslint/eslint
|
lib/rules/arrow-parens.js
|
parens
|
function parens(node) {
const isAsync = node.async;
const firstTokenOfParam = sourceCode.getFirstToken(node, isAsync ? 1 : 0);
/**
* Remove the parenthesis around a parameter
* @param {Fixer} fixer Fixer
* @returns {string} fixed parameter
*/
function fixParamsWithParenthesis(fixer) {
const paramToken = sourceCode.getTokenAfter(firstTokenOfParam);
/*
* ES8 allows Trailing commas in function parameter lists and calls
* https://github.com/eslint/eslint/issues/8834
*/
const closingParenToken = sourceCode.getTokenAfter(paramToken, astUtils.isClosingParenToken);
const asyncToken = isAsync ? sourceCode.getTokenBefore(firstTokenOfParam) : null;
const shouldAddSpaceForAsync = asyncToken && (asyncToken.range[1] === firstTokenOfParam.range[0]);
return fixer.replaceTextRange([
firstTokenOfParam.range[0],
closingParenToken.range[1]
], `${shouldAddSpaceForAsync ? " " : ""}${paramToken.value}`);
}
// "as-needed", { "requireForBlockBody": true }: x => x
if (
requireForBlockBody &&
node.params.length === 1 &&
node.params[0].type === "Identifier" &&
!node.params[0].typeAnnotation &&
node.body.type !== "BlockStatement" &&
!node.returnType
) {
if (astUtils.isOpeningParenToken(firstTokenOfParam)) {
context.report({
node,
messageId: "unexpectedParensInline",
fix: fixParamsWithParenthesis
});
}
return;
}
if (
requireForBlockBody &&
node.body.type === "BlockStatement"
) {
if (!astUtils.isOpeningParenToken(firstTokenOfParam)) {
context.report({
node,
messageId: "expectedParensBlock",
fix(fixer) {
return fixer.replaceText(firstTokenOfParam, `(${firstTokenOfParam.value})`);
}
});
}
return;
}
// "as-needed": x => x
if (asNeeded &&
node.params.length === 1 &&
node.params[0].type === "Identifier" &&
!node.params[0].typeAnnotation &&
!node.returnType
) {
if (astUtils.isOpeningParenToken(firstTokenOfParam)) {
context.report({
node,
messageId: "unexpectedParens",
fix: fixParamsWithParenthesis
});
}
return;
}
if (firstTokenOfParam.type === "Identifier") {
const after = sourceCode.getTokenAfter(firstTokenOfParam);
// (x) => x
if (after.value !== ")") {
context.report({
node,
messageId: "expectedParens",
fix(fixer) {
return fixer.replaceText(firstTokenOfParam, `(${firstTokenOfParam.value})`);
}
});
}
}
}
|
javascript
|
function parens(node) {
const isAsync = node.async;
const firstTokenOfParam = sourceCode.getFirstToken(node, isAsync ? 1 : 0);
/**
* Remove the parenthesis around a parameter
* @param {Fixer} fixer Fixer
* @returns {string} fixed parameter
*/
function fixParamsWithParenthesis(fixer) {
const paramToken = sourceCode.getTokenAfter(firstTokenOfParam);
/*
* ES8 allows Trailing commas in function parameter lists and calls
* https://github.com/eslint/eslint/issues/8834
*/
const closingParenToken = sourceCode.getTokenAfter(paramToken, astUtils.isClosingParenToken);
const asyncToken = isAsync ? sourceCode.getTokenBefore(firstTokenOfParam) : null;
const shouldAddSpaceForAsync = asyncToken && (asyncToken.range[1] === firstTokenOfParam.range[0]);
return fixer.replaceTextRange([
firstTokenOfParam.range[0],
closingParenToken.range[1]
], `${shouldAddSpaceForAsync ? " " : ""}${paramToken.value}`);
}
// "as-needed", { "requireForBlockBody": true }: x => x
if (
requireForBlockBody &&
node.params.length === 1 &&
node.params[0].type === "Identifier" &&
!node.params[0].typeAnnotation &&
node.body.type !== "BlockStatement" &&
!node.returnType
) {
if (astUtils.isOpeningParenToken(firstTokenOfParam)) {
context.report({
node,
messageId: "unexpectedParensInline",
fix: fixParamsWithParenthesis
});
}
return;
}
if (
requireForBlockBody &&
node.body.type === "BlockStatement"
) {
if (!astUtils.isOpeningParenToken(firstTokenOfParam)) {
context.report({
node,
messageId: "expectedParensBlock",
fix(fixer) {
return fixer.replaceText(firstTokenOfParam, `(${firstTokenOfParam.value})`);
}
});
}
return;
}
// "as-needed": x => x
if (asNeeded &&
node.params.length === 1 &&
node.params[0].type === "Identifier" &&
!node.params[0].typeAnnotation &&
!node.returnType
) {
if (astUtils.isOpeningParenToken(firstTokenOfParam)) {
context.report({
node,
messageId: "unexpectedParens",
fix: fixParamsWithParenthesis
});
}
return;
}
if (firstTokenOfParam.type === "Identifier") {
const after = sourceCode.getTokenAfter(firstTokenOfParam);
// (x) => x
if (after.value !== ")") {
context.report({
node,
messageId: "expectedParens",
fix(fixer) {
return fixer.replaceText(firstTokenOfParam, `(${firstTokenOfParam.value})`);
}
});
}
}
}
|
[
"function",
"parens",
"(",
"node",
")",
"{",
"const",
"isAsync",
"=",
"node",
".",
"async",
";",
"const",
"firstTokenOfParam",
"=",
"sourceCode",
".",
"getFirstToken",
"(",
"node",
",",
"isAsync",
"?",
"1",
":",
"0",
")",
";",
"function",
"fixParamsWithParenthesis",
"(",
"fixer",
")",
"{",
"const",
"paramToken",
"=",
"sourceCode",
".",
"getTokenAfter",
"(",
"firstTokenOfParam",
")",
";",
"const",
"closingParenToken",
"=",
"sourceCode",
".",
"getTokenAfter",
"(",
"paramToken",
",",
"astUtils",
".",
"isClosingParenToken",
")",
";",
"const",
"asyncToken",
"=",
"isAsync",
"?",
"sourceCode",
".",
"getTokenBefore",
"(",
"firstTokenOfParam",
")",
":",
"null",
";",
"const",
"shouldAddSpaceForAsync",
"=",
"asyncToken",
"&&",
"(",
"asyncToken",
".",
"range",
"[",
"1",
"]",
"===",
"firstTokenOfParam",
".",
"range",
"[",
"0",
"]",
")",
";",
"return",
"fixer",
".",
"replaceTextRange",
"(",
"[",
"firstTokenOfParam",
".",
"range",
"[",
"0",
"]",
",",
"closingParenToken",
".",
"range",
"[",
"1",
"]",
"]",
",",
"`",
"${",
"shouldAddSpaceForAsync",
"?",
"\" \"",
":",
"\"\"",
"}",
"${",
"paramToken",
".",
"value",
"}",
"`",
")",
";",
"}",
"if",
"(",
"requireForBlockBody",
"&&",
"node",
".",
"params",
".",
"length",
"===",
"1",
"&&",
"node",
".",
"params",
"[",
"0",
"]",
".",
"type",
"===",
"\"Identifier\"",
"&&",
"!",
"node",
".",
"params",
"[",
"0",
"]",
".",
"typeAnnotation",
"&&",
"node",
".",
"body",
".",
"type",
"!==",
"\"BlockStatement\"",
"&&",
"!",
"node",
".",
"returnType",
")",
"{",
"if",
"(",
"astUtils",
".",
"isOpeningParenToken",
"(",
"firstTokenOfParam",
")",
")",
"{",
"context",
".",
"report",
"(",
"{",
"node",
",",
"messageId",
":",
"\"unexpectedParensInline\"",
",",
"fix",
":",
"fixParamsWithParenthesis",
"}",
")",
";",
"}",
"return",
";",
"}",
"if",
"(",
"requireForBlockBody",
"&&",
"node",
".",
"body",
".",
"type",
"===",
"\"BlockStatement\"",
")",
"{",
"if",
"(",
"!",
"astUtils",
".",
"isOpeningParenToken",
"(",
"firstTokenOfParam",
")",
")",
"{",
"context",
".",
"report",
"(",
"{",
"node",
",",
"messageId",
":",
"\"expectedParensBlock\"",
",",
"fix",
"(",
"fixer",
")",
"{",
"return",
"fixer",
".",
"replaceText",
"(",
"firstTokenOfParam",
",",
"`",
"${",
"firstTokenOfParam",
".",
"value",
"}",
"`",
")",
";",
"}",
"}",
")",
";",
"}",
"return",
";",
"}",
"if",
"(",
"asNeeded",
"&&",
"node",
".",
"params",
".",
"length",
"===",
"1",
"&&",
"node",
".",
"params",
"[",
"0",
"]",
".",
"type",
"===",
"\"Identifier\"",
"&&",
"!",
"node",
".",
"params",
"[",
"0",
"]",
".",
"typeAnnotation",
"&&",
"!",
"node",
".",
"returnType",
")",
"{",
"if",
"(",
"astUtils",
".",
"isOpeningParenToken",
"(",
"firstTokenOfParam",
")",
")",
"{",
"context",
".",
"report",
"(",
"{",
"node",
",",
"messageId",
":",
"\"unexpectedParens\"",
",",
"fix",
":",
"fixParamsWithParenthesis",
"}",
")",
";",
"}",
"return",
";",
"}",
"if",
"(",
"firstTokenOfParam",
".",
"type",
"===",
"\"Identifier\"",
")",
"{",
"const",
"after",
"=",
"sourceCode",
".",
"getTokenAfter",
"(",
"firstTokenOfParam",
")",
";",
"if",
"(",
"after",
".",
"value",
"!==",
"\")\"",
")",
"{",
"context",
".",
"report",
"(",
"{",
"node",
",",
"messageId",
":",
"\"expectedParens\"",
",",
"fix",
"(",
"fixer",
")",
"{",
"return",
"fixer",
".",
"replaceText",
"(",
"firstTokenOfParam",
",",
"`",
"${",
"firstTokenOfParam",
".",
"value",
"}",
"`",
")",
";",
"}",
"}",
")",
";",
"}",
"}",
"}"
] |
Determines whether a arrow function argument end with `)`
@param {ASTNode} node The arrow function node.
@returns {void}
|
[
"Determines",
"whether",
"a",
"arrow",
"function",
"argument",
"end",
"with",
")"
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/arrow-parens.js#L66-L158
|
train
|
eslint/eslint
|
lib/rules/arrow-parens.js
|
fixParamsWithParenthesis
|
function fixParamsWithParenthesis(fixer) {
const paramToken = sourceCode.getTokenAfter(firstTokenOfParam);
/*
* ES8 allows Trailing commas in function parameter lists and calls
* https://github.com/eslint/eslint/issues/8834
*/
const closingParenToken = sourceCode.getTokenAfter(paramToken, astUtils.isClosingParenToken);
const asyncToken = isAsync ? sourceCode.getTokenBefore(firstTokenOfParam) : null;
const shouldAddSpaceForAsync = asyncToken && (asyncToken.range[1] === firstTokenOfParam.range[0]);
return fixer.replaceTextRange([
firstTokenOfParam.range[0],
closingParenToken.range[1]
], `${shouldAddSpaceForAsync ? " " : ""}${paramToken.value}`);
}
|
javascript
|
function fixParamsWithParenthesis(fixer) {
const paramToken = sourceCode.getTokenAfter(firstTokenOfParam);
/*
* ES8 allows Trailing commas in function parameter lists and calls
* https://github.com/eslint/eslint/issues/8834
*/
const closingParenToken = sourceCode.getTokenAfter(paramToken, astUtils.isClosingParenToken);
const asyncToken = isAsync ? sourceCode.getTokenBefore(firstTokenOfParam) : null;
const shouldAddSpaceForAsync = asyncToken && (asyncToken.range[1] === firstTokenOfParam.range[0]);
return fixer.replaceTextRange([
firstTokenOfParam.range[0],
closingParenToken.range[1]
], `${shouldAddSpaceForAsync ? " " : ""}${paramToken.value}`);
}
|
[
"function",
"fixParamsWithParenthesis",
"(",
"fixer",
")",
"{",
"const",
"paramToken",
"=",
"sourceCode",
".",
"getTokenAfter",
"(",
"firstTokenOfParam",
")",
";",
"const",
"closingParenToken",
"=",
"sourceCode",
".",
"getTokenAfter",
"(",
"paramToken",
",",
"astUtils",
".",
"isClosingParenToken",
")",
";",
"const",
"asyncToken",
"=",
"isAsync",
"?",
"sourceCode",
".",
"getTokenBefore",
"(",
"firstTokenOfParam",
")",
":",
"null",
";",
"const",
"shouldAddSpaceForAsync",
"=",
"asyncToken",
"&&",
"(",
"asyncToken",
".",
"range",
"[",
"1",
"]",
"===",
"firstTokenOfParam",
".",
"range",
"[",
"0",
"]",
")",
";",
"return",
"fixer",
".",
"replaceTextRange",
"(",
"[",
"firstTokenOfParam",
".",
"range",
"[",
"0",
"]",
",",
"closingParenToken",
".",
"range",
"[",
"1",
"]",
"]",
",",
"`",
"${",
"shouldAddSpaceForAsync",
"?",
"\" \"",
":",
"\"\"",
"}",
"${",
"paramToken",
".",
"value",
"}",
"`",
")",
";",
"}"
] |
Remove the parenthesis around a parameter
@param {Fixer} fixer Fixer
@returns {string} fixed parameter
|
[
"Remove",
"the",
"parenthesis",
"around",
"a",
"parameter"
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/arrow-parens.js#L75-L90
|
train
|
eslint/eslint
|
lib/rules/no-self-assign.js
|
isSameProperty
|
function isSameProperty(left, right) {
if (left.property.type === "Identifier" &&
left.property.type === right.property.type &&
left.property.name === right.property.name &&
left.computed === right.computed
) {
return true;
}
const lname = astUtils.getStaticPropertyName(left);
const rname = astUtils.getStaticPropertyName(right);
return lname !== null && lname === rname;
}
|
javascript
|
function isSameProperty(left, right) {
if (left.property.type === "Identifier" &&
left.property.type === right.property.type &&
left.property.name === right.property.name &&
left.computed === right.computed
) {
return true;
}
const lname = astUtils.getStaticPropertyName(left);
const rname = astUtils.getStaticPropertyName(right);
return lname !== null && lname === rname;
}
|
[
"function",
"isSameProperty",
"(",
"left",
",",
"right",
")",
"{",
"if",
"(",
"left",
".",
"property",
".",
"type",
"===",
"\"Identifier\"",
"&&",
"left",
".",
"property",
".",
"type",
"===",
"right",
".",
"property",
".",
"type",
"&&",
"left",
".",
"property",
".",
"name",
"===",
"right",
".",
"property",
".",
"name",
"&&",
"left",
".",
"computed",
"===",
"right",
".",
"computed",
")",
"{",
"return",
"true",
";",
"}",
"const",
"lname",
"=",
"astUtils",
".",
"getStaticPropertyName",
"(",
"left",
")",
";",
"const",
"rname",
"=",
"astUtils",
".",
"getStaticPropertyName",
"(",
"right",
")",
";",
"return",
"lname",
"!==",
"null",
"&&",
"lname",
"===",
"rname",
";",
"}"
] |
Checks whether the property of 2 given member expression nodes are the same
property or not.
@param {ASTNode} left - A member expression node to check.
@param {ASTNode} right - Another member expression node to check.
@returns {boolean} `true` if the member expressions have the same property.
|
[
"Checks",
"whether",
"the",
"property",
"of",
"2",
"given",
"member",
"expression",
"nodes",
"are",
"the",
"same",
"property",
"or",
"not",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-self-assign.js#L28-L41
|
train
|
eslint/eslint
|
lib/rules/no-self-assign.js
|
isSameMember
|
function isSameMember(left, right) {
if (!isSameProperty(left, right)) {
return false;
}
const lobj = left.object;
const robj = right.object;
if (lobj.type !== robj.type) {
return false;
}
if (lobj.type === "MemberExpression") {
return isSameMember(lobj, robj);
}
return lobj.type === "Identifier" && lobj.name === robj.name;
}
|
javascript
|
function isSameMember(left, right) {
if (!isSameProperty(left, right)) {
return false;
}
const lobj = left.object;
const robj = right.object;
if (lobj.type !== robj.type) {
return false;
}
if (lobj.type === "MemberExpression") {
return isSameMember(lobj, robj);
}
return lobj.type === "Identifier" && lobj.name === robj.name;
}
|
[
"function",
"isSameMember",
"(",
"left",
",",
"right",
")",
"{",
"if",
"(",
"!",
"isSameProperty",
"(",
"left",
",",
"right",
")",
")",
"{",
"return",
"false",
";",
"}",
"const",
"lobj",
"=",
"left",
".",
"object",
";",
"const",
"robj",
"=",
"right",
".",
"object",
";",
"if",
"(",
"lobj",
".",
"type",
"!==",
"robj",
".",
"type",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"lobj",
".",
"type",
"===",
"\"MemberExpression\"",
")",
"{",
"return",
"isSameMember",
"(",
"lobj",
",",
"robj",
")",
";",
"}",
"return",
"lobj",
".",
"type",
"===",
"\"Identifier\"",
"&&",
"lobj",
".",
"name",
"===",
"robj",
".",
"name",
";",
"}"
] |
Checks whether 2 given member expression nodes are the reference to the same
property or not.
@param {ASTNode} left - A member expression node to check.
@param {ASTNode} right - Another member expression node to check.
@returns {boolean} `true` if the member expressions are the reference to the
same property or not.
|
[
"Checks",
"whether",
"2",
"given",
"member",
"expression",
"nodes",
"are",
"the",
"reference",
"to",
"the",
"same",
"property",
"or",
"not",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-self-assign.js#L52-L67
|
train
|
eslint/eslint
|
lib/rules/no-self-assign.js
|
eachSelfAssignment
|
function eachSelfAssignment(left, right, props, report) {
if (!left || !right) {
// do nothing
} else if (
left.type === "Identifier" &&
right.type === "Identifier" &&
left.name === right.name
) {
report(right);
} else if (
left.type === "ArrayPattern" &&
right.type === "ArrayExpression"
) {
const end = Math.min(left.elements.length, right.elements.length);
for (let i = 0; i < end; ++i) {
const rightElement = right.elements[i];
eachSelfAssignment(left.elements[i], rightElement, props, report);
// After a spread element, those indices are unknown.
if (rightElement && rightElement.type === "SpreadElement") {
break;
}
}
} else if (
left.type === "RestElement" &&
right.type === "SpreadElement"
) {
eachSelfAssignment(left.argument, right.argument, props, report);
} else if (
left.type === "ObjectPattern" &&
right.type === "ObjectExpression" &&
right.properties.length >= 1
) {
/*
* Gets the index of the last spread property.
* It's possible to overwrite properties followed by it.
*/
let startJ = 0;
for (let i = right.properties.length - 1; i >= 0; --i) {
const propType = right.properties[i].type;
if (propType === "SpreadElement" || propType === "ExperimentalSpreadProperty") {
startJ = i + 1;
break;
}
}
for (let i = 0; i < left.properties.length; ++i) {
for (let j = startJ; j < right.properties.length; ++j) {
eachSelfAssignment(
left.properties[i],
right.properties[j],
props,
report
);
}
}
} else if (
left.type === "Property" &&
right.type === "Property" &&
!left.computed &&
!right.computed &&
right.kind === "init" &&
!right.method &&
left.key.name === right.key.name
) {
eachSelfAssignment(left.value, right.value, props, report);
} else if (
props &&
left.type === "MemberExpression" &&
right.type === "MemberExpression" &&
isSameMember(left, right)
) {
report(right);
}
}
|
javascript
|
function eachSelfAssignment(left, right, props, report) {
if (!left || !right) {
// do nothing
} else if (
left.type === "Identifier" &&
right.type === "Identifier" &&
left.name === right.name
) {
report(right);
} else if (
left.type === "ArrayPattern" &&
right.type === "ArrayExpression"
) {
const end = Math.min(left.elements.length, right.elements.length);
for (let i = 0; i < end; ++i) {
const rightElement = right.elements[i];
eachSelfAssignment(left.elements[i], rightElement, props, report);
// After a spread element, those indices are unknown.
if (rightElement && rightElement.type === "SpreadElement") {
break;
}
}
} else if (
left.type === "RestElement" &&
right.type === "SpreadElement"
) {
eachSelfAssignment(left.argument, right.argument, props, report);
} else if (
left.type === "ObjectPattern" &&
right.type === "ObjectExpression" &&
right.properties.length >= 1
) {
/*
* Gets the index of the last spread property.
* It's possible to overwrite properties followed by it.
*/
let startJ = 0;
for (let i = right.properties.length - 1; i >= 0; --i) {
const propType = right.properties[i].type;
if (propType === "SpreadElement" || propType === "ExperimentalSpreadProperty") {
startJ = i + 1;
break;
}
}
for (let i = 0; i < left.properties.length; ++i) {
for (let j = startJ; j < right.properties.length; ++j) {
eachSelfAssignment(
left.properties[i],
right.properties[j],
props,
report
);
}
}
} else if (
left.type === "Property" &&
right.type === "Property" &&
!left.computed &&
!right.computed &&
right.kind === "init" &&
!right.method &&
left.key.name === right.key.name
) {
eachSelfAssignment(left.value, right.value, props, report);
} else if (
props &&
left.type === "MemberExpression" &&
right.type === "MemberExpression" &&
isSameMember(left, right)
) {
report(right);
}
}
|
[
"function",
"eachSelfAssignment",
"(",
"left",
",",
"right",
",",
"props",
",",
"report",
")",
"{",
"if",
"(",
"!",
"left",
"||",
"!",
"right",
")",
"{",
"}",
"else",
"if",
"(",
"left",
".",
"type",
"===",
"\"Identifier\"",
"&&",
"right",
".",
"type",
"===",
"\"Identifier\"",
"&&",
"left",
".",
"name",
"===",
"right",
".",
"name",
")",
"{",
"report",
"(",
"right",
")",
";",
"}",
"else",
"if",
"(",
"left",
".",
"type",
"===",
"\"ArrayPattern\"",
"&&",
"right",
".",
"type",
"===",
"\"ArrayExpression\"",
")",
"{",
"const",
"end",
"=",
"Math",
".",
"min",
"(",
"left",
".",
"elements",
".",
"length",
",",
"right",
".",
"elements",
".",
"length",
")",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"end",
";",
"++",
"i",
")",
"{",
"const",
"rightElement",
"=",
"right",
".",
"elements",
"[",
"i",
"]",
";",
"eachSelfAssignment",
"(",
"left",
".",
"elements",
"[",
"i",
"]",
",",
"rightElement",
",",
"props",
",",
"report",
")",
";",
"if",
"(",
"rightElement",
"&&",
"rightElement",
".",
"type",
"===",
"\"SpreadElement\"",
")",
"{",
"break",
";",
"}",
"}",
"}",
"else",
"if",
"(",
"left",
".",
"type",
"===",
"\"RestElement\"",
"&&",
"right",
".",
"type",
"===",
"\"SpreadElement\"",
")",
"{",
"eachSelfAssignment",
"(",
"left",
".",
"argument",
",",
"right",
".",
"argument",
",",
"props",
",",
"report",
")",
";",
"}",
"else",
"if",
"(",
"left",
".",
"type",
"===",
"\"ObjectPattern\"",
"&&",
"right",
".",
"type",
"===",
"\"ObjectExpression\"",
"&&",
"right",
".",
"properties",
".",
"length",
">=",
"1",
")",
"{",
"let",
"startJ",
"=",
"0",
";",
"for",
"(",
"let",
"i",
"=",
"right",
".",
"properties",
".",
"length",
"-",
"1",
";",
"i",
">=",
"0",
";",
"--",
"i",
")",
"{",
"const",
"propType",
"=",
"right",
".",
"properties",
"[",
"i",
"]",
".",
"type",
";",
"if",
"(",
"propType",
"===",
"\"SpreadElement\"",
"||",
"propType",
"===",
"\"ExperimentalSpreadProperty\"",
")",
"{",
"startJ",
"=",
"i",
"+",
"1",
";",
"break",
";",
"}",
"}",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"left",
".",
"properties",
".",
"length",
";",
"++",
"i",
")",
"{",
"for",
"(",
"let",
"j",
"=",
"startJ",
";",
"j",
"<",
"right",
".",
"properties",
".",
"length",
";",
"++",
"j",
")",
"{",
"eachSelfAssignment",
"(",
"left",
".",
"properties",
"[",
"i",
"]",
",",
"right",
".",
"properties",
"[",
"j",
"]",
",",
"props",
",",
"report",
")",
";",
"}",
"}",
"}",
"else",
"if",
"(",
"left",
".",
"type",
"===",
"\"Property\"",
"&&",
"right",
".",
"type",
"===",
"\"Property\"",
"&&",
"!",
"left",
".",
"computed",
"&&",
"!",
"right",
".",
"computed",
"&&",
"right",
".",
"kind",
"===",
"\"init\"",
"&&",
"!",
"right",
".",
"method",
"&&",
"left",
".",
"key",
".",
"name",
"===",
"right",
".",
"key",
".",
"name",
")",
"{",
"eachSelfAssignment",
"(",
"left",
".",
"value",
",",
"right",
".",
"value",
",",
"props",
",",
"report",
")",
";",
"}",
"else",
"if",
"(",
"props",
"&&",
"left",
".",
"type",
"===",
"\"MemberExpression\"",
"&&",
"right",
".",
"type",
"===",
"\"MemberExpression\"",
"&&",
"isSameMember",
"(",
"left",
",",
"right",
")",
")",
"{",
"report",
"(",
"right",
")",
";",
"}",
"}"
] |
Traverses 2 Pattern nodes in parallel, then reports self-assignments.
@param {ASTNode|null} left - A left node to traverse. This is a Pattern or
a Property.
@param {ASTNode|null} right - A right node to traverse. This is a Pattern or
a Property.
@param {boolean} props - The flag to check member expressions as well.
@param {Function} report - A callback function to report.
@returns {void}
|
[
"Traverses",
"2",
"Pattern",
"nodes",
"in",
"parallel",
"then",
"reports",
"self",
"-",
"assignments",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-self-assign.js#L80-L160
|
train
|
eslint/eslint
|
lib/rules/no-self-assign.js
|
report
|
function report(node) {
context.report({
node,
message: "'{{name}}' is assigned to itself.",
data: {
name: sourceCode.getText(node).replace(SPACES, "")
}
});
}
|
javascript
|
function report(node) {
context.report({
node,
message: "'{{name}}' is assigned to itself.",
data: {
name: sourceCode.getText(node).replace(SPACES, "")
}
});
}
|
[
"function",
"report",
"(",
"node",
")",
"{",
"context",
".",
"report",
"(",
"{",
"node",
",",
"message",
":",
"\"'{{name}}' is assigned to itself.\"",
",",
"data",
":",
"{",
"name",
":",
"sourceCode",
".",
"getText",
"(",
"node",
")",
".",
"replace",
"(",
"SPACES",
",",
"\"\"",
")",
"}",
"}",
")",
";",
"}"
] |
Reports a given node as self assignments.
@param {ASTNode} node - A node to report. This is an Identifier node.
@returns {void}
|
[
"Reports",
"a",
"given",
"node",
"as",
"self",
"assignments",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-self-assign.js#L201-L209
|
train
|
eslint/eslint
|
lib/rules/comma-style.js
|
getFixerFunction
|
function getFixerFunction(styleType, previousItemToken, commaToken, currentItemToken) {
const text =
sourceCode.text.slice(previousItemToken.range[1], commaToken.range[0]) +
sourceCode.text.slice(commaToken.range[1], currentItemToken.range[0]);
const range = [previousItemToken.range[1], currentItemToken.range[0]];
return function(fixer) {
return fixer.replaceTextRange(range, getReplacedText(styleType, text));
};
}
|
javascript
|
function getFixerFunction(styleType, previousItemToken, commaToken, currentItemToken) {
const text =
sourceCode.text.slice(previousItemToken.range[1], commaToken.range[0]) +
sourceCode.text.slice(commaToken.range[1], currentItemToken.range[0]);
const range = [previousItemToken.range[1], currentItemToken.range[0]];
return function(fixer) {
return fixer.replaceTextRange(range, getReplacedText(styleType, text));
};
}
|
[
"function",
"getFixerFunction",
"(",
"styleType",
",",
"previousItemToken",
",",
"commaToken",
",",
"currentItemToken",
")",
"{",
"const",
"text",
"=",
"sourceCode",
".",
"text",
".",
"slice",
"(",
"previousItemToken",
".",
"range",
"[",
"1",
"]",
",",
"commaToken",
".",
"range",
"[",
"0",
"]",
")",
"+",
"sourceCode",
".",
"text",
".",
"slice",
"(",
"commaToken",
".",
"range",
"[",
"1",
"]",
",",
"currentItemToken",
".",
"range",
"[",
"0",
"]",
")",
";",
"const",
"range",
"=",
"[",
"previousItemToken",
".",
"range",
"[",
"1",
"]",
",",
"currentItemToken",
".",
"range",
"[",
"0",
"]",
"]",
";",
"return",
"function",
"(",
"fixer",
")",
"{",
"return",
"fixer",
".",
"replaceTextRange",
"(",
"range",
",",
"getReplacedText",
"(",
"styleType",
",",
"text",
")",
")",
";",
"}",
";",
"}"
] |
Determines the fixer function for a given style.
@param {string} styleType comma style
@param {ASTNode} previousItemToken The token to check.
@param {ASTNode} commaToken The token to check.
@param {ASTNode} currentItemToken The token to check.
@returns {Function} Fixer function
@private
|
[
"Determines",
"the",
"fixer",
"function",
"for",
"a",
"given",
"style",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/comma-style.js#L110-L119
|
train
|
eslint/eslint
|
lib/rules/comma-style.js
|
validateCommaItemSpacing
|
function validateCommaItemSpacing(previousItemToken, commaToken, currentItemToken, reportItem) {
// if single line
if (astUtils.isTokenOnSameLine(commaToken, currentItemToken) &&
astUtils.isTokenOnSameLine(previousItemToken, commaToken)) {
// do nothing.
} else if (!astUtils.isTokenOnSameLine(commaToken, currentItemToken) &&
!astUtils.isTokenOnSameLine(previousItemToken, commaToken)) {
const comment = sourceCode.getCommentsAfter(commaToken)[0];
const styleType = comment && comment.type === "Block" && astUtils.isTokenOnSameLine(commaToken, comment)
? style
: "between";
// lone comma
context.report({
node: reportItem,
loc: {
line: commaToken.loc.end.line,
column: commaToken.loc.start.column
},
messageId: "unexpectedLineBeforeAndAfterComma",
fix: getFixerFunction(styleType, previousItemToken, commaToken, currentItemToken)
});
} else if (style === "first" && !astUtils.isTokenOnSameLine(commaToken, currentItemToken)) {
context.report({
node: reportItem,
messageId: "expectedCommaFirst",
fix: getFixerFunction(style, previousItemToken, commaToken, currentItemToken)
});
} else if (style === "last" && astUtils.isTokenOnSameLine(commaToken, currentItemToken)) {
context.report({
node: reportItem,
loc: {
line: commaToken.loc.end.line,
column: commaToken.loc.end.column
},
messageId: "expectedCommaLast",
fix: getFixerFunction(style, previousItemToken, commaToken, currentItemToken)
});
}
}
|
javascript
|
function validateCommaItemSpacing(previousItemToken, commaToken, currentItemToken, reportItem) {
// if single line
if (astUtils.isTokenOnSameLine(commaToken, currentItemToken) &&
astUtils.isTokenOnSameLine(previousItemToken, commaToken)) {
// do nothing.
} else if (!astUtils.isTokenOnSameLine(commaToken, currentItemToken) &&
!astUtils.isTokenOnSameLine(previousItemToken, commaToken)) {
const comment = sourceCode.getCommentsAfter(commaToken)[0];
const styleType = comment && comment.type === "Block" && astUtils.isTokenOnSameLine(commaToken, comment)
? style
: "between";
// lone comma
context.report({
node: reportItem,
loc: {
line: commaToken.loc.end.line,
column: commaToken.loc.start.column
},
messageId: "unexpectedLineBeforeAndAfterComma",
fix: getFixerFunction(styleType, previousItemToken, commaToken, currentItemToken)
});
} else if (style === "first" && !astUtils.isTokenOnSameLine(commaToken, currentItemToken)) {
context.report({
node: reportItem,
messageId: "expectedCommaFirst",
fix: getFixerFunction(style, previousItemToken, commaToken, currentItemToken)
});
} else if (style === "last" && astUtils.isTokenOnSameLine(commaToken, currentItemToken)) {
context.report({
node: reportItem,
loc: {
line: commaToken.loc.end.line,
column: commaToken.loc.end.column
},
messageId: "expectedCommaLast",
fix: getFixerFunction(style, previousItemToken, commaToken, currentItemToken)
});
}
}
|
[
"function",
"validateCommaItemSpacing",
"(",
"previousItemToken",
",",
"commaToken",
",",
"currentItemToken",
",",
"reportItem",
")",
"{",
"if",
"(",
"astUtils",
".",
"isTokenOnSameLine",
"(",
"commaToken",
",",
"currentItemToken",
")",
"&&",
"astUtils",
".",
"isTokenOnSameLine",
"(",
"previousItemToken",
",",
"commaToken",
")",
")",
"{",
"}",
"else",
"if",
"(",
"!",
"astUtils",
".",
"isTokenOnSameLine",
"(",
"commaToken",
",",
"currentItemToken",
")",
"&&",
"!",
"astUtils",
".",
"isTokenOnSameLine",
"(",
"previousItemToken",
",",
"commaToken",
")",
")",
"{",
"const",
"comment",
"=",
"sourceCode",
".",
"getCommentsAfter",
"(",
"commaToken",
")",
"[",
"0",
"]",
";",
"const",
"styleType",
"=",
"comment",
"&&",
"comment",
".",
"type",
"===",
"\"Block\"",
"&&",
"astUtils",
".",
"isTokenOnSameLine",
"(",
"commaToken",
",",
"comment",
")",
"?",
"style",
":",
"\"between\"",
";",
"context",
".",
"report",
"(",
"{",
"node",
":",
"reportItem",
",",
"loc",
":",
"{",
"line",
":",
"commaToken",
".",
"loc",
".",
"end",
".",
"line",
",",
"column",
":",
"commaToken",
".",
"loc",
".",
"start",
".",
"column",
"}",
",",
"messageId",
":",
"\"unexpectedLineBeforeAndAfterComma\"",
",",
"fix",
":",
"getFixerFunction",
"(",
"styleType",
",",
"previousItemToken",
",",
"commaToken",
",",
"currentItemToken",
")",
"}",
")",
";",
"}",
"else",
"if",
"(",
"style",
"===",
"\"first\"",
"&&",
"!",
"astUtils",
".",
"isTokenOnSameLine",
"(",
"commaToken",
",",
"currentItemToken",
")",
")",
"{",
"context",
".",
"report",
"(",
"{",
"node",
":",
"reportItem",
",",
"messageId",
":",
"\"expectedCommaFirst\"",
",",
"fix",
":",
"getFixerFunction",
"(",
"style",
",",
"previousItemToken",
",",
"commaToken",
",",
"currentItemToken",
")",
"}",
")",
";",
"}",
"else",
"if",
"(",
"style",
"===",
"\"last\"",
"&&",
"astUtils",
".",
"isTokenOnSameLine",
"(",
"commaToken",
",",
"currentItemToken",
")",
")",
"{",
"context",
".",
"report",
"(",
"{",
"node",
":",
"reportItem",
",",
"loc",
":",
"{",
"line",
":",
"commaToken",
".",
"loc",
".",
"end",
".",
"line",
",",
"column",
":",
"commaToken",
".",
"loc",
".",
"end",
".",
"column",
"}",
",",
"messageId",
":",
"\"expectedCommaLast\"",
",",
"fix",
":",
"getFixerFunction",
"(",
"style",
",",
"previousItemToken",
",",
"commaToken",
",",
"currentItemToken",
")",
"}",
")",
";",
"}",
"}"
] |
Validates the spacing around single items in lists.
@param {Token} previousItemToken The last token from the previous item.
@param {Token} commaToken The token representing the comma.
@param {Token} currentItemToken The first token of the current item.
@param {Token} reportItem The item to use when reporting an error.
@returns {void}
@private
|
[
"Validates",
"the",
"spacing",
"around",
"single",
"items",
"in",
"lists",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/comma-style.js#L130-L177
|
train
|
eslint/eslint
|
lib/rules/accessor-pairs.js
|
isArgumentOfMethodCall
|
function isArgumentOfMethodCall(node, index, object, property) {
const parent = node.parent;
return (
parent.type === "CallExpression" &&
parent.callee.type === "MemberExpression" &&
parent.callee.computed === false &&
isIdentifier(parent.callee.object, object) &&
isIdentifier(parent.callee.property, property) &&
parent.arguments[index] === node
);
}
|
javascript
|
function isArgumentOfMethodCall(node, index, object, property) {
const parent = node.parent;
return (
parent.type === "CallExpression" &&
parent.callee.type === "MemberExpression" &&
parent.callee.computed === false &&
isIdentifier(parent.callee.object, object) &&
isIdentifier(parent.callee.property, property) &&
parent.arguments[index] === node
);
}
|
[
"function",
"isArgumentOfMethodCall",
"(",
"node",
",",
"index",
",",
"object",
",",
"property",
")",
"{",
"const",
"parent",
"=",
"node",
".",
"parent",
";",
"return",
"(",
"parent",
".",
"type",
"===",
"\"CallExpression\"",
"&&",
"parent",
".",
"callee",
".",
"type",
"===",
"\"MemberExpression\"",
"&&",
"parent",
".",
"callee",
".",
"computed",
"===",
"false",
"&&",
"isIdentifier",
"(",
"parent",
".",
"callee",
".",
"object",
",",
"object",
")",
"&&",
"isIdentifier",
"(",
"parent",
".",
"callee",
".",
"property",
",",
"property",
")",
"&&",
"parent",
".",
"arguments",
"[",
"index",
"]",
"===",
"node",
")",
";",
"}"
] |
Checks whether or not a given node is an argument of a specified method call.
@param {ASTNode} node - A node to check.
@param {number} index - An expected index of the node in arguments.
@param {string} object - An expected name of the object of the method.
@param {string} property - An expected name of the method.
@returns {boolean} `true` if the node is an argument of the specified method call.
|
[
"Checks",
"whether",
"or",
"not",
"a",
"given",
"node",
"is",
"an",
"argument",
"of",
"a",
"specified",
"method",
"call",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/accessor-pairs.js#L30-L41
|
train
|
eslint/eslint
|
lib/util/glob-utils.js
|
processPath
|
function processPath(options) {
const cwd = (options && options.cwd) || process.cwd();
let extensions = (options && options.extensions) || [".js"];
extensions = extensions.map(ext => ext.replace(/^\./u, ""));
let suffix = "/**";
if (extensions.length === 1) {
suffix += `/*.${extensions[0]}`;
} else {
suffix += `/*.{${extensions.join(",")}}`;
}
/**
* A function that converts a directory name to a glob pattern
*
* @param {string} pathname The directory path to be modified
* @returns {string} The glob path or the file path itself
* @private
*/
return function(pathname) {
if (pathname === "") {
return "";
}
let newPath = pathname;
const resolvedPath = path.resolve(cwd, pathname);
if (directoryExists(resolvedPath)) {
newPath = pathname.replace(/[/\\]$/u, "") + suffix;
}
return pathUtils.convertPathToPosix(newPath);
};
}
|
javascript
|
function processPath(options) {
const cwd = (options && options.cwd) || process.cwd();
let extensions = (options && options.extensions) || [".js"];
extensions = extensions.map(ext => ext.replace(/^\./u, ""));
let suffix = "/**";
if (extensions.length === 1) {
suffix += `/*.${extensions[0]}`;
} else {
suffix += `/*.{${extensions.join(",")}}`;
}
/**
* A function that converts a directory name to a glob pattern
*
* @param {string} pathname The directory path to be modified
* @returns {string} The glob path or the file path itself
* @private
*/
return function(pathname) {
if (pathname === "") {
return "";
}
let newPath = pathname;
const resolvedPath = path.resolve(cwd, pathname);
if (directoryExists(resolvedPath)) {
newPath = pathname.replace(/[/\\]$/u, "") + suffix;
}
return pathUtils.convertPathToPosix(newPath);
};
}
|
[
"function",
"processPath",
"(",
"options",
")",
"{",
"const",
"cwd",
"=",
"(",
"options",
"&&",
"options",
".",
"cwd",
")",
"||",
"process",
".",
"cwd",
"(",
")",
";",
"let",
"extensions",
"=",
"(",
"options",
"&&",
"options",
".",
"extensions",
")",
"||",
"[",
"\".js\"",
"]",
";",
"extensions",
"=",
"extensions",
".",
"map",
"(",
"ext",
"=>",
"ext",
".",
"replace",
"(",
"/",
"^\\.",
"/",
"u",
",",
"\"\"",
")",
")",
";",
"let",
"suffix",
"=",
"\"/**\"",
";",
"if",
"(",
"extensions",
".",
"length",
"===",
"1",
")",
"{",
"suffix",
"+=",
"`",
"${",
"extensions",
"[",
"0",
"]",
"}",
"`",
";",
"}",
"else",
"{",
"suffix",
"+=",
"`",
"${",
"extensions",
".",
"join",
"(",
"\",\"",
")",
"}",
"`",
";",
"}",
"return",
"function",
"(",
"pathname",
")",
"{",
"if",
"(",
"pathname",
"===",
"\"\"",
")",
"{",
"return",
"\"\"",
";",
"}",
"let",
"newPath",
"=",
"pathname",
";",
"const",
"resolvedPath",
"=",
"path",
".",
"resolve",
"(",
"cwd",
",",
"pathname",
")",
";",
"if",
"(",
"directoryExists",
"(",
"resolvedPath",
")",
")",
"{",
"newPath",
"=",
"pathname",
".",
"replace",
"(",
"/",
"[/\\\\]$",
"/",
"u",
",",
"\"\"",
")",
"+",
"suffix",
";",
"}",
"return",
"pathUtils",
".",
"convertPathToPosix",
"(",
"newPath",
")",
";",
"}",
";",
"}"
] |
Checks if a provided path is a directory and returns a glob string matching
all files under that directory if so, the path itself otherwise.
Reason for this is that `glob` needs `/**` to collect all the files under a
directory where as our previous implementation without `glob` simply walked
a directory that is passed. So this is to maintain backwards compatibility.
Also makes sure all path separators are POSIX style for `glob` compatibility.
@param {Object} [options] An options object
@param {string[]} [options.extensions=[".js"]] An array of accepted extensions
@param {string} [options.cwd=process.cwd()] The cwd to use to resolve relative pathnames
@returns {Function} A function that takes a pathname and returns a glob that
matches all files with the provided extensions if
pathname is a directory.
|
[
"Checks",
"if",
"a",
"provided",
"path",
"is",
"a",
"directory",
"and",
"returns",
"a",
"glob",
"string",
"matching",
"all",
"files",
"under",
"that",
"directory",
"if",
"so",
"the",
"path",
"itself",
"otherwise",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/util/glob-utils.js#L51-L86
|
train
|
eslint/eslint
|
lib/util/glob-utils.js
|
listFilesToProcess
|
function listFilesToProcess(globPatterns, providedOptions) {
const options = providedOptions || { ignore: true };
const cwd = options.cwd || process.cwd();
const getIgnorePaths = lodash.memoize(
optionsObj =>
new IgnoredPaths(optionsObj)
);
/*
* The test "should use default options if none are provided" (source-code-utils.js) checks that 'module.exports.resolveFileGlobPatterns' was called.
* So it cannot use the local function "resolveFileGlobPatterns".
*/
const resolvedGlobPatterns = module.exports.resolveFileGlobPatterns(globPatterns, options);
debug("Creating list of files to process.");
const resolvedPathsByGlobPattern = resolvedGlobPatterns.map(pattern => {
if (pattern === "") {
return [{
filename: "",
behavior: SILENTLY_IGNORE
}];
}
const file = path.resolve(cwd, pattern);
if (options.globInputPaths === false || (fs.existsSync(file) && fs.statSync(file).isFile())) {
const ignoredPaths = getIgnorePaths(options);
const fullPath = options.globInputPaths === false ? file : fs.realpathSync(file);
return [{
filename: fullPath,
behavior: testFileAgainstIgnorePatterns(fullPath, options, true, ignoredPaths)
}];
}
// regex to find .hidden or /.hidden patterns, but not ./relative or ../relative
const globIncludesDotfiles = dotfilesPattern.test(pattern);
let newOptions = options;
if (!options.dotfiles) {
newOptions = Object.assign({}, options, { dotfiles: globIncludesDotfiles });
}
const ignoredPaths = getIgnorePaths(newOptions);
const shouldIgnore = ignoredPaths.getIgnoredFoldersGlobChecker();
const globOptions = {
nodir: true,
dot: true,
cwd
};
return new GlobSync(pattern, globOptions, shouldIgnore).found.map(globMatch => {
const relativePath = path.resolve(cwd, globMatch);
return {
filename: relativePath,
behavior: testFileAgainstIgnorePatterns(relativePath, options, false, ignoredPaths)
};
});
});
const allPathDescriptors = resolvedPathsByGlobPattern.reduce((pathsForAllGlobs, pathsForCurrentGlob, index) => {
if (pathsForCurrentGlob.every(pathDescriptor => pathDescriptor.behavior === SILENTLY_IGNORE && pathDescriptor.filename !== "")) {
throw new (pathsForCurrentGlob.length ? AllFilesIgnoredError : NoFilesFoundError)(globPatterns[index]);
}
pathsForCurrentGlob.forEach(pathDescriptor => {
switch (pathDescriptor.behavior) {
case NORMAL_LINT:
pathsForAllGlobs.push({ filename: pathDescriptor.filename, ignored: false });
break;
case IGNORE_AND_WARN:
pathsForAllGlobs.push({ filename: pathDescriptor.filename, ignored: true });
break;
case SILENTLY_IGNORE:
// do nothing
break;
default:
throw new Error(`Unexpected file behavior for ${pathDescriptor.filename}`);
}
});
return pathsForAllGlobs;
}, []);
return lodash.uniqBy(allPathDescriptors, pathDescriptor => pathDescriptor.filename);
}
|
javascript
|
function listFilesToProcess(globPatterns, providedOptions) {
const options = providedOptions || { ignore: true };
const cwd = options.cwd || process.cwd();
const getIgnorePaths = lodash.memoize(
optionsObj =>
new IgnoredPaths(optionsObj)
);
/*
* The test "should use default options if none are provided" (source-code-utils.js) checks that 'module.exports.resolveFileGlobPatterns' was called.
* So it cannot use the local function "resolveFileGlobPatterns".
*/
const resolvedGlobPatterns = module.exports.resolveFileGlobPatterns(globPatterns, options);
debug("Creating list of files to process.");
const resolvedPathsByGlobPattern = resolvedGlobPatterns.map(pattern => {
if (pattern === "") {
return [{
filename: "",
behavior: SILENTLY_IGNORE
}];
}
const file = path.resolve(cwd, pattern);
if (options.globInputPaths === false || (fs.existsSync(file) && fs.statSync(file).isFile())) {
const ignoredPaths = getIgnorePaths(options);
const fullPath = options.globInputPaths === false ? file : fs.realpathSync(file);
return [{
filename: fullPath,
behavior: testFileAgainstIgnorePatterns(fullPath, options, true, ignoredPaths)
}];
}
// regex to find .hidden or /.hidden patterns, but not ./relative or ../relative
const globIncludesDotfiles = dotfilesPattern.test(pattern);
let newOptions = options;
if (!options.dotfiles) {
newOptions = Object.assign({}, options, { dotfiles: globIncludesDotfiles });
}
const ignoredPaths = getIgnorePaths(newOptions);
const shouldIgnore = ignoredPaths.getIgnoredFoldersGlobChecker();
const globOptions = {
nodir: true,
dot: true,
cwd
};
return new GlobSync(pattern, globOptions, shouldIgnore).found.map(globMatch => {
const relativePath = path.resolve(cwd, globMatch);
return {
filename: relativePath,
behavior: testFileAgainstIgnorePatterns(relativePath, options, false, ignoredPaths)
};
});
});
const allPathDescriptors = resolvedPathsByGlobPattern.reduce((pathsForAllGlobs, pathsForCurrentGlob, index) => {
if (pathsForCurrentGlob.every(pathDescriptor => pathDescriptor.behavior === SILENTLY_IGNORE && pathDescriptor.filename !== "")) {
throw new (pathsForCurrentGlob.length ? AllFilesIgnoredError : NoFilesFoundError)(globPatterns[index]);
}
pathsForCurrentGlob.forEach(pathDescriptor => {
switch (pathDescriptor.behavior) {
case NORMAL_LINT:
pathsForAllGlobs.push({ filename: pathDescriptor.filename, ignored: false });
break;
case IGNORE_AND_WARN:
pathsForAllGlobs.push({ filename: pathDescriptor.filename, ignored: true });
break;
case SILENTLY_IGNORE:
// do nothing
break;
default:
throw new Error(`Unexpected file behavior for ${pathDescriptor.filename}`);
}
});
return pathsForAllGlobs;
}, []);
return lodash.uniqBy(allPathDescriptors, pathDescriptor => pathDescriptor.filename);
}
|
[
"function",
"listFilesToProcess",
"(",
"globPatterns",
",",
"providedOptions",
")",
"{",
"const",
"options",
"=",
"providedOptions",
"||",
"{",
"ignore",
":",
"true",
"}",
";",
"const",
"cwd",
"=",
"options",
".",
"cwd",
"||",
"process",
".",
"cwd",
"(",
")",
";",
"const",
"getIgnorePaths",
"=",
"lodash",
".",
"memoize",
"(",
"optionsObj",
"=>",
"new",
"IgnoredPaths",
"(",
"optionsObj",
")",
")",
";",
"const",
"resolvedGlobPatterns",
"=",
"module",
".",
"exports",
".",
"resolveFileGlobPatterns",
"(",
"globPatterns",
",",
"options",
")",
";",
"debug",
"(",
"\"Creating list of files to process.\"",
")",
";",
"const",
"resolvedPathsByGlobPattern",
"=",
"resolvedGlobPatterns",
".",
"map",
"(",
"pattern",
"=>",
"{",
"if",
"(",
"pattern",
"===",
"\"\"",
")",
"{",
"return",
"[",
"{",
"filename",
":",
"\"\"",
",",
"behavior",
":",
"SILENTLY_IGNORE",
"}",
"]",
";",
"}",
"const",
"file",
"=",
"path",
".",
"resolve",
"(",
"cwd",
",",
"pattern",
")",
";",
"if",
"(",
"options",
".",
"globInputPaths",
"===",
"false",
"||",
"(",
"fs",
".",
"existsSync",
"(",
"file",
")",
"&&",
"fs",
".",
"statSync",
"(",
"file",
")",
".",
"isFile",
"(",
")",
")",
")",
"{",
"const",
"ignoredPaths",
"=",
"getIgnorePaths",
"(",
"options",
")",
";",
"const",
"fullPath",
"=",
"options",
".",
"globInputPaths",
"===",
"false",
"?",
"file",
":",
"fs",
".",
"realpathSync",
"(",
"file",
")",
";",
"return",
"[",
"{",
"filename",
":",
"fullPath",
",",
"behavior",
":",
"testFileAgainstIgnorePatterns",
"(",
"fullPath",
",",
"options",
",",
"true",
",",
"ignoredPaths",
")",
"}",
"]",
";",
"}",
"const",
"globIncludesDotfiles",
"=",
"dotfilesPattern",
".",
"test",
"(",
"pattern",
")",
";",
"let",
"newOptions",
"=",
"options",
";",
"if",
"(",
"!",
"options",
".",
"dotfiles",
")",
"{",
"newOptions",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"options",
",",
"{",
"dotfiles",
":",
"globIncludesDotfiles",
"}",
")",
";",
"}",
"const",
"ignoredPaths",
"=",
"getIgnorePaths",
"(",
"newOptions",
")",
";",
"const",
"shouldIgnore",
"=",
"ignoredPaths",
".",
"getIgnoredFoldersGlobChecker",
"(",
")",
";",
"const",
"globOptions",
"=",
"{",
"nodir",
":",
"true",
",",
"dot",
":",
"true",
",",
"cwd",
"}",
";",
"return",
"new",
"GlobSync",
"(",
"pattern",
",",
"globOptions",
",",
"shouldIgnore",
")",
".",
"found",
".",
"map",
"(",
"globMatch",
"=>",
"{",
"const",
"relativePath",
"=",
"path",
".",
"resolve",
"(",
"cwd",
",",
"globMatch",
")",
";",
"return",
"{",
"filename",
":",
"relativePath",
",",
"behavior",
":",
"testFileAgainstIgnorePatterns",
"(",
"relativePath",
",",
"options",
",",
"false",
",",
"ignoredPaths",
")",
"}",
";",
"}",
")",
";",
"}",
")",
";",
"const",
"allPathDescriptors",
"=",
"resolvedPathsByGlobPattern",
".",
"reduce",
"(",
"(",
"pathsForAllGlobs",
",",
"pathsForCurrentGlob",
",",
"index",
")",
"=>",
"{",
"if",
"(",
"pathsForCurrentGlob",
".",
"every",
"(",
"pathDescriptor",
"=>",
"pathDescriptor",
".",
"behavior",
"===",
"SILENTLY_IGNORE",
"&&",
"pathDescriptor",
".",
"filename",
"!==",
"\"\"",
")",
")",
"{",
"throw",
"new",
"(",
"pathsForCurrentGlob",
".",
"length",
"?",
"AllFilesIgnoredError",
":",
"NoFilesFoundError",
")",
"(",
"globPatterns",
"[",
"index",
"]",
")",
";",
"}",
"pathsForCurrentGlob",
".",
"forEach",
"(",
"pathDescriptor",
"=>",
"{",
"switch",
"(",
"pathDescriptor",
".",
"behavior",
")",
"{",
"case",
"NORMAL_LINT",
":",
"pathsForAllGlobs",
".",
"push",
"(",
"{",
"filename",
":",
"pathDescriptor",
".",
"filename",
",",
"ignored",
":",
"false",
"}",
")",
";",
"break",
";",
"case",
"IGNORE_AND_WARN",
":",
"pathsForAllGlobs",
".",
"push",
"(",
"{",
"filename",
":",
"pathDescriptor",
".",
"filename",
",",
"ignored",
":",
"true",
"}",
")",
";",
"break",
";",
"case",
"SILENTLY_IGNORE",
":",
"break",
";",
"default",
":",
"throw",
"new",
"Error",
"(",
"`",
"${",
"pathDescriptor",
".",
"filename",
"}",
"`",
")",
";",
"}",
"}",
")",
";",
"return",
"pathsForAllGlobs",
";",
"}",
",",
"[",
"]",
")",
";",
"return",
"lodash",
".",
"uniqBy",
"(",
"allPathDescriptors",
",",
"pathDescriptor",
"=>",
"pathDescriptor",
".",
"filename",
")",
";",
"}"
] |
Build a list of absolute filesnames on which ESLint will act.
Ignored files are excluded from the results, as are duplicates.
@param {string[]} globPatterns Glob patterns.
@param {Object} [providedOptions] An options object.
@param {string} [providedOptions.cwd] CWD (considered for relative filenames)
@param {boolean} [providedOptions.ignore] False disables use of .eslintignore.
@param {string} [providedOptions.ignorePath] The ignore file to use instead of .eslintignore.
@param {string} [providedOptions.ignorePattern] A pattern of files to ignore.
@param {string} [providedOptions.globInputPaths] False disables glob resolution.
@returns {string[]} Resolved absolute filenames.
|
[
"Build",
"a",
"list",
"of",
"absolute",
"filesnames",
"on",
"which",
"ESLint",
"will",
"act",
".",
"Ignored",
"files",
"are",
"excluded",
"from",
"the",
"results",
"as",
"are",
"duplicates",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/util/glob-utils.js#L191-L280
|
train
|
eslint/eslint
|
lib/rules/no-prototype-builtins.js
|
disallowBuiltIns
|
function disallowBuiltIns(node) {
if (node.callee.type !== "MemberExpression" || node.callee.computed) {
return;
}
const propName = node.callee.property.name;
if (DISALLOWED_PROPS.indexOf(propName) > -1) {
context.report({
message: "Do not access Object.prototype method '{{prop}}' from target object.",
loc: node.callee.property.loc.start,
data: { prop: propName },
node
});
}
}
|
javascript
|
function disallowBuiltIns(node) {
if (node.callee.type !== "MemberExpression" || node.callee.computed) {
return;
}
const propName = node.callee.property.name;
if (DISALLOWED_PROPS.indexOf(propName) > -1) {
context.report({
message: "Do not access Object.prototype method '{{prop}}' from target object.",
loc: node.callee.property.loc.start,
data: { prop: propName },
node
});
}
}
|
[
"function",
"disallowBuiltIns",
"(",
"node",
")",
"{",
"if",
"(",
"node",
".",
"callee",
".",
"type",
"!==",
"\"MemberExpression\"",
"||",
"node",
".",
"callee",
".",
"computed",
")",
"{",
"return",
";",
"}",
"const",
"propName",
"=",
"node",
".",
"callee",
".",
"property",
".",
"name",
";",
"if",
"(",
"DISALLOWED_PROPS",
".",
"indexOf",
"(",
"propName",
")",
">",
"-",
"1",
")",
"{",
"context",
".",
"report",
"(",
"{",
"message",
":",
"\"Do not access Object.prototype method '{{prop}}' from target object.\"",
",",
"loc",
":",
"node",
".",
"callee",
".",
"property",
".",
"loc",
".",
"start",
",",
"data",
":",
"{",
"prop",
":",
"propName",
"}",
",",
"node",
"}",
")",
";",
"}",
"}"
] |
Reports if a disallowed property is used in a CallExpression
@param {ASTNode} node The CallExpression node.
@returns {void}
|
[
"Reports",
"if",
"a",
"disallowed",
"property",
"is",
"used",
"in",
"a",
"CallExpression"
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-prototype-builtins.js#L37-L51
|
train
|
eslint/eslint
|
lib/rules/no-useless-escape.js
|
report
|
function report(node, startOffset, character) {
context.report({
node,
loc: sourceCode.getLocFromIndex(sourceCode.getIndexFromLoc(node.loc.start) + startOffset),
message: "Unnecessary escape character: \\{{character}}.",
data: { character }
});
}
|
javascript
|
function report(node, startOffset, character) {
context.report({
node,
loc: sourceCode.getLocFromIndex(sourceCode.getIndexFromLoc(node.loc.start) + startOffset),
message: "Unnecessary escape character: \\{{character}}.",
data: { character }
});
}
|
[
"function",
"report",
"(",
"node",
",",
"startOffset",
",",
"character",
")",
"{",
"context",
".",
"report",
"(",
"{",
"node",
",",
"loc",
":",
"sourceCode",
".",
"getLocFromIndex",
"(",
"sourceCode",
".",
"getIndexFromLoc",
"(",
"node",
".",
"loc",
".",
"start",
")",
"+",
"startOffset",
")",
",",
"message",
":",
"\"Unnecessary escape character: \\\\{{character}}.\"",
",",
"\\\\",
"}",
")",
";",
"}"
] |
Reports a node
@param {ASTNode} node The node to report
@param {number} startOffset The backslash's offset from the start of the node
@param {string} character The uselessly escaped character (not including the backslash)
@returns {void}
|
[
"Reports",
"a",
"node"
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-useless-escape.js#L104-L111
|
train
|
eslint/eslint
|
lib/rules/no-useless-escape.js
|
validateString
|
function validateString(node, match) {
const isTemplateElement = node.type === "TemplateElement";
const escapedChar = match[0][1];
let isUnnecessaryEscape = !VALID_STRING_ESCAPES.has(escapedChar);
let isQuoteEscape;
if (isTemplateElement) {
isQuoteEscape = escapedChar === "`";
if (escapedChar === "$") {
// Warn if `\$` is not followed by `{`
isUnnecessaryEscape = match.input[match.index + 2] !== "{";
} else if (escapedChar === "{") {
/*
* Warn if `\{` is not preceded by `$`. If preceded by `$`, escaping
* is necessary and the rule should not warn. If preceded by `/$`, the rule
* will warn for the `/$` instead, as it is the first unnecessarily escaped character.
*/
isUnnecessaryEscape = match.input[match.index - 1] !== "$";
}
} else {
isQuoteEscape = escapedChar === node.raw[0];
}
if (isUnnecessaryEscape && !isQuoteEscape) {
report(node, match.index + 1, match[0].slice(1));
}
}
|
javascript
|
function validateString(node, match) {
const isTemplateElement = node.type === "TemplateElement";
const escapedChar = match[0][1];
let isUnnecessaryEscape = !VALID_STRING_ESCAPES.has(escapedChar);
let isQuoteEscape;
if (isTemplateElement) {
isQuoteEscape = escapedChar === "`";
if (escapedChar === "$") {
// Warn if `\$` is not followed by `{`
isUnnecessaryEscape = match.input[match.index + 2] !== "{";
} else if (escapedChar === "{") {
/*
* Warn if `\{` is not preceded by `$`. If preceded by `$`, escaping
* is necessary and the rule should not warn. If preceded by `/$`, the rule
* will warn for the `/$` instead, as it is the first unnecessarily escaped character.
*/
isUnnecessaryEscape = match.input[match.index - 1] !== "$";
}
} else {
isQuoteEscape = escapedChar === node.raw[0];
}
if (isUnnecessaryEscape && !isQuoteEscape) {
report(node, match.index + 1, match[0].slice(1));
}
}
|
[
"function",
"validateString",
"(",
"node",
",",
"match",
")",
"{",
"const",
"isTemplateElement",
"=",
"node",
".",
"type",
"===",
"\"TemplateElement\"",
";",
"const",
"escapedChar",
"=",
"match",
"[",
"0",
"]",
"[",
"1",
"]",
";",
"let",
"isUnnecessaryEscape",
"=",
"!",
"VALID_STRING_ESCAPES",
".",
"has",
"(",
"escapedChar",
")",
";",
"let",
"isQuoteEscape",
";",
"if",
"(",
"isTemplateElement",
")",
"{",
"isQuoteEscape",
"=",
"escapedChar",
"===",
"\"`\"",
";",
"if",
"(",
"escapedChar",
"===",
"\"$\"",
")",
"{",
"isUnnecessaryEscape",
"=",
"match",
".",
"input",
"[",
"match",
".",
"index",
"+",
"2",
"]",
"!==",
"\"{\"",
";",
"}",
"else",
"if",
"(",
"escapedChar",
"===",
"\"{\"",
")",
"{",
"isUnnecessaryEscape",
"=",
"match",
".",
"input",
"[",
"match",
".",
"index",
"-",
"1",
"]",
"!==",
"\"$\"",
";",
"}",
"}",
"else",
"{",
"isQuoteEscape",
"=",
"escapedChar",
"===",
"node",
".",
"raw",
"[",
"0",
"]",
";",
"}",
"if",
"(",
"isUnnecessaryEscape",
"&&",
"!",
"isQuoteEscape",
")",
"{",
"report",
"(",
"node",
",",
"match",
".",
"index",
"+",
"1",
",",
"match",
"[",
"0",
"]",
".",
"slice",
"(",
"1",
")",
")",
";",
"}",
"}"
] |
Checks if the escape character in given string slice is unnecessary.
@private
@param {ASTNode} node - node to validate.
@param {string} match - string slice to validate.
@returns {void}
|
[
"Checks",
"if",
"the",
"escape",
"character",
"in",
"given",
"string",
"slice",
"is",
"unnecessary",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-useless-escape.js#L121-L150
|
train
|
eslint/eslint
|
lib/rules/no-useless-escape.js
|
check
|
function check(node) {
const isTemplateElement = node.type === "TemplateElement";
if (
isTemplateElement &&
node.parent &&
node.parent.parent &&
node.parent.parent.type === "TaggedTemplateExpression" &&
node.parent === node.parent.parent.quasi
) {
// Don't report tagged template literals, because the backslash character is accessible to the tag function.
return;
}
if (typeof node.value === "string" || isTemplateElement) {
/*
* JSXAttribute doesn't have any escape sequence: https://facebook.github.io/jsx/.
* In addition, backticks are not supported by JSX yet: https://github.com/facebook/jsx/issues/25.
*/
if (node.parent.type === "JSXAttribute" || node.parent.type === "JSXElement" || node.parent.type === "JSXFragment") {
return;
}
const value = isTemplateElement ? node.value.raw : node.raw.slice(1, -1);
const pattern = /\\[^\d]/gu;
let match;
while ((match = pattern.exec(value))) {
validateString(node, match);
}
} else if (node.regex) {
parseRegExp(node.regex.pattern)
/*
* The '-' character is a special case, because it's only valid to escape it if it's in a character
* class, and is not at either edge of the character class. To account for this, don't consider '-'
* characters to be valid in general, and filter out '-' characters that appear in the middle of a
* character class.
*/
.filter(charInfo => !(charInfo.text === "-" && charInfo.inCharClass && !charInfo.startsCharClass && !charInfo.endsCharClass))
/*
* The '^' character is also a special case; it must always be escaped outside of character classes, but
* it only needs to be escaped in character classes if it's at the beginning of the character class. To
* account for this, consider it to be a valid escape character outside of character classes, and filter
* out '^' characters that appear at the start of a character class.
*/
.filter(charInfo => !(charInfo.text === "^" && charInfo.startsCharClass))
// Filter out characters that aren't escaped.
.filter(charInfo => charInfo.escaped)
// Filter out characters that are valid to escape, based on their position in the regular expression.
.filter(charInfo => !(charInfo.inCharClass ? REGEX_GENERAL_ESCAPES : REGEX_NON_CHARCLASS_ESCAPES).has(charInfo.text))
// Report all the remaining characters.
.forEach(charInfo => report(node, charInfo.index, charInfo.text));
}
}
|
javascript
|
function check(node) {
const isTemplateElement = node.type === "TemplateElement";
if (
isTemplateElement &&
node.parent &&
node.parent.parent &&
node.parent.parent.type === "TaggedTemplateExpression" &&
node.parent === node.parent.parent.quasi
) {
// Don't report tagged template literals, because the backslash character is accessible to the tag function.
return;
}
if (typeof node.value === "string" || isTemplateElement) {
/*
* JSXAttribute doesn't have any escape sequence: https://facebook.github.io/jsx/.
* In addition, backticks are not supported by JSX yet: https://github.com/facebook/jsx/issues/25.
*/
if (node.parent.type === "JSXAttribute" || node.parent.type === "JSXElement" || node.parent.type === "JSXFragment") {
return;
}
const value = isTemplateElement ? node.value.raw : node.raw.slice(1, -1);
const pattern = /\\[^\d]/gu;
let match;
while ((match = pattern.exec(value))) {
validateString(node, match);
}
} else if (node.regex) {
parseRegExp(node.regex.pattern)
/*
* The '-' character is a special case, because it's only valid to escape it if it's in a character
* class, and is not at either edge of the character class. To account for this, don't consider '-'
* characters to be valid in general, and filter out '-' characters that appear in the middle of a
* character class.
*/
.filter(charInfo => !(charInfo.text === "-" && charInfo.inCharClass && !charInfo.startsCharClass && !charInfo.endsCharClass))
/*
* The '^' character is also a special case; it must always be escaped outside of character classes, but
* it only needs to be escaped in character classes if it's at the beginning of the character class. To
* account for this, consider it to be a valid escape character outside of character classes, and filter
* out '^' characters that appear at the start of a character class.
*/
.filter(charInfo => !(charInfo.text === "^" && charInfo.startsCharClass))
// Filter out characters that aren't escaped.
.filter(charInfo => charInfo.escaped)
// Filter out characters that are valid to escape, based on their position in the regular expression.
.filter(charInfo => !(charInfo.inCharClass ? REGEX_GENERAL_ESCAPES : REGEX_NON_CHARCLASS_ESCAPES).has(charInfo.text))
// Report all the remaining characters.
.forEach(charInfo => report(node, charInfo.index, charInfo.text));
}
}
|
[
"function",
"check",
"(",
"node",
")",
"{",
"const",
"isTemplateElement",
"=",
"node",
".",
"type",
"===",
"\"TemplateElement\"",
";",
"if",
"(",
"isTemplateElement",
"&&",
"node",
".",
"parent",
"&&",
"node",
".",
"parent",
".",
"parent",
"&&",
"node",
".",
"parent",
".",
"parent",
".",
"type",
"===",
"\"TaggedTemplateExpression\"",
"&&",
"node",
".",
"parent",
"===",
"node",
".",
"parent",
".",
"parent",
".",
"quasi",
")",
"{",
"return",
";",
"}",
"if",
"(",
"typeof",
"node",
".",
"value",
"===",
"\"string\"",
"||",
"isTemplateElement",
")",
"{",
"if",
"(",
"node",
".",
"parent",
".",
"type",
"===",
"\"JSXAttribute\"",
"||",
"node",
".",
"parent",
".",
"type",
"===",
"\"JSXElement\"",
"||",
"node",
".",
"parent",
".",
"type",
"===",
"\"JSXFragment\"",
")",
"{",
"return",
";",
"}",
"const",
"value",
"=",
"isTemplateElement",
"?",
"node",
".",
"value",
".",
"raw",
":",
"node",
".",
"raw",
".",
"slice",
"(",
"1",
",",
"-",
"1",
")",
";",
"const",
"pattern",
"=",
"/",
"\\\\[^\\d]",
"/",
"gu",
";",
"let",
"match",
";",
"while",
"(",
"(",
"match",
"=",
"pattern",
".",
"exec",
"(",
"value",
")",
")",
")",
"{",
"validateString",
"(",
"node",
",",
"match",
")",
";",
"}",
"}",
"else",
"if",
"(",
"node",
".",
"regex",
")",
"{",
"parseRegExp",
"(",
"node",
".",
"regex",
".",
"pattern",
")",
".",
"filter",
"(",
"charInfo",
"=>",
"!",
"(",
"charInfo",
".",
"text",
"===",
"\"-\"",
"&&",
"charInfo",
".",
"inCharClass",
"&&",
"!",
"charInfo",
".",
"startsCharClass",
"&&",
"!",
"charInfo",
".",
"endsCharClass",
")",
")",
".",
"filter",
"(",
"charInfo",
"=>",
"!",
"(",
"charInfo",
".",
"text",
"===",
"\"^\"",
"&&",
"charInfo",
".",
"startsCharClass",
")",
")",
".",
"filter",
"(",
"charInfo",
"=>",
"charInfo",
".",
"escaped",
")",
".",
"filter",
"(",
"charInfo",
"=>",
"!",
"(",
"charInfo",
".",
"inCharClass",
"?",
"REGEX_GENERAL_ESCAPES",
":",
"REGEX_NON_CHARCLASS_ESCAPES",
")",
".",
"has",
"(",
"charInfo",
".",
"text",
")",
")",
".",
"forEach",
"(",
"charInfo",
"=>",
"report",
"(",
"node",
",",
"charInfo",
".",
"index",
",",
"charInfo",
".",
"text",
")",
")",
";",
"}",
"}"
] |
Checks if a node has an escape.
@param {ASTNode} node - node to check.
@returns {void}
|
[
"Checks",
"if",
"a",
"node",
"has",
"an",
"escape",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-useless-escape.js#L158-L219
|
train
|
eslint/eslint
|
lib/formatters/table.js
|
drawTable
|
function drawTable(messages) {
const rows = [];
if (messages.length === 0) {
return "";
}
rows.push([
chalk.bold("Line"),
chalk.bold("Column"),
chalk.bold("Type"),
chalk.bold("Message"),
chalk.bold("Rule ID")
]);
messages.forEach(message => {
let messageType;
if (message.fatal || message.severity === 2) {
messageType = chalk.red("error");
} else {
messageType = chalk.yellow("warning");
}
rows.push([
message.line || 0,
message.column || 0,
messageType,
message.message,
message.ruleId || ""
]);
});
return table(rows, {
columns: {
0: {
width: 8,
wrapWord: true
},
1: {
width: 8,
wrapWord: true
},
2: {
width: 8,
wrapWord: true
},
3: {
paddingRight: 5,
width: 50,
wrapWord: true
},
4: {
width: 20,
wrapWord: true
}
},
drawHorizontalLine(index) {
return index === 1;
}
});
}
|
javascript
|
function drawTable(messages) {
const rows = [];
if (messages.length === 0) {
return "";
}
rows.push([
chalk.bold("Line"),
chalk.bold("Column"),
chalk.bold("Type"),
chalk.bold("Message"),
chalk.bold("Rule ID")
]);
messages.forEach(message => {
let messageType;
if (message.fatal || message.severity === 2) {
messageType = chalk.red("error");
} else {
messageType = chalk.yellow("warning");
}
rows.push([
message.line || 0,
message.column || 0,
messageType,
message.message,
message.ruleId || ""
]);
});
return table(rows, {
columns: {
0: {
width: 8,
wrapWord: true
},
1: {
width: 8,
wrapWord: true
},
2: {
width: 8,
wrapWord: true
},
3: {
paddingRight: 5,
width: 50,
wrapWord: true
},
4: {
width: 20,
wrapWord: true
}
},
drawHorizontalLine(index) {
return index === 1;
}
});
}
|
[
"function",
"drawTable",
"(",
"messages",
")",
"{",
"const",
"rows",
"=",
"[",
"]",
";",
"if",
"(",
"messages",
".",
"length",
"===",
"0",
")",
"{",
"return",
"\"\"",
";",
"}",
"rows",
".",
"push",
"(",
"[",
"chalk",
".",
"bold",
"(",
"\"Line\"",
")",
",",
"chalk",
".",
"bold",
"(",
"\"Column\"",
")",
",",
"chalk",
".",
"bold",
"(",
"\"Type\"",
")",
",",
"chalk",
".",
"bold",
"(",
"\"Message\"",
")",
",",
"chalk",
".",
"bold",
"(",
"\"Rule ID\"",
")",
"]",
")",
";",
"messages",
".",
"forEach",
"(",
"message",
"=>",
"{",
"let",
"messageType",
";",
"if",
"(",
"message",
".",
"fatal",
"||",
"message",
".",
"severity",
"===",
"2",
")",
"{",
"messageType",
"=",
"chalk",
".",
"red",
"(",
"\"error\"",
")",
";",
"}",
"else",
"{",
"messageType",
"=",
"chalk",
".",
"yellow",
"(",
"\"warning\"",
")",
";",
"}",
"rows",
".",
"push",
"(",
"[",
"message",
".",
"line",
"||",
"0",
",",
"message",
".",
"column",
"||",
"0",
",",
"messageType",
",",
"message",
".",
"message",
",",
"message",
".",
"ruleId",
"||",
"\"\"",
"]",
")",
";",
"}",
")",
";",
"return",
"table",
"(",
"rows",
",",
"{",
"columns",
":",
"{",
"0",
":",
"{",
"width",
":",
"8",
",",
"wrapWord",
":",
"true",
"}",
",",
"1",
":",
"{",
"width",
":",
"8",
",",
"wrapWord",
":",
"true",
"}",
",",
"2",
":",
"{",
"width",
":",
"8",
",",
"wrapWord",
":",
"true",
"}",
",",
"3",
":",
"{",
"paddingRight",
":",
"5",
",",
"width",
":",
"50",
",",
"wrapWord",
":",
"true",
"}",
",",
"4",
":",
"{",
"width",
":",
"20",
",",
"wrapWord",
":",
"true",
"}",
"}",
",",
"drawHorizontalLine",
"(",
"index",
")",
"{",
"return",
"index",
"===",
"1",
";",
"}",
"}",
")",
";",
"}"
] |
Draws text table.
@param {Array<Object>} messages Error messages relating to a specific file.
@returns {string} A text table.
|
[
"Draws",
"text",
"table",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/formatters/table.js#L33-L94
|
train
|
eslint/eslint
|
lib/util/npm-utils.js
|
fetchPeerDependencies
|
function fetchPeerDependencies(packageName) {
const npmProcess = spawn.sync(
"npm",
["show", "--json", packageName, "peerDependencies"],
{ encoding: "utf8" }
);
const error = npmProcess.error;
if (error && error.code === "ENOENT") {
return null;
}
const fetchedText = npmProcess.stdout.trim();
return JSON.parse(fetchedText || "{}");
}
|
javascript
|
function fetchPeerDependencies(packageName) {
const npmProcess = spawn.sync(
"npm",
["show", "--json", packageName, "peerDependencies"],
{ encoding: "utf8" }
);
const error = npmProcess.error;
if (error && error.code === "ENOENT") {
return null;
}
const fetchedText = npmProcess.stdout.trim();
return JSON.parse(fetchedText || "{}");
}
|
[
"function",
"fetchPeerDependencies",
"(",
"packageName",
")",
"{",
"const",
"npmProcess",
"=",
"spawn",
".",
"sync",
"(",
"\"npm\"",
",",
"[",
"\"show\"",
",",
"\"--json\"",
",",
"packageName",
",",
"\"peerDependencies\"",
"]",
",",
"{",
"encoding",
":",
"\"utf8\"",
"}",
")",
";",
"const",
"error",
"=",
"npmProcess",
".",
"error",
";",
"if",
"(",
"error",
"&&",
"error",
".",
"code",
"===",
"\"ENOENT\"",
")",
"{",
"return",
"null",
";",
"}",
"const",
"fetchedText",
"=",
"npmProcess",
".",
"stdout",
".",
"trim",
"(",
")",
";",
"return",
"JSON",
".",
"parse",
"(",
"fetchedText",
"||",
"\"{}\"",
")",
";",
"}"
] |
Fetch `peerDependencies` of the given package by `npm show` command.
@param {string} packageName The package name to fetch peerDependencies.
@returns {Object} Gotten peerDependencies. Returns null if npm was not found.
|
[
"Fetch",
"peerDependencies",
"of",
"the",
"given",
"package",
"by",
"npm",
"show",
"command",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/util/npm-utils.js#L70-L87
|
train
|
eslint/eslint
|
lib/util/npm-utils.js
|
check
|
function check(packages, opt) {
let deps = [];
const pkgJson = (opt) ? findPackageJson(opt.startDir) : findPackageJson();
let fileJson;
if (!pkgJson) {
throw new Error("Could not find a package.json file. Run 'npm init' to create one.");
}
try {
fileJson = JSON.parse(fs.readFileSync(pkgJson, "utf8"));
} catch (e) {
const error = new Error(e);
error.messageTemplate = "failed-to-read-json";
error.messageData = {
path: pkgJson,
message: e.message
};
throw error;
}
if (opt.devDependencies && typeof fileJson.devDependencies === "object") {
deps = deps.concat(Object.keys(fileJson.devDependencies));
}
if (opt.dependencies && typeof fileJson.dependencies === "object") {
deps = deps.concat(Object.keys(fileJson.dependencies));
}
return packages.reduce((status, pkg) => {
status[pkg] = deps.indexOf(pkg) !== -1;
return status;
}, {});
}
|
javascript
|
function check(packages, opt) {
let deps = [];
const pkgJson = (opt) ? findPackageJson(opt.startDir) : findPackageJson();
let fileJson;
if (!pkgJson) {
throw new Error("Could not find a package.json file. Run 'npm init' to create one.");
}
try {
fileJson = JSON.parse(fs.readFileSync(pkgJson, "utf8"));
} catch (e) {
const error = new Error(e);
error.messageTemplate = "failed-to-read-json";
error.messageData = {
path: pkgJson,
message: e.message
};
throw error;
}
if (opt.devDependencies && typeof fileJson.devDependencies === "object") {
deps = deps.concat(Object.keys(fileJson.devDependencies));
}
if (opt.dependencies && typeof fileJson.dependencies === "object") {
deps = deps.concat(Object.keys(fileJson.dependencies));
}
return packages.reduce((status, pkg) => {
status[pkg] = deps.indexOf(pkg) !== -1;
return status;
}, {});
}
|
[
"function",
"check",
"(",
"packages",
",",
"opt",
")",
"{",
"let",
"deps",
"=",
"[",
"]",
";",
"const",
"pkgJson",
"=",
"(",
"opt",
")",
"?",
"findPackageJson",
"(",
"opt",
".",
"startDir",
")",
":",
"findPackageJson",
"(",
")",
";",
"let",
"fileJson",
";",
"if",
"(",
"!",
"pkgJson",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"Could not find a package.json file. Run 'npm init' to create one.\"",
")",
";",
"}",
"try",
"{",
"fileJson",
"=",
"JSON",
".",
"parse",
"(",
"fs",
".",
"readFileSync",
"(",
"pkgJson",
",",
"\"utf8\"",
")",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"const",
"error",
"=",
"new",
"Error",
"(",
"e",
")",
";",
"error",
".",
"messageTemplate",
"=",
"\"failed-to-read-json\"",
";",
"error",
".",
"messageData",
"=",
"{",
"path",
":",
"pkgJson",
",",
"message",
":",
"e",
".",
"message",
"}",
";",
"throw",
"error",
";",
"}",
"if",
"(",
"opt",
".",
"devDependencies",
"&&",
"typeof",
"fileJson",
".",
"devDependencies",
"===",
"\"object\"",
")",
"{",
"deps",
"=",
"deps",
".",
"concat",
"(",
"Object",
".",
"keys",
"(",
"fileJson",
".",
"devDependencies",
")",
")",
";",
"}",
"if",
"(",
"opt",
".",
"dependencies",
"&&",
"typeof",
"fileJson",
".",
"dependencies",
"===",
"\"object\"",
")",
"{",
"deps",
"=",
"deps",
".",
"concat",
"(",
"Object",
".",
"keys",
"(",
"fileJson",
".",
"dependencies",
")",
")",
";",
"}",
"return",
"packages",
".",
"reduce",
"(",
"(",
"status",
",",
"pkg",
")",
"=>",
"{",
"status",
"[",
"pkg",
"]",
"=",
"deps",
".",
"indexOf",
"(",
"pkg",
")",
"!==",
"-",
"1",
";",
"return",
"status",
";",
"}",
",",
"{",
"}",
")",
";",
"}"
] |
Check whether node modules are include in a project's package.json.
@param {string[]} packages Array of node module names
@param {Object} opt Options Object
@param {boolean} opt.dependencies Set to true to check for direct dependencies
@param {boolean} opt.devDependencies Set to true to check for development dependencies
@param {boolean} opt.startdir Directory to begin searching from
@returns {Object} An object whose keys are the module names
and values are booleans indicating installation.
|
[
"Check",
"whether",
"node",
"modules",
"are",
"include",
"in",
"a",
"project",
"s",
"package",
".",
"json",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/util/npm-utils.js#L100-L132
|
train
|
eslint/eslint
|
lib/rules/vars-on-top.js
|
looksLikeImport
|
function looksLikeImport(node) {
return node.type === "ImportDeclaration" || node.type === "ImportSpecifier" ||
node.type === "ImportDefaultSpecifier" || node.type === "ImportNamespaceSpecifier";
}
|
javascript
|
function looksLikeImport(node) {
return node.type === "ImportDeclaration" || node.type === "ImportSpecifier" ||
node.type === "ImportDefaultSpecifier" || node.type === "ImportNamespaceSpecifier";
}
|
[
"function",
"looksLikeImport",
"(",
"node",
")",
"{",
"return",
"node",
".",
"type",
"===",
"\"ImportDeclaration\"",
"||",
"node",
".",
"type",
"===",
"\"ImportSpecifier\"",
"||",
"node",
".",
"type",
"===",
"\"ImportDefaultSpecifier\"",
"||",
"node",
".",
"type",
"===",
"\"ImportNamespaceSpecifier\"",
";",
"}"
] |
Check to see if its a ES6 import declaration
@param {ASTNode} node - any node
@returns {boolean} whether the given node represents a import declaration
|
[
"Check",
"to",
"see",
"if",
"its",
"a",
"ES6",
"import",
"declaration"
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/vars-on-top.js#L49-L52
|
train
|
eslint/eslint
|
lib/rules/vars-on-top.js
|
isVariableDeclaration
|
function isVariableDeclaration(node) {
return (
node.type === "VariableDeclaration" ||
(
node.type === "ExportNamedDeclaration" &&
node.declaration &&
node.declaration.type === "VariableDeclaration"
)
);
}
|
javascript
|
function isVariableDeclaration(node) {
return (
node.type === "VariableDeclaration" ||
(
node.type === "ExportNamedDeclaration" &&
node.declaration &&
node.declaration.type === "VariableDeclaration"
)
);
}
|
[
"function",
"isVariableDeclaration",
"(",
"node",
")",
"{",
"return",
"(",
"node",
".",
"type",
"===",
"\"VariableDeclaration\"",
"||",
"(",
"node",
".",
"type",
"===",
"\"ExportNamedDeclaration\"",
"&&",
"node",
".",
"declaration",
"&&",
"node",
".",
"declaration",
".",
"type",
"===",
"\"VariableDeclaration\"",
")",
")",
";",
"}"
] |
Checks whether a given node is a variable declaration or not.
@param {ASTNode} node - any node
@returns {boolean} `true` if the node is a variable declaration.
|
[
"Checks",
"whether",
"a",
"given",
"node",
"is",
"a",
"variable",
"declaration",
"or",
"not",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/vars-on-top.js#L60-L69
|
train
|
eslint/eslint
|
lib/rules/vars-on-top.js
|
isVarOnTop
|
function isVarOnTop(node, statements) {
const l = statements.length;
let i = 0;
// skip over directives
for (; i < l; ++i) {
if (!looksLikeDirective(statements[i]) && !looksLikeImport(statements[i])) {
break;
}
}
for (; i < l; ++i) {
if (!isVariableDeclaration(statements[i])) {
return false;
}
if (statements[i] === node) {
return true;
}
}
return false;
}
|
javascript
|
function isVarOnTop(node, statements) {
const l = statements.length;
let i = 0;
// skip over directives
for (; i < l; ++i) {
if (!looksLikeDirective(statements[i]) && !looksLikeImport(statements[i])) {
break;
}
}
for (; i < l; ++i) {
if (!isVariableDeclaration(statements[i])) {
return false;
}
if (statements[i] === node) {
return true;
}
}
return false;
}
|
[
"function",
"isVarOnTop",
"(",
"node",
",",
"statements",
")",
"{",
"const",
"l",
"=",
"statements",
".",
"length",
";",
"let",
"i",
"=",
"0",
";",
"for",
"(",
";",
"i",
"<",
"l",
";",
"++",
"i",
")",
"{",
"if",
"(",
"!",
"looksLikeDirective",
"(",
"statements",
"[",
"i",
"]",
")",
"&&",
"!",
"looksLikeImport",
"(",
"statements",
"[",
"i",
"]",
")",
")",
"{",
"break",
";",
"}",
"}",
"for",
"(",
";",
"i",
"<",
"l",
";",
"++",
"i",
")",
"{",
"if",
"(",
"!",
"isVariableDeclaration",
"(",
"statements",
"[",
"i",
"]",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"statements",
"[",
"i",
"]",
"===",
"node",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
] |
Checks whether this variable is on top of the block body
@param {ASTNode} node - The node to check
@param {ASTNode[]} statements - collection of ASTNodes for the parent node block
@returns {boolean} True if var is on top otherwise false
|
[
"Checks",
"whether",
"this",
"variable",
"is",
"on",
"top",
"of",
"the",
"block",
"body"
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/vars-on-top.js#L77-L98
|
train
|
eslint/eslint
|
lib/rules/vars-on-top.js
|
globalVarCheck
|
function globalVarCheck(node, parent) {
if (!isVarOnTop(node, parent.body)) {
context.report({ node, messageId: "top" });
}
}
|
javascript
|
function globalVarCheck(node, parent) {
if (!isVarOnTop(node, parent.body)) {
context.report({ node, messageId: "top" });
}
}
|
[
"function",
"globalVarCheck",
"(",
"node",
",",
"parent",
")",
"{",
"if",
"(",
"!",
"isVarOnTop",
"(",
"node",
",",
"parent",
".",
"body",
")",
")",
"{",
"context",
".",
"report",
"(",
"{",
"node",
",",
"messageId",
":",
"\"top\"",
"}",
")",
";",
"}",
"}"
] |
Checks whether variable is on top at the global level
@param {ASTNode} node - The node to check
@param {ASTNode} parent - Parent of the node
@returns {void}
|
[
"Checks",
"whether",
"variable",
"is",
"on",
"top",
"at",
"the",
"global",
"level"
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/vars-on-top.js#L106-L110
|
train
|
eslint/eslint
|
lib/rules/vars-on-top.js
|
blockScopeVarCheck
|
function blockScopeVarCheck(node, parent, grandParent) {
if (!(/Function/u.test(grandParent.type) &&
parent.type === "BlockStatement" &&
isVarOnTop(node, parent.body))) {
context.report({ node, messageId: "top" });
}
}
|
javascript
|
function blockScopeVarCheck(node, parent, grandParent) {
if (!(/Function/u.test(grandParent.type) &&
parent.type === "BlockStatement" &&
isVarOnTop(node, parent.body))) {
context.report({ node, messageId: "top" });
}
}
|
[
"function",
"blockScopeVarCheck",
"(",
"node",
",",
"parent",
",",
"grandParent",
")",
"{",
"if",
"(",
"!",
"(",
"/",
"Function",
"/",
"u",
".",
"test",
"(",
"grandParent",
".",
"type",
")",
"&&",
"parent",
".",
"type",
"===",
"\"BlockStatement\"",
"&&",
"isVarOnTop",
"(",
"node",
",",
"parent",
".",
"body",
")",
")",
")",
"{",
"context",
".",
"report",
"(",
"{",
"node",
",",
"messageId",
":",
"\"top\"",
"}",
")",
";",
"}",
"}"
] |
Checks whether variable is on top at functional block scope level
@param {ASTNode} node - The node to check
@param {ASTNode} parent - Parent of the node
@param {ASTNode} grandParent - Parent of the node's parent
@returns {void}
|
[
"Checks",
"whether",
"variable",
"is",
"on",
"top",
"at",
"functional",
"block",
"scope",
"level"
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/vars-on-top.js#L119-L125
|
train
|
eslint/eslint
|
tools/internal-rules/consistent-docs-url.js
|
checkMetaDocsUrl
|
function checkMetaDocsUrl(context, exportsNode) {
if (exportsNode.type !== "ObjectExpression") {
// if the exported node is not the correct format, "internal-no-invalid-meta" will already report this.
return;
}
const metaProperty = getPropertyFromObject("meta", exportsNode);
const metaDocs = metaProperty && getPropertyFromObject("docs", metaProperty.value);
const metaDocsUrl = metaDocs && getPropertyFromObject("url", metaDocs.value);
if (!metaDocs) {
context.report({
node: metaProperty,
message: "Rule is missing a meta.docs property"
});
return;
}
if (!metaDocsUrl) {
context.report({
node: metaDocs,
message: "Rule is missing a meta.docs.url property"
});
return;
}
const ruleId = path.basename(context.getFilename().replace(/.js$/u, ""));
const expected = `https://eslint.org/docs/rules/${ruleId}`;
const url = metaDocsUrl.value.value;
if (url !== expected) {
context.report({
node: metaDocsUrl.value,
message: `Incorrect url. Expected "${expected}" but got "${url}"`
});
}
}
|
javascript
|
function checkMetaDocsUrl(context, exportsNode) {
if (exportsNode.type !== "ObjectExpression") {
// if the exported node is not the correct format, "internal-no-invalid-meta" will already report this.
return;
}
const metaProperty = getPropertyFromObject("meta", exportsNode);
const metaDocs = metaProperty && getPropertyFromObject("docs", metaProperty.value);
const metaDocsUrl = metaDocs && getPropertyFromObject("url", metaDocs.value);
if (!metaDocs) {
context.report({
node: metaProperty,
message: "Rule is missing a meta.docs property"
});
return;
}
if (!metaDocsUrl) {
context.report({
node: metaDocs,
message: "Rule is missing a meta.docs.url property"
});
return;
}
const ruleId = path.basename(context.getFilename().replace(/.js$/u, ""));
const expected = `https://eslint.org/docs/rules/${ruleId}`;
const url = metaDocsUrl.value.value;
if (url !== expected) {
context.report({
node: metaDocsUrl.value,
message: `Incorrect url. Expected "${expected}" but got "${url}"`
});
}
}
|
[
"function",
"checkMetaDocsUrl",
"(",
"context",
",",
"exportsNode",
")",
"{",
"if",
"(",
"exportsNode",
".",
"type",
"!==",
"\"ObjectExpression\"",
")",
"{",
"return",
";",
"}",
"const",
"metaProperty",
"=",
"getPropertyFromObject",
"(",
"\"meta\"",
",",
"exportsNode",
")",
";",
"const",
"metaDocs",
"=",
"metaProperty",
"&&",
"getPropertyFromObject",
"(",
"\"docs\"",
",",
"metaProperty",
".",
"value",
")",
";",
"const",
"metaDocsUrl",
"=",
"metaDocs",
"&&",
"getPropertyFromObject",
"(",
"\"url\"",
",",
"metaDocs",
".",
"value",
")",
";",
"if",
"(",
"!",
"metaDocs",
")",
"{",
"context",
".",
"report",
"(",
"{",
"node",
":",
"metaProperty",
",",
"message",
":",
"\"Rule is missing a meta.docs property\"",
"}",
")",
";",
"return",
";",
"}",
"if",
"(",
"!",
"metaDocsUrl",
")",
"{",
"context",
".",
"report",
"(",
"{",
"node",
":",
"metaDocs",
",",
"message",
":",
"\"Rule is missing a meta.docs.url property\"",
"}",
")",
";",
"return",
";",
"}",
"const",
"ruleId",
"=",
"path",
".",
"basename",
"(",
"context",
".",
"getFilename",
"(",
")",
".",
"replace",
"(",
"/",
".js$",
"/",
"u",
",",
"\"\"",
")",
")",
";",
"const",
"expected",
"=",
"`",
"${",
"ruleId",
"}",
"`",
";",
"const",
"url",
"=",
"metaDocsUrl",
".",
"value",
".",
"value",
";",
"if",
"(",
"url",
"!==",
"expected",
")",
"{",
"context",
".",
"report",
"(",
"{",
"node",
":",
"metaDocsUrl",
".",
"value",
",",
"message",
":",
"`",
"${",
"expected",
"}",
"${",
"url",
"}",
"`",
"}",
")",
";",
"}",
"}"
] |
Verifies that the meta.docs.url property is present and has the correct value.
@param {RuleContext} context The ESLint rule context.
@param {ASTNode} exportsNode ObjectExpression node that the rule exports.
@returns {void}
|
[
"Verifies",
"that",
"the",
"meta",
".",
"docs",
".",
"url",
"property",
"is",
"present",
"and",
"has",
"the",
"correct",
"value",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/tools/internal-rules/consistent-docs-url.js#L46-L84
|
train
|
eslint/eslint
|
lib/rules/no-restricted-globals.js
|
reportReference
|
function reportReference(reference) {
const name = reference.identifier.name,
customMessage = restrictedGlobalMessages[name],
message = customMessage
? CUSTOM_MESSAGE_TEMPLATE
: DEFAULT_MESSAGE_TEMPLATE;
context.report({
node: reference.identifier,
message,
data: {
name,
customMessage
}
});
}
|
javascript
|
function reportReference(reference) {
const name = reference.identifier.name,
customMessage = restrictedGlobalMessages[name],
message = customMessage
? CUSTOM_MESSAGE_TEMPLATE
: DEFAULT_MESSAGE_TEMPLATE;
context.report({
node: reference.identifier,
message,
data: {
name,
customMessage
}
});
}
|
[
"function",
"reportReference",
"(",
"reference",
")",
"{",
"const",
"name",
"=",
"reference",
".",
"identifier",
".",
"name",
",",
"customMessage",
"=",
"restrictedGlobalMessages",
"[",
"name",
"]",
",",
"message",
"=",
"customMessage",
"?",
"CUSTOM_MESSAGE_TEMPLATE",
":",
"DEFAULT_MESSAGE_TEMPLATE",
";",
"context",
".",
"report",
"(",
"{",
"node",
":",
"reference",
".",
"identifier",
",",
"message",
",",
"data",
":",
"{",
"name",
",",
"customMessage",
"}",
"}",
")",
";",
"}"
] |
Report a variable to be used as a restricted global.
@param {Reference} reference the variable reference
@returns {void}
@private
|
[
"Report",
"a",
"variable",
"to",
"be",
"used",
"as",
"a",
"restricted",
"global",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-restricted-globals.js#L75-L90
|
train
|
eslint/eslint
|
lib/rules/newline-before-return.js
|
isFirstNode
|
function isFirstNode(node) {
const parentType = node.parent.type;
if (node.parent.body) {
return Array.isArray(node.parent.body)
? node.parent.body[0] === node
: node.parent.body === node;
}
if (parentType === "IfStatement") {
return isPrecededByTokens(node, ["else", ")"]);
}
if (parentType === "DoWhileStatement") {
return isPrecededByTokens(node, ["do"]);
}
if (parentType === "SwitchCase") {
return isPrecededByTokens(node, [":"]);
}
return isPrecededByTokens(node, [")"]);
}
|
javascript
|
function isFirstNode(node) {
const parentType = node.parent.type;
if (node.parent.body) {
return Array.isArray(node.parent.body)
? node.parent.body[0] === node
: node.parent.body === node;
}
if (parentType === "IfStatement") {
return isPrecededByTokens(node, ["else", ")"]);
}
if (parentType === "DoWhileStatement") {
return isPrecededByTokens(node, ["do"]);
}
if (parentType === "SwitchCase") {
return isPrecededByTokens(node, [":"]);
}
return isPrecededByTokens(node, [")"]);
}
|
[
"function",
"isFirstNode",
"(",
"node",
")",
"{",
"const",
"parentType",
"=",
"node",
".",
"parent",
".",
"type",
";",
"if",
"(",
"node",
".",
"parent",
".",
"body",
")",
"{",
"return",
"Array",
".",
"isArray",
"(",
"node",
".",
"parent",
".",
"body",
")",
"?",
"node",
".",
"parent",
".",
"body",
"[",
"0",
"]",
"===",
"node",
":",
"node",
".",
"parent",
".",
"body",
"===",
"node",
";",
"}",
"if",
"(",
"parentType",
"===",
"\"IfStatement\"",
")",
"{",
"return",
"isPrecededByTokens",
"(",
"node",
",",
"[",
"\"else\"",
",",
"\")\"",
"]",
")",
";",
"}",
"if",
"(",
"parentType",
"===",
"\"DoWhileStatement\"",
")",
"{",
"return",
"isPrecededByTokens",
"(",
"node",
",",
"[",
"\"do\"",
"]",
")",
";",
"}",
"if",
"(",
"parentType",
"===",
"\"SwitchCase\"",
")",
"{",
"return",
"isPrecededByTokens",
"(",
"node",
",",
"[",
"\":\"",
"]",
")",
";",
"}",
"return",
"isPrecededByTokens",
"(",
"node",
",",
"[",
"\")\"",
"]",
")",
";",
"}"
] |
Checks whether node is the first node after statement or in block
@param {ASTNode} node - node to check
@returns {boolean} Whether or not the node is the first node after statement or in block
@private
|
[
"Checks",
"whether",
"node",
"is",
"the",
"first",
"node",
"after",
"statement",
"or",
"in",
"block"
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/newline-before-return.js#L59-L79
|
train
|
eslint/eslint
|
lib/rules/newline-before-return.js
|
calcCommentLines
|
function calcCommentLines(node, lineNumTokenBefore) {
const comments = sourceCode.getCommentsBefore(node);
let numLinesComments = 0;
if (!comments.length) {
return numLinesComments;
}
comments.forEach(comment => {
numLinesComments++;
if (comment.type === "Block") {
numLinesComments += comment.loc.end.line - comment.loc.start.line;
}
// avoid counting lines with inline comments twice
if (comment.loc.start.line === lineNumTokenBefore) {
numLinesComments--;
}
if (comment.loc.end.line === node.loc.start.line) {
numLinesComments--;
}
});
return numLinesComments;
}
|
javascript
|
function calcCommentLines(node, lineNumTokenBefore) {
const comments = sourceCode.getCommentsBefore(node);
let numLinesComments = 0;
if (!comments.length) {
return numLinesComments;
}
comments.forEach(comment => {
numLinesComments++;
if (comment.type === "Block") {
numLinesComments += comment.loc.end.line - comment.loc.start.line;
}
// avoid counting lines with inline comments twice
if (comment.loc.start.line === lineNumTokenBefore) {
numLinesComments--;
}
if (comment.loc.end.line === node.loc.start.line) {
numLinesComments--;
}
});
return numLinesComments;
}
|
[
"function",
"calcCommentLines",
"(",
"node",
",",
"lineNumTokenBefore",
")",
"{",
"const",
"comments",
"=",
"sourceCode",
".",
"getCommentsBefore",
"(",
"node",
")",
";",
"let",
"numLinesComments",
"=",
"0",
";",
"if",
"(",
"!",
"comments",
".",
"length",
")",
"{",
"return",
"numLinesComments",
";",
"}",
"comments",
".",
"forEach",
"(",
"comment",
"=>",
"{",
"numLinesComments",
"++",
";",
"if",
"(",
"comment",
".",
"type",
"===",
"\"Block\"",
")",
"{",
"numLinesComments",
"+=",
"comment",
".",
"loc",
".",
"end",
".",
"line",
"-",
"comment",
".",
"loc",
".",
"start",
".",
"line",
";",
"}",
"if",
"(",
"comment",
".",
"loc",
".",
"start",
".",
"line",
"===",
"lineNumTokenBefore",
")",
"{",
"numLinesComments",
"--",
";",
"}",
"if",
"(",
"comment",
".",
"loc",
".",
"end",
".",
"line",
"===",
"node",
".",
"loc",
".",
"start",
".",
"line",
")",
"{",
"numLinesComments",
"--",
";",
"}",
"}",
")",
";",
"return",
"numLinesComments",
";",
"}"
] |
Returns the number of lines of comments that precede the node
@param {ASTNode} node - node to check for overlapping comments
@param {number} lineNumTokenBefore - line number of previous token, to check for overlapping comments
@returns {number} Number of lines of comments that precede the node
@private
|
[
"Returns",
"the",
"number",
"of",
"lines",
"of",
"comments",
"that",
"precede",
"the",
"node"
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/newline-before-return.js#L88-L114
|
train
|
eslint/eslint
|
lib/rules/newline-before-return.js
|
getLineNumberOfTokenBefore
|
function getLineNumberOfTokenBefore(node) {
const tokenBefore = sourceCode.getTokenBefore(node);
let lineNumTokenBefore;
/**
* Global return (at the beginning of a script) is a special case.
* If there is no token before `return`, then we expect no line
* break before the return. Comments are allowed to occupy lines
* before the global return, just no blank lines.
* Setting lineNumTokenBefore to zero in that case results in the
* desired behavior.
*/
if (tokenBefore) {
lineNumTokenBefore = tokenBefore.loc.end.line;
} else {
lineNumTokenBefore = 0; // global return at beginning of script
}
return lineNumTokenBefore;
}
|
javascript
|
function getLineNumberOfTokenBefore(node) {
const tokenBefore = sourceCode.getTokenBefore(node);
let lineNumTokenBefore;
/**
* Global return (at the beginning of a script) is a special case.
* If there is no token before `return`, then we expect no line
* break before the return. Comments are allowed to occupy lines
* before the global return, just no blank lines.
* Setting lineNumTokenBefore to zero in that case results in the
* desired behavior.
*/
if (tokenBefore) {
lineNumTokenBefore = tokenBefore.loc.end.line;
} else {
lineNumTokenBefore = 0; // global return at beginning of script
}
return lineNumTokenBefore;
}
|
[
"function",
"getLineNumberOfTokenBefore",
"(",
"node",
")",
"{",
"const",
"tokenBefore",
"=",
"sourceCode",
".",
"getTokenBefore",
"(",
"node",
")",
";",
"let",
"lineNumTokenBefore",
";",
"if",
"(",
"tokenBefore",
")",
"{",
"lineNumTokenBefore",
"=",
"tokenBefore",
".",
"loc",
".",
"end",
".",
"line",
";",
"}",
"else",
"{",
"lineNumTokenBefore",
"=",
"0",
";",
"}",
"return",
"lineNumTokenBefore",
";",
"}"
] |
Returns the line number of the token before the node that is passed in as an argument
@param {ASTNode} node - The node to use as the start of the calculation
@returns {number} Line number of the token before `node`
@private
|
[
"Returns",
"the",
"line",
"number",
"of",
"the",
"token",
"before",
"the",
"node",
"that",
"is",
"passed",
"in",
"as",
"an",
"argument"
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/newline-before-return.js#L122-L141
|
train
|
eslint/eslint
|
lib/rules/newline-before-return.js
|
hasNewlineBefore
|
function hasNewlineBefore(node) {
const lineNumNode = node.loc.start.line;
const lineNumTokenBefore = getLineNumberOfTokenBefore(node);
const commentLines = calcCommentLines(node, lineNumTokenBefore);
return (lineNumNode - lineNumTokenBefore - commentLines) > 1;
}
|
javascript
|
function hasNewlineBefore(node) {
const lineNumNode = node.loc.start.line;
const lineNumTokenBefore = getLineNumberOfTokenBefore(node);
const commentLines = calcCommentLines(node, lineNumTokenBefore);
return (lineNumNode - lineNumTokenBefore - commentLines) > 1;
}
|
[
"function",
"hasNewlineBefore",
"(",
"node",
")",
"{",
"const",
"lineNumNode",
"=",
"node",
".",
"loc",
".",
"start",
".",
"line",
";",
"const",
"lineNumTokenBefore",
"=",
"getLineNumberOfTokenBefore",
"(",
"node",
")",
";",
"const",
"commentLines",
"=",
"calcCommentLines",
"(",
"node",
",",
"lineNumTokenBefore",
")",
";",
"return",
"(",
"lineNumNode",
"-",
"lineNumTokenBefore",
"-",
"commentLines",
")",
">",
"1",
";",
"}"
] |
Checks whether node is preceded by a newline
@param {ASTNode} node - node to check
@returns {boolean} Whether or not the node is preceded by a newline
@private
|
[
"Checks",
"whether",
"node",
"is",
"preceded",
"by",
"a",
"newline"
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/newline-before-return.js#L149-L155
|
train
|
eslint/eslint
|
lib/rules/newline-before-return.js
|
canFix
|
function canFix(node) {
const leadingComments = sourceCode.getCommentsBefore(node);
const lastLeadingComment = leadingComments[leadingComments.length - 1];
const tokenBefore = sourceCode.getTokenBefore(node);
if (leadingComments.length === 0) {
return true;
}
/*
* if the last leading comment ends in the same line as the previous token and
* does not share a line with the `return` node, we can consider it safe to fix.
* Example:
* function a() {
* var b; //comment
* return;
* }
*/
if (lastLeadingComment.loc.end.line === tokenBefore.loc.end.line &&
lastLeadingComment.loc.end.line !== node.loc.start.line) {
return true;
}
return false;
}
|
javascript
|
function canFix(node) {
const leadingComments = sourceCode.getCommentsBefore(node);
const lastLeadingComment = leadingComments[leadingComments.length - 1];
const tokenBefore = sourceCode.getTokenBefore(node);
if (leadingComments.length === 0) {
return true;
}
/*
* if the last leading comment ends in the same line as the previous token and
* does not share a line with the `return` node, we can consider it safe to fix.
* Example:
* function a() {
* var b; //comment
* return;
* }
*/
if (lastLeadingComment.loc.end.line === tokenBefore.loc.end.line &&
lastLeadingComment.loc.end.line !== node.loc.start.line) {
return true;
}
return false;
}
|
[
"function",
"canFix",
"(",
"node",
")",
"{",
"const",
"leadingComments",
"=",
"sourceCode",
".",
"getCommentsBefore",
"(",
"node",
")",
";",
"const",
"lastLeadingComment",
"=",
"leadingComments",
"[",
"leadingComments",
".",
"length",
"-",
"1",
"]",
";",
"const",
"tokenBefore",
"=",
"sourceCode",
".",
"getTokenBefore",
"(",
"node",
")",
";",
"if",
"(",
"leadingComments",
".",
"length",
"===",
"0",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"lastLeadingComment",
".",
"loc",
".",
"end",
".",
"line",
"===",
"tokenBefore",
".",
"loc",
".",
"end",
".",
"line",
"&&",
"lastLeadingComment",
".",
"loc",
".",
"end",
".",
"line",
"!==",
"node",
".",
"loc",
".",
"start",
".",
"line",
")",
"{",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] |
Checks whether it is safe to apply a fix to a given return statement.
The fix is not considered safe if the given return statement has leading comments,
as we cannot safely determine if the newline should be added before or after the comments.
For more information, see: https://github.com/eslint/eslint/issues/5958#issuecomment-222767211
@param {ASTNode} node - The return statement node to check.
@returns {boolean} `true` if it can fix the node.
@private
|
[
"Checks",
"whether",
"it",
"is",
"safe",
"to",
"apply",
"a",
"fix",
"to",
"a",
"given",
"return",
"statement",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/newline-before-return.js#L168-L192
|
train
|
eslint/eslint
|
lib/rules/no-fallthrough.js
|
hasFallthroughComment
|
function hasFallthroughComment(node, context, fallthroughCommentPattern) {
const sourceCode = context.getSourceCode();
const comment = lodash.last(sourceCode.getCommentsBefore(node));
return Boolean(comment && fallthroughCommentPattern.test(comment.value));
}
|
javascript
|
function hasFallthroughComment(node, context, fallthroughCommentPattern) {
const sourceCode = context.getSourceCode();
const comment = lodash.last(sourceCode.getCommentsBefore(node));
return Boolean(comment && fallthroughCommentPattern.test(comment.value));
}
|
[
"function",
"hasFallthroughComment",
"(",
"node",
",",
"context",
",",
"fallthroughCommentPattern",
")",
"{",
"const",
"sourceCode",
"=",
"context",
".",
"getSourceCode",
"(",
")",
";",
"const",
"comment",
"=",
"lodash",
".",
"last",
"(",
"sourceCode",
".",
"getCommentsBefore",
"(",
"node",
")",
")",
";",
"return",
"Boolean",
"(",
"comment",
"&&",
"fallthroughCommentPattern",
".",
"test",
"(",
"comment",
".",
"value",
")",
")",
";",
"}"
] |
Checks whether or not a given node has a fallthrough comment.
@param {ASTNode} node - A SwitchCase node to get comments.
@param {RuleContext} context - A rule context which stores comments.
@param {RegExp} fallthroughCommentPattern - A pattern to match comment to.
@returns {boolean} `true` if the node has a valid fallthrough comment.
|
[
"Checks",
"whether",
"or",
"not",
"a",
"given",
"node",
"has",
"a",
"fallthrough",
"comment",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-fallthrough.js#L26-L31
|
train
|
eslint/eslint
|
lib/rules/no-fallthrough.js
|
hasBlankLinesBetween
|
function hasBlankLinesBetween(node, token) {
return token.loc.start.line > node.loc.end.line + 1;
}
|
javascript
|
function hasBlankLinesBetween(node, token) {
return token.loc.start.line > node.loc.end.line + 1;
}
|
[
"function",
"hasBlankLinesBetween",
"(",
"node",
",",
"token",
")",
"{",
"return",
"token",
".",
"loc",
".",
"start",
".",
"line",
">",
"node",
".",
"loc",
".",
"end",
".",
"line",
"+",
"1",
";",
"}"
] |
Checks whether a node and a token are separated by blank lines
@param {ASTNode} node - The node to check
@param {Token} token - The token to compare against
@returns {boolean} `true` if there are blank lines between node and token
|
[
"Checks",
"whether",
"a",
"node",
"and",
"a",
"token",
"are",
"separated",
"by",
"blank",
"lines"
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-fallthrough.js#L48-L50
|
train
|
eslint/eslint
|
lib/rules/quotes.js
|
isJSXLiteral
|
function isJSXLiteral(node) {
return node.parent.type === "JSXAttribute" || node.parent.type === "JSXElement" || node.parent.type === "JSXFragment";
}
|
javascript
|
function isJSXLiteral(node) {
return node.parent.type === "JSXAttribute" || node.parent.type === "JSXElement" || node.parent.type === "JSXFragment";
}
|
[
"function",
"isJSXLiteral",
"(",
"node",
")",
"{",
"return",
"node",
".",
"parent",
".",
"type",
"===",
"\"JSXAttribute\"",
"||",
"node",
".",
"parent",
".",
"type",
"===",
"\"JSXElement\"",
"||",
"node",
".",
"parent",
".",
"type",
"===",
"\"JSXFragment\"",
";",
"}"
] |
Determines if a given node is part of JSX syntax.
This function returns `true` in the following cases:
- `<div className="foo"></div>` ... If the literal is an attribute value, the parent of the literal is `JSXAttribute`.
- `<div>foo</div>` ... If the literal is a text content, the parent of the literal is `JSXElement`.
- `<>foo</>` ... If the literal is a text content, the parent of the literal is `JSXFragment`.
In particular, this function returns `false` in the following cases:
- `<div className={"foo"}></div>`
- `<div>{"foo"}</div>`
In both cases, inside of the braces is handled as normal JavaScript.
The braces are `JSXExpressionContainer` nodes.
@param {ASTNode} node The Literal node to check.
@returns {boolean} True if the node is a part of JSX, false if not.
@private
|
[
"Determines",
"if",
"a",
"given",
"node",
"is",
"part",
"of",
"JSX",
"syntax",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/quotes.js#L151-L153
|
train
|
eslint/eslint
|
lib/rules/quotes.js
|
isAllowedAsNonBacktick
|
function isAllowedAsNonBacktick(node) {
const parent = node.parent;
switch (parent.type) {
// Directive Prologues.
case "ExpressionStatement":
return isPartOfDirectivePrologue(node);
// LiteralPropertyName.
case "Property":
case "MethodDefinition":
return parent.key === node && !parent.computed;
// ModuleSpecifier.
case "ImportDeclaration":
case "ExportNamedDeclaration":
case "ExportAllDeclaration":
return parent.source === node;
// Others don't allow.
default:
return false;
}
}
|
javascript
|
function isAllowedAsNonBacktick(node) {
const parent = node.parent;
switch (parent.type) {
// Directive Prologues.
case "ExpressionStatement":
return isPartOfDirectivePrologue(node);
// LiteralPropertyName.
case "Property":
case "MethodDefinition":
return parent.key === node && !parent.computed;
// ModuleSpecifier.
case "ImportDeclaration":
case "ExportNamedDeclaration":
case "ExportAllDeclaration":
return parent.source === node;
// Others don't allow.
default:
return false;
}
}
|
[
"function",
"isAllowedAsNonBacktick",
"(",
"node",
")",
"{",
"const",
"parent",
"=",
"node",
".",
"parent",
";",
"switch",
"(",
"parent",
".",
"type",
")",
"{",
"case",
"\"ExpressionStatement\"",
":",
"return",
"isPartOfDirectivePrologue",
"(",
"node",
")",
";",
"case",
"\"Property\"",
":",
"case",
"\"MethodDefinition\"",
":",
"return",
"parent",
".",
"key",
"===",
"node",
"&&",
"!",
"parent",
".",
"computed",
";",
"case",
"\"ImportDeclaration\"",
":",
"case",
"\"ExportNamedDeclaration\"",
":",
"case",
"\"ExportAllDeclaration\"",
":",
"return",
"parent",
".",
"source",
"===",
"node",
";",
"default",
":",
"return",
"false",
";",
"}",
"}"
] |
Checks whether or not a given node is allowed as non backtick.
@param {ASTNode} node - A node to check.
@returns {boolean} Whether or not the node is allowed as non backtick.
@private
|
[
"Checks",
"whether",
"or",
"not",
"a",
"given",
"node",
"is",
"allowed",
"as",
"non",
"backtick",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/quotes.js#L205-L229
|
train
|
eslint/eslint
|
lib/rules/quotes.js
|
isUsingFeatureOfTemplateLiteral
|
function isUsingFeatureOfTemplateLiteral(node) {
const hasTag = node.parent.type === "TaggedTemplateExpression" && node === node.parent.quasi;
if (hasTag) {
return true;
}
const hasStringInterpolation = node.expressions.length > 0;
if (hasStringInterpolation) {
return true;
}
const isMultilineString = node.quasis.length >= 1 && UNESCAPED_LINEBREAK_PATTERN.test(node.quasis[0].value.raw);
if (isMultilineString) {
return true;
}
return false;
}
|
javascript
|
function isUsingFeatureOfTemplateLiteral(node) {
const hasTag = node.parent.type === "TaggedTemplateExpression" && node === node.parent.quasi;
if (hasTag) {
return true;
}
const hasStringInterpolation = node.expressions.length > 0;
if (hasStringInterpolation) {
return true;
}
const isMultilineString = node.quasis.length >= 1 && UNESCAPED_LINEBREAK_PATTERN.test(node.quasis[0].value.raw);
if (isMultilineString) {
return true;
}
return false;
}
|
[
"function",
"isUsingFeatureOfTemplateLiteral",
"(",
"node",
")",
"{",
"const",
"hasTag",
"=",
"node",
".",
"parent",
".",
"type",
"===",
"\"TaggedTemplateExpression\"",
"&&",
"node",
"===",
"node",
".",
"parent",
".",
"quasi",
";",
"if",
"(",
"hasTag",
")",
"{",
"return",
"true",
";",
"}",
"const",
"hasStringInterpolation",
"=",
"node",
".",
"expressions",
".",
"length",
">",
"0",
";",
"if",
"(",
"hasStringInterpolation",
")",
"{",
"return",
"true",
";",
"}",
"const",
"isMultilineString",
"=",
"node",
".",
"quasis",
".",
"length",
">=",
"1",
"&&",
"UNESCAPED_LINEBREAK_PATTERN",
".",
"test",
"(",
"node",
".",
"quasis",
"[",
"0",
"]",
".",
"value",
".",
"raw",
")",
";",
"if",
"(",
"isMultilineString",
")",
"{",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] |
Checks whether or not a given TemplateLiteral node is actually using any of the special features provided by template literal strings.
@param {ASTNode} node - A TemplateLiteral node to check.
@returns {boolean} Whether or not the TemplateLiteral node is using any of the special features provided by template literal strings.
@private
|
[
"Checks",
"whether",
"or",
"not",
"a",
"given",
"TemplateLiteral",
"node",
"is",
"actually",
"using",
"any",
"of",
"the",
"special",
"features",
"provided",
"by",
"template",
"literal",
"strings",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/quotes.js#L237-L257
|
train
|
eslint/eslint
|
lib/config/config-initializer.js
|
getPeerDependencies
|
function getPeerDependencies(moduleName) {
let result = getPeerDependencies.cache.get(moduleName);
if (!result) {
log.info(`Checking peerDependencies of ${moduleName}`);
result = npmUtils.fetchPeerDependencies(moduleName);
getPeerDependencies.cache.set(moduleName, result);
}
return result;
}
|
javascript
|
function getPeerDependencies(moduleName) {
let result = getPeerDependencies.cache.get(moduleName);
if (!result) {
log.info(`Checking peerDependencies of ${moduleName}`);
result = npmUtils.fetchPeerDependencies(moduleName);
getPeerDependencies.cache.set(moduleName, result);
}
return result;
}
|
[
"function",
"getPeerDependencies",
"(",
"moduleName",
")",
"{",
"let",
"result",
"=",
"getPeerDependencies",
".",
"cache",
".",
"get",
"(",
"moduleName",
")",
";",
"if",
"(",
"!",
"result",
")",
"{",
"log",
".",
"info",
"(",
"`",
"${",
"moduleName",
"}",
"`",
")",
";",
"result",
"=",
"npmUtils",
".",
"fetchPeerDependencies",
"(",
"moduleName",
")",
";",
"getPeerDependencies",
".",
"cache",
".",
"set",
"(",
"moduleName",
",",
"result",
")",
";",
"}",
"return",
"result",
";",
"}"
] |
Get the peer dependencies of the given module.
This adds the gotten value to cache at the first time, then reuses it.
In a process, this function is called twice, but `npmUtils.fetchPeerDependencies` needs to access network which is relatively slow.
@param {string} moduleName The module name to get.
@returns {Object} The peer dependencies of the given module.
This object is the object of `peerDependencies` field of `package.json`.
Returns null if npm was not found.
|
[
"Get",
"the",
"peer",
"dependencies",
"of",
"the",
"given",
"module",
".",
"This",
"adds",
"the",
"gotten",
"value",
"to",
"cache",
"at",
"the",
"first",
"time",
"then",
"reuses",
"it",
".",
"In",
"a",
"process",
"this",
"function",
"is",
"called",
"twice",
"but",
"npmUtils",
".",
"fetchPeerDependencies",
"needs",
"to",
"access",
"network",
"which",
"is",
"relatively",
"slow",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/config/config-initializer.js#L74-L85
|
train
|
eslint/eslint
|
lib/config/config-initializer.js
|
getModulesList
|
function getModulesList(config, installESLint) {
const modules = {};
// Create a list of modules which should be installed based on config
if (config.plugins) {
for (const plugin of config.plugins) {
modules[`eslint-plugin-${plugin}`] = "latest";
}
}
if (config.extends && config.extends.indexOf("eslint:") === -1) {
const moduleName = `eslint-config-${config.extends}`;
modules[moduleName] = "latest";
Object.assign(
modules,
getPeerDependencies(`${moduleName}@latest`)
);
}
if (installESLint === false) {
delete modules.eslint;
} else {
const installStatus = npmUtils.checkDevDeps(["eslint"]);
// Mark to show messages if it's new installation of eslint.
if (installStatus.eslint === false) {
log.info("Local ESLint installation not found.");
modules.eslint = modules.eslint || "latest";
config.installedESLint = true;
}
}
return Object.keys(modules).map(name => `${name}@${modules[name]}`);
}
|
javascript
|
function getModulesList(config, installESLint) {
const modules = {};
// Create a list of modules which should be installed based on config
if (config.plugins) {
for (const plugin of config.plugins) {
modules[`eslint-plugin-${plugin}`] = "latest";
}
}
if (config.extends && config.extends.indexOf("eslint:") === -1) {
const moduleName = `eslint-config-${config.extends}`;
modules[moduleName] = "latest";
Object.assign(
modules,
getPeerDependencies(`${moduleName}@latest`)
);
}
if (installESLint === false) {
delete modules.eslint;
} else {
const installStatus = npmUtils.checkDevDeps(["eslint"]);
// Mark to show messages if it's new installation of eslint.
if (installStatus.eslint === false) {
log.info("Local ESLint installation not found.");
modules.eslint = modules.eslint || "latest";
config.installedESLint = true;
}
}
return Object.keys(modules).map(name => `${name}@${modules[name]}`);
}
|
[
"function",
"getModulesList",
"(",
"config",
",",
"installESLint",
")",
"{",
"const",
"modules",
"=",
"{",
"}",
";",
"if",
"(",
"config",
".",
"plugins",
")",
"{",
"for",
"(",
"const",
"plugin",
"of",
"config",
".",
"plugins",
")",
"{",
"modules",
"[",
"`",
"${",
"plugin",
"}",
"`",
"]",
"=",
"\"latest\"",
";",
"}",
"}",
"if",
"(",
"config",
".",
"extends",
"&&",
"config",
".",
"extends",
".",
"indexOf",
"(",
"\"eslint:\"",
")",
"===",
"-",
"1",
")",
"{",
"const",
"moduleName",
"=",
"`",
"${",
"config",
".",
"extends",
"}",
"`",
";",
"modules",
"[",
"moduleName",
"]",
"=",
"\"latest\"",
";",
"Object",
".",
"assign",
"(",
"modules",
",",
"getPeerDependencies",
"(",
"`",
"${",
"moduleName",
"}",
"`",
")",
")",
";",
"}",
"if",
"(",
"installESLint",
"===",
"false",
")",
"{",
"delete",
"modules",
".",
"eslint",
";",
"}",
"else",
"{",
"const",
"installStatus",
"=",
"npmUtils",
".",
"checkDevDeps",
"(",
"[",
"\"eslint\"",
"]",
")",
";",
"if",
"(",
"installStatus",
".",
"eslint",
"===",
"false",
")",
"{",
"log",
".",
"info",
"(",
"\"Local ESLint installation not found.\"",
")",
";",
"modules",
".",
"eslint",
"=",
"modules",
".",
"eslint",
"||",
"\"latest\"",
";",
"config",
".",
"installedESLint",
"=",
"true",
";",
"}",
"}",
"return",
"Object",
".",
"keys",
"(",
"modules",
")",
".",
"map",
"(",
"name",
"=>",
"`",
"${",
"name",
"}",
"${",
"modules",
"[",
"name",
"]",
"}",
"`",
")",
";",
"}"
] |
Return necessary plugins, configs, parsers, etc. based on the config
@param {Object} config config object
@param {boolean} [installESLint=true] If `false` is given, it does not install eslint.
@returns {string[]} An array of modules to be installed.
|
[
"Return",
"necessary",
"plugins",
"configs",
"parsers",
"etc",
".",
"based",
"on",
"the",
"config"
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/config/config-initializer.js#L94-L127
|
train
|
eslint/eslint
|
lib/config/config-initializer.js
|
processAnswers
|
function processAnswers(answers) {
let config = {
rules: {},
env: {},
parserOptions: {},
extends: []
};
// set the latest ECMAScript version
config.parserOptions.ecmaVersion = DEFAULT_ECMA_VERSION;
config.env.es6 = true;
config.globals = {
Atomics: "readonly",
SharedArrayBuffer: "readonly"
};
// set the module type
if (answers.moduleType === "esm") {
config.parserOptions.sourceType = "module";
} else if (answers.moduleType === "commonjs") {
config.env.commonjs = true;
}
// add in browser and node environments if necessary
answers.env.forEach(env => {
config.env[env] = true;
});
// add in library information
if (answers.framework === "react") {
config.parserOptions.ecmaFeatures = {
jsx: true
};
config.plugins = ["react"];
} else if (answers.framework === "vue") {
config.plugins = ["vue"];
config.extends.push("plugin:vue/essential");
}
// setup rules based on problems/style enforcement preferences
if (answers.purpose === "problems") {
config.extends.unshift("eslint:recommended");
} else if (answers.purpose === "style") {
if (answers.source === "prompt") {
config.extends.unshift("eslint:recommended");
config.rules.indent = ["error", answers.indent];
config.rules.quotes = ["error", answers.quotes];
config.rules["linebreak-style"] = ["error", answers.linebreak];
config.rules.semi = ["error", answers.semi ? "always" : "never"];
} else if (answers.source === "auto") {
config = configureRules(answers, config);
config = autoconfig.extendFromRecommended(config);
}
}
// normalize extends
if (config.extends.length === 0) {
delete config.extends;
} else if (config.extends.length === 1) {
config.extends = config.extends[0];
}
ConfigOps.normalizeToStrings(config);
return config;
}
|
javascript
|
function processAnswers(answers) {
let config = {
rules: {},
env: {},
parserOptions: {},
extends: []
};
// set the latest ECMAScript version
config.parserOptions.ecmaVersion = DEFAULT_ECMA_VERSION;
config.env.es6 = true;
config.globals = {
Atomics: "readonly",
SharedArrayBuffer: "readonly"
};
// set the module type
if (answers.moduleType === "esm") {
config.parserOptions.sourceType = "module";
} else if (answers.moduleType === "commonjs") {
config.env.commonjs = true;
}
// add in browser and node environments if necessary
answers.env.forEach(env => {
config.env[env] = true;
});
// add in library information
if (answers.framework === "react") {
config.parserOptions.ecmaFeatures = {
jsx: true
};
config.plugins = ["react"];
} else if (answers.framework === "vue") {
config.plugins = ["vue"];
config.extends.push("plugin:vue/essential");
}
// setup rules based on problems/style enforcement preferences
if (answers.purpose === "problems") {
config.extends.unshift("eslint:recommended");
} else if (answers.purpose === "style") {
if (answers.source === "prompt") {
config.extends.unshift("eslint:recommended");
config.rules.indent = ["error", answers.indent];
config.rules.quotes = ["error", answers.quotes];
config.rules["linebreak-style"] = ["error", answers.linebreak];
config.rules.semi = ["error", answers.semi ? "always" : "never"];
} else if (answers.source === "auto") {
config = configureRules(answers, config);
config = autoconfig.extendFromRecommended(config);
}
}
// normalize extends
if (config.extends.length === 0) {
delete config.extends;
} else if (config.extends.length === 1) {
config.extends = config.extends[0];
}
ConfigOps.normalizeToStrings(config);
return config;
}
|
[
"function",
"processAnswers",
"(",
"answers",
")",
"{",
"let",
"config",
"=",
"{",
"rules",
":",
"{",
"}",
",",
"env",
":",
"{",
"}",
",",
"parserOptions",
":",
"{",
"}",
",",
"extends",
":",
"[",
"]",
"}",
";",
"config",
".",
"parserOptions",
".",
"ecmaVersion",
"=",
"DEFAULT_ECMA_VERSION",
";",
"config",
".",
"env",
".",
"es6",
"=",
"true",
";",
"config",
".",
"globals",
"=",
"{",
"Atomics",
":",
"\"readonly\"",
",",
"SharedArrayBuffer",
":",
"\"readonly\"",
"}",
";",
"if",
"(",
"answers",
".",
"moduleType",
"===",
"\"esm\"",
")",
"{",
"config",
".",
"parserOptions",
".",
"sourceType",
"=",
"\"module\"",
";",
"}",
"else",
"if",
"(",
"answers",
".",
"moduleType",
"===",
"\"commonjs\"",
")",
"{",
"config",
".",
"env",
".",
"commonjs",
"=",
"true",
";",
"}",
"answers",
".",
"env",
".",
"forEach",
"(",
"env",
"=>",
"{",
"config",
".",
"env",
"[",
"env",
"]",
"=",
"true",
";",
"}",
")",
";",
"if",
"(",
"answers",
".",
"framework",
"===",
"\"react\"",
")",
"{",
"config",
".",
"parserOptions",
".",
"ecmaFeatures",
"=",
"{",
"jsx",
":",
"true",
"}",
";",
"config",
".",
"plugins",
"=",
"[",
"\"react\"",
"]",
";",
"}",
"else",
"if",
"(",
"answers",
".",
"framework",
"===",
"\"vue\"",
")",
"{",
"config",
".",
"plugins",
"=",
"[",
"\"vue\"",
"]",
";",
"config",
".",
"extends",
".",
"push",
"(",
"\"plugin:vue/essential\"",
")",
";",
"}",
"if",
"(",
"answers",
".",
"purpose",
"===",
"\"problems\"",
")",
"{",
"config",
".",
"extends",
".",
"unshift",
"(",
"\"eslint:recommended\"",
")",
";",
"}",
"else",
"if",
"(",
"answers",
".",
"purpose",
"===",
"\"style\"",
")",
"{",
"if",
"(",
"answers",
".",
"source",
"===",
"\"prompt\"",
")",
"{",
"config",
".",
"extends",
".",
"unshift",
"(",
"\"eslint:recommended\"",
")",
";",
"config",
".",
"rules",
".",
"indent",
"=",
"[",
"\"error\"",
",",
"answers",
".",
"indent",
"]",
";",
"config",
".",
"rules",
".",
"quotes",
"=",
"[",
"\"error\"",
",",
"answers",
".",
"quotes",
"]",
";",
"config",
".",
"rules",
"[",
"\"linebreak-style\"",
"]",
"=",
"[",
"\"error\"",
",",
"answers",
".",
"linebreak",
"]",
";",
"config",
".",
"rules",
".",
"semi",
"=",
"[",
"\"error\"",
",",
"answers",
".",
"semi",
"?",
"\"always\"",
":",
"\"never\"",
"]",
";",
"}",
"else",
"if",
"(",
"answers",
".",
"source",
"===",
"\"auto\"",
")",
"{",
"config",
"=",
"configureRules",
"(",
"answers",
",",
"config",
")",
";",
"config",
"=",
"autoconfig",
".",
"extendFromRecommended",
"(",
"config",
")",
";",
"}",
"}",
"if",
"(",
"config",
".",
"extends",
".",
"length",
"===",
"0",
")",
"{",
"delete",
"config",
".",
"extends",
";",
"}",
"else",
"if",
"(",
"config",
".",
"extends",
".",
"length",
"===",
"1",
")",
"{",
"config",
".",
"extends",
"=",
"config",
".",
"extends",
"[",
"0",
"]",
";",
"}",
"ConfigOps",
".",
"normalizeToStrings",
"(",
"config",
")",
";",
"return",
"config",
";",
"}"
] |
process user's answers and create config object
@param {Object} answers answers received from inquirer
@returns {Object} config object
|
[
"process",
"user",
"s",
"answers",
"and",
"create",
"config",
"object"
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/config/config-initializer.js#L245-L309
|
train
|
eslint/eslint
|
lib/config/config-initializer.js
|
getConfigForStyleGuide
|
function getConfigForStyleGuide(guide) {
const guides = {
google: { extends: "google" },
airbnb: { extends: "airbnb" },
"airbnb-base": { extends: "airbnb-base" },
standard: { extends: "standard" }
};
if (!guides[guide]) {
throw new Error("You referenced an unsupported guide.");
}
return guides[guide];
}
|
javascript
|
function getConfigForStyleGuide(guide) {
const guides = {
google: { extends: "google" },
airbnb: { extends: "airbnb" },
"airbnb-base": { extends: "airbnb-base" },
standard: { extends: "standard" }
};
if (!guides[guide]) {
throw new Error("You referenced an unsupported guide.");
}
return guides[guide];
}
|
[
"function",
"getConfigForStyleGuide",
"(",
"guide",
")",
"{",
"const",
"guides",
"=",
"{",
"google",
":",
"{",
"extends",
":",
"\"google\"",
"}",
",",
"airbnb",
":",
"{",
"extends",
":",
"\"airbnb\"",
"}",
",",
"\"airbnb-base\"",
":",
"{",
"extends",
":",
"\"airbnb-base\"",
"}",
",",
"standard",
":",
"{",
"extends",
":",
"\"standard\"",
"}",
"}",
";",
"if",
"(",
"!",
"guides",
"[",
"guide",
"]",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"You referenced an unsupported guide.\"",
")",
";",
"}",
"return",
"guides",
"[",
"guide",
"]",
";",
"}"
] |
process user's style guide of choice and return an appropriate config object.
@param {string} guide name of the chosen style guide
@returns {Object} config object
|
[
"process",
"user",
"s",
"style",
"guide",
"of",
"choice",
"and",
"return",
"an",
"appropriate",
"config",
"object",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/config/config-initializer.js#L316-L329
|
train
|
eslint/eslint
|
lib/config/config-initializer.js
|
getLocalESLintVersion
|
function getLocalESLintVersion() {
try {
const eslintPath = relativeModuleResolver("eslint", path.join(process.cwd(), "__placeholder__.js"));
const eslint = require(eslintPath);
return eslint.linter.version || null;
} catch (_err) {
return null;
}
}
|
javascript
|
function getLocalESLintVersion() {
try {
const eslintPath = relativeModuleResolver("eslint", path.join(process.cwd(), "__placeholder__.js"));
const eslint = require(eslintPath);
return eslint.linter.version || null;
} catch (_err) {
return null;
}
}
|
[
"function",
"getLocalESLintVersion",
"(",
")",
"{",
"try",
"{",
"const",
"eslintPath",
"=",
"relativeModuleResolver",
"(",
"\"eslint\"",
",",
"path",
".",
"join",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"\"__placeholder__.js\"",
")",
")",
";",
"const",
"eslint",
"=",
"require",
"(",
"eslintPath",
")",
";",
"return",
"eslint",
".",
"linter",
".",
"version",
"||",
"null",
";",
"}",
"catch",
"(",
"_err",
")",
"{",
"return",
"null",
";",
"}",
"}"
] |
Get the version of the local ESLint.
@returns {string|null} The version. If the local ESLint was not found, returns null.
|
[
"Get",
"the",
"version",
"of",
"the",
"local",
"ESLint",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/config/config-initializer.js#L335-L344
|
train
|
eslint/eslint
|
lib/config/config-initializer.js
|
hasESLintVersionConflict
|
function hasESLintVersionConflict(answers) {
// Get the local ESLint version.
const localESLintVersion = getLocalESLintVersion();
if (!localESLintVersion) {
return false;
}
// Get the required range of ESLint version.
const configName = getStyleGuideName(answers);
const moduleName = `eslint-config-${configName}@latest`;
const peerDependencies = getPeerDependencies(moduleName) || {};
const requiredESLintVersionRange = peerDependencies.eslint;
if (!requiredESLintVersionRange) {
return false;
}
answers.localESLintVersion = localESLintVersion;
answers.requiredESLintVersionRange = requiredESLintVersionRange;
// Check the version.
if (semver.satisfies(localESLintVersion, requiredESLintVersionRange)) {
answers.installESLint = false;
return false;
}
return true;
}
|
javascript
|
function hasESLintVersionConflict(answers) {
// Get the local ESLint version.
const localESLintVersion = getLocalESLintVersion();
if (!localESLintVersion) {
return false;
}
// Get the required range of ESLint version.
const configName = getStyleGuideName(answers);
const moduleName = `eslint-config-${configName}@latest`;
const peerDependencies = getPeerDependencies(moduleName) || {};
const requiredESLintVersionRange = peerDependencies.eslint;
if (!requiredESLintVersionRange) {
return false;
}
answers.localESLintVersion = localESLintVersion;
answers.requiredESLintVersionRange = requiredESLintVersionRange;
// Check the version.
if (semver.satisfies(localESLintVersion, requiredESLintVersionRange)) {
answers.installESLint = false;
return false;
}
return true;
}
|
[
"function",
"hasESLintVersionConflict",
"(",
"answers",
")",
"{",
"const",
"localESLintVersion",
"=",
"getLocalESLintVersion",
"(",
")",
";",
"if",
"(",
"!",
"localESLintVersion",
")",
"{",
"return",
"false",
";",
"}",
"const",
"configName",
"=",
"getStyleGuideName",
"(",
"answers",
")",
";",
"const",
"moduleName",
"=",
"`",
"${",
"configName",
"}",
"`",
";",
"const",
"peerDependencies",
"=",
"getPeerDependencies",
"(",
"moduleName",
")",
"||",
"{",
"}",
";",
"const",
"requiredESLintVersionRange",
"=",
"peerDependencies",
".",
"eslint",
";",
"if",
"(",
"!",
"requiredESLintVersionRange",
")",
"{",
"return",
"false",
";",
"}",
"answers",
".",
"localESLintVersion",
"=",
"localESLintVersion",
";",
"answers",
".",
"requiredESLintVersionRange",
"=",
"requiredESLintVersionRange",
";",
"if",
"(",
"semver",
".",
"satisfies",
"(",
"localESLintVersion",
",",
"requiredESLintVersionRange",
")",
")",
"{",
"answers",
".",
"installESLint",
"=",
"false",
";",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}"
] |
Check whether the local ESLint version conflicts with the required version of the chosen shareable config.
@param {Object} answers The answers object.
@returns {boolean} `true` if the local ESLint is found then it conflicts with the required version of the chosen shareable config.
|
[
"Check",
"whether",
"the",
"local",
"ESLint",
"version",
"conflicts",
"with",
"the",
"required",
"version",
"of",
"the",
"chosen",
"shareable",
"config",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/config/config-initializer.js#L363-L392
|
train
|
eslint/eslint
|
lib/rules/no-useless-return.js
|
isInFinally
|
function isInFinally(node) {
for (
let currentNode = node;
currentNode && currentNode.parent && !astUtils.isFunction(currentNode);
currentNode = currentNode.parent
) {
if (currentNode.parent.type === "TryStatement" && currentNode.parent.finalizer === currentNode) {
return true;
}
}
return false;
}
|
javascript
|
function isInFinally(node) {
for (
let currentNode = node;
currentNode && currentNode.parent && !astUtils.isFunction(currentNode);
currentNode = currentNode.parent
) {
if (currentNode.parent.type === "TryStatement" && currentNode.parent.finalizer === currentNode) {
return true;
}
}
return false;
}
|
[
"function",
"isInFinally",
"(",
"node",
")",
"{",
"for",
"(",
"let",
"currentNode",
"=",
"node",
";",
"currentNode",
"&&",
"currentNode",
".",
"parent",
"&&",
"!",
"astUtils",
".",
"isFunction",
"(",
"currentNode",
")",
";",
"currentNode",
"=",
"currentNode",
".",
"parent",
")",
"{",
"if",
"(",
"currentNode",
".",
"parent",
".",
"type",
"===",
"\"TryStatement\"",
"&&",
"currentNode",
".",
"parent",
".",
"finalizer",
"===",
"currentNode",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
] |
Checks whether the given return statement is in a `finally` block or not.
@param {ASTNode} node - The return statement node to check.
@returns {boolean} `true` if the node is in a `finally` block.
|
[
"Checks",
"whether",
"the",
"given",
"return",
"statement",
"is",
"in",
"a",
"finally",
"block",
"or",
"not",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-useless-return.js#L49-L61
|
train
|
eslint/eslint
|
lib/rules/no-useless-return.js
|
getUselessReturns
|
function getUselessReturns(uselessReturns, prevSegments, providedTraversedSegments) {
const traversedSegments = providedTraversedSegments || new WeakSet();
for (const segment of prevSegments) {
if (!segment.reachable) {
if (!traversedSegments.has(segment)) {
traversedSegments.add(segment);
getUselessReturns(
uselessReturns,
segment.allPrevSegments.filter(isReturned),
traversedSegments
);
}
continue;
}
uselessReturns.push(...segmentInfoMap.get(segment).uselessReturns);
}
return uselessReturns;
}
|
javascript
|
function getUselessReturns(uselessReturns, prevSegments, providedTraversedSegments) {
const traversedSegments = providedTraversedSegments || new WeakSet();
for (const segment of prevSegments) {
if (!segment.reachable) {
if (!traversedSegments.has(segment)) {
traversedSegments.add(segment);
getUselessReturns(
uselessReturns,
segment.allPrevSegments.filter(isReturned),
traversedSegments
);
}
continue;
}
uselessReturns.push(...segmentInfoMap.get(segment).uselessReturns);
}
return uselessReturns;
}
|
[
"function",
"getUselessReturns",
"(",
"uselessReturns",
",",
"prevSegments",
",",
"providedTraversedSegments",
")",
"{",
"const",
"traversedSegments",
"=",
"providedTraversedSegments",
"||",
"new",
"WeakSet",
"(",
")",
";",
"for",
"(",
"const",
"segment",
"of",
"prevSegments",
")",
"{",
"if",
"(",
"!",
"segment",
".",
"reachable",
")",
"{",
"if",
"(",
"!",
"traversedSegments",
".",
"has",
"(",
"segment",
")",
")",
"{",
"traversedSegments",
".",
"add",
"(",
"segment",
")",
";",
"getUselessReturns",
"(",
"uselessReturns",
",",
"segment",
".",
"allPrevSegments",
".",
"filter",
"(",
"isReturned",
")",
",",
"traversedSegments",
")",
";",
"}",
"continue",
";",
"}",
"uselessReturns",
".",
"push",
"(",
"...",
"segmentInfoMap",
".",
"get",
"(",
"segment",
")",
".",
"uselessReturns",
")",
";",
"}",
"return",
"uselessReturns",
";",
"}"
] |
Collects useless return statements from the given previous segments.
A previous segment may be an unreachable segment.
In that case, the information object of the unreachable segment is not
initialized because `onCodePathSegmentStart` event is not notified for
unreachable segments.
This goes to the previous segments of the unreachable segment recursively
if the unreachable segment was generated by a return statement. Otherwise,
this ignores the unreachable segment.
This behavior would simulate code paths for the case that the return
statement does not exist.
@param {ASTNode[]} uselessReturns - The collected return statements.
@param {CodePathSegment[]} prevSegments - The previous segments to traverse.
@param {WeakSet<CodePathSegment>} [providedTraversedSegments] A set of segments that have already been traversed in this call
@returns {ASTNode[]} `uselessReturns`.
|
[
"Collects",
"useless",
"return",
"statements",
"from",
"the",
"given",
"previous",
"segments",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-useless-return.js#L118-L138
|
train
|
eslint/eslint
|
lib/rules/no-useless-return.js
|
markReturnStatementsOnSegmentAsUsed
|
function markReturnStatementsOnSegmentAsUsed(segment) {
if (!segment.reachable) {
usedUnreachableSegments.add(segment);
segment.allPrevSegments
.filter(isReturned)
.filter(prevSegment => !usedUnreachableSegments.has(prevSegment))
.forEach(markReturnStatementsOnSegmentAsUsed);
return;
}
const info = segmentInfoMap.get(segment);
for (const node of info.uselessReturns) {
remove(scopeInfo.uselessReturns, node);
}
info.uselessReturns = [];
}
|
javascript
|
function markReturnStatementsOnSegmentAsUsed(segment) {
if (!segment.reachable) {
usedUnreachableSegments.add(segment);
segment.allPrevSegments
.filter(isReturned)
.filter(prevSegment => !usedUnreachableSegments.has(prevSegment))
.forEach(markReturnStatementsOnSegmentAsUsed);
return;
}
const info = segmentInfoMap.get(segment);
for (const node of info.uselessReturns) {
remove(scopeInfo.uselessReturns, node);
}
info.uselessReturns = [];
}
|
[
"function",
"markReturnStatementsOnSegmentAsUsed",
"(",
"segment",
")",
"{",
"if",
"(",
"!",
"segment",
".",
"reachable",
")",
"{",
"usedUnreachableSegments",
".",
"add",
"(",
"segment",
")",
";",
"segment",
".",
"allPrevSegments",
".",
"filter",
"(",
"isReturned",
")",
".",
"filter",
"(",
"prevSegment",
"=>",
"!",
"usedUnreachableSegments",
".",
"has",
"(",
"prevSegment",
")",
")",
".",
"forEach",
"(",
"markReturnStatementsOnSegmentAsUsed",
")",
";",
"return",
";",
"}",
"const",
"info",
"=",
"segmentInfoMap",
".",
"get",
"(",
"segment",
")",
";",
"for",
"(",
"const",
"node",
"of",
"info",
".",
"uselessReturns",
")",
"{",
"remove",
"(",
"scopeInfo",
".",
"uselessReturns",
",",
"node",
")",
";",
"}",
"info",
".",
"uselessReturns",
"=",
"[",
"]",
";",
"}"
] |
Removes the return statements on the given segment from the useless return
statement list.
This segment may be an unreachable segment.
In that case, the information object of the unreachable segment is not
initialized because `onCodePathSegmentStart` event is not notified for
unreachable segments.
This goes to the previous segments of the unreachable segment recursively
if the unreachable segment was generated by a return statement. Otherwise,
this ignores the unreachable segment.
This behavior would simulate code paths for the case that the return
statement does not exist.
@param {CodePathSegment} segment - The segment to get return statements.
@returns {void}
|
[
"Removes",
"the",
"return",
"statements",
"on",
"the",
"given",
"segment",
"from",
"the",
"useless",
"return",
"statement",
"list",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-useless-return.js#L158-L174
|
train
|
eslint/eslint
|
lib/rules/keyword-spacing.js
|
parseOptions
|
function parseOptions(options = {}) {
const before = options.before !== false;
const after = options.after !== false;
const defaultValue = {
before: before ? expectSpaceBefore : unexpectSpaceBefore,
after: after ? expectSpaceAfter : unexpectSpaceAfter
};
const overrides = (options && options.overrides) || {};
const retv = Object.create(null);
for (let i = 0; i < KEYS.length; ++i) {
const key = KEYS[i];
const override = overrides[key];
if (override) {
const thisBefore = ("before" in override) ? override.before : before;
const thisAfter = ("after" in override) ? override.after : after;
retv[key] = {
before: thisBefore ? expectSpaceBefore : unexpectSpaceBefore,
after: thisAfter ? expectSpaceAfter : unexpectSpaceAfter
};
} else {
retv[key] = defaultValue;
}
}
return retv;
}
|
javascript
|
function parseOptions(options = {}) {
const before = options.before !== false;
const after = options.after !== false;
const defaultValue = {
before: before ? expectSpaceBefore : unexpectSpaceBefore,
after: after ? expectSpaceAfter : unexpectSpaceAfter
};
const overrides = (options && options.overrides) || {};
const retv = Object.create(null);
for (let i = 0; i < KEYS.length; ++i) {
const key = KEYS[i];
const override = overrides[key];
if (override) {
const thisBefore = ("before" in override) ? override.before : before;
const thisAfter = ("after" in override) ? override.after : after;
retv[key] = {
before: thisBefore ? expectSpaceBefore : unexpectSpaceBefore,
after: thisAfter ? expectSpaceAfter : unexpectSpaceAfter
};
} else {
retv[key] = defaultValue;
}
}
return retv;
}
|
[
"function",
"parseOptions",
"(",
"options",
"=",
"{",
"}",
")",
"{",
"const",
"before",
"=",
"options",
".",
"before",
"!==",
"false",
";",
"const",
"after",
"=",
"options",
".",
"after",
"!==",
"false",
";",
"const",
"defaultValue",
"=",
"{",
"before",
":",
"before",
"?",
"expectSpaceBefore",
":",
"unexpectSpaceBefore",
",",
"after",
":",
"after",
"?",
"expectSpaceAfter",
":",
"unexpectSpaceAfter",
"}",
";",
"const",
"overrides",
"=",
"(",
"options",
"&&",
"options",
".",
"overrides",
")",
"||",
"{",
"}",
";",
"const",
"retv",
"=",
"Object",
".",
"create",
"(",
"null",
")",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"KEYS",
".",
"length",
";",
"++",
"i",
")",
"{",
"const",
"key",
"=",
"KEYS",
"[",
"i",
"]",
";",
"const",
"override",
"=",
"overrides",
"[",
"key",
"]",
";",
"if",
"(",
"override",
")",
"{",
"const",
"thisBefore",
"=",
"(",
"\"before\"",
"in",
"override",
")",
"?",
"override",
".",
"before",
":",
"before",
";",
"const",
"thisAfter",
"=",
"(",
"\"after\"",
"in",
"override",
")",
"?",
"override",
".",
"after",
":",
"after",
";",
"retv",
"[",
"key",
"]",
"=",
"{",
"before",
":",
"thisBefore",
"?",
"expectSpaceBefore",
":",
"unexpectSpaceBefore",
",",
"after",
":",
"thisAfter",
"?",
"expectSpaceAfter",
":",
"unexpectSpaceAfter",
"}",
";",
"}",
"else",
"{",
"retv",
"[",
"key",
"]",
"=",
"defaultValue",
";",
"}",
"}",
"return",
"retv",
";",
"}"
] |
Parses the option object and determines check methods for each keyword.
@param {Object|undefined} options - The option object to parse.
@returns {Object} - Normalized option object.
Keys are keywords (there are for every keyword).
Values are instances of `{"before": function, "after": function}`.
|
[
"Parses",
"the",
"option",
"object",
"and",
"determines",
"check",
"methods",
"for",
"each",
"keyword",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/keyword-spacing.js#L231-L259
|
train
|
eslint/eslint
|
lib/rules/keyword-spacing.js
|
checkSpacingBefore
|
function checkSpacingBefore(token, pattern) {
checkMethodMap[token.value].before(token, pattern || PREV_TOKEN);
}
|
javascript
|
function checkSpacingBefore(token, pattern) {
checkMethodMap[token.value].before(token, pattern || PREV_TOKEN);
}
|
[
"function",
"checkSpacingBefore",
"(",
"token",
",",
"pattern",
")",
"{",
"checkMethodMap",
"[",
"token",
".",
"value",
"]",
".",
"before",
"(",
"token",
",",
"pattern",
"||",
"PREV_TOKEN",
")",
";",
"}"
] |
Reports a given token if usage of spacing followed by the token is
invalid.
@param {Token} token - A token to report.
@param {RegExp|undefined} pattern - Optional. A pattern of the previous
token to check.
@returns {void}
|
[
"Reports",
"a",
"given",
"token",
"if",
"usage",
"of",
"spacing",
"followed",
"by",
"the",
"token",
"is",
"invalid",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/keyword-spacing.js#L272-L274
|
train
|
eslint/eslint
|
lib/rules/keyword-spacing.js
|
checkSpacingAfter
|
function checkSpacingAfter(token, pattern) {
checkMethodMap[token.value].after(token, pattern || NEXT_TOKEN);
}
|
javascript
|
function checkSpacingAfter(token, pattern) {
checkMethodMap[token.value].after(token, pattern || NEXT_TOKEN);
}
|
[
"function",
"checkSpacingAfter",
"(",
"token",
",",
"pattern",
")",
"{",
"checkMethodMap",
"[",
"token",
".",
"value",
"]",
".",
"after",
"(",
"token",
",",
"pattern",
"||",
"NEXT_TOKEN",
")",
";",
"}"
] |
Reports a given token if usage of spacing preceded by the token is
invalid.
@param {Token} token - A token to report.
@param {RegExp|undefined} pattern - Optional. A pattern of the next
token to check.
@returns {void}
|
[
"Reports",
"a",
"given",
"token",
"if",
"usage",
"of",
"spacing",
"preceded",
"by",
"the",
"token",
"is",
"invalid",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/keyword-spacing.js#L285-L287
|
train
|
eslint/eslint
|
lib/rules/keyword-spacing.js
|
checkSpacingAroundFirstToken
|
function checkSpacingAroundFirstToken(node) {
const firstToken = node && sourceCode.getFirstToken(node);
if (firstToken && firstToken.type === "Keyword") {
checkSpacingAround(firstToken);
}
}
|
javascript
|
function checkSpacingAroundFirstToken(node) {
const firstToken = node && sourceCode.getFirstToken(node);
if (firstToken && firstToken.type === "Keyword") {
checkSpacingAround(firstToken);
}
}
|
[
"function",
"checkSpacingAroundFirstToken",
"(",
"node",
")",
"{",
"const",
"firstToken",
"=",
"node",
"&&",
"sourceCode",
".",
"getFirstToken",
"(",
"node",
")",
";",
"if",
"(",
"firstToken",
"&&",
"firstToken",
".",
"type",
"===",
"\"Keyword\"",
")",
"{",
"checkSpacingAround",
"(",
"firstToken",
")",
";",
"}",
"}"
] |
Reports the first token of a given node if the first token is a keyword
and usage of spacing around the token is invalid.
@param {ASTNode|null} node - A node to report.
@returns {void}
|
[
"Reports",
"the",
"first",
"token",
"of",
"a",
"given",
"node",
"if",
"the",
"first",
"token",
"is",
"a",
"keyword",
"and",
"usage",
"of",
"spacing",
"around",
"the",
"token",
"is",
"invalid",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/keyword-spacing.js#L307-L313
|
train
|
eslint/eslint
|
lib/rules/keyword-spacing.js
|
checkSpacingBeforeFirstToken
|
function checkSpacingBeforeFirstToken(node) {
const firstToken = node && sourceCode.getFirstToken(node);
if (firstToken && firstToken.type === "Keyword") {
checkSpacingBefore(firstToken);
}
}
|
javascript
|
function checkSpacingBeforeFirstToken(node) {
const firstToken = node && sourceCode.getFirstToken(node);
if (firstToken && firstToken.type === "Keyword") {
checkSpacingBefore(firstToken);
}
}
|
[
"function",
"checkSpacingBeforeFirstToken",
"(",
"node",
")",
"{",
"const",
"firstToken",
"=",
"node",
"&&",
"sourceCode",
".",
"getFirstToken",
"(",
"node",
")",
";",
"if",
"(",
"firstToken",
"&&",
"firstToken",
".",
"type",
"===",
"\"Keyword\"",
")",
"{",
"checkSpacingBefore",
"(",
"firstToken",
")",
";",
"}",
"}"
] |
Reports the first token of a given node if the first token is a keyword
and usage of spacing followed by the token is invalid.
This is used for unary operators (e.g. `typeof`), `function`, and `super`.
Other rules are handling usage of spacing preceded by those keywords.
@param {ASTNode|null} node - A node to report.
@returns {void}
|
[
"Reports",
"the",
"first",
"token",
"of",
"a",
"given",
"node",
"if",
"the",
"first",
"token",
"is",
"a",
"keyword",
"and",
"usage",
"of",
"spacing",
"followed",
"by",
"the",
"token",
"is",
"invalid",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/keyword-spacing.js#L325-L331
|
train
|
eslint/eslint
|
lib/rules/keyword-spacing.js
|
checkSpacingAroundTokenBefore
|
function checkSpacingAroundTokenBefore(node) {
if (node) {
const token = sourceCode.getTokenBefore(node, astUtils.isKeywordToken);
checkSpacingAround(token);
}
}
|
javascript
|
function checkSpacingAroundTokenBefore(node) {
if (node) {
const token = sourceCode.getTokenBefore(node, astUtils.isKeywordToken);
checkSpacingAround(token);
}
}
|
[
"function",
"checkSpacingAroundTokenBefore",
"(",
"node",
")",
"{",
"if",
"(",
"node",
")",
"{",
"const",
"token",
"=",
"sourceCode",
".",
"getTokenBefore",
"(",
"node",
",",
"astUtils",
".",
"isKeywordToken",
")",
";",
"checkSpacingAround",
"(",
"token",
")",
";",
"}",
"}"
] |
Reports the previous token of a given node if the token is a keyword and
usage of spacing around the token is invalid.
@param {ASTNode|null} node - A node to report.
@returns {void}
|
[
"Reports",
"the",
"previous",
"token",
"of",
"a",
"given",
"node",
"if",
"the",
"token",
"is",
"a",
"keyword",
"and",
"usage",
"of",
"spacing",
"around",
"the",
"token",
"is",
"invalid",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/keyword-spacing.js#L340-L346
|
train
|
eslint/eslint
|
lib/rules/keyword-spacing.js
|
checkSpacingForFunction
|
function checkSpacingForFunction(node) {
const firstToken = node && sourceCode.getFirstToken(node);
if (firstToken &&
((firstToken.type === "Keyword" && firstToken.value === "function") ||
firstToken.value === "async")
) {
checkSpacingBefore(firstToken);
}
}
|
javascript
|
function checkSpacingForFunction(node) {
const firstToken = node && sourceCode.getFirstToken(node);
if (firstToken &&
((firstToken.type === "Keyword" && firstToken.value === "function") ||
firstToken.value === "async")
) {
checkSpacingBefore(firstToken);
}
}
|
[
"function",
"checkSpacingForFunction",
"(",
"node",
")",
"{",
"const",
"firstToken",
"=",
"node",
"&&",
"sourceCode",
".",
"getFirstToken",
"(",
"node",
")",
";",
"if",
"(",
"firstToken",
"&&",
"(",
"(",
"firstToken",
".",
"type",
"===",
"\"Keyword\"",
"&&",
"firstToken",
".",
"value",
"===",
"\"function\"",
")",
"||",
"firstToken",
".",
"value",
"===",
"\"async\"",
")",
")",
"{",
"checkSpacingBefore",
"(",
"firstToken",
")",
";",
"}",
"}"
] |
Reports `async` or `function` keywords of a given node if usage of
spacing around those keywords is invalid.
@param {ASTNode} node - A node to report.
@returns {void}
|
[
"Reports",
"async",
"or",
"function",
"keywords",
"of",
"a",
"given",
"node",
"if",
"usage",
"of",
"spacing",
"around",
"those",
"keywords",
"is",
"invalid",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/keyword-spacing.js#L355-L364
|
train
|
eslint/eslint
|
lib/rules/keyword-spacing.js
|
checkSpacingForTryStatement
|
function checkSpacingForTryStatement(node) {
checkSpacingAroundFirstToken(node);
checkSpacingAroundFirstToken(node.handler);
checkSpacingAroundTokenBefore(node.finalizer);
}
|
javascript
|
function checkSpacingForTryStatement(node) {
checkSpacingAroundFirstToken(node);
checkSpacingAroundFirstToken(node.handler);
checkSpacingAroundTokenBefore(node.finalizer);
}
|
[
"function",
"checkSpacingForTryStatement",
"(",
"node",
")",
"{",
"checkSpacingAroundFirstToken",
"(",
"node",
")",
";",
"checkSpacingAroundFirstToken",
"(",
"node",
".",
"handler",
")",
";",
"checkSpacingAroundTokenBefore",
"(",
"node",
".",
"finalizer",
")",
";",
"}"
] |
Reports `try`, `catch`, and `finally` keywords of a given node if usage
of spacing around those keywords is invalid.
@param {ASTNode} node - A node to report.
@returns {void}
|
[
"Reports",
"try",
"catch",
"and",
"finally",
"keywords",
"of",
"a",
"given",
"node",
"if",
"usage",
"of",
"spacing",
"around",
"those",
"keywords",
"is",
"invalid",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/keyword-spacing.js#L397-L401
|
train
|
eslint/eslint
|
lib/rules/keyword-spacing.js
|
checkSpacingForForOfStatement
|
function checkSpacingForForOfStatement(node) {
if (node.await) {
checkSpacingBefore(sourceCode.getFirstToken(node, 0));
checkSpacingAfter(sourceCode.getFirstToken(node, 1));
} else {
checkSpacingAroundFirstToken(node);
}
checkSpacingAround(sourceCode.getTokenBefore(node.right, astUtils.isNotOpeningParenToken));
}
|
javascript
|
function checkSpacingForForOfStatement(node) {
if (node.await) {
checkSpacingBefore(sourceCode.getFirstToken(node, 0));
checkSpacingAfter(sourceCode.getFirstToken(node, 1));
} else {
checkSpacingAroundFirstToken(node);
}
checkSpacingAround(sourceCode.getTokenBefore(node.right, astUtils.isNotOpeningParenToken));
}
|
[
"function",
"checkSpacingForForOfStatement",
"(",
"node",
")",
"{",
"if",
"(",
"node",
".",
"await",
")",
"{",
"checkSpacingBefore",
"(",
"sourceCode",
".",
"getFirstToken",
"(",
"node",
",",
"0",
")",
")",
";",
"checkSpacingAfter",
"(",
"sourceCode",
".",
"getFirstToken",
"(",
"node",
",",
"1",
")",
")",
";",
"}",
"else",
"{",
"checkSpacingAroundFirstToken",
"(",
"node",
")",
";",
"}",
"checkSpacingAround",
"(",
"sourceCode",
".",
"getTokenBefore",
"(",
"node",
".",
"right",
",",
"astUtils",
".",
"isNotOpeningParenToken",
")",
")",
";",
"}"
] |
Reports `for` and `of` keywords of a given node if usage of spacing
around those keywords is invalid.
@param {ASTNode} node - A node to report.
@returns {void}
|
[
"Reports",
"for",
"and",
"of",
"keywords",
"of",
"a",
"given",
"node",
"if",
"usage",
"of",
"spacing",
"around",
"those",
"keywords",
"is",
"invalid",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/keyword-spacing.js#L434-L442
|
train
|
eslint/eslint
|
lib/rules/keyword-spacing.js
|
checkSpacingForModuleDeclaration
|
function checkSpacingForModuleDeclaration(node) {
const firstToken = sourceCode.getFirstToken(node);
checkSpacingBefore(firstToken, PREV_TOKEN_M);
checkSpacingAfter(firstToken, NEXT_TOKEN_M);
if (node.type === "ExportDefaultDeclaration") {
checkSpacingAround(sourceCode.getTokenAfter(firstToken));
}
if (node.source) {
const fromToken = sourceCode.getTokenBefore(node.source);
checkSpacingBefore(fromToken, PREV_TOKEN_M);
checkSpacingAfter(fromToken, NEXT_TOKEN_M);
}
}
|
javascript
|
function checkSpacingForModuleDeclaration(node) {
const firstToken = sourceCode.getFirstToken(node);
checkSpacingBefore(firstToken, PREV_TOKEN_M);
checkSpacingAfter(firstToken, NEXT_TOKEN_M);
if (node.type === "ExportDefaultDeclaration") {
checkSpacingAround(sourceCode.getTokenAfter(firstToken));
}
if (node.source) {
const fromToken = sourceCode.getTokenBefore(node.source);
checkSpacingBefore(fromToken, PREV_TOKEN_M);
checkSpacingAfter(fromToken, NEXT_TOKEN_M);
}
}
|
[
"function",
"checkSpacingForModuleDeclaration",
"(",
"node",
")",
"{",
"const",
"firstToken",
"=",
"sourceCode",
".",
"getFirstToken",
"(",
"node",
")",
";",
"checkSpacingBefore",
"(",
"firstToken",
",",
"PREV_TOKEN_M",
")",
";",
"checkSpacingAfter",
"(",
"firstToken",
",",
"NEXT_TOKEN_M",
")",
";",
"if",
"(",
"node",
".",
"type",
"===",
"\"ExportDefaultDeclaration\"",
")",
"{",
"checkSpacingAround",
"(",
"sourceCode",
".",
"getTokenAfter",
"(",
"firstToken",
")",
")",
";",
"}",
"if",
"(",
"node",
".",
"source",
")",
"{",
"const",
"fromToken",
"=",
"sourceCode",
".",
"getTokenBefore",
"(",
"node",
".",
"source",
")",
";",
"checkSpacingBefore",
"(",
"fromToken",
",",
"PREV_TOKEN_M",
")",
";",
"checkSpacingAfter",
"(",
"fromToken",
",",
"NEXT_TOKEN_M",
")",
";",
"}",
"}"
] |
Reports `import`, `export`, `as`, and `from` keywords of a given node if
usage of spacing around those keywords is invalid.
This rule handles the `*` token in module declarations.
import*as A from "./a"; /*error Expected space(s) after "import".
error Expected space(s) before "as".
@param {ASTNode} node - A node to report.
@returns {void}
|
[
"Reports",
"import",
"export",
"as",
"and",
"from",
"keywords",
"of",
"a",
"given",
"node",
"if",
"usage",
"of",
"spacing",
"around",
"those",
"keywords",
"is",
"invalid",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/keyword-spacing.js#L456-L472
|
train
|
eslint/eslint
|
lib/rules/keyword-spacing.js
|
checkSpacingForProperty
|
function checkSpacingForProperty(node) {
if (node.static) {
checkSpacingAroundFirstToken(node);
}
if (node.kind === "get" ||
node.kind === "set" ||
(
(node.method || node.type === "MethodDefinition") &&
node.value.async
)
) {
const token = sourceCode.getTokenBefore(
node.key,
tok => {
switch (tok.value) {
case "get":
case "set":
case "async":
return true;
default:
return false;
}
}
);
if (!token) {
throw new Error("Failed to find token get, set, or async beside method name");
}
checkSpacingAround(token);
}
}
|
javascript
|
function checkSpacingForProperty(node) {
if (node.static) {
checkSpacingAroundFirstToken(node);
}
if (node.kind === "get" ||
node.kind === "set" ||
(
(node.method || node.type === "MethodDefinition") &&
node.value.async
)
) {
const token = sourceCode.getTokenBefore(
node.key,
tok => {
switch (tok.value) {
case "get":
case "set":
case "async":
return true;
default:
return false;
}
}
);
if (!token) {
throw new Error("Failed to find token get, set, or async beside method name");
}
checkSpacingAround(token);
}
}
|
[
"function",
"checkSpacingForProperty",
"(",
"node",
")",
"{",
"if",
"(",
"node",
".",
"static",
")",
"{",
"checkSpacingAroundFirstToken",
"(",
"node",
")",
";",
"}",
"if",
"(",
"node",
".",
"kind",
"===",
"\"get\"",
"||",
"node",
".",
"kind",
"===",
"\"set\"",
"||",
"(",
"(",
"node",
".",
"method",
"||",
"node",
".",
"type",
"===",
"\"MethodDefinition\"",
")",
"&&",
"node",
".",
"value",
".",
"async",
")",
")",
"{",
"const",
"token",
"=",
"sourceCode",
".",
"getTokenBefore",
"(",
"node",
".",
"key",
",",
"tok",
"=>",
"{",
"switch",
"(",
"tok",
".",
"value",
")",
"{",
"case",
"\"get\"",
":",
"case",
"\"set\"",
":",
"case",
"\"async\"",
":",
"return",
"true",
";",
"default",
":",
"return",
"false",
";",
"}",
"}",
")",
";",
"if",
"(",
"!",
"token",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"Failed to find token get, set, or async beside method name\"",
")",
";",
"}",
"checkSpacingAround",
"(",
"token",
")",
";",
"}",
"}"
] |
Reports `static`, `get`, and `set` keywords of a given node if usage of
spacing around those keywords is invalid.
@param {ASTNode} node - A node to report.
@returns {void}
|
[
"Reports",
"static",
"get",
"and",
"set",
"keywords",
"of",
"a",
"given",
"node",
"if",
"usage",
"of",
"spacing",
"around",
"those",
"keywords",
"is",
"invalid",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/keyword-spacing.js#L494-L526
|
train
|
eslint/eslint
|
lib/util/lint-result-cache.js
|
hashOfConfigFor
|
function hashOfConfigFor(configHelper, filename) {
const config = configHelper.getConfig(filename);
if (!configHashCache.has(config)) {
configHashCache.set(config, hash(`${pkg.version}_${stringify(config)}`));
}
return configHashCache.get(config);
}
|
javascript
|
function hashOfConfigFor(configHelper, filename) {
const config = configHelper.getConfig(filename);
if (!configHashCache.has(config)) {
configHashCache.set(config, hash(`${pkg.version}_${stringify(config)}`));
}
return configHashCache.get(config);
}
|
[
"function",
"hashOfConfigFor",
"(",
"configHelper",
",",
"filename",
")",
"{",
"const",
"config",
"=",
"configHelper",
".",
"getConfig",
"(",
"filename",
")",
";",
"if",
"(",
"!",
"configHashCache",
".",
"has",
"(",
"config",
")",
")",
"{",
"configHashCache",
".",
"set",
"(",
"config",
",",
"hash",
"(",
"`",
"${",
"pkg",
".",
"version",
"}",
"${",
"stringify",
"(",
"config",
")",
"}",
"`",
")",
")",
";",
"}",
"return",
"configHashCache",
".",
"get",
"(",
"config",
")",
";",
"}"
] |
Calculates the hash of the config file used to validate a given file
@param {Object} configHelper The config helper for retrieving configuration information
@param {string} filename The path of the file to retrieve a config object for to calculate the hash
@returns {string} The hash of the config
|
[
"Calculates",
"the",
"hash",
"of",
"the",
"config",
"file",
"used",
"to",
"validate",
"a",
"given",
"file"
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/util/lint-result-cache.js#L30-L38
|
train
|
eslint/eslint
|
lib/rules/constructor-super.js
|
isPossibleConstructor
|
function isPossibleConstructor(node) {
if (!node) {
return false;
}
switch (node.type) {
case "ClassExpression":
case "FunctionExpression":
case "ThisExpression":
case "MemberExpression":
case "CallExpression":
case "NewExpression":
case "YieldExpression":
case "TaggedTemplateExpression":
case "MetaProperty":
return true;
case "Identifier":
return node.name !== "undefined";
case "AssignmentExpression":
return isPossibleConstructor(node.right);
case "LogicalExpression":
return (
isPossibleConstructor(node.left) ||
isPossibleConstructor(node.right)
);
case "ConditionalExpression":
return (
isPossibleConstructor(node.alternate) ||
isPossibleConstructor(node.consequent)
);
case "SequenceExpression": {
const lastExpression = node.expressions[node.expressions.length - 1];
return isPossibleConstructor(lastExpression);
}
default:
return false;
}
}
|
javascript
|
function isPossibleConstructor(node) {
if (!node) {
return false;
}
switch (node.type) {
case "ClassExpression":
case "FunctionExpression":
case "ThisExpression":
case "MemberExpression":
case "CallExpression":
case "NewExpression":
case "YieldExpression":
case "TaggedTemplateExpression":
case "MetaProperty":
return true;
case "Identifier":
return node.name !== "undefined";
case "AssignmentExpression":
return isPossibleConstructor(node.right);
case "LogicalExpression":
return (
isPossibleConstructor(node.left) ||
isPossibleConstructor(node.right)
);
case "ConditionalExpression":
return (
isPossibleConstructor(node.alternate) ||
isPossibleConstructor(node.consequent)
);
case "SequenceExpression": {
const lastExpression = node.expressions[node.expressions.length - 1];
return isPossibleConstructor(lastExpression);
}
default:
return false;
}
}
|
[
"function",
"isPossibleConstructor",
"(",
"node",
")",
"{",
"if",
"(",
"!",
"node",
")",
"{",
"return",
"false",
";",
"}",
"switch",
"(",
"node",
".",
"type",
")",
"{",
"case",
"\"ClassExpression\"",
":",
"case",
"\"FunctionExpression\"",
":",
"case",
"\"ThisExpression\"",
":",
"case",
"\"MemberExpression\"",
":",
"case",
"\"CallExpression\"",
":",
"case",
"\"NewExpression\"",
":",
"case",
"\"YieldExpression\"",
":",
"case",
"\"TaggedTemplateExpression\"",
":",
"case",
"\"MetaProperty\"",
":",
"return",
"true",
";",
"case",
"\"Identifier\"",
":",
"return",
"node",
".",
"name",
"!==",
"\"undefined\"",
";",
"case",
"\"AssignmentExpression\"",
":",
"return",
"isPossibleConstructor",
"(",
"node",
".",
"right",
")",
";",
"case",
"\"LogicalExpression\"",
":",
"return",
"(",
"isPossibleConstructor",
"(",
"node",
".",
"left",
")",
"||",
"isPossibleConstructor",
"(",
"node",
".",
"right",
")",
")",
";",
"case",
"\"ConditionalExpression\"",
":",
"return",
"(",
"isPossibleConstructor",
"(",
"node",
".",
"alternate",
")",
"||",
"isPossibleConstructor",
"(",
"node",
".",
"consequent",
")",
")",
";",
"case",
"\"SequenceExpression\"",
":",
"{",
"const",
"lastExpression",
"=",
"node",
".",
"expressions",
"[",
"node",
".",
"expressions",
".",
"length",
"-",
"1",
"]",
";",
"return",
"isPossibleConstructor",
"(",
"lastExpression",
")",
";",
"}",
"default",
":",
"return",
"false",
";",
"}",
"}"
] |
Checks whether a given node can be a constructor or not.
@param {ASTNode} node - A node to check.
@returns {boolean} `true` if the node can be a constructor.
|
[
"Checks",
"whether",
"a",
"given",
"node",
"can",
"be",
"a",
"constructor",
"or",
"not",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/constructor-super.js#L43-L87
|
train
|
eslint/eslint
|
lib/rules/no-restricted-properties.js
|
checkPropertyAccess
|
function checkPropertyAccess(node, objectName, propertyName) {
if (propertyName === null) {
return;
}
const matchedObject = restrictedProperties.get(objectName);
const matchedObjectProperty = matchedObject ? matchedObject.get(propertyName) : globallyRestrictedObjects.get(objectName);
const globalMatchedProperty = globallyRestrictedProperties.get(propertyName);
if (matchedObjectProperty) {
const message = matchedObjectProperty.message ? ` ${matchedObjectProperty.message}` : "";
context.report({
node,
// eslint-disable-next-line eslint-plugin/report-message-format
message: "'{{objectName}}.{{propertyName}}' is restricted from being used.{{message}}",
data: {
objectName,
propertyName,
message
}
});
} else if (globalMatchedProperty) {
const message = globalMatchedProperty.message ? ` ${globalMatchedProperty.message}` : "";
context.report({
node,
// eslint-disable-next-line eslint-plugin/report-message-format
message: "'{{propertyName}}' is restricted from being used.{{message}}",
data: {
propertyName,
message
}
});
}
}
|
javascript
|
function checkPropertyAccess(node, objectName, propertyName) {
if (propertyName === null) {
return;
}
const matchedObject = restrictedProperties.get(objectName);
const matchedObjectProperty = matchedObject ? matchedObject.get(propertyName) : globallyRestrictedObjects.get(objectName);
const globalMatchedProperty = globallyRestrictedProperties.get(propertyName);
if (matchedObjectProperty) {
const message = matchedObjectProperty.message ? ` ${matchedObjectProperty.message}` : "";
context.report({
node,
// eslint-disable-next-line eslint-plugin/report-message-format
message: "'{{objectName}}.{{propertyName}}' is restricted from being used.{{message}}",
data: {
objectName,
propertyName,
message
}
});
} else if (globalMatchedProperty) {
const message = globalMatchedProperty.message ? ` ${globalMatchedProperty.message}` : "";
context.report({
node,
// eslint-disable-next-line eslint-plugin/report-message-format
message: "'{{propertyName}}' is restricted from being used.{{message}}",
data: {
propertyName,
message
}
});
}
}
|
[
"function",
"checkPropertyAccess",
"(",
"node",
",",
"objectName",
",",
"propertyName",
")",
"{",
"if",
"(",
"propertyName",
"===",
"null",
")",
"{",
"return",
";",
"}",
"const",
"matchedObject",
"=",
"restrictedProperties",
".",
"get",
"(",
"objectName",
")",
";",
"const",
"matchedObjectProperty",
"=",
"matchedObject",
"?",
"matchedObject",
".",
"get",
"(",
"propertyName",
")",
":",
"globallyRestrictedObjects",
".",
"get",
"(",
"objectName",
")",
";",
"const",
"globalMatchedProperty",
"=",
"globallyRestrictedProperties",
".",
"get",
"(",
"propertyName",
")",
";",
"if",
"(",
"matchedObjectProperty",
")",
"{",
"const",
"message",
"=",
"matchedObjectProperty",
".",
"message",
"?",
"`",
"${",
"matchedObjectProperty",
".",
"message",
"}",
"`",
":",
"\"\"",
";",
"context",
".",
"report",
"(",
"{",
"node",
",",
"message",
":",
"\"'{{objectName}}.{{propertyName}}' is restricted from being used.{{message}}\"",
",",
"data",
":",
"{",
"objectName",
",",
"propertyName",
",",
"message",
"}",
"}",
")",
";",
"}",
"else",
"if",
"(",
"globalMatchedProperty",
")",
"{",
"const",
"message",
"=",
"globalMatchedProperty",
".",
"message",
"?",
"`",
"${",
"globalMatchedProperty",
".",
"message",
"}",
"`",
":",
"\"\"",
";",
"context",
".",
"report",
"(",
"{",
"node",
",",
"message",
":",
"\"'{{propertyName}}' is restricted from being used.{{message}}\"",
",",
"data",
":",
"{",
"propertyName",
",",
"message",
"}",
"}",
")",
";",
"}",
"}"
] |
Checks to see whether a property access is restricted, and reports it if so.
@param {ASTNode} node The node to report
@param {string} objectName The name of the object
@param {string} propertyName The name of the property
@returns {undefined}
|
[
"Checks",
"to",
"see",
"whether",
"a",
"property",
"access",
"is",
"restricted",
"and",
"reports",
"it",
"if",
"so",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-restricted-properties.js#L104-L138
|
train
|
eslint/eslint
|
lib/rules/no-extra-label.js
|
enterBreakableStatement
|
function enterBreakableStatement(node) {
scopeInfo = {
label: node.parent.type === "LabeledStatement" ? node.parent.label : null,
breakable: true,
upper: scopeInfo
};
}
|
javascript
|
function enterBreakableStatement(node) {
scopeInfo = {
label: node.parent.type === "LabeledStatement" ? node.parent.label : null,
breakable: true,
upper: scopeInfo
};
}
|
[
"function",
"enterBreakableStatement",
"(",
"node",
")",
"{",
"scopeInfo",
"=",
"{",
"label",
":",
"node",
".",
"parent",
".",
"type",
"===",
"\"LabeledStatement\"",
"?",
"node",
".",
"parent",
".",
"label",
":",
"null",
",",
"breakable",
":",
"true",
",",
"upper",
":",
"scopeInfo",
"}",
";",
"}"
] |
Creates a new scope with a breakable statement.
@param {ASTNode} node - A node to create. This is a BreakableStatement.
@returns {void}
|
[
"Creates",
"a",
"new",
"scope",
"with",
"a",
"breakable",
"statement",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-extra-label.js#L47-L53
|
train
|
eslint/eslint
|
lib/rules/no-extra-label.js
|
enterLabeledStatement
|
function enterLabeledStatement(node) {
if (!astUtils.isBreakableStatement(node.body)) {
scopeInfo = {
label: node.label,
breakable: false,
upper: scopeInfo
};
}
}
|
javascript
|
function enterLabeledStatement(node) {
if (!astUtils.isBreakableStatement(node.body)) {
scopeInfo = {
label: node.label,
breakable: false,
upper: scopeInfo
};
}
}
|
[
"function",
"enterLabeledStatement",
"(",
"node",
")",
"{",
"if",
"(",
"!",
"astUtils",
".",
"isBreakableStatement",
"(",
"node",
".",
"body",
")",
")",
"{",
"scopeInfo",
"=",
"{",
"label",
":",
"node",
".",
"label",
",",
"breakable",
":",
"false",
",",
"upper",
":",
"scopeInfo",
"}",
";",
"}",
"}"
] |
Creates a new scope with a labeled statement.
This ignores it if the body is a breakable statement.
In this case it's handled in the `enterBreakableStatement` function.
@param {ASTNode} node - A node to create. This is a LabeledStatement.
@returns {void}
|
[
"Creates",
"a",
"new",
"scope",
"with",
"a",
"labeled",
"statement",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-extra-label.js#L73-L81
|
train
|
eslint/eslint
|
lib/rules/no-extra-label.js
|
reportIfUnnecessary
|
function reportIfUnnecessary(node) {
if (!node.label) {
return;
}
const labelNode = node.label;
for (let info = scopeInfo; info !== null; info = info.upper) {
if (info.breakable || info.label && info.label.name === labelNode.name) {
if (info.breakable && info.label && info.label.name === labelNode.name) {
context.report({
node: labelNode,
messageId: "unexpected",
data: labelNode,
fix: fixer => fixer.removeRange([sourceCode.getFirstToken(node).range[1], labelNode.range[1]])
});
}
return;
}
}
}
|
javascript
|
function reportIfUnnecessary(node) {
if (!node.label) {
return;
}
const labelNode = node.label;
for (let info = scopeInfo; info !== null; info = info.upper) {
if (info.breakable || info.label && info.label.name === labelNode.name) {
if (info.breakable && info.label && info.label.name === labelNode.name) {
context.report({
node: labelNode,
messageId: "unexpected",
data: labelNode,
fix: fixer => fixer.removeRange([sourceCode.getFirstToken(node).range[1], labelNode.range[1]])
});
}
return;
}
}
}
|
[
"function",
"reportIfUnnecessary",
"(",
"node",
")",
"{",
"if",
"(",
"!",
"node",
".",
"label",
")",
"{",
"return",
";",
"}",
"const",
"labelNode",
"=",
"node",
".",
"label",
";",
"for",
"(",
"let",
"info",
"=",
"scopeInfo",
";",
"info",
"!==",
"null",
";",
"info",
"=",
"info",
".",
"upper",
")",
"{",
"if",
"(",
"info",
".",
"breakable",
"||",
"info",
".",
"label",
"&&",
"info",
".",
"label",
".",
"name",
"===",
"labelNode",
".",
"name",
")",
"{",
"if",
"(",
"info",
".",
"breakable",
"&&",
"info",
".",
"label",
"&&",
"info",
".",
"label",
".",
"name",
"===",
"labelNode",
".",
"name",
")",
"{",
"context",
".",
"report",
"(",
"{",
"node",
":",
"labelNode",
",",
"messageId",
":",
"\"unexpected\"",
",",
"data",
":",
"labelNode",
",",
"fix",
":",
"fixer",
"=>",
"fixer",
".",
"removeRange",
"(",
"[",
"sourceCode",
".",
"getFirstToken",
"(",
"node",
")",
".",
"range",
"[",
"1",
"]",
",",
"labelNode",
".",
"range",
"[",
"1",
"]",
"]",
")",
"}",
")",
";",
"}",
"return",
";",
"}",
"}",
"}"
] |
Reports a given control node if it's unnecessary.
@param {ASTNode} node - A node. This is a BreakStatement or a
ContinueStatement.
@returns {void}
|
[
"Reports",
"a",
"given",
"control",
"node",
"if",
"it",
"s",
"unnecessary",
"."
] |
bc0819c94aad14f7fad3cbc2338ea15658b0f272
|
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-extra-label.js#L105-L125
|
train
|
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",
"}",
"`",
";",
"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
|
train
|
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
|
train
|
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",
")",
";",
"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
|
train
|
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",
")",
";",
"yield",
"fixer",
".",
"remove",
"(",
"node",
".",
"callee",
")",
";",
"if",
"(",
"needsParens",
"(",
"node",
",",
"sourceCode",
")",
")",
"{",
"yield",
"fixer",
".",
"replaceText",
"(",
"leftParen",
",",
"\"({\"",
")",
";",
"yield",
"fixer",
".",
"replaceText",
"(",
"rightParen",
",",
"\"})\"",
")",
";",
"}",
"else",
"{",
"yield",
"fixer",
".",
"replaceText",
"(",
"leftParen",
",",
"\"{\"",
")",
";",
"yield",
"fixer",
".",
"replaceText",
"(",
"rightParen",
",",
"\"}\"",
")",
";",
"}",
"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",
")",
";",
"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",
"]",
")",
",",
"right",
".",
"range",
"[",
"1",
"]",
"]",
";",
"yield",
"fixer",
".",
"removeRange",
"(",
"leftRange",
")",
";",
"yield",
"fixer",
".",
"removeRange",
"(",
"rightRange",
")",
";",
"if",
"(",
"(",
"argNode",
".",
"properties",
".",
"length",
"===",
"0",
"||",
"isCommaToken",
"(",
"maybeTrailingComma",
")",
")",
"&&",
"isCommaToken",
"(",
"maybeArgumentComma",
")",
")",
"{",
"yield",
"fixer",
".",
"remove",
"(",
"maybeArgumentComma",
")",
";",
"}",
"}",
"else",
"{",
"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
|
train
|
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\"",
")",
"{",
"if",
"(",
"node",
".",
"async",
"&&",
"astUtils",
".",
"isOpeningParenToken",
"(",
"sourceCode",
".",
"getFirstToken",
"(",
"node",
",",
"{",
"skip",
":",
"1",
"}",
")",
")",
")",
"{",
"return",
"overrideConfig",
".",
"asyncArrow",
"||",
"baseConfig",
";",
"}",
"}",
"else",
"if",
"(",
"isNamedFunction",
"(",
"node",
")",
")",
"{",
"return",
"overrideConfig",
".",
"named",
"||",
"baseConfig",
";",
"}",
"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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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",
")",
"{",
"if",
"(",
"DEFAULT_IGNORE_PATTERN",
".",
"test",
"(",
"comment",
".",
"value",
")",
")",
"{",
"return",
"true",
";",
"}",
"const",
"commentWithoutAsterisks",
"=",
"comment",
".",
"value",
".",
"replace",
"(",
"/",
"\\*",
"/",
"gu",
",",
"\"\"",
")",
";",
"if",
"(",
"options",
".",
"ignorePatternRegExp",
"&&",
"options",
".",
"ignorePatternRegExp",
".",
"test",
"(",
"commentWithoutAsterisks",
")",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"options",
".",
"ignoreInlineComments",
"&&",
"isInlineComment",
"(",
"comment",
")",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"options",
".",
"ignoreConsecutiveComments",
"&&",
"isConsecutiveComment",
"(",
"comment",
")",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"MAYBE_URL",
".",
"test",
"(",
"commentWithoutAsterisks",
")",
")",
"{",
"return",
"true",
";",
"}",
"const",
"commentWordCharsOnly",
"=",
"commentWithoutAsterisks",
".",
"replace",
"(",
"WHITESPACE",
",",
"\"\"",
")",
";",
"if",
"(",
"commentWordCharsOnly",
".",
"length",
"===",
"0",
")",
"{",
"return",
"true",
";",
"}",
"const",
"firstWordChar",
"=",
"commentWordCharsOnly",
"[",
"0",
"]",
";",
"if",
"(",
"!",
"LETTER_PATTERN",
".",
"test",
"(",
"firstWordChar",
")",
")",
"{",
"return",
"true",
";",
"}",
"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
|
train
|
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",
",",
"loc",
":",
"comment",
".",
"loc",
",",
"messageId",
",",
"fix",
"(",
"fixer",
")",
"{",
"const",
"match",
"=",
"comment",
".",
"value",
".",
"match",
"(",
"LETTER_PATTERN",
")",
";",
"return",
"fixer",
".",
"replaceTextRange",
"(",
"[",
"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
|
train
|
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
|
train
|
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",
";",
"if",
"(",
"!",
"funcInfo",
".",
"hasReturnValue",
"||",
"funcInfo",
".",
"codePath",
".",
"currentSegments",
".",
"every",
"(",
"isUnreachable",
")",
"||",
"astUtils",
".",
"isES5Constructor",
"(",
"node",
")",
"||",
"isClassConstructor",
"(",
"node",
")",
")",
"{",
"return",
";",
"}",
"if",
"(",
"node",
".",
"type",
"===",
"\"Program\"",
")",
"{",
"loc",
"=",
"{",
"line",
":",
"1",
",",
"column",
":",
"0",
"}",
";",
"name",
"=",
"\"program\"",
";",
"}",
"else",
"if",
"(",
"node",
".",
"type",
"===",
"\"ArrowFunctionExpression\"",
")",
"{",
"loc",
"=",
"context",
".",
"getSourceCode",
"(",
")",
".",
"getTokenBefore",
"(",
"node",
".",
"body",
",",
"astUtils",
".",
"isArrowToken",
")",
".",
"loc",
".",
"start",
";",
"}",
"else",
"if",
"(",
"node",
".",
"parent",
".",
"type",
"===",
"\"MethodDefinition\"",
"||",
"(",
"node",
".",
"parent",
".",
"type",
"===",
"\"Property\"",
"&&",
"node",
".",
"parent",
".",
"method",
")",
")",
"{",
"loc",
"=",
"node",
".",
"parent",
".",
"key",
".",
"loc",
".",
"start",
";",
"}",
"else",
"{",
"loc",
"=",
"(",
"node",
".",
"id",
"||",
"node",
")",
".",
"loc",
".",
"start",
";",
"}",
"if",
"(",
"!",
"name",
")",
"{",
"name",
"=",
"astUtils",
".",
"getFunctionNameWithKind",
"(",
"node",
")",
";",
"}",
"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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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",
";",
"if",
"(",
"SINGLE_CHILD_ALLOWED",
".",
"test",
"(",
"node",
".",
"parent",
".",
"type",
")",
"&&",
"node",
".",
"parent",
".",
"alternate",
"!==",
"node",
")",
"{",
"return",
";",
"}",
"if",
"(",
"line",
"===",
"lastStatementLine",
")",
"{",
"numberOfStatementsOnThisLine",
"+=",
"1",
";",
"}",
"else",
"{",
"reportFirstExtraStatementAndClear",
"(",
")",
";",
"numberOfStatementsOnThisLine",
"=",
"1",
";",
"lastStatementLine",
"=",
"line",
";",
"}",
"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
|
train
|
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",
";",
"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
|
train
|
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",
")",
"{",
"const",
"openBrace",
"=",
"getOpenBrace",
"(",
"node",
")",
";",
"const",
"closeBrace",
"=",
"sourceCode",
".",
"getLastToken",
"(",
"node",
")",
";",
"const",
"firstToken",
"=",
"sourceCode",
".",
"getTokenAfter",
"(",
"openBrace",
",",
"{",
"includeComments",
":",
"true",
"}",
")",
";",
"const",
"lastToken",
"=",
"sourceCode",
".",
"getTokenBefore",
"(",
"closeBrace",
",",
"{",
"includeComments",
":",
"true",
"}",
")",
";",
"if",
"(",
"openBrace",
".",
"type",
"!==",
"\"Punctuator\"",
"||",
"openBrace",
".",
"value",
"!==",
"\"{\"",
"||",
"closeBrace",
".",
"type",
"!==",
"\"Punctuator\"",
"||",
"closeBrace",
".",
"value",
"!==",
"\"}\"",
"||",
"firstToken",
"===",
"closeBrace",
")",
"{",
"return",
";",
"}",
"if",
"(",
"!",
"always",
"&&",
"firstToken",
".",
"type",
"===",
"\"Line\"",
")",
"{",
"return",
";",
"}",
"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
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.