Skip to main content

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