Skip to main content

mir_codebase/
storage.rs

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