Lexer.php 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  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. * @package twig
  15. * @author Fabien Potencier <fabien@symfony.com>
  16. */
  17. class Twig_Lexer implements Twig_LexerInterface
  18. {
  19. protected $tokens;
  20. protected $code;
  21. protected $cursor;
  22. protected $lineno;
  23. protected $end;
  24. protected $state;
  25. protected $brackets;
  26. protected $env;
  27. protected $filename;
  28. protected $options;
  29. const STATE_DATA = 0;
  30. const STATE_BLOCK = 1;
  31. const STATE_VAR = 2;
  32. const REGEX_NAME = '/[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/A';
  33. const REGEX_NUMBER = '/[0-9]+(?:\.[0-9]+)?/A';
  34. const REGEX_STRING = '/"([^"\\\\]*(?:\\\\.[^"\\\\]*)*)"|\'([^\'\\\\]*(?:\\\\.[^\'\\\\]*)*)\'/As';
  35. const PUNCTUATION = '()[]{}?:.,|';
  36. public function __construct(Twig_Environment $env, array $options = array())
  37. {
  38. $this->env = $env;
  39. $this->options = array_merge(array(
  40. 'tag_comment' => array('{#', '#}'),
  41. 'tag_block' => array('{%', '%}'),
  42. 'tag_variable' => array('{{', '}}'),
  43. 'whitespace_trim' => '-',
  44. ), $options);
  45. $this->options['lex_var_regex'] = '/\s*'.preg_quote($this->options['whitespace_trim'].$this->options['tag_variable'][1], '/').'\s*|\s*'.preg_quote($this->options['tag_variable'][1], '/').'/A';
  46. $this->options['lex_block_regex'] = '/\s*(?:'.preg_quote($this->options['whitespace_trim'].$this->options['tag_block'][1], '/').'\s*|\s*'.preg_quote($this->options['tag_block'][1], '/').')\n?/A';
  47. $this->options['lex_raw_data_regex'] = '/'.preg_quote($this->options['tag_block'][0], '/').'\s*endraw\s*'.preg_quote($this->options['tag_block'][1], '/').'/s';
  48. $this->options['operator_regex'] = $this->getOperatorRegex();
  49. $this->options['lex_comment_regex'] = '/(?:'.preg_quote($this->options['whitespace_trim'], '/').preg_quote($this->options['tag_comment'][1], '/').'\s*|'.preg_quote($this->options['tag_comment'][1], '/').')\n?/s';
  50. $this->options['lex_block_raw_regex'] = '/\s*raw\s*'.preg_quote($this->options['tag_block'][1], '/').'/As';
  51. $this->options['lex_block_line_regex'] = '/\s*line\s+(\d+)\s*'.preg_quote($this->options['tag_block'][1], '/').'/As';
  52. $this->options['lex_tokens_start_regex'] = '/('.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';
  53. }
  54. /**
  55. * Tokenizes a source code.
  56. *
  57. * @param string $code The source code
  58. * @param string $filename A unique identifier for the source code
  59. *
  60. * @return Twig_TokenStream A token stream instance
  61. */
  62. public function tokenize($code, $filename = null)
  63. {
  64. if (function_exists('mb_internal_encoding') && ((int) ini_get('mbstring.func_overload')) & 2) {
  65. $mbEncoding = mb_internal_encoding();
  66. mb_internal_encoding('ASCII');
  67. }
  68. $this->code = str_replace(array("\r\n", "\r"), "\n", $code);
  69. $this->filename = $filename;
  70. $this->cursor = 0;
  71. $this->lineno = 1;
  72. $this->end = strlen($this->code);
  73. $this->tokens = array();
  74. $this->state = self::STATE_DATA;
  75. $this->brackets = array();
  76. $this->position = -1;
  77. // find all token starts in one go
  78. preg_match_all($this->options['lex_tokens_start_regex'], $this->code, $matches, PREG_OFFSET_CAPTURE);
  79. $this->positions = $matches;
  80. while ($this->cursor < $this->end) {
  81. // dispatch to the lexing functions depending
  82. // on the current state
  83. switch ($this->state) {
  84. case self::STATE_DATA:
  85. $this->lexData();
  86. break;
  87. case self::STATE_BLOCK:
  88. $this->lexBlock();
  89. break;
  90. case self::STATE_VAR:
  91. $this->lexVar();
  92. break;
  93. }
  94. }
  95. $this->pushToken(Twig_Token::EOF_TYPE);
  96. if (!empty($this->brackets)) {
  97. list($expect, $lineno) = array_pop($this->brackets);
  98. throw new Twig_Error_Syntax(sprintf('Unclosed "%s"', $expect), $lineno, $this->filename);
  99. }
  100. if (isset($mbEncoding)) {
  101. mb_internal_encoding($mbEncoding);
  102. }
  103. return new Twig_TokenStream($this->tokens, $this->filename);
  104. }
  105. protected function lexData()
  106. {
  107. // if no matches are left we return the rest of the template as simple text token
  108. if ($this->position == count($this->positions[0]) - 1) {
  109. $this->pushToken(Twig_Token::TEXT_TYPE, substr($this->code, $this->cursor));
  110. $this->cursor = $this->end;
  111. return;
  112. }
  113. // Find the first token after the current cursor
  114. $position = $this->positions[0][++$this->position];
  115. while ($position[1] < $this->cursor) {
  116. if ($this->position == count($this->positions[0]) - 1) {
  117. return;
  118. }
  119. $position = $this->positions[0][++$this->position];
  120. }
  121. // push the template text first
  122. $text = $textContent = substr($this->code, $this->cursor, $position[1] - $this->cursor);
  123. if (isset($this->positions[2][$this->position][0])) {
  124. $text = rtrim($text);
  125. }
  126. $this->pushToken(Twig_Token::TEXT_TYPE, $text);
  127. $this->moveCursor($textContent.$position[0]);
  128. switch ($this->positions[1][$this->position][0]) {
  129. case $this->options['tag_comment'][0]:
  130. $this->lexComment();
  131. break;
  132. case $this->options['tag_block'][0]:
  133. // raw data?
  134. if (preg_match($this->options['lex_block_raw_regex'], $this->code, $match, null, $this->cursor)) {
  135. $this->moveCursor($match[0]);
  136. $this->lexRawData();
  137. $this->state = self::STATE_DATA;
  138. // {% line \d+ %}
  139. } else if (preg_match($this->options['lex_block_line_regex'], $this->code, $match, null, $this->cursor)) {
  140. $this->moveCursor($match[0]);
  141. $this->lineno = (int) $match[1];
  142. $this->state = self::STATE_DATA;
  143. } else {
  144. $this->pushToken(Twig_Token::BLOCK_START_TYPE);
  145. $this->state = self::STATE_BLOCK;
  146. }
  147. break;
  148. case $this->options['tag_variable'][0]:
  149. $this->pushToken(Twig_Token::VAR_START_TYPE);
  150. $this->state = self::STATE_VAR;
  151. break;
  152. }
  153. }
  154. protected function lexBlock()
  155. {
  156. if (empty($this->brackets) && preg_match($this->options['lex_block_regex'], $this->code, $match, null, $this->cursor)) {
  157. $this->pushToken(Twig_Token::BLOCK_END_TYPE);
  158. $this->moveCursor($match[0]);
  159. $this->state = self::STATE_DATA;
  160. } else {
  161. $this->lexExpression();
  162. }
  163. }
  164. protected function lexVar()
  165. {
  166. if (empty($this->brackets) && preg_match($this->options['lex_var_regex'], $this->code, $match, null, $this->cursor)) {
  167. $this->pushToken(Twig_Token::VAR_END_TYPE);
  168. $this->moveCursor($match[0]);
  169. $this->state = self::STATE_DATA;
  170. } else {
  171. $this->lexExpression();
  172. }
  173. }
  174. protected function lexExpression()
  175. {
  176. // whitespace
  177. if (preg_match('/\s+/A', $this->code, $match, null, $this->cursor)) {
  178. $this->moveCursor($match[0]);
  179. if ($this->cursor >= $this->end) {
  180. throw new Twig_Error_Syntax(sprintf('Unexpected end of file: Unclosed "%s"', $this->state === self::STATE_BLOCK ? 'block' : 'variable'));
  181. }
  182. }
  183. // operators
  184. if (preg_match($this->options['operator_regex'], $this->code, $match, null, $this->cursor)) {
  185. $this->pushToken(Twig_Token::OPERATOR_TYPE, $match[0]);
  186. $this->moveCursor($match[0]);
  187. }
  188. // names
  189. elseif (preg_match(self::REGEX_NAME, $this->code, $match, null, $this->cursor)) {
  190. $this->pushToken(Twig_Token::NAME_TYPE, $match[0]);
  191. $this->moveCursor($match[0]);
  192. }
  193. // numbers
  194. elseif (preg_match(self::REGEX_NUMBER, $this->code, $match, null, $this->cursor)) {
  195. $number = (float) $match[0]; // floats
  196. if (ctype_digit($match[0]) && $number <= PHP_INT_MAX) {
  197. $number = (int) $match[0]; // integers lower than the maximum
  198. }
  199. $this->pushToken(Twig_Token::NUMBER_TYPE, $number);
  200. $this->moveCursor($match[0]);
  201. }
  202. // punctuation
  203. elseif (false !== strpos(self::PUNCTUATION, $this->code[$this->cursor])) {
  204. // opening bracket
  205. if (false !== strpos('([{', $this->code[$this->cursor])) {
  206. $this->brackets[] = array($this->code[$this->cursor], $this->lineno);
  207. }
  208. // closing bracket
  209. elseif (false !== strpos(')]}', $this->code[$this->cursor])) {
  210. if (empty($this->brackets)) {
  211. throw new Twig_Error_Syntax(sprintf('Unexpected "%s"', $this->code[$this->cursor]), $this->lineno, $this->filename);
  212. }
  213. list($expect, $lineno) = array_pop($this->brackets);
  214. if ($this->code[$this->cursor] != strtr($expect, '([{', ')]}')) {
  215. throw new Twig_Error_Syntax(sprintf('Unclosed "%s"', $expect), $lineno, $this->filename);
  216. }
  217. }
  218. $this->pushToken(Twig_Token::PUNCTUATION_TYPE, $this->code[$this->cursor]);
  219. ++$this->cursor;
  220. }
  221. // strings
  222. elseif (preg_match(self::REGEX_STRING, $this->code, $match, null, $this->cursor)) {
  223. $this->pushToken(Twig_Token::STRING_TYPE, stripcslashes(substr($match[0], 1, -1)));
  224. $this->moveCursor($match[0]);
  225. }
  226. // unlexable
  227. else {
  228. throw new Twig_Error_Syntax(sprintf('Unexpected character "%s"', $this->code[$this->cursor]), $this->lineno, $this->filename);
  229. }
  230. }
  231. protected function lexRawData()
  232. {
  233. if (!preg_match($this->options['lex_raw_data_regex'], $this->code, $match, PREG_OFFSET_CAPTURE, $this->cursor)) {
  234. throw new Twig_Error_Syntax(sprintf('Unexpected end of file: Unclosed "block"'));
  235. }
  236. $text = substr($this->code, $this->cursor, $match[0][1] - $this->cursor);
  237. $this->pushToken(Twig_Token::TEXT_TYPE, $text);
  238. $this->moveCursor($text.$match[0][0]);
  239. }
  240. protected function lexComment()
  241. {
  242. if (!preg_match($this->options['lex_comment_regex'], $this->code, $match, PREG_OFFSET_CAPTURE, $this->cursor)) {
  243. throw new Twig_Error_Syntax('Unclosed comment', $this->lineno, $this->filename);
  244. }
  245. $this->moveCursor(substr($this->code, $this->cursor, $match[0][1] - $this->cursor).$match[0][0]);
  246. }
  247. protected function pushToken($type, $value = '')
  248. {
  249. // do not push empty text tokens
  250. if (Twig_Token::TEXT_TYPE === $type && '' === $value) {
  251. return;
  252. }
  253. $this->tokens[] = new Twig_Token($type, $value, $this->lineno);
  254. }
  255. protected function moveCursor($text)
  256. {
  257. $this->cursor += strlen($text);
  258. $this->lineno += substr_count($text, "\n");
  259. }
  260. protected function getOperatorRegex()
  261. {
  262. $operators = array_merge(
  263. array('='),
  264. array_keys($this->env->getUnaryOperators()),
  265. array_keys($this->env->getBinaryOperators())
  266. );
  267. $operators = array_combine($operators, array_map('strlen', $operators));
  268. arsort($operators);
  269. $regex = array();
  270. foreach ($operators as $operator => $length) {
  271. // an operator that ends with a character must be followed by
  272. // a whitespace or a parenthesis
  273. if (ctype_alpha($operator[$length - 1])) {
  274. $regex[] = preg_quote($operator, '/').'(?=[ ()])';
  275. } else {
  276. $regex[] = preg_quote($operator, '/');
  277. }
  278. }
  279. return '/'.implode('|', $regex).'/A';
  280. }
  281. }