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.

  1. $ node
  2. > var esprima = require('esprima')
  3. > esprima.parse('"use strict"; with (x) {}')
  4. 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:

  1. $ node
  2. > var esprima = require('esprima')
  3. > esprima.parse('"use strict"; with (x) {}', { tolerant: true })
  4. Program {
  5. type: 'Program',
  6. body:
  7. [ Directive {
  8. type: 'ExpressionStatement',
  9. expression: [Object],
  10. directive: 'use strict' },
  11. WithStatement { type: 'WithStatement', object: [Object], body: [Object] } ],
  12. sourceType: 'script',
  13. errors:
  14. [ { Error: Line 1: Strict mode code may not include a with statement
  15. index: 13,
  16. lineNumber: 1,
  17. 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.