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