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