• Home
  • History
  • Annotate
Name Date Size #Lines LOC

..16-Feb-2021-

bin/H16-Feb-2021-52

dist/H03-May-2022-5,3844,733

CHANGELOG.mdH A D16-Feb-202114.3 KiB607305

LICENSEH A D16-Feb-20211.1 KiB2016

README.mdH A D16-Feb-202110.3 KiB271204

package.jsonH A D16-Feb-2021832 3635

README.md

1# Acorn
2
3A tiny, fast JavaScript parser written in JavaScript.
4
5## Community
6
7Acorn is open source software released under an
8[MIT license](https://github.com/acornjs/acorn/blob/master/acorn/LICENSE).
9
10You are welcome to
11[report bugs](https://github.com/acornjs/acorn/issues) or create pull
12requests on [github](https://github.com/acornjs/acorn). For questions
13and discussion, please use the
14[Tern discussion forum](https://discuss.ternjs.net).
15
16## Installation
17
18The easiest way to install acorn is from [`npm`](https://www.npmjs.com/):
19
20```sh
21npm install acorn
22```
23
24Alternately, you can download the source and build acorn yourself:
25
26```sh
27git clone https://github.com/acornjs/acorn.git
28cd acorn
29npm install
30```
31
32## Interface
33
34**parse**`(input, options)` is the main interface to the library. The
35`input` parameter is a string, `options` can be undefined or an object
36setting some of the options listed below. The return value will be an
37abstract syntax tree object as specified by the [ESTree
38spec](https://github.com/estree/estree).
39
40```javascript
41let acorn = require("acorn");
42console.log(acorn.parse("1 + 1"));
43```
44
45When encountering a syntax error, the parser will raise a
46`SyntaxError` object with a meaningful message. The error object will
47have a `pos` property that indicates the string offset at which the
48error occurred, and a `loc` object that contains a `{line, column}`
49object referring to that same position.
50
51Options can be provided by passing a second argument, which should be
52an object containing any of these fields:
53
54- **ecmaVersion**: Indicates the ECMAScript version to parse. Must be
55  either 3, 5, 6 (2015), 7 (2016), 8 (2017), 9 (2018), 10 (2019) or 11
56  (2020, partial support). This influences support for strict mode,
57  the set of reserved words, and support for new syntax features.
58  Default is 10.
59
60  **NOTE**: Only 'stage 4' (finalized) ECMAScript features are being
61  implemented by Acorn. Other proposed new features can be implemented
62  through plugins.
63
64- **sourceType**: Indicate the mode the code should be parsed in. Can be
65  either `"script"` or `"module"`. This influences global strict mode
66  and parsing of `import` and `export` declarations.
67
68  **NOTE**: If set to `"module"`, then static `import` / `export` syntax
69  will be valid, even if `ecmaVersion` is less than 6.
70
71- **onInsertedSemicolon**: If given a callback, that callback will be
72  called whenever a missing semicolon is inserted by the parser. The
73  callback will be given the character offset of the point where the
74  semicolon is inserted as argument, and if `locations` is on, also a
75  `{line, column}` object representing this position.
76
77- **onTrailingComma**: Like `onInsertedSemicolon`, but for trailing
78  commas.
79
80- **allowReserved**: If `false`, using a reserved word will generate
81  an error. Defaults to `true` for `ecmaVersion` 3, `false` for higher
82  versions. When given the value `"never"`, reserved words and
83  keywords can also not be used as property names (as in Internet
84  Explorer's old parser).
85
86- **allowReturnOutsideFunction**: By default, a return statement at
87  the top level raises an error. Set this to `true` to accept such
88  code.
89
90- **allowImportExportEverywhere**: By default, `import` and `export`
91  declarations can only appear at a program's top level. Setting this
92  option to `true` allows them anywhere where a statement is allowed.
93
94- **allowAwaitOutsideFunction**: By default, `await` expressions can
95  only appear inside `async` functions. Setting this option to
96  `true` allows to have top-level `await` expressions. They are
97  still not allowed in non-`async` functions, though.
98
99- **allowHashBang**: When this is enabled (off by default), if the
100  code starts with the characters `#!` (as in a shellscript), the
101  first line will be treated as a comment.
102
103- **locations**: When `true`, each node has a `loc` object attached
104  with `start` and `end` subobjects, each of which contains the
105  one-based line and zero-based column numbers in `{line, column}`
106  form. Default is `false`.
107
108- **onToken**: If a function is passed for this option, each found
109  token will be passed in same format as tokens returned from
110  `tokenizer().getToken()`.
111
112  If array is passed, each found token is pushed to it.
113
114  Note that you are not allowed to call the parser from the
115  callback—that will corrupt its internal state.
116
117- **onComment**: If a function is passed for this option, whenever a
118  comment is encountered the function will be called with the
119  following parameters:
120
121  - `block`: `true` if the comment is a block comment, false if it
122    is a line comment.
123  - `text`: The content of the comment.
124  - `start`: Character offset of the start of the comment.
125  - `end`: Character offset of the end of the comment.
126
127  When the `locations` options is on, the `{line, column}` locations
128  of the comment’s start and end are passed as two additional
129  parameters.
130
131  If array is passed for this option, each found comment is pushed
132  to it as object in Esprima format:
133
134  ```javascript
135  {
136    "type": "Line" | "Block",
137    "value": "comment text",
138    "start": Number,
139    "end": Number,
140    // If `locations` option is on:
141    "loc": {
142      "start": {line: Number, column: Number}
143      "end": {line: Number, column: Number}
144    },
145    // If `ranges` option is on:
146    "range": [Number, Number]
147  }
148  ```
149
150  Note that you are not allowed to call the parser from the
151  callback—that will corrupt its internal state.
152
153- **ranges**: Nodes have their start and end characters offsets
154  recorded in `start` and `end` properties (directly on the node,
155  rather than the `loc` object, which holds line/column data. To also
156  add a
157  [semi-standardized](https://bugzilla.mozilla.org/show_bug.cgi?id=745678)
158  `range` property holding a `[start, end]` array with the same
159  numbers, set the `ranges` option to `true`.
160
161- **program**: It is possible to parse multiple files into a single
162  AST by passing the tree produced by parsing the first file as the
163  `program` option in subsequent parses. This will add the toplevel
164  forms of the parsed file to the "Program" (top) node of an existing
165  parse tree.
166
167- **sourceFile**: When the `locations` option is `true`, you can pass
168  this option to add a `source` attribute in every node’s `loc`
169  object. Note that the contents of this option are not examined or
170  processed in any way; you are free to use whatever format you
171  choose.
172
173- **directSourceFile**: Like `sourceFile`, but a `sourceFile` property
174  will be added (regardless of the `location` option) directly to the
175  nodes, rather than the `loc` object.
176
177- **preserveParens**: If this option is `true`, parenthesized expressions
178  are represented by (non-standard) `ParenthesizedExpression` nodes
179  that have a single `expression` property containing the expression
180  inside parentheses.
181
182**parseExpressionAt**`(input, offset, options)` will parse a single
183expression in a string, and return its AST. It will not complain if
184there is more of the string left after the expression.
185
186**tokenizer**`(input, options)` returns an object with a `getToken`
187method that can be called repeatedly to get the next token, a `{start,
188end, type, value}` object (with added `loc` property when the
189`locations` option is enabled and `range` property when the `ranges`
190option is enabled). When the token's type is `tokTypes.eof`, you
191should stop calling the method, since it will keep returning that same
192token forever.
193
194In ES6 environment, returned result can be used as any other
195protocol-compliant iterable:
196
197```javascript
198for (let token of acorn.tokenizer(str)) {
199  // iterate over the tokens
200}
201
202// transform code to array of tokens:
203var tokens = [...acorn.tokenizer(str)];
204```
205
206**tokTypes** holds an object mapping names to the token type objects
207that end up in the `type` properties of tokens.
208
209**getLineInfo**`(input, offset)` can be used to get a `{line,
210column}` object for a given program string and offset.
211
212### The `Parser` class
213
214Instances of the **`Parser`** class contain all the state and logic
215that drives a parse. It has static methods `parse`,
216`parseExpressionAt`, and `tokenizer` that match the top-level
217functions by the same name.
218
219When extending the parser with plugins, you need to call these methods
220on the extended version of the class. To extend a parser with plugins,
221you can use its static `extend` method.
222
223```javascript
224var acorn = require("acorn");
225var jsx = require("acorn-jsx");
226var JSXParser = acorn.Parser.extend(jsx());
227JSXParser.parse("foo(<bar/>)");
228```
229
230The `extend` method takes any number of plugin values, and returns a
231new `Parser` class that includes the extra parser logic provided by
232the plugins.
233
234## Command line interface
235
236The `bin/acorn` utility can be used to parse a file from the command
237line. It accepts as arguments its input file and the following
238options:
239
240- `--ecma3|--ecma5|--ecma6|--ecma7|--ecma8|--ecma9|--ecma10`: Sets the ECMAScript version
241  to parse. Default is version 9.
242
243- `--module`: Sets the parsing mode to `"module"`. Is set to `"script"` otherwise.
244
245- `--locations`: Attaches a "loc" object to each node with "start" and
246  "end" subobjects, each of which contains the one-based line and
247  zero-based column numbers in `{line, column}` form.
248
249- `--allow-hash-bang`: If the code starts with the characters #! (as
250  in a shellscript), the first line will be treated as a comment.
251
252- `--compact`: No whitespace is used in the AST output.
253
254- `--silent`: Do not output the AST, just return the exit status.
255
256- `--help`: Print the usage information and quit.
257
258The utility spits out the syntax tree as JSON data.
259
260## Existing plugins
261
262 - [`acorn-jsx`](https://github.com/RReverser/acorn-jsx): Parse [Facebook JSX syntax extensions](https://github.com/facebook/jsx)
263
264Plugins for ECMAScript proposals:
265
266 - [`acorn-stage3`](https://github.com/acornjs/acorn-stage3): Parse most stage 3 proposals, bundling:
267   - [`acorn-class-fields`](https://github.com/acornjs/acorn-class-fields): Parse [class fields proposal](https://github.com/tc39/proposal-class-fields)
268   - [`acorn-import-meta`](https://github.com/acornjs/acorn-import-meta): Parse [import.meta proposal](https://github.com/tc39/proposal-import-meta)
269   - [`acorn-numeric-separator`](https://github.com/acornjs/acorn-numeric-separator): Parse [numeric separator proposal](https://github.com/tc39/proposal-numeric-separator)
270   - [`acorn-private-methods`](https://github.com/acornjs/acorn-private-methods): parse [private methods, getters and setters proposal](https://github.com/tc39/proposal-private-methods)n
271