|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Remorhaz\JSON\Path\Parser; |
|
6
|
|
|
|
|
7
|
|
|
use Remorhaz\JSON\Path\Query\AstBuilder; |
|
8
|
|
|
use Remorhaz\JSON\Path\TokenMatcher; |
|
9
|
|
|
use Remorhaz\UniLex\AST\Tree; |
|
10
|
|
|
use Remorhaz\UniLex\Exception as UnilexException; |
|
11
|
|
|
use Remorhaz\UniLex\Grammar\ContextFree\GrammarInterface; |
|
12
|
|
|
use Remorhaz\UniLex\Grammar\ContextFree\GrammarLoader; |
|
13
|
|
|
use Remorhaz\UniLex\Grammar\ContextFree\TokenFactory; |
|
14
|
|
|
use Remorhaz\UniLex\Lexer\TokenReader; |
|
15
|
|
|
use Remorhaz\UniLex\Lexer\TokenReaderInterface; |
|
16
|
|
|
use Remorhaz\UniLex\Parser\LL1\Parser as Ll1Parser; |
|
17
|
|
|
use Remorhaz\UniLex\Parser\LL1\TranslationSchemeApplier; |
|
18
|
|
|
use Remorhaz\UniLex\Unicode\CharBufferFactory; |
|
19
|
|
|
use Throwable; |
|
20
|
|
|
|
|
21
|
|
|
final class Ll1ParserFactory implements Ll1ParserFactoryInterface |
|
22
|
|
|
{ |
|
23
|
|
|
|
|
24
|
|
|
private $grammar; |
|
25
|
|
|
|
|
26
|
4 |
|
public function createParser(string $source, Tree $queryAst): Ll1Parser |
|
27
|
|
|
{ |
|
28
|
|
|
try { |
|
29
|
4 |
|
$scheme = new TranslationScheme(new AstBuilder($queryAst)); |
|
30
|
4 |
|
$parser = new Ll1Parser( |
|
31
|
4 |
|
$this->getGrammar(), |
|
32
|
4 |
|
$this->createSourceReader($source), |
|
33
|
4 |
|
new TranslationSchemeApplier($scheme) |
|
34
|
|
|
); |
|
35
|
4 |
|
$parser->loadLookupTable(__DIR__ . '/../../generated/LookupTable.php'); |
|
36
|
|
|
} catch (Throwable $e) { |
|
37
|
|
|
throw new Exception\ParserCreationFailedException($e); |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
4 |
|
return $parser; |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
/** |
|
44
|
|
|
* @return GrammarInterface |
|
45
|
|
|
* @throws UnilexException |
|
46
|
|
|
*/ |
|
47
|
4 |
|
private function getGrammar(): GrammarInterface |
|
48
|
|
|
{ |
|
49
|
4 |
|
if (!isset($this->grammar)) { |
|
50
|
4 |
|
$this->grammar = GrammarLoader::loadFile(__DIR__ . '/../../spec/GrammarSpec.php'); |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
4 |
|
return $this->grammar; |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
/** |
|
57
|
|
|
* @param string $source |
|
58
|
|
|
* @return TokenReaderInterface |
|
59
|
|
|
* @throws UnilexException |
|
60
|
|
|
*/ |
|
61
|
4 |
|
private function createSourceReader(string $source): TokenReaderInterface |
|
62
|
|
|
{ |
|
63
|
4 |
|
return new TokenReader( |
|
64
|
4 |
|
CharBufferFactory::createFromString($source), |
|
65
|
4 |
|
new TokenMatcher(), |
|
66
|
4 |
|
new TokenFactory($this->getGrammar()) |
|
67
|
|
|
); |
|
68
|
|
|
} |
|
69
|
|
|
} |
|
70
|
|
|
|