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