• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1'use strict';
2
3var path = require('path');
4var fs = require('fs');
5var acorn = require('./acorn.js');
6
7var infile, forceFile, silent = false, compact = false, tokenize = false;
8var options = {};
9
10function help(status) {
11  var print = (status === 0) ? console.log : console.error;
12  print("usage: " + path.basename(process.argv[1]) + " [--ecma3|--ecma5|--ecma6|--ecma7|--ecma8|--ecma9|...|--ecma2015|--ecma2016|--ecma2017|--ecma2018|...]");
13  print("        [--tokenize] [--locations] [---allow-hash-bang] [--allow-await-outside-function] [--compact] [--silent] [--module] [--help] [--] [infile]");
14  process.exit(status);
15}
16
17for (var i = 2; i < process.argv.length; ++i) {
18  var arg = process.argv[i];
19  if ((arg === "-" || arg[0] !== "-") && !infile) { infile = arg; }
20  else if (arg === "--" && !infile && i + 2 === process.argv.length) { forceFile = infile = process.argv[++i]; }
21  else if (arg === "--locations") { options.locations = true; }
22  else if (arg === "--allow-hash-bang") { options.allowHashBang = true; }
23  else if (arg === "--allow-await-outside-function") { options.allowAwaitOutsideFunction = true; }
24  else if (arg === "--silent") { silent = true; }
25  else if (arg === "--compact") { compact = true; }
26  else if (arg === "--help") { help(0); }
27  else if (arg === "--tokenize") { tokenize = true; }
28  else if (arg === "--module") { options.sourceType = "module"; }
29  else {
30    var match = arg.match(/^--ecma(\d+)$/);
31    if (match)
32      { options.ecmaVersion = +match[1]; }
33    else
34      { help(1); }
35  }
36}
37
38function run(code) {
39  var result;
40  try {
41    if (!tokenize) {
42      result = acorn.parse(code, options);
43    } else {
44      result = [];
45      var tokenizer = acorn.tokenizer(code, options), token;
46      do {
47        token = tokenizer.getToken();
48        result.push(token);
49      } while (token.type !== acorn.tokTypes.eof)
50    }
51  } catch (e) {
52    console.error(infile && infile !== "-" ? e.message.replace(/\(\d+:\d+\)$/, function (m) { return m.slice(0, 1) + infile + " " + m.slice(1); }) : e.message);
53    process.exit(1);
54  }
55  if (!silent) { console.log(JSON.stringify(result, null, compact ? null : 2)); }
56}
57
58if (forceFile || infile && infile !== "-") {
59  run(fs.readFileSync(infile, "utf8"));
60} else {
61  var code = "";
62  process.stdin.resume();
63  process.stdin.on("data", function (chunk) { return code += chunk; });
64  process.stdin.on("end", function () { return run(code); });
65}
66