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