mir_codebase/definitions.rs
1use std::sync::Arc;
2
3/// Insertion-ordered member map keyed by lowercased member name.
4/// FxHash instead of SipHash: member lookup is one of the hottest analyzer
5/// operations and the keys are short trusted identifiers.
6pub type MemberMap<V> = indexmap::IndexMap<std::sync::Arc<str>, V, rustc_hash::FxBuildHasher>;
7use mir_types::{Location, Name, Type};
8use rustc_hash::FxHashMap;
9use serde::{Deserialize, Serialize};
10
11// ---------------------------------------------------------------------------
12// Interned common types for deduplication
13// ---------------------------------------------------------------------------
14
15/// Interned Type types for common parameter/property types.
16/// Deduplicates allocations when thousands of parameters share types like `string`, `int`, etc.
17mod interned_types {
18 use super::*;
19 use std::sync::OnceLock;
20
21 fn intern_string() -> Arc<Type> {
22 Arc::new(Type::string())
23 }
24
25 fn intern_int() -> Arc<Type> {
26 Arc::new(Type::int())
27 }
28
29 fn intern_float() -> Arc<Type> {
30 Arc::new(Type::float())
31 }
32
33 fn intern_bool() -> Arc<Type> {
34 Arc::new(Type::bool())
35 }
36
37 fn intern_mixed() -> Arc<Type> {
38 Arc::new(Type::mixed())
39 }
40
41 fn intern_null() -> Arc<Type> {
42 Arc::new(Type::null())
43 }
44
45 fn intern_void() -> Arc<Type> {
46 Arc::new(Type::void())
47 }
48
49 static STRING: OnceLock<Arc<Type>> = OnceLock::new();
50 static INT: OnceLock<Arc<Type>> = OnceLock::new();
51 static FLOAT: OnceLock<Arc<Type>> = OnceLock::new();
52 static BOOL: OnceLock<Arc<Type>> = OnceLock::new();
53 static MIXED: OnceLock<Arc<Type>> = OnceLock::new();
54 static NULL: OnceLock<Arc<Type>> = OnceLock::new();
55 static VOID: OnceLock<Arc<Type>> = OnceLock::new();
56
57 pub fn string() -> Arc<Type> {
58 STRING.get_or_init(intern_string).clone()
59 }
60
61 pub fn int() -> Arc<Type> {
62 INT.get_or_init(intern_int).clone()
63 }
64
65 pub fn float() -> Arc<Type> {
66 FLOAT.get_or_init(intern_float).clone()
67 }
68
69 pub fn bool() -> Arc<Type> {
70 BOOL.get_or_init(intern_bool).clone()
71 }
72
73 pub fn mixed() -> Arc<Type> {
74 MIXED.get_or_init(intern_mixed).clone()
75 }
76
77 pub fn null() -> Arc<Type> {
78 NULL.get_or_init(intern_null).clone()
79 }
80
81 pub fn void() -> Arc<Type> {
82 VOID.get_or_init(intern_void).clone()
83 }
84
85 /// Global content-keyed `Arc<Type>` interner. Any structurally-identical
86 /// Type is shared as a single Arc across the session.
87 ///
88 /// Why: PHP codebases re-declare a small set of type shapes thousands of
89 /// times — `string|null` return types, `int` params, `array<string, mixed>`
90 /// property types. Without interning, each declaration allocates its own
91 /// `Arc<Type>` plus the inline `SmallVec<[Atomic; 2]>` and any boxed
92 /// `Atomic` payloads. With interning, only the first occurrence allocates.
93 ///
94 /// Trade-off: every `intern_or_wrap` call hashes + does one DashMap lookup.
95 /// Hashing a `Type` is cheap (SmallVec, small atomics) — measured cost is
96 /// well below the alloc-savings benefit on real workloads.
97 type InternTable = dashmap::DashMap<Type, Arc<Type>, rustc_hash::FxBuildHasher>;
98
99 static GLOBAL_UNION_INTERN: std::sync::OnceLock<InternTable> = std::sync::OnceLock::new();
100
101 fn global_intern_table() -> &'static InternTable {
102 GLOBAL_UNION_INTERN.get_or_init(|| dashmap::DashMap::with_hasher(Default::default()))
103 }
104
105 /// Try to intern a Type if it matches a common type, otherwise wrap in Arc.
106 pub fn intern_or_wrap(union: Type) -> Arc<Type> {
107 // Fast path 1: single-atomic scalar — covered by `OnceLock` constants.
108 // Avoids any DashMap traffic for the most common case.
109 if union.types.len() == 1 && !union.possibly_undefined && !union.from_docblock {
110 match &union.types[0] {
111 mir_types::Atomic::TString => return string(),
112 mir_types::Atomic::TInt => return int(),
113 mir_types::Atomic::TFloat => return float(),
114 mir_types::Atomic::TBool => return bool(),
115 mir_types::Atomic::TMixed => return mixed(),
116 mir_types::Atomic::TNull => return null(),
117 mir_types::Atomic::TVoid => return void(),
118 _ => {}
119 }
120 }
121 // Fast path 2: empty Type — also a common case (e.g. unresolved
122 // return type). Don't pollute the intern table with these.
123 if union.types.is_empty() {
124 return Arc::new(union);
125 }
126 // Global path: dedup against any previously-seen identical Type.
127 let table = global_intern_table();
128 if let Some(existing) = table.get(&union) {
129 return Arc::clone(existing.value());
130 }
131 let arc = Arc::new(union.clone());
132 // `insert` semantics: if a parallel thread beat us, its Arc wins.
133 // The lookup-before-insert race is benign — both Arcs are content-
134 // equal — but we still want to share the canonical one going forward.
135 match table.entry(union) {
136 dashmap::mapref::entry::Entry::Occupied(o) => Arc::clone(o.get()),
137 dashmap::mapref::entry::Entry::Vacant(v) => {
138 v.insert(Arc::clone(&arc));
139 arc
140 }
141 }
142 }
143}
144
145// ---------------------------------------------------------------------------
146// Shared primitives
147// ---------------------------------------------------------------------------
148
149#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
150pub enum Visibility {
151 Public,
152 Protected,
153 Private,
154}
155
156impl Visibility {
157 pub fn is_at_least(&self, required: Visibility) -> bool {
158 *self <= required
159 }
160}
161
162impl std::fmt::Display for Visibility {
163 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
164 match self {
165 Visibility::Public => write!(f, "public"),
166 Visibility::Protected => write!(f, "protected"),
167 Visibility::Private => write!(f, "private"),
168 }
169 }
170}
171
172fn serialize_template_bound<S>(value: &Option<Arc<Type>>, serializer: S) -> Result<S::Ok, S::Error>
173where
174 S: serde::Serializer,
175{
176 value.as_deref().serialize(serializer)
177}
178
179fn deserialize_template_bound<'de, D>(deserializer: D) -> Result<Option<Arc<Type>>, D::Error>
180where
181 D: serde::Deserializer<'de>,
182{
183 Option::<Type>::deserialize(deserializer).map(|opt| opt.map(interned_types::intern_or_wrap))
184}
185
186#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
187pub struct TemplateParam {
188 pub name: Name,
189 /// Declared upper bound, e.g. `@template T of Traversable`.
190 /// Stored as `Option<Arc<Type>>` so common bounds (e.g. `object`, `mixed`)
191 /// are deduplicated across all template params via the global intern table.
192 #[serde(
193 serialize_with = "serialize_template_bound",
194 deserialize_with = "deserialize_template_bound"
195 )]
196 pub bound: Option<Arc<Type>>,
197 /// Default type used when nothing binds this template param, e.g.
198 /// `@template T = string`. Falls back to `mixed` when absent, same as
199 /// before this field existed.
200 #[serde(
201 default,
202 serialize_with = "serialize_template_bound",
203 deserialize_with = "deserialize_template_bound"
204 )]
205 pub default: Option<Arc<Type>>,
206 /// The entity (class or function FQN) that declared this template param.
207 pub defining_entity: Name,
208 pub variance: mir_types::Variance,
209}
210
211#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
212pub struct DeclaredParam {
213 pub name: Name,
214 /// Parameter type. Stored as `Option<Arc<Type>>` to enable deduplication of
215 /// common types across parameters. Many parameters share types like `string`,
216 /// `int`, `bool`, etc., so interning via Arc saves allocations.
217 #[serde(
218 deserialize_with = "deserialize_param_type",
219 serialize_with = "serialize_param_type"
220 )]
221 pub ty: Option<Arc<Type>>,
222 /// Out-type declared via `@param-out` / `@psalm-param-out`. When set, this
223 /// type is written back to the caller's argument variable after the call
224 /// instead of (or in addition to) the declared in-type.
225 #[serde(
226 default,
227 deserialize_with = "deserialize_param_type",
228 serialize_with = "serialize_param_type"
229 )]
230 pub out_ty: Option<Arc<Type>>,
231 /// Whether this parameter has a default value. During analysis, defaults are
232 /// never used for their value — only for marking parameters as optional.
233 pub has_default: bool,
234 pub is_variadic: bool,
235 pub is_byref: bool,
236 pub is_optional: bool,
237}
238
239impl std::hash::Hash for DeclaredParam {
240 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
241 self.name.hash(state);
242 self.has_default.hash(state);
243 self.is_variadic.hash(state);
244 self.is_byref.hash(state);
245 self.is_optional.hash(state);
246 // Hash the type value (not the Arc pointer) so that two FnParams with
247 // equal types (PartialEq) always produce the same hash, even when they
248 // are backed by different Arc allocations.
249 self.ty.as_deref().hash(state);
250 self.out_ty.as_deref().hash(state);
251 }
252}
253
254// Serde helpers to transparently convert between Option<Type> and Option<Arc<Type>>
255fn deserialize_param_type<'de, D>(deserializer: D) -> Result<Option<Arc<Type>>, D::Error>
256where
257 D: serde::Deserializer<'de>,
258{
259 Option::<Type>::deserialize(deserializer).map(|opt| opt.map(interned_types::intern_or_wrap))
260}
261
262fn serialize_param_type<S>(value: &Option<Arc<Type>>, serializer: S) -> Result<S::Ok, S::Error>
263where
264 S: serde::Serializer,
265{
266 let opt = value.as_ref().map(|arc| (**arc).clone());
267 opt.serialize(serializer)
268}
269
270fn deserialize_return_type<'de, D>(deserializer: D) -> Result<Option<Arc<Type>>, D::Error>
271where
272 D: serde::Deserializer<'de>,
273{
274 Option::<Type>::deserialize(deserializer).map(|opt| opt.map(interned_types::intern_or_wrap))
275}
276
277fn serialize_return_type<S>(value: &Option<Arc<Type>>, serializer: S) -> Result<S::Ok, S::Error>
278where
279 S: serde::Serializer,
280{
281 let opt = value.as_ref().map(|arc| (**arc).clone());
282 opt.serialize(serializer)
283}
284
285fn deserialize_params<'de, D>(deserializer: D) -> Result<Arc<[DeclaredParam]>, D::Error>
286where
287 D: serde::Deserializer<'de>,
288{
289 Vec::<DeclaredParam>::deserialize(deserializer).map(|v| Arc::from(v.into_boxed_slice()))
290}
291
292fn default_imports() -> Arc<FxHashMap<Name, Name>> {
293 Arc::new(FxHashMap::default())
294}
295
296/// Deserialize imports map. Supports both new (Name-keyed) and legacy
297/// (String-keyed) on-disk formats — older `cache.bin` files have plain
298/// `HashMap<String, String>`. Either way, we intern at load time so the
299/// in-memory representation is always `Arc<FxHashMap<Name, Name>>`.
300fn deserialize_imports<'de, D>(deserializer: D) -> Result<Arc<FxHashMap<Name, Name>>, D::Error>
301where
302 D: serde::Deserializer<'de>,
303{
304 let raw = FxHashMap::<String, String>::deserialize(deserializer)?;
305 let mut out: FxHashMap<Name, Name> =
306 FxHashMap::with_capacity_and_hasher(raw.len(), Default::default());
307 for (k, v) in raw {
308 out.insert(Name::new(&k), Name::new(&v));
309 }
310 Ok(Arc::new(out))
311}
312
313/// Serialize imports as the legacy `HashMap<String, String>` shape so disk
314/// caches written by this version remain compatible with readers that haven't
315/// been recompiled yet (and vice-versa).
316fn serialize_imports<S>(
317 value: &Arc<FxHashMap<Name, Name>>,
318 serializer: S,
319) -> Result<S::Ok, S::Error>
320where
321 S: serde::Serializer,
322{
323 use serde::ser::SerializeMap;
324 let mut map = serializer.serialize_map(Some(value.len()))?;
325 for (k, v) in value.iter() {
326 map.serialize_entry(k.as_str(), v.as_str())?;
327 }
328 map.end()
329}
330
331fn serialize_params<S>(value: &Arc<[DeclaredParam]>, serializer: S) -> Result<S::Ok, S::Error>
332where
333 S: serde::Serializer,
334{
335 value.as_ref().serialize(serializer)
336}
337
338/// Helper to wrap Option<Type> in interned Arc<Type>.
339pub fn wrap_param_type(ty: Option<Type>) -> Option<Arc<Type>> {
340 ty.map(interned_types::intern_or_wrap)
341}
342
343/// Helper to wrap return type Option<Type> in interned Arc<Type>.
344pub fn wrap_return_type(ty: Option<Type>) -> Option<Arc<Type>> {
345 ty.map(interned_types::intern_or_wrap)
346}
347
348/// Helper to wrap a `PropertyDef` type field (`ty`/`inferred_ty`/`default`) in
349/// an interned `Arc<Type>`, deduplicating common property types via the global
350/// pool. See [`PropertyDef`].
351pub fn wrap_property_type(ty: Option<Type>) -> Option<Arc<Type>> {
352 ty.map(interned_types::intern_or_wrap)
353}
354
355/// Helper to wrap a `TemplateParam.bound` in an interned `Arc<Type>`.
356pub fn wrap_template_bound(ty: Option<Type>) -> Option<Arc<Type>> {
357 ty.map(interned_types::intern_or_wrap)
358}
359
360/// Wrap a variable type in an interned `Arc<Type>`. Use instead of
361/// `Arc::new(ty)` at `FlowState::set_var` and parameter-init sites so that
362/// common scalars (string, int, bool, null, mixed) share a static Arc rather
363/// than allocating a fresh one per assignment.
364pub fn wrap_var_type(ty: Type) -> Arc<Type> {
365 interned_types::intern_or_wrap(ty)
366}
367
368// ---------------------------------------------------------------------------
369// Assertion — `@psalm-assert`, `@psalm-assert-if-true`, etc.
370// ---------------------------------------------------------------------------
371
372#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
373pub enum AssertionKind {
374 Assert,
375 AssertIfTrue,
376 AssertIfFalse,
377}
378
379#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
380pub struct Assertion {
381 pub kind: AssertionKind,
382 pub param: Arc<str>,
383 pub ty: Type,
384 /// True for the `!Type` negated form (`@psalm-assert !null $x`): the
385 /// parameter is asserted to NOT be `ty`, rather than to BE it.
386 #[serde(default)]
387 pub negated: bool,
388 /// Set for an assertion targeting a specific (possibly nested) array key
389 /// path of `param` rather than the whole parameter (`@psalm-assert-if-true
390 /// string $arr['a']['b']` — `param` is `"arr"`, `param_key` is
391 /// `[String("a"), String("b")]`). Empty means "targets the whole parameter".
392 #[serde(default)]
393 pub param_key: Vec<mir_types::atomic::ArrayKey>,
394}
395
396// ---------------------------------------------------------------------------
397// MethodDef
398// ---------------------------------------------------------------------------
399
400#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
401pub struct MethodDef {
402 pub name: Arc<str>,
403 pub fqcn: Arc<str>,
404 #[serde(
405 deserialize_with = "deserialize_params",
406 serialize_with = "serialize_params"
407 )]
408 pub params: Arc<[DeclaredParam]>,
409 /// Type from annotation (`@return` / native type hint). `None` means unannotated.
410 /// Stored as `Option<Arc<Type>>` to enable deduplication of common return types
411 /// (e.g., `void`, `string`, `mixed`, `bool`) across thousands of methods.
412 #[serde(
413 deserialize_with = "deserialize_return_type",
414 serialize_with = "serialize_return_type"
415 )]
416 pub return_type: Option<Arc<Type>>,
417 /// Type inferred from body analysis. Stored as `Option<Arc<Type>>` (8 B) rather
418 /// than inline `Option<Type>` (176 B, no niche) — inference is now demand-driven
419 /// via salsa (`inferred_*_return_type_demand`), so this field is a rarely/never
420 /// populated fallback; shrinking it saves ~168 B on every MethodDef.
421 #[serde(
422 deserialize_with = "deserialize_return_type",
423 serialize_with = "serialize_return_type"
424 )]
425 pub inferred_return_type: Option<Arc<Type>>,
426 pub visibility: Visibility,
427 pub is_static: bool,
428 pub is_abstract: bool,
429 pub is_final: bool,
430 pub is_constructor: bool,
431 pub template_params: Vec<TemplateParam>,
432 pub assertions: Vec<Assertion>,
433 pub throws: Vec<Arc<str>>,
434 pub deprecated: Option<Arc<str>>,
435 pub is_internal: bool,
436 pub is_pure: bool,
437 /// `@no-named-arguments` — callers must not use named argument syntax.
438 #[serde(default)]
439 pub no_named_arguments: bool,
440 /// True when the method has the `#[Override]` PHP attribute.
441 #[serde(default)]
442 pub is_override: bool,
443 pub location: Option<Location>,
444 /// Plain-text description from the docblock (text before `@tag` lines).
445 /// Used for hover info.
446 #[serde(default)]
447 pub docstring: Option<Arc<str>>,
448 /// True for methods added via `@method` docblock annotations. Virtual
449 /// methods must not be required as concrete interface implementations.
450 #[serde(default)]
451 pub is_virtual: bool,
452 /// Parameters declared as taint sinks via `@taint-sink <kind> $param`.
453 /// Each entry is `(param_name_without_dollar, sink_kind_string)`.
454 #[serde(default)]
455 pub taint_sink_params: Vec<(Arc<str>, Arc<str>)>,
456 /// `@taint-source` — this method's return value is treated as tainted
457 /// (attacker-controlled) at every call site, mirroring `@taint-sink`'s
458 /// mechanism but marking the source side instead.
459 #[serde(default)]
460 pub is_taint_source: bool,
461 /// `@if-this-is Type` — the resolved constraint a receiver's type must
462 /// satisfy for this method to be callable. `None` when absent.
463 #[serde(default)]
464 pub if_this_is: Option<Arc<Type>>,
465 /// `@psalm-self-out Type` / `@phpstan-self-out Type` — the receiver's type
466 /// after this call returns (e.g. a fluent builder that narrows `$this` as
467 /// it's configured). `None` when absent.
468 #[serde(default)]
469 pub self_out: Option<Arc<Type>>,
470 /// True when the method has `@inheritDoc` / `{@inheritDoc}` in its docblock.
471 /// The analyzer inherits the parent's return type, param types, throws, and
472 /// template params when this method has none of its own.
473 #[serde(default)]
474 pub is_inherit_doc: bool,
475 /// `@psalm-mutation-free` / `@phpstan-mutation-free` — this method must not
476 /// assign to `$this` properties (same constraint as `@psalm-immutable` on the
477 /// class, but scoped to this single method).
478 #[serde(default)]
479 pub is_mutation_free: bool,
480 /// `@psalm-external-mutation-free` — this method must not mutate any objects
481 /// passed as arguments, but is allowed to modify `$this`.
482 #[serde(default)]
483 pub is_external_mutation_free: bool,
484 /// Method names referenced via `@dataProvider name` / `#[DataProvider('name')]`
485 /// (PHPUnit) — treated as used by dead-code analysis, since PHPUnit invokes
486 /// them by name through reflection rather than a direct call site.
487 #[serde(default)]
488 pub data_provider_targets: Vec<Arc<str>>,
489}
490
491impl MethodDef {
492 pub fn effective_return_type(&self) -> Option<&Type> {
493 self.return_type
494 .as_deref()
495 .or(self.inferred_return_type.as_deref())
496 }
497}
498
499// ---------------------------------------------------------------------------
500// PropertyDef
501// ---------------------------------------------------------------------------
502
503#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
504pub struct PropertyDef {
505 pub name: Arc<str>,
506 /// Declared/inferred/default types. Stored as `Option<Arc<Type>>` (8 B)
507 /// rather than inline `Option<Type>` (176 B, no niche) and interned via the
508 /// global pool on construction/deserialization — common property types
509 /// (`string`, `int`, a shared class type) dedup to one allocation. Mirrors
510 /// `DeclaredParam::ty`. On-disk format is unchanged (the serde helpers (de)serialize
511 /// the inner `Type` transparently).
512 #[serde(
513 deserialize_with = "deserialize_param_type",
514 serialize_with = "serialize_param_type"
515 )]
516 pub ty: Option<Arc<Type>>,
517 #[serde(
518 deserialize_with = "deserialize_param_type",
519 serialize_with = "serialize_param_type"
520 )]
521 pub inferred_ty: Option<Arc<Type>>,
522 pub visibility: Visibility,
523 pub is_static: bool,
524 pub is_readonly: bool,
525 #[serde(
526 deserialize_with = "deserialize_param_type",
527 serialize_with = "serialize_param_type"
528 )]
529 pub default: Option<Arc<Type>>,
530 pub location: Option<Location>,
531 /// `@deprecated` docblock annotation, if present.
532 #[serde(default)]
533 pub deprecated: Option<Arc<str>>,
534 /// True when the property declares a PHP native type hint (`public int $x`).
535 /// A property typed only via a `@var` docblock (or untyped entirely) is
536 /// `false`: PHP gives such a property an implicit `null` default, so it is
537 /// never "uninitialized" (no MissingConstructor) and accepts `null` on
538 /// assignment regardless of the advisory docblock type.
539 #[serde(default)]
540 pub has_native_type: bool,
541 /// True when this entry was synthesised from a `@property` / `@property-read` /
542 /// `@property-write` docblock tag rather than a real PHP property declaration.
543 /// Such entries describe magic properties accessible via `__get`/`__set` and
544 /// do **not** participate in PHP's inheritance visibility rules.
545 #[serde(default)]
546 pub from_docblock: bool,
547 /// True when `readonly` comes from a native PHP keyword (`readonly` modifier or
548 /// `readonly class`). False when only a `@readonly` docblock annotation is present.
549 /// Distinguishes PHP-enforced read-only from advisory documentation.
550 #[serde(default)]
551 pub has_native_readonly: bool,
552 /// The PHP native type hint alone, with any `@var` docblock refinement stripped —
553 /// `None` when `has_native_type` is false. `ty` mixes in the docblock type when
554 /// present, which makes it unsuitable for checking PHP's redeclared-property
555 /// type invariance rule: that rule is enforced by the runtime purely on the
556 /// native hint, never on the (unenforced) docblock annotation.
557 #[serde(default)]
558 #[serde(
559 deserialize_with = "deserialize_param_type",
560 serialize_with = "serialize_param_type"
561 )]
562 pub native_ty: Option<Arc<Type>>,
563}
564
565// ---------------------------------------------------------------------------
566// ConstantDef
567// ---------------------------------------------------------------------------
568
569#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
570pub struct ConstantDef {
571 pub name: Arc<str>,
572 pub ty: Type,
573 pub visibility: Option<Visibility>,
574 #[serde(default)]
575 pub is_final: bool,
576 pub location: Option<Location>,
577 /// `@deprecated` docblock annotation, if present.
578 #[serde(default)]
579 pub deprecated: Option<Arc<str>>,
580}
581
582// ---------------------------------------------------------------------------
583// ClassDef
584// ---------------------------------------------------------------------------
585
586#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
587pub struct ClassDef {
588 pub fqcn: Arc<str>,
589 pub short_name: Arc<str>,
590 pub parent: Option<Arc<str>>,
591 pub interfaces: Vec<Arc<str>>,
592 pub traits: Vec<Arc<str>>,
593 pub own_methods: MemberMap<Arc<MethodDef>>,
594 pub own_properties: MemberMap<PropertyDef>,
595 pub own_constants: MemberMap<ConstantDef>,
596 #[serde(default)]
597 pub mixins: Vec<Arc<str>>,
598 pub template_params: Vec<TemplateParam>,
599 /// Type arguments from `@extends ParentClass<T1, T2>` — maps parent's template params to concrete types.
600 pub extends_type_args: Vec<Type>,
601 /// Type arguments from `@implements Interface<T1, T2>`.
602 #[serde(default)]
603 pub implements_type_args: Vec<(Arc<str>, Vec<Type>)>,
604 /// Type arguments from `@use TraitName<T1, T2>`, keyed by the used
605 /// trait's FQCN — a class's `use` clause (unlike `@extends`) may name
606 /// several traits at once.
607 #[serde(default)]
608 pub trait_use_type_args: Vec<(Arc<str>, Vec<Type>)>,
609 pub is_abstract: bool,
610 pub is_final: bool,
611 pub is_readonly: bool,
612 pub deprecated: Option<Arc<str>>,
613 pub is_internal: bool,
614 /// Set when the class carries `@psalm-immutable` — non-constructor methods must not
615 /// assign to `$this` properties.
616 #[serde(default)]
617 pub is_immutable: bool,
618 /// Attribute target flags if this class has `#[Attribute]` annotation.
619 /// `None` = not an attribute class. The value is a bitmask of PHP's
620 /// `Attribute::TARGET_*` constants (e.g. `Attribute::TARGET_CLASS = 1`).
621 #[serde(default)]
622 pub attribute_flags: Option<i64>,
623 pub location: Option<Location>,
624 /// Per-`use` statement locations for each used trait: `(fqcn, location)` in
625 /// declaration order, parallel to `traits`. Absent from older serialized
626 /// slices; defaults to empty.
627 #[serde(default)]
628 pub trait_use_locations: Vec<(Arc<str>, Location)>,
629 /// Type aliases declared on this class via `@psalm-type` / `@phpstan-type`.
630 #[serde(default)]
631 pub type_aliases: FxHashMap<Arc<str>, Type>,
632 /// Raw import-type declarations (`(local_name, original_name, from_class)`) — resolved during finalization.
633 #[serde(default)]
634 pub pending_import_types: Vec<(Arc<str>, Arc<str>, Arc<str>)>,
635 /// Trait precedence exclusions from `insteadof` declarations in this class's `use` blocks.
636 /// Maps method_name_lowercase → list of trait FQCNs whose version of the method is excluded.
637 /// E.g. `use A, B { B::hello insteadof A; }` stores `"hello" → ["A"]`.
638 #[serde(default)]
639 pub trait_insteadof: MemberMap<Vec<Arc<str>>>,
640 /// Trait method aliases from `as` declarations in this class's `use` blocks.
641 /// Maps new_name_lowercase → (optional_trait_fqcn, original_method_name_lowercase, visibility_override, alias_cased).
642 /// `alias_cased` is the alias name preserving the original PHP casing (for error messages / case checks).
643 /// Visibility is `None` when the `as` clause only renames without changing visibility.
644 /// E.g. `use Base { __construct as __constructBase; }` stores
645 /// `"__constructbase" → (None, "__construct", None, "__constructBase")`.
646 /// E.g. `use T { foo as private traitFoo; }` stores
647 /// `"traitfoo" → (None, "foo", Some(Private), "traitFoo")`.
648 #[serde(default)]
649 #[allow(clippy::type_complexity)]
650 pub trait_aliases:
651 FxHashMap<Arc<str>, (Option<Arc<str>>, Arc<str>, Option<Visibility>, Arc<str>)>,
652}
653
654impl ClassDef {
655 pub fn get_method(&self, name: &str) -> Option<&MethodDef> {
656 // PHP method names are case-insensitive; caller should pass lowercase name.
657 // Only searches own_methods — inherited method resolution is done by
658 // `db::lookup_method_in_chain`.
659 self.own_methods.get(name).map(Arc::as_ref).or_else(|| {
660 self.own_methods
661 .iter()
662 .find(|(k, _)| k.as_ref().eq_ignore_ascii_case(name))
663 .map(|(_, v)| v.as_ref())
664 })
665 }
666
667 pub fn get_property(&self, name: &str) -> Option<&PropertyDef> {
668 self.own_properties.get(name)
669 }
670}
671
672// ---------------------------------------------------------------------------
673// InterfaceDef
674// ---------------------------------------------------------------------------
675
676#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
677pub struct InterfaceDef {
678 pub fqcn: Arc<str>,
679 pub short_name: Arc<str>,
680 pub extends: Vec<Arc<str>>,
681 pub own_methods: MemberMap<Arc<MethodDef>>,
682 pub own_constants: MemberMap<ConstantDef>,
683 pub template_params: Vec<TemplateParam>,
684 pub location: Option<Location>,
685 /// `@deprecated` docblock annotation, if present.
686 #[serde(default)]
687 pub deprecated: Option<Arc<str>>,
688 /// Properties declared via `@property*` docblock annotations on the interface.
689 #[serde(default)]
690 pub own_properties: MemberMap<PropertyDef>,
691 /// `@seal-properties` / `@psalm-seal-properties` — disallows undeclared property access.
692 #[serde(default)]
693 pub seal_properties: bool,
694 /// Type arguments from `@extends BaseIface<T1, T2>` docblock lines, keyed by the
695 /// extended interface's FQCN — an interface's native `extends` list (unlike a
696 /// class's single parent) may name several base interfaces at once.
697 #[serde(default)]
698 pub extends_type_args: Vec<(Arc<str>, Vec<Type>)>,
699 /// Type aliases declared on this interface via `@psalm-type` / `@phpstan-type`.
700 #[serde(default)]
701 pub type_aliases: FxHashMap<Arc<str>, Type>,
702}
703
704// ---------------------------------------------------------------------------
705// TraitDef
706// ---------------------------------------------------------------------------
707
708#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
709pub struct TraitDef {
710 pub fqcn: Arc<str>,
711 pub short_name: Arc<str>,
712 pub own_methods: MemberMap<Arc<MethodDef>>,
713 pub own_properties: MemberMap<PropertyDef>,
714 pub own_constants: MemberMap<ConstantDef>,
715 pub template_params: Vec<TemplateParam>,
716 /// Traits used by this trait (`use OtherTrait;` inside a trait body).
717 pub traits: Vec<Arc<str>>,
718 pub location: Option<Location>,
719 /// Per-`use` statement locations for each used trait: `(fqcn, location)` in
720 /// declaration order, parallel to `traits`. Mirrors `ClassDef`/`EnumDef`'s
721 /// field of the same name. Absent from older serialized slices; defaults
722 /// to empty.
723 #[serde(default)]
724 pub trait_use_locations: Vec<(Arc<str>, Location)>,
725 /// Type arguments from `@use OtherTrait<T1, T2>` (a trait may itself
726 /// `use` a generic trait).
727 #[serde(default)]
728 pub trait_use_type_args: Vec<(Arc<str>, Vec<Type>)>,
729 /// `@psalm-require-extends` / `@phpstan-require-extends` — FQCNs that using classes must extend.
730 #[serde(default)]
731 pub require_extends: Vec<Arc<str>>,
732 /// `@psalm-require-implements` / `@phpstan-require-implements` — FQCNs that using classes must implement.
733 #[serde(default)]
734 pub require_implements: Vec<Arc<str>>,
735 /// `@deprecated` docblock annotation, if present.
736 #[serde(default)]
737 pub deprecated: Option<Arc<str>>,
738 /// Type aliases declared on this trait via `@psalm-type` / `@phpstan-type`.
739 #[serde(default)]
740 pub type_aliases: FxHashMap<Arc<str>, Type>,
741}
742
743// ---------------------------------------------------------------------------
744// EnumDef
745// ---------------------------------------------------------------------------
746
747#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
748pub struct EnumCaseDef {
749 pub name: Arc<str>,
750 pub value: Option<Type>,
751 pub location: Option<Location>,
752 /// `@deprecated` docblock annotation, if present.
753 #[serde(default)]
754 pub deprecated: Option<Arc<str>>,
755}
756
757#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
758pub struct EnumDef {
759 pub fqcn: Arc<str>,
760 pub short_name: Arc<str>,
761 pub scalar_type: Option<Type>,
762 pub interfaces: Vec<Arc<str>>,
763 /// Type arguments from `@implements Interface<T1, T2>`.
764 #[serde(default)]
765 pub implements_type_args: Vec<(Arc<str>, Vec<Type>)>,
766 pub cases: MemberMap<EnumCaseDef>,
767 pub own_methods: MemberMap<Arc<MethodDef>>,
768 pub own_constants: MemberMap<ConstantDef>,
769 /// `use SomeTrait;` declarations. PHP enums may use traits (for methods),
770 /// just never carry instance properties from them.
771 #[serde(default)]
772 pub traits: Vec<Arc<str>>,
773 #[serde(default)]
774 pub trait_use_locations: Vec<(Arc<str>, Location)>,
775 /// Type arguments from `@use SomeTrait<T1, T2>`.
776 #[serde(default)]
777 pub trait_use_type_args: Vec<(Arc<str>, Vec<Type>)>,
778 pub location: Option<Location>,
779 /// `@deprecated` docblock annotation (or `#[Deprecated]` attribute), if present.
780 #[serde(default)]
781 pub deprecated: Option<Arc<str>>,
782 /// Type aliases declared on this enum via `@psalm-type` / `@phpstan-type`.
783 #[serde(default)]
784 pub type_aliases: FxHashMap<Arc<str>, Type>,
785 /// Properties declared via `@property*` docblock annotations on the enum.
786 #[serde(default)]
787 pub own_properties: MemberMap<PropertyDef>,
788}
789
790// ---------------------------------------------------------------------------
791// FunctionDef
792// ---------------------------------------------------------------------------
793
794#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
795pub struct FunctionDef {
796 pub fqn: Arc<str>,
797 pub short_name: Arc<str>,
798 #[serde(
799 deserialize_with = "deserialize_params",
800 serialize_with = "serialize_params"
801 )]
802 pub params: Arc<[DeclaredParam]>,
803 /// Type from annotation (`@return` / native type hint). `None` means unannotated.
804 /// Stored as `Option<Arc<Type>>` to enable deduplication of common return types.
805 #[serde(
806 deserialize_with = "deserialize_return_type",
807 serialize_with = "serialize_return_type"
808 )]
809 pub return_type: Option<Arc<Type>>,
810 /// See `MethodDef::inferred_return_type` — `Option<Arc<Type>>` (8 B) for the
811 /// same demand-driven-inference reason.
812 #[serde(
813 deserialize_with = "deserialize_return_type",
814 serialize_with = "serialize_return_type"
815 )]
816 pub inferred_return_type: Option<Arc<Type>>,
817 pub template_params: Vec<TemplateParam>,
818 pub assertions: Vec<Assertion>,
819 pub throws: Vec<Arc<str>>,
820 pub deprecated: Option<Arc<str>>,
821 pub is_pure: bool,
822 /// `@psalm-mutation-free` / `@phpstan-mutation-free` on a free function.
823 /// A free function has no `$this`, so this is behaviorally equivalent to
824 /// `is_external_mutation_free` here (both forbid mutating a parameter);
825 /// see `MethodDef::is_mutation_free` for the method-level (has-`$this`)
826 /// distinction this mirrors.
827 #[serde(default)]
828 pub is_mutation_free: bool,
829 /// `@psalm-external-mutation-free` on a free function — must not mutate
830 /// any object passed as an argument.
831 #[serde(default)]
832 pub is_external_mutation_free: bool,
833 /// `@no-named-arguments` — callers must not use named argument syntax.
834 #[serde(default)]
835 pub no_named_arguments: bool,
836 pub location: Option<Location>,
837 /// Plain-text description from the docblock (text before `@tag` lines).
838 /// Used for hover info.
839 #[serde(default)]
840 pub docstring: Option<Arc<str>>,
841 /// Parameters declared as taint sinks via `@taint-sink <kind> $param`.
842 /// Each entry is `(param_name_without_dollar, sink_kind_string)`.
843 #[serde(default)]
844 pub taint_sink_params: Vec<(Arc<str>, Arc<str>)>,
845 /// `@taint-source` — this function's return value is treated as tainted
846 /// (attacker-controlled) at every call site, mirroring `@taint-sink`'s
847 /// mechanism but marking the source side instead.
848 #[serde(default)]
849 pub is_taint_source: bool,
850 /// Type aliases declared on this function via `@psalm-type` / `@phpstan-type`.
851 #[serde(default)]
852 pub type_aliases: FxHashMap<Arc<str>, Type>,
853}
854
855impl FunctionDef {
856 pub fn effective_return_type(&self) -> Option<&Type> {
857 self.return_type
858 .as_deref()
859 .or(self.inferred_return_type.as_deref())
860 }
861}
862
863// ---------------------------------------------------------------------------
864// StubSlice — serializable bundle of definitions from one extension's stubs
865// ---------------------------------------------------------------------------
866
867/// A snapshot of all PHP definitions contributed by a single stub file set.
868///
869/// Produced by `mir-stubs-gen` at code-generation time and deserialized at
870/// runtime to ingest definitions into the salsa db via
871/// `MirDatabase::ingest_stub_slice`.
872#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
873pub struct StubSlice {
874 pub classes: Vec<Arc<ClassDef>>,
875 pub interfaces: Vec<Arc<InterfaceDef>>,
876 pub traits: Vec<Arc<TraitDef>>,
877 pub enums: Vec<Arc<EnumDef>>,
878 pub functions: Vec<Arc<FunctionDef>>,
879 #[serde(default)]
880 pub constants: Vec<(Arc<str>, Type)>,
881 /// Source file this slice was collected from. `None` for bundled stub slices
882 /// that were pre-computed and are not tied to a specific on-disk file.
883 #[serde(default)]
884 pub file: Option<Arc<str>>,
885 /// Types of `@var`-annotated global variables collected from this file.
886 /// Populated by `DefinitionCollector`; ingested into the salsa db's
887 /// `global_vars` table by `ingest_stub_slice` when `file` is `Some`.
888 #[serde(default)]
889 pub global_vars: Vec<(Arc<str>, Type)>,
890 /// The first namespace declared in this file (e.g. `"App\\Service"`).
891 /// Populated by `DefinitionCollector`; ingested into the salsa db's
892 /// `file_namespaces` table by `ingest_stub_slice` when `file` is `Some`.
893 #[serde(default)]
894 pub namespace: Option<Arc<str>>,
895 /// `use` alias map for this file: alias → FQCN.
896 ///
897 /// Stored as `Arc<FxHashMap<Name, Name>>` so that `file_imports()`
898 /// returns a cheap Arc clone instead of deep-cloning the map on every
899 /// `resolve_name` call (which fires once per symbol reference in
900 /// Pass 2). `Name` keys/values shrink each entry from ~108 bytes
901 /// (two `String` headers + two heap allocs averaging ~30 chars) to
902 /// 16 bytes (two `Ustr` u64 handles); the global ustr interner holds
903 /// one copy of each unique alias / FQCN string for the whole session.
904 #[serde(
905 deserialize_with = "deserialize_imports",
906 serialize_with = "serialize_imports"
907 )]
908 #[serde(default = "default_imports")]
909 pub imports: Arc<FxHashMap<Name, Name>>,
910 /// Subset of `imports` containing only `use` items that import a
911 /// class/interface/trait/enum (`UseKind::Normal`) — excludes `use
912 /// function`/`use const` aliases. Class-name resolution consults this
913 /// instead of `imports` so a function/constant import can't shadow a
914 /// same-named class reference (`use function Foo\bar;` must not make an
915 /// unrelated `bar` type hint resolve to `Foo\bar`).
916 #[serde(
917 deserialize_with = "deserialize_imports",
918 serialize_with = "serialize_imports"
919 )]
920 #[serde(default = "default_imports")]
921 pub class_imports: Arc<FxHashMap<Name, Name>>,
922 /// Set to `true` after `deduplicate_params_in_slice` has run on this slice.
923 /// `ingest_stub_slice` skips the clone+re-dedup when this flag is set.
924 #[serde(skip)]
925 pub is_deduped: bool,
926}
927
928// ---------------------------------------------------------------------------
929// Param list deduplication
930// ---------------------------------------------------------------------------
931
932use std::sync::Mutex;
933
934type ParamCache = Mutex<FxHashMap<Vec<DeclaredParam>, Arc<[DeclaredParam]>>>;
935
936/// Global cache of canonical Arc<[DeclaredParam]> instances for deduplication.
937/// Shared across all StubSlices to deduplicate vendor code with millions of
938/// methods that often have identical parameter lists.
939static PARAM_DEDUP_CACHE: std::sync::OnceLock<ParamCache> = std::sync::OnceLock::new();
940
941/// Deduplicate parameter lists across all methods and functions in a StubSlice.
942/// Many PHP framework methods share identical parameter lists (e.g., thousands
943/// of `(string $arg, array $opts)` signatures). This function groups identical
944/// param lists globally (across all slices processed so far) and replaces them
945/// with Arc<[DeclaredParam]> pointers to shared allocations.
946///
947/// Expected memory savings: 100–150 MiB on cold start (vendor collection).
948pub fn deduplicate_params_in_slice(slice: &mut StubSlice) {
949 let cache: &ParamCache = PARAM_DEDUP_CACHE.get_or_init(|| Mutex::new(FxHashMap::default()));
950 let mut canonical_params = cache.lock().unwrap();
951
952 let mut deduplicate = |params: &mut Arc<[DeclaredParam]>| {
953 if let Some(existing) = canonical_params.get(params.as_ref()) {
954 *params = existing.clone();
955 } else {
956 canonical_params.insert(params.as_ref().to_vec(), params.clone());
957 }
958 };
959
960 // Deduplicate method params in all classes
961 for cls in &mut slice.classes {
962 for method in Arc::make_mut(cls).own_methods.values_mut() {
963 deduplicate(&mut Arc::make_mut(method).params);
964 }
965 }
966
967 // Deduplicate method params in all interfaces
968 for iface in &mut slice.interfaces {
969 for method in Arc::make_mut(iface).own_methods.values_mut() {
970 deduplicate(&mut Arc::make_mut(method).params);
971 }
972 }
973
974 // Deduplicate method params in all traits
975 for tr in &mut slice.traits {
976 for method in Arc::make_mut(tr).own_methods.values_mut() {
977 deduplicate(&mut Arc::make_mut(method).params);
978 }
979 }
980
981 // Deduplicate method params in all enums
982 for en in &mut slice.enums {
983 for method in Arc::make_mut(en).own_methods.values_mut() {
984 deduplicate(&mut Arc::make_mut(method).params);
985 }
986 }
987
988 // Deduplicate function params
989 for func in &mut slice.functions {
990 deduplicate(&mut Arc::make_mut(func).params);
991 }
992 slice.is_deduped = true;
993}