Skip to main content

mago_codex/metadata/
mod.rs

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