Repository navigation
Expand file tree
/
Copy pathCompiledExpressionLanguage.php
More file actions
279 lines (231 loc) · 10.8 KB
/
Copy pathCompiledExpressionLanguage.php
File metadata and controls
279 lines (231 loc) · 10.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\ExpressionLanguage;
/**
* Decorates an expression language to evaluate and lint the expressions compiled by dumpCompiled() without parsing them.
*
* @author Nicolas Grekas <p@tchwork.com>
*/
final class CompiledExpressionLanguage extends ExpressionLanguage
{
/**
* @var array<string, array{callable(array<string, mixed>, array<string, array>=): mixed, array<string, int|null>, bool}>
*/
private array $compiledExpressions;
private string|false $compiledExpressionsPath = false;
/**
* @param string|null $compiledExpressionsFile A file generated with dumpCompiled()
*/
public function __construct(
private ExpressionLanguage $expressionLanguage,
private ?string $compiledExpressionsFile = null,
) {
// the parent constructor is not called: every method delegates to the decorated expression language
}
public function compile(Expression|string $expression, array $names = []): string
{
return $this->expressionLanguage->compile($expression, $names);
}
public function evaluate(Expression|string $expression, array $values = []): mixed
{
if (null === $compiled = $this->getCompiledExpression($expression)) {
return $this->expressionLanguage->evaluate($expression, $values);
}
[$evaluator, $variables, $usesFunctions] = $compiled;
// the expression was compiled without knowing which variables would be valid:
// when one is missing, parsing it again reports the error the way it always did
foreach ($variables as $name => $cursor) {
if (null === $cursor) {
break;
}
if (!\array_key_exists($name, $values)) {
return $this->expressionLanguage->evaluate($expression, $values);
}
}
// an error raised by the compiled code is reported the way evaluating the nodes reports it
$path = $this->compiledExpressionsPath;
$previous = set_error_handler(static function (int $type, string $message, string $file = '', int $line = 0) use (&$previous, $path): bool {
if ($path === $file) {
throw new \ErrorException($message, 0, $type, $file, $line);
}
return null !== $previous && false !== $previous($type, $message, $file, $line);
});
try {
return $usesFunctions ? $evaluator($values, $this->expressionLanguage->functions) : $evaluator($values);
} catch (\Throwable $e) {
if ($path !== $e->getFile()) {
throw $e;
}
} finally {
restore_error_handler();
}
return $this->expressionLanguage->evaluate($expression, $values);
}
public function parse(Expression|string $expression, array $names, int $flags = 0): ParsedExpression
{
return $this->expressionLanguage->parse($expression, $names, $flags);
}
public function lint(Expression|string $expression, array $names, int $flags = 0): void
{
if ($expression instanceof ParsedExpression || null === $compiled = $this->getCompiledExpression($expression)) {
$this->expressionLanguage->lint($expression, $names, $flags);
return;
}
if ($flags & Parser::IGNORE_UNKNOWN_VARIABLES) {
return;
}
// variables are sorted by the position where they're first read without "??", like the parser meets them
foreach ($compiled[1] as $name => $cursor) {
if (null === $cursor) {
return;
}
if (!\in_array($name, $names, true)) {
throw new SyntaxError(\sprintf('Variable "%s" is not valid.', $name), $cursor, (string) $expression, $name, $names);
}
}
}
/**
* Compiles expressions to the PHP code of a file that the constructor can load.
*
* The expressions this file holds are then evaluated and linted without being parsed.
* A function whose compiler throws is called through its evaluator.
* The expressions that cannot be compiled are left out.
*
* @param iterable<Expression|string> $expressions
*/
public function dumpCompiled(iterable $expressions): string
{
$parser = new Parser($this->expressionLanguage->functions);
$methods = $map = [];
// placeholders for the parameters of the generated methods, renamed once the variables of each expression are known
$valuesPlaceholder = 'values'.bin2hex(random_bytes(8));
$functionsPlaceholder = 'functions'.bin2hex(random_bytes(8));
$functions = [];
foreach ($this->expressionLanguage->functions as $name => $function) {
$compile = $function['compiler'];
$function['compiler'] = static function (...$arguments) use ($compile, $name, $valuesPlaceholder, $functionsPlaceholder): string {
try {
return $compile(...$arguments);
} catch (\Exception) {
return \sprintf('$%s[%s][\'evaluator\']($%s%s)', $functionsPlaceholder, var_export($name, true), $valuesPlaceholder, $arguments ? ', '.implode(', ', $arguments) : '');
}
};
$functions[$name] = $function;
}
$compiler = new Compiler($functions);
$lexer = new Lexer();
foreach ($expressions as $expression) {
if (isset($map[$expression = (string) $expression])) {
continue;
}
try {
$nodes = $parser->parse($lexer->tokenize($expression), [], Parser::IGNORE_UNKNOWN_VARIABLES);
$variables = $parser->getVariables();
uasort($variables, static fn (?int $a, ?int $b) => ($a ?? \PHP_INT_MAX) <=> ($b ?? \PHP_INT_MAX));
$thisVariable = null;
if (\array_key_exists('this', $variables)) {
$thisVariable = 'this_';
while (\array_key_exists($thisVariable, $variables)) {
$thisVariable .= '_';
}
self::renameVariable($nodes, 'this', $thisVariable);
}
$source = $compiler->reset()->compile($nodes)->getSource();
} catch (\Exception) {
continue;
}
$phpVariables = [];
foreach (token_get_all('<?php '.$source) as $token) {
if (\is_array($token) && \T_VARIABLE === $token[0]) {
$phpVariables[substr($token[1], 1)] = true;
}
}
if (isset($phpVariables['this'])) {
continue;
}
$usesFunctions = isset($phpVariables[$functionsPlaceholder]);
unset($phpVariables[$valuesPlaceholder], $phpVariables[$functionsPlaceholder]);
$param = 'values';
while (isset($phpVariables[$param])) {
$param .= '_';
}
$params = 'array $'.$param;
$source = str_replace('$'.$valuesPlaceholder, '$'.$param, $source);
if ($usesFunctions) {
$functionsParam = 'functions';
while (isset($phpVariables[$functionsParam])) {
$functionsParam .= '_';
}
$params .= ', array $'.$functionsParam;
$source = str_replace('$'.$functionsPlaceholder, '$'.$functionsParam, $source);
}
$method = 'e'.\count($methods);
$code = '';
foreach ($phpVariables as $name => $_) {
$code .= \sprintf(" \$%s = \$%s[%s] ?? null;\n", $name, $param, var_export($thisVariable === $name ? 'this' : $name, true));
}
$methods[$method] = \sprintf(" public static function %s(%s): mixed\n {\n%s return %s;\n }\n", $method, $params, $code ? $code."\n" : '', $source);
$map[$expression] = [$method, $variables, $usesFunctions];
}
if (!$map) {
return "<?php\n\nreturn [];\n";
}
$namespace = 'ExpressionLanguage'.substr(hash('xxh128', $methods = implode("\n", $methods)), 0, 16);
$code = "<?php\n\n// This file has been auto-generated by the Symfony ExpressionLanguage component.\n\nnamespace {$namespace};\n\n";
$code .= "if (!\\class_exists(CompiledExpressions::class, false)) {\n final class CompiledExpressions\n {\n{$methods} }\n}\n\nreturn [\n";
foreach ($map as $expression => [$method, $variables, $usesFunctions]) {
$code .= \sprintf(" %s => [%s, %s, %s],\n", var_export($expression, true), var_export($namespace.'\\CompiledExpressions::'.$method, true), self::exportVariables($variables), $usesFunctions ? 'true' : 'false');
}
return $code."];\n";
}
public function register(string $name, callable $compiler, callable $evaluator): void
{
$this->expressionLanguage->register($name, $compiler, $evaluator);
}
public function addFunction(ExpressionFunction $function): void
{
$this->expressionLanguage->addFunction($function);
}
public function registerProvider(ExpressionFunctionProviderInterface $provider): void
{
$this->expressionLanguage->registerProvider($provider);
}
/**
* @return array{callable(array<string, mixed>, array<string, array>=): mixed, array<string, int|null>, bool}|null
*/
private function getCompiledExpression(Expression|string $expression): ?array
{
if (!isset($this->compiledExpressions)) {
$this->compiledExpressions = [];
if (null !== $this->compiledExpressionsFile && is_file($this->compiledExpressionsFile)) {
$this->compiledExpressions = require $this->compiledExpressionsFile;
$this->compiledExpressionsPath = realpath($this->compiledExpressionsFile);
}
}
return $this->compiledExpressions[(string) $expression] ?? null;
}
private static function renameVariable(Node\Node $node, string $from, string $to): void
{
if ($node instanceof Node\NameNode && $from === $node->attributes['name']) {
$node->attributes['name'] = $to;
}
foreach ($node->nodes as $child) {
self::renameVariable($child, $from, $to);
}
}
private static function exportVariables(array $variables): string
{
$code = [];
foreach ($variables as $name => $cursor) {
$code[] = var_export($name, true).' => '.var_export($cursor, true);
}
return '['.implode(', ', $code).']';
}
}