Tolerant Mode
When Esprima parser is given an input that does not represent a valid JavaScript program, it throws an exception. With the tolerant mode however, the parser may choose to continue parsing and produce a syntax tree. This is best demonstrated with an example.
Consider the following parsing session. The exception is expected, since a with
statement is not permitted in strict mode.
- $ node
- > var esprima = require('esprima')
- > esprima.parse('"use strict"; with (x) {}')
- Error: Line 1: Strict mode code may not include a with statement
If the tolerant mode is activated by setting the tolerant
flag to true in the parsing configuration, the parser behaves differently:
- $ node
- > var esprima = require('esprima')
- > esprima.parse('"use strict"; with (x) {}', { tolerant: true })
- Program {
- type: 'Program',
- body:
- [ Directive {
- type: 'ExpressionStatement',
- expression: [Object],
- directive: 'use strict' },
- WithStatement { type: 'WithStatement', object: [Object], body: [Object] } ],
- sourceType: 'script',
- errors:
- [ { Error: Line 1: Strict mode code may not include a with statement
- index: 13,
- lineNumber: 1,
- description: 'Strict mode code may not include a with statement' } ] }
In the above case, the parser does not throw an exception and it still returns a syntax tree. However, it also adds a new array named errors
, it contains each and every syntax error that the parser manages to tolerate without causing it to stop right away. Each entry in the errors
has the detailed information regarding the error, including the description and the location.
Note that the tolerant mode is intended to deal with very few types of syntax errors. It is unable to robustly handle every possible invalid program.