_acorn.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #!/usr/bin/env node
  2. 'use strict';
  3. var path = require('path');
  4. var fs = require('fs');
  5. var acorn = require('../dist/acorn.js');
  6. var infile;
  7. var forceFile;
  8. var silent = false;
  9. var compact = false;
  10. var tokenize = false;
  11. var options = {};
  12. function help(status) {
  13. var print = (status == 0) ? console.log : console.error;
  14. print("usage: " + path.basename(process.argv[1]) + " [--ecma3|--ecma5|--ecma6|--ecma7|--ecma8|--ecma9|...|--ecma2015|--ecma2016|--ecma2017|--ecma2018|...]");
  15. print(" [--tokenize] [--locations] [---allow-hash-bang] [--compact] [--silent] [--module] [--help] [--] [infile]");
  16. process.exit(status);
  17. }
  18. for (var i = 2; i < process.argv.length; ++i) {
  19. var arg = process.argv[i];
  20. if ((arg == "-" || arg[0] != "-") && !infile) { infile = arg; }
  21. else if (arg == "--" && !infile && i + 2 == process.argv.length) { forceFile = infile = process.argv[++i]; }
  22. else if (arg == "--locations") { options.locations = true; }
  23. else if (arg == "--allow-hash-bang") { options.allowHashBang = 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. function run(code) {
  38. var result;
  39. try {
  40. if (!tokenize) {
  41. result = acorn.parse(code, options);
  42. } else {
  43. result = [];
  44. var tokenizer$$1 = acorn.tokenizer(code, options), token;
  45. do {
  46. token = tokenizer$$1.getToken();
  47. result.push(token);
  48. } while (token.type != acorn.tokTypes.eof)
  49. }
  50. } catch (e) {
  51. console.error(e.message);
  52. process.exit(1);
  53. }
  54. if (!silent) { console.log(JSON.stringify(result, null, compact ? null : 2)); }
  55. }
  56. if (forceFile || infile && infile != "-") {
  57. run(fs.readFileSync(infile, "utf8"));
  58. } else {
  59. var code = "";
  60. process.stdin.resume();
  61. process.stdin.on("data", function (chunk) { return code += chunk; });
  62. process.stdin.on("end", function () { return run(code); });
  63. }