tools: update to ESLint 4.12.0

PR-URL: https://github.com/nodejs/node/pull/16948
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Rich Trott <rtrott@gmail.com>
This commit is contained in:
cjihrig authored and Gibson Fahnestock committed 2017-12-20 01:59:30 +00:00
1 parent ef7261006e
commit 3fb2183464
231 files changed
+6170 -19748

No files matched your search

+2 -2
View File
@@ -116,6 +116,7 @@ These folks keep the project moving and are resources for help.
* Alberto Rodríguez ([@alberto](https://github.com/alberto))
* Kai Cataldo ([@kaicataldo](https://github.com/kaicataldo))
* Teddy Katz ([@not-an-aardvark](https://github.com/not-an-aardvark))
* Kevin Partington ([@platinumazure](https://github.com/platinumazure))
### Development Team
@@ -130,7 +131,6 @@ These folks keep the project moving and are resources for help.
* Henry Zhu ([@hzoo](https://github.com/hzoo))
* Marat Dulin ([@mdevils](https://github.com/mdevils))
* Alexej Yaroshevich ([@zxqfox](https://github.com/zxqfox))
* Kevin Partington ([@platinumazure](https://github.com/platinumazure))
* Vitor Balocco ([@vitorbal](https://github.com/vitorbal))
* James Henry ([@JamesHenry](https://github.com/JamesHenry))
* Reyad Attiyat ([@soda0289](https://github.com/soda0289))
@@ -225,7 +225,7 @@ In all cases, make sure your plugins' peerDependencies have been installed as we
### Does ESLint support JSX?
Yes, ESLint natively supports parsing JSX syntax (this must be enabled in [configuration](https://eslint.org/docs/user-guide/configuring).). Please note that supporting JSX syntax *is not* the same as supporting React. React applies specific semantics to JSX syntax that ESLint doesn't recognize. We recommend using [eslint-plugin-react](https://www.npmjs.com/package/eslint-plugin-react) if you are using React and want React semantics.
Yes, ESLint natively supports parsing JSX syntax (this must be enabled in [configuration](https://eslint.org/docs/user-guide/configuring)). Please note that supporting JSX syntax *is not* the same as supporting React. React applies specific semantics to JSX syntax that ESLint doesn't recognize. We recommend using [eslint-plugin-react](https://www.npmjs.com/package/eslint-plugin-react) if you are using React and want React semantics.
### What about ECMAScript 6 support?
+5 -3
View File
@@ -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,
+128 -4
View File
@@ -17,10 +17,126 @@ const globals = require("globals");
module.exports = {
builtin: globals.es5,
browser: {
globals: globals.browser
/*
* For backward compatibility.
* Remove those on the next major release.
*/
globals: Object.assign(
{
AutocompleteErrorEvent: false,
CDATASection: false,
ClientRect: false,
ClientRectList: false,
CSSAnimation: false,
CSSTransition: false,
CSSUnknownRule: false,
CSSViewportRule: false,
Debug: false,
DocumentTimeline: false,
DOMSettableTokenList: false,
ElementTimeControl: false,
FederatedCredential: false,
FileError: false,
HTMLAppletElement: false,
HTMLBlockquoteElement: false,
HTMLIsIndexElement: false,
HTMLKeygenElement: false,
HTMLLayerElement: false,
IDBEnvironment: false,
InputMethodContext: false,
MediaKeyError: false,
MediaKeyEvent: false,
MediaKeys: false,
opera: false,
PasswordCredential: false,
ReadableByteStream: false,
SharedKeyframeList: false,
showModalDialog: false,
SiteBoundCredential: false,
SVGAltGlyphDefElement: false,
SVGAltGlyphElement: false,
SVGAltGlyphItemElement: false,
SVGAnimateColorElement: false,
SVGAnimatedPathData: false,
SVGAnimatedPoints: false,
SVGColor: false,
SVGColorProfileElement: false,
SVGColorProfileRule: false,
SVGCSSRule: false,
SVGCursorElement: false,
SVGDocument: false,
SVGElementInstance: false,
SVGElementInstanceList: false,
SVGEvent: false,
SVGExternalResourcesRequired: false,
SVGFilterPrimitiveStandardAttributes: false,
SVGFitToViewBox: false,
SVGFontElement: false,
SVGFontFaceElement: false,
SVGFontFaceFormatElement: false,
SVGFontFaceNameElement: false,
SVGFontFaceSrcElement: false,
SVGFontFaceUriElement: false,
SVGGlyphElement: false,
SVGGlyphRefElement: false,
SVGHKernElement: false,
SVGICCColor: false,
SVGLangSpace: false,
SVGLocatable: false,
SVGMissingGlyphElement: false,
SVGPaint: false,
SVGPathSeg: false,
SVGPathSegArcAbs: false,
SVGPathSegArcRel: false,
SVGPathSegClosePath: false,
SVGPathSegCurvetoCubicAbs: false,
SVGPathSegCurvetoCubicRel: false,
SVGPathSegCurvetoCubicSmoothAbs: false,
SVGPathSegCurvetoCubicSmoothRel: false,
SVGPathSegCurvetoQuadraticAbs: false,
SVGPathSegCurvetoQuadraticRel: false,
SVGPathSegCurvetoQuadraticSmoothAbs: false,
SVGPathSegCurvetoQuadraticSmoothRel: false,
SVGPathSegLinetoAbs: false,
SVGPathSegLinetoHorizontalAbs: false,
SVGPathSegLinetoHorizontalRel: false,
SVGPathSegLinetoRel: false,
SVGPathSegLinetoVerticalAbs: false,
SVGPathSegLinetoVerticalRel: false,
SVGPathSegList: false,
SVGPathSegMovetoAbs: false,
SVGPathSegMovetoRel: false,
SVGRenderingIntent: false,
SVGStylable: false,
SVGTests: false,
SVGTransformable: false,
SVGTRefElement: false,
SVGURIReference: false,
SVGViewSpec: false,
SVGVKernElement: false,
SVGZoomAndPan: false,
SVGZoomEvent: false,
TimeEvent: false,
XDomainRequest: false,
XMLHttpRequestProgressEvent: false,
XPathException: false,
XPathNamespace: false,
XPathNSResolver: false
},
globals.browser
)
},
node: {
globals: globals.node,
/*
* For backward compatibility.
* Remove those on the next major release.
*/
globals: Object.assign(
{ arguments: false, GLOBAL: false, root: false },
globals.node
),
parserOptions: {
ecmaFeatures: {
globalReturn: true
@@ -51,7 +167,15 @@ module.exports = {
globals: globals.jasmine
},
jest: {
globals: globals.jest
/*
* For backward compatibility.
* Remove those on the next major release.
*/
globals: Object.assign(
{ check: false, gen: false },
globals.jest
)
},
phantomjs: {
globals: globals.phantomjs
@@ -96,7 +220,7 @@ module.exports = {
globals: globals.webextensions
},
es6: {
globals: globals.es6,
globals: globals.es2015,
parserOptions: {
ecmaVersion: 6
}
+1
View File
@@ -53,6 +53,7 @@ module.exports = {
"id-blacklist": "off",
"id-length": "off",
"id-match": "off",
"implicit-arrow-linebreak": "off",
indent: "off",
"indent-legacy": "off",
"init-declarations": "off",
+81 -41
View File
@@ -406,6 +406,31 @@ function createGlobalLinebreakMatcher() {
return new RegExp(LINEBREAK_MATCHER.source, "g");
}
/**
* Checks whether or not the tokens of two given nodes are same.
* @param {ASTNode} left - A node 1 to compare.
* @param {ASTNode} right - A node 2 to compare.
* @param {SourceCode} sourceCode - The ESLint source code object.
* @returns {boolean} the source code for the given node.
*/
function equalTokens(left, right, sourceCode) {
const tokensL = sourceCode.getTokens(left);
const tokensR = sourceCode.getTokens(right);
if (tokensL.length !== tokensR.length) {
return false;
}
for (let i = 0; i < tokensL.length; ++i) {
if (tokensL[i].type !== tokensR[i].type ||
tokensL[i].value !== tokensR[i].value
) {
return false;
}
}
return true;
}
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
@@ -438,6 +463,7 @@ module.exports = {
isArrayFromMethod,
isParenthesised,
createGlobalLinebreakMatcher,
equalTokens,
isArrowToken,
isClosingBraceToken,
@@ -620,15 +646,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 +673,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 +708,10 @@ module.exports = {
}
return true;
// e.g.
// var Foo = function() { ... };
/*
* e.g.
* var Foo = function() { ... };
*/
case "VariableDeclarator":
return !(
isAnonymous &&
@@ -686,10 +720,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 +736,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 +968,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 +994,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 +1223,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);
+27 -12
View File
@@ -24,12 +24,16 @@ const fs = require("fs"),
fileEntryCache = require("file-entry-cache"),
globUtil = require("./util/glob-util"),
validator = require("./config/config-validator"),
stringify = require("json-stable-stringify"),
stringify = require("json-stable-stringify-without-jsonify"),
hash = require("./util/hash"),
ModuleResolver = require("./util/module-resolver"),
naming = require("./util/naming"),
pkg = require("../package.json");
const debug = require("debug")("eslint:cli-engine");
const resolver = new ModuleResolver();
//------------------------------------------------------------------------------
// Typedefs
//------------------------------------------------------------------------------
@@ -405,9 +409,13 @@ class CLIEngine {
});
}
Object.keys(this.options.rules || {}).forEach(name => {
validator.validateRuleOptions(name, this.options.rules[name], "CLI", this.linter.rules);
});
if (this.options.rules && Object.keys(this.options.rules).length) {
const loadedRules = this.linter.getRules();
Object.keys(this.options.rules).forEach(name => {
validator.validateRuleOptions(loadedRules.get(name), name, this.options.rules[name], "CLI");
});
}
this.config = new Config(this.options, this.linter);
}
@@ -542,10 +550,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 {
@@ -670,15 +678,22 @@ class CLIEngine {
// replace \ with / for Windows compatibility
format = format.replace(/\\/g, "/");
const cwd = this.options ? this.options.cwd : process.cwd();
const namespace = naming.getNamespaceFromTerm(format);
let formatterPath;
// if there's a slash, then it's a file
if (format.indexOf("/") > -1) {
const cwd = this.options ? this.options.cwd : process.cwd();
if (!namespace && format.indexOf("/") > -1) {
formatterPath = path.resolve(cwd, format);
} else {
formatterPath = `./formatters/${format}`;
try {
const npmFormat = naming.normalizePackageName(format, "eslint-formatter");
formatterPath = resolver.resolve(npmFormat, `${cwd}/node_modules`);
} catch (e) {
formatterPath = `./formatters/${format}`;
}
}
try {
@@ -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.
@@ -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;
@@ -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();
}
+12 -8
View File
@@ -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 });
}
+14 -12
View File
@@ -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]
+8 -51
View File
@@ -13,11 +13,11 @@ const fs = require("fs"),
path = require("path"),
ConfigOps = require("./config-ops"),
validator = require("./config-validator"),
pathUtil = require("../util/path-util"),
ModuleResolver = require("../util/module-resolver"),
naming = require("../util/naming"),
pathIsInside = require("path-is-inside"),
stripComments = require("strip-json-comments"),
stringify = require("json-stable-stringify"),
stringify = require("json-stable-stringify-without-jsonify"),
requireUncached = require("require-uncached");
const debug = require("debug")("eslint:config-file");
@@ -29,7 +29,7 @@ const debug = require("debug")("eslint:config-file");
/**
* Determines sort order for object keys for json-stable-stringify
*
* see: https://github.com/substack/json-stable-stringify#cmp
* see: https://github.com/samn/json-stable-stringify#cmp
*
* @param {Object} a The first comparison object ({key: akey, value: avalue})
* @param {Object} b The second comparison object ({key: bkey, value: bvalue})
@@ -436,50 +436,6 @@ function applyExtends(config, configContext, filePath, relativeTo) {
return config;
}
/**
* Brings package name to correct format based on prefix
* @param {string} name The name of the package.
* @param {string} prefix Can be either "eslint-plugin" or "eslint-config
* @returns {string} Normalized name of the package
* @private
*/
function normalizePackageName(name, prefix) {
/*
* On Windows, name can come in with Windows slashes instead of Unix slashes.
* Normalize to Unix first to avoid errors later on.
* https://github.com/eslint/eslint/issues/5644
*/
if (name.indexOf("\\") > -1) {
name = pathUtil.convertPathToPosix(name);
}
if (name.charAt(0) === "@") {
/*
* it's a scoped package
* package name is "eslint-config", or just a username
*/
const scopedPackageShortcutRegex = new RegExp(`^(@[^/]+)(?:/(?:${prefix})?)?$`),
scopedPackageNameRegex = new RegExp(`^${prefix}(-|$)`);
if (scopedPackageShortcutRegex.test(name)) {
name = name.replace(scopedPackageShortcutRegex, `$1/${prefix}`);
} else if (!scopedPackageNameRegex.test(name.split("/")[1])) {
/*
* for scoped packages, insert the eslint-config after the first / unless
* the path is already @scope/eslint or @scope/eslint-config-xxx
*/
name = name.replace(/^@([^/]+)\/(.*)$/, `@$1/${prefix}-$2`);
}
} else if (name.indexOf(`${prefix}-`) !== 0) {
name = `${prefix}-${name}`;
}
return name;
}
/**
* Resolves a configuration file path into the fully-formed path, whether filename
* or package name.
@@ -505,12 +461,12 @@ function resolve(filePath, relativeTo) {
const pluginName = filePath.slice(7, filePath.lastIndexOf("/"));
const configName = filePath.slice(filePath.lastIndexOf("/") + 1);
normalizedPackageName = normalizePackageName(pluginName, "eslint-plugin");
normalizedPackageName = naming.normalizePackageName(pluginName, "eslint-plugin");
debug(`Attempting to resolve ${normalizedPackageName}`);
filePath = resolver.resolve(normalizedPackageName, getLookupPath(relativeTo));
return { filePath, configName, configFullName };
}
normalizedPackageName = normalizePackageName(filePath, "eslint-config");
normalizedPackageName = naming.normalizePackageName(filePath, "eslint-config");
debug(`Attempting to resolve ${normalizedPackageName}`);
filePath = resolver.resolve(normalizedPackageName, getLookupPath(relativeTo));
return { filePath, configFullName: filePath };
@@ -545,8 +501,10 @@ function loadFromDisk(resolvedPath, configContext) {
}
}
const ruleMap = configContext.linterContext.getRules();
// validate the configuration before continuing
validator.validate(config, resolvedPath.configFullName, configContext.linterContext.rules, configContext.linterContext.environments);
validator.validate(config, resolvedPath.configFullName, ruleMap.get.bind(ruleMap), configContext.linterContext.environments);
/*
* If an `extends` property is defined, it represents a configuration file to use as
@@ -614,7 +572,6 @@ module.exports = {
resolve,
write,
applyExtends,
normalizePackageName,
CONFIG_FILES,
/**
+10 -6
View File
@@ -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
+21 -21
View File
@@ -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.
*/
/*
+24 -24
View File
@@ -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();
+37 -35
View File
@@ -14,9 +14,7 @@ const ajv = require("../util/ajv"),
configSchema = require("../../conf/config-schema.js"),
util = require("util");
const validators = {
rules: Object.create(null)
};
const ruleValidators = new WeakMap();
//------------------------------------------------------------------------------
// Private
@@ -25,13 +23,11 @@ let validateSchema;
/**
* Gets a complete options schema for a rule.
* @param {string} id The rule's unique name.
* @param {Rules} rulesContext Rule context
* @param {{create: Function, schema: (Array|null)}} rule A new-style rule object
* @returns {Object} JSON Schema for the rule's options.
*/
function getRuleOptionsSchema(id, rulesContext) {
const rule = rulesContext.get(id),
schema = rule && rule.schema || rule && rule.meta && rule.meta.schema;
function getRuleOptionsSchema(rule) {
const schema = rule.schema || rule.meta && rule.meta.schema;
// Given a tuple of schemas, insert warning level at the beginning
if (Array.isArray(schema)) {
@@ -56,10 +52,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,46 +67,52 @@ 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}
*/
function validateRuleSchema(id, localOptions, rulesContext) {
const schema = getRuleOptionsSchema(id, rulesContext);
* Validates the non-severity options passed to a rule, based on its schema.
* @param {{create: Function}} rule The rule to validate
* @param {array} localOptions The options for the rule, excluding severity
* @returns {void}
*/
function validateRuleSchema(rule, localOptions) {
if (!ruleValidators.has(rule)) {
const schema = getRuleOptionsSchema(rule);
if (!validators.rules[id] && schema) {
validators.rules[id] = ajv.compile(schema);
if (schema) {
ruleValidators.set(rule, ajv.compile(schema));
}
}
const validateRule = validators.rules[id];
const validateRule = ruleValidators.get(rule);
if (validateRule) {
validateRule(localOptions);
if (validateRule.errors) {
throw new Error(validateRule.errors.map(error => `\tValue "${error.data}" ${error.message}.\n`).join(""));
throw new Error(validateRule.errors.map(
error => `\tValue ${JSON.stringify(error.data)} ${error.message}.\n`
).join(""));
}
}
}
/**
* Validates a rule's options against its schema.
* @param {string} id The rule's unique name.
* @param {{create: Function}|null} rule The rule that the config is being validated for
* @param {string} ruleId The rule's unique name.
* @param {array|number} options The given options for the rule.
* @param {string} source The name of the configuration source to report in any errors.
* @param {Rules} rulesContext Rule context
* @returns {void}
*/
function validateRuleOptions(id, options, source, rulesContext) {
function validateRuleOptions(rule, ruleId, options, source) {
if (!rule) {
return;
}
try {
const severity = validateRuleSeverity(options);
if (severity !== 0 && !(typeof severity === "string" && severity.toLowerCase() === "off")) {
validateRuleSchema(id, Array.isArray(options) ? options.slice(1) : [], rulesContext);
validateRuleSchema(rule, Array.isArray(options) ? options.slice(1) : []);
}
} catch (err) {
throw new Error(`${source}:\n\tConfiguration for rule "${id}" is invalid:\n${err.message}`);
throw new Error(`${source}:\n\tConfiguration for rule "${ruleId}" is invalid:\n${err.message}`);
}
}
@@ -141,16 +143,16 @@ function validateEnvironment(environment, source, envContext) {
* Validates a rules config object
* @param {Object} rulesConfig The rules config object to validate.
* @param {string} source The name of the configuration source to report in any errors.
* @param {Rules} rulesContext Rule context
* @param {function(string): {create: Function}} ruleMapper A mapper function from strings to loaded rules
* @returns {void}
*/
function validateRules(rulesConfig, source, rulesContext) {
function validateRules(rulesConfig, source, ruleMapper) {
if (!rulesConfig) {
return;
}
Object.keys(rulesConfig).forEach(id => {
validateRuleOptions(id, rulesConfig[id], source, rulesContext);
validateRuleOptions(ruleMapper(id), id, rulesConfig[id], source);
});
}
@@ -221,13 +223,13 @@ function validateConfigSchema(config, source) {
* Validates an entire config object.
* @param {Object} config The config object to validate.
* @param {string} source The name of the configuration source to report in any errors.
* @param {Rules} rulesContext The rules context
* @param {function(string): {create: Function}} ruleMapper A mapper function from rule IDs to defined rules
* @param {Environments} envContext The env context
* @returns {void}
*/
function validate(config, source, rulesContext, envContext) {
function validate(config, source, ruleMapper, envContext) {
validateConfigSchema(config, source);
validateRules(config.rules, source, rulesContext);
validateRules(config.rules, source, ruleMapper);
validateEnvironment(config.env, source, envContext);
}
+8 -35
View File
@@ -9,13 +9,13 @@
//------------------------------------------------------------------------------
const debug = require("debug")("eslint:plugins");
const naming = require("../util/naming");
//------------------------------------------------------------------------------
// Private
//------------------------------------------------------------------------------
const PLUGIN_NAME_PREFIX = "eslint-plugin-",
NAMESPACE_REGEX = /^@.*\//i;
const PLUGIN_NAME_PREFIX = "eslint-plugin-";
//------------------------------------------------------------------------------
// Public Interface
@@ -37,33 +37,6 @@ class Plugins {
this._rules = rulesContext;
}
/**
* Removes the prefix `eslint-plugin-` from a plugin name.
* @param {string} pluginName The name of the plugin which may have the prefix.
* @returns {string} The name of the plugin without prefix.
*/
static removePrefix(pluginName) {
return pluginName.startsWith(PLUGIN_NAME_PREFIX) ? pluginName.slice(PLUGIN_NAME_PREFIX.length) : pluginName;
}
/**
* Gets the scope (namespace) of a plugin.
* @param {string} pluginName The name of the plugin which may have the prefix.
* @returns {string} The name of the plugins namepace if it has one.
*/
static getNamespace(pluginName) {
return pluginName.match(NAMESPACE_REGEX) ? pluginName.match(NAMESPACE_REGEX)[0] : "";
}
/**
* Removes the namespace from a plugin name.
* @param {string} pluginName The name of the plugin which may have the prefix.
* @returns {string} The name of the plugin without the namespace.
*/
static removeNamespace(pluginName) {
return pluginName.replace(NAMESPACE_REGEX, "");
}
/**
* Defines a plugin with a given name rather than loading from disk.
* @param {string} pluginName The name of the plugin to load.
@@ -71,9 +44,9 @@ class Plugins {
* @returns {void}
*/
define(pluginName, plugin) {
const pluginNamespace = Plugins.getNamespace(pluginName),
pluginNameWithoutNamespace = Plugins.removeNamespace(pluginName),
pluginNameWithoutPrefix = Plugins.removePrefix(pluginNameWithoutNamespace),
const pluginNamespace = naming.getNamespaceFromTerm(pluginName),
pluginNameWithoutNamespace = naming.removeNamespaceFromTerm(pluginName),
pluginNameWithoutPrefix = naming.removePrefixFromTerm(PLUGIN_NAME_PREFIX, pluginNameWithoutNamespace),
shortName = pluginNamespace + pluginNameWithoutPrefix;
// load up environments and rules
@@ -106,9 +79,9 @@ class Plugins {
* @throws {Error} If the plugin cannot be loaded.
*/
load(pluginName) {
const pluginNamespace = Plugins.getNamespace(pluginName),
pluginNameWithoutNamespace = Plugins.removeNamespace(pluginName),
pluginNameWithoutPrefix = Plugins.removePrefix(pluginNameWithoutNamespace),
const pluginNamespace = naming.getNamespaceFromTerm(pluginName),
pluginNameWithoutNamespace = naming.removeNamespaceFromTerm(pluginName),
pluginNameWithoutPrefix = naming.removePrefixFromTerm(PLUGIN_NAME_PREFIX, pluginNameWithoutNamespace),
shortName = pluginNamespace + pluginNameWithoutPrefix,
longName = pluginNamespace + PLUGIN_NAME_PREFIX + pluginNameWithoutPrefix;
let plugin = null;
+1 -1
View File
@@ -32,7 +32,7 @@ module.exports = function(results) {
let output = "";
output += "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
output += "<?xml version=\"1.1\" encoding=\"utf-8\"?>";
output += "<checkstyle version=\"4.3\">";
results.forEach(result => {
+1 -1
View File
@@ -14,7 +14,7 @@ module.exports = function(results) {
let output = "";
output += "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
output += "<?xml version=\"1.1\" encoding=\"utf-8\"?>";
output += "<jslint>";
results.forEach(result => {
+22 -16
View File
@@ -32,29 +32,35 @@ module.exports = function(results) {
let output = "";
output += "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
output += "<?xml version=\"1.1\" encoding=\"utf-8\"?>\n";
output += "<testsuites>\n";
results.forEach(result => {
const messages = result.messages;
output += `<testsuite package="org.eslint" time="0" tests="${messages.length}" errors="${messages.length}" name="${result.filePath}">\n`;
messages.forEach(message => {
const type = message.fatal ? "error" : "failure";
if (messages.length > 0) {
output += `<testsuite package="org.eslint" time="0" tests="${messages.length}" errors="${messages.length}" name="${result.filePath}">\n`;
messages.forEach(message => {
const type = message.fatal ? "error" : "failure";
output += `<testcase time="0" name="org.eslint.${message.ruleId || "unknown"}">`;
output += `<${type} message="${xmlEscape(message.message || "")}">`;
output += "<![CDATA[";
output += `line ${message.line || 0}, col `;
output += `${message.column || 0}, ${getMessageType(message)}`;
output += ` - ${xmlEscape(message.message || "")}`;
output += (message.ruleId ? ` (${message.ruleId})` : "");
output += "]]>";
output += `</${type}>`;
output += "</testcase>\n";
});
output += "</testsuite>\n";
output += `<testcase time="0" name="org.eslint.${message.ruleId || "unknown"}">`;
output += `<${type} message="${xmlEscape(message.message || "")}">`;
output += "<![CDATA[";
output += `line ${message.line || 0}, col `;
output += `${message.column || 0}, ${getMessageType(message)}`;
output += ` - ${xmlEscape(message.message || "")}`;
output += (message.ruleId ? ` (${message.ruleId})` : "");
output += "]]>";
output += `</${type}>`;
output += "</testcase>\n";
});
output += "</testsuite>\n";
} else {
output += `<testsuite package="org.eslint" time="0" tests="1" errors="0" name="${result.filePath}">\n`;
output += `<testcase time="0" name="${result.filePath}" />\n`;
output += "</testsuite>\n";
}
});
+5 -3
View File
@@ -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 = [];
+4 -2
View File
@@ -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 = [];
+45 -32
View File
@@ -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 {
@@ -276,7 +278,7 @@ function createDisableDirectives(type, loc, value) {
* @param {string} filename The file being checked.
* @param {ASTNode} ast The top node of the AST.
* @param {Object} config The existing configuration data.
* @param {Linter} linterContext Linter context object
* @param {function(string): {create: Function}} ruleMapper A map from rule IDs to defined rules
* @returns {{
* config: Object,
* problems: Problem[],
@@ -289,7 +291,7 @@ function createDisableDirectives(type, loc, value) {
* }} Modified config object, along with any problems encountered
* while parsing config comments
*/
function modifyConfigsFromComments(filename, ast, config, linterContext) {
function modifyConfigsFromComments(filename, ast, config, ruleMapper) {
const commentConfig = {
exported: {},
@@ -335,7 +337,7 @@ function modifyConfigsFromComments(filename, ast, config, linterContext) {
Object.keys(parseResult.config).forEach(name => {
const ruleValue = parseResult.config[name];
validator.validateRuleOptions(name, ruleValue, `${filename} line ${comment.loc.start.line}`, linterContext.rules);
validator.validateRuleOptions(ruleMapper(name), name, ruleValue, `${filename} line ${comment.loc.start.line}`);
commentRules[name] = ruleValue;
});
} else {
@@ -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;
}
@@ -503,13 +507,13 @@ function getRuleOptions(ruleConfig) {
* as possible
* @param {string} text The text to parse.
* @param {Object} providedParserOptions Options to pass to the parser
* @param {string} parserName The name of the parser
* @param {Object} parser The parser module
* @param {string} filePath The path to the file being parsed.
* @returns {{success: false, error: Problem}|{success: true,ast: ASTNode, services: Object}}
* An object containing the AST and parser services if parsing was successful, or the error if parsing failed
* @private
*/
function parse(text, providedParserOptions, parserName, filePath) {
function parse(text, providedParserOptions, parser, filePath) {
const parserOptions = Object.assign({}, providedParserOptions, {
loc: true,
@@ -520,25 +524,6 @@ function parse(text, providedParserOptions, parserName, filePath) {
filePath
});
let parser;
try {
parser = require(parserName);
} catch (ex) {
return {
success: false,
error: {
ruleId: null,
fatal: true,
severity: 2,
source: null,
message: ex.message,
line: 0,
column: 0
}
};
}
/*
* Check for parsing errors first. If there's a parsing error, nothing
* else can happen. However, a parsing error does not throw an error
@@ -702,6 +687,7 @@ module.exports = class Linter {
this.version = pkg.version;
this.rules = new Rules();
this._parsers = new Map();
this.environments = new Environments();
}
@@ -781,10 +767,25 @@ module.exports = class Linter {
return [];
}
let parser;
try {
parser = this._parsers.get(config.parser) || require(config.parser);
} catch (ex) {
return [{
ruleId: null,
fatal: true,
severity: 2,
source: null,
message: ex.message,
line: 0,
column: 0
}];
}
const parseResult = parse(
stripUnicodeBOM(text).replace(astUtils.SHEBANG_MATCHER, (match, captured) => `//${captured}`),
config.parserOptions,
config.parser,
parser,
filename
);
@@ -802,7 +803,7 @@ module.exports = class Linter {
// parse global comments and modify config
if (allowInlineConfig !== false) {
const modifyConfigResult = modifyConfigsFromComments(filename, sourceCode.ast, config, this);
const modifyConfigResult = modifyConfigsFromComments(filename, sourceCode.ast, config, ruleId => this.rules.get(ruleId));
config = modifyConfigResult.config;
modifyConfigResult.problems.forEach(problem => problems.push(problem));
@@ -1032,6 +1033,16 @@ module.exports = class Linter {
return this.rules.getAllLoadedRules();
}
/**
* Define a new parser module
* @param {any} parserId Name of the parser
* @param {any} parserModule The parser object
* @returns {void}
*/
defineParser(parserId, parserModule) {
this._parsers.set(parserId, parserModule);
}
/**
* Performs multiple autofix passes over the text until as many fixes as possible
* have been applied.
@@ -1076,8 +1087,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;
}
+2 -2
View File
@@ -1,3 +1,3 @@
rules:
internal-no-invalid-meta: "error"
internal-consistent-docs-description: "error"
rulesdir/no-invalid-meta: "error"
rulesdir/consistent-docs-description: "error"
+20 -20
View File
@@ -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,
+28 -28
View File
@@ -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");
}
@@ -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 (
@@ -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 });
+12 -6
View File
@@ -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));
}
+4 -2
View File
@@ -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]);
+14 -14
View File
@@ -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);
@@ -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,
+4 -4
View File
@@ -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 &&
+4 -2
View File
@@ -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;
+13 -9
View File
@@ -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 }));
+5 -5
View File
@@ -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) &&
+4 -2
View File
@@ -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]]);
}
+2 -1
View File
@@ -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.
*/
@@ -0,0 +1,86 @@
/**
* @fileoverview enforce the location of arrow function bodies
* @author Sharmila Jesupaul
*/
"use strict";
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
module.exports = {
meta: {
docs: {
description: "enforce the location of arrow function bodies",
category: "Stylistic Issues",
recommended: false
},
fixable: "whitespace",
schema: [
{
enum: ["beside", "below"]
}
]
},
create(context) {
const sourceCode = context.getSourceCode();
//----------------------------------------------------------------------
// Helpers
//----------------------------------------------------------------------
/**
* Gets the applicable preference for a particular keyword
* @returns {string} The applicable option for the keyword, e.g. 'beside'
*/
function getOption() {
return context.options[0] || "beside";
}
/**
* Validates the location of an arrow function body
* @param {ASTNode} node The arrow function body
* @param {string} keywordName The applicable keyword name for the arrow function body
* @returns {void}
*/
function validateExpression(node) {
const option = getOption();
let tokenBefore = sourceCode.getTokenBefore(node.body);
const hasParens = tokenBefore.value === "(";
if (node.type === "BlockStatement") {
return;
}
let fixerTarget = node.body;
if (hasParens) {
// Gets the first token before the function body that is not an open paren
tokenBefore = sourceCode.getTokenBefore(node.body, token => token.value !== "(");
fixerTarget = sourceCode.getTokenAfter(tokenBefore);
}
if (tokenBefore.loc.end.line === fixerTarget.loc.start.line && option === "below") {
context.report({
node: fixerTarget,
message: "Expected a linebreak before this expression.",
fix: fixer => fixer.insertTextBefore(fixerTarget, "\n")
});
} else if (tokenBefore.loc.end.line !== fixerTarget.loc.start.line && option === "beside") {
context.report({
node: fixerTarget,
message: "Expected no linebreak before this expression.",
fix: fixer => fixer.replaceTextRange([tokenBefore.range[1], fixerTarget.range[0]], " ")
});
}
}
//----------------------------------------------------------------------
// Public
//----------------------------------------------------------------------
return {
ArrowFunctionExpression: node => validateExpression(node)
};
}
};
+20 -12
View File
@@ -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;
}
+77 -73
View File
@@ -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);
+5 -3
View File
@@ -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 (
@@ -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;
}
@@ -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
) {
+8 -6
View File
@@ -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;
}
@@ -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;
+17 -9
View File
@@ -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) ||
+5 -3
View File
@@ -5,9 +5,11 @@
"use strict";
//
// Set of bitwise operators.
//
/*
*
* Set of bitwise operators.
*
*/
const BITWISE_OPERATORS = [
"^", "|", "&", "<<", ">>", ">>>",
"^=", "|=", "&=", "<<=", ">>=", ">>>=",
+4 -2
View File
@@ -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;
}
+2 -1
View File
@@ -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'.
*/
+17 -11
View File
@@ -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);
@@ -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]*$/;
//------------------------------------------------------------------------------
+16 -8
View File
@@ -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)
)
+5 -3
View File
@@ -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);
+4 -2
View File
@@ -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({
@@ -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;
+2 -1
View File
@@ -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.
*/
+4 -2
View File
@@ -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." });
}
+3 -3
View File
@@ -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;
+8 -4
View File
@@ -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
+4 -2
View File
@@ -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({
+4 -2
View File
@@ -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()) {
+1 -1
View File
@@ -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
*/
+137 -28
View File
@@ -8,8 +8,8 @@
// Helpers
//------------------------------------------------------------------------------
const DEFAULT_MESSAGE_TEMPLATE = "'{{importName}}' import is restricted from being used.";
const CUSTOM_MESSAGE_TEMPLATE = "'{{importName}}' import is restricted from being used. {{customMessage}}";
const DEFAULT_MESSAGE_TEMPLATE = "'{{importSource}}' import is restricted from being used.";
const CUSTOM_MESSAGE_TEMPLATE = "'{{importSource}}' import is restricted from being used. {{customMessage}}";
//------------------------------------------------------------------------------
// Rule Definition
@@ -35,6 +35,12 @@ const arrayOfStringsOrObjects = {
message: {
type: "string",
minLength: 1
},
importNames: {
type: "array",
items: {
type: "string"
}
}
},
additionalProperties: false,
@@ -81,11 +87,14 @@ module.exports = {
const restrictedPaths = (isPathAndPatternsObject ? options[0].paths : context.options) || [];
const restrictedPatterns = (isPathAndPatternsObject ? options[0].patterns : []) || [];
const restrictedPathMessages = restrictedPaths.reduce((memo, importName) => {
if (typeof importName === "string") {
memo[importName] = null;
const restrictedPathMessages = restrictedPaths.reduce((memo, importSource) => {
if (typeof importSource === "string") {
memo[importSource] = { message: null };
} else {
memo[importName.name] = importName.message;
memo[importSource.name] = {
message: importSource.message,
importNames: importSource.importNames
};
}
return memo;
}, {});
@@ -95,7 +104,16 @@ module.exports = {
return {};
}
const ig = ignore().add(restrictedPatterns);
const restrictedPatternsMatcher = ignore().add(restrictedPatterns);
/**
* Checks to see if "*" is being used to import everything.
* @param {Set.<string>} importNames - Set of import names that are being imported
* @returns {boolean} whether everything is imported or not
*/
function isEverythingImported(importNames) {
return importNames.has("*");
}
/**
* Report a restricted path.
@@ -104,8 +122,8 @@ module.exports = {
* @private
*/
function reportPath(node) {
const importName = node.source.value.trim();
const customMessage = restrictedPathMessages[importName];
const importSource = node.source.value.trim();
const customMessage = restrictedPathMessages[importSource] && restrictedPathMessages[importSource].message;
const message = customMessage
? CUSTOM_MESSAGE_TEMPLATE
: DEFAULT_MESSAGE_TEMPLATE;
@@ -114,39 +132,130 @@ module.exports = {
node,
message,
data: {
importName,
importSource,
customMessage
}
});
}
/**
* Check if the given name is a restricted path name.
* @param {string} name name of a variable
* Report a restricted path specifically for patterns.
* @param {node} node - representing the restricted path reference
* @returns {void}
* @private
*/
function reportPathForPatterns(node) {
const importSource = node.source.value.trim();
context.report({
node,
message: "'{{importSource}}' import is restricted from being used by a pattern.",
data: {
importSource
}
});
}
/**
* Report a restricted path specifically when using the '*' import.
* @param {string} importSource - path of the import
* @param {node} node - representing the restricted path reference
* @returns {void}
* @private
*/
function reportPathForEverythingImported(importSource, node) {
const importNames = restrictedPathMessages[importSource].importNames;
context.report({
node,
message: "* import is invalid because '{{importNames}}' from '{{importSource}}' is restricted.",
data: {
importSource,
importNames
}
});
}
/**
* Check if the given importSource is restricted because '*' is being imported.
* @param {string} importSource - path of the import
* @param {Set.<string>} importNames - Set of import names that are being imported
* @returns {boolean} whether the path is restricted
* @private
*/
function isRestrictedForEverythingImported(importSource, importNames) {
return Object.prototype.hasOwnProperty.call(restrictedPathMessages, importSource) &&
restrictedPathMessages[importSource].importNames &&
isEverythingImported(importNames);
}
/**
* Check if the given importNames are restricted given a list of restrictedImportNames.
* @param {Set.<string>} importNames - Set of import names that are being imported
* @param {[string]} restrictedImportNames - array of import names that are restricted for this import
* @returns {boolean} whether the objectName is restricted
* @private
*/
function isRestrictedObject(importNames, restrictedImportNames) {
return restrictedImportNames.some(restrictedObjectName => (
importNames.has(restrictedObjectName)
));
}
/**
* Check if the given importSource is a restricted path.
* @param {string} importSource - path of the import
* @param {Set.<string>} importNames - Set of import names that are being imported
* @returns {boolean} whether the variable is a restricted path or not
* @private
*/
function isRestrictedPath(name) {
return Object.prototype.hasOwnProperty.call(restrictedPathMessages, name);
function isRestrictedPath(importSource, importNames) {
let isRestricted = false;
if (Object.prototype.hasOwnProperty.call(restrictedPathMessages, importSource)) {
if (restrictedPathMessages[importSource].importNames) {
isRestricted = isRestrictedObject(importNames, restrictedPathMessages[importSource].importNames);
} else {
isRestricted = true;
}
}
return isRestricted;
}
/**
* Check if the given importSource is restricted by a pattern.
* @param {string} importSource - path of the import
* @returns {boolean} whether the variable is a restricted pattern or not
* @private
*/
function isRestrictedPattern(importSource) {
return restrictedPatterns.length > 0 && restrictedPatternsMatcher.ignores(importSource);
}
return {
ImportDeclaration(node) {
if (node && node.source && node.source.value) {
const importName = node.source.value.trim();
const importSource = node.source.value.trim();
const importNames = node.specifiers.reduce((set, specifier) => {
if (specifier.type === "ImportDefaultSpecifier") {
set.add("default");
} else if (specifier.type === "ImportNamespaceSpecifier") {
set.add("*");
} else {
set.add(specifier.imported.name);
}
return set;
}, new Set());
if (isRestrictedPath(importName)) {
reportPath(node);
}
if (restrictedPatterns.length > 0 && ig.ignores(importName)) {
context.report({
node,
message: "'{{importName}}' import is restricted from being used by a pattern.",
data: {
importName
}
});
}
if (isRestrictedForEverythingImported(importSource, importNames)) {
reportPathForEverythingImported(importSource, node);
}
if (isRestrictedPath(importSource, importNames)) {
reportPath(node);
}
if (isRestrictedPattern(importSource)) {
reportPathForPatterns(node);
}
}
};
@@ -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;
+6 -6
View File
@@ -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;
+4 -2
View File
@@ -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) {
+6 -4
View File
@@ -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
*/
};
/**
+13 -7
View File
@@ -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;
+4 -2
View File
@@ -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.",
+13 -11
View File
@@ -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 ||
+1 -25
View File
@@ -28,30 +28,6 @@ function isCallOrNonVariadicApply(node) {
);
}
/**
* Checks whether or not the tokens of two given nodes are same.
* @param {ASTNode} left - A node 1 to compare.
* @param {ASTNode} right - A node 2 to compare.
* @param {SourceCode} sourceCode - The ESLint source code object.
* @returns {boolean} the source code for the given node.
*/
function equalTokens(left, right, sourceCode) {
const tokensL = sourceCode.getTokens(left);
const tokensR = sourceCode.getTokens(right);
if (tokensL.length !== tokensR.length) {
return false;
}
for (let i = 0; i < tokensL.length; ++i) {
if (tokensL[i].type !== tokensR[i].type ||
tokensL[i].value !== tokensR[i].value
) {
return false;
}
}
return true;
}
/**
* Checks whether or not `thisArg` is not changed by `.call()`/`.apply()`.
@@ -64,7 +40,7 @@ function isValidThisArg(expectedThis, thisArg, sourceCode) {
if (!expectedThis) {
return astUtils.isNullOrUndefined(thisArg);
}
return equalTokens(expectedThis, thisArg, sourceCode);
return astUtils.equalTokens(expectedThis, thisArg, sourceCode);
}
//------------------------------------------------------------------------------
+23 -22
View File
@@ -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.
*/
+14 -8
View File
@@ -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,
@@ -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);
@@ -131,8 +131,15 @@ module.exports = {
*/
function check(node) {
const options = normalizedOptions[node.type];
const openBrace = sourceCode.getFirstToken(node);
const closeBrace = sourceCode.getLastToken(node);
const openBrace = sourceCode.getFirstToken(node, token => token.value === "{");
let closeBrace;
if (node.typeAnnotation) {
closeBrace = sourceCode.getTokenBefore(node.typeAnnotation);
} else {
closeBrace = sourceCode.getLastToken(node);
}
let first = sourceCode.getTokenAfter(openBrace, { includeComments: true });
let last = sourceCode.getTokenBefore(closeBrace, { includeComments: true });
const needsLinebreaks = (
+20 -20
View File
@@ -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,
+41 -33
View File
@@ -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));
}
@@ -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);
}
+12 -10
View File
@@ -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);
@@ -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;
}
+12 -10
View File
@@ -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;
}
+18 -10
View File
@@ -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 => {
@@ -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",
@@ -143,7 +145,7 @@ module.exports = {
* @returns {void}
*/
function performCheck(leftNode, rightNode, reportNode) {
if (rightNode.type !== "MemberExpression") {
if (rightNode.type !== "MemberExpression" || rightNode.object.type === "Super") {
return;
}
@@ -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);
@@ -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.
+4 -2
View File
@@ -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;
}
}
+1 -25
View File
@@ -28,30 +28,6 @@ function isVariadicApplyCalling(node) {
);
}
/**
* Checks whether or not the tokens of two given nodes are same.
* @param {ASTNode} left - A node 1 to compare.
* @param {ASTNode} right - A node 2 to compare.
* @param {SourceCode} sourceCode - The ESLint source code object.
* @returns {boolean} the source code for the given node.
*/
function equalTokens(left, right, sourceCode) {
const tokensL = sourceCode.getTokens(left);
const tokensR = sourceCode.getTokens(right);
if (tokensL.length !== tokensR.length) {
return false;
}
for (let i = 0; i < tokensL.length; ++i) {
if (tokensL[i].type !== tokensR[i].type ||
tokensL[i].value !== tokensR[i].value
) {
return false;
}
}
return true;
}
/**
* Checks whether or not `thisArg` is not changed by `.apply()`.
@@ -64,7 +40,7 @@ function isValidThisArg(expectedThis, thisArg, context) {
if (!expectedThis) {
return astUtils.isNullOrUndefined(thisArg);
}
return equalTokens(expectedThis, thisArg, context);
return astUtils.equalTokens(expectedThis, thisArg, context);
}
//------------------------------------------------------------------------------
+33 -29
View File
@@ -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)}`;
}
+8 -8
View File
@@ -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") {
+44 -19
View File
@@ -18,13 +18,51 @@ const astUtils = require("../ast-utils");
const SELECTOR = `:matches(${
[
"BreakStatement", "ContinueStatement", "DebuggerStatement",
"DoWhileStatement", "EmptyStatement", "ExportAllDeclaration",
"DoWhileStatement", "ExportAllDeclaration",
"ExportDefaultDeclaration", "ExportNamedDeclaration",
"ExpressionStatement", "ImportDeclaration", "ReturnStatement",
"ThrowStatement", "VariableDeclaration"
].join(",")
})`;
/**
* Get the child node list of a given node.
* This returns `Program#body`, `BlockStatement#body`, or `SwitchCase#consequent`.
* This is used to check whether a node is the first/last child.
* @param {Node} node A node to get child node list.
* @returns {Node[]|null} The child node list.
*/
function getChildren(node) {
const t = node.type;
if (t === "BlockStatement" || t === "Program") {
return node.body;
}
if (t === "SwitchCase") {
return node.consequent;
}
return null;
}
/**
* Check whether a given node is the last statement in the parent block.
* @param {Node} node A node to check.
* @returns {boolean} `true` if the node is the last statement in the parent block.
*/
function isLastChild(node) {
const t = node.parent.type;
if (t === "IfStatement" && node.parent.consequent === node && node.parent.alternate) { // before `else` keyword.
return true;
}
if (t === "DoWhileStatement") { // before `while` keyword.
return true;
}
const nodeList = getChildren(node.parent);
return nodeList !== null && nodeList[nodeList.length - 1] === node; // before `}` or etc.
}
module.exports = {
meta: {
docs: {
@@ -40,23 +78,6 @@ module.exports = {
const sourceCode = context.getSourceCode();
const option = context.options[0] || "last";
/**
* Check whether comments exist between the given 2 tokens.
* @param {Token} left The left token to check.
* @param {Token} right The right token to check.
* @returns {boolean} `true` if comments exist between the given 2 tokens.
*/
function commentsExistBetween(left, right) {
return sourceCode.getFirstTokenBetween(
left,
right,
{
includeComments: true,
filter: astUtils.isCommentToken
}
) !== null;
}
/**
* Check the given semicolon token.
* @param {Token} semiToken The semicolon token to check.
@@ -79,7 +100,7 @@ module.exports = {
: "the beginning of the next line"
},
fix(fixer) {
if (prevToken && nextToken && commentsExistBetween(prevToken, nextToken)) {
if (prevToken && nextToken && sourceCode.commentsExistBetween(prevToken, nextToken)) {
return null;
}
@@ -95,6 +116,10 @@ module.exports = {
return {
[SELECTOR](node) {
if (option === "first" && isLastChild(node)) {
return;
}
const lastToken = sourceCode.getLastToken(node);
if (astUtils.isSemicolonToken(lastToken)) {
+138 -41
View File
@@ -32,10 +32,19 @@ module.exports = {
items: [
{
enum: ["never"]
},
{
type: "object",
properties: {
beforeStatementContinuationChars: {
enum: ["always", "any", "never"]
}
},
additionalProperties: false
}
],
minItems: 0,
maxItems: 1
maxItems: 2
},
{
type: "array",
@@ -62,9 +71,10 @@ module.exports = {
const OPT_OUT_PATTERN = /^[-[(/+`]/; // One of [(/+-`
const options = context.options[1];
const never = context.options[0] === "never",
exceptOneLine = options && options.omitLastInOneLineBlock === true,
sourceCode = context.getSourceCode();
const never = context.options[0] === "never";
const exceptOneLine = Boolean(options && options.omitLastInOneLineBlock);
const beforeStatementContinuationChars = (options && options.beforeStatementContinuationChars) || "any";
const sourceCode = context.getSourceCode();
//--------------------------------------------------------------------------
// Helpers
@@ -93,9 +103,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);
@@ -112,29 +124,115 @@ module.exports = {
}
/**
* Check if a semicolon is unnecessary, only true if:
* - next token is on a new line and is not one of the opt-out tokens
* - next token is a valid statement divider
* @param {Token} lastToken last token of current node.
* @returns {boolean} whether the semicolon is unnecessary.
* Check whether a given semicolon token is redandant.
* @param {Token} semiToken A semicolon token to check.
* @returns {boolean} `true` if the next token is `;` or `}`.
*/
function isUnnecessarySemicolon(lastToken) {
if (!astUtils.isSemicolonToken(lastToken)) {
function isRedundantSemi(semiToken) {
const nextToken = sourceCode.getTokenAfter(semiToken);
return (
!nextToken ||
astUtils.isClosingBraceToken(nextToken) ||
astUtils.isSemicolonToken(nextToken)
);
}
/**
* Check whether a given token is the closing brace of an arrow function.
* @param {Token} lastToken A token to check.
* @returns {boolean} `true` if the token is the closing brace of an arrow function.
*/
function isEndOfArrowBlock(lastToken) {
if (!astUtils.isClosingBraceToken(lastToken)) {
return false;
}
const node = sourceCode.getNodeByRangeIndex(lastToken.range[0]);
return (
node.type === "BlockStatement" &&
node.parent.type === "ArrowFunctionExpression"
);
}
/**
* Check whether a given node is on the same line with the next token.
* @param {Node} node A statement node to check.
* @returns {boolean} `true` if the node is on the same line with the next token.
*/
function isOnSameLineWithNextToken(node) {
const prevToken = sourceCode.getLastToken(node, 1);
const nextToken = sourceCode.getTokenAfter(node);
return !!nextToken && astUtils.isTokenOnSameLine(prevToken, nextToken);
}
/**
* Check whether a given node can connect the next line if the next line is unreliable.
* @param {Node} node A statement node to check.
* @returns {boolean} `true` if the node can connect the next line.
*/
function maybeAsiHazardAfter(node) {
const t = node.type;
if (t === "DoWhileStatement" ||
t === "BreakStatement" ||
t === "ContinueStatement" ||
t === "DebuggerStatement" ||
t === "ImportDeclaration" ||
t === "ExportAllDeclaration"
) {
return false;
}
if (t === "ReturnStatement") {
return Boolean(node.argument);
}
if (t === "ExportNamedDeclaration") {
return Boolean(node.declaration);
}
if (isEndOfArrowBlock(sourceCode.getLastToken(node, 1))) {
return false;
}
const nextToken = sourceCode.getTokenAfter(lastToken);
return true;
}
if (!nextToken) {
return true;
/**
* Check whether a given token can connect the previous statement.
* @param {Token} token A token to check.
* @returns {boolean} `true` if the token is one of `[`, `(`, `/`, `+`, `-`, ```, `++`, and `--`.
*/
function maybeAsiHazardBefore(token) {
return (
Boolean(token) &&
OPT_OUT_PATTERN.test(token.value) &&
token.value !== "++" &&
token.value !== "--"
);
}
/**
* Check if the semicolon of a given node is unnecessary, only true if:
* - next token is a valid statement divider (`;` or `}`).
* - next token is on a new line and the node is not connectable to the new line.
* @param {Node} node A statement node to check.
* @returns {boolean} whether the semicolon is unnecessary.
*/
function canRemoveSemicolon(node) {
if (isRedundantSemi(sourceCode.getLastToken(node))) {
return true; // `;;` or `;}`
}
if (isOnSameLineWithNextToken(node)) {
return false; // One liner.
}
if (beforeStatementContinuationChars === "never" && !maybeAsiHazardAfter(node)) {
return true; // ASI works. This statement doesn't connect to the next.
}
if (!maybeAsiHazardBefore(sourceCode.getTokenAfter(node))) {
return true; // ASI works. The next token doesn't connect to this statement.
}
const lastTokenLine = lastToken.loc.end.line;
const nextTokenLine = nextToken.loc.start.line;
const isOptOutToken = OPT_OUT_PATTERN.test(nextToken.value) && nextToken.value !== "++" && nextToken.value !== "--";
const isDivider = (astUtils.isClosingBraceToken(nextToken) || astUtils.isSemicolonToken(nextToken));
return (lastTokenLine !== nextTokenLine && !isOptOutToken) || isDivider;
return false;
}
/**
@@ -143,16 +241,17 @@ module.exports = {
* @returns {boolean} whether the node is in a one-liner block statement.
*/
function isOneLinerBlock(node) {
const parent = node.parent;
const nextToken = sourceCode.getTokenAfter(node);
if (!nextToken || nextToken.value !== "}") {
return false;
}
const parent = node.parent;
return parent && parent.type === "BlockStatement" &&
parent.loc.start.line === parent.loc.end.line;
return (
!!parent &&
parent.type === "BlockStatement" &&
parent.loc.start.line === parent.loc.end.line
);
}
/**
@@ -161,21 +260,21 @@ module.exports = {
* @returns {void}
*/
function checkForSemicolon(node) {
const lastToken = sourceCode.getLastToken(node);
const isSemi = astUtils.isSemicolonToken(sourceCode.getLastToken(node));
if (never) {
if (isUnnecessarySemicolon(lastToken)) {
if (isSemi && canRemoveSemicolon(node)) {
report(node, true);
} else if (!isSemi && beforeStatementContinuationChars === "always" && maybeAsiHazardBefore(sourceCode.getTokenAfter(node))) {
report(node);
}
} else {
if (!astUtils.isSemicolonToken(lastToken)) {
if (!exceptOneLine || !isOneLinerBlock(node)) {
report(node);
}
} else {
if (exceptOneLine && isOneLinerBlock(node)) {
report(node, true);
}
const oneLinerBlock = (exceptOneLine && isOneLinerBlock(node));
if (isSemi && oneLinerBlock) {
report(node, true);
} else if (!isSemi && !oneLinerBlock) {
report(node);
}
}
}
@@ -186,9 +285,7 @@ module.exports = {
* @returns {void}
*/
function checkForSemicolonForVariableDeclaration(node) {
const ancestors = context.getAncestors(),
parentIndex = ancestors.length - 1,
parent = ancestors[parentIndex];
const parent = node.parent;
if ((parent.type !== "ForStatement" || parent.init !== node) &&
(!/^For(?:In|Of)Statement/.test(parent.type) || parent.left !== node)
+5 -3
View File
@@ -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({
+45 -10
View File
@@ -27,29 +27,64 @@ module.exports = {
},
additionalProperties: false
}
]
],
fixable: "code"
},
create(context) {
const configuration = context.options[0] || {},
ignoreCase = configuration.ignoreCase || false;
ignoreCase = configuration.ignoreCase || false,
sourceCode = context.getSourceCode();
return {
VariableDeclaration(node) {
const idDeclarations = node.declarations.filter(decl => decl.id.type === "Identifier");
const getSortableName = ignoreCase ? decl => decl.id.name.toLowerCase() : decl => decl.id.name;
const unfixable = idDeclarations.some(decl => decl.init !== null && decl.init.type !== "Literal");
let fixed = false;
idDeclarations.slice(1).reduce((memo, decl) => {
let lastVariableName = memo.id.name,
currenVariableName = decl.id.name;
const lastVariableName = getSortableName(memo),
currentVariableName = getSortableName(decl);
if (ignoreCase) {
lastVariableName = lastVariableName.toLowerCase();
currenVariableName = currenVariableName.toLowerCase();
}
if (currentVariableName < lastVariableName) {
context.report({
node: decl,
message: "Variables within the same declaration block should be sorted alphabetically.",
fix(fixer) {
if (unfixable || fixed) {
return null;
}
return fixer.replaceTextRange(
[idDeclarations[0].range[0], idDeclarations[idDeclarations.length - 1].range[1]],
idDeclarations
if (currenVariableName < lastVariableName) {
context.report({ node: decl, message: "Variables within the same declaration block should be sorted alphabetically." });
// Clone the idDeclarations array to avoid mutating it
.slice()
// Sort the array into the desired order
.sort((declA, declB) => {
const aName = getSortableName(declA);
const bName = getSortableName(declB);
return aName > bName ? 1 : -1;
})
// Build a string out of the sorted list of identifier declarations and the text between the originals
.reduce((sourceText, identifier, index) => {
const textAfterIdentifier = index === idDeclarations.length - 1
? ""
: sourceCode.getText().slice(idDeclarations[index].range[1], idDeclarations[index + 1].range[0]);
return sourceText + sourceCode.getText(identifier) + textAfterIdentifier;
}, "")
);
}
});
fixed = true;
return memo;
}
return decl;
+1 -2
View File
@@ -45,8 +45,7 @@ module.exports = {
const MISSING_SPACE_MESSAGE = "There must be a space inside this paren.",
REJECTED_SPACE_MESSAGE = "There should be no spaces inside this paren.",
ALWAYS = context.options[0] === "always",
exceptionsArrayOptions = (context.options.length === 2) ? context.options[1].exceptions : [],
exceptionsArrayOptions = (context.options[1] && context.options[1].exceptions) || [],
options = {};
let exceptions;
+61 -61
View File
@@ -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)
+8 -8
View File
@@ -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);
}
+4 -4
View File
@@ -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";
}
+4 -4
View File
@@ -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;
+9 -7
View File
@@ -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]);
Loaded 100 of 231 files, more files were not shown because too many files have changed in this diff. Show more