1 | <?php |
||
20 | class Parser { |
||
21 | /** |
||
22 | * @var TokenStream |
||
23 | */ |
||
24 | private $input; |
||
25 | |||
26 | /** |
||
27 | * Parser constructor. |
||
28 | * |
||
29 | * @param TokenStream $input |
||
30 | */ |
||
31 | 24 | public function __construct(TokenStream $input) { |
|
34 | |||
35 | /** |
||
36 | * @return ASTNode |
||
37 | * |
||
38 | * @throws ParseException |
||
39 | */ |
||
40 | 24 | public function parse() { |
|
56 | |||
57 | /** |
||
58 | * @return ASTNode |
||
59 | * |
||
60 | * @throws ParseException |
||
61 | */ |
||
62 | 24 | protected function parseInternal() { |
|
63 | 24 | if ($this->isPunctuation('{')) { |
|
64 | 13 | return $this->parseTable(); |
|
65 | } |
||
66 | 23 | if ($this->isPunctuation('[')) { |
|
67 | 4 | return $this->parseTableKey(); |
|
68 | } |
||
69 | 23 | $token = $this->input->next(); |
|
70 | 23 | if ($token->getType() == Token::TYPE_NUMBER) { |
|
71 | 8 | return new NumberASTNode($token->getValue()); |
|
72 | } |
||
73 | 21 | if ($token->getType() == Token::TYPE_STRING || $token->getType() == Token::TYPE_IDENTIFIER) { |
|
74 | 18 | return new StringASTNode($token->getValue()); |
|
75 | } |
||
76 | 5 | if ($token->getType() == Token::TYPE_KEYWORD) { |
|
77 | 5 | if ($token->getValue() === 'nil') { |
|
78 | 4 | return new NilASTNode(); |
|
79 | } else { |
||
80 | 1 | $this->input->error('Unexpected keyword: ' . $token->getValue()); |
|
81 | } |
||
82 | } |
||
83 | $this->unexpected(); |
||
84 | } |
||
85 | |||
86 | /** |
||
87 | * @return TableASTNode |
||
88 | */ |
||
89 | 13 | protected function parseTable() { |
|
99 | |||
100 | /** |
||
101 | * @return TableEntryASTNode |
||
102 | */ |
||
103 | 12 | protected function parseTableEntry() { |
|
115 | |||
116 | /** |
||
117 | * @return ASTNode |
||
118 | */ |
||
119 | 4 | protected function parseTableKey() { |
|
125 | |||
126 | /** |
||
127 | * @param string $start |
||
128 | * @param string $stop |
||
129 | * @param string $separator |
||
130 | * @param callable $parser |
||
131 | * |
||
132 | * @return array |
||
133 | */ |
||
134 | 13 | protected function delimited($start, $stop, $separator, callable $parser) { |
|
155 | |||
156 | /** |
||
157 | * @param string|null $char |
||
158 | * |
||
159 | * @return bool |
||
160 | */ |
||
161 | 24 | protected function isPunctuation($char = null) { |
|
166 | |||
167 | /** |
||
168 | * @param string|null $char |
||
169 | * |
||
170 | * @throws ParseException |
||
171 | */ |
||
172 | 14 | protected function skipPunctuation($char = null) { |
|
179 | |||
180 | /** |
||
181 | * @throws ParseException |
||
182 | */ |
||
183 | protected function unexpected() { |
||
186 | } |
Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code: