-
Notifications
You must be signed in to change notification settings - Fork 477
/
TypeInferenceTestCase.php
240 lines (214 loc) · 7.56 KB
/
TypeInferenceTestCase.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
<?php declare(strict_types = 1);
namespace PHPStan\Testing;
use PhpParser\Node;
use PhpParser\Node\Expr\StaticCall;
use PhpParser\Node\Name;
use PHPStan\Analyser\NodeScopeResolver;
use PHPStan\Analyser\Scope;
use PHPStan\Analyser\ScopeContext;
use PHPStan\DependencyInjection\Type\DynamicThrowTypeExtensionProvider;
use PHPStan\File\FileHelper;
use PHPStan\Php\PhpVersion;
use PHPStan\PhpDoc\PhpDocInheritanceResolver;
use PHPStan\PhpDoc\StubPhpDocProvider;
use PHPStan\Reflection\InitializerExprTypeResolver;
use PHPStan\Rules\Properties\ReadWritePropertiesExtensionProvider;
use PHPStan\TrinaryLogic;
use PHPStan\Type\ConstantScalarType;
use PHPStan\Type\FileTypeMapper;
use PHPStan\Type\VerbosityLevel;
use function array_map;
use function array_merge;
use function count;
use function in_array;
use function is_string;
use function sprintf;
use function stripos;
use function strtolower;
/** @api */
abstract class TypeInferenceTestCase extends PHPStanTestCase
{
/**
* @param callable(Node , Scope ): void $callback
* @param string[] $dynamicConstantNames
*/
public static function processFile(
string $file,
callable $callback,
array $dynamicConstantNames = [],
): void
{
$reflectionProvider = self::createReflectionProvider();
$typeSpecifier = self::getContainer()->getService('typeSpecifier');
$fileHelper = self::getContainer()->getByType(FileHelper::class);
$resolver = new NodeScopeResolver(
$reflectionProvider,
self::getContainer()->getByType(InitializerExprTypeResolver::class),
self::getReflector(),
self::getClassReflectionExtensionRegistryProvider(),
self::getParser(),
self::getContainer()->getByType(FileTypeMapper::class),
self::getContainer()->getByType(StubPhpDocProvider::class),
self::getContainer()->getByType(PhpVersion::class),
self::getContainer()->getByType(PhpDocInheritanceResolver::class),
self::getContainer()->getByType(FileHelper::class),
$typeSpecifier,
self::getContainer()->getByType(DynamicThrowTypeExtensionProvider::class),
self::getContainer()->getByType(ReadWritePropertiesExtensionProvider::class),
self::createScopeFactory($reflectionProvider, $typeSpecifier),
true,
true,
static::getEarlyTerminatingMethodCalls(),
static::getEarlyTerminatingFunctionCalls(),
true,
self::getContainer()->getParameter('treatPhpDocTypesAsCertain'),
self::getContainer()->getParameter('featureToggles')['detectDeadTypeInMultiCatch'],
);
$resolver->setAnalysedFiles(array_map(static fn (string $file): string => $fileHelper->normalizePath($file), array_merge([$file], static::getAdditionalAnalysedFiles())));
$scopeFactory = self::createScopeFactory($reflectionProvider, $typeSpecifier, $dynamicConstantNames);
$scope = $scopeFactory->create(ScopeContext::create($file));
$resolver->processNodes(
self::getParser()->parseFile($file),
$scope,
$callback,
);
}
/**
* @api
* @param mixed ...$args
*/
public function assertFileAsserts(
string $assertType,
string $file,
...$args,
): void
{
if ($assertType === 'type') {
$expectedType = $args[0];
$this->assertInstanceOf(ConstantScalarType::class, $expectedType);
$expected = $expectedType->getValue();
$actualType = $args[1];
$actual = $actualType->describe(VerbosityLevel::precise());
$this->assertSame(
$expected,
$actual,
sprintf('Expected type %s, got type %s in %s on line %d.', $expected, $actual, $file, $args[2]),
);
} elseif ($assertType === 'variableCertainty') {
$expectedCertainty = $args[0];
$actualCertainty = $args[1];
$variableName = $args[2];
$this->assertTrue(
$expectedCertainty->equals($actualCertainty),
sprintf('Expected %s, actual certainty of variable $%s is %s in %s on line %d.', $expectedCertainty->describe(), $variableName, $actualCertainty->describe(), $file, $args[3]),
);
}
}
/**
* @api
* @return array<string, mixed[]>
*/
public static function gatherAssertTypes(string $file): array
{
$asserts = [];
self::processFile($file, static function (Node $node, Scope $scope) use (&$asserts, $file): void {
if (!$node instanceof Node\Expr\FuncCall) {
return;
}
$nameNode = $node->name;
if (!$nameNode instanceof Name) {
return;
}
$functionName = $nameNode->toString();
if (in_array(strtolower($functionName), ['asserttype', 'assertnativetype', 'assertvariablecertainty'], true)) {
self::fail(sprintf(
'Missing use statement for %s() on line %d.',
$functionName,
$node->getLine(),
));
} elseif ($functionName === 'PHPStan\\Testing\\assertType') {
$expectedType = $scope->getType($node->getArgs()[0]->value);
$actualType = $scope->getType($node->getArgs()[1]->value);
$assert = ['type', $file, $expectedType, $actualType, $node->getLine()];
} elseif ($functionName === 'PHPStan\\Testing\\assertNativeType') {
$expectedType = $scope->getType($node->getArgs()[0]->value);
$actualType = $scope->getNativeType($node->getArgs()[1]->value);
$assert = ['type', $file, $expectedType, $actualType, $node->getLine()];
} elseif ($functionName === 'PHPStan\\Testing\\assertVariableCertainty') {
$certainty = $node->getArgs()[0]->value;
if (!$certainty instanceof StaticCall) {
self::fail(sprintf('First argument of %s() must be TrinaryLogic call', $functionName));
}
if (!$certainty->class instanceof Node\Name) {
self::fail(sprintf('ERROR: Invalid TrinaryLogic call.'));
}
if ($certainty->class->toString() !== 'PHPStan\\TrinaryLogic') {
self::fail(sprintf('ERROR: Invalid TrinaryLogic call.'));
}
if (!$certainty->name instanceof Node\Identifier) {
self::fail(sprintf('ERROR: Invalid TrinaryLogic call.'));
}
// @phpstan-ignore-next-line
$expectedertaintyValue = TrinaryLogic::{$certainty->name->toString()}();
$variable = $node->getArgs()[1]->value;
if (!$variable instanceof Node\Expr\Variable) {
self::fail(sprintf('ERROR: Invalid assertVariableCertainty call.'));
}
if (!is_string($variable->name)) {
self::fail(sprintf('ERROR: Invalid assertVariableCertainty call.'));
}
$actualCertaintyValue = $scope->hasVariableType($variable->name);
$assert = ['variableCertainty', $file, $expectedertaintyValue, $actualCertaintyValue, $variable->name, $node->getLine()];
} else {
$correctFunction = null;
$assertFunctions = [
'assertType' => 'PHPStan\\Testing\\assertType',
'assertNativeType' => 'PHPStan\\Testing\\assertNativeType',
'assertVariableCertainty' => 'PHPStan\\Testing\\assertVariableCertainty',
];
foreach ($assertFunctions as $assertFn => $fqFunctionName) {
if (stripos($functionName, $assertFn) === false) {
continue;
}
$correctFunction = $fqFunctionName;
}
if ($correctFunction === null) {
return;
}
self::fail(sprintf(
'Function %s imported with wrong namespace %s called on line %d.',
$correctFunction,
$functionName,
$node->getLine(),
));
}
if (count($node->getArgs()) !== 2) {
self::fail(sprintf(
'ERROR: Wrong %s() call on line %d.',
$functionName,
$node->getLine(),
));
}
$asserts[$file . ':' . $node->getLine()] = $assert;
});
if (count($asserts) === 0) {
self::fail(sprintf('File %s does not contain any asserts', $file));
}
return $asserts;
}
/** @return string[] */
protected static function getAdditionalAnalysedFiles(): array
{
return [];
}
/** @return string[][] */
protected static function getEarlyTerminatingMethodCalls(): array
{
return [];
}
/** @return string[] */
protected static function getEarlyTerminatingFunctionCalls(): array
{
return [];
}
}