Upgrade to https://github.com/acornjs/acorn.git commit 84eda6bf
[jst.git] / src / bin / acorn.js
1 import {basename} from "path"
2 import {readFileSync as readFile} from "fs"
3 import * as acorn from "acorn"
4
5 let inputFilePaths = [], forceFileName = false, fileMode = false, silent = false, compact = false, tokenize = false
6 const options = {}
7
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>...]")
12   process.exit(status)
13 }
14
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))
20     forceFileName = true
21     break
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"
30   else {
31     let match = arg.match(/^--ecma(\d+)$/)
32     if (match)
33       options.ecmaVersion = +match[1]
34     else
35       help(1)
36   }
37 }
38
39 function run(codeList) {
40   let result = [], fileIdx = 0
41   try {
42     codeList.forEach((code, idx) => {
43       fileIdx = idx
44       if (!tokenize) {
45         result = acorn.parse(code, options)
46         options.program = result
47       } else {
48         let tokenizer = acorn.tokenizer(code, options), token
49         do {
50           token = tokenizer.getToken()
51           result.push(token)
52         } while (token.type !== acorn.tokTypes.eof)
53       }
54     })
55   } catch (e) {
56     console.error(fileMode ? e.message.replace(/\(\d+:\d+\)$/, m => m.slice(0, 1) + inputFilePaths[fileIdx] + " " + m.slice(1)) : e.message)
57     process.exit(1)
58   }
59   if (!silent) console.log(JSON.stringify(result, null, compact ? null : 2))
60 }
61
62 if (fileMode = inputFilePaths.length && (forceFileName || !inputFilePaths.includes("-") || inputFilePaths.length !== 1)) {
63   run(inputFilePaths.map(path => readFile(path, "utf8")))
64 } else {
65   let code = ""
66   process.stdin.resume()
67   process.stdin.on("data", chunk => code += chunk)
68   process.stdin.on("end", () => run([code]))
69 }