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
use std::ops::ControlFlow;
use std::sync::Arc;
use mir_codebase::definitions::{ConstantDef, EnumCaseDef};
use mir_issues::{Issue, IssueKind};
use mir_types::Type;
use php_ast::owned::EnumMemberKind;
use super::DefinitionCollector;
use crate::parser::{name_to_string_owned, type_from_hint_owned};
impl DefinitionCollector<'_> {
pub(super) fn collect_enum(
&mut self,
decl: &php_ast::owned::EnumDecl,
stmt_span: php_ast::Span,
) -> ControlFlow<()> {
let enum_name = decl.name.as_deref().unwrap_or_default().to_string();
let fqcn = self.declared_fqn(&enum_name);
let enum_doc = decl
.doc_comment
.as_ref()
.map(|c| crate::parser::DocblockParser::parse(&c.text))
.unwrap_or_default();
let enum_doc_span = decl
.doc_comment
.as_ref()
.map(|c| c.span.start)
.unwrap_or(stmt_span.start);
self.emit_docblock_issues(&enum_doc, enum_doc_span);
if !self.version_allows(&enum_doc) {
return ControlFlow::Continue(());
}
let scalar_type = decl
.scalar_type
.as_ref()
.map(|n| crate::parser::docblock::parse_type_string(&name_to_string_owned(n)));
let mut interfaces: Vec<Arc<str>> = decl
.implements
.iter()
.map(|n| self.resolve_name(&name_to_string_owned(n)).into())
.collect();
// PHP automatically makes every enum implement UnitEnum (and backed enums
// implement IntBackedEnum / StringBackedEnum, which extend BackedEnum → UnitEnum).
// Inject the appropriate interface so method resolution finds cases() / from() /
// tryFrom() in the stubs without the user having to write `implements BackedEnum`.
let implicit_iface: Arc<str> = match decl.scalar_type.as_ref() {
None => Arc::from("UnitEnum"),
Some(n) if name_to_string_owned(n).eq_ignore_ascii_case("string") => {
Arc::from("StringBackedEnum")
}
_ => Arc::from("IntBackedEnum"),
};
if !interfaces.contains(&implicit_iface) {
interfaces.push(implicit_iface);
}
let mut cases = mir_codebase::definitions::MemberMap::default();
let mut own_methods = mir_codebase::definitions::MemberMap::default();
let mut own_constants = mir_codebase::definitions::MemberMap::default();
let mut traits: Vec<Arc<str>> = Vec::new();
let mut trait_use_locations: Vec<(Arc<str>, mir_types::Location)> = Vec::new();
// See `class.rs` for why this runs before the loop: it lets
// `int-mask-of<self::*>` in a method docblock below resolve against
// the enum's own literal-int `const` declarations (not its cases —
// those aren't class constants).
let self_int_constants: Arc<rustc_hash::FxHashMap<Arc<str>, i64>> = Arc::new(
decl.body
.members
.iter()
.filter_map(|m| match &m.kind {
EnumMemberKind::ClassConst(c) => {
let name = c.name.as_deref()?;
match super::infer_const_value(self, &c.value.kind) {
Some(t) if t.types.len() == 1 => match &t.types[0] {
mir_types::Atomic::TLiteralInt(n) => Some((Arc::from(name), *n)),
_ => None,
},
_ => None,
}
}
_ => None,
})
.collect(),
);
let _int_mask_guard =
crate::parser::docblock::SelfIntConstantsGuard::activate(&fqcn, &self_int_constants);
// Hoisted above the member loop (mirroring class.rs) so an enum
// method's own `@param`/`@return`/assertion tags can resolve a
// same-file `@psalm-type` alias declared on the enum itself — a
// method body is otherwise processed with `aliases: None` below,
// silently leaving any alias reference in its docblock unexpanded.
let type_aliases = self.build_type_aliases(&enum_doc);
for member in decl.body.members.iter() {
match &member.kind {
EnumMemberKind::Case(c) => {
let case_name = c.name.as_deref().unwrap_or_default();
let case_doc = c
.doc_comment
.as_ref()
.map(|d| crate::parser::DocblockParser::parse(&d.text))
.unwrap_or_default();
let case_doc_span = c
.doc_comment
.as_ref()
.map(|d| d.span.start)
.unwrap_or(member.span.start);
self.emit_docblock_issues(&case_doc, case_doc_span);
if !self.version_allows(&case_doc) {
continue;
}
let case_deprecated =
case_doc.deprecated.as_deref().map(Arc::from).or_else(|| {
if c.attributes.iter().any(|a| {
a.name
.parts
.last()
.map(|p| p.as_ref().eq_ignore_ascii_case("Deprecated"))
.unwrap_or(false)
}) {
Some(Arc::from(""))
} else {
None
}
});
// Extract the literal type from the case value expression (e.g. `= 'foo'`, `= 42`).
// Falls back to mixed when the expression is not a simple literal (class constant,
// const expression) — those can't be statically checked at collection time.
let value_ty = c
.value
.as_ref()
.and_then(|expr| super::infer_const_value(self, &expr.kind));
// Validate the case value's type against the backing scalar type.
if let (Some(backing), Some(case_val_ty)) = (&scalar_type, &value_ty) {
if !case_val_ty.is_subtype_structural(backing) {
let lc = self.source_map.offset_to_line_col(member.span.start);
let line = lc.line + 1;
self.issues.add(Issue::new(
IssueKind::BackedEnumCaseTypeMismatch {
enum_name: fqcn.clone(),
case_name: case_name.to_string(),
expected: backing.to_string(),
actual: case_val_ty.to_string(),
},
mir_issues::Location {
file: self.file.clone(),
line,
line_end: line,
col_start: 0,
col_end: 0,
},
));
}
}
cases.insert(
Arc::from(case_name),
EnumCaseDef {
name: Arc::from(case_name),
// Store the inferred literal type; fall back to mixed for non-literal values.
value: Some(value_ty.unwrap_or_else(Type::mixed)),
location: Some(self.location(member.span.start, member.span.end)),
deprecated: case_deprecated,
},
);
}
EnumMemberKind::Method(m) => {
if let Some(method) = self.build_method_storage(
m,
&fqcn,
Some(&member.span),
Some(&type_aliases),
&[],
) {
own_methods.insert(
Arc::from(crate::util::php_ident_lowercase(&method.name).as_str()),
Arc::new(method),
);
}
if let Some(body) = &m.body {
self.scan_stmts_for_defines(&body.stmts);
}
}
EnumMemberKind::ClassConst(c) => {
let const_name = c.name.as_deref().unwrap_or_default();
let const_doc = self.parse_docblock_from_node(c.doc_comment.as_ref());
let const_doc_span = c
.doc_comment
.as_ref()
.map(|d| d.span.start)
.unwrap_or(member.span.start);
self.emit_docblock_issues(&const_doc, const_doc_span);
if !self.version_allows(&const_doc) {
continue;
}
// PHP 8.3: typed enum constants (`const int FOO = 1;`).
// Prefer @var docblock, then a same-kind literal narrowing
// of the native hint, then the bare hint, then mixed —
// same precedence as class.rs.
let hint_ty = self.resolve_union_opt(
c.type_hint
.as_ref()
.map(|h| type_from_hint_owned(h, Some(&fqcn))),
);
let const_ty = const_doc
.var_type
.map(|t| self.resolve_union_doc_with_aliases(t, &type_aliases))
.or_else(|| {
super::const_type_with_literal_narrowing(
hint_ty,
super::infer_const_value(self, &c.value.kind),
)
})
.unwrap_or_else(Type::mixed);
own_constants.insert(
Arc::from(const_name),
ConstantDef {
name: Arc::from(const_name),
ty: const_ty,
visibility: c.visibility.map(|v| Self::convert_visibility(Some(v))),
is_final: c.is_final,
location: Some(self.location(member.span.start, member.span.end)),
deprecated: const_doc.deprecated.as_deref().map(Arc::from).or_else(
|| {
if c.attributes.iter().any(|a| {
a.name
.parts
.last()
.map(|p| p.as_ref().eq_ignore_ascii_case("Deprecated"))
.unwrap_or(false)
}) {
Some(Arc::from(""))
} else {
None
}
},
),
},
);
}
EnumMemberKind::TraitUse(tu) => {
for t in tu.traits.iter() {
let trait_fqcn: Arc<str> =
self.resolve_name(&name_to_string_owned(t)).into();
trait_use_locations
.push((trait_fqcn.clone(), self.location(t.span.start, t.span.end)));
traits.push(trait_fqcn);
}
}
}
}
// `@implements Interface<T1, T2>` — enums have no `@template` of their
// own, so there's nothing to substitute into the type args (unlike
// class.rs's `implements_type_args`, which resolves them against the
// class's own template params); just FQN-qualify the names.
let implements_type_args: Vec<(Arc<str>, Vec<Type>)> = enum_doc
.implements
.iter()
.filter_map(|ty| {
if let Some(mir_types::Atomic::TNamedObject {
fqcn: iface,
type_params,
}) = ty.types.first()
{
Some((
self.resolve_type_name(iface.as_str(), true).into(),
type_params
.iter()
.map(|tp| {
self.resolve_union_doc_with_templates(
super::expand_aliases_only(tp.clone(), &type_aliases),
&rustc_hash::FxHashSet::default(),
&fqcn,
&[],
)
})
.collect(),
))
} else {
None
}
})
.collect();
let trait_use_type_args: Vec<(Arc<str>, Vec<mir_types::Type>)> = enum_doc
.uses
.iter()
.filter_map(|ty| {
if let Some(mir_types::Atomic::TNamedObject {
fqcn: used_trait,
type_params,
}) = ty.types.first()
{
Some((
self.resolve_type_name(used_trait.as_str(), true).into(),
type_params
.iter()
.map(|tp| {
self.resolve_union_doc_with_templates(
super::expand_aliases_only(tp.clone(), &type_aliases),
&rustc_hash::FxHashSet::default(),
&fqcn,
&[],
)
})
.collect(),
))
} else {
None
}
})
.collect();
let mut own_properties = mir_codebase::definitions::MemberMap::default();
self.add_docblock_members(
&enum_doc,
&type_aliases,
&fqcn,
&mut own_methods,
&mut own_properties,
Some(self.location(stmt_span.start, stmt_span.end)),
&rustc_hash::FxHashSet::default(),
&[],
);
self.slice
.enums
.push(std::sync::Arc::new(mir_codebase::EnumDef {
fqcn: fqcn.into(),
short_name: Arc::from(enum_name.as_str()),
scalar_type,
interfaces,
implements_type_args,
cases,
own_methods,
own_constants,
traits,
trait_use_locations,
trait_use_type_args,
location: Some(self.location(stmt_span.start, stmt_span.end)),
deprecated: Self::deprecated_from_doc_or_attrs(
enum_doc.deprecated.as_deref(),
&decl.attributes,
),
type_aliases: type_aliases
.iter()
.map(|(k, v)| (Arc::from(k.as_str()), v.clone()))
.collect(),
own_properties,
}));
ControlFlow::Continue(())
}
}