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) => {
522                self.function_likes.get(&(empty_word(), name.to_ascii_lowercase()))
523            }
524            FunctionLikeIdentifier::Method(class, method) => {
525                self.get_method_by_id(&MethodIdentifier::new(*class, *method))
526            }
527            FunctionLikeIdentifier::Closure(name) => self.get_closure(name),
528        }
529    }
530
531    /// Retrieves metadata for a global constant.
532    /// Namespace lookup is case-insensitive, constant name is case-sensitive.
533    #[inline]
534    #[must_use]
535    pub fn get_constant(&self, name: &[u8]) -> Option<&ConstantMetadata> {
536        let lowercase_name = ascii_lowercase_constant_name_word(name);
537        self.constants.get(&lowercase_name)
538    }
539
540    /// The declaration name span of a top-level symbol named `name`: a
541    /// class-like (class/interface/trait/enum), a function, or a constant.
542    ///
543    /// Prefers the symbol's name span over its full declaration span, so callers
544    /// land on the identifier rather than the whole declaration body. The lookup
545    /// is case-insensitive, like every symbol lookup here.
546    #[inline]
547    #[must_use]
548    pub fn span_of(&self, name: &[u8]) -> Option<Span> {
549        if let Some(meta) = self.get_class_like(name) {
550            return Some(meta.name_span.unwrap_or(meta.span));
551        }
552
553        if let Some(meta) = self.get_function(name) {
554            return Some(meta.name_span.unwrap_or(meta.span));
555        }
556
557        self.get_constant(name).map(|meta| meta.span)
558    }
559
560    /// Retrieves metadata for a class constant.
561    /// Class name is case-insensitive, constant name is case-sensitive.
562    #[inline]
563    #[must_use]
564    pub fn get_class_constant(&self, class: &[u8], constant: &[u8]) -> Option<&ClassLikeConstantMetadata> {
565        let lowercase_class = ascii_lowercase_word(class);
566        let constant_name = word(constant);
567        self.get_class_like_by_word(lowercase_class).and_then(|meta| meta.constants.get(&constant_name))
568    }
569
570    /// Retrieves metadata for an enum case.
571    #[inline]
572    #[must_use]
573    pub fn get_enum_case(&self, class: &[u8], case: &[u8]) -> Option<&EnumCaseMetadata> {
574        let lowercase_class = ascii_lowercase_word(class);
575        let case_name = word(case);
576        self.get_class_like_by_word(lowercase_class).and_then(|meta| meta.enum_cases.get(&case_name))
577    }
578
579    /// Retrieves metadata for a property directly from the class where it's declared.
580    /// Class name is case-insensitive, property name is case-sensitive.
581    /// Sees real declarations only; magic `@property*` tags are reachable through
582    /// `ClassLikeMetadata::magic_property_ids`.
583    #[inline]
584    #[must_use]
585    pub fn get_property(&self, class: &[u8], property: &[u8]) -> Option<&PropertyMetadata> {
586        let lowercase_class = ascii_lowercase_word(class);
587        let property_name = word(property);
588        self.get_class_like_by_word(lowercase_class)?.properties.get(&property_name)
589    }
590
591    /// Retrieves magic `@property*` metadata declared directly on a class-like.
592    /// Class name is case-insensitive, property name is case-sensitive.
593    #[inline]
594    #[must_use]
595    pub fn get_magic_property(&self, class: &[u8], property: &[u8]) -> Option<&PropertyMetadata> {
596        let lowercase_class = ascii_lowercase_word(class);
597        let property_name = word(property);
598        self.get_class_like_by_word(lowercase_class)?.magic_properties.get(&property_name)
599    }
600
601    /// Retrieves the property metadata, potentially from a parent class if inherited.
602    #[inline]
603    #[must_use]
604    pub fn get_declaring_property(&self, class: &[u8], property: &[u8]) -> Option<&PropertyMetadata> {
605        let lowercase_class = ascii_lowercase_word(class);
606        let property_name = word(property);
607        let declaring_class =
608            self.get_class_like_by_word(lowercase_class)?.declaring_property_ids.get(&property_name)?;
609        self.class_likes.get(declaring_class)?.properties.get(&property_name)
610    }
611
612    /// Retrieves magic `@property*` metadata, potentially from an inherited tag.
613    /// Class name is case-insensitive, property name is case-sensitive.
614    #[inline]
615    #[must_use]
616    pub fn get_declaring_magic_property(&self, class: &[u8], property: &[u8]) -> Option<&PropertyMetadata> {
617        let lowercase_class = ascii_lowercase_word(class);
618        let property_name = word(property);
619        let declaring_class = self.get_class_like_by_word(lowercase_class)?.magic_property_ids.get(&property_name)?;
620        self.class_likes.get(declaring_class)?.magic_properties.get(&property_name)
621    }
622    // Type Resolution
623
624    /// Gets the type of a property, resolving it from the declaring class if needed.
625    #[inline]
626    #[must_use]
627    pub fn get_property_type(&self, class: &[u8], property: &[u8]) -> Option<&TUnion> {
628        let lowercase_class = ascii_lowercase_word(class);
629        let property_name = word(property);
630        let declaring_class =
631            self.get_class_like_by_word(lowercase_class)?.declaring_property_ids.get(&property_name)?;
632        let property_meta = self.class_likes.get(declaring_class)?.properties.get(&property_name)?;
633        property_meta.type_metadata.as_ref().map(|tm| &tm.type_union)
634    }
635
636    /// Gets the type of a class constant, considering both type hints and inferred types.
637    #[must_use]
638    pub fn get_class_constant_type<'meta>(&'meta self, class: &[u8], constant: &[u8]) -> Option<Cow<'meta, TUnion>> {
639        let lowercase_class = ascii_lowercase_word(class);
640        let constant_name = word(constant);
641        let class_meta = self.get_class_like_by_word(lowercase_class)?;
642
643        // Check if it's an enum case
644        if class_meta.kind.is_enum() && class_meta.enum_cases.contains_key(&constant_name) {
645            let atomic = TAtomic::Object(TObject::new_enum_case(class_meta.original_name, constant_name));
646            return Some(Cow::Owned(TUnion::from_atomic(atomic)));
647        }
648
649        // It's a regular class constant
650        let constant_meta = class_meta.constants.get(&constant_name)?;
651
652        // Prefer the type signature if available
653        if let Some(type_meta) = constant_meta.type_metadata.as_ref() {
654            return Some(Cow::Borrowed(&type_meta.type_union));
655        }
656
657        // Fall back to inferred type
658        constant_meta.inferred_type.as_ref().map(|atomic| Cow::Owned(TUnion::from_atomic(atomic.clone())))
659    }
660    // Inheritance Queries
661
662    /// Checks if a child class extends a parent class (case-insensitive).
663    #[inline]
664    #[must_use]
665    pub fn class_extends(&self, child: &[u8], parent: &[u8]) -> bool {
666        let lowercase_child = ascii_lowercase_word(child);
667        let lowercase_parent = ascii_lowercase_word(parent);
668        let Some(metadata) = self.get_class_like_by_word(lowercase_child) else {
669            return false;
670        };
671
672        if metadata.all_parent_classes.contains(&lowercase_parent) {
673            return true;
674        }
675
676        if self.class_like_aliases.is_empty() || self.class_likes.contains_key(&lowercase_parent) {
677            return false;
678        }
679
680        self.class_like_aliases
681            .get(&lowercase_parent)
682            .is_some_and(|actual| metadata.all_parent_classes.contains(actual))
683    }
684
685    /// Checks if a class implements an interface (case-insensitive).
686    #[inline]
687    #[must_use]
688    pub fn class_implements(&self, class: &[u8], interface: &[u8]) -> bool {
689        let lowercase_class = ascii_lowercase_word(class);
690        let lowercase_interface = ascii_lowercase_word(interface);
691        let Some(metadata) = self.get_class_like_by_word(lowercase_class) else {
692            return false;
693        };
694
695        if metadata.all_parent_interfaces.contains(&lowercase_interface) {
696            return true;
697        }
698
699        if self.class_like_aliases.is_empty() || self.class_likes.contains_key(&lowercase_interface) {
700            return false;
701        }
702
703        self.class_like_aliases
704            .get(&lowercase_interface)
705            .is_some_and(|actual| metadata.all_parent_interfaces.contains(actual))
706    }
707
708    /// Checks if a class uses a trait (case-insensitive).
709    #[inline]
710    #[must_use]
711    pub fn class_uses_trait(&self, class: &[u8], trait_name: &[u8]) -> bool {
712        let lowercase_class = ascii_lowercase_word(class);
713        let lowercase_trait = ascii_lowercase_word(trait_name);
714        let Some(metadata) = self.get_class_like_by_word(lowercase_class) else {
715            return false;
716        };
717
718        if metadata.used_traits.contains(&lowercase_trait) {
719            return true;
720        }
721
722        if self.class_like_aliases.is_empty() || self.class_likes.contains_key(&lowercase_trait) {
723            return false;
724        }
725
726        self.class_like_aliases.get(&lowercase_trait).is_some_and(|actual| metadata.used_traits.contains(actual))
727    }
728
729    /// Checks if child is an instance of parent (via extends or implements).
730    #[inline]
731    #[must_use]
732    pub fn is_instance_of(&self, child: &[u8], parent: &[u8]) -> bool {
733        if child == parent {
734            return true;
735        }
736
737        let lowercase_child = ascii_lowercase_word(child);
738        let lowercase_parent = ascii_lowercase_word(parent);
739
740        if lowercase_child == lowercase_parent {
741            return true;
742        }
743
744        let Some(metadata) = self.get_class_like_by_word(lowercase_child) else {
745            return false;
746        };
747
748        let matches = |parent| {
749            metadata.name == parent
750                || metadata.all_parent_classes.contains(&parent)
751                || metadata.all_parent_interfaces.contains(&parent)
752                || metadata.used_traits.contains(&parent)
753                || metadata.require_extends.contains(&parent)
754                || metadata.require_implements.contains(&parent)
755        };
756
757        if matches(lowercase_parent) {
758            return true;
759        }
760
761        if self.class_like_aliases.is_empty() || self.class_likes.contains_key(&lowercase_parent) {
762            return false;
763        }
764
765        self.class_like_aliases.get(&lowercase_parent).is_some_and(|actual| matches(*actual))
766    }
767
768    /// Checks if the given name is an enum or final class.
769    #[inline]
770    #[must_use]
771    pub fn is_enum_or_final_class(&self, name: &[u8]) -> bool {
772        let lowercase_name = ascii_lowercase_word(name);
773        self.get_class_like_by_word(lowercase_name).is_some_and(|meta| meta.kind.is_enum() || meta.flags.is_final())
774    }
775
776    /// Checks if a class-like can be part of an intersection.
777    /// Generally, only final classes and enums cannot be intersected.
778    #[inline]
779    #[must_use]
780    pub fn is_inheritable(&self, name: &[u8]) -> bool {
781        let lowercase_name = ascii_lowercase_word(name);
782        match self.symbols.get_kind(lowercase_name) {
783            Some(SymbolKind::Class) => {
784                self.get_class_like_by_word(lowercase_name).is_some_and(|meta| !meta.flags.is_final())
785            }
786            Some(SymbolKind::Enum) => false,
787            Some(SymbolKind::Interface | SymbolKind::Trait) | None => true,
788        }
789    }
790
791    /// Gets all descendants of a class (recursive).
792    #[inline]
793    #[must_use]
794    pub fn get_class_descendants(&self, class: &[u8]) -> WordSet {
795        let lowercase_class = ascii_lowercase_word(class);
796        let lowercase_class = self.resolve_class_like_word(lowercase_class).unwrap_or(lowercase_class);
797        let mut all_descendants = WordSet::default();
798        let mut queue = vec![&lowercase_class];
799        let mut visited = WordSet::default();
800        visited.insert(lowercase_class);
801
802        while let Some(current_name) = queue.pop() {
803            if let Some(direct_descendants) = self.direct_classlike_descendants.get(current_name) {
804                for descendant in direct_descendants {
805                    if visited.insert(*descendant) {
806                        all_descendants.insert(*descendant);
807                        queue.push(descendant);
808                    }
809                }
810            }
811        }
812
813        all_descendants
814    }
815
816    /// Gets all ancestors of a class (parents + interfaces).
817    #[inline]
818    #[must_use]
819    pub fn get_class_ancestors(&self, class: &[u8]) -> WordSet {
820        let lowercase_class = ascii_lowercase_word(class);
821        let mut ancestors = WordSet::default();
822        if let Some(meta) = self.get_class_like_by_word(lowercase_class) {
823            ancestors.extend(meta.all_parent_classes.iter().copied());
824            ancestors.extend(meta.all_parent_interfaces.iter().copied());
825        }
826        ancestors
827    }
828
829    /// Gets the class where a method is declared (following inheritance).
830    #[inline]
831    #[must_use]
832    pub fn get_declaring_method_class(&self, class: &[u8], method: &[u8]) -> Option<Word> {
833        self.get_declaring_method_class_by_id(&MethodIdentifier::new(
834            ascii_lowercase_word(class),
835            ascii_lowercase_word(method),
836        ))
837    }
838
839    /// Gets the declaring class of an interned method name, ignoring ASCII case.
840    #[inline]
841    #[must_use]
842    pub fn get_declaring_method_class_by_id(&self, method: &MethodIdentifier) -> Option<Word> {
843        let lowercase_class = method.get_class_name().to_ascii_lowercase();
844        let lowercase_method = method.get_method_name().to_ascii_lowercase();
845
846        self.get_class_like_by_word(lowercase_class)?
847            .declaring_method_ids
848            .get(&lowercase_method)
849            .map(|method_id| method_id.get_class_name())
850    }
851
852    /// Gets the declaring method identifier for a method.
853    #[must_use]
854    pub fn get_declaring_method_identifier(&self, method_id: &MethodIdentifier) -> MethodIdentifier {
855        let lowercase_class = method_id.get_class_name().to_ascii_lowercase();
856        let lowercase_method = method_id.get_method_name().to_ascii_lowercase();
857
858        let Some(class_meta) = self.get_class_like_by_word(lowercase_class) else {
859            return *method_id;
860        };
861
862        if let Some(declaring_method_id) = class_meta.declaring_method_ids.get(&lowercase_method) {
863            return *declaring_method_id;
864        }
865
866        if class_meta.flags.is_abstract()
867            && let Some(overridden_map) = class_meta.overridden_method_ids.get(&lowercase_method)
868            && let Some((_, first_method_id)) = overridden_map.first()
869        {
870            return *first_method_id;
871        }
872
873        *method_id
874    }
875
876    /// Checks if a method is overriding a parent method.
877    #[inline]
878    #[must_use]
879    pub fn method_is_overriding(&self, class: &[u8], method: &[u8]) -> bool {
880        let lowercase_class = ascii_lowercase_word(class);
881        let lowercase_method = ascii_lowercase_word(method);
882        self.get_class_like_by_word(lowercase_class)
883            .is_some_and(|meta| meta.overridden_method_ids.contains_key(&lowercase_method))
884    }
885
886    /// Checks if a method is abstract.
887    #[inline]
888    #[must_use]
889    pub fn method_is_abstract(&self, class: &[u8], method: &[u8]) -> bool {
890        let lowercase_class = ascii_lowercase_word(class);
891        let lowercase_method = ascii_lowercase_word(method);
892        self.get_method_by_words(lowercase_class, lowercase_method)
893            .and_then(|meta| meta.method_metadata.as_ref())
894            .is_some_and(|method_meta| method_meta.is_abstract)
895    }
896
897    /// Checks if a method is final.
898    #[inline]
899    #[must_use]
900    pub fn method_is_final(&self, class: &[u8], method: &[u8]) -> bool {
901        let lowercase_class = ascii_lowercase_word(class);
902        let lowercase_method = ascii_lowercase_word(method);
903        self.get_method_by_words(lowercase_class, lowercase_method)
904            .and_then(|meta| meta.method_metadata.as_ref())
905            .is_some_and(|method_meta| method_meta.is_final)
906    }
907
908    /// Gets the effective visibility of a method, taking into account trait alias visibility overrides.
909    ///
910    /// When a trait method is aliased with a visibility modifier (e.g., `use Trait { method as public aliasedMethod; }`),
911    /// the visibility is stored in the class's `trait_visibility_map`. This method checks that map first,
912    /// then falls back to the method's declared visibility.
913    #[inline]
914    #[must_use]
915    pub fn get_method_visibility(&self, class: &[u8], method: &[u8]) -> Option<Visibility> {
916        self.get_method_visibility_by_id(&MethodIdentifier::new(
917            ascii_lowercase_word(class),
918            ascii_lowercase_word(method),
919        ))
920    }
921
922    /// Gets a method's visibility from interned names, including trait visibility overrides.
923    #[inline]
924    #[must_use]
925    pub fn get_method_visibility_by_id(&self, method: &MethodIdentifier) -> Option<Visibility> {
926        let lowercase_class = method.get_class_name().to_ascii_lowercase();
927        let lowercase_method = method.get_method_name().to_ascii_lowercase();
928        let class_meta = self.get_class_like_by_word(lowercase_class)?;
929
930        // First check if there's a trait visibility override for this method
931        if let Some(overridden_visibility) = class_meta.trait_visibility_map.get(&lowercase_method) {
932            return Some(*overridden_visibility);
933        }
934
935        // Fall back to the method's declared visibility
936        let declaring_class = class_meta.declaring_method_ids.get(&lowercase_method)?.get_class_name();
937        let identifier = (declaring_class, lowercase_method);
938
939        self.function_likes
940            .get(&identifier)
941            .and_then(|meta| meta.method_metadata.as_ref())
942            .map(|method_meta| method_meta.visibility)
943    }
944
945    /// Gets thrown types for a function-like, including inherited throws.
946    #[must_use]
947    pub fn get_function_like_thrown_types<'meta>(
948        &'meta self,
949        class_like: Option<&'meta ClassLikeMetadata>,
950        function_like: &'meta FunctionLikeMetadata,
951    ) -> &'meta [TypeMetadata] {
952        if !function_like.thrown_types.is_empty() {
953            return function_like.thrown_types.as_slice();
954        }
955
956        if !function_like.kind.is_method() {
957            return &[];
958        }
959
960        let Some(class_like) = class_like else {
961            return &[];
962        };
963
964        let method_name = &function_like.name;
965
966        if let Some(overridden_map) = class_like.overridden_method_ids.get(method_name) {
967            for (parent_class_name, parent_method_id) in overridden_map {
968                if class_like.name.as_bytes().eq_ignore_ascii_case(parent_class_name.as_bytes()) {
969                    continue; // Skip self-recursion if the method overrides itself
970                }
971
972                let Some(parent_class) = self.class_likes.get(parent_class_name) else {
973                    continue;
974                };
975
976                let parent_method_key = (parent_method_id.get_class_name(), parent_method_id.get_method_name());
977                if let Some(parent_method) = self.function_likes.get(&parent_method_key) {
978                    let thrown = self.get_function_like_thrown_types(Some(parent_class), parent_method);
979                    if !thrown.is_empty() {
980                        return thrown;
981                    }
982                }
983            }
984        }
985
986        &[]
987    }
988
989    /// Gets the class where a property is declared.
990    /// Sees real declarations only; magic `@property*` tags are reachable through
991    /// `ClassLikeMetadata::magic_property_ids`.
992    #[inline]
993    #[must_use]
994    pub fn get_declaring_property_class(&self, class: &[u8], property: &[u8]) -> Option<Word> {
995        let lowercase_class = ascii_lowercase_word(class);
996        let property_name = word(property);
997        self.get_class_like_by_word(lowercase_class)?.declaring_property_ids.get(&property_name).copied()
998    }
999
1000    /// Gets all descendants of a class (recursive).
1001    #[must_use]
1002    pub fn get_all_descendants(&self, class: &[u8]) -> WordSet {
1003        let lowercase_class = ascii_lowercase_word(class);
1004        let lowercase_class = self.resolve_class_like_word(lowercase_class).unwrap_or(lowercase_class);
1005        let mut all_descendants = WordSet::default();
1006        let mut queue = vec![&lowercase_class];
1007        let mut visited = WordSet::default();
1008        visited.insert(lowercase_class);
1009
1010        while let Some(current_name) = queue.pop() {
1011            if let Some(direct_descendants) = self.direct_classlike_descendants.get(current_name) {
1012                for descendant in direct_descendants {
1013                    if visited.insert(*descendant) {
1014                        all_descendants.insert(*descendant);
1015                        queue.push(descendant);
1016                    }
1017                }
1018            }
1019        }
1020
1021        all_descendants
1022    }
1023
1024    /// Generates the synthetic display name for an anonymous class based on
1025    /// its declaring file and span. Delegates to [`crate::get_anonymous_class_name`].
1026    #[must_use]
1027    pub fn get_anonymous_class_name(file: &File, span: Span) -> Word {
1028        crate::get_anonymous_class_name(file, span)
1029    }
1030
1031    /// Retrieves the metadata for an anonymous class based on its declaring
1032    /// file and span.
1033    #[must_use]
1034    pub fn get_anonymous_class(&self, file: &File, span: Span) -> Option<&ClassLikeMetadata> {
1035        let name = Self::get_anonymous_class_name(file, span);
1036        self.get_class_like_by_name(name)
1037    }
1038
1039    /// Gets the file signature for a given file ID.
1040    ///
1041    /// # Arguments
1042    ///
1043    /// * `file_id` - The file identifier
1044    ///
1045    /// # Returns
1046    ///
1047    /// A reference to the `FileSignature` if it exists, or `None` if the file has no signature.
1048    #[inline]
1049    #[must_use]
1050    pub fn get_file_signature(&self, file_id: &FileId) -> Option<&FileSignature> {
1051        self.file_signatures.get(file_id)
1052    }
1053
1054    /// Adds or updates a file signature for a given file ID.
1055    ///
1056    /// # Arguments
1057    ///
1058    /// * `file_id` - The file identifier
1059    /// * `signature` - The file signature
1060    ///
1061    /// # Returns
1062    ///
1063    /// The previous `FileSignature` if it existed.
1064    #[inline]
1065    pub fn set_file_signature(&mut self, file_id: FileId, signature: FileSignature) -> Option<FileSignature> {
1066        self.file_signatures.insert(file_id, signature)
1067    }
1068
1069    /// Marks safe symbols based on diff and invalidation cascade.
1070    ///
1071    /// After this function runs, `self.safe_symbols` and `self.safe_symbol_members`
1072    /// will contain all symbols that can be safely skipped during analysis.
1073    ///
1074    /// # Arguments
1075    ///
1076    /// * `diff` - The computed diff between old and new code
1077    /// * `references` - Symbol reference graph from previous run
1078    ///
1079    /// # Returns
1080    /// Returns the logical names of files whose top-level code references an invalidated
1081    /// symbol. Returns `None` if the cascade was too large to compute.
1082    pub fn mark_safe_symbols(&mut self, diff: &CodebaseDiff, references: &SymbolReferences) -> Option<WordSet> {
1083        let (invalid_symbols, partially_invalid, invalid_files) = references.get_invalid_symbols(diff)?;
1084
1085        // Mark all symbols in 'keep' set as safe (unless invalidated by cascade)
1086        for keep_symbol in diff.get_keep() {
1087            if !invalid_symbols.contains(keep_symbol) {
1088                if keep_symbol.1.is_empty() {
1089                    // Top-level symbol (class, function, constant)
1090                    if !partially_invalid.contains(&keep_symbol.0) {
1091                        self.safe_symbols.insert(keep_symbol.0);
1092                    }
1093                } else {
1094                    // Member (method, property, class constant)
1095                    self.safe_symbol_members.insert(*keep_symbol);
1096                }
1097            }
1098        }
1099
1100        Some(invalid_files)
1101    }
1102
1103    /// Merges information from another `CodebaseMetadata` into this one.
1104    ///
1105    /// When both metadata have the same priority, the one with the smaller span is kept
1106    /// for deterministic results regardless of scan order.
1107    pub fn extend(&mut self, other: CodebaseMetadata) {
1108        let class_likes_changed = !other.class_likes.is_empty();
1109        for (k, mut v) in other.class_likes {
1110            match self.class_likes.entry(k) {
1111                Entry::Occupied(mut entry) => {
1112                    if should_replace_metadata(entry.get().flags, entry.get().span, v.flags, v.span) {
1113                        v.version_constraint.merge(entry.get().version_constraint.clone());
1114                        entry.insert(v);
1115                    } else {
1116                        entry.get_mut().version_constraint.merge(v.version_constraint);
1117                    }
1118                }
1119                Entry::Vacant(entry) => {
1120                    entry.insert(v);
1121                }
1122            }
1123        }
1124
1125        if class_likes_changed && !self.class_like_alias_declarations.is_empty() {
1126            self.class_like_aliases_dirty = true;
1127        }
1128
1129        self.merge_class_like_alias_declarations(other.class_like_alias_declarations);
1130
1131        merge_function_likes(&mut self.function_likes, other.function_likes);
1132
1133        for (k, mut v) in other.constants {
1134            match self.constants.entry(k) {
1135                Entry::Occupied(mut entry) => {
1136                    if should_replace_metadata(entry.get().flags, entry.get().span, v.flags, v.span) {
1137                        v.version_constraint.merge(entry.get().version_constraint.clone());
1138                        entry.insert(v);
1139                    } else {
1140                        entry.get_mut().version_constraint.merge(v.version_constraint);
1141                    }
1142                }
1143                Entry::Vacant(entry) => {
1144                    entry.insert(v);
1145                }
1146            }
1147        }
1148
1149        self.symbols.extend(other.symbols);
1150
1151        for (k, v) in other.all_class_like_descendants {
1152            self.all_class_like_descendants.entry(k).or_default().extend(v);
1153        }
1154
1155        for (k, v) in other.direct_classlike_descendants {
1156            self.direct_classlike_descendants.entry(k).or_default().extend(v);
1157        }
1158
1159        self.file_signatures.extend(other.file_signatures);
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, 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(&mut self, incoming: impl IntoIterator<Item = ((Word, Word), FunctionLikeMetadata)>) {
1314        for (k, v) in incoming {
1315            match self.patch_function_likes.entry(k) {
1316                Entry::Occupied(mut entry) => {
1317                    if k.0.is_empty() {
1318                        let diagnostic = duplicate_patch_function_diagnostic(entry.get(), &v);
1319                        entry.get_mut().issues.push(diagnostic);
1320                    }
1321                }
1322                Entry::Vacant(entry) => {
1323                    entry.insert(v);
1324                }
1325            }
1326        }
1327    }
1328
1329    /// Merges patch constants from another codebase, diagnosing collisions.
1330    fn merge_patch_constants(&mut self, incoming: impl IntoIterator<Item = (Word, ConstantMetadata)>) {
1331        for (k, v) in incoming {
1332            match self.patch_constants.entry(k) {
1333                Entry::Occupied(mut entry) => {
1334                    let diagnostic = duplicate_patch_constant_diagnostic(entry.get(), &v);
1335                    entry.get_mut().issues.push(diagnostic);
1336                }
1337                Entry::Vacant(entry) => {
1338                    entry.insert(v);
1339                }
1340            }
1341        }
1342    }
1343
1344    /// Moves every scanned entry of this per-file partial into the patch maps.
1345    ///
1346    /// Called on a per-file partial right after `scan_program` when the file is a
1347    /// [`FileType::Patch`]. Symbols and descendants from a patch partial are dropped — the
1348    /// FQCN belongs to whichever non-patch source originally declared it (or it's an orphan
1349    /// which `apply_patches_pass` will diagnose later).
1350    pub fn convert_partial_to_patch(&mut self) {
1351        for (k, v) in std::mem::take(&mut self.class_likes) {
1352            self.patch_class_likes.insert(k, v);
1353        }
1354
1355        for (k, v) in std::mem::take(&mut self.function_likes) {
1356            self.patch_function_likes.insert(k, v);
1357        }
1358
1359        for (k, v) in std::mem::take(&mut self.constants) {
1360            self.patch_constants.insert(k, v);
1361        }
1362
1363        self.symbols = Symbols::new();
1364        self.class_like_aliases.clear();
1365        self.class_like_alias_declarations.clear();
1366        self.class_like_aliases_dirty = false;
1367        self.all_class_like_descendants.clear();
1368        self.direct_classlike_descendants.clear();
1369    }
1370
1371    /// Folds every entry in the `patch_*` maps into the matching vendor / built-in entry,
1372    /// attaching validation diagnostics to the patch entry's `issues` list.
1373    ///
1374    /// At most one patch may target a given symbol, so each entry is applied directly to its
1375    /// target. A patch whose target is user-defined is inert (user definitions win); a patch
1376    /// with no matching target is diagnosed as an orphan.
1377    ///
1378    /// Must be called after all partials have been merged so the slots patches target are
1379    /// present.
1380    pub fn apply_patches_pass(&mut self) {
1381        // `(class, method)` slots where a patch overrides a method inherited from an ancestor.
1382        // No function-like exists at these keys yet, so the function loop below materializes
1383        // them from the patch's own scanned declaration rather than treating them as orphans.
1384        let mut inherited_overrides: HashSet<(Word, Word)> = HashSet::default();
1385
1386        let class_keys: Vec<Word> = self.patch_class_likes.keys().copied().collect();
1387        for fqcn in class_keys {
1388            let Some(target) = self.class_likes.get(&fqcn) else {
1389                if let Some(p) = self.patch_class_likes.get_mut(&fqcn) {
1390                    let diag = orphan_patch_class_diagnostic(p);
1391                    p.issues.push(diag);
1392                }
1393                continue;
1394            };
1395            // User-defined targets win; the patch entry is inert. Leave any scan-time issues
1396            // on it intact — they still belong to the patch source.
1397            if target.flags.is_user_defined() {
1398                continue;
1399            }
1400
1401            let mut working = target.clone();
1402            let inherited =
1403                collect_inherited_patch_methods(&working, &self.patch_class_likes[&fqcn], &self.class_likes);
1404            inherited_overrides.extend(inherited.iter().map(|method| (fqcn, *method)));
1405            if let Some(patch_entry) = self.patch_class_likes.get_mut(&fqcn) {
1406                working.apply_patch(patch_entry, &inherited);
1407            }
1408            self.class_likes.insert(fqcn, working);
1409        }
1410
1411        let func_keys: Vec<(Word, Word)> = self.patch_function_likes.keys().copied().collect();
1412        for key in func_keys {
1413            let Some(target) = self.function_likes.get(&key) else {
1414                if inherited_overrides.contains(&key) {
1415                    // The patch overrides a method inherited from an ancestor, so no slot exists
1416                    // at `(class, method)` yet. The patch file declares the method in full, so
1417                    // promote its scanned function-like as this class's own declaration; the
1418                    // class loop has already pointed the declaring/appearing ids at this slot.
1419                    if let Some(p) = self.patch_function_likes.get(&key) {
1420                        let materialized = p.clone();
1421                        self.function_likes.insert(key, materialized);
1422                    }
1423                    continue;
1424                }
1425                // Methods of an orphan patch class are covered by the class-level diagnostic;
1426                // only free functions need their own orphan diagnostic.
1427                if key.0.is_empty()
1428                    && let Some(p) = self.patch_function_likes.get_mut(&key)
1429                {
1430                    let diag = orphan_patch_function_diagnostic(p);
1431                    p.issues.push(diag);
1432                }
1433                continue;
1434            };
1435            if target.flags.is_user_defined() {
1436                continue;
1437            }
1438
1439            let mut working = target.clone();
1440            if let Some(patch_entry) = self.patch_function_likes.get_mut(&key) {
1441                working.apply_patch(patch_entry);
1442            }
1443            self.function_likes.insert(key, working);
1444        }
1445
1446        let const_keys: Vec<Word> = self.patch_constants.keys().copied().collect();
1447        for fqcn in const_keys {
1448            let Some(target) = self.constants.get(&fqcn) else {
1449                if let Some(p) = self.patch_constants.get_mut(&fqcn) {
1450                    let diag = orphan_patch_constant_diagnostic(p);
1451                    p.issues.push(diag);
1452                }
1453                continue;
1454            };
1455            if target.flags.is_user_defined() {
1456                continue;
1457            }
1458
1459            let mut working = target.clone();
1460            if let Some(patch_entry) = self.patch_constants.get(&fqcn) {
1461                working.apply_patch(patch_entry);
1462            }
1463            self.constants.insert(fqcn, working);
1464        }
1465    }
1466
1467    /// Extracts only the keys that this per-file metadata currently "owns" in the given
1468    /// merged codebase; i.e. keys whose span in `merged` matches this metadata's span.
1469    ///
1470    /// This is what you want for incremental fingerprints. [`extract_keys`](Self::extract_keys)
1471    /// captures *every* key the scan produced, including ones that lost the tiebreak in
1472    /// [`extend`](Self::extend) / [`extend_ref`](Self::extend_ref) when another file defined
1473    /// the same FQN. Using `extract_keys` as a removal fingerprint then causes a nasty
1474    /// cross-file bug: touching file *B* can remove an entry that file *A* actually owns,
1475    /// because [`remove_entries_by_keys`](Self::remove_entries_by_keys) deletes by FQN
1476    /// without checking who the current owner is. The analyzer then reports a spurious
1477    /// "duplicate definition" when it walks *A* and finds *B*'s span in the codebase.
1478    ///
1479    /// By only recording the keys whose spans still match *this* metadata, removing the
1480    /// fingerprint later becomes a safe no-op when another file won the merge. The
1481    /// removal only drops the entries this file genuinely put into the merged codebase.
1482    #[must_use]
1483    pub fn extract_owned_keys(&self, merged: &CodebaseMetadata) -> CodebaseEntryKeys {
1484        let class_like_names = self
1485            .class_likes
1486            .iter()
1487            .filter(|(name, meta)| merged.class_likes.get(*name).is_some_and(|m| m.span == meta.span))
1488            .map(|(name, _)| *name)
1489            .collect();
1490
1491        let class_like_aliases = self
1492            .class_like_alias_declarations
1493            .iter()
1494            .filter(|(name, (_, span, _))| {
1495                merged.class_like_alias_declarations.get(*name).is_some_and(|(_, merged_span, _)| merged_span == span)
1496            })
1497            .map(|(alias, (target, span, _))| (*alias, *target, *span))
1498            .collect();
1499
1500        let function_like_keys = self
1501            .function_likes
1502            .iter()
1503            .filter(|(key, meta)| merged.function_likes.get(*key).is_some_and(|m| m.span == meta.span))
1504            .map(|(key, _)| *key)
1505            .collect();
1506
1507        let constant_names = self
1508            .constants
1509            .iter()
1510            .filter(|(name, meta)| merged.constants.get(*name).is_some_and(|m| m.span == meta.span))
1511            .map(|(name, _)| *name)
1512            .collect();
1513
1514        // A file signature is always owned by its file (there is at most one per file).
1515        let file_ids = self.file_signatures.keys().copied().collect();
1516
1517        CodebaseEntryKeys { class_like_names, class_like_aliases, function_like_keys, constant_names, file_ids }
1518    }
1519
1520    /// Removes entries whose keys match the given [`CodebaseEntryKeys`].
1521    ///
1522    /// This is the lightweight equivalent of [`remove_entries_of()`] — it performs the
1523    /// same removals but from a compact key set instead of a full `CodebaseMetadata` reference.
1524    pub fn remove_entries_by_keys(&mut self, keys: &CodebaseEntryKeys) {
1525        if !keys.class_like_names.is_empty() && !self.class_like_alias_declarations.is_empty() {
1526            self.class_like_aliases_dirty = true;
1527        }
1528
1529        for k in &keys.class_like_names {
1530            self.class_likes.remove(k);
1531            self.symbols.remove(*k);
1532        }
1533
1534        for (alias, _, _) in &keys.class_like_aliases {
1535            self.class_like_alias_declarations.remove(alias);
1536            self.class_like_aliases_dirty = true;
1537        }
1538
1539        for k in &keys.function_like_keys {
1540            self.function_likes.remove(k);
1541        }
1542
1543        for k in &keys.constant_names {
1544            self.constants.remove(k);
1545        }
1546
1547        for k in &keys.file_ids {
1548            self.file_signatures.remove(k);
1549        }
1550
1551        // Drop any patch entry that originated from a file signature we just removed; a patch
1552        // entry's originating file is recorded on its span.
1553        let removed_files: HashSet<FileId> = keys.file_ids.iter().copied().collect();
1554        self.patch_class_likes.retain(|_, m| !removed_files.contains(&m.span.file_id));
1555        self.patch_function_likes.retain(|_, m| !removed_files.contains(&m.span.file_id));
1556        self.patch_constants.retain(|_, m| !removed_files.contains(&m.span.file_id));
1557    }
1558
1559    /// Takes all issues from the codebase metadata.
1560    pub fn take_issues(&mut self, user_defined: bool) -> IssueCollection {
1561        let mut issues = IssueCollection::new();
1562
1563        for meta in self.class_likes.values_mut() {
1564            if user_defined && !meta.flags.is_user_defined() {
1565                continue;
1566            }
1567            issues.extend(meta.take_issues());
1568        }
1569
1570        for meta in self.function_likes.values_mut() {
1571            if user_defined && !meta.flags.is_user_defined() {
1572                continue;
1573            }
1574            issues.extend(meta.take_issues());
1575        }
1576
1577        for meta in self.constants.values_mut() {
1578            if user_defined && !meta.flags.is_user_defined() {
1579                continue;
1580            }
1581            issues.extend(meta.take_issues());
1582        }
1583
1584        // Patches are user-authored, so their issues are always reported regardless of the
1585        // `user_defined` filter. They live in their own maps and never appear in the regular
1586        // class_likes/function_likes/constants iteration above.
1587        for meta in self.patch_class_likes.values_mut() {
1588            issues.extend(meta.take_issues());
1589        }
1590
1591        for meta in self.patch_function_likes.values_mut() {
1592            issues.extend(meta.take_issues());
1593        }
1594
1595        for meta in self.patch_constants.values_mut() {
1596            issues.extend(meta.take_issues());
1597        }
1598
1599        issues
1600    }
1601
1602    /// Gets all file IDs that have signatures in this metadata.
1603    ///
1604    /// This is a helper method for incremental analysis to iterate over all files.
1605    #[must_use]
1606    pub fn get_all_file_ids(&self) -> Vec<FileId> {
1607        self.file_signatures.keys().copied().collect()
1608    }
1609}
1610
1611/// Returns the subset of methods declared by `patch` that are inherited by `target` from
1612/// an ancestor but not declared on `target` itself. Used by `apply_patch` on class-like
1613/// metadata to distinguish patch-declared overrides of inherited methods (allowed) from
1614/// patch-introduced new methods (disallowed).
1615fn collect_inherited_patch_methods(
1616    target: &ClassLikeMetadata,
1617    patch: &ClassLikeMetadata,
1618    class_likes: &WordMap<ClassLikeMetadata>,
1619) -> WordSet {
1620    if patch.methods.is_empty() {
1621        return WordSet::default();
1622    }
1623    let ancestor_methods = class_like::collect_ancestor_methods(target, class_likes);
1624    patch.methods.iter().filter(|m| ancestor_methods.contains(*m)).copied().collect()
1625}
1626
1627fn duplicate_patch_class_diagnostic(kept: &ClassLikeMetadata, dropped: &ClassLikeMetadata) -> Issue {
1628    Issue::error(format!(
1629        "Multiple patches target `{}`; at most one patch may target a given symbol.",
1630        kept.original_name
1631    ))
1632    .with_code(ScanningIssueKind::PatchDuplicateTarget)
1633    .with_annotation(Annotation::primary(dropped.span).with_message("Duplicate patch for this symbol."))
1634    .with_annotation(Annotation::secondary(kept.span).with_message("Already patched here."))
1635    .with_help("Merge the conflicting declarations into a single patch, or remove all but one.")
1636}
1637
1638fn duplicate_patch_function_diagnostic(kept: &FunctionLikeMetadata, dropped: &FunctionLikeMetadata) -> Issue {
1639    Issue::error(format!(
1640        "Multiple patches target function `{}`; at most one patch may target a given symbol.",
1641        kept.name
1642    ))
1643    .with_code(ScanningIssueKind::PatchDuplicateTarget)
1644    .with_annotation(Annotation::primary(dropped.span).with_message("Duplicate patch for this function."))
1645    .with_annotation(Annotation::secondary(kept.span).with_message("Already patched here."))
1646    .with_help("Merge the conflicting declarations into a single patch, or remove all but one.")
1647}
1648
1649fn duplicate_patch_constant_diagnostic(kept: &ConstantMetadata, dropped: &ConstantMetadata) -> Issue {
1650    Issue::error(format!(
1651        "Multiple patches target constant `{}`; at most one patch may target a given symbol.",
1652        kept.name
1653    ))
1654    .with_code(ScanningIssueKind::PatchDuplicateTarget)
1655    .with_annotation(Annotation::primary(dropped.span).with_message("Duplicate patch for this constant."))
1656    .with_annotation(Annotation::secondary(kept.span).with_message("Already patched here."))
1657    .with_help("Merge the conflicting declarations into a single patch, or remove all but one.")
1658}
1659
1660fn orphan_patch_class_diagnostic(meta: &ClassLikeMetadata) -> Issue {
1661    Issue::error(format!(
1662        "Patch declares `{}` but no vendored or built-in definition exists to patch.",
1663        meta.original_name,
1664    ))
1665    .with_code(ScanningIssueKind::PatchIntroducesNewSymbol)
1666    .with_annotation(Annotation::primary(meta.span))
1667    .with_help(
1668        "The patch may be misnamed or out-of-date relative to the vendored or built-in definition; \
1669         check the symbol name and verify the patch still matches the upstream source.",
1670    )
1671}
1672
1673fn orphan_patch_function_diagnostic(meta: &FunctionLikeMetadata) -> Issue {
1674    Issue::error(format!(
1675        "Patch declares function `{}` but no vendored or built-in definition exists to patch.",
1676        meta.name,
1677    ))
1678    .with_code(ScanningIssueKind::PatchIntroducesNewSymbol)
1679    .with_annotation(Annotation::primary(meta.span))
1680    .with_help(
1681        "The patch may be misnamed or out-of-date relative to the vendored or built-in definition; \
1682         check the function name and verify the patch still matches the upstream source.",
1683    )
1684}
1685
1686fn orphan_patch_constant_diagnostic(meta: &ConstantMetadata) -> Issue {
1687    Issue::error(format!(
1688        "Patch declares constant `{}` but no vendored or built-in definition exists to patch.",
1689        meta.name,
1690    ))
1691    .with_code(ScanningIssueKind::PatchIntroducesNewSymbol)
1692    .with_annotation(Annotation::primary(meta.span))
1693    .with_help(
1694        "The patch may be misnamed or out-of-date relative to the vendored or built-in definition; \
1695         check the constant name and verify the patch still matches the upstream source.",
1696    )
1697}
1698
1699fn merge_function_likes(
1700    target: &mut HashMap<(Word, Word), FunctionLikeMetadata>,
1701    incoming: HashMap<(Word, Word), FunctionLikeMetadata>,
1702) {
1703    for (key, mut metadata) in incoming {
1704        match target.entry(key) {
1705            Entry::Occupied(mut entry) => {
1706                if should_replace_metadata(entry.get().flags, entry.get().span, metadata.flags, metadata.span) {
1707                    metadata.version_constraint.merge(entry.get().version_constraint.clone());
1708                    entry.insert(metadata);
1709                } else {
1710                    entry.get_mut().version_constraint.merge(metadata.version_constraint);
1711                }
1712            }
1713            Entry::Vacant(entry) => {
1714                entry.insert(metadata);
1715            }
1716        }
1717    }
1718}
1719
1720/// Determines which metadata value to keep when merging duplicates.
1721///
1722/// Priority:
1723///   1. user-defined > patch > external > built-in > other.
1724///   2. non-polyfill > polyfill — tools like rector/phpstan/psalm ship
1725///      skeleton stubs gated by `if (!class_exists('X'))` that should never
1726///      shadow a concrete definition.
1727///   3. smaller span wins as a deterministic tie-breaker.
1728///
1729/// Returns `true` if the new value should replace the existing one.
1730fn should_replace_metadata(
1731    existing_flags: MetadataFlags,
1732    existing_span: Span,
1733    new_flags: MetadataFlags,
1734    new_span: Span,
1735) -> bool {
1736    let new_is_user_defined = new_flags.is_user_defined();
1737    let existing_is_user_defined = existing_flags.is_user_defined();
1738
1739    if new_is_user_defined != existing_is_user_defined {
1740        return new_is_user_defined;
1741    }
1742
1743    let new_is_patch = new_flags.is_patch();
1744    let existing_is_patch = existing_flags.is_patch();
1745
1746    if new_is_patch != existing_is_patch {
1747        return new_is_patch;
1748    }
1749
1750    let new_is_external = new_flags.is_external();
1751    let existing_is_external = existing_flags.is_external();
1752
1753    if new_is_external != existing_is_external {
1754        return new_is_external;
1755    }
1756
1757    let new_is_built_in = new_flags.is_built_in();
1758    let existing_is_built_in = existing_flags.is_built_in();
1759
1760    if new_is_built_in != existing_is_built_in {
1761        return new_is_built_in;
1762    }
1763
1764    let new_is_polyfill = new_flags.is_polyfill();
1765    let existing_is_polyfill = existing_flags.is_polyfill();
1766
1767    if new_is_polyfill != existing_is_polyfill {
1768        return !new_is_polyfill;
1769    }
1770
1771    new_span < existing_span
1772}
1773
1774#[cfg(test)]
1775mod should_replace_metadata_tests {
1776    use super::*;
1777
1778    #[test]
1779    fn non_polyfill_replaces_polyfill() {
1780        let polyfill = MetadataFlags::POLYFILL;
1781        let real = MetadataFlags::empty();
1782        assert!(should_replace_metadata(polyfill, Span::dummy(0, 100), real, Span::dummy(0, 100)));
1783        assert!(!should_replace_metadata(real, Span::dummy(0, 100), polyfill, Span::dummy(0, 100)));
1784    }
1785
1786    #[test]
1787    fn polyfill_does_not_replace_non_polyfill_even_with_smaller_span() {
1788        let real = MetadataFlags::empty();
1789        let polyfill = MetadataFlags::POLYFILL;
1790        assert!(!should_replace_metadata(real, Span::dummy(500, 600), polyfill, Span::dummy(0, 10)));
1791    }
1792
1793    #[test]
1794    fn user_defined_beats_polyfill_flag() {
1795        let polyfill_user = MetadataFlags::POLYFILL | MetadataFlags::USER_DEFINED;
1796        let plain = MetadataFlags::empty();
1797        assert!(!should_replace_metadata(polyfill_user, Span::dummy(0, 10), plain, Span::dummy(0, 10)));
1798        assert!(should_replace_metadata(plain, Span::dummy(0, 10), polyfill_user, Span::dummy(0, 10)));
1799    }
1800
1801    #[test]
1802    fn two_user_defined_fall_through_to_polyfill_check() {
1803        let a = MetadataFlags::POLYFILL | MetadataFlags::USER_DEFINED;
1804        let b = MetadataFlags::USER_DEFINED;
1805        assert!(should_replace_metadata(a, Span::dummy(0, 10), b, Span::dummy(0, 10)));
1806        assert!(!should_replace_metadata(b, Span::dummy(0, 10), a, Span::dummy(0, 10)));
1807    }
1808
1809    #[test]
1810    fn two_non_polyfills_fall_through_to_priority_rules() {
1811        let user = MetadataFlags::USER_DEFINED;
1812        let builtin = MetadataFlags::BUILTIN;
1813        assert!(!should_replace_metadata(user, Span::dummy(0, 10), builtin, Span::dummy(0, 10)));
1814        assert!(should_replace_metadata(builtin, Span::dummy(0, 10), user, Span::dummy(0, 10)));
1815    }
1816
1817    #[test]
1818    fn patch_beats_vendored() {
1819        let vendored = MetadataFlags::empty();
1820        let patch = MetadataFlags::PATCH;
1821        assert!(should_replace_metadata(vendored, Span::dummy(0, 100), patch, Span::dummy(0, 100)));
1822        assert!(!should_replace_metadata(patch, Span::dummy(0, 100), vendored, Span::dummy(0, 100)));
1823    }
1824
1825    #[test]
1826    fn patch_beats_builtin() {
1827        let builtin = MetadataFlags::BUILTIN;
1828        let patch = MetadataFlags::PATCH;
1829        assert!(should_replace_metadata(builtin, Span::dummy(0, 100), patch, Span::dummy(0, 100)));
1830        assert!(!should_replace_metadata(patch, Span::dummy(0, 100), builtin, Span::dummy(0, 100)));
1831    }
1832
1833    #[test]
1834    fn external_beats_builtin_and_vendored() {
1835        let external = MetadataFlags::EXTERNAL;
1836        let builtin = MetadataFlags::BUILTIN;
1837        let vendored = MetadataFlags::empty();
1838
1839        assert!(should_replace_metadata(builtin, Span::dummy(0, 100), external, Span::dummy(500, 600)));
1840        assert!(!should_replace_metadata(external, Span::dummy(500, 600), builtin, Span::dummy(0, 100)));
1841        assert!(should_replace_metadata(vendored, Span::dummy(0, 100), external, Span::dummy(500, 600)));
1842        assert!(!should_replace_metadata(external, Span::dummy(500, 600), vendored, Span::dummy(0, 100)));
1843    }
1844
1845    #[test]
1846    fn patch_and_user_defined_beat_external() {
1847        let external = MetadataFlags::EXTERNAL;
1848        let patch = MetadataFlags::PATCH;
1849        let user = MetadataFlags::USER_DEFINED;
1850
1851        assert!(should_replace_metadata(external, Span::dummy(0, 100), patch, Span::dummy(500, 600)));
1852        assert!(!should_replace_metadata(patch, Span::dummy(500, 600), external, Span::dummy(0, 100)));
1853        assert!(should_replace_metadata(external, Span::dummy(0, 100), user, Span::dummy(500, 600)));
1854        assert!(!should_replace_metadata(user, Span::dummy(500, 600), external, Span::dummy(0, 100)));
1855    }
1856
1857    #[test]
1858    fn user_defined_beats_patch() {
1859        let user = MetadataFlags::USER_DEFINED;
1860        let patch = MetadataFlags::PATCH;
1861        assert!(!should_replace_metadata(user, Span::dummy(0, 100), patch, Span::dummy(0, 100)));
1862        assert!(should_replace_metadata(patch, Span::dummy(0, 100), user, Span::dummy(0, 100)));
1863    }
1864
1865    #[test]
1866    fn patch_does_not_beat_user_defined_even_with_smaller_span() {
1867        let user = MetadataFlags::USER_DEFINED;
1868        let patch = MetadataFlags::PATCH;
1869        assert!(!should_replace_metadata(user, Span::dummy(500, 600), patch, Span::dummy(0, 10)));
1870    }
1871
1872    #[test]
1873    #[allow(clippy::expect_used)]
1874    fn patch_function_like_leaves_vendor_owning_slot() {
1875        // Patches may only refine type information on an existing function-like; they must
1876        // never become the slot owner. The non-patch source's span/file id stay put so that
1877        // `extract_owned_keys` records vendor-as-owner — otherwise the patch's entry would
1878        // outlive a vendor deletion in incremental mode (orphan function-like bug).
1879        use crate::metadata::function_like::FunctionLikeKind;
1880
1881        let name = word("foo");
1882        let key = (empty_word(), name);
1883        let vendor_span = Span::dummy(0, 100);
1884        let patch_span = Span::dummy(500, 600);
1885
1886        let vendor =
1887            FunctionLikeMetadata::new(FunctionLikeKind::Function, name, name, vendor_span, MetadataFlags::empty());
1888        let mut codebase = CodebaseMetadata::new();
1889        codebase.function_likes.insert(key, vendor);
1890
1891        let patch = FunctionLikeMetadata::new(FunctionLikeKind::Function, name, name, patch_span, MetadataFlags::PATCH);
1892        codebase.patch_function_likes.insert(key, patch);
1893
1894        codebase.apply_patches_pass();
1895
1896        let merged = codebase.function_likes.get(&key).expect("function-like must remain after patch");
1897        assert_eq!(merged.span, vendor_span, "patch must not move the slot's span");
1898        assert!(!merged.flags.is_patch(), "patch must not flip the slot's flags");
1899    }
1900
1901    #[test]
1902    fn patch_does_not_apply_to_user_defined_class() {
1903        let class_name = word("MyClass");
1904        let method_existing = word("doIt");
1905
1906        let mut user_class =
1907            ClassLikeMetadata::new(class_name, class_name, Span::dummy(0, 100), None, MetadataFlags::USER_DEFINED);
1908        user_class.methods.insert(method_existing);
1909
1910        let mut codebase = CodebaseMetadata::new();
1911        codebase.class_likes.insert(class_name, user_class);
1912
1913        let mut patch_class =
1914            ClassLikeMetadata::new(class_name, class_name, Span::dummy(0, 50), None, MetadataFlags::PATCH);
1915        let method_new = word("patchedMethod");
1916        patch_class.methods.insert(method_new);
1917
1918        codebase.patch_class_likes.insert(class_name, patch_class);
1919
1920        codebase.apply_patches_pass();
1921
1922        let class = &codebase.class_likes[&class_name];
1923        // Patch must not apply to a user-defined class.
1924        assert!(!class.methods.contains(&method_new));
1925        // User-defined class must be preserved intact.
1926        assert!(class.methods.contains(&method_existing));
1927        assert!(class.flags.is_user_defined());
1928        // No issues should be emitted.
1929        assert!(class.issues.is_empty());
1930    }
1931}