Technical Documentation: acornjs/acorn
βΉοΈ Provenance: Multi-Tier Ingestion Β· CodeWiki Reference
Overview (`README.md`)
Acorn
A tiny, fast JavaScript parser, written completely in JavaScript.
Community
Acorn is open source software released under an
MIT license.
You are welcome to
report bugs or create pull
requests on github.
Packages
This repository holds three packages:
- acorn: The
main parser - acorn-loose: The
error-tolerant parser - acorn-walk: The
syntax tree walker
To build the content of the repository, run npm install.
git clone https://github.com/acornjs/acorn.git
cd acorn
npm installPlugin developments
Acorn is designed to support plugins which can, within reasonable
bounds, redefine the way the parser works. Plugins can add new token
types and new tokenizer contexts (if necessary), and extend methods in
the parser object. This is not a clean, elegant APIβusing it requires
an understanding of Acorn's internals, and plugins are likely to break
whenever those internals are significantly changed. But still, it is
possible, in this way, to create parsers for JavaScript dialects
without forking all of Acorn. And in principle it is even possible to
combine such plugins, so that if you have, for example, a plugin for
parsing types and a plugin for parsing JSX-style XML literals, you
could load them both and parse code with both JSX tags and types.
A plugin is a function from a parser class to an extended parser
class. Plugins can be used by simply applying them to the Parser
class (or a version of that already extended by another plugin). But
because that gets a little awkward, syntactically, when you are using
multiple plugins, the static method Parser.extend can be called with
any number of plugin values as arguments to create a Parser class
extended by all those plugins. You'll usually want to create such an
extended class only once, and then repeatedly call parse on it, to
avoid needlessly confusing the JavaScript engine's optimizer.
const {Parser} = require("acorn")
const MyParser = Parser.extend(
require("acorn-jsx")(),
require("acorn-bigint")
)
console.log(MyParser.parse("// Some bigint + JSX code"))Plugins override methods in their new parser class to implement
additional functionality. It is recommended for a plugin package to
export its plugin function as its default value or, if it takes
configuration parameters, to export a constructor function that
creates the plugin function.
This is what a trivial plugin, which adds a bit of code to thereadToken method, might look like:
module.exports = function noisyReadToken(Parser) {
return class extends Parser {
readToken(code) {
console.log("Reading a token!")
super.readToken(code)
}
}
}Overview (`acorn-loose/README.md`)
Acorn loose parser
An error-tolerant JavaScript parser written in JavaScript.
This parser will parse any text into an
ESTree syntax tree that is a
reasonable approximation of what it might mean as a JavaScript
program.
It will, to recover from missing brackets, treat whitespace as
significant, which has the downside that it might mis-parse a valid
but weirdly indented file. It is recommended to always try a parse
with the regular acorn parser first, and only fall back to this
parser when that one finds syntax errors.
Community
Acorn is open source software released under an
MIT license.
You are welcome to report
bugs or create pull requests
on github.
Installation
The easiest way to install acorn-loose is from npm:
npm install acorn-looseAlternately, you can download the source and build acorn yourself:
git clone https://github.com/acornjs/acorn.git
cd acorn
npm installInterface
parse(input, options) takes an input string and a set of options
(the same options as
acorn
takes), and returns a syntax tree, even if the code isn't
syntactically valid. It'll insert identifier nodes with name "β" as
placeholders in places where it can't make sense of the input. Depends
on the acorn package, because it uses the same tokenizer.
import * as acornLoose from "acorn-loose"
console.log(acornLoose.parse("1 / * 4 )[2]", {ecmaVersion: 2020}))Like the regular parser, the loose parser supports plugins. You can
take the LooseParser class exported by the module, and call its
static extend method with one or more plugins to get a customized
parser class. The class has a static parse method that acts like the
top-level parse method.
isDummy(node) takes a Node and returns true if it is a dummy node
inserted by the parser. The function performs a simple equality check on the
node's name.
Overview (`acorn-walk/README.md`)
Acorn AST walker
An abstract syntax tree walker for the
ESTree format.
Community
Acorn is open source software released under an
MIT license.
You are welcome to
report bugs or create pull
requests on github.
Installation
The easiest way to install acorn is from npm:
npm install acorn-walkAlternately, you can download the source and build acorn yourself:
git clone https://github.com/acornjs/acorn.git
cd acorn
npm installInterface
An algorithm for recursing through a syntax tree is stored as an
object, with a property for each tree node type holding a function
that will recurse through such a node. There are several ways to run
such a walker.
simple(node, visitors, base, state) does a 'simple' walk over a
tree. node should be the AST node to walk, and visitors an object
with properties whose names correspond to node types in the ESTree
spec. The properties should contain
functions that will be called with the node object and, if applicable
the state at that point. The last two arguments are optional. base
is a walker algorithm, and state is a start state. The default
walker will simply visit all statements and expressions and not
produce a meaningful state. (An example of a use of state is to track
scope at each point in the tree.)
import * as acorn from "acorn"
import * as walk from "acorn-walk"
walk.simple(acorn.parse("let x = 10"), {
Literal(node) {
console.log(`Found a literal: ${node.value}`)
}
})ancestor(node, visitors, base, state) does a 'simple' walk over
a tree, building up an array of ancestor nodes (including the current node)
and passing the array to the callbacks as a third parameter.
import * as acorn from "acorn"
import * as walk from "acorn-walk"
walk.ancestor(acorn.parse("foo('hi')"), {
Literal(_node, _state, ancestors) {
console.log("This literal's ancestors are:", ancestors.map(n => n.type))
}
})recursive(node, state, functions, base) does a 'recursive'
walk, where the walker functions are responsible for continuing the
walk on the child nodes of their target node. state is the start
state, and functions should contain an object that maps node types
to walker functions. Such functions are called with (node, state, c)
arguments, and can cause the walk to continue on a sub-node by calling
the c argument on it with (node, state) arguments. The optionalbase argument provides the fallback walker functions for node types
that aren't handled in the functions object. If not given, the
default walkers will be used.
make(functions, base) builds a new walker object by using the
walker functions in functions and filling in the missing ones by
taking defaults from base.
full(node, callback, base, state) does a 'full' walk over a
tree, calling the callback with the arguments (node, state, type) for
each node
fullAncestor(node, callback, base, state) does a 'full' walk
over a tree, building up an array of ancestor nodes (including the
current node) and passing the array to the callbacks as a third
parameter.
import * as acorn from "acorn"
import * as walk from "acorn-walk"
walk.full(acorn.parse("1 + 1"), node => {
console.log(`There's a ${node.type} node at ${node.ch}`)
})findNodeAt(node, start, end, test, base, state) tries to locate
a node in a tree at the given start and/or end offsets, which
satisfies the predicate test. start and end can be either null
(as wildcard) or a number. test may be a string (indicating a node
type) or a function that takes (nodeType, node) arguments and
returns a boolean indicating whether this node is interesting. base
and state are optional, and can be used to specify a custom walker.
Nodes are tested from inner to outer, so if two nodes match the
boundaries, the inner one will be preferred.
findNodeAround(node, pos, test, base, state) is a lot likefindNodeAt, but will match any node that exists 'around' (spanning)
the given position.
findNodeAfter(node, pos, test, base, state) is similar tofindNodeAround, but will match all nodes after the given position
(testing outer nodes before inner nodes).
Overview (`acorn/README.md`)
Acorn
A tiny, fast JavaScript parser written in JavaScript.
Community
Acorn is open source software released under an
MIT license.
You are welcome to
report bugs or create pull
requests on github.
Installation
The easiest way to install acorn is from npm:
npm install acornAlternately, you can download the source and build acorn yourself:
git clone https://github.com/acornjs/acorn.git
cd acorn
npm installImporting acorn
ESM as well as CommonJS is supported for all 3: acorn, acorn-walk and acorn-loose.
ESM example for acorn:
import * as acorn from "acorn"CommonJS example for acorn:
let acorn = require("acorn")ESM is preferred, as it allows better editor auto-completions by offering TypeScript support.
For this reason, following examples will use ESM imports.
Interface
parse(input, options) is the main interface to the library. Theinput parameter is a string, options must be an object setting
some of the options listed below. The return value will be an abstract
syntax tree object as specified by the ESTree
spec.
import * as acorn from "acorn"
console.log(acorn.parse("1 + 1", {ecmaVersion: 2020}))When encountering a syntax error, the parser will raise aSyntaxError object with a meaningful message. The error object will
have a pos property that indicates the string offset at which the
error occurred, and a loc object that contains a {line, column}
object referring to that same position.
Options are provided by in a second argument, which should be an
object containing any of these fields (only ecmaVersion is
required):
ecmaVersion: Indicates the ECMAScript version to parse. Can be a
number, either in year (2022) or plain version number (6) form,
or"latest"(the latest the library supports). This influences
support for strict mode, the set of reserved words, and support for
new syntax features.NOTE: Only 'stage 4' (finalized) ECMAScript features are being
implemented by Acorn. Other proposed new features must be
implemented through plugins.sourceType: Indicate the mode the code should be parsed in. Can be
either"script","module"or"commonjs". This influences global strict mode
and parsing ofimportandexportdeclarations.NOTE: If set to
"module", then staticimport/exportsyntax
will be valid, even ifecmaVersionis less than 6. If set to"commonjs",
it is the same as"script"except that the top-level scope behaves like a function.strict: When set to true, enable strict parsing mode even if
sourceTypeis"script".onInsertedSemicolon: If given a callback, that callback will be
called whenever a missing semicolon is inserted by the parser. The
callback will be given the character offset of the point where the
semicolon is inserted as argument, and iflocationsis on, also a{line, column}object representing this position.onTrailingComma: Like
onInsertedSemicolon, but for trailing
commas.allowReserved: If
false, using a reserved word will generate
an error. Defaults totrueforecmaVersion3,falsefor higher
versions. When given the value"never", reserved words and
keywords can also not be used as property names (as in Internet
Explorer's old parser).allowReturnOutsideFunction: By default, a return statement at
the top level raises an error. Set this totrueto accept such
code.allowImportExportEverywhere: By default,
importandexport
declarations can only appear at a program's top level. Setting this
option totrueallows them anywhere where a statement is allowed,
and also allowsimport.metaexpressions to appear in scripts
(whensourceTypeis not"module").allowAwaitOutsideFunction: If
false,awaitexpressions can
only appear insideasyncfunctions. Defaults totruein modules
forecmaVersion2022 and later,falsefor lower versions.
Setting this option totrueallows to have top-levelawait
expressions. They are still not allowed in non-asyncfunctions,
though. Setting this option totrueis not allowed whensourceType: "commonjs".allowSuperOutsideMethod: By default,
superoutside a method
raises an error. Set this totrueto accept such code.allowHashBang: When this is enabled, if the code starts with the
characters#!(as in a shellscript), the first line will be
treated as a comment. Defaults to true whenecmaVersion>= 2023.checkPrivateFields: By default, the parser will verify that
private properties are only used in places where they are valid and
have been declared. Set this to false to turn such checks off.locations: When
true, each node has alocobject attached
withstartandendsubobjects, each of which contains the
one-based line and zero-based column numbers in{line, column}
form. Default isfalse.startLocation: An optional
{line, column}object to use for
the start of the parse. This is mostly useful when usingparseExpressionAtwithlocations: true, to prevent the parser
from having to determine the line position at the start position.onToken: If a function is passed for this option, each found
token will be passed in same format as tokens returned fromtokenizer().getToken().If array is passed, each found token is pushed to it.
Note that you are not allowed to call the parser from the
callbackβthat will corrupt its internal state.onComment: If a function is passed for this option, whenever a
comment is encountered the function will be called with the
following parameters:block:trueif the comment is a block comment, false if it
is a line comment.text: The content of the comment.start: Character offset of the start of the comment.end: Character offset of the end of the comment.
When the
locationsoptions is on, the{line, column}locations
of the commentβs start and end are passed as two additional
parameters.If array is passed for this option, each found comment is pushed
to it as object in Esprima format:javascript{ "type": "Line" | "Block", "value": "comment text", "start": Number, "end": Number, // If `locations` option is on: "loc": { "start": {line: Number, column: Number} "end": {line: Number, column: Number} }, // If `ranges` option is on: "range": [Number, Number] }Note that you are not allowed to call the parser from the
callbackβthat will corrupt its internal state.ranges: Nodes have their start and end characters offsets
recorded instartandendproperties (directly on the node,
rather than thelocobject, which holds line/column data. To also
add a
semi-standardizedrangeproperty holding a[start, end]array with the same
numbers, set therangesoption totrue.program: It is possible to parse multiple files into a single
AST by passing the tree produced by parsing the first file as theprogramoption in subsequent parses. This will add the toplevel
forms of the parsed file to the "Program" (top) node of an existing
parse tree.sourceFile: When the
locationsoption istrue, you can pass
this option to add asourceattribute in every nodeβsloc
object. Note that the contents of this option are not examined or
processed in any way; you are free to use whatever format you
choose.directSourceFile: Like
sourceFile, but asourceFileproperty
will be added (regardless of thelocationoption) directly to the
nodes, rather than thelocobject.preserveParens: If this option is
true, parenthesized expressions
are represented by (non-standard)ParenthesizedExpressionnodes
that have a singleexpressionproperty containing the expression
inside parentheses.
parseExpressionAt(input, offset, options) will parse a single
expression in a string, and return its AST. It will not complain if
there is more of the string left after the expression.
tokenizer(input, options) returns an object with a getToken
method that can be called repeatedly to get the next token, a {start, end, type, value} object (with added loc property when thelocations option is enabled and range property when the ranges
option is enabled). When the token's type is tokTypes.eof, you
should stop calling the method, since it will keep returning that same
token forever.
Note that tokenizing JavaScript without parsing it is, in modern
versions of the language, not really possible due to the way syntax is
overloaded in ways that can only be disambiguated by the parse
context. This package applies a bunch of heuristics to try and do a
reasonable job, but you are advised to use parse with the onToken
option instead of this.
In ES6 environment, returned result can be used as any other
protocol-compliant iterable:
for (let token of acorn.tokenizer(str)) {
// iterate over the tokens
}
// transform code to array of tokens:
var tokens = [...acorn.tokenizer(str)]tokTypes holds an object mapping names to the token type objects
that end up in the type properties of tokens.
getLineInfo(input, offset) can be used to get a {line, column} object for a given program string and offset.
The `Parser` class
Instances of the Parser class contain all the state and logic
that drives a parse. It has static methods parse,parseExpressionAt, and tokenizer that match the top-level
functions by the same name.
When extending the parser with plugins, you need to call these methods
on the extended version of the class. To extend a parser with plugins,
you can use its static extend method.
var acorn = require("acorn")
var jsx = require("acorn-jsx")
var JSXParser = acorn.Parser.extend(jsx())
JSXParser.parse("foo(<bar/>)", {ecmaVersion: 2020})The extend method takes any number of plugin values, and returns a
new Parser class that includes the extra parser logic provided by
the plugins.
Command line interface
The bin/acorn utility can be used to parse a file from the command
line. It accepts as arguments its input file and the following
options:
--ecma3|--ecma5|--ecma6|--ecma7|--ecma8|--ecma9|--ecma10: Sets the ECMAScript version
to parse. Default is version 9.--module: Sets the parsing mode to"module". Is set to"script"otherwise.--locations: Attaches a "loc" object to each node with "start" and
"end" subobjects, each of which contains the one-based line and
zero-based column numbers in{line, column}form.--allow-hash-bang: If the code starts with the characters #! (as
in a shellscript), the first line will be treated as a comment.--allow-await-outside-function: Allows top-levelawaitexpressions.
See theallowAwaitOutsideFunctionoption for more information.--compact: No whitespace is used in the AST output.--silent: Do not output the AST, just return the exit status.--help: Print the usage information and quit.
The utility spits out the syntax tree as JSON data.
Existing plugins
--- METRICS ---
- Files Extracted: 4
- Estimated Token Budget: ~5495 tokens
- Canonical Reference: https://codewiki.google/github.com/acornjs/acorn