Skip to content

Commit

Permalink
Introducing SimpleParser
Browse files Browse the repository at this point in the history
  • Loading branch information
ondrejmirtes committed Oct 22, 2020
1 parent 93bbcf2 commit afc5092
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 2 deletions.
10 changes: 8 additions & 2 deletions conf/config.neon
Original file line number Diff line number Diff line change
Expand Up @@ -519,7 +519,7 @@ services:
-
class: PHPStan\Parser\CachedParser
arguments:
originalParser: @currentPhpVersionParser
originalParser: @currentPhpVersionRichParser
cachedNodesByStringCountMax: %cache.nodesByStringCountMax%

-
Expand Down Expand Up @@ -1173,13 +1173,19 @@ services:
directory: %tmpDir%/cache/PHPStan
autowired: no

currentPhpVersionParser:
currentPhpVersionRichParser:
class: PHPStan\Parser\RichParser
arguments:
parser: @currentPhpVersionPhpParser
lexer: @currentPhpVersionLexer
autowired: no

currentPhpVersionSimpleParser:
class: PHPStan\Parser\SimpleParser
arguments:
parser: @currentPhpVersionPhpParser
autowired: no

phpParserDecorator:
class: PHPStan\Parser\PhpParserDecorator
arguments:
Expand Down
61 changes: 61 additions & 0 deletions src/Parser/SimpleParser.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
<?php declare(strict_types = 1);

namespace PHPStan\Parser;

use PhpParser\ErrorHandler\Collecting;
use PhpParser\NodeTraverser;
use PhpParser\NodeVisitor\NameResolver;
use PHPStan\File\FileReader;

class SimpleParser implements Parser
{

private \PhpParser\Parser $parser;

private NameResolver $nameResolver;

public function __construct(
\PhpParser\Parser $parser,
NameResolver $nameResolver
)
{
$this->parser = $parser;
$this->nameResolver = $nameResolver;
}

/**
* @param string $file path to a file to parse
* @return \PhpParser\Node\Stmt[]
*/
public function parseFile(string $file): array
{
try {
return $this->parseString(FileReader::read($file));
} catch (\PHPStan\Parser\ParserErrorsException $e) {
throw new \PHPStan\Parser\ParserErrorsException($e->getErrors(), $file);
}
}

/**
* @param string $sourceCode
* @return \PhpParser\Node\Stmt[]
*/
public function parseString(string $sourceCode): array
{
$errorHandler = new Collecting();
$nodes = $this->parser->parse($sourceCode, $errorHandler);
if ($errorHandler->hasErrors()) {
throw new \PHPStan\Parser\ParserErrorsException($errorHandler->getErrors(), null);
}
if ($nodes === null) {
throw new \PHPStan\ShouldNotHappenException();
}

$nodeTraverser = new NodeTraverser();
$nodeTraverser->addVisitor($this->nameResolver);

/** @var array<\PhpParser\Node\Stmt> */
return $nodeTraverser->traverse($nodes);
}

}

0 comments on commit afc5092

Please sign in to comment.