bin.js 2.2 KB

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