Chapter 2. Syntactic Analysis (Parsing)
The main use case of Esprima is to parse a JavaScript program. This is also known as syntactic analysis.
Esprima parser takes a string representing a valid JavaScript program and produces a syntax tree, an ordered tree that describes the syntactic structure of the program. The resulting syntax tree is useful for various purposes, from program transformation to static program analysis.
The interface of the parseScript
/parseModule
function is as follows:
- esprima.parseScript(input, config, delegate)
- esprima.parseModule(input, config, delegate)
where
input
is the string representing the program to be parsedconfig
is an object used to customize the parsing behavior (optional)delegate
is a callback function invoked for every single node (optional)
The input
argument is mandatory. Its type must be a string, otherwise the parsing behavior is not determined. The other two arguments, config
and delegate
, are optional.
The object returned by the parseScript
/parseModule
function is the syntax tree, following the format described in details in Appendix A. Syntax Tree Format.
The description of various parsing configuration is summarized in the following table:
Name | Type | Default | Description |
---|---|---|---|
jsx | Boolean | false | Support JSX syntax |
range | Boolean | false | Annotate each node with its index-based location |
loc | Boolean | false | Annotate each node with its column and row-based location |
tolerant | Boolean | false | Tolerate a few cases of syntax errors |
tokens | Boolean | false | Collect every token |
comment | Boolean | false | Collect every line and block comment |
The previous chapter, Getting Started, already demonstrates the simplest possible example of using Esprima parser. To use it as the basis for further experiments, use Runkit and tweak the existing demo notebook: runkit.com/ariya/esprima-parse-demo.