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