-
Notifications
You must be signed in to change notification settings - Fork 563
Expand file tree
/
Copy pathgenerate-function-metadata.php
More file actions
executable file
·225 lines (199 loc) · 6.71 KB
/
generate-function-metadata.php
File metadata and controls
executable file
·225 lines (199 loc) · 6.71 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
#!/usr/bin/env php
<?php declare(strict_types = 1);
use JetBrains\PhpStorm\Pure;
use PhpParser\Node;
use PhpParser\NodeTraverser;
use PhpParser\NodeVisitor\NameResolver;
use PhpParser\NodeVisitor\NodeConnectingVisitor;
use PhpParser\NodeVisitorAbstract;
use PhpParser\ParserFactory;
use PHPStan\File\FileReader;
use PHPStan\File\FileWriter;
use PHPStan\ShouldNotHappenException;
use Symfony\Component\Finder\Finder;
(function (): void {
require_once __DIR__ . '/../vendor/autoload.php';
$parser = (new ParserFactory())->createForNewestSupportedVersion();
$finder = new Finder();
$finder->in(__DIR__ . '/../vendor/jetbrains/phpstorm-stubs')->files()->name('*.php');
$visitor = new class() extends NodeVisitorAbstract {
/** @var string[] */
public array $functions = [];
/** @var list<string> */
public array $impureFunctions = [];
/** @var string[] */
public array $methods = [];
public function enterNode(Node $node)
{
if ($node instanceof Node\Stmt\Function_) {
assert(isset($node->namespacedName));
$functionName = $node->namespacedName->toLowerString();
foreach ($node->attrGroups as $attrGroup) {
foreach ($attrGroup->attrs as $attr) {
if ($attr->name->toString() !== Pure::class) {
continue;
}
// The following functions have side effects, but their state is managed within the PHPStan scope:
if (in_array($functionName, [
'stat',
'lstat',
'file_exists',
'is_writable',
'is_writeable',
'is_readable',
'is_executable',
'is_file',
'is_dir',
'is_link',
'filectime',
'fileatime',
'filemtime',
'fileinode',
'filegroup',
'fileowner',
'filesize',
'filetype',
'fileperms',
'ftell',
'ini_get',
'function_exists',
'json_last_error',
'json_last_error_msg',
], true)) {
$this->functions[] = $functionName;
break 2;
}
// PhpStorm stub's #[Pure(true)] means the function has side effects but its return value is important.
// In PHPStan's criteria, these functions are simply considered as ['hasSideEffect' => true].
if (isset($attr->args[0]->value->name->name) && $attr->args[0]->value->name->name === 'true') {
$this->impureFunctions[] = $functionName;
} else {
$this->functions[] = $functionName;
}
break 2;
}
}
}
if ($node instanceof Node\Stmt\ClassMethod) {
$class = $node->getAttribute('parent');
if (!$class instanceof Node\Stmt\ClassLike) {
throw new ShouldNotHappenException($node->name->toString());
}
$className = $class->namespacedName->toString();
foreach ($node->attrGroups as $attrGroup) {
foreach ($attrGroup->attrs as $attr) {
if ($attr->name->toString() === Pure::class) {
$this->methods[] = sprintf('%s::%s', $className, $node->name->toString());
break 2;
}
}
}
}
return null;
}
};
foreach ($finder as $stubFile) {
$path = $stubFile->getPathname();
$traverser = new NodeTraverser();
$traverser->addVisitor(new NameResolver());
$traverser->addVisitor(new NodeConnectingVisitor());
$traverser->addVisitor($visitor);
$traverser->traverse(
$parser->parse(FileReader::read($path)),
);
}
/** @var array<string, array{hasSideEffects: bool}> $metadata */
$metadata = require __DIR__ . '/functionMetadata_original.php';
foreach ($visitor->functions as $functionName) {
if (array_key_exists($functionName, $metadata)) {
if (isset($metadata[$functionName]['hasSideEffects']) && $metadata[$functionName]['hasSideEffects']) {
throw new ShouldNotHappenException($functionName);
}
if (isset($metadata[$functionName]['pureUnlessCallableIsImpureParameters'])) {
$metadata[$functionName] = [
'pureUnlessCallableIsImpureParameters' => $metadata[$functionName]['pureUnlessCallableIsImpureParameters'],
];
continue;
}
}
$metadata[$functionName] = ['hasSideEffects' => false];
}
foreach ($visitor->impureFunctions as $functionName) {
if (in_array($functionName, [
'class_exists',
'enum_exists',
'interface_exists',
'trait_exists',
], true)) {
continue;
}
if (array_key_exists($functionName, $metadata)) {
if (in_array($functionName, [
'ob_get_contents',
], true)) {
continue;
}
if (!$metadata[$functionName]['hasSideEffects']) {
throw new ShouldNotHappenException($functionName);
}
}
$metadata[$functionName] = ['hasSideEffects' => true];
}
foreach ($visitor->methods as $methodName) {
if (array_key_exists($methodName, $metadata)) {
if ($metadata[$methodName]['hasSideEffects']) {
throw new ShouldNotHappenException($methodName);
}
}
$metadata[$methodName] = ['hasSideEffects' => false];
}
ksort($metadata);
$template = <<<'php'
<?php declare(strict_types = 1);
/**
* GENERATED FILE - DO NOT EDIT!
*
* This file is generated automatically when running bin/generate-function-metadata.php
* and the result is merged from bin/functionMetadata_original.php and by looking at jetbrains/phpstorm-stubs methods
* and functions with the #[Pure] attribute.
*
* If you want to add new entries here follow these steps:
* 1) verify on https://phpstan.org/try whether the entry you are going to add does not already work as expected.
* 2) Contribute the functions that have 'hasSideEffects' => true as a modification to bin/functionMetadata_original.php.
* 3) Contribute the #[Pure] functions without side effects to https://github.com/JetBrains/phpstorm-stubs
* 4) Once the PR from 3) is merged, please update the package here and run ./bin/generate-function-metadata.php.
*/
return [
%s
];
php;
$content = '';
$escape = static fn (mixed $value): string => var_export($value, true);
$encodeHasSideEffects = static fn (array $meta) => [$escape('hasSideEffects'), $escape($meta['hasSideEffects'])];
$encodePureUnlessCallableIsImpureParameters = static fn (array $meta) => [
$escape('pureUnlessCallableIsImpureParameters'),
sprintf(
'[%s]',
implode(
' ,',
array_map(
static fn ($key, $param) => sprintf('%s => %s', $escape($key), $escape($param)),
array_keys($meta['pureUnlessCallableIsImpureParameters']),
$meta['pureUnlessCallableIsImpureParameters'],
),
),
),
];
foreach ($metadata as $name => $meta) {
$content .= sprintf(
"\t%s => [%s => %s],\n",
var_export($name, true),
...match (true) {
isset($meta['hasSideEffects']) => $encodeHasSideEffects($meta),
isset($meta['pureUnlessCallableIsImpureParameters']) => $encodePureUnlessCallableIsImpureParameters($meta),
default => throw new ShouldNotHappenException($escape($meta)),
},
);
}
FileWriter::write(__DIR__ . '/../resources/functionMetadata.php', sprintf($template, $content));
})();