租房小程序前端代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

282 lines
10 KiB

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