From 8e1a095f4cc3b371a0a424b66e13ec77734193a2 Mon Sep 17 00:00:00 2001 From: Teddy Katz Date: Sun, 29 Oct 2017 01:30:12 -0400 Subject: [PATCH] Chore: enable a modified version of multiline-comment-style on codebase (#9452) This makes the following changes: * Creates a project-specific `multiline-comment-style` rule, which is the same as the built-in `multiline-comment-style` rule except that it ignores the banner comments that we use at the top of files. * Enables the `multiline-comment-style` rule on the ESLint codebase --- .eslintrc.js | 3 +- Makefile.js | 8 +- conf/default-cli-options.js | 8 +- lib/ast-utils.js | 96 ++++---- lib/cli-engine.js | 8 +- lib/code-path-analysis/code-path-analyzer.js | 12 +- lib/code-path-analysis/code-path-segment.js | 6 +- lib/code-path-analysis/code-path-state.js | 6 +- lib/config.js | 20 +- lib/config/autoconfig.js | 26 ++- lib/config/config-initializer.js | 16 +- lib/config/config-ops.js | 42 ++-- lib/config/config-rule.js | 48 ++-- lib/config/config-validator.js | 20 +- lib/formatters/tap.js | 8 +- lib/ignored-paths.js | 6 +- lib/linter.js | 18 +- lib/rules/array-bracket-newline.js | 40 ++-- lib/rules/array-bracket-spacing.js | 56 ++--- lib/rules/array-callback-return.js | 22 +- lib/rules/array-element-newline.js | 16 +- lib/rules/arrow-body-style.js | 18 +- lib/rules/arrow-parens.js | 6 +- lib/rules/brace-style.js | 28 +-- lib/rules/computed-property-spacing.js | 44 ++-- lib/rules/consistent-return.js | 8 +- lib/rules/consistent-this.js | 6 +- lib/rules/curly.js | 22 +- lib/rules/dot-notation.js | 10 +- lib/rules/func-call-spacing.js | 6 +- lib/rules/getter-return.js | 3 +- lib/rules/indent-legacy.js | 32 ++- lib/rules/indent.js | 150 +++++++------ lib/rules/key-spacing.js | 8 +- lib/rules/lines-around-directive.js | 28 ++- lib/rules/max-statements-per-line.js | 8 +- lib/rules/newline-after-var.js | 14 +- lib/rules/newline-before-return.js | 16 +- lib/rules/no-await-in-loop.js | 26 ++- lib/rules/no-bitwise.js | 8 +- lib/rules/no-catch-shadow.js | 6 +- lib/rules/no-console.js | 3 +- lib/rules/no-else-return.js | 28 ++- lib/rules/no-empty-character-class.js | 22 +- lib/rules/no-extra-parens.js | 24 +- lib/rules/no-extra-semi.js | 8 +- lib/rules/no-global-assign.js | 6 +- lib/rules/no-implicit-coercion.js | 12 +- lib/rules/no-implied-eval.js | 3 +- lib/rules/no-label-var.js | 6 +- lib/rules/no-lone-blocks.js | 6 +- lib/rules/no-loop-func.js | 12 +- lib/rules/no-native-reassign.js | 6 +- lib/rules/no-param-reassign.js | 6 +- lib/rules/no-regex-spaces.js | 2 +- lib/rules/no-restricted-properties.js | 20 +- lib/rules/no-return-await.js | 12 +- lib/rules/no-self-assign.js | 6 +- lib/rules/no-sequences.js | 10 +- lib/rules/no-trailing-spaces.js | 20 +- lib/rules/no-unreachable.js | 6 +- lib/rules/no-use-before-define.js | 24 +- lib/rules/no-useless-escape.js | 45 ++-- lib/rules/no-useless-return.js | 22 +- lib/rules/no-whitespace-before-property.js | 6 +- lib/rules/object-curly-spacing.js | 40 ++-- lib/rules/object-shorthand.js | 74 ++++--- lib/rules/operator-assignment.js | 18 +- lib/rules/operator-linebreak.js | 22 +- lib/rules/padding-line-between-statements.js | 6 +- lib/rules/prefer-arrow-callback.js | 22 +- lib/rules/prefer-const.js | 28 ++- lib/rules/prefer-destructuring.js | 6 +- lib/rules/prefer-numeric-literals.js | 6 +- lib/rules/prefer-promise-reject-errors.js | 32 +-- lib/rules/prefer-rest-params.js | 6 +- lib/rules/prefer-template.js | 62 +++--- lib/rules/quote-props.js | 16 +- lib/rules/semi.js | 8 +- lib/rules/sort-imports.js | 8 +- lib/rules/space-unary-ops.js | 122 +++++----- lib/rules/strict.js | 16 +- lib/rules/valid-typeof.js | 8 +- lib/rules/wrap-iife.js | 8 +- lib/rules/yoda.js | 16 +- lib/testers/rule-tester.js | 20 +- lib/token-store/backward-token-cursor.js | 8 +- lib/token-store/forward-token-cursor.js | 8 +- lib/token-store/utils.js | 12 +- lib/util/glob.js | 2 +- lib/util/node-event-generator.js | 20 +- lib/util/source-code-fixer.js | 6 +- lib/util/source-code.js | 3 +- package.json | 1 + tests/bin/eslint.js | 38 ++-- tests/lib/ast-utils.js | 6 +- tests/lib/cli-engine.js | 20 +- tests/lib/cli.js | 6 +- tests/lib/code-path-analysis/code-path.js | 3 + tests/lib/config.js | 7 +- tests/lib/formatters/stylish.js | 6 +- tests/lib/linter.js | 7 +- tests/lib/rules/array-bracket-newline.js | 30 ++- tests/lib/rules/array-element-newline.js | 24 +- tests/lib/rules/constructor-super.js | 6 +- tests/lib/rules/getter-return.js | 36 ++- tests/lib/rules/indent.js | 60 +++-- tests/lib/rules/keyword-spacing.js | 19 +- tests/lib/rules/lines-around-directive.js | 208 ++++++++++++------ tests/lib/rules/max-statements.js | 16 +- tests/lib/rules/newline-before-return.js | 6 +- tests/lib/rules/no-unused-labels.js | 12 +- tests/lib/rules/no-unused-vars.js | 28 +-- tests/lib/rules/no-useless-return.js | 6 +- tests/lib/rules/no-var.js | 6 +- tests/lib/rules/object-curly-spacing.js | 6 +- .../rules/padding-line-between-statements.js | 3 +- tests/lib/rules/prefer-const.js | 6 +- tests/lib/token-store.js | 24 +- tests/lib/util/source-code-fixer.js | 6 +- .../internal-rules/multiline-comment-style.js | 38 ++++ .../internal-rules/multiline-comment-style.js | 25 +++ 122 files changed, 1470 insertions(+), 1039 deletions(-) create mode 100644 tests/tools/internal-rules/multiline-comment-style.js create mode 100644 tools/internal-rules/multiline-comment-style.js diff --git a/.eslintrc.js b/.eslintrc.js index 11c9ebe23ba..b7b73ec55e8 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -24,6 +24,7 @@ module.exports = { "eslint-plugin/prefer-placeholders": "error", "eslint-plugin/report-message-format": ["error", "[^a-z].*\\.$"], "eslint-plugin/test-case-property-ordering": "error", - "eslint-plugin/test-case-shorthand-strings": "error" + "eslint-plugin/test-case-shorthand-strings": "error", + "rulesdir/multiline-comment-style": "error" } }; diff --git a/Makefile.js b/Makefile.js index 505fc143dec..544ee8fc647 100644 --- a/Makefile.js +++ b/Makefile.js @@ -843,9 +843,11 @@ target.checkRuleFiles = function() { const docText = cat(docFilename); const idOldAtEndOfTitleRegExp = new RegExp(`^# (.*?) \\(${id}\\)`); // original format const idNewAtBeginningOfTitleRegExp = new RegExp(`^# ${id}: `); // new format is same as rules index - // 1. Added support for new format. - // 2. Will remove support for old format after all docs files have new format. - // 3. Will remove this check when the main heading is automatically generated from rule metadata. + /* + * 1. Added support for new format. + * 2. Will remove support for old format after all docs files have new format. + * 3. Will remove this check when the main heading is automatically generated from rule metadata. + */ return idNewAtBeginningOfTitleRegExp.test(docText) || idOldAtEndOfTitleRegExp.test(docText); } diff --git a/conf/default-cli-options.js b/conf/default-cli-options.js index 6e4a113003e..7d46d46c521 100644 --- a/conf/default-cli-options.js +++ b/conf/default-cli-options.js @@ -17,9 +17,11 @@ module.exports = { ignorePath: null, cache: false, - // in order to honor the cacheFile option if specified - // this option should not have a default value otherwise - // it will always be used + /* + * in order to honor the cacheFile option if specified + * this option should not have a default value otherwise + * it will always be used + */ cacheLocation: "", cacheFile: ".eslintcache", fix: false, diff --git a/lib/ast-utils.js b/lib/ast-utils.js index fc0471e9a4a..23d2a7dcbc4 100644 --- a/lib/ast-utils.js +++ b/lib/ast-utils.js @@ -620,15 +620,17 @@ module.exports = { node = parent; break; - // If the upper function is IIFE, checks the destination of the return value. - // e.g. - // obj.foo = (function() { - // // setup... - // return function foo() { ... }; - // })(); - // obj.foo = (() => - // function foo() { ... } - // )(); + /* + * If the upper function is IIFE, checks the destination of the return value. + * e.g. + * obj.foo = (function() { + * // setup... + * return function foo() { ... }; + * })(); + * obj.foo = (() => + * function foo() { ... } + * )(); + */ case "ReturnStatement": { const func = getUpperFunction(parent); @@ -645,23 +647,27 @@ module.exports = { node = parent.parent; break; - // e.g. - // var obj = { foo() { ... } }; - // var obj = { foo: function() { ... } }; - // class A { constructor() { ... } } - // class A { foo() { ... } } - // class A { get foo() { ... } } - // class A { set foo() { ... } } - // class A { static foo() { ... } } + /* + * e.g. + * var obj = { foo() { ... } }; + * var obj = { foo: function() { ... } }; + * class A { constructor() { ... } } + * class A { foo() { ... } } + * class A { get foo() { ... } } + * class A { set foo() { ... } } + * class A { static foo() { ... } } + */ case "Property": case "MethodDefinition": return parent.value !== node; - // e.g. - // obj.foo = function foo() { ... }; - // Foo = function() { ... }; - // [obj.foo = function foo() { ... }] = a; - // [Foo = function() { ... }] = a; + /* + * e.g. + * obj.foo = function foo() { ... }; + * Foo = function() { ... }; + * [obj.foo = function foo() { ... }] = a; + * [Foo = function() { ... }] = a; + */ case "AssignmentExpression": case "AssignmentPattern": if (parent.left.type === "MemberExpression") { @@ -676,8 +682,10 @@ module.exports = { } return true; - // e.g. - // var Foo = function() { ... }; + /* + * e.g. + * var Foo = function() { ... }; + */ case "VariableDeclarator": return !( isAnonymous && @@ -686,10 +694,12 @@ module.exports = { startsWithUpperCase(parent.id.name) ); - // e.g. - // var foo = function foo() { ... }.bind(obj); - // (function foo() { ... }).call(obj); - // (function foo() { ... }).apply(obj, []); + /* + * e.g. + * var foo = function foo() { ... }.bind(obj); + * (function foo() { ... }).call(obj); + * (function foo() { ... }).apply(obj, []); + */ case "MemberExpression": return ( parent.object !== node || @@ -700,10 +710,12 @@ module.exports = { isNullOrUndefined(parent.parent.arguments[0]) ); - // e.g. - // Reflect.apply(function() {}, obj, []); - // Array.from([], function() {}, obj); - // list.forEach(function() {}, obj); + /* + * e.g. + * Reflect.apply(function() {}, obj, []); + * Array.from([], function() {}, obj); + * list.forEach(function() {}, obj); + */ case "CallExpression": if (isReflectApply(parent.callee)) { return ( @@ -930,8 +942,10 @@ module.exports = { node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || - // Do not check arrow functions with implicit return. - // `() => "use strict";` returns the string `"use strict"`. + /* + * Do not check arrow functions with implicit return. + * `() => "use strict";` returns the string `"use strict"`. + */ (node.type === "ArrowFunctionExpression" && node.body.type === "BlockStatement") ) { const statements = node.type === "Program" ? node.body : node.body.body; @@ -954,7 +968,7 @@ module.exports = { /** * Determines whether this node is a decimal integer literal. If a node is a decimal integer literal, a dot added - after the node will be parsed as a decimal point, rather than a property-access dot. + * after the node will be parsed as a decimal point, rather than a property-access dot. * @param {ASTNode} node - The node to check. * @returns {boolean} `true` if this node is a decimal integer. * @example @@ -1183,12 +1197,12 @@ module.exports = { }, /** - * Gets the parenthesized text of a node. This is similar to sourceCode.getText(node), but it also includes any parentheses - * surrounding the node. - * @param {SourceCode} sourceCode The source code object - * @param {ASTNode} node An expression node - * @returns {string} The text representing the node, with all surrounding parentheses included - */ + * Gets the parenthesized text of a node. This is similar to sourceCode.getText(node), but it also includes any parentheses + * surrounding the node. + * @param {SourceCode} sourceCode The source code object + * @param {ASTNode} node An expression node + * @returns {string} The text representing the node, with all surrounding parentheses included + */ getParenthesisedText(sourceCode, node) { let leftToken = sourceCode.getFirstToken(node); let rightToken = sourceCode.getLastToken(node); diff --git a/lib/cli-engine.js b/lib/cli-engine.js index 5fc35ae0ac8..29ee9fef560 100644 --- a/lib/cli-engine.js +++ b/lib/cli-engine.js @@ -542,10 +542,10 @@ class CLIEngine { if (result.messages.length) { /* - * if a file contains errors or warnings we don't want to - * store the file in the cache so we can guarantee that - * next execution will also operate on this file - */ + * if a file contains errors or warnings we don't want to + * store the file in the cache so we can guarantee that + * next execution will also operate on this file + */ fileCache.removeEntry(result.filePath); } else { diff --git a/lib/code-path-analysis/code-path-analyzer.js b/lib/code-path-analysis/code-path-analyzer.js index 899f240bc45..1a4f7870baa 100644 --- a/lib/code-path-analysis/code-path-analyzer.js +++ b/lib/code-path-analysis/code-path-analyzer.js @@ -598,8 +598,10 @@ class CodePathAnalyzer { preprocess(this, node); } - // Updates the code path. - // And emits onCodePathStart/onCodePathSegmentStart events. + /* + * Updates the code path. + * And emits onCodePathStart/onCodePathSegmentStart events. + */ processCodePathToEnter(this, node); // Emits node events. @@ -618,8 +620,10 @@ class CodePathAnalyzer { leaveNode(node) { this.currentNode = node; - // Updates the code path. - // And emits onCodePathStart/onCodePathSegmentStart events. + /* + * Updates the code path. + * And emits onCodePathStart/onCodePathSegmentStart events. + */ processCodePathToExit(this, node); // Emits node events. diff --git a/lib/code-path-analysis/code-path-segment.js b/lib/code-path-analysis/code-path-segment.js index 9de4264b130..8145f928016 100644 --- a/lib/code-path-analysis/code-path-segment.js +++ b/lib/code-path-analysis/code-path-segment.js @@ -141,8 +141,10 @@ class CodePathSegment { static newUnreachable(id, allPrevSegments) { const segment = new CodePathSegment(id, CodePathSegment.flattenUnusedSegments(allPrevSegments), false); - // In `if (a) return a; foo();` case, the unreachable segment preceded by - // the return statement is not used but must not be remove. + /* + * In `if (a) return a; foo();` case, the unreachable segment preceded by + * the return statement is not used but must not be remove. + */ CodePathSegment.markUsed(segment); return segment; diff --git a/lib/code-path-analysis/code-path-state.js b/lib/code-path-analysis/code-path-state.js index 068caca9e6d..0c31e2072b0 100644 --- a/lib/code-path-analysis/code-path-state.js +++ b/lib/code-path-analysis/code-path-state.js @@ -774,8 +774,10 @@ class CodePathState { // Sets the normal path as the next. this.forkContext.replaceHead(normalSegments); - // If both paths of the `try` block and the `catch` block are - // unreachable, the next path becomes unreachable as well. + /* + * If both paths of the `try` block and the `catch` block are + * unreachable, the next path becomes unreachable as well. + */ if (!context.lastOfTryIsReachable && !context.lastOfCatchIsReachable) { this.forkContext.makeUnreachable(); } diff --git a/lib/config.js b/lib/config.js index c20522f6b36..b66b9f41e0d 100644 --- a/lib/config.js +++ b/lib/config.js @@ -120,10 +120,10 @@ class Config { } /** - * Loads the config options from a config specified on the command line. - * @param {string} [config] A shareable named config or path to a config file. - * @returns {void} - */ + * Loads the config options from a config specified on the command line. + * @param {string} [config] A shareable named config or path to a config file. + * @returns {void} + */ loadSpecificConfig(config) { if (config) { debug(`Using command line config ${config}`); @@ -216,8 +216,10 @@ class Config { return localConfigHierarchy; } - // Don't consider the personal config file in the home directory, - // except if the home directory is the same as the current working directory + /* + * Don't consider the personal config file in the home directory, + * except if the home directory is the same as the current working directory + */ if (localConfigDirectory === PERSONAL_CONFIG_DIR && localConfigFile !== projectConfigPath) { continue; } @@ -343,8 +345,10 @@ class Config { this.plugins.loadAll(this.cliConfig.plugins); } - // Step 3: Override parser only if it is passed explicitly through the command line - // or if it's not defined yet (because the final object will at least have the parser key) + /* + * Step 3: Override parser only if it is passed explicitly through the command line + * or if it's not defined yet (because the final object will at least have the parser key) + */ if (this.parser || !config.parser) { config = ConfigOps.merge(config, { parser: this.parser }); } diff --git a/lib/config/autoconfig.js b/lib/config/autoconfig.js index 6614a1bc48b..8536fdc55ad 100644 --- a/lib/config/autoconfig.js +++ b/lib/config/autoconfig.js @@ -61,13 +61,13 @@ function makeRegistryItems(rulesConfig) { } /** -* Creates an object in which to store rule configs and error counts -* -* Unless a rulesConfig is provided at construction, the registry will not contain -* any rules, only methods. This will be useful for building up registries manually. -* -* Registry class -*/ + * Creates an object in which to store rule configs and error counts + * + * Unless a rulesConfig is provided at construction, the registry will not contain + * any rules, only methods. This will be useful for building up registries manually. + * + * Registry class + */ class Registry { /** @@ -293,11 +293,13 @@ class Registry { lintResults.forEach(result => { - // It is possible that the error is from a configuration comment - // in a linted file, in which case there may not be a config - // set in this ruleSetIdx. - // (https://github.com/eslint/eslint/issues/5992) - // (https://github.com/eslint/eslint/issues/7860) + /* + * It is possible that the error is from a configuration comment + * in a linted file, in which case there may not be a config + * set in this ruleSetIdx. + * (https://github.com/eslint/eslint/issues/5992) + * (https://github.com/eslint/eslint/issues/7860) + */ if ( lintedRegistry.rules[result.ruleId] && lintedRegistry.rules[result.ruleId][ruleSetIdx] diff --git a/lib/config/config-initializer.js b/lib/config/config-initializer.js index 47139e06e3c..e4865a008ca 100644 --- a/lib/config/config-initializer.js +++ b/lib/config/config-initializer.js @@ -201,14 +201,18 @@ function configureRules(answers, config) { // Now that we know which rules to disable, strip out configs with errors registry = registry.stripFailingConfigs(); - // If there is only one config that results in no errors for a rule, we should use it. - // createConfig will only add rules that have one configuration in the registry. + /* + * If there is only one config that results in no errors for a rule, we should use it. + * createConfig will only add rules that have one configuration in the registry. + */ const singleConfigs = registry.createConfig().rules; - // The "sweet spot" for number of options in a config seems to be two (severity plus one option). - // Very often, a third option (usually an object) is available to address - // edge cases, exceptions, or unique situations. We will prefer to use a config with - // specificity of two. + /* + * The "sweet spot" for number of options in a config seems to be two (severity plus one option). + * Very often, a third option (usually an object) is available to address + * edge cases, exceptions, or unique situations. We will prefer to use a config with + * specificity of two. + */ const specTwoConfigs = registry.filterBySpecificity(2).createConfig().rules; // Maybe a specific combination using all three options works diff --git a/lib/config/config-ops.js b/lib/config/config-ops.js index 4ed5ec6b02e..2ce500a4f47 100644 --- a/lib/config/config-ops.js +++ b/lib/config/config-ops.js @@ -105,27 +105,27 @@ module.exports = { merge: function deepmerge(target, src, combine, isRule) { /* - The MIT License (MIT) - - Copyright (c) 2012 Nicholas Fisher - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. + * The MIT License (MIT) + * + * Copyright (c) 2012 Nicholas Fisher + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. */ /* diff --git a/lib/config/config-rule.js b/lib/config/config-rule.js index 174b34a47d6..5fc38ac5d17 100644 --- a/lib/config/config-rule.js +++ b/lib/config/config-rule.js @@ -187,19 +187,19 @@ class RuleConfigSet { constructor(configs) { /** - * Stored valid rule configurations for this instance - * @type {array} - */ + * Stored valid rule configurations for this instance + * @type {array} + */ this.ruleConfigs = configs || []; } /** - * Add a severity level to the front of all configs in the instance. - * This should only be called after all configs have been added to the instance. - * - * @param {number} [severity=2] The level of severity for the rule (0, 1, 2) - * @returns {void} - */ + * Add a severity level to the front of all configs in the instance. + * This should only be called after all configs have been added to the instance. + * + * @param {number} [severity=2] The level of severity for the rule (0, 1, 2) + * @returns {void} + */ addErrorSeverity(severity) { severity = severity || 2; @@ -213,19 +213,19 @@ class RuleConfigSet { } /** - * Add rule configs from an array of strings (schema enums) - * @param {string[]} enums Array of valid rule options (e.g. ["always", "never"]) - * @returns {void} - */ + * Add rule configs from an array of strings (schema enums) + * @param {string[]} enums Array of valid rule options (e.g. ["always", "never"]) + * @returns {void} + */ addEnums(enums) { this.ruleConfigs = this.ruleConfigs.concat(combineArrays(this.ruleConfigs, enums)); } /** - * Add rule configurations from a schema object - * @param {Object} obj Schema item with type === "object" - * @returns {boolean} true if at least one schema for the object could be generated, false otherwise - */ + * Add rule configurations from a schema object + * @param {Object} obj Schema item with type === "object" + * @returns {boolean} true if at least one schema for the object could be generated, false otherwise + */ addObject(obj) { const objectConfigSet = { objectConfigs: [], @@ -267,10 +267,10 @@ class RuleConfigSet { } /** -* 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 + * @param {Object} schema A rule's schema object + * @returns {array[]} Valid rule configurations + */ function generateConfigsFromSchema(schema) { const configSet = new RuleConfigSet(); @@ -296,9 +296,9 @@ function generateConfigsFromSchema(schema) { } /** -* 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 + * @returns {rulesConfig} Hash of rule names and arrays of possible configurations + */ function createCoreRuleConfigs() { const ruleList = loadRules(); diff --git a/lib/config/config-validator.js b/lib/config/config-validator.js index 22bc1efbd0d..5aeb635c1d4 100644 --- a/lib/config/config-validator.js +++ b/lib/config/config-validator.js @@ -56,10 +56,10 @@ function getRuleOptionsSchema(id, rulesContext) { } /** -* 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. + * @param {options} options The given options for the rule. + * @returns {number|string} The rule's severity value + */ function validateRuleSeverity(options) { const severity = Array.isArray(options) ? options[0] : options; @@ -71,12 +71,12 @@ function validateRuleSeverity(options) { } /** -* Validates the non-severity options passed to a rule, based on its schema. -* @param {string} id The rule's unique name -* @param {array} localOptions The options for the rule, excluding severity -* @param {Rules} rulesContext Rule context -* @returns {void} -*/ + * Validates the non-severity options passed to a rule, based on its schema. + * @param {string} id The rule's unique name + * @param {array} localOptions The options for the rule, excluding severity + * @param {Rules} rulesContext Rule context + * @returns {void} + */ function validateRuleSchema(id, localOptions, rulesContext) { const schema = getRuleOptionsSchema(id, rulesContext); diff --git a/lib/formatters/tap.js b/lib/formatters/tap.js index 06699257b58..9651a2bcf12 100644 --- a/lib/formatters/tap.js +++ b/lib/formatters/tap.js @@ -63,9 +63,11 @@ module.exports = function(results) { } }; - // If we have multiple messages place them under a messages key - // The first error will be logged as message key - // This is to adhere to TAP 13 loosely defined specification of having a message key + /* + * If we have multiple messages place them under a messages key + * The first error will be logged as message key + * This is to adhere to TAP 13 loosely defined specification of having a message key + */ if ("message" in diagnostics) { if (typeof diagnostics.messages === "undefined") { diagnostics.messages = []; diff --git a/lib/ignored-paths.js b/lib/ignored-paths.js index f43ce464228..c02e83bc2a5 100644 --- a/lib/ignored-paths.js +++ b/lib/ignored-paths.js @@ -114,8 +114,10 @@ class IgnoredPaths { default: ignore() }; - // Add a way to keep track of ignored files. This was present in node-ignore - // 2.x, but dropped for now as of 3.0.10. + /* + * Add a way to keep track of ignored files. This was present in node-ignore + * 2.x, but dropped for now as of 3.0.10. + */ this.ig.custom.ignoreFiles = []; this.ig.default.ignoreFiles = []; diff --git a/lib/linter.js b/lib/linter.js index 089f0bb2503..12879842453 100755 --- a/lib/linter.js +++ b/lib/linter.js @@ -111,8 +111,10 @@ function parseJsonConfig(string, location) { // ignore to parse the string by a fallback. } - // Optionator cannot parse commaless notations. - // But we are supporting that. So this is a fallback for that. + /* + * Optionator cannot parse commaless notations. + * But we are supporting that. So this is a fallback for that. + */ items = {}; string = string.replace(/([a-zA-Z0-9\-/]+):/g, "\"$1\":").replace(/(]|[0-9])\s+(?=")/, "$1,"); try { @@ -379,8 +381,10 @@ function normalizeEcmaVersion(ecmaVersion, isModule) { ecmaVersion = 6; } - // Calculate ECMAScript edition number from official year version starting with - // ES2015, which corresponds with ES6 (or a difference of 2009). + /* + * Calculate ECMAScript edition number from official year version starting with + * ES2015, which corresponds with ES6 (or a difference of 2009). + */ if (ecmaVersion >= 2015) { ecmaVersion -= 2009; } @@ -1076,8 +1080,10 @@ module.exports = class Linter { debug(`Generating fixed text for ${debugTextDescription} (pass ${passNumber})`); fixedResult = SourceCodeFixer.applyFixes(text, messages, shouldFix); - // stop if there are any syntax errors. - // 'fixedResult.output' is a empty string. + /* + * stop if there are any syntax errors. + * 'fixedResult.output' is a empty string. + */ if (messages.length === 1 && messages[0].fatal) { break; } diff --git a/lib/rules/array-bracket-newline.js b/lib/rules/array-bracket-newline.js index 5115ef4b568..cb7350a8250 100644 --- a/lib/rules/array-bracket-newline.js +++ b/lib/rules/array-bracket-newline.js @@ -96,11 +96,11 @@ module.exports = { } /** - * Reports that there shouldn't be a linebreak after the first token - * @param {ASTNode} node - The node to report in the event of an error. - * @param {Token} token - The token to use for the report. - * @returns {void} - */ + * Reports that there shouldn't be a linebreak after the first token + * @param {ASTNode} node - The node to report in the event of an error. + * @param {Token} token - The token to use for the report. + * @returns {void} + */ function reportNoBeginningLinebreak(node, token) { context.report({ node, @@ -119,11 +119,11 @@ module.exports = { } /** - * Reports that there shouldn't be a linebreak before the last token - * @param {ASTNode} node - The node to report in the event of an error. - * @param {Token} token - The token to use for the report. - * @returns {void} - */ + * Reports that there shouldn't be a linebreak before the last token + * @param {ASTNode} node - The node to report in the event of an error. + * @param {Token} token - The token to use for the report. + * @returns {void} + */ function reportNoEndingLinebreak(node, token) { context.report({ node, @@ -142,11 +142,11 @@ module.exports = { } /** - * Reports that there should be a linebreak after the first token - * @param {ASTNode} node - The node to report in the event of an error. - * @param {Token} token - The token to use for the report. - * @returns {void} - */ + * Reports that there should be a linebreak after the first token + * @param {ASTNode} node - The node to report in the event of an error. + * @param {Token} token - The token to use for the report. + * @returns {void} + */ function reportRequiredBeginningLinebreak(node, token) { context.report({ node, @@ -159,11 +159,11 @@ module.exports = { } /** - * Reports that there should be a linebreak before the last token - * @param {ASTNode} node - The node to report in the event of an error. - * @param {Token} token - The token to use for the report. - * @returns {void} - */ + * Reports that there should be a linebreak before the last token + * @param {ASTNode} node - The node to report in the event of an error. + * @param {Token} token - The token to use for the report. + * @returns {void} + */ function reportRequiredEndingLinebreak(node, token) { context.report({ node, diff --git a/lib/rules/array-bracket-spacing.js b/lib/rules/array-bracket-spacing.js index 73cfbdc3c1f..aecef2c4f20 100644 --- a/lib/rules/array-bracket-spacing.js +++ b/lib/rules/array-bracket-spacing.js @@ -66,11 +66,11 @@ module.exports = { //-------------------------------------------------------------------------- /** - * Reports that there shouldn't be a space after the first token - * @param {ASTNode} node - The node to report in the event of an error. - * @param {Token} token - The token to use for the report. - * @returns {void} - */ + * Reports that there shouldn't be a space after the first token + * @param {ASTNode} node - The node to report in the event of an error. + * @param {Token} token - The token to use for the report. + * @returns {void} + */ function reportNoBeginningSpace(node, token) { context.report({ node, @@ -88,11 +88,11 @@ module.exports = { } /** - * Reports that there shouldn't be a space before the last token - * @param {ASTNode} node - The node to report in the event of an error. - * @param {Token} token - The token to use for the report. - * @returns {void} - */ + * Reports that there shouldn't be a space before the last token + * @param {ASTNode} node - The node to report in the event of an error. + * @param {Token} token - The token to use for the report. + * @returns {void} + */ function reportNoEndingSpace(node, token) { context.report({ node, @@ -110,11 +110,11 @@ module.exports = { } /** - * Reports that there should be a space after the first token - * @param {ASTNode} node - The node to report in the event of an error. - * @param {Token} token - The token to use for the report. - * @returns {void} - */ + * Reports that there should be a space after the first token + * @param {ASTNode} node - The node to report in the event of an error. + * @param {Token} token - The token to use for the report. + * @returns {void} + */ function reportRequiredBeginningSpace(node, token) { context.report({ node, @@ -130,11 +130,11 @@ module.exports = { } /** - * Reports that there should be a space before the last token - * @param {ASTNode} node - The node to report in the event of an error. - * @param {Token} token - The token to use for the report. - * @returns {void} - */ + * Reports that there should be a space before the last token + * @param {ASTNode} node - The node to report in the event of an error. + * @param {Token} token - The token to use for the report. + * @returns {void} + */ function reportRequiredEndingSpace(node, token) { context.report({ node, @@ -150,19 +150,19 @@ module.exports = { } /** - * Determines if a node is an object type - * @param {ASTNode} node - The node to check. - * @returns {boolean} Whether or not the node is an object type. - */ + * Determines if a node is an object type + * @param {ASTNode} node - The node to check. + * @returns {boolean} Whether or not the node is an object type. + */ function isObjectType(node) { return node && (node.type === "ObjectExpression" || node.type === "ObjectPattern"); } /** - * Determines if a node is an array type - * @param {ASTNode} node - The node to check. - * @returns {boolean} Whether or not the node is an array type. - */ + * Determines if a node is an array type + * @param {ASTNode} node - The node to check. + * @returns {boolean} Whether or not the node is an array type. + */ function isArrayType(node) { return node && (node.type === "ArrayExpression" || node.type === "ArrayPattern"); } diff --git a/lib/rules/array-callback-return.js b/lib/rules/array-callback-return.js index cf64a98e327..37d6ebe3a72 100644 --- a/lib/rules/array-callback-return.js +++ b/lib/rules/array-callback-return.js @@ -85,12 +85,14 @@ function isCallbackOfArrayMethod(node) { node = parent; break; - // If the upper function is IIFE, checks the destination of the return value. - // e.g. - // foo.every((function() { - // // setup... - // return function callback() { ... }; - // })()); + /* + * If the upper function is IIFE, checks the destination of the return value. + * e.g. + * foo.every((function() { + * // setup... + * return function callback() { ... }; + * })()); + */ case "ReturnStatement": { const func = astUtils.getUpperFunction(parent); @@ -101,9 +103,11 @@ function isCallbackOfArrayMethod(node) { break; } - // e.g. - // Array.from([], function() {}); - // list.every(function() {}); + /* + * e.g. + * Array.from([], function() {}); + * list.every(function() {}); + */ case "CallExpression": if (astUtils.isArrayFromMethod(parent.callee)) { return ( diff --git a/lib/rules/array-element-newline.js b/lib/rules/array-element-newline.js index 8cccae082e2..26dc9bfa0b6 100644 --- a/lib/rules/array-element-newline.js +++ b/lib/rules/array-element-newline.js @@ -87,10 +87,10 @@ module.exports = { } /** - * 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 + * @param {Token} token - The token to use for the report. + * @returns {void} + */ function reportNoLineBreak(token) { const tokenBefore = sourceCode.getTokenBefore(token, { includeComments: true }); @@ -136,10 +136,10 @@ module.exports = { } /** - * 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 + * @param {Token} token - The token to use for the report. + * @returns {void} + */ function reportRequiredLineBreak(token) { const tokenBefore = sourceCode.getTokenBefore(token, { includeComments: true }); diff --git a/lib/rules/arrow-body-style.js b/lib/rules/arrow-body-style.js index 1630b893720..78a391334d7 100644 --- a/lib/rules/arrow-body-style.js +++ b/lib/rules/arrow-body-style.js @@ -132,8 +132,10 @@ module.exports = { sourceCode.commentsExistBetween(openingBrace, firstValueToken) || sourceCode.commentsExistBetween(lastValueToken, closingBrace); - // Remove tokens around the return value. - // If comments don't exist, remove extra spaces as well. + /* + * Remove tokens around the return value. + * If comments don't exist, remove extra spaces as well. + */ if (commentsExist) { fixes.push( fixer.remove(openingBrace), @@ -147,8 +149,10 @@ module.exports = { ); } - // If the first token of the reutrn value is `{`, - // enclose the return value by parentheses to avoid syntax error. + /* + * If the first token of the reutrn value is `{`, + * enclose the return value by parentheses to avoid syntax error. + */ if (astUtils.isOpeningBraceToken(firstValueToken)) { fixes.push( fixer.insertTextBefore(firstValueToken, "("), @@ -156,8 +160,10 @@ module.exports = { ); } - // If the last token of the return statement is semicolon, remove it. - // Non-block arrow body is an expression, not a statement. + /* + * If the last token of the return statement is semicolon, remove it. + * Non-block arrow body is an expression, not a statement. + */ if (astUtils.isSemicolonToken(lastValueToken)) { fixes.push(fixer.remove(lastValueToken)); } diff --git a/lib/rules/arrow-parens.js b/lib/rules/arrow-parens.js index a756baa46b3..e8f8ddd8e76 100644 --- a/lib/rules/arrow-parens.js +++ b/lib/rules/arrow-parens.js @@ -67,8 +67,10 @@ module.exports = { function fixParamsWithParenthesis(fixer) { const paramToken = sourceCode.getTokenAfter(firstTokenOfParam); - // ES8 allows Trailing commas in function parameter lists and calls - // https://github.com/eslint/eslint/issues/8834 + /* + * ES8 allows Trailing commas in function parameter lists and calls + * https://github.com/eslint/eslint/issues/8834 + */ const closingParenToken = sourceCode.getTokenAfter(paramToken, astUtils.isClosingParenToken); const asyncToken = isAsync ? sourceCode.getTokenBefore(firstTokenOfParam) : null; const shouldAddSpaceForAsync = asyncToken && (asyncToken.range[1] === firstTokenOfParam.range[0]); diff --git a/lib/rules/brace-style.js b/lib/rules/brace-style.js index 44bd6d2c80b..320da9dac91 100644 --- a/lib/rules/brace-style.js +++ b/lib/rules/brace-style.js @@ -54,11 +54,11 @@ module.exports = { //-------------------------------------------------------------------------- /** - * Fixes a place where a newline unexpectedly appears - * @param {Token} firstToken The token before the unexpected newline - * @param {Token} secondToken The token after the unexpected newline - * @returns {Function} A fixer function to remove the newlines between the tokens - */ + * Fixes a place where a newline unexpectedly appears + * @param {Token} firstToken The token before the unexpected newline + * @param {Token} secondToken The token after the unexpected newline + * @returns {Function} A fixer function to remove the newlines between the tokens + */ function removeNewlineBetween(firstToken, secondToken) { const textRange = [firstToken.range[1], secondToken.range[0]]; const textBetween = sourceCode.text.slice(textRange[0], textRange[1]); @@ -71,11 +71,11 @@ module.exports = { } /** - * Validates a pair of curly brackets based on the user's config - * @param {Token} openingCurly The opening curly bracket - * @param {Token} closingCurly The closing curly bracket - * @returns {void} - */ + * Validates a pair of curly brackets based on the user's config + * @param {Token} openingCurly The opening curly bracket + * @param {Token} closingCurly The closing curly bracket + * @returns {void} + */ function validateCurlyPair(openingCurly, closingCurly) { const tokenBeforeOpeningCurly = sourceCode.getTokenBefore(openingCurly); const tokenAfterOpeningCurly = sourceCode.getTokenAfter(openingCurly); @@ -116,10 +116,10 @@ module.exports = { } /** - * Validates the location of a token that appears before a keyword (e.g. a newline before `else`) - * @param {Token} curlyToken The closing curly token. This is assumed to precede a keyword token (such as `else` or `finally`). - * @returns {void} - */ + * Validates the location of a token that appears before a keyword (e.g. a newline before `else`) + * @param {Token} curlyToken The closing curly token. This is assumed to precede a keyword token (such as `else` or `finally`). + * @returns {void} + */ function validateCurlyBeforeKeyword(curlyToken) { const keywordToken = sourceCode.getTokenAfter(curlyToken); diff --git a/lib/rules/computed-property-spacing.js b/lib/rules/computed-property-spacing.js index 0c05d9b4852..19c28fd22e1 100644 --- a/lib/rules/computed-property-spacing.js +++ b/lib/rules/computed-property-spacing.js @@ -36,12 +36,12 @@ module.exports = { //-------------------------------------------------------------------------- /** - * Reports that there shouldn't be a space after the first token - * @param {ASTNode} node - The node to report in the event of an error. - * @param {Token} token - The token to use for the report. - * @param {Token} tokenAfter - The token after `token`. - * @returns {void} - */ + * Reports that there shouldn't be a space after the first token + * @param {ASTNode} node - The node to report in the event of an error. + * @param {Token} token - The token to use for the report. + * @param {Token} tokenAfter - The token after `token`. + * @returns {void} + */ function reportNoBeginningSpace(node, token, tokenAfter) { context.report({ node, @@ -57,12 +57,12 @@ module.exports = { } /** - * Reports that there shouldn't be a space before the last token - * @param {ASTNode} node - The node to report in the event of an error. - * @param {Token} token - The token to use for the report. - * @param {Token} tokenBefore - The token before `token`. - * @returns {void} - */ + * Reports that there shouldn't be a space before the last token + * @param {ASTNode} node - The node to report in the event of an error. + * @param {Token} token - The token to use for the report. + * @param {Token} tokenBefore - The token before `token`. + * @returns {void} + */ function reportNoEndingSpace(node, token, tokenBefore) { context.report({ node, @@ -78,11 +78,11 @@ module.exports = { } /** - * Reports that there should be a space after the first token - * @param {ASTNode} node - The node to report in the event of an error. - * @param {Token} token - The token to use for the report. - * @returns {void} - */ + * Reports that there should be a space after the first token + * @param {ASTNode} node - The node to report in the event of an error. + * @param {Token} token - The token to use for the report. + * @returns {void} + */ function reportRequiredBeginningSpace(node, token) { context.report({ node, @@ -98,11 +98,11 @@ module.exports = { } /** - * Reports that there should be a space before the last token - * @param {ASTNode} node - The node to report in the event of an error. - * @param {Token} token - The token to use for the report. - * @returns {void} - */ + * Reports that there should be a space before the last token + * @param {ASTNode} node - The node to report in the event of an error. + * @param {Token} token - The token to use for the report. + * @returns {void} + */ function reportRequiredEndingSpace(node, token) { context.report({ node, diff --git a/lib/rules/consistent-return.js b/lib/rules/consistent-return.js index 20469772a91..a42faaa1ed6 100644 --- a/lib/rules/consistent-return.js +++ b/lib/rules/consistent-return.js @@ -36,10 +36,10 @@ function isUnreachable(segment) { } /** -* Checks whether a given node is a `constructor` method in an ES6 class -* @param {ASTNode} node A node to check -* @returns {boolean} `true` if the node is a `constructor` method -*/ + * Checks whether a given node is a `constructor` method in an ES6 class + * @param {ASTNode} node A node to check + * @returns {boolean} `true` if the node is a `constructor` method + */ function isClassConstructor(node) { return node.type === "FunctionExpression" && node.parent && diff --git a/lib/rules/consistent-this.js b/lib/rules/consistent-this.js index 35c2d56272a..151cdcf9c9c 100644 --- a/lib/rules/consistent-this.js +++ b/lib/rules/consistent-this.js @@ -86,8 +86,10 @@ module.exports = { return; } - // The alias has been declared and not assigned: check it was - // assigned later in the same scope. + /* + * The alias has been declared and not assigned: check it was + * assigned later in the same scope. + */ if (!variable.references.some(reference => { const write = reference.writeExpr; diff --git a/lib/rules/curly.js b/lib/rules/curly.js index 2d867c72b58..37f07d95eec 100644 --- a/lib/rules/curly.js +++ b/lib/rules/curly.js @@ -164,10 +164,10 @@ module.exports = { } /** - * Determines if a semicolon needs to be inserted after removing a set of curly brackets, in order to avoid a SyntaxError. - * @param {Token} closingBracket The } token - * @returns {boolean} `true` if a semicolon needs to be inserted after the last statement in the block. - */ + * Determines if a semicolon needs to be inserted after removing a set of curly brackets, in order to avoid a SyntaxError. + * @param {Token} closingBracket The } token + * @returns {boolean} `true` if a semicolon needs to be inserted after the last statement in the block. + */ function needsSemicolon(closingBracket) { const tokenBefore = sourceCode.getTokenBefore(closingBracket); const tokenAfter = sourceCode.getTokenAfter(closingBracket); @@ -187,9 +187,11 @@ module.exports = { if (lastBlockNode.type === "BlockStatement" && lastBlockNode.parent.type !== "FunctionExpression" && lastBlockNode.parent.type !== "ArrowFunctionExpression") { - // If the last node surrounded by curly brackets is a BlockStatement (other than a FunctionExpression or an ArrowFunctionExpression), - // don't insert a semicolon. Otherwise, the semicolon would be parsed as a separate statement, which would cause - // a SyntaxError if it was followed by `else`. + /* + * If the last node surrounded by curly brackets is a BlockStatement (other than a FunctionExpression or an ArrowFunctionExpression), + * don't insert a semicolon. Otherwise, the semicolon would be parsed as a separate statement, which would cause + * a SyntaxError if it was followed by `else`. + */ return false; } @@ -235,8 +237,10 @@ module.exports = { }, fix(fixer) { - // `do while` expressions sometimes need a space to be inserted after `do`. - // e.g. `do{foo()} while (bar)` should be corrected to `do foo() while (bar)` + /* + * `do while` expressions sometimes need a space to be inserted after `do`. + * e.g. `do{foo()} while (bar)` should be corrected to `do foo() while (bar)` + */ const needsPrecedingSpace = node.type === "DoWhileStatement" && sourceCode.getTokenBefore(bodyNode).range[1] === bodyNode.range[0] && !astUtils.canTokensBeAdjacent("do", sourceCode.getFirstToken(bodyNode, { skip: 1 })); diff --git a/lib/rules/dot-notation.js b/lib/rules/dot-notation.js index cb557993266..21e3df17412 100644 --- a/lib/rules/dot-notation.js +++ b/lib/rules/dot-notation.js @@ -55,11 +55,11 @@ module.exports = { } /** - * Check if the property is valid dot notation - * @param {ASTNode} node The dot notation node - * @param {string} value Value which is to be checked - * @returns {void} - */ + * Check if the property is valid dot notation + * @param {ASTNode} node The dot notation node + * @param {string} value Value which is to be checked + * @returns {void} + */ function checkComputedProperty(node, value) { if ( validIdentifier.test(value) && diff --git a/lib/rules/func-call-spacing.js b/lib/rules/func-call-spacing.js index 4fd78c864b3..00e677d33b0 100644 --- a/lib/rules/func-call-spacing.js +++ b/lib/rules/func-call-spacing.js @@ -118,8 +118,10 @@ module.exports = { message: "Unexpected space between function name and paren.", fix(fixer) { - // Only autofix if there is no newline - // https://github.com/eslint/eslint/issues/7787 + /* + * Only autofix if there is no newline + * https://github.com/eslint/eslint/issues/7787 + */ if (!hasNewline) { return fixer.removeRange([prevToken.range[1], parenToken.range[0]]); } diff --git a/lib/rules/getter-return.js b/lib/rules/getter-return.js index 58fac8bdac2..6eb1efc00c4 100644 --- a/lib/rules/getter-return.js +++ b/lib/rules/getter-return.js @@ -102,7 +102,8 @@ module.exports = { } } - /** Checks whether a node means a getter function. + /** + * Checks whether a node means a getter function. * @param {ASTNode} node - a node to check. * @returns {boolean} if node means a getter, return true; else return false. */ diff --git a/lib/rules/indent-legacy.js b/lib/rules/indent-legacy.js index a5db2bb5d77..cf914068062 100644 --- a/lib/rules/indent-legacy.js +++ b/lib/rules/indent-legacy.js @@ -274,8 +274,10 @@ module.exports = { foundStatement = `${actualSpaces} ${foundSpacesWord} and ${actualTabs} ${foundTabsWord}`; // e.g. "1 space and 2 tabs" } else if (actualSpaces > 0) { - // Abbreviate the message if the expected indentation is also spaces. - // e.g. 'Expected 4 spaces but found 2' rather than 'Expected 4 spaces but found 2 spaces' + /* + * Abbreviate the message if the expected indentation is also spaces. + * e.g. 'Expected 4 spaces but found 2' rather than 'Expected 4 spaces but found 2 spaces' + */ foundStatement = indentType === "space" ? actualSpaces : `${actualSpaces} ${foundSpacesWord}`; } else if (actualTabs > 0) { foundStatement = indentType === "tab" ? actualTabs : `${actualTabs} ${foundTabsWord}`; @@ -323,8 +325,8 @@ module.exports = { * @param {ASTNode|Token} node Node to examine * @param {boolean} [byLastLine=false] get indent of node's last line * @returns {Object} The node's indent. Contains keys `space` and `tab`, representing the indent of each character. Also - contains keys `goodChar` and `badChar`, where `goodChar` is the amount of the user's desired indentation character, and - `badChar` is the amount of the other indentation character. + * contains keys `goodChar` and `badChar`, where `goodChar` is the amount of the user's desired indentation character, and + * `badChar` is the amount of the other indentation character. */ function getNodeIndent(node, byLastLine) { const token = byLastLine ? sourceCode.getLastToken(node) : sourceCode.getFirstToken(node); @@ -445,8 +447,10 @@ module.exports = { */ function checkLastReturnStatementLineIndent(node, firstLineIndent) { - // in case if return statement ends with ');' we have traverse back to ')' - // otherwise we'll measure indent for ';' and replace ')' + /* + * in case if return statement ends with ');' we have traverse back to ')' + * otherwise we'll measure indent for ';' and replace ')' + */ const lastToken = sourceCode.getLastToken(node, astUtils.isClosingParenToken); const textBeforeClosingParenthesis = sourceCode.getText(lastToken, lastToken.loc.start.column).slice(0, -1); @@ -645,8 +649,10 @@ module.exports = { } } - // function body indent should be indent + indent size, unless this - // is a FunctionDeclaration, FunctionExpression, or outer IIFE and the corresponding options are enabled. + /* + * function body indent should be indent + indent size, unless this + * is a FunctionDeclaration, FunctionExpression, or outer IIFE and the corresponding options are enabled. + */ let functionOffset = indentSize; if (options.outerIIFEBody !== null && isOuterIIFE(calleeNode)) { @@ -1027,10 +1033,12 @@ module.exports = { return; } - // The typical layout of variable declarations and assignments - // alter the expectation of correct indentation. Skip them. - // TODO: Add appropriate configuration options for variable - // declarations and assignments. + /* + * The typical layout of variable declarations and assignments + * alter the expectation of correct indentation. Skip them. + * TODO: Add appropriate configuration options for variable + * declarations and assignments. + */ if (getParentNodeByType(node, "VariableDeclarator", ["FunctionExpression", "ArrowFunctionExpression"])) { return; } diff --git a/lib/rules/indent.js b/lib/rules/indent.js index a804f544ab0..42cebf9ea53 100644 --- a/lib/rules/indent.js +++ b/lib/rules/indent.js @@ -200,19 +200,19 @@ class TokenInfo { } /** - * Gets the first token on a given token's line - * @param {Token|ASTNode} token a node or token - * @returns {Token} The first token on the given line - */ + * Gets the first token on a given token's line + * @param {Token|ASTNode} token a node or token + * @returns {Token} The first token on the given line + */ getFirstTokenOfLine(token) { return this.firstTokensByLineNumber.get(token.loc.start.line); } /** - * Determines whether a token is the first token in its line - * @param {Token} token The token - * @returns {boolean} `true` if the token is the first on its line - */ + * Determines whether a token is the first token in its line + * @param {Token} token The token + * @returns {boolean} `true` if the token is the first on its line + */ isFirstTokenOfLine(token) { return this.getFirstTokenOfLine(token) === token; } @@ -336,31 +336,31 @@ class OffsetStorage { } /** - * Sets the desired offset of all tokens in a range - * It's common for node listeners in this file to need to apply the same offset to a large, contiguous range of tokens. - * Moreover, the offset of any given token is usually updated multiple times (roughly once for each node that contains - * it). This means that the offset of each token is updated O(AST depth) times. - * It would not be performant to store and update the offsets for each token independently, because the rule would end - * up having a time complexity of O(number of tokens * AST depth), which is quite slow for large files. - * - * Instead, the offset tree is represented as a collection of contiguous offset ranges in a file. For example, the following - * list could represent the state of the offset tree at a given point: - * - * * Tokens starting in the interval [0, 15) are aligned with the beginning of the file - * * Tokens starting in the interval [15, 30) are offset by 1 indent level from the `bar` token - * * Tokens starting in the interval [30, 43) are offset by 1 indent level from the `foo` token - * * Tokens starting in the interval [43, 820) are offset by 2 indent levels from the `bar` token - * * Tokens starting in the interval [820, ∞) are offset by 1 indent level from the `baz` token - * - * The `setDesiredOffsets` methods inserts ranges like the ones above. The third line above would be inserted by using: - * `setDesiredOffsets([30, 43], fooToken, 1);` - * - * @param {[number, number]} range A [start, end] pair. All tokens with range[0] <= token.start < range[1] will have the offset applied. - * @param {Token} fromToken The token that this is offset from - * @param {number} offset The desired indent level - * @param {boolean} force `true` if this offset should not use the normal collapsing behavior. This should almost always be false. - * @returns {void} - */ + * Sets the desired offset of all tokens in a range + * It's common for node listeners in this file to need to apply the same offset to a large, contiguous range of tokens. + * Moreover, the offset of any given token is usually updated multiple times (roughly once for each node that contains + * it). This means that the offset of each token is updated O(AST depth) times. + * It would not be performant to store and update the offsets for each token independently, because the rule would end + * up having a time complexity of O(number of tokens * AST depth), which is quite slow for large files. + * + * Instead, the offset tree is represented as a collection of contiguous offset ranges in a file. For example, the following + * list could represent the state of the offset tree at a given point: + * + * * Tokens starting in the interval [0, 15) are aligned with the beginning of the file + * * Tokens starting in the interval [15, 30) are offset by 1 indent level from the `bar` token + * * Tokens starting in the interval [30, 43) are offset by 1 indent level from the `foo` token + * * Tokens starting in the interval [43, 820) are offset by 2 indent levels from the `bar` token + * * Tokens starting in the interval [820, ∞) are offset by 1 indent level from the `baz` token + * + * The `setDesiredOffsets` methods inserts ranges like the ones above. The third line above would be inserted by using: + * `setDesiredOffsets([30, 43], fooToken, 1);` + * + * @param {[number, number]} range A [start, end] pair. All tokens with range[0] <= token.start < range[1] will have the offset applied. + * @param {Token} fromToken The token that this is offset from + * @param {number} offset The desired indent level + * @param {boolean} force `true` if this offset should not use the normal collapsing behavior. This should almost always be false. + * @returns {void} + */ setDesiredOffsets(range, fromToken, offset, force) { /* @@ -408,17 +408,19 @@ class OffsetStorage { } /** - * Gets the desired indent of a token - * @param {Token} token The token - * @returns {string} The desired indent of the token - */ + * Gets the desired indent of a token + * @param {Token} token The token + * @returns {string} The desired indent of the token + */ getDesiredIndent(token) { if (!this._desiredIndentCache.has(token)) { if (this._ignoredTokens.has(token)) { - // If the token is ignored, use the actual indent of the token as the desired indent. - // This ensures that no errors are reported for this token. + /* + * If the token is ignored, use the actual indent of the token as the desired indent. + * This ensures that no errors are reported for this token. + */ this._desiredIndentCache.set( token, this._tokenInfo.getTokenIndent(token) @@ -453,10 +455,10 @@ class OffsetStorage { } /** - * Ignores a token, preventing it from being reported. - * @param {Token} token The token - * @returns {void} - */ + * Ignores a token, preventing it from being reported. + * @param {Token} token The token + * @returns {void} + */ ignoreToken(token) { if (this._tokenInfo.isFirstTokenOfLine(token)) { this._ignoredTokens.add(token); @@ -681,8 +683,10 @@ module.exports = { if (actualSpaces > 0) { - // Abbreviate the message if the expected indentation is also spaces. - // e.g. 'Expected 4 spaces but found 2' rather than 'Expected 4 spaces but found 2 spaces' + /* + * Abbreviate the message if the expected indentation is also spaces. + * e.g. 'Expected 4 spaces but found 2' rather than 'Expected 4 spaces but found 2 spaces' + */ foundStatement = indentType === "space" ? actualSpaces : `${actualSpaces} ${foundSpacesWord}`; } else if (actualTabs > 0) { foundStatement = indentType === "tab" ? actualTabs : `${actualTabs} ${foundTabsWord}`; @@ -770,20 +774,20 @@ module.exports = { } /** - * Check indentation for lists of elements (arrays, objects, function params) - * @param {ASTNode[]} elements List of elements that should be offset - * @param {Token} startToken The start token of the list that element should be aligned against, e.g. '[' - * @param {Token} endToken The end token of the list, e.g. ']' - * @param {number|string} offset The amount that the elements should be offset - * @returns {void} - */ + * Check indentation for lists of elements (arrays, objects, function params) + * @param {ASTNode[]} elements List of elements that should be offset + * @param {Token} startToken The start token of the list that element should be aligned against, e.g. '[' + * @param {Token} endToken The end token of the list, e.g. ']' + * @param {number|string} offset The amount that the elements should be offset + * @returns {void} + */ function addElementListIndent(elements, startToken, endToken, offset) { /** - * Gets the first token of a given element, including surrounding parentheses. - * @param {ASTNode} element A node in the `elements` list - * @returns {Token} The first token of this element - */ + * Gets the first token of a given element, including surrounding parentheses. + * @param {ASTNode} element A node in the `elements` list + * @returns {Token} The first token of this element + */ function getFirstToken(element) { let token = sourceCode.getTokenBefore(element); @@ -872,10 +876,10 @@ module.exports = { } /** - * Checks the indentation for nodes that are like function calls (`CallExpression` and `NewExpression`) - * @param {ASTNode} node A CallExpression or NewExpression node - * @returns {void} - */ + * Checks the indentation for nodes that are like function calls (`CallExpression` and `NewExpression`) + * @param {ASTNode} node A CallExpression or NewExpression node + * @returns {void} + */ function addFunctionCallIndent(node) { let openingParen; @@ -894,10 +898,10 @@ module.exports = { } /** - * Checks the indentation of parenthesized values, given a list of tokens in a program - * @param {Token[]} tokens A list of tokens - * @returns {void} - */ + * Checks the indentation of parenthesized values, given a list of tokens in a program + * @param {Token[]} tokens A list of tokens + * @returns {void} + */ function addParensIndent(tokens) { const parenStack = []; const parenPairs = []; @@ -932,11 +936,11 @@ module.exports = { } /** - * Ignore all tokens within an unknown node whose offset do not depend - * on another token's offset within the unknown node - * @param {ASTNode} node Unknown Node - * @returns {void} - */ + * Ignore all tokens within an unknown node whose offset do not depend + * on another token's offset within the unknown node + * @param {ASTNode} node Unknown Node + * @returns {void} + */ function ignoreNode(node) { const unknownNodeTokens = new Set(sourceCode.getTokens(node, { includeComments: true })); @@ -1023,10 +1027,10 @@ module.exports = { const operator = sourceCode.getFirstTokenBetween(node.left, node.right, token => token.value === node.operator); /* - * For backwards compatibility, don't check BinaryExpression indents, e.g. - * var foo = bar && - * baz; - */ + * For backwards compatibility, don't check BinaryExpression indents, e.g. + * var foo = bar && + * baz; + */ const tokenAfterOperator = sourceCode.getTokenAfter(operator); diff --git a/lib/rules/key-spacing.js b/lib/rules/key-spacing.js index a7b825072c1..1c62ad42892 100644 --- a/lib/rules/key-spacing.js +++ b/lib/rules/key-spacing.js @@ -329,9 +329,11 @@ module.exports = { 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. + /* + * 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 ( diff --git a/lib/rules/lines-around-directive.js b/lib/rules/lines-around-directive.js index 65b6cd1db59..b560009f714 100644 --- a/lib/rules/lines-around-directive.js +++ b/lib/rules/lines-around-directive.js @@ -67,12 +67,12 @@ module.exports = { } /** - * 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. + * @param {ASTNode} node A directive node + * @returns {Token} The last token of the node on the line + */ function getLastTokenOnLine(node) { const lastToken = sourceCode.getLastToken(node); const secondToLastToken = sourceCode.getTokenBefore(lastToken); @@ -136,9 +136,11 @@ module.exports = { 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. + /* + * 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); @@ -159,9 +161,11 @@ module.exports = { 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. + /* + * 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; } diff --git a/lib/rules/max-statements-per-line.js b/lib/rules/max-statements-per-line.js index 3bf370efd88..3d18da4ee10 100644 --- a/lib/rules/max-statements-per-line.js +++ b/lib/rules/max-statements-per-line.js @@ -93,9 +93,11 @@ module.exports = { function enterStatement(node) { const line = node.loc.start.line; - // Skip to allow non-block statements if this is direct child of control statements. - // `if (a) foo();` is counted as 1. - // But `if (a) foo(); else foo();` should be counted as 2. + /* + * Skip to allow non-block statements if this is direct child of control statements. + * `if (a) foo();` is counted as 1. + * But `if (a) foo(); else foo();` should be counted as 2. + */ if (SINGLE_CHILD_ALLOWED.test(node.parent.type) && node.parent.alternate !== node ) { diff --git a/lib/rules/newline-after-var.js b/lib/rules/newline-after-var.js index 744a52a580a..80f73c836fa 100644 --- a/lib/rules/newline-after-var.js +++ b/lib/rules/newline-after-var.js @@ -132,10 +132,10 @@ module.exports = { } /** - * Gets the last line of a group of consecutive comments - * @param {number} commentStartLine The starting line of the group - * @returns {number} The number of the last comment line of the group - */ + * Gets the last line of a group of consecutive comments + * @param {number} commentStartLine The starting line of the group + * @returns {number} The number of the last comment line of the group + */ function getLastCommentLineOfBlock(commentStartLine) { const currentCommentEnd = commentEndLine[commentStartLine]; @@ -190,8 +190,10 @@ module.exports = { return; } - // Some coding styles use multiple `var` statements, so do nothing if - // the next token is a `var` statement. + /* + * Some coding styles use multiple `var` statements, so do nothing if + * the next token is a `var` statement. + */ if (nextToken.type === "Keyword" && isVar(nextToken.value)) { return; } diff --git a/lib/rules/newline-before-return.js b/lib/rules/newline-before-return.js index ef6c4a9264e..02bd66db137 100644 --- a/lib/rules/newline-before-return.js +++ b/lib/rules/newline-before-return.js @@ -166,13 +166,15 @@ module.exports = { return true; } - // if the last leading comment ends in the same line as the previous token and - // does not share a line with the `return` node, we can consider it safe to fix. - // Example: - // function a() { - // var b; //comment - // return; - // } + /* + * if the last leading comment ends in the same line as the previous token and + * does not share a line with the `return` node, we can consider it safe to fix. + * Example: + * function a() { + * var b; //comment + * return; + * } + */ if (lastLeadingComment.loc.end.line === tokenBefore.loc.end.line && lastLeadingComment.loc.end.line !== node.loc.start.line) { return true; diff --git a/lib/rules/no-await-in-loop.js b/lib/rules/no-await-in-loop.js index 97fff7f18e0..d1ed92b704c 100644 --- a/lib/rules/no-await-in-loop.js +++ b/lib/rules/no-await-in-loop.js @@ -13,8 +13,10 @@ const loopTypes = new Set([ "DoWhileStatement" ]); -// Node types at which we should stop looking for loops. For example, it is fine to declare an async -// function within a loop, and use await inside of that. +/* + * Node types at which we should stop looking for loops. For example, it is fine to declare an async + * function within a loop, and use await inside of that. + */ const boundaryTypes = new Set([ "FunctionDeclaration", "FunctionExpression", @@ -38,9 +40,11 @@ module.exports = { // Reverse so that we can traverse from the deepest node upwards. ancestors.reverse(); - // Create a set of all the ancestors plus this node so that we can check - // if this use of await appears in the body of the loop as opposed to - // the right-hand side of a for...of, for example. + /* + * Create a set of all the ancestors plus this node so that we can check + * if this use of await appears in the body of the loop as opposed to + * the right-hand side of a for...of, for example. + */ const ancestorSet = new Set(ancestors).add(node); for (let i = 0; i < ancestors.length; i++) { @@ -48,14 +52,18 @@ module.exports = { if (boundaryTypes.has(ancestor.type)) { - // Short-circuit out if we encounter a boundary type. Loops above - // this do not matter. + /* + * Short-circuit out if we encounter a boundary type. Loops above + * this do not matter. + */ return; } if (loopTypes.has(ancestor.type)) { - // Only report if we are actually in the body or another part that gets executed on - // every iteration. + /* + * Only report if we are actually in the body or another part that gets executed on + * every iteration. + */ if ( ancestorSet.has(ancestor.body) || ancestorSet.has(ancestor.test) || diff --git a/lib/rules/no-bitwise.js b/lib/rules/no-bitwise.js index 28028028cae..f062ad26699 100644 --- a/lib/rules/no-bitwise.js +++ b/lib/rules/no-bitwise.js @@ -5,9 +5,11 @@ "use strict"; -// -// Set of bitwise operators. -// +/* + * + * Set of bitwise operators. + * + */ const BITWISE_OPERATORS = [ "^", "|", "&", "<<", ">>", ">>>", "^=", "|=", "&=", "<<=", ">>=", ">>>=", diff --git a/lib/rules/no-catch-shadow.js b/lib/rules/no-catch-shadow.js index beb16aa2baf..bef61902e90 100644 --- a/lib/rules/no-catch-shadow.js +++ b/lib/rules/no-catch-shadow.js @@ -51,8 +51,10 @@ module.exports = { CatchClause(node) { let scope = context.getScope(); - // When ecmaVersion >= 6, CatchClause creates its own scope - // so start from one upper scope to exclude the current node + /* + * When ecmaVersion >= 6, CatchClause creates its own scope + * so start from one upper scope to exclude the current node + */ if (scope.block === node) { scope = scope.upper; } diff --git a/lib/rules/no-console.js b/lib/rules/no-console.js index 32bdf6d1f4d..f5a3a235e6b 100644 --- a/lib/rules/no-console.js +++ b/lib/rules/no-console.js @@ -111,7 +111,8 @@ module.exports = { const consoleVar = astUtils.getVariableByName(scope, "console"); const shadowed = consoleVar && consoleVar.defs.length > 0; - /* 'scope.through' includes all references to undefined + /* + * 'scope.through' includes all references to undefined * variables. If the variable 'console' is not defined, it uses * 'scope.through'. */ diff --git a/lib/rules/no-else-return.js b/lib/rules/no-else-return.js index 6eb6717495b..deeff41ab83 100644 --- a/lib/rules/no-else-return.js +++ b/lib/rules/no-else-return.js @@ -66,10 +66,12 @@ module.exports = { firstTokenOfElseBlock = startToken; } - // If the if block does not have curly braces and does not end in a semicolon - // and the else block starts with (, [, /, +, ` or -, then it is not - // safe to remove the else keyword, because ASI will not add a semicolon - // after the if block + /* + * If the if block does not have curly braces and does not end in a semicolon + * and the else block starts with (, [, /, +, ` or -, then it is not + * safe to remove the else keyword, because ASI will not add a semicolon + * after the if block + */ const ifBlockMaybeUnsafe = node.parent.consequent.type !== "BlockStatement" && lastIfToken.value !== ";"; const elseBlockUnsafe = /^[([/+`-]/.test(firstTokenOfElseBlock.value); @@ -86,10 +88,12 @@ module.exports = { const nextTokenUnsafe = nextToken && /^[([/+`-]/.test(nextToken.value); const nextTokenOnSameLine = nextToken && nextToken.loc.start.line === lastTokenOfElseBlock.loc.start.line; - // If the else block contents does not end in a semicolon, - // and the else block starts with (, [, /, +, ` or -, then it is not - // safe to remove the else block, because ASI will not add a semicolon - // after the remaining else block contents + /* + * If the else block contents does not end in a semicolon, + * and the else block starts with (, [, /, +, ` or -, then it is not + * safe to remove the else block, because ASI will not add a semicolon + * after the remaining else block contents + */ if (nextTokenUnsafe || (nextTokenOnSameLine && nextToken.value !== "}")) { return null; } @@ -101,9 +105,11 @@ module.exports = { fixedSource = source; } - // Extend the replacement range to include the entire - // function to avoid conflicting with no-useless-return. - // https://github.com/eslint/eslint/issues/8026 + /* + * Extend the replacement range to include the entire + * function to avoid conflicting with no-useless-return. + * https://github.com/eslint/eslint/issues/8026 + */ return new FixTracker(fixer, sourceCode) .retainEnclosingFunction(node) .replaceTextRange([elseToken.range[0], node.range[1]], fixedSource); diff --git a/lib/rules/no-empty-character-class.js b/lib/rules/no-empty-character-class.js index f36c6c9f0d8..0ea7c5a0d1c 100644 --- a/lib/rules/no-empty-character-class.js +++ b/lib/rules/no-empty-character-class.js @@ -10,17 +10,17 @@ //------------------------------------------------------------------------------ /* -plain-English description of the following regexp: -0. `^` fix the match at the beginning of the string -1. `\/`: the `/` that begins the regexp -2. `([^\\[]|\\.|\[([^\\\]]|\\.)+\])*`: regexp contents; 0 or more of the following - 2.0. `[^\\[]`: any character that's not a `\` or a `[` (anything but escape sequences and character classes) - 2.1. `\\.`: an escape sequence - 2.2. `\[([^\\\]]|\\.)+\]`: a character class that isn't empty -3. `\/` the `/` that ends the regexp -4. `[gimuy]*`: optional regexp flags -5. `$`: fix the match at the end of the string -*/ + * plain-English description of the following regexp: + * 0. `^` fix the match at the beginning of the string + * 1. `\/`: the `/` that begins the regexp + * 2. `([^\\[]|\\.|\[([^\\\]]|\\.)+\])*`: regexp contents; 0 or more of the following + * 2.0. `[^\\[]`: any character that's not a `\` or a `[` (anything but escape sequences and character classes) + * 2.1. `\\.`: an escape sequence + * 2.2. `\[([^\\\]]|\\.)+\]`: a character class that isn't empty + * 3. `\/` the `/` that ends the regexp + * 4. `[gimuy]*`: optional regexp flags + * 5. `$`: fix the match at the end of the string + */ const regex = /^\/([^\\[]|\\.|\[([^\\\]]|\\.)+])*\/[gimuy]*$/; //------------------------------------------------------------------------------ diff --git a/lib/rules/no-extra-parens.js b/lib/rules/no-extra-parens.js index 020d2aeb10f..d8e0df64a7b 100644 --- a/lib/rules/no-extra-parens.js +++ b/lib/rules/no-extra-parens.js @@ -372,8 +372,10 @@ module.exports = { hasDoubleExcessParens(callee) || !isIIFE(node) && !hasNewParensException && !( - // Allow extra parens around a new expression if - // there are intervening parentheses. + /* + * Allow extra parens around a new expression if + * there are intervening parentheses. + */ callee.type === "MemberExpression" && doesMemberExpressionContainCallExpression(callee) ) @@ -425,8 +427,10 @@ module.exports = { return; } - // If `node.superClass` is a LeftHandSideExpression, parentheses are extra. - // Otherwise, parentheses are needed. + /* + * If `node.superClass` is a LeftHandSideExpression, parentheses are extra. + * Otherwise, parentheses are needed. + */ const hasExtraParens = precedence(node.superClass) > PRECEDENCE_OF_UPDATE_EXPR ? hasExcessParens(node.superClass) : hasDoubleExcessParens(node.superClass); @@ -560,12 +564,16 @@ module.exports = { if ( firstLeftToken.value === "let" && ( - // If `let` is the only thing on the left side of the loop, it's the loop variable: `for ((let) of foo);` - // Removing it will cause a syntax error, because it will be parsed as the start of a VariableDeclarator. + /* + * If `let` is the only thing on the left side of the loop, it's the loop variable: `for ((let) of foo);` + * Removing it will cause a syntax error, because it will be parsed as the start of a VariableDeclarator. + */ firstLeftToken.range[1] === node.left.range[1] || - // If `let` is followed by a `[` token, it's a property access on the `let` value: `for ((let[foo]) of bar);` - // Removing it will cause the property access to be parsed as a destructuring declaration of `foo` instead. + /* + * If `let` is followed by a `[` token, it's a property access on the `let` value: `for ((let[foo]) of bar);` + * Removing it will cause the property access to be parsed as a destructuring declaration of `foo` instead. + */ astUtils.isOpeningBracketToken( sourceCode.getTokenAfter(firstLeftToken, astUtils.isNotClosingParenToken) ) diff --git a/lib/rules/no-extra-semi.js b/lib/rules/no-extra-semi.js index 0ec914989d4..acd312b32b2 100644 --- a/lib/rules/no-extra-semi.js +++ b/lib/rules/no-extra-semi.js @@ -42,9 +42,11 @@ module.exports = { message: "Unnecessary semicolon.", fix(fixer) { - // Expand the replacement range to include the surrounding - // tokens to avoid conflicting with semi. - // https://github.com/eslint/eslint/issues/7928 + /* + * Expand the replacement range to include the surrounding + * tokens to avoid conflicting with semi. + * https://github.com/eslint/eslint/issues/7928 + */ return new FixTracker(fixer, context.getSourceCode()) .retainSurroundingTokens(nodeOrToken) .remove(nodeOrToken); diff --git a/lib/rules/no-global-assign.js b/lib/rules/no-global-assign.js index 5a1cc64aeb2..679650cb70f 100644 --- a/lib/rules/no-global-assign.js +++ b/lib/rules/no-global-assign.js @@ -49,8 +49,10 @@ module.exports = { if (reference.init === false && reference.isWrite() && - // Destructuring assignments can have multiple default value, - // so possibly there are multiple writeable references for the same identifier. + /* + * Destructuring assignments can have multiple default value, + * so possibly there are multiple writeable references for the same identifier. + */ (index === 0 || references[index - 1].identifier !== identifier) ) { context.report({ diff --git a/lib/rules/no-implicit-coercion.js b/lib/rules/no-implicit-coercion.js index cec411af75d..24e04858f06 100644 --- a/lib/rules/no-implicit-coercion.js +++ b/lib/rules/no-implicit-coercion.js @@ -189,12 +189,12 @@ module.exports = { const sourceCode = context.getSourceCode(); /** - * 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 + * @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} + */ function report(node, recommendation, shouldFix) { shouldFix = typeof shouldFix === "undefined" ? true : shouldFix; diff --git a/lib/rules/no-implied-eval.js b/lib/rules/no-implied-eval.js index 4daadd8fb87..cfb16dbf73e 100644 --- a/lib/rules/no-implied-eval.js +++ b/lib/rules/no-implied-eval.js @@ -125,7 +125,8 @@ module.exports = { "CallExpression:exit"(node) { if (node === last(last(impliedEvalAncestorsStack))) { - /* Destroys the entire sub-stack, rather than just using + /* + * Destroys the entire sub-stack, rather than just using * last(impliedEvalAncestorsStack).pop(), as a CallExpression is * always the bottom of a impliedEvalAncestorsStack substack. */ diff --git a/lib/rules/no-label-var.js b/lib/rules/no-label-var.js index 00133685613..954066aef32 100644 --- a/lib/rules/no-label-var.js +++ b/lib/rules/no-label-var.js @@ -54,8 +54,10 @@ module.exports = { // Fetch the innermost scope. const scope = context.getScope(); - // Recursively find the identifier walking up the scope, starting - // with the innermost scope. + /* + * Recursively find the identifier walking up the scope, starting + * with the innermost scope. + */ if (findIdentifier(scope, node.label.name)) { context.report({ node, message: "Found identifier with same name as label." }); } diff --git a/lib/rules/no-lone-blocks.js b/lib/rules/no-lone-blocks.js index 652812fba7b..2b5666e213c 100644 --- a/lib/rules/no-lone-blocks.js +++ b/lib/rules/no-lone-blocks.js @@ -30,7 +30,7 @@ module.exports = { * Reports a node as invalid. * @param {ASTNode} node - The node to be reported. * @returns {void} - */ + */ function report(node) { const message = node.parent.type === "BlockStatement" ? "Nested block is redundant." : "Block is redundant."; @@ -41,7 +41,7 @@ module.exports = { * Checks for any ocurrence of a BlockStatement in a place where lists of statements can appear * @param {ASTNode} node The node to check * @returns {boolean} True if the node is a lone block. - */ + */ function isLoneBlock(node) { return node.parent.type === "BlockStatement" || node.parent.type === "Program" || @@ -54,7 +54,7 @@ module.exports = { * Checks the enclosing block of the current node for block-level bindings, * and "marks it" as valid if any. * @returns {void} - */ + */ function markLoneBlock() { if (loneBlocks.length === 0) { return; diff --git a/lib/rules/no-loop-func.js b/lib/rules/no-loop-func.js index 0e586394d1f..c97e0c3c5ae 100644 --- a/lib/rules/no-loop-func.js +++ b/lib/rules/no-loop-func.js @@ -105,8 +105,10 @@ function isSafe(loopNode, reference) { return true; } - // Variables which are declared by `let` in the loop is safe. - // It's a different instance from the next loop step's. + /* + * 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] @@ -114,8 +116,10 @@ function isSafe(loopNode, reference) { return true; } - // WriteReferences which exist after this border are unsafe because those - // can modify the variable. + /* + * WriteReferences which exist after this border are unsafe because those + * can modify the variable. + */ const border = getTopLoopNode( loopNode, (kind === "let") ? declaration : null diff --git a/lib/rules/no-native-reassign.js b/lib/rules/no-native-reassign.js index d3dfefbaf05..a60d4e499cb 100644 --- a/lib/rules/no-native-reassign.js +++ b/lib/rules/no-native-reassign.js @@ -53,8 +53,10 @@ module.exports = { if (reference.init === false && reference.isWrite() && - // Destructuring assignments can have multiple default value, - // so possibly there are multiple writeable references for the same identifier. + /* + * Destructuring assignments can have multiple default value, + * so possibly there are multiple writeable references for the same identifier. + */ (index === 0 || references[index - 1].identifier !== identifier) ) { context.report({ diff --git a/lib/rules/no-param-reassign.js b/lib/rules/no-param-reassign.js index 560d1d6b6f2..f32e42ae2fa 100644 --- a/lib/rules/no-param-reassign.js +++ b/lib/rules/no-param-reassign.js @@ -127,8 +127,10 @@ module.exports = { if (identifier && !reference.init && - // Destructuring assignments can have multiple default value, - // so possibly there are multiple writeable references for the same identifier. + /* + * Destructuring assignments can have multiple default value, + * so possibly there are multiple writeable references for the same identifier. + */ (index === 0 || references[index - 1].identifier !== identifier) ) { if (reference.isWrite()) { diff --git a/lib/rules/no-regex-spaces.js b/lib/rules/no-regex-spaces.js index b0c840df3a2..9250437caa4 100644 --- a/lib/rules/no-regex-spaces.js +++ b/lib/rules/no-regex-spaces.js @@ -32,7 +32,7 @@ module.exports = { * @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` + * `sourceCode.getText().slice(valueStart, valueStart + value.length) === value` * @returns {void} * @private */ diff --git a/lib/rules/no-restricted-properties.js b/lib/rules/no-restricted-properties.js index 44db74f5354..cdc73f9e410 100644 --- a/lib/rules/no-restricted-properties.js +++ b/lib/rules/no-restricted-properties.js @@ -92,12 +92,12 @@ module.exports = { }); /** - * Checks to see whether a property access is restricted, and reports it if so. - * @param {ASTNode} node The node to report - * @param {string} objectName The name of the object - * @param {string} propertyName The name of the property - * @returns {undefined} - */ + * Checks to see whether a property access is restricted, and reports it if so. + * @param {ASTNode} node The node to report + * @param {string} objectName The name of the object + * @param {string} propertyName The name of the property + * @returns {undefined} + */ function checkPropertyAccess(node, objectName, propertyName) { if (propertyName === null) { return; @@ -135,10 +135,10 @@ module.exports = { } /** - * Checks property accesses in a destructuring assignment expression, e.g. `var foo; ({foo} = bar);` - * @param {ASTNode} node An AssignmentExpression or AssignmentPattern node - * @returns {undefined} - */ + * Checks property accesses in a destructuring assignment expression, e.g. `var foo; ({foo} = bar);` + * @param {ASTNode} node An AssignmentExpression or AssignmentPattern node + * @returns {undefined} + */ function checkDestructuringAssignment(node) { if (node.right.type === "Identifier") { const objectName = node.right.name; diff --git a/lib/rules/no-return-await.js b/lib/rules/no-return-await.js index a7933460d47..2f06b611084 100644 --- a/lib/rules/no-return-await.js +++ b/lib/rules/no-return-await.js @@ -40,12 +40,12 @@ module.exports = { } /** - * Determines whether a thrown error from this node will be caught/handled within this function rather than immediately halting - * this function. For example, a statement in a `try` block will always have an error handler. A statement in - * a `catch` block will only have an error handler if there is also a `finally` block. - * @param {ASTNode} node A node representing a location where an could be thrown - * @returns {boolean} `true` if a thrown error will be caught/handled in this function - */ + * Determines whether a thrown error from this node will be caught/handled within this function rather than immediately halting + * this function. For example, a statement in a `try` block will always have an error handler. A statement in + * a `catch` block will only have an error handler if there is also a `finally` block. + * @param {ASTNode} node A node representing a location where an could be thrown + * @returns {boolean} `true` if a thrown error will be caught/handled in this function + */ function hasErrorHandler(node) { let ancestor = node; diff --git a/lib/rules/no-self-assign.js b/lib/rules/no-self-assign.js index 8b9314a3e87..48b922d46b8 100644 --- a/lib/rules/no-self-assign.js +++ b/lib/rules/no-self-assign.js @@ -114,8 +114,10 @@ function eachSelfAssignment(left, right, props, report) { right.properties.length >= 1 ) { - // Gets the index of the last spread property. - // It's possible to overwrite properties followed by it. + /* + * Gets the index of the last spread property. + * It's possible to overwrite properties followed by it. + */ let startJ = 0; for (let i = right.properties.length - 1; i >= 0; --i) { diff --git a/lib/rules/no-sequences.js b/lib/rules/no-sequences.js index 23c1956ebeb..5e746dfa88f 100644 --- a/lib/rules/no-sequences.js +++ b/lib/rules/no-sequences.js @@ -40,10 +40,12 @@ module.exports = { WithStatement: "object", ArrowFunctionExpression: "body" - // Omitting CallExpression - commas are parsed as argument separators - // Omitting NewExpression - commas are parsed as argument separators - // Omitting ForInStatement - parts aren't individually parenthesised - // Omitting ForStatement - parts aren't individually parenthesised + /* + * Omitting CallExpression - commas are parsed as argument separators + * Omitting NewExpression - commas are parsed as argument separators + * Omitting ForInStatement - parts aren't individually parenthesised + * Omitting ForStatement - parts aren't individually parenthesised + */ }; /** diff --git a/lib/rules/no-trailing-spaces.js b/lib/rules/no-trailing-spaces.js index 598bbea4f9d..fbbc6402175 100644 --- a/lib/rules/no-trailing-spaces.js +++ b/lib/rules/no-trailing-spaces.js @@ -101,8 +101,10 @@ module.exports = { Program: function checkTrailingSpaces(node) { - // Let's hack. Since Espree does not return whitespace nodes, - // fetch the source code and do matching via regexps. + /* + * Let's hack. Since Espree does not return whitespace nodes, + * fetch the source code and do matching via regexps. + */ const re = new RegExp(NONBLANK), skipMatch = new RegExp(SKIP_BLANK), @@ -117,9 +119,11 @@ module.exports = { for (let i = 0, ii = lines.length; i < ii; i++) { const matches = re.exec(lines[i]); - // Always add linebreak length to line length to accommodate for line break (\n or \r\n) - // Because during the fix time they also reserve one spot in the array. - // Usually linebreak length is 2 for \r\n (CRLF) and 1 for \n (LF) + /* + * Always add linebreak length to line length to accommodate for line break (\n or \r\n) + * Because during the fix time they also reserve one spot in the array. + * Usually linebreak length is 2 for \r\n (CRLF) and 1 for \n (LF) + */ const linebreakLength = linebreaks && linebreaks[i] ? linebreaks[i].length : 1; const lineLength = lines[i].length + linebreakLength; @@ -140,8 +144,10 @@ module.exports = { continue; } - // If the line has only whitespace, and skipBlankLines - // is true, don't report it + /* + * If the line has only whitespace, and skipBlankLines + * is true, don't report it + */ if (skipBlankLines && skipMatch.test(lines[i])) { totalLength += lineLength; continue; diff --git a/lib/rules/no-unreachable.js b/lib/rules/no-unreachable.js index 82ef8301a36..217a6a42995 100644 --- a/lib/rules/no-unreachable.js +++ b/lib/rules/no-unreachable.js @@ -145,8 +145,10 @@ module.exports = { nextNode = node; } - // Report the current range since this statement is reachable or is - // not consecutive to the current range. + /* + * Report the current range since this statement is reachable or is + * not consecutive to the current range. + */ if (!range.isEmpty) { context.report({ message: "Unreachable code.", diff --git a/lib/rules/no-use-before-define.js b/lib/rules/no-use-before-define.js index bdff23934c2..ada01815d9c 100644 --- a/lib/rules/no-use-before-define.js +++ b/lib/rules/no-use-before-define.js @@ -59,11 +59,11 @@ function isOuterClass(variable, reference) { } /** -* Checks whether or not a given variable is a variable declaration in an upper function scope. -* @param {eslint-scope.Variable} variable - A variable to check. -* @param {eslint-scope.Reference} reference - A reference to check. -* @returns {boolean} `true` if the variable is a variable declaration. -*/ + * Checks whether or not a given variable is a variable declaration in an upper function scope. + * @param {eslint-scope.Variable} variable - A variable to check. + * @param {eslint-scope.Reference} reference - A reference to check. + * @returns {boolean} `true` if the variable is a variable declaration. + */ function isOuterVariable(variable, reference) { return ( variable.defs[0].type === "Variable" && @@ -194,12 +194,14 @@ module.exports = { scope.references.forEach(reference => { const variable = reference.resolved; - // Skips when the reference is: - // - initialization's. - // - referring to an undefined variable. - // - referring to a global environment variable (there're no identifiers). - // - located preceded by the variable (except in initializers). - // - allowed by options. + /* + * Skips when the reference is: + * - initialization's. + * - referring to an undefined variable. + * - referring to a global environment variable (there're no identifiers). + * - located preceded by the variable (except in initializers). + * - allowed by options. + */ if (reference.init || !variable || variable.identifiers.length === 0 || diff --git a/lib/rules/no-useless-escape.js b/lib/rules/no-useless-escape.js index 9e39eb6f43f..cdc3e98df85 100644 --- a/lib/rules/no-useless-escape.js +++ b/lib/rules/no-useless-escape.js @@ -12,11 +12,11 @@ const astUtils = require("../ast-utils"); //------------------------------------------------------------------------------ /** -* Returns the union of two sets. -* @param {Set} setA The first set -* @param {Set} setB The second set -* @returns {Set} The union of the two sets -*/ + * Returns the union of two sets. + * @param {Set} setA The first set + * @param {Set} setB The second set + * @returns {Set} The union of the two sets + */ function union(setA, setB) { return new Set(function *() { yield* setA; @@ -29,22 +29,22 @@ const REGEX_GENERAL_ESCAPES = new Set("\\bcdDfnrsStvwWxu0123456789]"); const REGEX_NON_CHARCLASS_ESCAPES = union(REGEX_GENERAL_ESCAPES, new Set("^/.$*+?[{}|()B")); /** -* Parses a regular expression into a list of characters with character class info. -* @param {string} regExpText The raw text used to create the regular expression -* @returns {Object[]} A list of characters, each with info on escaping and whether they're in a character class. -* @example -* -* parseRegExp('a\\b[cd-]') -* -* returns: -* [ -* {text: 'a', index: 0, escaped: false, inCharClass: false, startsCharClass: false, endsCharClass: false}, -* {text: 'b', index: 2, escaped: true, inCharClass: false, startsCharClass: false, endsCharClass: false}, -* {text: 'c', index: 4, escaped: false, inCharClass: true, startsCharClass: true, endsCharClass: false}, -* {text: 'd', index: 5, escaped: false, inCharClass: true, startsCharClass: false, endsCharClass: false}, -* {text: '-', index: 6, escaped: false, inCharClass: true, startsCharClass: false, endsCharClass: false} -* ] -*/ + * Parses a regular expression into a list of characters with character class info. + * @param {string} regExpText The raw text used to create the regular expression + * @returns {Object[]} A list of characters, each with info on escaping and whether they're in a character class. + * @example + * + * parseRegExp('a\\b[cd-]') + * + * returns: + * [ + * {text: 'a', index: 0, escaped: false, inCharClass: false, startsCharClass: false, endsCharClass: false}, + * {text: 'b', index: 2, escaped: true, inCharClass: false, startsCharClass: false, endsCharClass: false}, + * {text: 'c', index: 4, escaped: false, inCharClass: true, startsCharClass: true, endsCharClass: false}, + * {text: 'd', index: 5, escaped: false, inCharClass: true, startsCharClass: false, endsCharClass: false}, + * {text: '-', index: 6, escaped: false, inCharClass: true, startsCharClass: false, endsCharClass: false} + * ] + */ function parseRegExp(regExpText) { const charList = []; @@ -130,7 +130,8 @@ module.exports = { isUnnecessaryEscape = match.input[match.index + 2] !== "{"; } else if (escapedChar === "{") { - /* Warn if `\{` is not preceded by `$`. If preceded by `$`, escaping + /* + * Warn if `\{` is not preceded by `$`. If preceded by `$`, escaping * is necessary and the rule should not warn. If preceded by `/$`, the rule * will warn for the `/$` instead, as it is the first unnecessarily escaped character. */ diff --git a/lib/rules/no-useless-return.js b/lib/rules/no-useless-return.js index 29f644cc43d..5415bf59b80 100644 --- a/lib/rules/no-useless-return.js +++ b/lib/rules/no-useless-return.js @@ -222,10 +222,12 @@ module.exports = { fix(fixer) { if (isRemovable(node)) { - // Extend the replacement range to include the - // entire function to avoid conflicting with - // no-else-return. - // https://github.com/eslint/eslint/issues/8026 + /* + * Extend the replacement range to include the + * entire function to avoid conflicting with + * no-else-return. + * https://github.com/eslint/eslint/issues/8026 + */ return new FixTracker(fixer, context.getSourceCode()) .retainEnclosingFunction(node) .remove(node); @@ -238,8 +240,10 @@ module.exports = { scopeInfo = scopeInfo.upper; }, - // Initializes segments. - // NOTE: This event is notified for only reachable segments. + /* + * Initializes segments. + * NOTE: This event is notified for only reachable segments. + */ onCodePathSegmentStart(segment) { const info = { uselessReturns: getUselessReturns([], segment.allPrevSegments), @@ -270,8 +274,10 @@ module.exports = { scopeInfo.uselessReturns.push(node); }, - // Registers for all statement nodes except FunctionDeclaration, BlockStatement, BreakStatement. - // Removes return statements of the current segments from the useless return statement list. + /* + * Registers for all statement nodes except FunctionDeclaration, BlockStatement, BreakStatement. + * Removes return statements of the current segments from the useless return statement list. + */ ClassDeclaration: markReturnStatementsOnCurrentSegmentsAsUsed, ContinueStatement: markReturnStatementsOnCurrentSegmentsAsUsed, DebuggerStatement: markReturnStatementsOnCurrentSegmentsAsUsed, diff --git a/lib/rules/no-whitespace-before-property.js b/lib/rules/no-whitespace-before-property.js index 71db50c4395..2d476b66c0a 100644 --- a/lib/rules/no-whitespace-before-property.js +++ b/lib/rules/no-whitespace-before-property.js @@ -53,8 +53,10 @@ module.exports = { fix(fixer) { if (!node.computed && astUtils.isDecimalInteger(node.object)) { - // If the object is a number literal, fixing it to something like 5.toString() would cause a SyntaxError. - // Don't fix this case. + /* + * If the object is a number literal, fixing it to something like 5.toString() would cause a SyntaxError. + * Don't fix this case. + */ return null; } return fixer.replaceTextRange([leftToken.range[1], rightToken.range[0]], replacementText); diff --git a/lib/rules/object-curly-spacing.js b/lib/rules/object-curly-spacing.js index c1d83c73df4..3341e915f24 100644 --- a/lib/rules/object-curly-spacing.js +++ b/lib/rules/object-curly-spacing.js @@ -65,11 +65,11 @@ module.exports = { //-------------------------------------------------------------------------- /** - * Reports that there shouldn't be a space after the first token - * @param {ASTNode} node - The node to report in the event of an error. - * @param {Token} token - The token to use for the report. - * @returns {void} - */ + * Reports that there shouldn't be a space after the first token + * @param {ASTNode} node - The node to report in the event of an error. + * @param {Token} token - The token to use for the report. + * @returns {void} + */ function reportNoBeginningSpace(node, token) { context.report({ node, @@ -87,11 +87,11 @@ module.exports = { } /** - * Reports that there shouldn't be a space before the last token - * @param {ASTNode} node - The node to report in the event of an error. - * @param {Token} token - The token to use for the report. - * @returns {void} - */ + * Reports that there shouldn't be a space before the last token + * @param {ASTNode} node - The node to report in the event of an error. + * @param {Token} token - The token to use for the report. + * @returns {void} + */ function reportNoEndingSpace(node, token) { context.report({ node, @@ -109,11 +109,11 @@ module.exports = { } /** - * Reports that there should be a space after the first token - * @param {ASTNode} node - The node to report in the event of an error. - * @param {Token} token - The token to use for the report. - * @returns {void} - */ + * Reports that there should be a space after the first token + * @param {ASTNode} node - The node to report in the event of an error. + * @param {Token} token - The token to use for the report. + * @returns {void} + */ function reportRequiredBeginningSpace(node, token) { context.report({ node, @@ -129,11 +129,11 @@ module.exports = { } /** - * Reports that there should be a space before the last token - * @param {ASTNode} node - The node to report in the event of an error. - * @param {Token} token - The token to use for the report. - * @returns {void} - */ + * Reports that there should be a space before the last token + * @param {ASTNode} node - The node to report in the event of an error. + * @param {Token} token - The token to use for the report. + * @returns {void} + */ function reportRequiredEndingSpace(node, token) { context.report({ node, diff --git a/lib/rules/object-shorthand.js b/lib/rules/object-shorthand.js index dfd8d1a64e0..980d0fc35a5 100644 --- a/lib/rules/object-shorthand.js +++ b/lib/rules/object-shorthand.js @@ -127,16 +127,17 @@ module.exports = { * @param {ASTNode} property Property AST node * @returns {boolean} True if the property can have a shorthand form * @private - **/ + * + */ function canHaveShorthand(property) { return (property.kind !== "set" && property.kind !== "get" && property.type !== "SpreadProperty" && property.type !== "ExperimentalSpreadProperty"); } /** - * Checks whether a node is a string literal. - * @param {ASTNode} node - Any AST node. - * @returns {boolean} `true` if it is a string literal. - */ + * Checks whether a node is a string literal. + * @param {ASTNode} node - Any AST node. + * @returns {boolean} `true` if it is a string literal. + */ function isStringLiteral(node) { return node.type === "Literal" && typeof node.value === "string"; } @@ -146,7 +147,8 @@ module.exports = { * @param {ASTNode} property Property AST node * @returns {boolean} True if the property is considered shorthand, false if not. * @private - **/ + * + */ function isShorthand(property) { // property.method is true when `{a(){}}`. @@ -158,7 +160,8 @@ module.exports = { * @param {ASTNode} property Property AST node * @returns {boolean} True if the key and value are named equally, false if not. * @private - **/ + * + */ function isRedundant(property) { const value = property.value; @@ -177,7 +180,8 @@ module.exports = { * @param {ASTNode} node Property AST node * @param {boolean} checkRedundancy Whether to check longform redundancy * @returns {void} - **/ + * + */ function checkConsistency(node, checkRedundancy) { // We are excluding getters/setters and spread properties as they are considered neither longform nor shorthand. @@ -187,8 +191,10 @@ module.exports = { if (properties.length > 0) { const shorthandProperties = properties.filter(isShorthand); - // If we do not have an equal number of longform properties as - // shorthand properties, we are using the annotations inconsistently + /* + * If we do not have an equal number of longform properties as + * shorthand properties, we are using the annotations inconsistently + */ if (shorthandProperties.length !== properties.length) { // We have at least 1 shorthand property @@ -196,8 +202,10 @@ module.exports = { context.report({ node, message: "Unexpected mix of shorthand and non-shorthand properties." }); } else if (checkRedundancy) { - // If all properties of the object contain a method or value with a name matching it's key, - // all the keys are redundant. + /* + * If all properties of the object contain a method or value with a name matching it's key, + * all the keys are redundant. + */ const canAlwaysUseShorthand = properties.every(isRedundant); if (canAlwaysUseShorthand) { @@ -209,11 +217,11 @@ module.exports = { } /** - * Fixes a FunctionExpression node by making it into a shorthand property. - * @param {SourceCodeFixer} fixer The fixer object - * @param {ASTNode} node A `Property` node that has a `FunctionExpression` or `ArrowFunctionExpression` as its value - * @returns {Object} A fix for this node - */ + * Fixes a FunctionExpression node by making it into a shorthand property. + * @param {SourceCodeFixer} fixer The fixer object + * @param {ASTNode} node A `Property` node that has a `FunctionExpression` or `ArrowFunctionExpression` as its value + * @returns {Object} A fix for this node + */ function makeFunctionShorthand(fixer, node) { const firstKeyToken = node.computed ? sourceCode.getFirstToken(node, astUtils.isOpeningBracketToken) @@ -253,11 +261,11 @@ module.exports = { } /** - * Fixes a FunctionExpression node by making it into a longform property. - * @param {SourceCodeFixer} fixer The fixer object - * @param {ASTNode} node A `Property` node that has a `FunctionExpression` as its value - * @returns {Object} A fix for this node - */ + * Fixes a FunctionExpression node by making it into a longform property. + * @param {SourceCodeFixer} fixer The fixer object + * @param {ASTNode} node A `Property` node that has a `FunctionExpression` as its value + * @returns {Object} A fix for this node + */ function makeFunctionLongform(fixer, node) { const firstKeyToken = node.computed ? sourceCode.getTokens(node).find(token => token.value === "[") : sourceCode.getFirstToken(node.key); const lastKeyToken = node.computed ? sourceCode.getTokensBetween(node.key, node.value).find(token => token.value === "]") : sourceCode.getLastToken(node.key); @@ -288,10 +296,10 @@ module.exports = { const argumentsIdentifiers = new WeakSet(); /** - * Enters a function. This creates a new lexical identifier scope, so a new Set of arrow functions is pushed onto the stack. - * Also, this marks all `arguments` identifiers so that they can be detected later. - * @returns {void} - */ + * Enters a function. This creates a new lexical identifier scope, so a new Set of arrow functions is pushed onto the stack. + * Also, this marks all `arguments` identifiers so that they can be detected later. + * @returns {void} + */ function enterFunction() { lexicalScopeStack.unshift(new Set()); context.getScope().variables.filter(variable => variable.name === "arguments").forEach(variable => { @@ -300,18 +308,18 @@ module.exports = { } /** - * Exits a function. This pops the current set of arrow functions off the lexical scope stack. - * @returns {void} - */ + * Exits a function. This pops the current set of arrow functions off the lexical scope stack. + * @returns {void} + */ function exitFunction() { lexicalScopeStack.shift(); } /** - * Marks the current function as having a lexical keyword. This implies that all arrow functions - * in the current lexical scope contain a reference to this lexical keyword. - * @returns {void} - */ + * Marks the current function as having a lexical keyword. This implies that all arrow functions + * in the current lexical scope contain a reference to this lexical keyword. + * @returns {void} + */ function reportLexicalIdentifier() { lexicalScopeStack[0].forEach(arrowFunction => arrowsWithLexicalIdentifiers.add(arrowFunction)); } diff --git a/lib/rules/operator-assignment.js b/lib/rules/operator-assignment.js index 99cca356f27..f776609f5e3 100644 --- a/lib/rules/operator-assignment.js +++ b/lib/rules/operator-assignment.js @@ -77,11 +77,11 @@ function same(a, b) { } /** -* Determines if the left side of a node can be safely fixed (i.e. if it activates the same getters/setters and) -* toString calls regardless of whether assignment shorthand is used) -* @param {ASTNode} node The node on the left side of the expression -* @returns {boolean} `true` if the node can be fixed -*/ + * Determines if the left side of a node can be safely fixed (i.e. if it activates the same getters/setters and) + * toString calls regardless of whether assignment shorthand is used) + * @param {ASTNode} node The node on the left side of the expression + * @returns {boolean} `true` if the node can be fixed + */ function canBeFixed(node) { return node.type === "Identifier" || node.type === "MemberExpression" && node.object.type === "Identifier" && (!node.computed || node.property.type === "Literal"); @@ -109,10 +109,10 @@ module.exports = { const sourceCode = context.getSourceCode(); /** - * Returns the operator token of an AssignmentExpression or BinaryExpression - * @param {ASTNode} node An AssignmentExpression or BinaryExpression node - * @returns {Token} The operator token in the node - */ + * Returns the operator token of an AssignmentExpression or BinaryExpression + * @param {ASTNode} node An AssignmentExpression or BinaryExpression node + * @returns {Token} The operator token in the node + */ function getOperatorToken(node) { return sourceCode.getFirstTokenBetween(node.left, node.right, token => token.value === node.operator); } diff --git a/lib/rules/operator-linebreak.js b/lib/rules/operator-linebreak.js index 809da1fc8c5..271cbb35c1d 100644 --- a/lib/rules/operator-linebreak.js +++ b/lib/rules/operator-linebreak.js @@ -69,11 +69,11 @@ module.exports = { //-------------------------------------------------------------------------- /** - * Gets a fixer function to fix rule issues - * @param {Token} operatorToken The operator token of an expression - * @param {string} desiredStyle The style for the rule. One of 'before', 'after', 'none' - * @returns {Function} A fixer function - */ + * Gets a fixer function to fix rule issues + * @param {Token} operatorToken The operator token of an expression + * @param {string} desiredStyle The style for the rule. One of 'before', 'after', 'none' + * @returns {Function} A fixer function + */ function getFixer(operatorToken, desiredStyle) { return fixer => { const tokenBefore = sourceCode.getTokenBefore(operatorToken); @@ -135,11 +135,13 @@ module.exports = { */ function validateNode(node, leftSide) { - // When the left part of a binary expression is a single expression wrapped in - // parentheses (ex: `(a) + b`), leftToken will be the last token of the expression - // and operatorToken will be the closing parenthesis. - // The leftToken should be the last closing parenthesis, and the operatorToken - // should be the token right after that. + /* + * When the left part of a binary expression is a single expression wrapped in + * parentheses (ex: `(a) + b`), leftToken will be the last token of the expression + * and operatorToken will be the closing parenthesis. + * The leftToken should be the last closing parenthesis, and the operatorToken + * should be the token right after that. + */ const operatorToken = sourceCode.getTokenAfter(leftSide, astUtils.isNotClosingParenToken); const leftToken = sourceCode.getTokenBefore(operatorToken); const rightToken = sourceCode.getTokenAfter(operatorToken); diff --git a/lib/rules/padding-line-between-statements.js b/lib/rules/padding-line-between-statements.js index bc6b26ee957..a89c49decf5 100644 --- a/lib/rules/padding-line-between-statements.js +++ b/lib/rules/padding-line-between-statements.js @@ -85,8 +85,10 @@ function isBlockLikeStatement(sourceCode, node) { return true; } - // IIFE is a block-like statement specially from - // JSCS#disallowPaddingNewLinesAfterBlocks. + /* + * IIFE is a block-like statement specially from + * JSCS#disallowPaddingNewLinesAfterBlocks. + */ if (isIIFEStatement(node)) { return true; } diff --git a/lib/rules/prefer-arrow-callback.js b/lib/rules/prefer-arrow-callback.js index 7565e445f83..31ae2859fea 100644 --- a/lib/rules/prefer-arrow-callback.js +++ b/lib/rules/prefer-arrow-callback.js @@ -115,12 +115,12 @@ function getCallbackInfo(node) { } /** -* Checks whether a simple list of parameters contains any duplicates. This does not handle complex -parameter lists (e.g. with destructuring), since complex parameter lists are a SyntaxError with duplicate -parameter names anyway. Instead, it always returns `false` for complex parameter lists. -* @param {ASTNode[]} paramsList The list of parameters for a function -* @returns {boolean} `true` if the list of parameters contains any duplicates -*/ + * Checks whether a simple list of parameters contains any duplicates. This does not handle complex + * parameter lists (e.g. with destructuring), since complex parameter lists are a SyntaxError with duplicate + * parameter names anyway. Instead, it always returns `false` for complex parameter lists. + * @param {ASTNode[]} paramsList The list of parameters for a function + * @returns {boolean} `true` if the list of parameters contains any duplicates + */ function hasDuplicateParams(paramsList) { return paramsList.every(param => param.type === "Identifier") && paramsList.length !== new Set(paramsList.map(param => param.name)).size; } @@ -265,10 +265,12 @@ module.exports = { fix(fixer) { if ((!callbackInfo.isLexicalThis && scopeInfo.this) || hasDuplicateParams(node.params)) { - // If the callback function does not have .bind(this) and contains a reference to `this`, there - // is no way to determine what `this` should be, so don't perform any fixes. - // If the callback function has duplicates in its list of parameters (possible in sloppy mode), - // don't replace it with an arrow function, because this is a SyntaxError with arrow functions. + /* + * If the callback function does not have .bind(this) and contains a reference to `this`, there + * is no way to determine what `this` should be, so don't perform any fixes. + * If the callback function has duplicates in its list of parameters (possible in sloppy mode), + * don't replace it with an arrow function, because this is a SyntaxError with arrow functions. + */ return null; } diff --git a/lib/rules/prefer-const.js b/lib/rules/prefer-const.js index 1395e0a8a08..a8cf3b7ef61 100644 --- a/lib/rules/prefer-const.js +++ b/lib/rules/prefer-const.js @@ -112,8 +112,10 @@ function getIdentifierIfShouldBeConst(variable, ignoreReadBeforeAssign) { } } - // If the assignment is from a different scope, ignore it. - // If the assignment cannot change to a declaration, ignore it. + /* + * If the assignment is from a different scope, ignore it. + * If the assignment cannot change to a declaration, ignore it. + */ const shouldBeConst = ( writer !== null && writer.from === variable.scope && @@ -179,8 +181,10 @@ function groupByDestructuring(variables, ignoreReadBeforeAssign) { const reference = references[j]; const id = reference.identifier; - // Avoid counting a reference twice or more for default values of - // destructuring. + /* + * Avoid counting a reference twice or more for default values of + * destructuring. + */ if (id === prevId) { continue; } @@ -274,17 +278,21 @@ module.exports = { const varDeclParent = findUp(nodes[0], "VariableDeclaration", parentNode => parentNode.type.endsWith("Statement")); const shouldFix = varDeclParent && - // If there are multiple variable declarations, like {let a = 1, b = 2}, then - // do not attempt to fix if one of the declarations should be `const`. It's - // too hard to know how the developer would want to automatically resolve the issue. + /* + * If there are multiple variable declarations, like {let a = 1, b = 2}, then + * do not attempt to fix if one of the declarations should be `const`. It's + * too hard to know how the developer would want to automatically resolve the issue. + */ varDeclParent.declarations.length === 1 && // Don't do a fix unless the variable is initialized (or it's in a for-in or for-of loop) (varDeclParent.parent.type === "ForInStatement" || varDeclParent.parent.type === "ForOfStatement" || varDeclParent.declarations[0].init) && - // If options.destucturing is "all", then this warning will not occur unless - // every assignment in the destructuring should be const. In that case, it's safe - // to apply the fix. + /* + * If options.destucturing is "all", then this warning will not occur unless + * every assignment in the destructuring should be const. In that case, it's safe + * to apply the fix. + */ nodesToReport.length === nodes.length; nodesToReport.forEach(node => { diff --git a/lib/rules/prefer-destructuring.js b/lib/rules/prefer-destructuring.js index ebf4e713b3b..eeb5e060ca0 100644 --- a/lib/rules/prefer-destructuring.js +++ b/lib/rules/prefer-destructuring.js @@ -18,8 +18,10 @@ module.exports = { schema: [ { - // old support {array: Boolean, object: Boolean} - // new support {VariableDeclarator: {}, AssignmentExpression: {}} + /* + * old support {array: Boolean, object: Boolean} + * new support {VariableDeclarator: {}, AssignmentExpression: {}} + */ oneOf: [ { type: "object", diff --git a/lib/rules/prefer-numeric-literals.js b/lib/rules/prefer-numeric-literals.js index 08deedd624d..929e660c665 100644 --- a/lib/rules/prefer-numeric-literals.js +++ b/lib/rules/prefer-numeric-literals.js @@ -96,8 +96,10 @@ module.exports = { if (+(newPrefix + node.arguments[0].value) !== parseInt(node.arguments[0].value, node.arguments[1].value)) { - // If the newly-produced literal would be invalid, (e.g. 0b1234), - // or it would yield an incorrect parseInt result for some other reason, don't make a fix. + /* + * If the newly-produced literal would be invalid, (e.g. 0b1234), + * or it would yield an incorrect parseInt result for some other reason, don't make a fix. + */ return null; } return fixer.replaceText(node, prefixMap[node.arguments[1].value] + node.arguments[0].value); diff --git a/lib/rules/prefer-promise-reject-errors.js b/lib/rules/prefer-promise-reject-errors.js index 97223a65a82..d2a6b5df102 100644 --- a/lib/rules/prefer-promise-reject-errors.js +++ b/lib/rules/prefer-promise-reject-errors.js @@ -38,10 +38,10 @@ module.exports = { //---------------------------------------------------------------------- /** - * Checks the argument of a reject() or Promise.reject() CallExpression, and reports it if it can't be an Error - * @param {ASTNode} callExpression A CallExpression node which is used to reject a Promise - * @returns {void} - */ + * Checks the argument of a reject() or Promise.reject() CallExpression, and reports it if it can't be an Error + * @param {ASTNode} callExpression A CallExpression node which is used to reject a Promise + * @returns {void} + */ function checkRejectCall(callExpression) { if (!callExpression.arguments.length && ALLOW_EMPTY_REJECT) { return; @@ -59,10 +59,10 @@ module.exports = { } /** - * Determines whether a function call is a Promise.reject() call - * @param {ASTNode} node A CallExpression node - * @returns {boolean} `true` if the call is a Promise.reject() call - */ + * Determines whether a function call is a Promise.reject() call + * @param {ASTNode} node A CallExpression node + * @returns {boolean} `true` if the call is a Promise.reject() call + */ function isPromiseRejectCall(node) { return node.callee.type === "MemberExpression" && node.callee.object.type === "Identifier" && node.callee.object.name === "Promise" && @@ -96,14 +96,14 @@ module.exports = { context.getDeclaredVariables(node.arguments[0]) /* - * Find the first variable that matches the second parameter's name. - * If the first parameter has the same name as the second parameter, then the variable will actually - * be "declared" when the first parameter is evaluated, but then it will be immediately overwritten - * by the second parameter. It's not possible for an expression with the variable to be evaluated before - * the variable is overwritten, because functions with duplicate parameters cannot have destructuring or - * default assignments in their parameter lists. Therefore, it's not necessary to explicitly account for - * this case. - */ + * Find the first variable that matches the second parameter's name. + * If the first parameter has the same name as the second parameter, then the variable will actually + * be "declared" when the first parameter is evaluated, but then it will be immediately overwritten + * by the second parameter. It's not possible for an expression with the variable to be evaluated before + * the variable is overwritten, because functions with duplicate parameters cannot have destructuring or + * default assignments in their parameter lists. Therefore, it's not necessary to explicitly account for + * this case. + */ .find(variable => variable.name === node.arguments[0].params[1].name) // Get the references to that variable. diff --git a/lib/rules/prefer-rest-params.js b/lib/rules/prefer-rest-params.js index d55d5dad02a..03342371b2b 100644 --- a/lib/rules/prefer-rest-params.js +++ b/lib/rules/prefer-rest-params.js @@ -22,8 +22,10 @@ function getVariableOfArguments(scope) { if (variable.name === "arguments") { - // If there was a parameter which is named "arguments", the implicit "arguments" is not defined. - // So does fast return with null. + /* + * If there was a parameter which is named "arguments", the implicit "arguments" is not defined. + * So does fast return with null. + */ return (variable.identifiers.length === 0) ? variable : null; } } diff --git a/lib/rules/prefer-template.js b/lib/rules/prefer-template.js index 9dc05e8be24..076ce6a3ea8 100644 --- a/lib/rules/prefer-template.js +++ b/lib/rules/prefer-template.js @@ -37,10 +37,10 @@ function getTopConcatBinaryExpression(node) { } /** -* Checks whether or not a given binary expression has string literals. -* @param {ASTNode} node - A node to check. -* @returns {boolean} `true` if the node has string literals. -*/ + * Checks whether or not a given binary expression has string literals. + * @param {ASTNode} node - A node to check. + * @returns {boolean} `true` if the node has string literals. + */ function hasStringLiteral(node) { if (isConcatenation(node)) { @@ -65,10 +65,10 @@ function hasNonStringLiteral(node) { } /** -* Determines whether a given node will start with a template curly expression (`${}`) when being converted to a template literal. -* @param {ASTNode} node The node that will be fixed to a template literal -* @returns {boolean} `true` if the node will start with a template curly. -*/ + * Determines whether a given node will start with a template curly expression (`${}`) when being converted to a template literal. + * @param {ASTNode} node The node that will be fixed to a template literal + * @returns {boolean} `true` if the node will start with a template curly. + */ function startsWithTemplateCurly(node) { if (node.type === "BinaryExpression") { return startsWithTemplateCurly(node.left); @@ -80,10 +80,10 @@ function startsWithTemplateCurly(node) { } /** -* Determines whether a given node end with a template curly expression (`${}`) when being converted to a template literal. -* @param {ASTNode} node The node that will be fixed to a template literal -* @returns {boolean} `true` if the node will end with a template curly. -*/ + * Determines whether a given node end with a template curly expression (`${}`) when being converted to a template literal. + * @param {ASTNode} node The node that will be fixed to a template literal + * @returns {boolean} `true` if the node will end with a template curly. + */ function endsWithTemplateCurly(node) { if (node.type === "BinaryExpression") { return startsWithTemplateCurly(node.right); @@ -116,11 +116,11 @@ module.exports = { let done = Object.create(null); /** - * Gets the non-token text between two nodes, ignoring any other tokens that appear between the two tokens. - * @param {ASTNode} node1 The first node - * @param {ASTNode} node2 The second node - * @returns {string} The text between the nodes, excluding other tokens - */ + * Gets the non-token text between two nodes, ignoring any other tokens that appear between the two tokens. + * @param {ASTNode} node1 The first node + * @param {ASTNode} node2 The second node + * @returns {string} The text between the nodes, excluding other tokens + */ function getTextBetween(node1, node2) { const allTokens = [node1].concat(sourceCode.getTokensBetween(node1, node2)).concat(node2); const sourceText = sourceCode.getText(); @@ -129,19 +129,21 @@ module.exports = { } /** - * Returns a template literal form of the given node. - * @param {ASTNode} currentNode A node that should be converted to a template literal - * @param {string} textBeforeNode Text that should appear before the node - * @param {string} textAfterNode Text that should appear after the node - * @returns {string} A string form of this node, represented as a template literal - */ + * Returns a template literal form of the given node. + * @param {ASTNode} currentNode A node that should be converted to a template literal + * @param {string} textBeforeNode Text that should appear before the node + * @param {string} textAfterNode Text that should appear after the node + * @returns {string} A string form of this node, represented as a template literal + */ function getTemplateLiteral(currentNode, textBeforeNode, textAfterNode) { if (currentNode.type === "Literal" && typeof currentNode.value === "string") { - // If the current node is a string literal, escape any instances of ${ or ` to prevent them from being interpreted - // as a template placeholder. However, if the code already contains a backslash before the ${ or ` - // for some reason, don't add another backslash, because that would change the meaning of the code (it would cause - // an actual backslash character to appear before the dollar sign). + /* + * If the current node is a string literal, escape any instances of ${ or ` to prevent them from being interpreted + * as a template placeholder. However, if the code already contains a backslash before the ${ or ` + * for some reason, don't add another backslash, because that would change the meaning of the code (it would cause + * an actual backslash character to appear before the dollar sign). + */ return `\`${currentNode.raw.slice(1, -1).replace(/\\*(\${|`)/g, matched => { if (matched.lastIndexOf("\\") % 2) { return `\\${matched}`; @@ -178,8 +180,10 @@ module.exports = { getTemplateLiteral(currentNode.right, textBeforePlus + textAfterPlus, textAfterNode).slice(1); } - // Otherwise, these nodes should not be combined into a template curly, since there is nowhere to put - // the text between them. + /* + * Otherwise, these nodes should not be combined into a template curly, since there is nowhere to put + * the text between them. + */ return `${getTemplateLiteral(currentNode.left, textBeforeNode, null)}${textBeforePlus}+${textAfterPlus}${getTemplateLiteral(currentNode.right, textAfterNode, null)}`; } diff --git a/lib/rules/quote-props.js b/lib/rules/quote-props.js index 305a1b41b6d..6ac1f3c138f 100644 --- a/lib/rules/quote-props.js +++ b/lib/rules/quote-props.js @@ -104,19 +104,19 @@ module.exports = { } /** - * Returns a string representation of a property node with quotes removed - * @param {ASTNode} key Key AST Node, which may or may not be quoted - * @returns {string} A replacement string for this property - */ + * Returns a string representation of a property node with quotes removed + * @param {ASTNode} key Key AST Node, which may or may not be quoted + * @returns {string} A replacement string for this property + */ function getUnquotedKey(key) { return key.type === "Identifier" ? key.name : key.value; } /** - * Returns a string representation of a property node with quotes added - * @param {ASTNode} key Key AST Node, which may or may not be quoted - * @returns {string} A replacement string for this property - */ + * Returns a string representation of a property node with quotes added + * @param {ASTNode} key Key AST Node, which may or may not be quoted + * @returns {string} A replacement string for this property + */ function getQuotedKey(key) { if (key.type === "Literal" && typeof key.value === "string") { diff --git a/lib/rules/semi.js b/lib/rules/semi.js index 0bfdff110f2..b5e058ba3c7 100644 --- a/lib/rules/semi.js +++ b/lib/rules/semi.js @@ -93,9 +93,11 @@ module.exports = { loc = loc.start; fix = function(fixer) { - // Expand the replacement range to include the surrounding - // tokens to avoid conflicting with no-extra-semi. - // https://github.com/eslint/eslint/issues/7928 + /* + * Expand the replacement range to include the surrounding + * tokens to avoid conflicting with no-extra-semi. + * https://github.com/eslint/eslint/issues/7928 + */ return new FixTracker(fixer, sourceCode) .retainSurroundingTokens(lastToken) .remove(lastToken); diff --git a/lib/rules/sort-imports.js b/lib/rules/sort-imports.js index be1605dc47f..2bd415e9746 100644 --- a/lib/rules/sort-imports.js +++ b/lib/rules/sort-imports.js @@ -113,9 +113,11 @@ module.exports = { currentLocalMemberName = currentLocalMemberName && currentLocalMemberName.toLowerCase(); } - // When the current declaration uses a different member syntax, - // then check if the ordering is correct. - // Otherwise, make a default string compare (like rule sort-vars to be consistent) of the first used local member name. + /* + * When the current declaration uses a different member syntax, + * then check if the ordering is correct. + * Otherwise, make a default string compare (like rule sort-vars to be consistent) of the first used local member name. + */ if (currentMemberSyntaxGroupIndex !== previousMemberSyntaxGroupIndex) { if (currentMemberSyntaxGroupIndex < previousMemberSyntaxGroupIndex) { context.report({ diff --git a/lib/rules/space-unary-ops.js b/lib/rules/space-unary-ops.js index fadaff74b02..06a70fb6ade 100644 --- a/lib/rules/space-unary-ops.js +++ b/lib/rules/space-unary-ops.js @@ -56,50 +56,50 @@ module.exports = { //-------------------------------------------------------------------------- /** - * Check if the node is the first "!" in a "!!" convert to Boolean expression - * @param {ASTnode} node AST node - * @returns {boolean} Whether or not the node is first "!" in "!!" - */ + * Check if the node is the first "!" in a "!!" convert to Boolean expression + * @param {ASTnode} node AST node + * @returns {boolean} Whether or not the node is first "!" in "!!" + */ function isFirstBangInBangBangExpression(node) { return node && node.type === "UnaryExpression" && node.argument.operator === "!" && node.argument && node.argument.type === "UnaryExpression" && node.argument.operator === "!"; } /** - * Check if the node's child argument is an "ObjectExpression" - * @param {ASTnode} node AST node - * @returns {boolean} Whether or not the argument's type is "ObjectExpression" - */ + * Check if the node's child argument is an "ObjectExpression" + * @param {ASTnode} node AST node + * @returns {boolean} Whether or not the argument's type is "ObjectExpression" + */ function isArgumentObjectExpression(node) { return node.argument && node.argument.type && node.argument.type === "ObjectExpression"; } /** - * Checks if an override exists for a given operator. - * @param {string} operator Operator - * @returns {boolean} Whether or not an override has been provided for the operator - */ + * Checks if an override exists for a given operator. + * @param {string} operator Operator + * @returns {boolean} Whether or not an override has been provided for the operator + */ function overrideExistsForOperator(operator) { return options.overrides && options.overrides.hasOwnProperty(operator); } /** - * Gets the value that the override was set to for this operator - * @param {string} operator Operator - * @returns {boolean} Whether or not an override enforces a space with this operator - */ + * Gets the value that the override was set to for this operator + * @param {string} operator Operator + * @returns {boolean} Whether or not an override enforces a space with this operator + */ function overrideEnforcesSpaces(operator) { return options.overrides[operator]; } /** - * Verify Unary Word Operator has spaces after the word operator - * @param {ASTnode} node AST node - * @param {Object} firstToken first token from the AST node - * @param {Object} secondToken second token from the AST node - * @param {string} word The word to be used for reporting - * @returns {void} - */ + * Verify Unary Word Operator has spaces after the word operator + * @param {ASTnode} node AST node + * @param {Object} firstToken first token from the AST node + * @param {Object} secondToken second token from the AST node + * @param {string} word The word to be used for reporting + * @returns {void} + */ function verifyWordHasSpaces(node, firstToken, secondToken, word) { if (secondToken.range[0] === firstToken.range[1]) { context.report({ @@ -116,13 +116,13 @@ module.exports = { } /** - * Verify Unary Word Operator doesn't have spaces after the word operator - * @param {ASTnode} node AST node - * @param {Object} firstToken first token from the AST node - * @param {Object} secondToken second token from the AST node - * @param {string} word The word to be used for reporting - * @returns {void} - */ + * Verify Unary Word Operator doesn't have spaces after the word operator + * @param {ASTnode} node AST node + * @param {Object} firstToken first token from the AST node + * @param {Object} secondToken second token from the AST node + * @param {string} word The word to be used for reporting + * @returns {void} + */ function verifyWordDoesntHaveSpaces(node, firstToken, secondToken, word) { if (isArgumentObjectExpression(node)) { if (secondToken.range[0] > firstToken.range[1]) { @@ -141,13 +141,13 @@ module.exports = { } /** - * Check Unary Word Operators for spaces after the word operator - * @param {ASTnode} node AST node - * @param {Object} firstToken first token from the AST node - * @param {Object} secondToken second token from the AST node - * @param {string} word The word to be used for reporting - * @returns {void} - */ + * Check Unary Word Operators for spaces after the word operator + * @param {ASTnode} node AST node + * @param {Object} firstToken first token from the AST node + * @param {Object} secondToken second token from the AST node + * @param {string} word The word to be used for reporting + * @returns {void} + */ function checkUnaryWordOperatorForSpaces(node, firstToken, secondToken, word) { word = word || firstToken.value; @@ -165,10 +165,10 @@ module.exports = { } /** - * Verifies YieldExpressions satisfy spacing requirements - * @param {ASTnode} node AST node - * @returns {void} - */ + * Verifies YieldExpressions satisfy spacing requirements + * @param {ASTnode} node AST node + * @returns {void} + */ function checkForSpacesAfterYield(node) { const tokens = sourceCode.getFirstTokens(node, 3), word = "yield"; @@ -181,10 +181,10 @@ module.exports = { } /** - * Verifies AwaitExpressions satisfy spacing requirements - * @param {ASTNode} node AwaitExpression AST node - * @returns {void} - */ + * Verifies AwaitExpressions satisfy spacing requirements + * @param {ASTNode} node AwaitExpression AST node + * @returns {void} + */ function checkForSpacesAfterAwait(node) { const tokens = sourceCode.getFirstTokens(node, 3); @@ -192,12 +192,12 @@ module.exports = { } /** - * Verifies UnaryExpression, UpdateExpression and NewExpression have spaces before or after the operator - * @param {ASTnode} node AST node - * @param {Object} firstToken First token in the expression - * @param {Object} secondToken Second token in the expression - * @returns {void} - */ + * Verifies UnaryExpression, UpdateExpression and NewExpression have spaces before or after the operator + * @param {ASTnode} node AST node + * @param {Object} firstToken First token in the expression + * @param {Object} secondToken Second token in the expression + * @returns {void} + */ function verifyNonWordsHaveSpaces(node, firstToken, secondToken) { if (node.prefix) { if (isFirstBangInBangBangExpression(node)) { @@ -232,12 +232,12 @@ module.exports = { } /** - * Verifies UnaryExpression, UpdateExpression and NewExpression don't have spaces before or after the operator - * @param {ASTnode} node AST node - * @param {Object} firstToken First token in the expression - * @param {Object} secondToken Second token in the expression - * @returns {void} - */ + * Verifies UnaryExpression, UpdateExpression and NewExpression don't have spaces before or after the operator + * @param {ASTnode} node AST node + * @param {Object} firstToken First token in the expression + * @param {Object} secondToken Second token in the expression + * @returns {void} + */ function verifyNonWordsDontHaveSpaces(node, firstToken, secondToken) { if (node.prefix) { if (secondToken.range[0] > firstToken.range[1]) { @@ -272,10 +272,10 @@ module.exports = { } /** - * Verifies UnaryExpression, UpdateExpression and NewExpression satisfy spacing requirements - * @param {ASTnode} node AST node - * @returns {void} - */ + * Verifies UnaryExpression, UpdateExpression and NewExpression satisfy spacing requirements + * @param {ASTnode} node AST node + * @returns {void} + */ function checkForSpaces(node) { const tokens = node.type === "UpdateExpression" && !node.prefix ? sourceCode.getLastTokens(node, 2) diff --git a/lib/rules/strict.js b/lib/rules/strict.js index bb926f66614..433b4713679 100644 --- a/lib/rules/strict.js +++ b/lib/rules/strict.js @@ -109,19 +109,19 @@ module.exports = { } /** - * Determines whether a reported error should be fixed, depending on the error type. - * @param {string} errorType The type of error - * @returns {boolean} `true` if the reported error should be fixed - */ + * Determines whether a reported error should be fixed, depending on the error type. + * @param {string} errorType The type of error + * @returns {boolean} `true` if the reported error should be fixed + */ function shouldFix(errorType) { return errorType === "multiple" || errorType === "unnecessary" || errorType === "module" || errorType === "implied" || errorType === "unnecessaryInClasses"; } /** - * Gets a fixer function to remove a given 'use strict' directive. - * @param {ASTNode} node The directive that should be removed - * @returns {Function} A fixer function - */ + * Gets a fixer function to remove a given 'use strict' directive. + * @param {ASTNode} node The directive that should be removed + * @returns {Function} A fixer function + */ function getFixFunction(node) { return fixer => fixer.remove(node); } diff --git a/lib/rules/valid-typeof.js b/lib/rules/valid-typeof.js index 94b407b600a..fba4cc5712a 100644 --- a/lib/rules/valid-typeof.js +++ b/lib/rules/valid-typeof.js @@ -37,10 +37,10 @@ module.exports = { const requireStringLiterals = context.options[0] && context.options[0].requireStringLiterals; /** - * Determines whether a node is a typeof expression. - * @param {ASTNode} node The node - * @returns {boolean} `true` if the node is a typeof expression - */ + * Determines whether a node is a typeof expression. + * @param {ASTNode} node The node + * @returns {boolean} `true` if the node is a typeof expression + */ function isTypeofExpression(node) { return node.type === "UnaryExpression" && node.operator === "typeof"; } diff --git a/lib/rules/wrap-iife.js b/lib/rules/wrap-iife.js index 59179eb17ed..c4e6a9e0c73 100644 --- a/lib/rules/wrap-iife.js +++ b/lib/rules/wrap-iife.js @@ -59,10 +59,10 @@ module.exports = { } /** - * Get the function node from an IIFE - * @param {ASTNode} node node to evaluate - * @returns {ASTNode} node that is the function expression of the given IIFE, or null if none exist - */ + * Get the function node from an IIFE + * @param {ASTNode} node node to evaluate + * @returns {ASTNode} node that is the function expression of the given IIFE, or null if none exist + */ function getFunctionNodeFromIIFE(node) { const callee = node.callee; diff --git a/lib/rules/yoda.js b/lib/rules/yoda.js index bdb7d2a4278..2ccb61f73a0 100644 --- a/lib/rules/yoda.js +++ b/lib/rules/yoda.js @@ -126,9 +126,11 @@ function same(a, b) { ); } - // x[0] = x[0] - // x[y] = x[y] - // x.y = x.y + /* + * x[0] = x[0] + * x[y] = x[y] + * x.y = x.y + */ return ( a.computed === b.computed && same(a.object, b.object) && @@ -259,10 +261,10 @@ module.exports = { }; /** - * Returns a string representation of a BinaryExpression node with its sides/operator flipped around. - * @param {ASTNode} node The BinaryExpression node - * @returns {string} A string representation of the node with the sides and operator flipped - */ + * Returns a string representation of a BinaryExpression node with its sides/operator flipped around. + * @param {ASTNode} node The BinaryExpression node + * @returns {string} A string representation of the node with the sides and operator flipped + */ function getFlippedString(node) { const operatorToken = sourceCode.getFirstTokenBetween(node.left, node.right, token => token.value === node.operator); const textBeforeOperator = sourceCode.getText().slice(sourceCode.getTokenBefore(operatorToken).range[1], operatorToken.range[0]); diff --git a/lib/testers/rule-tester.js b/lib/testers/rule-tester.js index a76a38c6550..9861998ff77 100644 --- a/lib/testers/rule-tester.js +++ b/lib/testers/rule-tester.js @@ -204,9 +204,11 @@ class RuleTester { } - // If people use `mocha test.js --watch` command, `describe` and `it` function - // instances are different for each execution. So `describe` and `it` should get fresh instance - // always. + /* + * If people use `mocha test.js --watch` command, `describe` and `it` function + * instances are different for each execution. So `describe` and `it` should get fresh instance + * always. + */ static get describe() { return ( this[DESCRIBE] || @@ -284,12 +286,16 @@ class RuleTester { } else { code = item.code; - // Assumes everything on the item is a config except for the - // parameters used by this tester + /* + * Assumes everything on the item is a config except for the + * parameters used by this tester + */ const itemConfig = lodash.omit(item, RuleTesterParameters); - // Create the config object from the tester config and this item - // specific configurations. + /* + * Create the config object from the tester config and this item + * specific configurations. + */ config = lodash.merge( config, itemConfig diff --git a/lib/token-store/backward-token-cursor.js b/lib/token-store/backward-token-cursor.js index caa117faeac..93973bce443 100644 --- a/lib/token-store/backward-token-cursor.js +++ b/lib/token-store/backward-token-cursor.js @@ -45,9 +45,11 @@ module.exports = class BackwardTokenCursor extends Cursor { return false; } - // - // Shorthand for performance. - // + /* + * + * Shorthand for performance. + * + */ /** @inheritdoc */ getOneToken() { diff --git a/lib/token-store/forward-token-cursor.js b/lib/token-store/forward-token-cursor.js index 5748cb45a62..523ed398fa3 100644 --- a/lib/token-store/forward-token-cursor.js +++ b/lib/token-store/forward-token-cursor.js @@ -45,9 +45,11 @@ module.exports = class ForwardTokenCursor extends Cursor { return false; } - // - // Shorthand for performance. - // + /* + * + * Shorthand for performance. + * + */ /** @inheritdoc */ getOneToken() { diff --git a/lib/token-store/utils.js b/lib/token-store/utils.js index f83b6cf6999..34b0a9af6da 100644 --- a/lib/token-store/utils.js +++ b/lib/token-store/utils.js @@ -62,8 +62,10 @@ exports.getFirstIndex = function getFirstIndex(tokens, indexMap, startLoc) { const index = indexMap[startLoc - 1]; const token = (index >= 0 && index < tokens.length) ? tokens[index] : null; - // For the map of "comment's location -> token's index", it points the next token of a comment. - // In that case, +1 is unnecessary. + /* + * For the map of "comment's location -> token's index", it points the next token of a comment. + * In that case, +1 is unnecessary. + */ if (token && token.range[0] >= startLoc) { return index; } @@ -89,8 +91,10 @@ exports.getLastIndex = function getLastIndex(tokens, indexMap, endLoc) { const index = indexMap[endLoc - 1]; const token = (index >= 0 && index < tokens.length) ? tokens[index] : null; - // For the map of "comment's location -> token's index", it points the next token of a comment. - // In that case, -1 is necessary. + /* + * For the map of "comment's location -> token's index", it points the next token of a comment. + * In that case, -1 is necessary. + */ if (token && token.range[1] > endLoc) { return index - 1; } diff --git a/lib/util/glob.js b/lib/util/glob.js index a231e16f4d0..f352dae7a4d 100644 --- a/lib/util/glob.js +++ b/lib/util/glob.js @@ -47,7 +47,7 @@ GlobSync.prototype._readdir = function(abs, inGlobStar) { * `options.nodir` makes `options.mark` as `true`. * Mark `abs` first * to make sure `"node_modules"` will be ignored immediately with ignore pattern `"node_modules/"`. - + * * There is a built-in cache about marked `File.Stat` in `glob`, so that we could not worry about the extra invocation of `this._mark()` */ const marked = this._mark(abs); diff --git a/lib/util/node-event-generator.js b/lib/util/node-event-generator.js index 34ee78b4941..9d477bbb4e6 100644 --- a/lib/util/node-event-generator.js +++ b/lib/util/node-event-generator.js @@ -33,10 +33,10 @@ const lodash = require("lodash"); //------------------------------------------------------------------------------ /** -* Gets the possible types of a selector -* @param {Object} parsedSelector An object (from esquery) describing the matching behavior of the selector -* @returns {string[]|null} The node types that could possibly trigger this selector, or `null` if all node types could trigger it -*/ + * Gets the possible types of a selector + * @param {Object} parsedSelector An object (from esquery) describing the matching behavior of the selector + * @returns {string[]|null} The node types that could possibly trigger this selector, or `null` if all node types could trigger it + */ function getPossibleTypes(parsedSelector) { switch (parsedSelector.type) { case "identifier": @@ -203,12 +203,12 @@ const parseSelector = lodash.memoize(rawSelector => { class NodeEventGenerator { /** - * @param {SafeEmitter} emitter - * An SafeEmitter which is the destination of events. This emitter must already - * have registered listeners for all of the events that it needs to listen for. - * (See lib/util/safe-emitter.js for more details on `SafeEmitter`.) - * @returns {NodeEventGenerator} new instance - */ + * @param {SafeEmitter} emitter + * An SafeEmitter which is the destination of events. This emitter must already + * have registered listeners for all of the events that it needs to listen for. + * (See lib/util/safe-emitter.js for more details on `SafeEmitter`.) + * @returns {NodeEventGenerator} new instance + */ constructor(emitter) { this.emitter = emitter; this.currentAncestry = []; diff --git a/lib/util/source-code-fixer.js b/lib/util/source-code-fixer.js index ebb7e3e02df..b5bfc7457a7 100644 --- a/lib/util/source-code-fixer.js +++ b/lib/util/source-code-fixer.js @@ -122,8 +122,10 @@ SourceCodeFixer.applyFixes = function(sourceText, messages, shouldFix) { if (typeof shouldFix !== "function" || shouldFix(problem)) { attemptFix(problem); - // The only time attemptFix will fail is if a previous fix was - // applied which conflicts with it. So we can mark this as true. + /* + * The only time attemptFix will fail is if a previous fix was + * applied which conflicts with it. So we can mark this as true. + */ fixesWereApplied = true; } else { remainingMessages.push(problem); diff --git a/lib/util/source-code.js b/lib/util/source-code.js index d3fed5989cb..0bd710bf67a 100644 --- a/lib/util/source-code.js +++ b/lib/util/source-code.js @@ -227,7 +227,8 @@ class SourceCode extends TokenStore { } } else { - /* Return comments as trailing comments of nodes that only contain + /* + * Return comments as trailing comments of nodes that only contain * comments (to mimic the comment attachment behavior present in Espree). */ if ((node.type === "BlockStatement" || node.type === "ClassBody") && node.body.length === 0 || diff --git a/package.json b/package.json index 509b9510730..46dc70e47c0 100644 --- a/package.json +++ b/package.json @@ -84,6 +84,7 @@ "coveralls": "^2.13.1", "dateformat": "^2.0.0", "ejs": "^2.5.6", + "eslint-rule-composer": "^0.1.0", "eslint-plugin-eslint-plugin": "^1.2.0", "eslint-plugin-node": "^5.1.0", "eslint-plugin-rulesdir": "^0.1.0", diff --git a/tests/bin/eslint.js b/tests/bin/eslint.js index 7d6bbaf69b0..7742eb71f16 100644 --- a/tests/bin/eslint.js +++ b/tests/bin/eslint.js @@ -11,20 +11,20 @@ const assert = require("chai").assert; const EXECUTABLE_PATH = require("path").resolve(`${__dirname}/../../bin/eslint.js`); /** -* Returns a Promise for when a child process exits -* @param {ChildProcess} exitingProcess The child process -* @returns {Promise} A Promise that fulfills with the exit code when the child process exits -*/ + * Returns a Promise for when a child process exits + * @param {ChildProcess} exitingProcess The child process + * @returns {Promise} A Promise that fulfills with the exit code when the child process exits + */ function awaitExit(exitingProcess) { return new Promise(resolve => exitingProcess.once("exit", resolve)); } /** -* Asserts that the exit code of a given child process will equal the given value. -* @param {ChildProcess} exitingProcess The child process -* @param {number} expectedExitCode The expected exit code of the child process -* @returns {Promise} A Promise that fufills if the exit code ends up matching, and rejects otherwise. -*/ + * Asserts that the exit code of a given child process will equal the given value. + * @param {ChildProcess} exitingProcess The child process + * @param {number} expectedExitCode The expected exit code of the child process + * @returns {Promise} A Promise that fufills if the exit code ends up matching, and rejects otherwise. + */ function assertExitCode(exitingProcess, expectedExitCode) { return awaitExit(exitingProcess).then(exitCode => { assert.strictEqual(exitCode, expectedExitCode, `Expected an exit code of ${expectedExitCode} but got ${exitCode}.`); @@ -32,11 +32,11 @@ function assertExitCode(exitingProcess, expectedExitCode) { } /** -* Returns a Promise for the stdout of a process. -* @param {ChildProcess} runningProcess The child process -* @returns {Promise<{stdout: string, stderr: string}>} A Promise that fulfills with all of the -* stdout and stderr output produced by the process when it exits. -*/ + * Returns a Promise for the stdout of a process. + * @param {ChildProcess} runningProcess The child process + * @returns {Promise<{stdout: string, stderr: string}>} A Promise that fulfills with all of the + * stdout and stderr output produced by the process when it exits. + */ function getOutput(runningProcess) { let stdout = ""; let stderr = ""; @@ -50,11 +50,11 @@ describe("bin/eslint.js", () => { const forkedProcesses = new Set(); /** - * Forks the process to run an instance of ESLint. - * @param {string[]} [args] An array of arguments - * @param {Object} [options] An object containing options for the resulting child process - * @returns {ChildProcess} The resulting child process - */ + * Forks the process to run an instance of ESLint. + * @param {string[]} [args] An array of arguments + * @param {Object} [options] An object containing options for the resulting child process + * @returns {ChildProcess} The resulting child process + */ function runESLint(args, options) { const newProcess = childProcess.fork(EXECUTABLE_PATH, args, Object.assign({ silent: true }, options)); diff --git a/tests/lib/ast-utils.js b/tests/lib/ast-utils.js index 994ef141a8e..65600f3532a 100644 --- a/tests/lib/ast-utils.js +++ b/tests/lib/ast-utils.js @@ -184,7 +184,8 @@ describe("ast-utils", () => { * Asserts the node is NOT a directive comment * @param {ASTNode} node node to assert * @returns {void} - * */ + * + */ function assertFalse(node) { assert.isFalse(astUtils.isDirectiveComment(node)); } @@ -193,7 +194,8 @@ describe("ast-utils", () => { * Asserts the node is a directive comment * @param {ASTNode} node node to assert * @returns {void} - * */ + * + */ function assertTrue(node) { assert.isTrue(astUtils.isDirectiveComment(node)); } diff --git a/tests/lib/cli-engine.js b/tests/lib/cli-engine.js index 7cc1c12dc10..81d00a96e62 100644 --- a/tests/lib/cli-engine.js +++ b/tests/lib/cli-engine.js @@ -1853,9 +1853,9 @@ describe("CLIEngine", () => { describe("when the cacheFile is a directory or looks like a directory", () => { /** - * helper method to delete the cache files created during testing - * @returns {void} - */ + * helper method to delete the cache files created during testing + * @returns {void} + */ function deleteCacheDir() { try { fs.unlinkSync("./tmp/.cacheFileDir/.cache_hashOfCurrentWorkingDirectory"); @@ -2166,8 +2166,10 @@ describe("CLIEngine", () => { // delete the file from the file system fs.unlinkSync(toBeDeletedFile); - // file-entry-cache@2.0.0 will remove from the cache deleted files - // even when they were not part of the array of files to be analyzed + /* + * file-entry-cache@2.0.0 will remove from the cache deleted files + * even when they were not part of the array of files to be analyzed + */ engine.executeOnFiles([badFile, goodFile]); cache = JSON.parse(fs.readFileSync(cacheFile)); @@ -2205,9 +2207,11 @@ describe("CLIEngine", () => { assert.isTrue(typeof cache[testFile2] === "object", "the entry for the test-file2 is in the cache"); - // we pass a different set of files minus test-file2 - // previous version of file-entry-cache would remove the non visited - // entries. 2.0.0 version will keep them unless they don't exist + /* + * we pass a different set of files minus test-file2 + * previous version of file-entry-cache would remove the non visited + * entries. 2.0.0 version will keep them unless they don't exist + */ engine.executeOnFiles([badFile, goodFile]); cache = JSON.parse(fs.readFileSync(cacheFile)); diff --git a/tests/lib/cli.js b/tests/lib/cli.js index 8a8bc938a0e..b50615f260e 100644 --- a/tests/lib/cli.js +++ b/tests/lib/cli.js @@ -5,8 +5,10 @@ "use strict"; -// NOTE: If you are adding new tests for cli.js, use verifyCLIEngineOpts(). The -// test only needs to verify that CLIEngine receives the correct opts. +/* + * NOTE: If you are adding new tests for cli.js, use verifyCLIEngineOpts(). The + * test only needs to verify that CLIEngine receives the correct opts. + */ //------------------------------------------------------------------------------ // Requirements diff --git a/tests/lib/code-path-analysis/code-path.js b/tests/lib/code-path-analysis/code-path.js index e4d73c0d598..6b90b57bf3c 100644 --- a/tests/lib/code-path-analysis/code-path.js +++ b/tests/lib/code-path-analysis/code-path.js @@ -66,6 +66,7 @@ function getOrderOfTraversing(codePath, options, callback) { describe("CodePathAnalyzer", () => { describe(".traverseSegments()", () => { describe("should traverse segments from the first to the end:", () => { + /* eslint-disable rulesdir/multiline-comment-style */ it("simple", () => { const codePath = parseCodePaths("foo(); bar(); baz();")[0]; const order = getOrderOfTraversing(codePath); @@ -301,5 +302,7 @@ describe("CodePathAnalyzer", () => { } */ }); + + /* eslint-enable rulesdir/multiline-comment-style */ }); }); diff --git a/tests/lib/config.js b/tests/lib/config.js index 570c05f9144..9b7458db150 100644 --- a/tests/lib/config.js +++ b/tests/lib/config.js @@ -386,9 +386,10 @@ describe("Config", () => { assert.strictEqual(config.parser, path.resolve(path.dirname(configPath), "./custom.js")); }); - // Configuration hierarchy --------------------------------------------- - - // https://github.com/eslint/eslint/issues/3915 + /* + * Configuration hierarchy --------------------------------------------- + * https://github.com/eslint/eslint/issues/3915 + */ it("should correctly merge environment settings", () => { const configHelper = new Config({ useEslintrc: true, cwd: process.cwd() }, linter), file = getFixturePath("envs", "sub", "foo.js"), diff --git a/tests/lib/formatters/stylish.js b/tests/lib/formatters/stylish.js index 5749c1c7d39..8137880167b 100644 --- a/tests/lib/formatters/stylish.js +++ b/tests/lib/formatters/stylish.js @@ -14,8 +14,10 @@ const assert = require("chai").assert, proxyquire = require("proxyquire"), sinon = require("sinon"); -// Chalk protects its methods so we need to inherit from it -// for Sinon to work. +/* + * Chalk protects its methods so we need to inherit from it + * for Sinon to work. + */ const chalkStub = Object.create(chalk, { yellow: { value(str) { diff --git a/tests/lib/linter.js b/tests/lib/linter.js index 85f9d6bf10c..891be8c14d9 100644 --- a/tests/lib/linter.js +++ b/tests/lib/linter.js @@ -3930,9 +3930,10 @@ describe("Linter", () => { it("should not rewrite env setting in core (https://github.com/eslint/eslint/issues/4814)", () => { - // This test focuses on the instance of https://github.com/eslint/eslint/blob/v2.0.0-alpha-2/conf/environments.js#L26-L28 - - // This `verify()` takes the instance and runs https://github.com/eslint/eslint/blob/v2.0.0-alpha-2/lib/eslint.js#L416 + /* + * This test focuses on the instance of https://github.com/eslint/eslint/blob/v2.0.0-alpha-2/conf/environments.js#L26-L28 + * This `verify()` takes the instance and runs https://github.com/eslint/eslint/blob/v2.0.0-alpha-2/lib/eslint.js#L416 + */ linter.defineRule("test", () => ({})); linter.verify("var a = 0;", { env: { node: true }, diff --git a/tests/lib/rules/array-bracket-newline.js b/tests/lib/rules/array-bracket-newline.js index 1258dc18ff9..86eee8fba3b 100644 --- a/tests/lib/rules/array-bracket-newline.js +++ b/tests/lib/rules/array-bracket-newline.js @@ -28,8 +28,10 @@ ruleTester.run("array-bracket-newline", rule, { valid: [ - // ArrayExpression - // "default" { multiline: true } + /* + * ArrayExpression + * "default" { multiline: true } + */ "var foo = [];", "var foo = [1];", "var foo = /* any comment */[1];", @@ -130,8 +132,10 @@ ruleTester.run("array-bracket-newline", rule, { { code: "var d = [\n1,\n2\n];", options: [{ multiline: true, minItems: 2 }] }, { code: "var e = [\nfunction foo() {\ndosomething();\n}\n];", options: [{ multiline: true, minItems: 2 }] }, - // ArrayPattern - // default { multiline: true } + /* + * ArrayPattern + * default { multiline: true } + */ { code: "var [] = foo", parserOptions: { ecmaVersion: 6 } }, { code: "var [a] = foo;", parserOptions: { ecmaVersion: 6 } }, { code: "var /* any comment */[a] = foo;", parserOptions: { ecmaVersion: 6 } }, @@ -173,8 +177,10 @@ ruleTester.run("array-bracket-newline", rule, { invalid: [ - // ArrayExpression - // "always" + /* + * ArrayExpression + * "always" + */ { code: "var foo = [];", output: "var foo = [\n];", @@ -1131,8 +1137,10 @@ ruleTester.run("array-bracket-newline", rule, { ] }, - // extra test cases - // "always" + /* + * extra test cases + * "always" + */ { code: "var foo = [\n1, 2];", output: "var foo = [\n1, 2\n];", @@ -1276,8 +1284,10 @@ ruleTester.run("array-bracket-newline", rule, { ] }, - // ArrayPattern - // "always" + /* + * ArrayPattern + * "always" + */ { code: "var [] = foo;", output: "var [\n] = foo;", diff --git a/tests/lib/rules/array-element-newline.js b/tests/lib/rules/array-element-newline.js index 0a1bd7e0827..c918c0ce053 100644 --- a/tests/lib/rules/array-element-newline.js +++ b/tests/lib/rules/array-element-newline.js @@ -26,8 +26,10 @@ ruleTester.run("array-element-newline", rule, { valid: [ - // ArrayExpression - // "always" + /* + * ArrayExpression + * "always" + */ "var foo = [];", "var foo = [1];", "var foo = [1,\n2];", @@ -103,8 +105,10 @@ ruleTester.run("array-element-newline", rule, { { code: "var foo = [1,\n2,\n// any comment\n, 3];", options: [{ multiline: true, minItems: 3 }] }, { code: "var foo = [\nfunction foo() {\ndosomething();\n},\nfunction bar() {\ndosomething();\n}\n];", options: [{ multiline: true, minItems: 3 }] }, - // ArrayPattern - // "always" + /* + * ArrayPattern + * "always" + */ { code: "var [] = foo;", parserOptions: { ecmaVersion: 6 } }, { code: "var [a] = foo;", parserOptions: { ecmaVersion: 6 } }, { code: "var [a,\nb] = foo;", parserOptions: { ecmaVersion: 6 } }, @@ -123,8 +127,10 @@ ruleTester.run("array-element-newline", rule, { invalid: [ - // ArrayExpression - // "always" + /* + * ArrayExpression + * "always" + */ { code: "var foo = [1, 2];", output: "var foo = [1,\n2];", @@ -657,8 +663,10 @@ ruleTester.run("array-element-newline", rule, { ] }, - // ArrayPattern - // "always" + /* + * ArrayPattern + * "always" + */ { code: "var [a, b] = foo;", output: "var [a,\nb] = foo;", diff --git a/tests/lib/rules/constructor-super.js b/tests/lib/rules/constructor-super.js index a2e6805cedb..d4da041f6db 100644 --- a/tests/lib/rules/constructor-super.js +++ b/tests/lib/rules/constructor-super.js @@ -25,8 +25,10 @@ ruleTester.run("constructor-super", rule, { "class A { }", "class A { constructor() { } }", - // inherit from non constructors. - // those are valid if we don't define the constructor. + /* + * inherit from non constructors. + * those are valid if we don't define the constructor. + */ "class A extends null { }", // derived classes. diff --git a/tests/lib/rules/getter-return.js b/tests/lib/rules/getter-return.js index e605c388aa0..b988c28a6bc 100644 --- a/tests/lib/rules/getter-return.js +++ b/tests/lib/rules/getter-return.js @@ -28,8 +28,10 @@ ruleTester.run("getter-return", rule, { valid: [ - // test obj: get - // option: {allowImplicit: false} + /* + * test obj: get + * option: {allowImplicit: false} + */ "var foo = { get bar(){return true;} };", // option: {allowImplicit: true} @@ -37,8 +39,10 @@ ruleTester.run("getter-return", rule, { { code: "var foo = { get bar(){return true;} };", options }, { code: "var foo = { get bar(){if(bar) {return;} return true;} };", options }, - // test class: get - // option: {allowImplicit: false} + /* + * test class: get + * option: {allowImplicit: false} + */ "class foo { get bar(){return true;} }", "class foo { get bar(){if(baz){return true;} else {return false;} } }", "class foo { get(){return true;} }", @@ -47,8 +51,10 @@ ruleTester.run("getter-return", rule, { { code: "class foo { get bar(){return true;} }", options }, { code: "class foo { get bar(){return;} }", options }, - // test object.defineProperty(s) - // option: {allowImplicit: false} + /* + * test object.defineProperty(s) + * option: {allowImplicit: false} + */ "Object.defineProperty(foo, \"bar\", { get: function () {return true;}});", "Object.defineProperty(foo, \"bar\", { get: function () { ~function (){ return true; }();return true;}});", "Object.defineProperties(foo, { bar: { get: function () {return true;}} });", @@ -74,8 +80,10 @@ ruleTester.run("getter-return", rule, { invalid: [ - // test obj: get - // option: {allowImplicit: false} + /* + * test obj: get + * option: {allowImplicit: false} + */ { code: "var foo = { get bar() {} };", errors: [{ message: noReturnMessage }] }, { code: "var foo = { get bar(){if(baz) {return true;}} };", errors: [{ message: noLastReturnMessage }] }, { code: "var foo = { get bar() { ~function () {return true;}} };", errors: [{ message: noReturnMessage }] }, @@ -84,8 +92,10 @@ ruleTester.run("getter-return", rule, { { code: "var foo = { get bar() {} };", options, errors: [{ message: noReturnMessage }] }, { code: "var foo = { get bar() {if (baz) {return;}} };", options, errors: [{ message: noLastReturnMessage }] }, - // test class: get - // option: {allowImplicit: false} + /* + * test class: get + * option: {allowImplicit: false} + */ { code: "class foo { get bar(){} }", errors: [{ message: noReturnMessage }] }, { code: "class foo { get bar(){ if (baz) { return true; }}}", errors: [{ noLastReturnMessage }] }, { code: "class foo { get bar(){ ~function () { return true; }()}}", errors: [{ noLastReturnMessage }] }, @@ -94,8 +104,10 @@ ruleTester.run("getter-return", rule, { { code: "class foo { get bar(){} }", options, errors: [{ message: noReturnMessage }] }, { code: "class foo { get bar(){if (baz) {return true;} } }", options, errors: [{ message: noLastReturnMessage }] }, - // test object.defineProperty(s) - // option: {allowImplicit: false} + /* + * test object.defineProperty(s) + * option: {allowImplicit: false} + */ { code: "Object.defineProperty(foo, \"bar\", { get: function (){}});", errors: [{ noReturnMessage }] }, { code: "Object.defineProperty(foo, \"bar\", { get: () => {}});", errors: [{ noReturnMessage }] }, { code: "Object.defineProperty(foo, \"bar\", { get: function (){if(bar) {return true;}}});", errors: [{ message: "Expected method 'get' to always return a value." }] }, diff --git a/tests/lib/rules/indent.js b/tests/lib/rules/indent.js index 0a7718492f1..5100f52381f 100644 --- a/tests/lib/rules/indent.js +++ b/tests/lib/rules/indent.js @@ -54,10 +54,10 @@ function expectedErrors(indentType, errors) { } /** -* Prevents leading spaces in a multiline template literal from appearing in the resulting string -* @param {string[]} strings The strings in the template literal -* @returns {string} The template literal, with spaces removed from all lines -*/ + * Prevents leading spaces in a multiline template literal from appearing in the resulting string + * @param {string[]} strings The strings in the template literal + * @returns {string} The template literal, with spaces removed from all lines + */ function unIndent(strings) { const templateValue = strings[0]; const lines = templateValue.replace(/^\n/, "").replace(/\n\s*$/, "").split("\n"); @@ -2051,8 +2051,10 @@ ruleTester.run("indent", rule, { `, { - // Checking comments: - // https://github.com/eslint/eslint/issues/3845, https://github.com/eslint/eslint/issues/6571 + /* + * Checking comments: + * https://github.com/eslint/eslint/issues/3845, https://github.com/eslint/eslint/issues/6571 + */ code: unIndent` foo(); // Line @@ -2090,8 +2092,10 @@ ruleTester.run("indent", rule, { `, { - // Destructuring assignments: - // https://github.com/eslint/eslint/issues/6813 + /* + * Destructuring assignments: + * https://github.com/eslint/eslint/issues/6813 + */ code: unIndent` var { foo, @@ -7061,8 +7065,10 @@ ruleTester.run("indent", rule, { }, { - // Checking comments: - // https://github.com/eslint/eslint/issues/6571 + /* + * Checking comments: + * https://github.com/eslint/eslint/issues/6571 + */ code: unIndent` foo(); // comment @@ -7124,8 +7130,10 @@ ruleTester.run("indent", rule, { }, { - // Destructuring assignments: - // https://github.com/eslint/eslint/issues/6813 + /* + * Destructuring assignments: + * https://github.com/eslint/eslint/issues/6813 + */ code: unIndent` var { foo, @@ -7649,10 +7657,12 @@ ruleTester.run("indent", rule, { }, { - // https://github.com/eslint/eslint/issues/1801 - // Note: This issue also mentioned checking the indentation for the 2 below. However, - // this is intentionally ignored because everyone seems to have a different idea of how - // BinaryExpressions should be indented. + /* + * https://github.com/eslint/eslint/issues/1801 + * Note: This issue also mentioned checking the indentation for the 2 below. However, + * this is intentionally ignored because everyone seems to have a different idea of how + * BinaryExpressions should be indented. + */ code: unIndent` if (true) { a = ( @@ -8718,8 +8728,10 @@ ruleTester.run("indent", rule, { }, { - // Multiline ternary - // (colon at the end of the first expression) + /* + * Multiline ternary + * (colon at the end of the first expression) + */ code: unIndent` foo ? : @@ -8734,8 +8746,10 @@ ruleTester.run("indent", rule, { }, { - // Multiline ternary - // (colon on its own line) + /* + * Multiline ternary + * (colon on its own line) + */ code: unIndent` foo ? @@ -8752,8 +8766,10 @@ ruleTester.run("indent", rule, { }, { - // Multiline ternary - // (colon at the end of the first expression, parenthesized first expression) + /* + * Multiline ternary + * (colon at the end of the first expression, parenthesized first expression) + */ code: unIndent` foo ? ( diff --git a/tests/lib/rules/keyword-spacing.js b/tests/lib/rules/keyword-spacing.js index 0f6a6fed848..6b993c43ad6 100644 --- a/tests/lib/rules/keyword-spacing.js +++ b/tests/lib/rules/keyword-spacing.js @@ -681,8 +681,10 @@ ruleTester.run("keyword-spacing", rule, { ";function foo() {};", { code: "; function foo() {} ;", options: [NEITHER] }, - // not conflict with `space-before-function-paren` - // not conflict with `space-in-parens` + /* + * not conflict with `space-before-function-paren` + * not conflict with `space-in-parens` + */ "(function() {})", { code: "( function () {})", options: [NEITHER] }, @@ -1286,12 +1288,13 @@ ruleTester.run("keyword-spacing", rule, { { code: "function* foo() { [yield] }", parserOptions: { ecmaVersion: 6 } }, { code: "function* foo() { [ yield ] }", options: [NEITHER], parserOptions: { ecmaVersion: 6 } }, - // This is invalid syntax: https://github.com/eslint/eslint/issues/5405 - // not conflict with `arrow-spacing` - // {code: "function* foo() { (() =>yield foo) }", parserOptions: {ecmaVersion: 6}}, - // {code: "function* foo() { (() => yield foo) }", options: [NEITHER], parserOptions: {ecmaVersion: 6}}, - - // not conflict with `block-spacing` + /* + * This is invalid syntax: https://github.com/eslint/eslint/issues/5405 + * not conflict with `arrow-spacing` + * {code: "function* foo() { (() =>yield foo) }", parserOptions: {ecmaVersion: 6}}, + * {code: "function* foo() { (() => yield foo) }", options: [NEITHER], parserOptions: {ecmaVersion: 6}}, + * not conflict with `block-spacing` + */ { code: "function* foo() {yield}", parserOptions: { ecmaVersion: 6 } }, { code: "function* foo() { yield }", options: [NEITHER], parserOptions: { ecmaVersion: 6 } }, diff --git a/tests/lib/rules/lines-around-directive.js b/tests/lib/rules/lines-around-directive.js index 7e166a1bc68..b3ef8883ae8 100644 --- a/tests/lib/rules/lines-around-directive.js +++ b/tests/lib/rules/lines-around-directive.js @@ -25,9 +25,11 @@ ruleTester.run("lines-around-directive", rule, { // use "always" by default "//comment\n\n'use strict';\n'use asm';\n\nvar foo;", - // "always" - // at top of file - // single directive + /* + * "always" + * at top of file + * single directive + */ { code: "'use strict';\n\nvar foo;", options: ["always"] @@ -63,8 +65,10 @@ ruleTester.run("lines-around-directive", rule, { options: ["always"] }, - // after comment at top of file - // single directive + /* + * after comment at top of file + * single directive + */ { code: "#!/usr/bin/env node\n\n'use strict';\n\nvar foo;", options: ["always"] @@ -102,8 +106,10 @@ ruleTester.run("lines-around-directive", rule, { options: ["always"] }, - // at the top of function blocks - // single directive + /* + * at the top of function blocks + * single directive + */ { code: "function foo() {\n'use strict';\n\nvar bar;\n}", options: ["always"] @@ -143,8 +149,10 @@ ruleTester.run("lines-around-directive", rule, { parserOptions: { ecmaVersion: 6 } }, - // after comment at top of function blocks - // single directive + /* + * after comment at top of function blocks + * single directive + */ { code: "function foo() {\n//comment\n\n'use strict';\n\nvar bar;\n}", options: ["always"] @@ -196,9 +204,11 @@ ruleTester.run("lines-around-directive", rule, { options: ["always"] }, - // "never" - // at top of file - // single directive + /* + * "never" + * at top of file + * single directive + */ { code: "'use strict';\nvar foo;", options: ["never"] @@ -226,8 +236,10 @@ ruleTester.run("lines-around-directive", rule, { options: ["never"] }, - // after comment at top of file - // single directive + /* + * after comment at top of file + * single directive + */ { code: "#!/usr/bin/env node\n'use strict';\nvar foo;", options: ["never"] @@ -263,8 +275,10 @@ ruleTester.run("lines-around-directive", rule, { options: ["never"] }, - // at the top of function blocks - // single directive + /* + * at the top of function blocks + * single directive + */ { code: "function foo() {\n'use strict';\nvar bar;\n}", options: ["never"] @@ -304,8 +318,10 @@ ruleTester.run("lines-around-directive", rule, { parserOptions: { ecmaVersion: 6 } }, - // after comment at top of function blocks - // single directive + /* + * after comment at top of function blocks + * single directive + */ { code: "function foo() {\n//comment\n'use strict';\nvar bar;\n}", options: ["never"] @@ -363,9 +379,11 @@ ruleTester.run("lines-around-directive", rule, { options: ["never"] }, - // { "before": "never", "after": "always" } - // at top of file - // single directive + /* + * { "before": "never", "after": "always" } + * at top of file + * single directive + */ { code: "'use strict';\n\nvar foo;", options: [{ before: "never", after: "always" }] @@ -393,8 +411,10 @@ ruleTester.run("lines-around-directive", rule, { options: [{ before: "never", after: "always" }] }, - // after comment at top of file - // single directive + /* + * after comment at top of file + * single directive + */ { code: "#!/usr/bin/env node\n'use strict';\n\nvar foo;", options: [{ before: "never", after: "always" }] @@ -422,8 +442,10 @@ ruleTester.run("lines-around-directive", rule, { options: [{ before: "never", after: "always" }] }, - // at the top of function blocks - // single directive + /* + * at the top of function blocks + * single directive + */ { code: "function foo() {\n'use strict';\n\nvar bar;\n}", options: [{ before: "never", after: "always" }] @@ -463,8 +485,10 @@ ruleTester.run("lines-around-directive", rule, { parserOptions: { ecmaVersion: 6 } }, - // after comment at top of function blocks - // single directive + /* + * after comment at top of function blocks + * single directive + */ { code: "function foo() {\n//comment\n'use strict';\n\nvar bar;\n}", options: [{ before: "never", after: "always" }] @@ -504,9 +528,11 @@ ruleTester.run("lines-around-directive", rule, { parserOptions: { ecmaVersion: 6 } }, - // { "before": "always", "after": "never" } - // at top of file - // single directive + /* + * { "before": "always", "after": "never" } + * at top of file + * single directive + */ { code: "'use strict';\nvar foo;", options: [{ before: "always", after: "never" }] @@ -542,8 +568,10 @@ ruleTester.run("lines-around-directive", rule, { options: [{ before: "always", after: "never" }] }, - // after comment at top of file - // single directive + /* + * after comment at top of file + * single directive + */ { code: "#!/usr/bin/env node\n\n'use strict';\nvar foo;", options: [{ before: "always", after: "never" }] @@ -571,8 +599,10 @@ ruleTester.run("lines-around-directive", rule, { options: [{ before: "always", after: "never" }] }, - // at the top of function blocks - // single directive + /* + * at the top of function blocks + * single directive + */ { code: "function foo() {\n'use strict';\nvar bar;\n}", options: [{ before: "always", after: "never" }] @@ -612,8 +642,10 @@ ruleTester.run("lines-around-directive", rule, { parserOptions: { ecmaVersion: 6 } }, - // after comment at top of function blocks - // single directive + /* + * after comment at top of function blocks + * single directive + */ { code: "function foo() {\n//comment\n\n'use strict';\nvar bar;\n}", options: [{ before: "always", after: "never" }] @@ -666,9 +698,11 @@ ruleTester.run("lines-around-directive", rule, { invalid: [ - // "always" - // at top of file - // single directive + /* + * "always" + * at top of file + * single directive + */ { code: "'use strict';\nvar foo;", output: "'use strict';\n\nvar foo;", @@ -708,8 +742,10 @@ ruleTester.run("lines-around-directive", rule, { errors: ["Expected newline after \"use asm\" directive."] }, - // after comment at top of file - // single directive + /* + * after comment at top of file + * single directive + */ { code: "#!/usr/bin/env node\n'use strict';\nvar foo;", output: "#!/usr/bin/env node\n\n'use strict';\n\nvar foo;", @@ -785,8 +821,10 @@ ruleTester.run("lines-around-directive", rule, { ] }, - // at the top of function blocks - // single directive + /* + * at the top of function blocks + * single directive + */ { code: "function foo() {\n'use strict';\nvar bar;\n}", output: "function foo() {\n'use strict';\n\nvar bar;\n}", @@ -816,8 +854,10 @@ ruleTester.run("lines-around-directive", rule, { errors: ["Expected newline after \"use asm\" directive."] }, - // after comment at top of function blocks - // single directive + /* + * after comment at top of function blocks + * single directive + */ { code: "function foo() {\n//comment\n'use strict';\nvar bar;\n}", output: "function foo() {\n//comment\n\n'use strict';\n\nvar bar;\n}", @@ -897,9 +937,11 @@ ruleTester.run("lines-around-directive", rule, { ] }, - // "never" - // at top of file - // single directive + /* + * "never" + * at top of file + * single directive + */ { code: "'use strict';\n\nvar foo;", output: "'use strict';\nvar foo;", @@ -939,8 +981,10 @@ ruleTester.run("lines-around-directive", rule, { errors: ["Unexpected newline after \"use asm\" directive."] }, - // after comment at top of file - // single directive + /* + * after comment at top of file + * single directive + */ { code: "#!/usr/bin/env node\n\n'use strict';\n\nvar foo;", output: "#!/usr/bin/env node\n'use strict';\nvar foo;", @@ -1016,8 +1060,10 @@ ruleTester.run("lines-around-directive", rule, { ] }, - // at the top of function blocks - // single directive + /* + * at the top of function blocks + * single directive + */ { code: "function foo() {\n'use strict';\n\nvar bar;\n}", output: "function foo() {\n'use strict';\nvar bar;\n}", @@ -1047,8 +1093,10 @@ ruleTester.run("lines-around-directive", rule, { errors: ["Unexpected newline after \"use asm\" directive."] }, - // after comment at top of function blocks - // single directive + /* + * after comment at top of function blocks + * single directive + */ { code: "function foo() {\n//comment\n\n'use strict';\n\nvar bar;\n}", output: "function foo() {\n//comment\n'use strict';\nvar bar;\n}", @@ -1129,9 +1177,11 @@ ruleTester.run("lines-around-directive", rule, { }, - // { "before": "never", "after": "always" } - // at top of file - // single directive + /* + * { "before": "never", "after": "always" } + * at top of file + * single directive + */ { code: "'use strict';\nvar foo;", output: "'use strict';\n\nvar foo;", @@ -1171,8 +1221,10 @@ ruleTester.run("lines-around-directive", rule, { errors: ["Expected newline after \"use asm\" directive."] }, - // after comment at top of file - // single directive + /* + * after comment at top of file + * single directive + */ { code: "#!/usr/bin/env node\n\n'use strict';\nvar foo;", output: "#!/usr/bin/env node\n'use strict';\n\nvar foo;", @@ -1230,8 +1282,10 @@ ruleTester.run("lines-around-directive", rule, { ] }, - // at the top of function blocks - // single directive + /* + * at the top of function blocks + * single directive + */ { code: "function foo() {\n'use strict';\nvar bar;\n}", output: "function foo() {\n'use strict';\n\nvar bar;\n}", @@ -1287,8 +1341,10 @@ ruleTester.run("lines-around-directive", rule, { errors: ["Expected newline after \"use asm\" directive."] }, - // after comment at top of function blocks - // single directive + /* + * after comment at top of function blocks + * single directive + */ { code: "function foo() {\n//comment\n\n'use strict';\nvar bar;\n}", output: "function foo() {\n//comment\n'use strict';\n\nvar bar;\n}", @@ -1368,9 +1424,11 @@ ruleTester.run("lines-around-directive", rule, { ] }, - // { "before": "always", "after": "never" } - // at top of file - // single directive + /* + * { "before": "always", "after": "never" } + * at top of file + * single directive + */ { code: "'use strict';\n\nvar foo;", output: "'use strict';\nvar foo;", @@ -1410,8 +1468,10 @@ ruleTester.run("lines-around-directive", rule, { errors: ["Unexpected newline after \"use asm\" directive."] }, - // after comment at top of file - // single directive + /* + * after comment at top of file + * single directive + */ { code: "#!/usr/bin/env node\n'use strict';\n\nvar foo;", output: "#!/usr/bin/env node\n\n'use strict';\nvar foo;", @@ -1469,8 +1529,10 @@ ruleTester.run("lines-around-directive", rule, { ] }, - // at the top of function blocks - // single directive + /* + * at the top of function blocks + * single directive + */ { code: "function foo() {\n'use strict';\n\nvar bar;\n}", output: "function foo() {\n'use strict';\nvar bar;\n}", @@ -1526,8 +1588,10 @@ ruleTester.run("lines-around-directive", rule, { errors: ["Unexpected newline after \"use asm\" directive."] }, - // after comment at top of function blocks - // single directive + /* + * after comment at top of function blocks + * single directive + */ { code: "function foo() {\n//comment\n'use strict';\n\nvar bar;\n}", output: "function foo() {\n//comment\n\n'use strict';\nvar bar;\n}", diff --git a/tests/lib/rules/max-statements.js b/tests/lib/rules/max-statements.js index 2b030a7e0ec..173e3411f75 100644 --- a/tests/lib/rules/max-statements.js +++ b/tests/lib/rules/max-statements.js @@ -113,13 +113,15 @@ ruleTester.run("max-statements", rule, { errors: [{ message: "Method 'thing' has too many statements (3). Maximum allowed is 2." }] }, - // TODO decide if we want this or not - // { - // code: "var foo = { ['thing']() { var bar = 1; var baz = 2; var baz2; } }", - // options: [2], - // parserOptions: { ecmaVersion: 6 }, - // errors: [{ message: "Method ''thing'' has too many statements (3). Maximum allowed is 2." }] - // }, + /* + * TODO decide if we want this or not + * { + * code: "var foo = { ['thing']() { var bar = 1; var baz = 2; var baz2; } }", + * options: [2], + * parserOptions: { ecmaVersion: 6 }, + * errors: [{ message: "Method ''thing'' has too many statements (3). Maximum allowed is 2." }] + * }, + */ { code: "var foo = { thing: () => { var bar = 1; var baz = 2; var baz2; } }", diff --git a/tests/lib/rules/newline-before-return.js b/tests/lib/rules/newline-before-return.js index 552202a0117..591ccce19b3 100644 --- a/tests/lib/rules/newline-before-return.js +++ b/tests/lib/rules/newline-before-return.js @@ -220,8 +220,10 @@ ruleTester.run("newline-before-return", rule, { errors: ["Expected newline before return statement."] }, - // Testing edge cases of the fixer when the `return` statement has leading comments. - // https://github.com/eslint/eslint/issues/5958 + /* + * Testing edge cases of the fixer when the `return` statement has leading comments. + * https://github.com/eslint/eslint/issues/5958 + */ { code: "function a() {\nvar b; /*multi-line\ncomment*/\nreturn c;\n}", output: null, diff --git a/tests/lib/rules/no-unused-labels.js b/tests/lib/rules/no-unused-labels.js index 9a9bdb71cef..08e6f093bf0 100644 --- a/tests/lib/rules/no-unused-labels.js +++ b/tests/lib/rules/no-unused-labels.js @@ -75,10 +75,12 @@ ruleTester.run("no-unused-labels", rule, { errors: ["'A:' is defined but never used."] } - // Below is fatal errors. - // "A: break B", - // "A: function foo() { break A; }", - // "A: class Foo { foo() { break A; } }", - // "A: { A: { break A; } }" + /* + * Below is fatal errors. + * "A: break B", + * "A: function foo() { break A; }", + * "A: class Foo { foo() { break A; } }", + * "A: { A: { break A; } }" + */ ] }); diff --git a/tests/lib/rules/no-unused-vars.js b/tests/lib/rules/no-unused-vars.js index b7ccc38446f..3e452ce3d66 100644 --- a/tests/lib/rules/no-unused-vars.js +++ b/tests/lib/rules/no-unused-vars.js @@ -35,10 +35,10 @@ ruleTester.defineRule("use-every-a", context => { }); /** -* Returns an extended test that includes es2017 parser options. -* @param {Object} test The test to extend -* @returns {Object} A parser-extended test case -*/ + * Returns an extended test that includes es2017 parser options. + * @param {Object} test The test to extend + * @returns {Object} A parser-extended test case + */ function includeRestPropertyParser(test) { return Object.assign({ parserOptions: { @@ -51,21 +51,21 @@ function includeRestPropertyParser(test) { } /** -* Returns an expected error for defined-but-not-used variables. -* @param {string} varName The name of the variable -* @param {string} [type] The node type (defaults to "Identifier") -* @returns {Object} An expected error object -*/ + * Returns an expected error for defined-but-not-used variables. + * @param {string} varName The name of the variable + * @param {string} [type] The node type (defaults to "Identifier") + * @returns {Object} An expected error object + */ function definedError(varName, type) { return { message: `'${varName}' is defined but never used.`, type: type || "Identifier" }; } /** -* Returns an expected error for assigned-but-not-used variables. -* @param {string} varName The name of the variable -* @param {string} [type] The node type (defaults to "Identifier") -* @returns {Object} An expected error object -*/ + * Returns an expected error for assigned-but-not-used variables. + * @param {string} varName The name of the variable + * @param {string} [type] The node type (defaults to "Identifier") + * @returns {Object} An expected error object + */ function assignedError(varName, type) { return { message: `'${varName}' is assigned a value but never used.`, type: type || "Identifier" }; } diff --git a/tests/lib/rules/no-useless-return.js b/tests/lib/rules/no-useless-return.js index 78e82fb2688..56ad245c2c9 100644 --- a/tests/lib/rules/no-useless-return.js +++ b/tests/lib/rules/no-useless-return.js @@ -368,8 +368,10 @@ ruleTester.run("no-useless-return", rule, { ` }, - // FIXME: Re-add this case (removed due to https://github.com/eslint/eslint/issues/7481): - // https://github.com/eslint/eslint/blob/261d7287820253408ec87c344beccdba2fe829a4/tests/lib/rules/no-useless-return.js#L308-L329 + /* + * FIXME: Re-add this case (removed due to https://github.com/eslint/eslint/issues/7481): + * https://github.com/eslint/eslint/blob/261d7287820253408ec87c344beccdba2fe829a4/tests/lib/rules/no-useless-return.js#L308-L329 + */ { code: ` diff --git a/tests/lib/rules/no-var.js b/tests/lib/rules/no-var.js index 48511d82592..98b3be5e5c3 100644 --- a/tests/lib/rules/no-var.js +++ b/tests/lib/rules/no-var.js @@ -254,8 +254,10 @@ ruleTester.run("no-var", rule, { ] }, - // This case is not in TDZ, but it's very hard to distinguish the reference is in TDZ or not. - // So this rule does not fix it for safe. + /* + * This case is not in TDZ, but it's very hard to distinguish the reference is in TDZ or not. + * So this rule does not fix it for safe. + */ { code: "function foo() { a } var a = 1; foo()", output: null, diff --git a/tests/lib/rules/object-curly-spacing.js b/tests/lib/rules/object-curly-spacing.js index 1b22ccd9fcf..dc2a26180a6 100644 --- a/tests/lib/rules/object-curly-spacing.js +++ b/tests/lib/rules/object-curly-spacing.js @@ -124,8 +124,10 @@ ruleTester.run("object-curly-spacing", rule, { // never - objectsInObjects { code: "var obj = {'foo': {'bar': 1, 'baz': 2} };", options: ["never", { objectsInObjects: true }] }, - // https://github.com/eslint/eslint/issues/3658 - // Empty cases. + /* + * https://github.com/eslint/eslint/issues/3658 + * Empty cases. + */ { code: "var {} = foo;", parserOptions: { ecmaVersion: 6 } }, { code: "var [] = foo;", parserOptions: { ecmaVersion: 6 } }, { code: "var {a: {}} = foo;", parserOptions: { ecmaVersion: 6 } }, diff --git a/tests/lib/rules/padding-line-between-statements.js b/tests/lib/rules/padding-line-between-statements.js index 8e6054f7edd..aa91a6b077b 100644 --- a/tests/lib/rules/padding-line-between-statements.js +++ b/tests/lib/rules/padding-line-between-statements.js @@ -2129,7 +2129,8 @@ ruleTester.run("padding-line-between-statements", rule, { ] }, - /* TODO: May it need an option to ignore blank lines followed by comments? + /* + * TODO: May it need an option to ignore blank lines followed by comments? * { * code: "var a = 2;\n\n// foo\nmodule.exports = a;", * options: [ diff --git a/tests/lib/rules/prefer-const.js b/tests/lib/rules/prefer-const.js index f389dcd3026..31dceb45a62 100644 --- a/tests/lib/rules/prefer-const.js +++ b/tests/lib/rules/prefer-const.js @@ -70,8 +70,10 @@ ruleTester.run("prefer-const", rule, { "/*exported a*/ let a = 1", "let a; if (true) a = 0; foo(a);", - // The assignment is located in a different scope. - // Those are warned by prefer-smaller-scope. + /* + * The assignment is located in a different scope. + * Those are warned by prefer-smaller-scope. + */ "let x; { x = 0; foo(x); }", "(function() { let x; { x = 0; foo(x); } })();", "let x; for (const a of [1,2,3]) { x = foo(); bar(x); }", diff --git a/tests/lib/token-store.js b/tests/lib/token-store.js index 373ac2ad590..cf27c53b32d 100644 --- a/tests/lib/token-store.js +++ b/tests/lib/token-store.js @@ -626,8 +626,10 @@ describe("TokenStore", () => { const ast = espree.parse(code, { loc: true, range: true, tokens: true, comment: true }); const tokenStore = new TokenStore(ast.tokens, ast.comments); - // Actually, the first of nodes is always tokens, not comments. - // But I think this test case is needed for completeness. + /* + * Actually, the first of nodes is always tokens, not comments. + * But I think this test case is needed for completeness. + */ const token = tokenStore.getFirstToken( { range: [ast.comments[0].range[0], ast.tokens[5].range[1]] }, { includeComments: true } @@ -641,8 +643,10 @@ describe("TokenStore", () => { const ast = espree.parse(code, { loc: true, range: true, tokens: true, comment: true }); const tokenStore = new TokenStore(ast.tokens, ast.comments); - // Actually, the first of nodes is always tokens, not comments. - // But I think this test case is needed for completeness. + /* + * Actually, the first of nodes is always tokens, not comments. + * But I think this test case is needed for completeness. + */ const token = tokenStore.getFirstToken( { range: [ast.comments[0].range[0], ast.tokens[5].range[1]] } ); @@ -809,8 +813,10 @@ describe("TokenStore", () => { const ast = espree.parse(code, { loc: true, range: true, tokens: true, comment: true }); const tokenStore = new TokenStore(ast.tokens, ast.comments); - // Actually, the last of nodes is always tokens, not comments. - // But I think this test case is needed for completeness. + /* + * Actually, the last of nodes is always tokens, not comments. + * But I think this test case is needed for completeness. + */ const token = tokenStore.getLastToken( { range: [ast.tokens[0].range[0], ast.comments[0].range[1]] }, { includeComments: true } @@ -824,8 +830,10 @@ describe("TokenStore", () => { const ast = espree.parse(code, { loc: true, range: true, tokens: true, comment: true }); const tokenStore = new TokenStore(ast.tokens, ast.comments); - // Actually, the last of nodes is always tokens, not comments. - // But I think this test case is needed for completeness. + /* + * Actually, the last of nodes is always tokens, not comments. + * But I think this test case is needed for completeness. + */ const token = tokenStore.getLastToken( { range: [ast.tokens[0].range[0], ast.comments[0].range[1]] } ); diff --git a/tests/lib/util/source-code-fixer.js b/tests/lib/util/source-code-fixer.js index 7be5cf189f4..56918f51340 100644 --- a/tests/lib/util/source-code-fixer.js +++ b/tests/lib/util/source-code-fixer.js @@ -423,8 +423,10 @@ describe("SourceCodeFixer", () => { }); - // This section is almost same as "with no BOM". - // Just `result.output` has BOM. + /* + * This section is almost same as "with no BOM". + * Just `result.output` has BOM. + */ describe("applyFixes() with BOM", () => { const TEST_CODE_WITH_BOM = `\uFEFF${TEST_CODE}`; diff --git a/tests/tools/internal-rules/multiline-comment-style.js b/tests/tools/internal-rules/multiline-comment-style.js new file mode 100644 index 00000000000..2b67918a3de --- /dev/null +++ b/tests/tools/internal-rules/multiline-comment-style.js @@ -0,0 +1,38 @@ +"use strict"; + +const rule = require("../../../tools/internal-rules/multiline-comment-style"); +const RuleTester = require("../../../lib/testers/rule-tester"); +const ruleTester = new RuleTester(); + +ruleTester.run("internal-rules/multiline-comment-style", rule, { + valid: [ + ` + //---------------- + // Rule Description + //---------------- + `, + ` + /* + * Block comment + */ + `, + ` + // single-line comment + ` + ], + invalid: [ + { + code: ` + // foo + // bar + `, + output: ` + /* + * foo + * bar + */ + `, + errors: [{ message: "Expected a block comment instead of consecutive line comments." }] + } + ] +}); diff --git a/tools/internal-rules/multiline-comment-style.js b/tools/internal-rules/multiline-comment-style.js new file mode 100644 index 00000000000..2ded6c72ed4 --- /dev/null +++ b/tools/internal-rules/multiline-comment-style.js @@ -0,0 +1,25 @@ +/** + * @fileoverview A modified version of the `multiline-comment-style` rule that ignores banner comments. + * @author Teddy Katz + */ + +"use strict"; + +const ruleComposer = require("eslint-rule-composer"); +const multilineCommentStyle = require("../../lib/rules/multiline-comment-style"); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +// The `no-invalid-meta` internal rule has a false positive here. +// eslint-disable-next-line rulesdir/no-invalid-meta +module.exports = ruleComposer.filterReports( + multilineCommentStyle, + (problem, metadata) => { + const problemIndex = metadata.sourceCode.getIndexFromLoc(problem.loc.start); + const reportedToken = metadata.sourceCode.getTokenByRangeStart(problemIndex, { includeComments: true }); + + return !(reportedToken && reportedToken.type === "Line" && /^-{2,}$/.test(reportedToken.value)); + } +);