Skip to main content

mago_codex/metadata/
class_like.rs

1use std::borrow::Borrow;
2use std::sync::Arc;
3
4use foldhash::fast::RandomState;
5use indexmap::IndexMap;
6use mago_php_version::PHPVersion;
7use mago_php_version::PHPVersionRange;
8
9use mago_reporting::Annotation;
10use mago_reporting::Issue;
11use mago_span::Span;
12use mago_word::Word;
13use mago_word::WordMap;
14use mago_word::WordSet;
15
16use crate::flags::attribute::AttributeFlags;
17use crate::identifier::method::MethodIdentifier;
18use crate::issue::ScanningIssueKind;
19use crate::metadata::attribute::AttributeMetadata;
20use crate::metadata::class_like_constant::ClassLikeConstantMetadata;
21use crate::metadata::enum_case::EnumCaseMetadata;
22use crate::metadata::flags::MetadataFlags;
23use crate::metadata::property::PropertyMetadata;
24use crate::metadata::trait_adaptation::TraitMethodAdaptations;
25use crate::metadata::ttype::TypeMetadata;
26use crate::metadata::version_constraint::VersionConstraint;
27use crate::symbol::SymbolKind;
28use crate::ttype::atomic::TAtomic;
29use crate::ttype::template::GenericTemplate;
30use crate::ttype::template::variance::Variance;
31use crate::ttype::union::TUnion;
32use crate::visibility::Visibility;
33
34/// Type alias for template types stored in metadata.
35/// Maps template parameter names to their defining entity and constraint type.
36pub type TemplateTypes = IndexMap<Word, GenericTemplate, RandomState>;
37
38#[derive(Clone, Copy, Debug, PartialEq, Eq)]
39#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
40enum DeclaredAncestor {
41    ParentClass(Word),
42    ParentInterface(Word),
43    Trait(Word),
44    RequiredClass(Word),
45    RequiredInterface(Word),
46}
47
48/// Contains comprehensive metadata for a PHP class-like structure (class, interface, trait, enum).
49///
50/// Aggregates information about inheritance, traits, generics, methods, properties, constants,
51/// attributes, docblock tags, analysis flags, and more.
52#[derive(Clone, Debug, PartialEq, Eq)]
53#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
54#[non_exhaustive]
55pub struct ClassLikeMetadata {
56    pub name: Word,
57    pub original_name: Word,
58    #[cfg_attr(feature = "serde", serde(default))]
59    pub aliases: Vec<Word>,
60    pub span: Span,
61    pub direct_parent_interfaces: WordSet,
62    pub all_parent_interfaces: WordSet,
63    pub direct_parent_class: Option<Word>,
64    pub require_extends: WordSet,
65    pub require_implements: WordSet,
66    pub all_parent_classes: WordSet,
67    pub used_traits: WordSet,
68    #[cfg_attr(feature = "serde", serde(default))]
69    declared_ancestry: Option<Box<[DeclaredAncestor]>>,
70    pub trait_alias_map: WordMap<Word>,
71    pub trait_visibility_map: WordMap<Visibility>,
72    pub trait_final_map: WordSet,
73    #[cfg_attr(feature = "serde", serde(default))]
74    pub(crate) trait_method_adaptations: Option<Box<TraitMethodAdaptations>>,
75    pub child_class_likes: Option<WordSet>,
76    pub name_span: Option<Span>,
77    pub kind: SymbolKind,
78    pub template_types: TemplateTypes,
79    pub template_readonly: WordSet,
80    pub template_variance: Vec<Variance>,
81    pub template_extended_offsets: WordMap<Vec<TUnion>>,
82    pub template_extended_parameters: WordMap<IndexMap<Word, TUnion, RandomState>>,
83    pub template_extended_parameter_paths: WordMap<Vec<IndexMap<Word, TUnion, RandomState>>>,
84    pub template_type_extends_count: WordMap<usize>,
85    pub template_type_implements_count: WordMap<usize>,
86    pub template_type_uses_count: WordMap<usize>,
87    pub methods: WordSet,
88    pub pseudo_methods: WordSet,
89    pub static_pseudo_methods: WordSet,
90    pub declaring_method_ids: WordMap<MethodIdentifier>,
91    pub appearing_method_ids: WordMap<MethodIdentifier>,
92    pub inheritable_method_ids: WordMap<MethodIdentifier>,
93    pub overridden_method_ids: WordMap<Arc<IndexMap<Word, MethodIdentifier, RandomState>>>,
94    pub properties: WordMap<PropertyMetadata>,
95    /// Magic properties documented via `@property`/`@property-read`/`@property-write` in this
96    /// class-like's own docblock.
97    ///
98    /// These describe the external `__get`/`__set` interface and are kept separate from the
99    /// real declarations in `properties`; which of the two governs a given access is decided
100    /// at resolution time from the call site's scope.  Inherited tags are reachable through
101    /// `magic_property_ids`, mirroring how `declaring_property_ids` works for real properties.
102    pub magic_properties: WordMap<PropertyMetadata>,
103    /// Maps every magic property name reachable on this class-like (own or inherited) to the
104    /// class-like whose docblock declares the tag.  An own tag beats inherited ones; between
105    /// tags inherited from unrelated parents, the first-populated parent wins (as with real
106    /// property inheritance).
107    pub magic_property_ids: WordMap<Word>,
108    pub appearing_property_ids: WordMap<Word>,
109    pub declaring_property_ids: WordMap<Word>,
110    pub inheritable_property_ids: WordMap<Word>,
111    pub overridden_property_ids: WordMap<WordSet>,
112    pub initialized_properties: WordSet,
113    pub constants: WordMap<ClassLikeConstantMetadata>,
114    #[cfg_attr(feature = "serde", serde(default))]
115    declared_constants: Option<Box<[Word]>>,
116    pub trait_constant_ids: WordMap<Word>,
117    pub enum_cases: WordMap<EnumCaseMetadata>,
118    pub invalid_dependencies: WordSet,
119    pub attributes: Vec<AttributeMetadata>,
120    pub enum_type: Option<TAtomic>,
121    pub has_sealed_methods: Option<bool>,
122    pub has_sealed_properties: Option<bool>,
123    pub permitted_inheritors: Option<WordSet>,
124    pub issues: Vec<Issue>,
125    pub attribute_flags: Option<AttributeFlags>,
126    pub flags: MetadataFlags,
127    pub type_aliases: WordMap<TypeMetadata>,
128    /// Imported type aliases in the form of (`from_fqcn`, `type_name`, span)
129    pub imported_type_aliases: WordMap<(Word, Word, Span)>,
130    /// Mixin types from @mixin annotations - these types' methods/properties
131    /// can be accessed via magic methods (__call, __get, __set, __callStatic)
132    pub mixins: Vec<TypeMetadata>,
133    #[cfg_attr(feature = "serde", serde(default))]
134    declared_mixin_count: Option<usize>,
135    pub version_constraint: VersionConstraint,
136}
137
138impl ClassLikeMetadata {
139    /// Returns whether this class-like's inherited metadata is incomplete.
140    ///
141    /// Synthetic enum contracts are materialized by the scanner and do not make
142    /// an enum incomplete when their own metadata is unavailable.
143    #[inline]
144    #[must_use]
145    pub fn has_incomplete_hierarchy(&self) -> bool {
146        self.incomplete_hierarchy_dependencies().next().is_some()
147    }
148
149    /// Returns the unresolved dependencies that make this class-like's
150    /// inherited metadata incomplete.
151    ///
152    /// Synthetic enum contracts are materialized by the scanner and are not
153    /// exposed as unresolved hierarchy dependencies.
154    #[inline]
155    pub fn incomplete_hierarchy_dependencies(&self) -> impl Iterator<Item = Word> + '_ {
156        let is_enum = self.kind.is_enum();
157        self.invalid_dependencies.iter().copied().filter(move |dependency| {
158            !is_enum
159                || !matches!(
160                    dependency.as_bytes(),
161                    b"unitenum"
162                        | b"backedenum"
163                        | b"__internal_do_not_use__intbackedenum"
164                        | b"__internal_do_not_use__stringbackedenum"
165                )
166        })
167    }
168
169    #[must_use]
170    pub fn new(
171        name: Word,
172        original_name: Word,
173        span: Span,
174        name_span: Option<Span>,
175        flags: MetadataFlags,
176    ) -> ClassLikeMetadata {
177        ClassLikeMetadata {
178            constants: WordMap::default(),
179            declared_constants: None,
180            trait_constant_ids: WordMap::default(),
181            enum_cases: WordMap::default(),
182            flags,
183            kind: SymbolKind::Class,
184            direct_parent_interfaces: WordSet::default(),
185            all_parent_classes: WordSet::default(),
186            appearing_method_ids: WordMap::default(),
187            attributes: Vec::new(),
188            all_parent_interfaces: WordSet::default(),
189            declaring_method_ids: WordMap::default(),
190            appearing_property_ids: WordMap::default(),
191            declaring_property_ids: WordMap::default(),
192            direct_parent_class: None,
193            require_extends: WordSet::default(),
194            require_implements: WordSet::default(),
195            inheritable_method_ids: WordMap::default(),
196            enum_type: None,
197            inheritable_property_ids: WordMap::default(),
198            initialized_properties: WordSet::default(),
199            invalid_dependencies: WordSet::default(),
200            span,
201            name_span,
202            methods: WordSet::default(),
203            pseudo_methods: WordSet::default(),
204            static_pseudo_methods: WordSet::default(),
205            overridden_method_ids: WordMap::default(),
206            overridden_property_ids: WordMap::default(),
207            properties: WordMap::default(),
208            magic_properties: WordMap::default(),
209            magic_property_ids: WordMap::default(),
210            template_variance: Vec::new(),
211            template_type_extends_count: WordMap::default(),
212            template_extended_parameters: WordMap::default(),
213            template_extended_parameter_paths: WordMap::default(),
214            template_extended_offsets: WordMap::default(),
215            template_type_implements_count: WordMap::default(),
216            template_type_uses_count: WordMap::default(),
217            template_types: TemplateTypes::default(),
218            used_traits: WordSet::default(),
219            declared_ancestry: None,
220            trait_alias_map: WordMap::default(),
221            trait_visibility_map: WordMap::default(),
222            trait_final_map: WordSet::default(),
223            trait_method_adaptations: None,
224            name,
225            original_name,
226            aliases: Vec::new(),
227            child_class_likes: None,
228            template_readonly: WordSet::default(),
229            has_sealed_methods: None,
230            has_sealed_properties: None,
231            permitted_inheritors: None,
232            issues: vec![],
233            attribute_flags: None,
234            type_aliases: WordMap::default(),
235            imported_type_aliases: WordMap::default(),
236            mixins: Vec::default(),
237            declared_mixin_count: None,
238            version_constraint: VersionConstraint::unconstrained(),
239        }
240    }
241
242    /// Returns `true` when this class-like is available in the given PHP
243    /// version.
244    #[inline]
245    #[must_use]
246    pub fn is_available_in_version(&self, version: PHPVersion) -> bool {
247        self.version_constraint.allows_version(version)
248    }
249
250    /// Returns `true` when this class-like is available across the entire
251    /// supplied [`PHPVersionRange`].
252    #[inline]
253    #[must_use]
254    pub fn is_available_in_version_range(&self, range: PHPVersionRange) -> bool {
255        self.version_constraint.allows_version_range(range)
256    }
257
258    /// Returns a reference to the map of trait method aliases.
259    #[inline]
260    #[must_use]
261    pub fn get_trait_alias_map(&self) -> &WordMap<Word> {
262        &self.trait_alias_map
263    }
264
265    /// Returns a vector of the generic type parameter names.
266    #[inline]
267    #[must_use]
268    pub fn get_template_type_names(&self) -> Vec<Word> {
269        self.template_types.keys().copied().collect()
270    }
271
272    /// Returns type parameters for a specific generic parameter name.
273    #[inline]
274    #[must_use]
275    pub fn get_template_type(&self, name: Word) -> Option<&GenericTemplate> {
276        self.template_types.get(&name)
277    }
278
279    #[must_use]
280    pub fn get_template_name_for_index(&self, index: usize) -> Option<Word> {
281        self.template_types.get_index(index).map(|(name, _)| *name)
282    }
283
284    #[must_use]
285    pub fn get_template_index_for_name(&self, name: Word) -> Option<usize> {
286        self.template_types.get_index_of(&name)
287    }
288
289    /// Checks if a specific parent is either a parent class or interface.
290    #[inline]
291    #[must_use]
292    pub fn has_parent(&self, parent: Word) -> bool {
293        self.all_parent_classes.contains(&parent) || self.all_parent_interfaces.contains(&parent)
294    }
295
296    /// Checks if a specific method appears in this class-like.
297    #[inline]
298    #[must_use]
299    pub fn has_appearing_method(&self, method: Word) -> bool {
300        self.appearing_method_ids.contains_key(&method)
301    }
302
303    /// Returns a vector of property names.
304    #[inline]
305    #[must_use]
306    pub fn get_property_names(&self) -> WordSet {
307        self.properties.keys().copied().collect()
308    }
309
310    /// Checks if a specific property appears in this class-like.
311    #[inline]
312    #[must_use]
313    pub fn has_appearing_property(&self, name: Word) -> bool {
314        self.appearing_property_ids.contains_key(&name)
315    }
316
317    /// Takes ownership of the issues found for this class-like structure.
318    #[inline]
319    pub fn take_issues(&mut self) -> Vec<Issue> {
320        std::mem::take(&mut self.issues)
321    }
322
323    /// Adds a single direct parent interface.
324    #[inline]
325    pub fn add_direct_parent_interface(&mut self, interface: Word) {
326        self.direct_parent_interfaces.insert(interface);
327        self.all_parent_interfaces.insert(interface);
328    }
329
330    /// Adds a single used trait. Returns `true` if the trait was not already present.
331    #[inline]
332    pub fn add_used_trait(&mut self, trait_name: Word) -> bool {
333        self.used_traits.insert(trait_name)
334    }
335
336    /// Adds multiple used traits.
337    #[inline]
338    pub fn add_used_traits(&mut self, traits: impl IntoIterator<Item = Word>) {
339        self.used_traits.extend(traits);
340    }
341
342    pub fn direct_trait_names(&self) -> impl Iterator<Item = Word> + '_ {
343        self.declared_ancestry
344            .as_deref()
345            .into_iter()
346            .flatten()
347            .filter_map(|ancestor| match ancestor {
348                DeclaredAncestor::Trait(name) => Some(*name),
349                _ => None,
350            })
351            .chain(self.used_traits.iter().copied().filter(|_| self.declared_ancestry.is_none()))
352    }
353
354    pub(crate) fn declared_mixin_count(&self) -> usize {
355        self.declared_mixin_count.unwrap_or(self.mixins.len())
356    }
357
358    pub(crate) fn reset_inherited_members(&mut self) {
359        let declared_mixins = *self.declared_mixin_count.get_or_insert(self.mixins.len());
360        self.mixins.truncate(declared_mixins);
361        self.properties
362            .retain(|name, _| self.declaring_property_ids.get(name).is_none_or(|declaring| *declaring == self.name));
363        self.inheritable_method_ids.retain(|_, method| method.get_class_name() == self.name);
364        self.inheritable_property_ids.clear();
365        self.inheritable_property_ids.extend(
366            self.properties.iter().filter(|(_, property)| !property.is_final()).map(|(name, _)| (*name, self.name)),
367        );
368
369        self.magic_property_ids.retain(|_, declaring| *declaring == self.name);
370    }
371
372    pub(crate) fn reset_inherited_constants(&mut self) {
373        let declared = self.declared_constants.get_or_insert_with(|| {
374            let mut names: Box<[_]> = self.constants.keys().copied().collect();
375            names.sort_unstable();
376            names
377        });
378
379        self.constants.retain(|name, _| declared.binary_search(name).is_ok());
380        self.trait_constant_ids.clear();
381    }
382
383    pub(crate) fn reset_ancestry(&mut self) {
384        if self.declared_ancestry.is_none() {
385            self.declared_ancestry = Some(
386                self.direct_parent_class
387                    .into_iter()
388                    .map(DeclaredAncestor::ParentClass)
389                    .chain(self.direct_parent_interfaces.iter().copied().map(DeclaredAncestor::ParentInterface))
390                    .chain(self.used_traits.iter().copied().map(DeclaredAncestor::Trait))
391                    .chain(self.require_extends.iter().copied().map(DeclaredAncestor::RequiredClass))
392                    .chain(self.require_implements.iter().copied().map(DeclaredAncestor::RequiredInterface))
393                    .collect(),
394            );
395        }
396
397        self.direct_parent_class = None;
398        self.direct_parent_interfaces.clear();
399        self.all_parent_classes.clear();
400        self.all_parent_interfaces.clear();
401        self.used_traits.clear();
402        self.require_extends.clear();
403        self.require_implements.clear();
404        self.template_extended_parameters.clear();
405        self.template_extended_parameter_paths.clear();
406
407        for ancestor in self.declared_ancestry.as_deref().unwrap_or_default() {
408            match *ancestor {
409                DeclaredAncestor::ParentClass(name) => {
410                    self.direct_parent_class = Some(name);
411                    self.all_parent_classes.insert(name);
412                }
413                DeclaredAncestor::ParentInterface(name) => {
414                    self.direct_parent_interfaces.insert(name);
415                    self.all_parent_interfaces.insert(name);
416                }
417                DeclaredAncestor::Trait(name) => {
418                    self.used_traits.insert(name);
419                }
420                DeclaredAncestor::RequiredClass(name) => {
421                    self.require_extends.insert(name);
422                }
423                DeclaredAncestor::RequiredInterface(name) => {
424                    self.require_implements.insert(name);
425                }
426            }
427        }
428    }
429
430    /// Adds or updates a single trait alias. Returns the previous original name if one existed for the alias.
431    #[inline]
432    pub fn add_trait_alias(&mut self, method: Word, alias: Word) -> Option<Word> {
433        self.trait_alias_map.insert(alias, method)
434    }
435
436    /// Adds or updates a single trait visibility override. Returns the previous visibility if one existed.
437    #[inline]
438    pub fn add_trait_visibility(&mut self, method: Word, visibility: Visibility) -> Option<Visibility> {
439        self.trait_visibility_map.insert(method, visibility)
440    }
441
442    /// Adds a single template type definition.
443    #[inline]
444    pub fn add_template_type(&mut self, name: Word, constraint: GenericTemplate) {
445        self.template_types.insert(name, constraint);
446    }
447
448    /// Set the variance for the template parameters
449    #[inline]
450    pub fn set_template_variance(&mut self, template_variance: Vec<Variance>) {
451        self.template_variance = template_variance;
452    }
453
454    /// Adds or replaces the offset types for a specific template parameter name.
455    #[inline]
456    pub fn add_template_extended_offset(&mut self, name: Word, types: Vec<TUnion>) -> Option<Vec<TUnion>> {
457        self.template_extended_offsets.insert(name, types)
458    }
459
460    /// Adds or replaces the resolved parameters for a specific parent FQCN.
461    #[inline]
462    pub fn extend_template_extended_parameters(
463        &mut self,
464        template_extended_parameters: WordMap<IndexMap<Word, TUnion, RandomState>>,
465    ) {
466        self.template_extended_parameters.extend(template_extended_parameters);
467    }
468
469    /// Adds or replaces a single resolved parameter for the parent FQCN.
470    #[inline]
471    pub fn add_template_extended_parameter(
472        &mut self,
473        parent_fqcn: Word,
474        parameter_name: Word,
475        parameter_type: TUnion,
476    ) -> Option<TUnion> {
477        self.template_extended_parameters.entry(parent_fqcn).or_default().insert(parameter_name, parameter_type)
478    }
479
480    /// Records one complete parameterization of `ancestor` (a single inheritance
481    /// path), de-duplicating against parameterizations already recorded.
482    #[inline]
483    pub fn record_template_extended_path(&mut self, ancestor: Word, parameters: IndexMap<Word, TUnion, RandomState>) {
484        if parameters.is_empty() {
485            return;
486        }
487
488        let paths = self.template_extended_parameter_paths.entry(ancestor).or_default();
489        if !paths.contains(&parameters) {
490            paths.push(parameters);
491        }
492    }
493
494    /// Adds or updates the declaring method identifier for a method name.
495    #[inline]
496    pub fn add_declaring_method_id(
497        &mut self,
498        method: Word,
499        declaring_method_id: MethodIdentifier,
500    ) -> Option<MethodIdentifier> {
501        self.add_appearing_method_id(method, declaring_method_id);
502        self.declaring_method_ids.insert(method, declaring_method_id)
503    }
504
505    /// Adds or updates the appearing method identifier for a method name.
506    #[inline]
507    pub fn add_appearing_method_id(
508        &mut self,
509        method: Word,
510        appearing_method_id: MethodIdentifier,
511    ) -> Option<MethodIdentifier> {
512        self.appearing_method_ids.insert(method, appearing_method_id)
513    }
514
515    /// Adds a parent method identifier to the map for an overridden method. Initializes map if needed. Returns the previous value if one existed.
516    #[inline]
517    pub fn add_overridden_method_parent(
518        &mut self,
519        method: Word,
520        parent_method_id: MethodIdentifier,
521    ) -> Option<MethodIdentifier> {
522        Arc::make_mut(self.overridden_method_ids.entry(method).or_default())
523            .insert(parent_method_id.get_class_name(), parent_method_id)
524    }
525
526    /// Adds or updates a property's metadata. Returns the previous metadata if the property existed.
527    #[inline]
528    pub fn add_property(&mut self, name: Word, property_metadata: PropertyMetadata) -> Option<PropertyMetadata> {
529        let class_name = self.name;
530
531        self.add_declaring_property_id(name, class_name);
532        if property_metadata.flags.has_default() {
533            self.initialized_properties.insert(name);
534        }
535
536        if !property_metadata.is_final() {
537            self.inheritable_property_ids.insert(name, class_name);
538        }
539
540        self.properties.insert(name, property_metadata)
541    }
542
543    /// Adds or updates a property's metadata using just the property metadata. Returns the previous metadata if the property existed.
544    #[inline]
545    pub fn add_property_metadata(&mut self, property_metadata: PropertyMetadata) -> Option<PropertyMetadata> {
546        let name = property_metadata.get_name().0;
547
548        self.add_property(name, property_metadata)
549    }
550
551    /// Adds or updates the declaring class FQCN for a property name.
552    #[inline]
553    pub fn add_declaring_property_id(&mut self, prop: Word, declaring_fqcn: Word) -> Option<Word> {
554        self.appearing_property_ids.insert(prop, declaring_fqcn);
555        self.declaring_property_ids.insert(prop, declaring_fqcn)
556    }
557
558    #[must_use]
559    pub fn get_missing_required_interface<'meta>(&self, other: &'meta ClassLikeMetadata) -> Option<&'meta Word> {
560        for required_interface in &other.require_implements {
561            if self.all_parent_interfaces.contains(required_interface) {
562                continue;
563            }
564
565            if (self.flags.is_abstract() || self.kind.is_trait())
566                && self.require_implements.contains(required_interface)
567            {
568                continue; // Abstract classes and traits can require interfaces they implement
569            }
570
571            return Some(required_interface);
572        }
573
574        None
575    }
576
577    #[must_use]
578    pub fn get_missing_required_extends<'meta>(&self, other: &'meta ClassLikeMetadata) -> Option<&'meta Word> {
579        for required_extend in &other.require_extends {
580            if self.name == *required_extend {
581                continue;
582            }
583
584            if self.all_parent_classes.contains(required_extend) {
585                continue;
586            }
587
588            if self.kind.is_interface() && self.all_parent_interfaces.contains(required_extend) {
589                continue;
590            }
591
592            if (self.flags.is_abstract() || self.kind.is_trait()) && self.require_extends.contains(required_extend) {
593                continue; // Abstract classes and traits can require classes they extend
594            }
595
596            return Some(required_extend);
597        }
598
599        None
600    }
601
602    #[must_use]
603    pub fn is_permitted_to_inherit(&self, other: &ClassLikeMetadata) -> bool {
604        if self.kind.is_trait() || self.flags.is_abstract() {
605            return true; // Traits and abstract classes can always inherit
606        }
607
608        let Some(permitted_inheritors) = &other.permitted_inheritors else {
609            return true; // No restrictions, inheriting is allowed
610        };
611
612        if permitted_inheritors.contains(&self.name) {
613            return true; // This class-like is explicitly permitted to inherit
614        }
615
616        self.all_parent_interfaces.iter().any(|parent_interface| permitted_inheritors.contains(parent_interface))
617            || self.all_parent_classes.iter().any(|parent_class| permitted_inheritors.contains(parent_class))
618            || self.used_traits.iter().any(|used_trait| permitted_inheritors.contains(used_trait))
619    }
620
621    #[inline]
622    pub fn mark_as_populated(&mut self) {
623        self.flags |= MetadataFlags::POPULATED;
624        self.shrink_to_fit();
625    }
626
627    /// Applies a patch to this class in place, refining member type information while leaving
628    /// structure (hierarchy, override chains, initialization state, enum cases) untouched.
629    ///
630    /// At most one patch targets a given symbol, so there is no accumulation to worry about.
631    /// Diagnostics about the patch are appended to `patch.issues`, where scan-time diagnostics
632    /// also live, so they flow out through `take_issues`. The full set of rules a patch must
633    /// obey is documented in the `[source]` patching guide.
634    pub fn apply_patch(&mut self, patch: &mut ClassLikeMetadata, inherited_methods: &WordSet) {
635        // Patches redeclare the same class by name, so their member identifiers
636        // already carry the correct class name and merge cleanly.
637        debug_assert_eq!(self.name, patch.name, "patch class name must match the patched class");
638
639        // A kind or hierarchy mismatch means the patch targets a different symbol; reject
640        // it wholesale rather than refining members against the wrong class.
641        if self.report_kind_mismatch(patch) || self.report_hierarchy_mismatch(patch) {
642            return;
643        }
644
645        self.report_readonly_mismatch(patch);
646        self.report_trait_usage(patch);
647
648        self.patch_templates(patch);
649        self.patch_methods(patch, inherited_methods);
650        self.patch_properties(patch);
651        self.patch_constants(patch);
652        self.report_enum_cases(patch);
653
654        // Type aliases
655        self.type_aliases.extend(patch.type_aliases.iter().map(|(k, v)| (*k, v.clone())));
656    }
657
658    /// Reports a `kind` mismatch between the patch and the original symbol.
659    ///
660    /// Returns `true` when the kinds differ, in which case the patch must be rejected
661    /// wholesale because it targets a different kind of symbol.
662    fn report_kind_mismatch(&self, patch: &mut ClassLikeMetadata) -> bool {
663        if self.kind == patch.kind {
664            return false;
665        }
666
667        patch.issues.push(
668            Issue::error(format!(
669                "Patch declares `{}` as a {} but the original symbol is a {}; patch members are ignored.",
670                patch.original_name,
671                patch.kind.as_str(),
672                self.kind.as_str(),
673            ))
674            .with_code(ScanningIssueKind::PatchKindMismatch)
675            .with_annotation(Annotation::primary(patch.span))
676            .with_help(format!(
677                "Declare `{}` as a {} in the patch so it matches the original symbol, \
678                 or remove the patch if it targets the wrong symbol.",
679                patch.original_name,
680                self.kind.as_str(),
681            )),
682        );
683
684        true
685    }
686
687    /// Reports a hierarchy mismatch between the patch and the original symbol.
688    ///
689    /// Hierarchy declarations must match the original exactly if declared; a mismatch means
690    /// the patch is describing a different class. Returns `true` when they differ, in which
691    /// case the patch must be rejected wholesale.
692    fn report_hierarchy_mismatch(&self, patch: &mut ClassLikeMetadata) -> bool {
693        let hierarchy_mismatch = (patch.direct_parent_class.is_some()
694            && patch.direct_parent_class != self.direct_parent_class)
695            || (!patch.direct_parent_interfaces.is_empty()
696                && patch.direct_parent_interfaces != self.direct_parent_interfaces)
697            || (!patch.require_extends.is_empty() && patch.require_extends != self.require_extends)
698            || (!patch.require_implements.is_empty() && patch.require_implements != self.require_implements);
699
700        if !hierarchy_mismatch {
701            return false;
702        }
703
704        patch.issues.push(
705            Issue::error(format!(
706                "Patch for `{}` declares hierarchy that does not match the original; patch members are ignored.",
707                patch.original_name,
708            ))
709            .with_code(ScanningIssueKind::PatchHierarchyMismatch)
710            .with_annotation(Annotation::primary(patch.span))
711            .with_help(
712                "Patches do not need to restate hierarchy. Drop the parent class, interface, \
713                 `@require-extends`, or `@require-implements` declarations from the patch, or \
714                 correct them to match the original exactly.",
715            ),
716        );
717
718        true
719    }
720
721    /// Reports a `readonly class` modifier mismatch.
722    ///
723    /// `readonly class` is a structural modifier — a patch cannot add or remove it. This is a
724    /// warning only and does not abort the patch.
725    fn report_readonly_mismatch(&self, patch: &mut ClassLikeMetadata) {
726        if patch.flags.contains(MetadataFlags::READONLY) == self.flags.contains(MetadataFlags::READONLY) {
727            return;
728        }
729
730        patch.issues.push(
731            Issue::warning(format!(
732                "Patch declares `{}` as a {} class but the original is {}; readonly modifier is ignored.",
733                patch.original_name,
734                if patch.flags.contains(MetadataFlags::READONLY) { "readonly" } else { "non-readonly" },
735                if self.flags.contains(MetadataFlags::READONLY) { "readonly" } else { "non-readonly" },
736            ))
737            .with_code(ScanningIssueKind::PatchReadonlyMismatch)
738            .with_annotation(Annotation::primary(patch.span))
739            .with_help(
740                "The `readonly` class modifier is structural and cannot be changed by a patch. \
741                 Match the original by adding or removing `readonly` on the patched class declaration.",
742            ),
743        );
744    }
745
746    /// Reports `use` trait declarations on the patch, which are never valid.
747    ///
748    /// Patches refine member type information only; trait usage declarations are ignored.
749    fn report_trait_usage(&self, patch: &mut ClassLikeMetadata) {
750        if patch.used_traits.is_empty() {
751            return;
752        }
753
754        patch.issues.push(
755            Issue::warning(format!(
756                "Patch for `{}` declares `use` traits; patches refine member type information only and trait usage declarations are ignored.",
757                patch.original_name,
758            ))
759            .with_code(ScanningIssueKind::PatchDeclaresTrait)
760            .with_annotation(Annotation::primary(patch.span))
761            .with_help(
762                "Remove the `use` trait statement from the patch. To refine the type information \
763                 of members the trait contributes, patch those members on the class directly.",
764            ),
765        );
766    }
767
768    /// Merges `@template` declarations from the patch: existing names are overridden, new
769    /// names appended.
770    ///
771    /// `template_variance` is keyed by position in the `template_types` IndexMap and must be
772    /// rebuilt after the merge; `template_readonly` is name-keyed and can be extended directly.
773    fn patch_templates(&mut self, patch: &ClassLikeMetadata) {
774        if patch.template_types.is_empty() {
775            return;
776        }
777
778        // Collect name → variance for the current (original) state.
779        let mut name_to_variance: WordMap<Variance> = self
780            .template_types
781            .keys()
782            .enumerate()
783            .map(|(i, name)| (*name, self.template_variance.get(i).copied().unwrap_or(Variance::Invariant)))
784            .collect();
785
786        // Patch overrides existing entries and contributes new ones.
787        name_to_variance.extend(
788            patch
789                .template_types
790                .keys()
791                .enumerate()
792                .map(|(i, name)| (*name, patch.template_variance.get(i).copied().unwrap_or(Variance::Invariant))),
793        );
794
795        // Extend the IndexMap: existing names get updated definitions, new ones are appended.
796        self.template_types.extend(patch.template_types.iter().map(|(k, v)| (*k, v.clone())));
797
798        // Rebuild position-indexed variance vec to match the merged IndexMap order.
799        // template_readonly is name-keyed so it doesn't need rebuilding — just extend it.
800        self.template_variance = self
801            .template_types
802            .keys()
803            .map(|name| name_to_variance.get(name).copied().unwrap_or(Variance::Invariant))
804            .collect();
805        self.template_readonly.extend(patch.template_readonly.iter().copied());
806    }
807
808    /// Applies method declarations from the patch.
809    ///
810    /// A real method already declared on the original needs no change here — its type info
811    /// flows through `FunctionLikeMetadata::apply_patch` on the function-like. A method
812    /// inherited from an ancestor is added to the structural maps so the populator treats this
813    /// class as the declaring site, and `apply_patches_pass` then materializes the
814    /// function-like. A method that exists nowhere in the chain is rejected as a new member.
815    /// Pseudo-methods (`@method`) are class-level and always update the structural maps.
816    fn patch_methods(&mut self, patch: &mut ClassLikeMetadata, inherited_methods: &WordSet) {
817        for method_name in &patch.methods {
818            if patch.pseudo_methods.contains(method_name) || patch.static_pseudo_methods.contains(method_name) {
819                continue;
820            }
821            if inherited_methods.contains(method_name) {
822                // The patch introduces an override for an inherited method. Mirror what the
823                // scanner records for a directly-declared method so the populator preserves
824                // this class as the declaring/appearing site (rather than re-inheriting the
825                // ancestor's ids) and the refined function-like at `(self, method)` wins.
826                // `apply_patches_pass` materializes that function-like from the ancestor.
827                if self.methods.insert(*method_name) {
828                    if let Some(id) = patch.declaring_method_ids.get(method_name) {
829                        self.declaring_method_ids.insert(*method_name, *id);
830                    }
831                    if let Some(id) = patch.appearing_method_ids.get(method_name) {
832                        self.appearing_method_ids.insert(*method_name, *id);
833                    }
834                    if let Some(id) = patch.inheritable_method_ids.get(method_name) {
835                        self.inheritable_method_ids.insert(*method_name, *id);
836                    }
837                }
838            } else if !self.methods.contains(method_name) {
839                patch.issues.push(
840                    Issue::error(format!(
841                        "Patch for `{}` declares method `{}` which does not exist in the original \
842                         or any of its ancestors; patches cannot introduce new methods.",
843                        patch.original_name, method_name,
844                    ))
845                    .with_code(ScanningIssueKind::PatchIntroducesNewMethod)
846                    .with_annotation(Annotation::primary(patch.span))
847                    .with_help(format!(
848                        "Remove `{method_name}` from the patch, or correct its name to match a method \
849                         that already exists on `{}` or one of its ancestors. To annotate a magic \
850                         method handled by `__call`/`__callStatic`, declare it with `@method` instead. \
851                         Patches can only refine the types of existing methods.",
852                        patch.original_name,
853                    )),
854                );
855            }
856        }
857
858        for name in patch.pseudo_methods.iter().chain(patch.static_pseudo_methods.iter()) {
859            if let Some(id) = patch.declaring_method_ids.get(name) {
860                self.declaring_method_ids.insert(*name, *id);
861            }
862            if let Some(id) = patch.appearing_method_ids.get(name) {
863                self.appearing_method_ids.insert(*name, *id);
864            }
865            if let Some(id) = patch.inheritable_method_ids.get(name) {
866                self.inheritable_method_ids.insert(*name, *id);
867            }
868        }
869
870        self.pseudo_methods.extend(patch.pseudo_methods.iter().copied());
871        self.static_pseudo_methods.extend(patch.static_pseudo_methods.iter().copied());
872    }
873
874    /// Refines type annotations on existing properties. New properties are rejected unless
875    /// they are magic properties (`@property`/`@property-read`/`@property-write`), which carry
876    /// no runtime existence claim. Structural attributes must match the original.
877    fn patch_properties(&mut self, patch: &mut ClassLikeMetadata) {
878        let patch_span = patch.span;
879        let patch_name = patch.original_name;
880        for (name, prop_metadata) in &patch.properties {
881            if let Some(slot) = self.properties.get_mut(name) {
882                // Patches can only refine type annotations. Structural attributes
883                // (visibility, modifiers, hooks) must match the original exactly;
884                // if they differ the patch is wrong and we should say so rather than
885                // silently discarding the mismatch.
886                let visibility_mismatch = prop_metadata.read_visibility != slot.read_visibility
887                    || prop_metadata.write_visibility != slot.write_visibility;
888                // READONLY, STATIC, ABSTRACT: any mismatch is structural.
889                // FINAL: only an error when removed (vendor has it, patch doesn't);
890                //        adding final via a patch is allowed.
891                let structural_flag_mismatch =
892                    [MetadataFlags::READONLY, MetadataFlags::STATIC, MetadataFlags::ABSTRACT]
893                        .iter()
894                        .any(|&f| prop_metadata.flags.contains(f) != slot.flags.contains(f))
895                        || (slot.flags.contains(MetadataFlags::FINAL)
896                            && !prop_metadata.flags.contains(MetadataFlags::FINAL));
897                let has_hooks = !prop_metadata.hooks.is_empty();
898
899                if visibility_mismatch || structural_flag_mismatch || has_hooks {
900                    patch.issues.push(
901                        Issue::error(format!(
902                            "Patch for `{}::{}` declares structural attributes (visibility, modifiers, \
903                             or hooks) that differ from the original; only type annotations are applied.",
904                            patch_name, name,
905                        ))
906                        .with_code(ScanningIssueKind::PatchPropertyStructuralMismatch)
907                        .with_annotation(Annotation::primary(prop_metadata.span.unwrap_or(patch_span)))
908                        .with_help(format!(
909                            "Declare `{patch_name}::{name}` with the same visibility and modifiers as \
910                             the original and drop any property hooks; a patch may only refine the \
911                             property's type.",
912                        )),
913                    );
914                }
915
916                slot.type_declaration_metadata.clone_from(&prop_metadata.type_declaration_metadata);
917                slot.type_metadata.clone_from(&prop_metadata.type_metadata);
918                slot.write_type_metadata.clone_from(&prop_metadata.write_type_metadata);
919            } else {
920                patch.issues.push(
921                    Issue::error(format!(
922                        "Patch declares property `{}::{}` which does not exist in the original; \
923                         patches cannot introduce new properties.",
924                        patch_name, name,
925                    ))
926                    .with_code(ScanningIssueKind::PatchIntroducesNewProperty)
927                    .with_annotation(Annotation::primary(patch_span))
928                    .with_help(format!(
929                        "Remove `{patch_name}::{name}` from the patch, or correct its name to match an \
930                         existing property. To annotate a magic property handled by `__get`/`__set`, \
931                         declare it with `@property`, `@property-read`, or `@property-write` instead.",
932                    )),
933                );
934            }
935        }
936
937        // Magic `@property*` annotations carry no runtime existence claim: a patch may both
938        // refine an existing annotation and introduce a new one.
939        for (name, prop_metadata) in &patch.magic_properties {
940            self.magic_properties.insert(*name, prop_metadata.clone());
941            self.magic_property_ids.insert(*name, self.name);
942        }
943    }
944
945    /// Refines type annotations on existing constants; new constants are rejected and
946    /// structural attributes must match the original.
947    fn patch_constants(&mut self, patch: &mut ClassLikeMetadata) {
948        let patch_span = patch.span;
949        let patch_name = patch.original_name;
950        for (name, const_metadata) in &patch.constants {
951            if let Some(slot) = self.constants.get_mut(name) {
952                let visibility_mismatch = const_metadata.visibility != slot.visibility;
953                // ABSTRACT: any mismatch is structural.
954                // FINAL: only an error when removed (vendor has it, patch doesn't);
955                //        adding final via a patch is allowed.
956                let structural_flag_mismatch = const_metadata.flags.contains(MetadataFlags::ABSTRACT)
957                    != slot.flags.contains(MetadataFlags::ABSTRACT)
958                    || (slot.flags.contains(MetadataFlags::FINAL)
959                        && !const_metadata.flags.contains(MetadataFlags::FINAL));
960
961                if visibility_mismatch || structural_flag_mismatch {
962                    patch.issues.push(
963                        Issue::error(format!(
964                            "Patch for `{}::{}` declares structural attributes (visibility or modifiers) \
965                             that differ from the original; only type annotations are applied.",
966                            patch_name, name,
967                        ))
968                        .with_code(ScanningIssueKind::PatchConstantStructuralMismatch)
969                        .with_annotation(Annotation::primary(const_metadata.span))
970                        .with_help(format!(
971                            "Declare `{patch_name}::{name}` with the same visibility and modifiers as \
972                             the original; a patch may only refine the constant's type.",
973                        )),
974                    );
975                }
976
977                slot.type_declaration.clone_from(&const_metadata.type_declaration);
978                slot.type_metadata.clone_from(&const_metadata.type_metadata);
979            } else {
980                patch.issues.push(
981                    Issue::error(format!(
982                        "Patch declares constant `{}::{}` which does not exist in the original; \
983                         patches cannot introduce new constants.",
984                        patch_name, name,
985                    ))
986                    .with_code(ScanningIssueKind::PatchIntroducesNewConstant)
987                    .with_annotation(Annotation::primary(patch_span))
988                    .with_help(format!(
989                        "Remove `{patch_name}::{name}` from the patch, or correct its name to match a \
990                         constant that already exists on the original. Patches can only refine the \
991                         types of existing constants.",
992                    )),
993                );
994            }
995        }
996    }
997
998    /// Reports enum case declarations on the patch, which are never valid.
999    ///
1000    /// Enum cases are structural (they define the valid runtime values of an enum)
1001    /// and cannot be modified by a patch.
1002    fn report_enum_cases(&self, patch: &mut ClassLikeMetadata) {
1003        if patch.enum_cases.is_empty() {
1004            return;
1005        }
1006
1007        patch.issues.push(
1008            Issue::error(format!(
1009                "Patch for `{}` declares enum case(s); enum cases are structural and cannot be \
1010                 refined — patch enum cases are ignored.",
1011                patch.original_name,
1012            ))
1013            .with_code(ScanningIssueKind::PatchEnumCasesIgnored)
1014            .with_annotation(Annotation::primary(patch.span))
1015            .with_help(
1016                "Remove the enum case declarations from the patch. Enum cases define the runtime \
1017                 values of the enum and must stay in the original definition; a patch can only \
1018                 refine the types of existing members.",
1019            ),
1020        );
1021    }
1022
1023    #[inline]
1024    pub fn shrink_to_fit(&mut self) {
1025        self.aliases.shrink_to_fit();
1026        self.properties.shrink_to_fit();
1027        self.magic_properties.shrink_to_fit();
1028        self.magic_property_ids.shrink_to_fit();
1029        self.initialized_properties.shrink_to_fit();
1030        self.appearing_property_ids.shrink_to_fit();
1031        self.declaring_property_ids.shrink_to_fit();
1032        self.inheritable_property_ids.shrink_to_fit();
1033        self.overridden_property_ids.shrink_to_fit();
1034        self.appearing_method_ids.shrink_to_fit();
1035        self.declaring_method_ids.shrink_to_fit();
1036        self.inheritable_method_ids.shrink_to_fit();
1037        self.overridden_method_ids.shrink_to_fit();
1038        self.attributes.shrink_to_fit();
1039        self.constants.shrink_to_fit();
1040        self.enum_cases.shrink_to_fit();
1041        self.type_aliases.shrink_to_fit();
1042    }
1043}
1044
1045/// Collects all method names reachable through the ancestors of `class_meta`.
1046///
1047/// Does not include methods defined directly on `class_meta` itself.
1048#[must_use]
1049pub fn collect_ancestor_methods<T>(class_meta: &ClassLikeMetadata, class_likes: &WordMap<T>) -> WordSet
1050where
1051    T: Borrow<ClassLikeMetadata>,
1052{
1053    let mut visited = WordSet::default();
1054    let mut methods = WordSet::default();
1055    collect_ancestor_methods_inner(class_meta, class_likes, &mut visited, &mut methods);
1056    methods
1057}
1058
1059fn collect_ancestor_methods_inner<T>(
1060    class_meta: &ClassLikeMetadata,
1061    class_likes: &WordMap<T>,
1062    visited: &mut WordSet,
1063    methods: &mut WordSet,
1064) where
1065    T: Borrow<ClassLikeMetadata>,
1066{
1067    if !visited.insert(class_meta.name) {
1068        return;
1069    }
1070    if let Some(parent_name) = class_meta.direct_parent_class
1071        && let Some(parent_meta) = class_likes.get(&parent_name).map(Borrow::borrow)
1072    {
1073        methods.extend(parent_meta.methods.iter().copied());
1074        collect_ancestor_methods_inner(parent_meta, class_likes, visited, methods);
1075    }
1076    for interface_name in &class_meta.direct_parent_interfaces {
1077        if let Some(interface_meta) = class_likes.get(interface_name).map(Borrow::borrow) {
1078            methods.extend(interface_meta.methods.iter().copied());
1079            collect_ancestor_methods_inner(interface_meta, class_likes, visited, methods);
1080        }
1081    }
1082    for trait_name in &class_meta.used_traits {
1083        if let Some(trait_meta) = class_likes.get(trait_name).map(Borrow::borrow) {
1084            methods.extend(trait_meta.methods.iter().copied());
1085            collect_ancestor_methods_inner(trait_meta, class_likes, visited, methods);
1086        }
1087    }
1088}
1089
1090#[cfg(test)]
1091mod tests {
1092    use std::iter::once;
1093
1094    use mago_span::Span;
1095    use mago_word::WordSet;
1096    use mago_word::word;
1097
1098    use crate::identifier::method::MethodIdentifier;
1099    use crate::issue::ScanningIssueKind;
1100    use crate::metadata::class_like_constant::ClassLikeConstantMetadata;
1101    use crate::metadata::enum_case::EnumCaseMetadata;
1102    use crate::metadata::flags::MetadataFlags;
1103    use crate::metadata::property::PropertyMetadata;
1104    use crate::misc::GenericParent;
1105    use crate::misc::VariableIdentifier;
1106    use crate::symbol::SymbolKind;
1107    use crate::ttype;
1108    use crate::ttype::template::GenericTemplate;
1109    use crate::ttype::template::variance::Variance;
1110    use crate::visibility::Visibility;
1111
1112    use super::ClassLikeMetadata;
1113
1114    fn has_code(issues: &[mago_reporting::Issue], kind: ScanningIssueKind) -> bool {
1115        let code = kind.to_string();
1116        issues.iter().any(|i| i.code.as_deref() == Some(code.as_str()))
1117    }
1118
1119    fn make(name: &str) -> ClassLikeMetadata {
1120        let a = word(name);
1121        ClassLikeMetadata::new(a, a, Span::dummy(0, 10), None, MetadataFlags::empty())
1122    }
1123
1124    #[test]
1125    fn incomplete_hierarchy_dependencies_hide_synthetic_enum_contracts() {
1126        let mut metadata = make("Example");
1127        metadata.kind = SymbolKind::Enum;
1128        metadata.invalid_dependencies.extend([
1129            word("unitenum"),
1130            word("backedenum"),
1131            word("__internal_do_not_use__intbackedenum"),
1132        ]);
1133
1134        assert!(!metadata.has_incomplete_hierarchy());
1135        assert_eq!(metadata.incomplete_hierarchy_dependencies().collect::<Vec<_>>(), []);
1136
1137        let missing = word("vendor\\missing\\contract");
1138        metadata.invalid_dependencies.insert(missing);
1139
1140        assert!(metadata.has_incomplete_hierarchy());
1141        assert_eq!(metadata.incomplete_hierarchy_dependencies().collect::<Vec<_>>(), [missing]);
1142    }
1143
1144    #[test]
1145    fn apply_patch_adds_override_for_inherited_real_method() {
1146        let class_name = word("VendorClass");
1147        let mut vendored = make("VendorClass");
1148        let method_existing = word("existing");
1149        vendored.methods.insert(method_existing);
1150        vendored.declaring_method_ids.insert(method_existing, MethodIdentifier::new(class_name, method_existing));
1151
1152        let mut patch = make("VendorClass");
1153        let method_override = word("inherited_method");
1154        patch.methods.insert(method_override);
1155        patch.declaring_method_ids.insert(method_override, MethodIdentifier::new(class_name, method_override));
1156        patch.appearing_method_ids.insert(method_override, MethodIdentifier::new(class_name, method_override));
1157        patch.inheritable_method_ids.insert(method_override, MethodIdentifier::new(class_name, method_override));
1158
1159        let inherited: WordSet = once(method_override).collect();
1160        vendored.apply_patch(&mut patch, &inherited);
1161        let issues = patch.issues;
1162
1163        // The override is added to the real method set and to all three method-id maps, mirroring
1164        // what the scanner records for a directly-declared method. Seeding declaring/appearing is
1165        // what makes the populator keep this class (not the ancestor) as the declaring site, so the
1166        // refined function-like materialized at `(self, method)` actually wins.
1167        assert!(vendored.methods.contains(&method_override));
1168        assert_eq!(
1169            vendored.declaring_method_ids.get(&method_override),
1170            Some(&MethodIdentifier::new(class_name, method_override)),
1171        );
1172        assert_eq!(
1173            vendored.appearing_method_ids.get(&method_override),
1174            Some(&MethodIdentifier::new(class_name, method_override)),
1175        );
1176        assert!(vendored.inheritable_method_ids.contains_key(&method_override));
1177
1178        // No warning: patch overrides of inherited methods are expected and intentional.
1179        assert!(issues.is_empty());
1180    }
1181
1182    #[test]
1183    fn apply_patch_adds_pseudo_methods() {
1184        let class_name = word("VendorClass");
1185        let mut vendored = make("VendorClass");
1186
1187        let mut patch = make("VendorClass");
1188        let pseudo = word("magicMethod");
1189        patch.pseudo_methods.insert(pseudo);
1190        patch.declaring_method_ids.insert(pseudo, MethodIdentifier::new(class_name, pseudo));
1191        patch.appearing_method_ids.insert(pseudo, MethodIdentifier::new(class_name, pseudo));
1192        patch.inheritable_method_ids.insert(pseudo, MethodIdentifier::new(class_name, pseudo));
1193
1194        vendored.apply_patch(&mut patch, &WordSet::default());
1195        let issues = patch.issues;
1196
1197        // Pseudo-method added to the right sets and ID maps.
1198        assert!(vendored.pseudo_methods.contains(&pseudo));
1199        assert!(vendored.declaring_method_ids.contains_key(&pseudo));
1200        assert!(vendored.appearing_method_ids.contains_key(&pseudo));
1201        assert!(vendored.inheritable_method_ids.contains_key(&pseudo));
1202
1203        // Must not appear as a real method.
1204        assert!(!vendored.methods.contains(&pseudo));
1205
1206        // No issues.
1207        assert!(issues.is_empty());
1208    }
1209
1210    #[test]
1211    fn apply_patch_accepts_new_magic_property() {
1212        let mut vendored = make("VendorClass");
1213
1214        let mut patch = make("VendorClass");
1215        let prop_magic = word("$magic");
1216        patch
1217            .magic_properties
1218            .insert(prop_magic, PropertyMetadata::new(VariableIdentifier(prop_magic), MetadataFlags::PATCH));
1219
1220        vendored.apply_patch(&mut patch, &WordSet::default());
1221        let issues = patch.issues;
1222
1223        assert!(vendored.magic_properties.contains_key(&prop_magic));
1224        assert_eq!(vendored.magic_property_ids.get(&prop_magic), Some(&vendored.name));
1225        assert!(issues.is_empty());
1226    }
1227
1228    #[test]
1229    fn apply_patch_does_not_touch_initialized_or_override_maps() {
1230        let mut vendored = make("VendorClass");
1231        let prop = word("$x");
1232        vendored.properties.insert(prop, PropertyMetadata::new(VariableIdentifier(prop), MetadataFlags::empty()));
1233        vendored.initialized_properties.insert(prop);
1234        vendored.overridden_property_ids.insert(prop, once(word("ParentClass")).collect());
1235
1236        let mut patch = make("VendorClass");
1237        patch.properties.insert(prop, PropertyMetadata::new(VariableIdentifier(prop), MetadataFlags::PATCH));
1238        // patch has no initialized_properties entry and no overridden_property_ids
1239
1240        vendored.apply_patch(&mut patch, &WordSet::default());
1241        let issues = patch.issues;
1242
1243        // initialized_properties must not be cleared by the patch
1244        assert!(vendored.initialized_properties.contains(&prop));
1245        // overridden_property_ids must not be cleared by the patch
1246        assert!(vendored.overridden_property_ids.contains_key(&prop));
1247        assert!(issues.is_empty());
1248    }
1249
1250    #[test]
1251    fn apply_patch_adds_template_types() {
1252        let class_name = word("VendorClass");
1253        let mut vendored = make("VendorClass");
1254
1255        let mut patch = make("VendorClass");
1256        let t = word("T");
1257        patch.template_types.insert(t, GenericTemplate::new(GenericParent::ClassLike(class_name), ttype::get_mixed()));
1258        patch.template_variance.push(Variance::Covariant);
1259        patch.template_readonly.insert(t);
1260
1261        vendored.apply_patch(&mut patch, &WordSet::default());
1262        let issues = patch.issues;
1263
1264        assert!(vendored.template_types.contains_key(&t));
1265        assert_eq!(vendored.template_variance.first().copied(), Some(Variance::Covariant));
1266        assert!(vendored.template_readonly.contains(&t));
1267        assert!(issues.is_empty());
1268    }
1269
1270    #[test]
1271    fn apply_patch_refines_existing_template_and_appends_new() {
1272        let class_name = word("VendorClass");
1273        let mut vendored = make("VendorClass");
1274        let t = word("T");
1275        let u = word("U");
1276
1277        // Original has T (invariant, constraint = mixed) and U (covariant).
1278        vendored
1279            .template_types
1280            .insert(t, GenericTemplate::new(GenericParent::ClassLike(class_name), ttype::get_mixed()));
1281        vendored
1282            .template_types
1283            .insert(u, GenericTemplate::new(GenericParent::ClassLike(class_name), ttype::get_mixed()));
1284        vendored.template_variance = vec![Variance::Invariant, Variance::Covariant];
1285
1286        // Patch refines T (now contravariant) and adds V (invariant).
1287        let mut patch = make("VendorClass");
1288        let v = word("V");
1289        patch.template_types.insert(t, GenericTemplate::new(GenericParent::ClassLike(class_name), ttype::get_int()));
1290        patch.template_types.insert(v, GenericTemplate::new(GenericParent::ClassLike(class_name), ttype::get_string()));
1291        patch.template_variance = vec![Variance::Contravariant, Variance::Invariant];
1292
1293        vendored.apply_patch(&mut patch, &WordSet::default());
1294        let issues = patch.issues;
1295
1296        // T refined, U preserved, V appended → order T=0, U=1, V=2
1297        assert_eq!(vendored.template_types.keys().copied().collect::<Vec<_>>(), [t, u, v]);
1298        assert_eq!(vendored.template_variance, [Variance::Contravariant, Variance::Covariant, Variance::Invariant]);
1299
1300        assert!(issues.is_empty());
1301    }
1302
1303    #[test]
1304    fn apply_patch_preserves_original_only_readonly_template() {
1305        // Original: T is readonly. Patch adds U but does not re-declare T.
1306        // T must remain readonly after the patch — the patch can add readonly
1307        // entries but must not strip existing ones by omitting them.
1308        let class_name = word("VendorClass");
1309        let mut vendored = make("VendorClass");
1310        let t = word("T");
1311        vendored
1312            .template_types
1313            .insert(t, GenericTemplate::new(GenericParent::ClassLike(class_name), ttype::get_mixed()));
1314        vendored.template_variance.push(Variance::Invariant);
1315        vendored.template_readonly.insert(t);
1316
1317        let mut patch = make("VendorClass");
1318        let u = word("U");
1319        patch.template_types.insert(u, GenericTemplate::new(GenericParent::ClassLike(class_name), ttype::get_mixed()));
1320        patch.template_variance.push(Variance::Invariant);
1321
1322        vendored.apply_patch(&mut patch, &WordSet::default());
1323        let issues = patch.issues;
1324
1325        assert!(vendored.template_readonly.contains(&t), "T should remain readonly after patch");
1326        assert!(!vendored.template_readonly.contains(&u), "U was not declared readonly by the patch");
1327        assert!(issues.is_empty());
1328    }
1329
1330    #[test]
1331    fn apply_patch_rejects_kind_mismatch() {
1332        let mut vendored = make("VendorClass");
1333        let mut patch = make("VendorClass");
1334        patch.kind = SymbolKind::Interface;
1335
1336        vendored.apply_patch(&mut patch, &WordSet::default());
1337        let issues = patch.issues;
1338
1339        assert!(has_code(&issues, ScanningIssueKind::PatchKindMismatch));
1340    }
1341
1342    #[test]
1343    fn apply_patch_rejects_trait_use() {
1344        let mut vendored = make("VendorClass");
1345        let mut patch = make("VendorClass");
1346        patch.used_traits.insert(word("SomeTrait"));
1347
1348        vendored.apply_patch(&mut patch, &WordSet::default());
1349        let issues = patch.issues;
1350
1351        assert!(has_code(&issues, ScanningIssueKind::PatchDeclaresTrait));
1352    }
1353
1354    #[test]
1355    fn apply_patch_rejects_hierarchy_mismatch() {
1356        let mut vendored = make("VendorClass");
1357        vendored.direct_parent_class = Some(word("ActualParent"));
1358
1359        let mut patch = make("VendorClass");
1360        patch.direct_parent_class = Some(word("WrongParent"));
1361
1362        vendored.apply_patch(&mut patch, &WordSet::default());
1363        let issues = patch.issues;
1364
1365        assert!(has_code(&issues, ScanningIssueKind::PatchHierarchyMismatch));
1366    }
1367
1368    #[test]
1369    fn apply_patch_rejects_new_method_not_in_ancestors() {
1370        let mut vendored = make("VendorClass");
1371        let mut patch = make("VendorClass");
1372        patch.methods.insert(word("newMethod"));
1373
1374        vendored.apply_patch(&mut patch, &WordSet::default());
1375        let issues = patch.issues;
1376
1377        assert!(has_code(&issues, ScanningIssueKind::PatchIntroducesNewMethod));
1378    }
1379
1380    #[test]
1381    fn apply_patch_rejects_new_property() {
1382        let mut vendored = make("VendorClass");
1383        let mut patch = make("VendorClass");
1384        let prop = word("$newProp");
1385        patch.properties.insert(prop, PropertyMetadata::new(VariableIdentifier(prop), MetadataFlags::PATCH));
1386
1387        vendored.apply_patch(&mut patch, &WordSet::default());
1388        let issues = patch.issues;
1389
1390        assert!(has_code(&issues, ScanningIssueKind::PatchIntroducesNewProperty));
1391    }
1392
1393    #[test]
1394    fn apply_patch_rejects_new_constant() {
1395        let mut vendored = make("VendorClass");
1396        let mut patch = make("VendorClass");
1397        let c = word("NEW_CONST");
1398        patch
1399            .constants
1400            .insert(c, ClassLikeConstantMetadata::new(c, Span::dummy(0, 5), Visibility::Public, MetadataFlags::PATCH));
1401
1402        vendored.apply_patch(&mut patch, &WordSet::default());
1403        let issues = patch.issues;
1404
1405        assert!(has_code(&issues, ScanningIssueKind::PatchIntroducesNewConstant));
1406    }
1407
1408    #[test]
1409    fn apply_patch_rejects_enum_cases() {
1410        let mut vendored = make("VendorClass");
1411        let mut patch = make("VendorClass");
1412        let case = word("CaseA");
1413        patch
1414            .enum_cases
1415            .insert(case, EnumCaseMetadata::new(case, Span::dummy(0, 3), Span::dummy(0, 5), MetadataFlags::PATCH));
1416
1417        vendored.apply_patch(&mut patch, &WordSet::default());
1418        let issues = patch.issues;
1419
1420        assert!(has_code(&issues, ScanningIssueKind::PatchEnumCasesIgnored));
1421    }
1422
1423    #[test]
1424    fn apply_patch_rejects_property_structural_mismatch() {
1425        let mut vendored = make("VendorClass");
1426        let prop = word("$x");
1427        vendored.properties.insert(prop, PropertyMetadata::new(VariableIdentifier(prop), MetadataFlags::empty()));
1428
1429        let mut patch = make("VendorClass");
1430        patch.properties.insert(
1431            prop,
1432            PropertyMetadata::new(VariableIdentifier(prop), MetadataFlags::PATCH | MetadataFlags::STATIC),
1433        );
1434
1435        vendored.apply_patch(&mut patch, &WordSet::default());
1436        let issues = patch.issues;
1437
1438        assert!(has_code(&issues, ScanningIssueKind::PatchPropertyStructuralMismatch));
1439    }
1440
1441    #[test]
1442    fn apply_patch_rejects_constant_structural_mismatch() {
1443        let mut vendored = make("VendorClass");
1444        let c = word("MY_CONST");
1445        vendored.constants.insert(
1446            c,
1447            ClassLikeConstantMetadata::new(c, Span::dummy(0, 5), Visibility::Private, MetadataFlags::empty()),
1448        );
1449
1450        let mut patch = make("VendorClass");
1451        patch
1452            .constants
1453            .insert(c, ClassLikeConstantMetadata::new(c, Span::dummy(0, 5), Visibility::Public, MetadataFlags::PATCH));
1454
1455        vendored.apply_patch(&mut patch, &WordSet::default());
1456        let issues = patch.issues;
1457
1458        assert!(has_code(&issues, ScanningIssueKind::PatchConstantStructuralMismatch));
1459    }
1460}