eslint 5.0.0-alpha.4 → 5.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -6,21 +6,15 @@
6
6
 
7
7
  "use strict";
8
8
 
9
- const matchAll = require("string.prototype.matchall");
9
+ const { CALL, ReferenceTracker } = require("eslint-utils");
10
+ const {
11
+ isCommaToken,
12
+ isOpeningParenToken,
13
+ isClosingParenToken,
14
+ isParenthesised
15
+ } = require("../ast-utils");
10
16
 
11
- /**
12
- * Helper that checks if the node is an Object.assign call
13
- * @param {ASTNode} node - The node that the rule warns on
14
- * @returns {boolean} - Returns true if the node is an Object.assign call
15
- */
16
- function isObjectAssign(node) {
17
- return (
18
- node.callee &&
19
- node.callee.type === "MemberExpression" &&
20
- node.callee.object.name === "Object" &&
21
- node.callee.property.name === "assign"
22
- );
23
- }
17
+ const ANY_SPACE = /\s/;
24
18
 
25
19
  /**
26
20
  * Helper that checks if the Object.assign call has array spread
@@ -35,15 +29,12 @@ function hasArraySpread(node) {
35
29
  * Helper that checks if the node needs parentheses to be valid JS.
36
30
  * The default is to wrap the node in parentheses to avoid parsing errors.
37
31
  * @param {ASTNode} node - The node that the rule warns on
32
+ * @param {Object} sourceCode - in context sourcecode object
38
33
  * @returns {boolean} - Returns true if the node needs parentheses
39
34
  */
