-
Notifications
You must be signed in to change notification settings - Fork 504
/
Copy pathFileAnalyser.php
375 lines (336 loc) · 13 KB
/
FileAnalyser.php
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
<?php declare(strict_types = 1);
namespace PHPStan\Analyser;
use PhpParser\Node;
use PHPStan\AnalysedCodeException;
use PHPStan\BetterReflection\NodeCompiler\Exception\UnableToCompileNode;
use PHPStan\BetterReflection\Reflection\Exception\CircularReference;
use PHPStan\BetterReflection\Reflector\Exception\IdentifierNotFound;
use PHPStan\Collectors\CollectedData;
use PHPStan\Collectors\Registry as CollectorRegistry;
use PHPStan\Dependency\DependencyResolver;
use PHPStan\Node\FileNode;
use PHPStan\Node\InTraitNode;
use PHPStan\Parser\Parser;
use PHPStan\Parser\ParserErrorsException;
use PHPStan\Rules\Registry as RuleRegistry;
use function array_keys;
use function array_unique;
use function array_values;
use function count;
use function error_reporting;
use function get_class;
use function is_dir;
use function is_file;
use function restore_error_handler;
use function set_error_handler;
use function sprintf;
use const E_DEPRECATED;
use const E_ERROR;
use const E_NOTICE;
use const E_PARSE;
use const E_STRICT;
use const E_USER_DEPRECATED;
use const E_USER_ERROR;
use const E_USER_NOTICE;
use const E_USER_WARNING;
use const E_WARNING;
final class FileAnalyser
{
/** @var list<Error> */
private array $allPhpErrors = [];
/** @var list<Error> */
private array $filteredPhpErrors = [];
public function __construct(
private ScopeFactory $scopeFactory,
private NodeScopeResolver $nodeScopeResolver,
private Parser $parser,
private DependencyResolver $dependencyResolver,
private RuleErrorTransformer $ruleErrorTransformer,
private LocalIgnoresProcessor $localIgnoresProcessor,
)
{
}
/**
* @param array<string, true> $analysedFiles
* @param callable(Node $node, Scope $scope): void|null $outerNodeCallback
*/
public function analyseFile(
string $file,
array $analysedFiles,
RuleRegistry $ruleRegistry,
CollectorRegistry $collectorRegistry,
?callable $outerNodeCallback,
): FileAnalyserResult
{
/** @var list<Error> $fileErrors */
$fileErrors = [];
/** @var list<Error> $locallyIgnoredErrors */
$locallyIgnoredErrors = [];
/** @var list<CollectedData> $fileCollectedData */
$fileCollectedData = [];
$fileDependencies = [];
$exportedNodes = [];
$linesToIgnore = [];
$unmatchedLineIgnores = [];
if (is_file($file)) {
try {
$this->collectErrors($analysedFiles);
$parserNodes = $this->parser->parseFile($file);
$linesToIgnore = $unmatchedLineIgnores = [$file => $this->getLinesToIgnoreFromTokens($parserNodes)];
$temporaryFileErrors = [];
$nodeCallback = function (Node $node, Scope $scope) use (&$fileErrors, &$fileCollectedData, &$fileDependencies, &$exportedNodes, $file, $ruleRegistry, $collectorRegistry, $outerNodeCallback, $analysedFiles, &$linesToIgnore, &$unmatchedLineIgnores, &$temporaryFileErrors): void {
if ($node instanceof Node\Stmt\Trait_) {
foreach (array_keys($linesToIgnore[$file] ?? []) as $lineToIgnore) {
if ($lineToIgnore < $node->getStartLine() || $lineToIgnore > $node->getEndLine()) {
continue;
}
unset($unmatchedLineIgnores[$file][$lineToIgnore]);
}
}
if ($node instanceof InTraitNode) {
$traitNode = $node->getOriginalNode();
$linesToIgnore[$scope->getFileDescription()] = $this->getLinesToIgnoreFromTokens([$traitNode]);
}
if ($outerNodeCallback !== null) {
$outerNodeCallback($node, $scope);
}
$uniquedAnalysedCodeExceptionMessages = [];
$nodeType = get_class($node);
foreach ($ruleRegistry->getRules($nodeType) as $rule) {
try {
$ruleErrors = $rule->processNode($node, $scope);
} catch (AnalysedCodeException $e) {
if (isset($uniquedAnalysedCodeExceptionMessages[$e->getMessage()])) {
continue;
}
$uniquedAnalysedCodeExceptionMessages[$e->getMessage()] = true;
$fileErrors[] = (new Error($e->getMessage(), $file, $node->getStartLine(), $e, null, null, $e->getTip()))
->withIdentifier('phpstan.internal')
->withMetadata([
InternalError::STACK_TRACE_METADATA_KEY => InternalError::prepareTrace($e),
InternalError::STACK_TRACE_AS_STRING_METADATA_KEY => $e->getTraceAsString(),
]);
continue;
} catch (IdentifierNotFound $e) {
$fileErrors[] = (new Error(sprintf('Reflection error: %s not found.', $e->getIdentifier()->getName()), $file, $node->getStartLine(), $e, null, null, 'Learn more at https://phpstan.org/user-guide/discovering-symbols'))
->withIdentifier('phpstan.reflection')
->withMetadata([
InternalError::STACK_TRACE_METADATA_KEY => InternalError::prepareTrace($e),
InternalError::STACK_TRACE_AS_STRING_METADATA_KEY => $e->getTraceAsString(),
]);
continue;
} catch (UnableToCompileNode | CircularReference $e) {
$fileErrors[] = (new Error(sprintf('Reflection error: %s', $e->getMessage()), $file, $node->getStartLine(), $e))
->withIdentifier('phpstan.reflection')
->withMetadata([
InternalError::STACK_TRACE_METADATA_KEY => InternalError::prepareTrace($e),
InternalError::STACK_TRACE_AS_STRING_METADATA_KEY => $e->getTraceAsString(),
]);
continue;
}
foreach ($ruleErrors as $ruleError) {
$temporaryFileErrors[] = $this->ruleErrorTransformer->transform($ruleError, $scope, $nodeType, $node->getStartLine());
}
}
foreach ($collectorRegistry->getCollectors($nodeType) as $collector) {
try {
$collectedData = $collector->processNode($node, $scope);
} catch (AnalysedCodeException $e) {
if (isset($uniquedAnalysedCodeExceptionMessages[$e->getMessage()])) {
continue;
}
$uniquedAnalysedCodeExceptionMessages[$e->getMessage()] = true;
$fileErrors[] = (new Error($e->getMessage(), $file, $node->getStartLine(), $e, null, null, $e->getTip()))
->withIdentifier('phpstan.internal')
->withMetadata([
InternalError::STACK_TRACE_METADATA_KEY => InternalError::prepareTrace($e),
InternalError::STACK_TRACE_AS_STRING_METADATA_KEY => $e->getTraceAsString(),
]);
continue;
} catch (IdentifierNotFound $e) {
$fileErrors[] = (new Error(sprintf('Reflection error: %s not found.', $e->getIdentifier()->getName()), $file, $node->getStartLine(), $e, null, null, 'Learn more at https://phpstan.org/user-guide/discovering-symbols'))
->withIdentifier('phpstan.reflection')
->withMetadata([
InternalError::STACK_TRACE_METADATA_KEY => InternalError::prepareTrace($e),
InternalError::STACK_TRACE_AS_STRING_METADATA_KEY => $e->getTraceAsString(),
]);
continue;
} catch (UnableToCompileNode | CircularReference $e) {
$fileErrors[] = (new Error(sprintf('Reflection error: %s', $e->getMessage()), $file, $node->getStartLine(), $e))
->withIdentifier('phpstan.reflection')
->withMetadata([
InternalError::STACK_TRACE_METADATA_KEY => InternalError::prepareTrace($e),
InternalError::STACK_TRACE_AS_STRING_METADATA_KEY => $e->getTraceAsString(),
]);
continue;
}
if ($collectedData === null) {
continue;
}
$fileCollectedData[] = new CollectedData(
$collectedData,
$scope->getFile(),
get_class($collector),
);
}
try {
$dependencies = $this->dependencyResolver->resolveDependencies($node, $scope);
foreach ($dependencies->getFileDependencies($scope->getFile(), $analysedFiles) as $dependentFile) {
$fileDependencies[] = $dependentFile;
}
if ($dependencies->getExportedNode() !== null) {
$exportedNodes[] = $dependencies->getExportedNode();
}
} catch (AnalysedCodeException) {
// pass
} catch (IdentifierNotFound) {
// pass
} catch (UnableToCompileNode) {
// pass
}
};
$scope = $this->scopeFactory->create(ScopeContext::create($file));
$nodeCallback(new FileNode($parserNodes), $scope);
$this->nodeScopeResolver->processNodes(
$parserNodes,
$scope,
$nodeCallback,
);
$localIgnoresProcessorResult = $this->localIgnoresProcessor->process(
$temporaryFileErrors,
$linesToIgnore,
$unmatchedLineIgnores,
);
foreach ($localIgnoresProcessorResult->getFileErrors() as $fileError) {
$fileErrors[] = $fileError;
}
foreach ($localIgnoresProcessorResult->getLocallyIgnoredErrors() as $locallyIgnoredError) {
$locallyIgnoredErrors[] = $locallyIgnoredError;
}
$linesToIgnore = $localIgnoresProcessorResult->getLinesToIgnore();
$unmatchedLineIgnores = $localIgnoresProcessorResult->getUnmatchedLineIgnores();
} catch (\PhpParser\Error $e) {
$fileErrors[] = (new Error($e->getRawMessage(), $file, $e->getStartLine() !== -1 ? $e->getStartLine() : null, $e))->withIdentifier('phpstan.parse');
} catch (ParserErrorsException $e) {
foreach ($e->getErrors() as $error) {
$fileErrors[] = (new Error($error->getMessage(), $e->getParsedFile() ?? $file, $error->getLine() !== -1 ? $error->getStartLine() : null, $e))->withIdentifier('phpstan.parse');
}
} catch (AnalysedCodeException $e) {
$fileErrors[] = (new Error($e->getMessage(), $file, null, $e, null, null, $e->getTip()))
->withIdentifier('phpstan.internal')
->withMetadata([
InternalError::STACK_TRACE_METADATA_KEY => InternalError::prepareTrace($e),
InternalError::STACK_TRACE_AS_STRING_METADATA_KEY => $e->getTraceAsString(),
]);
} catch (IdentifierNotFound $e) {
$fileErrors[] = (new Error(sprintf('Reflection error: %s not found.', $e->getIdentifier()->getName()), $file, null, $e, null, null, 'Learn more at https://phpstan.org/user-guide/discovering-symbols'))
->withIdentifier('phpstan.reflection')
->withMetadata([
InternalError::STACK_TRACE_METADATA_KEY => InternalError::prepareTrace($e),
InternalError::STACK_TRACE_AS_STRING_METADATA_KEY => $e->getTraceAsString(),
]);
} catch (UnableToCompileNode | CircularReference $e) {
$fileErrors[] = (new Error(sprintf('Reflection error: %s', $e->getMessage()), $file, null, $e))
->withIdentifier('phpstan.reflection')
->withMetadata([
InternalError::STACK_TRACE_METADATA_KEY => InternalError::prepareTrace($e),
InternalError::STACK_TRACE_AS_STRING_METADATA_KEY => $e->getTraceAsString(),
]);
}
} elseif (is_dir($file)) {
$fileErrors[] = (new Error(sprintf('File %s is a directory.', $file), $file, null, false))->withIdentifier('phpstan.path');
} else {
$fileErrors[] = (new Error(sprintf('File %s does not exist.', $file), $file, null, false))->withIdentifier('phpstan.path');
}
$this->restoreCollectErrorsHandler();
foreach ($linesToIgnore as $fileKey => $lines) {
if (count($lines) > 0) {
continue;
}
unset($linesToIgnore[$fileKey]);
}
foreach ($unmatchedLineIgnores as $fileKey => $lines) {
if (count($lines) > 0) {
continue;
}
unset($unmatchedLineIgnores[$fileKey]);
}
return new FileAnalyserResult(
$fileErrors,
$this->filteredPhpErrors,
$this->allPhpErrors,
$locallyIgnoredErrors,
$fileCollectedData,
array_values(array_unique($fileDependencies)),
$exportedNodes,
$linesToIgnore,
$unmatchedLineIgnores,
);
}
/**
* @param Node[] $nodes
* @return array<int, non-empty-list<string>|null>
*/
private function getLinesToIgnoreFromTokens(array $nodes): array
{
if (!isset($nodes[0])) {
return [];
}
/** @var array<int, non-empty-list<string>|null> */
return $nodes[0]->getAttribute('linesToIgnore', []);
}
/**
* @param array<string, true> $analysedFiles
*/
private function collectErrors(array $analysedFiles): void
{
$this->filteredPhpErrors = [];
$this->allPhpErrors = [];
set_error_handler(function (int $errno, string $errstr, string $errfile, int $errline) use ($analysedFiles): bool {
if ((error_reporting() & $errno) === 0) {
// silence @ operator
return true;
}
$errorMessage = sprintf('%s: %s', $this->getErrorLabel($errno), $errstr);
$this->allPhpErrors[] = (new Error($errorMessage, $errfile, $errline, false))->withIdentifier('phpstan.php');
if ($errno === E_DEPRECATED) {
return true;
}
if (!isset($analysedFiles[$errfile])) {
return true;
}
$this->filteredPhpErrors[] = (new Error($errorMessage, $errfile, $errline, $errno === E_USER_DEPRECATED))->withIdentifier('phpstan.php');
return true;
});
}
private function restoreCollectErrorsHandler(): void
{
restore_error_handler();
}
private function getErrorLabel(int $errno): string
{
switch ($errno) {
case E_ERROR:
return 'Fatal error';
case E_WARNING:
return 'Warning';
case E_PARSE:
return 'Parse error';
case E_NOTICE:
return 'Notice';
case E_DEPRECATED:
return 'Deprecated';
case E_USER_ERROR:
return 'User error (E_USER_ERROR)';
case E_USER_WARNING:
return 'User warning (E_USER_WARNING)';
case E_USER_NOTICE:
return 'User notice (E_USER_NOTICE)';
case E_USER_DEPRECATED:
return 'Deprecated (E_USER_DEPRECATED)';
case E_STRICT:
return 'Strict error (E_STRICT)';
}
return 'Unknown PHP error';
}
}