-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFromSyntaxTree.class.php
More file actions
executable file
·244 lines (214 loc) · 8.21 KB
/
FromSyntaxTree.class.php
File metadata and controls
executable file
·244 lines (214 loc) · 8.21 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
<?php namespace lang\meta;
use lang\IllegalArgumentException;
use lang\ast\nodes\{ArrayLiteral, FunctionDeclaration};
use lang\ast\{Language, Token, Tokens, Visitor, Code};
/**
* Parses annotations from AST, using PHP language syntax.
*
* @see https://github.com/xp-framework/ast
*/
class FromSyntaxTree {
const CACHE_SIZE= 16;
private static $lang;
private static $parse= null;
private $cache= [];
static function __static() {
self::$lang= Language::named('PHP');
}
/** Locates an anonymous class creation expression */
private function anonymous($tree, $start, $end) {
foreach ($tree->children() as $child) {
yield from $this->anonymous($child, $start, $end);
if ('newclass' === $child->kind && $child->line >= $start && $child->line <= $end) yield $child;
}
}
/** Returns the syntax tree for a given type using a cache */
private function tree($reflect) {
// Handle generic class names correctly
if ($class= \xp::$cn[$reflect->name] ?? null) {
$class= substr($class, 0, strcspn($class, '<'));
} else {
$class= strtr($reflect->name, '\\', '.');
}
if (!isset($this->cache[$class])) {
if ($reflect->isAnonymous()) {
$tree= self::$lang->parse(new Tokens(file_get_contents($reflect->getFileName()), '<anonymous>'))->tree();
$type= $this->anonymous($tree, $reflect->getStartLine(), $reflect->getEndLine())->current()->definition;
} else {
sscanf(\xp::$cl[$class], '%[^:]://%[^$]', $cl, $argument);
$instanceFor= [literal($cl), 'instanceFor'];
$tree= self::$lang->parse(new Tokens($instanceFor($argument)->loadClassBytes($class), $class))->tree();
$type= $tree->type(strtr($class, '.', '\\'));
}
// Limit cache
$this->cache[$class]= new SyntaxTree($tree, $type);
if (sizeof($this->cache) > self::CACHE_SIZE) unset($this->cache[key($this->cache)]);
}
return $this->cache[$class];
}
private function parse($code, $resolver) {
if (null === self::$parse) {
// Parse lambdas and closures into code
self::$parse= clone self::$lang;
self::$parse->prefix('fn', 0, function($parse, $token) {
$signature= $this->signature($parse);
$parse->expecting('=>', 'fn');
// Parse expression
$code= '';
$b= $c= 0;
do {
switch ($parse->token->value) {
case '(': $b++; break;
case ')': $b--; if ($b < 0) break 2; else break;
case '[': $c++; break;
case ']': $c--; if ($c < 0) break 2; else break;
case ',': if ($c <= 0 && $b <= 0) break 2; else break; // outside of arrays or argument lists
case '$': $parse->forward(); $parse->token->value= '$'.$parse->token->value; break;
}
$code.= ' '.$parse->token->value;
$parse->forward();
} while (';' !== $parse->token->value);
$params= '';
foreach ($signature->parameters as $param) {
$params.=
', '.
($param->type ? $param->type->literal() : '').
($param->variadic ? '...' : '').
($param->reference ? ' &$': ' $').
$param->name.
($param->default ? '='.$param->default->expression : '')
;
}
$return= $signature->returns ? ':'.$signature->returns->literal() : '';
if (0 === strncmp($code, ' throw ', 7)) {
return new Code('function('.substr($params, 2).')'.$return.' {'.$code.'; }');
} else {
return new Code('function('.substr($params, 2).')'.$return.' { return'.$code.'; }');
}
});
$function= function($parse, $token) {
$signature= $this->signature($parse);
// Parse body
$code= '';
$b= 0;
do {
if ('{' === $parse->token->value) {
$b++;
} else if ('}' === $parse->token->value) {
if (0 === --$b) break;
} else if ('$' === $parse->token->value) {
$parse->forward();
$parse->token->value= '$'.$parse->token->value;
}
$code.= ' '.$parse->token->value;
$parse->forward();
} while (null !== $parse->token->value);
$parse->forward();
$params= '';
foreach ($signature->parameters as $param) {
$params.=
', '.
($param->type ? $param->type->literal() : '').
($param->variadic ? '...' : '').
($param->reference ? ' &$': ' $').
$param->name.
($param->default ? '='.$param->default->expression : '')
;
}
$return= $signature->returns ? ':'.$signature->returns->literal() : '';
return new Code('function('.substr($params, 2).')'.$return.$code.' }');
};
// Function expressions and function expressions used as statement
self::$parse->prefix('function', 0, $function);
self::$parse->stmt('function', function($parse, $token) use($function) {
if ('(' === $parse->token->value) return $function->call($this, $parse, $token);
$name= $parse->token->value;
$parse->forward();
$signature= $this->signature($parse);
$parse->expecting('{', 'function');
$statements= $this->statements($parse);
$parse->expecting('}', 'function');
return new FunctionDeclaration($name, $signature, $statements, $token->line);
});
}
return self::$parse->parse(new Tokens($code.';', '(evaluated)'), $resolver);
}
public function evaluate($arg, $code) {
$tree= $arg instanceof SyntaxTree ? $arg : $this->tree($arg);
$parsed= self::parse($code, $tree->resolver())->tree()->children();
if (1 === sizeof($parsed)) {
return $parsed[0]->visit($tree);
}
throw new IllegalArgumentException('Given code must be a single expression');
}
/**
* Evaluates annotation values, including special-case handling for the
* named argument `eval`.
*
* @param lang.annotations.SyntaxTree $tree
* @param lang.ast.nodes.Annotated $annotated
* @return [:var]
*/
private function annotations($tree, $annotated) {
if (null === $annotated->annotations) return [];
$r= [];
foreach ($annotated->annotations as $type => $args) {
$ptr= &$r[$type];
if (!isset($args['eval'])) {
$ptr= [];
foreach ($args as $name => $argument) {
$ptr[$name]= $argument->visit($tree);
}
} else if ($args['eval'] instanceof ArrayLiteral) {
$ptr= [];
$i= 0;
foreach ($args['eval']->values as list($key, $value)) {
$ptr[$key ? $key->visit($tree) : $i++]= $this->evaluate($tree, $value->visit($tree).';');
}
} else {
$ptr= [$this->evaluate($tree, $args['eval']->visit($tree).';')];
}
}
return $r;
}
public function imports($reflect) {
$imports= ['class' => [], 'function' => [], 'const' => []];
foreach ($this->tree($reflect)->root()->children() as $child) {
if ($child->is('import')) {
foreach ($child->names as $import => $alias) {
$imports[$child->type ?? 'class'][$alias ?? false === ($p= strrpos($import, '\\')) ? $import : substr($import, $p + 1)]= $import;
}
}
}
return $imports;
}
/** @return iterable */
public function ofType($reflect) {
$tree= $this->tree($reflect);
return $this->annotations($tree, $tree->type());
}
/** @return iterable */
public function ofConstant($reflect) {
$tree= $this->tree($reflect->getDeclaringClass());
return $this->annotations($tree, $tree->type()->constant($reflect->name));
}
/** @return iterable */
public function ofProperty($reflect) {
$tree= $this->tree($reflect->getDeclaringClass());
return $this->annotations($tree, $tree->type()->property($reflect->name));
}
/** @return iterable */
public function ofMethod($reflect) {
$tree= $this->tree($reflect->getDeclaringClass());
return $this->annotations($tree, $tree->type()->method($reflect->name));
}
/** @return iterable */
public function ofParameter($method, $reflect) {
$tree= $this->tree($method->getDeclaringClass());
return $this->annotations($tree, $tree->type()
->method($method->name)
->signature
->parameters[$reflect->getPosition()]
);
}
}