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