repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
partition
stringclasses
1 value
eslint/eslint
lib/rules/multiline-comment-style.js
convertToStarredBlock
function convertToStarredBlock(firstComment, commentLinesList) { const initialOffset = sourceCode.text.slice(firstComment.range[0] - firstComment.loc.start.column, firstComment.range[0]); const starredLines = commentLinesList.map(line => `${initialOffset} *${line}`); return `\n${starredLines.join("\n")}\n${initialOffset} `; }
javascript
function convertToStarredBlock(firstComment, commentLinesList) { const initialOffset = sourceCode.text.slice(firstComment.range[0] - firstComment.loc.start.column, firstComment.range[0]); const starredLines = commentLinesList.map(line => `${initialOffset} *${line}`); return `\n${starredLines.join("\n")}\n${initialOffset} `; }
[ "function", "convertToStarredBlock", "(", "firstComment", ",", "commentLinesList", ")", "{", "const", "initialOffset", "=", "sourceCode", ".", "text", ".", "slice", "(", "firstComment", ".", "range", "[", "0", "]", "-", "firstComment", ".", "loc", ".", "start", ".", "column", ",", "firstComment", ".", "range", "[", "0", "]", ")", ";", "const", "starredLines", "=", "commentLinesList", ".", "map", "(", "line", "=>", "`", "${", "initialOffset", "}", "${", "line", "}", "`", ")", ";", "return", "`", "\\n", "${", "starredLines", ".", "join", "(", "\"\\n\"", ")", "}", "\\n", "\\n", "`", ";", "}" ]
Converts a comment into starred-block form @param {Token} firstComment The first comment of the group being converted @param {string[]} commentLinesList A list of lines to appear in the new starred-block comment @returns {string} A representation of the comment value in starred-block form, excluding start and end markers
[ "Converts", "a", "comment", "into", "starred", "-", "block", "form" ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/multiline-comment-style.js#L64-L69
train
eslint/eslint
lib/rules/multiline-comment-style.js
convertToSeparateLines
function convertToSeparateLines(firstComment, commentLinesList) { const initialOffset = sourceCode.text.slice(firstComment.range[0] - firstComment.loc.start.column, firstComment.range[0]); const separateLines = commentLinesList.map(line => `// ${line.trim()}`); return separateLines.join(`\n${initialOffset}`); }
javascript
function convertToSeparateLines(firstComment, commentLinesList) { const initialOffset = sourceCode.text.slice(firstComment.range[0] - firstComment.loc.start.column, firstComment.range[0]); const separateLines = commentLinesList.map(line => `// ${line.trim()}`); return separateLines.join(`\n${initialOffset}`); }
[ "function", "convertToSeparateLines", "(", "firstComment", ",", "commentLinesList", ")", "{", "const", "initialOffset", "=", "sourceCode", ".", "text", ".", "slice", "(", "firstComment", ".", "range", "[", "0", "]", "-", "firstComment", ".", "loc", ".", "start", ".", "column", ",", "firstComment", ".", "range", "[", "0", "]", ")", ";", "const", "separateLines", "=", "commentLinesList", ".", "map", "(", "line", "=>", "`", "${", "line", ".", "trim", "(", ")", "}", "`", ")", ";", "return", "separateLines", ".", "join", "(", "`", "\\n", "${", "initialOffset", "}", "`", ")", ";", "}" ]
Converts a comment into separate-line form @param {Token} firstComment The first comment of the group being converted @param {string[]} commentLinesList A list of lines to appear in the new starred-block comment @returns {string} A representation of the comment value in separate-line form
[ "Converts", "a", "comment", "into", "separate", "-", "line", "form" ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/multiline-comment-style.js#L77-L82
train
eslint/eslint
lib/rules/multiline-comment-style.js
convertToBlock
function convertToBlock(firstComment, commentLinesList) { const initialOffset = sourceCode.text.slice(firstComment.range[0] - firstComment.loc.start.column, firstComment.range[0]); const blockLines = commentLinesList.map(line => line.trim()); return `/* ${blockLines.join(`\n${initialOffset} `)} */`; }
javascript
function convertToBlock(firstComment, commentLinesList) { const initialOffset = sourceCode.text.slice(firstComment.range[0] - firstComment.loc.start.column, firstComment.range[0]); const blockLines = commentLinesList.map(line => line.trim()); return `/* ${blockLines.join(`\n${initialOffset} `)} */`; }
[ "function", "convertToBlock", "(", "firstComment", ",", "commentLinesList", ")", "{", "const", "initialOffset", "=", "sourceCode", ".", "text", ".", "slice", "(", "firstComment", ".", "range", "[", "0", "]", "-", "firstComment", ".", "loc", ".", "start", ".", "column", ",", "firstComment", ".", "range", "[", "0", "]", ")", ";", "const", "blockLines", "=", "commentLinesList", ".", "map", "(", "line", "=>", "line", ".", "trim", "(", ")", ")", ";", "return", "`", "${", "blockLines", ".", "join", "(", "`", "\\n", "${", "initialOffset", "}", "`", ")", "}", "`", ";", "}" ]
Converts a comment into bare-block form @param {Token} firstComment The first comment of the group being converted @param {string[]} commentLinesList A list of lines to appear in the new starred-block comment @returns {string} A representation of the comment value in bare-block form
[ "Converts", "a", "comment", "into", "bare", "-", "block", "form" ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/multiline-comment-style.js#L90-L95
train
eslint/eslint
lib/rules/multiline-comment-style.js
isJSDoc
function isJSDoc(commentGroup) { const lines = commentGroup[0].value.split(astUtils.LINEBREAK_MATCHER); return commentGroup[0].type === "Block" && /^\*\s*$/u.test(lines[0]) && lines.slice(1, -1).every(line => /^\s* /u.test(line)) && /^\s*$/u.test(lines[lines.length - 1]); }
javascript
function isJSDoc(commentGroup) { const lines = commentGroup[0].value.split(astUtils.LINEBREAK_MATCHER); return commentGroup[0].type === "Block" && /^\*\s*$/u.test(lines[0]) && lines.slice(1, -1).every(line => /^\s* /u.test(line)) && /^\s*$/u.test(lines[lines.length - 1]); }
[ "function", "isJSDoc", "(", "commentGroup", ")", "{", "const", "lines", "=", "commentGroup", "[", "0", "]", ".", "value", ".", "split", "(", "astUtils", ".", "LINEBREAK_MATCHER", ")", ";", "return", "commentGroup", "[", "0", "]", ".", "type", "===", "\"Block\"", "&&", "/", "^\\*\\s*$", "/", "u", ".", "test", "(", "lines", "[", "0", "]", ")", "&&", "lines", ".", "slice", "(", "1", ",", "-", "1", ")", ".", "every", "(", "line", "=>", "/", "^\\s* ", "/", "u", ".", "test", "(", "line", ")", ")", "&&", "/", "^\\s*$", "/", "u", ".", "test", "(", "lines", "[", "lines", ".", "length", "-", "1", "]", ")", ";", "}" ]
Check a comment is JSDoc form @param {Token[]} commentGroup A group of comments, containing either multiple line comments or a single block comment @returns {boolean} if commentGroup is JSDoc form, return true
[ "Check", "a", "comment", "is", "JSDoc", "form" ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/multiline-comment-style.js#L102-L109
train
eslint/eslint
lib/code-path-analysis/code-path-analyzer.js
isIdentifierReference
function isIdentifierReference(node) { const parent = node.parent; switch (parent.type) { case "LabeledStatement": case "BreakStatement": case "ContinueStatement": case "ArrayPattern": case "RestElement": case "ImportSpecifier": case "ImportDefaultSpecifier": case "ImportNamespaceSpecifier": case "CatchClause": return false; case "FunctionDeclaration": case "FunctionExpression": case "ArrowFunctionExpression": case "ClassDeclaration": case "ClassExpression": case "VariableDeclarator": return parent.id !== node; case "Property": case "MethodDefinition": return ( parent.key !== node || parent.computed || parent.shorthand ); case "AssignmentPattern": return parent.key !== node; default: return true; } }
javascript
function isIdentifierReference(node) { const parent = node.parent; switch (parent.type) { case "LabeledStatement": case "BreakStatement": case "ContinueStatement": case "ArrayPattern": case "RestElement": case "ImportSpecifier": case "ImportDefaultSpecifier": case "ImportNamespaceSpecifier": case "CatchClause": return false; case "FunctionDeclaration": case "FunctionExpression": case "ArrowFunctionExpression": case "ClassDeclaration": case "ClassExpression": case "VariableDeclarator": return parent.id !== node; case "Property": case "MethodDefinition": return ( parent.key !== node || parent.computed || parent.shorthand ); case "AssignmentPattern": return parent.key !== node; default: return true; } }
[ "function", "isIdentifierReference", "(", "node", ")", "{", "const", "parent", "=", "node", ".", "parent", ";", "switch", "(", "parent", ".", "type", ")", "{", "case", "\"LabeledStatement\"", ":", "case", "\"BreakStatement\"", ":", "case", "\"ContinueStatement\"", ":", "case", "\"ArrayPattern\"", ":", "case", "\"RestElement\"", ":", "case", "\"ImportSpecifier\"", ":", "case", "\"ImportDefaultSpecifier\"", ":", "case", "\"ImportNamespaceSpecifier\"", ":", "case", "\"CatchClause\"", ":", "return", "false", ";", "case", "\"FunctionDeclaration\"", ":", "case", "\"FunctionExpression\"", ":", "case", "\"ArrowFunctionExpression\"", ":", "case", "\"ClassDeclaration\"", ":", "case", "\"ClassExpression\"", ":", "case", "\"VariableDeclarator\"", ":", "return", "parent", ".", "id", "!==", "node", ";", "case", "\"Property\"", ":", "case", "\"MethodDefinition\"", ":", "return", "(", "parent", ".", "key", "!==", "node", "||", "parent", ".", "computed", "||", "parent", ".", "shorthand", ")", ";", "case", "\"AssignmentPattern\"", ":", "return", "parent", ".", "key", "!==", "node", ";", "default", ":", "return", "true", ";", "}", "}" ]
Checks that a given identifier node is a reference or not. This is used to detect the first throwable node in a `try` block. @param {ASTNode} node - An Identifier node to check. @returns {boolean} `true` if the node is a reference.
[ "Checks", "that", "a", "given", "identifier", "node", "is", "a", "reference", "or", "not", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/code-path-analysis/code-path-analyzer.js#L96-L133
train
eslint/eslint
lib/code-path-analysis/code-path-analyzer.js
leaveFromCurrentSegment
function leaveFromCurrentSegment(analyzer, node) { const state = CodePath.getState(analyzer.codePath); const currentSegments = state.currentSegments; for (let i = 0; i < currentSegments.length; ++i) { const currentSegment = currentSegments[i]; debug.dump(`onCodePathSegmentEnd ${currentSegment.id}`); if (currentSegment.reachable) { analyzer.emitter.emit( "onCodePathSegmentEnd", currentSegment, node ); } } state.currentSegments = []; }
javascript
function leaveFromCurrentSegment(analyzer, node) { const state = CodePath.getState(analyzer.codePath); const currentSegments = state.currentSegments; for (let i = 0; i < currentSegments.length; ++i) { const currentSegment = currentSegments[i]; debug.dump(`onCodePathSegmentEnd ${currentSegment.id}`); if (currentSegment.reachable) { analyzer.emitter.emit( "onCodePathSegmentEnd", currentSegment, node ); } } state.currentSegments = []; }
[ "function", "leaveFromCurrentSegment", "(", "analyzer", ",", "node", ")", "{", "const", "state", "=", "CodePath", ".", "getState", "(", "analyzer", ".", "codePath", ")", ";", "const", "currentSegments", "=", "state", ".", "currentSegments", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "currentSegments", ".", "length", ";", "++", "i", ")", "{", "const", "currentSegment", "=", "currentSegments", "[", "i", "]", ";", "debug", ".", "dump", "(", "`", "${", "currentSegment", ".", "id", "}", "`", ")", ";", "if", "(", "currentSegment", ".", "reachable", ")", "{", "analyzer", ".", "emitter", ".", "emit", "(", "\"onCodePathSegmentEnd\"", ",", "currentSegment", ",", "node", ")", ";", "}", "}", "state", ".", "currentSegments", "=", "[", "]", ";", "}" ]
Updates the current segment with empty. This is called at the last of functions or the program. @param {CodePathAnalyzer} analyzer - The instance. @param {ASTNode} node - The current AST node. @returns {void}
[ "Updates", "the", "current", "segment", "with", "empty", ".", "This", "is", "called", "at", "the", "last", "of", "functions", "or", "the", "program", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/code-path-analysis/code-path-analyzer.js#L206-L224
train
eslint/eslint
lib/code-path-analysis/code-path-analyzer.js
preprocess
function preprocess(analyzer, node) { const codePath = analyzer.codePath; const state = CodePath.getState(codePath); const parent = node.parent; switch (parent.type) { case "LogicalExpression": if ( parent.right === node && isHandledLogicalOperator(parent.operator) ) { state.makeLogicalRight(); } break; case "ConditionalExpression": case "IfStatement": /* * Fork if this node is at `consequent`/`alternate`. * `popForkContext()` exists at `IfStatement:exit` and * `ConditionalExpression:exit`. */ if (parent.consequent === node) { state.makeIfConsequent(); } else if (parent.alternate === node) { state.makeIfAlternate(); } break; case "SwitchCase": if (parent.consequent[0] === node) { state.makeSwitchCaseBody(false, !parent.test); } break; case "TryStatement": if (parent.handler === node) { state.makeCatchBlock(); } else if (parent.finalizer === node) { state.makeFinallyBlock(); } break; case "WhileStatement": if (parent.test === node) { state.makeWhileTest(getBooleanValueIfSimpleConstant(node)); } else { assert(parent.body === node); state.makeWhileBody(); } break; case "DoWhileStatement": if (parent.body === node) { state.makeDoWhileBody(); } else { assert(parent.test === node); state.makeDoWhileTest(getBooleanValueIfSimpleConstant(node)); } break; case "ForStatement": if (parent.test === node) { state.makeForTest(getBooleanValueIfSimpleConstant(node)); } else if (parent.update === node) { state.makeForUpdate(); } else if (parent.body === node) { state.makeForBody(); } break; case "ForInStatement": case "ForOfStatement": if (parent.left === node) { state.makeForInOfLeft(); } else if (parent.right === node) { state.makeForInOfRight(); } else { assert(parent.body === node); state.makeForInOfBody(); } break; case "AssignmentPattern": /* * Fork if this node is at `right`. * `left` is executed always, so it uses the current path. * `popForkContext()` exists at `AssignmentPattern:exit`. */ if (parent.right === node) { state.pushForkContext(); state.forkBypassPath(); state.forkPath(); } break; default: break; } }
javascript
function preprocess(analyzer, node) { const codePath = analyzer.codePath; const state = CodePath.getState(codePath); const parent = node.parent; switch (parent.type) { case "LogicalExpression": if ( parent.right === node && isHandledLogicalOperator(parent.operator) ) { state.makeLogicalRight(); } break; case "ConditionalExpression": case "IfStatement": /* * Fork if this node is at `consequent`/`alternate`. * `popForkContext()` exists at `IfStatement:exit` and * `ConditionalExpression:exit`. */ if (parent.consequent === node) { state.makeIfConsequent(); } else if (parent.alternate === node) { state.makeIfAlternate(); } break; case "SwitchCase": if (parent.consequent[0] === node) { state.makeSwitchCaseBody(false, !parent.test); } break; case "TryStatement": if (parent.handler === node) { state.makeCatchBlock(); } else if (parent.finalizer === node) { state.makeFinallyBlock(); } break; case "WhileStatement": if (parent.test === node) { state.makeWhileTest(getBooleanValueIfSimpleConstant(node)); } else { assert(parent.body === node); state.makeWhileBody(); } break; case "DoWhileStatement": if (parent.body === node) { state.makeDoWhileBody(); } else { assert(parent.test === node); state.makeDoWhileTest(getBooleanValueIfSimpleConstant(node)); } break; case "ForStatement": if (parent.test === node) { state.makeForTest(getBooleanValueIfSimpleConstant(node)); } else if (parent.update === node) { state.makeForUpdate(); } else if (parent.body === node) { state.makeForBody(); } break; case "ForInStatement": case "ForOfStatement": if (parent.left === node) { state.makeForInOfLeft(); } else if (parent.right === node) { state.makeForInOfRight(); } else { assert(parent.body === node); state.makeForInOfBody(); } break; case "AssignmentPattern": /* * Fork if this node is at `right`. * `left` is executed always, so it uses the current path. * `popForkContext()` exists at `AssignmentPattern:exit`. */ if (parent.right === node) { state.pushForkContext(); state.forkBypassPath(); state.forkPath(); } break; default: break; } }
[ "function", "preprocess", "(", "analyzer", ",", "node", ")", "{", "const", "codePath", "=", "analyzer", ".", "codePath", ";", "const", "state", "=", "CodePath", ".", "getState", "(", "codePath", ")", ";", "const", "parent", "=", "node", ".", "parent", ";", "switch", "(", "parent", ".", "type", ")", "{", "case", "\"LogicalExpression\"", ":", "if", "(", "parent", ".", "right", "===", "node", "&&", "isHandledLogicalOperator", "(", "parent", ".", "operator", ")", ")", "{", "state", ".", "makeLogicalRight", "(", ")", ";", "}", "break", ";", "case", "\"ConditionalExpression\"", ":", "case", "\"IfStatement\"", ":", "if", "(", "parent", ".", "consequent", "===", "node", ")", "{", "state", ".", "makeIfConsequent", "(", ")", ";", "}", "else", "if", "(", "parent", ".", "alternate", "===", "node", ")", "{", "state", ".", "makeIfAlternate", "(", ")", ";", "}", "break", ";", "case", "\"SwitchCase\"", ":", "if", "(", "parent", ".", "consequent", "[", "0", "]", "===", "node", ")", "{", "state", ".", "makeSwitchCaseBody", "(", "false", ",", "!", "parent", ".", "test", ")", ";", "}", "break", ";", "case", "\"TryStatement\"", ":", "if", "(", "parent", ".", "handler", "===", "node", ")", "{", "state", ".", "makeCatchBlock", "(", ")", ";", "}", "else", "if", "(", "parent", ".", "finalizer", "===", "node", ")", "{", "state", ".", "makeFinallyBlock", "(", ")", ";", "}", "break", ";", "case", "\"WhileStatement\"", ":", "if", "(", "parent", ".", "test", "===", "node", ")", "{", "state", ".", "makeWhileTest", "(", "getBooleanValueIfSimpleConstant", "(", "node", ")", ")", ";", "}", "else", "{", "assert", "(", "parent", ".", "body", "===", "node", ")", ";", "state", ".", "makeWhileBody", "(", ")", ";", "}", "break", ";", "case", "\"DoWhileStatement\"", ":", "if", "(", "parent", ".", "body", "===", "node", ")", "{", "state", ".", "makeDoWhileBody", "(", ")", ";", "}", "else", "{", "assert", "(", "parent", ".", "test", "===", "node", ")", ";", "state", ".", "makeDoWhileTest", "(", "getBooleanValueIfSimpleConstant", "(", "node", ")", ")", ";", "}", "break", ";", "case", "\"ForStatement\"", ":", "if", "(", "parent", ".", "test", "===", "node", ")", "{", "state", ".", "makeForTest", "(", "getBooleanValueIfSimpleConstant", "(", "node", ")", ")", ";", "}", "else", "if", "(", "parent", ".", "update", "===", "node", ")", "{", "state", ".", "makeForUpdate", "(", ")", ";", "}", "else", "if", "(", "parent", ".", "body", "===", "node", ")", "{", "state", ".", "makeForBody", "(", ")", ";", "}", "break", ";", "case", "\"ForInStatement\"", ":", "case", "\"ForOfStatement\"", ":", "if", "(", "parent", ".", "left", "===", "node", ")", "{", "state", ".", "makeForInOfLeft", "(", ")", ";", "}", "else", "if", "(", "parent", ".", "right", "===", "node", ")", "{", "state", ".", "makeForInOfRight", "(", ")", ";", "}", "else", "{", "assert", "(", "parent", ".", "body", "===", "node", ")", ";", "state", ".", "makeForInOfBody", "(", ")", ";", "}", "break", ";", "case", "\"AssignmentPattern\"", ":", "if", "(", "parent", ".", "right", "===", "node", ")", "{", "state", ".", "pushForkContext", "(", ")", ";", "state", ".", "forkBypassPath", "(", ")", ";", "state", ".", "forkPath", "(", ")", ";", "}", "break", ";", "default", ":", "break", ";", "}", "}" ]
Updates the code path due to the position of a given node in the parent node thereof. For example, if the node is `parent.consequent`, this creates a fork from the current path. @param {CodePathAnalyzer} analyzer - The instance. @param {ASTNode} node - The current AST node. @returns {void}
[ "Updates", "the", "code", "path", "due", "to", "the", "position", "of", "a", "given", "node", "in", "the", "parent", "node", "thereof", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/code-path-analysis/code-path-analyzer.js#L237-L338
train
eslint/eslint
lib/code-path-analysis/code-path-analyzer.js
processCodePathToEnter
function processCodePathToEnter(analyzer, node) { let codePath = analyzer.codePath; let state = codePath && CodePath.getState(codePath); const parent = node.parent; switch (node.type) { case "Program": case "FunctionDeclaration": case "FunctionExpression": case "ArrowFunctionExpression": if (codePath) { // Emits onCodePathSegmentStart events if updated. forwardCurrentToHead(analyzer, node); debug.dumpState(node, state, false); } // Create the code path of this scope. codePath = analyzer.codePath = new CodePath( analyzer.idGenerator.next(), codePath, analyzer.onLooped ); state = CodePath.getState(codePath); // Emits onCodePathStart events. debug.dump(`onCodePathStart ${codePath.id}`); analyzer.emitter.emit("onCodePathStart", codePath, node); break; case "LogicalExpression": if (isHandledLogicalOperator(node.operator)) { state.pushChoiceContext( node.operator, isForkingByTrueOrFalse(node) ); } break; case "ConditionalExpression": case "IfStatement": state.pushChoiceContext("test", false); break; case "SwitchStatement": state.pushSwitchContext( node.cases.some(isCaseNode), astUtils.getLabel(node) ); break; case "TryStatement": state.pushTryContext(Boolean(node.finalizer)); break; case "SwitchCase": /* * Fork if this node is after the 2st node in `cases`. * It's similar to `else` blocks. * The next `test` node is processed in this path. */ if (parent.discriminant !== node && parent.cases[0] !== node) { state.forkPath(); } break; case "WhileStatement": case "DoWhileStatement": case "ForStatement": case "ForInStatement": case "ForOfStatement": state.pushLoopContext(node.type, astUtils.getLabel(node)); break; case "LabeledStatement": if (!astUtils.isBreakableStatement(node.body)) { state.pushBreakContext(false, node.label.name); } break; default: break; } // Emits onCodePathSegmentStart events if updated. forwardCurrentToHead(analyzer, node); debug.dumpState(node, state, false); }
javascript
function processCodePathToEnter(analyzer, node) { let codePath = analyzer.codePath; let state = codePath && CodePath.getState(codePath); const parent = node.parent; switch (node.type) { case "Program": case "FunctionDeclaration": case "FunctionExpression": case "ArrowFunctionExpression": if (codePath) { // Emits onCodePathSegmentStart events if updated. forwardCurrentToHead(analyzer, node); debug.dumpState(node, state, false); } // Create the code path of this scope. codePath = analyzer.codePath = new CodePath( analyzer.idGenerator.next(), codePath, analyzer.onLooped ); state = CodePath.getState(codePath); // Emits onCodePathStart events. debug.dump(`onCodePathStart ${codePath.id}`); analyzer.emitter.emit("onCodePathStart", codePath, node); break; case "LogicalExpression": if (isHandledLogicalOperator(node.operator)) { state.pushChoiceContext( node.operator, isForkingByTrueOrFalse(node) ); } break; case "ConditionalExpression": case "IfStatement": state.pushChoiceContext("test", false); break; case "SwitchStatement": state.pushSwitchContext( node.cases.some(isCaseNode), astUtils.getLabel(node) ); break; case "TryStatement": state.pushTryContext(Boolean(node.finalizer)); break; case "SwitchCase": /* * Fork if this node is after the 2st node in `cases`. * It's similar to `else` blocks. * The next `test` node is processed in this path. */ if (parent.discriminant !== node && parent.cases[0] !== node) { state.forkPath(); } break; case "WhileStatement": case "DoWhileStatement": case "ForStatement": case "ForInStatement": case "ForOfStatement": state.pushLoopContext(node.type, astUtils.getLabel(node)); break; case "LabeledStatement": if (!astUtils.isBreakableStatement(node.body)) { state.pushBreakContext(false, node.label.name); } break; default: break; } // Emits onCodePathSegmentStart events if updated. forwardCurrentToHead(analyzer, node); debug.dumpState(node, state, false); }
[ "function", "processCodePathToEnter", "(", "analyzer", ",", "node", ")", "{", "let", "codePath", "=", "analyzer", ".", "codePath", ";", "let", "state", "=", "codePath", "&&", "CodePath", ".", "getState", "(", "codePath", ")", ";", "const", "parent", "=", "node", ".", "parent", ";", "switch", "(", "node", ".", "type", ")", "{", "case", "\"Program\"", ":", "case", "\"FunctionDeclaration\"", ":", "case", "\"FunctionExpression\"", ":", "case", "\"ArrowFunctionExpression\"", ":", "if", "(", "codePath", ")", "{", "forwardCurrentToHead", "(", "analyzer", ",", "node", ")", ";", "debug", ".", "dumpState", "(", "node", ",", "state", ",", "false", ")", ";", "}", "codePath", "=", "analyzer", ".", "codePath", "=", "new", "CodePath", "(", "analyzer", ".", "idGenerator", ".", "next", "(", ")", ",", "codePath", ",", "analyzer", ".", "onLooped", ")", ";", "state", "=", "CodePath", ".", "getState", "(", "codePath", ")", ";", "debug", ".", "dump", "(", "`", "${", "codePath", ".", "id", "}", "`", ")", ";", "analyzer", ".", "emitter", ".", "emit", "(", "\"onCodePathStart\"", ",", "codePath", ",", "node", ")", ";", "break", ";", "case", "\"LogicalExpression\"", ":", "if", "(", "isHandledLogicalOperator", "(", "node", ".", "operator", ")", ")", "{", "state", ".", "pushChoiceContext", "(", "node", ".", "operator", ",", "isForkingByTrueOrFalse", "(", "node", ")", ")", ";", "}", "break", ";", "case", "\"ConditionalExpression\"", ":", "case", "\"IfStatement\"", ":", "state", ".", "pushChoiceContext", "(", "\"test\"", ",", "false", ")", ";", "break", ";", "case", "\"SwitchStatement\"", ":", "state", ".", "pushSwitchContext", "(", "node", ".", "cases", ".", "some", "(", "isCaseNode", ")", ",", "astUtils", ".", "getLabel", "(", "node", ")", ")", ";", "break", ";", "case", "\"TryStatement\"", ":", "state", ".", "pushTryContext", "(", "Boolean", "(", "node", ".", "finalizer", ")", ")", ";", "break", ";", "case", "\"SwitchCase\"", ":", "if", "(", "parent", ".", "discriminant", "!==", "node", "&&", "parent", ".", "cases", "[", "0", "]", "!==", "node", ")", "{", "state", ".", "forkPath", "(", ")", ";", "}", "break", ";", "case", "\"WhileStatement\"", ":", "case", "\"DoWhileStatement\"", ":", "case", "\"ForStatement\"", ":", "case", "\"ForInStatement\"", ":", "case", "\"ForOfStatement\"", ":", "state", ".", "pushLoopContext", "(", "node", ".", "type", ",", "astUtils", ".", "getLabel", "(", "node", ")", ")", ";", "break", ";", "case", "\"LabeledStatement\"", ":", "if", "(", "!", "astUtils", ".", "isBreakableStatement", "(", "node", ".", "body", ")", ")", "{", "state", ".", "pushBreakContext", "(", "false", ",", "node", ".", "label", ".", "name", ")", ";", "}", "break", ";", "default", ":", "break", ";", "}", "forwardCurrentToHead", "(", "analyzer", ",", "node", ")", ";", "debug", ".", "dumpState", "(", "node", ",", "state", ",", "false", ")", ";", "}" ]
Updates the code path due to the type of a given node in entering. @param {CodePathAnalyzer} analyzer - The instance. @param {ASTNode} node - The current AST node. @returns {void}
[ "Updates", "the", "code", "path", "due", "to", "the", "type", "of", "a", "given", "node", "in", "entering", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/code-path-analysis/code-path-analyzer.js#L347-L435
train
eslint/eslint
lib/code-path-analysis/code-path-analyzer.js
processCodePathToExit
function processCodePathToExit(analyzer, node) { const codePath = analyzer.codePath; const state = CodePath.getState(codePath); let dontForward = false; switch (node.type) { case "IfStatement": case "ConditionalExpression": state.popChoiceContext(); break; case "LogicalExpression": if (isHandledLogicalOperator(node.operator)) { state.popChoiceContext(); } break; case "SwitchStatement": state.popSwitchContext(); break; case "SwitchCase": /* * This is the same as the process at the 1st `consequent` node in * `preprocess` function. * Must do if this `consequent` is empty. */ if (node.consequent.length === 0) { state.makeSwitchCaseBody(true, !node.test); } if (state.forkContext.reachable) { dontForward = true; } break; case "TryStatement": state.popTryContext(); break; case "BreakStatement": forwardCurrentToHead(analyzer, node); state.makeBreak(node.label && node.label.name); dontForward = true; break; case "ContinueStatement": forwardCurrentToHead(analyzer, node); state.makeContinue(node.label && node.label.name); dontForward = true; break; case "ReturnStatement": forwardCurrentToHead(analyzer, node); state.makeReturn(); dontForward = true; break; case "ThrowStatement": forwardCurrentToHead(analyzer, node); state.makeThrow(); dontForward = true; break; case "Identifier": if (isIdentifierReference(node)) { state.makeFirstThrowablePathInTryBlock(); dontForward = true; } break; case "CallExpression": case "MemberExpression": case "NewExpression": state.makeFirstThrowablePathInTryBlock(); break; case "WhileStatement": case "DoWhileStatement": case "ForStatement": case "ForInStatement": case "ForOfStatement": state.popLoopContext(); break; case "AssignmentPattern": state.popForkContext(); break; case "LabeledStatement": if (!astUtils.isBreakableStatement(node.body)) { state.popBreakContext(); } break; default: break; } // Emits onCodePathSegmentStart events if updated. if (!dontForward) { forwardCurrentToHead(analyzer, node); } debug.dumpState(node, state, true); }
javascript
function processCodePathToExit(analyzer, node) { const codePath = analyzer.codePath; const state = CodePath.getState(codePath); let dontForward = false; switch (node.type) { case "IfStatement": case "ConditionalExpression": state.popChoiceContext(); break; case "LogicalExpression": if (isHandledLogicalOperator(node.operator)) { state.popChoiceContext(); } break; case "SwitchStatement": state.popSwitchContext(); break; case "SwitchCase": /* * This is the same as the process at the 1st `consequent` node in * `preprocess` function. * Must do if this `consequent` is empty. */ if (node.consequent.length === 0) { state.makeSwitchCaseBody(true, !node.test); } if (state.forkContext.reachable) { dontForward = true; } break; case "TryStatement": state.popTryContext(); break; case "BreakStatement": forwardCurrentToHead(analyzer, node); state.makeBreak(node.label && node.label.name); dontForward = true; break; case "ContinueStatement": forwardCurrentToHead(analyzer, node); state.makeContinue(node.label && node.label.name); dontForward = true; break; case "ReturnStatement": forwardCurrentToHead(analyzer, node); state.makeReturn(); dontForward = true; break; case "ThrowStatement": forwardCurrentToHead(analyzer, node); state.makeThrow(); dontForward = true; break; case "Identifier": if (isIdentifierReference(node)) { state.makeFirstThrowablePathInTryBlock(); dontForward = true; } break; case "CallExpression": case "MemberExpression": case "NewExpression": state.makeFirstThrowablePathInTryBlock(); break; case "WhileStatement": case "DoWhileStatement": case "ForStatement": case "ForInStatement": case "ForOfStatement": state.popLoopContext(); break; case "AssignmentPattern": state.popForkContext(); break; case "LabeledStatement": if (!astUtils.isBreakableStatement(node.body)) { state.popBreakContext(); } break; default: break; } // Emits onCodePathSegmentStart events if updated. if (!dontForward) { forwardCurrentToHead(analyzer, node); } debug.dumpState(node, state, true); }
[ "function", "processCodePathToExit", "(", "analyzer", ",", "node", ")", "{", "const", "codePath", "=", "analyzer", ".", "codePath", ";", "const", "state", "=", "CodePath", ".", "getState", "(", "codePath", ")", ";", "let", "dontForward", "=", "false", ";", "switch", "(", "node", ".", "type", ")", "{", "case", "\"IfStatement\"", ":", "case", "\"ConditionalExpression\"", ":", "state", ".", "popChoiceContext", "(", ")", ";", "break", ";", "case", "\"LogicalExpression\"", ":", "if", "(", "isHandledLogicalOperator", "(", "node", ".", "operator", ")", ")", "{", "state", ".", "popChoiceContext", "(", ")", ";", "}", "break", ";", "case", "\"SwitchStatement\"", ":", "state", ".", "popSwitchContext", "(", ")", ";", "break", ";", "case", "\"SwitchCase\"", ":", "if", "(", "node", ".", "consequent", ".", "length", "===", "0", ")", "{", "state", ".", "makeSwitchCaseBody", "(", "true", ",", "!", "node", ".", "test", ")", ";", "}", "if", "(", "state", ".", "forkContext", ".", "reachable", ")", "{", "dontForward", "=", "true", ";", "}", "break", ";", "case", "\"TryStatement\"", ":", "state", ".", "popTryContext", "(", ")", ";", "break", ";", "case", "\"BreakStatement\"", ":", "forwardCurrentToHead", "(", "analyzer", ",", "node", ")", ";", "state", ".", "makeBreak", "(", "node", ".", "label", "&&", "node", ".", "label", ".", "name", ")", ";", "dontForward", "=", "true", ";", "break", ";", "case", "\"ContinueStatement\"", ":", "forwardCurrentToHead", "(", "analyzer", ",", "node", ")", ";", "state", ".", "makeContinue", "(", "node", ".", "label", "&&", "node", ".", "label", ".", "name", ")", ";", "dontForward", "=", "true", ";", "break", ";", "case", "\"ReturnStatement\"", ":", "forwardCurrentToHead", "(", "analyzer", ",", "node", ")", ";", "state", ".", "makeReturn", "(", ")", ";", "dontForward", "=", "true", ";", "break", ";", "case", "\"ThrowStatement\"", ":", "forwardCurrentToHead", "(", "analyzer", ",", "node", ")", ";", "state", ".", "makeThrow", "(", ")", ";", "dontForward", "=", "true", ";", "break", ";", "case", "\"Identifier\"", ":", "if", "(", "isIdentifierReference", "(", "node", ")", ")", "{", "state", ".", "makeFirstThrowablePathInTryBlock", "(", ")", ";", "dontForward", "=", "true", ";", "}", "break", ";", "case", "\"CallExpression\"", ":", "case", "\"MemberExpression\"", ":", "case", "\"NewExpression\"", ":", "state", ".", "makeFirstThrowablePathInTryBlock", "(", ")", ";", "break", ";", "case", "\"WhileStatement\"", ":", "case", "\"DoWhileStatement\"", ":", "case", "\"ForStatement\"", ":", "case", "\"ForInStatement\"", ":", "case", "\"ForOfStatement\"", ":", "state", ".", "popLoopContext", "(", ")", ";", "break", ";", "case", "\"AssignmentPattern\"", ":", "state", ".", "popForkContext", "(", ")", ";", "break", ";", "case", "\"LabeledStatement\"", ":", "if", "(", "!", "astUtils", ".", "isBreakableStatement", "(", "node", ".", "body", ")", ")", "{", "state", ".", "popBreakContext", "(", ")", ";", "}", "break", ";", "default", ":", "break", ";", "}", "if", "(", "!", "dontForward", ")", "{", "forwardCurrentToHead", "(", "analyzer", ",", "node", ")", ";", "}", "debug", ".", "dumpState", "(", "node", ",", "state", ",", "true", ")", ";", "}" ]
Updates the code path due to the type of a given node in leaving. @param {CodePathAnalyzer} analyzer - The instance. @param {ASTNode} node - The current AST node. @returns {void}
[ "Updates", "the", "code", "path", "due", "to", "the", "type", "of", "a", "given", "node", "in", "leaving", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/code-path-analysis/code-path-analyzer.js#L444-L548
train
eslint/eslint
lib/rules/operator-assignment.js
getOperatorToken
function getOperatorToken(node) { return sourceCode.getFirstTokenBetween(node.left, node.right, token => token.value === node.operator); }
javascript
function getOperatorToken(node) { return sourceCode.getFirstTokenBetween(node.left, node.right, token => token.value === node.operator); }
[ "function", "getOperatorToken", "(", "node", ")", "{", "return", "sourceCode", ".", "getFirstTokenBetween", "(", "node", ".", "left", ",", "node", ".", "right", ",", "token", "=>", "token", ".", "value", "===", "node", ".", "operator", ")", ";", "}" ]
Returns the operator token of an AssignmentExpression or BinaryExpression @param {ASTNode} node An AssignmentExpression or BinaryExpression node @returns {Token} The operator token in the node
[ "Returns", "the", "operator", "token", "of", "an", "AssignmentExpression", "or", "BinaryExpression" ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/operator-assignment.js#L123-L125
train
eslint/eslint
lib/rules/operator-assignment.js
verify
function verify(node) { if (node.operator !== "=" || node.right.type !== "BinaryExpression") { return; } const left = node.left; const expr = node.right; const operator = expr.operator; if (isCommutativeOperatorWithShorthand(operator) || isNonCommutativeOperatorWithShorthand(operator)) { if (same(left, expr.left)) { context.report({ node, messageId: "replaced", fix(fixer) { if (canBeFixed(left)) { const equalsToken = getOperatorToken(node); const operatorToken = getOperatorToken(expr); const leftText = sourceCode.getText().slice(node.range[0], equalsToken.range[0]); const rightText = sourceCode.getText().slice(operatorToken.range[1], node.right.range[1]); return fixer.replaceText(node, `${leftText}${expr.operator}=${rightText}`); } return null; } }); } else if (same(left, expr.right) && isCommutativeOperatorWithShorthand(operator)) { /* * This case can't be fixed safely. * If `a` and `b` both have custom valueOf() behavior, then fixing `a = b * a` to `a *= b` would * change the execution order of the valueOf() functions. */ context.report({ node, messageId: "replaced" }); } } }
javascript
function verify(node) { if (node.operator !== "=" || node.right.type !== "BinaryExpression") { return; } const left = node.left; const expr = node.right; const operator = expr.operator; if (isCommutativeOperatorWithShorthand(operator) || isNonCommutativeOperatorWithShorthand(operator)) { if (same(left, expr.left)) { context.report({ node, messageId: "replaced", fix(fixer) { if (canBeFixed(left)) { const equalsToken = getOperatorToken(node); const operatorToken = getOperatorToken(expr); const leftText = sourceCode.getText().slice(node.range[0], equalsToken.range[0]); const rightText = sourceCode.getText().slice(operatorToken.range[1], node.right.range[1]); return fixer.replaceText(node, `${leftText}${expr.operator}=${rightText}`); } return null; } }); } else if (same(left, expr.right) && isCommutativeOperatorWithShorthand(operator)) { /* * This case can't be fixed safely. * If `a` and `b` both have custom valueOf() behavior, then fixing `a = b * a` to `a *= b` would * change the execution order of the valueOf() functions. */ context.report({ node, messageId: "replaced" }); } } }
[ "function", "verify", "(", "node", ")", "{", "if", "(", "node", ".", "operator", "!==", "\"=\"", "||", "node", ".", "right", ".", "type", "!==", "\"BinaryExpression\"", ")", "{", "return", ";", "}", "const", "left", "=", "node", ".", "left", ";", "const", "expr", "=", "node", ".", "right", ";", "const", "operator", "=", "expr", ".", "operator", ";", "if", "(", "isCommutativeOperatorWithShorthand", "(", "operator", ")", "||", "isNonCommutativeOperatorWithShorthand", "(", "operator", ")", ")", "{", "if", "(", "same", "(", "left", ",", "expr", ".", "left", ")", ")", "{", "context", ".", "report", "(", "{", "node", ",", "messageId", ":", "\"replaced\"", ",", "fix", "(", "fixer", ")", "{", "if", "(", "canBeFixed", "(", "left", ")", ")", "{", "const", "equalsToken", "=", "getOperatorToken", "(", "node", ")", ";", "const", "operatorToken", "=", "getOperatorToken", "(", "expr", ")", ";", "const", "leftText", "=", "sourceCode", ".", "getText", "(", ")", ".", "slice", "(", "node", ".", "range", "[", "0", "]", ",", "equalsToken", ".", "range", "[", "0", "]", ")", ";", "const", "rightText", "=", "sourceCode", ".", "getText", "(", ")", ".", "slice", "(", "operatorToken", ".", "range", "[", "1", "]", ",", "node", ".", "right", ".", "range", "[", "1", "]", ")", ";", "return", "fixer", ".", "replaceText", "(", "node", ",", "`", "${", "leftText", "}", "${", "expr", ".", "operator", "}", "${", "rightText", "}", "`", ")", ";", "}", "return", "null", ";", "}", "}", ")", ";", "}", "else", "if", "(", "same", "(", "left", ",", "expr", ".", "right", ")", "&&", "isCommutativeOperatorWithShorthand", "(", "operator", ")", ")", "{", "context", ".", "report", "(", "{", "node", ",", "messageId", ":", "\"replaced\"", "}", ")", ";", "}", "}", "}" ]
Ensures that an assignment uses the shorthand form where possible. @param {ASTNode} node An AssignmentExpression node. @returns {void}
[ "Ensures", "that", "an", "assignment", "uses", "the", "shorthand", "form", "where", "possible", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/operator-assignment.js#L132-L171
train
eslint/eslint
lib/rules/operator-assignment.js
prohibit
function prohibit(node) { if (node.operator !== "=") { context.report({ node, messageId: "unexpected", fix(fixer) { if (canBeFixed(node.left)) { const operatorToken = getOperatorToken(node); const leftText = sourceCode.getText().slice(node.range[0], operatorToken.range[0]); const newOperator = node.operator.slice(0, -1); let rightText; // If this change would modify precedence (e.g. `foo *= bar + 1` => `foo = foo * (bar + 1)`), parenthesize the right side. if ( astUtils.getPrecedence(node.right) <= astUtils.getPrecedence({ type: "BinaryExpression", operator: newOperator }) && !astUtils.isParenthesised(sourceCode, node.right) ) { rightText = `${sourceCode.text.slice(operatorToken.range[1], node.right.range[0])}(${sourceCode.getText(node.right)})`; } else { rightText = sourceCode.text.slice(operatorToken.range[1], node.range[1]); } return fixer.replaceText(node, `${leftText}= ${leftText}${newOperator}${rightText}`); } return null; } }); } }
javascript
function prohibit(node) { if (node.operator !== "=") { context.report({ node, messageId: "unexpected", fix(fixer) { if (canBeFixed(node.left)) { const operatorToken = getOperatorToken(node); const leftText = sourceCode.getText().slice(node.range[0], operatorToken.range[0]); const newOperator = node.operator.slice(0, -1); let rightText; // If this change would modify precedence (e.g. `foo *= bar + 1` => `foo = foo * (bar + 1)`), parenthesize the right side. if ( astUtils.getPrecedence(node.right) <= astUtils.getPrecedence({ type: "BinaryExpression", operator: newOperator }) && !astUtils.isParenthesised(sourceCode, node.right) ) { rightText = `${sourceCode.text.slice(operatorToken.range[1], node.right.range[0])}(${sourceCode.getText(node.right)})`; } else { rightText = sourceCode.text.slice(operatorToken.range[1], node.range[1]); } return fixer.replaceText(node, `${leftText}= ${leftText}${newOperator}${rightText}`); } return null; } }); } }
[ "function", "prohibit", "(", "node", ")", "{", "if", "(", "node", ".", "operator", "!==", "\"=\"", ")", "{", "context", ".", "report", "(", "{", "node", ",", "messageId", ":", "\"unexpected\"", ",", "fix", "(", "fixer", ")", "{", "if", "(", "canBeFixed", "(", "node", ".", "left", ")", ")", "{", "const", "operatorToken", "=", "getOperatorToken", "(", "node", ")", ";", "const", "leftText", "=", "sourceCode", ".", "getText", "(", ")", ".", "slice", "(", "node", ".", "range", "[", "0", "]", ",", "operatorToken", ".", "range", "[", "0", "]", ")", ";", "const", "newOperator", "=", "node", ".", "operator", ".", "slice", "(", "0", ",", "-", "1", ")", ";", "let", "rightText", ";", "if", "(", "astUtils", ".", "getPrecedence", "(", "node", ".", "right", ")", "<=", "astUtils", ".", "getPrecedence", "(", "{", "type", ":", "\"BinaryExpression\"", ",", "operator", ":", "newOperator", "}", ")", "&&", "!", "astUtils", ".", "isParenthesised", "(", "sourceCode", ",", "node", ".", "right", ")", ")", "{", "rightText", "=", "`", "${", "sourceCode", ".", "text", ".", "slice", "(", "operatorToken", ".", "range", "[", "1", "]", ",", "node", ".", "right", ".", "range", "[", "0", "]", ")", "}", "${", "sourceCode", ".", "getText", "(", "node", ".", "right", ")", "}", "`", ";", "}", "else", "{", "rightText", "=", "sourceCode", ".", "text", ".", "slice", "(", "operatorToken", ".", "range", "[", "1", "]", ",", "node", ".", "range", "[", "1", "]", ")", ";", "}", "return", "fixer", ".", "replaceText", "(", "node", ",", "`", "${", "leftText", "}", "${", "leftText", "}", "${", "newOperator", "}", "${", "rightText", "}", "`", ")", ";", "}", "return", "null", ";", "}", "}", ")", ";", "}", "}" ]
Warns if an assignment expression uses operator assignment shorthand. @param {ASTNode} node An AssignmentExpression node. @returns {void}
[ "Warns", "if", "an", "assignment", "expression", "uses", "operator", "assignment", "shorthand", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/operator-assignment.js#L178-L206
train
eslint/eslint
lib/rules/function-paren-newline.js
validateArguments
function validateArguments(parens, elements) { const leftParen = parens.leftParen; const tokenAfterLeftParen = sourceCode.getTokenAfter(leftParen); const hasLeftNewline = !astUtils.isTokenOnSameLine(leftParen, tokenAfterLeftParen); const needsNewlines = shouldHaveNewlines(elements, hasLeftNewline); for (let i = 0; i <= elements.length - 2; i++) { const currentElement = elements[i]; const nextElement = elements[i + 1]; const hasNewLine = currentElement.loc.end.line !== nextElement.loc.start.line; if (!hasNewLine && needsNewlines) { context.report({ node: currentElement, messageId: "expectedBetween", fix: fixer => fixer.insertTextBefore(nextElement, "\n") }); } } }
javascript
function validateArguments(parens, elements) { const leftParen = parens.leftParen; const tokenAfterLeftParen = sourceCode.getTokenAfter(leftParen); const hasLeftNewline = !astUtils.isTokenOnSameLine(leftParen, tokenAfterLeftParen); const needsNewlines = shouldHaveNewlines(elements, hasLeftNewline); for (let i = 0; i <= elements.length - 2; i++) { const currentElement = elements[i]; const nextElement = elements[i + 1]; const hasNewLine = currentElement.loc.end.line !== nextElement.loc.start.line; if (!hasNewLine && needsNewlines) { context.report({ node: currentElement, messageId: "expectedBetween", fix: fixer => fixer.insertTextBefore(nextElement, "\n") }); } } }
[ "function", "validateArguments", "(", "parens", ",", "elements", ")", "{", "const", "leftParen", "=", "parens", ".", "leftParen", ";", "const", "tokenAfterLeftParen", "=", "sourceCode", ".", "getTokenAfter", "(", "leftParen", ")", ";", "const", "hasLeftNewline", "=", "!", "astUtils", ".", "isTokenOnSameLine", "(", "leftParen", ",", "tokenAfterLeftParen", ")", ";", "const", "needsNewlines", "=", "shouldHaveNewlines", "(", "elements", ",", "hasLeftNewline", ")", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<=", "elements", ".", "length", "-", "2", ";", "i", "++", ")", "{", "const", "currentElement", "=", "elements", "[", "i", "]", ";", "const", "nextElement", "=", "elements", "[", "i", "+", "1", "]", ";", "const", "hasNewLine", "=", "currentElement", ".", "loc", ".", "end", ".", "line", "!==", "nextElement", ".", "loc", ".", "start", ".", "line", ";", "if", "(", "!", "hasNewLine", "&&", "needsNewlines", ")", "{", "context", ".", "report", "(", "{", "node", ":", "currentElement", ",", "messageId", ":", "\"expectedBetween\"", ",", "fix", ":", "fixer", "=>", "fixer", ".", "insertTextBefore", "(", "nextElement", ",", "\"\\n\"", ")", "}", ")", ";", "}", "}", "}" ]
Validates a list of arguments or parameters @param {Object} parens An object with keys `leftParen` for the left paren token, and `rightParen` for the right paren token @param {ASTNode[]} elements The arguments or parameters in the list @returns {void}
[ "Validates", "a", "list", "of", "arguments", "or", "parameters" ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/function-paren-newline.js#L162-L181
train
eslint/eslint
lib/rules/function-paren-newline.js
getParenTokens
function getParenTokens(node) { switch (node.type) { case "NewExpression": if (!node.arguments.length && !( astUtils.isOpeningParenToken(sourceCode.getLastToken(node, { skip: 1 })) && astUtils.isClosingParenToken(sourceCode.getLastToken(node)) )) { // If the NewExpression does not have parens (e.g. `new Foo`), return null. return null; } // falls through case "CallExpression": return { leftParen: sourceCode.getTokenAfter(node.callee, astUtils.isOpeningParenToken), rightParen: sourceCode.getLastToken(node) }; case "FunctionDeclaration": case "FunctionExpression": { const leftParen = sourceCode.getFirstToken(node, astUtils.isOpeningParenToken); const rightParen = node.params.length ? sourceCode.getTokenAfter(node.params[node.params.length - 1], astUtils.isClosingParenToken) : sourceCode.getTokenAfter(leftParen); return { leftParen, rightParen }; } case "ArrowFunctionExpression": { const firstToken = sourceCode.getFirstToken(node); if (!astUtils.isOpeningParenToken(firstToken)) { // If the ArrowFunctionExpression has a single param without parens, return null. return null; } return { leftParen: firstToken, rightParen: sourceCode.getTokenBefore(node.body, astUtils.isClosingParenToken) }; } default: throw new TypeError(`unexpected node with type ${node.type}`); } }
javascript
function getParenTokens(node) { switch (node.type) { case "NewExpression": if (!node.arguments.length && !( astUtils.isOpeningParenToken(sourceCode.getLastToken(node, { skip: 1 })) && astUtils.isClosingParenToken(sourceCode.getLastToken(node)) )) { // If the NewExpression does not have parens (e.g. `new Foo`), return null. return null; } // falls through case "CallExpression": return { leftParen: sourceCode.getTokenAfter(node.callee, astUtils.isOpeningParenToken), rightParen: sourceCode.getLastToken(node) }; case "FunctionDeclaration": case "FunctionExpression": { const leftParen = sourceCode.getFirstToken(node, astUtils.isOpeningParenToken); const rightParen = node.params.length ? sourceCode.getTokenAfter(node.params[node.params.length - 1], astUtils.isClosingParenToken) : sourceCode.getTokenAfter(leftParen); return { leftParen, rightParen }; } case "ArrowFunctionExpression": { const firstToken = sourceCode.getFirstToken(node); if (!astUtils.isOpeningParenToken(firstToken)) { // If the ArrowFunctionExpression has a single param without parens, return null. return null; } return { leftParen: firstToken, rightParen: sourceCode.getTokenBefore(node.body, astUtils.isClosingParenToken) }; } default: throw new TypeError(`unexpected node with type ${node.type}`); } }
[ "function", "getParenTokens", "(", "node", ")", "{", "switch", "(", "node", ".", "type", ")", "{", "case", "\"NewExpression\"", ":", "if", "(", "!", "node", ".", "arguments", ".", "length", "&&", "!", "(", "astUtils", ".", "isOpeningParenToken", "(", "sourceCode", ".", "getLastToken", "(", "node", ",", "{", "skip", ":", "1", "}", ")", ")", "&&", "astUtils", ".", "isClosingParenToken", "(", "sourceCode", ".", "getLastToken", "(", "node", ")", ")", ")", ")", "{", "return", "null", ";", "}", "case", "\"CallExpression\"", ":", "return", "{", "leftParen", ":", "sourceCode", ".", "getTokenAfter", "(", "node", ".", "callee", ",", "astUtils", ".", "isOpeningParenToken", ")", ",", "rightParen", ":", "sourceCode", ".", "getLastToken", "(", "node", ")", "}", ";", "case", "\"FunctionDeclaration\"", ":", "case", "\"FunctionExpression\"", ":", "{", "const", "leftParen", "=", "sourceCode", ".", "getFirstToken", "(", "node", ",", "astUtils", ".", "isOpeningParenToken", ")", ";", "const", "rightParen", "=", "node", ".", "params", ".", "length", "?", "sourceCode", ".", "getTokenAfter", "(", "node", ".", "params", "[", "node", ".", "params", ".", "length", "-", "1", "]", ",", "astUtils", ".", "isClosingParenToken", ")", ":", "sourceCode", ".", "getTokenAfter", "(", "leftParen", ")", ";", "return", "{", "leftParen", ",", "rightParen", "}", ";", "}", "case", "\"ArrowFunctionExpression\"", ":", "{", "const", "firstToken", "=", "sourceCode", ".", "getFirstToken", "(", "node", ")", ";", "if", "(", "!", "astUtils", ".", "isOpeningParenToken", "(", "firstToken", ")", ")", "{", "return", "null", ";", "}", "return", "{", "leftParen", ":", "firstToken", ",", "rightParen", ":", "sourceCode", ".", "getTokenBefore", "(", "node", ".", "body", ",", "astUtils", ".", "isClosingParenToken", ")", "}", ";", "}", "default", ":", "throw", "new", "TypeError", "(", "`", "${", "node", ".", "type", "}", "`", ")", ";", "}", "}" ]
Gets the left paren and right paren tokens of a node. @param {ASTNode} node The node with parens @returns {Object} An object with keys `leftParen` for the left paren token, and `rightParen` for the right paren token. Can also return `null` if an expression has no parens (e.g. a NewExpression with no arguments, or an ArrowFunctionExpression with a single parameter)
[ "Gets", "the", "left", "paren", "and", "right", "paren", "tokens", "of", "a", "node", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/function-paren-newline.js#L190-L238
train
eslint/eslint
lib/rules/function-paren-newline.js
validateNode
function validateNode(node) { const parens = getParenTokens(node); if (parens) { validateParens(parens, astUtils.isFunction(node) ? node.params : node.arguments); if (multilineArgumentsOption) { validateArguments(parens, astUtils.isFunction(node) ? node.params : node.arguments); } } }
javascript
function validateNode(node) { const parens = getParenTokens(node); if (parens) { validateParens(parens, astUtils.isFunction(node) ? node.params : node.arguments); if (multilineArgumentsOption) { validateArguments(parens, astUtils.isFunction(node) ? node.params : node.arguments); } } }
[ "function", "validateNode", "(", "node", ")", "{", "const", "parens", "=", "getParenTokens", "(", "node", ")", ";", "if", "(", "parens", ")", "{", "validateParens", "(", "parens", ",", "astUtils", ".", "isFunction", "(", "node", ")", "?", "node", ".", "params", ":", "node", ".", "arguments", ")", ";", "if", "(", "multilineArgumentsOption", ")", "{", "validateArguments", "(", "parens", ",", "astUtils", ".", "isFunction", "(", "node", ")", "?", "node", ".", "params", ":", "node", ".", "arguments", ")", ";", "}", "}", "}" ]
Validates the parentheses for a node @param {ASTNode} node The node with parens @returns {void}
[ "Validates", "the", "parentheses", "for", "a", "node" ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/function-paren-newline.js#L245-L255
train
eslint/eslint
lib/rules/no-unused-vars.js
getDefinedMessage
function getDefinedMessage(unusedVar) { const defType = unusedVar.defs && unusedVar.defs[0] && unusedVar.defs[0].type; let type; let pattern; if (defType === "CatchClause" && config.caughtErrorsIgnorePattern) { type = "args"; pattern = config.caughtErrorsIgnorePattern.toString(); } else if (defType === "Parameter" && config.argsIgnorePattern) { type = "args"; pattern = config.argsIgnorePattern.toString(); } else if (defType !== "Parameter" && config.varsIgnorePattern) { type = "vars"; pattern = config.varsIgnorePattern.toString(); } const additional = type ? ` Allowed unused ${type} must match ${pattern}.` : ""; return `'{{name}}' is defined but never used.${additional}`; }
javascript
function getDefinedMessage(unusedVar) { const defType = unusedVar.defs && unusedVar.defs[0] && unusedVar.defs[0].type; let type; let pattern; if (defType === "CatchClause" && config.caughtErrorsIgnorePattern) { type = "args"; pattern = config.caughtErrorsIgnorePattern.toString(); } else if (defType === "Parameter" && config.argsIgnorePattern) { type = "args"; pattern = config.argsIgnorePattern.toString(); } else if (defType !== "Parameter" && config.varsIgnorePattern) { type = "vars"; pattern = config.varsIgnorePattern.toString(); } const additional = type ? ` Allowed unused ${type} must match ${pattern}.` : ""; return `'{{name}}' is defined but never used.${additional}`; }
[ "function", "getDefinedMessage", "(", "unusedVar", ")", "{", "const", "defType", "=", "unusedVar", ".", "defs", "&&", "unusedVar", ".", "defs", "[", "0", "]", "&&", "unusedVar", ".", "defs", "[", "0", "]", ".", "type", ";", "let", "type", ";", "let", "pattern", ";", "if", "(", "defType", "===", "\"CatchClause\"", "&&", "config", ".", "caughtErrorsIgnorePattern", ")", "{", "type", "=", "\"args\"", ";", "pattern", "=", "config", ".", "caughtErrorsIgnorePattern", ".", "toString", "(", ")", ";", "}", "else", "if", "(", "defType", "===", "\"Parameter\"", "&&", "config", ".", "argsIgnorePattern", ")", "{", "type", "=", "\"args\"", ";", "pattern", "=", "config", ".", "argsIgnorePattern", ".", "toString", "(", ")", ";", "}", "else", "if", "(", "defType", "!==", "\"Parameter\"", "&&", "config", ".", "varsIgnorePattern", ")", "{", "type", "=", "\"vars\"", ";", "pattern", "=", "config", ".", "varsIgnorePattern", ".", "toString", "(", ")", ";", "}", "const", "additional", "=", "type", "?", "`", "${", "type", "}", "${", "pattern", "}", "`", ":", "\"\"", ";", "return", "`", "${", "additional", "}", "`", ";", "}" ]
Generate the warning message about the variable being defined and unused, including the ignore pattern if configured. @param {Variable} unusedVar - eslint-scope variable object. @returns {string} The warning message to be used with this unused variable.
[ "Generate", "the", "warning", "message", "about", "the", "variable", "being", "defined", "and", "unused", "including", "the", "ignore", "pattern", "if", "configured", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-unused-vars.js#L109-L128
train
eslint/eslint
lib/rules/no-unused-vars.js
hasRestSpreadSibling
function hasRestSpreadSibling(variable) { if (config.ignoreRestSiblings) { return variable.defs.some(def => { const propertyNode = def.name.parent; const patternNode = propertyNode.parent; return ( propertyNode.type === "Property" && patternNode.type === "ObjectPattern" && REST_PROPERTY_TYPE.test(patternNode.properties[patternNode.properties.length - 1].type) ); }); } return false; }
javascript
function hasRestSpreadSibling(variable) { if (config.ignoreRestSiblings) { return variable.defs.some(def => { const propertyNode = def.name.parent; const patternNode = propertyNode.parent; return ( propertyNode.type === "Property" && patternNode.type === "ObjectPattern" && REST_PROPERTY_TYPE.test(patternNode.properties[patternNode.properties.length - 1].type) ); }); } return false; }
[ "function", "hasRestSpreadSibling", "(", "variable", ")", "{", "if", "(", "config", ".", "ignoreRestSiblings", ")", "{", "return", "variable", ".", "defs", ".", "some", "(", "def", "=>", "{", "const", "propertyNode", "=", "def", ".", "name", ".", "parent", ";", "const", "patternNode", "=", "propertyNode", ".", "parent", ";", "return", "(", "propertyNode", ".", "type", "===", "\"Property\"", "&&", "patternNode", ".", "type", "===", "\"ObjectPattern\"", "&&", "REST_PROPERTY_TYPE", ".", "test", "(", "patternNode", ".", "properties", "[", "patternNode", ".", "properties", ".", "length", "-", "1", "]", ".", "type", ")", ")", ";", "}", ")", ";", "}", "return", "false", ";", "}" ]
Determines if a variable has a sibling rest property @param {Variable} variable - eslint-scope variable object. @returns {boolean} True if the variable is exported, false if not. @private
[ "Determines", "if", "a", "variable", "has", "a", "sibling", "rest", "property" ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-unused-vars.js#L179-L194
train
eslint/eslint
lib/rules/no-unused-vars.js
isSelfReference
function isSelfReference(ref, nodes) { let scope = ref.from; while (scope) { if (nodes.indexOf(scope.block) >= 0) { return true; } scope = scope.upper; } return false; }
javascript
function isSelfReference(ref, nodes) { let scope = ref.from; while (scope) { if (nodes.indexOf(scope.block) >= 0) { return true; } scope = scope.upper; } return false; }
[ "function", "isSelfReference", "(", "ref", ",", "nodes", ")", "{", "let", "scope", "=", "ref", ".", "from", ";", "while", "(", "scope", ")", "{", "if", "(", "nodes", ".", "indexOf", "(", "scope", ".", "block", ")", ">=", "0", ")", "{", "return", "true", ";", "}", "scope", "=", "scope", ".", "upper", ";", "}", "return", "false", ";", "}" ]
Determine if an identifier is referencing an enclosing function name. @param {Reference} ref - The reference to check. @param {ASTNode[]} nodes - The candidate function nodes. @returns {boolean} True if it's a self-reference, false if not. @private
[ "Determine", "if", "an", "identifier", "is", "referencing", "an", "enclosing", "function", "name", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-unused-vars.js#L213-L225
train
eslint/eslint
lib/rules/no-unused-vars.js
getFunctionDefinitions
function getFunctionDefinitions(variable) { const functionDefinitions = []; variable.defs.forEach(def => { const { type, node } = def; // FunctionDeclarations if (type === "FunctionName") { functionDefinitions.push(node); } // FunctionExpressions if (type === "Variable" && node.init && (node.init.type === "FunctionExpression" || node.init.type === "ArrowFunctionExpression")) { functionDefinitions.push(node.init); } }); return functionDefinitions; }
javascript
function getFunctionDefinitions(variable) { const functionDefinitions = []; variable.defs.forEach(def => { const { type, node } = def; // FunctionDeclarations if (type === "FunctionName") { functionDefinitions.push(node); } // FunctionExpressions if (type === "Variable" && node.init && (node.init.type === "FunctionExpression" || node.init.type === "ArrowFunctionExpression")) { functionDefinitions.push(node.init); } }); return functionDefinitions; }
[ "function", "getFunctionDefinitions", "(", "variable", ")", "{", "const", "functionDefinitions", "=", "[", "]", ";", "variable", ".", "defs", ".", "forEach", "(", "def", "=>", "{", "const", "{", "type", ",", "node", "}", "=", "def", ";", "if", "(", "type", "===", "\"FunctionName\"", ")", "{", "functionDefinitions", ".", "push", "(", "node", ")", ";", "}", "if", "(", "type", "===", "\"Variable\"", "&&", "node", ".", "init", "&&", "(", "node", ".", "init", ".", "type", "===", "\"FunctionExpression\"", "||", "node", ".", "init", ".", "type", "===", "\"ArrowFunctionExpression\"", ")", ")", "{", "functionDefinitions", ".", "push", "(", "node", ".", "init", ")", ";", "}", "}", ")", ";", "return", "functionDefinitions", ";", "}" ]
Gets a list of function definitions for a specified variable. @param {Variable} variable - eslint-scope variable object. @returns {ASTNode[]} Function nodes. @private
[ "Gets", "a", "list", "of", "function", "definitions", "for", "a", "specified", "variable", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-unused-vars.js#L233-L251
train
eslint/eslint
lib/rules/no-unused-vars.js
isInside
function isInside(inner, outer) { return ( inner.range[0] >= outer.range[0] && inner.range[1] <= outer.range[1] ); }
javascript
function isInside(inner, outer) { return ( inner.range[0] >= outer.range[0] && inner.range[1] <= outer.range[1] ); }
[ "function", "isInside", "(", "inner", ",", "outer", ")", "{", "return", "(", "inner", ".", "range", "[", "0", "]", ">=", "outer", ".", "range", "[", "0", "]", "&&", "inner", ".", "range", "[", "1", "]", "<=", "outer", ".", "range", "[", "1", "]", ")", ";", "}" ]
Checks the position of given nodes. @param {ASTNode} inner - A node which is expected as inside. @param {ASTNode} outer - A node which is expected as outside. @returns {boolean} `true` if the `inner` node exists in the `outer` node. @private
[ "Checks", "the", "position", "of", "given", "nodes", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-unused-vars.js#L261-L266
train
eslint/eslint
lib/rules/no-unused-vars.js
getRhsNode
function getRhsNode(ref, prevRhsNode) { const id = ref.identifier; const parent = id.parent; const granpa = parent.parent; const refScope = ref.from.variableScope; const varScope = ref.resolved.scope.variableScope; const canBeUsedLater = refScope !== varScope || astUtils.isInLoop(id); /* * Inherits the previous node if this reference is in the node. * This is for `a = a + a`-like code. */ if (prevRhsNode && isInside(id, prevRhsNode)) { return prevRhsNode; } if (parent.type === "AssignmentExpression" && granpa.type === "ExpressionStatement" && id === parent.left && !canBeUsedLater ) { return parent.right; } return null; }
javascript
function getRhsNode(ref, prevRhsNode) { const id = ref.identifier; const parent = id.parent; const granpa = parent.parent; const refScope = ref.from.variableScope; const varScope = ref.resolved.scope.variableScope; const canBeUsedLater = refScope !== varScope || astUtils.isInLoop(id); /* * Inherits the previous node if this reference is in the node. * This is for `a = a + a`-like code. */ if (prevRhsNode && isInside(id, prevRhsNode)) { return prevRhsNode; } if (parent.type === "AssignmentExpression" && granpa.type === "ExpressionStatement" && id === parent.left && !canBeUsedLater ) { return parent.right; } return null; }
[ "function", "getRhsNode", "(", "ref", ",", "prevRhsNode", ")", "{", "const", "id", "=", "ref", ".", "identifier", ";", "const", "parent", "=", "id", ".", "parent", ";", "const", "granpa", "=", "parent", ".", "parent", ";", "const", "refScope", "=", "ref", ".", "from", ".", "variableScope", ";", "const", "varScope", "=", "ref", ".", "resolved", ".", "scope", ".", "variableScope", ";", "const", "canBeUsedLater", "=", "refScope", "!==", "varScope", "||", "astUtils", ".", "isInLoop", "(", "id", ")", ";", "if", "(", "prevRhsNode", "&&", "isInside", "(", "id", ",", "prevRhsNode", ")", ")", "{", "return", "prevRhsNode", ";", "}", "if", "(", "parent", ".", "type", "===", "\"AssignmentExpression\"", "&&", "granpa", ".", "type", "===", "\"ExpressionStatement\"", "&&", "id", "===", "parent", ".", "left", "&&", "!", "canBeUsedLater", ")", "{", "return", "parent", ".", "right", ";", "}", "return", "null", ";", "}" ]
If a given reference is left-hand side of an assignment, this gets the right-hand side node of the assignment. In the following cases, this returns null. - The reference is not the LHS of an assignment expression. - The reference is inside of a loop. - The reference is inside of a function scope which is different from the declaration. @param {eslint-scope.Reference} ref - A reference to check. @param {ASTNode} prevRhsNode - The previous RHS node. @returns {ASTNode|null} The RHS node or null. @private
[ "If", "a", "given", "reference", "is", "left", "-", "hand", "side", "of", "an", "assignment", "this", "gets", "the", "right", "-", "hand", "side", "node", "of", "the", "assignment", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-unused-vars.js#L284-L308
train
eslint/eslint
lib/rules/no-unused-vars.js
isReadForItself
function isReadForItself(ref, rhsNode) { const id = ref.identifier; const parent = id.parent; const granpa = parent.parent; return ref.isRead() && ( // self update. e.g. `a += 1`, `a++` (// in RHS of an assignment for itself. e.g. `a = a + 1` (( parent.type === "AssignmentExpression" && granpa.type === "ExpressionStatement" && parent.left === id ) || ( parent.type === "UpdateExpression" && granpa.type === "ExpressionStatement" ) || rhsNode && isInside(id, rhsNode) && !isInsideOfStorableFunction(id, rhsNode))) ); }
javascript
function isReadForItself(ref, rhsNode) { const id = ref.identifier; const parent = id.parent; const granpa = parent.parent; return ref.isRead() && ( // self update. e.g. `a += 1`, `a++` (// in RHS of an assignment for itself. e.g. `a = a + 1` (( parent.type === "AssignmentExpression" && granpa.type === "ExpressionStatement" && parent.left === id ) || ( parent.type === "UpdateExpression" && granpa.type === "ExpressionStatement" ) || rhsNode && isInside(id, rhsNode) && !isInsideOfStorableFunction(id, rhsNode))) ); }
[ "function", "isReadForItself", "(", "ref", ",", "rhsNode", ")", "{", "const", "id", "=", "ref", ".", "identifier", ";", "const", "parent", "=", "id", ".", "parent", ";", "const", "granpa", "=", "parent", ".", "parent", ";", "return", "ref", ".", "isRead", "(", ")", "&&", "(", "(", "(", "(", "parent", ".", "type", "===", "\"AssignmentExpression\"", "&&", "granpa", ".", "type", "===", "\"ExpressionStatement\"", "&&", "parent", ".", "left", "===", "id", ")", "||", "(", "parent", ".", "type", "===", "\"UpdateExpression\"", "&&", "granpa", ".", "type", "===", "\"ExpressionStatement\"", ")", "||", "rhsNode", "&&", "isInside", "(", "id", ",", "rhsNode", ")", "&&", "!", "isInsideOfStorableFunction", "(", "id", ",", "rhsNode", ")", ")", ")", ")", ";", "}" ]
Checks whether a given reference is a read to update itself or not. @param {eslint-scope.Reference} ref - A reference to check. @param {ASTNode} rhsNode - The RHS node of the previous assignment. @returns {boolean} The reference is a read to update itself. @private
[ "Checks", "whether", "a", "given", "reference", "is", "a", "read", "to", "update", "itself", "or", "not", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-unused-vars.js#L394-L415
train
eslint/eslint
lib/rules/no-unused-vars.js
isForInRef
function isForInRef(ref) { let target = ref.identifier.parent; // "for (var ...) { return; }" if (target.type === "VariableDeclarator") { target = target.parent.parent; } if (target.type !== "ForInStatement") { return false; } // "for (...) { return; }" if (target.body.type === "BlockStatement") { target = target.body.body[0]; // "for (...) return;" } else { target = target.body; } // For empty loop body if (!target) { return false; } return target.type === "ReturnStatement"; }
javascript
function isForInRef(ref) { let target = ref.identifier.parent; // "for (var ...) { return; }" if (target.type === "VariableDeclarator") { target = target.parent.parent; } if (target.type !== "ForInStatement") { return false; } // "for (...) { return; }" if (target.body.type === "BlockStatement") { target = target.body.body[0]; // "for (...) return;" } else { target = target.body; } // For empty loop body if (!target) { return false; } return target.type === "ReturnStatement"; }
[ "function", "isForInRef", "(", "ref", ")", "{", "let", "target", "=", "ref", ".", "identifier", ".", "parent", ";", "if", "(", "target", ".", "type", "===", "\"VariableDeclarator\"", ")", "{", "target", "=", "target", ".", "parent", ".", "parent", ";", "}", "if", "(", "target", ".", "type", "!==", "\"ForInStatement\"", ")", "{", "return", "false", ";", "}", "if", "(", "target", ".", "body", ".", "type", "===", "\"BlockStatement\"", ")", "{", "target", "=", "target", ".", "body", ".", "body", "[", "0", "]", ";", "}", "else", "{", "target", "=", "target", ".", "body", ";", "}", "if", "(", "!", "target", ")", "{", "return", "false", ";", "}", "return", "target", ".", "type", "===", "\"ReturnStatement\"", ";", "}" ]
Determine if an identifier is used either in for-in loops. @param {Reference} ref - The reference to check. @returns {boolean} whether reference is used in the for-in loops @private
[ "Determine", "if", "an", "identifier", "is", "used", "either", "in", "for", "-", "in", "loops", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-unused-vars.js#L424-L452
train
eslint/eslint
lib/rules/no-unused-vars.js
isAfterLastUsedArg
function isAfterLastUsedArg(variable) { const def = variable.defs[0]; const params = context.getDeclaredVariables(def.node); const posteriorParams = params.slice(params.indexOf(variable) + 1); // If any used parameters occur after this parameter, do not report. return !posteriorParams.some(v => v.references.length > 0 || v.eslintUsed); }
javascript
function isAfterLastUsedArg(variable) { const def = variable.defs[0]; const params = context.getDeclaredVariables(def.node); const posteriorParams = params.slice(params.indexOf(variable) + 1); // If any used parameters occur after this parameter, do not report. return !posteriorParams.some(v => v.references.length > 0 || v.eslintUsed); }
[ "function", "isAfterLastUsedArg", "(", "variable", ")", "{", "const", "def", "=", "variable", ".", "defs", "[", "0", "]", ";", "const", "params", "=", "context", ".", "getDeclaredVariables", "(", "def", ".", "node", ")", ";", "const", "posteriorParams", "=", "params", ".", "slice", "(", "params", ".", "indexOf", "(", "variable", ")", "+", "1", ")", ";", "return", "!", "posteriorParams", ".", "some", "(", "v", "=>", "v", ".", "references", ".", "length", ">", "0", "||", "v", ".", "eslintUsed", ")", ";", "}" ]
Checks whether the given variable is after the last used parameter. @param {eslint-scope.Variable} variable - The variable to check. @returns {boolean} `true` if the variable is defined after the last used parameter.
[ "Checks", "whether", "the", "given", "variable", "is", "after", "the", "last", "used", "parameter", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-unused-vars.js#L489-L496
train
eslint/eslint
lib/rules/comma-spacing.js
report
function report(node, loc, otherNode) { context.report({ node, fix(fixer) { if (options[loc]) { if (loc === "before") { return fixer.insertTextBefore(node, " "); } return fixer.insertTextAfter(node, " "); } let start, end; const newText = ""; if (loc === "before") { start = otherNode.range[1]; end = node.range[0]; } else { start = node.range[1]; end = otherNode.range[0]; } return fixer.replaceTextRange([start, end], newText); }, messageId: options[loc] ? "missing" : "unexpected", data: { loc } }); }
javascript
function report(node, loc, otherNode) { context.report({ node, fix(fixer) { if (options[loc]) { if (loc === "before") { return fixer.insertTextBefore(node, " "); } return fixer.insertTextAfter(node, " "); } let start, end; const newText = ""; if (loc === "before") { start = otherNode.range[1]; end = node.range[0]; } else { start = node.range[1]; end = otherNode.range[0]; } return fixer.replaceTextRange([start, end], newText); }, messageId: options[loc] ? "missing" : "unexpected", data: { loc } }); }
[ "function", "report", "(", "node", ",", "loc", ",", "otherNode", ")", "{", "context", ".", "report", "(", "{", "node", ",", "fix", "(", "fixer", ")", "{", "if", "(", "options", "[", "loc", "]", ")", "{", "if", "(", "loc", "===", "\"before\"", ")", "{", "return", "fixer", ".", "insertTextBefore", "(", "node", ",", "\" \"", ")", ";", "}", "return", "fixer", ".", "insertTextAfter", "(", "node", ",", "\" \"", ")", ";", "}", "let", "start", ",", "end", ";", "const", "newText", "=", "\"\"", ";", "if", "(", "loc", "===", "\"before\"", ")", "{", "start", "=", "otherNode", ".", "range", "[", "1", "]", ";", "end", "=", "node", ".", "range", "[", "0", "]", ";", "}", "else", "{", "start", "=", "node", ".", "range", "[", "1", "]", ";", "end", "=", "otherNode", ".", "range", "[", "0", "]", ";", "}", "return", "fixer", ".", "replaceTextRange", "(", "[", "start", ",", "end", "]", ",", "newText", ")", ";", "}", ",", "messageId", ":", "options", "[", "loc", "]", "?", "\"missing\"", ":", "\"unexpected\"", ",", "data", ":", "{", "loc", "}", "}", ")", ";", "}" ]
Reports a spacing error with an appropriate message. @param {ASTNode} node The binary expression node to report. @param {string} loc Is the error "before" or "after" the comma? @param {ASTNode} otherNode The node at the left or right of `node` @returns {void} @private
[ "Reports", "a", "spacing", "error", "with", "an", "appropriate", "message", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/comma-spacing.js#L74-L104
train
eslint/eslint
lib/rules/comma-spacing.js
validateCommaItemSpacing
function validateCommaItemSpacing(tokens, reportItem) { if (tokens.left && astUtils.isTokenOnSameLine(tokens.left, tokens.comma) && (options.before !== sourceCode.isSpaceBetweenTokens(tokens.left, tokens.comma)) ) { report(reportItem, "before", tokens.left); } if (tokens.right && astUtils.isClosingParenToken(tokens.right)) { return; } if (tokens.right && !options.after && tokens.right.type === "Line") { return; } if (tokens.right && astUtils.isTokenOnSameLine(tokens.comma, tokens.right) && (options.after !== sourceCode.isSpaceBetweenTokens(tokens.comma, tokens.right)) ) { report(reportItem, "after", tokens.right); } }
javascript
function validateCommaItemSpacing(tokens, reportItem) { if (tokens.left && astUtils.isTokenOnSameLine(tokens.left, tokens.comma) && (options.before !== sourceCode.isSpaceBetweenTokens(tokens.left, tokens.comma)) ) { report(reportItem, "before", tokens.left); } if (tokens.right && astUtils.isClosingParenToken(tokens.right)) { return; } if (tokens.right && !options.after && tokens.right.type === "Line") { return; } if (tokens.right && astUtils.isTokenOnSameLine(tokens.comma, tokens.right) && (options.after !== sourceCode.isSpaceBetweenTokens(tokens.comma, tokens.right)) ) { report(reportItem, "after", tokens.right); } }
[ "function", "validateCommaItemSpacing", "(", "tokens", ",", "reportItem", ")", "{", "if", "(", "tokens", ".", "left", "&&", "astUtils", ".", "isTokenOnSameLine", "(", "tokens", ".", "left", ",", "tokens", ".", "comma", ")", "&&", "(", "options", ".", "before", "!==", "sourceCode", ".", "isSpaceBetweenTokens", "(", "tokens", ".", "left", ",", "tokens", ".", "comma", ")", ")", ")", "{", "report", "(", "reportItem", ",", "\"before\"", ",", "tokens", ".", "left", ")", ";", "}", "if", "(", "tokens", ".", "right", "&&", "astUtils", ".", "isClosingParenToken", "(", "tokens", ".", "right", ")", ")", "{", "return", ";", "}", "if", "(", "tokens", ".", "right", "&&", "!", "options", ".", "after", "&&", "tokens", ".", "right", ".", "type", "===", "\"Line\"", ")", "{", "return", ";", "}", "if", "(", "tokens", ".", "right", "&&", "astUtils", ".", "isTokenOnSameLine", "(", "tokens", ".", "comma", ",", "tokens", ".", "right", ")", "&&", "(", "options", ".", "after", "!==", "sourceCode", ".", "isSpaceBetweenTokens", "(", "tokens", ".", "comma", ",", "tokens", ".", "right", ")", ")", ")", "{", "report", "(", "reportItem", ",", "\"after\"", ",", "tokens", ".", "right", ")", ";", "}", "}" ]
Validates the spacing around a comma token. @param {Object} tokens - The tokens to be validated. @param {Token} tokens.comma The token representing the comma. @param {Token} [tokens.left] The last token before the comma. @param {Token} [tokens.right] The first token after the comma. @param {Token|ASTNode} reportItem The item to use when reporting an error. @returns {void} @private
[ "Validates", "the", "spacing", "around", "a", "comma", "token", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/comma-spacing.js#L116-L136
train
eslint/eslint
lib/rules/comma-spacing.js
addNullElementsToIgnoreList
function addNullElementsToIgnoreList(node) { let previousToken = sourceCode.getFirstToken(node); node.elements.forEach(element => { let token; if (element === null) { token = sourceCode.getTokenAfter(previousToken); if (astUtils.isCommaToken(token)) { commaTokensToIgnore.push(token); } } else { token = sourceCode.getTokenAfter(element); } previousToken = token; }); }
javascript
function addNullElementsToIgnoreList(node) { let previousToken = sourceCode.getFirstToken(node); node.elements.forEach(element => { let token; if (element === null) { token = sourceCode.getTokenAfter(previousToken); if (astUtils.isCommaToken(token)) { commaTokensToIgnore.push(token); } } else { token = sourceCode.getTokenAfter(element); } previousToken = token; }); }
[ "function", "addNullElementsToIgnoreList", "(", "node", ")", "{", "let", "previousToken", "=", "sourceCode", ".", "getFirstToken", "(", "node", ")", ";", "node", ".", "elements", ".", "forEach", "(", "element", "=>", "{", "let", "token", ";", "if", "(", "element", "===", "null", ")", "{", "token", "=", "sourceCode", ".", "getTokenAfter", "(", "previousToken", ")", ";", "if", "(", "astUtils", ".", "isCommaToken", "(", "token", ")", ")", "{", "commaTokensToIgnore", ".", "push", "(", "token", ")", ";", "}", "}", "else", "{", "token", "=", "sourceCode", ".", "getTokenAfter", "(", "element", ")", ";", "}", "previousToken", "=", "token", ";", "}", ")", ";", "}" ]
Adds null elements of the given ArrayExpression or ArrayPattern node to the ignore list. @param {ASTNode} node An ArrayExpression or ArrayPattern node. @returns {void}
[ "Adds", "null", "elements", "of", "the", "given", "ArrayExpression", "or", "ArrayPattern", "node", "to", "the", "ignore", "list", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/comma-spacing.js#L143-L161
train
eslint/eslint
lib/rules/no-var.js
getEnclosingFunctionScope
function getEnclosingFunctionScope(scope) { let currentScope = scope; while (currentScope.type !== "function" && currentScope.type !== "global") { currentScope = currentScope.upper; } return currentScope; }
javascript
function getEnclosingFunctionScope(scope) { let currentScope = scope; while (currentScope.type !== "function" && currentScope.type !== "global") { currentScope = currentScope.upper; } return currentScope; }
[ "function", "getEnclosingFunctionScope", "(", "scope", ")", "{", "let", "currentScope", "=", "scope", ";", "while", "(", "currentScope", ".", "type", "!==", "\"function\"", "&&", "currentScope", ".", "type", "!==", "\"global\"", ")", "{", "currentScope", "=", "currentScope", ".", "upper", ";", "}", "return", "currentScope", ";", "}" ]
Finds the nearest function scope or global scope walking up the scope hierarchy. @param {eslint-scope.Scope} scope - The scope to traverse. @returns {eslint-scope.Scope} a function scope or global scope containing the given scope.
[ "Finds", "the", "nearest", "function", "scope", "or", "global", "scope", "walking", "up", "the", "scope", "hierarchy", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-var.js#L35-L42
train
eslint/eslint
lib/rules/no-var.js
isLoopAssignee
function isLoopAssignee(node) { return (node.parent.type === "ForOfStatement" || node.parent.type === "ForInStatement") && node === node.parent.left; }
javascript
function isLoopAssignee(node) { return (node.parent.type === "ForOfStatement" || node.parent.type === "ForInStatement") && node === node.parent.left; }
[ "function", "isLoopAssignee", "(", "node", ")", "{", "return", "(", "node", ".", "parent", ".", "type", "===", "\"ForOfStatement\"", "||", "node", ".", "parent", ".", "type", "===", "\"ForInStatement\"", ")", "&&", "node", "===", "node", ".", "parent", ".", "left", ";", "}" ]
Checks whether the given node is the assignee of a loop. @param {ASTNode} node - A VariableDeclaration node to check. @returns {boolean} `true` if the declaration is assigned as part of loop iteration.
[ "Checks", "whether", "the", "given", "node", "is", "the", "assignee", "of", "a", "loop", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-var.js#L65-L68
train
eslint/eslint
lib/rules/no-var.js
getScopeNode
function getScopeNode(node) { for (let currentNode = node; currentNode; currentNode = currentNode.parent) { if (SCOPE_NODE_TYPE.test(currentNode.type)) { return currentNode; } } /* istanbul ignore next : unreachable */ return null; }
javascript
function getScopeNode(node) { for (let currentNode = node; currentNode; currentNode = currentNode.parent) { if (SCOPE_NODE_TYPE.test(currentNode.type)) { return currentNode; } } /* istanbul ignore next : unreachable */ return null; }
[ "function", "getScopeNode", "(", "node", ")", "{", "for", "(", "let", "currentNode", "=", "node", ";", "currentNode", ";", "currentNode", "=", "currentNode", ".", "parent", ")", "{", "if", "(", "SCOPE_NODE_TYPE", ".", "test", "(", "currentNode", ".", "type", ")", ")", "{", "return", "currentNode", ";", "}", "}", "return", "null", ";", "}" ]
Gets the scope node which directly contains a given node. @param {ASTNode} node - A node to get. This is a `VariableDeclaration` or an `Identifier`. @returns {ASTNode} A scope node. This is one of `Program`, `BlockStatement`, `SwitchStatement`, `ForStatement`, `ForInStatement`, and `ForOfStatement`.
[ "Gets", "the", "scope", "node", "which", "directly", "contains", "a", "given", "node", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-var.js#L91-L100
train
eslint/eslint
lib/rules/no-var.js
isUsedFromOutsideOf
function isUsedFromOutsideOf(scopeNode) { /** * Checks whether a given reference is inside of the specified scope or not. * * @param {eslint-scope.Reference} reference - A reference to check. * @returns {boolean} `true` if the reference is inside of the specified * scope. */ function isOutsideOfScope(reference) { const scope = scopeNode.range; const id = reference.identifier.range; return id[0] < scope[0] || id[1] > scope[1]; } return function(variable) { return variable.references.some(isOutsideOfScope); }; }
javascript
function isUsedFromOutsideOf(scopeNode) { /** * Checks whether a given reference is inside of the specified scope or not. * * @param {eslint-scope.Reference} reference - A reference to check. * @returns {boolean} `true` if the reference is inside of the specified * scope. */ function isOutsideOfScope(reference) { const scope = scopeNode.range; const id = reference.identifier.range; return id[0] < scope[0] || id[1] > scope[1]; } return function(variable) { return variable.references.some(isOutsideOfScope); }; }
[ "function", "isUsedFromOutsideOf", "(", "scopeNode", ")", "{", "function", "isOutsideOfScope", "(", "reference", ")", "{", "const", "scope", "=", "scopeNode", ".", "range", ";", "const", "id", "=", "reference", ".", "identifier", ".", "range", ";", "return", "id", "[", "0", "]", "<", "scope", "[", "0", "]", "||", "id", "[", "1", "]", ">", "scope", "[", "1", "]", ";", "}", "return", "function", "(", "variable", ")", "{", "return", "variable", ".", "references", ".", "some", "(", "isOutsideOfScope", ")", ";", "}", ";", "}" ]
Checks whether a given variable is used from outside of the specified scope. @param {ASTNode} scopeNode - A scope node to check. @returns {Function} The predicate function which checks whether a given variable is used from outside of the specified scope.
[ "Checks", "whether", "a", "given", "variable", "is", "used", "from", "outside", "of", "the", "specified", "scope", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-var.js#L119-L138
train
eslint/eslint
lib/rules/no-var.js
isOutsideOfScope
function isOutsideOfScope(reference) { const scope = scopeNode.range; const id = reference.identifier.range; return id[0] < scope[0] || id[1] > scope[1]; }
javascript
function isOutsideOfScope(reference) { const scope = scopeNode.range; const id = reference.identifier.range; return id[0] < scope[0] || id[1] > scope[1]; }
[ "function", "isOutsideOfScope", "(", "reference", ")", "{", "const", "scope", "=", "scopeNode", ".", "range", ";", "const", "id", "=", "reference", ".", "identifier", ".", "range", ";", "return", "id", "[", "0", "]", "<", "scope", "[", "0", "]", "||", "id", "[", "1", "]", ">", "scope", "[", "1", "]", ";", "}" ]
Checks whether a given reference is inside of the specified scope or not. @param {eslint-scope.Reference} reference - A reference to check. @returns {boolean} `true` if the reference is inside of the specified scope.
[ "Checks", "whether", "a", "given", "reference", "is", "inside", "of", "the", "specified", "scope", "or", "not", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-var.js#L128-L133
train
eslint/eslint
lib/rules/no-var.js
hasReferenceInTDZ
function hasReferenceInTDZ(node) { const initStart = node.range[0]; const initEnd = node.range[1]; return variable => { const id = variable.defs[0].name; const idStart = id.range[0]; const defaultValue = (id.parent.type === "AssignmentPattern" ? id.parent.right : null); const defaultStart = defaultValue && defaultValue.range[0]; const defaultEnd = defaultValue && defaultValue.range[1]; return variable.references.some(reference => { const start = reference.identifier.range[0]; const end = reference.identifier.range[1]; return !reference.init && ( start < idStart || (defaultValue !== null && start >= defaultStart && end <= defaultEnd) || (start >= initStart && end <= initEnd) ); }); }; }
javascript
function hasReferenceInTDZ(node) { const initStart = node.range[0]; const initEnd = node.range[1]; return variable => { const id = variable.defs[0].name; const idStart = id.range[0]; const defaultValue = (id.parent.type === "AssignmentPattern" ? id.parent.right : null); const defaultStart = defaultValue && defaultValue.range[0]; const defaultEnd = defaultValue && defaultValue.range[1]; return variable.references.some(reference => { const start = reference.identifier.range[0]; const end = reference.identifier.range[1]; return !reference.init && ( start < idStart || (defaultValue !== null && start >= defaultStart && end <= defaultEnd) || (start >= initStart && end <= initEnd) ); }); }; }
[ "function", "hasReferenceInTDZ", "(", "node", ")", "{", "const", "initStart", "=", "node", ".", "range", "[", "0", "]", ";", "const", "initEnd", "=", "node", ".", "range", "[", "1", "]", ";", "return", "variable", "=>", "{", "const", "id", "=", "variable", ".", "defs", "[", "0", "]", ".", "name", ";", "const", "idStart", "=", "id", ".", "range", "[", "0", "]", ";", "const", "defaultValue", "=", "(", "id", ".", "parent", ".", "type", "===", "\"AssignmentPattern\"", "?", "id", ".", "parent", ".", "right", ":", "null", ")", ";", "const", "defaultStart", "=", "defaultValue", "&&", "defaultValue", ".", "range", "[", "0", "]", ";", "const", "defaultEnd", "=", "defaultValue", "&&", "defaultValue", ".", "range", "[", "1", "]", ";", "return", "variable", ".", "references", ".", "some", "(", "reference", "=>", "{", "const", "start", "=", "reference", ".", "identifier", ".", "range", "[", "0", "]", ";", "const", "end", "=", "reference", ".", "identifier", ".", "range", "[", "1", "]", ";", "return", "!", "reference", ".", "init", "&&", "(", "start", "<", "idStart", "||", "(", "defaultValue", "!==", "null", "&&", "start", ">=", "defaultStart", "&&", "end", "<=", "defaultEnd", ")", "||", "(", "start", ">=", "initStart", "&&", "end", "<=", "initEnd", ")", ")", ";", "}", ")", ";", "}", ";", "}" ]
Creates the predicate function which checks whether a variable has their references in TDZ. The predicate function would return `true`: - if a reference is before the declarator. E.g. (var a = b, b = 1;)(var {a = b, b} = {};) - if a reference is in the expression of their default value. E.g. (var {a = a} = {};) - if a reference is in the expression of their initializer. E.g. (var a = a;) @param {ASTNode} node - The initializer node of VariableDeclarator. @returns {Function} The predicate function. @private
[ "Creates", "the", "predicate", "function", "which", "checks", "whether", "a", "variable", "has", "their", "references", "in", "TDZ", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-var.js#L153-L175
train
eslint/eslint
lib/rules/no-var.js
hasSelfReferenceInTDZ
function hasSelfReferenceInTDZ(declarator) { if (!declarator.init) { return false; } const variables = context.getDeclaredVariables(declarator); return variables.some(hasReferenceInTDZ(declarator.init)); }
javascript
function hasSelfReferenceInTDZ(declarator) { if (!declarator.init) { return false; } const variables = context.getDeclaredVariables(declarator); return variables.some(hasReferenceInTDZ(declarator.init)); }
[ "function", "hasSelfReferenceInTDZ", "(", "declarator", ")", "{", "if", "(", "!", "declarator", ".", "init", ")", "{", "return", "false", ";", "}", "const", "variables", "=", "context", ".", "getDeclaredVariables", "(", "declarator", ")", ";", "return", "variables", ".", "some", "(", "hasReferenceInTDZ", "(", "declarator", ".", "init", ")", ")", ";", "}" ]
Checks whether the variables which are defined by the given declarator node have their references in TDZ. @param {ASTNode} declarator - The VariableDeclarator node to check. @returns {boolean} `true` if one of the variables which are defined by the given declarator node have their references in TDZ.
[ "Checks", "whether", "the", "variables", "which", "are", "defined", "by", "the", "given", "declarator", "node", "have", "their", "references", "in", "TDZ", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-var.js#L205-L212
train
eslint/eslint
lib/rules/no-var.js
report
function report(node) { context.report({ node, message: "Unexpected var, use let or const instead.", fix(fixer) { const varToken = sourceCode.getFirstToken(node, { filter: t => t.value === "var" }); return canFix(node) ? fixer.replaceText(varToken, "let") : null; } }); }
javascript
function report(node) { context.report({ node, message: "Unexpected var, use let or const instead.", fix(fixer) { const varToken = sourceCode.getFirstToken(node, { filter: t => t.value === "var" }); return canFix(node) ? fixer.replaceText(varToken, "let") : null; } }); }
[ "function", "report", "(", "node", ")", "{", "context", ".", "report", "(", "{", "node", ",", "message", ":", "\"Unexpected var, use let or const instead.\"", ",", "fix", "(", "fixer", ")", "{", "const", "varToken", "=", "sourceCode", ".", "getFirstToken", "(", "node", ",", "{", "filter", ":", "t", "=>", "t", ".", "value", "===", "\"var\"", "}", ")", ";", "return", "canFix", "(", "node", ")", "?", "fixer", ".", "replaceText", "(", "varToken", ",", "\"let\"", ")", ":", "null", ";", "}", "}", ")", ";", "}" ]
Reports a given variable declaration node. @param {ASTNode} node - A variable declaration node to report. @returns {void}
[ "Reports", "a", "given", "variable", "declaration", "node", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-var.js#L307-L320
train
eslint/eslint
lib/rules/no-confusing-arrow.js
checkArrowFunc
function checkArrowFunc(node) { const body = node.body; if (isConditional(body) && !(allowParens && astUtils.isParenthesised(sourceCode, body))) { context.report({ node, messageId: "confusing", fix(fixer) { // if `allowParens` is not set to true dont bother wrapping in parens return allowParens && fixer.replaceText(node.body, `(${sourceCode.getText(node.body)})`); } }); } }
javascript
function checkArrowFunc(node) { const body = node.body; if (isConditional(body) && !(allowParens && astUtils.isParenthesised(sourceCode, body))) { context.report({ node, messageId: "confusing", fix(fixer) { // if `allowParens` is not set to true dont bother wrapping in parens return allowParens && fixer.replaceText(node.body, `(${sourceCode.getText(node.body)})`); } }); } }
[ "function", "checkArrowFunc", "(", "node", ")", "{", "const", "body", "=", "node", ".", "body", ";", "if", "(", "isConditional", "(", "body", ")", "&&", "!", "(", "allowParens", "&&", "astUtils", ".", "isParenthesised", "(", "sourceCode", ",", "body", ")", ")", ")", "{", "context", ".", "report", "(", "{", "node", ",", "messageId", ":", "\"confusing\"", ",", "fix", "(", "fixer", ")", "{", "return", "allowParens", "&&", "fixer", ".", "replaceText", "(", "node", ".", "body", ",", "`", "${", "sourceCode", ".", "getText", "(", "node", ".", "body", ")", "}", "`", ")", ";", "}", "}", ")", ";", "}", "}" ]
Reports if an arrow function contains an ambiguous conditional. @param {ASTNode} node - A node to check and report. @returns {void}
[ "Reports", "if", "an", "arrow", "function", "contains", "an", "ambiguous", "conditional", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-confusing-arrow.js#L65-L79
train
eslint/eslint
lib/rules/max-nested-callbacks.js
checkFunction
function checkFunction(node) { const parent = node.parent; if (parent.type === "CallExpression") { callbackStack.push(node); } if (callbackStack.length > THRESHOLD) { const opts = { num: callbackStack.length, max: THRESHOLD }; context.report({ node, messageId: "exceed", data: opts }); } }
javascript
function checkFunction(node) { const parent = node.parent; if (parent.type === "CallExpression") { callbackStack.push(node); } if (callbackStack.length > THRESHOLD) { const opts = { num: callbackStack.length, max: THRESHOLD }; context.report({ node, messageId: "exceed", data: opts }); } }
[ "function", "checkFunction", "(", "node", ")", "{", "const", "parent", "=", "node", ".", "parent", ";", "if", "(", "parent", ".", "type", "===", "\"CallExpression\"", ")", "{", "callbackStack", ".", "push", "(", "node", ")", ";", "}", "if", "(", "callbackStack", ".", "length", ">", "THRESHOLD", ")", "{", "const", "opts", "=", "{", "num", ":", "callbackStack", ".", "length", ",", "max", ":", "THRESHOLD", "}", ";", "context", ".", "report", "(", "{", "node", ",", "messageId", ":", "\"exceed\"", ",", "data", ":", "opts", "}", ")", ";", "}", "}" ]
Checks a given function node for too many callbacks. @param {ASTNode} node The node to check. @returns {void} @private
[ "Checks", "a", "given", "function", "node", "for", "too", "many", "callbacks", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/max-nested-callbacks.js#L81-L93
train
eslint/eslint
lib/rules/init-declarations.js
isInitialized
function isInitialized(node) { const declaration = node.parent; const block = declaration.parent; if (isForLoop(block)) { if (block.type === "ForStatement") { return block.init === declaration; } return block.left === declaration; } return Boolean(node.init); }
javascript
function isInitialized(node) { const declaration = node.parent; const block = declaration.parent; if (isForLoop(block)) { if (block.type === "ForStatement") { return block.init === declaration; } return block.left === declaration; } return Boolean(node.init); }
[ "function", "isInitialized", "(", "node", ")", "{", "const", "declaration", "=", "node", ".", "parent", ";", "const", "block", "=", "declaration", ".", "parent", ";", "if", "(", "isForLoop", "(", "block", ")", ")", "{", "if", "(", "block", ".", "type", "===", "\"ForStatement\"", ")", "{", "return", "block", ".", "init", "===", "declaration", ";", "}", "return", "block", ".", "left", "===", "declaration", ";", "}", "return", "Boolean", "(", "node", ".", "init", ")", ";", "}" ]
Checks whether or not a given declarator node has its initializer. @param {ASTNode} node - A declarator node to check. @returns {boolean} `true` when the node has its initializer.
[ "Checks", "whether", "or", "not", "a", "given", "declarator", "node", "has", "its", "initializer", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/init-declarations.js#L28-L39
train
eslint/eslint
lib/rules/new-cap.js
checkArray
function checkArray(obj, key, fallback) { /* istanbul ignore if */ if (Object.prototype.hasOwnProperty.call(obj, key) && !Array.isArray(obj[key])) { throw new TypeError(`${key}, if provided, must be an Array`); } return obj[key] || fallback; }
javascript
function checkArray(obj, key, fallback) { /* istanbul ignore if */ if (Object.prototype.hasOwnProperty.call(obj, key) && !Array.isArray(obj[key])) { throw new TypeError(`${key}, if provided, must be an Array`); } return obj[key] || fallback; }
[ "function", "checkArray", "(", "obj", ",", "key", ",", "fallback", ")", "{", "if", "(", "Object", ".", "prototype", ".", "hasOwnProperty", ".", "call", "(", "obj", ",", "key", ")", "&&", "!", "Array", ".", "isArray", "(", "obj", "[", "key", "]", ")", ")", "{", "throw", "new", "TypeError", "(", "`", "${", "key", "}", "`", ")", ";", "}", "return", "obj", "[", "key", "]", "||", "fallback", ";", "}" ]
Ensure that if the key is provided, it must be an array. @param {Object} obj Object to check with `key`. @param {string} key Object key to check on `obj`. @param {*} fallback If obj[key] is not present, this will be returned. @returns {string[]} Returns obj[key] if it's an Array, otherwise `fallback`
[ "Ensure", "that", "if", "the", "key", "is", "provided", "it", "must", "be", "an", "array", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/new-cap.js#L36-L43
train
eslint/eslint
lib/rules/new-cap.js
calculateCapIsNewExceptions
function calculateCapIsNewExceptions(config) { let capIsNewExceptions = checkArray(config, "capIsNewExceptions", CAPS_ALLOWED); if (capIsNewExceptions !== CAPS_ALLOWED) { capIsNewExceptions = capIsNewExceptions.concat(CAPS_ALLOWED); } return capIsNewExceptions.reduce(invert, {}); }
javascript
function calculateCapIsNewExceptions(config) { let capIsNewExceptions = checkArray(config, "capIsNewExceptions", CAPS_ALLOWED); if (capIsNewExceptions !== CAPS_ALLOWED) { capIsNewExceptions = capIsNewExceptions.concat(CAPS_ALLOWED); } return capIsNewExceptions.reduce(invert, {}); }
[ "function", "calculateCapIsNewExceptions", "(", "config", ")", "{", "let", "capIsNewExceptions", "=", "checkArray", "(", "config", ",", "\"capIsNewExceptions\"", ",", "CAPS_ALLOWED", ")", ";", "if", "(", "capIsNewExceptions", "!==", "CAPS_ALLOWED", ")", "{", "capIsNewExceptions", "=", "capIsNewExceptions", ".", "concat", "(", "CAPS_ALLOWED", ")", ";", "}", "return", "capIsNewExceptions", ".", "reduce", "(", "invert", ",", "{", "}", ")", ";", "}" ]
Creates an object with the cap is new exceptions as its keys and true as their values. @param {Object} config Rule configuration @returns {Object} Object with cap is new exceptions.
[ "Creates", "an", "object", "with", "the", "cap", "is", "new", "exceptions", "as", "its", "keys", "and", "true", "as", "their", "values", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/new-cap.js#L61-L69
train
eslint/eslint
lib/rules/new-cap.js
getCap
function getCap(str) { const firstChar = str.charAt(0); const firstCharLower = firstChar.toLowerCase(); const firstCharUpper = firstChar.toUpperCase(); if (firstCharLower === firstCharUpper) { // char has no uppercase variant, so it's non-alphabetic return "non-alpha"; } if (firstChar === firstCharLower) { return "lower"; } return "upper"; }
javascript
function getCap(str) { const firstChar = str.charAt(0); const firstCharLower = firstChar.toLowerCase(); const firstCharUpper = firstChar.toUpperCase(); if (firstCharLower === firstCharUpper) { // char has no uppercase variant, so it's non-alphabetic return "non-alpha"; } if (firstChar === firstCharLower) { return "lower"; } return "upper"; }
[ "function", "getCap", "(", "str", ")", "{", "const", "firstChar", "=", "str", ".", "charAt", "(", "0", ")", ";", "const", "firstCharLower", "=", "firstChar", ".", "toLowerCase", "(", ")", ";", "const", "firstCharUpper", "=", "firstChar", ".", "toUpperCase", "(", ")", ";", "if", "(", "firstCharLower", "===", "firstCharUpper", ")", "{", "return", "\"non-alpha\"", ";", "}", "if", "(", "firstChar", "===", "firstCharLower", ")", "{", "return", "\"lower\"", ";", "}", "return", "\"upper\"", ";", "}" ]
Returns the capitalization state of the string - Whether the first character is uppercase, lowercase, or non-alphabetic @param {string} str String @returns {string} capitalization state: "non-alpha", "lower", or "upper"
[ "Returns", "the", "capitalization", "state", "of", "the", "string", "-", "Whether", "the", "first", "character", "is", "uppercase", "lowercase", "or", "non", "-", "alphabetic" ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/new-cap.js#L181-L197
train
eslint/eslint
lib/rules/new-cap.js
isCapAllowed
function isCapAllowed(allowedMap, node, calleeName, pattern) { const sourceText = sourceCode.getText(node.callee); if (allowedMap[calleeName] || allowedMap[sourceText]) { return true; } if (pattern && pattern.test(sourceText)) { return true; } if (calleeName === "UTC" && node.callee.type === "MemberExpression") { // allow if callee is Date.UTC return node.callee.object.type === "Identifier" && node.callee.object.name === "Date"; } return skipProperties && node.callee.type === "MemberExpression"; }
javascript
function isCapAllowed(allowedMap, node, calleeName, pattern) { const sourceText = sourceCode.getText(node.callee); if (allowedMap[calleeName] || allowedMap[sourceText]) { return true; } if (pattern && pattern.test(sourceText)) { return true; } if (calleeName === "UTC" && node.callee.type === "MemberExpression") { // allow if callee is Date.UTC return node.callee.object.type === "Identifier" && node.callee.object.name === "Date"; } return skipProperties && node.callee.type === "MemberExpression"; }
[ "function", "isCapAllowed", "(", "allowedMap", ",", "node", ",", "calleeName", ",", "pattern", ")", "{", "const", "sourceText", "=", "sourceCode", ".", "getText", "(", "node", ".", "callee", ")", ";", "if", "(", "allowedMap", "[", "calleeName", "]", "||", "allowedMap", "[", "sourceText", "]", ")", "{", "return", "true", ";", "}", "if", "(", "pattern", "&&", "pattern", ".", "test", "(", "sourceText", ")", ")", "{", "return", "true", ";", "}", "if", "(", "calleeName", "===", "\"UTC\"", "&&", "node", ".", "callee", ".", "type", "===", "\"MemberExpression\"", ")", "{", "return", "node", ".", "callee", ".", "object", ".", "type", "===", "\"Identifier\"", "&&", "node", ".", "callee", ".", "object", ".", "name", "===", "\"Date\"", ";", "}", "return", "skipProperties", "&&", "node", ".", "callee", ".", "type", "===", "\"MemberExpression\"", ";", "}" ]
Check if capitalization is allowed for a CallExpression @param {Object} allowedMap Object mapping calleeName to a Boolean @param {ASTNode} node CallExpression node @param {string} calleeName Capitalized callee name from a CallExpression @param {Object} pattern RegExp object from options pattern @returns {boolean} Returns true if the callee may be capitalized
[ "Check", "if", "capitalization", "is", "allowed", "for", "a", "CallExpression" ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/new-cap.js#L207-L226
train
eslint/eslint
lib/rules/new-cap.js
report
function report(node, messageId) { let callee = node.callee; if (callee.type === "MemberExpression") { callee = callee.property; } context.report({ node, loc: callee.loc.start, messageId }); }
javascript
function report(node, messageId) { let callee = node.callee; if (callee.type === "MemberExpression") { callee = callee.property; } context.report({ node, loc: callee.loc.start, messageId }); }
[ "function", "report", "(", "node", ",", "messageId", ")", "{", "let", "callee", "=", "node", ".", "callee", ";", "if", "(", "callee", ".", "type", "===", "\"MemberExpression\"", ")", "{", "callee", "=", "callee", ".", "property", ";", "}", "context", ".", "report", "(", "{", "node", ",", "loc", ":", "callee", ".", "loc", ".", "start", ",", "messageId", "}", ")", ";", "}" ]
Reports the given messageId for the given node. The location will be the start of the property or the callee. @param {ASTNode} node CallExpression or NewExpression node. @param {string} messageId The messageId to report. @returns {void}
[ "Reports", "the", "given", "messageId", "for", "the", "given", "node", ".", "The", "location", "will", "be", "the", "start", "of", "the", "property", "or", "the", "callee", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/new-cap.js#L234-L242
train
eslint/eslint
lib/util/traverser.js
getVisitorKeys
function getVisitorKeys(visitorKeys, node) { let keys = visitorKeys[node.type]; if (!keys) { keys = vk.getKeys(node); debug("Unknown node type \"%s\": Estimated visitor keys %j", node.type, keys); } return keys; }
javascript
function getVisitorKeys(visitorKeys, node) { let keys = visitorKeys[node.type]; if (!keys) { keys = vk.getKeys(node); debug("Unknown node type \"%s\": Estimated visitor keys %j", node.type, keys); } return keys; }
[ "function", "getVisitorKeys", "(", "visitorKeys", ",", "node", ")", "{", "let", "keys", "=", "visitorKeys", "[", "node", ".", "type", "]", ";", "if", "(", "!", "keys", ")", "{", "keys", "=", "vk", ".", "getKeys", "(", "node", ")", ";", "debug", "(", "\"Unknown node type \\\"%s\\\": Estimated visitor keys %j\"", ",", "\\\"", ",", "\\\"", ")", ";", "}", "node", ".", "type", "}" ]
Get the visitor keys of a given node. @param {Object} visitorKeys The map of visitor keys. @param {ASTNode} node The node to get their visitor keys. @returns {string[]} The visitor keys of the node.
[ "Get", "the", "visitor", "keys", "of", "a", "given", "node", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/util/traverser.js#L43-L52
train
eslint/eslint
lib/rules/yoda.js
looksLikeLiteral
function looksLikeLiteral(node) { return (node.type === "UnaryExpression" && node.operator === "-" && node.prefix && node.argument.type === "Literal" && typeof node.argument.value === "number"); }
javascript
function looksLikeLiteral(node) { return (node.type === "UnaryExpression" && node.operator === "-" && node.prefix && node.argument.type === "Literal" && typeof node.argument.value === "number"); }
[ "function", "looksLikeLiteral", "(", "node", ")", "{", "return", "(", "node", ".", "type", "===", "\"UnaryExpression\"", "&&", "node", ".", "operator", "===", "\"-\"", "&&", "node", ".", "prefix", "&&", "node", ".", "argument", ".", "type", "===", "\"Literal\"", "&&", "typeof", "node", ".", "argument", ".", "value", "===", "\"number\"", ")", ";", "}" ]
Determines whether a non-Literal node is a negative number that should be treated as if it were a single Literal node. @param {ASTNode} node Node to test. @returns {boolean} True if the node is a negative number that looks like a real literal and should be treated as such.
[ "Determines", "whether", "a", "non", "-", "Literal", "node", "is", "a", "negative", "number", "that", "should", "be", "treated", "as", "if", "it", "were", "a", "single", "Literal", "node", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/yoda.js#L52-L58
train
eslint/eslint
lib/rules/prefer-reflect.js
report
function report(node, existing, substitute) { context.report({ node, message: "Avoid using {{existing}}, instead use {{substitute}}.", data: { existing, substitute } }); }
javascript
function report(node, existing, substitute) { context.report({ node, message: "Avoid using {{existing}}, instead use {{substitute}}.", data: { existing, substitute } }); }
[ "function", "report", "(", "node", ",", "existing", ",", "substitute", ")", "{", "context", ".", "report", "(", "{", "node", ",", "message", ":", "\"Avoid using {{existing}}, instead use {{substitute}}.\"", ",", "data", ":", "{", "existing", ",", "substitute", "}", "}", ")", ";", "}" ]
Reports the Reflect violation based on the `existing` and `substitute` @param {Object} node The node that violates the rule. @param {string} existing The existing method name that has been used. @param {string} substitute The Reflect substitute that should be used. @returns {void}
[ "Reports", "the", "Reflect", "violation", "based", "on", "the", "existing", "and", "substitute" ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/prefer-reflect.js#L89-L98
train
eslint/eslint
lib/rules/prefer-named-capture-group.js
checkRegex
function checkRegex(regex, node, uFlag) { let ast; try { ast = parser.parsePattern(regex, 0, regex.length, uFlag); } catch (_) { // ignore regex syntax errors return; } regexpp.visitRegExpAST(ast, { onCapturingGroupEnter(group) { if (!group.name) { const locNode = node.type === "Literal" ? node : node.arguments[0]; context.report({ node, messageId: "required", loc: { start: { line: locNode.loc.start.line, column: locNode.loc.start.column + group.start + 1 }, end: { line: locNode.loc.start.line, column: locNode.loc.start.column + group.end + 1 } }, data: { group: group.raw } }); } } }); }
javascript
function checkRegex(regex, node, uFlag) { let ast; try { ast = parser.parsePattern(regex, 0, regex.length, uFlag); } catch (_) { // ignore regex syntax errors return; } regexpp.visitRegExpAST(ast, { onCapturingGroupEnter(group) { if (!group.name) { const locNode = node.type === "Literal" ? node : node.arguments[0]; context.report({ node, messageId: "required", loc: { start: { line: locNode.loc.start.line, column: locNode.loc.start.column + group.start + 1 }, end: { line: locNode.loc.start.line, column: locNode.loc.start.column + group.end + 1 } }, data: { group: group.raw } }); } } }); }
[ "function", "checkRegex", "(", "regex", ",", "node", ",", "uFlag", ")", "{", "let", "ast", ";", "try", "{", "ast", "=", "parser", ".", "parsePattern", "(", "regex", ",", "0", ",", "regex", ".", "length", ",", "uFlag", ")", ";", "}", "catch", "(", "_", ")", "{", "return", ";", "}", "regexpp", ".", "visitRegExpAST", "(", "ast", ",", "{", "onCapturingGroupEnter", "(", "group", ")", "{", "if", "(", "!", "group", ".", "name", ")", "{", "const", "locNode", "=", "node", ".", "type", "===", "\"Literal\"", "?", "node", ":", "node", ".", "arguments", "[", "0", "]", ";", "context", ".", "report", "(", "{", "node", ",", "messageId", ":", "\"required\"", ",", "loc", ":", "{", "start", ":", "{", "line", ":", "locNode", ".", "loc", ".", "start", ".", "line", ",", "column", ":", "locNode", ".", "loc", ".", "start", ".", "column", "+", "group", ".", "start", "+", "1", "}", ",", "end", ":", "{", "line", ":", "locNode", ".", "loc", ".", "start", ".", "line", ",", "column", ":", "locNode", ".", "loc", ".", "start", ".", "column", "+", "group", ".", "end", "+", "1", "}", "}", ",", "data", ":", "{", "group", ":", "group", ".", "raw", "}", "}", ")", ";", "}", "}", "}", ")", ";", "}" ]
Function to check regular expression. @param {string} regex The regular expression to be check. @param {ASTNode} node AST node which contains regular expression. @param {boolean} uFlag Flag indicates whether unicode mode is enabled or not. @returns {void}
[ "Function", "to", "check", "regular", "expression", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/prefer-named-capture-group.js#L58-L94
train
eslint/eslint
lib/util/file-finder.js
normalizeDirectoryEntries
function normalizeDirectoryEntries(entries, directory, supportedConfigs) { const fileHash = {}; entries.forEach(entry => { if (supportedConfigs.indexOf(entry) >= 0) { const resolvedEntry = path.resolve(directory, entry); if (fs.statSync(resolvedEntry).isFile()) { fileHash[entry] = resolvedEntry; } } }); return fileHash; }
javascript
function normalizeDirectoryEntries(entries, directory, supportedConfigs) { const fileHash = {}; entries.forEach(entry => { if (supportedConfigs.indexOf(entry) >= 0) { const resolvedEntry = path.resolve(directory, entry); if (fs.statSync(resolvedEntry).isFile()) { fileHash[entry] = resolvedEntry; } } }); return fileHash; }
[ "function", "normalizeDirectoryEntries", "(", "entries", ",", "directory", ",", "supportedConfigs", ")", "{", "const", "fileHash", "=", "{", "}", ";", "entries", ".", "forEach", "(", "entry", "=>", "{", "if", "(", "supportedConfigs", ".", "indexOf", "(", "entry", ")", ">=", "0", ")", "{", "const", "resolvedEntry", "=", "path", ".", "resolve", "(", "directory", ",", "entry", ")", ";", "if", "(", "fs", ".", "statSync", "(", "resolvedEntry", ")", ".", "isFile", "(", ")", ")", "{", "fileHash", "[", "entry", "]", "=", "resolvedEntry", ";", "}", "}", "}", ")", ";", "return", "fileHash", ";", "}" ]
Create a hash of filenames from a directory listing @param {string[]} entries Array of directory entries. @param {string} directory Path to a current directory. @param {string[]} supportedConfigs List of support filenames. @returns {Object} Hashmap of filenames
[ "Create", "a", "hash", "of", "filenames", "from", "a", "directory", "listing" ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/util/file-finder.js#L42-L55
train
eslint/eslint
lib/rules/no-empty-function.js
getKind
function getKind(node) { const parent = node.parent; let kind = ""; if (node.type === "ArrowFunctionExpression") { return "arrowFunctions"; } // Detects main kind. if (parent.type === "Property") { if (parent.kind === "get") { return "getters"; } if (parent.kind === "set") { return "setters"; } kind = parent.method ? "methods" : "functions"; } else if (parent.type === "MethodDefinition") { if (parent.kind === "get") { return "getters"; } if (parent.kind === "set") { return "setters"; } if (parent.kind === "constructor") { return "constructors"; } kind = "methods"; } else { kind = "functions"; } // Detects prefix. let prefix = ""; if (node.generator) { prefix = "generator"; } else if (node.async) { prefix = "async"; } else { return kind; } return prefix + kind[0].toUpperCase() + kind.slice(1); }
javascript
function getKind(node) { const parent = node.parent; let kind = ""; if (node.type === "ArrowFunctionExpression") { return "arrowFunctions"; } // Detects main kind. if (parent.type === "Property") { if (parent.kind === "get") { return "getters"; } if (parent.kind === "set") { return "setters"; } kind = parent.method ? "methods" : "functions"; } else if (parent.type === "MethodDefinition") { if (parent.kind === "get") { return "getters"; } if (parent.kind === "set") { return "setters"; } if (parent.kind === "constructor") { return "constructors"; } kind = "methods"; } else { kind = "functions"; } // Detects prefix. let prefix = ""; if (node.generator) { prefix = "generator"; } else if (node.async) { prefix = "async"; } else { return kind; } return prefix + kind[0].toUpperCase() + kind.slice(1); }
[ "function", "getKind", "(", "node", ")", "{", "const", "parent", "=", "node", ".", "parent", ";", "let", "kind", "=", "\"\"", ";", "if", "(", "node", ".", "type", "===", "\"ArrowFunctionExpression\"", ")", "{", "return", "\"arrowFunctions\"", ";", "}", "if", "(", "parent", ".", "type", "===", "\"Property\"", ")", "{", "if", "(", "parent", ".", "kind", "===", "\"get\"", ")", "{", "return", "\"getters\"", ";", "}", "if", "(", "parent", ".", "kind", "===", "\"set\"", ")", "{", "return", "\"setters\"", ";", "}", "kind", "=", "parent", ".", "method", "?", "\"methods\"", ":", "\"functions\"", ";", "}", "else", "if", "(", "parent", ".", "type", "===", "\"MethodDefinition\"", ")", "{", "if", "(", "parent", ".", "kind", "===", "\"get\"", ")", "{", "return", "\"getters\"", ";", "}", "if", "(", "parent", ".", "kind", "===", "\"set\"", ")", "{", "return", "\"setters\"", ";", "}", "if", "(", "parent", ".", "kind", "===", "\"constructor\"", ")", "{", "return", "\"constructors\"", ";", "}", "kind", "=", "\"methods\"", ";", "}", "else", "{", "kind", "=", "\"functions\"", ";", "}", "let", "prefix", "=", "\"\"", ";", "if", "(", "node", ".", "generator", ")", "{", "prefix", "=", "\"generator\"", ";", "}", "else", "if", "(", "node", ".", "async", ")", "{", "prefix", "=", "\"async\"", ";", "}", "else", "{", "return", "kind", ";", "}", "return", "prefix", "+", "kind", "[", "0", "]", ".", "toUpperCase", "(", ")", "+", "kind", ".", "slice", "(", "1", ")", ";", "}" ]
Gets the kind of a given function node. @param {ASTNode} node - A function node to get. This is one of an ArrowFunctionExpression, a FunctionDeclaration, or a FunctionExpression. @returns {string} The kind of the function. This is one of "functions", "arrowFunctions", "generatorFunctions", "asyncFunctions", "methods", "generatorMethods", "asyncMethods", "getters", "setters", and "constructors".
[ "Gets", "the", "kind", "of", "a", "given", "function", "node", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-empty-function.js#L40-L85
train
eslint/eslint
lib/rules/no-empty-function.js
reportIfEmpty
function reportIfEmpty(node) { const kind = getKind(node); const name = astUtils.getFunctionNameWithKind(node); const innerComments = sourceCode.getTokens(node.body, { includeComments: true, filter: astUtils.isCommentToken }); if (allowed.indexOf(kind) === -1 && node.body.type === "BlockStatement" && node.body.body.length === 0 && innerComments.length === 0 ) { context.report({ node, loc: node.body.loc.start, messageId: "unexpected", data: { name } }); } }
javascript
function reportIfEmpty(node) { const kind = getKind(node); const name = astUtils.getFunctionNameWithKind(node); const innerComments = sourceCode.getTokens(node.body, { includeComments: true, filter: astUtils.isCommentToken }); if (allowed.indexOf(kind) === -1 && node.body.type === "BlockStatement" && node.body.body.length === 0 && innerComments.length === 0 ) { context.report({ node, loc: node.body.loc.start, messageId: "unexpected", data: { name } }); } }
[ "function", "reportIfEmpty", "(", "node", ")", "{", "const", "kind", "=", "getKind", "(", "node", ")", ";", "const", "name", "=", "astUtils", ".", "getFunctionNameWithKind", "(", "node", ")", ";", "const", "innerComments", "=", "sourceCode", ".", "getTokens", "(", "node", ".", "body", ",", "{", "includeComments", ":", "true", ",", "filter", ":", "astUtils", ".", "isCommentToken", "}", ")", ";", "if", "(", "allowed", ".", "indexOf", "(", "kind", ")", "===", "-", "1", "&&", "node", ".", "body", ".", "type", "===", "\"BlockStatement\"", "&&", "node", ".", "body", ".", "body", ".", "length", "===", "0", "&&", "innerComments", ".", "length", "===", "0", ")", "{", "context", ".", "report", "(", "{", "node", ",", "loc", ":", "node", ".", "body", ".", "loc", ".", "start", ",", "messageId", ":", "\"unexpected\"", ",", "data", ":", "{", "name", "}", "}", ")", ";", "}", "}" ]
Reports a given function node if the node matches the following patterns. - Not allowed by options. - The body is empty. - The body doesn't have any comments. @param {ASTNode} node - A function node to report. This is one of an ArrowFunctionExpression, a FunctionDeclaration, or a FunctionExpression. @returns {void}
[ "Reports", "a", "given", "function", "node", "if", "the", "node", "matches", "the", "following", "patterns", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-empty-function.js#L139-L159
train
eslint/eslint
lib/rules/no-unused-labels.js
enterLabeledScope
function enterLabeledScope(node) { scopeInfo = { label: node.label.name, used: false, upper: scopeInfo }; }
javascript
function enterLabeledScope(node) { scopeInfo = { label: node.label.name, used: false, upper: scopeInfo }; }
[ "function", "enterLabeledScope", "(", "node", ")", "{", "scopeInfo", "=", "{", "label", ":", "node", ".", "label", ".", "name", ",", "used", ":", "false", ",", "upper", ":", "scopeInfo", "}", ";", "}" ]
Adds a scope info to the stack. @param {ASTNode} node - A node to add. This is a LabeledStatement. @returns {void}
[ "Adds", "a", "scope", "info", "to", "the", "stack", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-unused-labels.js#L42-L48
train
eslint/eslint
lib/rules/no-unused-labels.js
exitLabeledScope
function exitLabeledScope(node) { if (!scopeInfo.used) { context.report({ node: node.label, messageId: "unused", data: node.label, fix(fixer) { /* * Only perform a fix if there are no comments between the label and the body. This will be the case * when there is exactly one token/comment (the ":") between the label and the body. */ if (sourceCode.getTokenAfter(node.label, { includeComments: true }) === sourceCode.getTokenBefore(node.body, { includeComments: true })) { return fixer.removeRange([node.range[0], node.body.range[0]]); } return null; } }); } scopeInfo = scopeInfo.upper; }
javascript
function exitLabeledScope(node) { if (!scopeInfo.used) { context.report({ node: node.label, messageId: "unused", data: node.label, fix(fixer) { /* * Only perform a fix if there are no comments between the label and the body. This will be the case * when there is exactly one token/comment (the ":") between the label and the body. */ if (sourceCode.getTokenAfter(node.label, { includeComments: true }) === sourceCode.getTokenBefore(node.body, { includeComments: true })) { return fixer.removeRange([node.range[0], node.body.range[0]]); } return null; } }); } scopeInfo = scopeInfo.upper; }
[ "function", "exitLabeledScope", "(", "node", ")", "{", "if", "(", "!", "scopeInfo", ".", "used", ")", "{", "context", ".", "report", "(", "{", "node", ":", "node", ".", "label", ",", "messageId", ":", "\"unused\"", ",", "data", ":", "node", ".", "label", ",", "fix", "(", "fixer", ")", "{", "if", "(", "sourceCode", ".", "getTokenAfter", "(", "node", ".", "label", ",", "{", "includeComments", ":", "true", "}", ")", "===", "sourceCode", ".", "getTokenBefore", "(", "node", ".", "body", ",", "{", "includeComments", ":", "true", "}", ")", ")", "{", "return", "fixer", ".", "removeRange", "(", "[", "node", ".", "range", "[", "0", "]", ",", "node", ".", "body", ".", "range", "[", "0", "]", "]", ")", ";", "}", "return", "null", ";", "}", "}", ")", ";", "}", "scopeInfo", "=", "scopeInfo", ".", "upper", ";", "}" ]
Removes the top of the stack. At the same time, this reports the label if it's never used. @param {ASTNode} node - A node to report. This is a LabeledStatement. @returns {void}
[ "Removes", "the", "top", "of", "the", "stack", ".", "At", "the", "same", "time", "this", "reports", "the", "label", "if", "it", "s", "never", "used", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-unused-labels.js#L57-L80
train
eslint/eslint
lib/rules/no-unused-labels.js
markAsUsed
function markAsUsed(node) { if (!node.label) { return; } const label = node.label.name; let info = scopeInfo; while (info) { if (info.label === label) { info.used = true; break; } info = info.upper; } }
javascript
function markAsUsed(node) { if (!node.label) { return; } const label = node.label.name; let info = scopeInfo; while (info) { if (info.label === label) { info.used = true; break; } info = info.upper; } }
[ "function", "markAsUsed", "(", "node", ")", "{", "if", "(", "!", "node", ".", "label", ")", "{", "return", ";", "}", "const", "label", "=", "node", ".", "label", ".", "name", ";", "let", "info", "=", "scopeInfo", ";", "while", "(", "info", ")", "{", "if", "(", "info", ".", "label", "===", "label", ")", "{", "info", ".", "used", "=", "true", ";", "break", ";", "}", "info", "=", "info", ".", "upper", ";", "}", "}" ]
Marks the label of a given node as used. @param {ASTNode} node - A node to mark. This is a BreakStatement or ContinueStatement. @returns {void}
[ "Marks", "the", "label", "of", "a", "given", "node", "as", "used", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-unused-labels.js#L89-L104
train
eslint/eslint
lib/rules/padding-line-between-statements.js
isIIFEStatement
function isIIFEStatement(node) { if (node.type === "ExpressionStatement") { let call = node.expression; if (call.type === "UnaryExpression") { call = call.argument; } return call.type === "CallExpression" && astUtils.isFunction(call.callee); } return false; }
javascript
function isIIFEStatement(node) { if (node.type === "ExpressionStatement") { let call = node.expression; if (call.type === "UnaryExpression") { call = call.argument; } return call.type === "CallExpression" && astUtils.isFunction(call.callee); } return false; }
[ "function", "isIIFEStatement", "(", "node", ")", "{", "if", "(", "node", ".", "type", "===", "\"ExpressionStatement\"", ")", "{", "let", "call", "=", "node", ".", "expression", ";", "if", "(", "call", ".", "type", "===", "\"UnaryExpression\"", ")", "{", "call", "=", "call", ".", "argument", ";", "}", "return", "call", ".", "type", "===", "\"CallExpression\"", "&&", "astUtils", ".", "isFunction", "(", "call", ".", "callee", ")", ";", "}", "return", "false", ";", "}" ]
Checks the given node is an expression statement of IIFE. @param {ASTNode} node The node to check. @returns {boolean} `true` if the node is an expression statement of IIFE. @private
[ "Checks", "the", "given", "node", "is", "an", "expression", "statement", "of", "IIFE", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/padding-line-between-statements.js#L91-L101
train
eslint/eslint
lib/rules/padding-line-between-statements.js
isBlockLikeStatement
function isBlockLikeStatement(sourceCode, node) { // do-while with a block is a block-like statement. if (node.type === "DoWhileStatement" && node.body.type === "BlockStatement") { return true; } /* * IIFE is a block-like statement specially from * JSCS#disallowPaddingNewLinesAfterBlocks. */ if (isIIFEStatement(node)) { return true; } // Checks the last token is a closing brace of blocks. const lastToken = sourceCode.getLastToken(node, astUtils.isNotSemicolonToken); const belongingNode = lastToken && astUtils.isClosingBraceToken(lastToken) ? sourceCode.getNodeByRangeIndex(lastToken.range[0]) : null; return Boolean(belongingNode) && ( belongingNode.type === "BlockStatement" || belongingNode.type === "SwitchStatement" ); }
javascript
function isBlockLikeStatement(sourceCode, node) { // do-while with a block is a block-like statement. if (node.type === "DoWhileStatement" && node.body.type === "BlockStatement") { return true; } /* * IIFE is a block-like statement specially from * JSCS#disallowPaddingNewLinesAfterBlocks. */ if (isIIFEStatement(node)) { return true; } // Checks the last token is a closing brace of blocks. const lastToken = sourceCode.getLastToken(node, astUtils.isNotSemicolonToken); const belongingNode = lastToken && astUtils.isClosingBraceToken(lastToken) ? sourceCode.getNodeByRangeIndex(lastToken.range[0]) : null; return Boolean(belongingNode) && ( belongingNode.type === "BlockStatement" || belongingNode.type === "SwitchStatement" ); }
[ "function", "isBlockLikeStatement", "(", "sourceCode", ",", "node", ")", "{", "if", "(", "node", ".", "type", "===", "\"DoWhileStatement\"", "&&", "node", ".", "body", ".", "type", "===", "\"BlockStatement\"", ")", "{", "return", "true", ";", "}", "if", "(", "isIIFEStatement", "(", "node", ")", ")", "{", "return", "true", ";", "}", "const", "lastToken", "=", "sourceCode", ".", "getLastToken", "(", "node", ",", "astUtils", ".", "isNotSemicolonToken", ")", ";", "const", "belongingNode", "=", "lastToken", "&&", "astUtils", ".", "isClosingBraceToken", "(", "lastToken", ")", "?", "sourceCode", ".", "getNodeByRangeIndex", "(", "lastToken", ".", "range", "[", "0", "]", ")", ":", "null", ";", "return", "Boolean", "(", "belongingNode", ")", "&&", "(", "belongingNode", ".", "type", "===", "\"BlockStatement\"", "||", "belongingNode", ".", "type", "===", "\"SwitchStatement\"", ")", ";", "}" ]
Checks whether the given node is a block-like statement. This checks the last token of the node is the closing brace of a block. @param {SourceCode} sourceCode The source code to get tokens. @param {ASTNode} node The node to check. @returns {boolean} `true` if the node is a block-like statement. @private
[ "Checks", "whether", "the", "given", "node", "is", "a", "block", "-", "like", "statement", ".", "This", "checks", "the", "last", "token", "of", "the", "node", "is", "the", "closing", "brace", "of", "a", "block", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/padding-line-between-statements.js#L112-L137
train
eslint/eslint
lib/rules/padding-line-between-statements.js
isDirective
function isDirective(node, sourceCode) { return ( node.type === "ExpressionStatement" && ( node.parent.type === "Program" || ( node.parent.type === "BlockStatement" && astUtils.isFunction(node.parent.parent) ) ) && node.expression.type === "Literal" && typeof node.expression.value === "string" && !astUtils.isParenthesised(sourceCode, node.expression) ); }
javascript
function isDirective(node, sourceCode) { return ( node.type === "ExpressionStatement" && ( node.parent.type === "Program" || ( node.parent.type === "BlockStatement" && astUtils.isFunction(node.parent.parent) ) ) && node.expression.type === "Literal" && typeof node.expression.value === "string" && !astUtils.isParenthesised(sourceCode, node.expression) ); }
[ "function", "isDirective", "(", "node", ",", "sourceCode", ")", "{", "return", "(", "node", ".", "type", "===", "\"ExpressionStatement\"", "&&", "(", "node", ".", "parent", ".", "type", "===", "\"Program\"", "||", "(", "node", ".", "parent", ".", "type", "===", "\"BlockStatement\"", "&&", "astUtils", ".", "isFunction", "(", "node", ".", "parent", ".", "parent", ")", ")", ")", "&&", "node", ".", "expression", ".", "type", "===", "\"Literal\"", "&&", "typeof", "node", ".", "expression", ".", "value", "===", "\"string\"", "&&", "!", "astUtils", ".", "isParenthesised", "(", "sourceCode", ",", "node", ".", "expression", ")", ")", ";", "}" ]
Check whether the given node is a directive or not. @param {ASTNode} node The node to check. @param {SourceCode} sourceCode The source code object to get tokens. @returns {boolean} `true` if the node is a directive.
[ "Check", "whether", "the", "given", "node", "is", "a", "directive", "or", "not", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/padding-line-between-statements.js#L145-L159
train
eslint/eslint
lib/rules/padding-line-between-statements.js
isDirectivePrologue
function isDirectivePrologue(node, sourceCode) { if (isDirective(node, sourceCode)) { for (const sibling of node.parent.body) { if (sibling === node) { break; } if (!isDirective(sibling, sourceCode)) { return false; } } return true; } return false; }
javascript
function isDirectivePrologue(node, sourceCode) { if (isDirective(node, sourceCode)) { for (const sibling of node.parent.body) { if (sibling === node) { break; } if (!isDirective(sibling, sourceCode)) { return false; } } return true; } return false; }
[ "function", "isDirectivePrologue", "(", "node", ",", "sourceCode", ")", "{", "if", "(", "isDirective", "(", "node", ",", "sourceCode", ")", ")", "{", "for", "(", "const", "sibling", "of", "node", ".", "parent", ".", "body", ")", "{", "if", "(", "sibling", "===", "node", ")", "{", "break", ";", "}", "if", "(", "!", "isDirective", "(", "sibling", ",", "sourceCode", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}", "return", "false", ";", "}" ]
Check whether the given node is a part of directive prologue or not. @param {ASTNode} node The node to check. @param {SourceCode} sourceCode The source code object to get tokens. @returns {boolean} `true` if the node is a part of directive prologue.
[ "Check", "whether", "the", "given", "node", "is", "a", "part", "of", "directive", "prologue", "or", "not", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/padding-line-between-statements.js#L167-L180
train
eslint/eslint
lib/rules/padding-line-between-statements.js
getActualLastToken
function getActualLastToken(sourceCode, node) { const semiToken = sourceCode.getLastToken(node); const prevToken = sourceCode.getTokenBefore(semiToken); const nextToken = sourceCode.getTokenAfter(semiToken); const isSemicolonLessStyle = Boolean( prevToken && nextToken && prevToken.range[0] >= node.range[0] && astUtils.isSemicolonToken(semiToken) && semiToken.loc.start.line !== prevToken.loc.end.line && semiToken.loc.end.line === nextToken.loc.start.line ); return isSemicolonLessStyle ? prevToken : semiToken; }
javascript
function getActualLastToken(sourceCode, node) { const semiToken = sourceCode.getLastToken(node); const prevToken = sourceCode.getTokenBefore(semiToken); const nextToken = sourceCode.getTokenAfter(semiToken); const isSemicolonLessStyle = Boolean( prevToken && nextToken && prevToken.range[0] >= node.range[0] && astUtils.isSemicolonToken(semiToken) && semiToken.loc.start.line !== prevToken.loc.end.line && semiToken.loc.end.line === nextToken.loc.start.line ); return isSemicolonLessStyle ? prevToken : semiToken; }
[ "function", "getActualLastToken", "(", "sourceCode", ",", "node", ")", "{", "const", "semiToken", "=", "sourceCode", ".", "getLastToken", "(", "node", ")", ";", "const", "prevToken", "=", "sourceCode", ".", "getTokenBefore", "(", "semiToken", ")", ";", "const", "nextToken", "=", "sourceCode", ".", "getTokenAfter", "(", "semiToken", ")", ";", "const", "isSemicolonLessStyle", "=", "Boolean", "(", "prevToken", "&&", "nextToken", "&&", "prevToken", ".", "range", "[", "0", "]", ">=", "node", ".", "range", "[", "0", "]", "&&", "astUtils", ".", "isSemicolonToken", "(", "semiToken", ")", "&&", "semiToken", ".", "loc", ".", "start", ".", "line", "!==", "prevToken", ".", "loc", ".", "end", ".", "line", "&&", "semiToken", ".", "loc", ".", "end", ".", "line", "===", "nextToken", ".", "loc", ".", "start", ".", "line", ")", ";", "return", "isSemicolonLessStyle", "?", "prevToken", ":", "semiToken", ";", "}" ]
Gets the actual last token. If a semicolon is semicolon-less style's semicolon, this ignores it. For example: foo() ;[1, 2, 3].forEach(bar) @param {SourceCode} sourceCode The source code to get tokens. @param {ASTNode} node The node to get. @returns {Token} The actual last token. @private
[ "Gets", "the", "actual", "last", "token", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/padding-line-between-statements.js#L196-L210
train
eslint/eslint
lib/rules/padding-line-between-statements.js
verifyForNever
function verifyForNever(context, _, nextNode, paddingLines) { if (paddingLines.length === 0) { return; } context.report({ node: nextNode, message: "Unexpected blank line before this statement.", fix(fixer) { if (paddingLines.length >= 2) { return null; } const prevToken = paddingLines[0][0]; const nextToken = paddingLines[0][1]; const start = prevToken.range[1]; const end = nextToken.range[0]; const text = context.getSourceCode().text .slice(start, end) .replace(PADDING_LINE_SEQUENCE, replacerToRemovePaddingLines); return fixer.replaceTextRange([start, end], text); } }); }
javascript
function verifyForNever(context, _, nextNode, paddingLines) { if (paddingLines.length === 0) { return; } context.report({ node: nextNode, message: "Unexpected blank line before this statement.", fix(fixer) { if (paddingLines.length >= 2) { return null; } const prevToken = paddingLines[0][0]; const nextToken = paddingLines[0][1]; const start = prevToken.range[1]; const end = nextToken.range[0]; const text = context.getSourceCode().text .slice(start, end) .replace(PADDING_LINE_SEQUENCE, replacerToRemovePaddingLines); return fixer.replaceTextRange([start, end], text); } }); }
[ "function", "verifyForNever", "(", "context", ",", "_", ",", "nextNode", ",", "paddingLines", ")", "{", "if", "(", "paddingLines", ".", "length", "===", "0", ")", "{", "return", ";", "}", "context", ".", "report", "(", "{", "node", ":", "nextNode", ",", "message", ":", "\"Unexpected blank line before this statement.\"", ",", "fix", "(", "fixer", ")", "{", "if", "(", "paddingLines", ".", "length", ">=", "2", ")", "{", "return", "null", ";", "}", "const", "prevToken", "=", "paddingLines", "[", "0", "]", "[", "0", "]", ";", "const", "nextToken", "=", "paddingLines", "[", "0", "]", "[", "1", "]", ";", "const", "start", "=", "prevToken", ".", "range", "[", "1", "]", ";", "const", "end", "=", "nextToken", ".", "range", "[", "0", "]", ";", "const", "text", "=", "context", ".", "getSourceCode", "(", ")", ".", "text", ".", "slice", "(", "start", ",", "end", ")", ".", "replace", "(", "PADDING_LINE_SEQUENCE", ",", "replacerToRemovePaddingLines", ")", ";", "return", "fixer", ".", "replaceTextRange", "(", "[", "start", ",", "end", "]", ",", "text", ")", ";", "}", "}", ")", ";", "}" ]
Check and report statements for `never` configuration. This autofix removes blank lines between the given 2 statements. However, if comments exist between 2 blank lines, it does not remove those blank lines automatically. @param {RuleContext} context The rule context to report. @param {ASTNode} _ Unused. The previous node to check. @param {ASTNode} nextNode The next node to check. @param {Array<Token[]>} paddingLines The array of token pairs that blank lines exist between the pair. @returns {void} @private
[ "Check", "and", "report", "statements", "for", "never", "configuration", ".", "This", "autofix", "removes", "blank", "lines", "between", "the", "given", "2", "statements", ".", "However", "if", "comments", "exist", "between", "2", "blank", "lines", "it", "does", "not", "remove", "those", "blank", "lines", "automatically", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/padding-line-between-statements.js#L248-L272
train
eslint/eslint
lib/rules/padding-line-between-statements.js
verifyForAlways
function verifyForAlways(context, prevNode, nextNode, paddingLines) { if (paddingLines.length > 0) { return; } context.report({ node: nextNode, message: "Expected blank line before this statement.", fix(fixer) { const sourceCode = context.getSourceCode(); let prevToken = getActualLastToken(sourceCode, prevNode); const nextToken = sourceCode.getFirstTokenBetween( prevToken, nextNode, { includeComments: true, /** * Skip the trailing comments of the previous node. * This inserts a blank line after the last trailing comment. * * For example: * * foo(); // trailing comment. * // comment. * bar(); * * Get fixed to: * * foo(); // trailing comment. * * // comment. * bar(); * * @param {Token} token The token to check. * @returns {boolean} `true` if the token is not a trailing comment. * @private */ filter(token) { if (astUtils.isTokenOnSameLine(prevToken, token)) { prevToken = token; return false; } return true; } } ) || nextNode; const insertText = astUtils.isTokenOnSameLine(prevToken, nextToken) ? "\n\n" : "\n"; return fixer.insertTextAfter(prevToken, insertText); } }); }
javascript
function verifyForAlways(context, prevNode, nextNode, paddingLines) { if (paddingLines.length > 0) { return; } context.report({ node: nextNode, message: "Expected blank line before this statement.", fix(fixer) { const sourceCode = context.getSourceCode(); let prevToken = getActualLastToken(sourceCode, prevNode); const nextToken = sourceCode.getFirstTokenBetween( prevToken, nextNode, { includeComments: true, /** * Skip the trailing comments of the previous node. * This inserts a blank line after the last trailing comment. * * For example: * * foo(); // trailing comment. * // comment. * bar(); * * Get fixed to: * * foo(); // trailing comment. * * // comment. * bar(); * * @param {Token} token The token to check. * @returns {boolean} `true` if the token is not a trailing comment. * @private */ filter(token) { if (astUtils.isTokenOnSameLine(prevToken, token)) { prevToken = token; return false; } return true; } } ) || nextNode; const insertText = astUtils.isTokenOnSameLine(prevToken, nextToken) ? "\n\n" : "\n"; return fixer.insertTextAfter(prevToken, insertText); } }); }
[ "function", "verifyForAlways", "(", "context", ",", "prevNode", ",", "nextNode", ",", "paddingLines", ")", "{", "if", "(", "paddingLines", ".", "length", ">", "0", ")", "{", "return", ";", "}", "context", ".", "report", "(", "{", "node", ":", "nextNode", ",", "message", ":", "\"Expected blank line before this statement.\"", ",", "fix", "(", "fixer", ")", "{", "const", "sourceCode", "=", "context", ".", "getSourceCode", "(", ")", ";", "let", "prevToken", "=", "getActualLastToken", "(", "sourceCode", ",", "prevNode", ")", ";", "const", "nextToken", "=", "sourceCode", ".", "getFirstTokenBetween", "(", "prevToken", ",", "nextNode", ",", "{", "includeComments", ":", "true", ",", "filter", "(", "token", ")", "{", "if", "(", "astUtils", ".", "isTokenOnSameLine", "(", "prevToken", ",", "token", ")", ")", "{", "prevToken", "=", "token", ";", "return", "false", ";", "}", "return", "true", ";", "}", "}", ")", "||", "nextNode", ";", "const", "insertText", "=", "astUtils", ".", "isTokenOnSameLine", "(", "prevToken", ",", "nextToken", ")", "?", "\"\\n\\n\"", ":", "\\n", ";", "\\n", "}", "}", ")", ";", "}" ]
Check and report statements for `always` configuration. This autofix inserts a blank line between the given 2 statements. If the `prevNode` has trailing comments, it inserts a blank line after the trailing comments. @param {RuleContext} context The rule context to report. @param {ASTNode} prevNode The previous node to check. @param {ASTNode} nextNode The next node to check. @param {Array<Token[]>} paddingLines The array of token pairs that blank lines exist between the pair. @returns {void} @private
[ "Check", "and", "report", "statements", "for", "always", "configuration", ".", "This", "autofix", "inserts", "a", "blank", "line", "between", "the", "given", "2", "statements", ".", "If", "the", "prevNode", "has", "trailing", "comments", "it", "inserts", "a", "blank", "line", "after", "the", "trailing", "comments", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/padding-line-between-statements.js#L288-L342
train
eslint/eslint
lib/rules/padding-line-between-statements.js
match
function match(node, type) { let innerStatementNode = node; while (innerStatementNode.type === "LabeledStatement") { innerStatementNode = innerStatementNode.body; } if (Array.isArray(type)) { return type.some(match.bind(null, innerStatementNode)); } return StatementTypes[type].test(innerStatementNode, sourceCode); }
javascript
function match(node, type) { let innerStatementNode = node; while (innerStatementNode.type === "LabeledStatement") { innerStatementNode = innerStatementNode.body; } if (Array.isArray(type)) { return type.some(match.bind(null, innerStatementNode)); } return StatementTypes[type].test(innerStatementNode, sourceCode); }
[ "function", "match", "(", "node", ",", "type", ")", "{", "let", "innerStatementNode", "=", "node", ";", "while", "(", "innerStatementNode", ".", "type", "===", "\"LabeledStatement\"", ")", "{", "innerStatementNode", "=", "innerStatementNode", ".", "body", ";", "}", "if", "(", "Array", ".", "isArray", "(", "type", ")", ")", "{", "return", "type", ".", "some", "(", "match", ".", "bind", "(", "null", ",", "innerStatementNode", ")", ")", ";", "}", "return", "StatementTypes", "[", "type", "]", ".", "test", "(", "innerStatementNode", ",", "sourceCode", ")", ";", "}" ]
Checks whether the given node matches the given type. @param {ASTNode} node The statement node to check. @param {string|string[]} type The statement type to check. @returns {boolean} `true` if the statement node matched the type. @private
[ "Checks", "whether", "the", "given", "node", "matches", "the", "given", "type", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/padding-line-between-statements.js#L520-L530
train
eslint/eslint
lib/rules/padding-line-between-statements.js
getPaddingType
function getPaddingType(prevNode, nextNode) { for (let i = configureList.length - 1; i >= 0; --i) { const configure = configureList[i]; const matched = match(prevNode, configure.prev) && match(nextNode, configure.next); if (matched) { return PaddingTypes[configure.blankLine]; } } return PaddingTypes.any; }
javascript
function getPaddingType(prevNode, nextNode) { for (let i = configureList.length - 1; i >= 0; --i) { const configure = configureList[i]; const matched = match(prevNode, configure.prev) && match(nextNode, configure.next); if (matched) { return PaddingTypes[configure.blankLine]; } } return PaddingTypes.any; }
[ "function", "getPaddingType", "(", "prevNode", ",", "nextNode", ")", "{", "for", "(", "let", "i", "=", "configureList", ".", "length", "-", "1", ";", "i", ">=", "0", ";", "--", "i", ")", "{", "const", "configure", "=", "configureList", "[", "i", "]", ";", "const", "matched", "=", "match", "(", "prevNode", ",", "configure", ".", "prev", ")", "&&", "match", "(", "nextNode", ",", "configure", ".", "next", ")", ";", "if", "(", "matched", ")", "{", "return", "PaddingTypes", "[", "configure", ".", "blankLine", "]", ";", "}", "}", "return", "PaddingTypes", ".", "any", ";", "}" ]
Finds the last matched configure from configureList. @param {ASTNode} prevNode The previous statement to match. @param {ASTNode} nextNode The current statement to match. @returns {Object} The tester of the last matched configure. @private
[ "Finds", "the", "last", "matched", "configure", "from", "configureList", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/padding-line-between-statements.js#L540-L552
train
eslint/eslint
lib/rules/padding-line-between-statements.js
getPaddingLineSequences
function getPaddingLineSequences(prevNode, nextNode) { const pairs = []; let prevToken = getActualLastToken(sourceCode, prevNode); if (nextNode.loc.start.line - prevToken.loc.end.line >= 2) { do { const token = sourceCode.getTokenAfter( prevToken, { includeComments: true } ); if (token.loc.start.line - prevToken.loc.end.line >= 2) { pairs.push([prevToken, token]); } prevToken = token; } while (prevToken.range[0] < nextNode.range[0]); } return pairs; }
javascript
function getPaddingLineSequences(prevNode, nextNode) { const pairs = []; let prevToken = getActualLastToken(sourceCode, prevNode); if (nextNode.loc.start.line - prevToken.loc.end.line >= 2) { do { const token = sourceCode.getTokenAfter( prevToken, { includeComments: true } ); if (token.loc.start.line - prevToken.loc.end.line >= 2) { pairs.push([prevToken, token]); } prevToken = token; } while (prevToken.range[0] < nextNode.range[0]); } return pairs; }
[ "function", "getPaddingLineSequences", "(", "prevNode", ",", "nextNode", ")", "{", "const", "pairs", "=", "[", "]", ";", "let", "prevToken", "=", "getActualLastToken", "(", "sourceCode", ",", "prevNode", ")", ";", "if", "(", "nextNode", ".", "loc", ".", "start", ".", "line", "-", "prevToken", ".", "loc", ".", "end", ".", "line", ">=", "2", ")", "{", "do", "{", "const", "token", "=", "sourceCode", ".", "getTokenAfter", "(", "prevToken", ",", "{", "includeComments", ":", "true", "}", ")", ";", "if", "(", "token", ".", "loc", ".", "start", ".", "line", "-", "prevToken", ".", "loc", ".", "end", ".", "line", ">=", "2", ")", "{", "pairs", ".", "push", "(", "[", "prevToken", ",", "token", "]", ")", ";", "}", "prevToken", "=", "token", ";", "}", "while", "(", "prevToken", ".", "range", "[", "0", "]", "<", "nextNode", ".", "range", "[", "0", "]", ")", ";", "}", "return", "pairs", ";", "}" ]
Gets padding line sequences between the given 2 statements. Comments are separators of the padding line sequences. @param {ASTNode} prevNode The previous statement to count. @param {ASTNode} nextNode The current statement to count. @returns {Array<Token[]>} The array of token pairs. @private
[ "Gets", "padding", "line", "sequences", "between", "the", "given", "2", "statements", ".", "Comments", "are", "separators", "of", "the", "padding", "line", "sequences", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/padding-line-between-statements.js#L563-L583
train
eslint/eslint
lib/rules/padding-line-between-statements.js
verify
function verify(node) { const parentType = node.parent.type; const validParent = astUtils.STATEMENT_LIST_PARENTS.has(parentType) || parentType === "SwitchStatement"; if (!validParent) { return; } // Save this node as the current previous statement. const prevNode = scopeInfo.prevNode; // Verify. if (prevNode) { const type = getPaddingType(prevNode, node); const paddingLines = getPaddingLineSequences(prevNode, node); type.verify(context, prevNode, node, paddingLines); } scopeInfo.prevNode = node; }
javascript
function verify(node) { const parentType = node.parent.type; const validParent = astUtils.STATEMENT_LIST_PARENTS.has(parentType) || parentType === "SwitchStatement"; if (!validParent) { return; } // Save this node as the current previous statement. const prevNode = scopeInfo.prevNode; // Verify. if (prevNode) { const type = getPaddingType(prevNode, node); const paddingLines = getPaddingLineSequences(prevNode, node); type.verify(context, prevNode, node, paddingLines); } scopeInfo.prevNode = node; }
[ "function", "verify", "(", "node", ")", "{", "const", "parentType", "=", "node", ".", "parent", ".", "type", ";", "const", "validParent", "=", "astUtils", ".", "STATEMENT_LIST_PARENTS", ".", "has", "(", "parentType", ")", "||", "parentType", "===", "\"SwitchStatement\"", ";", "if", "(", "!", "validParent", ")", "{", "return", ";", "}", "const", "prevNode", "=", "scopeInfo", ".", "prevNode", ";", "if", "(", "prevNode", ")", "{", "const", "type", "=", "getPaddingType", "(", "prevNode", ",", "node", ")", ";", "const", "paddingLines", "=", "getPaddingLineSequences", "(", "prevNode", ",", "node", ")", ";", "type", ".", "verify", "(", "context", ",", "prevNode", ",", "node", ",", "paddingLines", ")", ";", "}", "scopeInfo", ".", "prevNode", "=", "node", ";", "}" ]
Verify padding lines between the given node and the previous node. @param {ASTNode} node The node to verify. @returns {void} @private
[ "Verify", "padding", "lines", "between", "the", "given", "node", "and", "the", "previous", "node", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/padding-line-between-statements.js#L592-L614
train
eslint/eslint
lib/rules/dot-location.js
checkDotLocation
function checkDotLocation(obj, prop, node) { const dot = sourceCode.getTokenBefore(prop); const textBeforeDot = sourceCode.getText().slice(obj.range[1], dot.range[0]); const textAfterDot = sourceCode.getText().slice(dot.range[1], prop.range[0]); if (dot.type === "Punctuator" && dot.value === ".") { if (onObject) { if (!astUtils.isTokenOnSameLine(obj, dot)) { const neededTextAfterObj = astUtils.isDecimalInteger(obj) ? " " : ""; context.report({ node, loc: dot.loc.start, messageId: "expectedDotAfterObject", fix: fixer => fixer.replaceTextRange([obj.range[1], prop.range[0]], `${neededTextAfterObj}.${textBeforeDot}${textAfterDot}`) }); } } else if (!astUtils.isTokenOnSameLine(dot, prop)) { context.report({ node, loc: dot.loc.start, messageId: "expectedDotBeforeProperty", fix: fixer => fixer.replaceTextRange([obj.range[1], prop.range[0]], `${textBeforeDot}${textAfterDot}.`) }); } } }
javascript
function checkDotLocation(obj, prop, node) { const dot = sourceCode.getTokenBefore(prop); const textBeforeDot = sourceCode.getText().slice(obj.range[1], dot.range[0]); const textAfterDot = sourceCode.getText().slice(dot.range[1], prop.range[0]); if (dot.type === "Punctuator" && dot.value === ".") { if (onObject) { if (!astUtils.isTokenOnSameLine(obj, dot)) { const neededTextAfterObj = astUtils.isDecimalInteger(obj) ? " " : ""; context.report({ node, loc: dot.loc.start, messageId: "expectedDotAfterObject", fix: fixer => fixer.replaceTextRange([obj.range[1], prop.range[0]], `${neededTextAfterObj}.${textBeforeDot}${textAfterDot}`) }); } } else if (!astUtils.isTokenOnSameLine(dot, prop)) { context.report({ node, loc: dot.loc.start, messageId: "expectedDotBeforeProperty", fix: fixer => fixer.replaceTextRange([obj.range[1], prop.range[0]], `${textBeforeDot}${textAfterDot}.`) }); } } }
[ "function", "checkDotLocation", "(", "obj", ",", "prop", ",", "node", ")", "{", "const", "dot", "=", "sourceCode", ".", "getTokenBefore", "(", "prop", ")", ";", "const", "textBeforeDot", "=", "sourceCode", ".", "getText", "(", ")", ".", "slice", "(", "obj", ".", "range", "[", "1", "]", ",", "dot", ".", "range", "[", "0", "]", ")", ";", "const", "textAfterDot", "=", "sourceCode", ".", "getText", "(", ")", ".", "slice", "(", "dot", ".", "range", "[", "1", "]", ",", "prop", ".", "range", "[", "0", "]", ")", ";", "if", "(", "dot", ".", "type", "===", "\"Punctuator\"", "&&", "dot", ".", "value", "===", "\".\"", ")", "{", "if", "(", "onObject", ")", "{", "if", "(", "!", "astUtils", ".", "isTokenOnSameLine", "(", "obj", ",", "dot", ")", ")", "{", "const", "neededTextAfterObj", "=", "astUtils", ".", "isDecimalInteger", "(", "obj", ")", "?", "\" \"", ":", "\"\"", ";", "context", ".", "report", "(", "{", "node", ",", "loc", ":", "dot", ".", "loc", ".", "start", ",", "messageId", ":", "\"expectedDotAfterObject\"", ",", "fix", ":", "fixer", "=>", "fixer", ".", "replaceTextRange", "(", "[", "obj", ".", "range", "[", "1", "]", ",", "prop", ".", "range", "[", "0", "]", "]", ",", "`", "${", "neededTextAfterObj", "}", "${", "textBeforeDot", "}", "${", "textAfterDot", "}", "`", ")", "}", ")", ";", "}", "}", "else", "if", "(", "!", "astUtils", ".", "isTokenOnSameLine", "(", "dot", ",", "prop", ")", ")", "{", "context", ".", "report", "(", "{", "node", ",", "loc", ":", "dot", ".", "loc", ".", "start", ",", "messageId", ":", "\"expectedDotBeforeProperty\"", ",", "fix", ":", "fixer", "=>", "fixer", ".", "replaceTextRange", "(", "[", "obj", ".", "range", "[", "1", "]", ",", "prop", ".", "range", "[", "0", "]", "]", ",", "`", "${", "textBeforeDot", "}", "${", "textAfterDot", "}", "`", ")", "}", ")", ";", "}", "}", "}" ]
Reports if the dot between object and property is on the correct loccation. @param {ASTNode} obj The object owning the property. @param {ASTNode} prop The property of the object. @param {ASTNode} node The corresponding node of the token. @returns {void}
[ "Reports", "if", "the", "dot", "between", "object", "and", "property", "is", "on", "the", "correct", "loccation", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/dot-location.js#L55-L81
train
eslint/eslint
lib/rules/nonblock-statement-body-position.js
validateStatement
function validateStatement(node, keywordName) { const option = getOption(keywordName); if (node.type === "BlockStatement" || option === "any") { return; } const tokenBefore = sourceCode.getTokenBefore(node); if (tokenBefore.loc.end.line === node.loc.start.line && option === "below") { context.report({ node, message: "Expected a linebreak before this statement.", fix: fixer => fixer.insertTextBefore(node, "\n") }); } else if (tokenBefore.loc.end.line !== node.loc.start.line && option === "beside") { context.report({ node, message: "Expected no linebreak before this statement.", fix(fixer) { if (sourceCode.getText().slice(tokenBefore.range[1], node.range[0]).trim()) { return null; } return fixer.replaceTextRange([tokenBefore.range[1], node.range[0]], " "); } }); } }
javascript
function validateStatement(node, keywordName) { const option = getOption(keywordName); if (node.type === "BlockStatement" || option === "any") { return; } const tokenBefore = sourceCode.getTokenBefore(node); if (tokenBefore.loc.end.line === node.loc.start.line && option === "below") { context.report({ node, message: "Expected a linebreak before this statement.", fix: fixer => fixer.insertTextBefore(node, "\n") }); } else if (tokenBefore.loc.end.line !== node.loc.start.line && option === "beside") { context.report({ node, message: "Expected no linebreak before this statement.", fix(fixer) { if (sourceCode.getText().slice(tokenBefore.range[1], node.range[0]).trim()) { return null; } return fixer.replaceTextRange([tokenBefore.range[1], node.range[0]], " "); } }); } }
[ "function", "validateStatement", "(", "node", ",", "keywordName", ")", "{", "const", "option", "=", "getOption", "(", "keywordName", ")", ";", "if", "(", "node", ".", "type", "===", "\"BlockStatement\"", "||", "option", "===", "\"any\"", ")", "{", "return", ";", "}", "const", "tokenBefore", "=", "sourceCode", ".", "getTokenBefore", "(", "node", ")", ";", "if", "(", "tokenBefore", ".", "loc", ".", "end", ".", "line", "===", "node", ".", "loc", ".", "start", ".", "line", "&&", "option", "===", "\"below\"", ")", "{", "context", ".", "report", "(", "{", "node", ",", "message", ":", "\"Expected a linebreak before this statement.\"", ",", "fix", ":", "fixer", "=>", "fixer", ".", "insertTextBefore", "(", "node", ",", "\"\\n\"", ")", "}", ")", ";", "}", "else", "\\n", "}" ]
Validates the location of a single-line statement @param {ASTNode} node The single-line statement @param {string} keywordName The applicable keyword name for the single-line statement @returns {void}
[ "Validates", "the", "location", "of", "a", "single", "-", "line", "statement" ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/nonblock-statement-body-position.js#L70-L97
train
eslint/eslint
lib/util/source-code-fixer.js
compareMessagesByFixRange
function compareMessagesByFixRange(a, b) { return a.fix.range[0] - b.fix.range[0] || a.fix.range[1] - b.fix.range[1]; }
javascript
function compareMessagesByFixRange(a, b) { return a.fix.range[0] - b.fix.range[0] || a.fix.range[1] - b.fix.range[1]; }
[ "function", "compareMessagesByFixRange", "(", "a", ",", "b", ")", "{", "return", "a", ".", "fix", ".", "range", "[", "0", "]", "-", "b", ".", "fix", ".", "range", "[", "0", "]", "||", "a", ".", "fix", ".", "range", "[", "1", "]", "-", "b", ".", "fix", ".", "range", "[", "1", "]", ";", "}" ]
Compares items in a messages array by range. @param {Message} a The first message. @param {Message} b The second message. @returns {int} -1 if a comes before b, 1 if a comes after b, 0 if equal. @private
[ "Compares", "items", "in", "a", "messages", "array", "by", "range", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/util/source-code-fixer.js#L26-L28
train
eslint/eslint
lib/util/source-code-fixer.js
attemptFix
function attemptFix(problem) { const fix = problem.fix; const start = fix.range[0]; const end = fix.range[1]; // Remain it as a problem if it's overlapped or it's a negative range if (lastPos >= start || start > end) { remainingMessages.push(problem); return false; } // Remove BOM. if ((start < 0 && end >= 0) || (start === 0 && fix.text.startsWith(BOM))) { output = ""; } // Make output to this fix. output += text.slice(Math.max(0, lastPos), Math.max(0, start)); output += fix.text; lastPos = end; return true; }
javascript
function attemptFix(problem) { const fix = problem.fix; const start = fix.range[0]; const end = fix.range[1]; // Remain it as a problem if it's overlapped or it's a negative range if (lastPos >= start || start > end) { remainingMessages.push(problem); return false; } // Remove BOM. if ((start < 0 && end >= 0) || (start === 0 && fix.text.startsWith(BOM))) { output = ""; } // Make output to this fix. output += text.slice(Math.max(0, lastPos), Math.max(0, start)); output += fix.text; lastPos = end; return true; }
[ "function", "attemptFix", "(", "problem", ")", "{", "const", "fix", "=", "problem", ".", "fix", ";", "const", "start", "=", "fix", ".", "range", "[", "0", "]", ";", "const", "end", "=", "fix", ".", "range", "[", "1", "]", ";", "if", "(", "lastPos", ">=", "start", "||", "start", ">", "end", ")", "{", "remainingMessages", ".", "push", "(", "problem", ")", ";", "return", "false", ";", "}", "if", "(", "(", "start", "<", "0", "&&", "end", ">=", "0", ")", "||", "(", "start", "===", "0", "&&", "fix", ".", "text", ".", "startsWith", "(", "BOM", ")", ")", ")", "{", "output", "=", "\"\"", ";", "}", "output", "+=", "text", ".", "slice", "(", "Math", ".", "max", "(", "0", ",", "lastPos", ")", ",", "Math", ".", "max", "(", "0", ",", "start", ")", ")", ";", "output", "+=", "fix", ".", "text", ";", "lastPos", "=", "end", ";", "return", "true", ";", "}" ]
Try to use the 'fix' from a problem. @param {Message} problem The message object to apply fixes from @returns {boolean} Whether fix was successfully applied
[ "Try", "to", "use", "the", "fix", "from", "a", "problem", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/util/source-code-fixer.js#L86-L107
train
eslint/eslint
lib/util/source-code.js
looksLikeExport
function looksLikeExport(astNode) { return astNode.type === "ExportDefaultDeclaration" || astNode.type === "ExportNamedDeclaration" || astNode.type === "ExportAllDeclaration" || astNode.type === "ExportSpecifier"; }
javascript
function looksLikeExport(astNode) { return astNode.type === "ExportDefaultDeclaration" || astNode.type === "ExportNamedDeclaration" || astNode.type === "ExportAllDeclaration" || astNode.type === "ExportSpecifier"; }
[ "function", "looksLikeExport", "(", "astNode", ")", "{", "return", "astNode", ".", "type", "===", "\"ExportDefaultDeclaration\"", "||", "astNode", ".", "type", "===", "\"ExportNamedDeclaration\"", "||", "astNode", ".", "type", "===", "\"ExportAllDeclaration\"", "||", "astNode", ".", "type", "===", "\"ExportSpecifier\"", ";", "}" ]
Check to see if its a ES6 export declaration. @param {ASTNode} astNode An AST node. @returns {boolean} whether the given node represents an export declaration. @private
[ "Check", "to", "see", "if", "its", "a", "ES6", "export", "declaration", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/util/source-code.js#L51-L54
train
eslint/eslint
lib/rules/no-trailing-spaces.js
getCommentLineNumbers
function getCommentLineNumbers(comments) { const lines = new Set(); comments.forEach(comment => { for (let i = comment.loc.start.line; i <= comment.loc.end.line; i++) { lines.add(i); } }); return lines; }
javascript
function getCommentLineNumbers(comments) { const lines = new Set(); comments.forEach(comment => { for (let i = comment.loc.start.line; i <= comment.loc.end.line; i++) { lines.add(i); } }); return lines; }
[ "function", "getCommentLineNumbers", "(", "comments", ")", "{", "const", "lines", "=", "new", "Set", "(", ")", ";", "comments", ".", "forEach", "(", "comment", "=>", "{", "for", "(", "let", "i", "=", "comment", ".", "loc", ".", "start", ".", "line", ";", "i", "<=", "comment", ".", "loc", ".", "end", ".", "line", ";", "i", "++", ")", "{", "lines", ".", "add", "(", "i", ")", ";", "}", "}", ")", ";", "return", "lines", ";", "}" ]
Given a list of comment nodes, return the line numbers for those comments. @param {Array} comments An array of comment nodes. @returns {number[]} An array of line numbers containing comments.
[ "Given", "a", "list", "of", "comment", "nodes", "return", "the", "line", "numbers", "for", "those", "comments", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-trailing-spaces.js#L89-L99
train
eslint/eslint
lib/rules/no-use-before-define.js
isOuterVariable
function isOuterVariable(variable, reference) { return ( variable.defs[0].type === "Variable" && variable.scope.variableScope !== reference.from.variableScope ); }
javascript
function isOuterVariable(variable, reference) { return ( variable.defs[0].type === "Variable" && variable.scope.variableScope !== reference.from.variableScope ); }
[ "function", "isOuterVariable", "(", "variable", ",", "reference", ")", "{", "return", "(", "variable", ".", "defs", "[", "0", "]", ".", "type", "===", "\"Variable\"", "&&", "variable", ".", "scope", ".", "variableScope", "!==", "reference", ".", "from", ".", "variableScope", ")", ";", "}" ]
Checks whether or not a given variable is a variable declaration in an upper function scope. @param {eslint-scope.Variable} variable - A variable to check. @param {eslint-scope.Reference} reference - A reference to check. @returns {boolean} `true` if the variable is a variable declaration.
[ "Checks", "whether", "or", "not", "a", "given", "variable", "is", "a", "variable", "declaration", "in", "an", "upper", "function", "scope", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-use-before-define.js#L67-L72
train
eslint/eslint
lib/rules/no-use-before-define.js
isInRange
function isInRange(node, location) { return node && node.range[0] <= location && location <= node.range[1]; }
javascript
function isInRange(node, location) { return node && node.range[0] <= location && location <= node.range[1]; }
[ "function", "isInRange", "(", "node", ",", "location", ")", "{", "return", "node", "&&", "node", ".", "range", "[", "0", "]", "<=", "location", "&&", "location", "<=", "node", ".", "range", "[", "1", "]", ";", "}" ]
Checks whether or not a given location is inside of the range of a given node. @param {ASTNode} node - An node to check. @param {number} location - A location to check. @returns {boolean} `true` if the location is inside of the range of the node.
[ "Checks", "whether", "or", "not", "a", "given", "location", "is", "inside", "of", "the", "range", "of", "a", "given", "node", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-use-before-define.js#L81-L83
train
eslint/eslint
lib/rules/no-use-before-define.js
isInInitializer
function isInInitializer(variable, reference) { if (variable.scope !== reference.from) { return false; } let node = variable.identifiers[0].parent; const location = reference.identifier.range[1]; while (node) { if (node.type === "VariableDeclarator") { if (isInRange(node.init, location)) { return true; } if (FOR_IN_OF_TYPE.test(node.parent.parent.type) && isInRange(node.parent.parent.right, location) ) { return true; } break; } else if (node.type === "AssignmentPattern") { if (isInRange(node.right, location)) { return true; } } else if (SENTINEL_TYPE.test(node.type)) { break; } node = node.parent; } return false; }
javascript
function isInInitializer(variable, reference) { if (variable.scope !== reference.from) { return false; } let node = variable.identifiers[0].parent; const location = reference.identifier.range[1]; while (node) { if (node.type === "VariableDeclarator") { if (isInRange(node.init, location)) { return true; } if (FOR_IN_OF_TYPE.test(node.parent.parent.type) && isInRange(node.parent.parent.right, location) ) { return true; } break; } else if (node.type === "AssignmentPattern") { if (isInRange(node.right, location)) { return true; } } else if (SENTINEL_TYPE.test(node.type)) { break; } node = node.parent; } return false; }
[ "function", "isInInitializer", "(", "variable", ",", "reference", ")", "{", "if", "(", "variable", ".", "scope", "!==", "reference", ".", "from", ")", "{", "return", "false", ";", "}", "let", "node", "=", "variable", ".", "identifiers", "[", "0", "]", ".", "parent", ";", "const", "location", "=", "reference", ".", "identifier", ".", "range", "[", "1", "]", ";", "while", "(", "node", ")", "{", "if", "(", "node", ".", "type", "===", "\"VariableDeclarator\"", ")", "{", "if", "(", "isInRange", "(", "node", ".", "init", ",", "location", ")", ")", "{", "return", "true", ";", "}", "if", "(", "FOR_IN_OF_TYPE", ".", "test", "(", "node", ".", "parent", ".", "parent", ".", "type", ")", "&&", "isInRange", "(", "node", ".", "parent", ".", "parent", ".", "right", ",", "location", ")", ")", "{", "return", "true", ";", "}", "break", ";", "}", "else", "if", "(", "node", ".", "type", "===", "\"AssignmentPattern\"", ")", "{", "if", "(", "isInRange", "(", "node", ".", "right", ",", "location", ")", ")", "{", "return", "true", ";", "}", "}", "else", "if", "(", "SENTINEL_TYPE", ".", "test", "(", "node", ".", "type", ")", ")", "{", "break", ";", "}", "node", "=", "node", ".", "parent", ";", "}", "return", "false", ";", "}" ]
Checks whether or not a given reference is inside of the initializers of a given variable. This returns `true` in the following cases: var a = a var [a = a] = list var {a = a} = obj for (var a in a) {} for (var a of a) {} @param {Variable} variable - A variable to check. @param {Reference} reference - A reference to check. @returns {boolean} `true` if the reference is inside of the initializers.
[ "Checks", "whether", "or", "not", "a", "given", "reference", "is", "inside", "of", "the", "initializers", "of", "a", "given", "variable", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-use-before-define.js#L100-L131
train
eslint/eslint
lib/rules/no-use-before-define.js
findVariablesInScope
function findVariablesInScope(scope) { scope.references.forEach(reference => { const variable = reference.resolved; /* * Skips when the reference is: * - initialization's. * - referring to an undefined variable. * - referring to a global environment variable (there're no identifiers). * - located preceded by the variable (except in initializers). * - allowed by options. */ if (reference.init || !variable || variable.identifiers.length === 0 || (variable.identifiers[0].range[1] < reference.identifier.range[1] && !isInInitializer(variable, reference)) || !isForbidden(variable, reference) ) { return; } // Reports. context.report({ node: reference.identifier, message: "'{{name}}' was used before it was defined.", data: reference.identifier }); }); scope.childScopes.forEach(findVariablesInScope); }
javascript
function findVariablesInScope(scope) { scope.references.forEach(reference => { const variable = reference.resolved; /* * Skips when the reference is: * - initialization's. * - referring to an undefined variable. * - referring to a global environment variable (there're no identifiers). * - located preceded by the variable (except in initializers). * - allowed by options. */ if (reference.init || !variable || variable.identifiers.length === 0 || (variable.identifiers[0].range[1] < reference.identifier.range[1] && !isInInitializer(variable, reference)) || !isForbidden(variable, reference) ) { return; } // Reports. context.report({ node: reference.identifier, message: "'{{name}}' was used before it was defined.", data: reference.identifier }); }); scope.childScopes.forEach(findVariablesInScope); }
[ "function", "findVariablesInScope", "(", "scope", ")", "{", "scope", ".", "references", ".", "forEach", "(", "reference", "=>", "{", "const", "variable", "=", "reference", ".", "resolved", ";", "if", "(", "reference", ".", "init", "||", "!", "variable", "||", "variable", ".", "identifiers", ".", "length", "===", "0", "||", "(", "variable", ".", "identifiers", "[", "0", "]", ".", "range", "[", "1", "]", "<", "reference", ".", "identifier", ".", "range", "[", "1", "]", "&&", "!", "isInInitializer", "(", "variable", ",", "reference", ")", ")", "||", "!", "isForbidden", "(", "variable", ",", "reference", ")", ")", "{", "return", ";", "}", "context", ".", "report", "(", "{", "node", ":", "reference", ".", "identifier", ",", "message", ":", "\"'{{name}}' was used before it was defined.\"", ",", "data", ":", "reference", ".", "identifier", "}", ")", ";", "}", ")", ";", "scope", ".", "childScopes", ".", "forEach", "(", "findVariablesInScope", ")", ";", "}" ]
Finds and validates all variables in a given scope. @param {Scope} scope The scope object. @returns {void} @private
[ "Finds", "and", "validates", "all", "variables", "in", "a", "given", "scope", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-use-before-define.js#L196-L226
train
eslint/eslint
lib/rules/semi-style.js
isLastChild
function isLastChild(node) { const t = node.parent.type; if (t === "IfStatement" && node.parent.consequent === node && node.parent.alternate) { // before `else` keyword. return true; } if (t === "DoWhileStatement") { // before `while` keyword. return true; } const nodeList = getChildren(node.parent); return nodeList !== null && nodeList[nodeList.length - 1] === node; // before `}` or etc. }
javascript
function isLastChild(node) { const t = node.parent.type; if (t === "IfStatement" && node.parent.consequent === node && node.parent.alternate) { // before `else` keyword. return true; } if (t === "DoWhileStatement") { // before `while` keyword. return true; } const nodeList = getChildren(node.parent); return nodeList !== null && nodeList[nodeList.length - 1] === node; // before `}` or etc. }
[ "function", "isLastChild", "(", "node", ")", "{", "const", "t", "=", "node", ".", "parent", ".", "type", ";", "if", "(", "t", "===", "\"IfStatement\"", "&&", "node", ".", "parent", ".", "consequent", "===", "node", "&&", "node", ".", "parent", ".", "alternate", ")", "{", "return", "true", ";", "}", "if", "(", "t", "===", "\"DoWhileStatement\"", ")", "{", "return", "true", ";", "}", "const", "nodeList", "=", "getChildren", "(", "node", ".", "parent", ")", ";", "return", "nodeList", "!==", "null", "&&", "nodeList", "[", "nodeList", ".", "length", "-", "1", "]", "===", "node", ";", "}" ]
Check whether a given node is the last statement in the parent block. @param {Node} node A node to check. @returns {boolean} `true` if the node is the last statement in the parent block.
[ "Check", "whether", "a", "given", "node", "is", "the", "last", "statement", "in", "the", "parent", "block", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/semi-style.js#L52-L64
train
eslint/eslint
lib/rules/semi-style.js
check
function check(semiToken, expected) { const prevToken = sourceCode.getTokenBefore(semiToken); const nextToken = sourceCode.getTokenAfter(semiToken); const prevIsSameLine = !prevToken || astUtils.isTokenOnSameLine(prevToken, semiToken); const nextIsSameLine = !nextToken || astUtils.isTokenOnSameLine(semiToken, nextToken); if ((expected === "last" && !prevIsSameLine) || (expected === "first" && !nextIsSameLine)) { context.report({ loc: semiToken.loc, message: "Expected this semicolon to be at {{pos}}.", data: { pos: (expected === "last") ? "the end of the previous line" : "the beginning of the next line" }, fix(fixer) { if (prevToken && nextToken && sourceCode.commentsExistBetween(prevToken, nextToken)) { return null; } const start = prevToken ? prevToken.range[1] : semiToken.range[0]; const end = nextToken ? nextToken.range[0] : semiToken.range[1]; const text = (expected === "last") ? ";\n" : "\n;"; return fixer.replaceTextRange([start, end], text); } }); } }
javascript
function check(semiToken, expected) { const prevToken = sourceCode.getTokenBefore(semiToken); const nextToken = sourceCode.getTokenAfter(semiToken); const prevIsSameLine = !prevToken || astUtils.isTokenOnSameLine(prevToken, semiToken); const nextIsSameLine = !nextToken || astUtils.isTokenOnSameLine(semiToken, nextToken); if ((expected === "last" && !prevIsSameLine) || (expected === "first" && !nextIsSameLine)) { context.report({ loc: semiToken.loc, message: "Expected this semicolon to be at {{pos}}.", data: { pos: (expected === "last") ? "the end of the previous line" : "the beginning of the next line" }, fix(fixer) { if (prevToken && nextToken && sourceCode.commentsExistBetween(prevToken, nextToken)) { return null; } const start = prevToken ? prevToken.range[1] : semiToken.range[0]; const end = nextToken ? nextToken.range[0] : semiToken.range[1]; const text = (expected === "last") ? ";\n" : "\n;"; return fixer.replaceTextRange([start, end], text); } }); } }
[ "function", "check", "(", "semiToken", ",", "expected", ")", "{", "const", "prevToken", "=", "sourceCode", ".", "getTokenBefore", "(", "semiToken", ")", ";", "const", "nextToken", "=", "sourceCode", ".", "getTokenAfter", "(", "semiToken", ")", ";", "const", "prevIsSameLine", "=", "!", "prevToken", "||", "astUtils", ".", "isTokenOnSameLine", "(", "prevToken", ",", "semiToken", ")", ";", "const", "nextIsSameLine", "=", "!", "nextToken", "||", "astUtils", ".", "isTokenOnSameLine", "(", "semiToken", ",", "nextToken", ")", ";", "if", "(", "(", "expected", "===", "\"last\"", "&&", "!", "prevIsSameLine", ")", "||", "(", "expected", "===", "\"first\"", "&&", "!", "nextIsSameLine", ")", ")", "{", "context", ".", "report", "(", "{", "loc", ":", "semiToken", ".", "loc", ",", "message", ":", "\"Expected this semicolon to be at {{pos}}.\"", ",", "data", ":", "{", "pos", ":", "(", "expected", "===", "\"last\"", ")", "?", "\"the end of the previous line\"", ":", "\"the beginning of the next line\"", "}", ",", "fix", "(", "fixer", ")", "{", "if", "(", "prevToken", "&&", "nextToken", "&&", "sourceCode", ".", "commentsExistBetween", "(", "prevToken", ",", "nextToken", ")", ")", "{", "return", "null", ";", "}", "const", "start", "=", "prevToken", "?", "prevToken", ".", "range", "[", "1", "]", ":", "semiToken", ".", "range", "[", "0", "]", ";", "const", "end", "=", "nextToken", "?", "nextToken", ".", "range", "[", "0", "]", ":", "semiToken", ".", "range", "[", "1", "]", ";", "const", "text", "=", "(", "expected", "===", "\"last\"", ")", "?", "\";\\n\"", ":", "\\n", ";", "\"\\n;\"", "}", "}", ")", ";", "}", "}" ]
Check the given semicolon token. @param {Token} semiToken The semicolon token to check. @param {"first"|"last"} expected The expected location to check. @returns {void}
[ "Check", "the", "given", "semicolon", "token", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/semi-style.js#L91-L119
train
eslint/eslint
lib/rules/no-extra-parens.js
ruleApplies
function ruleApplies(node) { if (node.type === "JSXElement" || node.type === "JSXFragment") { const isSingleLine = node.loc.start.line === node.loc.end.line; switch (IGNORE_JSX) { // Exclude this JSX element from linting case "all": return false; // Exclude this JSX element if it is multi-line element case "multi-line": return isSingleLine; // Exclude this JSX element if it is single-line element case "single-line": return !isSingleLine; // Nothing special to be done for JSX elements case "none": break; // no default } } return ALL_NODES || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression"; }
javascript
function ruleApplies(node) { if (node.type === "JSXElement" || node.type === "JSXFragment") { const isSingleLine = node.loc.start.line === node.loc.end.line; switch (IGNORE_JSX) { // Exclude this JSX element from linting case "all": return false; // Exclude this JSX element if it is multi-line element case "multi-line": return isSingleLine; // Exclude this JSX element if it is single-line element case "single-line": return !isSingleLine; // Nothing special to be done for JSX elements case "none": break; // no default } } return ALL_NODES || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression"; }
[ "function", "ruleApplies", "(", "node", ")", "{", "if", "(", "node", ".", "type", "===", "\"JSXElement\"", "||", "node", ".", "type", "===", "\"JSXFragment\"", ")", "{", "const", "isSingleLine", "=", "node", ".", "loc", ".", "start", ".", "line", "===", "node", ".", "loc", ".", "end", ".", "line", ";", "switch", "(", "IGNORE_JSX", ")", "{", "case", "\"all\"", ":", "return", "false", ";", "case", "\"multi-line\"", ":", "return", "isSingleLine", ";", "case", "\"single-line\"", ":", "return", "!", "isSingleLine", ";", "case", "\"none\"", ":", "break", ";", "}", "}", "return", "ALL_NODES", "||", "node", ".", "type", "===", "\"FunctionExpression\"", "||", "node", ".", "type", "===", "\"ArrowFunctionExpression\"", ";", "}" ]
Determines if this rule should be enforced for a node given the current configuration. @param {ASTNode} node - The node to be checked. @returns {boolean} True if the rule should be enforced for this node. @private
[ "Determines", "if", "this", "rule", "should", "be", "enforced", "for", "a", "node", "given", "the", "current", "configuration", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-extra-parens.js#L90-L117
train
eslint/eslint
lib/rules/no-extra-parens.js
isNewExpressionWithParens
function isNewExpressionWithParens(newExpression) { const lastToken = sourceCode.getLastToken(newExpression); const penultimateToken = sourceCode.getTokenBefore(lastToken); return newExpression.arguments.length > 0 || astUtils.isOpeningParenToken(penultimateToken) && astUtils.isClosingParenToken(lastToken); }
javascript
function isNewExpressionWithParens(newExpression) { const lastToken = sourceCode.getLastToken(newExpression); const penultimateToken = sourceCode.getTokenBefore(lastToken); return newExpression.arguments.length > 0 || astUtils.isOpeningParenToken(penultimateToken) && astUtils.isClosingParenToken(lastToken); }
[ "function", "isNewExpressionWithParens", "(", "newExpression", ")", "{", "const", "lastToken", "=", "sourceCode", ".", "getLastToken", "(", "newExpression", ")", ";", "const", "penultimateToken", "=", "sourceCode", ".", "getTokenBefore", "(", "lastToken", ")", ";", "return", "newExpression", ".", "arguments", ".", "length", ">", "0", "||", "astUtils", ".", "isOpeningParenToken", "(", "penultimateToken", ")", "&&", "astUtils", ".", "isClosingParenToken", "(", "lastToken", ")", ";", "}" ]
Determines if a constructor function is newed-up with parens @param {ASTNode} newExpression - The NewExpression node to be checked. @returns {boolean} True if the constructor is called with parens. @private
[ "Determines", "if", "a", "constructor", "function", "is", "newed", "-", "up", "with", "parens" ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-extra-parens.js#L190-L195
train
eslint/eslint
lib/rules/no-extra-parens.js
requiresLeadingSpace
function requiresLeadingSpace(node) { const leftParenToken = sourceCode.getTokenBefore(node); const tokenBeforeLeftParen = sourceCode.getTokenBefore(node, 1); const firstToken = sourceCode.getFirstToken(node); return tokenBeforeLeftParen && tokenBeforeLeftParen.range[1] === leftParenToken.range[0] && leftParenToken.range[1] === firstToken.range[0] && !astUtils.canTokensBeAdjacent(tokenBeforeLeftParen, firstToken); }
javascript
function requiresLeadingSpace(node) { const leftParenToken = sourceCode.getTokenBefore(node); const tokenBeforeLeftParen = sourceCode.getTokenBefore(node, 1); const firstToken = sourceCode.getFirstToken(node); return tokenBeforeLeftParen && tokenBeforeLeftParen.range[1] === leftParenToken.range[0] && leftParenToken.range[1] === firstToken.range[0] && !astUtils.canTokensBeAdjacent(tokenBeforeLeftParen, firstToken); }
[ "function", "requiresLeadingSpace", "(", "node", ")", "{", "const", "leftParenToken", "=", "sourceCode", ".", "getTokenBefore", "(", "node", ")", ";", "const", "tokenBeforeLeftParen", "=", "sourceCode", ".", "getTokenBefore", "(", "node", ",", "1", ")", ";", "const", "firstToken", "=", "sourceCode", ".", "getFirstToken", "(", "node", ")", ";", "return", "tokenBeforeLeftParen", "&&", "tokenBeforeLeftParen", ".", "range", "[", "1", "]", "===", "leftParenToken", ".", "range", "[", "0", "]", "&&", "leftParenToken", ".", "range", "[", "1", "]", "===", "firstToken", ".", "range", "[", "0", "]", "&&", "!", "astUtils", ".", "canTokensBeAdjacent", "(", "tokenBeforeLeftParen", ",", "firstToken", ")", ";", "}" ]
Determines whether a node should be preceded by an additional space when removing parens @param {ASTNode} node node to evaluate; must be surrounded by parentheses @returns {boolean} `true` if a space should be inserted before the node @private
[ "Determines", "whether", "a", "node", "should", "be", "preceded", "by", "an", "additional", "space", "when", "removing", "parens" ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-extra-parens.js#L262-L271
train
eslint/eslint
lib/rules/no-extra-parens.js
requiresTrailingSpace
function requiresTrailingSpace(node) { const nextTwoTokens = sourceCode.getTokensAfter(node, { count: 2 }); const rightParenToken = nextTwoTokens[0]; const tokenAfterRightParen = nextTwoTokens[1]; const tokenBeforeRightParen = sourceCode.getLastToken(node); return rightParenToken && tokenAfterRightParen && !sourceCode.isSpaceBetweenTokens(rightParenToken, tokenAfterRightParen) && !astUtils.canTokensBeAdjacent(tokenBeforeRightParen, tokenAfterRightParen); }
javascript
function requiresTrailingSpace(node) { const nextTwoTokens = sourceCode.getTokensAfter(node, { count: 2 }); const rightParenToken = nextTwoTokens[0]; const tokenAfterRightParen = nextTwoTokens[1]; const tokenBeforeRightParen = sourceCode.getLastToken(node); return rightParenToken && tokenAfterRightParen && !sourceCode.isSpaceBetweenTokens(rightParenToken, tokenAfterRightParen) && !astUtils.canTokensBeAdjacent(tokenBeforeRightParen, tokenAfterRightParen); }
[ "function", "requiresTrailingSpace", "(", "node", ")", "{", "const", "nextTwoTokens", "=", "sourceCode", ".", "getTokensAfter", "(", "node", ",", "{", "count", ":", "2", "}", ")", ";", "const", "rightParenToken", "=", "nextTwoTokens", "[", "0", "]", ";", "const", "tokenAfterRightParen", "=", "nextTwoTokens", "[", "1", "]", ";", "const", "tokenBeforeRightParen", "=", "sourceCode", ".", "getLastToken", "(", "node", ")", ";", "return", "rightParenToken", "&&", "tokenAfterRightParen", "&&", "!", "sourceCode", ".", "isSpaceBetweenTokens", "(", "rightParenToken", ",", "tokenAfterRightParen", ")", "&&", "!", "astUtils", ".", "canTokensBeAdjacent", "(", "tokenBeforeRightParen", ",", "tokenAfterRightParen", ")", ";", "}" ]
Determines whether a node should be followed by an additional space when removing parens @param {ASTNode} node node to evaluate; must be surrounded by parentheses @returns {boolean} `true` if a space should be inserted after the node @private
[ "Determines", "whether", "a", "node", "should", "be", "followed", "by", "an", "additional", "space", "when", "removing", "parens" ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-extra-parens.js#L279-L288
train
eslint/eslint
lib/rules/no-extra-parens.js
doesMemberExpressionContainCallExpression
function doesMemberExpressionContainCallExpression(node) { let currentNode = node.object; let currentNodeType = node.object.type; while (currentNodeType === "MemberExpression") { currentNode = currentNode.object; currentNodeType = currentNode.type; } return currentNodeType === "CallExpression"; }
javascript
function doesMemberExpressionContainCallExpression(node) { let currentNode = node.object; let currentNodeType = node.object.type; while (currentNodeType === "MemberExpression") { currentNode = currentNode.object; currentNodeType = currentNode.type; } return currentNodeType === "CallExpression"; }
[ "function", "doesMemberExpressionContainCallExpression", "(", "node", ")", "{", "let", "currentNode", "=", "node", ".", "object", ";", "let", "currentNodeType", "=", "node", ".", "object", ".", "type", ";", "while", "(", "currentNodeType", "===", "\"MemberExpression\"", ")", "{", "currentNode", "=", "currentNode", ".", "object", ";", "currentNodeType", "=", "currentNode", ".", "type", ";", "}", "return", "currentNodeType", "===", "\"CallExpression\"", ";", "}" ]
Check if a member expression contains a call expression @param {ASTNode} node MemberExpression node to evaluate @returns {boolean} true if found, false if not
[ "Check", "if", "a", "member", "expression", "contains", "a", "call", "expression" ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-extra-parens.js#L355-L365
train
eslint/eslint
lib/rules/no-extra-parens.js
checkClass
function checkClass(node) { if (!node.superClass) { return; } /* * If `node.superClass` is a LeftHandSideExpression, parentheses are extra. * Otherwise, parentheses are needed. */ const hasExtraParens = precedence(node.superClass) > PRECEDENCE_OF_UPDATE_EXPR ? hasExcessParens(node.superClass) : hasDoubleExcessParens(node.superClass); if (hasExtraParens) { report(node.superClass); } }
javascript
function checkClass(node) { if (!node.superClass) { return; } /* * If `node.superClass` is a LeftHandSideExpression, parentheses are extra. * Otherwise, parentheses are needed. */ const hasExtraParens = precedence(node.superClass) > PRECEDENCE_OF_UPDATE_EXPR ? hasExcessParens(node.superClass) : hasDoubleExcessParens(node.superClass); if (hasExtraParens) { report(node.superClass); } }
[ "function", "checkClass", "(", "node", ")", "{", "if", "(", "!", "node", ".", "superClass", ")", "{", "return", ";", "}", "const", "hasExtraParens", "=", "precedence", "(", "node", ".", "superClass", ")", ">", "PRECEDENCE_OF_UPDATE_EXPR", "?", "hasExcessParens", "(", "node", ".", "superClass", ")", ":", "hasDoubleExcessParens", "(", "node", ".", "superClass", ")", ";", "if", "(", "hasExtraParens", ")", "{", "report", "(", "node", ".", "superClass", ")", ";", "}", "}" ]
Check the parentheses around the super class of the given class definition. @param {ASTNode} node The node of class declarations to check. @returns {void}
[ "Check", "the", "parentheses", "around", "the", "super", "class", "of", "the", "given", "class", "definition", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-extra-parens.js#L432-L448
train
eslint/eslint
lib/rules/no-extra-parens.js
checkSpreadOperator
function checkSpreadOperator(node) { const hasExtraParens = precedence(node.argument) >= PRECEDENCE_OF_ASSIGNMENT_EXPR ? hasExcessParens(node.argument) : hasDoubleExcessParens(node.argument); if (hasExtraParens) { report(node.argument); } }
javascript
function checkSpreadOperator(node) { const hasExtraParens = precedence(node.argument) >= PRECEDENCE_OF_ASSIGNMENT_EXPR ? hasExcessParens(node.argument) : hasDoubleExcessParens(node.argument); if (hasExtraParens) { report(node.argument); } }
[ "function", "checkSpreadOperator", "(", "node", ")", "{", "const", "hasExtraParens", "=", "precedence", "(", "node", ".", "argument", ")", ">=", "PRECEDENCE_OF_ASSIGNMENT_EXPR", "?", "hasExcessParens", "(", "node", ".", "argument", ")", ":", "hasDoubleExcessParens", "(", "node", ".", "argument", ")", ";", "if", "(", "hasExtraParens", ")", "{", "report", "(", "node", ".", "argument", ")", ";", "}", "}" ]
Check the parentheses around the argument of the given spread operator. @param {ASTNode} node The node of spread elements/properties to check. @returns {void}
[ "Check", "the", "parentheses", "around", "the", "argument", "of", "the", "given", "spread", "operator", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-extra-parens.js#L455-L463
train
eslint/eslint
lib/rules/no-extra-parens.js
checkExpressionOrExportStatement
function checkExpressionOrExportStatement(node) { const firstToken = isParenthesised(node) ? sourceCode.getTokenBefore(node) : sourceCode.getFirstToken(node); const secondToken = sourceCode.getTokenAfter(firstToken, astUtils.isNotOpeningParenToken); const thirdToken = secondToken ? sourceCode.getTokenAfter(secondToken) : null; const tokenAfterClosingParens = secondToken ? sourceCode.getTokenAfter(secondToken, astUtils.isNotClosingParenToken) : null; if ( astUtils.isOpeningParenToken(firstToken) && ( astUtils.isOpeningBraceToken(secondToken) || secondToken.type === "Keyword" && ( secondToken.value === "function" || secondToken.value === "class" || secondToken.value === "let" && tokenAfterClosingParens && ( astUtils.isOpeningBracketToken(tokenAfterClosingParens) || tokenAfterClosingParens.type === "Identifier" ) ) || secondToken && secondToken.type === "Identifier" && secondToken.value === "async" && thirdToken && thirdToken.type === "Keyword" && thirdToken.value === "function" ) ) { tokensToIgnore.add(secondToken); } if (hasExcessParens(node)) { report(node); } }
javascript
function checkExpressionOrExportStatement(node) { const firstToken = isParenthesised(node) ? sourceCode.getTokenBefore(node) : sourceCode.getFirstToken(node); const secondToken = sourceCode.getTokenAfter(firstToken, astUtils.isNotOpeningParenToken); const thirdToken = secondToken ? sourceCode.getTokenAfter(secondToken) : null; const tokenAfterClosingParens = secondToken ? sourceCode.getTokenAfter(secondToken, astUtils.isNotClosingParenToken) : null; if ( astUtils.isOpeningParenToken(firstToken) && ( astUtils.isOpeningBraceToken(secondToken) || secondToken.type === "Keyword" && ( secondToken.value === "function" || secondToken.value === "class" || secondToken.value === "let" && tokenAfterClosingParens && ( astUtils.isOpeningBracketToken(tokenAfterClosingParens) || tokenAfterClosingParens.type === "Identifier" ) ) || secondToken && secondToken.type === "Identifier" && secondToken.value === "async" && thirdToken && thirdToken.type === "Keyword" && thirdToken.value === "function" ) ) { tokensToIgnore.add(secondToken); } if (hasExcessParens(node)) { report(node); } }
[ "function", "checkExpressionOrExportStatement", "(", "node", ")", "{", "const", "firstToken", "=", "isParenthesised", "(", "node", ")", "?", "sourceCode", ".", "getTokenBefore", "(", "node", ")", ":", "sourceCode", ".", "getFirstToken", "(", "node", ")", ";", "const", "secondToken", "=", "sourceCode", ".", "getTokenAfter", "(", "firstToken", ",", "astUtils", ".", "isNotOpeningParenToken", ")", ";", "const", "thirdToken", "=", "secondToken", "?", "sourceCode", ".", "getTokenAfter", "(", "secondToken", ")", ":", "null", ";", "const", "tokenAfterClosingParens", "=", "secondToken", "?", "sourceCode", ".", "getTokenAfter", "(", "secondToken", ",", "astUtils", ".", "isNotClosingParenToken", ")", ":", "null", ";", "if", "(", "astUtils", ".", "isOpeningParenToken", "(", "firstToken", ")", "&&", "(", "astUtils", ".", "isOpeningBraceToken", "(", "secondToken", ")", "||", "secondToken", ".", "type", "===", "\"Keyword\"", "&&", "(", "secondToken", ".", "value", "===", "\"function\"", "||", "secondToken", ".", "value", "===", "\"class\"", "||", "secondToken", ".", "value", "===", "\"let\"", "&&", "tokenAfterClosingParens", "&&", "(", "astUtils", ".", "isOpeningBracketToken", "(", "tokenAfterClosingParens", ")", "||", "tokenAfterClosingParens", ".", "type", "===", "\"Identifier\"", ")", ")", "||", "secondToken", "&&", "secondToken", ".", "type", "===", "\"Identifier\"", "&&", "secondToken", ".", "value", "===", "\"async\"", "&&", "thirdToken", "&&", "thirdToken", ".", "type", "===", "\"Keyword\"", "&&", "thirdToken", ".", "value", "===", "\"function\"", ")", ")", "{", "tokensToIgnore", ".", "add", "(", "secondToken", ")", ";", "}", "if", "(", "hasExcessParens", "(", "node", ")", ")", "{", "report", "(", "node", ")", ";", "}", "}" ]
Checks the parentheses for an ExpressionStatement or ExportDefaultDeclaration @param {ASTNode} node The ExpressionStatement.expression or ExportDefaultDeclaration.declaration node @returns {void}
[ "Checks", "the", "parentheses", "for", "an", "ExpressionStatement", "or", "ExportDefaultDeclaration" ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-extra-parens.js#L470-L499
train
eslint/eslint
lib/rules/no-useless-rename.js
checkDestructured
function checkDestructured(node) { if (ignoreDestructuring) { return; } const properties = node.properties; for (let i = 0; i < properties.length; i++) { if (properties[i].shorthand) { continue; } /** * If an ObjectPattern property is computed, we have no idea * if a rename is useless or not. If an ObjectPattern property * lacks a key, it is likely an ExperimentalRestProperty and * so there is no "renaming" occurring here. */ if (properties[i].computed || !properties[i].key) { continue; } if (properties[i].key.type === "Identifier" && properties[i].key.name === properties[i].value.name || properties[i].key.type === "Literal" && properties[i].key.value === properties[i].value.name) { reportError(properties[i], properties[i].key, properties[i].value, "Destructuring assignment"); } } }
javascript
function checkDestructured(node) { if (ignoreDestructuring) { return; } const properties = node.properties; for (let i = 0; i < properties.length; i++) { if (properties[i].shorthand) { continue; } /** * If an ObjectPattern property is computed, we have no idea * if a rename is useless or not. If an ObjectPattern property * lacks a key, it is likely an ExperimentalRestProperty and * so there is no "renaming" occurring here. */ if (properties[i].computed || !properties[i].key) { continue; } if (properties[i].key.type === "Identifier" && properties[i].key.name === properties[i].value.name || properties[i].key.type === "Literal" && properties[i].key.value === properties[i].value.name) { reportError(properties[i], properties[i].key, properties[i].value, "Destructuring assignment"); } } }
[ "function", "checkDestructured", "(", "node", ")", "{", "if", "(", "ignoreDestructuring", ")", "{", "return", ";", "}", "const", "properties", "=", "node", ".", "properties", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "properties", ".", "length", ";", "i", "++", ")", "{", "if", "(", "properties", "[", "i", "]", ".", "shorthand", ")", "{", "continue", ";", "}", "if", "(", "properties", "[", "i", "]", ".", "computed", "||", "!", "properties", "[", "i", "]", ".", "key", ")", "{", "continue", ";", "}", "if", "(", "properties", "[", "i", "]", ".", "key", ".", "type", "===", "\"Identifier\"", "&&", "properties", "[", "i", "]", ".", "key", ".", "name", "===", "properties", "[", "i", "]", ".", "value", ".", "name", "||", "properties", "[", "i", "]", ".", "key", ".", "type", "===", "\"Literal\"", "&&", "properties", "[", "i", "]", ".", "key", ".", "value", "===", "properties", "[", "i", "]", ".", "value", ".", "name", ")", "{", "reportError", "(", "properties", "[", "i", "]", ",", "properties", "[", "i", "]", ".", "key", ",", "properties", "[", "i", "]", ".", "value", ",", "\"Destructuring assignment\"", ")", ";", "}", "}", "}" ]
Checks whether a destructured assignment is unnecessarily renamed @param {ASTNode} node - node to check @returns {void}
[ "Checks", "whether", "a", "destructured", "assignment", "is", "unnecessarily", "renamed" ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-useless-rename.js#L80-L107
train
eslint/eslint
lib/rules/no-useless-rename.js
checkImport
function checkImport(node) { if (ignoreImport) { return; } if (node.imported.name === node.local.name && node.imported.range[0] !== node.local.range[0]) { reportError(node, node.imported, node.local, "Import"); } }
javascript
function checkImport(node) { if (ignoreImport) { return; } if (node.imported.name === node.local.name && node.imported.range[0] !== node.local.range[0]) { reportError(node, node.imported, node.local, "Import"); } }
[ "function", "checkImport", "(", "node", ")", "{", "if", "(", "ignoreImport", ")", "{", "return", ";", "}", "if", "(", "node", ".", "imported", ".", "name", "===", "node", ".", "local", ".", "name", "&&", "node", ".", "imported", ".", "range", "[", "0", "]", "!==", "node", ".", "local", ".", "range", "[", "0", "]", ")", "{", "reportError", "(", "node", ",", "node", ".", "imported", ",", "node", ".", "local", ",", "\"Import\"", ")", ";", "}", "}" ]
Checks whether an import is unnecessarily renamed @param {ASTNode} node - node to check @returns {void}
[ "Checks", "whether", "an", "import", "is", "unnecessarily", "renamed" ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-useless-rename.js#L114-L123
train
eslint/eslint
lib/rules/no-useless-rename.js
checkExport
function checkExport(node) { if (ignoreExport) { return; } if (node.local.name === node.exported.name && node.local.range[0] !== node.exported.range[0]) { reportError(node, node.local, node.exported, "Export"); } }
javascript
function checkExport(node) { if (ignoreExport) { return; } if (node.local.name === node.exported.name && node.local.range[0] !== node.exported.range[0]) { reportError(node, node.local, node.exported, "Export"); } }
[ "function", "checkExport", "(", "node", ")", "{", "if", "(", "ignoreExport", ")", "{", "return", ";", "}", "if", "(", "node", ".", "local", ".", "name", "===", "node", ".", "exported", ".", "name", "&&", "node", ".", "local", ".", "range", "[", "0", "]", "!==", "node", ".", "exported", ".", "range", "[", "0", "]", ")", "{", "reportError", "(", "node", ",", "node", ".", "local", ",", "node", ".", "exported", ",", "\"Export\"", ")", ";", "}", "}" ]
Checks whether an export is unnecessarily renamed @param {ASTNode} node - node to check @returns {void}
[ "Checks", "whether", "an", "export", "is", "unnecessarily", "renamed" ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-useless-rename.js#L130-L140
train
eslint/eslint
lib/rules/max-params.js
checkFunction
function checkFunction(node) { if (node.params.length > numParams) { context.report({ loc: astUtils.getFunctionHeadLoc(node, sourceCode), node, messageId: "exceed", data: { name: lodash.upperFirst(astUtils.getFunctionNameWithKind(node)), count: node.params.length, max: numParams } }); } }
javascript
function checkFunction(node) { if (node.params.length > numParams) { context.report({ loc: astUtils.getFunctionHeadLoc(node, sourceCode), node, messageId: "exceed", data: { name: lodash.upperFirst(astUtils.getFunctionNameWithKind(node)), count: node.params.length, max: numParams } }); } }
[ "function", "checkFunction", "(", "node", ")", "{", "if", "(", "node", ".", "params", ".", "length", ">", "numParams", ")", "{", "context", ".", "report", "(", "{", "loc", ":", "astUtils", ".", "getFunctionHeadLoc", "(", "node", ",", "sourceCode", ")", ",", "node", ",", "messageId", ":", "\"exceed\"", ",", "data", ":", "{", "name", ":", "lodash", ".", "upperFirst", "(", "astUtils", ".", "getFunctionNameWithKind", "(", "node", ")", ")", ",", "count", ":", "node", ".", "params", ".", "length", ",", "max", ":", "numParams", "}", "}", ")", ";", "}", "}" ]
Checks a function to see if it has too many parameters. @param {ASTNode} node The node to check. @returns {void} @private
[ "Checks", "a", "function", "to", "see", "if", "it", "has", "too", "many", "parameters", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/max-params.js#L81-L94
train
eslint/eslint
lib/rules/spaced-comment.js
reportBegin
function reportBegin(node, message, match, refChar) { const type = node.type.toLowerCase(), commentIdentifier = type === "block" ? "/*" : "//"; context.report({ node, fix(fixer) { const start = node.range[0]; let end = start + 2; if (requireSpace) { if (match) { end += match[0].length; } return fixer.insertTextAfterRange([start, end], " "); } end += match[0].length; return fixer.replaceTextRange([start, end], commentIdentifier + (match[1] ? match[1] : "")); }, message, data: { refChar } }); }
javascript
function reportBegin(node, message, match, refChar) { const type = node.type.toLowerCase(), commentIdentifier = type === "block" ? "/*" : "//"; context.report({ node, fix(fixer) { const start = node.range[0]; let end = start + 2; if (requireSpace) { if (match) { end += match[0].length; } return fixer.insertTextAfterRange([start, end], " "); } end += match[0].length; return fixer.replaceTextRange([start, end], commentIdentifier + (match[1] ? match[1] : "")); }, message, data: { refChar } }); }
[ "function", "reportBegin", "(", "node", ",", "message", ",", "match", ",", "refChar", ")", "{", "const", "type", "=", "node", ".", "type", ".", "toLowerCase", "(", ")", ",", "commentIdentifier", "=", "type", "===", "\"block\"", "?", "\"/*\"", ":", "\"//\"", ";", "context", ".", "report", "(", "{", "node", ",", "fix", "(", "fixer", ")", "{", "const", "start", "=", "node", ".", "range", "[", "0", "]", ";", "let", "end", "=", "start", "+", "2", ";", "if", "(", "requireSpace", ")", "{", "if", "(", "match", ")", "{", "end", "+=", "match", "[", "0", "]", ".", "length", ";", "}", "return", "fixer", ".", "insertTextAfterRange", "(", "[", "start", ",", "end", "]", ",", "\" \"", ")", ";", "}", "end", "+=", "match", "[", "0", "]", ".", "length", ";", "return", "fixer", ".", "replaceTextRange", "(", "[", "start", ",", "end", "]", ",", "commentIdentifier", "+", "(", "match", "[", "1", "]", "?", "match", "[", "1", "]", ":", "\"\"", ")", ")", ";", "}", ",", "message", ",", "data", ":", "{", "refChar", "}", "}", ")", ";", "}" ]
Reports a beginning spacing error with an appropriate message. @param {ASTNode} node - A comment node to check. @param {string} message - An error message to report. @param {Array} match - An array of match results for markers. @param {string} refChar - Character used for reference in the error message. @returns {void}
[ "Reports", "a", "beginning", "spacing", "error", "with", "an", "appropriate", "message", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/spaced-comment.js#L269-L292
train
eslint/eslint
lib/rules/spaced-comment.js
reportEnd
function reportEnd(node, message, match) { context.report({ node, fix(fixer) { if (requireSpace) { return fixer.insertTextAfterRange([node.range[0], node.range[1] - 2], " "); } const end = node.range[1] - 2, start = end - match[0].length; return fixer.replaceTextRange([start, end], ""); }, message }); }
javascript
function reportEnd(node, message, match) { context.report({ node, fix(fixer) { if (requireSpace) { return fixer.insertTextAfterRange([node.range[0], node.range[1] - 2], " "); } const end = node.range[1] - 2, start = end - match[0].length; return fixer.replaceTextRange([start, end], ""); }, message }); }
[ "function", "reportEnd", "(", "node", ",", "message", ",", "match", ")", "{", "context", ".", "report", "(", "{", "node", ",", "fix", "(", "fixer", ")", "{", "if", "(", "requireSpace", ")", "{", "return", "fixer", ".", "insertTextAfterRange", "(", "[", "node", ".", "range", "[", "0", "]", ",", "node", ".", "range", "[", "1", "]", "-", "2", "]", ",", "\" \"", ")", ";", "}", "const", "end", "=", "node", ".", "range", "[", "1", "]", "-", "2", ",", "start", "=", "end", "-", "match", "[", "0", "]", ".", "length", ";", "return", "fixer", ".", "replaceTextRange", "(", "[", "start", ",", "end", "]", ",", "\"\"", ")", ";", "}", ",", "message", "}", ")", ";", "}" ]
Reports an ending spacing error with an appropriate message. @param {ASTNode} node - A comment node to check. @param {string} message - An error message to report. @param {string} match - An array of the matched whitespace characters. @returns {void}
[ "Reports", "an", "ending", "spacing", "error", "with", "an", "appropriate", "message", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/spaced-comment.js#L301-L316
train
eslint/eslint
lib/rules/spaced-comment.js
checkCommentForSpace
function checkCommentForSpace(node) { const type = node.type.toLowerCase(), rule = styleRules[type], commentIdentifier = type === "block" ? "/*" : "//"; // Ignores empty comments. if (node.value.length === 0) { return; } const beginMatch = rule.beginRegex.exec(node.value); const endMatch = rule.endRegex.exec(node.value); // Checks. if (requireSpace) { if (!beginMatch) { const hasMarker = rule.markers.exec(node.value); const marker = hasMarker ? commentIdentifier + hasMarker[0] : commentIdentifier; if (rule.hasExceptions) { reportBegin(node, "Expected exception block, space or tab after '{{refChar}}' in comment.", hasMarker, marker); } else { reportBegin(node, "Expected space or tab after '{{refChar}}' in comment.", hasMarker, marker); } } if (balanced && type === "block" && !endMatch) { reportEnd(node, "Expected space or tab before '*/' in comment."); } } else { if (beginMatch) { if (!beginMatch[1]) { reportBegin(node, "Unexpected space or tab after '{{refChar}}' in comment.", beginMatch, commentIdentifier); } else { reportBegin(node, "Unexpected space or tab after marker ({{refChar}}) in comment.", beginMatch, beginMatch[1]); } } if (balanced && type === "block" && endMatch) { reportEnd(node, "Unexpected space or tab before '*/' in comment.", endMatch); } } }
javascript
function checkCommentForSpace(node) { const type = node.type.toLowerCase(), rule = styleRules[type], commentIdentifier = type === "block" ? "/*" : "//"; // Ignores empty comments. if (node.value.length === 0) { return; } const beginMatch = rule.beginRegex.exec(node.value); const endMatch = rule.endRegex.exec(node.value); // Checks. if (requireSpace) { if (!beginMatch) { const hasMarker = rule.markers.exec(node.value); const marker = hasMarker ? commentIdentifier + hasMarker[0] : commentIdentifier; if (rule.hasExceptions) { reportBegin(node, "Expected exception block, space or tab after '{{refChar}}' in comment.", hasMarker, marker); } else { reportBegin(node, "Expected space or tab after '{{refChar}}' in comment.", hasMarker, marker); } } if (balanced && type === "block" && !endMatch) { reportEnd(node, "Expected space or tab before '*/' in comment."); } } else { if (beginMatch) { if (!beginMatch[1]) { reportBegin(node, "Unexpected space or tab after '{{refChar}}' in comment.", beginMatch, commentIdentifier); } else { reportBegin(node, "Unexpected space or tab after marker ({{refChar}}) in comment.", beginMatch, beginMatch[1]); } } if (balanced && type === "block" && endMatch) { reportEnd(node, "Unexpected space or tab before '*/' in comment.", endMatch); } } }
[ "function", "checkCommentForSpace", "(", "node", ")", "{", "const", "type", "=", "node", ".", "type", ".", "toLowerCase", "(", ")", ",", "rule", "=", "styleRules", "[", "type", "]", ",", "commentIdentifier", "=", "type", "===", "\"block\"", "?", "\"/*\"", ":", "\"//\"", ";", "if", "(", "node", ".", "value", ".", "length", "===", "0", ")", "{", "return", ";", "}", "const", "beginMatch", "=", "rule", ".", "beginRegex", ".", "exec", "(", "node", ".", "value", ")", ";", "const", "endMatch", "=", "rule", ".", "endRegex", ".", "exec", "(", "node", ".", "value", ")", ";", "if", "(", "requireSpace", ")", "{", "if", "(", "!", "beginMatch", ")", "{", "const", "hasMarker", "=", "rule", ".", "markers", ".", "exec", "(", "node", ".", "value", ")", ";", "const", "marker", "=", "hasMarker", "?", "commentIdentifier", "+", "hasMarker", "[", "0", "]", ":", "commentIdentifier", ";", "if", "(", "rule", ".", "hasExceptions", ")", "{", "reportBegin", "(", "node", ",", "\"Expected exception block, space or tab after '{{refChar}}' in comment.\"", ",", "hasMarker", ",", "marker", ")", ";", "}", "else", "{", "reportBegin", "(", "node", ",", "\"Expected space or tab after '{{refChar}}' in comment.\"", ",", "hasMarker", ",", "marker", ")", ";", "}", "}", "if", "(", "balanced", "&&", "type", "===", "\"block\"", "&&", "!", "endMatch", ")", "{", "reportEnd", "(", "node", ",", "\"Expected space or tab before '*/' in comment.\"", ")", ";", "}", "}", "else", "{", "if", "(", "beginMatch", ")", "{", "if", "(", "!", "beginMatch", "[", "1", "]", ")", "{", "reportBegin", "(", "node", ",", "\"Unexpected space or tab after '{{refChar}}' in comment.\"", ",", "beginMatch", ",", "commentIdentifier", ")", ";", "}", "else", "{", "reportBegin", "(", "node", ",", "\"Unexpected space or tab after marker ({{refChar}}) in comment.\"", ",", "beginMatch", ",", "beginMatch", "[", "1", "]", ")", ";", "}", "}", "if", "(", "balanced", "&&", "type", "===", "\"block\"", "&&", "endMatch", ")", "{", "reportEnd", "(", "node", ",", "\"Unexpected space or tab before '*/' in comment.\"", ",", "endMatch", ")", ";", "}", "}", "}" ]
Reports a given comment if it's invalid. @param {ASTNode} node - a comment node to check. @returns {void}
[ "Reports", "a", "given", "comment", "if", "it", "s", "invalid", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/spaced-comment.js#L323-L365
train
eslint/eslint
tools/eslint-fuzzer.js
isolateBadConfig
function isolateBadConfig(text, config, problemType) { for (const ruleId of Object.keys(config.rules)) { const reducedConfig = Object.assign({}, config, { rules: { [ruleId]: config.rules[ruleId] } }); let fixResult; try { fixResult = linter.verifyAndFix(text, reducedConfig, {}); } catch (err) { return reducedConfig; } if (fixResult.messages.length === 1 && fixResult.messages[0].fatal && problemType === "autofix") { return reducedConfig; } } return config; }
javascript
function isolateBadConfig(text, config, problemType) { for (const ruleId of Object.keys(config.rules)) { const reducedConfig = Object.assign({}, config, { rules: { [ruleId]: config.rules[ruleId] } }); let fixResult; try { fixResult = linter.verifyAndFix(text, reducedConfig, {}); } catch (err) { return reducedConfig; } if (fixResult.messages.length === 1 && fixResult.messages[0].fatal && problemType === "autofix") { return reducedConfig; } } return config; }
[ "function", "isolateBadConfig", "(", "text", ",", "config", ",", "problemType", ")", "{", "for", "(", "const", "ruleId", "of", "Object", ".", "keys", "(", "config", ".", "rules", ")", ")", "{", "const", "reducedConfig", "=", "Object", ".", "assign", "(", "{", "}", ",", "config", ",", "{", "rules", ":", "{", "[", "ruleId", "]", ":", "config", ".", "rules", "[", "ruleId", "]", "}", "}", ")", ";", "let", "fixResult", ";", "try", "{", "fixResult", "=", "linter", ".", "verifyAndFix", "(", "text", ",", "reducedConfig", ",", "{", "}", ")", ";", "}", "catch", "(", "err", ")", "{", "return", "reducedConfig", ";", "}", "if", "(", "fixResult", ".", "messages", ".", "length", "===", "1", "&&", "fixResult", ".", "messages", "[", "0", "]", ".", "fatal", "&&", "problemType", "===", "\"autofix\"", ")", "{", "return", "reducedConfig", ";", "}", "}", "return", "config", ";", "}" ]
Tries to isolate the smallest config that reproduces a problem @param {string} text The source text to lint @param {Object} config A config object that causes a crash or autofix error @param {("crash"|"autofix")} problemType The type of problem that occurred @returns {Object} A config object with only one rule enabled that produces the same crash or autofix error, if possible. Otherwise, the same as `config`
[ "Tries", "to", "isolate", "the", "smallest", "config", "that", "reproduces", "a", "problem" ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/tools/eslint-fuzzer.js#L59-L75
train
eslint/eslint
tools/eslint-fuzzer.js
isolateBadAutofixPass
function isolateBadAutofixPass(originalText, config) { let lastGoodText = originalText; let currentText = originalText; do { let messages; try { messages = linter.verify(currentText, config); } catch (err) { return lastGoodText; } if (messages.length === 1 && messages[0].fatal) { return lastGoodText; } lastGoodText = currentText; currentText = SourceCodeFixer.applyFixes(currentText, messages).output; } while (lastGoodText !== currentText); return lastGoodText; }
javascript
function isolateBadAutofixPass(originalText, config) { let lastGoodText = originalText; let currentText = originalText; do { let messages; try { messages = linter.verify(currentText, config); } catch (err) { return lastGoodText; } if (messages.length === 1 && messages[0].fatal) { return lastGoodText; } lastGoodText = currentText; currentText = SourceCodeFixer.applyFixes(currentText, messages).output; } while (lastGoodText !== currentText); return lastGoodText; }
[ "function", "isolateBadAutofixPass", "(", "originalText", ",", "config", ")", "{", "let", "lastGoodText", "=", "originalText", ";", "let", "currentText", "=", "originalText", ";", "do", "{", "let", "messages", ";", "try", "{", "messages", "=", "linter", ".", "verify", "(", "currentText", ",", "config", ")", ";", "}", "catch", "(", "err", ")", "{", "return", "lastGoodText", ";", "}", "if", "(", "messages", ".", "length", "===", "1", "&&", "messages", "[", "0", "]", ".", "fatal", ")", "{", "return", "lastGoodText", ";", "}", "lastGoodText", "=", "currentText", ";", "currentText", "=", "SourceCodeFixer", ".", "applyFixes", "(", "currentText", ",", "messages", ")", ".", "output", ";", "}", "while", "(", "lastGoodText", "!==", "currentText", ")", ";", "return", "lastGoodText", ";", "}" ]
Runs multipass autofix one pass at a time to find the last good source text before a fatal error occurs @param {string} originalText Syntactically valid source code that results in a syntax error or crash when autofixing with `config` @param {Object} config The config to lint with @returns {string} A possibly-modified version of originalText that results in the same syntax error or crash after only one pass
[ "Runs", "multipass", "autofix", "one", "pass", "at", "a", "time", "to", "find", "the", "last", "good", "source", "text", "before", "a", "fatal", "error", "occurs" ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/tools/eslint-fuzzer.js#L83-L105
train
eslint/eslint
lib/util/path-utils.js
getRelativePath
function getRelativePath(filepath, baseDir) { const absolutePath = path.isAbsolute(filepath) ? filepath : path.resolve(filepath); if (baseDir) { if (!path.isAbsolute(baseDir)) { throw new Error(`baseDir should be an absolute path: ${baseDir}`); } return path.relative(baseDir, absolutePath); } return absolutePath.replace(/^\//u, ""); }
javascript
function getRelativePath(filepath, baseDir) { const absolutePath = path.isAbsolute(filepath) ? filepath : path.resolve(filepath); if (baseDir) { if (!path.isAbsolute(baseDir)) { throw new Error(`baseDir should be an absolute path: ${baseDir}`); } return path.relative(baseDir, absolutePath); } return absolutePath.replace(/^\//u, ""); }
[ "function", "getRelativePath", "(", "filepath", ",", "baseDir", ")", "{", "const", "absolutePath", "=", "path", ".", "isAbsolute", "(", "filepath", ")", "?", "filepath", ":", "path", ".", "resolve", "(", "filepath", ")", ";", "if", "(", "baseDir", ")", "{", "if", "(", "!", "path", ".", "isAbsolute", "(", "baseDir", ")", ")", "{", "throw", "new", "Error", "(", "`", "${", "baseDir", "}", "`", ")", ";", "}", "return", "path", ".", "relative", "(", "baseDir", ",", "absolutePath", ")", ";", "}", "return", "absolutePath", ".", "replace", "(", "/", "^\\/", "/", "u", ",", "\"\"", ")", ";", "}" ]
Converts an absolute filepath to a relative path from a given base path For example, if the filepath is `/my/awesome/project/foo.bar`, and the base directory is `/my/awesome/project/`, then this function should return `foo.bar`. path.relative() does something similar, but it requires a baseDir (`from` argument). This function makes it optional and just removes a leading slash if the baseDir is not given. It does not take into account symlinks (for now). @param {string} filepath Path to convert to relative path. If already relative, it will be assumed to be relative to process.cwd(), converted to absolute, and then processed. @param {string} [baseDir] Absolute base directory to resolve the filepath from. If not provided, all this function will do is remove a leading slash. @returns {string} Relative filepath
[ "Converts", "an", "absolute", "filepath", "to", "a", "relative", "path", "from", "a", "given", "base", "path" ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/util/path-utils.js#L50-L63
train
eslint/eslint
tools/update-readme.js
formatSponsors
function formatSponsors(sponsors) { const nonEmptySponsors = Object.keys(sponsors).filter(tier => sponsors[tier].length > 0); /* eslint-disable indent*/ return stripIndents`<!--sponsorsstart--> ${ nonEmptySponsors.map(tier => `<h3>${tier[0].toUpperCase()}${tier.slice(1)} Sponsors</h3> <p>${ sponsors[tier].map(sponsor => `<a href="${sponsor.url}"><img src="${sponsor.image}" alt="${sponsor.name}" height="${heights[tier]}"></a>`).join(" ") }</p>`).join("") } <!--sponsorsend-->`; /* eslint-enable indent*/ }
javascript
function formatSponsors(sponsors) { const nonEmptySponsors = Object.keys(sponsors).filter(tier => sponsors[tier].length > 0); /* eslint-disable indent*/ return stripIndents`<!--sponsorsstart--> ${ nonEmptySponsors.map(tier => `<h3>${tier[0].toUpperCase()}${tier.slice(1)} Sponsors</h3> <p>${ sponsors[tier].map(sponsor => `<a href="${sponsor.url}"><img src="${sponsor.image}" alt="${sponsor.name}" height="${heights[tier]}"></a>`).join(" ") }</p>`).join("") } <!--sponsorsend-->`; /* eslint-enable indent*/ }
[ "function", "formatSponsors", "(", "sponsors", ")", "{", "const", "nonEmptySponsors", "=", "Object", ".", "keys", "(", "sponsors", ")", ".", "filter", "(", "tier", "=>", "sponsors", "[", "tier", "]", ".", "length", ">", "0", ")", ";", "return", "stripIndents", "`", "${", "nonEmptySponsors", ".", "map", "(", "tier", "=>", "`", "${", "tier", "[", "0", "]", ".", "toUpperCase", "(", ")", "}", "${", "tier", ".", "slice", "(", "1", ")", "}", "${", "sponsors", "[", "tier", "]", ".", "map", "(", "sponsor", "=>", "`", "${", "sponsor", ".", "url", "}", "${", "sponsor", ".", "image", "}", "${", "sponsor", ".", "name", "}", "${", "heights", "[", "tier", "]", "}", "`", ")", ".", "join", "(", "\" \"", ")", "}", "`", ")", ".", "join", "(", "\"\"", ")", "}", "`", ";", "}" ]
Formats an array of sponsors into HTML for the readme. @param {Array} sponsors The array of sponsors. @returns {string} The HTML for the readme.
[ "Formats", "an", "array", "of", "sponsors", "into", "HTML", "for", "the", "readme", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/tools/update-readme.js#L69-L82
train
eslint/eslint
lib/rules/max-len.js
computeLineLength
function computeLineLength(line, tabWidth) { let extraCharacterCount = 0; line.replace(/\t/gu, (match, offset) => { const totalOffset = offset + extraCharacterCount, previousTabStopOffset = tabWidth ? totalOffset % tabWidth : 0, spaceCount = tabWidth - previousTabStopOffset; extraCharacterCount += spaceCount - 1; // -1 for the replaced tab }); return Array.from(line).length + extraCharacterCount; }
javascript
function computeLineLength(line, tabWidth) { let extraCharacterCount = 0; line.replace(/\t/gu, (match, offset) => { const totalOffset = offset + extraCharacterCount, previousTabStopOffset = tabWidth ? totalOffset % tabWidth : 0, spaceCount = tabWidth - previousTabStopOffset; extraCharacterCount += spaceCount - 1; // -1 for the replaced tab }); return Array.from(line).length + extraCharacterCount; }
[ "function", "computeLineLength", "(", "line", ",", "tabWidth", ")", "{", "let", "extraCharacterCount", "=", "0", ";", "line", ".", "replace", "(", "/", "\\t", "/", "gu", ",", "(", "match", ",", "offset", ")", "=>", "{", "const", "totalOffset", "=", "offset", "+", "extraCharacterCount", ",", "previousTabStopOffset", "=", "tabWidth", "?", "totalOffset", "%", "tabWidth", ":", "0", ",", "spaceCount", "=", "tabWidth", "-", "previousTabStopOffset", ";", "extraCharacterCount", "+=", "spaceCount", "-", "1", ";", "}", ")", ";", "return", "Array", ".", "from", "(", "line", ")", ".", "length", "+", "extraCharacterCount", ";", "}" ]
Computes the length of a line that may contain tabs. The width of each tab will be the number of spaces to the next tab stop. @param {string} line The line. @param {int} tabWidth The width of each tab stop in spaces. @returns {int} The computed line length. @private
[ "Computes", "the", "length", "of", "a", "line", "that", "may", "contain", "tabs", ".", "The", "width", "of", "each", "tab", "will", "be", "the", "number", "of", "spaces", "to", "the", "next", "tab", "stop", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/max-len.js#L110-L121
train
eslint/eslint
lib/rules/max-len.js
stripTrailingComment
function stripTrailingComment(line, comment) { // loc.column is zero-indexed return line.slice(0, comment.loc.start.column).replace(/\s+$/u, ""); }
javascript
function stripTrailingComment(line, comment) { // loc.column is zero-indexed return line.slice(0, comment.loc.start.column).replace(/\s+$/u, ""); }
[ "function", "stripTrailingComment", "(", "line", ",", "comment", ")", "{", "return", "line", ".", "slice", "(", "0", ",", "comment", ".", "loc", ".", "start", ".", "column", ")", ".", "replace", "(", "/", "\\s+$", "/", "u", ",", "\"\"", ")", ";", "}" ]
Gets the line after the comment and any remaining trailing whitespace is stripped. @param {string} line The source line with a trailing comment @param {ASTNode} comment The comment to remove @returns {string} Line without comment and trailing whitepace
[ "Gets", "the", "line", "after", "the", "comment", "and", "any", "remaining", "trailing", "whitespace", "is", "stripped", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/max-len.js#L193-L197
train
eslint/eslint
lib/rules/max-len.js
groupByLineNumber
function groupByLineNumber(acc, node) { for (let i = node.loc.start.line; i <= node.loc.end.line; ++i) { ensureArrayAndPush(acc, i, node); } return acc; }
javascript
function groupByLineNumber(acc, node) { for (let i = node.loc.start.line; i <= node.loc.end.line; ++i) { ensureArrayAndPush(acc, i, node); } return acc; }
[ "function", "groupByLineNumber", "(", "acc", ",", "node", ")", "{", "for", "(", "let", "i", "=", "node", ".", "loc", ".", "start", ".", "line", ";", "i", "<=", "node", ".", "loc", ".", "end", ".", "line", ";", "++", "i", ")", "{", "ensureArrayAndPush", "(", "acc", ",", "i", ",", "node", ")", ";", "}", "return", "acc", ";", "}" ]
A reducer to group an AST node by line number, both start and end. @param {Object} acc the accumulator @param {ASTNode} node the AST node in question @returns {Object} the modified accumulator @private
[ "A", "reducer", "to", "group", "an", "AST", "node", "by", "line", "number", "both", "start", "and", "end", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/max-len.js#L253-L258
train
eslint/eslint
lib/rules/max-len.js
checkProgramForMaxLength
function checkProgramForMaxLength(node) { // split (honors line-ending) const lines = sourceCode.lines, // list of comments to ignore comments = ignoreComments || maxCommentLength || ignoreTrailingComments ? sourceCode.getAllComments() : []; // we iterate over comments in parallel with the lines let commentsIndex = 0; const strings = getAllStrings(); const stringsByLine = strings.reduce(groupByLineNumber, {}); const templateLiterals = getAllTemplateLiterals(); const templateLiteralsByLine = templateLiterals.reduce(groupByLineNumber, {}); const regExpLiterals = getAllRegExpLiterals(); const regExpLiteralsByLine = regExpLiterals.reduce(groupByLineNumber, {}); lines.forEach((line, i) => { // i is zero-indexed, line numbers are one-indexed const lineNumber = i + 1; /* * if we're checking comment length; we need to know whether this * line is a comment */ let lineIsComment = false; let textToMeasure; /* * We can short-circuit the comment checks if we're already out of * comments to check. */ if (commentsIndex < comments.length) { let comment = null; // iterate over comments until we find one past the current line do { comment = comments[++commentsIndex]; } while (comment && comment.loc.start.line <= lineNumber); // and step back by one comment = comments[--commentsIndex]; if (isFullLineComment(line, lineNumber, comment)) { lineIsComment = true; textToMeasure = line; } else if (ignoreTrailingComments && isTrailingComment(line, lineNumber, comment)) { textToMeasure = stripTrailingComment(line, comment); } else { textToMeasure = line; } } else { textToMeasure = line; } if (ignorePattern && ignorePattern.test(textToMeasure) || ignoreUrls && URL_REGEXP.test(textToMeasure) || ignoreStrings && stringsByLine[lineNumber] || ignoreTemplateLiterals && templateLiteralsByLine[lineNumber] || ignoreRegExpLiterals && regExpLiteralsByLine[lineNumber] ) { // ignore this line return; } const lineLength = computeLineLength(textToMeasure, tabWidth); const commentLengthApplies = lineIsComment && maxCommentLength; if (lineIsComment && ignoreComments) { return; } if (commentLengthApplies) { if (lineLength > maxCommentLength) { context.report({ node, loc: { line: lineNumber, column: 0 }, messageId: "maxComment", data: { lineNumber: i + 1, maxCommentLength } }); } } else if (lineLength > maxLength) { context.report({ node, loc: { line: lineNumber, column: 0 }, messageId: "max", data: { lineNumber: i + 1, maxLength } }); } }); }
javascript
function checkProgramForMaxLength(node) { // split (honors line-ending) const lines = sourceCode.lines, // list of comments to ignore comments = ignoreComments || maxCommentLength || ignoreTrailingComments ? sourceCode.getAllComments() : []; // we iterate over comments in parallel with the lines let commentsIndex = 0; const strings = getAllStrings(); const stringsByLine = strings.reduce(groupByLineNumber, {}); const templateLiterals = getAllTemplateLiterals(); const templateLiteralsByLine = templateLiterals.reduce(groupByLineNumber, {}); const regExpLiterals = getAllRegExpLiterals(); const regExpLiteralsByLine = regExpLiterals.reduce(groupByLineNumber, {}); lines.forEach((line, i) => { // i is zero-indexed, line numbers are one-indexed const lineNumber = i + 1; /* * if we're checking comment length; we need to know whether this * line is a comment */ let lineIsComment = false; let textToMeasure; /* * We can short-circuit the comment checks if we're already out of * comments to check. */ if (commentsIndex < comments.length) { let comment = null; // iterate over comments until we find one past the current line do { comment = comments[++commentsIndex]; } while (comment && comment.loc.start.line <= lineNumber); // and step back by one comment = comments[--commentsIndex]; if (isFullLineComment(line, lineNumber, comment)) { lineIsComment = true; textToMeasure = line; } else if (ignoreTrailingComments && isTrailingComment(line, lineNumber, comment)) { textToMeasure = stripTrailingComment(line, comment); } else { textToMeasure = line; } } else { textToMeasure = line; } if (ignorePattern && ignorePattern.test(textToMeasure) || ignoreUrls && URL_REGEXP.test(textToMeasure) || ignoreStrings && stringsByLine[lineNumber] || ignoreTemplateLiterals && templateLiteralsByLine[lineNumber] || ignoreRegExpLiterals && regExpLiteralsByLine[lineNumber] ) { // ignore this line return; } const lineLength = computeLineLength(textToMeasure, tabWidth); const commentLengthApplies = lineIsComment && maxCommentLength; if (lineIsComment && ignoreComments) { return; } if (commentLengthApplies) { if (lineLength > maxCommentLength) { context.report({ node, loc: { line: lineNumber, column: 0 }, messageId: "maxComment", data: { lineNumber: i + 1, maxCommentLength } }); } } else if (lineLength > maxLength) { context.report({ node, loc: { line: lineNumber, column: 0 }, messageId: "max", data: { lineNumber: i + 1, maxLength } }); } }); }
[ "function", "checkProgramForMaxLength", "(", "node", ")", "{", "const", "lines", "=", "sourceCode", ".", "lines", ",", "comments", "=", "ignoreComments", "||", "maxCommentLength", "||", "ignoreTrailingComments", "?", "sourceCode", ".", "getAllComments", "(", ")", ":", "[", "]", ";", "let", "commentsIndex", "=", "0", ";", "const", "strings", "=", "getAllStrings", "(", ")", ";", "const", "stringsByLine", "=", "strings", ".", "reduce", "(", "groupByLineNumber", ",", "{", "}", ")", ";", "const", "templateLiterals", "=", "getAllTemplateLiterals", "(", ")", ";", "const", "templateLiteralsByLine", "=", "templateLiterals", ".", "reduce", "(", "groupByLineNumber", ",", "{", "}", ")", ";", "const", "regExpLiterals", "=", "getAllRegExpLiterals", "(", ")", ";", "const", "regExpLiteralsByLine", "=", "regExpLiterals", ".", "reduce", "(", "groupByLineNumber", ",", "{", "}", ")", ";", "lines", ".", "forEach", "(", "(", "line", ",", "i", ")", "=>", "{", "const", "lineNumber", "=", "i", "+", "1", ";", "let", "lineIsComment", "=", "false", ";", "let", "textToMeasure", ";", "if", "(", "commentsIndex", "<", "comments", ".", "length", ")", "{", "let", "comment", "=", "null", ";", "do", "{", "comment", "=", "comments", "[", "++", "commentsIndex", "]", ";", "}", "while", "(", "comment", "&&", "comment", ".", "loc", ".", "start", ".", "line", "<=", "lineNumber", ")", ";", "comment", "=", "comments", "[", "--", "commentsIndex", "]", ";", "if", "(", "isFullLineComment", "(", "line", ",", "lineNumber", ",", "comment", ")", ")", "{", "lineIsComment", "=", "true", ";", "textToMeasure", "=", "line", ";", "}", "else", "if", "(", "ignoreTrailingComments", "&&", "isTrailingComment", "(", "line", ",", "lineNumber", ",", "comment", ")", ")", "{", "textToMeasure", "=", "stripTrailingComment", "(", "line", ",", "comment", ")", ";", "}", "else", "{", "textToMeasure", "=", "line", ";", "}", "}", "else", "{", "textToMeasure", "=", "line", ";", "}", "if", "(", "ignorePattern", "&&", "ignorePattern", ".", "test", "(", "textToMeasure", ")", "||", "ignoreUrls", "&&", "URL_REGEXP", ".", "test", "(", "textToMeasure", ")", "||", "ignoreStrings", "&&", "stringsByLine", "[", "lineNumber", "]", "||", "ignoreTemplateLiterals", "&&", "templateLiteralsByLine", "[", "lineNumber", "]", "||", "ignoreRegExpLiterals", "&&", "regExpLiteralsByLine", "[", "lineNumber", "]", ")", "{", "return", ";", "}", "const", "lineLength", "=", "computeLineLength", "(", "textToMeasure", ",", "tabWidth", ")", ";", "const", "commentLengthApplies", "=", "lineIsComment", "&&", "maxCommentLength", ";", "if", "(", "lineIsComment", "&&", "ignoreComments", ")", "{", "return", ";", "}", "if", "(", "commentLengthApplies", ")", "{", "if", "(", "lineLength", ">", "maxCommentLength", ")", "{", "context", ".", "report", "(", "{", "node", ",", "loc", ":", "{", "line", ":", "lineNumber", ",", "column", ":", "0", "}", ",", "messageId", ":", "\"maxComment\"", ",", "data", ":", "{", "lineNumber", ":", "i", "+", "1", ",", "maxCommentLength", "}", "}", ")", ";", "}", "}", "else", "if", "(", "lineLength", ">", "maxLength", ")", "{", "context", ".", "report", "(", "{", "node", ",", "loc", ":", "{", "line", ":", "lineNumber", ",", "column", ":", "0", "}", ",", "messageId", ":", "\"max\"", ",", "data", ":", "{", "lineNumber", ":", "i", "+", "1", ",", "maxLength", "}", "}", ")", ";", "}", "}", ")", ";", "}" ]
Check the program for max length @param {ASTNode} node Node to examine @returns {void} @private
[ "Check", "the", "program", "for", "max", "length" ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/max-len.js#L266-L366
train
eslint/eslint
lib/rules/no-eval.js
isConstant
function isConstant(node, name) { switch (node.type) { case "Literal": return node.value === name; case "TemplateLiteral": return ( node.expressions.length === 0 && node.quasis[0].value.cooked === name ); default: return false; } }
javascript
function isConstant(node, name) { switch (node.type) { case "Literal": return node.value === name; case "TemplateLiteral": return ( node.expressions.length === 0 && node.quasis[0].value.cooked === name ); default: return false; } }
[ "function", "isConstant", "(", "node", ",", "name", ")", "{", "switch", "(", "node", ".", "type", ")", "{", "case", "\"Literal\"", ":", "return", "node", ".", "value", "===", "name", ";", "case", "\"TemplateLiteral\"", ":", "return", "(", "node", ".", "expressions", ".", "length", "===", "0", "&&", "node", ".", "quasis", "[", "0", "]", ".", "value", ".", "cooked", "===", "name", ")", ";", "default", ":", "return", "false", ";", "}", "}" ]
Checks a given node is a Literal node of the specified string value. @param {ASTNode} node - A node to check. @param {string} name - A name to check. @returns {boolean} `true` if the node is a Literal node of the name.
[ "Checks", "a", "given", "node", "is", "a", "Literal", "node", "of", "the", "specified", "string", "value", "." ]
bc0819c94aad14f7fad3cbc2338ea15658b0f272
https://github.com/eslint/eslint/blob/bc0819c94aad14f7fad3cbc2338ea15658b0f272/lib/rules/no-eval.js#L41-L55
train