1Error handling
2==============
3
4Errors during parsing or analysis are represented using the `PhpParser\Error` exception class. In addition to an error
5message, an error can also store additional information about the location the error occurred at.
6
7How much location information is available depends on the origin of the error. At a minimum the start line of the error
8is usually available.
9
10Column information
11------------------
12
13Before using column information, its availability needs to be checked with `$e->hasColumnInfo()`, as the precise
14location of an error cannot always be determined. The methods for retrieving column information also have to be passed
15the source code of the parsed file. An example for printing an error:
16
17```php
18if ($e->hasColumnInfo()) {
19    echo $e->getRawMessage() . ' from ' . $e->getStartLine() . ':' . $e->getStartColumn($code)
20        . ' to ' . $e->getEndLine() . ':' . $e->getEndColumn($code);
21    // or:
22    echo $e->getMessageWithColumnInfo($code);
23} else {
24    echo $e->getMessage();
25}
26```
27
28Both line numbers and column numbers are 1-based. EOF errors will be located at the position one past the end of the
29file.
30
31Error recovery
32--------------
33
34The error behavior of the parser (and other components) is controlled by an `ErrorHandler`. Whenever an error is
35encountered, `ErrorHandler::handleError()` is invoked. The default error handling strategy is `ErrorHandler\Throwing`,
36which will immediately throw when an error is encountered.
37
38To instead collect all encountered errors into an array, while trying to continue parsing the rest of the source code,
39an instance of `ErrorHandler\Collecting` can be passed to the `Parser::parse()` method. A usage example:
40
41```php
42$parser = (new PhpParser\ParserFactory())->createForHostVersion();
43$errorHandler = new PhpParser\ErrorHandler\Collecting;
44
45$stmts = $parser->parse($code, $errorHandler);
46
47if ($errorHandler->hasErrors()) {
48    foreach ($errorHandler->getErrors() as $error) {
49        // $error is an ordinary PhpParser\Error
50    }
51}
52
53if (null !== $stmts) {
54    // $stmts is a best-effort partial AST
55}
56```
57
58The partial AST may contain `Expr\Error` nodes that indicate that an error occurred while parsing an expression.
59
60The `NameResolver` visitor also accepts an `ErrorHandler` as a constructor argument.
61