Skip to main content

mago_codex/metadata/
mod.rs

1use std::borrow::Cow;
2use std::collections::hash_map::Entry;
3
4use foldhash::HashMap;
5use foldhash::HashSet;
6
7use mago_database::file::File;
8use mago_database::file::FileId;
9use mago_reporting::Annotation;
10use mago_reporting::Issue;
11use mago_reporting::IssueCollection;
12use mago_span::Span;
13use mago_word::Word;
14use mago_word::WordMap;
15use mago_word::WordSet;
16use mago_word::ascii_lowercase_constant_name_word;
17use mago_word::ascii_lowercase_word;
18use mago_word::empty_word;
19use mago_word::word;
20
21use crate::diff::CodebaseDiff;
22use crate::identifier::method::MethodIdentifier;
23use crate::issue::ScanningIssueKind;
24use crate::metadata::class_like::ClassLikeMetadata;
25use crate::metadata::class_like_constant::ClassLikeConstantMetadata;
26use crate::metadata::constant::ConstantMetadata;
27use crate::metadata::enum_case::EnumCaseMetadata;
28use crate::metadata::flags::MetadataFlags;
29use crate::metadata::function_like::FunctionLikeMetadata;
30use crate::metadata::inherited_methods::collect_inherited_patch_methods;
31use crate::metadata::inherited_methods::reset_patch_methods;
32use crate::metadata::inherited_methods::resolve_inherited_patch_methods;
33use crate::metadata::patch::PATCHABLE_FUNCTION_DOCBLOCK_FLAGS;
34use crate::metadata::patch::merge_explicit_docblock_flags;
35use crate::metadata::patch::propagate_inherited_docblock_flags;
36use crate::metadata::property::PropertyMetadata;
37use crate::metadata::ttype::TypeMetadata;
38use crate::reference::SymbolReferences;
39use crate::signature::FileSignature;
40use crate::symbol::SymbolKind;
41use crate::symbol::Symbols;
42use crate::ttype::atomic::TAtomic;
43use crate::ttype::atomic::object::TObject;
44use crate::ttype::expander::StaticClassType;
45use crate::ttype::expander::TypeExpansionOptions;
46use crate::ttype::expander::expand_union;
47use crate::ttype::get_mixed;
48use crate::ttype::union::TUnion;
49use crate::visibility::Visibility;
50
51pub mod attribute;
52pub mod class_like;
53pub mod class_like_constant;
54pub mod constant;
55mod entry_spans;
56pub mod enum_case;
57pub mod flags;
58pub mod function_like;
59mod inherited_methods;
60pub mod parameter;
61mod patch;
62pub mod property;
63pub mod property_hook;
64mod trait_adaptation;
65pub mod ttype;
66pub mod version_constraint;
67
68pub use entry_spans::CodebaseEntrySpans;
69
70/// Lightweight set of keys extracted from a per-file [`CodebaseMetadata`].
71///
72/// Used by the incremental engine to efficiently remove a file's contributions from the
73/// merged codebase without keeping a full `CodebaseMetadata` clone per file.
74/// Created via [`CodebaseMetadata::extract_owned_keys()`].
75#[derive(Debug, Clone)]
76pub struct CodebaseEntryKeys {
77    /// Class-like FQCN atoms (also used for symbol removal).
78    pub class_like_names: Vec<Word>,
79    pub class_like_aliases: Vec<(Word, Word, Span)>,
80    /// Function-like `(scope, name)` tuples.
81    pub function_like_keys: Vec<(Word, Word)>,
82    /// Constant FQN atoms.
83    pub constant_names: Vec<Word>,
84    /// File IDs that had signatures in this metadata.
85    pub file_ids: Vec<FileId>,
86}
87
88/// Holds all analyzed information about the symbols, structures, and relationships within a codebase.
89///
90/// This acts as the central repository for metadata gathered during static analysis,
91/// including details about classes, interfaces, traits, enums, functions, constants,
92/// their members, inheritance, dependencies, and associated types.
93#[derive(Clone, Debug, PartialEq, Default)]
94#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
95#[non_exhaustive]
96#[allow(clippy::unsafe_derive_deserialize)]
97pub struct CodebaseMetadata {
98    /// Configuration flag: Should types be inferred based on usage patterns?
99    pub infer_types_from_usage: bool,
100    /// Map from class-like FQCN (`Word`) to its detailed metadata (`ClassLikeMetadata`).
101    pub class_likes: WordMap<Box<ClassLikeMetadata>>,
102    #[cfg_attr(feature = "serde", serde(default))]
103    pub class_like_aliases: WordMap<Word>,
104    #[cfg_attr(feature = "serde", serde(default))]
105    class_like_alias_declarations: WordMap<(Word, Span, MetadataFlags)>,
106    #[cfg_attr(feature = "serde", serde(skip, default))]
107    class_like_aliases_dirty: bool,
108    /// Map from a function/method identifier tuple `(scope_id, function_id)` to its metadata (`FunctionLikeMetadata`).
109    /// `scope_id` is the FQCN for methods or often `Word::empty()` for global functions.
110    pub function_likes: HashMap<(Word, Word), Box<FunctionLikeMetadata>>,
111    /// Stores the kind (Class, Interface, etc.) for every known symbol FQCN.
112    pub symbols: Symbols,
113    /// Map from global constant FQN (`Word`) to its metadata (`ConstantMetadata`).
114    pub constants: WordMap<ConstantMetadata>,
115    /// Map from class/interface FQCN to the set of all its descendants (recursive).
116    pub all_class_like_descendants: WordMap<WordSet>,
117    /// Map from class/interface FQCN to the set of its direct descendants (children).
118    pub direct_classlike_descendants: WordMap<WordSet>,
119    /// Set of symbols (FQCNs) that are considered safe/validated.
120    pub safe_symbols: WordSet,
121    /// Set of specific members `(SymbolFQCN, MemberName)` that are considered safe/validated.
122    pub safe_symbol_members: HashSet<(Word, Word)>,
123    /// Each `FileSignature` contains a hierarchical tree of `DefSignatureNode` representing
124    /// top-level symbols (classes, functions, constants) and their nested members (methods, properties).
125    pub file_signatures: HashMap<FileId, FileSignature>,
126    /// Per-patch class-like metadata, keyed by FQCN.
127    ///
128    /// Vendor and patch files declare symbols under the same FQCN, so patches cannot share
129    /// the `class_likes` map. At most one patch may target a given symbol; a second patch for
130    /// the same FQCN is diagnosed as a [`PatchDuplicateTarget`](ScanningIssueKind::PatchDuplicateTarget)
131    /// rather than silently overwriting the first. Entries here are folded into `class_likes`
132    /// by [`apply_patches_pass`](Self::apply_patches_pass).
133    pub patch_class_likes: WordMap<Box<ClassLikeMetadata>>,
134    /// Per-patch function-like metadata, keyed by `(scope, name)`.
135    ///
136    /// The key matches the existing `function_likes` key shape: the FQCN for methods,
137    /// `empty_word()` for free functions.
138    pub patch_function_likes: HashMap<(Word, Word), Box<FunctionLikeMetadata>>,
139    /// Per-patch constant metadata, keyed by FQN.
140    pub patch_constants: WordMap<ConstantMetadata>,
141}
142
143impl CodebaseMetadata {
144    /// Creates a new, empty `CodebaseMetadata` with default values.
145    #[inline]
146    #[must_use]
147    pub fn new() -> Self {
148        Self::default()
149    }
150
151    pub(crate) fn add_class_like_alias(&mut self, alias: Word, target: Word, span: Span, flags: MetadataFlags) {
152        let replace =
153            self.class_like_alias_declarations.get(&alias).is_none_or(|(_, existing_span, existing_flags)| {
154                should_replace_metadata(*existing_flags, *existing_span, flags, span)
155            });
156
157        if replace {
158            self.class_like_alias_declarations.insert(alias, (target, span, flags));
159            self.class_like_aliases_dirty = true;
160        }
161    }
162
163    #[inline]
164    pub fn class_like_alias_declarations(&self) -> impl Iterator<Item = (Word, Word, Span)> + '_ {
165        self.class_like_alias_declarations.iter().map(|(alias, (target, span, _))| (*alias, *target, *span))
166    }
167
168    pub fn populate_class_like_aliases(&mut self) -> bool {
169        if !self.class_like_aliases_dirty {
170            return false;
171        }
172
173        let previous_aliases = std::mem::take(&mut self.class_like_aliases);
174        for alias in previous_aliases.keys().copied() {
175            if let Some(metadata) = self.class_likes.get(&alias) {
176                self.symbols.add_symbol_name(alias, metadata.kind);
177            } else {
178                self.symbols.remove(alias);
179            }
180        }
181
182        for metadata in self.class_likes.values_mut() {
183            metadata.aliases.clear();
184        }
185
186        let mut aliases = WordMap::default();
187        for alias in self.class_like_alias_declarations.keys().copied() {
188            if self.class_likes.contains_key(&alias) {
189                continue;
190            }
191
192            if let Some(actual) = self.resolve_class_like_alias_declaration(alias) {
193                aliases.insert(alias, actual);
194            }
195        }
196
197        let aliases_changed = aliases != previous_aliases;
198        self.class_like_aliases = aliases;
199        let mut aliased_classes = WordSet::default();
200        for (alias, actual) in &self.class_like_aliases {
201            let Some(metadata) = self.class_likes.get_mut(actual) else {
202                continue;
203            };
204
205            metadata.aliases.push(*alias);
206            aliased_classes.insert(*actual);
207            self.symbols.add_symbol_name(*alias, metadata.kind);
208        }
209
210        for actual in aliased_classes {
211            if let Some(metadata) = self.class_likes.get_mut(&actual) {
212                metadata.aliases.sort_unstable();
213            }
214        }
215
216        self.class_like_aliases_dirty = false;
217        aliases_changed
218    }
219
220    fn resolve_class_like_alias_declaration(&self, alias: Word) -> Option<Word> {
221        let mut current = self.class_like_alias_declarations.get(&alias)?.0;
222
223        for _ in 0..self.class_like_alias_declarations.len() {
224            if self.class_likes.contains_key(&current) {
225                return Some(current);
226            }
227
228            current = self.class_like_alias_declarations.get(&current)?.0;
229        }
230
231        None
232    }
233
234    #[inline]
235    pub(crate) fn resolve_class_like_word(&self, name: Word) -> Option<Word> {
236        if self.class_likes.contains_key(&name) {
237            return Some(name);
238        }
239
240        if self.class_like_aliases.is_empty() {
241            return None;
242        }
243
244        self.class_like_aliases.get(&name).copied()
245    }
246
247    #[inline]
248    pub(crate) fn get_class_like_by_word(&self, name: Word) -> Option<&ClassLikeMetadata> {
249        if let Some(metadata) = self.class_likes.get(&name) {
250            return Some(metadata.as_ref());
251        }
252
253        if self.class_like_aliases.is_empty() {
254            return None;
255        }
256
257        self.class_like_aliases.get(&name).and_then(|actual| self.class_likes.get(actual)).map(Box::as_ref)
258    }
259
260    #[inline]
261    fn get_method_by_words(&self, class: Word, method: Word) -> Option<&FunctionLikeMetadata> {
262        if let Some(metadata) = self.function_likes.get(&(class, method)) {
263            return Some(metadata.as_ref());
264        }
265
266        if self.class_like_aliases.is_empty() {
267            return None;
268        }
269
270        let actual = self.class_like_aliases.get(&class)?;
271        self.function_likes.get(&(*actual, method)).map(Box::as_ref)
272    }
273
274    /// Checks if a class exists in the codebase (case-insensitive).
275    ///
276    /// # Examples
277    /// ```ignore
278    /// if codebase.class_exists("MyClass") {
279    ///     // MyClass is a class
280    /// }
281    /// ```
282    #[inline]
283    #[must_use]
284    pub fn class_exists(&self, name: &[u8]) -> bool {
285        let lowercase_name = ascii_lowercase_word(name);
286        matches!(self.symbols.get_kind(lowercase_name), Some(SymbolKind::Class))
287    }
288
289    /// Checks if an interface exists in the codebase (case-insensitive).
290    #[inline]
291    #[must_use]
292    pub fn interface_exists(&self, name: &[u8]) -> bool {
293        let lowercase_name = ascii_lowercase_word(name);
294        matches!(self.symbols.get_kind(lowercase_name), Some(SymbolKind::Interface))
295    }
296
297    /// Checks if a trait exists in the codebase (case-insensitive).
298    #[inline]
299    #[must_use]
300    pub fn trait_exists(&self, name: &[u8]) -> bool {
301        let lowercase_name = ascii_lowercase_word(name);
302        matches!(self.symbols.get_kind(lowercase_name), Some(SymbolKind::Trait))
303    }
304
305    /// Checks if an enum exists in the codebase (case-insensitive).
306    #[inline]
307    #[must_use]
308    pub fn enum_exists(&self, name: &[u8]) -> bool {
309        let lowercase_name = ascii_lowercase_word(name);
310        matches!(self.symbols.get_kind(lowercase_name), Some(SymbolKind::Enum))
311    }
312
313    /// Checks if a class-like (class, interface, trait, or enum) exists (case-insensitive).
314    #[inline]
315    #[must_use]
316    pub fn class_like_exists(&self, name: &[u8]) -> bool {
317        let lowercase_name = ascii_lowercase_word(name);
318        self.symbols.contains(lowercase_name)
319    }
320
321    /// Checks if a namespace exists (case-insensitive).
322    #[inline]
323    #[must_use]
324    pub fn namespace_exists(&self, name: &[u8]) -> bool {
325        let lowercase_name = ascii_lowercase_word(name);
326        self.symbols.contains_namespace(lowercase_name)
327    }
328
329    /// Checks if a class or trait exists in the codebase (case-insensitive).
330    #[inline]
331    #[must_use]
332    pub fn class_or_trait_exists(&self, name: &[u8]) -> bool {
333        let lowercase_name = ascii_lowercase_word(name);
334        matches!(self.symbols.get_kind(lowercase_name), Some(SymbolKind::Class | SymbolKind::Trait))
335    }
336
337    /// Checks if a class or interface exists in the codebase (case-insensitive).
338    #[inline]
339    #[must_use]
340    pub fn class_or_interface_exists(&self, name: &[u8]) -> bool {
341        let lowercase_name = ascii_lowercase_word(name);
342        matches!(self.symbols.get_kind(lowercase_name), Some(SymbolKind::Class | SymbolKind::Interface))
343    }
344
345    /// Checks if a method identifier exists in the codebase.
346    #[inline]
347    #[must_use]
348    pub fn method_identifier_exists(&self, method_id: &MethodIdentifier) -> bool {
349        let lowercase_class = method_id.get_class_name().to_ascii_lowercase();
350        let lowercase_method = method_id.get_method_name().to_ascii_lowercase();
351        self.get_method_by_words(lowercase_class, lowercase_method).is_some()
352    }
353
354    /// Checks if a global function exists in the codebase (case-insensitive).
355    #[inline]
356    #[must_use]
357    pub fn function_exists(&self, name: &[u8]) -> bool {
358        let lowercase_name = ascii_lowercase_word(name);
359        let identifier = (empty_word(), lowercase_name);
360        self.function_likes.contains_key(&identifier)
361    }
362
363    /// Checks if a global constant exists in the codebase.
364    /// The namespace part is case-insensitive, but the constant name is case-sensitive.
365    #[inline]
366    #[must_use]
367    pub fn constant_exists(&self, name: &[u8]) -> bool {
368        let lowercase_name = ascii_lowercase_constant_name_word(name);
369        self.constants.contains_key(&lowercase_name)
370    }
371
372    /// Checks if a method exists on a class-like, including inherited methods (case-insensitive).
373    #[inline]
374    #[must_use]
375    pub fn method_exists(&self, class: &[u8], method: &[u8]) -> bool {
376        let lowercase_class = ascii_lowercase_word(class);
377        let lowercase_method = ascii_lowercase_word(method);
378        self.get_class_like_by_word(lowercase_class)
379            .is_some_and(|meta| meta.appearing_method_ids.contains_key(&lowercase_method))
380    }
381
382    /// Checks if a property exists on a class-like, including inherited properties.
383    /// Class name is case-insensitive, property name is case-sensitive.
384    /// Sees real declarations only; magic `@property*` tags are reachable through
385    /// `ClassLikeMetadata::magic_property_ids`.
386    #[inline]
387    #[must_use]
388    pub fn property_exists(&self, class: &[u8], property: &[u8]) -> bool {
389        let lowercase_class = ascii_lowercase_word(class);
390        let property_name = word(property);
391        self.get_class_like_by_word(lowercase_class)
392            .is_some_and(|meta| meta.appearing_property_ids.contains_key(&property_name))
393    }
394
395    /// Checks if a magic `@property*` exists on a class-like, including inherited tags.
396    /// Class name is case-insensitive, property name is case-sensitive.
397    #[inline]
398    #[must_use]
399    pub fn magic_property_exists(&self, class: &[u8], property: &[u8]) -> bool {
400        let lowercase_class = ascii_lowercase_word(class);
401        let property_name = word(property);
402        self.get_class_like_by_word(lowercase_class)
403            .is_some_and(|meta| meta.magic_property_ids.contains_key(&property_name))
404    }
405
406    /// Checks if a class constant or enum case exists on a class-like.
407    /// Class name is case-insensitive, constant/case name is case-sensitive.
408    #[inline]
409    #[must_use]
410    pub fn class_constant_exists(&self, class: &[u8], constant: &[u8]) -> bool {
411        let lowercase_class = ascii_lowercase_word(class);
412        let constant_name = word(constant);
413        self.get_class_like_by_word(lowercase_class).is_some_and(|meta| {
414            meta.constants.contains_key(&constant_name) || meta.enum_cases.contains_key(&constant_name)
415        })
416    }
417
418    /// Retrieves metadata for a class (case-insensitive).
419    /// Returns `None` if the name doesn't correspond to a class.
420    #[inline]
421    #[must_use]
422    pub fn get_class(&self, name: &[u8]) -> Option<&ClassLikeMetadata> {
423        let lowercase_name = ascii_lowercase_word(name);
424        self.get_class_like_by_word(lowercase_name).filter(|metadata| metadata.kind.is_class())
425    }
426
427    /// Retrieves metadata for an interface (case-insensitive).
428    #[inline]
429    #[must_use]
430    pub fn get_interface(&self, name: &[u8]) -> Option<&ClassLikeMetadata> {
431        let lowercase_name = ascii_lowercase_word(name);
432        self.get_class_like_by_word(lowercase_name).filter(|metadata| metadata.kind.is_interface())
433    }
434
435    /// Retrieves metadata for a trait (case-insensitive).
436    #[inline]
437    #[must_use]
438    pub fn get_trait(&self, name: &[u8]) -> Option<&ClassLikeMetadata> {
439        let lowercase_name = ascii_lowercase_word(name);
440        self.get_class_like_by_word(lowercase_name).filter(|metadata| metadata.kind.is_trait())
441    }
442
443    /// Retrieves metadata for an enum (case-insensitive).
444    #[inline]
445    #[must_use]
446    pub fn get_enum(&self, name: &[u8]) -> Option<&ClassLikeMetadata> {
447        let lowercase_name = ascii_lowercase_word(name);
448        self.get_class_like_by_word(lowercase_name).filter(|metadata| metadata.kind.is_enum())
449    }
450
451    /// Retrieves metadata for any class-like structure (case-insensitive).
452    #[inline]
453    #[must_use]
454    pub fn get_class_like(&self, name: &[u8]) -> Option<&ClassLikeMetadata> {
455        let lowercase_name = ascii_lowercase_word(name);
456        self.get_class_like_by_word(lowercase_name)
457    }
458
459    /// Retrieves class-like metadata by interned name, ignoring ASCII case.
460    #[inline]
461    #[must_use]
462    pub fn get_class_like_by_name(&self, name: Word) -> Option<&ClassLikeMetadata> {
463        self.get_class_like_by_word(name.to_ascii_lowercase())
464    }
465
466    /// Retrieves metadata for a global function (case-insensitive).
467    #[inline]
468    #[must_use]
469    pub fn get_function(&self, name: &[u8]) -> Option<&FunctionLikeMetadata> {
470        let lowercase_name = ascii_lowercase_word(name);
471        let identifier = (empty_word(), lowercase_name);
472        self.function_likes.get(&identifier).map(Box::as_ref)
473    }
474
475    /// Retrieves metadata for a method (case-insensitive for both class and method names).
476    #[inline]
477    #[must_use]
478    pub fn get_method(&self, class: &[u8], method: &[u8]) -> Option<&FunctionLikeMetadata> {
479        let lowercase_class = ascii_lowercase_word(class);
480        let lowercase_method = ascii_lowercase_word(method);
481        self.get_method_by_words(lowercase_class, lowercase_method)
482    }
483
484    /// Retrieves metadata for a closure or arrow function by its synthetic
485    /// name (e.g. `{closure:src/foo.php:12:5}`).
486    #[inline]
487    #[must_use]
488    pub fn get_closure(&self, synthetic_name: &Word) -> Option<&FunctionLikeMetadata> {
489        self.function_likes.get(&(empty_word(), *synthetic_name)).map(Box::as_ref)
490    }
491
492    /// Retrieves metadata for a closure declared at the given file and span.
493    /// Convenience wrapper that rebuilds the synthetic name and delegates to
494    /// [`Self::get_closure`].
495    #[inline]
496    #[must_use]
497    pub fn get_closure_at(&self, file: &File, span: Span) -> Option<&FunctionLikeMetadata> {
498        let name = crate::build_synthetic_name("closure", file, span);
499        self.get_closure(&name)
500    }
501
502    /// Retrieves method metadata by `MethodIdentifier`.
503    #[inline]
504    #[must_use]
505    pub fn get_method_by_id(&self, method_id: &MethodIdentifier) -> Option<&FunctionLikeMetadata> {
506        let lowercase_class = method_id.get_class_name().to_ascii_lowercase();
507        let lowercase_method = method_id.get_method_name().to_ascii_lowercase();
508        self.get_method_by_words(lowercase_class, lowercase_method)
509    }
510
511    pub(crate) fn can_replace_inherited_method(&self, current: MethodIdentifier, parent: Word) -> bool {
512        let Some(method) = self.get_method_by_id(&current) else { return false };
513        method.method_metadata.as_ref().is_some_and(|metadata| metadata.is_abstract)
514            || (method.flags.is_magic_method()
515                && self.class_likes.get(&current.get_class_name()).is_some_and(|class| class.kind.is_trait())
516                && self.class_likes.get(&parent).is_some_and(|class| !class.kind.is_trait()))
517    }
518
519    /// Retrieves the declaring method metadata, following the inheritance chain.
520    /// This finds where the method is actually implemented.
521    #[inline]
522    #[must_use]
523    pub fn get_declaring_method(&self, class: &[u8], method: &[u8]) -> Option<&FunctionLikeMetadata> {
524        let method_id = MethodIdentifier::new(word(class), word(method));
525        self.get_declaring_method_by_id(&method_id)
526    }
527
528    /// Retrieves the declaring method by identifier, following inheritance and ignoring ASCII case.
529    #[inline]
530    #[must_use]
531    pub fn get_declaring_method_by_id(&self, method_id: &MethodIdentifier) -> Option<&FunctionLikeMetadata> {
532        self.get_method_by_id(&self.get_declaring_method_identifier(method_id))
533    }
534
535    /// Retrieves metadata for any function-like construct (function, method, or closure).
536    /// This is a convenience method that delegates to the appropriate getter based on the identifier type.
537    #[inline]
538    #[must_use]
539    pub fn get_function_like(
540        &self,
541        identifier: &crate::identifier::function_like::FunctionLikeIdentifier,
542    ) -> Option<&FunctionLikeMetadata> {
543        use crate::identifier::function_like::FunctionLikeIdentifier;
544        match identifier {
545            FunctionLikeIdentifier::Function(name) => {
546                self.function_likes.get(&(empty_word(), name.to_ascii_lowercase())).map(Box::as_ref)
547            }
548            FunctionLikeIdentifier::Method(class, method) => {
549                self.get_method_by_id(&MethodIdentifier::new(*class, *method))
550            }
551            FunctionLikeIdentifier::Closure(name) => self.get_closure(name),
552        }
553    }
554
555    /// Retrieves metadata for a global constant.
556    /// Namespace lookup is case-insensitive, constant name is case-sensitive.
557    #[inline]
558    #[must_use]
559    pub fn get_constant(&self, name: &[u8]) -> Option<&ConstantMetadata> {
560        let lowercase_name = ascii_lowercase_constant_name_word(name);
561        self.constants.get(&lowercase_name)
562    }
563
564    /// The declaration name span of a top-level symbol named `name`: a
565    /// class-like (class/interface/trait/enum), a function, or a constant.
566    ///
567    /// Prefers the symbol's name span over its full declaration span, so callers
568    /// land on the identifier rather than the whole declaration body. The lookup
569    /// is case-insensitive, like every symbol lookup here.
570    #[inline]
571    #[must_use]
572    pub fn span_of(&self, name: &[u8]) -> Option<Span> {
573        if let Some(meta) = self.get_class_like(name) {
574            return Some(meta.name_span.unwrap_or(meta.span));
575        }
576
577        if let Some(meta) = self.get_function(name) {
578            return Some(meta.name_span.unwrap_or(meta.span));
579        }
580
581        self.get_constant(name).map(|meta| meta.span)
582    }
583
584    /// Retrieves metadata for a class constant.
585    /// Class name is case-insensitive, constant name is case-sensitive.
586    #[inline]
587    #[must_use]
588    pub fn get_class_constant(&self, class: &[u8], constant: &[u8]) -> Option<&ClassLikeConstantMetadata> {
589        let lowercase_class = ascii_lowercase_word(class);
590        let constant_name = word(constant);
591        self.get_class_like_by_word(lowercase_class).and_then(|meta| meta.constants.get(&constant_name))
592    }
593
594    /// Retrieves metadata for an enum case.
595    #[inline]
596    #[must_use]
597    pub fn get_enum_case(&self, class: &[u8], case: &[u8]) -> Option<&EnumCaseMetadata> {
598        let lowercase_class = ascii_lowercase_word(class);
599        let case_name = word(case);
600        self.get_class_like_by_word(lowercase_class).and_then(|meta| meta.enum_cases.get(&case_name))
601    }
602
603    /// Retrieves metadata for a property directly from the class where it's declared.
604    /// Class name is case-insensitive, property name is case-sensitive.
605    /// Sees real declarations only; magic `@property*` tags are reachable through
606    /// `ClassLikeMetadata::magic_property_ids`.
607    #[inline]
608    #[must_use]
609    pub fn get_property(&self, class: &[u8], property: &[u8]) -> Option<&PropertyMetadata> {
610        let lowercase_class = ascii_lowercase_word(class);
611        let property_name = word(property);
612        self.get_class_like_by_word(lowercase_class)?.properties.get(&property_name)
613    }
614
615    /// Retrieves magic `@property*` metadata declared directly on a class-like.
616    /// Class name is case-insensitive, property name is case-sensitive.
617    #[inline]
618    #[must_use]
619    pub fn get_magic_property(&self, class: &[u8], property: &[u8]) -> Option<&PropertyMetadata> {
620        let lowercase_class = ascii_lowercase_word(class);
621        let property_name = word(property);
622        self.get_class_like_by_word(lowercase_class)?.magic_properties.get(&property_name)
623    }
624
625    /// Retrieves the property metadata, potentially from a parent class if inherited.
626    #[inline]
627    #[must_use]
628    pub fn get_declaring_property(&self, class: &[u8], property: &[u8]) -> Option<&PropertyMetadata> {
629        let lowercase_class = ascii_lowercase_word(class);
630        let property_name = word(property);
631        let declaring_class =
632            self.get_class_like_by_word(lowercase_class)?.declaring_property_ids.get(&property_name)?;
633        self.class_likes.get(declaring_class)?.properties.get(&property_name)
634    }
635
636    /// Retrieves magic `@property*` metadata, potentially from an inherited tag.
637    /// Class name is case-insensitive, property name is case-sensitive.
638    #[inline]
639    #[must_use]
640    pub fn get_declaring_magic_property(&self, class: &[u8], property: &[u8]) -> Option<&PropertyMetadata> {
641        let lowercase_class = ascii_lowercase_word(class);
642        let property_name = word(property);
643        let declaring_class = self.get_class_like_by_word(lowercase_class)?.magic_property_ids.get(&property_name)?;
644        self.class_likes.get(declaring_class)?.magic_properties.get(&property_name)
645    }
646    // Type Resolution
647
648    /// Gets the type of a property, resolving it from the declaring class if needed.
649    #[inline]
650    #[must_use]
651    pub fn get_property_type(&self, class: &[u8], property: &[u8]) -> Option<&TUnion> {
652        let lowercase_class = ascii_lowercase_word(class);
653        let property_name = word(property);
654        let declaring_class =
655            self.get_class_like_by_word(lowercase_class)?.declaring_property_ids.get(&property_name)?;
656        let property_meta = self.class_likes.get(declaring_class)?.properties.get(&property_name)?;
657        property_meta.type_metadata.as_ref().map(|tm| &tm.type_union)
658    }
659
660    /// Gets the type of a class constant, considering both type hints and inferred types.
661    #[must_use]
662    pub fn get_class_constant_type<'meta>(&'meta self, class: &[u8], constant: &[u8]) -> Option<Cow<'meta, TUnion>> {
663        let lowercase_class = ascii_lowercase_word(class);
664        let constant_name = word(constant);
665        let class_meta = self.get_class_like_by_word(lowercase_class)?;
666
667        // Check if it's an enum case
668        if class_meta.kind.is_enum() && class_meta.enum_cases.contains_key(&constant_name) {
669            let atomic = TAtomic::Object(TObject::new_enum_case(class_meta.original_name, constant_name));
670            return Some(Cow::Owned(TUnion::from_atomic(atomic)));
671        }
672
673        // It's a regular class constant
674        let constant_meta = class_meta.constants.get(&constant_name)?;
675
676        Some(Cow::Owned(self.get_expanded_class_constant_type(class_meta, constant_meta)))
677    }
678
679    /// Computes the type of a class constant the same way the analyzer does for a
680    /// class constant access: the `@var` docblock type wins, otherwise the inferred
681    /// type is preferred over the declared one. References inside the type, such as
682    /// enum cases (`Locale::DeDe`), are expanded.
683    fn get_expanded_class_constant_type(
684        &self,
685        class_meta: &ClassLikeMetadata,
686        constant_meta: &ClassLikeConstantMetadata,
687    ) -> TUnion {
688        let mut constant_type = if let Some(type_metadata) = &constant_meta.type_metadata
689            && type_metadata.from_docblock
690        {
691            type_metadata.type_union.clone()
692        } else {
693            constant_meta
694                .inferred_type
695                .clone()
696                .map(TUnion::from_atomic)
697                .or_else(|| constant_meta.type_metadata.as_ref().map(|type_metadata| type_metadata.type_union.clone()))
698                .unwrap_or_else(get_mixed)
699        };
700
701        expand_union(
702            self,
703            &mut constant_type,
704            &TypeExpansionOptions {
705                self_class: Some(class_meta.name),
706                static_class_type: StaticClassType::Name(class_meta.name),
707                function_is_final: class_meta.flags.is_final(),
708                ..Default::default()
709            },
710        );
711
712        constant_type
713    }
714    // Inheritance Queries
715
716    /// Checks if a child class extends a parent class (case-insensitive).
717    #[inline]
718    #[must_use]
719    pub fn class_extends(&self, child: &[u8], parent: &[u8]) -> bool {
720        let lowercase_child = ascii_lowercase_word(child);
721        let lowercase_parent = ascii_lowercase_word(parent);
722        let Some(metadata) = self.get_class_like_by_word(lowercase_child) else {
723            return false;
724        };
725
726        if metadata.all_parent_classes.contains(&lowercase_parent) {
727            return true;
728        }
729
730        if self.class_like_aliases.is_empty() || self.class_likes.contains_key(&lowercase_parent) {
731            return false;
732        }
733
734        self.class_like_aliases
735            .get(&lowercase_parent)
736            .is_some_and(|actual| metadata.all_parent_classes.contains(actual))
737    }
738
739    /// Checks if a class implements an interface (case-insensitive).
740    #[inline]
741    #[must_use]
742    pub fn class_implements(&self, class: &[u8], interface: &[u8]) -> bool {
743        let lowercase_class = ascii_lowercase_word(class);
744        let lowercase_interface = ascii_lowercase_word(interface);
745        let Some(metadata) = self.get_class_like_by_word(lowercase_class) else {
746            return false;
747        };
748
749        if metadata.all_parent_interfaces.contains(&lowercase_interface) {
750            return true;
751        }
752
753        if self.class_like_aliases.is_empty() || self.class_likes.contains_key(&lowercase_interface) {
754            return false;
755        }
756
757        self.class_like_aliases
758            .get(&lowercase_interface)
759            .is_some_and(|actual| metadata.all_parent_interfaces.contains(actual))
760    }
761
762    /// Checks if a class uses a trait (case-insensitive).
763    #[inline]
764    #[must_use]
765    pub fn class_uses_trait(&self, class: &[u8], trait_name: &[u8]) -> bool {
766        let lowercase_class = ascii_lowercase_word(class);
767        let lowercase_trait = ascii_lowercase_word(trait_name);
768        let Some(metadata) = self.get_class_like_by_word(lowercase_class) else {
769            return false;
770        };
771
772        if metadata.used_traits.contains(&lowercase_trait) {
773            return true;
774        }
775
776        if self.class_like_aliases.is_empty() || self.class_likes.contains_key(&lowercase_trait) {
777            return false;
778        }
779
780        self.class_like_aliases.get(&lowercase_trait).is_some_and(|actual| metadata.used_traits.contains(actual))
781    }
782
783    /// Checks if child is an instance of parent (via extends or implements).
784    #[inline]
785    #[must_use]
786    pub fn is_instance_of(&self, child: &[u8], parent: &[u8]) -> bool {
787        if child == parent {
788            return true;
789        }
790
791        let lowercase_child = ascii_lowercase_word(child);
792        let lowercase_parent = ascii_lowercase_word(parent);
793
794        if lowercase_child == lowercase_parent {
795            return true;
796        }
797
798        let Some(metadata) = self.get_class_like_by_word(lowercase_child) else {
799            return false;
800        };
801
802        let matches = |parent| {
803            metadata.name == parent
804                || metadata.all_parent_classes.contains(&parent)
805                || metadata.all_parent_interfaces.contains(&parent)
806                || metadata.used_traits.contains(&parent)
807                || metadata.require_extends.contains(&parent)
808                || metadata.require_implements.contains(&parent)
809        };
810
811        if matches(lowercase_parent) {
812            return true;
813        }
814
815        if self.class_like_aliases.is_empty() || self.class_likes.contains_key(&lowercase_parent) {
816            return false;
817        }
818
819        self.class_like_aliases.get(&lowercase_parent).is_some_and(|actual| matches(*actual))
820    }
821
822    /// Checks if the given name is an enum or final class.
823    #[inline]
824    #[must_use]
825    pub fn is_enum_or_final_class(&self, name: &[u8]) -> bool {
826        let lowercase_name = ascii_lowercase_word(name);
827        self.get_class_like_by_word(lowercase_name).is_some_and(|meta| meta.kind.is_enum() || meta.flags.is_final())
828    }
829
830    /// Checks if a class-like can be part of an intersection.
831    /// Generally, only final classes and enums cannot be intersected.
832    #[inline]
833    #[must_use]
834    pub fn is_inheritable(&self, name: &[u8]) -> bool {
835        let lowercase_name = ascii_lowercase_word(name);
836        match self.symbols.get_kind(lowercase_name) {
837            Some(SymbolKind::Class) => {
838                self.get_class_like_by_word(lowercase_name).is_some_and(|meta| !meta.flags.is_final())
839            }
840            Some(SymbolKind::Enum) => false,
841            Some(SymbolKind::Interface | SymbolKind::Trait) | None => true,
842        }
843    }
844
845    /// Gets all descendants of a class (recursive).
846    #[inline]
847    #[must_use]
848    pub fn get_class_descendants(&self, class: &[u8]) -> WordSet {
849        let lowercase_class = ascii_lowercase_word(class);
850        let lowercase_class = self.resolve_class_like_word(lowercase_class).unwrap_or(lowercase_class);
851        let mut all_descendants = WordSet::default();
852        let mut queue = vec![&lowercase_class];
853        let mut visited = WordSet::default();
854        visited.insert(lowercase_class);
855
856        while let Some(current_name) = queue.pop() {
857            if let Some(direct_descendants) = self.direct_classlike_descendants.get(current_name) {
858                for descendant in direct_descendants {
859                    if visited.insert(*descendant) {
860                        all_descendants.insert(*descendant);
861                        queue.push(descendant);
862                    }
863                }
864            }
865        }
866
867        all_descendants
868    }
869
870    /// Gets all ancestors of a class (parents + interfaces).
871    #[inline]
872    #[must_use]
873    pub fn get_class_ancestors(&self, class: &[u8]) -> WordSet {
874        let lowercase_class = ascii_lowercase_word(class);
875        let mut ancestors = WordSet::default();
876        if let Some(meta) = self.get_class_like_by_word(lowercase_class) {
877            ancestors.extend(meta.all_parent_classes.iter().copied());
878            ancestors.extend(meta.all_parent_interfaces.iter().copied());
879        }
880        ancestors
881    }
882
883    /// Gets the class where a method is declared (following inheritance).
884    #[inline]
885    #[must_use]
886    pub fn get_declaring_method_class(&self, class: &[u8], method: &[u8]) -> Option<Word> {
887        self.get_declaring_method_class_by_id(&MethodIdentifier::new(
888            ascii_lowercase_word(class),
889            ascii_lowercase_word(method),
890        ))
891    }
892
893    /// Gets the declaring class of an interned method name, ignoring ASCII case.
894    #[inline]
895    #[must_use]
896    pub fn get_declaring_method_class_by_id(&self, method: &MethodIdentifier) -> Option<Word> {
897        let lowercase_class = method.get_class_name().to_ascii_lowercase();
898        let lowercase_method = method.get_method_name().to_ascii_lowercase();
899
900        self.get_class_like_by_word(lowercase_class)?
901            .declaring_method_ids
902            .get(&lowercase_method)
903            .map(|method_id| method_id.get_class_name())
904    }
905
906    /// Gets the declaring method identifier for a method.
907    #[must_use]
908    pub fn get_declaring_method_identifier(&self, method_id: &MethodIdentifier) -> MethodIdentifier {
909        let lowercase_class = method_id.get_class_name().to_ascii_lowercase();
910        let lowercase_method = method_id.get_method_name().to_ascii_lowercase();
911
912        let Some(class_meta) = self.get_class_like_by_word(lowercase_class) else {
913            return *method_id;
914        };
915
916        if let Some(declaring_method_id) = class_meta.declaring_method_ids.get(&lowercase_method) {
917            return *declaring_method_id;
918        }
919
920        if class_meta.flags.is_abstract()
921            && let Some(overridden_map) = class_meta.overridden_method_ids.get(&lowercase_method)
922            && let Some((_, first_method_id)) = overridden_map.first()
923        {
924            return *first_method_id;
925        }
926
927        *method_id
928    }
929
930    /// Checks if a method is overriding a parent method.
931    #[inline]
932    #[must_use]
933    pub fn method_is_overriding(&self, class: &[u8], method: &[u8]) -> bool {
934        let lowercase_class = ascii_lowercase_word(class);
935        let lowercase_method = ascii_lowercase_word(method);
936        self.get_class_like_by_word(lowercase_class)
937            .is_some_and(|meta| meta.overridden_method_ids.contains_key(&lowercase_method))
938    }
939
940    /// Checks if a method is abstract.
941    #[inline]
942    #[must_use]
943    pub fn method_is_abstract(&self, class: &[u8], method: &[u8]) -> bool {
944        let lowercase_class = ascii_lowercase_word(class);
945        let lowercase_method = ascii_lowercase_word(method);
946        self.get_method_by_words(lowercase_class, lowercase_method)
947            .and_then(|meta| meta.method_metadata.as_ref())
948            .is_some_and(|method_meta| method_meta.is_abstract)
949    }
950
951    /// Checks if a method is final.
952    #[inline]
953    #[must_use]
954    pub fn method_is_final(&self, class: &[u8], method: &[u8]) -> bool {
955        let lowercase_class = ascii_lowercase_word(class);
956        let lowercase_method = ascii_lowercase_word(method);
957        let Some(class) = self.get_class_like_by_word(lowercase_class) else { return false };
958        let declaring = self.get_declaring_method_identifier(&MethodIdentifier::new(lowercase_class, lowercase_method));
959        self.get_method_by_id(&declaring)
960            .and_then(|meta| meta.method_metadata.as_ref())
961            .is_some_and(|method| method.is_final)
962            || self.effective_trait_method_modifiers(class, lowercase_method, declaring).is_final
963    }
964
965    /// Gets a method's visibility through inheritance and trait adaptations.
966    /// The nearest visibility adaptation wins; otherwise the source declaration supplies it.
967    #[inline]
968    #[must_use]
969    pub fn get_method_visibility(&self, class: &[u8], method: &[u8]) -> Option<Visibility> {
970        self.get_method_visibility_by_id(&MethodIdentifier::new(
971            ascii_lowercase_word(class),
972            ascii_lowercase_word(method),
973        ))
974    }
975
976    /// Gets a method's visibility from interned names, including trait visibility overrides.
977    #[inline]
978    #[must_use]
979    pub fn get_method_visibility_by_id(&self, method: &MethodIdentifier) -> Option<Visibility> {
980        let lowercase_class = method.get_class_name().to_ascii_lowercase();
981        let lowercase_method = method.get_method_name().to_ascii_lowercase();
982        let class_meta = self.get_class_like_by_word(lowercase_class)?;
983
984        let declaring = *class_meta.declaring_method_ids.get(&lowercase_method)?;
985        self.effective_trait_method_modifiers(class_meta, lowercase_method, declaring).visibility.or_else(|| {
986            self.get_method_by_id(&declaring)
987                .and_then(|meta| meta.method_metadata.as_ref())
988                .map(|method| method.visibility)
989        })
990    }
991
992    /// Gets thrown types for a function-like, including inherited throws.
993    #[must_use]
994    pub fn get_function_like_thrown_types<'meta>(
995        &'meta self,
996        class_like: Option<&'meta ClassLikeMetadata>,
997        function_like: &'meta FunctionLikeMetadata,
998    ) -> &'meta [TypeMetadata] {
999        if !function_like.thrown_types.is_empty() {
1000            return function_like.thrown_types.as_slice();
1001        }
1002
1003        if !function_like.kind.is_method() {
1004            return &[];
1005        }
1006
1007        let Some(class_like) = class_like else {
1008            return &[];
1009        };
1010
1011        let method_name = &function_like.name;
1012
1013        if let Some(overridden_map) = class_like.overridden_method_ids.get(method_name) {
1014            for (parent_class_name, parent_method_id) in overridden_map.iter() {
1015                if class_like.name.as_bytes().eq_ignore_ascii_case(parent_class_name.as_bytes()) {
1016                    continue; // Skip self-recursion if the method overrides itself
1017                }
1018
1019                let Some(parent_class) = self.class_likes.get(parent_class_name) else {
1020                    continue;
1021                };
1022
1023                let parent_method_key = (parent_method_id.get_class_name(), parent_method_id.get_method_name());
1024                if let Some(parent_method) = self.function_likes.get(&parent_method_key) {
1025                    let thrown = self.get_function_like_thrown_types(Some(parent_class), parent_method);
1026                    if !thrown.is_empty() {
1027                        return thrown;
1028                    }
1029                }
1030            }
1031        }
1032
1033        &[]
1034    }
1035
1036    /// Gets the class where a property is declared.
1037    /// Sees real declarations only; magic `@property*` tags are reachable through
1038    /// `ClassLikeMetadata::magic_property_ids`.
1039    #[inline]
1040    #[must_use]
1041    pub fn get_declaring_property_class(&self, class: &[u8], property: &[u8]) -> Option<Word> {
1042        let lowercase_class = ascii_lowercase_word(class);
1043        let property_name = word(property);
1044        self.get_class_like_by_word(lowercase_class)?.declaring_property_ids.get(&property_name).copied()
1045    }
1046
1047    /// Gets all descendants of a class (recursive).
1048    #[must_use]
1049    pub fn get_all_descendants(&self, class: &[u8]) -> WordSet {
1050        let lowercase_class = ascii_lowercase_word(class);
1051        let lowercase_class = self.resolve_class_like_word(lowercase_class).unwrap_or(lowercase_class);
1052        let mut all_descendants = WordSet::default();
1053        let mut queue = vec![&lowercase_class];
1054        let mut visited = WordSet::default();
1055        visited.insert(lowercase_class);
1056
1057        while let Some(current_name) = queue.pop() {
1058            if let Some(direct_descendants) = self.direct_classlike_descendants.get(current_name) {
1059                for descendant in direct_descendants {
1060                    if visited.insert(*descendant) {
1061                        all_descendants.insert(*descendant);
1062                        queue.push(descendant);
1063                    }
1064                }
1065            }
1066        }
1067
1068        all_descendants
1069    }
1070
1071    /// Generates the synthetic display name for an anonymous class based on
1072    /// its declaring file and span. Delegates to [`crate::get_anonymous_class_name`].
1073    #[must_use]
1074    pub fn get_anonymous_class_name(file: &File, span: Span) -> Word {
1075        crate::get_anonymous_class_name(file, span)
1076    }
1077
1078    /// Retrieves the metadata for an anonymous class based on its declaring
1079    /// file and span.
1080    #[must_use]
1081    pub fn get_anonymous_class(&self, file: &File, span: Span) -> Option<&ClassLikeMetadata> {
1082        let name = Self::get_anonymous_class_name(file, span);
1083        self.get_class_like_by_name(name)
1084    }
1085
1086    /// Gets the file signature for a given file ID.
1087    ///
1088    /// # Arguments
1089    ///
1090    /// * `file_id` - The file identifier
1091    ///
1092    /// # Returns
1093    ///
1094    /// A reference to the `FileSignature` if it exists, or `None` if the file has no signature.
1095    #[inline]
1096    #[must_use]
1097    pub fn get_file_signature(&self, file_id: &FileId) -> Option<&FileSignature> {
1098        self.file_signatures.get(file_id)
1099    }
1100
1101    /// Adds or updates a file signature for a given file ID.
1102    ///
1103    /// # Arguments
1104    ///
1105    /// * `file_id` - The file identifier
1106    /// * `signature` - The file signature
1107    ///
1108    /// # Returns
1109    ///
1110    /// The previous `FileSignature` if it existed.
1111    #[inline]
1112    pub fn set_file_signature(&mut self, file_id: FileId, signature: FileSignature) -> Option<FileSignature> {
1113        self.file_signatures.insert(file_id, signature)
1114    }
1115
1116    /// Marks safe symbols based on diff and invalidation cascade.
1117    ///
1118    /// After this function runs, `self.safe_symbols` and `self.safe_symbol_members`
1119    /// will contain all symbols that can be safely skipped during analysis.
1120    ///
1121    /// # Arguments
1122    ///
1123    /// * `diff` - The computed diff between old and new code
1124    /// * `references` - Symbol reference graph from previous run
1125    ///
1126    /// # Returns
1127    /// Returns the logical names of files whose top-level code references an invalidated
1128    /// symbol. Returns `None` if the cascade was too large to compute.
1129    pub fn mark_safe_symbols(&mut self, diff: &CodebaseDiff, references: &SymbolReferences) -> Option<WordSet> {
1130        let (invalid_symbols, partially_invalid, invalid_files) = references.get_invalid_symbols(diff)?;
1131
1132        // Mark all symbols in 'keep' set as safe (unless invalidated by cascade)
1133        for keep_symbol in diff.get_keep() {
1134            if !invalid_symbols.contains(keep_symbol) {
1135                if keep_symbol.1.is_empty() {
1136                    // Top-level symbol (class, function, constant)
1137                    if !partially_invalid.contains(&keep_symbol.0) {
1138                        self.safe_symbols.insert(keep_symbol.0);
1139                    }
1140                } else {
1141                    // Member (method, property, class constant)
1142                    self.safe_symbol_members.insert(*keep_symbol);
1143                }
1144            }
1145        }
1146
1147        Some(invalid_files)
1148    }
1149
1150    /// Merges information from another `CodebaseMetadata` into this one.
1151    ///
1152    /// When both metadata have the same priority, the one with the smaller span is kept
1153    /// for deterministic results regardless of scan order.
1154    pub fn extend(&mut self, other: CodebaseMetadata) {
1155        let class_likes_changed = !other.class_likes.is_empty();
1156        for (k, mut v) in other.class_likes {
1157            match self.class_likes.entry(k) {
1158                Entry::Occupied(mut entry) => {
1159                    if should_replace_metadata(entry.get().flags, entry.get().span, v.flags, v.span) {
1160                        v.version_constraint.merge(entry.get().version_constraint.clone());
1161                        entry.insert(v);
1162                    } else {
1163                        entry.get_mut().version_constraint.merge(v.version_constraint);
1164                    }
1165                }
1166                Entry::Vacant(entry) => {
1167                    entry.insert(v);
1168                }
1169            }
1170        }
1171
1172        if class_likes_changed && !self.class_like_alias_declarations.is_empty() {
1173            self.class_like_aliases_dirty = true;
1174        }
1175
1176        self.merge_class_like_alias_declarations(other.class_like_alias_declarations);
1177
1178        merge_function_likes(&mut self.function_likes, other.function_likes);
1179
1180        for (k, mut v) in other.constants {
1181            match self.constants.entry(k) {
1182                Entry::Occupied(mut entry) => {
1183                    if should_replace_metadata(entry.get().flags, entry.get().span, v.flags, v.span) {
1184                        v.version_constraint.merge(entry.get().version_constraint.clone());
1185                        entry.insert(v);
1186                    } else {
1187                        entry.get_mut().version_constraint.merge(v.version_constraint);
1188                    }
1189                }
1190                Entry::Vacant(entry) => {
1191                    entry.insert(v);
1192                }
1193            }
1194        }
1195
1196        self.symbols.extend(other.symbols);
1197
1198        for (k, v) in other.all_class_like_descendants {
1199            self.all_class_like_descendants.entry(k).or_default().extend(v);
1200        }
1201
1202        for (k, v) in other.direct_classlike_descendants {
1203            self.direct_classlike_descendants.entry(k).or_default().extend(v);
1204        }
1205
1206        for (file_id, signature) in other.file_signatures {
1207            self.file_signatures.entry(file_id).insert_entry(signature);
1208        }
1209
1210        self.safe_symbols.extend(other.safe_symbols);
1211        self.safe_symbol_members.extend(other.safe_symbol_members);
1212        self.infer_types_from_usage |= other.infer_types_from_usage;
1213        self.merge_patch_class_likes(other.patch_class_likes);
1214        self.merge_patch_function_likes(other.patch_function_likes);
1215        self.merge_patch_constants(other.patch_constants);
1216    }
1217
1218    /// Merges file metadata in order, with function metadata on a separate worker.
1219    pub fn extend_many_parallel(&mut self, mut others: Vec<Self>) {
1220        if others.len() < 128 || rayon::current_num_threads() == 1 {
1221            for other in others {
1222                self.extend(other);
1223            }
1224            return;
1225        }
1226
1227        let mut function_likes = std::mem::take(&mut self.function_likes);
1228        let functions: Vec<_> = others.iter_mut().map(|other| std::mem::take(&mut other.function_likes)).collect();
1229        rayon::join(
1230            || {
1231                for incoming in functions {
1232                    merge_function_likes(&mut function_likes, incoming);
1233                }
1234            },
1235            || {
1236                for other in others {
1237                    self.extend(other);
1238                }
1239            },
1240        );
1241        self.function_likes = function_likes;
1242    }
1243
1244    /// Extends this codebase with another by reference, cloning only individual entries.
1245    ///
1246    /// This is more efficient than `extend(other.clone())` because it avoids allocating
1247    /// a full clone of the source metadata's outer HashMap/WordMap structures. Only
1248    /// individual entries that need insertion are cloned.
1249    pub fn extend_ref(&mut self, other: &CodebaseMetadata) {
1250        let class_likes_changed = !other.class_likes.is_empty();
1251        for (k, v) in &other.class_likes {
1252            match self.class_likes.entry(*k) {
1253                Entry::Occupied(mut entry) => {
1254                    if should_replace_metadata(entry.get().flags, entry.get().span, v.flags, v.span) {
1255                        let mut new = v.clone();
1256                        new.version_constraint.merge(entry.get().version_constraint.clone());
1257                        entry.insert(new);
1258                    } else {
1259                        entry.get_mut().version_constraint.merge(v.version_constraint.clone());
1260                    }
1261                }
1262                Entry::Vacant(entry) => {
1263                    entry.insert(v.clone());
1264                }
1265            }
1266        }
1267
1268        if class_likes_changed && !self.class_like_alias_declarations.is_empty() {
1269            self.class_like_aliases_dirty = true;
1270        }
1271
1272        self.merge_class_like_alias_declarations(
1273            other.class_like_alias_declarations.iter().map(|(alias, declaration)| (*alias, *declaration)),
1274        );
1275
1276        for (k, v) in &other.function_likes {
1277            match self.function_likes.entry(*k) {
1278                Entry::Occupied(mut entry) => {
1279                    if should_replace_metadata(entry.get().flags, entry.get().span, v.flags, v.span) {
1280                        let mut new = v.clone();
1281                        new.version_constraint.merge(entry.get().version_constraint.clone());
1282                        entry.insert(new);
1283                    } else {
1284                        entry.get_mut().version_constraint.merge(v.version_constraint.clone());
1285                    }
1286                }
1287                Entry::Vacant(entry) => {
1288                    entry.insert(v.clone());
1289                }
1290            }
1291        }
1292
1293        for (k, v) in &other.constants {
1294            match self.constants.entry(*k) {
1295                Entry::Occupied(mut entry) => {
1296                    if should_replace_metadata(entry.get().flags, entry.get().span, v.flags, v.span) {
1297                        let mut new = v.clone();
1298                        new.version_constraint.merge(entry.get().version_constraint.clone());
1299                        entry.insert(new);
1300                    } else {
1301                        entry.get_mut().version_constraint.merge(v.version_constraint.clone());
1302                    }
1303                }
1304                Entry::Vacant(entry) => {
1305                    entry.insert(v.clone());
1306                }
1307            }
1308        }
1309
1310        self.symbols.extend_ref(&other.symbols);
1311
1312        for (k, v) in &other.all_class_like_descendants {
1313            self.all_class_like_descendants.entry(*k).or_default().extend(v.iter().copied());
1314        }
1315
1316        for (k, v) in &other.direct_classlike_descendants {
1317            self.direct_classlike_descendants.entry(*k).or_default().extend(v.iter().copied());
1318        }
1319
1320        for (k, v) in &other.file_signatures {
1321            self.file_signatures.insert(*k, v.clone());
1322        }
1323        self.safe_symbols.extend(other.safe_symbols.iter().copied());
1324        self.safe_symbol_members.extend(other.safe_symbol_members.iter().copied());
1325        self.infer_types_from_usage |= other.infer_types_from_usage;
1326        self.merge_patch_class_likes(other.patch_class_likes.iter().map(|(k, v)| (*k, v.clone())));
1327        self.merge_patch_function_likes(other.patch_function_likes.iter().map(|(k, v)| (*k, v.clone())));
1328        self.merge_patch_constants(other.patch_constants.iter().map(|(k, v)| (*k, v.clone())));
1329    }
1330
1331    fn merge_class_like_alias_declarations(
1332        &mut self,
1333        declarations: impl IntoIterator<Item = (Word, (Word, Span, MetadataFlags))>,
1334    ) {
1335        for (alias, (target, span, flags)) in declarations {
1336            self.add_class_like_alias(alias, target, span, flags);
1337        }
1338    }
1339
1340    /// Merges patch class-likes from another codebase, diagnosing collisions.
1341    ///
1342    /// At most one patch may target a given symbol. When two patches collide, the first-merged
1343    /// entry is kept and a [`PatchDuplicateTarget`](ScanningIssueKind::PatchDuplicateTarget)
1344    /// diagnostic referencing both sites is attached to it, rather than letting one silently
1345    /// overwrite the other in hash-order.
1346    fn merge_patch_class_likes(&mut self, incoming: impl IntoIterator<Item = (Word, Box<ClassLikeMetadata>)>) {
1347        for (k, v) in incoming {
1348            match self.patch_class_likes.entry(k) {
1349                Entry::Occupied(mut entry) => {
1350                    let diagnostic = duplicate_patch_class_diagnostic(entry.get(), &v);
1351                    entry.get_mut().issues.push(diagnostic);
1352                }
1353                Entry::Vacant(entry) => {
1354                    entry.insert(v);
1355                }
1356            }
1357        }
1358    }
1359
1360    /// Merges patch function-likes from another codebase, diagnosing collisions on free
1361    /// functions. Method collisions are subsumed by the enclosing class's duplicate
1362    /// diagnostic, so only keys with an empty class component are reported here.
1363    fn merge_patch_function_likes(
1364        &mut self,
1365        incoming: impl IntoIterator<Item = ((Word, Word), Box<FunctionLikeMetadata>)>,
1366    ) {
1367        for (k, v) in incoming {
1368            match self.patch_function_likes.entry(k) {
1369                Entry::Occupied(mut entry) => {
1370                    if k.0.is_empty() {
1371                        let diagnostic = duplicate_patch_function_diagnostic(entry.get(), &v);
1372                        entry.get_mut().issues.push(diagnostic);
1373                    }
1374                }
1375                Entry::Vacant(entry) => {
1376                    entry.insert(v);
1377                }
1378            }
1379        }
1380    }
1381
1382    /// Merges patch constants from another codebase, diagnosing collisions.
1383    fn merge_patch_constants(&mut self, incoming: impl IntoIterator<Item = (Word, ConstantMetadata)>) {
1384        for (k, v) in incoming {
1385            match self.patch_constants.entry(k) {
1386                Entry::Occupied(mut entry) => {
1387                    let diagnostic = duplicate_patch_constant_diagnostic(entry.get(), &v);
1388                    entry.get_mut().issues.push(diagnostic);
1389                }
1390                Entry::Vacant(entry) => {
1391                    entry.insert(v);
1392                }
1393            }
1394        }
1395    }
1396
1397    /// Moves every scanned entry of this per-file partial into the patch maps.
1398    ///
1399    /// Called on a per-file partial right after `scan_program` when the file is a
1400    /// [`FileType::Patch`]. Symbols and descendants from a patch partial are dropped — the
1401    /// FQCN belongs to whichever non-patch source originally declared it (or it's an orphan
1402    /// which `apply_patches_pass` will diagnose later).
1403    pub fn convert_partial_to_patch(&mut self) {
1404        for (k, v) in std::mem::take(&mut self.class_likes) {
1405            self.patch_class_likes.insert(k, v);
1406        }
1407
1408        for (k, v) in std::mem::take(&mut self.function_likes) {
1409            self.patch_function_likes.insert(k, v);
1410        }
1411
1412        for (k, v) in std::mem::take(&mut self.constants) {
1413            self.patch_constants.insert(k, v);
1414        }
1415
1416        self.symbols = Symbols::new();
1417        self.class_like_aliases.clear();
1418        self.class_like_alias_declarations.clear();
1419        self.class_like_aliases_dirty = false;
1420        self.all_class_like_descendants.clear();
1421        self.direct_classlike_descendants.clear();
1422    }
1423
1424    /// Folds every entry in the `patch_*` maps into the matching vendor / built-in entry,
1425    /// attaching validation diagnostics to the patch entry's `issues` list.
1426    ///
1427    /// At most one patch may target a given symbol, so each entry is applied directly to its
1428    /// target. A patch whose target is user-defined is inert (user definitions win); a patch
1429    /// with no matching target is diagnosed as an orphan.
1430    ///
1431    /// Must be called after all partials have been merged so the slots patches target are
1432    /// present.
1433    pub fn apply_patches_pass(&mut self) {
1434        reset_patch_methods(self);
1435        // `(class, method)` slots where a patch overrides a method inherited from an ancestor.
1436        // No function-like exists at these keys yet, so the function loop below materializes
1437        // them from the patch's own scanned declaration rather than treating them as orphans.
1438        let mut inherited_overrides: HashSet<(Word, Word)> = HashSet::default();
1439        let mut inherited_methods = collect_inherited_patch_methods(self);
1440        let mut applied_classes = Vec::new();
1441
1442        let class_keys: Vec<Word> = self.patch_class_likes.keys().copied().collect();
1443        for fqcn in class_keys {
1444            let Some(target) = self.class_likes.get(&fqcn) else {
1445                if let Some(p) = self.patch_class_likes.get_mut(&fqcn) {
1446                    let diag = orphan_patch_class_diagnostic(p);
1447                    p.issues.push(diag);
1448                }
1449                continue;
1450            };
1451            // User-defined targets win; the patch entry is inert. Leave any scan-time issues
1452            // on it intact — they still belong to the patch source.
1453            if target.flags.is_user_defined() {
1454                continue;
1455            }
1456
1457            let mut working = target.clone();
1458            let inherited = inherited_methods.remove(&fqcn).unwrap_or_default();
1459            inherited_overrides.extend(inherited.iter().map(|method| (fqcn, *method)));
1460            let constructor_name = word("__construct");
1461            let patch_declares_constructor = self.patch_class_likes[&fqcn].methods.contains(&constructor_name);
1462            if let Some(patch_entry) = self.patch_class_likes.get_mut(&fqcn)
1463                && working.apply_patch(patch_entry, &inherited)
1464            {
1465                applied_classes.push(fqcn);
1466            }
1467            if working.flags.has_consistent_constructor()
1468                && !patch_declares_constructor
1469                && !inherited.contains(&constructor_name)
1470                && let Some(constructor) = working.add_implicit_constructor()
1471            {
1472                self.function_likes.entry((fqcn, constructor_name)).or_insert_with(|| Box::new(constructor));
1473            }
1474            self.class_likes.insert(fqcn, working);
1475        }
1476
1477        propagate_inherited_docblock_flags(self, applied_classes);
1478
1479        let func_keys: Vec<(Word, Word)> = self.patch_function_likes.keys().copied().collect();
1480        for key in &func_keys {
1481            let Some(target) = self.function_likes.get(key) else { continue };
1482            if target.flags.is_user_defined() {
1483                continue;
1484            }
1485
1486            let mut working = target.clone();
1487            if let Some(patch_entry) = self.patch_function_likes.get_mut(key) {
1488                working.apply_patch(patch_entry);
1489            }
1490            self.function_likes.insert(*key, working);
1491        }
1492
1493        let inherited_keys: Vec<_> = func_keys
1494            .iter()
1495            .copied()
1496            .filter(|key| inherited_overrides.contains(key) && !self.function_likes.contains_key(key))
1497            .map(|(class, method)| MethodIdentifier::new(class, method))
1498            .collect();
1499
1500        for inherited in resolve_inherited_patch_methods(self, inherited_keys) {
1501            let key = inherited.target.get_key();
1502            let Some(patch) = self.patch_function_likes.get(&key) else { continue };
1503            let mut materialized = patch.clone();
1504            if let Some(inherited_flags) = inherited
1505                .source
1506                .and_then(|source| self.function_likes.get(&source.get_key()))
1507                .map(|source| source.flags)
1508            {
1509                let patch_origin_flag = materialized.flags & MetadataFlags::PATCH;
1510                materialized.flags = inherited_flags | patch_origin_flag;
1511                materialized.flags.remove(MetadataFlags::POPULATED);
1512                merge_explicit_docblock_flags(
1513                    &mut materialized.flags,
1514                    patch.flags,
1515                    patch.explicit_docblock_flags,
1516                    PATCHABLE_FUNCTION_DOCBLOCK_FLAGS,
1517                );
1518            }
1519            self.function_likes.insert(key, materialized);
1520        }
1521
1522        for key in func_keys {
1523            if self.function_likes.contains_key(&key) || !key.0.is_empty() {
1524                continue;
1525            }
1526            if let Some(patch) = self.patch_function_likes.get_mut(&key) {
1527                let diag = orphan_patch_function_diagnostic(patch);
1528                patch.issues.push(diag);
1529            }
1530        }
1531
1532        let const_keys: Vec<Word> = self.patch_constants.keys().copied().collect();
1533        for fqcn in const_keys {
1534            let Some(target) = self.constants.get(&fqcn) else {
1535                if let Some(p) = self.patch_constants.get_mut(&fqcn) {
1536                    let diag = orphan_patch_constant_diagnostic(p);
1537                    p.issues.push(diag);
1538                }
1539                continue;
1540            };
1541            if target.flags.is_user_defined() {
1542                continue;
1543            }
1544
1545            let mut working = target.clone();
1546            if let Some(patch_entry) = self.patch_constants.get(&fqcn) {
1547                working.apply_patch(patch_entry);
1548            }
1549            self.constants.insert(fqcn, working);
1550        }
1551    }
1552
1553    /// Extracts only the keys that this per-file metadata currently "owns" in the given
1554    /// merged codebase; i.e. keys whose span in `merged` matches this metadata's span.
1555    ///
1556    /// This is what you want for incremental fingerprints. [`extract_keys`](Self::extract_keys)
1557    /// captures *every* key the scan produced, including ones that lost the tiebreak in
1558    /// [`extend`](Self::extend) / [`extend_ref`](Self::extend_ref) when another file defined
1559    /// the same FQN. Using `extract_keys` as a removal fingerprint then causes a nasty
1560    /// cross-file bug: touching file *B* can remove an entry that file *A* actually owns,
1561    /// because [`remove_entries_by_keys`](Self::remove_entries_by_keys) deletes by FQN
1562    /// without checking who the current owner is. The analyzer then reports a spurious
1563    /// "duplicate definition" when it walks *A* and finds *B*'s span in the codebase.
1564    ///
1565    /// By only recording the keys whose spans still match *this* metadata, removing the
1566    /// fingerprint later becomes a safe no-op when another file won the merge. The
1567    /// removal only drops the entries this file genuinely put into the merged codebase.
1568    #[must_use]
1569    pub fn extract_owned_keys(&self, merged: &CodebaseMetadata) -> CodebaseEntryKeys {
1570        let class_like_names = self
1571            .class_likes
1572            .iter()
1573            .filter(|(name, meta)| merged.class_likes.get(*name).is_some_and(|m| m.span == meta.span))
1574            .map(|(name, _)| *name)
1575            .collect();
1576
1577        let class_like_aliases = self
1578            .class_like_alias_declarations
1579            .iter()
1580            .filter(|(name, (_, span, _))| {
1581                merged.class_like_alias_declarations.get(*name).is_some_and(|(_, merged_span, _)| merged_span == span)
1582            })
1583            .map(|(alias, (target, span, _))| (*alias, *target, *span))
1584            .collect();
1585
1586        let function_like_keys = self
1587            .function_likes
1588            .iter()
1589            .filter(|(key, meta)| merged.function_likes.get(*key).is_some_and(|m| m.span == meta.span))
1590            .map(|(key, _)| *key)
1591            .collect();
1592
1593        let constant_names = self
1594            .constants
1595            .iter()
1596            .filter(|(name, meta)| merged.constants.get(*name).is_some_and(|m| m.span == meta.span))
1597            .map(|(name, _)| *name)
1598            .collect();
1599
1600        // A file signature is always owned by its file (there is at most one per file).
1601        let file_ids = self.file_signatures.keys().copied().collect();
1602
1603        CodebaseEntryKeys { class_like_names, class_like_aliases, function_like_keys, constant_names, file_ids }
1604    }
1605
1606    /// Removes entries whose keys match the given [`CodebaseEntryKeys`].
1607    ///
1608    /// This is the lightweight equivalent of [`remove_entries_of()`] — it performs the
1609    /// same removals but from a compact key set instead of a full `CodebaseMetadata` reference.
1610    pub fn remove_entries_by_keys(&mut self, keys: &CodebaseEntryKeys) {
1611        if !keys.class_like_names.is_empty() && !self.class_like_alias_declarations.is_empty() {
1612            self.class_like_aliases_dirty = true;
1613        }
1614
1615        for k in &keys.class_like_names {
1616            self.class_likes.remove(k);
1617            self.symbols.remove(*k);
1618        }
1619
1620        for (alias, _, _) in &keys.class_like_aliases {
1621            self.class_like_alias_declarations.remove(alias);
1622            self.class_like_aliases_dirty = true;
1623        }
1624
1625        for k in &keys.function_like_keys {
1626            self.function_likes.remove(k);
1627        }
1628
1629        for k in &keys.constant_names {
1630            self.constants.remove(k);
1631        }
1632
1633        for k in &keys.file_ids {
1634            self.file_signatures.remove(k);
1635        }
1636
1637        // Drop any patch entry that originated from a file signature we just removed; a patch
1638        // entry's originating file is recorded on its span.
1639        let removed_files: HashSet<FileId> = keys.file_ids.iter().copied().collect();
1640        self.patch_class_likes.retain(|_, m| !removed_files.contains(&m.span.file_id));
1641        self.patch_function_likes.retain(|_, m| !removed_files.contains(&m.span.file_id));
1642        self.patch_constants.retain(|_, m| !removed_files.contains(&m.span.file_id));
1643    }
1644
1645    /// Takes all issues from the codebase metadata.
1646    pub fn take_issues(&mut self, user_defined: bool) -> IssueCollection {
1647        let mut issues = IssueCollection::new();
1648
1649        for meta in self.class_likes.values_mut() {
1650            if user_defined && !meta.flags.is_user_defined() {
1651                continue;
1652            }
1653            issues.extend(meta.take_issues());
1654        }
1655
1656        for meta in self.function_likes.values_mut() {
1657            if user_defined && !meta.flags.is_user_defined() {
1658                continue;
1659            }
1660            issues.extend(meta.take_issues());
1661        }
1662
1663        for meta in self.constants.values_mut() {
1664            if user_defined && !meta.flags.is_user_defined() {
1665                continue;
1666            }
1667            issues.extend(meta.take_issues());
1668        }
1669
1670        // Patches are user-authored, so their issues are always reported regardless of the
1671        // `user_defined` filter. They live in their own maps and never appear in the regular
1672        // class_likes/function_likes/constants iteration above.
1673        for meta in self.patch_class_likes.values_mut() {
1674            issues.extend(meta.take_issues());
1675        }
1676
1677        for meta in self.patch_function_likes.values_mut() {
1678            issues.extend(meta.take_issues());
1679        }
1680
1681        for meta in self.patch_constants.values_mut() {
1682            issues.extend(meta.take_issues());
1683        }
1684
1685        issues
1686    }
1687
1688    /// Gets all file IDs that have signatures in this metadata.
1689    ///
1690    /// This is a helper method for incremental analysis to iterate over all files.
1691    #[must_use]
1692    pub fn get_all_file_ids(&self) -> Vec<FileId> {
1693        self.file_signatures.keys().copied().collect()
1694    }
1695}
1696
1697fn duplicate_patch_class_diagnostic(kept: &ClassLikeMetadata, dropped: &ClassLikeMetadata) -> Issue {
1698    Issue::error(format!(
1699        "Multiple patches target `{}`; at most one patch may target a given symbol.",
1700        kept.original_name
1701    ))
1702    .with_code(ScanningIssueKind::PatchDuplicateTarget)
1703    .with_annotation(Annotation::primary(dropped.span).with_message("Duplicate patch for this symbol."))
1704    .with_annotation(Annotation::secondary(kept.span).with_message("Already patched here."))
1705    .with_help("Merge the conflicting declarations into a single patch, or remove all but one.")
1706}
1707
1708fn duplicate_patch_function_diagnostic(kept: &FunctionLikeMetadata, dropped: &FunctionLikeMetadata) -> Issue {
1709    Issue::error(format!(
1710        "Multiple patches target function `{}`; at most one patch may target a given symbol.",
1711        kept.name
1712    ))
1713    .with_code(ScanningIssueKind::PatchDuplicateTarget)
1714    .with_annotation(Annotation::primary(dropped.span).with_message("Duplicate patch for this function."))
1715    .with_annotation(Annotation::secondary(kept.span).with_message("Already patched here."))
1716    .with_help("Merge the conflicting declarations into a single patch, or remove all but one.")
1717}
1718
1719fn duplicate_patch_constant_diagnostic(kept: &ConstantMetadata, dropped: &ConstantMetadata) -> Issue {
1720    Issue::error(format!(
1721        "Multiple patches target constant `{}`; at most one patch may target a given symbol.",
1722        kept.name
1723    ))
1724    .with_code(ScanningIssueKind::PatchDuplicateTarget)
1725    .with_annotation(Annotation::primary(dropped.span).with_message("Duplicate patch for this constant."))
1726    .with_annotation(Annotation::secondary(kept.span).with_message("Already patched here."))
1727    .with_help("Merge the conflicting declarations into a single patch, or remove all but one.")
1728}
1729
1730fn orphan_patch_class_diagnostic(meta: &ClassLikeMetadata) -> Issue {
1731    Issue::error(format!(
1732        "Patch declares `{}` but no vendored or built-in definition exists to patch.",
1733        meta.original_name,
1734    ))
1735    .with_code(ScanningIssueKind::PatchIntroducesNewSymbol)
1736    .with_annotation(Annotation::primary(meta.span))
1737    .with_help(
1738        "The patch may be misnamed or out-of-date relative to the vendored or built-in definition; \
1739         check the symbol name and verify the patch still matches the upstream source.",
1740    )
1741}
1742
1743fn orphan_patch_function_diagnostic(meta: &FunctionLikeMetadata) -> Issue {
1744    Issue::error(format!(
1745        "Patch declares function `{}` but no vendored or built-in definition exists to patch.",
1746        meta.name,
1747    ))
1748    .with_code(ScanningIssueKind::PatchIntroducesNewSymbol)
1749    .with_annotation(Annotation::primary(meta.span))
1750    .with_help(
1751        "The patch may be misnamed or out-of-date relative to the vendored or built-in definition; \
1752         check the function name and verify the patch still matches the upstream source.",
1753    )
1754}
1755
1756fn orphan_patch_constant_diagnostic(meta: &ConstantMetadata) -> Issue {
1757    Issue::error(format!(
1758        "Patch declares constant `{}` but no vendored or built-in definition exists to patch.",
1759        meta.name,
1760    ))
1761    .with_code(ScanningIssueKind::PatchIntroducesNewSymbol)
1762    .with_annotation(Annotation::primary(meta.span))
1763    .with_help(
1764        "The patch may be misnamed or out-of-date relative to the vendored or built-in definition; \
1765         check the constant name and verify the patch still matches the upstream source.",
1766    )
1767}
1768
1769fn merge_function_likes(
1770    target: &mut HashMap<(Word, Word), Box<FunctionLikeMetadata>>,
1771    incoming: HashMap<(Word, Word), Box<FunctionLikeMetadata>>,
1772) {
1773    for (key, mut metadata) in incoming {
1774        match target.entry(key) {
1775            Entry::Occupied(mut entry) => {
1776                if should_replace_metadata(entry.get().flags, entry.get().span, metadata.flags, metadata.span) {
1777                    metadata.version_constraint.merge(entry.get().version_constraint.clone());
1778                    entry.insert(metadata);
1779                } else {
1780                    entry.get_mut().version_constraint.merge(metadata.version_constraint);
1781                }
1782            }
1783            Entry::Vacant(entry) => {
1784                entry.insert(metadata);
1785            }
1786        }
1787    }
1788}
1789
1790/// Determines which metadata value to keep when merging duplicates.
1791///
1792/// Priority:
1793///   1. user-defined > patch > external > built-in > other.
1794///   2. non-polyfill > polyfill — tools like rector/phpstan/psalm ship
1795///      skeleton stubs gated by `if (!class_exists('X'))` that should never
1796///      shadow a concrete definition.
1797///   3. smaller span wins as a deterministic tie-breaker.
1798///
1799/// Returns `true` if the new value should replace the existing one.
1800fn should_replace_metadata(
1801    existing_flags: MetadataFlags,
1802    existing_span: Span,
1803    new_flags: MetadataFlags,
1804    new_span: Span,
1805) -> bool {
1806    let new_is_user_defined = new_flags.is_user_defined();
1807    let existing_is_user_defined = existing_flags.is_user_defined();
1808
1809    if new_is_user_defined != existing_is_user_defined {
1810        return new_is_user_defined;
1811    }
1812
1813    let new_is_patch = new_flags.is_patch();
1814    let existing_is_patch = existing_flags.is_patch();
1815
1816    if new_is_patch != existing_is_patch {
1817        return new_is_patch;
1818    }
1819
1820    let new_is_external = new_flags.is_external();
1821    let existing_is_external = existing_flags.is_external();
1822
1823    if new_is_external != existing_is_external {
1824        return new_is_external;
1825    }
1826
1827    let new_is_built_in = new_flags.is_built_in();
1828    let existing_is_built_in = existing_flags.is_built_in();
1829
1830    if new_is_built_in != existing_is_built_in {
1831        return new_is_built_in;
1832    }
1833
1834    let new_is_polyfill = new_flags.is_polyfill();
1835    let existing_is_polyfill = existing_flags.is_polyfill();
1836
1837    if new_is_polyfill != existing_is_polyfill {
1838        return !new_is_polyfill;
1839    }
1840
1841    new_span < existing_span
1842}
1843
1844#[cfg(test)]
1845mod should_replace_metadata_tests {
1846    use super::*;
1847
1848    #[test]
1849    fn replacing_file_signatures_keeps_map_capacity() {
1850        let mut codebase = CodebaseMetadata::new();
1851        codebase.file_signatures.reserve(3);
1852        let capacity = codebase.file_signatures.capacity();
1853        for index in 0..capacity {
1854            codebase.set_file_signature(FileId::new(format!("{index}.php").as_bytes()), FileSignature::default());
1855        }
1856
1857        let file_id = FileId::new(b"0.php");
1858
1859        for hash in 1..=3 {
1860            let mut incoming = CodebaseMetadata::new();
1861            incoming.set_file_signature(file_id, FileSignature { hash, ..FileSignature::default() });
1862            codebase.extend(incoming);
1863            assert_eq!(codebase.file_signatures.len(), capacity);
1864            assert_eq!(codebase.file_signatures.capacity(), capacity);
1865            assert_eq!(codebase.file_signatures[&file_id].hash, hash);
1866        }
1867    }
1868
1869    #[test]
1870    fn non_polyfill_replaces_polyfill() {
1871        let polyfill = MetadataFlags::POLYFILL;
1872        let real = MetadataFlags::empty();
1873        assert!(should_replace_metadata(polyfill, Span::dummy(0, 100), real, Span::dummy(0, 100)));
1874        assert!(!should_replace_metadata(real, Span::dummy(0, 100), polyfill, Span::dummy(0, 100)));
1875    }
1876
1877    #[test]
1878    fn polyfill_does_not_replace_non_polyfill_even_with_smaller_span() {
1879        let real = MetadataFlags::empty();
1880        let polyfill = MetadataFlags::POLYFILL;
1881        assert!(!should_replace_metadata(real, Span::dummy(500, 600), polyfill, Span::dummy(0, 10)));
1882    }
1883
1884    #[test]
1885    fn user_defined_beats_polyfill_flag() {
1886        let polyfill_user = MetadataFlags::POLYFILL | MetadataFlags::USER_DEFINED;
1887        let plain = MetadataFlags::empty();
1888        assert!(!should_replace_metadata(polyfill_user, Span::dummy(0, 10), plain, Span::dummy(0, 10)));
1889        assert!(should_replace_metadata(plain, Span::dummy(0, 10), polyfill_user, Span::dummy(0, 10)));
1890    }
1891
1892    #[test]
1893    fn two_user_defined_fall_through_to_polyfill_check() {
1894        let a = MetadataFlags::POLYFILL | MetadataFlags::USER_DEFINED;
1895        let b = MetadataFlags::USER_DEFINED;
1896        assert!(should_replace_metadata(a, Span::dummy(0, 10), b, Span::dummy(0, 10)));
1897        assert!(!should_replace_metadata(b, Span::dummy(0, 10), a, Span::dummy(0, 10)));
1898    }
1899
1900    #[test]
1901    fn two_non_polyfills_fall_through_to_priority_rules() {
1902        let user = MetadataFlags::USER_DEFINED;
1903        let builtin = MetadataFlags::BUILTIN;
1904        assert!(!should_replace_metadata(user, Span::dummy(0, 10), builtin, Span::dummy(0, 10)));
1905        assert!(should_replace_metadata(builtin, Span::dummy(0, 10), user, Span::dummy(0, 10)));
1906    }
1907
1908    #[test]
1909    fn patch_beats_vendored() {
1910        let vendored = MetadataFlags::empty();
1911        let patch = MetadataFlags::PATCH;
1912        assert!(should_replace_metadata(vendored, Span::dummy(0, 100), patch, Span::dummy(0, 100)));
1913        assert!(!should_replace_metadata(patch, Span::dummy(0, 100), vendored, Span::dummy(0, 100)));
1914    }
1915
1916    #[test]
1917    fn patch_beats_builtin() {
1918        let builtin = MetadataFlags::BUILTIN;
1919        let patch = MetadataFlags::PATCH;
1920        assert!(should_replace_metadata(builtin, Span::dummy(0, 100), patch, Span::dummy(0, 100)));
1921        assert!(!should_replace_metadata(patch, Span::dummy(0, 100), builtin, Span::dummy(0, 100)));
1922    }
1923
1924    #[test]
1925    fn external_beats_builtin_and_vendored() {
1926        let external = MetadataFlags::EXTERNAL;
1927        let builtin = MetadataFlags::BUILTIN;
1928        let vendored = MetadataFlags::empty();
1929
1930        assert!(should_replace_metadata(builtin, Span::dummy(0, 100), external, Span::dummy(500, 600)));
1931        assert!(!should_replace_metadata(external, Span::dummy(500, 600), builtin, Span::dummy(0, 100)));
1932        assert!(should_replace_metadata(vendored, Span::dummy(0, 100), external, Span::dummy(500, 600)));
1933        assert!(!should_replace_metadata(external, Span::dummy(500, 600), vendored, Span::dummy(0, 100)));
1934    }
1935
1936    #[test]
1937    fn patch_and_user_defined_beat_external() {
1938        let external = MetadataFlags::EXTERNAL;
1939        let patch = MetadataFlags::PATCH;
1940        let user = MetadataFlags::USER_DEFINED;
1941
1942        assert!(should_replace_metadata(external, Span::dummy(0, 100), patch, Span::dummy(500, 600)));
1943        assert!(!should_replace_metadata(patch, Span::dummy(500, 600), external, Span::dummy(0, 100)));
1944        assert!(should_replace_metadata(external, Span::dummy(0, 100), user, Span::dummy(500, 600)));
1945        assert!(!should_replace_metadata(user, Span::dummy(500, 600), external, Span::dummy(0, 100)));
1946    }
1947
1948    #[test]
1949    fn user_defined_beats_patch() {
1950        let user = MetadataFlags::USER_DEFINED;
1951        let patch = MetadataFlags::PATCH;
1952        assert!(!should_replace_metadata(user, Span::dummy(0, 100), patch, Span::dummy(0, 100)));
1953        assert!(should_replace_metadata(patch, Span::dummy(0, 100), user, Span::dummy(0, 100)));
1954    }
1955
1956    #[test]
1957    fn patch_does_not_beat_user_defined_even_with_smaller_span() {
1958        let user = MetadataFlags::USER_DEFINED;
1959        let patch = MetadataFlags::PATCH;
1960        assert!(!should_replace_metadata(user, Span::dummy(500, 600), patch, Span::dummy(0, 10)));
1961    }
1962
1963    #[test]
1964    #[allow(clippy::expect_used)]
1965    fn patch_function_like_leaves_vendor_owning_slot() {
1966        // Patches may only refine types and supported flags on an existing function-like; they
1967        // must never become the slot owner. The non-patch source's span/file id stay put so that
1968        // `extract_owned_keys` records vendor-as-owner — otherwise the patch's entry would
1969        // outlive a vendor deletion in incremental mode (orphan function-like bug).
1970        use crate::metadata::function_like::FunctionLikeKind;
1971
1972        let name = word("foo");
1973        let key = (empty_word(), name);
1974        let vendor_span = Span::dummy(0, 100);
1975        let patch_span = Span::dummy(500, 600);
1976
1977        let vendor =
1978            FunctionLikeMetadata::new(FunctionLikeKind::Function, name, name, vendor_span, MetadataFlags::empty());
1979        let mut codebase = CodebaseMetadata::new();
1980        codebase.function_likes.insert(key, Box::new(vendor));
1981
1982        let patch = FunctionLikeMetadata::new(FunctionLikeKind::Function, name, name, patch_span, MetadataFlags::PATCH);
1983        codebase.patch_function_likes.insert(key, Box::new(patch));
1984
1985        codebase.apply_patches_pass();
1986
1987        let merged = codebase.function_likes.get(&key).expect("function-like must remain after patch");
1988        assert_eq!(merged.span, vendor_span, "patch must not move the slot's span");
1989        assert!(!merged.flags.is_patch(), "patch must not flip the slot's flags");
1990    }
1991
1992    #[test]
1993    fn patch_does_not_apply_to_user_defined_class() {
1994        let class_name = word("MyClass");
1995        let method_existing = word("doIt");
1996
1997        let mut user_class =
1998            ClassLikeMetadata::new(class_name, class_name, Span::dummy(0, 100), None, MetadataFlags::USER_DEFINED);
1999        user_class.methods.insert(method_existing);
2000
2001        let mut codebase = CodebaseMetadata::new();
2002        codebase.class_likes.insert(class_name, Box::new(user_class));
2003
2004        let mut patch_class =
2005            ClassLikeMetadata::new(class_name, class_name, Span::dummy(0, 50), None, MetadataFlags::PATCH);
2006        let method_new = word("patchedMethod");
2007        patch_class.methods.insert(method_new);
2008
2009        codebase.patch_class_likes.insert(class_name, Box::new(patch_class));
2010
2011        codebase.apply_patches_pass();
2012
2013        let class = &codebase.class_likes[&class_name];
2014        // Patch must not apply to a user-defined class.
2015        assert!(!class.methods.contains(&method_new));
2016        // User-defined class must be preserved intact.
2017        assert!(class.methods.contains(&method_existing));
2018        assert!(class.flags.is_user_defined());
2019        // No issues should be emitted.
2020        assert!(class.issues.is_empty());
2021    }
2022}