microsoft/tolerant-php-parser
Tolerant PHP parser from Microsoft that builds an AST even from incomplete or syntactically invalid code. Ideal for IDEs, refactoring tools, and static analysis, with error recovery and precise source positions for tokens and nodes.
Install via Composer: composer require microsoft/tolerant-php-parser. Start by parsing incomplete or syntactically invalid PHP code—this is the core value. For example, parse a file being edited in an IDE where braces are mismatched or semicolons are missing:
$parser = new \Microsoft\PhpParser\Parser();
$code = '<?php class Foo { public function bar( $x'; // Broken!
$ast = $parser->parseFile($code);
$diagnostics = $ast->getDiagnostics(); // Shows parse errors instead of crashing
Use getDiagnostics() to surface syntax issues programmatically—ideal for linters or live error highlighting. First-target use case: integrating real-time syntax feedback in a Laravel-based IDE extension or dev tool.
parseFile() on changed substrings during typing (e.g., with editor onDidChangeContent events) to maintain responsive tooling—no need to re-parse entire files.\Microsoft\PhpParser\NodeVisitor to traverse the AST and surface custom checks (e.g., detect insecure usage of eval()):
$ast->acceptVisitor(new class extends NodeVisitor {
public function visitCallExpression(Node $node) {
$funcName = $node->getFirstDescendantNode(NodeName::class);
if ($funcName && $funcName->getText() === 'eval') {
$this->reportIssue('Use of eval() detected', $node);
}
return NodeVisitor::DONT_TRAVERSE_CHILDREN;
}
});
nikic.start and length positions, not line/column. Convert with:
$line = substr_count($code, "\n", 0, $diagnostic->getPosition());
$col = $diagnostic->getPosition() - strrpos($code, "\n", $diagnostic->getPosition() - strlen($code)) - 1;
parseFile() never throws unless memory/core issues occur. Always check $ast->getDiagnostics() even if parsing "succeeds".<?php, use parseSourceString() and prepend <?php explicitly to avoid tokenization issues with T_INLINE_HTML.How can I help you explore Laravel packages today?