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