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