Acorn
A tiny, fast JavaScript parser, written completely in JavaScript.
The easiest way to install acorn is withnpm.
npm install acorn
Alternately, download the source.
git clone https://github.com/marijnh/acorn.git
When run in a CommonJS (node.js) or AMD environment, exported values appear in the interfaces exposed by the individual files, as usual. When loaded in the browser (Acorn works in any JS-enabled browser more recent than IE5) without any kind of module management, a single global objectacornwill be defined, and all the exported properties will be added to that.
This file contains the actual parser (and is what you get when yourequire("acorn")in node.js).
parse(input, options)is used to parse a JavaScript program. Theinputparameter is a string,optionscan be undefined or an object setting some of the options listed below. The return value will be an abstract syntax tree object as specified by theMozilla Parser API.
When encountering a syntax error, the parser will raise aSyntaxErrorobject with a meaningful message. The error object will have aposproperty that indicates the character offset at which the error occurred, and alocobject that contains a{line, column}object referring to that same position.
ecmaVersion: Indicates the ECMAScript version to parse. Must be either 3, 5, or 6. This influences support for strict mode, the set of reserved words, and support for new syntax features. Default is 5.
strictSemicolons: Iftrue, prevents the parser from doing automatic semicolon insertion, and statements that do not end with a semicolon will generate an error. Defaults tofalse.
allowTrailingCommas: Iffalse, the parser will not allow trailing commas in array and object literals. Default istrue.
forbidReserved: Iftrue, using a reserved word will generate an error. Defaults tofalse. When given the value"everywhere", 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.
locations: Whentrue, 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.
onToken: If a function is passed for this option, each found token will be passed in same format astokenize()returns.
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 thelocationsoptions 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:
{"type":"Line"|"Block","value":"comment text","range":...,"loc":...}
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 asemi-standardized"range" property 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 thelocationsoption istrue, you can pass this option to add asourceattribute in every node’slocobject. 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: LikesourceFile, but asourceFileproperty will be added directly to the nodes, rather than thelocobject.
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.
getLineInfo(input, offset)can be used to get a{line, column}object for a given program string and character offset.
tokenize(input, options)exports a primitive interface to Acorn's tokenizer. The function takes an input string and options similar toparse(though only some options are meaningful here), and returns a function that can be called repeatedly to read a single token, and returns a{start, end, type, value}object (with addedlocproperty when thelocationsoption is enabled andrangeproperty when therangesoption is enabled).
tokTypesholds an object mapping names to the token type objects that end up in thetypeproperties of tokens.
Escodegen supports generating comments from AST, attached in Esprima-specific format. In order to simulate same format in Acorn, consider following example:
varcomments=[], tokens=[];varast=acorn.parse('var x = 42; // answer', {//collect ranges for each noderanges:true,//collect comments in Esprima's formatonComment:comments,//collect token rangesonToken:tokens});//attach comments using collected informationescodegen.attachComments(ast, comments, tokens);//generate codeconsole.log(escodegen.generate(ast, {comment:true}));//> 'var x = 42; // answer'
Using Acorn in an environment with a Content Security Policy
Some contexts, such as Chrome Web Apps, disallow run-time code evaluation. Acorn usesnew Functionto generate fast functions that test whether a word is in a given set, and will trigger a security error when used in a context with such aContent Security Policy(see#90and#123).
Thebin/without_evalscript can be used to generate a version ofacorn.jsthat has the generated code inlined, and can thus run without evaluating anything. In versions of this library downloaded from NPM, this script will be available asacorn_csp.js.
This file implements an error-tolerant parser. It exposes a single function.
parse_dammit(input, options)takes the same arguments and returns the same syntax tree as theparsefunction inacorn.js, but never raises an error, and will do its best to parse syntactically invalid code in as meaningful a way as it can. It'll insert identifier nodes with name"✖"as placeholders in places where it can't make sense of the input. Depends onacorn.js, because it uses the same tokenizer.
Implements an abstract syntax tree walker. Will store its interface inacorn.walkwhen used without a module system.
simple(node, visitors, base, state)does a 'simple' walk over a tree.nodeshould be the AST node to walk, andvisitorsan object with properties whose names correspond to node types in theMozilla Parser API. 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.baseis a walker algorithm, andstateis 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 it to track scope at each point in the tree.)
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 callbacks in thestateparameter.
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.stateis the start state, andfunctionsshould 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 thecargument on it with(node, state)arguments. The optionalbaseargument provides the fallback walker functions for node types that aren't handled in thefunctionsobject. If not given, the default walkers will be used.
make(functions, base)builds a new walker object by using the walker functions infunctionsand filling in the missing ones by taking defaults frombase.
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 predicatetest.startendendcan be eithernull(as wildcard) or a number.testmay 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.baseandstateare 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 nodesafterthe given position (testing outer nodes before inner nodes).
Thebin/acornutility 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: Sets the ECMAScript version to parse. Default is version 5.
--strictSemicolons: Prevents the parser from doing automatic semicolon insertion. Statements that do not end in semicolons will generate an error.
--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.
--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.
网友评论