Skip to main content

mago_codex/metadata/
class_like.rs

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