id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
sequence
docstring
stringlengths
4
11.8k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
86
226
2,900
eslint/eslint
lib/rules/switch-colon-spacing.js
isValidSpacing
function isValidSpacing(left, right, expected) { return ( astUtils.isClosingBraceToken(right) || !astUtils.isTokenOnSameLine(left, right) || sourceCode.isSpaceBetweenTokens(left, right) === expected ); }
javascript
function isValidSpacing(left, right, expected) { return ( astUtils.isClosingBraceToken(right) || !astUtils.isTokenOnSameLine(left, right) || sourceCode.isSpaceBetweenTokens(left, right) === expected ); }
[ "function", "isValidSpacing", "(", "left", ",", "right", ",", "expected", ")", "{", "return", "(", "astUtils", ".", "isClosingBraceToken", "(", "right", ")", "||", "!", "astUtils", ".", "isTokenOnSameLine", "(", "left", ",", "right", ")", "||", "sourceCode", ".", "isSpaceBetweenTokens", "(", "left", ",", "right", ")", "===", "expected", ")", ";", "}" ]
Check whether the spacing between the given 2 tokens is valid or not. @param {Token} left The left token to check. @param {Token} right The right token to check. @param {boolean} expected The expected spacing to check. `true` if there should be a space. @returns {boolean} `true` if the spacing between the tokens is valid.
[ "Check", "whether", "the", "spacing", "between", "the", "given", "2", "tokens", "is", "valid", "or", "not", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/switch-colon-spacing.js#L73-L79
2,901
eslint/eslint
lib/rules/switch-colon-spacing.js
commentsExistBetween
function commentsExistBetween(left, right) { return sourceCode.getFirstTokenBetween( left, right, { includeComments: true, filter: astUtils.isCommentToken } ) !== null; }
javascript
function commentsExistBetween(left, right) { return sourceCode.getFirstTokenBetween( left, right, { includeComments: true, filter: astUtils.isCommentToken } ) !== null; }
[ "function", "commentsExistBetween", "(", "left", ",", "right", ")", "{", "return", "sourceCode", ".", "getFirstTokenBetween", "(", "left", ",", "right", ",", "{", "includeComments", ":", "true", ",", "filter", ":", "astUtils", ".", "isCommentToken", "}", ")", "!==", "null", ";", "}" ]
Check whether comments exist between the given 2 tokens. @param {Token} left The left token to check. @param {Token} right The right token to check. @returns {boolean} `true` if comments exist between the given 2 tokens.
[ "Check", "whether", "comments", "exist", "between", "the", "given", "2", "tokens", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/switch-colon-spacing.js#L87-L96
2,902
eslint/eslint
lib/rules/switch-colon-spacing.js
fix
function fix(fixer, left, right, spacing) { if (commentsExistBetween(left, right)) { return null; } if (spacing) { return fixer.insertTextAfter(left, " "); } return fixer.removeRange([left.range[1], right.range[0]]); }
javascript
function fix(fixer, left, right, spacing) { if (commentsExistBetween(left, right)) { return null; } if (spacing) { return fixer.insertTextAfter(left, " "); } return fixer.removeRange([left.range[1], right.range[0]]); }
[ "function", "fix", "(", "fixer", ",", "left", ",", "right", ",", "spacing", ")", "{", "if", "(", "commentsExistBetween", "(", "left", ",", "right", ")", ")", "{", "return", "null", ";", "}", "if", "(", "spacing", ")", "{", "return", "fixer", ".", "insertTextAfter", "(", "left", ",", "\" \"", ")", ";", "}", "return", "fixer", ".", "removeRange", "(", "[", "left", ".", "range", "[", "1", "]", ",", "right", ".", "range", "[", "0", "]", "]", ")", ";", "}" ]
Fix the spacing between the given 2 tokens. @param {RuleFixer} fixer The fixer to fix. @param {Token} left The left token of fix range. @param {Token} right The right token of fix range. @param {boolean} spacing The spacing style. `true` if there should be a space. @returns {Fix|null} The fix object.
[ "Fix", "the", "spacing", "between", "the", "given", "2", "tokens", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/switch-colon-spacing.js#L106-L114
2,903
eslint/eslint
lib/rules/callback-return.js
containsOnlyIdentifiers
function containsOnlyIdentifiers(node) { if (node.type === "Identifier") { return true; } if (node.type === "MemberExpression") { if (node.object.type === "Identifier") { return true; } if (node.object.type === "MemberExpression") { return containsOnlyIdentifiers(node.object); } } return false; }
javascript
function containsOnlyIdentifiers(node) { if (node.type === "Identifier") { return true; } if (node.type === "MemberExpression") { if (node.object.type === "Identifier") { return true; } if (node.object.type === "MemberExpression") { return containsOnlyIdentifiers(node.object); } } return false; }
[ "function", "containsOnlyIdentifiers", "(", "node", ")", "{", "if", "(", "node", ".", "type", "===", "\"Identifier\"", ")", "{", "return", "true", ";", "}", "if", "(", "node", ".", "type", "===", "\"MemberExpression\"", ")", "{", "if", "(", "node", ".", "object", ".", "type", "===", "\"Identifier\"", ")", "{", "return", "true", ";", "}", "if", "(", "node", ".", "object", ".", "type", "===", "\"MemberExpression\"", ")", "{", "return", "containsOnlyIdentifiers", "(", "node", ".", "object", ")", ";", "}", "}", "return", "false", ";", "}" ]
Check to see if a node contains only identifers @param {ASTNode} node The node to check @returns {boolean} Whether or not the node contains only identifers
[ "Check", "to", "see", "if", "a", "node", "contains", "only", "identifers" ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/callback-return.js#L62-L77
2,904
eslint/eslint
lib/rules/callback-return.js
isCallback
function isCallback(node) { return containsOnlyIdentifiers(node.callee) && callbacks.indexOf(sourceCode.getText(node.callee)) > -1; }
javascript
function isCallback(node) { return containsOnlyIdentifiers(node.callee) && callbacks.indexOf(sourceCode.getText(node.callee)) > -1; }
[ "function", "isCallback", "(", "node", ")", "{", "return", "containsOnlyIdentifiers", "(", "node", ".", "callee", ")", "&&", "callbacks", ".", "indexOf", "(", "sourceCode", ".", "getText", "(", "node", ".", "callee", ")", ")", ">", "-", "1", ";", "}" ]
Check to see if a CallExpression is in our callback list. @param {ASTNode} node The node to check against our callback names list. @returns {boolean} Whether or not this function matches our callback name.
[ "Check", "to", "see", "if", "a", "CallExpression", "is", "in", "our", "callback", "list", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/callback-return.js#L84-L86
2,905
eslint/eslint
lib/rules/callback-return.js
isCallbackExpression
function isCallbackExpression(node, parentNode) { // ensure the parent node exists and is an expression if (!parentNode || parentNode.type !== "ExpressionStatement") { return false; } // cb() if (parentNode.expression === node) { return true; } // special case for cb && cb() and similar if (parentNode.expression.type === "BinaryExpression" || parentNode.expression.type === "LogicalExpression") { if (parentNode.expression.right === node) { return true; } } return false; }
javascript
function isCallbackExpression(node, parentNode) { // ensure the parent node exists and is an expression if (!parentNode || parentNode.type !== "ExpressionStatement") { return false; } // cb() if (parentNode.expression === node) { return true; } // special case for cb && cb() and similar if (parentNode.expression.type === "BinaryExpression" || parentNode.expression.type === "LogicalExpression") { if (parentNode.expression.right === node) { return true; } } return false; }
[ "function", "isCallbackExpression", "(", "node", ",", "parentNode", ")", "{", "// ensure the parent node exists and is an expression", "if", "(", "!", "parentNode", "||", "parentNode", ".", "type", "!==", "\"ExpressionStatement\"", ")", "{", "return", "false", ";", "}", "// cb()", "if", "(", "parentNode", ".", "expression", "===", "node", ")", "{", "return", "true", ";", "}", "// special case for cb && cb() and similar", "if", "(", "parentNode", ".", "expression", ".", "type", "===", "\"BinaryExpression\"", "||", "parentNode", ".", "expression", ".", "type", "===", "\"LogicalExpression\"", ")", "{", "if", "(", "parentNode", ".", "expression", ".", "right", "===", "node", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Determines whether or not the callback is part of a callback expression. @param {ASTNode} node The callback node @param {ASTNode} parentNode The expression node @returns {boolean} Whether or not this is part of a callback expression
[ "Determines", "whether", "or", "not", "the", "callback", "is", "part", "of", "a", "callback", "expression", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/callback-return.js#L94-L114
2,906
eslint/eslint
lib/rules/no-invalid-this.js
enterFunction
function enterFunction(node) { // `this` can be invalid only under strict mode. stack.push({ init: !context.getScope().isStrict, node, valid: true }); }
javascript
function enterFunction(node) { // `this` can be invalid only under strict mode. stack.push({ init: !context.getScope().isStrict, node, valid: true }); }
[ "function", "enterFunction", "(", "node", ")", "{", "// `this` can be invalid only under strict mode.", "stack", ".", "push", "(", "{", "init", ":", "!", "context", ".", "getScope", "(", ")", ".", "isStrict", ",", "node", ",", "valid", ":", "true", "}", ")", ";", "}" ]
Pushs new checking context into the stack. The checking context is not initialized yet. Because most functions don't have `this` keyword. When `this` keyword was found, the checking context is initialized. @param {ASTNode} node - A function node that was entered. @returns {void}
[ "Pushs", "new", "checking", "context", "into", "the", "stack", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-invalid-this.js#L68-L76
2,907
eslint/eslint
lib/rules/object-curly-newline.js
areLineBreaksRequired
function areLineBreaksRequired(node, options, first, last) { let objectProperties; if (node.type === "ObjectExpression" || node.type === "ObjectPattern") { objectProperties = node.properties; } else { // is ImportDeclaration or ExportNamedDeclaration objectProperties = node.specifiers .filter(s => s.type === "ImportSpecifier" || s.type === "ExportSpecifier"); } return objectProperties.length >= options.minProperties || ( options.multiline && objectProperties.length > 0 && first.loc.start.line !== last.loc.end.line ); }
javascript
function areLineBreaksRequired(node, options, first, last) { let objectProperties; if (node.type === "ObjectExpression" || node.type === "ObjectPattern") { objectProperties = node.properties; } else { // is ImportDeclaration or ExportNamedDeclaration objectProperties = node.specifiers .filter(s => s.type === "ImportSpecifier" || s.type === "ExportSpecifier"); } return objectProperties.length >= options.minProperties || ( options.multiline && objectProperties.length > 0 && first.loc.start.line !== last.loc.end.line ); }
[ "function", "areLineBreaksRequired", "(", "node", ",", "options", ",", "first", ",", "last", ")", "{", "let", "objectProperties", ";", "if", "(", "node", ".", "type", "===", "\"ObjectExpression\"", "||", "node", ".", "type", "===", "\"ObjectPattern\"", ")", "{", "objectProperties", "=", "node", ".", "properties", ";", "}", "else", "{", "// is ImportDeclaration or ExportNamedDeclaration", "objectProperties", "=", "node", ".", "specifiers", ".", "filter", "(", "s", "=>", "s", ".", "type", "===", "\"ImportSpecifier\"", "||", "s", ".", "type", "===", "\"ExportSpecifier\"", ")", ";", "}", "return", "objectProperties", ".", "length", ">=", "options", ".", "minProperties", "||", "(", "options", ".", "multiline", "&&", "objectProperties", ".", "length", ">", "0", "&&", "first", ".", "loc", ".", "start", ".", "line", "!==", "last", ".", "loc", ".", "end", ".", "line", ")", ";", "}" ]
Determines if ObjectExpression, ObjectPattern, ImportDeclaration or ExportNamedDeclaration node needs to be checked for missing line breaks @param {ASTNode} node - Node under inspection @param {Object} options - option specific to node type @param {Token} first - First object property @param {Token} last - Last object property @returns {boolean} `true` if node needs to be checked for missing line breaks
[ "Determines", "if", "ObjectExpression", "ObjectPattern", "ImportDeclaration", "or", "ExportNamedDeclaration", "node", "needs", "to", "be", "checked", "for", "missing", "line", "breaks" ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/object-curly-newline.js#L111-L129
2,908
eslint/eslint
lib/cli-engine.js
calculateStatsPerFile
function calculateStatsPerFile(messages) { return messages.reduce((stat, message) => { if (message.fatal || message.severity === 2) { stat.errorCount++; if (message.fix) { stat.fixableErrorCount++; } } else { stat.warningCount++; if (message.fix) { stat.fixableWarningCount++; } } return stat; }, { errorCount: 0, warningCount: 0, fixableErrorCount: 0, fixableWarningCount: 0 }); }
javascript
function calculateStatsPerFile(messages) { return messages.reduce((stat, message) => { if (message.fatal || message.severity === 2) { stat.errorCount++; if (message.fix) { stat.fixableErrorCount++; } } else { stat.warningCount++; if (message.fix) { stat.fixableWarningCount++; } } return stat; }, { errorCount: 0, warningCount: 0, fixableErrorCount: 0, fixableWarningCount: 0 }); }
[ "function", "calculateStatsPerFile", "(", "messages", ")", "{", "return", "messages", ".", "reduce", "(", "(", "stat", ",", "message", ")", "=>", "{", "if", "(", "message", ".", "fatal", "||", "message", ".", "severity", "===", "2", ")", "{", "stat", ".", "errorCount", "++", ";", "if", "(", "message", ".", "fix", ")", "{", "stat", ".", "fixableErrorCount", "++", ";", "}", "}", "else", "{", "stat", ".", "warningCount", "++", ";", "if", "(", "message", ".", "fix", ")", "{", "stat", ".", "fixableWarningCount", "++", ";", "}", "}", "return", "stat", ";", "}", ",", "{", "errorCount", ":", "0", ",", "warningCount", ":", "0", ",", "fixableErrorCount", ":", "0", ",", "fixableWarningCount", ":", "0", "}", ")", ";", "}" ]
It will calculate the error and warning count for collection of messages per file @param {Object[]} messages - Collection of messages @returns {Object} Contains the stats @private
[ "It", "will", "calculate", "the", "error", "and", "warning", "count", "for", "collection", "of", "messages", "per", "file" ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/cli-engine.js#L112-L132
2,909
eslint/eslint
lib/cli-engine.js
calculateStatsPerRun
function calculateStatsPerRun(results) { return results.reduce((stat, result) => { stat.errorCount += result.errorCount; stat.warningCount += result.warningCount; stat.fixableErrorCount += result.fixableErrorCount; stat.fixableWarningCount += result.fixableWarningCount; return stat; }, { errorCount: 0, warningCount: 0, fixableErrorCount: 0, fixableWarningCount: 0 }); }
javascript
function calculateStatsPerRun(results) { return results.reduce((stat, result) => { stat.errorCount += result.errorCount; stat.warningCount += result.warningCount; stat.fixableErrorCount += result.fixableErrorCount; stat.fixableWarningCount += result.fixableWarningCount; return stat; }, { errorCount: 0, warningCount: 0, fixableErrorCount: 0, fixableWarningCount: 0 }); }
[ "function", "calculateStatsPerRun", "(", "results", ")", "{", "return", "results", ".", "reduce", "(", "(", "stat", ",", "result", ")", "=>", "{", "stat", ".", "errorCount", "+=", "result", ".", "errorCount", ";", "stat", ".", "warningCount", "+=", "result", ".", "warningCount", ";", "stat", ".", "fixableErrorCount", "+=", "result", ".", "fixableErrorCount", ";", "stat", ".", "fixableWarningCount", "+=", "result", ".", "fixableWarningCount", ";", "return", "stat", ";", "}", ",", "{", "errorCount", ":", "0", ",", "warningCount", ":", "0", ",", "fixableErrorCount", ":", "0", ",", "fixableWarningCount", ":", "0", "}", ")", ";", "}" ]
It will calculate the error and warning count for collection of results from all files @param {Object[]} results - Collection of messages from all the files @returns {Object} Contains the stats @private
[ "It", "will", "calculate", "the", "error", "and", "warning", "count", "for", "collection", "of", "results", "from", "all", "files" ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/cli-engine.js#L140-L153
2,910
eslint/eslint
lib/cli-engine.js
processFile
function processFile(filename, configHelper, options, linter) { const text = fs.readFileSync(path.resolve(filename), "utf8"); return processText( text, configHelper, filename, options.fix, options.allowInlineConfig, options.reportUnusedDisableDirectives, linter ); }
javascript
function processFile(filename, configHelper, options, linter) { const text = fs.readFileSync(path.resolve(filename), "utf8"); return processText( text, configHelper, filename, options.fix, options.allowInlineConfig, options.reportUnusedDisableDirectives, linter ); }
[ "function", "processFile", "(", "filename", ",", "configHelper", ",", "options", ",", "linter", ")", "{", "const", "text", "=", "fs", ".", "readFileSync", "(", "path", ".", "resolve", "(", "filename", ")", ",", "\"utf8\"", ")", ";", "return", "processText", "(", "text", ",", "configHelper", ",", "filename", ",", "options", ".", "fix", ",", "options", ".", "allowInlineConfig", ",", "options", ".", "reportUnusedDisableDirectives", ",", "linter", ")", ";", "}" ]
Processes an individual file using ESLint. Files used here are known to exist, so no need to check that here. @param {string} filename The filename of the file being checked. @param {Object} configHelper The configuration options for ESLint. @param {Object} options The CLIEngine options object. @param {Linter} linter Linter context @returns {{rules: LintResult, config: Object}} The results for linting on this text and the fully-resolved config for it. @private
[ "Processes", "an", "individual", "file", "using", "ESLint", ".", "Files", "used", "here", "are", "known", "to", "exist", "so", "no", "need", "to", "check", "that", "here", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/cli-engine.js#L243-L256
2,911
eslint/eslint
lib/rules/max-lines-per-function.js
isIIFE
function isIIFE(node) { return node.type === "FunctionExpression" && node.parent && node.parent.type === "CallExpression" && node.parent.callee === node; }
javascript
function isIIFE(node) { return node.type === "FunctionExpression" && node.parent && node.parent.type === "CallExpression" && node.parent.callee === node; }
[ "function", "isIIFE", "(", "node", ")", "{", "return", "node", ".", "type", "===", "\"FunctionExpression\"", "&&", "node", ".", "parent", "&&", "node", ".", "parent", ".", "type", "===", "\"CallExpression\"", "&&", "node", ".", "parent", ".", "callee", "===", "node", ";", "}" ]
Identifies is a node is a FunctionExpression which is part of an IIFE @param {ASTNode} node Node to test @returns {boolean} True if it's an IIFE
[ "Identifies", "is", "a", "node", "is", "a", "FunctionExpression", "which", "is", "part", "of", "an", "IIFE" ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/max-lines-per-function.js#L137-L139
2,912
eslint/eslint
lib/rules/max-lines-per-function.js
isEmbedded
function isEmbedded(node) { if (!node.parent) { return false; } if (node !== node.parent.value) { return false; } if (node.parent.type === "MethodDefinition") { return true; } if (node.parent.type === "Property") { return node.parent.method === true || node.parent.kind === "get" || node.parent.kind === "set"; } return false; }
javascript
function isEmbedded(node) { if (!node.parent) { return false; } if (node !== node.parent.value) { return false; } if (node.parent.type === "MethodDefinition") { return true; } if (node.parent.type === "Property") { return node.parent.method === true || node.parent.kind === "get" || node.parent.kind === "set"; } return false; }
[ "function", "isEmbedded", "(", "node", ")", "{", "if", "(", "!", "node", ".", "parent", ")", "{", "return", "false", ";", "}", "if", "(", "node", "!==", "node", ".", "parent", ".", "value", ")", "{", "return", "false", ";", "}", "if", "(", "node", ".", "parent", ".", "type", "===", "\"MethodDefinition\"", ")", "{", "return", "true", ";", "}", "if", "(", "node", ".", "parent", ".", "type", "===", "\"Property\"", ")", "{", "return", "node", ".", "parent", ".", "method", "===", "true", "||", "node", ".", "parent", ".", "kind", "===", "\"get\"", "||", "node", ".", "parent", ".", "kind", "===", "\"set\"", ";", "}", "return", "false", ";", "}" ]
Identifies is a node is a FunctionExpression which is embedded within a MethodDefinition or Property @param {ASTNode} node Node to test @returns {boolean} True if it's a FunctionExpression embedded within a MethodDefinition or Property
[ "Identifies", "is", "a", "node", "is", "a", "FunctionExpression", "which", "is", "embedded", "within", "a", "MethodDefinition", "or", "Property" ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/max-lines-per-function.js#L146-L160
2,913
eslint/eslint
lib/rules/max-lines-per-function.js
processFunction
function processFunction(funcNode) { const node = isEmbedded(funcNode) ? funcNode.parent : funcNode; if (!IIFEs && isIIFE(node)) { return; } let lineCount = 0; for (let i = node.loc.start.line - 1; i < node.loc.end.line; ++i) { const line = lines[i]; if (skipComments) { if (commentLineNumbers.has(i + 1) && isFullLineComment(line, i + 1, commentLineNumbers.get(i + 1))) { continue; } } if (skipBlankLines) { if (line.match(/^\s*$/u)) { continue; } } lineCount++; } if (lineCount > maxLines) { const name = astUtils.getFunctionNameWithKind(funcNode); context.report({ node, messageId: "exceed", data: { name, lineCount, maxLines } }); } }
javascript
function processFunction(funcNode) { const node = isEmbedded(funcNode) ? funcNode.parent : funcNode; if (!IIFEs && isIIFE(node)) { return; } let lineCount = 0; for (let i = node.loc.start.line - 1; i < node.loc.end.line; ++i) { const line = lines[i]; if (skipComments) { if (commentLineNumbers.has(i + 1) && isFullLineComment(line, i + 1, commentLineNumbers.get(i + 1))) { continue; } } if (skipBlankLines) { if (line.match(/^\s*$/u)) { continue; } } lineCount++; } if (lineCount > maxLines) { const name = astUtils.getFunctionNameWithKind(funcNode); context.report({ node, messageId: "exceed", data: { name, lineCount, maxLines } }); } }
[ "function", "processFunction", "(", "funcNode", ")", "{", "const", "node", "=", "isEmbedded", "(", "funcNode", ")", "?", "funcNode", ".", "parent", ":", "funcNode", ";", "if", "(", "!", "IIFEs", "&&", "isIIFE", "(", "node", ")", ")", "{", "return", ";", "}", "let", "lineCount", "=", "0", ";", "for", "(", "let", "i", "=", "node", ".", "loc", ".", "start", ".", "line", "-", "1", ";", "i", "<", "node", ".", "loc", ".", "end", ".", "line", ";", "++", "i", ")", "{", "const", "line", "=", "lines", "[", "i", "]", ";", "if", "(", "skipComments", ")", "{", "if", "(", "commentLineNumbers", ".", "has", "(", "i", "+", "1", ")", "&&", "isFullLineComment", "(", "line", ",", "i", "+", "1", ",", "commentLineNumbers", ".", "get", "(", "i", "+", "1", ")", ")", ")", "{", "continue", ";", "}", "}", "if", "(", "skipBlankLines", ")", "{", "if", "(", "line", ".", "match", "(", "/", "^\\s*$", "/", "u", ")", ")", "{", "continue", ";", "}", "}", "lineCount", "++", ";", "}", "if", "(", "lineCount", ">", "maxLines", ")", "{", "const", "name", "=", "astUtils", ".", "getFunctionNameWithKind", "(", "funcNode", ")", ";", "context", ".", "report", "(", "{", "node", ",", "messageId", ":", "\"exceed\"", ",", "data", ":", "{", "name", ",", "lineCount", ",", "maxLines", "}", "}", ")", ";", "}", "}" ]
Count the lines in the function @param {ASTNode} funcNode Function AST node @returns {void} @private
[ "Count", "the", "lines", "in", "the", "function" ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/max-lines-per-function.js#L168-L203
2,914
eslint/eslint
lib/rules/no-useless-constructor.js
isValidIdentifierPair
function isValidIdentifierPair(ctorParam, superArg) { return ( ctorParam.type === "Identifier" && superArg.type === "Identifier" && ctorParam.name === superArg.name ); }
javascript
function isValidIdentifierPair(ctorParam, superArg) { return ( ctorParam.type === "Identifier" && superArg.type === "Identifier" && ctorParam.name === superArg.name ); }
[ "function", "isValidIdentifierPair", "(", "ctorParam", ",", "superArg", ")", "{", "return", "(", "ctorParam", ".", "type", "===", "\"Identifier\"", "&&", "superArg", ".", "type", "===", "\"Identifier\"", "&&", "ctorParam", ".", "name", "===", "superArg", ".", "name", ")", ";", "}" ]
Checks whether given 2 nodes are identifiers which have the same name or not. @param {ASTNode} ctorParam - A node to check. @param {ASTNode} superArg - A node to check. @returns {boolean} `true` if the nodes are identifiers which have the same name.
[ "Checks", "whether", "given", "2", "nodes", "are", "identifiers", "which", "have", "the", "same", "name", "or", "not", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-useless-constructor.js#L61-L67
2,915
eslint/eslint
lib/rules/no-useless-constructor.js
isRedundantSuperCall
function isRedundantSuperCall(body, ctorParams) { return ( isSingleSuperCall(body) && ctorParams.every(isSimple) && ( isSpreadArguments(body[0].expression.arguments) || isPassingThrough(ctorParams, body[0].expression.arguments) ) ); }
javascript
function isRedundantSuperCall(body, ctorParams) { return ( isSingleSuperCall(body) && ctorParams.every(isSimple) && ( isSpreadArguments(body[0].expression.arguments) || isPassingThrough(ctorParams, body[0].expression.arguments) ) ); }
[ "function", "isRedundantSuperCall", "(", "body", ",", "ctorParams", ")", "{", "return", "(", "isSingleSuperCall", "(", "body", ")", "&&", "ctorParams", ".", "every", "(", "isSimple", ")", "&&", "(", "isSpreadArguments", "(", "body", "[", "0", "]", ".", "expression", ".", "arguments", ")", "||", "isPassingThrough", "(", "ctorParams", ",", "body", "[", "0", "]", ".", "expression", ".", "arguments", ")", ")", ")", ";", "}" ]
Checks whether the constructor body is a redundant super call. @param {Array} body - constructor body content. @param {Array} ctorParams - The params to check against super call. @returns {boolean} true if the construtor body is redundant
[ "Checks", "whether", "the", "constructor", "body", "is", "a", "redundant", "super", "call", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-useless-constructor.js#L128-L137
2,916
eslint/eslint
lib/rules/no-useless-constructor.js
checkForConstructor
function checkForConstructor(node) { if (node.kind !== "constructor") { return; } const body = node.value.body.body; const ctorParams = node.value.params; const superClass = node.parent.parent.superClass; if (superClass ? isRedundantSuperCall(body, ctorParams) : (body.length === 0)) { context.report({ node, message: "Useless constructor." }); } }
javascript
function checkForConstructor(node) { if (node.kind !== "constructor") { return; } const body = node.value.body.body; const ctorParams = node.value.params; const superClass = node.parent.parent.superClass; if (superClass ? isRedundantSuperCall(body, ctorParams) : (body.length === 0)) { context.report({ node, message: "Useless constructor." }); } }
[ "function", "checkForConstructor", "(", "node", ")", "{", "if", "(", "node", ".", "kind", "!==", "\"constructor\"", ")", "{", "return", ";", "}", "const", "body", "=", "node", ".", "value", ".", "body", ".", "body", ";", "const", "ctorParams", "=", "node", ".", "value", ".", "params", ";", "const", "superClass", "=", "node", ".", "parent", ".", "parent", ".", "superClass", ";", "if", "(", "superClass", "?", "isRedundantSuperCall", "(", "body", ",", "ctorParams", ")", ":", "(", "body", ".", "length", "===", "0", ")", ")", "{", "context", ".", "report", "(", "{", "node", ",", "message", ":", "\"Useless constructor.\"", "}", ")", ";", "}", "}" ]
Checks whether a node is a redundant constructor @param {ASTNode} node - node to check @returns {void}
[ "Checks", "whether", "a", "node", "is", "a", "redundant", "constructor" ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-useless-constructor.js#L164-L179
2,917
eslint/eslint
lib/rules/no-mixed-spaces-and-tabs.js
beforeLoc
function beforeLoc(loc, line, column) { if (line < loc.start.line) { return true; } return line === loc.start.line && column < loc.start.column; }
javascript
function beforeLoc(loc, line, column) { if (line < loc.start.line) { return true; } return line === loc.start.line && column < loc.start.column; }
[ "function", "beforeLoc", "(", "loc", ",", "line", ",", "column", ")", "{", "if", "(", "line", "<", "loc", ".", "start", ".", "line", ")", "{", "return", "true", ";", "}", "return", "line", "===", "loc", ".", "start", ".", "line", "&&", "column", "<", "loc", ".", "start", ".", "column", ";", "}" ]
Determines if a given line and column are before a location. @param {Location} loc The location object from an AST node. @param {int} line The line to check. @param {int} column The column to check. @returns {boolean} True if the line and column are before the location, false if not. @private
[ "Determines", "if", "a", "given", "line", "and", "column", "are", "before", "a", "location", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-mixed-spaces-and-tabs.js#L52-L57
2,918
eslint/eslint
lib/rules/no-mixed-spaces-and-tabs.js
afterLoc
function afterLoc(loc, line, column) { if (line > loc.end.line) { return true; } return line === loc.end.line && column > loc.end.column; }
javascript
function afterLoc(loc, line, column) { if (line > loc.end.line) { return true; } return line === loc.end.line && column > loc.end.column; }
[ "function", "afterLoc", "(", "loc", ",", "line", ",", "column", ")", "{", "if", "(", "line", ">", "loc", ".", "end", ".", "line", ")", "{", "return", "true", ";", "}", "return", "line", "===", "loc", ".", "end", ".", "line", "&&", "column", ">", "loc", ".", "end", ".", "column", ";", "}" ]
Determines if a given line and column are after a location. @param {Location} loc The location object from an AST node. @param {int} line The line to check. @param {int} column The column to check. @returns {boolean} True if the line and column are after the location, false if not. @private
[ "Determines", "if", "a", "given", "line", "and", "column", "are", "after", "a", "location", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-mixed-spaces-and-tabs.js#L67-L72
2,919
eslint/eslint
lib/token-store/index.js
createIndexMap
function createIndexMap(tokens, comments) { const map = Object.create(null); let tokenIndex = 0; let commentIndex = 0; let nextStart = 0; let range = null; while (tokenIndex < tokens.length || commentIndex < comments.length) { nextStart = (commentIndex < comments.length) ? comments[commentIndex].range[0] : Number.MAX_SAFE_INTEGER; while (tokenIndex < tokens.length && (range = tokens[tokenIndex].range)[0] < nextStart) { map[range[0]] = tokenIndex; map[range[1] - 1] = tokenIndex; tokenIndex += 1; } nextStart = (tokenIndex < tokens.length) ? tokens[tokenIndex].range[0] : Number.MAX_SAFE_INTEGER; while (commentIndex < comments.length && (range = comments[commentIndex].range)[0] < nextStart) { map[range[0]] = tokenIndex; map[range[1] - 1] = tokenIndex; commentIndex += 1; } } return map; }
javascript
function createIndexMap(tokens, comments) { const map = Object.create(null); let tokenIndex = 0; let commentIndex = 0; let nextStart = 0; let range = null; while (tokenIndex < tokens.length || commentIndex < comments.length) { nextStart = (commentIndex < comments.length) ? comments[commentIndex].range[0] : Number.MAX_SAFE_INTEGER; while (tokenIndex < tokens.length && (range = tokens[tokenIndex].range)[0] < nextStart) { map[range[0]] = tokenIndex; map[range[1] - 1] = tokenIndex; tokenIndex += 1; } nextStart = (tokenIndex < tokens.length) ? tokens[tokenIndex].range[0] : Number.MAX_SAFE_INTEGER; while (commentIndex < comments.length && (range = comments[commentIndex].range)[0] < nextStart) { map[range[0]] = tokenIndex; map[range[1] - 1] = tokenIndex; commentIndex += 1; } } return map; }
[ "function", "createIndexMap", "(", "tokens", ",", "comments", ")", "{", "const", "map", "=", "Object", ".", "create", "(", "null", ")", ";", "let", "tokenIndex", "=", "0", ";", "let", "commentIndex", "=", "0", ";", "let", "nextStart", "=", "0", ";", "let", "range", "=", "null", ";", "while", "(", "tokenIndex", "<", "tokens", ".", "length", "||", "commentIndex", "<", "comments", ".", "length", ")", "{", "nextStart", "=", "(", "commentIndex", "<", "comments", ".", "length", ")", "?", "comments", "[", "commentIndex", "]", ".", "range", "[", "0", "]", ":", "Number", ".", "MAX_SAFE_INTEGER", ";", "while", "(", "tokenIndex", "<", "tokens", ".", "length", "&&", "(", "range", "=", "tokens", "[", "tokenIndex", "]", ".", "range", ")", "[", "0", "]", "<", "nextStart", ")", "{", "map", "[", "range", "[", "0", "]", "]", "=", "tokenIndex", ";", "map", "[", "range", "[", "1", "]", "-", "1", "]", "=", "tokenIndex", ";", "tokenIndex", "+=", "1", ";", "}", "nextStart", "=", "(", "tokenIndex", "<", "tokens", ".", "length", ")", "?", "tokens", "[", "tokenIndex", "]", ".", "range", "[", "0", "]", ":", "Number", ".", "MAX_SAFE_INTEGER", ";", "while", "(", "commentIndex", "<", "comments", ".", "length", "&&", "(", "range", "=", "comments", "[", "commentIndex", "]", ".", "range", ")", "[", "0", "]", "<", "nextStart", ")", "{", "map", "[", "range", "[", "0", "]", "]", "=", "tokenIndex", ";", "map", "[", "range", "[", "1", "]", "-", "1", "]", "=", "tokenIndex", ";", "commentIndex", "+=", "1", ";", "}", "}", "return", "map", ";", "}" ]
Creates the map from locations to indices in `tokens`. The first/last location of tokens is mapped to the index of the token. The first/last location of comments is mapped to the index of the next token of each comment. @param {Token[]} tokens - The array of tokens. @param {Comment[]} comments - The array of comments. @returns {Object} The map from locations to indices in `tokens`. @private
[ "Creates", "the", "map", "from", "locations", "to", "indices", "in", "tokens", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/token-store/index.js#L37-L61
2,920
eslint/eslint
lib/token-store/index.js
createCursorWithPadding
function createCursorWithPadding(tokens, comments, indexMap, startLoc, endLoc, beforeCount, afterCount) { if (typeof beforeCount === "undefined" && typeof afterCount === "undefined") { return new ForwardTokenCursor(tokens, comments, indexMap, startLoc, endLoc); } if (typeof beforeCount === "number" || typeof beforeCount === "undefined") { return new PaddedTokenCursor(tokens, comments, indexMap, startLoc, endLoc, beforeCount | 0, afterCount | 0); } return createCursorWithCount(cursors.forward, tokens, comments, indexMap, startLoc, endLoc, beforeCount); }
javascript
function createCursorWithPadding(tokens, comments, indexMap, startLoc, endLoc, beforeCount, afterCount) { if (typeof beforeCount === "undefined" && typeof afterCount === "undefined") { return new ForwardTokenCursor(tokens, comments, indexMap, startLoc, endLoc); } if (typeof beforeCount === "number" || typeof beforeCount === "undefined") { return new PaddedTokenCursor(tokens, comments, indexMap, startLoc, endLoc, beforeCount | 0, afterCount | 0); } return createCursorWithCount(cursors.forward, tokens, comments, indexMap, startLoc, endLoc, beforeCount); }
[ "function", "createCursorWithPadding", "(", "tokens", ",", "comments", ",", "indexMap", ",", "startLoc", ",", "endLoc", ",", "beforeCount", ",", "afterCount", ")", "{", "if", "(", "typeof", "beforeCount", "===", "\"undefined\"", "&&", "typeof", "afterCount", "===", "\"undefined\"", ")", "{", "return", "new", "ForwardTokenCursor", "(", "tokens", ",", "comments", ",", "indexMap", ",", "startLoc", ",", "endLoc", ")", ";", "}", "if", "(", "typeof", "beforeCount", "===", "\"number\"", "||", "typeof", "beforeCount", "===", "\"undefined\"", ")", "{", "return", "new", "PaddedTokenCursor", "(", "tokens", ",", "comments", ",", "indexMap", ",", "startLoc", ",", "endLoc", ",", "beforeCount", "|", "0", ",", "afterCount", "|", "0", ")", ";", "}", "return", "createCursorWithCount", "(", "cursors", ".", "forward", ",", "tokens", ",", "comments", ",", "indexMap", ",", "startLoc", ",", "endLoc", ",", "beforeCount", ")", ";", "}" ]
Creates the cursor iterates tokens with options. This is overload function of the below. @param {Token[]} tokens - The array of tokens. @param {Comment[]} comments - The array of comments. @param {Object} indexMap - The map from locations to indices in `tokens`. @param {number} startLoc - The start location of the iteration range. @param {number} endLoc - The end location of the iteration range. @param {Function|Object} opts - The option object. If this is a function then it's `opts.filter`. @param {boolean} [opts.includeComments] - The flag to iterate comments as well. @param {Function|null} [opts.filter=null] - The predicate function to choose tokens. @param {number} [opts.count=0] - The maximum count of tokens the cursor iterates. Zero is no iteration for backward compatibility. @returns {Cursor} The created cursor. @private Creates the cursor iterates tokens with options. @param {Token[]} tokens - The array of tokens. @param {Comment[]} comments - The array of comments. @param {Object} indexMap - The map from locations to indices in `tokens`. @param {number} startLoc - The start location of the iteration range. @param {number} endLoc - The end location of the iteration range. @param {number} [beforeCount=0] - The number of tokens before the node to retrieve. @param {boolean} [afterCount=0] - The number of tokens after the node to retrieve. @returns {Cursor} The created cursor. @private
[ "Creates", "the", "cursor", "iterates", "tokens", "with", "options", ".", "This", "is", "overload", "function", "of", "the", "below", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/token-store/index.js#L167-L175
2,921
eslint/eslint
lib/token-store/index.js
getAdjacentCommentTokensFromCursor
function getAdjacentCommentTokensFromCursor(cursor) { const tokens = []; let currentToken = cursor.getOneToken(); while (currentToken && astUtils.isCommentToken(currentToken)) { tokens.push(currentToken); currentToken = cursor.getOneToken(); } return tokens; }
javascript
function getAdjacentCommentTokensFromCursor(cursor) { const tokens = []; let currentToken = cursor.getOneToken(); while (currentToken && astUtils.isCommentToken(currentToken)) { tokens.push(currentToken); currentToken = cursor.getOneToken(); } return tokens; }
[ "function", "getAdjacentCommentTokensFromCursor", "(", "cursor", ")", "{", "const", "tokens", "=", "[", "]", ";", "let", "currentToken", "=", "cursor", ".", "getOneToken", "(", ")", ";", "while", "(", "currentToken", "&&", "astUtils", ".", "isCommentToken", "(", "currentToken", ")", ")", "{", "tokens", ".", "push", "(", "currentToken", ")", ";", "currentToken", "=", "cursor", ".", "getOneToken", "(", ")", ";", "}", "return", "tokens", ";", "}" ]
Gets comment tokens that are adjacent to the current cursor position. @param {Cursor} cursor - A cursor instance. @returns {Array} An array of comment tokens adjacent to the current cursor position. @private
[ "Gets", "comment", "tokens", "that", "are", "adjacent", "to", "the", "current", "cursor", "position", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/token-store/index.js#L183-L193
2,922
eslint/eslint
lib/rules/semi-spacing.js
hasLeadingSpace
function hasLeadingSpace(token) { const tokenBefore = sourceCode.getTokenBefore(token); return tokenBefore && astUtils.isTokenOnSameLine(tokenBefore, token) && sourceCode.isSpaceBetweenTokens(tokenBefore, token); }
javascript
function hasLeadingSpace(token) { const tokenBefore = sourceCode.getTokenBefore(token); return tokenBefore && astUtils.isTokenOnSameLine(tokenBefore, token) && sourceCode.isSpaceBetweenTokens(tokenBefore, token); }
[ "function", "hasLeadingSpace", "(", "token", ")", "{", "const", "tokenBefore", "=", "sourceCode", ".", "getTokenBefore", "(", "token", ")", ";", "return", "tokenBefore", "&&", "astUtils", ".", "isTokenOnSameLine", "(", "tokenBefore", ",", "token", ")", "&&", "sourceCode", ".", "isSpaceBetweenTokens", "(", "tokenBefore", ",", "token", ")", ";", "}" ]
Checks if a given token has leading whitespace. @param {Object} token The token to check. @returns {boolean} True if the given token has leading space, false if not.
[ "Checks", "if", "a", "given", "token", "has", "leading", "whitespace", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/semi-spacing.js#L62-L66
2,923
eslint/eslint
lib/rules/semi-spacing.js
hasTrailingSpace
function hasTrailingSpace(token) { const tokenAfter = sourceCode.getTokenAfter(token); return tokenAfter && astUtils.isTokenOnSameLine(token, tokenAfter) && sourceCode.isSpaceBetweenTokens(token, tokenAfter); }
javascript
function hasTrailingSpace(token) { const tokenAfter = sourceCode.getTokenAfter(token); return tokenAfter && astUtils.isTokenOnSameLine(token, tokenAfter) && sourceCode.isSpaceBetweenTokens(token, tokenAfter); }
[ "function", "hasTrailingSpace", "(", "token", ")", "{", "const", "tokenAfter", "=", "sourceCode", ".", "getTokenAfter", "(", "token", ")", ";", "return", "tokenAfter", "&&", "astUtils", ".", "isTokenOnSameLine", "(", "token", ",", "tokenAfter", ")", "&&", "sourceCode", ".", "isSpaceBetweenTokens", "(", "token", ",", "tokenAfter", ")", ";", "}" ]
Checks if a given token has trailing whitespace. @param {Object} token The token to check. @returns {boolean} True if the given token has trailing space, false if not.
[ "Checks", "if", "a", "given", "token", "has", "trailing", "whitespace", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/semi-spacing.js#L73-L77
2,924
eslint/eslint
lib/rules/semi-spacing.js
isLastTokenInCurrentLine
function isLastTokenInCurrentLine(token) { const tokenAfter = sourceCode.getTokenAfter(token); return !(tokenAfter && astUtils.isTokenOnSameLine(token, tokenAfter)); }
javascript
function isLastTokenInCurrentLine(token) { const tokenAfter = sourceCode.getTokenAfter(token); return !(tokenAfter && astUtils.isTokenOnSameLine(token, tokenAfter)); }
[ "function", "isLastTokenInCurrentLine", "(", "token", ")", "{", "const", "tokenAfter", "=", "sourceCode", ".", "getTokenAfter", "(", "token", ")", ";", "return", "!", "(", "tokenAfter", "&&", "astUtils", ".", "isTokenOnSameLine", "(", "token", ",", "tokenAfter", ")", ")", ";", "}" ]
Checks if the given token is the last token in its line. @param {Token} token The token to check. @returns {boolean} Whether or not the token is the last in its line.
[ "Checks", "if", "the", "given", "token", "is", "the", "last", "token", "in", "its", "line", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/semi-spacing.js#L84-L88
2,925
eslint/eslint
lib/rules/semi-spacing.js
isFirstTokenInCurrentLine
function isFirstTokenInCurrentLine(token) { const tokenBefore = sourceCode.getTokenBefore(token); return !(tokenBefore && astUtils.isTokenOnSameLine(token, tokenBefore)); }
javascript
function isFirstTokenInCurrentLine(token) { const tokenBefore = sourceCode.getTokenBefore(token); return !(tokenBefore && astUtils.isTokenOnSameLine(token, tokenBefore)); }
[ "function", "isFirstTokenInCurrentLine", "(", "token", ")", "{", "const", "tokenBefore", "=", "sourceCode", ".", "getTokenBefore", "(", "token", ")", ";", "return", "!", "(", "tokenBefore", "&&", "astUtils", ".", "isTokenOnSameLine", "(", "token", ",", "tokenBefore", ")", ")", ";", "}" ]
Checks if the given token is the first token in its line @param {Token} token The token to check. @returns {boolean} Whether or not the token is the first in its line.
[ "Checks", "if", "the", "given", "token", "is", "the", "first", "token", "in", "its", "line" ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/semi-spacing.js#L95-L99
2,926
eslint/eslint
lib/rules/semi-spacing.js
isBeforeClosingParen
function isBeforeClosingParen(token) { const nextToken = sourceCode.getTokenAfter(token); return (nextToken && astUtils.isClosingBraceToken(nextToken) || astUtils.isClosingParenToken(nextToken)); }
javascript
function isBeforeClosingParen(token) { const nextToken = sourceCode.getTokenAfter(token); return (nextToken && astUtils.isClosingBraceToken(nextToken) || astUtils.isClosingParenToken(nextToken)); }
[ "function", "isBeforeClosingParen", "(", "token", ")", "{", "const", "nextToken", "=", "sourceCode", ".", "getTokenAfter", "(", "token", ")", ";", "return", "(", "nextToken", "&&", "astUtils", ".", "isClosingBraceToken", "(", "nextToken", ")", "||", "astUtils", ".", "isClosingParenToken", "(", "nextToken", ")", ")", ";", "}" ]
Checks if the next token of a given token is a closing parenthesis. @param {Token} token The token to check. @returns {boolean} Whether or not the next token of a given token is a closing parenthesis.
[ "Checks", "if", "the", "next", "token", "of", "a", "given", "token", "is", "a", "closing", "parenthesis", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/semi-spacing.js#L106-L110
2,927
eslint/eslint
lib/rules/semi-spacing.js
checkSemicolonSpacing
function checkSemicolonSpacing(token, node) { if (astUtils.isSemicolonToken(token)) { const location = token.loc.start; if (hasLeadingSpace(token)) { if (!requireSpaceBefore) { context.report({ node, loc: location, message: "Unexpected whitespace before semicolon.", fix(fixer) { const tokenBefore = sourceCode.getTokenBefore(token); return fixer.removeRange([tokenBefore.range[1], token.range[0]]); } }); } } else { if (requireSpaceBefore) { context.report({ node, loc: location, message: "Missing whitespace before semicolon.", fix(fixer) { return fixer.insertTextBefore(token, " "); } }); } } if (!isFirstTokenInCurrentLine(token) && !isLastTokenInCurrentLine(token) && !isBeforeClosingParen(token)) { if (hasTrailingSpace(token)) { if (!requireSpaceAfter) { context.report({ node, loc: location, message: "Unexpected whitespace after semicolon.", fix(fixer) { const tokenAfter = sourceCode.getTokenAfter(token); return fixer.removeRange([token.range[1], tokenAfter.range[0]]); } }); } } else { if (requireSpaceAfter) { context.report({ node, loc: location, message: "Missing whitespace after semicolon.", fix(fixer) { return fixer.insertTextAfter(token, " "); } }); } } } } }
javascript
function checkSemicolonSpacing(token, node) { if (astUtils.isSemicolonToken(token)) { const location = token.loc.start; if (hasLeadingSpace(token)) { if (!requireSpaceBefore) { context.report({ node, loc: location, message: "Unexpected whitespace before semicolon.", fix(fixer) { const tokenBefore = sourceCode.getTokenBefore(token); return fixer.removeRange([tokenBefore.range[1], token.range[0]]); } }); } } else { if (requireSpaceBefore) { context.report({ node, loc: location, message: "Missing whitespace before semicolon.", fix(fixer) { return fixer.insertTextBefore(token, " "); } }); } } if (!isFirstTokenInCurrentLine(token) && !isLastTokenInCurrentLine(token) && !isBeforeClosingParen(token)) { if (hasTrailingSpace(token)) { if (!requireSpaceAfter) { context.report({ node, loc: location, message: "Unexpected whitespace after semicolon.", fix(fixer) { const tokenAfter = sourceCode.getTokenAfter(token); return fixer.removeRange([token.range[1], tokenAfter.range[0]]); } }); } } else { if (requireSpaceAfter) { context.report({ node, loc: location, message: "Missing whitespace after semicolon.", fix(fixer) { return fixer.insertTextAfter(token, " "); } }); } } } } }
[ "function", "checkSemicolonSpacing", "(", "token", ",", "node", ")", "{", "if", "(", "astUtils", ".", "isSemicolonToken", "(", "token", ")", ")", "{", "const", "location", "=", "token", ".", "loc", ".", "start", ";", "if", "(", "hasLeadingSpace", "(", "token", ")", ")", "{", "if", "(", "!", "requireSpaceBefore", ")", "{", "context", ".", "report", "(", "{", "node", ",", "loc", ":", "location", ",", "message", ":", "\"Unexpected whitespace before semicolon.\"", ",", "fix", "(", "fixer", ")", "{", "const", "tokenBefore", "=", "sourceCode", ".", "getTokenBefore", "(", "token", ")", ";", "return", "fixer", ".", "removeRange", "(", "[", "tokenBefore", ".", "range", "[", "1", "]", ",", "token", ".", "range", "[", "0", "]", "]", ")", ";", "}", "}", ")", ";", "}", "}", "else", "{", "if", "(", "requireSpaceBefore", ")", "{", "context", ".", "report", "(", "{", "node", ",", "loc", ":", "location", ",", "message", ":", "\"Missing whitespace before semicolon.\"", ",", "fix", "(", "fixer", ")", "{", "return", "fixer", ".", "insertTextBefore", "(", "token", ",", "\" \"", ")", ";", "}", "}", ")", ";", "}", "}", "if", "(", "!", "isFirstTokenInCurrentLine", "(", "token", ")", "&&", "!", "isLastTokenInCurrentLine", "(", "token", ")", "&&", "!", "isBeforeClosingParen", "(", "token", ")", ")", "{", "if", "(", "hasTrailingSpace", "(", "token", ")", ")", "{", "if", "(", "!", "requireSpaceAfter", ")", "{", "context", ".", "report", "(", "{", "node", ",", "loc", ":", "location", ",", "message", ":", "\"Unexpected whitespace after semicolon.\"", ",", "fix", "(", "fixer", ")", "{", "const", "tokenAfter", "=", "sourceCode", ".", "getTokenAfter", "(", "token", ")", ";", "return", "fixer", ".", "removeRange", "(", "[", "token", ".", "range", "[", "1", "]", ",", "tokenAfter", ".", "range", "[", "0", "]", "]", ")", ";", "}", "}", ")", ";", "}", "}", "else", "{", "if", "(", "requireSpaceAfter", ")", "{", "context", ".", "report", "(", "{", "node", ",", "loc", ":", "location", ",", "message", ":", "\"Missing whitespace after semicolon.\"", ",", "fix", "(", "fixer", ")", "{", "return", "fixer", ".", "insertTextAfter", "(", "token", ",", "\" \"", ")", ";", "}", "}", ")", ";", "}", "}", "}", "}", "}" ]
Reports if the given token has invalid spacing. @param {Token} token The semicolon token to check. @param {ASTNode} node The corresponding node of the token. @returns {void}
[ "Reports", "if", "the", "given", "token", "has", "invalid", "spacing", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/semi-spacing.js#L118-L176
2,928
eslint/eslint
lib/rules/no-unexpected-multiline.js
checkForBreakAfter
function checkForBreakAfter(node, messageId) { const openParen = sourceCode.getTokenAfter(node, astUtils.isNotClosingParenToken); const nodeExpressionEnd = sourceCode.getTokenBefore(openParen); if (openParen.loc.start.line !== nodeExpressionEnd.loc.end.line) { context.report({ node, loc: openParen.loc.start, messageId, data: { char: openParen.value } }); } }
javascript
function checkForBreakAfter(node, messageId) { const openParen = sourceCode.getTokenAfter(node, astUtils.isNotClosingParenToken); const nodeExpressionEnd = sourceCode.getTokenBefore(openParen); if (openParen.loc.start.line !== nodeExpressionEnd.loc.end.line) { context.report({ node, loc: openParen.loc.start, messageId, data: { char: openParen.value } }); } }
[ "function", "checkForBreakAfter", "(", "node", ",", "messageId", ")", "{", "const", "openParen", "=", "sourceCode", ".", "getTokenAfter", "(", "node", ",", "astUtils", ".", "isNotClosingParenToken", ")", ";", "const", "nodeExpressionEnd", "=", "sourceCode", ".", "getTokenBefore", "(", "openParen", ")", ";", "if", "(", "openParen", ".", "loc", ".", "start", ".", "line", "!==", "nodeExpressionEnd", ".", "loc", ".", "end", ".", "line", ")", "{", "context", ".", "report", "(", "{", "node", ",", "loc", ":", "openParen", ".", "loc", ".", "start", ",", "messageId", ",", "data", ":", "{", "char", ":", "openParen", ".", "value", "}", "}", ")", ";", "}", "}" ]
Check to see if there is a newline between the node and the following open bracket line's expression @param {ASTNode} node The node to check. @param {string} messageId The error messageId to use. @returns {void} @private
[ "Check", "to", "see", "if", "there", "is", "a", "newline", "between", "the", "node", "and", "the", "following", "open", "bracket", "line", "s", "expression" ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-unexpected-multiline.js#L51-L58
2,929
eslint/eslint
lib/rules/no-loop-func.js
getTopLoopNode
function getTopLoopNode(node, excludedNode) { const border = excludedNode ? excludedNode.range[1] : 0; let retv = node; let containingLoopNode = node; while (containingLoopNode && containingLoopNode.range[0] >= border) { retv = containingLoopNode; containingLoopNode = getContainingLoopNode(containingLoopNode); } return retv; }
javascript
function getTopLoopNode(node, excludedNode) { const border = excludedNode ? excludedNode.range[1] : 0; let retv = node; let containingLoopNode = node; while (containingLoopNode && containingLoopNode.range[0] >= border) { retv = containingLoopNode; containingLoopNode = getContainingLoopNode(containingLoopNode); } return retv; }
[ "function", "getTopLoopNode", "(", "node", ",", "excludedNode", ")", "{", "const", "border", "=", "excludedNode", "?", "excludedNode", ".", "range", "[", "1", "]", ":", "0", ";", "let", "retv", "=", "node", ";", "let", "containingLoopNode", "=", "node", ";", "while", "(", "containingLoopNode", "&&", "containingLoopNode", ".", "range", "[", "0", "]", ">=", "border", ")", "{", "retv", "=", "containingLoopNode", ";", "containingLoopNode", "=", "getContainingLoopNode", "(", "containingLoopNode", ")", ";", "}", "return", "retv", ";", "}" ]
Gets the containing loop node of a given node. If the loop was nested, this returns the most outer loop. @param {ASTNode} node - A node to get. This is a loop node. @param {ASTNode|null} excludedNode - A node that the result node should not include. @returns {ASTNode} The most outer loop node.
[ "Gets", "the", "containing", "loop", "node", "of", "a", "given", "node", ".", "If", "the", "loop", "was", "nested", "this", "returns", "the", "most", "outer", "loop", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-loop-func.js#L72-L83
2,930
eslint/eslint
lib/rules/no-loop-func.js
isSafe
function isSafe(loopNode, reference) { const variable = reference.resolved; const definition = variable && variable.defs[0]; const declaration = definition && definition.parent; const kind = (declaration && declaration.type === "VariableDeclaration") ? declaration.kind : ""; // Variables which are declared by `const` is safe. if (kind === "const") { return true; } /* * Variables which are declared by `let` in the loop is safe. * It's a different instance from the next loop step's. */ if (kind === "let" && declaration.range[0] > loopNode.range[0] && declaration.range[1] < loopNode.range[1] ) { return true; } /* * WriteReferences which exist after this border are unsafe because those * can modify the variable. */ const border = getTopLoopNode( loopNode, (kind === "let") ? declaration : null ).range[0]; /** * Checks whether a given reference is safe or not. * The reference is every reference of the upper scope's variable we are * looking now. * * It's safeafe if the reference matches one of the following condition. * - is readonly. * - doesn't exist inside a local function and after the border. * * @param {eslint-scope.Reference} upperRef - A reference to check. * @returns {boolean} `true` if the reference is safe. */ function isSafeReference(upperRef) { const id = upperRef.identifier; return ( !upperRef.isWrite() || variable.scope.variableScope === upperRef.from.variableScope && id.range[0] < border ); } return Boolean(variable) && variable.references.every(isSafeReference); }
javascript
function isSafe(loopNode, reference) { const variable = reference.resolved; const definition = variable && variable.defs[0]; const declaration = definition && definition.parent; const kind = (declaration && declaration.type === "VariableDeclaration") ? declaration.kind : ""; // Variables which are declared by `const` is safe. if (kind === "const") { return true; } /* * Variables which are declared by `let` in the loop is safe. * It's a different instance from the next loop step's. */ if (kind === "let" && declaration.range[0] > loopNode.range[0] && declaration.range[1] < loopNode.range[1] ) { return true; } /* * WriteReferences which exist after this border are unsafe because those * can modify the variable. */ const border = getTopLoopNode( loopNode, (kind === "let") ? declaration : null ).range[0]; /** * Checks whether a given reference is safe or not. * The reference is every reference of the upper scope's variable we are * looking now. * * It's safeafe if the reference matches one of the following condition. * - is readonly. * - doesn't exist inside a local function and after the border. * * @param {eslint-scope.Reference} upperRef - A reference to check. * @returns {boolean} `true` if the reference is safe. */ function isSafeReference(upperRef) { const id = upperRef.identifier; return ( !upperRef.isWrite() || variable.scope.variableScope === upperRef.from.variableScope && id.range[0] < border ); } return Boolean(variable) && variable.references.every(isSafeReference); }
[ "function", "isSafe", "(", "loopNode", ",", "reference", ")", "{", "const", "variable", "=", "reference", ".", "resolved", ";", "const", "definition", "=", "variable", "&&", "variable", ".", "defs", "[", "0", "]", ";", "const", "declaration", "=", "definition", "&&", "definition", ".", "parent", ";", "const", "kind", "=", "(", "declaration", "&&", "declaration", ".", "type", "===", "\"VariableDeclaration\"", ")", "?", "declaration", ".", "kind", ":", "\"\"", ";", "// Variables which are declared by `const` is safe.", "if", "(", "kind", "===", "\"const\"", ")", "{", "return", "true", ";", "}", "/*\n * Variables which are declared by `let` in the loop is safe.\n * It's a different instance from the next loop step's.\n */", "if", "(", "kind", "===", "\"let\"", "&&", "declaration", ".", "range", "[", "0", "]", ">", "loopNode", ".", "range", "[", "0", "]", "&&", "declaration", ".", "range", "[", "1", "]", "<", "loopNode", ".", "range", "[", "1", "]", ")", "{", "return", "true", ";", "}", "/*\n * WriteReferences which exist after this border are unsafe because those\n * can modify the variable.\n */", "const", "border", "=", "getTopLoopNode", "(", "loopNode", ",", "(", "kind", "===", "\"let\"", ")", "?", "declaration", ":", "null", ")", ".", "range", "[", "0", "]", ";", "/**\n * Checks whether a given reference is safe or not.\n * The reference is every reference of the upper scope's variable we are\n * looking now.\n *\n * It's safeafe if the reference matches one of the following condition.\n * - is readonly.\n * - doesn't exist inside a local function and after the border.\n *\n * @param {eslint-scope.Reference} upperRef - A reference to check.\n * @returns {boolean} `true` if the reference is safe.\n */", "function", "isSafeReference", "(", "upperRef", ")", "{", "const", "id", "=", "upperRef", ".", "identifier", ";", "return", "(", "!", "upperRef", ".", "isWrite", "(", ")", "||", "variable", ".", "scope", ".", "variableScope", "===", "upperRef", ".", "from", ".", "variableScope", "&&", "id", ".", "range", "[", "0", "]", "<", "border", ")", ";", "}", "return", "Boolean", "(", "variable", ")", "&&", "variable", ".", "references", ".", "every", "(", "isSafeReference", ")", ";", "}" ]
Checks whether a given reference which refers to an upper scope's variable is safe or not. @param {ASTNode} loopNode - A containing loop node. @param {eslint-scope.Reference} reference - A reference to check. @returns {boolean} `true` if the reference is safe or not.
[ "Checks", "whether", "a", "given", "reference", "which", "refers", "to", "an", "upper", "scope", "s", "variable", "is", "safe", "or", "not", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-loop-func.js#L93-L149
2,931
eslint/eslint
lib/rules/no-loop-func.js
isSafeReference
function isSafeReference(upperRef) { const id = upperRef.identifier; return ( !upperRef.isWrite() || variable.scope.variableScope === upperRef.from.variableScope && id.range[0] < border ); }
javascript
function isSafeReference(upperRef) { const id = upperRef.identifier; return ( !upperRef.isWrite() || variable.scope.variableScope === upperRef.from.variableScope && id.range[0] < border ); }
[ "function", "isSafeReference", "(", "upperRef", ")", "{", "const", "id", "=", "upperRef", ".", "identifier", ";", "return", "(", "!", "upperRef", ".", "isWrite", "(", ")", "||", "variable", ".", "scope", ".", "variableScope", "===", "upperRef", ".", "from", ".", "variableScope", "&&", "id", ".", "range", "[", "0", "]", "<", "border", ")", ";", "}" ]
Checks whether a given reference is safe or not. The reference is every reference of the upper scope's variable we are looking now. It's safeafe if the reference matches one of the following condition. - is readonly. - doesn't exist inside a local function and after the border. @param {eslint-scope.Reference} upperRef - A reference to check. @returns {boolean} `true` if the reference is safe.
[ "Checks", "whether", "a", "given", "reference", "is", "safe", "or", "not", ".", "The", "reference", "is", "every", "reference", "of", "the", "upper", "scope", "s", "variable", "we", "are", "looking", "now", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-loop-func.js#L138-L146
2,932
eslint/eslint
lib/util/ast-utils.js
getUpperFunction
function getUpperFunction(node) { for (let currentNode = node; currentNode; currentNode = currentNode.parent) { if (anyFunctionPattern.test(currentNode.type)) { return currentNode; } } return null; }
javascript
function getUpperFunction(node) { for (let currentNode = node; currentNode; currentNode = currentNode.parent) { if (anyFunctionPattern.test(currentNode.type)) { return currentNode; } } return null; }
[ "function", "getUpperFunction", "(", "node", ")", "{", "for", "(", "let", "currentNode", "=", "node", ";", "currentNode", ";", "currentNode", "=", "currentNode", ".", "parent", ")", "{", "if", "(", "anyFunctionPattern", ".", "test", "(", "currentNode", ".", "type", ")", ")", "{", "return", "currentNode", ";", "}", "}", "return", "null", ";", "}" ]
Finds a function node from ancestors of a node. @param {ASTNode} node - A start node to find. @returns {Node|null} A found function node.
[ "Finds", "a", "function", "node", "from", "ancestors", "of", "a", "node", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/util/ast-utils.js#L87-L94
2,933
eslint/eslint
lib/util/ast-utils.js
isInLoop
function isInLoop(node) { for (let currentNode = node; currentNode && !isFunction(currentNode); currentNode = currentNode.parent) { if (isLoop(currentNode)) { return true; } } return false; }
javascript
function isInLoop(node) { for (let currentNode = node; currentNode && !isFunction(currentNode); currentNode = currentNode.parent) { if (isLoop(currentNode)) { return true; } } return false; }
[ "function", "isInLoop", "(", "node", ")", "{", "for", "(", "let", "currentNode", "=", "node", ";", "currentNode", "&&", "!", "isFunction", "(", "currentNode", ")", ";", "currentNode", "=", "currentNode", ".", "parent", ")", "{", "if", "(", "isLoop", "(", "currentNode", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Checks whether the given node is in a loop or not. @param {ASTNode} node - The node to check. @returns {boolean} `true` if the node is in a loop.
[ "Checks", "whether", "the", "given", "node", "is", "in", "a", "loop", "or", "not", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/util/ast-utils.js#L134-L142
2,934
eslint/eslint
lib/util/ast-utils.js
isMethodWhichHasThisArg
function isMethodWhichHasThisArg(node) { for ( let currentNode = node; currentNode.type === "MemberExpression" && !currentNode.computed; currentNode = currentNode.property ) { if (currentNode.property.type === "Identifier") { return arrayMethodPattern.test(currentNode.property.name); } } return false; }
javascript
function isMethodWhichHasThisArg(node) { for ( let currentNode = node; currentNode.type === "MemberExpression" && !currentNode.computed; currentNode = currentNode.property ) { if (currentNode.property.type === "Identifier") { return arrayMethodPattern.test(currentNode.property.name); } } return false; }
[ "function", "isMethodWhichHasThisArg", "(", "node", ")", "{", "for", "(", "let", "currentNode", "=", "node", ";", "currentNode", ".", "type", "===", "\"MemberExpression\"", "&&", "!", "currentNode", ".", "computed", ";", "currentNode", "=", "currentNode", ".", "property", ")", "{", "if", "(", "currentNode", ".", "property", ".", "type", "===", "\"Identifier\"", ")", "{", "return", "arrayMethodPattern", ".", "test", "(", "currentNode", ".", "property", ".", "name", ")", ";", "}", "}", "return", "false", ";", "}" ]
Checks whether or not a node is a method which has `thisArg`. @param {ASTNode} node - A node to check. @returns {boolean} Whether or not the node is a method which has `thisArg`.
[ "Checks", "whether", "or", "not", "a", "node", "is", "a", "method", "which", "has", "thisArg", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/util/ast-utils.js#L204-L216
2,935
eslint/eslint
lib/util/ast-utils.js
getOpeningParenOfParams
function getOpeningParenOfParams(node, sourceCode) { return node.id ? sourceCode.getTokenAfter(node.id, isOpeningParenToken) : sourceCode.getFirstToken(node, isOpeningParenToken); }
javascript
function getOpeningParenOfParams(node, sourceCode) { return node.id ? sourceCode.getTokenAfter(node.id, isOpeningParenToken) : sourceCode.getFirstToken(node, isOpeningParenToken); }
[ "function", "getOpeningParenOfParams", "(", "node", ",", "sourceCode", ")", "{", "return", "node", ".", "id", "?", "sourceCode", ".", "getTokenAfter", "(", "node", ".", "id", ",", "isOpeningParenToken", ")", ":", "sourceCode", ".", "getFirstToken", "(", "node", ",", "isOpeningParenToken", ")", ";", "}" ]
Gets the `(` token of the given function node. @param {ASTNode} node - The function node to get. @param {SourceCode} sourceCode - The source code object to get tokens. @returns {Token} `(` token.
[ "Gets", "the", "(", "token", "of", "the", "given", "function", "node", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/util/ast-utils.js#L390-L394
2,936
eslint/eslint
lib/util/ast-utils.js
equalTokens
function equalTokens(left, right, sourceCode) { const tokensL = sourceCode.getTokens(left); const tokensR = sourceCode.getTokens(right); if (tokensL.length !== tokensR.length) { return false; } for (let i = 0; i < tokensL.length; ++i) { if (tokensL[i].type !== tokensR[i].type || tokensL[i].value !== tokensR[i].value ) { return false; } } return true; }
javascript
function equalTokens(left, right, sourceCode) { const tokensL = sourceCode.getTokens(left); const tokensR = sourceCode.getTokens(right); if (tokensL.length !== tokensR.length) { return false; } for (let i = 0; i < tokensL.length; ++i) { if (tokensL[i].type !== tokensR[i].type || tokensL[i].value !== tokensR[i].value ) { return false; } } return true; }
[ "function", "equalTokens", "(", "left", ",", "right", ",", "sourceCode", ")", "{", "const", "tokensL", "=", "sourceCode", ".", "getTokens", "(", "left", ")", ";", "const", "tokensR", "=", "sourceCode", ".", "getTokens", "(", "right", ")", ";", "if", "(", "tokensL", ".", "length", "!==", "tokensR", ".", "length", ")", "{", "return", "false", ";", "}", "for", "(", "let", "i", "=", "0", ";", "i", "<", "tokensL", ".", "length", ";", "++", "i", ")", "{", "if", "(", "tokensL", "[", "i", "]", ".", "type", "!==", "tokensR", "[", "i", "]", ".", "type", "||", "tokensL", "[", "i", "]", ".", "value", "!==", "tokensR", "[", "i", "]", ".", "value", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Checks whether or not the tokens of two given nodes are same. @param {ASTNode} left - A node 1 to compare. @param {ASTNode} right - A node 2 to compare. @param {SourceCode} sourceCode - The ESLint source code object. @returns {boolean} the source code for the given node.
[ "Checks", "whether", "or", "not", "the", "tokens", "of", "two", "given", "nodes", "are", "same", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/util/ast-utils.js#L412-L428
2,937
eslint/eslint
lib/config/config-rule.js
combineArrays
function combineArrays(arr1, arr2) { const res = []; if (arr1.length === 0) { return explodeArray(arr2); } if (arr2.length === 0) { return explodeArray(arr1); } arr1.forEach(x1 => { arr2.forEach(x2 => { res.push([].concat(x1, x2)); }); }); return res; }
javascript
function combineArrays(arr1, arr2) { const res = []; if (arr1.length === 0) { return explodeArray(arr2); } if (arr2.length === 0) { return explodeArray(arr1); } arr1.forEach(x1 => { arr2.forEach(x2 => { res.push([].concat(x1, x2)); }); }); return res; }
[ "function", "combineArrays", "(", "arr1", ",", "arr2", ")", "{", "const", "res", "=", "[", "]", ";", "if", "(", "arr1", ".", "length", "===", "0", ")", "{", "return", "explodeArray", "(", "arr2", ")", ";", "}", "if", "(", "arr2", ".", "length", "===", "0", ")", "{", "return", "explodeArray", "(", "arr1", ")", ";", "}", "arr1", ".", "forEach", "(", "x1", "=>", "{", "arr2", ".", "forEach", "(", "x2", "=>", "{", "res", ".", "push", "(", "[", "]", ".", "concat", "(", "x1", ",", "x2", ")", ")", ";", "}", ")", ";", "}", ")", ";", "return", "res", ";", "}" ]
Mix two arrays such that each element of the second array is concatenated onto each element of the first array. For example: combineArrays([a, [b, c]], [x, y]); // -> [[a, x], [a, y], [b, c, x], [b, c, y]] @param {Array} arr1 The first array to combine. @param {Array} arr2 The second array to combine. @returns {Array} A mixture of the elements of the first and second arrays.
[ "Mix", "two", "arrays", "such", "that", "each", "element", "of", "the", "second", "array", "is", "concatenated", "onto", "each", "element", "of", "the", "first", "array", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/config/config-rule.js#L44-L59
2,938
eslint/eslint
lib/config/config-rule.js
groupByProperty
function groupByProperty(objects) { const groupedObj = objects.reduce((accumulator, obj) => { const prop = Object.keys(obj)[0]; accumulator[prop] = accumulator[prop] ? accumulator[prop].concat(obj) : [obj]; return accumulator; }, {}); return Object.keys(groupedObj).map(prop => groupedObj[prop]); }
javascript
function groupByProperty(objects) { const groupedObj = objects.reduce((accumulator, obj) => { const prop = Object.keys(obj)[0]; accumulator[prop] = accumulator[prop] ? accumulator[prop].concat(obj) : [obj]; return accumulator; }, {}); return Object.keys(groupedObj).map(prop => groupedObj[prop]); }
[ "function", "groupByProperty", "(", "objects", ")", "{", "const", "groupedObj", "=", "objects", ".", "reduce", "(", "(", "accumulator", ",", "obj", ")", "=>", "{", "const", "prop", "=", "Object", ".", "keys", "(", "obj", ")", "[", "0", "]", ";", "accumulator", "[", "prop", "]", "=", "accumulator", "[", "prop", "]", "?", "accumulator", "[", "prop", "]", ".", "concat", "(", "obj", ")", ":", "[", "obj", "]", ";", "return", "accumulator", ";", "}", ",", "{", "}", ")", ";", "return", "Object", ".", "keys", "(", "groupedObj", ")", ".", "map", "(", "prop", "=>", "groupedObj", "[", "prop", "]", ")", ";", "}" ]
Group together valid rule configurations based on object properties e.g.: groupByProperty([ {before: true}, {before: false}, {after: true}, {after: false} ]); will return: [ [{before: true}, {before: false}], [{after: true}, {after: false}] ] @param {Object[]} objects Array of objects, each with one property/value pair @returns {Array[]} Array of arrays of objects grouped by property
[ "Group", "together", "valid", "rule", "configurations", "based", "on", "object", "properties" ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/config/config-rule.js#L81-L90
2,939
eslint/eslint
lib/config/config-rule.js
generateConfigsFromSchema
function generateConfigsFromSchema(schema) { const configSet = new RuleConfigSet(); if (Array.isArray(schema)) { for (const opt of schema) { if (opt.enum) { configSet.addEnums(opt.enum); } else if (opt.type && opt.type === "object") { if (!configSet.addObject(opt)) { break; } // TODO (IanVS): support oneOf } else { // If we don't know how to fill in this option, don't fill in any of the following options. break; } } } configSet.addErrorSeverity(); return configSet.ruleConfigs; }
javascript
function generateConfigsFromSchema(schema) { const configSet = new RuleConfigSet(); if (Array.isArray(schema)) { for (const opt of schema) { if (opt.enum) { configSet.addEnums(opt.enum); } else if (opt.type && opt.type === "object") { if (!configSet.addObject(opt)) { break; } // TODO (IanVS): support oneOf } else { // If we don't know how to fill in this option, don't fill in any of the following options. break; } } } configSet.addErrorSeverity(); return configSet.ruleConfigs; }
[ "function", "generateConfigsFromSchema", "(", "schema", ")", "{", "const", "configSet", "=", "new", "RuleConfigSet", "(", ")", ";", "if", "(", "Array", ".", "isArray", "(", "schema", ")", ")", "{", "for", "(", "const", "opt", "of", "schema", ")", "{", "if", "(", "opt", ".", "enum", ")", "{", "configSet", ".", "addEnums", "(", "opt", ".", "enum", ")", ";", "}", "else", "if", "(", "opt", ".", "type", "&&", "opt", ".", "type", "===", "\"object\"", ")", "{", "if", "(", "!", "configSet", ".", "addObject", "(", "opt", ")", ")", "{", "break", ";", "}", "// TODO (IanVS): support oneOf", "}", "else", "{", "// If we don't know how to fill in this option, don't fill in any of the following options.", "break", ";", "}", "}", "}", "configSet", ".", "addErrorSeverity", "(", ")", ";", "return", "configSet", ".", "ruleConfigs", ";", "}" ]
Generate valid rule configurations based on a schema object @param {Object} schema A rule's schema object @returns {Array[]} Valid rule configurations
[ "Generate", "valid", "rule", "configurations", "based", "on", "a", "schema", "object" ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/config/config-rule.js#L273-L295
2,940
eslint/eslint
lib/config/config-rule.js
createCoreRuleConfigs
function createCoreRuleConfigs() { return Object.keys(builtInRules).reduce((accumulator, id) => { const rule = rules.get(id); const schema = (typeof rule === "function") ? rule.schema : rule.meta.schema; accumulator[id] = generateConfigsFromSchema(schema); return accumulator; }, {}); }
javascript
function createCoreRuleConfigs() { return Object.keys(builtInRules).reduce((accumulator, id) => { const rule = rules.get(id); const schema = (typeof rule === "function") ? rule.schema : rule.meta.schema; accumulator[id] = generateConfigsFromSchema(schema); return accumulator; }, {}); }
[ "function", "createCoreRuleConfigs", "(", ")", "{", "return", "Object", ".", "keys", "(", "builtInRules", ")", ".", "reduce", "(", "(", "accumulator", ",", "id", ")", "=>", "{", "const", "rule", "=", "rules", ".", "get", "(", "id", ")", ";", "const", "schema", "=", "(", "typeof", "rule", "===", "\"function\"", ")", "?", "rule", ".", "schema", ":", "rule", ".", "meta", ".", "schema", ";", "accumulator", "[", "id", "]", "=", "generateConfigsFromSchema", "(", "schema", ")", ";", "return", "accumulator", ";", "}", ",", "{", "}", ")", ";", "}" ]
Generate possible rule configurations for all of the core rules @returns {rulesConfig} Hash of rule names and arrays of possible configurations
[ "Generate", "possible", "rule", "configurations", "for", "all", "of", "the", "core", "rules" ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/config/config-rule.js#L301-L309
2,941
eslint/eslint
lib/rules/no-inner-declarations.js
nearestBody
function nearestBody() { const ancestors = context.getAncestors(); let ancestor = ancestors.pop(), generation = 1; while (ancestor && ["Program", "FunctionDeclaration", "FunctionExpression", "ArrowFunctionExpression" ].indexOf(ancestor.type) < 0) { generation += 1; ancestor = ancestors.pop(); } return { // Type of containing ancestor type: ancestor.type, // Separation between ancestor and node distance: generation }; }
javascript
function nearestBody() { const ancestors = context.getAncestors(); let ancestor = ancestors.pop(), generation = 1; while (ancestor && ["Program", "FunctionDeclaration", "FunctionExpression", "ArrowFunctionExpression" ].indexOf(ancestor.type) < 0) { generation += 1; ancestor = ancestors.pop(); } return { // Type of containing ancestor type: ancestor.type, // Separation between ancestor and node distance: generation }; }
[ "function", "nearestBody", "(", ")", "{", "const", "ancestors", "=", "context", ".", "getAncestors", "(", ")", ";", "let", "ancestor", "=", "ancestors", ".", "pop", "(", ")", ",", "generation", "=", "1", ";", "while", "(", "ancestor", "&&", "[", "\"Program\"", ",", "\"FunctionDeclaration\"", ",", "\"FunctionExpression\"", ",", "\"ArrowFunctionExpression\"", "]", ".", "indexOf", "(", "ancestor", ".", "type", ")", "<", "0", ")", "{", "generation", "+=", "1", ";", "ancestor", "=", "ancestors", ".", "pop", "(", ")", ";", "}", "return", "{", "// Type of containing ancestor", "type", ":", "ancestor", ".", "type", ",", "// Separation between ancestor and node", "distance", ":", "generation", "}", ";", "}" ]
Find the nearest Program or Function ancestor node. @returns {Object} Ancestor's type and distance from node.
[ "Find", "the", "nearest", "Program", "or", "Function", "ancestor", "node", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-inner-declarations.js#L36-L56
2,942
eslint/eslint
lib/rules/no-inner-declarations.js
check
function check(node) { const body = nearestBody(), valid = ((body.type === "Program" && body.distance === 1) || body.distance === 2); if (!valid) { context.report({ node, message: "Move {{type}} declaration to {{body}} root.", data: { type: (node.type === "FunctionDeclaration" ? "function" : "variable"), body: (body.type === "Program" ? "program" : "function body") } }); } }
javascript
function check(node) { const body = nearestBody(), valid = ((body.type === "Program" && body.distance === 1) || body.distance === 2); if (!valid) { context.report({ node, message: "Move {{type}} declaration to {{body}} root.", data: { type: (node.type === "FunctionDeclaration" ? "function" : "variable"), body: (body.type === "Program" ? "program" : "function body") } }); } }
[ "function", "check", "(", "node", ")", "{", "const", "body", "=", "nearestBody", "(", ")", ",", "valid", "=", "(", "(", "body", ".", "type", "===", "\"Program\"", "&&", "body", ".", "distance", "===", "1", ")", "||", "body", ".", "distance", "===", "2", ")", ";", "if", "(", "!", "valid", ")", "{", "context", ".", "report", "(", "{", "node", ",", "message", ":", "\"Move {{type}} declaration to {{body}} root.\"", ",", "data", ":", "{", "type", ":", "(", "node", ".", "type", "===", "\"FunctionDeclaration\"", "?", "\"function\"", ":", "\"variable\"", ")", ",", "body", ":", "(", "body", ".", "type", "===", "\"Program\"", "?", "\"program\"", ":", "\"function body\"", ")", "}", "}", ")", ";", "}", "}" ]
Ensure that a given node is at a program or function body's root. @param {ASTNode} node Declaration node to check. @returns {void}
[ "Ensure", "that", "a", "given", "node", "is", "at", "a", "program", "or", "function", "body", "s", "root", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-inner-declarations.js#L63-L78
2,943
eslint/eslint
lib/rules/max-statements.js
reportIfTooManyStatements
function reportIfTooManyStatements(node, count, max) { if (count > max) { const name = lodash.upperFirst(astUtils.getFunctionNameWithKind(node)); context.report({ node, messageId: "exceed", data: { name, count, max } }); } }
javascript
function reportIfTooManyStatements(node, count, max) { if (count > max) { const name = lodash.upperFirst(astUtils.getFunctionNameWithKind(node)); context.report({ node, messageId: "exceed", data: { name, count, max } }); } }
[ "function", "reportIfTooManyStatements", "(", "node", ",", "count", ",", "max", ")", "{", "if", "(", "count", ">", "max", ")", "{", "const", "name", "=", "lodash", ".", "upperFirst", "(", "astUtils", ".", "getFunctionNameWithKind", "(", "node", ")", ")", ";", "context", ".", "report", "(", "{", "node", ",", "messageId", ":", "\"exceed\"", ",", "data", ":", "{", "name", ",", "count", ",", "max", "}", "}", ")", ";", "}", "}" ]
Reports a node if it has too many statements @param {ASTNode} node node to evaluate @param {int} count Number of statements in node @param {int} max Maximum number of statements allowed @returns {void} @private
[ "Reports", "a", "node", "if", "it", "has", "too", "many", "statements" ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/max-statements.js#L98-L108
2,944
eslint/eslint
lib/rules/max-statements.js
endFunction
function endFunction(node) { const count = functionStack.pop(); if (ignoreTopLevelFunctions && functionStack.length === 0) { topLevelFunctions.push({ node, count }); } else { reportIfTooManyStatements(node, count, maxStatements); } }
javascript
function endFunction(node) { const count = functionStack.pop(); if (ignoreTopLevelFunctions && functionStack.length === 0) { topLevelFunctions.push({ node, count }); } else { reportIfTooManyStatements(node, count, maxStatements); } }
[ "function", "endFunction", "(", "node", ")", "{", "const", "count", "=", "functionStack", ".", "pop", "(", ")", ";", "if", "(", "ignoreTopLevelFunctions", "&&", "functionStack", ".", "length", "===", "0", ")", "{", "topLevelFunctions", ".", "push", "(", "{", "node", ",", "count", "}", ")", ";", "}", "else", "{", "reportIfTooManyStatements", "(", "node", ",", "count", ",", "maxStatements", ")", ";", "}", "}" ]
Evaluate the node at the end of function @param {ASTNode} node node to evaluate @returns {void} @private
[ "Evaluate", "the", "node", "at", "the", "end", "of", "function" ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/max-statements.js#L125-L133
2,945
eslint/eslint
lib/rules/array-element-newline.js
reportNoLineBreak
function reportNoLineBreak(token) { const tokenBefore = sourceCode.getTokenBefore(token, { includeComments: true }); context.report({ loc: { start: tokenBefore.loc.end, end: token.loc.start }, messageId: "unexpectedLineBreak", fix(fixer) { if (astUtils.isCommentToken(tokenBefore)) { return null; } if (!astUtils.isTokenOnSameLine(tokenBefore, token)) { return fixer.replaceTextRange([tokenBefore.range[1], token.range[0]], " "); } /* * This will check if the comma is on the same line as the next element * Following array: * [ * 1 * , 2 * , 3 * ] * * will be fixed to: * [ * 1, 2, 3 * ] */ const twoTokensBefore = sourceCode.getTokenBefore(tokenBefore, { includeComments: true }); if (astUtils.isCommentToken(twoTokensBefore)) { return null; } return fixer.replaceTextRange([twoTokensBefore.range[1], tokenBefore.range[0]], ""); } }); }
javascript
function reportNoLineBreak(token) { const tokenBefore = sourceCode.getTokenBefore(token, { includeComments: true }); context.report({ loc: { start: tokenBefore.loc.end, end: token.loc.start }, messageId: "unexpectedLineBreak", fix(fixer) { if (astUtils.isCommentToken(tokenBefore)) { return null; } if (!astUtils.isTokenOnSameLine(tokenBefore, token)) { return fixer.replaceTextRange([tokenBefore.range[1], token.range[0]], " "); } /* * This will check if the comma is on the same line as the next element * Following array: * [ * 1 * , 2 * , 3 * ] * * will be fixed to: * [ * 1, 2, 3 * ] */ const twoTokensBefore = sourceCode.getTokenBefore(tokenBefore, { includeComments: true }); if (astUtils.isCommentToken(twoTokensBefore)) { return null; } return fixer.replaceTextRange([twoTokensBefore.range[1], tokenBefore.range[0]], ""); } }); }
[ "function", "reportNoLineBreak", "(", "token", ")", "{", "const", "tokenBefore", "=", "sourceCode", ".", "getTokenBefore", "(", "token", ",", "{", "includeComments", ":", "true", "}", ")", ";", "context", ".", "report", "(", "{", "loc", ":", "{", "start", ":", "tokenBefore", ".", "loc", ".", "end", ",", "end", ":", "token", ".", "loc", ".", "start", "}", ",", "messageId", ":", "\"unexpectedLineBreak\"", ",", "fix", "(", "fixer", ")", "{", "if", "(", "astUtils", ".", "isCommentToken", "(", "tokenBefore", ")", ")", "{", "return", "null", ";", "}", "if", "(", "!", "astUtils", ".", "isTokenOnSameLine", "(", "tokenBefore", ",", "token", ")", ")", "{", "return", "fixer", ".", "replaceTextRange", "(", "[", "tokenBefore", ".", "range", "[", "1", "]", ",", "token", ".", "range", "[", "0", "]", "]", ",", "\" \"", ")", ";", "}", "/*\n * This will check if the comma is on the same line as the next element\n * Following array:\n * [\n * 1\n * , 2\n * , 3\n * ]\n *\n * will be fixed to:\n * [\n * 1, 2, 3\n * ]\n */", "const", "twoTokensBefore", "=", "sourceCode", ".", "getTokenBefore", "(", "tokenBefore", ",", "{", "includeComments", ":", "true", "}", ")", ";", "if", "(", "astUtils", ".", "isCommentToken", "(", "twoTokensBefore", ")", ")", "{", "return", "null", ";", "}", "return", "fixer", ".", "replaceTextRange", "(", "[", "twoTokensBefore", ".", "range", "[", "1", "]", ",", "tokenBefore", ".", "range", "[", "0", "]", "]", ",", "\"\"", ")", ";", "}", "}", ")", ";", "}" ]
Reports that there shouldn't be a line break after the first token @param {Token} token - The token to use for the report. @returns {void}
[ "Reports", "that", "there", "shouldn", "t", "be", "a", "line", "break", "after", "the", "first", "token" ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/array-element-newline.js#L108-L150
2,946
eslint/eslint
lib/rules/array-element-newline.js
reportRequiredLineBreak
function reportRequiredLineBreak(token) { const tokenBefore = sourceCode.getTokenBefore(token, { includeComments: true }); context.report({ loc: { start: tokenBefore.loc.end, end: token.loc.start }, messageId: "missingLineBreak", fix(fixer) { return fixer.replaceTextRange([tokenBefore.range[1], token.range[0]], "\n"); } }); }
javascript
function reportRequiredLineBreak(token) { const tokenBefore = sourceCode.getTokenBefore(token, { includeComments: true }); context.report({ loc: { start: tokenBefore.loc.end, end: token.loc.start }, messageId: "missingLineBreak", fix(fixer) { return fixer.replaceTextRange([tokenBefore.range[1], token.range[0]], "\n"); } }); }
[ "function", "reportRequiredLineBreak", "(", "token", ")", "{", "const", "tokenBefore", "=", "sourceCode", ".", "getTokenBefore", "(", "token", ",", "{", "includeComments", ":", "true", "}", ")", ";", "context", ".", "report", "(", "{", "loc", ":", "{", "start", ":", "tokenBefore", ".", "loc", ".", "end", ",", "end", ":", "token", ".", "loc", ".", "start", "}", ",", "messageId", ":", "\"missingLineBreak\"", ",", "fix", "(", "fixer", ")", "{", "return", "fixer", ".", "replaceTextRange", "(", "[", "tokenBefore", ".", "range", "[", "1", "]", ",", "token", ".", "range", "[", "0", "]", "]", ",", "\"\\n\"", ")", ";", "}", "}", ")", ";", "}" ]
Reports that there should be a line break after the first token @param {Token} token - The token to use for the report. @returns {void}
[ "Reports", "that", "there", "should", "be", "a", "line", "break", "after", "the", "first", "token" ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/array-element-newline.js#L157-L170
2,947
eslint/eslint
lib/rules/no-duplicate-imports.js
checkAndReport
function checkAndReport(context, node, value, array, messageId) { if (array.indexOf(value) !== -1) { context.report({ node, messageId, data: { module: value } }); } }
javascript
function checkAndReport(context, node, value, array, messageId) { if (array.indexOf(value) !== -1) { context.report({ node, messageId, data: { module: value } }); } }
[ "function", "checkAndReport", "(", "context", ",", "node", ",", "value", ",", "array", ",", "messageId", ")", "{", "if", "(", "array", ".", "indexOf", "(", "value", ")", "!==", "-", "1", ")", "{", "context", ".", "report", "(", "{", "node", ",", "messageId", ",", "data", ":", "{", "module", ":", "value", "}", "}", ")", ";", "}", "}" ]
Checks if the name of the import or export exists in the given array, and reports if so. @param {RuleContext} context - The ESLint rule context object. @param {ASTNode} node - A node to get. @param {string} value - The name of the imported or exported module. @param {string[]} array - The array containing other imports or exports in the file. @param {string} messageId - A messageId to be reported after the name of the module @returns {void} No return value
[ "Checks", "if", "the", "name", "of", "the", "import", "or", "export", "exists", "in", "the", "given", "array", "and", "reports", "if", "so", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-duplicate-imports.js#L36-L46
2,948
eslint/eslint
lib/rules/lines-around-directive.js
getLastTokenOnLine
function getLastTokenOnLine(node) { const lastToken = sourceCode.getLastToken(node); const secondToLastToken = sourceCode.getTokenBefore(lastToken); return astUtils.isSemicolonToken(lastToken) && lastToken.loc.start.line > secondToLastToken.loc.end.line ? secondToLastToken : lastToken; }
javascript
function getLastTokenOnLine(node) { const lastToken = sourceCode.getLastToken(node); const secondToLastToken = sourceCode.getTokenBefore(lastToken); return astUtils.isSemicolonToken(lastToken) && lastToken.loc.start.line > secondToLastToken.loc.end.line ? secondToLastToken : lastToken; }
[ "function", "getLastTokenOnLine", "(", "node", ")", "{", "const", "lastToken", "=", "sourceCode", ".", "getLastToken", "(", "node", ")", ";", "const", "secondToLastToken", "=", "sourceCode", ".", "getTokenBefore", "(", "lastToken", ")", ";", "return", "astUtils", ".", "isSemicolonToken", "(", "lastToken", ")", "&&", "lastToken", ".", "loc", ".", "start", ".", "line", ">", "secondToLastToken", ".", "loc", ".", "end", ".", "line", "?", "secondToLastToken", ":", "lastToken", ";", "}" ]
Gets the last token of a node that is on the same line as the rest of the node. This will usually be the last token of the node, but it will be the second-to-last token if the node has a trailing semicolon on a different line. @param {ASTNode} node A directive node @returns {Token} The last token of the node on the line
[ "Gets", "the", "last", "token", "of", "a", "node", "that", "is", "on", "the", "same", "line", "as", "the", "rest", "of", "the", "node", ".", "This", "will", "usually", "be", "the", "last", "token", "of", "the", "node", "but", "it", "will", "be", "the", "second", "-", "to", "-", "last", "token", "if", "the", "node", "has", "a", "trailing", "semicolon", "on", "a", "different", "line", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/lines-around-directive.js#L85-L92
2,949
eslint/eslint
lib/rules/lines-around-directive.js
hasNewlineAfter
function hasNewlineAfter(node) { const lastToken = getLastTokenOnLine(node); const tokenAfter = sourceCode.getTokenAfter(lastToken, { includeComments: true }); return tokenAfter.loc.start.line - lastToken.loc.end.line >= 2; }
javascript
function hasNewlineAfter(node) { const lastToken = getLastTokenOnLine(node); const tokenAfter = sourceCode.getTokenAfter(lastToken, { includeComments: true }); return tokenAfter.loc.start.line - lastToken.loc.end.line >= 2; }
[ "function", "hasNewlineAfter", "(", "node", ")", "{", "const", "lastToken", "=", "getLastTokenOnLine", "(", "node", ")", ";", "const", "tokenAfter", "=", "sourceCode", ".", "getTokenAfter", "(", "lastToken", ",", "{", "includeComments", ":", "true", "}", ")", ";", "return", "tokenAfter", ".", "loc", ".", "start", ".", "line", "-", "lastToken", ".", "loc", ".", "end", ".", "line", ">=", "2", ";", "}" ]
Check if node is followed by a blank newline. @param {ASTNode} node Node to check. @returns {boolean} Whether or not the passed in node is followed by a blank newline.
[ "Check", "if", "node", "is", "followed", "by", "a", "blank", "newline", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/lines-around-directive.js#L99-L104
2,950
eslint/eslint
lib/rules/lines-around-directive.js
reportError
function reportError(node, location, expected) { context.report({ node, messageId: expected ? "expected" : "unexpected", data: { value: node.expression.value, location }, fix(fixer) { const lastToken = getLastTokenOnLine(node); if (expected) { return location === "before" ? fixer.insertTextBefore(node, "\n") : fixer.insertTextAfter(lastToken, "\n"); } return fixer.removeRange(location === "before" ? [node.range[0] - 1, node.range[0]] : [lastToken.range[1], lastToken.range[1] + 1]); } }); }
javascript
function reportError(node, location, expected) { context.report({ node, messageId: expected ? "expected" : "unexpected", data: { value: node.expression.value, location }, fix(fixer) { const lastToken = getLastTokenOnLine(node); if (expected) { return location === "before" ? fixer.insertTextBefore(node, "\n") : fixer.insertTextAfter(lastToken, "\n"); } return fixer.removeRange(location === "before" ? [node.range[0] - 1, node.range[0]] : [lastToken.range[1], lastToken.range[1] + 1]); } }); }
[ "function", "reportError", "(", "node", ",", "location", ",", "expected", ")", "{", "context", ".", "report", "(", "{", "node", ",", "messageId", ":", "expected", "?", "\"expected\"", ":", "\"unexpected\"", ",", "data", ":", "{", "value", ":", "node", ".", "expression", ".", "value", ",", "location", "}", ",", "fix", "(", "fixer", ")", "{", "const", "lastToken", "=", "getLastTokenOnLine", "(", "node", ")", ";", "if", "(", "expected", ")", "{", "return", "location", "===", "\"before\"", "?", "fixer", ".", "insertTextBefore", "(", "node", ",", "\"\\n\"", ")", ":", "fixer", ".", "insertTextAfter", "(", "lastToken", ",", "\"\\n\"", ")", ";", "}", "return", "fixer", ".", "removeRange", "(", "location", "===", "\"before\"", "?", "[", "node", ".", "range", "[", "0", "]", "-", "1", ",", "node", ".", "range", "[", "0", "]", "]", ":", "[", "lastToken", ".", "range", "[", "1", "]", ",", "lastToken", ".", "range", "[", "1", "]", "+", "1", "]", ")", ";", "}", "}", ")", ";", "}" ]
Report errors for newlines around directives. @param {ASTNode} node Node to check. @param {string} location Whether the error was found before or after the directive. @param {boolean} expected Whether or not a newline was expected or unexpected. @returns {void}
[ "Report", "errors", "for", "newlines", "around", "directives", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/lines-around-directive.js#L113-L130
2,951
eslint/eslint
lib/rules/lines-around-directive.js
checkDirectives
function checkDirectives(node) { const directives = astUtils.getDirectivePrologue(node); if (!directives.length) { return; } const firstDirective = directives[0]; const leadingComments = sourceCode.getCommentsBefore(firstDirective); /* * Only check before the first directive if it is preceded by a comment or if it is at the top of * the file and expectLineBefore is set to "never". This is to not force a newline at the top of * the file if there are no comments as well as for compatibility with padded-blocks. */ if (leadingComments.length) { if (expectLineBefore === "always" && !hasNewlineBefore(firstDirective)) { reportError(firstDirective, "before", true); } if (expectLineBefore === "never" && hasNewlineBefore(firstDirective)) { reportError(firstDirective, "before", false); } } else if ( node.type === "Program" && expectLineBefore === "never" && !leadingComments.length && hasNewlineBefore(firstDirective) ) { reportError(firstDirective, "before", false); } const lastDirective = directives[directives.length - 1]; const statements = node.type === "Program" ? node.body : node.body.body; /* * Do not check after the last directive if the body only * contains a directive prologue and isn't followed by a comment to ensure * this rule behaves well with padded-blocks. */ if (lastDirective === statements[statements.length - 1] && !lastDirective.trailingComments) { return; } if (expectLineAfter === "always" && !hasNewlineAfter(lastDirective)) { reportError(lastDirective, "after", true); } if (expectLineAfter === "never" && hasNewlineAfter(lastDirective)) { reportError(lastDirective, "after", false); } }
javascript
function checkDirectives(node) { const directives = astUtils.getDirectivePrologue(node); if (!directives.length) { return; } const firstDirective = directives[0]; const leadingComments = sourceCode.getCommentsBefore(firstDirective); /* * Only check before the first directive if it is preceded by a comment or if it is at the top of * the file and expectLineBefore is set to "never". This is to not force a newline at the top of * the file if there are no comments as well as for compatibility with padded-blocks. */ if (leadingComments.length) { if (expectLineBefore === "always" && !hasNewlineBefore(firstDirective)) { reportError(firstDirective, "before", true); } if (expectLineBefore === "never" && hasNewlineBefore(firstDirective)) { reportError(firstDirective, "before", false); } } else if ( node.type === "Program" && expectLineBefore === "never" && !leadingComments.length && hasNewlineBefore(firstDirective) ) { reportError(firstDirective, "before", false); } const lastDirective = directives[directives.length - 1]; const statements = node.type === "Program" ? node.body : node.body.body; /* * Do not check after the last directive if the body only * contains a directive prologue and isn't followed by a comment to ensure * this rule behaves well with padded-blocks. */ if (lastDirective === statements[statements.length - 1] && !lastDirective.trailingComments) { return; } if (expectLineAfter === "always" && !hasNewlineAfter(lastDirective)) { reportError(lastDirective, "after", true); } if (expectLineAfter === "never" && hasNewlineAfter(lastDirective)) { reportError(lastDirective, "after", false); } }
[ "function", "checkDirectives", "(", "node", ")", "{", "const", "directives", "=", "astUtils", ".", "getDirectivePrologue", "(", "node", ")", ";", "if", "(", "!", "directives", ".", "length", ")", "{", "return", ";", "}", "const", "firstDirective", "=", "directives", "[", "0", "]", ";", "const", "leadingComments", "=", "sourceCode", ".", "getCommentsBefore", "(", "firstDirective", ")", ";", "/*\n * Only check before the first directive if it is preceded by a comment or if it is at the top of\n * the file and expectLineBefore is set to \"never\". This is to not force a newline at the top of\n * the file if there are no comments as well as for compatibility with padded-blocks.\n */", "if", "(", "leadingComments", ".", "length", ")", "{", "if", "(", "expectLineBefore", "===", "\"always\"", "&&", "!", "hasNewlineBefore", "(", "firstDirective", ")", ")", "{", "reportError", "(", "firstDirective", ",", "\"before\"", ",", "true", ")", ";", "}", "if", "(", "expectLineBefore", "===", "\"never\"", "&&", "hasNewlineBefore", "(", "firstDirective", ")", ")", "{", "reportError", "(", "firstDirective", ",", "\"before\"", ",", "false", ")", ";", "}", "}", "else", "if", "(", "node", ".", "type", "===", "\"Program\"", "&&", "expectLineBefore", "===", "\"never\"", "&&", "!", "leadingComments", ".", "length", "&&", "hasNewlineBefore", "(", "firstDirective", ")", ")", "{", "reportError", "(", "firstDirective", ",", "\"before\"", ",", "false", ")", ";", "}", "const", "lastDirective", "=", "directives", "[", "directives", ".", "length", "-", "1", "]", ";", "const", "statements", "=", "node", ".", "type", "===", "\"Program\"", "?", "node", ".", "body", ":", "node", ".", "body", ".", "body", ";", "/*\n * Do not check after the last directive if the body only\n * contains a directive prologue and isn't followed by a comment to ensure\n * this rule behaves well with padded-blocks.\n */", "if", "(", "lastDirective", "===", "statements", "[", "statements", ".", "length", "-", "1", "]", "&&", "!", "lastDirective", ".", "trailingComments", ")", "{", "return", ";", "}", "if", "(", "expectLineAfter", "===", "\"always\"", "&&", "!", "hasNewlineAfter", "(", "lastDirective", ")", ")", "{", "reportError", "(", "lastDirective", ",", "\"after\"", ",", "true", ")", ";", "}", "if", "(", "expectLineAfter", "===", "\"never\"", "&&", "hasNewlineAfter", "(", "lastDirective", ")", ")", "{", "reportError", "(", "lastDirective", ",", "\"after\"", ",", "false", ")", ";", "}", "}" ]
Check lines around directives in node @param {ASTNode} node - node to check @returns {void}
[ "Check", "lines", "around", "directives", "in", "node" ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/lines-around-directive.js#L137-L188
2,952
eslint/eslint
lib/rules/no-await-in-loop.js
isBoundary
function isBoundary(node) { const t = node.type; return ( t === "FunctionDeclaration" || t === "FunctionExpression" || t === "ArrowFunctionExpression" || /* * Don't report the await expressions on for-await-of loop since it's * asynchronous iteration intentionally. */ (t === "ForOfStatement" && node.await === true) ); }
javascript
function isBoundary(node) { const t = node.type; return ( t === "FunctionDeclaration" || t === "FunctionExpression" || t === "ArrowFunctionExpression" || /* * Don't report the await expressions on for-await-of loop since it's * asynchronous iteration intentionally. */ (t === "ForOfStatement" && node.await === true) ); }
[ "function", "isBoundary", "(", "node", ")", "{", "const", "t", "=", "node", ".", "type", ";", "return", "(", "t", "===", "\"FunctionDeclaration\"", "||", "t", "===", "\"FunctionExpression\"", "||", "t", "===", "\"ArrowFunctionExpression\"", "||", "/*\n * Don't report the await expressions on for-await-of loop since it's\n * asynchronous iteration intentionally.\n */", "(", "t", "===", "\"ForOfStatement\"", "&&", "node", ".", "await", "===", "true", ")", ")", ";", "}" ]
Check whether it should stop traversing ancestors at the given node. @param {ASTNode} node A node to check. @returns {boolean} `true` if it should stop traversing.
[ "Check", "whether", "it", "should", "stop", "traversing", "ancestors", "at", "the", "given", "node", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-await-in-loop.js#L12-L26
2,953
eslint/eslint
lib/rules/no-await-in-loop.js
isLooped
function isLooped(node, parent) { switch (parent.type) { case "ForStatement": return ( node === parent.test || node === parent.update || node === parent.body ); case "ForOfStatement": case "ForInStatement": return node === parent.body; case "WhileStatement": case "DoWhileStatement": return node === parent.test || node === parent.body; default: return false; } }
javascript
function isLooped(node, parent) { switch (parent.type) { case "ForStatement": return ( node === parent.test || node === parent.update || node === parent.body ); case "ForOfStatement": case "ForInStatement": return node === parent.body; case "WhileStatement": case "DoWhileStatement": return node === parent.test || node === parent.body; default: return false; } }
[ "function", "isLooped", "(", "node", ",", "parent", ")", "{", "switch", "(", "parent", ".", "type", ")", "{", "case", "\"ForStatement\"", ":", "return", "(", "node", "===", "parent", ".", "test", "||", "node", "===", "parent", ".", "update", "||", "node", "===", "parent", ".", "body", ")", ";", "case", "\"ForOfStatement\"", ":", "case", "\"ForInStatement\"", ":", "return", "node", "===", "parent", ".", "body", ";", "case", "\"WhileStatement\"", ":", "case", "\"DoWhileStatement\"", ":", "return", "node", "===", "parent", ".", "test", "||", "node", "===", "parent", ".", "body", ";", "default", ":", "return", "false", ";", "}", "}" ]
Check whether the given node is in loop. @param {ASTNode} node A node to check. @param {ASTNode} parent A parent node to check. @returns {boolean} `true` if the node is in loop.
[ "Check", "whether", "the", "given", "node", "is", "in", "loop", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-await-in-loop.js#L34-L54
2,954
eslint/eslint
lib/rules/no-await-in-loop.js
validate
function validate(awaitNode) { if (awaitNode.type === "ForOfStatement" && !awaitNode.await) { return; } let node = awaitNode; let parent = node.parent; while (parent && !isBoundary(parent)) { if (isLooped(node, parent)) { context.report({ node: awaitNode, messageId: "unexpectedAwait" }); return; } node = parent; parent = parent.parent; } }
javascript
function validate(awaitNode) { if (awaitNode.type === "ForOfStatement" && !awaitNode.await) { return; } let node = awaitNode; let parent = node.parent; while (parent && !isBoundary(parent)) { if (isLooped(node, parent)) { context.report({ node: awaitNode, messageId: "unexpectedAwait" }); return; } node = parent; parent = parent.parent; } }
[ "function", "validate", "(", "awaitNode", ")", "{", "if", "(", "awaitNode", ".", "type", "===", "\"ForOfStatement\"", "&&", "!", "awaitNode", ".", "await", ")", "{", "return", ";", "}", "let", "node", "=", "awaitNode", ";", "let", "parent", "=", "node", ".", "parent", ";", "while", "(", "parent", "&&", "!", "isBoundary", "(", "parent", ")", ")", "{", "if", "(", "isLooped", "(", "node", ",", "parent", ")", ")", "{", "context", ".", "report", "(", "{", "node", ":", "awaitNode", ",", "messageId", ":", "\"unexpectedAwait\"", "}", ")", ";", "return", ";", "}", "node", "=", "parent", ";", "parent", "=", "parent", ".", "parent", ";", "}", "}" ]
Validate an await expression. @param {ASTNode} awaitNode An AwaitExpression or ForOfStatement node to validate. @returns {void}
[ "Validate", "an", "await", "expression", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-await-in-loop.js#L80-L99
2,955
eslint/eslint
lib/util/apply-disable-directives.js
compareLocations
function compareLocations(itemA, itemB) { return itemA.line - itemB.line || itemA.column - itemB.column; }
javascript
function compareLocations(itemA, itemB) { return itemA.line - itemB.line || itemA.column - itemB.column; }
[ "function", "compareLocations", "(", "itemA", ",", "itemB", ")", "{", "return", "itemA", ".", "line", "-", "itemB", ".", "line", "||", "itemA", ".", "column", "-", "itemB", ".", "column", ";", "}" ]
Compares the locations of two objects in a source file @param {{line: number, column: number}} itemA The first object @param {{line: number, column: number}} itemB The second object @returns {number} A value less than 1 if itemA appears before itemB in the source file, greater than 1 if itemA appears after itemB in the source file, or 0 if itemA and itemB have the same location.
[ "Compares", "the", "locations", "of", "two", "objects", "in", "a", "source", "file" ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/util/apply-disable-directives.js#L17-L19
2,956
eslint/eslint
lib/util/apply-disable-directives.js
applyDirectives
function applyDirectives(options) { const problems = []; let nextDirectiveIndex = 0; let currentGlobalDisableDirective = null; const disabledRuleMap = new Map(); // enabledRules is only used when there is a current global disable directive. const enabledRules = new Set(); const usedDisableDirectives = new Set(); for (const problem of options.problems) { while ( nextDirectiveIndex < options.directives.length && compareLocations(options.directives[nextDirectiveIndex], problem) <= 0 ) { const directive = options.directives[nextDirectiveIndex++]; switch (directive.type) { case "disable": if (directive.ruleId === null) { currentGlobalDisableDirective = directive; disabledRuleMap.clear(); enabledRules.clear(); } else if (currentGlobalDisableDirective) { enabledRules.delete(directive.ruleId); disabledRuleMap.set(directive.ruleId, directive); } else { disabledRuleMap.set(directive.ruleId, directive); } break; case "enable": if (directive.ruleId === null) { currentGlobalDisableDirective = null; disabledRuleMap.clear(); } else if (currentGlobalDisableDirective) { enabledRules.add(directive.ruleId); disabledRuleMap.delete(directive.ruleId); } else { disabledRuleMap.delete(directive.ruleId); } break; // no default } } if (disabledRuleMap.has(problem.ruleId)) { usedDisableDirectives.add(disabledRuleMap.get(problem.ruleId)); } else if (currentGlobalDisableDirective && !enabledRules.has(problem.ruleId)) { usedDisableDirectives.add(currentGlobalDisableDirective); } else { problems.push(problem); } } const unusedDisableDirectives = options.directives .filter(directive => directive.type === "disable" && !usedDisableDirectives.has(directive)) .map(directive => ({ ruleId: null, message: directive.ruleId ? `Unused eslint-disable directive (no problems were reported from '${directive.ruleId}').` : "Unused eslint-disable directive (no problems were reported).", line: directive.unprocessedDirective.line, column: directive.unprocessedDirective.column, severity: 2, nodeType: null })); return { problems, unusedDisableDirectives }; }
javascript
function applyDirectives(options) { const problems = []; let nextDirectiveIndex = 0; let currentGlobalDisableDirective = null; const disabledRuleMap = new Map(); // enabledRules is only used when there is a current global disable directive. const enabledRules = new Set(); const usedDisableDirectives = new Set(); for (const problem of options.problems) { while ( nextDirectiveIndex < options.directives.length && compareLocations(options.directives[nextDirectiveIndex], problem) <= 0 ) { const directive = options.directives[nextDirectiveIndex++]; switch (directive.type) { case "disable": if (directive.ruleId === null) { currentGlobalDisableDirective = directive; disabledRuleMap.clear(); enabledRules.clear(); } else if (currentGlobalDisableDirective) { enabledRules.delete(directive.ruleId); disabledRuleMap.set(directive.ruleId, directive); } else { disabledRuleMap.set(directive.ruleId, directive); } break; case "enable": if (directive.ruleId === null) { currentGlobalDisableDirective = null; disabledRuleMap.clear(); } else if (currentGlobalDisableDirective) { enabledRules.add(directive.ruleId); disabledRuleMap.delete(directive.ruleId); } else { disabledRuleMap.delete(directive.ruleId); } break; // no default } } if (disabledRuleMap.has(problem.ruleId)) { usedDisableDirectives.add(disabledRuleMap.get(problem.ruleId)); } else if (currentGlobalDisableDirective && !enabledRules.has(problem.ruleId)) { usedDisableDirectives.add(currentGlobalDisableDirective); } else { problems.push(problem); } } const unusedDisableDirectives = options.directives .filter(directive => directive.type === "disable" && !usedDisableDirectives.has(directive)) .map(directive => ({ ruleId: null, message: directive.ruleId ? `Unused eslint-disable directive (no problems were reported from '${directive.ruleId}').` : "Unused eslint-disable directive (no problems were reported).", line: directive.unprocessedDirective.line, column: directive.unprocessedDirective.column, severity: 2, nodeType: null })); return { problems, unusedDisableDirectives }; }
[ "function", "applyDirectives", "(", "options", ")", "{", "const", "problems", "=", "[", "]", ";", "let", "nextDirectiveIndex", "=", "0", ";", "let", "currentGlobalDisableDirective", "=", "null", ";", "const", "disabledRuleMap", "=", "new", "Map", "(", ")", ";", "// enabledRules is only used when there is a current global disable directive.", "const", "enabledRules", "=", "new", "Set", "(", ")", ";", "const", "usedDisableDirectives", "=", "new", "Set", "(", ")", ";", "for", "(", "const", "problem", "of", "options", ".", "problems", ")", "{", "while", "(", "nextDirectiveIndex", "<", "options", ".", "directives", ".", "length", "&&", "compareLocations", "(", "options", ".", "directives", "[", "nextDirectiveIndex", "]", ",", "problem", ")", "<=", "0", ")", "{", "const", "directive", "=", "options", ".", "directives", "[", "nextDirectiveIndex", "++", "]", ";", "switch", "(", "directive", ".", "type", ")", "{", "case", "\"disable\"", ":", "if", "(", "directive", ".", "ruleId", "===", "null", ")", "{", "currentGlobalDisableDirective", "=", "directive", ";", "disabledRuleMap", ".", "clear", "(", ")", ";", "enabledRules", ".", "clear", "(", ")", ";", "}", "else", "if", "(", "currentGlobalDisableDirective", ")", "{", "enabledRules", ".", "delete", "(", "directive", ".", "ruleId", ")", ";", "disabledRuleMap", ".", "set", "(", "directive", ".", "ruleId", ",", "directive", ")", ";", "}", "else", "{", "disabledRuleMap", ".", "set", "(", "directive", ".", "ruleId", ",", "directive", ")", ";", "}", "break", ";", "case", "\"enable\"", ":", "if", "(", "directive", ".", "ruleId", "===", "null", ")", "{", "currentGlobalDisableDirective", "=", "null", ";", "disabledRuleMap", ".", "clear", "(", ")", ";", "}", "else", "if", "(", "currentGlobalDisableDirective", ")", "{", "enabledRules", ".", "add", "(", "directive", ".", "ruleId", ")", ";", "disabledRuleMap", ".", "delete", "(", "directive", ".", "ruleId", ")", ";", "}", "else", "{", "disabledRuleMap", ".", "delete", "(", "directive", ".", "ruleId", ")", ";", "}", "break", ";", "// no default", "}", "}", "if", "(", "disabledRuleMap", ".", "has", "(", "problem", ".", "ruleId", ")", ")", "{", "usedDisableDirectives", ".", "add", "(", "disabledRuleMap", ".", "get", "(", "problem", ".", "ruleId", ")", ")", ";", "}", "else", "if", "(", "currentGlobalDisableDirective", "&&", "!", "enabledRules", ".", "has", "(", "problem", ".", "ruleId", ")", ")", "{", "usedDisableDirectives", ".", "add", "(", "currentGlobalDisableDirective", ")", ";", "}", "else", "{", "problems", ".", "push", "(", "problem", ")", ";", "}", "}", "const", "unusedDisableDirectives", "=", "options", ".", "directives", ".", "filter", "(", "directive", "=>", "directive", ".", "type", "===", "\"disable\"", "&&", "!", "usedDisableDirectives", ".", "has", "(", "directive", ")", ")", ".", "map", "(", "directive", "=>", "(", "{", "ruleId", ":", "null", ",", "message", ":", "directive", ".", "ruleId", "?", "`", "${", "directive", ".", "ruleId", "}", "`", ":", "\"Unused eslint-disable directive (no problems were reported).\"", ",", "line", ":", "directive", ".", "unprocessedDirective", ".", "line", ",", "column", ":", "directive", ".", "unprocessedDirective", ".", "column", ",", "severity", ":", "2", ",", "nodeType", ":", "null", "}", ")", ")", ";", "return", "{", "problems", ",", "unusedDisableDirectives", "}", ";", "}" ]
This is the same as the exported function, except that it doesn't handle disable-line and disable-next-line directives, and it always reports unused disable directives. @param {Object} options options for applying directives. This is the same as the options for the exported function, except that `reportUnusedDisableDirectives` is not supported (this function always reports unused disable directives). @returns {{problems: Problem[], unusedDisableDirectives: Problem[]}} An object with a list of filtered problems and unused eslint-disable directives
[ "This", "is", "the", "same", "as", "the", "exported", "function", "except", "that", "it", "doesn", "t", "handle", "disable", "-", "line", "and", "disable", "-", "next", "-", "line", "directives", "and", "it", "always", "reports", "unused", "disable", "directives", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/util/apply-disable-directives.js#L31-L101
2,957
eslint/eslint
lib/rules/implicit-arrow-linebreak.js
validateExpression
function validateExpression(node) { if (node.body.type === "BlockStatement") { return; } const arrowToken = sourceCode.getTokenBefore(node.body, isNotOpeningParenToken); const firstTokenOfBody = sourceCode.getTokenAfter(arrowToken); if (arrowToken.loc.end.line === firstTokenOfBody.loc.start.line && option === "below") { context.report({ node: firstTokenOfBody, messageId: "expected", fix: fixer => fixer.insertTextBefore(firstTokenOfBody, "\n") }); } else if (arrowToken.loc.end.line !== firstTokenOfBody.loc.start.line && option === "beside") { context.report({ node: firstTokenOfBody, messageId: "unexpected", fix(fixer) { if (sourceCode.getFirstTokenBetween(arrowToken, firstTokenOfBody, { includeComments: true, filter: isCommentToken })) { return null; } return fixer.replaceTextRange([arrowToken.range[1], firstTokenOfBody.range[0]], " "); } }); } }
javascript
function validateExpression(node) { if (node.body.type === "BlockStatement") { return; } const arrowToken = sourceCode.getTokenBefore(node.body, isNotOpeningParenToken); const firstTokenOfBody = sourceCode.getTokenAfter(arrowToken); if (arrowToken.loc.end.line === firstTokenOfBody.loc.start.line && option === "below") { context.report({ node: firstTokenOfBody, messageId: "expected", fix: fixer => fixer.insertTextBefore(firstTokenOfBody, "\n") }); } else if (arrowToken.loc.end.line !== firstTokenOfBody.loc.start.line && option === "beside") { context.report({ node: firstTokenOfBody, messageId: "unexpected", fix(fixer) { if (sourceCode.getFirstTokenBetween(arrowToken, firstTokenOfBody, { includeComments: true, filter: isCommentToken })) { return null; } return fixer.replaceTextRange([arrowToken.range[1], firstTokenOfBody.range[0]], " "); } }); } }
[ "function", "validateExpression", "(", "node", ")", "{", "if", "(", "node", ".", "body", ".", "type", "===", "\"BlockStatement\"", ")", "{", "return", ";", "}", "const", "arrowToken", "=", "sourceCode", ".", "getTokenBefore", "(", "node", ".", "body", ",", "isNotOpeningParenToken", ")", ";", "const", "firstTokenOfBody", "=", "sourceCode", ".", "getTokenAfter", "(", "arrowToken", ")", ";", "if", "(", "arrowToken", ".", "loc", ".", "end", ".", "line", "===", "firstTokenOfBody", ".", "loc", ".", "start", ".", "line", "&&", "option", "===", "\"below\"", ")", "{", "context", ".", "report", "(", "{", "node", ":", "firstTokenOfBody", ",", "messageId", ":", "\"expected\"", ",", "fix", ":", "fixer", "=>", "fixer", ".", "insertTextBefore", "(", "firstTokenOfBody", ",", "\"\\n\"", ")", "}", ")", ";", "}", "else", "if", "(", "arrowToken", ".", "loc", ".", "end", ".", "line", "!==", "firstTokenOfBody", ".", "loc", ".", "start", ".", "line", "&&", "option", "===", "\"beside\"", ")", "{", "context", ".", "report", "(", "{", "node", ":", "firstTokenOfBody", ",", "messageId", ":", "\"unexpected\"", ",", "fix", "(", "fixer", ")", "{", "if", "(", "sourceCode", ".", "getFirstTokenBetween", "(", "arrowToken", ",", "firstTokenOfBody", ",", "{", "includeComments", ":", "true", ",", "filter", ":", "isCommentToken", "}", ")", ")", "{", "return", "null", ";", "}", "return", "fixer", ".", "replaceTextRange", "(", "[", "arrowToken", ".", "range", "[", "1", "]", ",", "firstTokenOfBody", ".", "range", "[", "0", "]", "]", ",", "\" \"", ")", ";", "}", "}", ")", ";", "}", "}" ]
Validates the location of an arrow function body @param {ASTNode} node The arrow function body @returns {void}
[ "Validates", "the", "location", "of", "an", "arrow", "function", "body" ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/implicit-arrow-linebreak.js#L45-L72
2,958
eslint/eslint
lib/rules/no-extra-boolean-cast.js
isInBooleanContext
function isInBooleanContext(node, parent) { return ( (BOOLEAN_NODE_TYPES.indexOf(parent.type) !== -1 && node === parent.test) || // !<bool> (parent.type === "UnaryExpression" && parent.operator === "!") ); }
javascript
function isInBooleanContext(node, parent) { return ( (BOOLEAN_NODE_TYPES.indexOf(parent.type) !== -1 && node === parent.test) || // !<bool> (parent.type === "UnaryExpression" && parent.operator === "!") ); }
[ "function", "isInBooleanContext", "(", "node", ",", "parent", ")", "{", "return", "(", "(", "BOOLEAN_NODE_TYPES", ".", "indexOf", "(", "parent", ".", "type", ")", "!==", "-", "1", "&&", "node", "===", "parent", ".", "test", ")", "||", "// !<bool>", "(", "parent", ".", "type", "===", "\"UnaryExpression\"", "&&", "parent", ".", "operator", "===", "\"!\"", ")", ")", ";", "}" ]
Check if a node is in a context where its value would be coerced to a boolean at runtime. @param {Object} node The node @param {Object} parent Its parent @returns {boolean} If it is in a boolean context
[ "Check", "if", "a", "node", "is", "in", "a", "context", "where", "its", "value", "would", "be", "coerced", "to", "a", "boolean", "at", "runtime", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-extra-boolean-cast.js#L57-L66
2,959
eslint/eslint
lib/rules/no-alert.js
findReference
function findReference(scope, node) { const references = scope.references.filter(reference => reference.identifier.range[0] === node.range[0] && reference.identifier.range[1] === node.range[1]); if (references.length === 1) { return references[0]; } return null; }
javascript
function findReference(scope, node) { const references = scope.references.filter(reference => reference.identifier.range[0] === node.range[0] && reference.identifier.range[1] === node.range[1]); if (references.length === 1) { return references[0]; } return null; }
[ "function", "findReference", "(", "scope", ",", "node", ")", "{", "const", "references", "=", "scope", ".", "references", ".", "filter", "(", "reference", "=>", "reference", ".", "identifier", ".", "range", "[", "0", "]", "===", "node", ".", "range", "[", "0", "]", "&&", "reference", ".", "identifier", ".", "range", "[", "1", "]", "===", "node", ".", "range", "[", "1", "]", ")", ";", "if", "(", "references", ".", "length", "===", "1", ")", "{", "return", "references", "[", "0", "]", ";", "}", "return", "null", ";", "}" ]
Finds the eslint-scope reference in the given scope. @param {Object} scope The scope to search. @param {ASTNode} node The identifier node. @returns {Reference|null} Returns the found reference or null if none were found.
[ "Finds", "the", "eslint", "-", "scope", "reference", "in", "the", "given", "scope", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-alert.js#L32-L40
2,960
eslint/eslint
lib/rules/no-alert.js
isShadowed
function isShadowed(scope, node) { const reference = findReference(scope, node); return reference && reference.resolved && reference.resolved.defs.length > 0; }
javascript
function isShadowed(scope, node) { const reference = findReference(scope, node); return reference && reference.resolved && reference.resolved.defs.length > 0; }
[ "function", "isShadowed", "(", "scope", ",", "node", ")", "{", "const", "reference", "=", "findReference", "(", "scope", ",", "node", ")", ";", "return", "reference", "&&", "reference", ".", "resolved", "&&", "reference", ".", "resolved", ".", "defs", ".", "length", ">", "0", ";", "}" ]
Checks if the given identifier node is shadowed in the given scope. @param {Object} scope The current scope. @param {string} node The identifier node to check @returns {boolean} Whether or not the name is shadowed.
[ "Checks", "if", "the", "given", "identifier", "node", "is", "shadowed", "in", "the", "given", "scope", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-alert.js#L48-L52
2,961
eslint/eslint
lib/rules/no-alert.js
isGlobalThisReferenceOrGlobalWindow
function isGlobalThisReferenceOrGlobalWindow(scope, node) { if (scope.type === "global" && node.type === "ThisExpression") { return true; } if (node.name === "window") { return !isShadowed(scope, node); } return false; }
javascript
function isGlobalThisReferenceOrGlobalWindow(scope, node) { if (scope.type === "global" && node.type === "ThisExpression") { return true; } if (node.name === "window") { return !isShadowed(scope, node); } return false; }
[ "function", "isGlobalThisReferenceOrGlobalWindow", "(", "scope", ",", "node", ")", "{", "if", "(", "scope", ".", "type", "===", "\"global\"", "&&", "node", ".", "type", "===", "\"ThisExpression\"", ")", "{", "return", "true", ";", "}", "if", "(", "node", ".", "name", "===", "\"window\"", ")", "{", "return", "!", "isShadowed", "(", "scope", ",", "node", ")", ";", "}", "return", "false", ";", "}" ]
Checks if the given identifier node is a ThisExpression in the global scope or the global window property. @param {Object} scope The current scope. @param {string} node The identifier node to check @returns {boolean} Whether or not the node is a reference to the global object.
[ "Checks", "if", "the", "given", "identifier", "node", "is", "a", "ThisExpression", "in", "the", "global", "scope", "or", "the", "global", "window", "property", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-alert.js#L60-L69
2,962
eslint/eslint
lib/rules/no-regex-spaces.js
checkRegex
function checkRegex(node, value, valueStart) { const multipleSpacesRegex = /( {2,})( [+*{?]|[^+*{?]|$)/u, regexResults = multipleSpacesRegex.exec(value); if (regexResults !== null) { const count = regexResults[1].length; context.report({ node, message: "Spaces are hard to count. Use {{{count}}}.", data: { count }, fix(fixer) { return fixer.replaceTextRange( [valueStart + regexResults.index, valueStart + regexResults.index + count], ` {${count}}` ); } }); /* * TODO: (platinumazure) Fix message to use rule message * substitution when api.report is fixed in lib/eslint.js. */ } }
javascript
function checkRegex(node, value, valueStart) { const multipleSpacesRegex = /( {2,})( [+*{?]|[^+*{?]|$)/u, regexResults = multipleSpacesRegex.exec(value); if (regexResults !== null) { const count = regexResults[1].length; context.report({ node, message: "Spaces are hard to count. Use {{{count}}}.", data: { count }, fix(fixer) { return fixer.replaceTextRange( [valueStart + regexResults.index, valueStart + regexResults.index + count], ` {${count}}` ); } }); /* * TODO: (platinumazure) Fix message to use rule message * substitution when api.report is fixed in lib/eslint.js. */ } }
[ "function", "checkRegex", "(", "node", ",", "value", ",", "valueStart", ")", "{", "const", "multipleSpacesRegex", "=", "/", "( {2,})( [+*{?]|[^+*{?]|$)", "/", "u", ",", "regexResults", "=", "multipleSpacesRegex", ".", "exec", "(", "value", ")", ";", "if", "(", "regexResults", "!==", "null", ")", "{", "const", "count", "=", "regexResults", "[", "1", "]", ".", "length", ";", "context", ".", "report", "(", "{", "node", ",", "message", ":", "\"Spaces are hard to count. Use {{{count}}}.\"", ",", "data", ":", "{", "count", "}", ",", "fix", "(", "fixer", ")", "{", "return", "fixer", ".", "replaceTextRange", "(", "[", "valueStart", "+", "regexResults", ".", "index", ",", "valueStart", "+", "regexResults", ".", "index", "+", "count", "]", ",", "`", "${", "count", "}", "`", ")", ";", "}", "}", ")", ";", "/*\n * TODO: (platinumazure) Fix message to use rule message\n * substitution when api.report is fixed in lib/eslint.js.\n */", "}", "}" ]
Validate regular expressions @param {ASTNode} node node to validate @param {string} value regular expression to validate @param {number} valueStart The start location of the regex/string literal. It will always be the case that `sourceCode.getText().slice(valueStart, valueStart + value.length) === value` @returns {void} @private
[ "Validate", "regular", "expressions" ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-regex-spaces.js#L41-L65
2,963
eslint/eslint
lib/rules/no-regex-spaces.js
checkLiteral
function checkLiteral(node) { const token = sourceCode.getFirstToken(node), nodeType = token.type, nodeValue = token.value; if (nodeType === "RegularExpression") { checkRegex(node, nodeValue, token.range[0]); } }
javascript
function checkLiteral(node) { const token = sourceCode.getFirstToken(node), nodeType = token.type, nodeValue = token.value; if (nodeType === "RegularExpression") { checkRegex(node, nodeValue, token.range[0]); } }
[ "function", "checkLiteral", "(", "node", ")", "{", "const", "token", "=", "sourceCode", ".", "getFirstToken", "(", "node", ")", ",", "nodeType", "=", "token", ".", "type", ",", "nodeValue", "=", "token", ".", "value", ";", "if", "(", "nodeType", "===", "\"RegularExpression\"", ")", "{", "checkRegex", "(", "node", ",", "nodeValue", ",", "token", ".", "range", "[", "0", "]", ")", ";", "}", "}" ]
Validate regular expression literals @param {ASTNode} node node to validate @returns {void} @private
[ "Validate", "regular", "expression", "literals" ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-regex-spaces.js#L73-L81
2,964
eslint/eslint
lib/rules/prefer-rest-params.js
isNotNormalMemberAccess
function isNotNormalMemberAccess(reference) { const id = reference.identifier; const parent = id.parent; return !( parent.type === "MemberExpression" && parent.object === id && !parent.computed ); }
javascript
function isNotNormalMemberAccess(reference) { const id = reference.identifier; const parent = id.parent; return !( parent.type === "MemberExpression" && parent.object === id && !parent.computed ); }
[ "function", "isNotNormalMemberAccess", "(", "reference", ")", "{", "const", "id", "=", "reference", ".", "identifier", ";", "const", "parent", "=", "id", ".", "parent", ";", "return", "!", "(", "parent", ".", "type", "===", "\"MemberExpression\"", "&&", "parent", ".", "object", "===", "id", "&&", "!", "parent", ".", "computed", ")", ";", "}" ]
Checks if the given reference is not normal member access. - arguments .... true // not member access - arguments[i] .... true // computed member access - arguments[0] .... true // computed member access - arguments.length .... false // normal member access @param {eslint-scope.Reference} reference - The reference to check. @returns {boolean} `true` if the reference is not normal member access.
[ "Checks", "if", "the", "given", "reference", "is", "not", "normal", "member", "access", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/prefer-rest-params.js#L48-L57
2,965
eslint/eslint
lib/rules/prefer-rest-params.js
report
function report(reference) { context.report({ node: reference.identifier, loc: reference.identifier.loc, message: "Use the rest parameters instead of 'arguments'." }); }
javascript
function report(reference) { context.report({ node: reference.identifier, loc: reference.identifier.loc, message: "Use the rest parameters instead of 'arguments'." }); }
[ "function", "report", "(", "reference", ")", "{", "context", ".", "report", "(", "{", "node", ":", "reference", ".", "identifier", ",", "loc", ":", "reference", ".", "identifier", ".", "loc", ",", "message", ":", "\"Use the rest parameters instead of 'arguments'.\"", "}", ")", ";", "}" ]
Reports a given reference. @param {eslint-scope.Reference} reference - A reference to report. @returns {void}
[ "Reports", "a", "given", "reference", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/prefer-rest-params.js#L85-L91
2,966
eslint/eslint
lib/rules/prefer-rest-params.js
checkForArguments
function checkForArguments() { const argumentsVar = getVariableOfArguments(context.getScope()); if (argumentsVar) { argumentsVar .references .filter(isNotNormalMemberAccess) .forEach(report); } }
javascript
function checkForArguments() { const argumentsVar = getVariableOfArguments(context.getScope()); if (argumentsVar) { argumentsVar .references .filter(isNotNormalMemberAccess) .forEach(report); } }
[ "function", "checkForArguments", "(", ")", "{", "const", "argumentsVar", "=", "getVariableOfArguments", "(", "context", ".", "getScope", "(", ")", ")", ";", "if", "(", "argumentsVar", ")", "{", "argumentsVar", ".", "references", ".", "filter", "(", "isNotNormalMemberAccess", ")", ".", "forEach", "(", "report", ")", ";", "}", "}" ]
Reports references of the implicit `arguments` variable if exist. @returns {void}
[ "Reports", "references", "of", "the", "implicit", "arguments", "variable", "if", "exist", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/prefer-rest-params.js#L98-L107
2,967
eslint/eslint
lib/rules/template-curly-spacing.js
checkSpacingBefore
function checkSpacingBefore(token) { const prevToken = sourceCode.getTokenBefore(token); if (prevToken && CLOSE_PAREN.test(token.value) && astUtils.isTokenOnSameLine(prevToken, token) && sourceCode.isSpaceBetweenTokens(prevToken, token) !== always ) { context.report({ loc: token.loc.start, messageId: `${prefix}Before`, fix(fixer) { if (always) { return fixer.insertTextBefore(token, " "); } return fixer.removeRange([ prevToken.range[1], token.range[0] ]); } }); } }
javascript
function checkSpacingBefore(token) { const prevToken = sourceCode.getTokenBefore(token); if (prevToken && CLOSE_PAREN.test(token.value) && astUtils.isTokenOnSameLine(prevToken, token) && sourceCode.isSpaceBetweenTokens(prevToken, token) !== always ) { context.report({ loc: token.loc.start, messageId: `${prefix}Before`, fix(fixer) { if (always) { return fixer.insertTextBefore(token, " "); } return fixer.removeRange([ prevToken.range[1], token.range[0] ]); } }); } }
[ "function", "checkSpacingBefore", "(", "token", ")", "{", "const", "prevToken", "=", "sourceCode", ".", "getTokenBefore", "(", "token", ")", ";", "if", "(", "prevToken", "&&", "CLOSE_PAREN", ".", "test", "(", "token", ".", "value", ")", "&&", "astUtils", ".", "isTokenOnSameLine", "(", "prevToken", ",", "token", ")", "&&", "sourceCode", ".", "isSpaceBetweenTokens", "(", "prevToken", ",", "token", ")", "!==", "always", ")", "{", "context", ".", "report", "(", "{", "loc", ":", "token", ".", "loc", ".", "start", ",", "messageId", ":", "`", "${", "prefix", "}", "`", ",", "fix", "(", "fixer", ")", "{", "if", "(", "always", ")", "{", "return", "fixer", ".", "insertTextBefore", "(", "token", ",", "\" \"", ")", ";", "}", "return", "fixer", ".", "removeRange", "(", "[", "prevToken", ".", "range", "[", "1", "]", ",", "token", ".", "range", "[", "0", "]", "]", ")", ";", "}", "}", ")", ";", "}", "}" ]
Checks spacing before `}` of a given token. @param {Token} token - A token to check. This is a Template token. @returns {void}
[ "Checks", "spacing", "before", "}", "of", "a", "given", "token", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/template-curly-spacing.js#L59-L81
2,968
eslint/eslint
lib/rules/no-cond-assign.js
findConditionalAncestor
function findConditionalAncestor(node) { let currentAncestor = node; do { if (isConditionalTestExpression(currentAncestor)) { return currentAncestor.parent; } } while ((currentAncestor = currentAncestor.parent) && !astUtils.isFunction(currentAncestor)); return null; }
javascript
function findConditionalAncestor(node) { let currentAncestor = node; do { if (isConditionalTestExpression(currentAncestor)) { return currentAncestor.parent; } } while ((currentAncestor = currentAncestor.parent) && !astUtils.isFunction(currentAncestor)); return null; }
[ "function", "findConditionalAncestor", "(", "node", ")", "{", "let", "currentAncestor", "=", "node", ";", "do", "{", "if", "(", "isConditionalTestExpression", "(", "currentAncestor", ")", ")", "{", "return", "currentAncestor", ".", "parent", ";", "}", "}", "while", "(", "(", "currentAncestor", "=", "currentAncestor", ".", "parent", ")", "&&", "!", "astUtils", ".", "isFunction", "(", "currentAncestor", ")", ")", ";", "return", "null", ";", "}" ]
Given an AST node, perform a bottom-up search for the first ancestor that represents a conditional statement. @param {!Object} node The node to use at the start of the search. @returns {?Object} The closest ancestor node that represents a conditional statement.
[ "Given", "an", "AST", "node", "perform", "a", "bottom", "-", "up", "search", "for", "the", "first", "ancestor", "that", "represents", "a", "conditional", "statement", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-cond-assign.js#L67-L77
2,969
eslint/eslint
lib/rules/func-name-matching.js
isIdentifier
function isIdentifier(name, ecmaVersion) { if (ecmaVersion >= 6) { return esutils.keyword.isIdentifierES6(name); } return esutils.keyword.isIdentifierES5(name); }
javascript
function isIdentifier(name, ecmaVersion) { if (ecmaVersion >= 6) { return esutils.keyword.isIdentifierES6(name); } return esutils.keyword.isIdentifierES5(name); }
[ "function", "isIdentifier", "(", "name", ",", "ecmaVersion", ")", "{", "if", "(", "ecmaVersion", ">=", "6", ")", "{", "return", "esutils", ".", "keyword", ".", "isIdentifierES6", "(", "name", ")", ";", "}", "return", "esutils", ".", "keyword", ".", "isIdentifierES5", "(", "name", ")", ";", "}" ]
Determines if a string name is a valid identifier @param {string} name The string to be checked @param {int} ecmaVersion The ECMAScript version if specified in the parserOptions config @returns {boolean} True if the string is a valid identifier
[ "Determines", "if", "a", "string", "name", "is", "a", "valid", "identifier" ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/func-name-matching.js#L46-L51
2,970
eslint/eslint
lib/rules/func-name-matching.js
isPropertyCall
function isPropertyCall(objName, funcName, node) { if (!node) { return false; } return node.type === "CallExpression" && node.callee.object.name === objName && node.callee.property.name === funcName; }
javascript
function isPropertyCall(objName, funcName, node) { if (!node) { return false; } return node.type === "CallExpression" && node.callee.object.name === objName && node.callee.property.name === funcName; }
[ "function", "isPropertyCall", "(", "objName", ",", "funcName", ",", "node", ")", "{", "if", "(", "!", "node", ")", "{", "return", "false", ";", "}", "return", "node", ".", "type", "===", "\"CallExpression\"", "&&", "node", ".", "callee", ".", "object", ".", "name", "===", "objName", "&&", "node", ".", "callee", ".", "property", ".", "name", "===", "funcName", ";", "}" ]
Check whether node is a certain CallExpression. @param {string} objName object name @param {string} funcName function name @param {ASTNode} node The node to check @returns {boolean} `true` if node matches CallExpression
[ "Check", "whether", "node", "is", "a", "certain", "CallExpression", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/func-name-matching.js#L116-L123
2,971
eslint/eslint
lib/rules/comma-dangle.js
normalizeOptions
function normalizeOptions(optionValue) { if (typeof optionValue === "string") { return { arrays: optionValue, objects: optionValue, imports: optionValue, exports: optionValue, // For backward compatibility, always ignore functions. functions: "ignore" }; } if (typeof optionValue === "object" && optionValue !== null) { return { arrays: optionValue.arrays || DEFAULT_OPTIONS.arrays, objects: optionValue.objects || DEFAULT_OPTIONS.objects, imports: optionValue.imports || DEFAULT_OPTIONS.imports, exports: optionValue.exports || DEFAULT_OPTIONS.exports, functions: optionValue.functions || DEFAULT_OPTIONS.functions }; } return DEFAULT_OPTIONS; }
javascript
function normalizeOptions(optionValue) { if (typeof optionValue === "string") { return { arrays: optionValue, objects: optionValue, imports: optionValue, exports: optionValue, // For backward compatibility, always ignore functions. functions: "ignore" }; } if (typeof optionValue === "object" && optionValue !== null) { return { arrays: optionValue.arrays || DEFAULT_OPTIONS.arrays, objects: optionValue.objects || DEFAULT_OPTIONS.objects, imports: optionValue.imports || DEFAULT_OPTIONS.imports, exports: optionValue.exports || DEFAULT_OPTIONS.exports, functions: optionValue.functions || DEFAULT_OPTIONS.functions }; } return DEFAULT_OPTIONS; }
[ "function", "normalizeOptions", "(", "optionValue", ")", "{", "if", "(", "typeof", "optionValue", "===", "\"string\"", ")", "{", "return", "{", "arrays", ":", "optionValue", ",", "objects", ":", "optionValue", ",", "imports", ":", "optionValue", ",", "exports", ":", "optionValue", ",", "// For backward compatibility, always ignore functions.", "functions", ":", "\"ignore\"", "}", ";", "}", "if", "(", "typeof", "optionValue", "===", "\"object\"", "&&", "optionValue", "!==", "null", ")", "{", "return", "{", "arrays", ":", "optionValue", ".", "arrays", "||", "DEFAULT_OPTIONS", ".", "arrays", ",", "objects", ":", "optionValue", ".", "objects", "||", "DEFAULT_OPTIONS", ".", "objects", ",", "imports", ":", "optionValue", ".", "imports", "||", "DEFAULT_OPTIONS", ".", "imports", ",", "exports", ":", "optionValue", ".", "exports", "||", "DEFAULT_OPTIONS", ".", "exports", ",", "functions", ":", "optionValue", ".", "functions", "||", "DEFAULT_OPTIONS", ".", "functions", "}", ";", "}", "return", "DEFAULT_OPTIONS", ";", "}" ]
Normalize option value. @param {string|Object|undefined} optionValue - The 1st option value to normalize. @returns {Object} The normalized option value.
[ "Normalize", "option", "value", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/comma-dangle.js#L48-L71
2,972
eslint/eslint
lib/rules/comma-dangle.js
getLastItem
function getLastItem(node) { switch (node.type) { case "ObjectExpression": case "ObjectPattern": return lodash.last(node.properties); case "ArrayExpression": case "ArrayPattern": return lodash.last(node.elements); case "ImportDeclaration": case "ExportNamedDeclaration": return lodash.last(node.specifiers); case "FunctionDeclaration": case "FunctionExpression": case "ArrowFunctionExpression": return lodash.last(node.params); case "CallExpression": case "NewExpression": return lodash.last(node.arguments); default: return null; } }
javascript
function getLastItem(node) { switch (node.type) { case "ObjectExpression": case "ObjectPattern": return lodash.last(node.properties); case "ArrayExpression": case "ArrayPattern": return lodash.last(node.elements); case "ImportDeclaration": case "ExportNamedDeclaration": return lodash.last(node.specifiers); case "FunctionDeclaration": case "FunctionExpression": case "ArrowFunctionExpression": return lodash.last(node.params); case "CallExpression": case "NewExpression": return lodash.last(node.arguments); default: return null; } }
[ "function", "getLastItem", "(", "node", ")", "{", "switch", "(", "node", ".", "type", ")", "{", "case", "\"ObjectExpression\"", ":", "case", "\"ObjectPattern\"", ":", "return", "lodash", ".", "last", "(", "node", ".", "properties", ")", ";", "case", "\"ArrayExpression\"", ":", "case", "\"ArrayPattern\"", ":", "return", "lodash", ".", "last", "(", "node", ".", "elements", ")", ";", "case", "\"ImportDeclaration\"", ":", "case", "\"ExportNamedDeclaration\"", ":", "return", "lodash", ".", "last", "(", "node", ".", "specifiers", ")", ";", "case", "\"FunctionDeclaration\"", ":", "case", "\"FunctionExpression\"", ":", "case", "\"ArrowFunctionExpression\"", ":", "return", "lodash", ".", "last", "(", "node", ".", "params", ")", ";", "case", "\"CallExpression\"", ":", "case", "\"NewExpression\"", ":", "return", "lodash", ".", "last", "(", "node", ".", "arguments", ")", ";", "default", ":", "return", "null", ";", "}", "}" ]
Gets the last item of the given node. @param {ASTNode} node - The node to get. @returns {ASTNode|null} The last node or null.
[ "Gets", "the", "last", "item", "of", "the", "given", "node", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/comma-dangle.js#L148-L169
2,973
eslint/eslint
lib/rules/comma-dangle.js
getTrailingToken
function getTrailingToken(node, lastItem) { switch (node.type) { case "ObjectExpression": case "ArrayExpression": case "CallExpression": case "NewExpression": return sourceCode.getLastToken(node, 1); default: { const nextToken = sourceCode.getTokenAfter(lastItem); if (astUtils.isCommaToken(nextToken)) { return nextToken; } return sourceCode.getLastToken(lastItem); } } }
javascript
function getTrailingToken(node, lastItem) { switch (node.type) { case "ObjectExpression": case "ArrayExpression": case "CallExpression": case "NewExpression": return sourceCode.getLastToken(node, 1); default: { const nextToken = sourceCode.getTokenAfter(lastItem); if (astUtils.isCommaToken(nextToken)) { return nextToken; } return sourceCode.getLastToken(lastItem); } } }
[ "function", "getTrailingToken", "(", "node", ",", "lastItem", ")", "{", "switch", "(", "node", ".", "type", ")", "{", "case", "\"ObjectExpression\"", ":", "case", "\"ArrayExpression\"", ":", "case", "\"CallExpression\"", ":", "case", "\"NewExpression\"", ":", "return", "sourceCode", ".", "getLastToken", "(", "node", ",", "1", ")", ";", "default", ":", "{", "const", "nextToken", "=", "sourceCode", ".", "getTokenAfter", "(", "lastItem", ")", ";", "if", "(", "astUtils", ".", "isCommaToken", "(", "nextToken", ")", ")", "{", "return", "nextToken", ";", "}", "return", "sourceCode", ".", "getLastToken", "(", "lastItem", ")", ";", "}", "}", "}" ]
Gets the trailing comma token of the given node. If the trailing comma does not exist, this returns the token which is the insertion point of the trailing comma token. @param {ASTNode} node - The node to get. @param {ASTNode} lastItem - The last item of the node. @returns {Token} The trailing comma token or the insertion point.
[ "Gets", "the", "trailing", "comma", "token", "of", "the", "given", "node", ".", "If", "the", "trailing", "comma", "does", "not", "exist", "this", "returns", "the", "token", "which", "is", "the", "insertion", "point", "of", "the", "trailing", "comma", "token", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/comma-dangle.js#L180-L196
2,974
eslint/eslint
lib/rules/comma-dangle.js
isMultiline
function isMultiline(node) { const lastItem = getLastItem(node); if (!lastItem) { return false; } const penultimateToken = getTrailingToken(node, lastItem); const lastToken = sourceCode.getTokenAfter(penultimateToken); return lastToken.loc.end.line !== penultimateToken.loc.end.line; }
javascript
function isMultiline(node) { const lastItem = getLastItem(node); if (!lastItem) { return false; } const penultimateToken = getTrailingToken(node, lastItem); const lastToken = sourceCode.getTokenAfter(penultimateToken); return lastToken.loc.end.line !== penultimateToken.loc.end.line; }
[ "function", "isMultiline", "(", "node", ")", "{", "const", "lastItem", "=", "getLastItem", "(", "node", ")", ";", "if", "(", "!", "lastItem", ")", "{", "return", "false", ";", "}", "const", "penultimateToken", "=", "getTrailingToken", "(", "node", ",", "lastItem", ")", ";", "const", "lastToken", "=", "sourceCode", ".", "getTokenAfter", "(", "penultimateToken", ")", ";", "return", "lastToken", ".", "loc", ".", "end", ".", "line", "!==", "penultimateToken", ".", "loc", ".", "end", ".", "line", ";", "}" ]
Checks whether or not a given node is multiline. This rule handles a given node as multiline when the closing parenthesis and the last element are not on the same line. @param {ASTNode} node - A node to check. @returns {boolean} `true` if the node is multiline.
[ "Checks", "whether", "or", "not", "a", "given", "node", "is", "multiline", ".", "This", "rule", "handles", "a", "given", "node", "as", "multiline", "when", "the", "closing", "parenthesis", "and", "the", "last", "element", "are", "not", "on", "the", "same", "line", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/comma-dangle.js#L206-L217
2,975
eslint/eslint
lib/rules/comma-dangle.js
forbidTrailingComma
function forbidTrailingComma(node) { const lastItem = getLastItem(node); if (!lastItem || (node.type === "ImportDeclaration" && lastItem.type !== "ImportSpecifier")) { return; } const trailingToken = getTrailingToken(node, lastItem); if (astUtils.isCommaToken(trailingToken)) { context.report({ node: lastItem, loc: trailingToken.loc.start, messageId: "unexpected", fix(fixer) { return fixer.remove(trailingToken); } }); } }
javascript
function forbidTrailingComma(node) { const lastItem = getLastItem(node); if (!lastItem || (node.type === "ImportDeclaration" && lastItem.type !== "ImportSpecifier")) { return; } const trailingToken = getTrailingToken(node, lastItem); if (astUtils.isCommaToken(trailingToken)) { context.report({ node: lastItem, loc: trailingToken.loc.start, messageId: "unexpected", fix(fixer) { return fixer.remove(trailingToken); } }); } }
[ "function", "forbidTrailingComma", "(", "node", ")", "{", "const", "lastItem", "=", "getLastItem", "(", "node", ")", ";", "if", "(", "!", "lastItem", "||", "(", "node", ".", "type", "===", "\"ImportDeclaration\"", "&&", "lastItem", ".", "type", "!==", "\"ImportSpecifier\"", ")", ")", "{", "return", ";", "}", "const", "trailingToken", "=", "getTrailingToken", "(", "node", ",", "lastItem", ")", ";", "if", "(", "astUtils", ".", "isCommaToken", "(", "trailingToken", ")", ")", "{", "context", ".", "report", "(", "{", "node", ":", "lastItem", ",", "loc", ":", "trailingToken", ".", "loc", ".", "start", ",", "messageId", ":", "\"unexpected\"", ",", "fix", "(", "fixer", ")", "{", "return", "fixer", ".", "remove", "(", "trailingToken", ")", ";", "}", "}", ")", ";", "}", "}" ]
Reports a trailing comma if it exists. @param {ASTNode} node - A node to check. Its type is one of ObjectExpression, ObjectPattern, ArrayExpression, ArrayPattern, ImportDeclaration, and ExportNamedDeclaration. @returns {void}
[ "Reports", "a", "trailing", "comma", "if", "it", "exists", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/comma-dangle.js#L227-L246
2,976
eslint/eslint
lib/rules/comma-dangle.js
forceTrailingComma
function forceTrailingComma(node) { const lastItem = getLastItem(node); if (!lastItem || (node.type === "ImportDeclaration" && lastItem.type !== "ImportSpecifier")) { return; } if (!isTrailingCommaAllowed(lastItem)) { forbidTrailingComma(node); return; } const trailingToken = getTrailingToken(node, lastItem); if (trailingToken.value !== ",") { context.report({ node: lastItem, loc: trailingToken.loc.end, messageId: "missing", fix(fixer) { return fixer.insertTextAfter(trailingToken, ","); } }); } }
javascript
function forceTrailingComma(node) { const lastItem = getLastItem(node); if (!lastItem || (node.type === "ImportDeclaration" && lastItem.type !== "ImportSpecifier")) { return; } if (!isTrailingCommaAllowed(lastItem)) { forbidTrailingComma(node); return; } const trailingToken = getTrailingToken(node, lastItem); if (trailingToken.value !== ",") { context.report({ node: lastItem, loc: trailingToken.loc.end, messageId: "missing", fix(fixer) { return fixer.insertTextAfter(trailingToken, ","); } }); } }
[ "function", "forceTrailingComma", "(", "node", ")", "{", "const", "lastItem", "=", "getLastItem", "(", "node", ")", ";", "if", "(", "!", "lastItem", "||", "(", "node", ".", "type", "===", "\"ImportDeclaration\"", "&&", "lastItem", ".", "type", "!==", "\"ImportSpecifier\"", ")", ")", "{", "return", ";", "}", "if", "(", "!", "isTrailingCommaAllowed", "(", "lastItem", ")", ")", "{", "forbidTrailingComma", "(", "node", ")", ";", "return", ";", "}", "const", "trailingToken", "=", "getTrailingToken", "(", "node", ",", "lastItem", ")", ";", "if", "(", "trailingToken", ".", "value", "!==", "\",\"", ")", "{", "context", ".", "report", "(", "{", "node", ":", "lastItem", ",", "loc", ":", "trailingToken", ".", "loc", ".", "end", ",", "messageId", ":", "\"missing\"", ",", "fix", "(", "fixer", ")", "{", "return", "fixer", ".", "insertTextAfter", "(", "trailingToken", ",", "\",\"", ")", ";", "}", "}", ")", ";", "}", "}" ]
Reports the last element of a given node if it does not have a trailing comma. If a given node is `ArrayPattern` which has `RestElement`, the trailing comma is disallowed, so report if it exists. @param {ASTNode} node - A node to check. Its type is one of ObjectExpression, ObjectPattern, ArrayExpression, ArrayPattern, ImportDeclaration, and ExportNamedDeclaration. @returns {void}
[ "Reports", "the", "last", "element", "of", "a", "given", "node", "if", "it", "does", "not", "have", "a", "trailing", "comma", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/comma-dangle.js#L260-L283
2,977
eslint/eslint
lib/rules/no-bitwise.js
report
function report(node) { context.report({ node, messageId: "unexpected", data: { operator: node.operator } }); }
javascript
function report(node) { context.report({ node, messageId: "unexpected", data: { operator: node.operator } }); }
[ "function", "report", "(", "node", ")", "{", "context", ".", "report", "(", "{", "node", ",", "messageId", ":", "\"unexpected\"", ",", "data", ":", "{", "operator", ":", "node", ".", "operator", "}", "}", ")", ";", "}" ]
Reports an unexpected use of a bitwise operator. @param {ASTNode} node Node which contains the bitwise operator. @returns {void}
[ "Reports", "an", "unexpected", "use", "of", "a", "bitwise", "operator", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-bitwise.js#L69-L71
2,978
eslint/eslint
lib/rules/no-bitwise.js
isInt32Hint
function isInt32Hint(node) { return int32Hint && node.operator === "|" && node.right && node.right.type === "Literal" && node.right.value === 0; }
javascript
function isInt32Hint(node) { return int32Hint && node.operator === "|" && node.right && node.right.type === "Literal" && node.right.value === 0; }
[ "function", "isInt32Hint", "(", "node", ")", "{", "return", "int32Hint", "&&", "node", ".", "operator", "===", "\"|\"", "&&", "node", ".", "right", "&&", "node", ".", "right", ".", "type", "===", "\"Literal\"", "&&", "node", ".", "right", ".", "value", "===", "0", ";", "}" ]
Checks if the given bitwise operator is used for integer typecasting, i.e. "|0" @param {ASTNode} node The node to check. @returns {boolean} whether the node is used in integer typecasting.
[ "Checks", "if", "the", "given", "bitwise", "operator", "is", "used", "for", "integer", "typecasting", "i", ".", "e", ".", "|0" ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-bitwise.js#L96-L99
2,979
eslint/eslint
lib/rules/no-bitwise.js
checkNodeForBitwiseOperator
function checkNodeForBitwiseOperator(node) { if (hasBitwiseOperator(node) && !allowedOperator(node) && !isInt32Hint(node)) { report(node); } }
javascript
function checkNodeForBitwiseOperator(node) { if (hasBitwiseOperator(node) && !allowedOperator(node) && !isInt32Hint(node)) { report(node); } }
[ "function", "checkNodeForBitwiseOperator", "(", "node", ")", "{", "if", "(", "hasBitwiseOperator", "(", "node", ")", "&&", "!", "allowedOperator", "(", "node", ")", "&&", "!", "isInt32Hint", "(", "node", ")", ")", "{", "report", "(", "node", ")", ";", "}", "}" ]
Report if the given node contains a bitwise operator. @param {ASTNode} node The node to check. @returns {void}
[ "Report", "if", "the", "given", "node", "contains", "a", "bitwise", "operator", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-bitwise.js#L106-L110
2,980
eslint/eslint
lib/cli.js
translateOptions
function translateOptions(cliOptions) { return { envs: cliOptions.env, extensions: cliOptions.ext, rules: cliOptions.rule, plugins: cliOptions.plugin, globals: cliOptions.global, ignore: cliOptions.ignore, ignorePath: cliOptions.ignorePath, ignorePattern: cliOptions.ignorePattern, configFile: cliOptions.config, rulePaths: cliOptions.rulesdir, useEslintrc: cliOptions.eslintrc, parser: cliOptions.parser, parserOptions: cliOptions.parserOptions, cache: cliOptions.cache, cacheFile: cliOptions.cacheFile, cacheLocation: cliOptions.cacheLocation, fix: (cliOptions.fix || cliOptions.fixDryRun) && (cliOptions.quiet ? quietFixPredicate : true), fixTypes: cliOptions.fixType, allowInlineConfig: cliOptions.inlineConfig, reportUnusedDisableDirectives: cliOptions.reportUnusedDisableDirectives }; }
javascript
function translateOptions(cliOptions) { return { envs: cliOptions.env, extensions: cliOptions.ext, rules: cliOptions.rule, plugins: cliOptions.plugin, globals: cliOptions.global, ignore: cliOptions.ignore, ignorePath: cliOptions.ignorePath, ignorePattern: cliOptions.ignorePattern, configFile: cliOptions.config, rulePaths: cliOptions.rulesdir, useEslintrc: cliOptions.eslintrc, parser: cliOptions.parser, parserOptions: cliOptions.parserOptions, cache: cliOptions.cache, cacheFile: cliOptions.cacheFile, cacheLocation: cliOptions.cacheLocation, fix: (cliOptions.fix || cliOptions.fixDryRun) && (cliOptions.quiet ? quietFixPredicate : true), fixTypes: cliOptions.fixType, allowInlineConfig: cliOptions.inlineConfig, reportUnusedDisableDirectives: cliOptions.reportUnusedDisableDirectives }; }
[ "function", "translateOptions", "(", "cliOptions", ")", "{", "return", "{", "envs", ":", "cliOptions", ".", "env", ",", "extensions", ":", "cliOptions", ".", "ext", ",", "rules", ":", "cliOptions", ".", "rule", ",", "plugins", ":", "cliOptions", ".", "plugin", ",", "globals", ":", "cliOptions", ".", "global", ",", "ignore", ":", "cliOptions", ".", "ignore", ",", "ignorePath", ":", "cliOptions", ".", "ignorePath", ",", "ignorePattern", ":", "cliOptions", ".", "ignorePattern", ",", "configFile", ":", "cliOptions", ".", "config", ",", "rulePaths", ":", "cliOptions", ".", "rulesdir", ",", "useEslintrc", ":", "cliOptions", ".", "eslintrc", ",", "parser", ":", "cliOptions", ".", "parser", ",", "parserOptions", ":", "cliOptions", ".", "parserOptions", ",", "cache", ":", "cliOptions", ".", "cache", ",", "cacheFile", ":", "cliOptions", ".", "cacheFile", ",", "cacheLocation", ":", "cliOptions", ".", "cacheLocation", ",", "fix", ":", "(", "cliOptions", ".", "fix", "||", "cliOptions", ".", "fixDryRun", ")", "&&", "(", "cliOptions", ".", "quiet", "?", "quietFixPredicate", ":", "true", ")", ",", "fixTypes", ":", "cliOptions", ".", "fixType", ",", "allowInlineConfig", ":", "cliOptions", ".", "inlineConfig", ",", "reportUnusedDisableDirectives", ":", "cliOptions", ".", "reportUnusedDisableDirectives", "}", ";", "}" ]
Translates the CLI options into the options expected by the CLIEngine. @param {Object} cliOptions The CLI options to translate. @returns {CLIEngineOptions} The options object for the CLIEngine. @private
[ "Translates", "the", "CLI", "options", "into", "the", "options", "expected", "by", "the", "CLIEngine", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/cli.js#L48-L71
2,981
eslint/eslint
lib/rules/no-else-return.js
checkForIf
function checkForIf(node) { return node.type === "IfStatement" && hasElse(node) && naiveHasReturn(node.alternate) && naiveHasReturn(node.consequent); }
javascript
function checkForIf(node) { return node.type === "IfStatement" && hasElse(node) && naiveHasReturn(node.alternate) && naiveHasReturn(node.consequent); }
[ "function", "checkForIf", "(", "node", ")", "{", "return", "node", ".", "type", "===", "\"IfStatement\"", "&&", "hasElse", "(", "node", ")", "&&", "naiveHasReturn", "(", "node", ".", "alternate", ")", "&&", "naiveHasReturn", "(", "node", ".", "consequent", ")", ";", "}" ]
If the consequent is an IfStatement, check to see if it has an else and both its consequent and alternate path return, meaning this is a nested case of rule violation. If-Else not considered currently. @param {Node} node The consequent node @returns {boolean} True if this is a nested rule violation
[ "If", "the", "consequent", "is", "an", "IfStatement", "check", "to", "see", "if", "it", "has", "an", "else", "and", "both", "its", "consequent", "and", "alternate", "path", "return", "meaning", "this", "is", "a", "nested", "case", "of", "rule", "violation", ".", "If", "-", "Else", "not", "considered", "currently", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-else-return.js#L176-L179
2,982
eslint/eslint
lib/rules/no-else-return.js
alwaysReturns
function alwaysReturns(node) { if (node.type === "BlockStatement") { // If we have a BlockStatement, check each consequent body node. return node.body.some(checkForReturnOrIf); } /* * If not a block statement, make sure the consequent isn't a * ReturnStatement or an IfStatement with returns on both paths. */ return checkForReturnOrIf(node); }
javascript
function alwaysReturns(node) { if (node.type === "BlockStatement") { // If we have a BlockStatement, check each consequent body node. return node.body.some(checkForReturnOrIf); } /* * If not a block statement, make sure the consequent isn't a * ReturnStatement or an IfStatement with returns on both paths. */ return checkForReturnOrIf(node); }
[ "function", "alwaysReturns", "(", "node", ")", "{", "if", "(", "node", ".", "type", "===", "\"BlockStatement\"", ")", "{", "// If we have a BlockStatement, check each consequent body node.", "return", "node", ".", "body", ".", "some", "(", "checkForReturnOrIf", ")", ";", "}", "/*\n * If not a block statement, make sure the consequent isn't a\n * ReturnStatement or an IfStatement with returns on both paths.\n */", "return", "checkForReturnOrIf", "(", "node", ")", ";", "}" ]
Check whether a node returns in every codepath. @param {Node} node The node to be checked @returns {boolean} `true` if it returns on every codepath.
[ "Check", "whether", "a", "node", "returns", "in", "every", "codepath", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-else-return.js#L199-L211
2,983
eslint/eslint
lib/rules/no-else-return.js
checkIfWithoutElse
function checkIfWithoutElse(node) { const parent = node.parent; /* * Fixing this would require splitting one statement into two, so no error should * be reported if this node is in a position where only one statement is allowed. */ if (!astUtils.STATEMENT_LIST_PARENTS.has(parent.type)) { return; } const consequents = []; let alternate; for (let currentNode = node; currentNode.type === "IfStatement"; currentNode = currentNode.alternate) { if (!currentNode.alternate) { return; } consequents.push(currentNode.consequent); alternate = currentNode.alternate; } if (consequents.every(alwaysReturns)) { displayReport(alternate); } }
javascript
function checkIfWithoutElse(node) { const parent = node.parent; /* * Fixing this would require splitting one statement into two, so no error should * be reported if this node is in a position where only one statement is allowed. */ if (!astUtils.STATEMENT_LIST_PARENTS.has(parent.type)) { return; } const consequents = []; let alternate; for (let currentNode = node; currentNode.type === "IfStatement"; currentNode = currentNode.alternate) { if (!currentNode.alternate) { return; } consequents.push(currentNode.consequent); alternate = currentNode.alternate; } if (consequents.every(alwaysReturns)) { displayReport(alternate); } }
[ "function", "checkIfWithoutElse", "(", "node", ")", "{", "const", "parent", "=", "node", ".", "parent", ";", "/*\n * Fixing this would require splitting one statement into two, so no error should\n * be reported if this node is in a position where only one statement is allowed.\n */", "if", "(", "!", "astUtils", ".", "STATEMENT_LIST_PARENTS", ".", "has", "(", "parent", ".", "type", ")", ")", "{", "return", ";", "}", "const", "consequents", "=", "[", "]", ";", "let", "alternate", ";", "for", "(", "let", "currentNode", "=", "node", ";", "currentNode", ".", "type", "===", "\"IfStatement\"", ";", "currentNode", "=", "currentNode", ".", "alternate", ")", "{", "if", "(", "!", "currentNode", ".", "alternate", ")", "{", "return", ";", "}", "consequents", ".", "push", "(", "currentNode", ".", "consequent", ")", ";", "alternate", "=", "currentNode", ".", "alternate", ";", "}", "if", "(", "consequents", ".", "every", "(", "alwaysReturns", ")", ")", "{", "displayReport", "(", "alternate", ")", ";", "}", "}" ]
Check the if statement, but don't catch else-if blocks. @returns {void} @param {Node} node The node for the if statement to check @private
[ "Check", "the", "if", "statement", "but", "don", "t", "catch", "else", "-", "if", "blocks", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-else-return.js#L220-L245
2,984
eslint/eslint
lib/rules/no-else-return.js
checkIfWithElse
function checkIfWithElse(node) { const parent = node.parent; /* * Fixing this would require splitting one statement into two, so no error should * be reported if this node is in a position where only one statement is allowed. */ if (!astUtils.STATEMENT_LIST_PARENTS.has(parent.type)) { return; } const alternate = node.alternate; if (alternate && alwaysReturns(node.consequent)) { displayReport(alternate); } }
javascript
function checkIfWithElse(node) { const parent = node.parent; /* * Fixing this would require splitting one statement into two, so no error should * be reported if this node is in a position where only one statement is allowed. */ if (!astUtils.STATEMENT_LIST_PARENTS.has(parent.type)) { return; } const alternate = node.alternate; if (alternate && alwaysReturns(node.consequent)) { displayReport(alternate); } }
[ "function", "checkIfWithElse", "(", "node", ")", "{", "const", "parent", "=", "node", ".", "parent", ";", "/*\n * Fixing this would require splitting one statement into two, so no error should\n * be reported if this node is in a position where only one statement is allowed.\n */", "if", "(", "!", "astUtils", ".", "STATEMENT_LIST_PARENTS", ".", "has", "(", "parent", ".", "type", ")", ")", "{", "return", ";", "}", "const", "alternate", "=", "node", ".", "alternate", ";", "if", "(", "alternate", "&&", "alwaysReturns", "(", "node", ".", "consequent", ")", ")", "{", "displayReport", "(", "alternate", ")", ";", "}", "}" ]
Check the if statement @returns {void} @param {Node} node The node for the if statement to check @private
[ "Check", "the", "if", "statement" ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-else-return.js#L253-L270
2,985
eslint/eslint
lib/rules/key-spacing.js
initOptionProperty
function initOptionProperty(toOptions, fromOptions) { toOptions.mode = fromOptions.mode || "strict"; // Set value of beforeColon if (typeof fromOptions.beforeColon !== "undefined") { toOptions.beforeColon = +fromOptions.beforeColon; } else { toOptions.beforeColon = 0; } // Set value of afterColon if (typeof fromOptions.afterColon !== "undefined") { toOptions.afterColon = +fromOptions.afterColon; } else { toOptions.afterColon = 1; } // Set align if exists if (typeof fromOptions.align !== "undefined") { if (typeof fromOptions.align === "object") { toOptions.align = fromOptions.align; } else { // "string" toOptions.align = { on: fromOptions.align, mode: toOptions.mode, beforeColon: toOptions.beforeColon, afterColon: toOptions.afterColon }; } } return toOptions; }
javascript
function initOptionProperty(toOptions, fromOptions) { toOptions.mode = fromOptions.mode || "strict"; // Set value of beforeColon if (typeof fromOptions.beforeColon !== "undefined") { toOptions.beforeColon = +fromOptions.beforeColon; } else { toOptions.beforeColon = 0; } // Set value of afterColon if (typeof fromOptions.afterColon !== "undefined") { toOptions.afterColon = +fromOptions.afterColon; } else { toOptions.afterColon = 1; } // Set align if exists if (typeof fromOptions.align !== "undefined") { if (typeof fromOptions.align === "object") { toOptions.align = fromOptions.align; } else { // "string" toOptions.align = { on: fromOptions.align, mode: toOptions.mode, beforeColon: toOptions.beforeColon, afterColon: toOptions.afterColon }; } } return toOptions; }
[ "function", "initOptionProperty", "(", "toOptions", ",", "fromOptions", ")", "{", "toOptions", ".", "mode", "=", "fromOptions", ".", "mode", "||", "\"strict\"", ";", "// Set value of beforeColon", "if", "(", "typeof", "fromOptions", ".", "beforeColon", "!==", "\"undefined\"", ")", "{", "toOptions", ".", "beforeColon", "=", "+", "fromOptions", ".", "beforeColon", ";", "}", "else", "{", "toOptions", ".", "beforeColon", "=", "0", ";", "}", "// Set value of afterColon", "if", "(", "typeof", "fromOptions", ".", "afterColon", "!==", "\"undefined\"", ")", "{", "toOptions", ".", "afterColon", "=", "+", "fromOptions", ".", "afterColon", ";", "}", "else", "{", "toOptions", ".", "afterColon", "=", "1", ";", "}", "// Set align if exists", "if", "(", "typeof", "fromOptions", ".", "align", "!==", "\"undefined\"", ")", "{", "if", "(", "typeof", "fromOptions", ".", "align", "===", "\"object\"", ")", "{", "toOptions", ".", "align", "=", "fromOptions", ".", "align", ";", "}", "else", "{", "// \"string\"", "toOptions", ".", "align", "=", "{", "on", ":", "fromOptions", ".", "align", ",", "mode", ":", "toOptions", ".", "mode", ",", "beforeColon", ":", "toOptions", ".", "beforeColon", ",", "afterColon", ":", "toOptions", ".", "afterColon", "}", ";", "}", "}", "return", "toOptions", ";", "}" ]
Initializes a single option property from the configuration with defaults for undefined values @param {Object} toOptions Object to be initialized @param {Object} fromOptions Object to be initialized from @returns {Object} The object with correctly initialized options and values
[ "Initializes", "a", "single", "option", "property", "from", "the", "configuration", "with", "defaults", "for", "undefined", "values" ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/key-spacing.js#L51-L83
2,986
eslint/eslint
lib/rules/key-spacing.js
continuesPropertyGroup
function continuesPropertyGroup(lastMember, candidate) { const groupEndLine = lastMember.loc.start.line, candidateStartLine = candidate.loc.start.line; if (candidateStartLine - groupEndLine <= 1) { return true; } /* * Check that the first comment is adjacent to the end of the group, the * last comment is adjacent to the candidate property, and that successive * comments are adjacent to each other. */ const leadingComments = sourceCode.getCommentsBefore(candidate); if ( leadingComments.length && leadingComments[0].loc.start.line - groupEndLine <= 1 && candidateStartLine - last(leadingComments).loc.end.line <= 1 ) { for (let i = 1; i < leadingComments.length; i++) { if (leadingComments[i].loc.start.line - leadingComments[i - 1].loc.end.line > 1) { return false; } } return true; } return false; }
javascript
function continuesPropertyGroup(lastMember, candidate) { const groupEndLine = lastMember.loc.start.line, candidateStartLine = candidate.loc.start.line; if (candidateStartLine - groupEndLine <= 1) { return true; } /* * Check that the first comment is adjacent to the end of the group, the * last comment is adjacent to the candidate property, and that successive * comments are adjacent to each other. */ const leadingComments = sourceCode.getCommentsBefore(candidate); if ( leadingComments.length && leadingComments[0].loc.start.line - groupEndLine <= 1 && candidateStartLine - last(leadingComments).loc.end.line <= 1 ) { for (let i = 1; i < leadingComments.length; i++) { if (leadingComments[i].loc.start.line - leadingComments[i - 1].loc.end.line > 1) { return false; } } return true; } return false; }
[ "function", "continuesPropertyGroup", "(", "lastMember", ",", "candidate", ")", "{", "const", "groupEndLine", "=", "lastMember", ".", "loc", ".", "start", ".", "line", ",", "candidateStartLine", "=", "candidate", ".", "loc", ".", "start", ".", "line", ";", "if", "(", "candidateStartLine", "-", "groupEndLine", "<=", "1", ")", "{", "return", "true", ";", "}", "/*\n * Check that the first comment is adjacent to the end of the group, the\n * last comment is adjacent to the candidate property, and that successive\n * comments are adjacent to each other.\n */", "const", "leadingComments", "=", "sourceCode", ".", "getCommentsBefore", "(", "candidate", ")", ";", "if", "(", "leadingComments", ".", "length", "&&", "leadingComments", "[", "0", "]", ".", "loc", ".", "start", ".", "line", "-", "groupEndLine", "<=", "1", "&&", "candidateStartLine", "-", "last", "(", "leadingComments", ")", ".", "loc", ".", "end", ".", "line", "<=", "1", ")", "{", "for", "(", "let", "i", "=", "1", ";", "i", "<", "leadingComments", ".", "length", ";", "i", "++", ")", "{", "if", "(", "leadingComments", "[", "i", "]", ".", "loc", ".", "start", ".", "line", "-", "leadingComments", "[", "i", "-", "1", "]", ".", "loc", ".", "end", ".", "line", ">", "1", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}", "return", "false", ";", "}" ]
Checks whether a property is a member of the property group it follows. @param {ASTNode} lastMember The last Property known to be in the group. @param {ASTNode} candidate The next Property that might be in the group. @returns {boolean} True if the candidate property is part of the group.
[ "Checks", "whether", "a", "property", "is", "a", "member", "of", "the", "property", "group", "it", "follows", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/key-spacing.js#L328-L357
2,987
eslint/eslint
lib/rules/key-spacing.js
isKeyValueProperty
function isKeyValueProperty(property) { return !( (property.method || property.shorthand || property.kind !== "init" || property.type !== "Property") // Could be "ExperimentalSpreadProperty" or "SpreadElement" ); }
javascript
function isKeyValueProperty(property) { return !( (property.method || property.shorthand || property.kind !== "init" || property.type !== "Property") // Could be "ExperimentalSpreadProperty" or "SpreadElement" ); }
[ "function", "isKeyValueProperty", "(", "property", ")", "{", "return", "!", "(", "(", "property", ".", "method", "||", "property", ".", "shorthand", "||", "property", ".", "kind", "!==", "\"init\"", "||", "property", ".", "type", "!==", "\"Property\"", ")", "// Could be \"ExperimentalSpreadProperty\" or \"SpreadElement\"", ")", ";", "}" ]
Determines if the given property is key-value property. @param {ASTNode} property Property node to check. @returns {boolean} Whether the property is a key-value property.
[ "Determines", "if", "the", "given", "property", "is", "key", "-", "value", "property", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/key-spacing.js#L364-L370
2,988
eslint/eslint
lib/rules/key-spacing.js
getKey
function getKey(property) { const key = property.key; if (property.computed) { return sourceCode.getText().slice(key.range[0], key.range[1]); } return property.key.name || property.key.value; }
javascript
function getKey(property) { const key = property.key; if (property.computed) { return sourceCode.getText().slice(key.range[0], key.range[1]); } return property.key.name || property.key.value; }
[ "function", "getKey", "(", "property", ")", "{", "const", "key", "=", "property", ".", "key", ";", "if", "(", "property", ".", "computed", ")", "{", "return", "sourceCode", ".", "getText", "(", ")", ".", "slice", "(", "key", ".", "range", "[", "0", "]", ",", "key", ".", "range", "[", "1", "]", ")", ";", "}", "return", "property", ".", "key", ".", "name", "||", "property", ".", "key", ".", "value", ";", "}" ]
Gets an object literal property's key as the identifier name or string value. @param {ASTNode} property Property node whose key to retrieve. @returns {string} The property's key.
[ "Gets", "an", "object", "literal", "property", "s", "key", "as", "the", "identifier", "name", "or", "string", "value", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/key-spacing.js#L399-L407
2,989
eslint/eslint
lib/rules/key-spacing.js
report
function report(property, side, whitespace, expected, mode) { const diff = whitespace.length - expected, nextColon = getNextColon(property.key), tokenBeforeColon = sourceCode.getTokenBefore(nextColon, { includeComments: true }), tokenAfterColon = sourceCode.getTokenAfter(nextColon, { includeComments: true }), isKeySide = side === "key", locStart = isKeySide ? tokenBeforeColon.loc.start : tokenAfterColon.loc.start, isExtra = diff > 0, diffAbs = Math.abs(diff), spaces = Array(diffAbs + 1).join(" "); if (( diff && mode === "strict" || diff < 0 && mode === "minimum" || diff > 0 && !expected && mode === "minimum") && !(expected && containsLineTerminator(whitespace)) ) { let fix; if (isExtra) { let range; // Remove whitespace if (isKeySide) { range = [tokenBeforeColon.range[1], tokenBeforeColon.range[1] + diffAbs]; } else { range = [tokenAfterColon.range[0] - diffAbs, tokenAfterColon.range[0]]; } fix = function(fixer) { return fixer.removeRange(range); }; } else { // Add whitespace if (isKeySide) { fix = function(fixer) { return fixer.insertTextAfter(tokenBeforeColon, spaces); }; } else { fix = function(fixer) { return fixer.insertTextBefore(tokenAfterColon, spaces); }; } } let messageId = ""; if (isExtra) { messageId = side === "key" ? "extraKey" : "extraValue"; } else { messageId = side === "key" ? "missingKey" : "missingValue"; } context.report({ node: property[side], loc: locStart, messageId, data: { computed: property.computed ? "computed " : "", key: getKey(property) }, fix }); } }
javascript
function report(property, side, whitespace, expected, mode) { const diff = whitespace.length - expected, nextColon = getNextColon(property.key), tokenBeforeColon = sourceCode.getTokenBefore(nextColon, { includeComments: true }), tokenAfterColon = sourceCode.getTokenAfter(nextColon, { includeComments: true }), isKeySide = side === "key", locStart = isKeySide ? tokenBeforeColon.loc.start : tokenAfterColon.loc.start, isExtra = diff > 0, diffAbs = Math.abs(diff), spaces = Array(diffAbs + 1).join(" "); if (( diff && mode === "strict" || diff < 0 && mode === "minimum" || diff > 0 && !expected && mode === "minimum") && !(expected && containsLineTerminator(whitespace)) ) { let fix; if (isExtra) { let range; // Remove whitespace if (isKeySide) { range = [tokenBeforeColon.range[1], tokenBeforeColon.range[1] + diffAbs]; } else { range = [tokenAfterColon.range[0] - diffAbs, tokenAfterColon.range[0]]; } fix = function(fixer) { return fixer.removeRange(range); }; } else { // Add whitespace if (isKeySide) { fix = function(fixer) { return fixer.insertTextAfter(tokenBeforeColon, spaces); }; } else { fix = function(fixer) { return fixer.insertTextBefore(tokenAfterColon, spaces); }; } } let messageId = ""; if (isExtra) { messageId = side === "key" ? "extraKey" : "extraValue"; } else { messageId = side === "key" ? "missingKey" : "missingValue"; } context.report({ node: property[side], loc: locStart, messageId, data: { computed: property.computed ? "computed " : "", key: getKey(property) }, fix }); } }
[ "function", "report", "(", "property", ",", "side", ",", "whitespace", ",", "expected", ",", "mode", ")", "{", "const", "diff", "=", "whitespace", ".", "length", "-", "expected", ",", "nextColon", "=", "getNextColon", "(", "property", ".", "key", ")", ",", "tokenBeforeColon", "=", "sourceCode", ".", "getTokenBefore", "(", "nextColon", ",", "{", "includeComments", ":", "true", "}", ")", ",", "tokenAfterColon", "=", "sourceCode", ".", "getTokenAfter", "(", "nextColon", ",", "{", "includeComments", ":", "true", "}", ")", ",", "isKeySide", "=", "side", "===", "\"key\"", ",", "locStart", "=", "isKeySide", "?", "tokenBeforeColon", ".", "loc", ".", "start", ":", "tokenAfterColon", ".", "loc", ".", "start", ",", "isExtra", "=", "diff", ">", "0", ",", "diffAbs", "=", "Math", ".", "abs", "(", "diff", ")", ",", "spaces", "=", "Array", "(", "diffAbs", "+", "1", ")", ".", "join", "(", "\" \"", ")", ";", "if", "(", "(", "diff", "&&", "mode", "===", "\"strict\"", "||", "diff", "<", "0", "&&", "mode", "===", "\"minimum\"", "||", "diff", ">", "0", "&&", "!", "expected", "&&", "mode", "===", "\"minimum\"", ")", "&&", "!", "(", "expected", "&&", "containsLineTerminator", "(", "whitespace", ")", ")", ")", "{", "let", "fix", ";", "if", "(", "isExtra", ")", "{", "let", "range", ";", "// Remove whitespace", "if", "(", "isKeySide", ")", "{", "range", "=", "[", "tokenBeforeColon", ".", "range", "[", "1", "]", ",", "tokenBeforeColon", ".", "range", "[", "1", "]", "+", "diffAbs", "]", ";", "}", "else", "{", "range", "=", "[", "tokenAfterColon", ".", "range", "[", "0", "]", "-", "diffAbs", ",", "tokenAfterColon", ".", "range", "[", "0", "]", "]", ";", "}", "fix", "=", "function", "(", "fixer", ")", "{", "return", "fixer", ".", "removeRange", "(", "range", ")", ";", "}", ";", "}", "else", "{", "// Add whitespace", "if", "(", "isKeySide", ")", "{", "fix", "=", "function", "(", "fixer", ")", "{", "return", "fixer", ".", "insertTextAfter", "(", "tokenBeforeColon", ",", "spaces", ")", ";", "}", ";", "}", "else", "{", "fix", "=", "function", "(", "fixer", ")", "{", "return", "fixer", ".", "insertTextBefore", "(", "tokenAfterColon", ",", "spaces", ")", ";", "}", ";", "}", "}", "let", "messageId", "=", "\"\"", ";", "if", "(", "isExtra", ")", "{", "messageId", "=", "side", "===", "\"key\"", "?", "\"extraKey\"", ":", "\"extraValue\"", ";", "}", "else", "{", "messageId", "=", "side", "===", "\"key\"", "?", "\"missingKey\"", ":", "\"missingValue\"", ";", "}", "context", ".", "report", "(", "{", "node", ":", "property", "[", "side", "]", ",", "loc", ":", "locStart", ",", "messageId", ",", "data", ":", "{", "computed", ":", "property", ".", "computed", "?", "\"computed \"", ":", "\"\"", ",", "key", ":", "getKey", "(", "property", ")", "}", ",", "fix", "}", ")", ";", "}", "}" ]
Reports an appropriately-formatted error if spacing is incorrect on one side of the colon. @param {ASTNode} property Key-value pair in an object literal. @param {string} side Side being verified - either "key" or "value". @param {string} whitespace Actual whitespace string. @param {int} expected Expected whitespace length. @param {string} mode Value of the mode as "strict" or "minimum" @returns {void}
[ "Reports", "an", "appropriately", "-", "formatted", "error", "if", "spacing", "is", "incorrect", "on", "one", "side", "of", "the", "colon", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/key-spacing.js#L419-L483
2,990
eslint/eslint
lib/rules/key-spacing.js
getKeyWidth
function getKeyWidth(property) { const startToken = sourceCode.getFirstToken(property); const endToken = getLastTokenBeforeColon(property.key); return endToken.range[1] - startToken.range[0]; }
javascript
function getKeyWidth(property) { const startToken = sourceCode.getFirstToken(property); const endToken = getLastTokenBeforeColon(property.key); return endToken.range[1] - startToken.range[0]; }
[ "function", "getKeyWidth", "(", "property", ")", "{", "const", "startToken", "=", "sourceCode", ".", "getFirstToken", "(", "property", ")", ";", "const", "endToken", "=", "getLastTokenBeforeColon", "(", "property", ".", "key", ")", ";", "return", "endToken", ".", "range", "[", "1", "]", "-", "startToken", ".", "range", "[", "0", "]", ";", "}" ]
Gets the number of characters in a key, including quotes around string keys and braces around computed property keys. @param {ASTNode} property Property of on object literal. @returns {int} Width of the key.
[ "Gets", "the", "number", "of", "characters", "in", "a", "key", "including", "quotes", "around", "string", "keys", "and", "braces", "around", "computed", "property", "keys", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/key-spacing.js#L491-L496
2,991
eslint/eslint
lib/rules/key-spacing.js
getPropertyWhitespace
function getPropertyWhitespace(property) { const whitespace = /(\s*):(\s*)/u.exec(sourceCode.getText().slice( property.key.range[1], property.value.range[0] )); if (whitespace) { return { beforeColon: whitespace[1], afterColon: whitespace[2] }; } return null; }
javascript
function getPropertyWhitespace(property) { const whitespace = /(\s*):(\s*)/u.exec(sourceCode.getText().slice( property.key.range[1], property.value.range[0] )); if (whitespace) { return { beforeColon: whitespace[1], afterColon: whitespace[2] }; } return null; }
[ "function", "getPropertyWhitespace", "(", "property", ")", "{", "const", "whitespace", "=", "/", "(\\s*):(\\s*)", "/", "u", ".", "exec", "(", "sourceCode", ".", "getText", "(", ")", ".", "slice", "(", "property", ".", "key", ".", "range", "[", "1", "]", ",", "property", ".", "value", ".", "range", "[", "0", "]", ")", ")", ";", "if", "(", "whitespace", ")", "{", "return", "{", "beforeColon", ":", "whitespace", "[", "1", "]", ",", "afterColon", ":", "whitespace", "[", "2", "]", "}", ";", "}", "return", "null", ";", "}" ]
Gets the whitespace around the colon in an object literal property. @param {ASTNode} property Property node from an object literal. @returns {Object} Whitespace before and after the property's colon.
[ "Gets", "the", "whitespace", "around", "the", "colon", "in", "an", "object", "literal", "property", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/key-spacing.js#L503-L515
2,992
eslint/eslint
lib/rules/key-spacing.js
createGroups
function createGroups(node) { if (node.properties.length === 1) { return [node.properties]; } return node.properties.reduce((groups, property) => { const currentGroup = last(groups), prev = last(currentGroup); if (!prev || continuesPropertyGroup(prev, property)) { currentGroup.push(property); } else { groups.push([property]); } return groups; }, [ [] ]); }
javascript
function createGroups(node) { if (node.properties.length === 1) { return [node.properties]; } return node.properties.reduce((groups, property) => { const currentGroup = last(groups), prev = last(currentGroup); if (!prev || continuesPropertyGroup(prev, property)) { currentGroup.push(property); } else { groups.push([property]); } return groups; }, [ [] ]); }
[ "function", "createGroups", "(", "node", ")", "{", "if", "(", "node", ".", "properties", ".", "length", "===", "1", ")", "{", "return", "[", "node", ".", "properties", "]", ";", "}", "return", "node", ".", "properties", ".", "reduce", "(", "(", "groups", ",", "property", ")", "=>", "{", "const", "currentGroup", "=", "last", "(", "groups", ")", ",", "prev", "=", "last", "(", "currentGroup", ")", ";", "if", "(", "!", "prev", "||", "continuesPropertyGroup", "(", "prev", ",", "property", ")", ")", "{", "currentGroup", ".", "push", "(", "property", ")", ";", "}", "else", "{", "groups", ".", "push", "(", "[", "property", "]", ")", ";", "}", "return", "groups", ";", "}", ",", "[", "[", "]", "]", ")", ";", "}" ]
Creates groups of properties. @param {ASTNode} node ObjectExpression node being evaluated. @returns {Array.<ASTNode[]>} Groups of property AST node lists.
[ "Creates", "groups", "of", "properties", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/key-spacing.js#L522-L541
2,993
eslint/eslint
lib/rules/key-spacing.js
verifyGroupAlignment
function verifyGroupAlignment(properties) { const length = properties.length, widths = properties.map(getKeyWidth), // Width of keys, including quotes align = alignmentOptions.on; // "value" or "colon" let targetWidth = Math.max(...widths), beforeColon, afterColon, mode; if (alignmentOptions && length > 1) { // When aligning values within a group, use the alignment configuration. beforeColon = alignmentOptions.beforeColon; afterColon = alignmentOptions.afterColon; mode = alignmentOptions.mode; } else { beforeColon = multiLineOptions.beforeColon; afterColon = multiLineOptions.afterColon; mode = alignmentOptions.mode; } // Conditionally include one space before or after colon targetWidth += (align === "colon" ? beforeColon : afterColon); for (let i = 0; i < length; i++) { const property = properties[i]; const whitespace = getPropertyWhitespace(property); if (whitespace) { // Object literal getters/setters lack a colon const width = widths[i]; if (align === "value") { report(property, "key", whitespace.beforeColon, beforeColon, mode); report(property, "value", whitespace.afterColon, targetWidth - width, mode); } else { // align = "colon" report(property, "key", whitespace.beforeColon, targetWidth - width, mode); report(property, "value", whitespace.afterColon, afterColon, mode); } } } }
javascript
function verifyGroupAlignment(properties) { const length = properties.length, widths = properties.map(getKeyWidth), // Width of keys, including quotes align = alignmentOptions.on; // "value" or "colon" let targetWidth = Math.max(...widths), beforeColon, afterColon, mode; if (alignmentOptions && length > 1) { // When aligning values within a group, use the alignment configuration. beforeColon = alignmentOptions.beforeColon; afterColon = alignmentOptions.afterColon; mode = alignmentOptions.mode; } else { beforeColon = multiLineOptions.beforeColon; afterColon = multiLineOptions.afterColon; mode = alignmentOptions.mode; } // Conditionally include one space before or after colon targetWidth += (align === "colon" ? beforeColon : afterColon); for (let i = 0; i < length; i++) { const property = properties[i]; const whitespace = getPropertyWhitespace(property); if (whitespace) { // Object literal getters/setters lack a colon const width = widths[i]; if (align === "value") { report(property, "key", whitespace.beforeColon, beforeColon, mode); report(property, "value", whitespace.afterColon, targetWidth - width, mode); } else { // align = "colon" report(property, "key", whitespace.beforeColon, targetWidth - width, mode); report(property, "value", whitespace.afterColon, afterColon, mode); } } } }
[ "function", "verifyGroupAlignment", "(", "properties", ")", "{", "const", "length", "=", "properties", ".", "length", ",", "widths", "=", "properties", ".", "map", "(", "getKeyWidth", ")", ",", "// Width of keys, including quotes", "align", "=", "alignmentOptions", ".", "on", ";", "// \"value\" or \"colon\"", "let", "targetWidth", "=", "Math", ".", "max", "(", "...", "widths", ")", ",", "beforeColon", ",", "afterColon", ",", "mode", ";", "if", "(", "alignmentOptions", "&&", "length", ">", "1", ")", "{", "// When aligning values within a group, use the alignment configuration.", "beforeColon", "=", "alignmentOptions", ".", "beforeColon", ";", "afterColon", "=", "alignmentOptions", ".", "afterColon", ";", "mode", "=", "alignmentOptions", ".", "mode", ";", "}", "else", "{", "beforeColon", "=", "multiLineOptions", ".", "beforeColon", ";", "afterColon", "=", "multiLineOptions", ".", "afterColon", ";", "mode", "=", "alignmentOptions", ".", "mode", ";", "}", "// Conditionally include one space before or after colon", "targetWidth", "+=", "(", "align", "===", "\"colon\"", "?", "beforeColon", ":", "afterColon", ")", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "length", ";", "i", "++", ")", "{", "const", "property", "=", "properties", "[", "i", "]", ";", "const", "whitespace", "=", "getPropertyWhitespace", "(", "property", ")", ";", "if", "(", "whitespace", ")", "{", "// Object literal getters/setters lack a colon", "const", "width", "=", "widths", "[", "i", "]", ";", "if", "(", "align", "===", "\"value\"", ")", "{", "report", "(", "property", ",", "\"key\"", ",", "whitespace", ".", "beforeColon", ",", "beforeColon", ",", "mode", ")", ";", "report", "(", "property", ",", "\"value\"", ",", "whitespace", ".", "afterColon", ",", "targetWidth", "-", "width", ",", "mode", ")", ";", "}", "else", "{", "// align = \"colon\"", "report", "(", "property", ",", "\"key\"", ",", "whitespace", ".", "beforeColon", ",", "targetWidth", "-", "width", ",", "mode", ")", ";", "report", "(", "property", ",", "\"value\"", ",", "whitespace", ".", "afterColon", ",", "afterColon", ",", "mode", ")", ";", "}", "}", "}", "}" ]
Verifies correct vertical alignment of a group of properties. @param {ASTNode[]} properties List of Property AST nodes. @returns {void}
[ "Verifies", "correct", "vertical", "alignment", "of", "a", "group", "of", "properties", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/key-spacing.js#L548-L584
2,994
eslint/eslint
lib/rules/key-spacing.js
verifyAlignment
function verifyAlignment(node) { createGroups(node).forEach(group => { verifyGroupAlignment(group.filter(isKeyValueProperty)); }); }
javascript
function verifyAlignment(node) { createGroups(node).forEach(group => { verifyGroupAlignment(group.filter(isKeyValueProperty)); }); }
[ "function", "verifyAlignment", "(", "node", ")", "{", "createGroups", "(", "node", ")", ".", "forEach", "(", "group", "=>", "{", "verifyGroupAlignment", "(", "group", ".", "filter", "(", "isKeyValueProperty", ")", ")", ";", "}", ")", ";", "}" ]
Verifies vertical alignment, taking into account groups of properties. @param {ASTNode} node ObjectExpression node being evaluated. @returns {void}
[ "Verifies", "vertical", "alignment", "taking", "into", "account", "groups", "of", "properties", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/key-spacing.js#L591-L595
2,995
eslint/eslint
lib/rules/key-spacing.js
verifySpacing
function verifySpacing(node, lineOptions) { const actual = getPropertyWhitespace(node); if (actual) { // Object literal getters/setters lack colons report(node, "key", actual.beforeColon, lineOptions.beforeColon, lineOptions.mode); report(node, "value", actual.afterColon, lineOptions.afterColon, lineOptions.mode); } }
javascript
function verifySpacing(node, lineOptions) { const actual = getPropertyWhitespace(node); if (actual) { // Object literal getters/setters lack colons report(node, "key", actual.beforeColon, lineOptions.beforeColon, lineOptions.mode); report(node, "value", actual.afterColon, lineOptions.afterColon, lineOptions.mode); } }
[ "function", "verifySpacing", "(", "node", ",", "lineOptions", ")", "{", "const", "actual", "=", "getPropertyWhitespace", "(", "node", ")", ";", "if", "(", "actual", ")", "{", "// Object literal getters/setters lack colons", "report", "(", "node", ",", "\"key\"", ",", "actual", ".", "beforeColon", ",", "lineOptions", ".", "beforeColon", ",", "lineOptions", ".", "mode", ")", ";", "report", "(", "node", ",", "\"value\"", ",", "actual", ".", "afterColon", ",", "lineOptions", ".", "afterColon", ",", "lineOptions", ".", "mode", ")", ";", "}", "}" ]
Verifies spacing of property conforms to specified options. @param {ASTNode} node Property node being evaluated. @param {Object} lineOptions Configured singleLine or multiLine options @returns {void}
[ "Verifies", "spacing", "of", "property", "conforms", "to", "specified", "options", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/key-spacing.js#L603-L610
2,996
eslint/eslint
lib/rules/key-spacing.js
verifyListSpacing
function verifyListSpacing(properties) { const length = properties.length; for (let i = 0; i < length; i++) { verifySpacing(properties[i], singleLineOptions); } }
javascript
function verifyListSpacing(properties) { const length = properties.length; for (let i = 0; i < length; i++) { verifySpacing(properties[i], singleLineOptions); } }
[ "function", "verifyListSpacing", "(", "properties", ")", "{", "const", "length", "=", "properties", ".", "length", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "length", ";", "i", "++", ")", "{", "verifySpacing", "(", "properties", "[", "i", "]", ",", "singleLineOptions", ")", ";", "}", "}" ]
Verifies spacing of each property in a list. @param {ASTNode[]} properties List of Property AST nodes. @returns {void}
[ "Verifies", "spacing", "of", "each", "property", "in", "a", "list", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/key-spacing.js#L617-L623
2,997
eslint/eslint
lib/rules/no-implicit-coercion.js
isMultiplyByOne
function isMultiplyByOne(node) { return node.operator === "*" && ( node.left.type === "Literal" && node.left.value === 1 || node.right.type === "Literal" && node.right.value === 1 ); }
javascript
function isMultiplyByOne(node) { return node.operator === "*" && ( node.left.type === "Literal" && node.left.value === 1 || node.right.type === "Literal" && node.right.value === 1 ); }
[ "function", "isMultiplyByOne", "(", "node", ")", "{", "return", "node", ".", "operator", "===", "\"*\"", "&&", "(", "node", ".", "left", ".", "type", "===", "\"Literal\"", "&&", "node", ".", "left", ".", "value", "===", "1", "||", "node", ".", "right", ".", "type", "===", "\"Literal\"", "&&", "node", ".", "right", ".", "value", "===", "1", ")", ";", "}" ]
Checks whether or not a node is a multiplying by one. @param {BinaryExpression} node - A BinaryExpression node to check. @returns {boolean} Whether or not the node is a multiplying by one.
[ "Checks", "whether", "or", "not", "a", "node", "is", "a", "multiplying", "by", "one", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-implicit-coercion.js#L64-L69
2,998
eslint/eslint
lib/rules/no-implicit-coercion.js
isNumeric
function isNumeric(node) { return ( node.type === "Literal" && typeof node.value === "number" || node.type === "CallExpression" && ( node.callee.name === "Number" || node.callee.name === "parseInt" || node.callee.name === "parseFloat" ) ); }
javascript
function isNumeric(node) { return ( node.type === "Literal" && typeof node.value === "number" || node.type === "CallExpression" && ( node.callee.name === "Number" || node.callee.name === "parseInt" || node.callee.name === "parseFloat" ) ); }
[ "function", "isNumeric", "(", "node", ")", "{", "return", "(", "node", ".", "type", "===", "\"Literal\"", "&&", "typeof", "node", ".", "value", "===", "\"number\"", "||", "node", ".", "type", "===", "\"CallExpression\"", "&&", "(", "node", ".", "callee", ".", "name", "===", "\"Number\"", "||", "node", ".", "callee", ".", "name", "===", "\"parseInt\"", "||", "node", ".", "callee", ".", "name", "===", "\"parseFloat\"", ")", ")", ";", "}" ]
Checks whether the result of a node is numeric or not @param {ASTNode} node The node to test @returns {boolean} true if the node is a number literal or a `Number()`, `parseInt` or `parseFloat` call
[ "Checks", "whether", "the", "result", "of", "a", "node", "is", "numeric", "or", "not" ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-implicit-coercion.js#L76-L85
2,999
eslint/eslint
lib/rules/no-implicit-coercion.js
getNonNumericOperand
function getNonNumericOperand(node) { const left = node.left, right = node.right; if (right.type !== "BinaryExpression" && !isNumeric(right)) { return right; } if (left.type !== "BinaryExpression" && !isNumeric(left)) { return left; } return null; }
javascript
function getNonNumericOperand(node) { const left = node.left, right = node.right; if (right.type !== "BinaryExpression" && !isNumeric(right)) { return right; } if (left.type !== "BinaryExpression" && !isNumeric(left)) { return left; } return null; }
[ "function", "getNonNumericOperand", "(", "node", ")", "{", "const", "left", "=", "node", ".", "left", ",", "right", "=", "node", ".", "right", ";", "if", "(", "right", ".", "type", "!==", "\"BinaryExpression\"", "&&", "!", "isNumeric", "(", "right", ")", ")", "{", "return", "right", ";", "}", "if", "(", "left", ".", "type", "!==", "\"BinaryExpression\"", "&&", "!", "isNumeric", "(", "left", ")", ")", "{", "return", "left", ";", "}", "return", "null", ";", "}" ]
Returns the first non-numeric operand in a BinaryExpression. Designed to be used from bottom to up since it walks up the BinaryExpression trees using node.parent to find the result. @param {BinaryExpression} node The BinaryExpression node to be walked up on @returns {ASTNode|null} The first non-numeric item in the BinaryExpression tree or null
[ "Returns", "the", "first", "non", "-", "numeric", "operand", "in", "a", "BinaryExpression", ".", "Designed", "to", "be", "used", "from", "bottom", "to", "up", "since", "it", "walks", "up", "the", "BinaryExpression", "trees", "using", "node", ".", "parent", "to", "find", "the", "result", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-implicit-coercion.js#L94-L107