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