1 import {basename} from "path"
2 import {readFileSync as readFile} from "fs"
3 import * as acorn from "acorn"
5 let inputFilePaths = [], forceFileName = false, fileMode = false, silent = false, compact = false, tokenize = false
8 function help(status) {
9 const print = (status === 0) ? console.log : console.error
10 print("usage: " + basename(process.argv[1]) + " [--ecma3|--ecma5|--ecma6|--ecma7|--ecma8|--ecma9|...|--ecma2015|--ecma2016|--ecma2017|--ecma2018|...]")
11 print(" [--tokenize] [--locations] [--allow-hash-bang] [--allow-await-outside-function] [--compact] [--silent] [--module] [--help] [--] [<infile>...]")
15 for (let i = 2; i < process.argv.length; ++i) {
16 const arg = process.argv[i]
17 if (arg[0] !== "-" || arg === "-") inputFilePaths.push(arg)
18 else if (arg === "--") {
19 inputFilePaths.push(...process.argv.slice(i + 1))
22 } else if (arg === "--locations") options.locations = true
23 else if (arg === "--allow-hash-bang") options.allowHashBang = true
24 else if (arg === "--allow-await-outside-function") options.allowAwaitOutsideFunction = true
25 else if (arg === "--silent") silent = true
26 else if (arg === "--compact") compact = true
27 else if (arg === "--help") help(0)
28 else if (arg === "--tokenize") tokenize = true
29 else if (arg === "--module") options.sourceType = "module"
31 let match = arg.match(/^--ecma(\d+)$/)
33 options.ecmaVersion = +match[1]
39 function run(codeList) {
40 let result = [], fileIdx = 0
42 codeList.forEach((code, idx) => {
45 result = acorn.parse(code, options)
46 options.program = result
48 let tokenizer = acorn.tokenizer(code, options), token
50 token = tokenizer.getToken()
52 } while (token.type !== acorn.tokTypes.eof)
56 console.error(fileMode ? e.message.replace(/\(\d+:\d+\)$/, m => m.slice(0, 1) + inputFilePaths[fileIdx] + " " + m.slice(1)) : e.message)
59 if (!silent) console.log(JSON.stringify(result, null, compact ? null : 2))
62 if (fileMode = inputFilePaths.length && (forceFileName || !inputFilePaths.includes("-") || inputFilePaths.length !== 1)) {
63 run(inputFilePaths.map(path => readFile(path, "utf8")))
66 process.stdin.resume()
67 process.stdin.on("data", chunk => code += chunk)
68 process.stdin.on("end", () => run([code]))