Lexer.php 16 KB

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