Lexer.php 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  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 $states;
  26. protected $brackets;
  27. protected $env;
  28. protected $filename;
  29. protected $options;
  30. protected $regexes;
  31. protected $position;
  32. protected $positions;
  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*endraw\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\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. * Tokenizes a source code.
  69. *
  70. * @param string $code The source code
  71. * @param string $filename A unique identifier for the source code
  72. *
  73. * @return Twig_TokenStream A token stream instance
  74. */
  75. public function tokenize($code, $filename = null)
  76. {
  77. if (function_exists('mb_internal_encoding') && ((int) ini_get('mbstring.func_overload')) & 2) {
  78. $mbEncoding = mb_internal_encoding();
  79. mb_internal_encoding('ASCII');
  80. }
  81. $this->code = str_replace(array("\r\n", "\r"), "\n", $code);
  82. $this->filename = $filename;
  83. $this->cursor = 0;
  84. $this->lineno = 1;
  85. $this->end = strlen($this->code);
  86. $this->tokens = array();
  87. $this->state = self::STATE_DATA;
  88. $this->states = array();
  89. $this->brackets = array();
  90. $this->position = -1;
  91. // find all token starts in one go
  92. preg_match_all($this->regexes['lex_tokens_start'], $this->code, $matches, PREG_OFFSET_CAPTURE);
  93. $this->positions = $matches;
  94. while ($this->cursor < $this->end) {
  95. // dispatch to the lexing functions depending
  96. // on the current state
  97. switch ($this->state) {
  98. case self::STATE_DATA:
  99. $this->lexData();
  100. break;
  101. case self::STATE_BLOCK:
  102. $this->lexBlock();
  103. break;
  104. case self::STATE_VAR:
  105. $this->lexVar();
  106. break;
  107. case self::STATE_STRING:
  108. $this->lexString();
  109. break;
  110. case self::STATE_INTERPOLATION:
  111. $this->lexInterpolation();
  112. break;
  113. }
  114. }
  115. $this->pushToken(Twig_Token::EOF_TYPE);
  116. if (!empty($this->brackets)) {
  117. list($expect, $lineno) = array_pop($this->brackets);
  118. throw new Twig_Error_Syntax(sprintf('Unclosed "%s"', $expect), $lineno, $this->filename);
  119. }
  120. if (isset($mbEncoding)) {
  121. mb_internal_encoding($mbEncoding);
  122. }
  123. return new Twig_TokenStream($this->tokens, $this->filename);
  124. }
  125. protected function lexData()
  126. {
  127. // if no matches are left we return the rest of the template as simple text token
  128. if ($this->position == count($this->positions[0]) - 1) {
  129. $this->pushToken(Twig_Token::TEXT_TYPE, substr($this->code, $this->cursor));
  130. $this->cursor = $this->end;
  131. return;
  132. }
  133. // Find the first token after the current cursor
  134. $position = $this->positions[0][++$this->position];
  135. while ($position[1] < $this->cursor) {
  136. if ($this->position == count($this->positions[0]) - 1) {
  137. return;
  138. }
  139. $position = $this->positions[0][++$this->position];
  140. }
  141. // push the template text first
  142. $text = $textContent = substr($this->code, $this->cursor, $position[1] - $this->cursor);
  143. if (isset($this->positions[2][$this->position][0])) {
  144. $text = rtrim($text);
  145. }
  146. $this->pushToken(Twig_Token::TEXT_TYPE, $text);
  147. $this->moveCursor($textContent.$position[0]);
  148. switch ($this->positions[1][$this->position][0]) {
  149. case $this->options['tag_comment'][0]:
  150. $this->lexComment();
  151. break;
  152. case $this->options['tag_block'][0]:
  153. // raw data?
  154. if (preg_match($this->regexes['lex_block_raw'], $this->code, $match, null, $this->cursor)) {
  155. $this->moveCursor($match[0]);
  156. $this->lexRawData();
  157. // {% line \d+ %}
  158. } elseif (preg_match($this->regexes['lex_block_line'], $this->code, $match, null, $this->cursor)) {
  159. $this->moveCursor($match[0]);
  160. $this->lineno = (int) $match[1];
  161. } else {
  162. $this->pushToken(Twig_Token::BLOCK_START_TYPE);
  163. $this->pushState(self::STATE_BLOCK);
  164. }
  165. break;
  166. case $this->options['tag_variable'][0]:
  167. $this->pushToken(Twig_Token::VAR_START_TYPE);
  168. $this->pushState(self::STATE_VAR);
  169. break;
  170. }
  171. }
  172. protected function lexBlock()
  173. {
  174. if (empty($this->brackets) && preg_match($this->regexes['lex_block'], $this->code, $match, null, $this->cursor)) {
  175. $this->pushToken(Twig_Token::BLOCK_END_TYPE);
  176. $this->moveCursor($match[0]);
  177. $this->popState();
  178. } else {
  179. $this->lexExpression();
  180. }
  181. }
  182. protected function lexVar()
  183. {
  184. if (empty($this->brackets) && preg_match($this->regexes['lex_var'], $this->code, $match, null, $this->cursor)) {
  185. $this->pushToken(Twig_Token::VAR_END_TYPE);
  186. $this->moveCursor($match[0]);
  187. $this->popState();
  188. } else {
  189. $this->lexExpression();
  190. }
  191. }
  192. protected function lexExpression()
  193. {
  194. // whitespace
  195. if (preg_match('/\s+/A', $this->code, $match, null, $this->cursor)) {
  196. $this->moveCursor($match[0]);
  197. if ($this->cursor >= $this->end) {
  198. throw new Twig_Error_Syntax(sprintf('Unexpected end of file: Unclosed "%s"', $this->state === self::STATE_BLOCK ? 'block' : 'variable'), $this->lineno, $this->filename);
  199. }
  200. }
  201. // operators
  202. if (preg_match($this->regexes['operator'], $this->code, $match, null, $this->cursor)) {
  203. $this->pushToken(Twig_Token::OPERATOR_TYPE, $match[0]);
  204. $this->moveCursor($match[0]);
  205. }
  206. // names
  207. elseif (preg_match(self::REGEX_NAME, $this->code, $match, null, $this->cursor)) {
  208. $this->pushToken(Twig_Token::NAME_TYPE, $match[0]);
  209. $this->moveCursor($match[0]);
  210. }
  211. // numbers
  212. elseif (preg_match(self::REGEX_NUMBER, $this->code, $match, null, $this->cursor)) {
  213. $number = (float) $match[0]; // floats
  214. if (ctype_digit($match[0]) && $number <= PHP_INT_MAX) {
  215. $number = (int) $match[0]; // integers lower than the maximum
  216. }
  217. $this->pushToken(Twig_Token::NUMBER_TYPE, $number);
  218. $this->moveCursor($match[0]);
  219. }
  220. // punctuation
  221. elseif (false !== strpos(self::PUNCTUATION, $this->code[$this->cursor])) {
  222. // opening bracket
  223. if (false !== strpos('([{', $this->code[$this->cursor])) {
  224. $this->brackets[] = array($this->code[$this->cursor], $this->lineno);
  225. }
  226. // closing bracket
  227. elseif (false !== strpos(')]}', $this->code[$this->cursor])) {
  228. if (empty($this->brackets)) {
  229. throw new Twig_Error_Syntax(sprintf('Unexpected "%s"', $this->code[$this->cursor]), $this->lineno, $this->filename);
  230. }
  231. list($expect, $lineno) = array_pop($this->brackets);
  232. if ($this->code[$this->cursor] != strtr($expect, '([{', ')]}')) {
  233. throw new Twig_Error_Syntax(sprintf('Unclosed "%s"', $expect), $lineno, $this->filename);
  234. }
  235. }
  236. $this->pushToken(Twig_Token::PUNCTUATION_TYPE, $this->code[$this->cursor]);
  237. ++$this->cursor;
  238. }
  239. // strings
  240. elseif (preg_match(self::REGEX_STRING, $this->code, $match, null, $this->cursor)) {
  241. $this->pushToken(Twig_Token::STRING_TYPE, stripcslashes(substr($match[0], 1, -1)));
  242. $this->moveCursor($match[0]);
  243. }
  244. // opening double quoted string
  245. elseif (preg_match(self::REGEX_DQ_STRING_DELIM, $this->code, $match, null, $this->cursor)) {
  246. $this->brackets[] = array('"', $this->lineno);
  247. $this->pushState(self::STATE_STRING);
  248. $this->moveCursor($match[0]);
  249. }
  250. // unlexable
  251. else {
  252. throw new Twig_Error_Syntax(sprintf('Unexpected character "%s"', $this->code[$this->cursor]), $this->lineno, $this->filename);
  253. }
  254. }
  255. protected function lexRawData()
  256. {
  257. if (!preg_match($this->regexes['lex_raw_data'], $this->code, $match, PREG_OFFSET_CAPTURE, $this->cursor)) {
  258. throw new Twig_Error_Syntax(sprintf('Unexpected end of file: Unclosed "block"'), $this->lineno, $this->filename);
  259. }
  260. $text = substr($this->code, $this->cursor, $match[0][1] - $this->cursor);
  261. $this->moveCursor($text.$match[0][0]);
  262. if (false !== strpos($match[1][0], $this->options['whitespace_trim'])) {
  263. $text = rtrim($text);
  264. }
  265. $this->pushToken(Twig_Token::TEXT_TYPE, $text);
  266. }
  267. protected function lexComment()
  268. {
  269. if (!preg_match($this->regexes['lex_comment'], $this->code, $match, PREG_OFFSET_CAPTURE, $this->cursor)) {
  270. throw new Twig_Error_Syntax('Unclosed comment', $this->lineno, $this->filename);
  271. }
  272. $this->moveCursor(substr($this->code, $this->cursor, $match[0][1] - $this->cursor).$match[0][0]);
  273. }
  274. protected function lexString()
  275. {
  276. if (preg_match($this->regexes['interpolation_start'], $this->code, $match, null, $this->cursor)) {
  277. $this->brackets[] = array($this->options['interpolation'][0], $this->lineno);
  278. $this->pushToken(Twig_Token::INTERPOLATION_START_TYPE);
  279. $this->moveCursor($match[0]);
  280. $this->pushState(self::STATE_INTERPOLATION);
  281. } elseif (preg_match(self::REGEX_DQ_STRING_PART, $this->code, $match, null, $this->cursor) && strlen($match[0]) > 0) {
  282. $this->pushToken(Twig_Token::STRING_TYPE, stripcslashes($match[0]));
  283. $this->moveCursor($match[0]);
  284. } elseif (preg_match(self::REGEX_DQ_STRING_DELIM, $this->code, $match, null, $this->cursor)) {
  285. list($expect, $lineno) = array_pop($this->brackets);
  286. if ($this->code[$this->cursor] != '"') {
  287. throw new Twig_Error_Syntax(sprintf('Unclosed "%s"', $expect), $lineno, $this->filename);
  288. }
  289. $this->popState();
  290. ++$this->cursor;
  291. }
  292. }
  293. protected function lexInterpolation()
  294. {
  295. $bracket = end($this->brackets);
  296. if ($this->options['interpolation'][0] === $bracket[0] && preg_match($this->regexes['interpolation_end'], $this->code, $match, null, $this->cursor)) {
  297. array_pop($this->brackets);
  298. $this->pushToken(Twig_Token::INTERPOLATION_END_TYPE);
  299. $this->moveCursor($match[0]);
  300. $this->popState();
  301. } else {
  302. $this->lexExpression();
  303. }
  304. }
  305. protected function pushToken($type, $value = '')
  306. {
  307. // do not push empty text tokens
  308. if (Twig_Token::TEXT_TYPE === $type && '' === $value) {
  309. return;
  310. }
  311. $this->tokens[] = new Twig_Token($type, $value, $this->lineno);
  312. }
  313. protected function moveCursor($text)
  314. {
  315. $this->cursor += strlen($text);
  316. $this->lineno += substr_count($text, "\n");
  317. }
  318. protected function getOperatorRegex()
  319. {
  320. $operators = array_merge(
  321. array('='),
  322. array_keys($this->env->getUnaryOperators()),
  323. array_keys($this->env->getBinaryOperators())
  324. );
  325. $operators = array_combine($operators, array_map('strlen', $operators));
  326. arsort($operators);
  327. $regex = array();
  328. foreach ($operators as $operator => $length) {
  329. // an operator that ends with a character must be followed by
  330. // a whitespace or a parenthesis
  331. if (ctype_alpha($operator[$length - 1])) {
  332. $regex[] = preg_quote($operator, '/').'(?=[\s()])';
  333. } else {
  334. $regex[] = preg_quote($operator, '/');
  335. }
  336. }
  337. return '/'.implode('|', $regex).'/A';
  338. }
  339. protected function pushState($state)
  340. {
  341. $this->states[] = $this->state;
  342. $this->state = $state;
  343. }
  344. protected function popState()
  345. {
  346. if (0 === count($this->states)) {
  347. throw new Exception('Cannot pop state without a previous state');
  348. }
  349. $this->state = array_pop($this->states);
  350. }
  351. }