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                .or_else(|| constant_meta.type_metadata.as_ref().map(|type_metadata| type_metadata.type_union.clone()))
715                .unwrap_or_else(get_mixed)
716        };
717
718        expand_union(
719            self,
720            &mut constant_type,
721            &TypeExpansionOptions {
722                self_class: Some(class_meta.name),
723                static_class_type: StaticClassType::Name(class_meta.name),
724                function_is_final: class_meta.flags.is_final(),
725                ..Default::default()
726            },
727        );
728
729        constant_type
730    }
731    // Inheritance Queries
732
733    /// Checks if a child class extends a parent class (case-insensitive).
734    #[inline]
735    #[must_use]
736    pub fn class_extends(&self, child: &[u8], parent: &[u8]) -> bool {
737        let lowercase_child = ascii_lowercase_word(child);
738        let lowercase_parent = ascii_lowercase_word(parent);
739        let Some(metadata) = self.get_class_like_by_word(lowercase_child) else {
740            return false;
741        };
742
743        if metadata.all_parent_classes.contains(&lowercase_parent) {
744            return true;
745        }
746
747        if self.class_like_aliases.is_empty() || self.class_likes.contains_key(&lowercase_parent) {
748            return false;
749        }
750
751        self.class_like_aliases
752            .get(&lowercase_parent)
753            .is_some_and(|actual| metadata.all_parent_classes.contains(actual))
754    }
755
756    /// Checks if a class implements an interface (case-insensitive).
757    #[inline]
758    #[must_use]
759    pub fn class_implements(&self, class: &[u8], interface: &[u8]) -> bool {
760        let lowercase_class = ascii_lowercase_word(class);
761        let lowercase_interface = ascii_lowercase_word(interface);
762        let Some(metadata) = self.get_class_like_by_word(lowercase_class) else {
763            return false;
764        };
765
766        if metadata.all_parent_interfaces.contains(&lowercase_interface) {
767            return true;
768        }
769
770        if self.class_like_aliases.is_empty() || self.class_likes.contains_key(&lowercase_interface) {
771            return false;
772        }
773
774        self.class_like_aliases
775            .get(&lowercase_interface)
776            .is_some_and(|actual| metadata.all_parent_interfaces.contains(actual))
777    }
778
779    /// Checks if a class uses a trait (case-insensitive).
780    #[inline]
781    #[must_use]
782    pub fn class_uses_trait(&self, class: &[u8], trait_name: &[u8]) -> bool {
783        let lowercase_class = ascii_lowercase_word(class);
784        let lowercase_trait = ascii_lowercase_word(trait_name);
785        let Some(metadata) = self.get_class_like_by_word(lowercase_class) else {
786            return false;
787        };
788
789        if metadata.used_traits.contains(&lowercase_trait) {
790            return true;
791        }
792
793        if self.class_like_aliases.is_empty() || self.class_likes.contains_key(&lowercase_trait) {
794            return false;
795        }
796
797        self.class_like_aliases.get(&lowercase_trait).is_some_and(|actual| metadata.used_traits.contains(actual))
798    }
799
800    /// Checks if child is an instance of parent (via extends or implements).
801    #[inline]
802    #[must_use]
803    pub fn is_instance_of(&self, child: &[u8], parent: &[u8]) -> bool {
804        if child == parent {
805            return true;
806        }
807
808        let lowercase_child = ascii_lowercase_word(child);
809        let lowercase_parent = ascii_lowercase_word(parent);
810
811        if lowercase_child == lowercase_parent {
812            return true;
813        }
814
815        let Some(metadata) = self.get_class_like_by_word(lowercase_child) else {
816            return false;
817        };
818
819        let matches = |parent| {
820            metadata.name == parent
821                || metadata.all_parent_classes.contains(&parent)
822                || metadata.all_parent_interfaces.contains(&parent)
823                || metadata.used_traits.contains(&parent)
824                || metadata.require_extends.contains(&parent)
825                || metadata.require_implements.contains(&parent)
826        };
827
828        if matches(lowercase_parent) {
829            return true;
830        }
831
832        if self.class_like_aliases.is_empty() || self.class_likes.contains_key(&lowercase_parent) {
833            return false;
834        }
835
836        self.class_like_aliases.get(&lowercase_parent).is_some_and(|actual| matches(*actual))
837    }
838
839    /// Checks if the given name is an enum or final class.
840    #[inline]
841    #[must_use]
842    pub fn is_enum_or_final_class(&self, name: &[u8]) -> bool {
843        let lowercase_name = ascii_lowercase_word(name);
844        self.get_class_like_by_word(lowercase_name).is_some_and(|meta| meta.kind.is_enum() || meta.flags.is_final())
845    }
846
847    /// Checks if a class-like can be part of an intersection.
848    /// Generally, only final classes and enums cannot be intersected.
849    #[inline]
850    #[must_use]
851    pub fn is_inheritable(&self, name: &[u8]) -> bool {
852        let lowercase_name = ascii_lowercase_word(name);
853        match self.symbols.get_kind(lowercase_name) {
854            Some(SymbolKind::Class) => {
855                self.get_class_like_by_word(lowercase_name).is_some_and(|meta| !meta.flags.is_final())
856            }
857            Some(SymbolKind::Enum) => false,
858            Some(SymbolKind::Interface | SymbolKind::Trait) | None => true,
859        }
860    }
861
862    /// Gets all descendants of a class (recursive).
863    #[inline]
864    #[must_use]
865    pub fn get_class_descendants(&self, class: &[u8]) -> WordSet {
866        let lowercase_class = ascii_lowercase_word(class);
867        let lowercase_class = self.resolve_class_like_word(lowercase_class).unwrap_or(lowercase_class);
868        let mut all_descendants = WordSet::default();
869        let mut queue = vec![&lowercase_class];
870        let mut visited = WordSet::default();
871        visited.insert(lowercase_class);
872
873        while let Some(current_name) = queue.pop() {
874            if let Some(direct_descendants) = self.direct_classlike_descendants.get(current_name) {
875                for descendant in direct_descendants {
876                    if visited.insert(*descendant) {
877                        all_descendants.insert(*descendant);
878                        queue.push(descendant);
879                    }
880                }
881            }
882        }
883
884        all_descendants
885    }
886
887    /// Gets all ancestors of a class (parents + interfaces).
888    #[inline]
889    #[must_use]
890    pub fn get_class_ancestors(&self, class: &[u8]) -> WordSet {
891        let lowercase_class = ascii_lowercase_word(class);
892        let mut ancestors = WordSet::default();
893        if let Some(meta) = self.get_class_like_by_word(lowercase_class) {
894            ancestors.extend(meta.all_parent_classes.iter().copied());
895            ancestors.extend(meta.all_parent_interfaces.iter().copied());
896        }
897        ancestors
898    }
899
900    /// Gets the class where a method is declared (following inheritance).
901    #[inline]
902    #[must_use]
903    pub fn get_declaring_method_class(&self, class: &[u8], method: &[u8]) -> Option<Word> {
904        self.get_declaring_method_class_by_id(&MethodIdentifier::new(
905            ascii_lowercase_word(class),
906            ascii_lowercase_word(method),
907        ))
908    }
909
910    /// Gets the declaring class of an interned method name, ignoring ASCII case.
911    #[inline]
912    #[must_use]
913    pub fn get_declaring_method_class_by_id(&self, method: &MethodIdentifier) -> Option<Word> {
914        let lowercase_class = method.get_class_name().to_ascii_lowercase();
915        let lowercase_method = method.get_method_name().to_ascii_lowercase();
916
917        self.get_class_like_by_word(lowercase_class)?
918            .declaring_method_ids
919            .get(&lowercase_method)
920            .map(|method_id| method_id.get_class_name())
921    }
922
923    /// Gets the declaring method identifier for a method.
924    #[must_use]
925    pub fn get_declaring_method_identifier(&self, method_id: &MethodIdentifier) -> MethodIdentifier {
926        let lowercase_class = method_id.get_class_name().to_ascii_lowercase();
927        let lowercase_method = method_id.get_method_name().to_ascii_lowercase();
928
929        let Some(class_meta) = self.get_class_like_by_word(lowercase_class) else {
930            return *method_id;
931        };
932
933        if let Some(declaring_method_id) = class_meta.declaring_method_ids.get(&lowercase_method) {
934            return *declaring_method_id;
935        }
936
937        if class_meta.flags.is_abstract()
938            && let Some(overridden_map) = class_meta.overridden_method_ids.get(&lowercase_method)
939            && let Some((_, first_method_id)) = overridden_map.first()
940        {
941            return *first_method_id;
942        }
943
944        *method_id
945    }
946
947    /// Checks if a method is overriding a parent method.
948    #[inline]
949    #[must_use]
950    pub fn method_is_overriding(&self, class: &[u8], method: &[u8]) -> bool {
951        let lowercase_class = ascii_lowercase_word(class);
952        let lowercase_method = ascii_lowercase_word(method);
953        self.get_class_like_by_word(lowercase_class)
954            .is_some_and(|meta| meta.overridden_method_ids.contains_key(&lowercase_method))
955    }
956
957    /// Checks if a method is abstract.
958    #[inline]
959    #[must_use]
960    pub fn method_is_abstract(&self, class: &[u8], method: &[u8]) -> bool {
961        let lowercase_class = ascii_lowercase_word(class);
962        let lowercase_method = ascii_lowercase_word(method);
963        self.get_method_by_words(lowercase_class, lowercase_method)
964            .and_then(|meta| meta.method_metadata.as_ref())
965            .is_some_and(|method_meta| method_meta.is_abstract)
966    }
967
968    /// Checks if a method is final.
969    #[inline]
970    #[must_use]
971    pub fn method_is_final(&self, class: &[u8], method: &[u8]) -> bool {
972        let lowercase_class = ascii_lowercase_word(class);
973        let lowercase_method = ascii_lowercase_word(method);
974        let Some(class) = self.get_class_like_by_word(lowercase_class) else { return false };
975        let declaring = self.get_declaring_method_identifier(&MethodIdentifier::new(lowercase_class, lowercase_method));
976        self.get_method_by_id(&declaring)
977            .and_then(|meta| meta.method_metadata.as_ref())
978            .is_some_and(|method| method.is_final)
979            || self.effective_trait_method_modifiers(class, lowercase_method, declaring).is_final
980    }
981
982    /// Gets a method's visibility through inheritance and trait adaptations.
983    /// The nearest visibility adaptation wins; otherwise the source declaration supplies it.
984    #[inline]
985    #[must_use]
986    pub fn get_method_visibility(&self, class: &[u8], method: &[u8]) -> Option<Visibility> {
987        self.get_method_visibility_by_id(&MethodIdentifier::new(
988            ascii_lowercase_word(class),
989            ascii_lowercase_word(method),
990        ))
991    }
992
993    /// Gets a method's visibility from interned names, including trait visibility overrides.
994    #[inline]
995    #[must_use]
996    pub fn get_method_visibility_by_id(&self, method: &MethodIdentifier) -> Option<Visibility> {
997        let lowercase_class = method.get_class_name().to_ascii_lowercase();
998        let lowercase_method = method.get_method_name().to_ascii_lowercase();
999        let class_meta = self.get_class_like_by_word(lowercase_class)?;
1000
1001        let declaring = *class_meta.declaring_method_ids.get(&lowercase_method)?;
1002        self.effective_trait_method_modifiers(class_meta, lowercase_method, declaring).visibility.or_else(|| {
1003            self.get_method_by_id(&declaring)
1004                .and_then(|meta| meta.method_metadata.as_ref())
1005                .map(|method| method.visibility)
1006        })
1007    }
1008
1009    /// Gets thrown types for a function-like, including inherited throws.
1010    #[must_use]
1011    pub fn get_function_like_thrown_types<'meta>(
1012        &'meta self,
1013        class_like: Option<&'meta ClassLikeMetadata>,
1014        function_like: &'meta FunctionLikeMetadata,
1015    ) -> &'meta [TypeMetadata] {
1016        if !function_like.thrown_types.is_empty() {
1017            return function_like.thrown_types.as_slice();
1018        }
1019
1020        if !function_like.kind.is_method() {
1021            return &[];
1022        }
1023
1024        let Some(class_like) = class_like else {
1025            return &[];
1026        };
1027
1028        let method_name = &function_like.name;
1029
1030        if let Some(overridden_map) = class_like.overridden_method_ids.get(method_name) {
1031            for (parent_class_name, parent_method_id) in overridden_map.iter() {
1032                if class_like.name.as_bytes().eq_ignore_ascii_case(parent_class_name.as_bytes()) {
1033                    continue; // Skip self-recursion if the method overrides itself
1034                }
1035
1036                let Some(parent_class) = self.class_likes.get(parent_class_name) else {
1037                    continue;
1038                };
1039
1040                let parent_method_key = (parent_method_id.get_class_name(), parent_method_id.get_method_name());
1041                if let Some(parent_method) = self.function_likes.get(&parent_method_key) {
1042                    let thrown = self.get_function_like_thrown_types(Some(parent_class), parent_method);
1043                    if !thrown.is_empty() {
1044                        return thrown;
1045                    }
1046                }
1047            }
1048        }
1049
1050        &[]
1051    }
1052
1053    /// Gets the class where a property is declared.
1054    /// Sees real declarations only; magic `@property*` tags are reachable through
1055    /// `ClassLikeMetadata::magic_property_ids`.
1056    #[inline]
1057    #[must_use]
1058    pub fn get_declaring_property_class(&self, class: &[u8], property: &[u8]) -> Option<Word> {
1059        let lowercase_class = ascii_lowercase_word(class);
1060        let property_name = word(property);
1061        self.get_class_like_by_word(lowercase_class)?.declaring_property_ids.get(&property_name).copied()
1062    }
1063
1064    /// Gets all descendants of a class (recursive).
1065    #[must_use]
1066    pub fn get_all_descendants(&self, class: &[u8]) -> WordSet {
1067        let lowercase_class = ascii_lowercase_word(class);
1068        let lowercase_class = self.resolve_class_like_word(lowercase_class).unwrap_or(lowercase_class);
1069        let mut all_descendants = WordSet::default();
1070        let mut queue = vec![&lowercase_class];
1071        let mut visited = WordSet::default();
1072        visited.insert(lowercase_class);
1073
1074        while let Some(current_name) = queue.pop() {
1075            if let Some(direct_descendants) = self.direct_classlike_descendants.get(current_name) {
1076                for descendant in direct_descendants {
1077                    if visited.insert(*descendant) {
1078                        all_descendants.insert(*descendant);
1079                        queue.push(descendant);
1080                    }
1081                }
1082            }
1083        }
1084
1085        all_descendants
1086    }
1087
1088    /// Generates the synthetic display name for an anonymous class based on
1089    /// its declaring file and span. Delegates to [`crate::get_anonymous_class_name`].
1090    #[must_use]
1091    pub fn get_anonymous_class_name(file: &File, span: Span) -> Word {
1092        crate::get_anonymous_class_name(file, span)
1093    }
1094
1095    /// Retrieves the metadata for an anonymous class based on its declaring
1096    /// file and span.
1097    #[must_use]
1098    pub fn get_anonymous_class(&self, file: &File, span: Span) -> Option<&ClassLikeMetadata> {
1099        let name = Self::get_anonymous_class_name(file, span);
1100        self.get_class_like_by_name(name)
1101    }
1102
1103    /// Gets the file signature for a given file ID.
1104    ///
1105    /// # Arguments
1106    ///
1107    /// * `file_id` - The file identifier
1108    ///
1109    /// # Returns
1110    ///
1111    /// A reference to the `FileSignature` if it exists, or `None` if the file has no signature.
1112    #[inline]
1113    #[must_use]
1114    pub fn get_file_signature(&self, file_id: &FileId) -> Option<&FileSignature> {
1115        self.file_signatures.get(file_id)
1116    }
1117
1118    /// Adds or updates a file signature for a given file ID.
1119    ///
1120    /// # Arguments
1121    ///
1122    /// * `file_id` - The file identifier
1123    /// * `signature` - The file signature
1124    ///
1125    /// # Returns
1126    ///
1127    /// The previous `FileSignature` if it existed.
1128    #[inline]
1129    pub fn set_file_signature(&mut self, file_id: FileId, signature: FileSignature) -> Option<FileSignature> {
1130        self.file_signatures.insert(file_id, signature)
1131    }
1132
1133    /// Marks safe symbols based on diff and invalidation cascade.
1134    ///
1135    /// After this function runs, `self.safe_symbols` and `self.safe_symbol_members`
1136    /// will contain all symbols that can be safely skipped during analysis.
1137    ///
1138    /// # Arguments
1139    ///
1140    /// * `diff` - The computed diff between old and new code
1141    /// * `references` - Symbol reference graph from previous run
1142    ///
1143    /// # Returns
1144    /// Returns the logical names of files whose top-level code references an invalidated
1145    /// symbol. Returns `None` if the cascade was too large to compute.
1146    pub fn mark_safe_symbols(&mut self, diff: &CodebaseDiff, references: &SymbolReferences) -> Option<WordSet> {
1147        let (invalid_symbols, partially_invalid, invalid_files) = references.get_invalid_symbols(diff)?;
1148
1149        // Mark all symbols in 'keep' set as safe (unless invalidated by cascade)
1150        for keep_symbol in diff.get_keep() {
1151            if !invalid_symbols.contains(keep_symbol) {
1152                if keep_symbol.1.is_empty() {
1153                    // Top-level symbol (class, function, constant)
1154                    if !partially_invalid.contains(&keep_symbol.0) {
1155                        self.safe_symbols.insert(keep_symbol.0);
1156                    }
1157                } else {
1158                    // Member (method, property, class constant)
1159                    self.safe_symbol_members.insert(*keep_symbol);
1160                }
1161            }
1162        }
1163
1164        Some(invalid_files)
1165    }
1166
1167    /// Merges information from another `CodebaseMetadata` into this one.
1168    ///
1169    /// When both metadata have the same priority, the one with the smaller span is kept
1170    /// for deterministic results regardless of scan order.
1171    pub fn extend(&mut self, other: CodebaseMetadata) {
1172        let class_likes_changed = !other.class_likes.is_empty();
1173        for (k, mut v) in other.class_likes {
1174            match self.class_likes.entry(k) {
1175                Entry::Occupied(mut entry) => {
1176                    if should_replace_metadata(entry.get().flags, entry.get().span, v.flags, v.span) {
1177                        v.version_constraint.merge(entry.get().version_constraint.clone());
1178                        entry.insert(v);
1179                    } else {
1180                        entry.get_mut().version_constraint.merge(v.version_constraint);
1181                    }
1182                }
1183                Entry::Vacant(entry) => {
1184                    entry.insert(v);
1185                }
1186            }
1187        }
1188
1189        if class_likes_changed && !self.class_like_alias_declarations.is_empty() {
1190            self.class_like_aliases_dirty = true;
1191        }
1192
1193        self.merge_class_like_alias_declarations(other.class_like_alias_declarations);
1194
1195        merge_function_likes(&mut self.function_likes, other.function_likes);
1196
1197        for (k, mut v) in other.constants {
1198            match self.constants.entry(k) {
1199                Entry::Occupied(mut entry) => {
1200                    let combined_type = combine_defined_constant_types(entry.get(), &v);
1201                    if should_replace_metadata(entry.get().flags, entry.get().span, v.flags, v.span) {
1202                        v.version_constraint.merge(entry.get().version_constraint.clone());
1203                        entry.insert(v);
1204                    } else {
1205                        entry.get_mut().version_constraint.merge(v.version_constraint);
1206                    }
1207
1208                    if combined_type.is_some() {
1209                        entry.get_mut().inferred_type = combined_type;
1210                    }
1211                }
1212                Entry::Vacant(entry) => {
1213                    entry.insert(v);
1214                }
1215            }
1216        }
1217
1218        self.symbols.extend(other.symbols);
1219
1220        for (k, v) in other.all_class_like_descendants {
1221            self.all_class_like_descendants.entry(k).or_default().extend(v);
1222        }
1223
1224        for (k, v) in other.direct_classlike_descendants {
1225            self.direct_classlike_descendants.entry(k).or_default().extend(v);
1226        }
1227
1228        for (file_id, signature) in other.file_signatures {
1229            self.file_signatures.entry(file_id).insert_entry(signature);
1230        }
1231
1232        self.safe_symbols.extend(other.safe_symbols);
1233        self.safe_symbol_members.extend(other.safe_symbol_members);
1234        self.infer_types_from_usage |= other.infer_types_from_usage;
1235        self.merge_patch_class_likes(other.patch_class_likes);
1236        self.merge_patch_function_likes(other.patch_function_likes);
1237        self.merge_patch_constants(other.patch_constants);
1238    }
1239
1240    /// Merges file metadata in order, with function metadata on a separate worker.
1241    pub fn extend_many_parallel(&mut self, mut others: Vec<Self>) {
1242        if others.len() < 128 || rayon::current_num_threads() == 1 {
1243            for other in others {
1244                self.extend(other);
1245            }
1246            return;
1247        }
1248
1249        let mut function_likes = std::mem::take(&mut self.function_likes);
1250        let mut symbols = std::mem::take(&mut self.symbols);
1251        let (functions, partial_symbols): (Vec<_>, Vec<_>) = others
1252            .par_iter_mut()
1253            .map(|other| (std::mem::take(&mut other.function_likes), std::mem::take(&mut other.symbols)))
1254            .unzip();
1255        rayon::join(
1256            || {
1257                function_likes.reserve(functions.iter().map(HashMap::len).sum());
1258                for incoming in functions {
1259                    merge_function_likes(&mut function_likes, incoming);
1260                }
1261                function_likes.shrink_to_fit();
1262            },
1263            || {
1264                rayon::join(
1265                    || {
1266                        for incoming in partial_symbols {
1267                            symbols.extend(incoming);
1268                        }
1269                    },
1270                    || {
1271                        for other in others {
1272                            self.extend(other);
1273                        }
1274                    },
1275                );
1276            },
1277        );
1278        self.function_likes = function_likes;
1279        self.symbols = symbols;
1280    }
1281
1282    /// Extends this codebase with another by reference, cloning only individual entries.
1283    ///
1284    /// This is more efficient than `extend(other.clone())` because it avoids allocating
1285    /// a full clone of the source metadata's outer HashMap/WordMap structures. Only
1286    /// individual entries that need insertion are cloned.
1287    pub fn extend_ref(&mut self, other: &CodebaseMetadata) {
1288        let class_likes_changed = !other.class_likes.is_empty();
1289        for (k, v) in &other.class_likes {
1290            match self.class_likes.entry(*k) {
1291                Entry::Occupied(mut entry) => {
1292                    if should_replace_metadata(entry.get().flags, entry.get().span, v.flags, v.span) {
1293                        let mut new = v.clone();
1294                        new.version_constraint.merge(entry.get().version_constraint.clone());
1295                        entry.insert(new);
1296                    } else {
1297                        entry.get_mut().version_constraint.merge(v.version_constraint.clone());
1298                    }
1299                }
1300                Entry::Vacant(entry) => {
1301                    entry.insert(v.clone());
1302                }
1303            }
1304        }
1305
1306        if class_likes_changed && !self.class_like_alias_declarations.is_empty() {
1307            self.class_like_aliases_dirty = true;
1308        }
1309
1310        self.merge_class_like_alias_declarations(
1311            other.class_like_alias_declarations.iter().map(|(alias, declaration)| (*alias, *declaration)),
1312        );
1313
1314        for (k, v) in &other.function_likes {
1315            match self.function_likes.entry(*k) {
1316                Entry::Occupied(mut entry) => {
1317                    if should_replace_metadata(entry.get().flags, entry.get().span, v.flags, v.span) {
1318                        let mut new = v.clone();
1319                        new.version_constraint.merge(entry.get().version_constraint.clone());
1320                        entry.insert(new);
1321                    } else {
1322                        entry.get_mut().version_constraint.merge(v.version_constraint.clone());
1323                    }
1324                }
1325                Entry::Vacant(entry) => {
1326                    entry.insert(v.clone());
1327                }
1328            }
1329        }
1330
1331        for (k, v) in &other.constants {
1332            match self.constants.entry(*k) {
1333                Entry::Occupied(mut entry) => {
1334                    let combined_type = combine_defined_constant_types(entry.get(), v);
1335                    if should_replace_metadata(entry.get().flags, entry.get().span, v.flags, v.span) {
1336                        let mut new = v.clone();
1337                        new.version_constraint.merge(entry.get().version_constraint.clone());
1338                        entry.insert(new);
1339                    } else {
1340                        entry.get_mut().version_constraint.merge(v.version_constraint.clone());
1341                    }
1342
1343                    if combined_type.is_some() {
1344                        entry.get_mut().inferred_type = combined_type;
1345                    }
1346                }
1347                Entry::Vacant(entry) => {
1348                    entry.insert(v.clone());
1349                }
1350            }
1351        }
1352
1353        self.symbols.extend_ref(&other.symbols);
1354
1355        for (k, v) in &other.all_class_like_descendants {
1356            self.all_class_like_descendants.entry(*k).or_default().extend(v.iter().copied());
1357        }
1358
1359        for (k, v) in &other.direct_classlike_descendants {
1360            self.direct_classlike_descendants.entry(*k).or_default().extend(v.iter().copied());
1361        }
1362
1363        for (k, v) in &other.file_signatures {
1364            self.file_signatures.insert(*k, v.clone());
1365        }
1366        self.safe_symbols.extend(other.safe_symbols.iter().copied());
1367        self.safe_symbol_members.extend(other.safe_symbol_members.iter().copied());
1368        self.infer_types_from_usage |= other.infer_types_from_usage;
1369        self.merge_patch_class_likes(other.patch_class_likes.iter().map(|(k, v)| (*k, v.clone())));
1370        self.merge_patch_function_likes(other.patch_function_likes.iter().map(|(k, v)| (*k, v.clone())));
1371        self.merge_patch_constants(other.patch_constants.iter().map(|(k, v)| (*k, v.clone())));
1372    }
1373
1374    fn merge_class_like_alias_declarations(
1375        &mut self,
1376        declarations: impl IntoIterator<Item = (Word, (Word, Span, MetadataFlags))>,
1377    ) {
1378        for (alias, (target, span, flags)) in declarations {
1379            self.add_class_like_alias(alias, target, span, flags);
1380        }
1381    }
1382
1383    /// Merges patch class-likes from another codebase, diagnosing collisions.
1384    ///
1385    /// At most one patch may target a given symbol. When two patches collide, the first-merged
1386    /// entry is kept and a [`PatchDuplicateTarget`](ScanningIssueKind::PatchDuplicateTarget)
1387    /// diagnostic referencing both sites is attached to it, rather than letting one silently
1388    /// overwrite the other in hash-order.
1389    fn merge_patch_class_likes(&mut self, incoming: impl IntoIterator<Item = (Word, Box<ClassLikeMetadata>)>) {
1390        for (k, v) in incoming {
1391            match self.patch_class_likes.entry(k) {
1392                Entry::Occupied(mut entry) => {
1393                    let diagnostic = duplicate_patch_class_diagnostic(entry.get(), &v);
1394                    entry.get_mut().issues.push(diagnostic);
1395                }
1396                Entry::Vacant(entry) => {
1397                    entry.insert(v);
1398                }
1399            }
1400        }
1401    }
1402
1403    /// Merges patch function-likes from another codebase, diagnosing collisions on free
1404    /// functions. Method collisions are subsumed by the enclosing class's duplicate
1405    /// diagnostic, so only keys with an empty class component are reported here.
1406    fn merge_patch_function_likes(
1407        &mut self,
1408        incoming: impl IntoIterator<Item = ((Word, Word), Box<FunctionLikeMetadata>)>,
1409    ) {
1410        for (k, v) in incoming {
1411            match self.patch_function_likes.entry(k) {
1412                Entry::Occupied(mut entry) => {
1413                    if k.0.is_empty() {
1414                        let diagnostic = duplicate_patch_function_diagnostic(entry.get(), &v);
1415                        entry.get_mut().issues.push(diagnostic);
1416                    }
1417                }
1418                Entry::Vacant(entry) => {
1419                    entry.insert(v);
1420                }
1421            }
1422        }
1423    }
1424
1425    /// Merges patch constants from another codebase, diagnosing collisions.
1426    fn merge_patch_constants(&mut self, incoming: impl IntoIterator<Item = (Word, ConstantMetadata)>) {
1427        for (k, v) in incoming {
1428            match self.patch_constants.entry(k) {
1429                Entry::Occupied(mut entry) => {
1430                    let diagnostic = duplicate_patch_constant_diagnostic(entry.get(), &v);
1431                    entry.get_mut().issues.push(diagnostic);
1432                }
1433                Entry::Vacant(entry) => {
1434                    entry.insert(v);
1435                }
1436            }
1437        }
1438    }
1439
1440    /// Moves every scanned entry of this per-file partial into the patch maps.
1441    ///
1442    /// Called on a per-file partial right after `scan_program` when the file is a
1443    /// [`FileType::Patch`]. Symbols and descendants from a patch partial are dropped — the
1444    /// FQCN belongs to whichever non-patch source originally declared it (or it's an orphan
1445    /// which `apply_patches_pass` will diagnose later).
1446    pub fn convert_partial_to_patch(&mut self) {
1447        for (k, v) in std::mem::take(&mut self.class_likes) {
1448            self.patch_class_likes.insert(k, v);
1449        }
1450
1451        for (k, v) in std::mem::take(&mut self.function_likes) {
1452            self.patch_function_likes.insert(k, v);
1453        }
1454
1455        for (k, v) in std::mem::take(&mut self.constants) {
1456            self.patch_constants.insert(k, v);
1457        }
1458
1459        self.symbols = Symbols::new();
1460        self.class_like_aliases.clear();
1461        self.class_like_alias_declarations.clear();
1462        self.class_like_aliases_dirty = false;
1463        self.all_class_like_descendants.clear();
1464        self.direct_classlike_descendants.clear();
1465    }
1466
1467    /// Folds every entry in the `patch_*` maps into the matching vendor / built-in entry,
1468    /// attaching validation diagnostics to the patch entry's `issues` list.
1469    ///
1470    /// At most one patch may target a given symbol, so each entry is applied directly to its
1471    /// target. A patch whose target is user-defined is inert (user definitions win); a patch
1472    /// with no matching target is diagnosed as an orphan.
1473    ///
1474    /// Must be called after all partials have been merged so the slots patches target are
1475    /// present.
1476    pub fn apply_patches_pass(&mut self) {
1477        reset_patch_methods(self);
1478        // `(class, method)` slots where a patch overrides a method inherited from an ancestor.
1479        // No function-like exists at these keys yet, so the function loop below materializes
1480        // them from the patch's own scanned declaration rather than treating them as orphans.
1481        let mut inherited_overrides: HashSet<(Word, Word)> = HashSet::default();
1482        let mut inherited_methods = collect_inherited_patch_methods(self);
1483        let mut applied_classes = Vec::new();
1484
1485        let class_keys: Vec<Word> = self.patch_class_likes.keys().copied().collect();
1486        for fqcn in class_keys {
1487            let Some(target) = self.class_likes.get(&fqcn) else {
1488                if let Some(p) = self.patch_class_likes.get_mut(&fqcn) {
1489                    let diag = orphan_patch_class_diagnostic(p);
1490                    p.issues.push(diag);
1491                }
1492                continue;
1493            };
1494            // User-defined targets win; the patch entry is inert. Leave any scan-time issues
1495            // on it intact — they still belong to the patch source.
1496            if target.flags.is_user_defined() {
1497                continue;
1498            }
1499
1500            let mut working = target.clone();
1501            let inherited = inherited_methods.remove(&fqcn).unwrap_or_default();
1502            inherited_overrides.extend(inherited.iter().map(|method| (fqcn, *method)));
1503            let constructor_name = word("__construct");
1504            let patch_declares_constructor = self.patch_class_likes[&fqcn].methods.contains(&constructor_name);
1505            if let Some(patch_entry) = self.patch_class_likes.get_mut(&fqcn)
1506                && working.apply_patch(patch_entry, &inherited)
1507            {
1508                applied_classes.push(fqcn);
1509            }
1510            if working.flags.has_consistent_constructor()
1511                && !patch_declares_constructor
1512                && !inherited.contains(&constructor_name)
1513                && let Some(constructor) = working.add_implicit_constructor()
1514            {
1515                self.function_likes.entry((fqcn, constructor_name)).or_insert_with(|| Box::new(constructor));
1516            }
1517            self.class_likes.insert(fqcn, working);
1518        }
1519
1520        propagate_inherited_docblock_flags(self, applied_classes);
1521
1522        let func_keys: Vec<(Word, Word)> = self.patch_function_likes.keys().copied().collect();
1523        for key in &func_keys {
1524            let Some(target) = self.function_likes.get(key) else { continue };
1525            if target.flags.is_user_defined() {
1526                continue;
1527            }
1528
1529            let mut working = target.clone();
1530            if let Some(patch_entry) = self.patch_function_likes.get_mut(key) {
1531                working.apply_patch(patch_entry);
1532            }
1533            self.function_likes.insert(*key, working);
1534        }
1535
1536        let inherited_keys: Vec<_> = func_keys
1537            .iter()
1538            .copied()
1539            .filter(|key| inherited_overrides.contains(key) && !self.function_likes.contains_key(key))
1540            .map(|(class, method)| MethodIdentifier::new(class, method))
1541            .collect();
1542
1543        for inherited in resolve_inherited_patch_methods(self, inherited_keys) {
1544            let key = inherited.target.get_key();
1545            let Some(patch) = self.patch_function_likes.get(&key) else { continue };
1546            let mut materialized = patch.clone();
1547            if let Some(inherited_flags) = inherited
1548                .source
1549                .and_then(|source| self.function_likes.get(&source.get_key()))
1550                .map(|source| source.flags)
1551            {
1552                let patch_origin_flag = materialized.flags & MetadataFlags::PATCH;
1553                materialized.flags = inherited_flags | patch_origin_flag;
1554                materialized.flags.remove(MetadataFlags::POPULATED);
1555                merge_explicit_docblock_flags(
1556                    &mut materialized.flags,
1557                    patch.flags,
1558                    patch.explicit_docblock_flags,
1559                    PATCHABLE_FUNCTION_DOCBLOCK_FLAGS,
1560                );
1561            }
1562            self.function_likes.insert(key, materialized);
1563        }
1564
1565        for key in func_keys {
1566            if self.function_likes.contains_key(&key) || !key.0.is_empty() {
1567                continue;
1568            }
1569            if let Some(patch) = self.patch_function_likes.get_mut(&key) {
1570                let diag = orphan_patch_function_diagnostic(patch);
1571                patch.issues.push(diag);
1572            }
1573        }
1574
1575        let const_keys: Vec<Word> = self.patch_constants.keys().copied().collect();
1576        for fqcn in const_keys {
1577            let Some(target) = self.constants.get(&fqcn) else {
1578                if let Some(p) = self.patch_constants.get_mut(&fqcn) {
1579                    let diag = orphan_patch_constant_diagnostic(p);
1580                    p.issues.push(diag);
1581                }
1582                continue;
1583            };
1584            if target.flags.is_user_defined() {
1585                continue;
1586            }
1587
1588            let mut working = target.clone();
1589            if let Some(patch_entry) = self.patch_constants.get(&fqcn) {
1590                working.apply_patch(patch_entry);
1591            }
1592            self.constants.insert(fqcn, working);
1593        }
1594    }
1595
1596    /// Extracts only the keys that this per-file metadata currently "owns" in the given
1597    /// merged codebase; i.e. keys whose span in `merged` matches this metadata's span.
1598    ///
1599    /// This is what you want for incremental fingerprints. [`extract_keys`](Self::extract_keys)
1600    /// captures *every* key the scan produced, including ones that lost the tiebreak in
1601    /// [`extend`](Self::extend) / [`extend_ref`](Self::extend_ref) when another file defined
1602    /// the same FQN. Using `extract_keys` as a removal fingerprint then causes a nasty
1603    /// cross-file bug: touching file *B* can remove an entry that file *A* actually owns,
1604    /// because [`remove_entries_by_keys`](Self::remove_entries_by_keys) deletes by FQN
1605    /// without checking who the current owner is. The analyzer then reports a spurious
1606    /// "duplicate definition" when it walks *A* and finds *B*'s span in the codebase.
1607    ///
1608    /// By only recording the keys whose spans still match *this* metadata, removing the
1609    /// fingerprint later becomes a safe no-op when another file won the merge. The
1610    /// removal only drops the entries this file genuinely put into the merged codebase.
1611    #[must_use]
1612    pub fn extract_owned_keys(&self, merged: &CodebaseMetadata) -> CodebaseEntryKeys {
1613        let class_like_names = self
1614            .class_likes
1615            .iter()
1616            .filter(|(name, meta)| merged.class_likes.get(*name).is_some_and(|m| m.span == meta.span))
1617            .map(|(name, _)| *name)
1618            .collect();
1619
1620        let class_like_aliases = self
1621            .class_like_alias_declarations
1622            .iter()
1623            .filter(|(name, (_, span, _))| {
1624                merged.class_like_alias_declarations.get(*name).is_some_and(|(_, merged_span, _)| merged_span == span)
1625            })
1626            .map(|(alias, (target, span, _))| (*alias, *target, *span))
1627            .collect();
1628
1629        let function_like_keys = self
1630            .function_likes
1631            .iter()
1632            .filter(|(key, meta)| merged.function_likes.get(*key).is_some_and(|m| m.span == meta.span))
1633            .map(|(key, _)| *key)
1634            .collect();
1635
1636        let constant_names = self
1637            .constants
1638            .iter()
1639            .filter(|(name, meta)| merged.constants.get(*name).is_some_and(|m| m.span == meta.span))
1640            .map(|(name, _)| *name)
1641            .collect();
1642
1643        // A file signature is always owned by its file (there is at most one per file).
1644        let file_ids = self.file_signatures.keys().copied().collect();
1645
1646        CodebaseEntryKeys { class_like_names, class_like_aliases, function_like_keys, constant_names, file_ids }
1647    }
1648
1649    /// Removes entries whose keys match the given [`CodebaseEntryKeys`].
1650    ///
1651    /// This is the lightweight equivalent of [`remove_entries_of()`] — it performs the
1652    /// same removals but from a compact key set instead of a full `CodebaseMetadata` reference.
1653    pub fn remove_entries_by_keys(&mut self, keys: &CodebaseEntryKeys) {
1654        if !keys.class_like_names.is_empty() && !self.class_like_alias_declarations.is_empty() {
1655            self.class_like_aliases_dirty = true;
1656        }
1657
1658        for k in &keys.class_like_names {
1659            self.class_likes.remove(k);
1660            self.symbols.remove(*k);
1661        }
1662
1663        for (alias, _, _) in &keys.class_like_aliases {
1664            self.class_like_alias_declarations.remove(alias);
1665            self.class_like_aliases_dirty = true;
1666        }
1667
1668        for k in &keys.function_like_keys {
1669            self.function_likes.remove(k);
1670        }
1671
1672        for k in &keys.constant_names {
1673            self.constants.remove(k);
1674        }
1675
1676        for k in &keys.file_ids {
1677            self.file_signatures.remove(k);
1678        }
1679
1680        // Drop any patch entry that originated from a file signature we just removed; a patch
1681        // entry's originating file is recorded on its span.
1682        let removed_files: HashSet<FileId> = keys.file_ids.iter().copied().collect();
1683        self.patch_class_likes.retain(|_, m| !removed_files.contains(&m.span.file_id));
1684        self.patch_function_likes.retain(|_, m| !removed_files.contains(&m.span.file_id));
1685        self.patch_constants.retain(|_, m| !removed_files.contains(&m.span.file_id));
1686    }
1687
1688    /// Takes all issues from the codebase metadata.
1689    pub fn take_issues(&mut self, user_defined: bool) -> IssueCollection {
1690        let mut issues = IssueCollection::new();
1691
1692        for meta in self.class_likes.values_mut() {
1693            if user_defined && !meta.flags.is_user_defined() {
1694                continue;
1695            }
1696            issues.extend(meta.take_issues());
1697        }
1698
1699        for meta in self.function_likes.values_mut() {
1700            if user_defined && !meta.flags.is_user_defined() {
1701                continue;
1702            }
1703            issues.extend(meta.take_issues());
1704        }
1705
1706        for meta in self.constants.values_mut() {
1707            if user_defined && !meta.flags.is_user_defined() {
1708                continue;
1709            }
1710            issues.extend(meta.take_issues());
1711        }
1712
1713        // Patches are user-authored, so their issues are always reported regardless of the
1714        // `user_defined` filter. They live in their own maps and never appear in the regular
1715        // class_likes/function_likes/constants iteration above.
1716        for meta in self.patch_class_likes.values_mut() {
1717            issues.extend(meta.take_issues());
1718        }
1719
1720        for meta in self.patch_function_likes.values_mut() {
1721            issues.extend(meta.take_issues());
1722        }
1723
1724        for meta in self.patch_constants.values_mut() {
1725            issues.extend(meta.take_issues());
1726        }
1727
1728        issues
1729    }
1730
1731    /// Gets all file IDs that have signatures in this metadata.
1732    ///
1733    /// This is a helper method for incremental analysis to iterate over all files.
1734    #[must_use]
1735    pub fn get_all_file_ids(&self) -> Vec<FileId> {
1736        self.file_signatures.keys().copied().collect()
1737    }
1738}
1739
1740fn duplicate_patch_class_diagnostic(kept: &ClassLikeMetadata, dropped: &ClassLikeMetadata) -> Issue {
1741    Issue::error(format!(
1742        "Multiple patches target `{}`; at most one patch may target a given symbol.",
1743        kept.original_name
1744    ))
1745    .with_code(ScanningIssueKind::PatchDuplicateTarget)
1746    .with_annotation(Annotation::primary(dropped.span).with_message("Duplicate patch for this symbol."))
1747    .with_annotation(Annotation::secondary(kept.span).with_message("Already patched here."))
1748    .with_help("Merge the conflicting declarations into a single patch, or remove all but one.")
1749}
1750
1751fn duplicate_patch_function_diagnostic(kept: &FunctionLikeMetadata, dropped: &FunctionLikeMetadata) -> Issue {
1752    Issue::error(format!(
1753        "Multiple patches target function `{}`; at most one patch may target a given symbol.",
1754        kept.name
1755    ))
1756    .with_code(ScanningIssueKind::PatchDuplicateTarget)
1757    .with_annotation(Annotation::primary(dropped.span).with_message("Duplicate patch for this function."))
1758    .with_annotation(Annotation::secondary(kept.span).with_message("Already patched here."))
1759    .with_help("Merge the conflicting declarations into a single patch, or remove all but one.")
1760}
1761
1762fn duplicate_patch_constant_diagnostic(kept: &ConstantMetadata, dropped: &ConstantMetadata) -> Issue {
1763    Issue::error(format!(
1764        "Multiple patches target constant `{}`; at most one patch may target a given symbol.",
1765        kept.name
1766    ))
1767    .with_code(ScanningIssueKind::PatchDuplicateTarget)
1768    .with_annotation(Annotation::primary(dropped.span).with_message("Duplicate patch for this constant."))
1769    .with_annotation(Annotation::secondary(kept.span).with_message("Already patched here."))
1770    .with_help("Merge the conflicting declarations into a single patch, or remove all but one.")
1771}
1772
1773fn orphan_patch_class_diagnostic(meta: &ClassLikeMetadata) -> Issue {
1774    Issue::error(format!(
1775        "Patch declares `{}` but no vendored or built-in definition exists to patch.",
1776        meta.original_name,
1777    ))
1778    .with_code(ScanningIssueKind::PatchIntroducesNewSymbol)
1779    .with_annotation(Annotation::primary(meta.span))
1780    .with_help(
1781        "The patch may be misnamed or out-of-date relative to the vendored or built-in definition; \
1782         check the symbol name and verify the patch still matches the upstream source.",
1783    )
1784}
1785
1786fn orphan_patch_function_diagnostic(meta: &FunctionLikeMetadata) -> Issue {
1787    Issue::error(format!(
1788        "Patch declares function `{}` but no vendored or built-in definition exists to patch.",
1789        meta.name,
1790    ))
1791    .with_code(ScanningIssueKind::PatchIntroducesNewSymbol)
1792    .with_annotation(Annotation::primary(meta.span))
1793    .with_help(
1794        "The patch may be misnamed or out-of-date relative to the vendored or built-in definition; \
1795         check the function name and verify the patch still matches the upstream source.",
1796    )
1797}
1798
1799fn orphan_patch_constant_diagnostic(meta: &ConstantMetadata) -> Issue {
1800    Issue::error(format!(
1801        "Patch declares constant `{}` but no vendored or built-in definition exists to patch.",
1802        meta.name,
1803    ))
1804    .with_code(ScanningIssueKind::PatchIntroducesNewSymbol)
1805    .with_annotation(Annotation::primary(meta.span))
1806    .with_help(
1807        "The patch may be misnamed or out-of-date relative to the vendored or built-in definition; \
1808         check the constant name and verify the patch still matches the upstream source.",
1809    )
1810}
1811
1812fn merge_function_likes(
1813    target: &mut HashMap<(Word, Word), Box<FunctionLikeMetadata>>,
1814    incoming: HashMap<(Word, Word), Box<FunctionLikeMetadata>>,
1815) {
1816    for (key, mut metadata) in incoming {
1817        match target.entry(key) {
1818            Entry::Occupied(mut entry) => {
1819                if should_replace_metadata(entry.get().flags, entry.get().span, metadata.flags, metadata.span) {
1820                    metadata.version_constraint.merge(entry.get().version_constraint.clone());
1821                    entry.insert(metadata);
1822                } else {
1823                    entry.get_mut().version_constraint.merge(metadata.version_constraint);
1824                }
1825            }
1826            Entry::Vacant(entry) => {
1827                entry.insert(metadata);
1828            }
1829        }
1830    }
1831}
1832
1833/// Determines which metadata value to keep when merging duplicates.
1834///
1835/// Priority:
1836///   1. user-defined > patch > external > built-in > other.
1837///   2. non-polyfill > polyfill — tools like rector/phpstan/psalm ship
1838///      skeleton stubs gated by `if (!class_exists('X'))` that should never
1839///      shadow a concrete definition.
1840///   3. smaller span wins as a deterministic tie-breaker.
1841///
1842/// Returns `true` if the new value should replace the existing one.
1843fn combine_defined_constant_types(existing: &ConstantMetadata, new: &ConstantMetadata) -> Option<TUnion> {
1844    if existing.flags.is_built_in() || new.flags.is_built_in() {
1845        return None;
1846    }
1847
1848    let (Some(existing_type), Some(new_type)) = (&existing.inferred_type, &new.inferred_type) else {
1849        return None;
1850    };
1851
1852    let missing: Vec<TAtomic> =
1853        new_type.types.iter().filter(|atomic| !existing_type.types.contains(atomic)).cloned().collect();
1854    if missing.is_empty() {
1855        return None;
1856    }
1857
1858    let mut types = existing_type.types.to_vec();
1859    types.extend(missing);
1860
1861    Some(TUnion::from_vec(types))
1862}
1863
1864fn should_replace_metadata(
1865    existing_flags: MetadataFlags,
1866    existing_span: Span,
1867    new_flags: MetadataFlags,
1868    new_span: Span,
1869) -> bool {
1870    let new_is_user_defined = new_flags.is_user_defined();
1871    let existing_is_user_defined = existing_flags.is_user_defined();
1872
1873    if new_is_user_defined != existing_is_user_defined {
1874        return new_is_user_defined;
1875    }
1876
1877    let new_is_patch = new_flags.is_patch();
1878    let existing_is_patch = existing_flags.is_patch();
1879
1880    if new_is_patch != existing_is_patch {
1881        return new_is_patch;
1882    }
1883
1884    let new_is_external = new_flags.is_external();
1885    let existing_is_external = existing_flags.is_external();
1886
1887    if new_is_external != existing_is_external {
1888        return new_is_external;
1889    }
1890
1891    let new_is_built_in = new_flags.is_built_in();
1892    let existing_is_built_in = existing_flags.is_built_in();
1893
1894    if new_is_built_in != existing_is_built_in {
1895        return new_is_built_in;
1896    }
1897
1898    let new_is_polyfill = new_flags.is_polyfill();
1899    let existing_is_polyfill = existing_flags.is_polyfill();
1900
1901    if new_is_polyfill != existing_is_polyfill {
1902        return !new_is_polyfill;
1903    }
1904
1905    new_span < existing_span
1906}
1907
1908#[cfg(test)]
1909mod should_replace_metadata_tests {
1910    use super::*;
1911
1912    #[test]
1913    fn constants_defined_with_different_values_keep_every_value() {
1914        let name = mago_word::word("MY_DEBUG");
1915        let mut first = CodebaseMetadata::new();
1916        let mut true_constant = ConstantMetadata::new(name, Span::zero(), MetadataFlags::USER_DEFINED);
1917        true_constant.inferred_type = Some(crate::ttype::get_true());
1918        first.constants.insert(name, true_constant);
1919
1920        let mut second = CodebaseMetadata::new();
1921        let mut false_constant = ConstantMetadata::new(name, Span::zero(), MetadataFlags::USER_DEFINED);
1922        false_constant.inferred_type = Some(crate::ttype::get_false());
1923        second.constants.insert(name, false_constant);
1924
1925        first.extend(second);
1926
1927        let constant_types = first.constants[&name].inferred_type.as_ref().map(|union| union.types.to_vec());
1928        assert!(constant_types.as_ref().is_some_and(|types| types.iter().any(TAtomic::is_true)));
1929        assert!(constant_types.is_some_and(|types| types.iter().any(TAtomic::is_false)));
1930    }
1931
1932    #[test]
1933    fn replacing_file_signatures_keeps_map_capacity() {
1934        let mut codebase = CodebaseMetadata::new();
1935        codebase.file_signatures.reserve(3);
1936        let capacity = codebase.file_signatures.capacity();
1937        for index in 0..capacity {
1938            codebase.set_file_signature(FileId::new(format!("{index}.php").as_bytes()), FileSignature::default());
1939        }
1940
1941        let file_id = FileId::new(b"0.php");
1942
1943        for hash in 1..=3 {
1944            let mut incoming = CodebaseMetadata::new();
1945            incoming.set_file_signature(file_id, FileSignature { hash, ..FileSignature::default() });
1946            codebase.extend(incoming);
1947            assert_eq!(codebase.file_signatures.len(), capacity);
1948            assert_eq!(codebase.file_signatures.capacity(), capacity);
1949            assert_eq!(codebase.file_signatures[&file_id].hash, hash);
1950        }
1951    }
1952
1953    #[test]
1954    fn non_polyfill_replaces_polyfill() {
1955        let polyfill = MetadataFlags::POLYFILL;
1956        let real = MetadataFlags::empty();
1957        assert!(should_replace_metadata(polyfill, Span::dummy(0, 100), real, Span::dummy(0, 100)));
1958        assert!(!should_replace_metadata(real, Span::dummy(0, 100), polyfill, Span::dummy(0, 100)));
1959    }
1960
1961    #[test]
1962    fn polyfill_does_not_replace_non_polyfill_even_with_smaller_span() {
1963        let real = MetadataFlags::empty();
1964        let polyfill = MetadataFlags::POLYFILL;
1965        assert!(!should_replace_metadata(real, Span::dummy(500, 600), polyfill, Span::dummy(0, 10)));
1966    }
1967
1968    #[test]
1969    fn user_defined_beats_polyfill_flag() {
1970        let polyfill_user = MetadataFlags::POLYFILL | MetadataFlags::USER_DEFINED;
1971        let plain = MetadataFlags::empty();
1972        assert!(!should_replace_metadata(polyfill_user, Span::dummy(0, 10), plain, Span::dummy(0, 10)));
1973        assert!(should_replace_metadata(plain, Span::dummy(0, 10), polyfill_user, Span::dummy(0, 10)));
1974    }
1975
1976    #[test]
1977    fn two_user_defined_fall_through_to_polyfill_check() {
1978        let a = MetadataFlags::POLYFILL | MetadataFlags::USER_DEFINED;
1979        let b = MetadataFlags::USER_DEFINED;
1980        assert!(should_replace_metadata(a, Span::dummy(0, 10), b, Span::dummy(0, 10)));
1981        assert!(!should_replace_metadata(b, Span::dummy(0, 10), a, Span::dummy(0, 10)));
1982    }
1983
1984    #[test]
1985    fn two_non_polyfills_fall_through_to_priority_rules() {
1986        let user = MetadataFlags::USER_DEFINED;
1987        let builtin = MetadataFlags::BUILTIN;
1988        assert!(!should_replace_metadata(user, Span::dummy(0, 10), builtin, Span::dummy(0, 10)));
1989        assert!(should_replace_metadata(builtin, Span::dummy(0, 10), user, Span::dummy(0, 10)));
1990    }
1991
1992    #[test]
1993    fn patch_beats_vendored() {
1994        let vendored = MetadataFlags::empty();
1995        let patch = MetadataFlags::PATCH;
1996        assert!(should_replace_metadata(vendored, Span::dummy(0, 100), patch, Span::dummy(0, 100)));
1997        assert!(!should_replace_metadata(patch, Span::dummy(0, 100), vendored, Span::dummy(0, 100)));
1998    }
1999
2000    #[test]
2001    fn patch_beats_builtin() {
2002        let builtin = MetadataFlags::BUILTIN;
2003        let patch = MetadataFlags::PATCH;
2004        assert!(should_replace_metadata(builtin, Span::dummy(0, 100), patch, Span::dummy(0, 100)));
2005        assert!(!should_replace_metadata(patch, Span::dummy(0, 100), builtin, Span::dummy(0, 100)));
2006    }
2007
2008    #[test]
2009    fn external_beats_builtin_and_vendored() {
2010        let external = MetadataFlags::EXTERNAL;
2011        let builtin = MetadataFlags::BUILTIN;
2012        let vendored = MetadataFlags::empty();
2013
2014        assert!(should_replace_metadata(builtin, Span::dummy(0, 100), external, Span::dummy(500, 600)));
2015        assert!(!should_replace_metadata(external, Span::dummy(500, 600), builtin, Span::dummy(0, 100)));
2016        assert!(should_replace_metadata(vendored, Span::dummy(0, 100), external, Span::dummy(500, 600)));
2017        assert!(!should_replace_metadata(external, Span::dummy(500, 600), vendored, Span::dummy(0, 100)));
2018    }
2019
2020    #[test]
2021    fn patch_and_user_defined_beat_external() {
2022        let external = MetadataFlags::EXTERNAL;
2023        let patch = MetadataFlags::PATCH;
2024        let user = MetadataFlags::USER_DEFINED;
2025
2026        assert!(should_replace_metadata(external, Span::dummy(0, 100), patch, Span::dummy(500, 600)));
2027        assert!(!should_replace_metadata(patch, Span::dummy(500, 600), external, Span::dummy(0, 100)));
2028        assert!(should_replace_metadata(external, Span::dummy(0, 100), user, Span::dummy(500, 600)));
2029        assert!(!should_replace_metadata(user, Span::dummy(500, 600), external, Span::dummy(0, 100)));
2030    }
2031
2032    #[test]
2033    fn user_defined_beats_patch() {
2034        let user = MetadataFlags::USER_DEFINED;
2035        let patch = MetadataFlags::PATCH;
2036        assert!(!should_replace_metadata(user, Span::dummy(0, 100), patch, Span::dummy(0, 100)));
2037        assert!(should_replace_metadata(patch, Span::dummy(0, 100), user, Span::dummy(0, 100)));
2038    }
2039
2040    #[test]
2041    fn patch_does_not_beat_user_defined_even_with_smaller_span() {
2042        let user = MetadataFlags::USER_DEFINED;
2043        let patch = MetadataFlags::PATCH;
2044        assert!(!should_replace_metadata(user, Span::dummy(500, 600), patch, Span::dummy(0, 10)));
2045    }
2046
2047    #[test]
2048    #[allow(clippy::expect_used)]
2049    fn patch_function_like_leaves_vendor_owning_slot() {
2050        // Patches may only refine types and supported flags on an existing function-like; they
2051        // must never become the slot owner. The non-patch source's span/file id stay put so that
2052        // `extract_owned_keys` records vendor-as-owner — otherwise the patch's entry would
2053        // outlive a vendor deletion in incremental mode (orphan function-like bug).
2054        use crate::metadata::function_like::FunctionLikeKind;
2055
2056        let name = word("foo");
2057        let key = (empty_word(), name);
2058        let vendor_span = Span::dummy(0, 100);
2059        let patch_span = Span::dummy(500, 600);
2060
2061        let vendor =
2062            FunctionLikeMetadata::new(FunctionLikeKind::Function, name, name, vendor_span, MetadataFlags::empty());
2063        let mut codebase = CodebaseMetadata::new();
2064        codebase.function_likes.insert(key, Box::new(vendor));
2065
2066        let patch = FunctionLikeMetadata::new(FunctionLikeKind::Function, name, name, patch_span, MetadataFlags::PATCH);
2067        codebase.patch_function_likes.insert(key, Box::new(patch));
2068
2069        codebase.apply_patches_pass();
2070
2071        let merged = codebase.function_likes.get(&key).expect("function-like must remain after patch");
2072        assert_eq!(merged.span, vendor_span, "patch must not move the slot's span");
2073        assert!(!merged.flags.is_patch(), "patch must not flip the slot's flags");
2074    }
2075
2076    #[test]
2077    fn patch_does_not_apply_to_user_defined_class() {
2078        let class_name = word("MyClass");
2079        let method_existing = word("doIt");
2080
2081        let mut user_class =
2082            ClassLikeMetadata::new(class_name, class_name, Span::dummy(0, 100), None, MetadataFlags::USER_DEFINED);
2083        user_class.methods.insert(method_existing);
2084
2085        let mut codebase = CodebaseMetadata::new();
2086        codebase.class_likes.insert(class_name, Box::new(user_class));
2087
2088        let mut patch_class =
2089            ClassLikeMetadata::new(class_name, class_name, Span::dummy(0, 50), None, MetadataFlags::PATCH);
2090        let method_new = word("patchedMethod");
2091        patch_class.methods.insert(method_new);
2092
2093        codebase.patch_class_likes.insert(class_name, Box::new(patch_class));
2094
2095        codebase.apply_patches_pass();
2096
2097        let class = &codebase.class_likes[&class_name];
2098        // Patch must not apply to a user-defined class.
2099        assert!(!class.methods.contains(&method_new));
2100        // User-defined class must be preserved intact.
2101        assert!(class.methods.contains(&method_existing));
2102        assert!(class.flags.is_user_defined());
2103        // No issues should be emitted.
2104        assert!(class.issues.is_empty());
2105    }
2106}