1 | <?php |
---|
2 | |
---|
3 | /* |
---|
4 | * This file is part of Twig. |
---|
5 | * |
---|
6 | * (c) 2009 Fabien Potencier |
---|
7 | * (c) 2009 Armin Ronacher |
---|
8 | * |
---|
9 | * For the full copyright and license information, please view the LICENSE |
---|
10 | * file that was distributed with this source code. |
---|
11 | */ |
---|
12 | |
---|
13 | /** |
---|
14 | * Lexes a template string. |
---|
15 | * |
---|
16 | * @package twig |
---|
17 | * @author Fabien Potencier <fabien@symfony.com> |
---|
18 | */ |
---|
19 | class Twig_Lexer implements Twig_LexerInterface |
---|
20 | { |
---|
21 | protected $tokens; |
---|
22 | protected $code; |
---|
23 | protected $cursor; |
---|
24 | protected $lineno; |
---|
25 | protected $end; |
---|
26 | protected $state; |
---|
27 | protected $states; |
---|
28 | protected $brackets; |
---|
29 | protected $env; |
---|
30 | protected $filename; |
---|
31 | protected $options; |
---|
32 | protected $regexes; |
---|
33 | protected $position; |
---|
34 | protected $positions; |
---|
35 | |
---|
36 | const STATE_DATA = 0; |
---|
37 | const STATE_BLOCK = 1; |
---|
38 | const STATE_VAR = 2; |
---|
39 | const STATE_STRING = 3; |
---|
40 | const STATE_INTERPOLATION = 4; |
---|
41 | |
---|
42 | const REGEX_NAME = '/[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/A'; |
---|
43 | const REGEX_NUMBER = '/[0-9]+(?:\.[0-9]+)?/A'; |
---|
44 | const REGEX_STRING = '/"([^#"\\\\]*(?:\\\\.[^#"\\\\]*)*)"|\'([^\'\\\\]*(?:\\\\.[^\'\\\\]*)*)\'/As'; |
---|
45 | const REGEX_DQ_STRING_DELIM = '/"/A'; |
---|
46 | const REGEX_DQ_STRING_PART = '/[^#"\\\\]*(?:(?:\\\\.|#(?!\{))[^#"\\\\]*)*/As'; |
---|
47 | const PUNCTUATION = '()[]{}?:.,|'; |
---|
48 | |
---|
49 | public function __construct(Twig_Environment $env, array $options = array()) |
---|
50 | { |
---|
51 | $this->env = $env; |
---|
52 | |
---|
53 | $this->options = array_merge(array( |
---|
54 | 'tag_comment' => array('{#', '#}'), |
---|
55 | 'tag_block' => array('{%', '%}'), |
---|
56 | 'tag_variable' => array('{{', '}}'), |
---|
57 | 'whitespace_trim' => '-', |
---|
58 | 'interpolation' => array('#{', '}'), |
---|
59 | ), $options); |
---|
60 | |
---|
61 | $this->regexes = array( |
---|
62 | 'lex_var' => '/\s*'.preg_quote($this->options['whitespace_trim'].$this->options['tag_variable'][1], '/').'\s*|\s*'.preg_quote($this->options['tag_variable'][1], '/').'/A', |
---|
63 | 'lex_block' => '/\s*(?:'.preg_quote($this->options['whitespace_trim'].$this->options['tag_block'][1], '/').'\s*|\s*'.preg_quote($this->options['tag_block'][1], '/').')\n?/A', |
---|
64 | 'lex_raw_data' => '/('.preg_quote($this->options['tag_block'][0].$this->options['whitespace_trim'], '/').'|'.preg_quote($this->options['tag_block'][0], '/').')\s*(?:end%s)\s*(?:'.preg_quote($this->options['whitespace_trim'].$this->options['tag_block'][1], '/').'\s*|\s*'.preg_quote($this->options['tag_block'][1], '/').')/s', |
---|
65 | 'operator' => $this->getOperatorRegex(), |
---|
66 | 'lex_comment' => '/(?:'.preg_quote($this->options['whitespace_trim'], '/').preg_quote($this->options['tag_comment'][1], '/').'\s*|'.preg_quote($this->options['tag_comment'][1], '/').')\n?/s', |
---|
67 | 'lex_block_raw' => '/\s*(raw|verbatim)\s*(?:'.preg_quote($this->options['whitespace_trim'].$this->options['tag_block'][1], '/').'\s*|\s*'.preg_quote($this->options['tag_block'][1], '/').')/As', |
---|
68 | 'lex_block_line' => '/\s*line\s+(\d+)\s*'.preg_quote($this->options['tag_block'][1], '/').'/As', |
---|
69 | 'lex_tokens_start' => '/('.preg_quote($this->options['tag_variable'][0], '/').'|'.preg_quote($this->options['tag_block'][0], '/').'|'.preg_quote($this->options['tag_comment'][0], '/').')('.preg_quote($this->options['whitespace_trim'], '/').')?/s', |
---|
70 | 'interpolation_start' => '/'.preg_quote($this->options['interpolation'][0], '/').'\s*/A', |
---|
71 | 'interpolation_end' => '/\s*'.preg_quote($this->options['interpolation'][1], '/').'/A', |
---|
72 | ); |
---|
73 | } |
---|
74 | |
---|
75 | /** |
---|
76 | * Tokenizes a source code. |
---|
77 | * |
---|
78 | * @param string $code The source code |
---|
79 | * @param string $filename A unique identifier for the source code |
---|
80 | * |
---|
81 | * @return Twig_TokenStream A token stream instance |
---|
82 | */ |
---|
83 | public function tokenize($code, $filename = null) |
---|
84 | { |
---|
85 | if (function_exists('mb_internal_encoding') && ((int) ini_get('mbstring.func_overload')) & 2) { |
---|
86 | $mbEncoding = mb_internal_encoding(); |
---|
87 | mb_internal_encoding('ASCII'); |
---|
88 | } |
---|
89 | |
---|
90 | $this->code = str_replace(array("\r\n", "\r"), "\n", $code); |
---|
91 | $this->filename = $filename; |
---|
92 | $this->cursor = 0; |
---|
93 | $this->lineno = 1; |
---|
94 | $this->end = strlen($this->code); |
---|
95 | $this->tokens = array(); |
---|
96 | $this->state = self::STATE_DATA; |
---|
97 | $this->states = array(); |
---|
98 | $this->brackets = array(); |
---|
99 | $this->position = -1; |
---|
100 | |
---|
101 | // find all token starts in one go |
---|
102 | preg_match_all($this->regexes['lex_tokens_start'], $this->code, $matches, PREG_OFFSET_CAPTURE); |
---|
103 | $this->positions = $matches; |
---|
104 | |
---|
105 | while ($this->cursor < $this->end) { |
---|
106 | // dispatch to the lexing functions depending |
---|
107 | // on the current state |
---|
108 | switch ($this->state) { |
---|
109 | case self::STATE_DATA: |
---|
110 | $this->lexData(); |
---|
111 | break; |
---|
112 | |
---|
113 | case self::STATE_BLOCK: |
---|
114 | $this->lexBlock(); |
---|
115 | break; |
---|
116 | |
---|
117 | case self::STATE_VAR: |
---|
118 | $this->lexVar(); |
---|
119 | break; |
---|
120 | |
---|
121 | case self::STATE_STRING: |
---|
122 | $this->lexString(); |
---|
123 | break; |
---|
124 | |
---|
125 | case self::STATE_INTERPOLATION: |
---|
126 | $this->lexInterpolation(); |
---|
127 | break; |
---|
128 | } |
---|
129 | } |
---|
130 | |
---|
131 | $this->pushToken(Twig_Token::EOF_TYPE); |
---|
132 | |
---|
133 | if (!empty($this->brackets)) { |
---|
134 | list($expect, $lineno) = array_pop($this->brackets); |
---|
135 | throw new Twig_Error_Syntax(sprintf('Unclosed "%s"', $expect), $lineno, $this->filename); |
---|
136 | } |
---|
137 | |
---|
138 | if (isset($mbEncoding)) { |
---|
139 | mb_internal_encoding($mbEncoding); |
---|
140 | } |
---|
141 | |
---|
142 | return new Twig_TokenStream($this->tokens, $this->filename); |
---|
143 | } |
---|
144 | |
---|
145 | protected function lexData() |
---|
146 | { |
---|
147 | // if no matches are left we return the rest of the template as simple text token |
---|
148 | if ($this->position == count($this->positions[0]) - 1) { |
---|
149 | $this->pushToken(Twig_Token::TEXT_TYPE, substr($this->code, $this->cursor)); |
---|
150 | $this->cursor = $this->end; |
---|
151 | |
---|
152 | return; |
---|
153 | } |
---|
154 | |
---|
155 | // Find the first token after the current cursor |
---|
156 | $position = $this->positions[0][++$this->position]; |
---|
157 | while ($position[1] < $this->cursor) { |
---|
158 | if ($this->position == count($this->positions[0]) - 1) { |
---|
159 | return; |
---|
160 | } |
---|
161 | $position = $this->positions[0][++$this->position]; |
---|
162 | } |
---|
163 | |
---|
164 | // push the template text first |
---|
165 | $text = $textContent = substr($this->code, $this->cursor, $position[1] - $this->cursor); |
---|
166 | if (isset($this->positions[2][$this->position][0])) { |
---|
167 | $text = rtrim($text); |
---|
168 | } |
---|
169 | $this->pushToken(Twig_Token::TEXT_TYPE, $text); |
---|
170 | $this->moveCursor($textContent.$position[0]); |
---|
171 | |
---|
172 | switch ($this->positions[1][$this->position][0]) { |
---|
173 | case $this->options['tag_comment'][0]: |
---|
174 | $this->lexComment(); |
---|
175 | break; |
---|
176 | |
---|
177 | case $this->options['tag_block'][0]: |
---|
178 | // raw data? |
---|
179 | if (preg_match($this->regexes['lex_block_raw'], $this->code, $match, null, $this->cursor)) { |
---|
180 | $this->moveCursor($match[0]); |
---|
181 | $this->lexRawData($match[1]); |
---|
182 | // {% line \d+ %} |
---|
183 | } elseif (preg_match($this->regexes['lex_block_line'], $this->code, $match, null, $this->cursor)) { |
---|
184 | $this->moveCursor($match[0]); |
---|
185 | $this->lineno = (int) $match[1]; |
---|
186 | } else { |
---|
187 | $this->pushToken(Twig_Token::BLOCK_START_TYPE); |
---|
188 | $this->pushState(self::STATE_BLOCK); |
---|
189 | } |
---|
190 | break; |
---|
191 | |
---|
192 | case $this->options['tag_variable'][0]: |
---|
193 | $this->pushToken(Twig_Token::VAR_START_TYPE); |
---|
194 | $this->pushState(self::STATE_VAR); |
---|
195 | break; |
---|
196 | } |
---|
197 | } |
---|
198 | |
---|
199 | protected function lexBlock() |
---|
200 | { |
---|
201 | if (empty($this->brackets) && preg_match($this->regexes['lex_block'], $this->code, $match, null, $this->cursor)) { |
---|
202 | $this->pushToken(Twig_Token::BLOCK_END_TYPE); |
---|
203 | $this->moveCursor($match[0]); |
---|
204 | $this->popState(); |
---|
205 | } else { |
---|
206 | $this->lexExpression(); |
---|
207 | } |
---|
208 | } |
---|
209 | |
---|
210 | protected function lexVar() |
---|
211 | { |
---|
212 | if (empty($this->brackets) && preg_match($this->regexes['lex_var'], $this->code, $match, null, $this->cursor)) { |
---|
213 | $this->pushToken(Twig_Token::VAR_END_TYPE); |
---|
214 | $this->moveCursor($match[0]); |
---|
215 | $this->popState(); |
---|
216 | } else { |
---|
217 | $this->lexExpression(); |
---|
218 | } |
---|
219 | } |
---|
220 | |
---|
221 | protected function lexExpression() |
---|
222 | { |
---|
223 | // whitespace |
---|
224 | if (preg_match('/\s+/A', $this->code, $match, null, $this->cursor)) { |
---|
225 | $this->moveCursor($match[0]); |
---|
226 | |
---|
227 | if ($this->cursor >= $this->end) { |
---|
228 | throw new Twig_Error_Syntax(sprintf('Unexpected end of file: Unclosed "%s"', $this->state === self::STATE_BLOCK ? 'block' : 'variable'), $this->lineno, $this->filename); |
---|
229 | } |
---|
230 | } |
---|
231 | |
---|
232 | // operators |
---|
233 | if (preg_match($this->regexes['operator'], $this->code, $match, null, $this->cursor)) { |
---|
234 | $this->pushToken(Twig_Token::OPERATOR_TYPE, $match[0]); |
---|
235 | $this->moveCursor($match[0]); |
---|
236 | } |
---|
237 | // names |
---|
238 | elseif (preg_match(self::REGEX_NAME, $this->code, $match, null, $this->cursor)) { |
---|
239 | $this->pushToken(Twig_Token::NAME_TYPE, $match[0]); |
---|
240 | $this->moveCursor($match[0]); |
---|
241 | } |
---|
242 | // numbers |
---|
243 | elseif (preg_match(self::REGEX_NUMBER, $this->code, $match, null, $this->cursor)) { |
---|
244 | $number = (float) $match[0]; // floats |
---|
245 | if (ctype_digit($match[0]) && $number <= PHP_INT_MAX) { |
---|
246 | $number = (int) $match[0]; // integers lower than the maximum |
---|
247 | } |
---|
248 | $this->pushToken(Twig_Token::NUMBER_TYPE, $number); |
---|
249 | $this->moveCursor($match[0]); |
---|
250 | } |
---|
251 | // punctuation |
---|
252 | elseif (false !== strpos(self::PUNCTUATION, $this->code[$this->cursor])) { |
---|
253 | // opening bracket |
---|
254 | if (false !== strpos('([{', $this->code[$this->cursor])) { |
---|
255 | $this->brackets[] = array($this->code[$this->cursor], $this->lineno); |
---|
256 | } |
---|
257 | // closing bracket |
---|
258 | elseif (false !== strpos(')]}', $this->code[$this->cursor])) { |
---|
259 | if (empty($this->brackets)) { |
---|
260 | throw new Twig_Error_Syntax(sprintf('Unexpected "%s"', $this->code[$this->cursor]), $this->lineno, $this->filename); |
---|
261 | } |
---|
262 | |
---|
263 | list($expect, $lineno) = array_pop($this->brackets); |
---|
264 | if ($this->code[$this->cursor] != strtr($expect, '([{', ')]}')) { |
---|
265 | throw new Twig_Error_Syntax(sprintf('Unclosed "%s"', $expect), $lineno, $this->filename); |
---|
266 | } |
---|
267 | } |
---|
268 | |
---|
269 | $this->pushToken(Twig_Token::PUNCTUATION_TYPE, $this->code[$this->cursor]); |
---|
270 | ++$this->cursor; |
---|
271 | } |
---|
272 | // strings |
---|
273 | elseif (preg_match(self::REGEX_STRING, $this->code, $match, null, $this->cursor)) { |
---|
274 | $this->pushToken(Twig_Token::STRING_TYPE, stripcslashes(substr($match[0], 1, -1))); |
---|
275 | $this->moveCursor($match[0]); |
---|
276 | } |
---|
277 | // opening double quoted string |
---|
278 | elseif (preg_match(self::REGEX_DQ_STRING_DELIM, $this->code, $match, null, $this->cursor)) { |
---|
279 | $this->brackets[] = array('"', $this->lineno); |
---|
280 | $this->pushState(self::STATE_STRING); |
---|
281 | $this->moveCursor($match[0]); |
---|
282 | } |
---|
283 | // unlexable |
---|
284 | else { |
---|
285 | throw new Twig_Error_Syntax(sprintf('Unexpected character "%s"', $this->code[$this->cursor]), $this->lineno, $this->filename); |
---|
286 | } |
---|
287 | } |
---|
288 | |
---|
289 | protected function lexRawData($tag) |
---|
290 | { |
---|
291 | if (!preg_match(str_replace('%s', $tag, $this->regexes['lex_raw_data']), $this->code, $match, PREG_OFFSET_CAPTURE, $this->cursor)) { |
---|
292 | throw new Twig_Error_Syntax(sprintf('Unexpected end of file: Unclosed "%s" block', $tag), $this->lineno, $this->filename); |
---|
293 | } |
---|
294 | |
---|
295 | $text = substr($this->code, $this->cursor, $match[0][1] - $this->cursor); |
---|
296 | $this->moveCursor($text.$match[0][0]); |
---|
297 | |
---|
298 | if (false !== strpos($match[1][0], $this->options['whitespace_trim'])) { |
---|
299 | $text = rtrim($text); |
---|
300 | } |
---|
301 | |
---|
302 | $this->pushToken(Twig_Token::TEXT_TYPE, $text); |
---|
303 | } |
---|
304 | |
---|
305 | protected function lexComment() |
---|
306 | { |
---|
307 | if (!preg_match($this->regexes['lex_comment'], $this->code, $match, PREG_OFFSET_CAPTURE, $this->cursor)) { |
---|
308 | throw new Twig_Error_Syntax('Unclosed comment', $this->lineno, $this->filename); |
---|
309 | } |
---|
310 | |
---|
311 | $this->moveCursor(substr($this->code, $this->cursor, $match[0][1] - $this->cursor).$match[0][0]); |
---|
312 | } |
---|
313 | |
---|
314 | protected function lexString() |
---|
315 | { |
---|
316 | if (preg_match($this->regexes['interpolation_start'], $this->code, $match, null, $this->cursor)) { |
---|
317 | $this->brackets[] = array($this->options['interpolation'][0], $this->lineno); |
---|
318 | $this->pushToken(Twig_Token::INTERPOLATION_START_TYPE); |
---|
319 | $this->moveCursor($match[0]); |
---|
320 | $this->pushState(self::STATE_INTERPOLATION); |
---|
321 | |
---|
322 | } elseif (preg_match(self::REGEX_DQ_STRING_PART, $this->code, $match, null, $this->cursor) && strlen($match[0]) > 0) { |
---|
323 | $this->pushToken(Twig_Token::STRING_TYPE, stripcslashes($match[0])); |
---|
324 | $this->moveCursor($match[0]); |
---|
325 | |
---|
326 | } elseif (preg_match(self::REGEX_DQ_STRING_DELIM, $this->code, $match, null, $this->cursor)) { |
---|
327 | |
---|
328 | list($expect, $lineno) = array_pop($this->brackets); |
---|
329 | if ($this->code[$this->cursor] != '"') { |
---|
330 | throw new Twig_Error_Syntax(sprintf('Unclosed "%s"', $expect), $lineno, $this->filename); |
---|
331 | } |
---|
332 | |
---|
333 | $this->popState(); |
---|
334 | ++$this->cursor; |
---|
335 | } |
---|
336 | } |
---|
337 | |
---|
338 | protected function lexInterpolation() |
---|
339 | { |
---|
340 | $bracket = end($this->brackets); |
---|
341 | if ($this->options['interpolation'][0] === $bracket[0] && preg_match($this->regexes['interpolation_end'], $this->code, $match, null, $this->cursor)) { |
---|
342 | array_pop($this->brackets); |
---|
343 | $this->pushToken(Twig_Token::INTERPOLATION_END_TYPE); |
---|
344 | $this->moveCursor($match[0]); |
---|
345 | $this->popState(); |
---|
346 | } else { |
---|
347 | $this->lexExpression(); |
---|
348 | } |
---|
349 | } |
---|
350 | |
---|
351 | protected function pushToken($type, $value = '') |
---|
352 | { |
---|
353 | // do not push empty text tokens |
---|
354 | if (Twig_Token::TEXT_TYPE === $type && '' === $value) { |
---|
355 | return; |
---|
356 | } |
---|
357 | |
---|
358 | $this->tokens[] = new Twig_Token($type, $value, $this->lineno); |
---|
359 | } |
---|
360 | |
---|
361 | protected function moveCursor($text) |
---|
362 | { |
---|
363 | $this->cursor += strlen($text); |
---|
364 | $this->lineno += substr_count($text, "\n"); |
---|
365 | } |
---|
366 | |
---|
367 | protected function getOperatorRegex() |
---|
368 | { |
---|
369 | $operators = array_merge( |
---|
370 | array('='), |
---|
371 | array_keys($this->env->getUnaryOperators()), |
---|
372 | array_keys($this->env->getBinaryOperators()) |
---|
373 | ); |
---|
374 | |
---|
375 | $operators = array_combine($operators, array_map('strlen', $operators)); |
---|
376 | arsort($operators); |
---|
377 | |
---|
378 | $regex = array(); |
---|
379 | foreach ($operators as $operator => $length) { |
---|
380 | // an operator that ends with a character must be followed by |
---|
381 | // a whitespace or a parenthesis |
---|
382 | if (ctype_alpha($operator[$length - 1])) { |
---|
383 | $regex[] = preg_quote($operator, '/').'(?=[\s()])'; |
---|
384 | } else { |
---|
385 | $regex[] = preg_quote($operator, '/'); |
---|
386 | } |
---|
387 | } |
---|
388 | |
---|
389 | return '/'.implode('|', $regex).'/A'; |
---|
390 | } |
---|
391 | |
---|
392 | protected function pushState($state) |
---|
393 | { |
---|
394 | $this->states[] = $this->state; |
---|
395 | $this->state = $state; |
---|
396 | } |
---|
397 | |
---|
398 | protected function popState() |
---|
399 | { |
---|
400 | if (0 === count($this->states)) { |
---|
401 | throw new Exception('Cannot pop state without a previous state'); |
---|
402 | } |
---|
403 | |
---|
404 | $this->state = array_pop($this->states); |
---|
405 | } |
---|
406 | } |
---|