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