-
Notifications
You must be signed in to change notification settings - Fork 4.1k
/
Copy pathSourceComplexParameterSymbol.cs
1280 lines (1118 loc) · 63.3 KB
/
SourceComplexParameterSymbol.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
/// <summary>
/// A source parameter, potentially with a default value, attributes, etc.
/// </summary>
internal class SourceComplexParameterSymbol : SourceParameterSymbol, IAttributeTargetSymbol
{
[Flags]
private enum ParameterSyntaxKind : byte
{
Regular = 0,
ParamsParameter = 1,
ExtensionThisParameter = 2,
DefaultParameter = 4,
}
private readonly SyntaxReference _syntaxRef;
private readonly ParameterSyntaxKind _parameterSyntaxKind;
private CustomAttributesBag<CSharpAttributeData> _lazyCustomAttributesBag;
private ThreeState _lazyHasOptionalAttribute;
protected ConstantValue _lazyDefaultSyntaxValue;
internal SourceComplexParameterSymbol(
Symbol owner,
int ordinal,
TypeWithAnnotations parameterType,
RefKind refKind,
string name,
ImmutableArray<Location> locations,
SyntaxReference syntaxRef,
bool isParams,
bool isExtensionMethodThis)
: base(owner, parameterType, ordinal, refKind, name, locations)
{
Debug.Assert((syntaxRef == null) || (syntaxRef.GetSyntax().IsKind(SyntaxKind.Parameter)));
_lazyHasOptionalAttribute = ThreeState.Unknown;
_syntaxRef = syntaxRef;
if (isParams)
{
_parameterSyntaxKind |= ParameterSyntaxKind.ParamsParameter;
}
if (isExtensionMethodThis)
{
_parameterSyntaxKind |= ParameterSyntaxKind.ExtensionThisParameter;
}
var parameterSyntax = this.CSharpSyntaxNode;
if (parameterSyntax != null && parameterSyntax.Default != null)
{
_parameterSyntaxKind |= ParameterSyntaxKind.DefaultParameter;
}
_lazyDefaultSyntaxValue = ConstantValue.Unset;
}
private Binder ParameterBinderOpt => (ContainingSymbol as SourceMethodSymbolWithAttributes)?.ParameterBinder;
internal sealed override SyntaxReference SyntaxReference => _syntaxRef;
private ParameterSyntax CSharpSyntaxNode => (ParameterSyntax)_syntaxRef?.GetSyntax();
public override bool IsDiscard => false;
internal sealed override ConstantValue ExplicitDefaultConstantValue
{
get
{
// Parameter has either default argument syntax or DefaultParameterValue attribute, but not both.
// We separate these since in some scenarios (delegate Invoke methods) we need to suppress syntactic
// default value but use value from pseudo-custom attribute.
//
// For example:
// public delegate void D([Optional, DefaultParameterValue(1)]int a, int b = 2);
//
// Dev11 emits the first parameter as option with default value and the second as regular parameter.
// The syntactic default value is suppressed since additional synthesized parameters are added at the end of the signature.
return DefaultSyntaxValue ?? DefaultValueFromAttributes;
}
}
internal sealed override ConstantValue DefaultValueFromAttributes
{
get
{
ParameterEarlyWellKnownAttributeData data = GetEarlyDecodedWellKnownAttributeData();
return (data != null && data.DefaultParameterValue != ConstantValue.Unset) ? data.DefaultParameterValue : ConstantValue.NotAvailable;
}
}
internal sealed override bool IsIDispatchConstant
=> GetDecodedWellKnownAttributeData()?.HasIDispatchConstantAttribute == true;
internal override bool IsIUnknownConstant
=> GetDecodedWellKnownAttributeData()?.HasIUnknownConstantAttribute == true;
internal override bool IsCallerLineNumber => GetEarlyDecodedWellKnownAttributeData()?.HasCallerLineNumberAttribute == true;
internal override bool IsCallerFilePath => GetEarlyDecodedWellKnownAttributeData()?.HasCallerFilePathAttribute == true;
internal override bool IsCallerMemberName => GetEarlyDecodedWellKnownAttributeData()?.HasCallerMemberNameAttribute == true;
internal override int CallerArgumentExpressionParameterIndex
{
get
{
return GetEarlyDecodedWellKnownAttributeData()?.CallerArgumentExpressionParameterIndex ?? -1;
}
}
internal override FlowAnalysisAnnotations FlowAnalysisAnnotations
{
get
{
return DecodeFlowAnalysisAttributes(GetDecodedWellKnownAttributeData());
}
}
private static FlowAnalysisAnnotations DecodeFlowAnalysisAttributes(ParameterWellKnownAttributeData attributeData)
{
if (attributeData == null)
{
return FlowAnalysisAnnotations.None;
}
FlowAnalysisAnnotations annotations = FlowAnalysisAnnotations.None;
if (attributeData.HasAllowNullAttribute) annotations |= FlowAnalysisAnnotations.AllowNull;
if (attributeData.HasDisallowNullAttribute) annotations |= FlowAnalysisAnnotations.DisallowNull;
if (attributeData.HasMaybeNullAttribute)
{
annotations |= FlowAnalysisAnnotations.MaybeNull;
}
else
{
if (attributeData.MaybeNullWhenAttribute is bool when)
{
annotations |= (when ? FlowAnalysisAnnotations.MaybeNullWhenTrue : FlowAnalysisAnnotations.MaybeNullWhenFalse);
}
}
if (attributeData.HasNotNullAttribute)
{
annotations |= FlowAnalysisAnnotations.NotNull;
}
else
{
if (attributeData.NotNullWhenAttribute is bool when)
{
annotations |= (when ? FlowAnalysisAnnotations.NotNullWhenTrue : FlowAnalysisAnnotations.NotNullWhenFalse);
}
}
if (attributeData.DoesNotReturnIfAttribute is bool condition)
{
annotations |= (condition ? FlowAnalysisAnnotations.DoesNotReturnIfTrue : FlowAnalysisAnnotations.DoesNotReturnIfFalse);
}
return annotations;
}
internal override ImmutableHashSet<string> NotNullIfParameterNotNull
=> GetDecodedWellKnownAttributeData()?.NotNullIfParameterNotNull ?? ImmutableHashSet<string>.Empty;
internal bool HasEnumeratorCancellationAttribute
{
get
{
ParameterWellKnownAttributeData attributeData = GetDecodedWellKnownAttributeData();
return attributeData?.HasEnumeratorCancellationAttribute == true;
}
}
#nullable enable
internal static SyntaxNode? GetDefaultValueSyntaxForIsNullableAnalysisEnabled(ParameterSyntax? parameterSyntax) =>
parameterSyntax?.Default?.Value;
private ConstantValue DefaultSyntaxValue
{
get
{
if (state.NotePartComplete(CompletionPart.StartDefaultSyntaxValue))
{
var diagnostics = BindingDiagnosticBag.GetInstance();
Debug.Assert(diagnostics.DiagnosticBag != null);
var previousValue = Interlocked.CompareExchange(
ref _lazyDefaultSyntaxValue,
MakeDefaultExpression(diagnostics, out var binder, out var parameterEqualsValue),
ConstantValue.Unset);
Debug.Assert(previousValue == ConstantValue.Unset);
var completedOnThisThread = state.NotePartComplete(CompletionPart.EndDefaultSyntaxValue);
Debug.Assert(completedOnThisThread);
if (parameterEqualsValue is not null)
{
if (binder is not null &&
GetDefaultValueSyntaxForIsNullableAnalysisEnabled(CSharpSyntaxNode) is { } valueSyntax)
{
NullableWalker.AnalyzeIfNeeded(binder, parameterEqualsValue, valueSyntax, diagnostics.DiagnosticBag);
}
if (!_lazyDefaultSyntaxValue.IsBad)
{
VerifyParamDefaultValueMatchesAttributeIfAny(_lazyDefaultSyntaxValue, parameterEqualsValue.Value.Syntax, diagnostics);
}
}
AddDeclarationDiagnostics(diagnostics);
diagnostics.Free();
completedOnThisThread = state.NotePartComplete(CompletionPart.EndDefaultSyntaxValueDiagnostics);
Debug.Assert(completedOnThisThread);
}
state.SpinWaitComplete(CompletionPart.EndDefaultSyntaxValue, default(CancellationToken));
return _lazyDefaultSyntaxValue;
}
}
private Binder GetBinder(SyntaxNode syntax)
{
var binder = ParameterBinderOpt;
// If binder is null, then get it from the compilation. Otherwise use the provided binder.
// Don't always get it from the compilation because we might be in a speculative context (local function parameter),
// in which case the declaring compilation is the wrong one.
if (binder == null)
{
var compilation = this.DeclaringCompilation;
var binderFactory = compilation.GetBinderFactory(syntax.SyntaxTree);
binder = binderFactory.GetBinder(syntax);
}
Debug.Assert(binder.GetBinder(syntax) == null);
return binder;
}
private void NullableAnalyzeParameterDefaultValueFromAttributes()
{
var parameterSyntax = this.CSharpSyntaxNode;
if (parameterSyntax == null)
{
// If there is no syntax at all for the parameter, it means we are in a situation like
// a property setter whose 'value' parameter has a default value from attributes.
// There isn't a sensible use for this in the language, so we just bail in such scenarios.
return;
}
// The syntax span used to determine whether the attribute value is in a nullable-enabled
// context is larger than necessary - it includes the entire attribute list rather than the specific
// default value attribute which is used in AttributeSemanticModel.IsNullableAnalysisEnabled().
var attributes = parameterSyntax.AttributeLists.Node;
if (attributes is null || !NullableWalker.NeedsAnalysis(DeclaringCompilation, attributes))
{
return;
}
var defaultValue = DefaultValueFromAttributes;
if (defaultValue == null || defaultValue.IsBad)
{
return;
}
var binder = GetBinder(parameterSyntax);
// Nullable warnings *within* the attribute argument (such as a W-warning for `(string)null`)
// are reported when we nullable-analyze attribute arguments separately from here.
// However, this analysis of the constant value's compatibility with the parameter
// needs to wait until the attributes are populated on the parameter symbol.
var parameterEqualsValue = new BoundParameterEqualsValue(
parameterSyntax,
this,
ImmutableArray<LocalSymbol>.Empty,
// note that if the parameter type conflicts with the default value from attributes,
// we will just get a bad constant value above and return early.
new BoundLiteral(parameterSyntax, defaultValue, Type));
var diagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics: true, withDependencies: false);
Debug.Assert(diagnostics.DiagnosticBag != null);
NullableWalker.AnalyzeIfNeeded(binder, parameterEqualsValue, parameterSyntax, diagnostics.DiagnosticBag);
AddDeclarationDiagnostics(diagnostics);
diagnostics.Free();
}
// This method *must not* depend on attributes on the parameter symbol.
// Otherwise we will have cycles when binding usage of attributes whose constructors have optional parameters
private ConstantValue MakeDefaultExpression(BindingDiagnosticBag diagnostics, out Binder? binder, out BoundParameterEqualsValue? parameterEqualsValue)
{
binder = null;
parameterEqualsValue = null;
var parameterSyntax = this.CSharpSyntaxNode;
if (parameterSyntax == null)
{
return ConstantValue.NotAvailable;
}
var defaultSyntax = parameterSyntax.Default;
if (defaultSyntax == null)
{
return ConstantValue.NotAvailable;
}
binder = GetBinder(defaultSyntax);
Binder binderForDefault = binder.CreateBinderForParameterDefaultValue(this, defaultSyntax);
Debug.Assert(binderForDefault.InParameterDefaultValue);
Debug.Assert(binderForDefault.ContainingMemberOrLambda == ContainingSymbol);
parameterEqualsValue = binderForDefault.BindParameterDefaultValue(defaultSyntax, this, diagnostics, out var valueBeforeConversion);
if (valueBeforeConversion.HasErrors)
{
return ConstantValue.Bad;
}
BoundExpression convertedExpression = parameterEqualsValue.Value;
bool hasErrors = ParameterHelpers.ReportDefaultParameterErrors(binder, ContainingSymbol, parameterSyntax, this, valueBeforeConversion, convertedExpression, diagnostics);
if (hasErrors)
{
return ConstantValue.Bad;
}
// If we have something like M(double? x = 1) then the expression we'll get is (double?)1, which
// does not have a constant value. The constant value we want is (double)1.
// The default literal conversion is an exception: (double)default would give the wrong value for M(double? x = default).
if (convertedExpression.ConstantValue == null && convertedExpression.Kind == BoundKind.Conversion &&
((BoundConversion)convertedExpression).ConversionKind != ConversionKind.DefaultLiteral)
{
if (parameterType.Type.IsNullableType())
{
convertedExpression = binder.GenerateConversionForAssignment(parameterType.Type.GetNullableUnderlyingType(),
valueBeforeConversion, diagnostics, isDefaultParameter: true);
}
}
// represent default(struct) by a Null constant:
var value = convertedExpression.ConstantValue ?? ConstantValue.Null;
return value;
}
#nullable disable
public override string MetadataName
{
get
{
// The metadata parameter name should be the name used in the partial definition.
var sourceMethod = this.ContainingSymbol as SourceOrdinaryMethodSymbol;
if ((object)sourceMethod == null)
{
return base.MetadataName;
}
var definition = sourceMethod.SourcePartialDefinition;
if ((object)definition == null)
{
return base.MetadataName;
}
return definition.Parameters[this.Ordinal].MetadataName;
}
}
protected virtual IAttributeTargetSymbol AttributeOwner => this;
IAttributeTargetSymbol IAttributeTargetSymbol.AttributesOwner => AttributeOwner;
AttributeLocation IAttributeTargetSymbol.DefaultAttributeLocation => AttributeLocation.Parameter;
AttributeLocation IAttributeTargetSymbol.AllowedAttributeLocations
{
get
{
if (SynthesizedRecordPropertySymbol.HaveCorrespondingSynthesizedRecordPropertySymbol(this))
{
return AttributeLocation.Parameter | AttributeLocation.Property | AttributeLocation.Field;
}
return AttributeLocation.Parameter;
}
}
/// <summary>
/// Symbol to copy bound attributes from, or null if the attributes are not shared among multiple source parameter symbols.
/// </summary>
/// <remarks>
/// Used for parameters of partial implementation. We bind the attributes only on the definition
/// part and copy them over to the implementation.
/// </remarks>
private SourceParameterSymbol BoundAttributesSource
{
get
{
var sourceMethod = this.ContainingSymbol as SourceOrdinaryMethodSymbol;
if ((object)sourceMethod == null)
{
return null;
}
var impl = sourceMethod.SourcePartialImplementation;
if ((object)impl == null)
{
return null;
}
return (SourceParameterSymbol)impl.Parameters[this.Ordinal];
}
}
internal sealed override SyntaxList<AttributeListSyntax> AttributeDeclarationList
{
get
{
var syntax = this.CSharpSyntaxNode;
return (syntax != null) ? syntax.AttributeLists : default(SyntaxList<AttributeListSyntax>);
}
}
/// <summary>
/// Gets the syntax list of custom attributes that declares attributes for this parameter symbol.
/// </summary>
internal virtual OneOrMany<SyntaxList<AttributeListSyntax>> GetAttributeDeclarations()
{
// C# spec:
// The attributes on the parameters of the resulting method declaration
// are the combined attributes of the corresponding parameters of the defining
// and the implementing partial method declaration in unspecified order.
// Duplicates are not removed.
SyntaxList<AttributeListSyntax> attributes = AttributeDeclarationList;
var sourceMethod = this.ContainingSymbol as SourceOrdinaryMethodSymbol;
if ((object)sourceMethod == null)
{
return OneOrMany.Create(attributes);
}
SyntaxList<AttributeListSyntax> otherAttributes;
// if this is a definition get the implementation and vice versa
SourceOrdinaryMethodSymbol otherPart = sourceMethod.OtherPartOfPartial;
if ((object)otherPart != null)
{
otherAttributes = ((SourceParameterSymbol)otherPart.Parameters[this.Ordinal]).AttributeDeclarationList;
}
else
{
otherAttributes = default(SyntaxList<AttributeListSyntax>);
}
if (attributes.Equals(default(SyntaxList<AttributeListSyntax>)))
{
return OneOrMany.Create(otherAttributes);
}
else if (otherAttributes.Equals(default(SyntaxList<AttributeListSyntax>)))
{
return OneOrMany.Create(attributes);
}
return OneOrMany.Create(ImmutableArray.Create(attributes, otherAttributes));
}
/// <summary>
/// Returns data decoded from well-known attributes applied to the symbol or null if there are no applied attributes.
/// </summary>
/// <remarks>
/// Forces binding and decoding of attributes.
/// </remarks>
internal ParameterWellKnownAttributeData GetDecodedWellKnownAttributeData()
{
var attributesBag = _lazyCustomAttributesBag;
if (attributesBag == null || !attributesBag.IsDecodedWellKnownAttributeDataComputed)
{
attributesBag = this.GetAttributesBag();
}
return (ParameterWellKnownAttributeData)attributesBag.DecodedWellKnownAttributeData;
}
/// <summary>
/// Returns data decoded from special early bound well-known attributes applied to the symbol or null if there are no applied attributes.
/// </summary>
/// <remarks>
/// Forces binding and decoding of attributes.
/// </remarks>
internal ParameterEarlyWellKnownAttributeData GetEarlyDecodedWellKnownAttributeData()
{
var attributesBag = _lazyCustomAttributesBag;
if (attributesBag == null || !attributesBag.IsEarlyDecodedWellKnownAttributeDataComputed)
{
attributesBag = this.GetAttributesBag();
}
return (ParameterEarlyWellKnownAttributeData)attributesBag.EarlyDecodedWellKnownAttributeData;
}
/// <summary>
/// Returns a bag of applied custom attributes and data decoded from well-known attributes. Returns null if there are no attributes applied on the symbol.
/// </summary>
/// <remarks>
/// Forces binding and decoding of attributes.
/// </remarks>
internal sealed override CustomAttributesBag<CSharpAttributeData> GetAttributesBag()
{
if (_lazyCustomAttributesBag == null || !_lazyCustomAttributesBag.IsSealed)
{
SourceParameterSymbol copyFrom = this.BoundAttributesSource;
// prevent infinite recursion:
Debug.Assert(!ReferenceEquals(copyFrom, this));
bool bagCreatedOnThisThread;
if ((object)copyFrom != null)
{
var attributesBag = copyFrom.GetAttributesBag();
bagCreatedOnThisThread = Interlocked.CompareExchange(ref _lazyCustomAttributesBag, attributesBag, null) == null;
}
else
{
var attributeSyntax = this.GetAttributeDeclarations();
bagCreatedOnThisThread = LoadAndValidateAttributes(attributeSyntax, ref _lazyCustomAttributesBag, binderOpt: ParameterBinderOpt);
}
if (bagCreatedOnThisThread)
{
NullableAnalyzeParameterDefaultValueFromAttributes();
state.NotePartComplete(CompletionPart.Attributes);
}
}
return _lazyCustomAttributesBag;
}
internal override void EarlyDecodeWellKnownAttributeType(NamedTypeSymbol attributeType, AttributeSyntax attributeSyntax)
{
Debug.Assert(!attributeType.IsErrorType());
// NOTE: OptionalAttribute is decoded specially before any of the other attributes and stored in the parameter
// symbol (rather than in the EarlyWellKnownAttributeData) because it is needed during overload resolution.
if (CSharpAttributeData.IsTargetEarlyAttribute(attributeType, attributeSyntax, AttributeDescription.OptionalAttribute))
{
_lazyHasOptionalAttribute = ThreeState.True;
}
}
internal override void PostEarlyDecodeWellKnownAttributeTypes()
{
if (_lazyHasOptionalAttribute == ThreeState.Unknown)
{
_lazyHasOptionalAttribute = ThreeState.False;
}
base.PostEarlyDecodeWellKnownAttributeTypes();
}
internal override CSharpAttributeData EarlyDecodeWellKnownAttribute(ref EarlyDecodeWellKnownAttributeArguments<EarlyWellKnownAttributeBinder, NamedTypeSymbol, AttributeSyntax, AttributeLocation> arguments)
{
if (CSharpAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.DefaultParameterValueAttribute))
{
return EarlyDecodeAttributeForDefaultParameterValue(AttributeDescription.DefaultParameterValueAttribute, ref arguments);
}
else if (CSharpAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.DecimalConstantAttribute))
{
return EarlyDecodeAttributeForDefaultParameterValue(AttributeDescription.DecimalConstantAttribute, ref arguments);
}
else if (CSharpAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.DateTimeConstantAttribute))
{
return EarlyDecodeAttributeForDefaultParameterValue(AttributeDescription.DateTimeConstantAttribute, ref arguments);
}
else if (!IsOnPartialImplementation(arguments.AttributeSyntax))
{
if (CSharpAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.CallerLineNumberAttribute))
{
arguments.GetOrCreateData<ParameterEarlyWellKnownAttributeData>().HasCallerLineNumberAttribute = true;
}
else if (CSharpAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.CallerFilePathAttribute))
{
arguments.GetOrCreateData<ParameterEarlyWellKnownAttributeData>().HasCallerFilePathAttribute = true;
}
else if (CSharpAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.CallerMemberNameAttribute))
{
arguments.GetOrCreateData<ParameterEarlyWellKnownAttributeData>().HasCallerMemberNameAttribute = true;
}
else if (CSharpAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.CallerArgumentExpressionAttribute))
{
var index = -1;
var attribute = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, out _);
if (!attribute.HasErrors)
{
var constructorArguments = attribute.CommonConstructorArguments;
Debug.Assert(constructorArguments.Length == 1);
if (constructorArguments[0].TryDecodeValue(SpecialType.System_String, out string value))
{
var parameters = ContainingSymbol.GetParameters();
for (int i = 0; i < parameters.Length; i++)
{
if (parameters[i].Name == parameterName)
{
index = i;
break;
}
}
}
}
arguments.GetOrCreateData<ParameterEarlyWellKnownAttributeData>().CallerArgumentExpressionParameterIndex = index;
}
}
return base.EarlyDecodeWellKnownAttribute(ref arguments);
}
private CSharpAttributeData EarlyDecodeAttributeForDefaultParameterValue(AttributeDescription description, ref EarlyDecodeWellKnownAttributeArguments<EarlyWellKnownAttributeBinder, NamedTypeSymbol, AttributeSyntax, AttributeLocation> arguments)
{
Debug.Assert(description.Equals(AttributeDescription.DefaultParameterValueAttribute) ||
description.Equals(AttributeDescription.DecimalConstantAttribute) ||
description.Equals(AttributeDescription.DateTimeConstantAttribute));
bool hasAnyDiagnostics;
var attribute = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, out hasAnyDiagnostics);
ConstantValue value;
if (attribute.HasErrors)
{
value = ConstantValue.Bad;
hasAnyDiagnostics = true;
}
else
{
value = DecodeDefaultParameterValueAttribute(description, attribute, arguments.AttributeSyntax, diagnose: false, diagnosticsOpt: null);
}
var paramData = arguments.GetOrCreateData<ParameterEarlyWellKnownAttributeData>();
if (paramData.DefaultParameterValue == ConstantValue.Unset)
{
paramData.DefaultParameterValue = value;
}
return !hasAnyDiagnostics ? attribute : null;
}
internal override void DecodeWellKnownAttribute(ref DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments)
{
Debug.Assert((object)arguments.AttributeSyntaxOpt != null);
var attribute = arguments.Attribute;
Debug.Assert(!attribute.HasErrors);
Debug.Assert(arguments.SymbolPart == AttributeLocation.None);
var diagnostics = (BindingDiagnosticBag)arguments.Diagnostics;
if (attribute.IsTargetAttribute(this, AttributeDescription.DefaultParameterValueAttribute))
{
// Attribute decoded and constant value stored during EarlyDecodeWellKnownAttribute.
DecodeDefaultParameterValueAttribute(AttributeDescription.DefaultParameterValueAttribute, ref arguments);
}
else if (attribute.IsTargetAttribute(this, AttributeDescription.DecimalConstantAttribute))
{
// Attribute decoded and constant value stored during EarlyDecodeWellKnownAttribute.
DecodeDefaultParameterValueAttribute(AttributeDescription.DecimalConstantAttribute, ref arguments);
}
else if (attribute.IsTargetAttribute(this, AttributeDescription.DateTimeConstantAttribute))
{
// Attribute decoded and constant value stored during EarlyDecodeWellKnownAttribute.
DecodeDefaultParameterValueAttribute(AttributeDescription.DateTimeConstantAttribute, ref arguments);
}
else if (attribute.IsTargetAttribute(this, AttributeDescription.OptionalAttribute))
{
Debug.Assert(_lazyHasOptionalAttribute == ThreeState.True);
if (HasDefaultArgumentSyntax)
{
// error CS1745: Cannot specify default parameter value in conjunction with DefaultParameterAttribute or OptionalAttribute
diagnostics.Add(ErrorCode.ERR_DefaultValueUsedWithAttributes, arguments.AttributeSyntaxOpt.Name.Location);
}
}
else if (attribute.IsTargetAttribute(this, AttributeDescription.ParamArrayAttribute))
{
// error CS0674: Do not use 'System.ParamArrayAttribute'. Use the 'params' keyword instead.
diagnostics.Add(ErrorCode.ERR_ExplicitParamArray, arguments.AttributeSyntaxOpt.Name.Location);
}
else if (attribute.IsTargetAttribute(this, AttributeDescription.InAttribute))
{
arguments.GetOrCreateData<ParameterWellKnownAttributeData>().HasInAttribute = true;
}
else if (attribute.IsTargetAttribute(this, AttributeDescription.OutAttribute))
{
arguments.GetOrCreateData<ParameterWellKnownAttributeData>().HasOutAttribute = true;
}
else if (attribute.IsTargetAttribute(this, AttributeDescription.MarshalAsAttribute))
{
MarshalAsAttributeDecoder<ParameterWellKnownAttributeData, AttributeSyntax, CSharpAttributeData, AttributeLocation>.Decode(ref arguments, AttributeTargets.Parameter, MessageProvider.Instance);
}
else if (attribute.IsTargetAttribute(this, AttributeDescription.IDispatchConstantAttribute))
{
arguments.GetOrCreateData<ParameterWellKnownAttributeData>().HasIDispatchConstantAttribute = true;
}
else if (attribute.IsTargetAttribute(this, AttributeDescription.IUnknownConstantAttribute))
{
arguments.GetOrCreateData<ParameterWellKnownAttributeData>().HasIUnknownConstantAttribute = true;
}
else if (attribute.IsTargetAttribute(this, AttributeDescription.CallerLineNumberAttribute))
{
ValidateCallerLineNumberAttribute(arguments.AttributeSyntaxOpt, diagnostics);
}
else if (attribute.IsTargetAttribute(this, AttributeDescription.CallerFilePathAttribute))
{
ValidateCallerFilePathAttribute(arguments.AttributeSyntaxOpt, diagnostics);
}
else if (attribute.IsTargetAttribute(this, AttributeDescription.CallerMemberNameAttribute))
{
ValidateCallerMemberNameAttribute(arguments.AttributeSyntaxOpt, diagnostics);
}
else if (attribute.IsTargetAttribute(this, AttributeDescription.CallerArgumentExpressionAttribute))
{
ValidateCallerArgumentExpressionAttribute(arguments.AttributeSyntaxOpt, attribute, diagnostics);
}
else if (ReportExplicitUseOfReservedAttributes(in arguments,
ReservedAttributes.DynamicAttribute | ReservedAttributes.IsReadOnlyAttribute | ReservedAttributes.IsUnmanagedAttribute | ReservedAttributes.IsByRefLikeAttribute | ReservedAttributes.TupleElementNamesAttribute | ReservedAttributes.NullableAttribute | ReservedAttributes.NativeIntegerAttribute))
{
}
else if (attribute.IsTargetAttribute(this, AttributeDescription.AllowNullAttribute))
{
arguments.GetOrCreateData<ParameterWellKnownAttributeData>().HasAllowNullAttribute = true;
}
else if (attribute.IsTargetAttribute(this, AttributeDescription.DisallowNullAttribute))
{
arguments.GetOrCreateData<ParameterWellKnownAttributeData>().HasDisallowNullAttribute = true;
}
else if (attribute.IsTargetAttribute(this, AttributeDescription.MaybeNullAttribute))
{
arguments.GetOrCreateData<ParameterWellKnownAttributeData>().HasMaybeNullAttribute = true;
}
else if (attribute.IsTargetAttribute(this, AttributeDescription.MaybeNullWhenAttribute))
{
arguments.GetOrCreateData<ParameterWellKnownAttributeData>().MaybeNullWhenAttribute = DecodeMaybeNullWhenOrNotNullWhenOrDoesNotReturnIfAttribute(AttributeDescription.MaybeNullWhenAttribute, attribute);
}
else if (attribute.IsTargetAttribute(this, AttributeDescription.NotNullAttribute))
{
arguments.GetOrCreateData<ParameterWellKnownAttributeData>().HasNotNullAttribute = true;
}
else if (attribute.IsTargetAttribute(this, AttributeDescription.NotNullWhenAttribute))
{
arguments.GetOrCreateData<ParameterWellKnownAttributeData>().NotNullWhenAttribute = DecodeMaybeNullWhenOrNotNullWhenOrDoesNotReturnIfAttribute(AttributeDescription.NotNullWhenAttribute, attribute);
}
else if (attribute.IsTargetAttribute(this, AttributeDescription.DoesNotReturnIfAttribute))
{
arguments.GetOrCreateData<ParameterWellKnownAttributeData>().DoesNotReturnIfAttribute = DecodeMaybeNullWhenOrNotNullWhenOrDoesNotReturnIfAttribute(AttributeDescription.DoesNotReturnIfAttribute, attribute);
}
else if (attribute.IsTargetAttribute(this, AttributeDescription.NotNullIfNotNullAttribute))
{
arguments.GetOrCreateData<ParameterWellKnownAttributeData>().AddNotNullIfParameterNotNull(attribute.DecodeNotNullIfNotNullAttribute());
}
else if (attribute.IsTargetAttribute(this, AttributeDescription.EnumeratorCancellationAttribute))
{
arguments.GetOrCreateData<ParameterWellKnownAttributeData>().HasEnumeratorCancellationAttribute = true;
ValidateCancellationTokenAttribute(arguments.AttributeSyntaxOpt, (BindingDiagnosticBag)arguments.Diagnostics);
}
}
private static bool? DecodeMaybeNullWhenOrNotNullWhenOrDoesNotReturnIfAttribute(AttributeDescription description, CSharpAttributeData attribute)
{
var arguments = attribute.CommonConstructorArguments;
return arguments.Length == 1 && arguments[0].TryDecodeValue(SpecialType.System_Boolean, out bool value) ?
(bool?)value :
null;
}
private void DecodeDefaultParameterValueAttribute(AttributeDescription description, ref DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments)
{
var attribute = arguments.Attribute;
var syntax = arguments.AttributeSyntaxOpt;
var diagnostics = (BindingDiagnosticBag)arguments.Diagnostics;
Debug.Assert(syntax != null);
Debug.Assert(diagnostics != null);
var value = DecodeDefaultParameterValueAttribute(description, attribute, syntax, diagnose: true, diagnosticsOpt: diagnostics);
if (!value.IsBad)
{
VerifyParamDefaultValueMatchesAttributeIfAny(value, syntax, diagnostics);
}
}
/// <summary>
/// Verify the default value matches the default value from any earlier attribute
/// (DefaultParameterValueAttribute, DateTimeConstantAttribute or DecimalConstantAttribute).
/// If not, report ERR_ParamDefaultValueDiffersFromAttribute.
/// </summary>
private void VerifyParamDefaultValueMatchesAttributeIfAny(ConstantValue value, SyntaxNode syntax, BindingDiagnosticBag diagnostics)
{
var data = GetEarlyDecodedWellKnownAttributeData();
if (data != null)
{
var attrValue = data.DefaultParameterValue;
if ((attrValue != ConstantValue.Unset) &&
(value != attrValue))
{
// CS8017: The parameter has multiple distinct default values.
diagnostics.Add(ErrorCode.ERR_ParamDefaultValueDiffersFromAttribute, syntax.Location);
}
}
}
private ConstantValue DecodeDefaultParameterValueAttribute(AttributeDescription description, CSharpAttributeData attribute, AttributeSyntax node, bool diagnose, BindingDiagnosticBag diagnosticsOpt)
{
Debug.Assert(!attribute.HasErrors);
if (description.Equals(AttributeDescription.DefaultParameterValueAttribute))
{
return DecodeDefaultParameterValueAttribute(attribute, node, diagnose, diagnosticsOpt);
}
else if (description.Equals(AttributeDescription.DecimalConstantAttribute))
{
return attribute.DecodeDecimalConstantValue();
}
else
{
Debug.Assert(description.Equals(AttributeDescription.DateTimeConstantAttribute));
return attribute.DecodeDateTimeConstantValue();
}
}
private ConstantValue DecodeDefaultParameterValueAttribute(CSharpAttributeData attribute, AttributeSyntax node, bool diagnose, BindingDiagnosticBag diagnosticsOpt)
{
Debug.Assert(!diagnose || diagnosticsOpt != null);
if (HasDefaultArgumentSyntax)
{
// error CS1745: Cannot specify default parameter value in conjunction with DefaultParameterAttribute or OptionalAttribute
if (diagnose)
{
diagnosticsOpt.Add(ErrorCode.ERR_DefaultValueUsedWithAttributes, node.Name.Location);
}
return ConstantValue.Bad;
}
// BREAK: In dev10, DefaultParameterValueAttribute could not be applied to System.Type or array parameters.
// When this was attempted, dev10 produced CS1909, ERR_DefaultValueBadParamType. Roslyn takes a different
// approach: instead of looking at the parameter type, we look at the argument type. There's nothing wrong
// with providing a default value for a System.Type or array parameter, as long as the default parameter
// is not a System.Type or an array (i.e. null is fine). Since we are no longer interested in the type of
// the parameter, all occurrences of CS1909 have been replaced with CS1910, ERR_DefaultValueBadValueType,
// to indicate that the argument type, rather than the parameter type, is the source of the problem.
Debug.Assert(attribute.CommonConstructorArguments.Length == 1);
// the type of the value is the type of the expression in the attribute:
var arg = attribute.CommonConstructorArguments[0];
SpecialType specialType = arg.Kind == TypedConstantKind.Enum ?
((NamedTypeSymbol)arg.TypeInternal).EnumUnderlyingType.SpecialType :
arg.TypeInternal.SpecialType;
var compilation = this.DeclaringCompilation;
var constantValueDiscriminator = ConstantValue.GetDiscriminator(specialType);
var useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(diagnosticsOpt, ContainingAssembly);
if (constantValueDiscriminator == ConstantValueTypeDiscriminator.Bad)
{
if (arg.Kind != TypedConstantKind.Array && arg.ValueInternal == null)
{
if (this.Type.IsReferenceType)
{
constantValueDiscriminator = ConstantValueTypeDiscriminator.Null;
}
else
{
// error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type
if (diagnose)
{
diagnosticsOpt.Add(ErrorCode.ERR_DefaultValueTypeMustMatch, node.Name.Location);
}
return ConstantValue.Bad;
}
}
else
{
// error CS1910: Argument of type '{0}' is not applicable for the DefaultParameterValue attribute
if (diagnose)
{
diagnosticsOpt.Add(ErrorCode.ERR_DefaultValueBadValueType, node.Name.Location, arg.TypeInternal);
}
return ConstantValue.Bad;
}
}
else if (!compilation.Conversions.ClassifyConversionFromType((TypeSymbol)arg.TypeInternal, this.Type, ref useSiteInfo).Kind.IsImplicitConversion())
{
// error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type
if (diagnose)
{
diagnosticsOpt.Add(ErrorCode.ERR_DefaultValueTypeMustMatch, node.Name.Location);
diagnosticsOpt.Add(node.Name.Location, useSiteInfo);
}
return ConstantValue.Bad;
}
if (diagnose)
{
diagnosticsOpt.Add(node.Name.Location, useSiteInfo);
}
return ConstantValue.Create(arg.ValueInternal, constantValueDiscriminator);
}
private bool IsValidCallerInfoContext(AttributeSyntax node) => !ContainingSymbol.IsExplicitInterfaceImplementation()
&& !ContainingSymbol.IsOperator()
&& !IsOnPartialImplementation(node);
/// <summary>
/// Is the attribute syntax appearing on a parameter of a partial method implementation part?
/// Since attributes are merged between the parts of a partial, we need to look at the syntax where the
/// attribute appeared in the source to see if it corresponds to a partial method implementation part.
/// </summary>
/// <param name="node"></param>
/// <returns></returns>
private bool IsOnPartialImplementation(AttributeSyntax node)
{
var method = ContainingSymbol as MethodSymbol;
if ((object)method == null) return false;
var impl = method.IsPartialImplementation() ? method : method.PartialImplementationPart;
if ((object)impl == null) return false;
var paramList =
node // AttributeSyntax
.Parent // AttributeListSyntax
.Parent // ParameterSyntax
.Parent as ParameterListSyntax; // ParameterListSyntax
if (paramList == null) return false;
var methDecl = paramList.Parent as MethodDeclarationSyntax;
if (methDecl == null) return false;
foreach (var r in impl.DeclaringSyntaxReferences)
{
if (r.GetSyntax() == methDecl) return true;
}
return false;
}
private void ValidateCallerLineNumberAttribute(AttributeSyntax node, BindingDiagnosticBag diagnostics)
{
CSharpCompilation compilation = this.DeclaringCompilation;
var useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(diagnostics, ContainingAssembly);
if (!IsValidCallerInfoContext(node))
{
// CS4024: The CallerLineNumberAttribute applied to parameter '{0}' will have no effect because it applies to a
// member that is used in contexts that do not allow optional arguments
diagnostics.Add(ErrorCode.WRN_CallerLineNumberParamForUnconsumedLocation, node.Name.Location, CSharpSyntaxNode.Identifier.ValueText);
}
else if (!compilation.Conversions.HasCallerLineNumberConversion(TypeWithAnnotations.Type, ref useSiteInfo))
{
// CS4017: CallerLineNumberAttribute cannot be applied because there are no standard conversions from type '{0}' to type '{1}'
TypeSymbol intType = compilation.GetSpecialType(SpecialType.System_Int32);
diagnostics.Add(ErrorCode.ERR_NoConversionForCallerLineNumberParam, node.Name.Location, intType, TypeWithAnnotations.Type);
}
else if (!HasExplicitDefaultValue && !ContainingSymbol.IsPartialImplementation()) // attribute applied to parameter without default
{
// Unconsumed location checks happen first, so we require a default value.
// CS4020: The CallerLineNumberAttribute may only be applied to parameters with default values
diagnostics.Add(ErrorCode.ERR_BadCallerLineNumberParamWithoutDefaultValue, node.Name.Location);
}
diagnostics.Add(node.Name.Location, useSiteInfo);
}
private void ValidateCallerFilePathAttribute(AttributeSyntax node, BindingDiagnosticBag diagnostics)
{
CSharpCompilation compilation = this.DeclaringCompilation;
var useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(diagnostics, ContainingAssembly);
if (!IsValidCallerInfoContext(node))
{
// CS4025: The CallerFilePathAttribute applied to parameter '{0}' will have no effect because it applies to a
// member that is used in contexts that do not allow optional arguments
diagnostics.Add(ErrorCode.WRN_CallerFilePathParamForUnconsumedLocation, node.Name.Location, CSharpSyntaxNode.Identifier.ValueText);
}
else if (!compilation.Conversions.HasCallerInfoStringConversion(TypeWithAnnotations.Type, ref useSiteInfo))
{
// CS4018: CallerFilePathAttribute cannot be applied because there are no standard conversions from type '{0}' to type '{1}'
TypeSymbol stringType = compilation.GetSpecialType(SpecialType.System_String);
diagnostics.Add(ErrorCode.ERR_NoConversionForCallerFilePathParam, node.Name.Location, stringType, TypeWithAnnotations.Type);
}
else if (!HasExplicitDefaultValue && !ContainingSymbol.IsPartialImplementation()) // attribute applied to parameter without default
{
// Unconsumed location checks happen first, so we require a default value.