PageRenderTime 43ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-content/plugins/mailpoet/vendor-prefixed/twig/twig/src/Lexer.php

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