summaryrefslogtreecommitdiffstats
path: root/tools/lint/eslint/eslint-plugin-mozilla/lib/helpers.js
blob: dc4106631a48a389faee4b2275328b6ff601da6b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
/**
 * @fileoverview A collection of helper functions.
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */
"use strict";

const parser = require("espree");
const { analyze } = require("eslint-scope");
const { KEYS: defaultVisitorKeys } = require("eslint-visitor-keys");
const estraverse = require("estraverse");
const path = require("path");
const fs = require("fs");
const toml = require("toml-eslint-parser");
const recommendedConfig = require("./configs/recommended");

var gRootDir = null;
var directoryManifests = new Map();

let xpidlData;

module.exports = {
  get servicesData() {
    return require("./services.json");
  },

  /**
   * Obtains xpidl data from the object directory specified in the
   * environment.
   *
   * @returns {Map<string, object>}
   *   A map of interface names to the interface details.
   */
  get xpidlData() {
    let xpidlDir;

    if (process.env.TASK_ID && !process.env.MOZ_XPT_ARTIFACTS_DIR) {
      throw new Error(
        "MOZ_XPT_ARTIFACTS_DIR must be set for this rule in automation"
      );
    }
    xpidlDir = process.env.MOZ_XPT_ARTIFACTS_DIR;

    if (!xpidlDir && process.env.MOZ_OBJDIR) {
      xpidlDir = `${process.env.MOZ_OBJDIR}/dist/xpt_artifacts/`;
      if (!fs.existsSync(xpidlDir)) {
        xpidlDir = `${process.env.MOZ_OBJDIR}/config/makefiles/xpidl/`;
      }
    }
    if (!xpidlDir) {
      throw new Error(
        "MOZ_OBJDIR must be defined in the environment for this rule, i.e. MOZ_OBJDIR=objdir-ff ./mach ..."
      );
    }
    if (xpidlData) {
      return xpidlData;
    }
    let files = fs.readdirSync(`${xpidlDir}`);
    // `Makefile` is an expected file in the directory.
    if (files.length <= 1) {
      throw new Error("Missing xpidl data files, maybe you need to build?");
    }
    xpidlData = new Map();
    for (let file of files) {
      if (!file.endsWith(".xpt")) {
        continue;
      }
      let data = JSON.parse(fs.readFileSync(path.join(`${xpidlDir}`, file)));
      for (let details of data) {
        xpidlData.set(details.name, details);
      }
    }
    return xpidlData;
  },

  /**
   * Gets the abstract syntax tree (AST) of the JavaScript source code contained
   * in sourceText. This matches the results for an eslint parser, see
   * https://eslint.org/docs/developer-guide/working-with-custom-parsers.
   *
   * @param  {String} sourceText
   *         Text containing valid JavaScript.
   * @param  {Object} astOptions
   *         Extra configuration to pass to the espree parser, these will override
   *         the configuration from getPermissiveConfig().
   * @param  {Object} configOptions
   *         Extra options for getPermissiveConfig().
   *
   * @return {Object}
   *         Returns an object containing `ast`, `scopeManager` and
   *         `visitorKeys`
   */
  parseCode(sourceText, astOptions = {}, configOptions = {}) {
    // Use a permissive config file to allow parsing of anything that Espree
    // can parse.
    let config = { ...this.getPermissiveConfig(configOptions), ...astOptions };

    let parseResult = parser.parse(sourceText, config);

    let visitorKeys = parseResult.visitorKeys || defaultVisitorKeys;

    // eslint-scope doesn't support "latest" as a version, so we pass a really
    // big number to ensure this always reads as the latest.
    // xref https://github.com/eslint/eslint-scope/issues/74
    config.ecmaVersion =
      config.ecmaVersion == "latest" ? 1e8 : config.ecmaVersion;

    return {
      ast: parseResult,
      scopeManager: parseResult.scopeManager || analyze(parseResult, config),
      visitorKeys,
    };
  },

  /**
   * A simplistic conversion of some AST nodes to a standard string form.
   *
   * @param  {Object} node
   *         The AST node to convert.
   *
   * @return {String}
   *         The JS source for the node.
   */
  getASTSource(node, context) {
    switch (node.type) {
      case "MemberExpression":
        if (node.computed) {
          let filename = context && context.getFilename();
          throw new Error(
            `getASTSource unsupported computed MemberExpression in ${filename}`
          );
        }
        return (
          this.getASTSource(node.object) +
          "." +
          this.getASTSource(node.property)
        );
      case "ThisExpression":
        return "this";
      case "Identifier":
        return node.name;
      case "Literal":
        return JSON.stringify(node.value);
      case "CallExpression":
        var args = node.arguments.map(a => this.getASTSource(a)).join(", ");
        return this.getASTSource(node.callee) + "(" + args + ")";
      case "ObjectExpression":
        return "{}";
      case "ExpressionStatement":
        return this.getASTSource(node.expression) + ";";
      case "FunctionExpression":
        return "function() {}";
      case "ArrayExpression":
        return "[" + node.elements.map(this.getASTSource, this).join(",") + "]";
      case "ArrowFunctionExpression":
        return "() => {}";
      case "AssignmentExpression":
        return (
          this.getASTSource(node.left) + " = " + this.getASTSource(node.right)
        );
      case "BinaryExpression":
        return (
          this.getASTSource(node.left) +
          " " +
          node.operator +
          " " +
          this.getASTSource(node.right)
        );
      case "UnaryExpression":
        return node.operator + " " + this.getASTSource(node.argument);
      default:
        throw new Error("getASTSource unsupported node type: " + node.type);
    }
  },

  /**
   * This walks an AST in a manner similar to ESLint passing node events to the
   * listener. The listener is expected to be a simple function
   * which accepts node type, node and parents arguments.
   *
   * @param  {Object} ast
   *         The AST to walk.
   * @param  {Array} visitorKeys
   *         The visitor keys to use for the AST.
   * @param  {Function} listener
   *         A callback function to call for the nodes. Passed three arguments,
   *         event type, node and an array of parent nodes for the current node.
   */
  walkAST(ast, visitorKeys, listener) {
    let parents = [];

    estraverse.traverse(ast, {
      enter(node, parent) {
        listener(node.type, node, parents);

        parents.push(node);
      },

      leave(node, parent) {
        if (!parents.length) {
          throw new Error("Left more nodes than entered.");
        }
        parents.pop();
      },

      keys: visitorKeys,
    });
    if (parents.length) {
      throw new Error("Entered more nodes than left.");
    }
  },

  /**
   * Add a variable to the current scope.
   * HACK: This relies on eslint internals so it could break at any time.
   *
   * @param {String} name
   *        The variable name to add to the scope.
   * @param {ASTScope} scope
   *        The scope to add to.
   * @param {boolean} writable
   *        Whether the global can be overwritten.
   * @param {Object} [node]
   *        The AST node that defined the globals.
   */
  addVarToScope(name, scope, writable, node) {
    scope.__defineGeneric(name, scope.set, scope.variables, null, null);

    let variable = scope.set.get(name);
    variable.eslintExplicitGlobal = false;
    variable.writeable = writable;
    if (node) {
      variable.defs.push({
        type: "Variable",
        node,
        name: { name, parent: node.parent },
      });
      variable.identifiers.push(node);
    }

    // Walk to the global scope which holds all undeclared variables.
    while (scope.type != "global") {
      scope = scope.upper;
    }

    // "through" contains all references with no found definition.
    scope.through = scope.through.filter(function (reference) {
      if (reference.identifier.name != name) {
        return true;
      }

      // Links the variable and the reference.
      // And this reference is removed from `Scope#through`.
      reference.resolved = variable;
      variable.references.push(reference);
      return false;
    });
  },

  /**
   * Adds a set of globals to a scope.
   *
   * @param {Array} globalVars
   *        An array of global variable names.
   * @param {ASTScope} scope
   *        The scope.
   * @param {Object} [node]
   *        The AST node that defined the globals.
   */
  addGlobals(globalVars, scope, node) {
    globalVars.forEach(v =>
      this.addVarToScope(v.name, scope, v.writable, v.explicit && node)
    );
  },

  /**
   * To allow espree to parse almost any JavaScript we need as many features as
   * possible turned on. This method returns that config.
   *
   * @param {Object} options
   *        {
   *          useBabel: {boolean} whether to set babelOptions.
   *        }
   * @return {Object}
   *         Espree compatible permissive config.
   */
  getPermissiveConfig({ useBabel = true } = {}) {
    return {
      range: true,
      loc: true,
      comment: true,
      attachComment: true,
      ecmaVersion: this.getECMAVersion(),
      sourceType: "script",
    };
  },

  /**
   * Returns the ECMA version of the recommended config.
   *
   * @return {Number} The ECMA version of the recommended config.
   */
  getECMAVersion() {
    return recommendedConfig.parserOptions.ecmaVersion;
  },

  /**
   * Check whether it's inside top-level script.
   *
   * @param {Array} ancestors
   *        The parents of the current node.
   *
   * @return {Boolean}
   *         True or false
   */
  getIsTopLevelScript(ancestors) {
    for (let parent of ancestors) {
      switch (parent.type) {
        case "ArrowFunctionExpression":
        case "FunctionDeclaration":
        case "FunctionExpression":
        case "PropertyDefinition":
        case "StaticBlock":
          return false;
      }
    }
    return true;
  },

  isTopLevel(ancestors) {
    for (let parent of ancestors) {
      switch (parent.type) {
        case "ArrowFunctionExpression":
        case "FunctionDeclaration":
        case "FunctionExpression":
        case "PropertyDefinition":
        case "StaticBlock":
        case "BlockStatement":
          return false;
      }
    }
    return true;
  },

  /**
   * Check whether `this` expression points the global this.
   *
   * @param {Array} ancestors
   *        The parents of the current node.
   *
   * @return {Boolean}
   *         True or false
   */
  getIsGlobalThis(ancestors) {
    for (let parent of ancestors) {
      switch (parent.type) {
        case "FunctionDeclaration":
        case "FunctionExpression":
        case "PropertyDefinition":
        case "StaticBlock":
          return false;
      }
    }
    return true;
  },

  /**
   * Check whether the node is evaluated at top-level script unconditionally.
   *
   * @param {Array} ancestors
   *        The parents of the current node.
   *
   * @return {Boolean}
   *         True or false
   */
  getIsTopLevelAndUnconditionallyExecuted(ancestors) {
    for (let parent of ancestors) {
      switch (parent.type) {
        // Control flow
        case "IfStatement":
        case "SwitchStatement":
        case "TryStatement":
        case "WhileStatement":
        case "DoWhileStatement":
        case "ForStatement":
        case "ForInStatement":
        case "ForOfStatement":
          return false;

        // Function
        case "FunctionDeclaration":
        case "FunctionExpression":
        case "ArrowFunctionExpression":
        case "ClassBody":
          return false;

        // Branch
        case "LogicalExpression":
        case "ConditionalExpression":
        case "ChainExpression":
          return false;

        case "AssignmentExpression":
          switch (parent.operator) {
            // Branch
            case "||=":
            case "&&=":
            case "??=":
              return false;
          }
          break;

        // Implicit branch (default value)
        case "ObjectPattern":
        case "ArrayPattern":
          return false;
      }
    }
    return true;
  },

  /**
   * Check whether we might be in a test head file.
   *
   * @param  {RuleContext} scope
   *         You should pass this from within a rule
   *         e.g. helpers.getIsHeadFile(context)
   *
   * @return {Boolean}
   *         True or false
   */
  getIsHeadFile(scope) {
    var pathAndFilename = this.cleanUpPath(scope.getFilename());

    return /.*[\\/]head(_.+)?\.js$/.test(pathAndFilename);
  },

  /**
   * Gets the head files for a potential test file
   *
   * @param  {RuleContext} scope
   *         You should pass this from within a rule
   *         e.g. helpers.getIsHeadFile(context)
   *
   * @return {String[]}
   *         Paths to head files to load for the test
   */
  getTestHeadFiles(scope) {
    if (!this.getIsTest(scope)) {
      return [];
    }

    let filepath = this.cleanUpPath(scope.getFilename());
    let dir = path.dirname(filepath);

    let names = fs
      .readdirSync(dir)
      .filter(
        name =>
          (name.startsWith("head") || name.startsWith("xpcshell-head")) &&
          name.endsWith(".js")
      )
      .map(name => path.join(dir, name));
    return names;
  },

  /**
   * Gets all the test manifest data for a directory
   *
   * @param  {String} dir
   *         The directory
   *
   * @return {Array}
   *         An array of objects with file and manifest properties
   */
  getManifestsForDirectory(dir) {
    if (directoryManifests.has(dir)) {
      return directoryManifests.get(dir);
    }

    let manifests = [];
    let names = [];
    try {
      names = fs.readdirSync(dir);
    } catch (err) {
      // Ignore directory not found, it might be faked by a test
      if (err.code !== "ENOENT") {
        throw err;
      }
    }

    for (let name of names) {
      if (name.endsWith(".toml")) {
        try {
          const ast = toml.parseTOML(
            fs.readFileSync(path.join(dir, name), "utf8")
          );
          var manifest = {};
          ast.body.forEach(top => {
            if (top.type == "TOMLTopLevelTable") {
              top.body.forEach(obj => {
                if (obj.type == "TOMLTable") {
                  manifest[obj.resolvedKey] = {};
                }
              });
            }
          });
          manifests.push({
            file: path.join(dir, name),
            manifest,
          });
        } catch (e) {
          console.log(
            "TOML ERROR: " +
              e.message +
              " @line: " +
              e.lineNumber +
              ", column: " +
              e.column
          );
        }
      }
    }

    directoryManifests.set(dir, manifests);
    return manifests;
  },

  /**
   * Gets the manifest file a test is listed in
   *
   * @param  {RuleContext} scope
   *         You should pass this from within a rule
   *         e.g. helpers.getIsHeadFile(context)
   *
   * @return {String}
   *         The path to the test manifest file
   */
  getTestManifest(scope) {
    let filepath = this.cleanUpPath(scope.getFilename());

    let dir = path.dirname(filepath);
    let filename = path.basename(filepath);

    for (let manifest of this.getManifestsForDirectory(dir)) {
      if (filename in manifest.manifest) {
        return manifest.file;
      }
    }

    return null;
  },

  /**
   * Check whether we are in a test of some kind.
   *
   * @param  {RuleContext} scope
   *         You should pass this from within a rule
   *         e.g. helpers.getIsTest(context)
   *
   * @return {Boolean}
   *         True or false
   */
  getIsTest(scope) {
    // Regardless of the manifest name being in a manifest means we're a test.
    let manifest = this.getTestManifest(scope);
    if (manifest) {
      return true;
    }

    return !!this.getTestType(scope);
  },

  /*
   * Check if this is an .sjs file.
   */
  getIsSjs(scope) {
    let filepath = this.cleanUpPath(scope.getFilename());

    return path.extname(filepath) == ".sjs";
  },

  /**
   * Gets the type of test or null if this isn't a test.
   *
   * @param  {RuleContext} scope
   *         You should pass this from within a rule
   *         e.g. helpers.getIsHeadFile(context)
   *
   * @return {String or null}
   *         Test type: xpcshell, browser, chrome, mochitest
   */
  getTestType(scope) {
    let testTypes = ["browser", "xpcshell", "chrome", "mochitest", "a11y"];
    let manifest = this.getTestManifest(scope);
    if (manifest) {
      let name = path.basename(manifest);
      for (let testType of testTypes) {
        if (name.startsWith(testType)) {
          return testType;
        }
      }
    }

    let filepath = this.cleanUpPath(scope.getFilename());
    let filename = path.basename(filepath);

    if (filename.startsWith("browser_")) {
      return "browser";
    }

    if (filename.startsWith("test_")) {
      let parent = path.basename(path.dirname(filepath));
      for (let testType of testTypes) {
        if (parent.startsWith(testType)) {
          return testType;
        }
      }

      // It likely is a test, we're just not sure what kind.
      return "unknown";
    }

    // Likely not a test
    return null;
  },

  getIsWorker(filePath) {
    let filename = path.basename(this.cleanUpPath(filePath)).toLowerCase();

    return filename.includes("worker");
  },

  /**
   * Gets the root directory of the repository by walking up directories from
   * this file until a .eslintignore file is found. If this fails, the same
   * procedure will be attempted from the current working dir.
   * @return {String} The absolute path of the repository directory
   */
  get rootDir() {
    if (!gRootDir) {
      function searchUpForIgnore(dirName, filename) {
        let parsed = path.parse(dirName);
        while (parsed.root !== dirName) {
          if (fs.existsSync(path.join(dirName, filename))) {
            return dirName;
          }
          // Move up a level
          dirName = parsed.dir;
          parsed = path.parse(dirName);
        }
        return null;
      }

      let possibleRoot = searchUpForIgnore(
        path.dirname(module.filename),
        ".eslintignore"
      );
      if (!possibleRoot) {
        possibleRoot = searchUpForIgnore(path.resolve(), ".eslintignore");
      }
      if (!possibleRoot) {
        possibleRoot = searchUpForIgnore(path.resolve(), "package.json");
      }
      if (!possibleRoot) {
        // We've couldn't find a root from the module or CWD, so lets just go
        // for the CWD. We really don't want to throw if possible, as that
        // tends to give confusing results when used with ESLint.
        possibleRoot = process.cwd();
      }

      gRootDir = possibleRoot;
    }

    return gRootDir;
  },

  /**
   * ESLint may be executed from various places: from mach, at the root of the
   * repository, or from a directory in the repository when, for instance,
   * executed by a text editor's plugin.
   * The value returned by context.getFileName() varies because of this.
   * This helper function makes sure to return an absolute file path for the
   * current context, by looking at process.cwd().
   * @param {Context} context
   * @return {String} The absolute path
   */
  getAbsoluteFilePath(context) {
    var fileName = this.cleanUpPath(context.getFilename());
    var cwd = process.cwd();

    if (path.isAbsolute(fileName)) {
      // Case 2: executed from the repo's root with mach:
      //   fileName: /path/to/mozilla/repo/a/b/c/d.js
      //   cwd: /path/to/mozilla/repo
      return fileName;
    } else if (path.basename(fileName) == fileName) {
      // Case 1b: executed from a nested directory, fileName is the base name
      // without any path info (happens in Atom with linter-eslint)
      return path.join(cwd, fileName);
    }
    // Case 1: executed form in a nested directory, e.g. from a text editor:
    //   fileName: a/b/c/d.js
    //   cwd: /path/to/mozilla/repo/a/b/c
    var dirName = path.dirname(fileName);
    return cwd.slice(0, cwd.length - dirName.length) + fileName;
  },

  /**
   * When ESLint is run from SublimeText, paths retrieved from
   * context.getFileName contain leading and trailing double-quote characters.
   * These characters need to be removed.
   */
  cleanUpPath(pathName) {
    return pathName.replace(/^"/, "").replace(/"$/, "");
  },

  get globalScriptPaths() {
    return [
      path.join(this.rootDir, "browser", "base", "content", "browser.xhtml"),
      path.join(
        this.rootDir,
        "browser",
        "base",
        "content",
        "global-scripts.inc"
      ),
    ];
  },

  isMozillaCentralBased() {
    return fs.existsSync(this.globalScriptPaths[0]);
  },

  getSavedEnvironmentItems(environment) {
    return require("./environments/saved-globals.json").environments[
      environment
    ];
  },

  getSavedRuleData(rule) {
    return require("./rules/saved-rules-data.json").rulesData[rule];
  },

  getBuildEnvironment() {
    var { execFileSync } = require("child_process");
    var output = execFileSync(
      path.join(this.rootDir, "mach"),
      ["environment", "--format=json"],
      { silent: true }
    );
    return JSON.parse(output);
  },

  /**
   * Extract the path of require (and require-like) helpers used in DevTools.
   */
  getDevToolsRequirePath(node) {
    if (
      node.callee.type == "Identifier" &&
      node.callee.name == "require" &&
      node.arguments.length == 1 &&
      node.arguments[0].type == "Literal"
    ) {
      return node.arguments[0].value;
    } else if (
      node.callee.type == "MemberExpression" &&
      node.callee.property.type == "Identifier" &&
      node.callee.property.name == "lazyRequireGetter" &&
      node.arguments.length >= 3 &&
      node.arguments[2].type == "Literal"
    ) {
      return node.arguments[2].value;
    }
    return null;
  },

  /**
   * Returns property name from MemberExpression. Also accepts Identifier for consistency.
   * @param {import("estree").MemberExpression | import("estree").Identifier} node
   * @returns {string | null}
   *
   * @example `foo` gives "foo"
   * @example `foo.bar` gives "bar"
   * @example `foo.bar.baz` gives "baz"
   */
  maybeGetMemberPropertyName(node) {
    if (node.type === "MemberExpression") {
      return node.property.name;
    }
    if (node.type === "Identifier") {
      return node.name;
    }
    return null;
  },
};