-
Notifications
You must be signed in to change notification settings - Fork 696
Expand file tree
/
Copy pathAttributesAnalyzer.php
More file actions
392 lines (352 loc) · 13.9 KB
/
AttributesAnalyzer.php
File metadata and controls
392 lines (352 loc) · 13.9 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
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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
<?php
declare(strict_types=1);
namespace Psalm\Internal\Analyzer;
use Attribute as GlobalAttribute;
use Generator;
use PhpParser\Node\Arg;
use PhpParser\Node\Attribute;
use PhpParser\Node\AttributeGroup;
use PhpParser\Node\Expr\New_;
use PhpParser\Node\Name\FullyQualified;
use PhpParser\Node\Stmt\Expression;
use Psalm\CodeLocation;
use Psalm\Context;
use Psalm\Internal\Analyzer\StatementsAnalyzer;
use Psalm\Internal\Codebase\ConstantTypeResolver;
use Psalm\Internal\Provider\NodeDataProvider;
use Psalm\Internal\Scanner\UnresolvedConstantComponent;
use Psalm\Issue\InvalidAttribute;
use Psalm\Issue\UndefinedClass;
use Psalm\IssueBuffer;
use Psalm\Storage\ClassLikeStorage;
use Psalm\Storage\HasAttributesInterface;
use Psalm\Type\Atomic\TLiteralString;
use Psalm\Type\Union;
use function array_key_first;
use function array_shift;
use function array_values;
use function assert;
use function count;
use function strtolower;
/**
* @internal
*/
final class AttributesAnalyzer
{
private const TARGET_DESCRIPTIONS = [
1 => 'class',
2 => 'function',
4 => 'method',
8 => 'property',
16 => 'class constant',
32 => 'function/method parameter',
40 => 'promoted property',
];
/**
* @param array<array-key, AttributeGroup> $attribute_groups
* @param key-of<self::TARGET_DESCRIPTIONS> $target
* @param array<array-key, string> $suppressed_issues
*/
public static function analyze(
SourceAnalyzer $source,
Context $context,
HasAttributesInterface $storage,
array $attribute_groups,
int $target,
array $suppressed_issues,
): void {
$codebase = $source->getCodebase();
$appearing_non_repeatable_attributes = [];
foreach (self::iterateAttributeNodes($attribute_groups) as $attribute) {
if ($attribute->name instanceof FullyQualified) {
$fq_attribute_name = (string) $attribute->name;
} else {
$fq_attribute_name = ClassLikeAnalyzer::getFQCLNFromNameObject($attribute->name, $source->getAliases());
}
$attribute_name = (string) $attribute->name;
$attribute_name_location = new CodeLocation($source, $attribute->name);
$attribute_class_storage = $codebase->classlikes->classExists($fq_attribute_name, null, $context)
? $codebase->classlike_storage_provider->get($fq_attribute_name)
: null;
$attribute_class_flags = self::getAttributeClassFlags(
$source,
$attribute_name,
$fq_attribute_name,
$attribute_name_location,
$attribute_class_storage,
$suppressed_issues,
);
self::analyzeAttributeConstruction(
$source,
$context,
$fq_attribute_name,
$attribute,
$suppressed_issues,
$storage instanceof ClassLikeStorage ? $storage : null,
);
if (($attribute_class_flags & GlobalAttribute::IS_REPEATABLE) === 0) {
// Not IS_REPEATABLE
if (isset($appearing_non_repeatable_attributes[$fq_attribute_name])) {
IssueBuffer::maybeAdd(
new InvalidAttribute(
"Attribute {$attribute_name} is not repeatable",
$attribute_name_location,
),
$suppressed_issues,
);
}
$appearing_non_repeatable_attributes[$fq_attribute_name] = true;
}
if (($attribute_class_flags & $target) === 0) {
IssueBuffer::maybeAdd(
new InvalidAttribute(
"Attribute {$attribute_name} cannot be used on a "
. self::TARGET_DESCRIPTIONS[$target],
$attribute_name_location,
),
$suppressed_issues,
);
}
}
}
/**
* @param array<array-key, string> $suppressed_issues
*/
private static function analyzeAttributeConstruction(
SourceAnalyzer $source,
Context $context,
string $fq_attribute_name,
Attribute $attribute,
array $suppressed_issues,
?ClassLikeStorage $classlike_storage = null,
): void {
$attribute_name_location = new CodeLocation($source, $attribute->name);
if (ClassLikeAnalyzer::checkFullyQualifiedClassLikeName(
$source,
$fq_attribute_name,
$attribute_name_location,
$context,
$suppressed_issues,
new ClassLikeNameOptions(
false,
false,
false,
false,
false,
true,
),
) === false) {
return;
}
if (strtolower($fq_attribute_name) === 'attribute' && $classlike_storage) {
if ($classlike_storage->is_trait) {
IssueBuffer::maybeAdd(
new InvalidAttribute(
'Traits cannot act as attribute classes',
$attribute_name_location,
),
$suppressed_issues,
);
} elseif ($classlike_storage->is_interface) {
IssueBuffer::maybeAdd(
new InvalidAttribute(
'Interfaces cannot act as attribute classes',
$attribute_name_location,
),
$suppressed_issues,
);
} elseif ($classlike_storage->abstract) {
IssueBuffer::maybeAdd(
new InvalidAttribute(
'Abstract classes cannot act as attribute classes',
$attribute_name_location,
),
$suppressed_issues,
);
} elseif (isset($classlike_storage->methods['__construct'])
&& $classlike_storage->methods['__construct']->visibility !== ClassLikeAnalyzer::VISIBILITY_PUBLIC
) {
IssueBuffer::maybeAdd(
new InvalidAttribute(
'Classes with protected/private constructors cannot act as attribute classes',
$attribute_name_location,
),
$suppressed_issues,
);
} elseif ($classlike_storage->is_enum) {
IssueBuffer::maybeAdd(
new InvalidAttribute(
'Enums cannot act as attribute classes',
$attribute_name_location,
),
$suppressed_issues,
);
}
}
$statements_analyzer = new StatementsAnalyzer(
$source,
new NodeDataProvider(),
false,
);
$statements_analyzer->addSuppressedIssues(array_values($suppressed_issues));
$had_returned = $context->has_returned;
$context->has_returned = false;
$was_inside_attribute = $context->inside_attribute;
$context->inside_attribute = true;
IssueBuffer::startRecording();
$statements_analyzer->analyze(
[new Expression(new New_($attribute->name, $attribute->args, $attribute->getAttributes()))],
// Use a new Context for the Attribute attribute so that it can't access `self`
strtolower($fq_attribute_name) === "attribute" ? new Context() : $context,
);
$context->has_returned = $had_returned;
$context->inside_attribute = $was_inside_attribute;
$issues = IssueBuffer::clearRecordingLevel();
IssueBuffer::stopRecording();
foreach ($issues as $issue) {
if ($issue instanceof UndefinedClass && $issue->fq_classlike_name === $fq_attribute_name) {
// Remove UndefinedClass for the attribute, since we already added UndefinedAttribute
continue;
}
IssueBuffer::bubbleUp($issue);
}
}
/**
* @param array<array-key, string> $suppressed_issues
*/
private static function getAttributeClassFlags(
SourceAnalyzer $source,
string $attribute_name,
string $fq_attribute_name,
CodeLocation $attribute_name_location,
?ClassLikeStorage $attribute_class_storage,
array $suppressed_issues,
): int {
if (strtolower($fq_attribute_name) === "attribute") {
// We override this here because we still want to analyze attributes
// for PHP 7.4 when the Attribute class doesn't yet exist.
return GlobalAttribute::TARGET_CLASS;
}
if ($attribute_class_storage === null) {
return GlobalAttribute::TARGET_ALL; // Defaults to TARGET_ALL
}
foreach ($attribute_class_storage->attributes as $attribute_attribute) {
if ($attribute_attribute->fq_class_name === 'Attribute') {
if (!$attribute_attribute->args) {
return GlobalAttribute::TARGET_ALL; // Defaults to TARGET_ALL
}
$first_arg = $attribute_attribute->args[array_key_first($attribute_attribute->args)];
$first_arg_type = $first_arg->type;
if ($first_arg_type instanceof UnresolvedConstantComponent) {
$first_arg_type = new Union([
ConstantTypeResolver::resolve(
$source->getCodebase()->classlikes,
$first_arg_type,
$source instanceof StatementsAnalyzer ? $source : null,
),
]);
}
if (!$first_arg_type->isSingleIntLiteral()) {
return GlobalAttribute::TARGET_ALL; // Fall back to default if it's invalid
}
return $first_arg_type->getSingleIntLiteral()->value;
}
}
IssueBuffer::maybeAdd(
new InvalidAttribute(
"The class {$attribute_name} doesn't have the Attribute attribute",
$attribute_name_location,
),
$suppressed_issues,
);
return GlobalAttribute::TARGET_ALL; // Fall back to default if it's invalid
}
/**
* @param iterable<AttributeGroup> $attribute_groups
* @return Generator<int, Attribute>
*/
private static function iterateAttributeNodes(iterable $attribute_groups): Generator
{
foreach ($attribute_groups as $attribute_group) {
foreach ($attribute_group->attrs as $attribute) {
yield $attribute;
}
}
}
/**
* Analyze Reflection getAttributes method calls.
* @param list<Arg> $args
*/
public static function analyzeGetAttributes(
StatementsAnalyzer $statements_analyzer,
string $method_id,
array $args,
): void {
if (count($args) !== 1) {
// We skip this analysis if $flags is specified on getAttributes, since the only option
// is ReflectionAttribute::IS_INSTANCEOF, which causes getAttributes to return children.
// When returning children we don't want to limit this since a child could add a target.
return;
}
switch ($method_id) {
case "ReflectionClass::getattributes":
$target = GlobalAttribute::TARGET_CLASS;
break;
case "ReflectionFunction::getattributes":
$target = GlobalAttribute::TARGET_FUNCTION;
break;
case "ReflectionMethod::getattributes":
$target = GlobalAttribute::TARGET_METHOD;
break;
case "ReflectionProperty::getattributes":
$target = GlobalAttribute::TARGET_PROPERTY;
break;
case "ReflectionClassConstant::getattributes":
$target = GlobalAttribute::TARGET_CLASS_CONSTANT;
break;
case "ReflectionParameter::getattributes":
$target = GlobalAttribute::TARGET_PARAMETER;
break;
default:
return;
}
$arg = $args[0];
if ($arg->name !== null) {
for (; !empty($args) && ($arg->name->name ?? null) !== "name"; $arg = array_shift($args));
if ($arg->name->name ?? null !== "name") {
// No named argument for "name" parameter
return;
}
}
$arg_type = $statements_analyzer->getNodeTypeProvider()->getType($arg->value);
if ($arg_type === null || !$arg_type->isSingle() || !$arg_type->hasLiteralString()) {
return;
}
$class_string = $arg_type->getSingleAtomic();
assert($class_string instanceof TLiteralString);
$codebase = $statements_analyzer->getCodebase();
if (!$codebase->classExists($class_string->value)) {
return;
}
$class_storage = $codebase->classlike_storage_provider->get($class_string->value);
$arg_location = new CodeLocation($statements_analyzer, $arg);
$class_attribute_target = self::getAttributeClassFlags(
$statements_analyzer,
$class_string->value,
$class_string->value,
$arg_location,
$class_storage,
$statements_analyzer->getSuppressedIssues(),
);
if (($class_attribute_target & $target) === 0) {
IssueBuffer::maybeAdd(
new InvalidAttribute(
"Attribute {$class_string->value} cannot be used on a "
. self::TARGET_DESCRIPTIONS[$target],
$arg_location,
),
$statements_analyzer->getSuppressedIssues(),
);
}
}
}