-
Notifications
You must be signed in to change notification settings - Fork 4.1k
/
SourceMemberContainerSymbol_ImplementationChecks.cs
1530 lines (1345 loc) · 81.2 KB
/
SourceMemberContainerSymbol_ImplementationChecks.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
internal partial class SourceMemberContainerTypeSymbol
{
/// <summary>
/// In some circumstances (e.g. implicit implementation of an interface method by a non-virtual method in a
/// base type from another assembly) it is necessary for the compiler to generate explicit implementations for
/// some interface methods. They don't go in the symbol table, but if we are emitting, then we should
/// generate code for them.
/// </summary>
internal ImmutableArray<SynthesizedExplicitImplementationForwardingMethod> GetSynthesizedExplicitImplementations(
CancellationToken cancellationToken)
{
if (_lazySynthesizedExplicitImplementations.IsDefault)
{
var diagnostics = DiagnosticBag.GetInstance();
try
{
cancellationToken.ThrowIfCancellationRequested();
CheckMembersAgainstBaseType(diagnostics, cancellationToken);
cancellationToken.ThrowIfCancellationRequested();
CheckAbstractClassImplementations(diagnostics);
cancellationToken.ThrowIfCancellationRequested();
CheckInterfaceUnification(diagnostics);
if (this.IsInterface)
{
cancellationToken.ThrowIfCancellationRequested();
this.CheckInterfaceVarianceSafety(diagnostics);
}
if (ImmutableInterlocked.InterlockedCompareExchange(
ref _lazySynthesizedExplicitImplementations,
ComputeInterfaceImplementations(diagnostics, cancellationToken),
default(ImmutableArray<SynthesizedExplicitImplementationForwardingMethod>)).IsDefault)
{
// Do not cancel from this point on. We've assigned the member, so we must add
// the diagnostics.
AddDeclarationDiagnostics(diagnostics);
state.NotePartComplete(CompletionPart.SynthesizedExplicitImplementations);
}
}
finally
{
diagnostics.Free();
}
}
return _lazySynthesizedExplicitImplementations;
}
private void CheckAbstractClassImplementations(DiagnosticBag diagnostics)
{
NamedTypeSymbol baseType = this.BaseTypeNoUseSiteDiagnostics;
if (this.IsAbstract || (object)baseType == null || !baseType.IsAbstract)
{
return;
}
// CONSIDER: We know that no-one will ask for NotOverriddenAbstractMembers again
// (since this class is concrete), so we could just call the construction method
// directly to avoid storing the result.
foreach (var abstractMember in this.AbstractMembers)
{
// Dev10 reports failure to implement properties/events in terms of the accessors
if (abstractMember.Kind == SymbolKind.Method)
{
diagnostics.Add(ErrorCode.ERR_UnimplementedAbstractMethod, this.Locations[0], this, abstractMember);
}
}
}
private ImmutableArray<SynthesizedExplicitImplementationForwardingMethod> ComputeInterfaceImplementations(
DiagnosticBag diagnostics,
CancellationToken cancellationToken)
{
var synthesizedImplementations = ArrayBuilder<SynthesizedExplicitImplementationForwardingMethod>.GetInstance();
// NOTE: We can't iterator over this collection directly, since it is not ordered. Instead we
// iterate over AllInterfaces and filter out the interfaces that are not in this set. This is
// preferable to doing the DFS ourselves because both AllInterfaces and
// InterfacesAndTheirBaseInterfaces are cached and used in multiple places.
MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> interfacesAndTheirBases = this.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics;
foreach (var @interface in this.AllInterfacesNoUseSiteDiagnostics)
{
cancellationToken.ThrowIfCancellationRequested();
if (!interfacesAndTheirBases[@interface].Contains(@interface))
{
continue;
}
HasBaseTypeDeclaringInterfaceResult? hasBaseClassDeclaringInterface = null;
foreach (var interfaceMember in @interface.GetMembersUnordered())
{
cancellationToken.ThrowIfCancellationRequested();
// Only require implementations for members that can be implemented in C#.
SymbolKind interfaceMemberKind = interfaceMember.Kind;
switch (interfaceMemberKind)
{
case SymbolKind.Method:
case SymbolKind.Property:
case SymbolKind.Event:
if (!interfaceMember.IsImplementableInterfaceMember())
{
continue;
}
break;
default:
continue;
}
SymbolAndDiagnostics implementingMemberAndDiagnostics;
if (this.IsInterface)
{
MultiDictionary<Symbol, Symbol>.ValueSet explicitImpl = this.GetExplicitImplementationForInterfaceMember(interfaceMember);
switch (explicitImpl.Count)
{
case 0:
continue; // There is no requirement to implement anything in an interface
case 1:
implementingMemberAndDiagnostics = new SymbolAndDiagnostics(explicitImpl.Single(), ImmutableArray<Diagnostic>.Empty);
break;
default:
Diagnostic diag = new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.ERR_DuplicateExplicitImpl, interfaceMember), this.Locations[0]);
implementingMemberAndDiagnostics = new SymbolAndDiagnostics(null, ImmutableArray.Create(diag));
break;
}
}
else
{
implementingMemberAndDiagnostics = this.FindImplementationForInterfaceMemberInNonInterfaceWithDiagnostics(interfaceMember);
}
var implementingMember = implementingMemberAndDiagnostics.Symbol;
var synthesizedImplementation = this.SynthesizeInterfaceMemberImplementation(implementingMemberAndDiagnostics, interfaceMember);
bool wasImplementingMemberFound = (object)implementingMember != null;
if ((object)synthesizedImplementation != null)
{
if (synthesizedImplementation.IsVararg)
{
diagnostics.Add(
ErrorCode.ERR_InterfaceImplementedImplicitlyByVariadic,
GetImplicitImplementationDiagnosticLocation(interfaceMember, this, implementingMember), implementingMember, interfaceMember, this);
}
else
{
synthesizedImplementations.Add(synthesizedImplementation);
}
}
if (wasImplementingMemberFound && interfaceMemberKind == SymbolKind.Event)
{
// NOTE: unlike dev11, we're including a related location for the implementing type, because
// otherwise the only error location will be in the containing type of the implementing event
// (i.e. no indication of which type's interface list is actually problematic).
EventSymbol interfaceEvent = (EventSymbol)interfaceMember;
EventSymbol implementingEvent = (EventSymbol)implementingMember;
EventSymbol maybeWinRTEvent;
EventSymbol maybeRegularEvent;
if (interfaceEvent.IsWindowsRuntimeEvent)
{
maybeWinRTEvent = interfaceEvent; // Definitely WinRT.
maybeRegularEvent = implementingEvent; // Maybe regular.
}
else
{
maybeWinRTEvent = implementingEvent; // Maybe WinRT.
maybeRegularEvent = interfaceEvent; // Definitely regular.
}
if (interfaceEvent.IsWindowsRuntimeEvent != implementingEvent.IsWindowsRuntimeEvent)
{
// At this point (and not before), we know that maybeWinRTEvent is definitely a WinRT event and maybeRegularEvent is definitely a regular event.
var args = new object[] { implementingEvent, interfaceEvent, maybeWinRTEvent, maybeRegularEvent };
var info = new CSDiagnosticInfo(ErrorCode.ERR_MixingWinRTEventWithRegular, args, ImmutableArray<Symbol>.Empty, ImmutableArray.Create<Location>(this.Locations[0]));
diagnostics.Add(info, implementingEvent.Locations[0]);
}
}
// Dev10: If a whole property is missing, report the property. If the property is present, but an accessor
// is missing, report just the accessor.
var associatedPropertyOrEvent = interfaceMemberKind == SymbolKind.Method ? ((MethodSymbol)interfaceMember).AssociatedSymbol : null;
if ((object)associatedPropertyOrEvent == null ||
ReportAccessorOfInterfacePropertyOrEvent(associatedPropertyOrEvent) ||
(wasImplementingMemberFound && !implementingMember.IsAccessor()))
{
//we're here because
//(a) the interface member is not an accessor, or
//(b) the interface member is an accessor of an interesting (see ReportAccessorOfInterfacePropertyOrEvent) property or event, or
//(c) the implementing member exists and is not an accessor.
bool reportedAnError = false;
if (implementingMemberAndDiagnostics.Diagnostics.Any())
{
diagnostics.AddRange(implementingMemberAndDiagnostics.Diagnostics);
reportedAnError = implementingMemberAndDiagnostics.Diagnostics.Any(d => d.Severity == DiagnosticSeverity.Error);
}
if (!reportedAnError)
{
if (!wasImplementingMemberFound ||
(!implementingMember.ContainingType.Equals(this, TypeCompareKind.ConsiderEverything) &&
implementingMember.GetExplicitInterfaceImplementations().Contains(interfaceMember, ExplicitInterfaceImplementationTargetMemberEqualityComparer.Instance)))
{
// NOTE: An alternative approach would be to keep track of this while searching for the implementing member.
// In some cases, we might even be able to stop looking and just accept that a base type has things covered
// (though we'd have to be careful about losing diagnostics and we might produce fewer bridge methods).
// However, this approach has the advantage that there is no cost unless we encounter a base type that
// claims to implement an interface, but we can't figure out how (i.e. free in nearly all cases).
hasBaseClassDeclaringInterface = hasBaseClassDeclaringInterface ?? HasBaseClassDeclaringInterface(@interface);
HasBaseTypeDeclaringInterfaceResult matchResult = hasBaseClassDeclaringInterface.GetValueOrDefault();
if (matchResult != HasBaseTypeDeclaringInterfaceResult.ExactMatch &&
wasImplementingMemberFound && implementingMember.ContainingType.IsInterface)
{
HasBaseInterfaceDeclaringInterface(implementingMember.ContainingType, @interface, ref matchResult);
}
// If a base type from metadata declares that it implements the interface, we'll just trust it.
// (See fFoundImport in SymbolPreparer::CheckInterfaceMethodImplementation.)
switch (matchResult)
{
case HasBaseTypeDeclaringInterfaceResult.NoMatch:
{
// CONSIDER: Dev10 does not emit this diagnostic for interface properties if the
// derived type attempts to implement an accessor directly as a method.
// Suppress for bogus properties and events and for indexed properties.
if (!interfaceMember.MustCallMethodsDirectly() && !interfaceMember.IsIndexedProperty())
{
DiagnosticInfo useSiteDiagnostic = interfaceMember.GetUseSiteDiagnostic();
if (useSiteDiagnostic != null && useSiteDiagnostic.DefaultSeverity == DiagnosticSeverity.Error)
{
diagnostics.Add(useSiteDiagnostic, GetImplementsLocation(@interface));
}
else
{
diagnostics.Add(ErrorCode.ERR_UnimplementedInterfaceMember, GetImplementsLocation(@interface) ?? this.Locations[0], this, interfaceMember);
}
}
}
break;
case HasBaseTypeDeclaringInterfaceResult.ExactMatch:
break;
case HasBaseTypeDeclaringInterfaceResult.IgnoringNullableMatch:
diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInInterfaceImplementedByBase, GetImplementsLocation(@interface) ?? this.Locations[0], this, interfaceMember);
break;
default:
throw ExceptionUtilities.UnexpectedValue(matchResult);
}
}
if (wasImplementingMemberFound && interfaceMemberKind == SymbolKind.Method)
{
// Don't report use site errors on properties - we'll report them on each of their accessors.
// Don't report use site errors for implementations in other types unless
// a synthesized implementation is needed that invokes the base method.
// We can do so only if there are no use-site errors.
if ((object)synthesizedImplementation != null || TypeSymbol.Equals(implementingMember.ContainingType, this, TypeCompareKind.ConsiderEverything2))
{
DiagnosticInfo useSiteDiagnostic = interfaceMember.GetUseSiteDiagnostic();
// CAVEAT: don't report ERR_ByRefReturnUnsupported since by-ref return types are
// specifically allowed for the purposes of interface implementation (for C++ interop).
// However, if there's a reference to the interface member in source, then we do want
// to produce a use site error.
if (useSiteDiagnostic != null && (ErrorCode)useSiteDiagnostic.Code != ErrorCode.ERR_ByRefReturnUnsupported)
{
// Don't report a use site error with a location in another compilation. For example,
// if the error is that a base type in another assembly implemented an interface member
// on our behalf and the use site error is that the current assembly does not reference
// some required assembly, then we want to report the error in the current assembly -
// not in the implementing assembly.
Location location = implementingMember.IsFromCompilation(this.DeclaringCompilation)
? implementingMember.Locations[0]
: this.Locations[0];
Symbol.ReportUseSiteDiagnostic(useSiteDiagnostic, diagnostics, location);
}
}
}
}
}
}
}
return synthesizedImplementations.ToImmutableAndFree();
}
protected abstract Location GetCorrespondingBaseListLocation(NamedTypeSymbol @base);
internal Location GetImplementsLocation(NamedTypeSymbol implementedInterface)
{
// We ideally want to identify the interface location in the base list with an exact match but
// will fall back and use the first derived interface if exact interface is not present.
// this is the similar logic as the VB implementation.
Debug.Assert(this.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics[implementedInterface].Contains(implementedInterface));
HashSet<DiagnosticInfo> unuseddiagnostics = null;
NamedTypeSymbol directInterface = null;
foreach (var iface in this.InterfacesNoUseSiteDiagnostics())
{
if (TypeSymbol.Equals(iface, implementedInterface, TypeCompareKind.ConsiderEverything2))
{
directInterface = iface;
break;
}
else if ((object)directInterface == null && iface.ImplementsInterface(implementedInterface, ref unuseddiagnostics))
{
directInterface = iface;
}
}
Debug.Assert((object)directInterface != null);
return GetCorrespondingBaseListLocation(directInterface);
}
/// <summary>
/// It's not interesting to report diagnostics on implementation of interface accessors
/// if the corresponding events or properties are not implemented (i.e. we want to suppress
/// cascading diagnostics).
/// Caveat: Indexed property accessors are always interesting.
/// Caveat: It's also uninteresting if a WinRT event is implemented by a non-WinRT event,
/// or vice versa.
/// </summary>
private bool ReportAccessorOfInterfacePropertyOrEvent(Symbol interfacePropertyOrEvent)
{
Debug.Assert((object)interfacePropertyOrEvent != null);
// Accessors of indexed properties are always interesting.
if (interfacePropertyOrEvent.IsIndexedProperty())
{
return true;
}
Symbol implementingPropertyOrEvent;
if (this.IsInterface)
{
MultiDictionary<Symbol, Symbol>.ValueSet explicitImpl = this.GetExplicitImplementationForInterfaceMember(interfacePropertyOrEvent);
switch (explicitImpl.Count)
{
case 0:
return true;
case 1:
implementingPropertyOrEvent = explicitImpl.Single();
break;
default:
implementingPropertyOrEvent = null;
break;
}
}
else
{
implementingPropertyOrEvent = this.FindImplementationForInterfaceMemberInNonInterface(interfacePropertyOrEvent);
}
// If the property or event wasn't implemented, then we'd prefer to report diagnostics about that.
if ((object)implementingPropertyOrEvent == null)
{
return false;
}
// If the property or event was an event and was implemented, but the WinRT-ness didn't agree,
// then we'd prefer to report diagnostics about that.
if (interfacePropertyOrEvent.Kind == SymbolKind.Event && implementingPropertyOrEvent.Kind == SymbolKind.Event &&
((EventSymbol)interfacePropertyOrEvent).IsWindowsRuntimeEvent != ((EventSymbol)implementingPropertyOrEvent).IsWindowsRuntimeEvent)
{
return false;
}
return true;
}
private enum HasBaseTypeDeclaringInterfaceResult
{
NoMatch,
IgnoringNullableMatch,
ExactMatch,
}
private HasBaseTypeDeclaringInterfaceResult HasBaseClassDeclaringInterface(NamedTypeSymbol @interface)
{
HasBaseTypeDeclaringInterfaceResult result = HasBaseTypeDeclaringInterfaceResult.NoMatch;
for (NamedTypeSymbol currType = this.BaseTypeNoUseSiteDiagnostics; (object)currType != null; currType = currType.BaseTypeNoUseSiteDiagnostics)
{
if (DeclaresBaseInterface(currType, @interface, ref result))
{
break;
}
}
return result;
}
static private bool DeclaresBaseInterface(NamedTypeSymbol currType, NamedTypeSymbol @interface, ref HasBaseTypeDeclaringInterfaceResult result)
{
MultiDictionary<NamedTypeSymbol, NamedTypeSymbol>.ValueSet set = currType.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics[@interface];
if (set.Count != 0)
{
if (set.Contains(@interface))
{
result = HasBaseTypeDeclaringInterfaceResult.ExactMatch;
return true;
}
else if (result == HasBaseTypeDeclaringInterfaceResult.NoMatch && set.Contains(@interface, Symbols.SymbolEqualityComparer.IgnoringNullable))
{
result = HasBaseTypeDeclaringInterfaceResult.IgnoringNullableMatch;
}
}
return false;
}
private void HasBaseInterfaceDeclaringInterface(NamedTypeSymbol baseInterface, NamedTypeSymbol @interface, ref HasBaseTypeDeclaringInterfaceResult matchResult)
{
// Let's check for the trivial case first
if (DeclaresBaseInterface(baseInterface, @interface, ref matchResult))
{
return;
}
foreach (var interfaceType in this.AllInterfacesNoUseSiteDiagnostics)
{
if ((object)interfaceType == baseInterface)
{
continue;
}
if (interfaceType.Equals(baseInterface, TypeCompareKind.CLRSignatureCompareOptions) &&
DeclaresBaseInterface(interfaceType, @interface, ref matchResult))
{
return;
}
}
}
private void CheckMembersAgainstBaseType(
DiagnosticBag diagnostics,
CancellationToken cancellationToken)
{
switch (this.TypeKind)
{
// These checks don't make sense for enums and delegates:
case TypeKind.Enum:
case TypeKind.Delegate:
return;
case TypeKind.Class:
case TypeKind.Struct:
case TypeKind.Interface:
case TypeKind.Submission: // we have to check that "override" is not used
break;
default:
throw ExceptionUtilities.UnexpectedValue(this.TypeKind);
}
foreach (var member in this.GetMembersUnordered())
{
cancellationToken.ThrowIfCancellationRequested();
bool suppressAccessors;
switch (member.Kind)
{
case SymbolKind.Method:
var method = (MethodSymbol)member;
if (MethodSymbol.CanOverrideOrHide(method.MethodKind) && !method.IsAccessor())
{
if (member.IsOverride)
{
CheckOverrideMember(method, method.OverriddenOrHiddenMembers, diagnostics, out suppressAccessors);
}
else
{
var sourceMethod = method as SourceMemberMethodSymbol;
if ((object)sourceMethod != null) // skip submission initializer
{
var isNew = sourceMethod.IsNew;
CheckNonOverrideMember(method, isNew, method.OverriddenOrHiddenMembers, diagnostics, out suppressAccessors);
}
}
}
else if (method.MethodKind == MethodKind.Destructor)
{
// NOTE: Normal finalize methods CanOverrideOrHide and will go through the normal code path.
// First is fine, since there should only be one, since there are no parameters.
MethodSymbol overridden = method.GetFirstRuntimeOverriddenMethodIgnoringNewSlot(ignoreInterfaceImplementationChanges: true);
// NOTE: Dev11 doesn't expose symbols, so it can treat destructors as override and let them go through the normal
// checks. Roslyn can't, since the language says they are not virtual/override and that's what we need to expose
// in the symbol model. Having said that, Dev11 doesn't seem to produce override errors other than this one
// (see SymbolPreparer::prepareOperator).
if ((object)overridden != null && overridden.IsMetadataFinal)
{
diagnostics.Add(ErrorCode.ERR_CantOverrideSealed, method.Locations[0], method, overridden);
}
}
break;
case SymbolKind.Property:
var property = (PropertySymbol)member;
var getMethod = property.GetMethod;
var setMethod = property.SetMethod;
// Handle the accessors here, instead of in the loop, so that we can ensure that
// they're checked *after* the corresponding property.
if (member.IsOverride)
{
CheckOverrideMember(property, property.OverriddenOrHiddenMembers, diagnostics, out suppressAccessors);
if (!suppressAccessors)
{
if ((object)getMethod != null)
{
CheckOverrideMember(getMethod, getMethod.OverriddenOrHiddenMembers, diagnostics, out suppressAccessors);
}
if ((object)setMethod != null)
{
CheckOverrideMember(setMethod, setMethod.OverriddenOrHiddenMembers, diagnostics, out suppressAccessors);
}
}
}
else
{
var isNewProperty = ((SourcePropertySymbol)property).IsNew;
CheckNonOverrideMember(property, isNewProperty, property.OverriddenOrHiddenMembers, diagnostics, out suppressAccessors);
if (!suppressAccessors)
{
if ((object)getMethod != null)
{
CheckNonOverrideMember(getMethod, isNewProperty, getMethod.OverriddenOrHiddenMembers, diagnostics, out suppressAccessors);
}
if ((object)setMethod != null)
{
CheckNonOverrideMember(setMethod, isNewProperty, setMethod.OverriddenOrHiddenMembers, diagnostics, out suppressAccessors);
}
}
}
break;
case SymbolKind.Event:
var @event = (EventSymbol)member;
var addMethod = @event.AddMethod;
var removeMethod = @event.RemoveMethod;
// Handle the accessors here, instead of in the loop, so that we can ensure that
// they're checked *after* the corresponding event.
if (member.IsOverride)
{
CheckOverrideMember(@event, @event.OverriddenOrHiddenMembers, diagnostics, out suppressAccessors);
if (!suppressAccessors)
{
if ((object)addMethod != null)
{
CheckOverrideMember(addMethod, addMethod.OverriddenOrHiddenMembers, diagnostics, out suppressAccessors);
}
if ((object)removeMethod != null)
{
CheckOverrideMember(removeMethod, removeMethod.OverriddenOrHiddenMembers, diagnostics, out suppressAccessors);
}
}
}
else
{
var isNewEvent = ((SourceEventSymbol)@event).IsNew;
CheckNonOverrideMember(@event, isNewEvent, @event.OverriddenOrHiddenMembers, diagnostics, out suppressAccessors);
if (!suppressAccessors)
{
if ((object)addMethod != null)
{
CheckNonOverrideMember(addMethod, isNewEvent, addMethod.OverriddenOrHiddenMembers, diagnostics, out suppressAccessors);
}
if ((object)removeMethod != null)
{
CheckNonOverrideMember(removeMethod, isNewEvent, removeMethod.OverriddenOrHiddenMembers, diagnostics, out suppressAccessors);
}
}
}
break;
case SymbolKind.Field:
var sourceField = member as SourceFieldSymbol;
var isNewField = (object)sourceField != null && sourceField.IsNew;
// We don't want to report diagnostics for field-like event backing fields (redundant),
// but that shouldn't be an issue since they shouldn't be in the member list.
Debug.Assert((object)sourceField == null || (object)sourceField.AssociatedSymbol == null ||
sourceField.AssociatedSymbol.Kind != SymbolKind.Event);
CheckNewModifier(member, isNewField, diagnostics);
break;
case SymbolKind.NamedType:
CheckNewModifier(member, ((SourceMemberContainerTypeSymbol)member).IsNew, diagnostics);
break;
}
}
}
private void CheckNewModifier(Symbol symbol, bool isNew, DiagnosticBag diagnostics)
{
Debug.Assert(symbol.Kind == SymbolKind.Field || symbol.Kind == SymbolKind.NamedType);
// Do not give warnings about missing 'new' modifier for implicitly declared members,
// e.g. backing fields for auto-properties
if (symbol.IsImplicitlyDeclared)
{
return;
}
if (symbol.ContainingType.IsInterface)
{
CheckNonOverrideMember(symbol, isNew,
OverriddenOrHiddenMembersHelpers.MakeInterfaceOverriddenOrHiddenMembers(symbol, memberIsFromSomeCompilation: true),
diagnostics, out _);
return;
}
// for error cases
if ((object)this.BaseTypeNoUseSiteDiagnostics == null)
{
return;
}
int symbolArity = symbol.GetMemberArity();
Location symbolLocation = symbol.Locations.FirstOrDefault();
bool unused = false;
NamedTypeSymbol currType = this.BaseTypeNoUseSiteDiagnostics;
while ((object)currType != null)
{
foreach (var hiddenMember in currType.GetMembers(symbol.Name))
{
if (hiddenMember.Kind == SymbolKind.Method && !((MethodSymbol)hiddenMember).CanBeHiddenByMemberKind(symbol.Kind))
{
continue;
}
HashSet<DiagnosticInfo> useSiteDiagnostics = null;
bool isAccessible = AccessCheck.IsSymbolAccessible(hiddenMember, this, ref useSiteDiagnostics);
diagnostics.Add(symbolLocation, useSiteDiagnostics);
if (isAccessible && hiddenMember.GetMemberArity() == symbolArity)
{
if (!isNew)
{
diagnostics.Add(ErrorCode.WRN_NewRequired, symbolLocation, symbol, hiddenMember);
}
AddHidingAbstractDiagnostic(symbol, symbolLocation, hiddenMember, diagnostics, ref unused);
return;
}
}
currType = currType.BaseTypeNoUseSiteDiagnostics;
}
if (isNew)
{
diagnostics.Add(ErrorCode.WRN_NewNotRequired, symbolLocation, symbol);
}
}
private static void CheckOverrideMember(Symbol overridingMember, OverriddenOrHiddenMembersResult overriddenOrHiddenMembers,
DiagnosticBag diagnostics, out bool suppressAccessors)
{
Debug.Assert((object)overridingMember != null);
Debug.Assert(overriddenOrHiddenMembers != null);
suppressAccessors = false;
var overridingMemberIsMethod = overridingMember.Kind == SymbolKind.Method;
var overridingMemberIsProperty = overridingMember.Kind == SymbolKind.Property;
var overridingMemberIsEvent = overridingMember.Kind == SymbolKind.Event;
Debug.Assert(overridingMemberIsMethod ^ overridingMemberIsProperty ^ overridingMemberIsEvent);
var overridingMemberLocation = overridingMember.Locations[0];
var overriddenMembers = overriddenOrHiddenMembers.OverriddenMembers;
Debug.Assert(!overriddenMembers.IsDefault);
if (overriddenMembers.Length == 0)
{
var hiddenMembers = overriddenOrHiddenMembers.HiddenMembers;
Debug.Assert(!hiddenMembers.IsDefault);
if (hiddenMembers.Any())
{
ErrorCode errorCode =
overridingMemberIsMethod ? ErrorCode.ERR_CantOverrideNonFunction :
overridingMemberIsProperty ? ErrorCode.ERR_CantOverrideNonProperty :
ErrorCode.ERR_CantOverrideNonEvent;
diagnostics.Add(errorCode, overridingMemberLocation, overridingMember, hiddenMembers[0]);
}
else
{
Symbol associatedPropertyOrEvent = null;
if (overridingMemberIsMethod)
{
associatedPropertyOrEvent = ((MethodSymbol)overridingMember).AssociatedSymbol;
}
if ((object)associatedPropertyOrEvent == null)
{
bool suppressError = false;
if (overridingMemberIsMethod || overridingMember.IsIndexer())
{
var parameterTypes = overridingMemberIsMethod
? ((MethodSymbol)overridingMember).ParameterTypesWithAnnotations
: ((PropertySymbol)overridingMember).ParameterTypesWithAnnotations;
foreach (var parameterType in parameterTypes)
{
if (isOrContainsErrorType(parameterType.Type))
{
suppressError = true; // The parameter type must be fixed before the override can be found, so suppress error
break;
}
}
}
if (!suppressError)
{
diagnostics.Add(ErrorCode.ERR_OverrideNotExpected, overridingMemberLocation, overridingMember);
}
}
else if (associatedPropertyOrEvent.Kind == SymbolKind.Property) //no specific errors for event accessors
{
PropertySymbol associatedProperty = (PropertySymbol)associatedPropertyOrEvent;
PropertySymbol overriddenProperty = associatedProperty.OverriddenProperty;
if ((object)overriddenProperty == null)
{
//skip remaining checks
}
else if (associatedProperty.GetMethod == overridingMember && (object)overriddenProperty.GetMethod == null)
{
diagnostics.Add(ErrorCode.ERR_NoGetToOverride, overridingMemberLocation, overridingMember, overriddenProperty);
}
else if (associatedProperty.SetMethod == overridingMember && (object)overriddenProperty.SetMethod == null)
{
diagnostics.Add(ErrorCode.ERR_NoSetToOverride, overridingMemberLocation, overridingMember, overriddenProperty);
}
else
{
diagnostics.Add(ErrorCode.ERR_OverrideNotExpected, overridingMemberLocation, overridingMember);
}
}
}
}
else
{
NamedTypeSymbol overridingType = overridingMember.ContainingType;
if (overriddenMembers.Length > 1)
{
diagnostics.Add(ErrorCode.ERR_AmbigOverride, overridingMemberLocation,
overriddenMembers[0].OriginalDefinition, overriddenMembers[1].OriginalDefinition, overridingType);
suppressAccessors = true;
}
else
{
var overriddenMember = overriddenMembers[0];
//otherwise, it would have been excluded during lookup
HashSet<DiagnosticInfo> useSiteDiagnosticsNotUsed = null;
Debug.Assert(AccessCheck.IsSymbolAccessible(overriddenMember, overridingType, ref useSiteDiagnosticsNotUsed));
Debug.Assert(overriddenMember.Kind == overridingMember.Kind);
if (overriddenMember.MustCallMethodsDirectly())
{
diagnostics.Add(ErrorCode.ERR_CantOverrideBogusMethod, overridingMemberLocation, overridingMember, overriddenMember);
suppressAccessors = true;
}
else if (!overriddenMember.IsVirtual && !overriddenMember.IsAbstract && !overriddenMember.IsOverride &&
!(overridingMemberIsMethod && ((MethodSymbol)overriddenMember).MethodKind == MethodKind.Destructor)) //destructors are metadata virtual
{
// CONSIDER: To match Dev10, skip the error for properties, and don't suppressAccessors
diagnostics.Add(ErrorCode.ERR_CantOverrideNonVirtual, overridingMemberLocation, overridingMember, overriddenMember);
suppressAccessors = true;
}
else if (overriddenMember.IsSealed)
{
// CONSIDER: To match Dev10, skip the error for properties, and don't suppressAccessors
diagnostics.Add(ErrorCode.ERR_CantOverrideSealed, overridingMemberLocation, overridingMember, overriddenMember);
suppressAccessors = true;
}
else if (!overridingMember.IsPartialMethod() && !OverrideHasCorrectAccessibility(overriddenMember, overridingMember))
{
var accessibility = SyntaxFacts.GetText(overriddenMember.DeclaredAccessibility);
diagnostics.Add(ErrorCode.ERR_CantChangeAccessOnOverride, overridingMemberLocation, overridingMember, accessibility, overriddenMember);
suppressAccessors = true;
}
else if (overridingMember.ContainsTupleNames() &&
MemberSignatureComparer.ConsideringTupleNamesCreatesDifference(overridingMember, overriddenMember))
{
// it is ok to override with no tuple names, for compatibility with C# 6, but otherwise names should match
diagnostics.Add(ErrorCode.ERR_CantChangeTupleNamesOnOverride, overridingMemberLocation, overridingMember, overriddenMember);
}
else
{
// As in dev11, we don't compare obsoleteness to the immediately-overridden member,
// but to the least-overridden member.
var leastOverriddenMember = overriddenMember.GetLeastOverriddenMember(overriddenMember.ContainingType);
overridingMember.ForceCompleteObsoleteAttribute();
leastOverriddenMember.ForceCompleteObsoleteAttribute();
Debug.Assert(overridingMember.ObsoleteState != ThreeState.Unknown);
Debug.Assert(leastOverriddenMember.ObsoleteState != ThreeState.Unknown);
bool overridingMemberIsObsolete = overridingMember.ObsoleteState == ThreeState.True;
bool leastOverriddenMemberIsObsolete = leastOverriddenMember.ObsoleteState == ThreeState.True;
if (overridingMemberIsObsolete != leastOverriddenMemberIsObsolete)
{
ErrorCode code = overridingMemberIsObsolete
? ErrorCode.WRN_ObsoleteOverridingNonObsolete
: ErrorCode.WRN_NonObsoleteOverridingObsolete;
diagnostics.Add(code, overridingMemberLocation, overridingMember, leastOverriddenMember);
}
if (overridingMemberIsProperty)
{
PropertySymbol overridingProperty = (PropertySymbol)overridingMember;
PropertySymbol overriddenProperty = (PropertySymbol)overriddenMember;
TypeWithAnnotations overridingMemberType = overridingProperty.TypeWithAnnotations;
TypeWithAnnotations overriddenMemberType = overriddenProperty.TypeWithAnnotations;
// Check for mismatched byref returns and return type. Ignore custom modifiers, because this diagnostic is based on the C# semantics.
if (overridingProperty.RefKind != overriddenProperty.RefKind)
{
diagnostics.Add(ErrorCode.ERR_CantChangeRefReturnOnOverride, overridingMemberLocation, overridingMember, overriddenMember);
suppressAccessors = true; //we get really unhelpful errors from the accessor if the ref kind is mismatched
}
else if (!overridingMemberType.Equals(overriddenMemberType, TypeCompareKind.AllIgnoreOptions))
{
// if the type is or contains an error type, the type must be fixed before the override can be found, so suppress error
if (!isOrContainsErrorType(overridingMemberType.Type))
{
diagnostics.Add(ErrorCode.ERR_CantChangeTypeOnOverride, overridingMemberLocation, overridingMember, overriddenMember, overriddenMemberType.Type);
}
suppressAccessors = true; //we get really unhelpful errors from the accessor if the type is mismatched
}
else
{
if (overridingProperty.GetMethod is object)
{
MethodSymbol overriddenGetMethod = overriddenProperty.GetOwnOrInheritedGetMethod();
checkValidNullableMethodOverride(
overridingProperty.GetMethod.Locations[0],
overriddenGetMethod,
overridingProperty.GetMethod,
diagnostics,
checkReturnType: true,
// Don't check parameters on the getter if there is a setter
// because they will be a subset of the setter
checkParameters: overridingProperty.SetMethod is null ||
overriddenGetMethod?.AssociatedSymbol != overriddenProperty ||
overriddenProperty.GetOwnOrInheritedSetMethod()?.AssociatedSymbol != overriddenProperty);
}
if (overridingProperty.SetMethod is object)
{
checkValidNullableMethodOverride(
overridingProperty.SetMethod.Locations[0],
overriddenProperty.GetOwnOrInheritedSetMethod(),
overridingProperty.SetMethod,
diagnostics,
checkReturnType: false,
checkParameters: true);
}
}
// If the overriding property is sealed, then the overridden accessors cannot be inaccessible, since we
// have to override them to make them sealed in metadata.
// CONSIDER: It might be nice if this had its own error code(s) since it's an implementation restriction,
// rather than a language restriction as above.
if (overridingProperty.IsSealed)
{
MethodSymbol ownOrInheritedGetMethod = overridingProperty.GetOwnOrInheritedGetMethod();
HashSet<DiagnosticInfo> useSiteDiagnostics = null;
if (overridingProperty.GetMethod != ownOrInheritedGetMethod && !AccessCheck.IsSymbolAccessible(ownOrInheritedGetMethod, overridingType, ref useSiteDiagnostics))
{
diagnostics.Add(ErrorCode.ERR_NoGetToOverride, overridingMemberLocation, overridingProperty, overriddenProperty);
}
MethodSymbol ownOrInheritedSetMethod = overridingProperty.GetOwnOrInheritedSetMethod();
if (overridingProperty.SetMethod != ownOrInheritedSetMethod && !AccessCheck.IsSymbolAccessible(ownOrInheritedSetMethod, overridingType, ref useSiteDiagnostics))
{
diagnostics.Add(ErrorCode.ERR_NoSetToOverride, overridingMemberLocation, overridingProperty, overriddenProperty);
}
diagnostics.Add(overridingMemberLocation, useSiteDiagnostics);
}
}
else if (overridingMemberIsEvent)
{
EventSymbol overridingEvent = (EventSymbol)overridingMember;
EventSymbol overriddenEvent = (EventSymbol)overriddenMember;
TypeWithAnnotations overridingMemberType = overridingEvent.TypeWithAnnotations;
TypeWithAnnotations overriddenMemberType = overriddenEvent.TypeWithAnnotations;
// Ignore custom modifiers because this diagnostic is based on the C# semantics.
if (!overridingMemberType.Equals(overriddenMemberType, TypeCompareKind.AllIgnoreOptions))
{
// if the type is or contains an error type, the type must be fixed before the override can be found, so suppress error
if (!isOrContainsErrorType(overridingMemberType.Type))
{
diagnostics.Add(ErrorCode.ERR_CantChangeTypeOnOverride, overridingMemberLocation, overridingMember, overriddenMember, overriddenMemberType.Type);
}
suppressAccessors = true; //we get really unhelpful errors from the accessor if the type is mismatched
}
else
{
CheckValidNullableEventOverride(overridingEvent.DeclaringCompilation, overriddenEvent, overridingEvent,
diagnostics,
(diagnostics, overriddenEvent, overridingEvent, location) => diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInTypeOnOverride, location),
overridingMemberLocation);
}
}
else
{
Debug.Assert(overridingMemberIsMethod);
var overridingMethod = (MethodSymbol)overridingMember;
var overriddenMethod = (MethodSymbol)overriddenMember;
if (overridingMethod.IsGenericMethod)
{
overriddenMethod = overriddenMethod.Construct(overridingMethod.TypeArgumentsWithAnnotations);
}
// Check for mismatched byref returns and return type. Ignore custom modifiers, because this diagnostic is based on the C# semantics.
if (overridingMethod.RefKind != overriddenMethod.RefKind)
{
diagnostics.Add(ErrorCode.ERR_CantChangeRefReturnOnOverride, overridingMemberLocation, overridingMember, overriddenMember);
}
else if (!overridingMethod.ReturnTypeWithAnnotations.Equals(overriddenMethod.ReturnTypeWithAnnotations, TypeCompareKind.AllIgnoreOptions))
{
// if the Return type is or contains an error type, the return type must be fixed before the override can be found, so suppress error
if (!isOrContainsErrorType(overridingMethod.ReturnType))
{
// error CS0508: return type must be 'C<V>' to match overridden member 'M<T>()'
diagnostics.Add(ErrorCode.ERR_CantChangeReturnTypeOnOverride, overridingMemberLocation, overridingMember, overriddenMember, overriddenMethod.ReturnType);
}
}
else if (overriddenMethod.IsRuntimeFinalizer())
{
diagnostics.Add(ErrorCode.ERR_OverrideFinalizeDeprecated, overridingMemberLocation);
}
else if (!overridingMethod.IsAccessor())
{
// Accessors will have already been checked above
checkValidNullableMethodOverride(
overridingMemberLocation,
overriddenMethod,
overridingMethod,
diagnostics,