40
- function needsParens(node) {
35
+ function needsParens(node, sourceCode) {
41
36
  const parent = node.parent;
42
37
 
43
- if (!parent || !node.type) {
44
- return true;
45
- }
46
-
47
38
  switch (parent.type) {
48
39
  case "VariableDeclarator":
49
40
  case "ArrayExpression":
@@ -51,180 +42,168 @@ function needsParens(node) {
51
42
  case "CallExpression":
52
43
  case "Property":
53
44
  return false;
45
+ case "AssignmentExpression":
46
+ return parent.left === node && !isParenthesised(sourceCode, node);
54
47
  default:
55
- return true;
48
+ return !isParenthesised(sourceCode, node);
56
49
  }
57
50
  }
58
51
 
59
52
  /**
60
53
  * Determines if an argument needs parentheses. The default is to not add parens.
61
54
  * @param {ASTNode} node - The node to be checked.
55
+ * @param {Object} sourceCode - in context sourcecode object
62
56
  * @returns {boolean} True if the node needs parentheses
63
57
  */
64
- function argNeedsParens(node) {
65
- if (!node.type) {
66
- return false;
67
- }
68
-
58
+ function argNeedsParens(node, sourceCode) {
69
59
  switch (node.type) {
70
60
  case "AssignmentExpression":
71
61
  case "ArrowFunctionExpression":
72
62
  case "ConditionalExpression":
73
- return true;
63
+ return !isParenthesised(sourceCode, node);
74
64
  default:
75
65
  return false;
76
66
  }
77
67
  }
78
68
 
79
69
  /**
80
- * Helper that adds a comma after the last non-whitespace character that is not a part of a comment.
81
- * @param {string} formattedArg - String of argument text
82
- * @param {array} comments - comments inside the argument
83
- * @returns {string} - argument with comma at the end of it
70
+ * Get the parenthesis tokens of a given ObjectExpression node.
71
+ * This incldues the braces of the object literal and enclosing parentheses.
72
+ * @param {ASTNode} node The node to get.
73
+ * @param {Token} leftArgumentListParen The opening paren token of the argument list.
74
+ * @param {SourceCode} sourceCode The source code object to get tokens.
75
+ * @returns {Token[]} The parenthesis tokens of the node. This is sorted by the location.
84
76
  */
85
- function addComma(formattedArg, comments) {
86
- const nonWhitespaceCharacterRegex = /[^\s\\]/g;
87
- const nonWhitespaceCharacters = Array.from(matchAll(formattedArg, nonWhitespaceCharacterRegex));
88
- const commentRanges = comments.map(comment => comment.range);
89
- const validWhitespaceMatches = [];
90
-
91
- // Create a list of indexes where non-whitespace characters exist.
92
- nonWhitespaceCharacters.forEach(match => {
93
- const insertIndex = match.index + match[0].length;
94
-
95
- if (!commentRanges.length) {
96
- validWhitespaceMatches.push(insertIndex);
97
- }
98
-
99
- // If comment ranges are found make sure that the non whitespace characters are not part of the comment.
100
- commentRanges.forEach(arr => {
101
- const commentStart = arr[0];
102
- const commentEnd = arr[1];
103
-
104
- if (insertIndex < commentStart || insertIndex > commentEnd) {
105
- validWhitespaceMatches.push(insertIndex);
106
- }
107
- });
108
- });
109
- const insertPos = Math.max(...validWhitespaceMatches);
110
- const regex = new RegExp(`^((?:.|[^/s/S]){${insertPos}}) *`);
77
+ function getParenTokens(node, leftArgumentListParen, sourceCode) {
78
+ const parens = [sourceCode.getFirstToken(node), sourceCode.getLastToken(node)];
79
+ let leftNext = sourceCode.getTokenBefore(node);
80
+ let rightNext = sourceCode.getTokenAfter(node);
81
+
82
+ // Note: don't include the parens of the argument list.
83
+ while (
84
+ leftNext &&
85
+ rightNext &&
86
+ leftNext.range[0] > leftArgumentListParen.range[0] &&
87
+ isOpeningParenToken(leftNext) &&
88
+ isClosingParenToken(rightNext)
89
+ ) {
90
+ parens.push(leftNext, rightNext);
91
+ leftNext = sourceCode.getTokenBefore(leftNext);
92
+ rightNext = sourceCode.getTokenAfter(rightNext);
93
+ }
111
94
 
112
- return formattedArg.replace(regex, "$1, ");
95
+ return parens.sort((a, b) => a.range[0] - b.range[0]);
113
96
  }
114
97
 
115
98
  /**
116
- * Helper formats an argument by either removing curlies or adding a spread operator
117
- * @param {ASTNode|null} arg - ast node representing argument to format
118
- * @param {boolean} isLast - true if on the last element of the array
119
- * @param {Object} sourceCode - in context sourcecode object
120
- * @param {array} comments - comments inside checked node
121
- * @returns {string} - formatted argument
99
+ * Get the range of a given token and around whitespaces.
100
+ * @param {Token} token The token to get range.
101
+ * @param {SourceCode} sourceCode The source code object to get tokens.
102
+ * @returns {number} The end of the range of the token and around whitespaces.
122
103
  */
123
- function formatArg(arg, isLast, sourceCode, comments) {
124
- const text = sourceCode.getText(arg);
125
- const parens = argNeedsParens(arg);
126
- const spread = arg.type === "SpreadElement" ? "" : "...";
127
-
128
- if (arg.type === "ObjectExpression" && arg.properties.length === 0) {
129
- return "";
130
- }
104
+ function getStartWithSpaces(token, sourceCode) {
105
+ const text = sourceCode.text;
106
+ let start = token.range[0];
131
107
 
132
- if (arg.type === "ObjectExpression") {
108
+ // If the previous token is a line comment then skip this step to avoid commenting this token out.
109
+ {
110
+ const prevToken = sourceCode.getTokenBefore(token, { includeComments: true });
133
111
 
134
- /**
135
- * This regex finds the opening curly brace and any following spaces and replaces it with whatever
136
- * exists before the curly brace. It also does the same for the closing curly brace. This is to avoid
137
- * having multiple spaces around the object expression depending on how the object properties are spaced.
138
- */
139
- const formattedObjectLiteral = text.replace(/^(.*){ */, "$1").replace(/ *}([^}]*)$/, "$1");
140
-
141
- return isLast ? formattedObjectLiteral : addComma(formattedObjectLiteral, comments);
112
+ if (prevToken && prevToken.type === "Line") {
113
+ return start;
114
+ }
142
115
  }
143
116
 
144
- if (isLast) {
145
- return parens ? `${spread}(${text})` : `${spread}${text}`;
117
+ // Detect spaces before the token.
118
+ while (ANY_SPACE.test(text[start - 1] || "")) {
119
+ start -= 1;
146
120
  }
147
121
 
148
- return parens ? addComma(`${spread}(${text})`, comments) : `${spread}${addComma(text, comments)}`;
122
+ return start;
149
123
  }
150
124
 
151
125
  /**
152
- * Autofixes the Object.assign call to use an object spread instead.
153
- * @param {ASTNode|null} node - The node that the rule warns on, i.e. the Object.assign call
154
- * @param {string} sourceCode - sourceCode of the Object.assign call
155
- * @returns {Function} autofixer - replaces the Object.assign with a spread object.
126
+ * Get the range of a given token and around whitespaces.
127
+ * @param {Token} token The token to get range.
128
+ * @param {SourceCode} sourceCode The source code object to get tokens.
129
+ * @returns {number} The start of the range of the token and around whitespaces.
156
130
  */
157
- function autofixSpread(node, sourceCode) {
158
- return fixer => {
159
- const args = node.arguments;
160
- const firstArg = args[0];
161
- const lastArg = args[args.length - 1];
162
- const parens = needsParens(node);
163
- const comments = sourceCode.getCommentsInside(node);
164
- const replaceObjectAssignStart = fixer.replaceTextRange(
165
- [node.range[0], firstArg.range[0]],
166
- `${parens ? "({" : "{"}`
167
- );
131
+ function getEndWithSpaces(token, sourceCode) {
132
+ const text = sourceCode.text;
133
+ let end = token.range[1];
168
134
 
169
- const handleArgs = args
170
- .map((arg, i, arr) => formatArg(arg, i + 1 >= arr.length, sourceCode, comments))
171
- .filter(arg => arg !== "," && arg !== "");
172
-
173
- const insertBody = fixer.replaceTextRange([firstArg.range[0], lastArg.range[1]], handleArgs.join(""));
174
- const replaceObjectAssignEnd = fixer.replaceTextRange([lastArg.range[1], node.range[1]], `${parens ? "})" : "}"}`);
135
+ // Detect spaces after the token.
136
+ while (ANY_SPACE.test(text[end] || "")) {
137
+ end += 1;
138
+ }
175
139
 
176
- return [
177
- replaceObjectAssignStart,
178
- insertBody,
179
- replaceObjectAssignEnd
180
- ];
181
- };
140
+ return end;
182
141
  }
183
142
 
184
143
  /**
185
- * Autofixes the Object.assign call with a single object literal as an argument
144
+ * Autofixes the Object.assign call to use an object spread instead.
186
145
  * @param {ASTNode|null} node - The node that the rule warns on, i.e. the Object.assign call
187
146
  * @param {string} sourceCode - sourceCode of the Object.assign call
188
- * @returns {Function} autofixer - replaces the Object.assign with a object literal.
147
+ * @returns {Function} autofixer - replaces the Object.assign with a spread object.
189
148
  */
190
- function autofixObjectLiteral(node, sourceCode) {
191
- return fixer => {
192
- const argument = node.arguments[0];
193
- const parens = needsParens(node);
149
+ function defineFixer(node, sourceCode) {
150
+ return function *(fixer) {
151
+ const leftParen = sourceCode.getTokenAfter(node.callee, isOpeningParenToken);
152
+ const rightParen = sourceCode.getLastToken(node);
153
+
154
+ // Remove the callee `Object.assign`
155
+ yield fixer.remove(node.callee);
156
+
157
+ // Replace the parens of argument list to braces.
158
+ if (needsParens(node, sourceCode)) {
159
+ yield fixer.replaceText(leftParen, "({");
160
+ yield fixer.replaceText(rightParen, "})");
161
+ } else {
162
+ yield fixer.replaceText(leftParen, "{");
163
+ yield fixer.replaceText(rightParen, "}");
164
+ }
194
165
 
195
- return fixer.replaceText(node, `${parens ? "(" : ""}${sourceCode.text.slice(argument.range[0], argument.range[1])}${parens ? ")" : ""}`);
196
- };
197
- }
166
+ // Process arguments.
167
+ for (const argNode of node.arguments) {
168
+ const innerParens = getParenTokens(argNode, leftParen, sourceCode);
169
+ const left = innerParens.shift();
170
+ const right = innerParens.pop();
198
171
 
199
- /**
200
- * Check if the node has modified a given variable
201
- * @param {ASTNode|null} node - The node that the rule warns on, i.e. the Object.assign call
202
- * @returns {boolean} - true if node is an assignment, variable declaration, or import statement
203
- */
204
- function isModifier(node) {
205
- if (!node.type) {
206
- return false;
207
- }
172
+ if (argNode.type === "ObjectExpression") {
173
+ const maybeTrailingComma = sourceCode.getLastToken(argNode, 1);
174
+ const maybeArgumentComma = sourceCode.getTokenAfter(right);
208
175
 
209
- return node.type === "AssignmentExpression" ||
210
- node.type === "VariableDeclarator" ||
211
- node.type === "ImportDeclaration";
212
- }
176
+ /*
177
+ * Make bare this object literal.
178
+ * And remove spaces inside of the braces for better formatting.
179
+ */
180
+ for (const innerParen of innerParens) {
181
+ yield fixer.remove(innerParen);
182
+ }
183
+ yield fixer.removeRange([left.range[0], getEndWithSpaces(left, sourceCode)]);
184
+ yield fixer.removeRange([getStartWithSpaces(right, sourceCode), right.range[1]]);
213
185
 
214
- /**
215
- * Check if the node has modified a given variable
216
- * @param {array} references - list of reference nodes
217
- * @returns {boolean} - true if node is has been overwritten by an assignment or import
218
- */
219
- function modifyingObjectReference(references) {
220
- return references.some(ref => (
221
- ref.identifier &&
222
- ref.identifier.parent &&
223
- isModifier(ref.identifier.parent)
224
- ));
186
+ // Remove the comma of this argument if it's duplication.
187
+ if (
188
+ (argNode.properties.length === 0 || isCommaToken(maybeTrailingComma)) &&
189
+ isCommaToken(maybeArgumentComma)
190
+ ) {
191
+ yield fixer.remove(maybeArgumentComma);
192
+ }
193
+ } else {
194
+
195
+ // Make spread.
196
+ if (argNeedsParens(argNode, sourceCode)) {
197
+ yield fixer.insertTextBefore(left, "...(");
198
+ yield fixer.insertTextAfter(right, ")");
199
+ } else {
200
+ yield fixer.insertTextBefore(left, "...");
201
+ }
202
+ }
203
+ }
204
+ };
225
205
  }
226
206
 
227
-
228
207
  module.exports = {
229
208
  meta: {
230
209
  docs: {
@@ -242,61 +221,33 @@ module.exports = {
242
221
  }
243
222
  },
244
223
 
245
- create: function rule(context) {
224
+ create(context) {
246
225
  const sourceCode = context.getSourceCode();
247
- const scope = context.getScope();
248
- const objectVariable = scope.variables.filter(variable => variable.name === "Object");
249
- const moduleReferences = scope.childScopes.filter(childScope => {
250
- const varNamedObject = childScope.variables.filter(variable => variable.name === "Object");
251
-
252
- return childScope.type === "module" && varNamedObject.length;
253
- });
254
- const references = [].concat(...objectVariable.map(variable => variable.references || []));
255
226
 
256
227
  return {
257
- CallExpression(node) {
258
-
259
- /*
260
- * If current file is either importing Object or redefining it,
261
- * we skip warning on this rule.
262
- */
263
- if (moduleReferences.length || (references.length && modifyingObjectReference(references))) {
264
- return;
265
- }
266
-
267
- /*
268
- * The condition below is cases where Object.assign has a single argument and
269
- * that argument is an object literal. e.g. `Object.assign({ foo: bar })`.
270
- * For now, we will warn on this case and autofix it.
271
- */
272
- if (
273
- node.arguments.length === 1 &&
274
- node.arguments[0].type === "ObjectExpression" &&
275
- isObjectAssign(node)
276
- ) {
277
- context.report({
278
- node,
279
- messageId: "useLiteralMessage",
280
- fix: autofixObjectLiteral(node, sourceCode)
281
- });
282
- }
283
-
284
- /*
285
- * The condition below warns on `Object.assign` calls that that have
286
- * an object literal as the first argument and have a second argument
287
- * that can be spread. e.g `Object.assign({ foo: bar }, baz)`
288
- */
289
- if (
290
- node.arguments.length > 1 &&
291
- node.arguments[0].type === "ObjectExpression" &&
292
- isObjectAssign(node) &&
293
- !hasArraySpread(node)
294
- ) {
295
- context.report({
296
- node,
297
- messageId: "useSpreadMessage",
298
- fix: autofixSpread(node, sourceCode)
299
- });
228
+ Program() {
229
+ const scope = context.getScope();
230
+ const tracker = new ReferenceTracker(scope);
231
+ const trackMap = {
232
+ Object: {
233
+ assign: { [CALL]: true }
234
+ }
235
+ };
236
+
237
+ // Iterate all calls of `Object.assign` (only of the global variable `Object`).
238
+ for (const { node } of tracker.iterateGlobalReferences(trackMap)) {
239
+ if (
240
+ node.arguments.length >= 1 &&
241
+ node.arguments[0].type === "ObjectExpression" &&
242
+ !hasArraySpread(node)
243
+ ) {
244
+ const messageId = node.arguments.length === 1
245
+ ? "useLiteralMessage"
246
+ : "useSpreadMessage";
247
+ const fix = defineFixer(node, sourceCode);
248
+
249
+ context.report({ node, messageId, fix });
250
+ }
300
251
  }
301
252
  }
302
253
  };
@@ -125,7 +125,7 @@ module.exports = {
125
125
  },
126
126
 
127
127
  Property(node) {
128
- if (node.parent.type === "ObjectPattern") {
128
+ if (node.parent.type === "ObjectPattern" || node.parent.properties.some(n => n.type === "SpreadElement")) {
129
129
  return;
130
130
  }
131
131
 
@@ -53,6 +53,9 @@ module.exports = {
53
53
  },
54
54
  requireReturnType: {
55
55
  type: "boolean"
56
+ },
57
+ requireParamType: {
58
+ type: "boolean"
56
59
  }
57
60
  },
58
61
  additionalProperties: false
@@ -73,6 +76,7 @@ module.exports = {
73
76
  requireParamDescription = options.requireParamDescription !== false,
74
77
  requireReturnDescription = options.requireReturnDescription !== false,
75
78
  requireReturnType = options.requireReturnType !== false,
79
+ requireParamType = options.requireParamType !== false,
76
80
  preferType = options.preferType || {},
77
81
  checkPreferType = Object.keys(preferType).length !== 0;
78
82
 
@@ -351,7 +355,7 @@ module.exports = {
351
355
  });
352
356
 
353
357
  paramTags.forEach(param => {
354
- if (!param.type) {
358
+ if (requireParamType && !param.type) {
355
359
  context.report({
356
360
  node: jsdocNode,
357
361
  message: "Missing JSDoc parameter type for '{{name}}'.",
@@ -404,7 +408,7 @@ module.exports = {
404
408
  if (!isOverride && !hasReturns && !hasConstructor && !isInterface &&
405
409
  node.parent.kind !== "get" && node.parent.kind !== "constructor" &&
406
410
  node.parent.kind !== "set" && !isTypeClass(node)) {
407
- if (requireReturn || functionData.returnPresent) {
411
+ if (requireReturn || (functionData.returnPresent && !node.async)) {
408
412
  context.report({
409
413
  node: jsdocNode,
410
414
  message: "Missing JSDoc @{{returns}} for function.",
@@ -20,7 +20,10 @@ module.exports = {
20
20
 
21
21
  schema: [],
22
22
 
23
- fixable: "code"
23
+ fixable: "code",
24
+ messages: {
25
+ requireParens: "Wrap the regexp literal in parens to disambiguate the slash."
26
+ }
24
27
  },
25
28
 
26
29
  create(context) {
@@ -33,15 +36,16 @@ module.exports = {
33
36
  nodeType = token.type;
34
37
 
35
38
  if (nodeType === "RegularExpression") {
36
- const source = sourceCode.getTokenBefore(node);
39
+ const beforeToken = sourceCode.getTokenBefore(node);
40
+ const afterToken = sourceCode.getTokenAfter(node);
37
41
  const ancestors = context.getAncestors();
38
42
  const grandparent = ancestors[ancestors.length - 1];
39
43
 
40
44
  if (grandparent.type === "MemberExpression" && grandparent.object === node &&
41
- (!source || source.value !== "(")) {
45
+ !(beforeToken && beforeToken.value === "(" && afterToken && afterToken.value === ")")) {
42
46
  context.report({
43
47
  node,
44
- message: "Wrap the regexp literal in parens to disambiguate the slash.",
48
+ messageId: "requireParens",
45
49
  fix: fixer => fixer.replaceText(node, `(${sourceCode.getText(node)})`)
46
50
  });
47
51
  }
@@ -109,8 +109,14 @@ function check(packages, opt) {
109
109
  try {
110
110
  fileJson = JSON.parse(fs.readFileSync(pkgJson, "utf8"));
111
111
  } catch (e) {
112
- log.info("Could not read package.json file. Please check that the file contains valid JSON.");
113
- throw new Error(e);
112
+ const error = new Error(e);
113
+
114
+ error.messageTemplate = "failed-to-read-json";
115
+ error.messageData = {
116
+ path: pkgJson,
117
+ message: e.message
118
+ };
119
+ throw error;
114
120
  }
115
121
 
116
122
  if (opt.devDependencies && typeof fileJson.devDependencies === "object") {
@@ -0,0 +1,3 @@
1
+ Failed to read JSON file at <%= path %>:
2
+
3
+ <%= message %>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "eslint",
3
- "version": "5.0.0-alpha.4",
3
+ "version": "5.1.0",
4
4
  "author": "Nicholas C. Zakas <nicholas+npm@nczconsulting.com>",
5
5
  "description": "An AST-based pattern checker for JavaScript.",
6
6
  "bin": {
@@ -15,6 +15,7 @@
15
15
  "ci-release": "node Makefile.js ciRelease",
16
16
  "alpharelease": "node Makefile.js prerelease -- alpha",
17
17
  "betarelease": "node Makefile.js prerelease -- beta",
18
+ "rcrelease": "node Makefile.js prerelease -- rc",
18
19
  "docs": "node Makefile.js docs",
19
20
  "gensite": "node Makefile.js gensite",
20
21
  "browserify": "node Makefile.js browserify",
@@ -40,15 +41,16 @@
40
41
  "cross-spawn": "^6.0.5",
41
42
  "debug": "^3.1.0",
42
43
  "doctrine": "^2.1.0",
43
- "eslint-scope": "^4.0.0-alpha.0",
44
+ "eslint-scope": "^4.0.0",
45
+ "eslint-utils": "^1.3.1",
44
46
  "eslint-visitor-keys": "^1.0.0",
45
- "espree": "^4.0.0-alpha.0",
47
+ "espree": "^4.0.0",
46
48
  "esquery": "^1.0.1",
47
49
  "esutils": "^2.0.2",
48
50
  "file-entry-cache": "^2.0.0",
49
51
  "functional-red-black-tree": "^1.0.1",
50
52
  "glob": "^7.1.2",
51
- "globals": "^11.5.0",
53
+ "globals": "^11.7.0",
52
54
  "ignore": "^3.3.3",
53
55
  "imurmurhash": "^0.1.4",
54
56
  "inquirer": "^5.2.0",