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