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    /// `@no-named-arguments` — callers must not use named argument syntax.
460    #[serde(default)]
461    pub no_named_arguments: bool,
462    /// True when the method has the `#[Override]` PHP attribute.
463    #[serde(default)]
464    pub is_override: bool,
465    pub location: Option<Location>,
466    /// Plain-text description from the docblock (text before `@tag` lines).
467    /// Used for hover info.
468    #[serde(default)]
469    pub docstring: Option<Arc<str>>,
470    /// True for methods added via `@method` docblock annotations. Virtual
471    /// methods must not be required as concrete interface implementations.
472    #[serde(default)]
473    pub is_virtual: bool,
474    /// Parameters declared as taint sinks via `@taint-sink <kind> $param`.
475    /// Each entry is `(param_name_without_dollar, sink_kind_string)`.
476    #[serde(default)]
477    pub taint_sink_params: Vec<(Arc<str>, Arc<str>)>,
478    /// `@taint-source` — this method's return value is treated as tainted
479    /// (attacker-controlled) at every call site, mirroring `@taint-sink`'s
480    /// mechanism but marking the source side instead.
481    #[serde(default)]
482    pub is_taint_source: bool,
483    /// `@if-this-is Type` — the resolved constraint a receiver's type must
484    /// satisfy for this method to be callable. `None` when absent.
485    #[serde(default)]
486    pub if_this_is: Option<Arc<Type>>,
487    /// `@psalm-self-out Type` / `@phpstan-self-out Type` — the receiver's type
488    /// after this call returns (e.g. a fluent builder that narrows `$this` as
489    /// it's configured). `None` when absent.
490    #[serde(default)]
491    pub self_out: Option<Arc<Type>>,
492    /// True when the method has `@inheritDoc` / `{@inheritDoc}` in its docblock.
493    /// The analyzer inherits the parent's return type, param types, throws, and
494    /// template params when this method has none of its own.
495    #[serde(default)]
496    pub is_inherit_doc: bool,
497    /// `@psalm-mutation-free` / `@phpstan-mutation-free` — this method must not
498    /// assign to `$this` properties (same constraint as `@psalm-immutable` on the
499    /// class, but scoped to this single method).
500    #[serde(default)]
501    pub is_mutation_free: bool,
502    /// `@psalm-external-mutation-free` — this method must not mutate any objects
503    /// passed as arguments, but is allowed to modify `$this`.
504    #[serde(default)]
505    pub is_external_mutation_free: bool,
506    /// Method names referenced via `@dataProvider name` / `#[DataProvider('name')]`
507    /// (PHPUnit) — treated as used by dead-code analysis, since PHPUnit invokes
508    /// them by name through reflection rather than a direct call site.
509    #[serde(default)]
510    pub data_provider_targets: Vec<Arc<str>>,
511}
512
513impl MethodDef {
514    pub fn effective_return_type(&self) -> Option<&Type> {
515        self.return_type
516            .as_deref()
517            .or(self.inferred_return_type.as_deref())
518    }
519}
520
521// ---------------------------------------------------------------------------
522// PropertyDef
523// ---------------------------------------------------------------------------
524
525#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
526pub struct PropertyDef {
527    pub name: Arc<str>,
528    /// Declared/inferred/default types. Stored as `Option<Arc<Type>>` (8 B)
529    /// rather than inline `Option<Type>` (176 B, no niche) and interned via the
530    /// global pool on construction/deserialization — common property types
531    /// (`string`, `int`, a shared class type) dedup to one allocation. Mirrors
532    /// `DeclaredParam::ty`. On-disk format is unchanged (the serde helpers (de)serialize
533    /// the inner `Type` transparently).
534    #[serde(
535        deserialize_with = "deserialize_param_type",
536        serialize_with = "serialize_param_type"
537    )]
538    pub ty: Option<Arc<Type>>,
539    #[serde(
540        deserialize_with = "deserialize_param_type",
541        serialize_with = "serialize_param_type"
542    )]
543    pub inferred_ty: Option<Arc<Type>>,
544    pub visibility: Visibility,
545    pub is_static: bool,
546    pub is_readonly: bool,
547    #[serde(
548        deserialize_with = "deserialize_param_type",
549        serialize_with = "serialize_param_type"
550    )]
551    pub default: Option<Arc<Type>>,
552    pub location: Option<Location>,
553    /// `@deprecated` docblock annotation, if present.
554    #[serde(default)]
555    pub deprecated: Option<Arc<str>>,
556    /// True when the property declares a PHP native type hint (`public int $x`).
557    /// A property typed only via a `@var` docblock (or untyped entirely) is
558    /// `false`: PHP gives such a property an implicit `null` default, so it is
559    /// never "uninitialized" (no MissingConstructor) and accepts `null` on
560    /// assignment regardless of the advisory docblock type.
561    #[serde(default)]
562    pub has_native_type: bool,
563    /// True when this entry was synthesised from a `@property` / `@property-read` /
564    /// `@property-write` docblock tag rather than a real PHP property declaration.
565    /// Such entries describe magic properties accessible via `__get`/`__set` and
566    /// do **not** participate in PHP's inheritance visibility rules.
567    #[serde(default)]
568    pub from_docblock: bool,
569    /// True when `readonly` comes from a native PHP keyword (`readonly` modifier or
570    /// `readonly class`). False when only a `@readonly` docblock annotation is present.
571    /// Distinguishes PHP-enforced read-only from advisory documentation.
572    #[serde(default)]
573    pub has_native_readonly: bool,
574    /// The PHP native type hint alone, with any `@var` docblock refinement stripped —
575    /// `None` when `has_native_type` is false. `ty` mixes in the docblock type when
576    /// present, which makes it unsuitable for checking PHP's redeclared-property
577    /// type invariance rule: that rule is enforced by the runtime purely on the
578    /// native hint, never on the (unenforced) docblock annotation.
579    #[serde(default)]
580    #[serde(
581        deserialize_with = "deserialize_param_type",
582        serialize_with = "serialize_param_type"
583    )]
584    pub native_ty: Option<Arc<Type>>,
585}
586
587// ---------------------------------------------------------------------------
588// ConstantDef
589// ---------------------------------------------------------------------------
590
591#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
592pub struct ConstantDef {
593    pub name: Arc<str>,
594    pub ty: Type,
595    pub visibility: Option<Visibility>,
596    #[serde(default)]
597    pub is_final: bool,
598    pub location: Option<Location>,
599    /// `@deprecated` docblock annotation, if present.
600    #[serde(default)]
601    pub deprecated: Option<Arc<str>>,
602}
603
604// ---------------------------------------------------------------------------
605// ClassDef
606// ---------------------------------------------------------------------------
607
608#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
609pub struct ClassDef {
610    pub fqcn: Arc<str>,
611    pub short_name: Arc<str>,
612    pub parent: Option<Arc<str>>,
613    pub interfaces: Vec<Arc<str>>,
614    pub traits: Vec<Arc<str>>,
615    pub own_methods: MemberMap<Arc<MethodDef>>,
616    pub own_properties: MemberMap<PropertyDef>,
617    pub own_constants: MemberMap<ConstantDef>,
618    #[serde(default)]
619    pub mixins: Vec<Arc<str>>,
620    pub template_params: Vec<TemplateParam>,
621    /// Type arguments from `@extends ParentClass<T1, T2>` — maps parent's template params to concrete types.
622    pub extends_type_args: Vec<Type>,
623    /// Type arguments from `@implements Interface<T1, T2>`.
624    #[serde(default)]
625    pub implements_type_args: Vec<(Arc<str>, Vec<Type>)>,
626    /// Type arguments from `@use TraitName<T1, T2>`, keyed by the used
627    /// trait's FQCN — a class's `use` clause (unlike `@extends`) may name
628    /// several traits at once.
629    #[serde(default)]
630    pub trait_use_type_args: Vec<(Arc<str>, Vec<Type>)>,
631    pub is_abstract: bool,
632    pub is_final: bool,
633    pub is_readonly: bool,
634    pub deprecated: Option<Arc<str>>,
635    pub is_internal: bool,
636    /// Set when the class carries `@psalm-immutable` — non-constructor methods must not
637    /// assign to `$this` properties.
638    #[serde(default)]
639    pub is_immutable: bool,
640    /// Attribute target flags if this class has `#[Attribute]` annotation.
641    /// `None` = not an attribute class. The value is a bitmask of PHP's
642    /// `Attribute::TARGET_*` constants (e.g. `Attribute::TARGET_CLASS = 1`).
643    #[serde(default)]
644    pub attribute_flags: Option<i64>,
645    pub location: Option<Location>,
646    /// Per-`use` statement locations for each used trait: `(fqcn, location)` in
647    /// declaration order, parallel to `traits`.  Absent from older serialized
648    /// slices; defaults to empty.
649    #[serde(default)]
650    pub trait_use_locations: Vec<(Arc<str>, Location)>,
651    /// Type aliases declared on this class via `@psalm-type` / `@phpstan-type`.
652    #[serde(default)]
653    pub type_aliases: FxHashMap<Arc<str>, Type>,
654    /// Raw import-type declarations (`(local_name, original_name, from_class)`) — resolved during finalization.
655    #[serde(default)]
656    pub pending_import_types: Vec<(Arc<str>, Arc<str>, Arc<str>)>,
657    /// Trait precedence exclusions from `insteadof` declarations in this class's `use` blocks.
658    /// Maps method_name_lowercase → list of trait FQCNs whose version of the method is excluded.
659    /// E.g. `use A, B { B::hello insteadof A; }` stores `"hello" → ["A"]`.
660    #[serde(default)]
661    pub trait_insteadof: MemberMap<Vec<Arc<str>>>,
662    /// Trait method aliases from `as` declarations in this class's `use` blocks.
663    /// Maps new_name_lowercase → (optional_trait_fqcn, original_method_name_lowercase, visibility_override, alias_cased).
664    /// `alias_cased` is the alias name preserving the original PHP casing (for error messages / case checks).
665    /// Visibility is `None` when the `as` clause only renames without changing visibility.
666    /// E.g. `use Base { __construct as __constructBase; }` stores
667    ///   `"__constructbase" → (None, "__construct", None, "__constructBase")`.
668    /// E.g. `use T { foo as private traitFoo; }` stores
669    ///   `"traitfoo" → (None, "foo", Some(Private), "traitFoo")`.
670    #[serde(default)]
671    #[allow(clippy::type_complexity)]
672    pub trait_aliases:
673        FxHashMap<Arc<str>, (Option<Arc<str>>, Arc<str>, Option<Visibility>, Arc<str>)>,
674}
675
676impl ClassDef {
677    pub fn get_method(&self, name: &str) -> Option<&MethodDef> {
678        // PHP method names are case-insensitive; caller should pass lowercase name.
679        // Only searches own_methods — inherited method resolution is done by
680        // `db::lookup_method_in_chain`.
681        self.own_methods.get(name).map(Arc::as_ref).or_else(|| {
682            self.own_methods
683                .iter()
684                .find(|(k, _)| k.as_ref().eq_ignore_ascii_case(name))
685                .map(|(_, v)| v.as_ref())
686        })
687    }
688
689    pub fn get_property(&self, name: &str) -> Option<&PropertyDef> {
690        self.own_properties.get(name)
691    }
692}
693
694// ---------------------------------------------------------------------------
695// InterfaceDef
696// ---------------------------------------------------------------------------
697
698#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
699pub struct InterfaceDef {
700    pub fqcn: Arc<str>,
701    pub short_name: Arc<str>,
702    pub extends: Vec<Arc<str>>,
703    pub own_methods: MemberMap<Arc<MethodDef>>,
704    pub own_constants: MemberMap<ConstantDef>,
705    pub template_params: Vec<TemplateParam>,
706    pub location: Option<Location>,
707    /// `@deprecated` docblock annotation, if present.
708    #[serde(default)]
709    pub deprecated: Option<Arc<str>>,
710    /// Properties declared via `@property*` docblock annotations on the interface.
711    #[serde(default)]
712    pub own_properties: MemberMap<PropertyDef>,
713    /// `@seal-properties` / `@psalm-seal-properties` — disallows undeclared property access.
714    #[serde(default)]
715    pub seal_properties: bool,
716    /// Type arguments from `@extends BaseIface<T1, T2>` docblock lines, keyed by the
717    /// extended interface's FQCN — an interface's native `extends` list (unlike a
718    /// class's single parent) may name several base interfaces at once.
719    #[serde(default)]
720    pub extends_type_args: Vec<(Arc<str>, Vec<Type>)>,
721    /// Type aliases declared on this interface via `@psalm-type` / `@phpstan-type`.
722    #[serde(default)]
723    pub type_aliases: FxHashMap<Arc<str>, Type>,
724}
725
726// ---------------------------------------------------------------------------
727// TraitDef
728// ---------------------------------------------------------------------------
729
730#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
731pub struct TraitDef {
732    pub fqcn: Arc<str>,
733    pub short_name: Arc<str>,
734    pub own_methods: MemberMap<Arc<MethodDef>>,
735    pub own_properties: MemberMap<PropertyDef>,
736    pub own_constants: MemberMap<ConstantDef>,
737    pub template_params: Vec<TemplateParam>,
738    /// Traits used by this trait (`use OtherTrait;` inside a trait body).
739    pub traits: Vec<Arc<str>>,
740    pub location: Option<Location>,
741    /// Per-`use` statement locations for each used trait: `(fqcn, location)` in
742    /// declaration order, parallel to `traits`. Mirrors `ClassDef`/`EnumDef`'s
743    /// field of the same name. Absent from older serialized slices; defaults
744    /// to empty.
745    #[serde(default)]
746    pub trait_use_locations: Vec<(Arc<str>, Location)>,
747    /// Type arguments from `@use OtherTrait<T1, T2>` (a trait may itself
748    /// `use` a generic trait).
749    #[serde(default)]
750    pub trait_use_type_args: Vec<(Arc<str>, Vec<Type>)>,
751    /// `@psalm-require-extends` / `@phpstan-require-extends` — FQCNs that using classes must extend.
752    #[serde(default)]
753    pub require_extends: Vec<Arc<str>>,
754    /// `@psalm-require-implements` / `@phpstan-require-implements` — FQCNs that using classes must implement.
755    #[serde(default)]
756    pub require_implements: Vec<Arc<str>>,
757    /// `@deprecated` docblock annotation, if present.
758    #[serde(default)]
759    pub deprecated: Option<Arc<str>>,
760    /// Type aliases declared on this trait via `@psalm-type` / `@phpstan-type`.
761    #[serde(default)]
762    pub type_aliases: FxHashMap<Arc<str>, Type>,
763}
764
765// ---------------------------------------------------------------------------
766// EnumDef
767// ---------------------------------------------------------------------------
768
769#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
770pub struct EnumCaseDef {
771    pub name: Arc<str>,
772    pub value: Option<Type>,
773    pub location: Option<Location>,
774    /// `@deprecated` docblock annotation, if present.
775    #[serde(default)]
776    pub deprecated: Option<Arc<str>>,
777}
778
779#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
780pub struct EnumDef {
781    pub fqcn: Arc<str>,
782    pub short_name: Arc<str>,
783    pub scalar_type: Option<Type>,
784    pub interfaces: Vec<Arc<str>>,
785    /// Type arguments from `@implements Interface<T1, T2>`.
786    #[serde(default)]
787    pub implements_type_args: Vec<(Arc<str>, Vec<Type>)>,
788    pub cases: MemberMap<EnumCaseDef>,
789    pub own_methods: MemberMap<Arc<MethodDef>>,
790    pub own_constants: MemberMap<ConstantDef>,
791    /// `use SomeTrait;` declarations. PHP enums may use traits (for methods),
792    /// just never carry instance properties from them.
793    #[serde(default)]
794    pub traits: Vec<Arc<str>>,
795    #[serde(default)]
796    pub trait_use_locations: Vec<(Arc<str>, Location)>,
797    /// Type arguments from `@use SomeTrait<T1, T2>`.
798    #[serde(default)]
799    pub trait_use_type_args: Vec<(Arc<str>, Vec<Type>)>,
800    pub location: Option<Location>,
801    /// `@deprecated` docblock annotation (or `#[Deprecated]` attribute), if present.
802    #[serde(default)]
803    pub deprecated: Option<Arc<str>>,
804    /// Type aliases declared on this enum via `@psalm-type` / `@phpstan-type`.
805    #[serde(default)]
806    pub type_aliases: FxHashMap<Arc<str>, Type>,
807    /// Properties declared via `@property*` docblock annotations on the enum.
808    #[serde(default)]
809    pub own_properties: MemberMap<PropertyDef>,
810}
811
812// ---------------------------------------------------------------------------
813// FunctionDef
814// ---------------------------------------------------------------------------
815
816#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
817pub struct FunctionDef {
818    pub fqn: Arc<str>,
819    pub short_name: Arc<str>,
820    #[serde(
821        deserialize_with = "deserialize_params",
822        serialize_with = "serialize_params"
823    )]
824    pub params: Arc<[DeclaredParam]>,
825    /// Type from annotation (`@return` / native type hint). `None` means unannotated.
826    /// Stored as `Option<Arc<Type>>` to enable deduplication of common return types.
827    #[serde(
828        deserialize_with = "deserialize_return_type",
829        serialize_with = "serialize_return_type"
830    )]
831    pub return_type: Option<Arc<Type>>,
832    /// See `MethodDef::inferred_return_type` — `Option<Arc<Type>>` (8 B) for the
833    /// same demand-driven-inference reason.
834    #[serde(
835        deserialize_with = "deserialize_return_type",
836        serialize_with = "serialize_return_type"
837    )]
838    pub inferred_return_type: Option<Arc<Type>>,
839    pub template_params: Vec<TemplateParam>,
840    pub assertions: Vec<Assertion>,
841    pub throws: Vec<Arc<str>>,
842    pub deprecated: Option<Arc<str>>,
843    pub is_pure: bool,
844    /// `@psalm-mutation-free` / `@phpstan-mutation-free` on a free function.
845    /// A free function has no `$this`, so this is behaviorally equivalent to
846    /// `is_external_mutation_free` here (both forbid mutating a parameter);
847    /// see `MethodDef::is_mutation_free` for the method-level (has-`$this`)
848    /// distinction this mirrors.
849    #[serde(default)]
850    pub is_mutation_free: bool,
851    /// `@psalm-external-mutation-free` on a free function — must not mutate
852    /// any object passed as an argument.
853    #[serde(default)]
854    pub is_external_mutation_free: bool,
855    /// `@no-named-arguments` — callers must not use named argument syntax.
856    #[serde(default)]
857    pub no_named_arguments: bool,
858    pub location: Option<Location>,
859    /// Plain-text description from the docblock (text before `@tag` lines).
860    /// Used for hover info.
861    #[serde(default)]
862    pub docstring: Option<Arc<str>>,
863    /// Parameters declared as taint sinks via `@taint-sink <kind> $param`.
864    /// Each entry is `(param_name_without_dollar, sink_kind_string)`.
865    #[serde(default)]
866    pub taint_sink_params: Vec<(Arc<str>, Arc<str>)>,
867    /// `@taint-source` — this function's return value is treated as tainted
868    /// (attacker-controlled) at every call site, mirroring `@taint-sink`'s
869    /// mechanism but marking the source side instead.
870    #[serde(default)]
871    pub is_taint_source: bool,
872    /// Type aliases declared on this function via `@psalm-type` / `@phpstan-type`.
873    #[serde(default)]
874    pub type_aliases: FxHashMap<Arc<str>, Type>,
875}
876
877impl FunctionDef {
878    pub fn effective_return_type(&self) -> Option<&Type> {
879        self.return_type
880            .as_deref()
881            .or(self.inferred_return_type.as_deref())
882    }
883}
884
885// ---------------------------------------------------------------------------
886// StubSlice — serializable bundle of definitions from one extension's stubs
887// ---------------------------------------------------------------------------
888
889/// A snapshot of all PHP definitions contributed by a single stub file set.
890///
891/// Produced by `mir-stubs-gen` at code-generation time and deserialized at
892/// runtime to ingest definitions into the salsa db via
893/// `MirDatabase::ingest_stub_slice`.
894#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
895pub struct StubSlice {
896    pub classes: Vec<Arc<ClassDef>>,
897    pub interfaces: Vec<Arc<InterfaceDef>>,
898    pub traits: Vec<Arc<TraitDef>>,
899    pub enums: Vec<Arc<EnumDef>>,
900    pub functions: Vec<Arc<FunctionDef>>,
901    #[serde(default)]
902    pub constants: Vec<(Arc<str>, Type)>,
903    /// Source file this slice was collected from. `None` for bundled stub slices
904    /// that were pre-computed and are not tied to a specific on-disk file.
905    #[serde(default)]
906    pub file: Option<Arc<str>>,
907    /// Types of `@var`-annotated global variables collected from this file.
908    /// Populated by `DefinitionCollector`; ingested into the salsa db's
909    /// `global_vars` table by `ingest_stub_slice` when `file` is `Some`.
910    #[serde(default)]
911    pub global_vars: Vec<(Arc<str>, Type)>,
912    /// The first namespace declared in this file (e.g. `"App\\Service"`).
913    /// Populated by `DefinitionCollector`; ingested into the salsa db's
914    /// `file_namespaces` table by `ingest_stub_slice` when `file` is `Some`.
915    #[serde(default)]
916    pub namespace: Option<Arc<str>>,
917    /// `use` alias map for this file: alias → FQCN.
918    ///
919    /// Stored as `Arc<FxHashMap<Name, Name>>` so that `file_imports()`
920    /// returns a cheap Arc clone instead of deep-cloning the map on every
921    /// `resolve_name` call (which fires once per symbol reference in
922    /// Pass 2). `Name` keys/values shrink each entry from ~108 bytes
923    /// (two `String` headers + two heap allocs averaging ~30 chars) to
924    /// 16 bytes (two `Ustr` u64 handles); the global ustr interner holds
925    /// one copy of each unique alias / FQCN string for the whole session.
926    #[serde(
927        deserialize_with = "deserialize_imports",
928        serialize_with = "serialize_imports"
929    )]
930    #[serde(default = "default_imports")]
931    pub imports: Arc<FxHashMap<Name, Name>>,
932    /// Subset of `imports` containing only `use` items that import a
933    /// class/interface/trait/enum (`UseKind::Normal`) — excludes `use
934    /// function`/`use const` aliases. Class-name resolution consults this
935    /// instead of `imports` so a function/constant import can't shadow a
936    /// same-named class reference (`use function Foo\bar;` must not make an
937    /// unrelated `bar` type hint resolve to `Foo\bar`).
938    #[serde(
939        deserialize_with = "deserialize_imports",
940        serialize_with = "serialize_imports"
941    )]
942    #[serde(default = "default_imports")]
943    pub class_imports: Arc<FxHashMap<Name, Name>>,
944    /// Set to `true` after `deduplicate_params_in_slice` has run on this slice.
945    /// `ingest_stub_slice` skips the clone+re-dedup when this flag is set.
946    #[serde(skip)]
947    pub is_deduped: bool,
948}
949
950// ---------------------------------------------------------------------------
951// Param list deduplication
952// ---------------------------------------------------------------------------
953
954use std::sync::Mutex;
955
956type ParamCache = Mutex<FxHashMap<Vec<DeclaredParam>, Arc<[DeclaredParam]>>>;
957
958/// Global cache of canonical Arc<[DeclaredParam]> instances for deduplication.
959/// Shared across all StubSlices to deduplicate vendor code with millions of
960/// methods that often have identical parameter lists.
961static PARAM_DEDUP_CACHE: std::sync::OnceLock<ParamCache> = std::sync::OnceLock::new();
962
963/// Deduplicate parameter lists across all methods and functions in a StubSlice.
964/// Many PHP framework methods share identical parameter lists (e.g., thousands
965/// of `(string $arg, array $opts)` signatures). This function groups identical
966/// param lists globally (across all slices processed so far) and replaces them
967/// with Arc<[DeclaredParam]> pointers to shared allocations.
968///
969/// Expected memory savings: 100–150 MiB on cold start (vendor collection).
970pub fn deduplicate_params_in_slice(slice: &mut StubSlice) {
971    let cache: &ParamCache = PARAM_DEDUP_CACHE.get_or_init(|| Mutex::new(FxHashMap::default()));
972    let mut canonical_params = cache.lock().unwrap();
973
974    let mut deduplicate = |params: &mut Arc<[DeclaredParam]>| {
975        if let Some(existing) = canonical_params.get(params.as_ref()) {
976            *params = existing.clone();
977        } else {
978            canonical_params.insert(params.as_ref().to_vec(), params.clone());
979        }
980    };
981
982    // Deduplicate method params in all classes
983    for cls in &mut slice.classes {
984        for method in Arc::make_mut(cls).own_methods.values_mut() {
985            deduplicate(&mut Arc::make_mut(method).params);
986        }
987    }
988
989    // Deduplicate method params in all interfaces
990    for iface in &mut slice.interfaces {
991        for method in Arc::make_mut(iface).own_methods.values_mut() {
992            deduplicate(&mut Arc::make_mut(method).params);
993        }
994    }
995
996    // Deduplicate method params in all traits
997    for tr in &mut slice.traits {
998        for method in Arc::make_mut(tr).own_methods.values_mut() {
999            deduplicate(&mut Arc::make_mut(method).params);
1000        }
1001    }
1002
1003    // Deduplicate method params in all enums
1004    for en in &mut slice.enums {
1005        for method in Arc::make_mut(en).own_methods.values_mut() {
1006            deduplicate(&mut Arc::make_mut(method).params);
1007        }
1008    }
1009
1010    // Deduplicate function params
1011    for func in &mut slice.functions {
1012        deduplicate(&mut Arc::make_mut(func).params);
1013    }
1014    slice.is_deduped = true;
1015}