Skip to main content

mago_codex/metadata/
mod.rs

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