1use std::borrow::Borrow;
2use std::sync::Arc;
3
4use foldhash::fast::RandomState;
5use indexmap::IndexMap;
6use mago_php_version::PHPVersion;
7use mago_php_version::PHPVersionRange;
8
9use mago_reporting::Annotation;
10use mago_reporting::Issue;
11use mago_span::Span;
12use mago_word::Word;
13use mago_word::WordMap;
14use mago_word::WordSet;
15
16use crate::flags::attribute::AttributeFlags;
17use crate::identifier::method::MethodIdentifier;
18use crate::issue::ScanningIssueKind;
19use crate::metadata::attribute::AttributeMetadata;
20use crate::metadata::class_like_constant::ClassLikeConstantMetadata;
21use crate::metadata::enum_case::EnumCaseMetadata;
22use crate::metadata::flags::MetadataFlags;
23use crate::metadata::property::PropertyMetadata;
24use crate::metadata::trait_adaptation::TraitMethodAdaptations;
25use crate::metadata::ttype::TypeMetadata;
26use crate::metadata::version_constraint::VersionConstraint;
27use crate::symbol::SymbolKind;
28use crate::ttype::atomic::TAtomic;
29use crate::ttype::template::GenericTemplate;
30use crate::ttype::template::variance::Variance;
31use crate::ttype::union::TUnion;
32use crate::visibility::Visibility;
33
34pub type TemplateTypes = IndexMap<Word, GenericTemplate, RandomState>;
37
38#[derive(Clone, Copy, Debug, PartialEq, Eq)]
39#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
40enum DeclaredAncestor {
41 ParentClass(Word),
42 ParentInterface(Word),
43 Trait(Word),
44 RequiredClass(Word),
45 RequiredInterface(Word),
46}
47
48#[derive(Clone, Debug, PartialEq, Eq)]
53#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
54#[non_exhaustive]
55pub struct ClassLikeMetadata {
56 pub name: Word,
57 pub original_name: Word,
58 #[cfg_attr(feature = "serde", serde(default))]
59 pub aliases: Vec<Word>,
60 pub span: Span,
61 pub direct_parent_interfaces: WordSet,
62 pub all_parent_interfaces: WordSet,
63 pub direct_parent_class: Option<Word>,
64 pub require_extends: WordSet,
65 pub require_implements: WordSet,
66 pub all_parent_classes: WordSet,
67 pub used_traits: WordSet,
68 #[cfg_attr(feature = "serde", serde(default))]
69 declared_ancestry: Option<Box<[DeclaredAncestor]>>,
70 pub trait_alias_map: WordMap<Word>,
71 pub trait_visibility_map: WordMap<Visibility>,
72 pub trait_final_map: WordSet,
73 #[cfg_attr(feature = "serde", serde(default))]
74 pub(crate) trait_method_adaptations: Option<Box<TraitMethodAdaptations>>,
75 pub child_class_likes: Option<WordSet>,
76 pub name_span: Option<Span>,
77 pub kind: SymbolKind,
78 pub template_types: TemplateTypes,
79 pub template_readonly: WordSet,
80 pub template_variance: Vec<Variance>,
81 pub template_extended_offsets: WordMap<Vec<TUnion>>,
82 pub template_extended_parameters: WordMap<IndexMap<Word, TUnion, RandomState>>,
83 pub template_extended_parameter_paths: WordMap<Vec<IndexMap<Word, TUnion, RandomState>>>,
84 pub template_type_extends_count: WordMap<usize>,
85 pub template_type_implements_count: WordMap<usize>,
86 pub template_type_uses_count: WordMap<usize>,
87 pub methods: WordSet,
88 pub pseudo_methods: WordSet,
89 pub static_pseudo_methods: WordSet,
90 pub declaring_method_ids: WordMap<MethodIdentifier>,
91 pub appearing_method_ids: WordMap<MethodIdentifier>,
92 pub inheritable_method_ids: WordMap<MethodIdentifier>,
93 pub overridden_method_ids: WordMap<Arc<IndexMap<Word, MethodIdentifier, RandomState>>>,
94 pub properties: WordMap<PropertyMetadata>,
95 pub magic_properties: WordMap<PropertyMetadata>,
103 pub magic_property_ids: WordMap<Word>,
108 pub appearing_property_ids: WordMap<Word>,
109 pub declaring_property_ids: WordMap<Word>,
110 pub inheritable_property_ids: WordMap<Word>,
111 pub overridden_property_ids: WordMap<WordSet>,
112 pub initialized_properties: WordSet,
113 pub constants: WordMap<ClassLikeConstantMetadata>,
114 #[cfg_attr(feature = "serde", serde(default))]
115 declared_constants: Option<Box<[Word]>>,
116 pub trait_constant_ids: WordMap<Word>,
117 pub enum_cases: WordMap<EnumCaseMetadata>,
118 pub invalid_dependencies: WordSet,
119 pub attributes: Vec<AttributeMetadata>,
120 pub enum_type: Option<TAtomic>,
121 pub has_sealed_methods: Option<bool>,
122 pub has_sealed_properties: Option<bool>,
123 pub permitted_inheritors: Option<WordSet>,
124 pub issues: Vec<Issue>,
125 pub attribute_flags: Option<AttributeFlags>,
126 pub flags: MetadataFlags,
127 pub type_aliases: WordMap<TypeMetadata>,
128 pub imported_type_aliases: WordMap<(Word, Word, Span)>,
130 pub mixins: Vec<TypeMetadata>,
133 #[cfg_attr(feature = "serde", serde(default))]
134 declared_mixin_count: Option<usize>,
135 pub version_constraint: VersionConstraint,
136}
137
138impl ClassLikeMetadata {
139 #[inline]
144 #[must_use]
145 pub fn has_incomplete_hierarchy(&self) -> bool {
146 self.incomplete_hierarchy_dependencies().next().is_some()
147 }
148
149 #[inline]
155 pub fn incomplete_hierarchy_dependencies(&self) -> impl Iterator<Item = Word> + '_ {
156 let is_enum = self.kind.is_enum();
157 self.invalid_dependencies.iter().copied().filter(move |dependency| {
158 !is_enum
159 || !matches!(
160 dependency.as_bytes(),
161 b"unitenum"
162 | b"backedenum"
163 | b"__internal_do_not_use__intbackedenum"
164 | b"__internal_do_not_use__stringbackedenum"
165 )
166 })
167 }
168
169 #[must_use]
170 pub fn new(
171 name: Word,
172 original_name: Word,
173 span: Span,
174 name_span: Option<Span>,
175 flags: MetadataFlags,
176 ) -> ClassLikeMetadata {
177 ClassLikeMetadata {
178 constants: WordMap::default(),
179 declared_constants: None,
180 trait_constant_ids: WordMap::default(),
181 enum_cases: WordMap::default(),
182 flags,
183 kind: SymbolKind::Class,
184 direct_parent_interfaces: WordSet::default(),
185 all_parent_classes: WordSet::default(),
186 appearing_method_ids: WordMap::default(),
187 attributes: Vec::new(),
188 all_parent_interfaces: WordSet::default(),
189 declaring_method_ids: WordMap::default(),
190 appearing_property_ids: WordMap::default(),
191 declaring_property_ids: WordMap::default(),
192 direct_parent_class: None,
193 require_extends: WordSet::default(),
194 require_implements: WordSet::default(),
195 inheritable_method_ids: WordMap::default(),
196 enum_type: None,
197 inheritable_property_ids: WordMap::default(),
198 initialized_properties: WordSet::default(),
199 invalid_dependencies: WordSet::default(),
200 span,
201 name_span,
202 methods: WordSet::default(),
203 pseudo_methods: WordSet::default(),
204 static_pseudo_methods: WordSet::default(),
205 overridden_method_ids: WordMap::default(),
206 overridden_property_ids: WordMap::default(),
207 properties: WordMap::default(),
208 magic_properties: WordMap::default(),
209 magic_property_ids: WordMap::default(),
210 template_variance: Vec::new(),
211 template_type_extends_count: WordMap::default(),
212 template_extended_parameters: WordMap::default(),
213 template_extended_parameter_paths: WordMap::default(),
214 template_extended_offsets: WordMap::default(),
215 template_type_implements_count: WordMap::default(),
216 template_type_uses_count: WordMap::default(),
217 template_types: TemplateTypes::default(),
218 used_traits: WordSet::default(),
219 declared_ancestry: None,
220 trait_alias_map: WordMap::default(),
221 trait_visibility_map: WordMap::default(),
222 trait_final_map: WordSet::default(),
223 trait_method_adaptations: None,
224 name,
225 original_name,
226 aliases: Vec::new(),
227 child_class_likes: None,
228 template_readonly: WordSet::default(),
229 has_sealed_methods: None,
230 has_sealed_properties: None,
231 permitted_inheritors: None,
232 issues: vec![],
233 attribute_flags: None,
234 type_aliases: WordMap::default(),
235 imported_type_aliases: WordMap::default(),
236 mixins: Vec::default(),
237 declared_mixin_count: None,
238 version_constraint: VersionConstraint::unconstrained(),
239 }
240 }
241
242 #[inline]
245 #[must_use]
246 pub fn is_available_in_version(&self, version: PHPVersion) -> bool {
247 self.version_constraint.allows_version(version)
248 }
249
250 #[inline]
253 #[must_use]
254 pub fn is_available_in_version_range(&self, range: PHPVersionRange) -> bool {
255 self.version_constraint.allows_version_range(range)
256 }
257
258 #[inline]
260 #[must_use]
261 pub fn get_trait_alias_map(&self) -> &WordMap<Word> {
262 &self.trait_alias_map
263 }
264
265 #[inline]
267 #[must_use]
268 pub fn get_template_type_names(&self) -> Vec<Word> {
269 self.template_types.keys().copied().collect()
270 }
271
272 #[inline]
274 #[must_use]
275 pub fn get_template_type(&self, name: Word) -> Option<&GenericTemplate> {
276 self.template_types.get(&name)
277 }
278
279 #[must_use]
280 pub fn get_template_name_for_index(&self, index: usize) -> Option<Word> {
281 self.template_types.get_index(index).map(|(name, _)| *name)
282 }
283
284 #[must_use]
285 pub fn get_template_index_for_name(&self, name: Word) -> Option<usize> {
286 self.template_types.get_index_of(&name)
287 }
288
289 #[inline]
291 #[must_use]
292 pub fn has_parent(&self, parent: Word) -> bool {
293 self.all_parent_classes.contains(&parent) || self.all_parent_interfaces.contains(&parent)
294 }
295
296 #[inline]
298 #[must_use]
299 pub fn has_appearing_method(&self, method: Word) -> bool {
300 self.appearing_method_ids.contains_key(&method)
301 }
302
303 #[inline]
305 #[must_use]
306 pub fn get_property_names(&self) -> WordSet {
307 self.properties.keys().copied().collect()
308 }
309
310 #[inline]
312 #[must_use]
313 pub fn has_appearing_property(&self, name: Word) -> bool {
314 self.appearing_property_ids.contains_key(&name)
315 }
316
317 #[inline]
319 pub fn take_issues(&mut self) -> Vec<Issue> {
320 std::mem::take(&mut self.issues)
321 }
322
323 #[inline]
325 pub fn add_direct_parent_interface(&mut self, interface: Word) {
326 self.direct_parent_interfaces.insert(interface);
327 self.all_parent_interfaces.insert(interface);
328 }
329
330 #[inline]
332 pub fn add_used_trait(&mut self, trait_name: Word) -> bool {
333 self.used_traits.insert(trait_name)
334 }
335
336 #[inline]
338 pub fn add_used_traits(&mut self, traits: impl IntoIterator<Item = Word>) {
339 self.used_traits.extend(traits);
340 }
341
342 pub fn direct_trait_names(&self) -> impl Iterator<Item = Word> + '_ {
343 self.declared_ancestry
344 .as_deref()
345 .into_iter()
346 .flatten()
347 .filter_map(|ancestor| match ancestor {
348 DeclaredAncestor::Trait(name) => Some(*name),
349 _ => None,
350 })
351 .chain(self.used_traits.iter().copied().filter(|_| self.declared_ancestry.is_none()))
352 }
353
354 pub(crate) fn declared_mixin_count(&self) -> usize {
355 self.declared_mixin_count.unwrap_or(self.mixins.len())
356 }
357
358 pub(crate) fn reset_inherited_members(&mut self) {
359 let declared_mixins = *self.declared_mixin_count.get_or_insert(self.mixins.len());
360 self.mixins.truncate(declared_mixins);
361 self.properties
362 .retain(|name, _| self.declaring_property_ids.get(name).is_none_or(|declaring| *declaring == self.name));
363 self.inheritable_method_ids.retain(|_, method| method.get_class_name() == self.name);
364 self.inheritable_property_ids.clear();
365 self.inheritable_property_ids.extend(
366 self.properties.iter().filter(|(_, property)| !property.is_final()).map(|(name, _)| (*name, self.name)),
367 );
368
369 self.magic_property_ids.retain(|_, declaring| *declaring == self.name);
370 }
371
372 pub(crate) fn reset_inherited_constants(&mut self) {
373 let declared = self.declared_constants.get_or_insert_with(|| {
374 let mut names: Box<[_]> = self.constants.keys().copied().collect();
375 names.sort_unstable();
376 names
377 });
378
379 self.constants.retain(|name, _| declared.binary_search(name).is_ok());
380 self.trait_constant_ids.clear();
381 }
382
383 pub(crate) fn reset_ancestry(&mut self) {
384 if self.declared_ancestry.is_none() {
385 self.declared_ancestry = Some(
386 self.direct_parent_class
387 .into_iter()
388 .map(DeclaredAncestor::ParentClass)
389 .chain(self.direct_parent_interfaces.iter().copied().map(DeclaredAncestor::ParentInterface))
390 .chain(self.used_traits.iter().copied().map(DeclaredAncestor::Trait))
391 .chain(self.require_extends.iter().copied().map(DeclaredAncestor::RequiredClass))
392 .chain(self.require_implements.iter().copied().map(DeclaredAncestor::RequiredInterface))
393 .collect(),
394 );
395 }
396
397 self.direct_parent_class = None;
398 self.direct_parent_interfaces.clear();
399 self.all_parent_classes.clear();
400 self.all_parent_interfaces.clear();
401 self.used_traits.clear();
402 self.require_extends.clear();
403 self.require_implements.clear();
404 self.template_extended_parameters.clear();
405 self.template_extended_parameter_paths.clear();
406
407 for ancestor in self.declared_ancestry.as_deref().unwrap_or_default() {
408 match *ancestor {
409 DeclaredAncestor::ParentClass(name) => {
410 self.direct_parent_class = Some(name);
411 self.all_parent_classes.insert(name);
412 }
413 DeclaredAncestor::ParentInterface(name) => {
414 self.direct_parent_interfaces.insert(name);
415 self.all_parent_interfaces.insert(name);
416 }
417 DeclaredAncestor::Trait(name) => {
418 self.used_traits.insert(name);
419 }
420 DeclaredAncestor::RequiredClass(name) => {
421 self.require_extends.insert(name);
422 }
423 DeclaredAncestor::RequiredInterface(name) => {
424 self.require_implements.insert(name);
425 }
426 }
427 }
428 }
429
430 #[inline]
432 pub fn add_trait_alias(&mut self, method: Word, alias: Word) -> Option<Word> {
433 self.trait_alias_map.insert(alias, method)
434 }
435
436 #[inline]
438 pub fn add_trait_visibility(&mut self, method: Word, visibility: Visibility) -> Option<Visibility> {
439 self.trait_visibility_map.insert(method, visibility)
440 }
441
442 #[inline]
444 pub fn add_template_type(&mut self, name: Word, constraint: GenericTemplate) {
445 self.template_types.insert(name, constraint);
446 }
447
448 #[inline]
450 pub fn set_template_variance(&mut self, template_variance: Vec<Variance>) {
451 self.template_variance = template_variance;
452 }
453
454 #[inline]
456 pub fn add_template_extended_offset(&mut self, name: Word, types: Vec<TUnion>) -> Option<Vec<TUnion>> {
457 self.template_extended_offsets.insert(name, types)
458 }
459
460 #[inline]
462 pub fn extend_template_extended_parameters(
463 &mut self,
464 template_extended_parameters: WordMap<IndexMap<Word, TUnion, RandomState>>,
465 ) {
466 self.template_extended_parameters.extend(template_extended_parameters);
467 }
468
469 #[inline]
471 pub fn add_template_extended_parameter(
472 &mut self,
473 parent_fqcn: Word,
474 parameter_name: Word,
475 parameter_type: TUnion,
476 ) -> Option<TUnion> {
477 self.template_extended_parameters.entry(parent_fqcn).or_default().insert(parameter_name, parameter_type)
478 }
479
480 #[inline]
483 pub fn record_template_extended_path(&mut self, ancestor: Word, parameters: IndexMap<Word, TUnion, RandomState>) {
484 if parameters.is_empty() {
485 return;
486 }
487
488 let paths = self.template_extended_parameter_paths.entry(ancestor).or_default();
489 if !paths.contains(¶meters) {
490 paths.push(parameters);
491 }
492 }
493
494 #[inline]
496 pub fn add_declaring_method_id(
497 &mut self,
498 method: Word,
499 declaring_method_id: MethodIdentifier,
500 ) -> Option<MethodIdentifier> {
501 self.add_appearing_method_id(method, declaring_method_id);
502 self.declaring_method_ids.insert(method, declaring_method_id)
503 }
504
505 #[inline]
507 pub fn add_appearing_method_id(
508 &mut self,
509 method: Word,
510 appearing_method_id: MethodIdentifier,
511 ) -> Option<MethodIdentifier> {
512 self.appearing_method_ids.insert(method, appearing_method_id)
513 }
514
515 #[inline]
517 pub fn add_overridden_method_parent(
518 &mut self,
519 method: Word,
520 parent_method_id: MethodIdentifier,
521 ) -> Option<MethodIdentifier> {
522 Arc::make_mut(self.overridden_method_ids.entry(method).or_default())
523 .insert(parent_method_id.get_class_name(), parent_method_id)
524 }
525
526 #[inline]
528 pub fn add_property(&mut self, name: Word, property_metadata: PropertyMetadata) -> Option<PropertyMetadata> {
529 let class_name = self.name;
530
531 self.add_declaring_property_id(name, class_name);
532 if property_metadata.flags.has_default() {
533 self.initialized_properties.insert(name);
534 }
535
536 if !property_metadata.is_final() {
537 self.inheritable_property_ids.insert(name, class_name);
538 }
539
540 self.properties.insert(name, property_metadata)
541 }
542
543 #[inline]
545 pub fn add_property_metadata(&mut self, property_metadata: PropertyMetadata) -> Option<PropertyMetadata> {
546 let name = property_metadata.get_name().0;
547
548 self.add_property(name, property_metadata)
549 }
550
551 #[inline]
553 pub fn add_declaring_property_id(&mut self, prop: Word, declaring_fqcn: Word) -> Option<Word> {
554 self.appearing_property_ids.insert(prop, declaring_fqcn);
555 self.declaring_property_ids.insert(prop, declaring_fqcn)
556 }
557
558 #[must_use]
559 pub fn get_missing_required_interface<'meta>(&self, other: &'meta ClassLikeMetadata) -> Option<&'meta Word> {
560 for required_interface in &other.require_implements {
561 if self.all_parent_interfaces.contains(required_interface) {
562 continue;
563 }
564
565 if (self.flags.is_abstract() || self.kind.is_trait())
566 && self.require_implements.contains(required_interface)
567 {
568 continue; }
570
571 return Some(required_interface);
572 }
573
574 None
575 }
576
577 #[must_use]
578 pub fn get_missing_required_extends<'meta>(&self, other: &'meta ClassLikeMetadata) -> Option<&'meta Word> {
579 for required_extend in &other.require_extends {
580 if self.name == *required_extend {
581 continue;
582 }
583
584 if self.all_parent_classes.contains(required_extend) {
585 continue;
586 }
587
588 if self.kind.is_interface() && self.all_parent_interfaces.contains(required_extend) {
589 continue;
590 }
591
592 if (self.flags.is_abstract() || self.kind.is_trait()) && self.require_extends.contains(required_extend) {
593 continue; }
595
596 return Some(required_extend);
597 }
598
599 None
600 }
601
602 #[must_use]
603 pub fn is_permitted_to_inherit(&self, other: &ClassLikeMetadata) -> bool {
604 if self.kind.is_trait() || self.flags.is_abstract() {
605 return true; }
607
608 let Some(permitted_inheritors) = &other.permitted_inheritors else {
609 return true; };
611
612 if permitted_inheritors.contains(&self.name) {
613 return true; }
615
616 self.all_parent_interfaces.iter().any(|parent_interface| permitted_inheritors.contains(parent_interface))
617 || self.all_parent_classes.iter().any(|parent_class| permitted_inheritors.contains(parent_class))
618 || self.used_traits.iter().any(|used_trait| permitted_inheritors.contains(used_trait))
619 }
620
621 #[inline]
622 pub fn mark_as_populated(&mut self) {
623 self.flags |= MetadataFlags::POPULATED;
624 self.shrink_to_fit();
625 }
626
627 pub fn apply_patch(&mut self, patch: &mut ClassLikeMetadata, inherited_methods: &WordSet) {
635 debug_assert_eq!(self.name, patch.name, "patch class name must match the patched class");
638
639 if self.report_kind_mismatch(patch) || self.report_hierarchy_mismatch(patch) {
642 return;
643 }
644
645 self.report_readonly_mismatch(patch);
646 self.report_trait_usage(patch);
647
648 self.patch_templates(patch);
649 self.template_extended_offsets.extend(
650 patch
651 .template_extended_offsets
652 .iter()
653 .filter(|(name, _)| {
654 patch.template_type_extends_count.contains_key(*name)
655 || patch.template_type_implements_count.contains_key(*name)
656 })
657 .map(|(name, types)| (*name, types.clone())),
658 );
659 self.template_type_extends_count
660 .extend(patch.template_type_extends_count.iter().map(|(name, count)| (*name, *count)));
661 self.template_type_implements_count
662 .extend(patch.template_type_implements_count.iter().map(|(name, count)| (*name, *count)));
663 self.patch_methods(patch, inherited_methods);
664 self.patch_properties(patch);
665 self.patch_constants(patch);
666 self.report_enum_cases(patch);
667
668 self.type_aliases.extend(patch.type_aliases.iter().map(|(k, v)| (*k, v.clone())));
670 }
671
672 fn report_kind_mismatch(&self, patch: &mut ClassLikeMetadata) -> bool {
677 if self.kind == patch.kind {
678 return false;
679 }
680
681 patch.issues.push(
682 Issue::error(format!(
683 "Patch declares `{}` as a {} but the original symbol is a {}; patch members are ignored.",
684 patch.original_name,
685 patch.kind.as_str(),
686 self.kind.as_str(),
687 ))
688 .with_code(ScanningIssueKind::PatchKindMismatch)
689 .with_annotation(Annotation::primary(patch.span))
690 .with_help(format!(
691 "Declare `{}` as a {} in the patch so it matches the original symbol, \
692 or remove the patch if it targets the wrong symbol.",
693 patch.original_name,
694 self.kind.as_str(),
695 )),
696 );
697
698 true
699 }
700
701 fn report_hierarchy_mismatch(&self, patch: &mut ClassLikeMetadata) -> bool {
707 let hierarchy_mismatch = (patch.direct_parent_class.is_some()
708 && patch.direct_parent_class != self.direct_parent_class)
709 || (!patch.direct_parent_interfaces.is_empty()
710 && patch.direct_parent_interfaces != self.direct_parent_interfaces)
711 || (!patch.require_extends.is_empty() && patch.require_extends != self.require_extends)
712 || (!patch.require_implements.is_empty() && patch.require_implements != self.require_implements);
713
714 if !hierarchy_mismatch {
715 return false;
716 }
717
718 patch.issues.push(
719 Issue::error(format!(
720 "Patch for `{}` declares hierarchy that does not match the original; patch members are ignored.",
721 patch.original_name,
722 ))
723 .with_code(ScanningIssueKind::PatchHierarchyMismatch)
724 .with_annotation(Annotation::primary(patch.span))
725 .with_help(
726 "Patches do not need to restate hierarchy. Drop the parent class, interface, \
727 `@require-extends`, or `@require-implements` declarations from the patch, or \
728 correct them to match the original exactly.",
729 ),
730 );
731
732 true
733 }
734
735 fn report_readonly_mismatch(&self, patch: &mut ClassLikeMetadata) {
740 if patch.flags.contains(MetadataFlags::READONLY) == self.flags.contains(MetadataFlags::READONLY) {
741 return;
742 }
743
744 patch.issues.push(
745 Issue::warning(format!(
746 "Patch declares `{}` as a {} class but the original is {}; readonly modifier is ignored.",
747 patch.original_name,
748 if patch.flags.contains(MetadataFlags::READONLY) { "readonly" } else { "non-readonly" },
749 if self.flags.contains(MetadataFlags::READONLY) { "readonly" } else { "non-readonly" },
750 ))
751 .with_code(ScanningIssueKind::PatchReadonlyMismatch)
752 .with_annotation(Annotation::primary(patch.span))
753 .with_help(
754 "The `readonly` class modifier is structural and cannot be changed by a patch. \
755 Match the original by adding or removing `readonly` on the patched class declaration.",
756 ),
757 );
758 }
759
760 fn report_trait_usage(&self, patch: &mut ClassLikeMetadata) {
764 if patch.used_traits.is_empty() {
765 return;
766 }
767
768 patch.issues.push(
769 Issue::warning(format!(
770 "Patch for `{}` declares `use` traits; patches refine member type information only and trait usage declarations are ignored.",
771 patch.original_name,
772 ))
773 .with_code(ScanningIssueKind::PatchDeclaresTrait)
774 .with_annotation(Annotation::primary(patch.span))
775 .with_help(
776 "Remove the `use` trait statement from the patch. To refine the type information \
777 of members the trait contributes, patch those members on the class directly.",
778 ),
779 );
780 }
781
782 fn patch_templates(&mut self, patch: &ClassLikeMetadata) {
788 if patch.template_types.is_empty() {
789 return;
790 }
791
792 let mut name_to_variance: WordMap<Variance> = self
794 .template_types
795 .keys()
796 .enumerate()
797 .map(|(i, name)| (*name, self.template_variance.get(i).copied().unwrap_or(Variance::Invariant)))
798 .collect();
799
800 name_to_variance.extend(
802 patch
803 .template_types
804 .keys()
805 .enumerate()
806 .map(|(i, name)| (*name, patch.template_variance.get(i).copied().unwrap_or(Variance::Invariant))),
807 );
808
809 self.template_types.extend(patch.template_types.iter().map(|(k, v)| (*k, v.clone())));
811
812 self.template_variance = self
815 .template_types
816 .keys()
817 .map(|name| name_to_variance.get(name).copied().unwrap_or(Variance::Invariant))
818 .collect();
819 self.template_readonly.extend(patch.template_readonly.iter().copied());
820 }
821
822 fn patch_methods(&mut self, patch: &mut ClassLikeMetadata, inherited_methods: &WordSet) {
831 for method_name in &patch.methods {
832 if patch.pseudo_methods.contains(method_name) || patch.static_pseudo_methods.contains(method_name) {
833 continue;
834 }
835 if inherited_methods.contains(method_name) {
836 if self.methods.insert(*method_name) {
842 if let Some(id) = patch.declaring_method_ids.get(method_name) {
843 self.declaring_method_ids.insert(*method_name, *id);
844 }
845 if let Some(id) = patch.appearing_method_ids.get(method_name) {
846 self.appearing_method_ids.insert(*method_name, *id);
847 }
848 if let Some(id) = patch.inheritable_method_ids.get(method_name) {
849 self.inheritable_method_ids.insert(*method_name, *id);
850 }
851 }
852 } else if !self.methods.contains(method_name) {
853 patch.issues.push(
854 Issue::error(format!(
855 "Patch for `{}` declares method `{}` which does not exist in the original \
856 or any of its ancestors; patches cannot introduce new methods.",
857 patch.original_name, method_name,
858 ))
859 .with_code(ScanningIssueKind::PatchIntroducesNewMethod)
860 .with_annotation(Annotation::primary(patch.span))
861 .with_help(format!(
862 "Remove `{method_name}` from the patch, or correct its name to match a method \
863 that already exists on `{}` or one of its ancestors. To annotate a magic \
864 method handled by `__call`/`__callStatic`, declare it with `@method` instead. \
865 Patches can only refine the types of existing methods.",
866 patch.original_name,
867 )),
868 );
869 }
870 }
871
872 for name in patch.pseudo_methods.iter().chain(patch.static_pseudo_methods.iter()) {
873 if let Some(id) = patch.declaring_method_ids.get(name) {
874 self.declaring_method_ids.insert(*name, *id);
875 }
876 if let Some(id) = patch.appearing_method_ids.get(name) {
877 self.appearing_method_ids.insert(*name, *id);
878 }
879 if let Some(id) = patch.inheritable_method_ids.get(name) {
880 self.inheritable_method_ids.insert(*name, *id);
881 }
882 }
883
884 self.pseudo_methods.extend(patch.pseudo_methods.iter().copied());
885 self.static_pseudo_methods.extend(patch.static_pseudo_methods.iter().copied());
886 }
887
888 fn patch_properties(&mut self, patch: &mut ClassLikeMetadata) {
892 let patch_span = patch.span;
893 let patch_name = patch.original_name;
894 for (name, prop_metadata) in &patch.properties {
895 if let Some(slot) = self.properties.get_mut(name) {
896 let visibility_mismatch = prop_metadata.read_visibility != slot.read_visibility
901 || prop_metadata.write_visibility != slot.write_visibility;
902 let structural_flag_mismatch =
906 [MetadataFlags::READONLY, MetadataFlags::STATIC, MetadataFlags::ABSTRACT]
907 .iter()
908 .any(|&f| prop_metadata.flags.contains(f) != slot.flags.contains(f))
909 || (slot.flags.contains(MetadataFlags::FINAL)
910 && !prop_metadata.flags.contains(MetadataFlags::FINAL));
911 let has_hooks = !prop_metadata.hooks.is_empty();
912
913 if visibility_mismatch || structural_flag_mismatch || has_hooks {
914 patch.issues.push(
915 Issue::error(format!(
916 "Patch for `{}::{}` declares structural attributes (visibility, modifiers, \
917 or hooks) that differ from the original; only type annotations are applied.",
918 patch_name, name,
919 ))
920 .with_code(ScanningIssueKind::PatchPropertyStructuralMismatch)
921 .with_annotation(Annotation::primary(prop_metadata.span.unwrap_or(patch_span)))
922 .with_help(format!(
923 "Declare `{patch_name}::{name}` with the same visibility and modifiers as \
924 the original and drop any property hooks; a patch may only refine the \
925 property's type.",
926 )),
927 );
928 }
929
930 slot.type_declaration_metadata.clone_from(&prop_metadata.type_declaration_metadata);
931 slot.type_metadata.clone_from(&prop_metadata.type_metadata);
932 slot.write_type_metadata.clone_from(&prop_metadata.write_type_metadata);
933 } else {
934 patch.issues.push(
935 Issue::error(format!(
936 "Patch declares property `{}::{}` which does not exist in the original; \
937 patches cannot introduce new properties.",
938 patch_name, name,
939 ))
940 .with_code(ScanningIssueKind::PatchIntroducesNewProperty)
941 .with_annotation(Annotation::primary(patch_span))
942 .with_help(format!(
943 "Remove `{patch_name}::{name}` from the patch, or correct its name to match an \
944 existing property. To annotate a magic property handled by `__get`/`__set`, \
945 declare it with `@property`, `@property-read`, or `@property-write` instead.",
946 )),
947 );
948 }
949 }
950
951 for (name, prop_metadata) in &patch.magic_properties {
954 self.magic_properties.insert(*name, prop_metadata.clone());
955 self.magic_property_ids.insert(*name, self.name);
956 }
957 }
958
959 fn patch_constants(&mut self, patch: &mut ClassLikeMetadata) {
962 let patch_span = patch.span;
963 let patch_name = patch.original_name;
964 for (name, const_metadata) in &patch.constants {
965 if let Some(slot) = self.constants.get_mut(name) {
966 let visibility_mismatch = const_metadata.visibility != slot.visibility;
967 let structural_flag_mismatch = const_metadata.flags.contains(MetadataFlags::ABSTRACT)
971 != slot.flags.contains(MetadataFlags::ABSTRACT)
972 || (slot.flags.contains(MetadataFlags::FINAL)
973 && !const_metadata.flags.contains(MetadataFlags::FINAL));
974
975 if visibility_mismatch || structural_flag_mismatch {
976 patch.issues.push(
977 Issue::error(format!(
978 "Patch for `{}::{}` declares structural attributes (visibility or modifiers) \
979 that differ from the original; only type annotations are applied.",
980 patch_name, name,
981 ))
982 .with_code(ScanningIssueKind::PatchConstantStructuralMismatch)
983 .with_annotation(Annotation::primary(const_metadata.span))
984 .with_help(format!(
985 "Declare `{patch_name}::{name}` with the same visibility and modifiers as \
986 the original; a patch may only refine the constant's type.",
987 )),
988 );
989 }
990
991 slot.type_declaration.clone_from(&const_metadata.type_declaration);
992 slot.type_metadata.clone_from(&const_metadata.type_metadata);
993 } else {
994 patch.issues.push(
995 Issue::error(format!(
996 "Patch declares constant `{}::{}` which does not exist in the original; \
997 patches cannot introduce new constants.",
998 patch_name, name,
999 ))
1000 .with_code(ScanningIssueKind::PatchIntroducesNewConstant)
1001 .with_annotation(Annotation::primary(patch_span))
1002 .with_help(format!(
1003 "Remove `{patch_name}::{name}` from the patch, or correct its name to match a \
1004 constant that already exists on the original. Patches can only refine the \
1005 types of existing constants.",
1006 )),
1007 );
1008 }
1009 }
1010 }
1011
1012 fn report_enum_cases(&self, patch: &mut ClassLikeMetadata) {
1017 if patch.enum_cases.is_empty() {
1018 return;
1019 }
1020
1021 patch.issues.push(
1022 Issue::error(format!(
1023 "Patch for `{}` declares enum case(s); enum cases are structural and cannot be \
1024 refined — patch enum cases are ignored.",
1025 patch.original_name,
1026 ))
1027 .with_code(ScanningIssueKind::PatchEnumCasesIgnored)
1028 .with_annotation(Annotation::primary(patch.span))
1029 .with_help(
1030 "Remove the enum case declarations from the patch. Enum cases define the runtime \
1031 values of the enum and must stay in the original definition; a patch can only \
1032 refine the types of existing members.",
1033 ),
1034 );
1035 }
1036
1037 #[inline]
1038 pub fn shrink_to_fit(&mut self) {
1039 self.aliases.shrink_to_fit();
1040 self.properties.shrink_to_fit();
1041 self.magic_properties.shrink_to_fit();
1042 self.magic_property_ids.shrink_to_fit();
1043 self.initialized_properties.shrink_to_fit();
1044 self.appearing_property_ids.shrink_to_fit();
1045 self.declaring_property_ids.shrink_to_fit();
1046 self.inheritable_property_ids.shrink_to_fit();
1047 self.overridden_property_ids.shrink_to_fit();
1048 self.appearing_method_ids.shrink_to_fit();
1049 self.declaring_method_ids.shrink_to_fit();
1050 self.inheritable_method_ids.shrink_to_fit();
1051 self.overridden_method_ids.shrink_to_fit();
1052 self.attributes.shrink_to_fit();
1053 self.constants.shrink_to_fit();
1054 self.enum_cases.shrink_to_fit();
1055 self.type_aliases.shrink_to_fit();
1056 }
1057}
1058
1059#[must_use]
1063pub fn collect_ancestor_methods<T>(class_meta: &ClassLikeMetadata, class_likes: &WordMap<T>) -> WordSet
1064where
1065 T: Borrow<ClassLikeMetadata>,
1066{
1067 let mut visited = WordSet::default();
1068 let mut methods = WordSet::default();
1069 collect_ancestor_methods_inner(class_meta, class_likes, &mut visited, &mut methods);
1070 methods
1071}
1072
1073fn collect_ancestor_methods_inner<T>(
1074 class_meta: &ClassLikeMetadata,
1075 class_likes: &WordMap<T>,
1076 visited: &mut WordSet,
1077 methods: &mut WordSet,
1078) where
1079 T: Borrow<ClassLikeMetadata>,
1080{
1081 if !visited.insert(class_meta.name) {
1082 return;
1083 }
1084 if let Some(parent_name) = class_meta.direct_parent_class
1085 && let Some(parent_meta) = class_likes.get(&parent_name).map(Borrow::borrow)
1086 {
1087 methods.extend(parent_meta.methods.iter().copied());
1088 collect_ancestor_methods_inner(parent_meta, class_likes, visited, methods);
1089 }
1090 for interface_name in &class_meta.direct_parent_interfaces {
1091 if let Some(interface_meta) = class_likes.get(interface_name).map(Borrow::borrow) {
1092 methods.extend(interface_meta.methods.iter().copied());
1093 collect_ancestor_methods_inner(interface_meta, class_likes, visited, methods);
1094 }
1095 }
1096 for trait_name in &class_meta.used_traits {
1097 if let Some(trait_meta) = class_likes.get(trait_name).map(Borrow::borrow) {
1098 methods.extend(trait_meta.methods.iter().copied());
1099 collect_ancestor_methods_inner(trait_meta, class_likes, visited, methods);
1100 }
1101 }
1102}
1103
1104#[cfg(test)]
1105mod tests {
1106 use std::iter::once;
1107
1108 use mago_span::Span;
1109 use mago_word::WordSet;
1110 use mago_word::word;
1111
1112 use crate::identifier::method::MethodIdentifier;
1113 use crate::issue::ScanningIssueKind;
1114 use crate::metadata::class_like_constant::ClassLikeConstantMetadata;
1115 use crate::metadata::enum_case::EnumCaseMetadata;
1116 use crate::metadata::flags::MetadataFlags;
1117 use crate::metadata::property::PropertyMetadata;
1118 use crate::misc::GenericParent;
1119 use crate::misc::VariableIdentifier;
1120 use crate::symbol::SymbolKind;
1121 use crate::ttype;
1122 use crate::ttype::template::GenericTemplate;
1123 use crate::ttype::template::variance::Variance;
1124 use crate::visibility::Visibility;
1125
1126 use super::ClassLikeMetadata;
1127
1128 fn has_code(issues: &[mago_reporting::Issue], kind: ScanningIssueKind) -> bool {
1129 let code = kind.to_string();
1130 issues.iter().any(|i| i.code.as_deref() == Some(code.as_str()))
1131 }
1132
1133 fn make(name: &str) -> ClassLikeMetadata {
1134 let a = word(name);
1135 ClassLikeMetadata::new(a, a, Span::dummy(0, 10), None, MetadataFlags::empty())
1136 }
1137
1138 #[test]
1139 fn incomplete_hierarchy_dependencies_hide_synthetic_enum_contracts() {
1140 let mut metadata = make("Example");
1141 metadata.kind = SymbolKind::Enum;
1142 metadata.invalid_dependencies.extend([
1143 word("unitenum"),
1144 word("backedenum"),
1145 word("__internal_do_not_use__intbackedenum"),
1146 ]);
1147
1148 assert!(!metadata.has_incomplete_hierarchy());
1149 assert_eq!(metadata.incomplete_hierarchy_dependencies().collect::<Vec<_>>(), []);
1150
1151 let missing = word("vendor\\missing\\contract");
1152 metadata.invalid_dependencies.insert(missing);
1153
1154 assert!(metadata.has_incomplete_hierarchy());
1155 assert_eq!(metadata.incomplete_hierarchy_dependencies().collect::<Vec<_>>(), [missing]);
1156 }
1157
1158 #[test]
1159 fn apply_patch_adds_override_for_inherited_real_method() {
1160 let class_name = word("VendorClass");
1161 let mut vendored = make("VendorClass");
1162 let method_existing = word("existing");
1163 vendored.methods.insert(method_existing);
1164 vendored.declaring_method_ids.insert(method_existing, MethodIdentifier::new(class_name, method_existing));
1165
1166 let mut patch = make("VendorClass");
1167 let method_override = word("inherited_method");
1168 patch.methods.insert(method_override);
1169 patch.declaring_method_ids.insert(method_override, MethodIdentifier::new(class_name, method_override));
1170 patch.appearing_method_ids.insert(method_override, MethodIdentifier::new(class_name, method_override));
1171 patch.inheritable_method_ids.insert(method_override, MethodIdentifier::new(class_name, method_override));
1172
1173 let inherited: WordSet = once(method_override).collect();
1174 vendored.apply_patch(&mut patch, &inherited);
1175 let issues = patch.issues;
1176
1177 assert!(vendored.methods.contains(&method_override));
1182 assert_eq!(
1183 vendored.declaring_method_ids.get(&method_override),
1184 Some(&MethodIdentifier::new(class_name, method_override)),
1185 );
1186 assert_eq!(
1187 vendored.appearing_method_ids.get(&method_override),
1188 Some(&MethodIdentifier::new(class_name, method_override)),
1189 );
1190 assert!(vendored.inheritable_method_ids.contains_key(&method_override));
1191
1192 assert!(issues.is_empty());
1194 }
1195
1196 #[test]
1197 fn apply_patch_adds_pseudo_methods() {
1198 let class_name = word("VendorClass");
1199 let mut vendored = make("VendorClass");
1200
1201 let mut patch = make("VendorClass");
1202 let pseudo = word("magicMethod");
1203 patch.pseudo_methods.insert(pseudo);
1204 patch.declaring_method_ids.insert(pseudo, MethodIdentifier::new(class_name, pseudo));
1205 patch.appearing_method_ids.insert(pseudo, MethodIdentifier::new(class_name, pseudo));
1206 patch.inheritable_method_ids.insert(pseudo, MethodIdentifier::new(class_name, pseudo));
1207
1208 vendored.apply_patch(&mut patch, &WordSet::default());
1209 let issues = patch.issues;
1210
1211 assert!(vendored.pseudo_methods.contains(&pseudo));
1213 assert!(vendored.declaring_method_ids.contains_key(&pseudo));
1214 assert!(vendored.appearing_method_ids.contains_key(&pseudo));
1215 assert!(vendored.inheritable_method_ids.contains_key(&pseudo));
1216
1217 assert!(!vendored.methods.contains(&pseudo));
1219
1220 assert!(issues.is_empty());
1222 }
1223
1224 #[test]
1225 fn apply_patch_accepts_new_magic_property() {
1226 let mut vendored = make("VendorClass");
1227
1228 let mut patch = make("VendorClass");
1229 let prop_magic = word("$magic");
1230 patch
1231 .magic_properties
1232 .insert(prop_magic, PropertyMetadata::new(VariableIdentifier(prop_magic), MetadataFlags::PATCH));
1233
1234 vendored.apply_patch(&mut patch, &WordSet::default());
1235 let issues = patch.issues;
1236
1237 assert!(vendored.magic_properties.contains_key(&prop_magic));
1238 assert_eq!(vendored.magic_property_ids.get(&prop_magic), Some(&vendored.name));
1239 assert!(issues.is_empty());
1240 }
1241
1242 #[test]
1243 fn apply_patch_does_not_touch_initialized_or_override_maps() {
1244 let mut vendored = make("VendorClass");
1245 let prop = word("$x");
1246 vendored.properties.insert(prop, PropertyMetadata::new(VariableIdentifier(prop), MetadataFlags::empty()));
1247 vendored.initialized_properties.insert(prop);
1248 vendored.overridden_property_ids.insert(prop, once(word("ParentClass")).collect());
1249
1250 let mut patch = make("VendorClass");
1251 patch.properties.insert(prop, PropertyMetadata::new(VariableIdentifier(prop), MetadataFlags::PATCH));
1252 vendored.apply_patch(&mut patch, &WordSet::default());
1255 let issues = patch.issues;
1256
1257 assert!(vendored.initialized_properties.contains(&prop));
1259 assert!(vendored.overridden_property_ids.contains_key(&prop));
1261 assert!(issues.is_empty());
1262 }
1263
1264 #[test]
1265 fn apply_patch_adds_template_types() {
1266 let class_name = word("VendorClass");
1267 let mut vendored = make("VendorClass");
1268
1269 let mut patch = make("VendorClass");
1270 let t = word("T");
1271 patch.template_types.insert(t, GenericTemplate::new(GenericParent::ClassLike(class_name), ttype::get_mixed()));
1272 patch.template_variance.push(Variance::Covariant);
1273 patch.template_readonly.insert(t);
1274
1275 vendored.apply_patch(&mut patch, &WordSet::default());
1276 let issues = patch.issues;
1277
1278 assert!(vendored.template_types.contains_key(&t));
1279 assert_eq!(vendored.template_variance.first().copied(), Some(Variance::Covariant));
1280 assert!(vendored.template_readonly.contains(&t));
1281 assert!(issues.is_empty());
1282 }
1283
1284 #[test]
1285 fn apply_patch_refines_existing_template_and_appends_new() {
1286 let class_name = word("VendorClass");
1287 let mut vendored = make("VendorClass");
1288 let t = word("T");
1289 let u = word("U");
1290
1291 vendored
1293 .template_types
1294 .insert(t, GenericTemplate::new(GenericParent::ClassLike(class_name), ttype::get_mixed()));
1295 vendored
1296 .template_types
1297 .insert(u, GenericTemplate::new(GenericParent::ClassLike(class_name), ttype::get_mixed()));
1298 vendored.template_variance = vec![Variance::Invariant, Variance::Covariant];
1299
1300 let mut patch = make("VendorClass");
1302 let v = word("V");
1303 patch.template_types.insert(t, GenericTemplate::new(GenericParent::ClassLike(class_name), ttype::get_int()));
1304 patch.template_types.insert(v, GenericTemplate::new(GenericParent::ClassLike(class_name), ttype::get_string()));
1305 patch.template_variance = vec![Variance::Contravariant, Variance::Invariant];
1306
1307 vendored.apply_patch(&mut patch, &WordSet::default());
1308 let issues = patch.issues;
1309
1310 assert_eq!(vendored.template_types.keys().copied().collect::<Vec<_>>(), [t, u, v]);
1312 assert_eq!(vendored.template_variance, [Variance::Contravariant, Variance::Covariant, Variance::Invariant]);
1313
1314 assert!(issues.is_empty());
1315 }
1316
1317 #[test]
1318 fn apply_patch_preserves_original_only_readonly_template() {
1319 let class_name = word("VendorClass");
1323 let mut vendored = make("VendorClass");
1324 let t = word("T");
1325 vendored
1326 .template_types
1327 .insert(t, GenericTemplate::new(GenericParent::ClassLike(class_name), ttype::get_mixed()));
1328 vendored.template_variance.push(Variance::Invariant);
1329 vendored.template_readonly.insert(t);
1330
1331 let mut patch = make("VendorClass");
1332 let u = word("U");
1333 patch.template_types.insert(u, GenericTemplate::new(GenericParent::ClassLike(class_name), ttype::get_mixed()));
1334 patch.template_variance.push(Variance::Invariant);
1335
1336 vendored.apply_patch(&mut patch, &WordSet::default());
1337 let issues = patch.issues;
1338
1339 assert!(vendored.template_readonly.contains(&t), "T should remain readonly after patch");
1340 assert!(!vendored.template_readonly.contains(&u), "U was not declared readonly by the patch");
1341 assert!(issues.is_empty());
1342 }
1343
1344 #[test]
1345 fn apply_patch_refines_parent_template_bindings() {
1346 let parent = word("Parent");
1347 let interface = word("Contract");
1348 let untouched = word("OtherContract");
1349 let mut vendored = make("VendorClass");
1350 vendored.direct_parent_class = Some(parent);
1351 vendored.direct_parent_interfaces.extend([interface, untouched]);
1352 vendored.template_extended_offsets.insert(parent, vec![ttype::get_int()]);
1353 vendored.template_extended_offsets.insert(interface, vec![ttype::get_int()]);
1354 vendored.template_extended_offsets.insert(untouched, vec![ttype::get_bool()]);
1355 vendored.template_type_extends_count.insert(parent, 1);
1356 vendored.template_type_implements_count.extend([(interface, 1), (untouched, 1)]);
1357
1358 let mut patch = make("VendorClass");
1359 patch.direct_parent_class = Some(parent);
1360 patch.direct_parent_interfaces.extend([interface, untouched]);
1361 patch.template_extended_offsets.insert(parent, vec![ttype::get_string(), ttype::get_int()]);
1362 patch.template_extended_offsets.insert(interface, vec![ttype::get_float()]);
1363 patch.template_type_extends_count.insert(parent, 2);
1364 patch.template_type_implements_count.insert(interface, 1);
1365
1366 vendored.apply_patch(&mut patch, &WordSet::default());
1367
1368 assert_eq!(vendored.template_extended_offsets[&parent], [ttype::get_string(), ttype::get_int()]);
1369 assert_eq!(vendored.template_extended_offsets[&interface], [ttype::get_float()]);
1370 assert_eq!(vendored.template_extended_offsets[&untouched], [ttype::get_bool()]);
1371 assert_eq!(vendored.template_type_extends_count[&parent], 2);
1372 assert_eq!(vendored.template_type_implements_count[&interface], 1);
1373 assert_eq!(vendored.template_type_implements_count[&untouched], 1);
1374 assert!(vendored.template_types.is_empty());
1375 assert!(patch.issues.is_empty());
1376 }
1377
1378 #[test]
1379 fn apply_patch_rejects_parent_template_bindings_on_hierarchy_mismatch() {
1380 let parent = word("Parent");
1381 let interface = word("Contract");
1382 for change_parent in [true, false] {
1383 let mut vendored = make("VendorClass");
1384 vendored.direct_parent_class = Some(parent);
1385 vendored.direct_parent_interfaces.insert(interface);
1386 vendored.template_extended_offsets.insert(parent, vec![ttype::get_int()]);
1387 vendored.template_extended_offsets.insert(interface, vec![ttype::get_int()]);
1388
1389 let mut patch = make("VendorClass");
1390 patch.direct_parent_class = Some(if change_parent { word("WrongParent") } else { parent });
1391 patch.direct_parent_interfaces.insert(if change_parent { interface } else { word("WrongContract") });
1392 patch.template_extended_offsets.insert(parent, vec![ttype::get_string()]);
1393 patch.template_extended_offsets.insert(interface, vec![ttype::get_string()]);
1394 patch.template_type_extends_count.insert(parent, 1);
1395 patch.template_type_implements_count.insert(interface, 1);
1396
1397 vendored.apply_patch(&mut patch, &WordSet::default());
1398
1399 assert_eq!(vendored.template_extended_offsets[&parent], [ttype::get_int()]);
1400 assert_eq!(vendored.template_extended_offsets[&interface], [ttype::get_int()]);
1401 assert!(has_code(&patch.issues, ScanningIssueKind::PatchHierarchyMismatch));
1402 }
1403 }
1404
1405 #[test]
1406 fn apply_patch_does_not_refine_trait_template_bindings() {
1407 let trait_name = word("GenericTrait");
1408 let mut vendored = make("VendorClass");
1409 vendored.used_traits.insert(trait_name);
1410 vendored.template_extended_offsets.insert(trait_name, vec![ttype::get_int()]);
1411
1412 let mut patch = make("VendorClass");
1413 patch.used_traits.insert(trait_name);
1414 patch.template_extended_offsets.insert(trait_name, vec![ttype::get_string()]);
1415 patch.template_type_uses_count.insert(trait_name, 1);
1416
1417 vendored.apply_patch(&mut patch, &WordSet::default());
1418
1419 assert_eq!(vendored.template_extended_offsets[&trait_name], [ttype::get_int()]);
1420 assert!(has_code(&patch.issues, ScanningIssueKind::PatchDeclaresTrait));
1421 }
1422
1423 #[test]
1424 fn apply_patch_rejects_kind_mismatch() {
1425 let mut vendored = make("VendorClass");
1426 let mut patch = make("VendorClass");
1427 patch.kind = SymbolKind::Interface;
1428
1429 vendored.apply_patch(&mut patch, &WordSet::default());
1430 let issues = patch.issues;
1431
1432 assert!(has_code(&issues, ScanningIssueKind::PatchKindMismatch));
1433 }
1434
1435 #[test]
1436 fn apply_patch_rejects_trait_use() {
1437 let mut vendored = make("VendorClass");
1438 let mut patch = make("VendorClass");
1439 patch.used_traits.insert(word("SomeTrait"));
1440
1441 vendored.apply_patch(&mut patch, &WordSet::default());
1442 let issues = patch.issues;
1443
1444 assert!(has_code(&issues, ScanningIssueKind::PatchDeclaresTrait));
1445 }
1446
1447 #[test]
1448 fn apply_patch_rejects_hierarchy_mismatch() {
1449 let mut vendored = make("VendorClass");
1450 vendored.direct_parent_class = Some(word("ActualParent"));
1451
1452 let mut patch = make("VendorClass");
1453 patch.direct_parent_class = Some(word("WrongParent"));
1454
1455 vendored.apply_patch(&mut patch, &WordSet::default());
1456 let issues = patch.issues;
1457
1458 assert!(has_code(&issues, ScanningIssueKind::PatchHierarchyMismatch));
1459 }
1460
1461 #[test]
1462 fn apply_patch_rejects_new_method_not_in_ancestors() {
1463 let mut vendored = make("VendorClass");
1464 let mut patch = make("VendorClass");
1465 patch.methods.insert(word("newMethod"));
1466
1467 vendored.apply_patch(&mut patch, &WordSet::default());
1468 let issues = patch.issues;
1469
1470 assert!(has_code(&issues, ScanningIssueKind::PatchIntroducesNewMethod));
1471 }
1472
1473 #[test]
1474 fn apply_patch_rejects_new_property() {
1475 let mut vendored = make("VendorClass");
1476 let mut patch = make("VendorClass");
1477 let prop = word("$newProp");
1478 patch.properties.insert(prop, PropertyMetadata::new(VariableIdentifier(prop), MetadataFlags::PATCH));
1479
1480 vendored.apply_patch(&mut patch, &WordSet::default());
1481 let issues = patch.issues;
1482
1483 assert!(has_code(&issues, ScanningIssueKind::PatchIntroducesNewProperty));
1484 }
1485
1486 #[test]
1487 fn apply_patch_rejects_new_constant() {
1488 let mut vendored = make("VendorClass");
1489 let mut patch = make("VendorClass");
1490 let c = word("NEW_CONST");
1491 patch
1492 .constants
1493 .insert(c, ClassLikeConstantMetadata::new(c, Span::dummy(0, 5), Visibility::Public, MetadataFlags::PATCH));
1494
1495 vendored.apply_patch(&mut patch, &WordSet::default());
1496 let issues = patch.issues;
1497
1498 assert!(has_code(&issues, ScanningIssueKind::PatchIntroducesNewConstant));
1499 }
1500
1501 #[test]
1502 fn apply_patch_rejects_enum_cases() {
1503 let mut vendored = make("VendorClass");
1504 let mut patch = make("VendorClass");
1505 let case = word("CaseA");
1506 patch
1507 .enum_cases
1508 .insert(case, EnumCaseMetadata::new(case, Span::dummy(0, 3), Span::dummy(0, 5), MetadataFlags::PATCH));
1509
1510 vendored.apply_patch(&mut patch, &WordSet::default());
1511 let issues = patch.issues;
1512
1513 assert!(has_code(&issues, ScanningIssueKind::PatchEnumCasesIgnored));
1514 }
1515
1516 #[test]
1517 fn apply_patch_rejects_property_structural_mismatch() {
1518 let mut vendored = make("VendorClass");
1519 let prop = word("$x");
1520 vendored.properties.insert(prop, PropertyMetadata::new(VariableIdentifier(prop), MetadataFlags::empty()));
1521
1522 let mut patch = make("VendorClass");
1523 patch.properties.insert(
1524 prop,
1525 PropertyMetadata::new(VariableIdentifier(prop), MetadataFlags::PATCH | MetadataFlags::STATIC),
1526 );
1527
1528 vendored.apply_patch(&mut patch, &WordSet::default());
1529 let issues = patch.issues;
1530
1531 assert!(has_code(&issues, ScanningIssueKind::PatchPropertyStructuralMismatch));
1532 }
1533
1534 #[test]
1535 fn apply_patch_rejects_constant_structural_mismatch() {
1536 let mut vendored = make("VendorClass");
1537 let c = word("MY_CONST");
1538 vendored.constants.insert(
1539 c,
1540 ClassLikeConstantMetadata::new(c, Span::dummy(0, 5), Visibility::Private, MetadataFlags::empty()),
1541 );
1542
1543 let mut patch = make("VendorClass");
1544 patch
1545 .constants
1546 .insert(c, ClassLikeConstantMetadata::new(c, Span::dummy(0, 5), Visibility::Public, MetadataFlags::PATCH));
1547
1548 vendored.apply_patch(&mut patch, &WordSet::default());
1549 let issues = patch.issues;
1550
1551 assert!(has_code(&issues, ScanningIssueKind::PatchConstantStructuralMismatch));
1552 }
1553}