-
Notifications
You must be signed in to change notification settings - Fork 4k
/
DecisionDagBuilder.cs
2487 lines (2276 loc) · 127 KB
/
DecisionDagBuilder.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.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Collections;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// <para>
/// A utility class for making a decision dag (directed acyclic graph) for a pattern-matching construct.
/// A decision dag is represented by
/// the class <see cref="BoundDecisionDag"/> and is a representation of a finite state automaton that performs a
/// sequence of binary tests. Each node is represented by a <see cref="BoundDecisionDagNode"/>. There are four
/// kind of nodes: <see cref="BoundTestDecisionDagNode"/> performs one of the binary tests;
/// <see cref="BoundEvaluationDecisionDagNode"/> simply performs some computation and stores it in one or more
/// temporary variables for use in subsequent nodes (think of it as a node with a single successor);
/// <see cref="BoundWhenDecisionDagNode"/> represents the test performed by evaluating the expression of the
/// when-clause of a switch case; and <see cref="BoundLeafDecisionDagNode"/> represents a leaf node when we
/// have finally determined exactly which case matches. Each test processes a single input, and there are
/// four kinds:<see cref="BoundDagExplicitNullTest"/> tests a value for null; <see cref="BoundDagNonNullTest"/>
/// tests that a value is not null; <see cref="BoundDagTypeTest"/> checks if the value is of a given type;
/// and <see cref="BoundDagValueTest"/> checks if the value is equal to a given constant. Of the evaluations,
/// there are <see cref="BoundDagDeconstructEvaluation"/> which represents an invocation of a type's
/// "Deconstruct" method; <see cref="BoundDagFieldEvaluation"/> reads a field; <see cref="BoundDagPropertyEvaluation"/>
/// reads a property; and <see cref="BoundDagTypeEvaluation"/> converts a value from one type to another (which
/// is performed only after testing that the value is of that type).
/// </para>
/// <para>
/// In order to build this automaton, we start (in <see cref="MakeBoundDecisionDag"/>) by computing a description of
/// the initial state in a <see cref="DagState"/>, and then for each such state description we decide what the test
/// or evaluation will be at that state, and compute the successor state descriptions. A state description
/// represented by a <see cref="DagState"/> is a collection of partially matched cases represented by <see
/// cref="StateForCase"/>. When we have computed <see cref="DagState"/> descriptions for all of the states, we
/// create a new <see cref="BoundDecisionDagNode"/> for each of them, containing the state transitions (including
/// the test to perform at each node and the successor nodes) but not the state descriptions. A <see
/// cref="BoundDecisionDag"/> containing this set of nodes becomes part of the bound nodes (e.g. in <see
/// cref="BoundSwitchStatement"/> and <see cref="BoundUnconvertedSwitchExpression"/>) and is used for semantic
/// analysis and lowering.
/// </para>
/// </summary>
internal sealed partial class DecisionDagBuilder
{
private static readonly ObjectPool<PooledDictionary<DagState, DagState>> s_uniqueStatePool =
PooledDictionary<DagState, DagState>.CreatePool(DagStateEquivalence.Instance);
private readonly CSharpCompilation _compilation;
private readonly Conversions _conversions;
private readonly BindingDiagnosticBag _diagnostics;
private readonly LabelSymbol _defaultLabel;
/// <summary>
/// We might need to build a dedicated dag for lowering during which we
/// avoid synthesizing tests to relate alternative indexers. This won't
/// affect code semantics but it results in a better code generation.
/// </summary>
private readonly bool _forLowering;
private DecisionDagBuilder(CSharpCompilation compilation, LabelSymbol defaultLabel, bool forLowering, BindingDiagnosticBag diagnostics)
{
this._compilation = compilation;
this._conversions = compilation.Conversions;
_diagnostics = diagnostics;
_defaultLabel = defaultLabel;
_forLowering = forLowering;
}
/// <summary>
/// Create a decision dag for a switch statement.
/// </summary>
public static BoundDecisionDag CreateDecisionDagForSwitchStatement(
CSharpCompilation compilation,
SyntaxNode syntax,
BoundExpression switchGoverningExpression,
ImmutableArray<BoundSwitchSection> switchSections,
LabelSymbol defaultLabel,
BindingDiagnosticBag diagnostics,
bool forLowering = false)
{
var builder = new DecisionDagBuilder(compilation, defaultLabel, forLowering, diagnostics);
return builder.CreateDecisionDagForSwitchStatement(syntax, switchGoverningExpression, switchSections);
}
/// <summary>
/// Create a decision dag for a switch expression.
/// </summary>
public static BoundDecisionDag CreateDecisionDagForSwitchExpression(
CSharpCompilation compilation,
SyntaxNode syntax,
BoundExpression switchExpressionInput,
ImmutableArray<BoundSwitchExpressionArm> switchArms,
LabelSymbol defaultLabel,
BindingDiagnosticBag diagnostics,
bool forLowering = false)
{
var builder = new DecisionDagBuilder(compilation, defaultLabel, forLowering, diagnostics);
return builder.CreateDecisionDagForSwitchExpression(syntax, switchExpressionInput, switchArms);
}
/// <summary>
/// Translate the pattern of an is-pattern expression.
/// </summary>
public static BoundDecisionDag CreateDecisionDagForIsPattern(
CSharpCompilation compilation,
SyntaxNode syntax,
BoundExpression inputExpression,
BoundPattern pattern,
LabelSymbol whenTrueLabel,
LabelSymbol whenFalseLabel,
BindingDiagnosticBag diagnostics,
bool forLowering = false)
{
var builder = new DecisionDagBuilder(compilation, defaultLabel: whenFalseLabel, forLowering, diagnostics);
return builder.CreateDecisionDagForIsPattern(syntax, inputExpression, pattern, whenTrueLabel);
}
private BoundDecisionDag CreateDecisionDagForIsPattern(
SyntaxNode syntax,
BoundExpression inputExpression,
BoundPattern pattern,
LabelSymbol whenTrueLabel)
{
var rootIdentifier = BoundDagTemp.ForOriginalInput(inputExpression);
using var builder = TemporaryArray<StateForCase>.Empty;
builder.Add(MakeTestsForPattern(index: 1, pattern.Syntax, rootIdentifier, pattern, whenClause: null, whenTrueLabel));
return MakeBoundDecisionDag(syntax, ref builder.AsRef());
}
private BoundDecisionDag CreateDecisionDagForSwitchStatement(
SyntaxNode syntax,
BoundExpression switchGoverningExpression,
ImmutableArray<BoundSwitchSection> switchSections)
{
var rootIdentifier = BoundDagTemp.ForOriginalInput(switchGoverningExpression);
int i = 0;
using var builder = TemporaryArray<StateForCase>.GetInstance(switchSections.Length);
foreach (BoundSwitchSection section in switchSections)
{
foreach (BoundSwitchLabel label in section.SwitchLabels)
{
if (label.Syntax.Kind() != SyntaxKind.DefaultSwitchLabel)
{
builder.Add(MakeTestsForPattern(++i, label.Syntax, rootIdentifier, label.Pattern, label.WhenClause, label.Label));
}
}
}
return MakeBoundDecisionDag(syntax, ref builder.AsRef());
}
/// <summary>
/// Used to create a decision dag for a switch expression.
/// </summary>
private BoundDecisionDag CreateDecisionDagForSwitchExpression(
SyntaxNode syntax,
BoundExpression switchExpressionInput,
ImmutableArray<BoundSwitchExpressionArm> switchArms)
{
var rootIdentifier = BoundDagTemp.ForOriginalInput(switchExpressionInput);
int i = 0;
using var builder = TemporaryArray<StateForCase>.GetInstance(switchArms.Length);
foreach (BoundSwitchExpressionArm arm in switchArms)
builder.Add(MakeTestsForPattern(++i, arm.Syntax, rootIdentifier, arm.Pattern, arm.WhenClause, arm.Label));
return MakeBoundDecisionDag(syntax, ref builder.AsRef());
}
/// <summary>
/// Compute the set of remaining tests for a pattern.
/// </summary>
private StateForCase MakeTestsForPattern(
int index,
SyntaxNode syntax,
BoundDagTemp input,
BoundPattern pattern,
BoundExpression? whenClause,
LabelSymbol label)
{
Tests tests = MakeAndSimplifyTestsAndBindings(input, pattern, out ImmutableArray<BoundPatternBinding> bindings);
return new StateForCase(index, syntax, tests, bindings, whenClause, label);
}
private Tests MakeAndSimplifyTestsAndBindings(
BoundDagTemp input,
BoundPattern pattern,
out ImmutableArray<BoundPatternBinding> bindings)
{
var bindingsBuilder = ArrayBuilder<BoundPatternBinding>.GetInstance();
Tests tests = MakeTestsAndBindings(input, pattern, bindingsBuilder);
tests = SimplifyTestsAndBindings(tests, bindingsBuilder);
bindings = bindingsBuilder.ToImmutableAndFree();
return tests;
}
private static Tests SimplifyTestsAndBindings(
Tests tests,
ArrayBuilder<BoundPatternBinding> bindingsBuilder)
{
// Now simplify the tests and bindings. We don't need anything in tests that does not
// contribute to the result. This will, for example, permit us to match `(2, 3) is (2, _)` without
// fetching `Item2` from the input.
var usedValues = PooledHashSet<BoundDagEvaluation>.GetInstance();
foreach (BoundPatternBinding binding in bindingsBuilder)
{
BoundDagTemp temp = binding.TempContainingValue;
if (temp.Source is { })
{
usedValues.Add(temp.Source);
}
}
var result = scanAndSimplify(tests);
usedValues.Free();
return result;
Tests scanAndSimplify(Tests tests)
{
switch (tests)
{
case Tests.SequenceTests seq:
var testSequence = seq.RemainingTests;
var length = testSequence.Length;
var newSequence = ArrayBuilder<Tests>.GetInstance(length);
newSequence.AddRange(testSequence);
for (int i = length - 1; i >= 0; i--)
{
newSequence[i] = scanAndSimplify(newSequence[i]);
}
return seq.Update(newSequence);
case Tests.True _:
case Tests.False _:
return tests;
case Tests.One(BoundDagEvaluation e):
if (usedValues.Contains(e))
{
if (e.Input.Source is { })
usedValues.Add(e.Input.Source);
return tests;
}
else
{
return Tests.True.Instance;
}
case Tests.One(BoundDagTest d):
if (d.Input.Source is { })
usedValues.Add(d.Input.Source);
return tests;
case Tests.Not n:
return Tests.Not.Create(scanAndSimplify(n.Negated));
default:
throw ExceptionUtilities.UnexpectedValue(tests);
}
}
}
private Tests MakeTestsAndBindings(
BoundDagTemp input,
BoundPattern pattern,
ArrayBuilder<BoundPatternBinding> bindings)
{
return MakeTestsAndBindings(input, pattern, out _, bindings);
}
/// <summary>
/// Make the tests and variable bindings for the given pattern with the given input. The pattern's
/// "output" value is placed in <paramref name="output"/>. The output is defined as the input
/// narrowed according to the pattern's *narrowed type*; see https://github.com/dotnet/csharplang/issues/2850.
/// </summary>
private Tests MakeTestsAndBindings(
BoundDagTemp input,
BoundPattern pattern,
out BoundDagTemp output,
ArrayBuilder<BoundPatternBinding> bindings)
{
Debug.Assert(pattern.HasErrors || pattern.InputType.Equals(input.Type, TypeCompareKind.AllIgnoreOptions) || pattern.InputType.IsErrorType());
switch (pattern)
{
case BoundDeclarationPattern declaration:
return MakeTestsAndBindingsForDeclarationPattern(input, declaration, out output, bindings);
case BoundConstantPattern constant:
return MakeTestsForConstantPattern(input, constant, out output);
case BoundDiscardPattern:
case BoundSlicePattern:
output = input;
return Tests.True.Instance;
case BoundListPattern list:
return MakeTestsAndBindingsForListPattern(input, list, out output, bindings);
case BoundRecursivePattern recursive:
return MakeTestsAndBindingsForRecursivePattern(input, recursive, out output, bindings);
case BoundITuplePattern iTuple:
return MakeTestsAndBindingsForITuplePattern(input, iTuple, out output, bindings);
case BoundTypePattern type:
return MakeTestsForTypePattern(input, type, out output);
case BoundRelationalPattern rel:
return MakeTestsAndBindingsForRelationalPattern(input, rel, out output);
case BoundNegatedPattern neg:
output = input;
return MakeTestsAndBindingsForNegatedPattern(input, neg, bindings);
case BoundBinaryPattern bin:
return MakeTestsAndBindingsForBinaryPattern(input, bin, out output, bindings);
default:
throw ExceptionUtilities.UnexpectedValue(pattern.Kind);
}
}
private Tests MakeTestsAndBindingsForITuplePattern(
BoundDagTemp input,
BoundITuplePattern pattern,
out BoundDagTemp output,
ArrayBuilder<BoundPatternBinding> bindings)
{
var syntax = pattern.Syntax;
var patternLength = pattern.Subpatterns.Length;
var objectType = this._compilation.GetSpecialType(SpecialType.System_Object);
var getLengthProperty = (PropertySymbol)pattern.GetLengthMethod.AssociatedSymbol;
RoslynDebug.Assert(getLengthProperty.Type.SpecialType == SpecialType.System_Int32);
var getItemProperty = (PropertySymbol)pattern.GetItemMethod.AssociatedSymbol;
var iTupleType = getLengthProperty.ContainingType;
RoslynDebug.Assert(iTupleType.Name == "ITuple");
var tests = ArrayBuilder<Tests>.GetInstance(4 + patternLength * 2);
tests.Add(new Tests.One(new BoundDagTypeTest(syntax, iTupleType, input)));
var valueAsITupleEvaluation = new BoundDagTypeEvaluation(syntax, iTupleType, input);
tests.Add(new Tests.One(valueAsITupleEvaluation));
var valueAsITuple = new BoundDagTemp(syntax, iTupleType, valueAsITupleEvaluation);
output = valueAsITuple;
var lengthEvaluation = new BoundDagPropertyEvaluation(syntax, getLengthProperty, isLengthOrCount: true, OriginalInput(valueAsITuple, getLengthProperty));
tests.Add(new Tests.One(lengthEvaluation));
var lengthTemp = new BoundDagTemp(syntax, this._compilation.GetSpecialType(SpecialType.System_Int32), lengthEvaluation);
tests.Add(new Tests.One(new BoundDagValueTest(syntax, ConstantValue.Create(patternLength), lengthTemp)));
var getItemPropertyInput = OriginalInput(valueAsITuple, getItemProperty);
for (int i = 0; i < patternLength; i++)
{
var indexEvaluation = new BoundDagIndexEvaluation(syntax, getItemProperty, i, getItemPropertyInput);
tests.Add(new Tests.One(indexEvaluation));
var indexTemp = new BoundDagTemp(syntax, objectType, indexEvaluation);
tests.Add(MakeTestsAndBindings(indexTemp, pattern.Subpatterns[i].Pattern, bindings));
}
return Tests.AndSequence.Create(tests);
}
/// <summary>
/// Get the earliest input of which the symbol is a member.
/// A BoundDagTypeEvaluation doesn't change the underlying object being pointed to.
/// So two evaluations act on the same input so long as they have the same original input.
/// We use this method to compute the original input for an evaluation.
/// </summary>
private BoundDagTemp OriginalInput(BoundDagTemp input, Symbol symbol)
{
while (input.Source is BoundDagTypeEvaluation source && isDerivedType(source.Input.Type, symbol.ContainingType))
{
input = source.Input;
}
return input;
bool isDerivedType(TypeSymbol possibleDerived, TypeSymbol possibleBase)
{
var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded;
return this._conversions.HasIdentityOrImplicitReferenceConversion(possibleDerived, possibleBase, ref discardedUseSiteInfo);
}
}
private static BoundDagTemp OriginalInput(BoundDagTemp input)
{
// Type evaluations do not change identity
while (input.Source is BoundDagTypeEvaluation source)
{
Debug.Assert(input.Index == 0);
input = source.Input;
}
return input;
}
private Tests MakeTestsAndBindingsForDeclarationPattern(
BoundDagTemp input,
BoundDeclarationPattern declaration,
out BoundDagTemp output,
ArrayBuilder<BoundPatternBinding> bindings)
{
TypeSymbol? type = declaration.DeclaredType?.Type;
var tests = ArrayBuilder<Tests>.GetInstance(1);
// Add a null and type test if needed.
if (!declaration.IsVar)
input = MakeConvertToType(input, declaration.Syntax, type!, isExplicitTest: false, tests);
BoundExpression? variableAccess = declaration.VariableAccess;
if (variableAccess is { })
{
Debug.Assert(variableAccess.Type!.Equals(input.Type, TypeCompareKind.AllIgnoreOptions) || variableAccess.Type.IsErrorType());
bindings.Add(new BoundPatternBinding(variableAccess, input));
}
else
{
RoslynDebug.Assert(declaration.Variable == null);
}
output = input;
return Tests.AndSequence.Create(tests);
}
private Tests MakeTestsForTypePattern(
BoundDagTemp input,
BoundTypePattern typePattern,
out BoundDagTemp output)
{
TypeSymbol type = typePattern.DeclaredType.Type;
var tests = ArrayBuilder<Tests>.GetInstance(4);
output = MakeConvertToType(input: input, syntax: typePattern.Syntax, type: type, isExplicitTest: typePattern.IsExplicitNotNullTest, tests: tests);
return Tests.AndSequence.Create(tests);
}
private static void MakeCheckNotNull(
BoundDagTemp input,
SyntaxNode syntax,
bool isExplicitTest,
ArrayBuilder<Tests> tests)
{
// Add a null test if needed
if (input.Type.CanContainNull() &&
// The slice value is assumed to be never null
input.Source is not BoundDagSliceEvaluation)
{
tests.Add(new Tests.One(new BoundDagNonNullTest(syntax, isExplicitTest, input)));
}
}
/// <summary>
/// Generate a not-null check and a type check.
/// </summary>
private BoundDagTemp MakeConvertToType(
BoundDagTemp input,
SyntaxNode syntax,
TypeSymbol type,
bool isExplicitTest,
ArrayBuilder<Tests> tests)
{
MakeCheckNotNull(input, syntax, isExplicitTest, tests);
if (!input.Type.Equals(type, TypeCompareKind.AllIgnoreOptions))
{
TypeSymbol inputType = input.Type.StrippedType(); // since a null check has already been done
var useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(_diagnostics, _compilation.Assembly);
Conversion conversion = _conversions.ClassifyBuiltInConversion(inputType, type, isChecked: false, ref useSiteInfo);
Debug.Assert(!conversion.IsUserDefined);
_diagnostics.Add(syntax, useSiteInfo);
if (input.Type.IsDynamic() ? type.SpecialType == SpecialType.System_Object : conversion.IsImplicit)
{
// type test not needed, only the type cast
}
else
{
// both type test and cast needed
tests.Add(new Tests.One(new BoundDagTypeTest(syntax, type, input)));
}
var evaluation = new BoundDagTypeEvaluation(syntax, type, input);
input = new BoundDagTemp(syntax, type, evaluation);
tests.Add(new Tests.One(evaluation));
}
return input;
}
private Tests MakeTestsForConstantPattern(
BoundDagTemp input,
BoundConstantPattern constant,
out BoundDagTemp output)
{
if (constant.ConstantValue == ConstantValue.Null)
{
output = input;
return new Tests.One(new BoundDagExplicitNullTest(constant.Syntax, input));
}
else if (constant.ConstantValue.IsString && input.Type.IsSpanOrReadOnlySpanChar())
{
output = input;
return new Tests.One(new BoundDagValueTest(constant.Syntax, constant.ConstantValue, input));
}
else
{
var tests = ArrayBuilder<Tests>.GetInstance(2);
Debug.Assert(constant.Value.Type is not null || constant.HasErrors);
output = input = constant.Value.Type is { } type ? MakeConvertToType(input, constant.Syntax, type, isExplicitTest: false, tests) : input;
if (ValueSetFactory.ForInput(input)?.Related(BinaryOperatorKind.Equal, constant.ConstantValue).IsEmpty == true)
{
// This could only happen for a length input where the permitted value domain (>=0) is a strict subset of possible values for the type (int)
Debug.Assert(input.Source is BoundDagPropertyEvaluation { IsLengthOrCount: true });
tests.Add(Tests.False.Instance);
}
else
{
tests.Add(new Tests.One(new BoundDagValueTest(constant.Syntax, constant.ConstantValue, input)));
}
return Tests.AndSequence.Create(tests);
}
}
private Tests MakeTestsAndBindingsForRecursivePattern(
BoundDagTemp input,
BoundRecursivePattern recursive,
out BoundDagTemp output,
ArrayBuilder<BoundPatternBinding> bindings)
{
RoslynDebug.Assert(input.Type.IsErrorType() || recursive.HasErrors || recursive.InputType.IsErrorType() || input.Type.Equals(recursive.InputType, TypeCompareKind.AllIgnoreOptions));
var inputType = recursive.DeclaredType?.Type ?? input.Type.StrippedType();
var tests = ArrayBuilder<Tests>.GetInstance(5);
output = input = MakeConvertToType(input, recursive.Syntax, inputType, isExplicitTest: recursive.IsExplicitNotNullTest, tests);
if (!recursive.Deconstruction.IsDefault)
{
// we have a "deconstruction" form, which is either an invocation of a Deconstruct method, or a disassembly of a tuple
if (recursive.DeconstructMethod != null)
{
MethodSymbol method = recursive.DeconstructMethod;
var evaluation = new BoundDagDeconstructEvaluation(recursive.Syntax, method, OriginalInput(input, method));
tests.Add(new Tests.One(evaluation));
int extensionExtra = method.IsStatic ? 1 : 0;
int count = Math.Min(method.ParameterCount - extensionExtra, recursive.Deconstruction.Length);
for (int i = 0; i < count; i++)
{
BoundPattern pattern = recursive.Deconstruction[i].Pattern;
SyntaxNode syntax = pattern.Syntax;
var element = new BoundDagTemp(syntax, method.Parameters[i + extensionExtra].Type, evaluation, i);
tests.Add(MakeTestsAndBindings(element, pattern, bindings));
}
}
else if (Binder.IsZeroElementTupleType(inputType))
{
// Work around https://github.com/dotnet/roslyn/issues/20648: The compiler's internal APIs such as `declType.IsTupleType`
// do not correctly treat the non-generic struct `System.ValueTuple` as a tuple type. We explicitly perform the tests
// required to identify it. When that bug is fixed we should be able to remove this if statement.
// nothing to do, as there are no tests for the zero elements of this tuple
}
else if (inputType.IsTupleType)
{
ImmutableArray<FieldSymbol> elements = inputType.TupleElements;
ImmutableArray<TypeWithAnnotations> elementTypes = inputType.TupleElementTypesWithAnnotations;
int count = Math.Min(elementTypes.Length, recursive.Deconstruction.Length);
for (int i = 0; i < count; i++)
{
BoundPattern pattern = recursive.Deconstruction[i].Pattern;
SyntaxNode syntax = pattern.Syntax;
FieldSymbol field = elements[i];
var evaluation = new BoundDagFieldEvaluation(syntax, field, OriginalInput(input, field)); // fetch the ItemN field
tests.Add(new Tests.One(evaluation));
var element = new BoundDagTemp(syntax, field.Type, evaluation);
tests.Add(MakeTestsAndBindings(element, pattern, bindings));
}
}
else
{
// This occurs in error cases.
RoslynDebug.Assert(recursive.HasAnyErrors);
// To prevent this pattern from subsuming other patterns and triggering a cascaded diagnostic, we add a test that will fail.
tests.Add(new Tests.One(new BoundDagTypeTest(recursive.Syntax, ErrorType(), input, hasErrors: true)));
}
}
if (!recursive.Properties.IsDefault)
{
// we have a "property" form
foreach (var subpattern in recursive.Properties)
{
BoundPattern pattern = subpattern.Pattern;
BoundDagTemp currentInput = input;
if (!tryMakeTestsForSubpatternMember(subpattern.Member, ref currentInput, subpattern.IsLengthOrCount))
{
Debug.Assert(recursive.HasAnyErrors);
tests.Add(new Tests.One(new BoundDagTypeTest(recursive.Syntax, ErrorType(), input, hasErrors: true)));
}
else
{
tests.Add(MakeTestsAndBindings(currentInput, pattern, bindings));
}
}
}
if (recursive.VariableAccess != null)
{
// we have a "variable" declaration
bindings.Add(new BoundPatternBinding(recursive.VariableAccess, input));
}
return Tests.AndSequence.Create(tests);
bool tryMakeTestsForSubpatternMember([NotNullWhen(true)] BoundPropertySubpatternMember? member, ref BoundDagTemp input, bool isLengthOrCount)
{
if (member is null)
return false;
// int doesn't have a property, so isLengthOrCount could never be true
if (tryMakeTestsForSubpatternMember(member.Receiver, ref input, isLengthOrCount: false))
{
// If this is not the first member, add null test, unwrap nullables, and continue.
input = MakeConvertToType(input, member.Syntax, member.Receiver.Type.StrippedType(), isExplicitTest: false, tests);
}
BoundDagEvaluation evaluation;
switch (member.Symbol)
{
case PropertySymbol property:
evaluation = new BoundDagPropertyEvaluation(member.Syntax, property, isLengthOrCount, OriginalInput(input, property));
break;
case FieldSymbol field:
evaluation = new BoundDagFieldEvaluation(member.Syntax, field, OriginalInput(input, field));
break;
default:
return false;
}
tests.Add(new Tests.One(evaluation));
input = new BoundDagTemp(member.Syntax, member.Type, evaluation);
return true;
}
}
private Tests MakeTestsAndBindingsForNegatedPattern(BoundDagTemp input, BoundNegatedPattern neg, ArrayBuilder<BoundPatternBinding> bindings)
{
var tests = MakeTestsAndBindings(input, neg.Negated, bindings);
return Tests.Not.Create(tests);
}
private Tests MakeTestsAndBindingsForBinaryPattern(
BoundDagTemp input,
BoundBinaryPattern bin,
out BoundDagTemp output,
ArrayBuilder<BoundPatternBinding> bindings)
{
var builder = ArrayBuilder<Tests>.GetInstance(2);
if (bin.Disjunction)
{
builder.Add(MakeTestsAndBindings(input, bin.Left, bindings));
builder.Add(MakeTestsAndBindings(input, bin.Right, bindings));
var result = Tests.OrSequence.Create(builder);
if (bin.InputType.Equals(bin.NarrowedType))
{
output = input;
return result;
}
else
{
builder = ArrayBuilder<Tests>.GetInstance(2);
builder.Add(result);
output = MakeConvertToType(input: input, syntax: bin.Syntax, type: bin.NarrowedType, isExplicitTest: false, tests: builder);
return Tests.AndSequence.Create(builder);
}
}
else
{
builder.Add(MakeTestsAndBindings(input, bin.Left, out var leftOutput, bindings));
builder.Add(MakeTestsAndBindings(leftOutput, bin.Right, out var rightOutput, bindings));
output = rightOutput;
Debug.Assert(bin.HasErrors || output.Type.Equals(bin.NarrowedType, TypeCompareKind.AllIgnoreOptions));
return Tests.AndSequence.Create(builder);
}
}
private Tests MakeTestsAndBindingsForRelationalPattern(
BoundDagTemp input,
BoundRelationalPattern rel,
out BoundDagTemp output)
{
var type = rel.Value.Type ?? input.Type;
Debug.Assert(type is { });
// check if the test is always true or always false
var tests = ArrayBuilder<Tests>.GetInstance(2);
output = MakeConvertToType(input, rel.Syntax, type, isExplicitTest: false, tests);
var fac = ValueSetFactory.ForInput(output);
var values = fac?.Related(rel.Relation.Operator(), rel.ConstantValue);
if (values?.IsEmpty == true)
{
tests.Add(Tests.False.Instance);
}
else if (values?.Complement().IsEmpty != true)
{
tests.Add(new Tests.One(new BoundDagRelationalTest(rel.Syntax, rel.Relation, rel.ConstantValue, output, rel.HasErrors)));
}
return Tests.AndSequence.Create(tests);
}
private TypeSymbol ErrorType(string name = "")
{
return new ExtendedErrorTypeSymbol(this._compilation, name, arity: 0, errorInfo: null, unreported: false);
}
/// <summary>
/// Compute and translate the decision dag, given a description of its initial state and a default
/// decision when no decision appears to match. This implementation is nonrecursive to avoid
/// overflowing the compiler's evaluation stack when compiling a large switch statement.
/// </summary>
private BoundDecisionDag MakeBoundDecisionDag(SyntaxNode syntax, ref TemporaryArray<StateForCase> cases)
{
// A mapping used to make each DagState unique (i.e. to de-dup identical states).
PooledDictionary<DagState, DagState> uniqueState = s_uniqueStatePool.Allocate();
// Build the state machine underlying the decision dag
DecisionDag decisionDag = MakeDecisionDag(ref cases, uniqueState);
// Note: It is useful for debugging the dag state table construction to set a breakpoint
// here and view `decisionDag.Dump()`.
;
// Compute the bound decision dag corresponding to each node of decisionDag, and store
// it in node.Dag.
var defaultDecision = new BoundLeafDecisionDagNode(syntax, _defaultLabel);
ComputeBoundDecisionDagNodes(decisionDag, defaultDecision);
var rootDecisionDagNode = decisionDag.RootNode.Dag;
RoslynDebug.Assert(rootDecisionDagNode != null);
var boundDecisionDag = new BoundDecisionDag(rootDecisionDagNode.Syntax, rootDecisionDagNode);
// Now go and clean up all the dag states we created
foreach (var kvp in uniqueState)
{
Debug.Assert(kvp.Key == kvp.Value);
kvp.Key.ClearAndFree();
}
uniqueState.Free();
#if DEBUG
// Note that this uses the custom equality in `BoundDagEvaluation`
// to make "equivalent" evaluation nodes share the same ID.
var nextTempNumber = 0;
var tempIdentifierMap = PooledDictionary<BoundDagEvaluation, int>.GetInstance();
var sortedBoundDagNodes = boundDecisionDag.TopologicallySortedNodes;
for (int i = 0; i < sortedBoundDagNodes.Length; i++)
{
var node = sortedBoundDagNodes[i];
node.Id = i;
switch (node)
{
case BoundEvaluationDecisionDagNode { Evaluation: { Id: -1 } evaluation }:
evaluation.Id = tempIdentifier(evaluation);
// Note that "equivalent" evaluations may be different object instances.
// Therefore we have to dig into the Input.Source of evaluations and tests to set their IDs.
if (evaluation.Input.Source is { Id: -1 } source)
{
source.Id = tempIdentifier(source);
}
break;
case BoundTestDecisionDagNode { Test: var test }:
if (test.Input.Source is { Id: -1 } testSource)
{
testSource.Id = tempIdentifier(testSource);
}
break;
}
}
tempIdentifierMap.Free();
int tempIdentifier(BoundDagEvaluation e)
{
return tempIdentifierMap.TryGetValue(e, out int value)
? value
: tempIdentifierMap[e] = ++nextTempNumber;
}
#endif
return boundDecisionDag;
}
/// <summary>
/// Make a <see cref="DecisionDag"/> (state machine) starting with the given set of cases in the root node,
/// and return the node for the root.
/// </summary>
private DecisionDag MakeDecisionDag(
ref TemporaryArray<StateForCase> casesForRootNode,
Dictionary<DagState, DagState> uniqueState)
{
// A work list of DagStates whose successors need to be computed. In practice (measured in roslyn and in
// tests, >75% of the time this worklist never goes past 4 items, so a TemporaryArray is a good choice here
// to keep everything on the stack.
using var workList = TemporaryArray<DagState>.Empty;
// We "intern" the states, so that we only have a single object representing one
// semantic state. Because the decision automaton may contain states that have more than one
// predecessor, we want to represent each such state as a reference-unique object
// so that it is processed only once. This object identity uniqueness will be important later when we
// start mutating the DagState nodes to compute successors and BoundDecisionDagNodes
// for each one. That is why we have to use an equivalence relation in the dictionary `uniqueState`.
DagState uniquifyState(FrozenArrayBuilder<StateForCase> cases, ImmutableDictionary<BoundDagTemp, IValueSet> remainingValues)
{
var state = DagState.GetInstance(cases, remainingValues);
if (uniqueState.TryGetValue(state, out DagState? existingState))
{
// We found an existing state that matches. Return the state we just created back to the pool and
// use the existing one instead. Null out the 'state' local so that any attempts to use it will
// fail fast.
state.ClearAndFree();
state = null;
// Update its set of possible remaining values of each temp by taking the union of the sets on each
// incoming edge.
var newRemainingValues = ImmutableDictionary.CreateBuilder<BoundDagTemp, IValueSet>();
foreach (var (dagTemp, valuesForTemp) in remainingValues)
{
// If one incoming edge does not have a set of possible values for the temp,
// that means the temp can take on any value of its type.
if (existingState.RemainingValues.TryGetValue(dagTemp, out var existingValuesForTemp))
{
var newExistingValuesForTemp = existingValuesForTemp.Union(valuesForTemp);
newRemainingValues.Add(dagTemp, newExistingValuesForTemp);
}
}
if (existingState.RemainingValues.Count != newRemainingValues.Count ||
!existingState.RemainingValues.All(kv => newRemainingValues.TryGetValue(kv.Key, out IValueSet? values) && kv.Value.Equals(values)))
{
existingState.UpdateRemainingValues(newRemainingValues.ToImmutable());
if (!workList.Contains(existingState))
workList.Add(existingState);
}
return existingState;
}
else
{
// When we add a new unique state, we add it to a work list so that we
// will process it to compute its successors.
uniqueState.Add(state, state);
workList.Add(state);
return state;
}
}
// Simplify the initial state based on impossible or earlier matched cases
var rewrittenCases = ArrayBuilder<StateForCase>.GetInstance(casesForRootNode.Count);
foreach (var state in casesForRootNode)
{
var rewrittenCase = state.RewriteNestedLengthTests();
if (rewrittenCase.IsImpossible)
continue;
rewrittenCases.Add(rewrittenCase);
if (rewrittenCase.IsFullyMatched)
break;
}
var initialState = uniquifyState(new
FrozenArrayBuilder<StateForCase>(rewrittenCases),
ImmutableDictionary<BoundDagTemp, IValueSet>.Empty);
// Go through the worklist of DagState nodes for which we have not yet computed
// successor states.
while (workList.Count != 0)
{
DagState state = workList.RemoveLast();
RoslynDebug.Assert(state.SelectedTest == null);
RoslynDebug.Assert(state.TrueBranch == null);
RoslynDebug.Assert(state.FalseBranch == null);
if (state.Cases.Count == 0)
{
// If this state has no more cases that could possibly match, then
// we know there is no case that will match and this node represents a "default"
// decision. We do not need to compute a successor, as it is a leaf node
continue;
}
StateForCase first = state.Cases[0];
Debug.Assert(!first.IsImpossible);
if (first.PatternIsSatisfied)
{
if (first.IsFullyMatched)
{
// The first of the remaining cases has fully matched, as there are no more tests to do.
// The language semantics of the switch statement and switch expression require that we
// execute the first matching case. There is no when clause to evaluate here,
// so this is a leaf node and required no further processing.
}
else
{
// There is a when clause to evaluate.
// In case the when clause fails, we prepare for the remaining cases.
var stateWhenFails = state.Cases.RemoveAt(0);
state.FalseBranch = uniquifyState(stateWhenFails, state.RemainingValues);
}
}
else
{
// Select the next test to do at this state, and compute successor states
switch (state.SelectedTest = state.ComputeSelectedTest())
{
case BoundDagAssignmentEvaluation e when state.RemainingValues.TryGetValue(e.Input, out IValueSet? currentValues):
Debug.Assert(e.Input.IsEquivalentTo(e.Target));
// Update the target temp entry with current values. Note that even though we have determined that the two are the same,
// we don't need to update values for the current input. We will emit another assignment node with this temp as the target
// if apropos, which has the effect of flowing the remaining values from the other test in the analysis of subsequent states.
if (state.RemainingValues.TryGetValue(e.Target, out IValueSet? targetValues))
{
// Take the intersection of entries as we have ruled out any impossible
// values for each alias of an element, and now we're dealiasing them.
currentValues = currentValues.Intersect(targetValues);
}
state.TrueBranch = uniquifyState(RemoveEvaluation(state.Cases, e), state.RemainingValues.SetItem(e.Target, currentValues));
break;
case BoundDagEvaluation e:
state.TrueBranch = uniquifyState(RemoveEvaluation(state.Cases, e), state.RemainingValues);
// An evaluation is considered to always succeed, so there is no false branch
break;
case BoundDagTest d:
bool foundExplicitNullTest = false;
SplitCases(state, d,
out var whenTrueDecisions, out var whenTrueValues,
out var whenFalseDecisions, out var whenFalseValues,
ref foundExplicitNullTest);
state.TrueBranch = uniquifyState(whenTrueDecisions, whenTrueValues);
state.FalseBranch = uniquifyState(whenFalseDecisions, whenFalseValues);
if (foundExplicitNullTest && d is BoundDagNonNullTest { IsExplicitTest: false } t)
{
// Turn an "implicit" non-null test into an explicit one
state.SelectedTest = new BoundDagNonNullTest(t.Syntax, isExplicitTest: true, t.Input, t.HasErrors);
}
break;
case var n:
throw ExceptionUtilities.UnexpectedValue(n.Kind);
}
}
}
return new DecisionDag(initialState);
}
/// <summary>
/// Compute the <see cref="BoundDecisionDag"/> corresponding to each <see cref="DagState"/> of the given <see cref="DecisionDag"/>
/// and store it in <see cref="DagState.Dag"/>.
/// </summary>
private void ComputeBoundDecisionDagNodes(DecisionDag decisionDag, BoundLeafDecisionDagNode defaultDecision)
{
Debug.Assert(_defaultLabel != null);
Debug.Assert(defaultDecision != null);
// Process the states in topological order, leaves first, and assign a BoundDecisionDag to each DagState.
bool wasAcyclic = decisionDag.TryGetTopologicallySortedReachableStates(out ImmutableArray<DagState> sortedStates);
if (!wasAcyclic)
{
// Since we intend the set of DagState nodes to be acyclic by construction, we do not expect
// this to occur. Just in case it does due to bugs, we recover gracefully to avoid crashing the
// compiler in production. If you find that this happens (the assert fails), please modify the
// DagState construction process to avoid creating a cyclic state graph.
Debug.Assert(wasAcyclic, "wasAcyclic"); // force failure in debug builds
// If the dag contains a cycle, return a short-circuit dag instead.
decisionDag.RootNode.Dag = defaultDecision;
return;
}
// We "intern" the dag nodes, so that we only have a single object representing one
// semantic node. We do this because different states may end up mapping to the same
// set of successor states. In this case we merge them when producing the bound state machine.
var uniqueNodes = PooledDictionary<BoundDecisionDagNode, BoundDecisionDagNode>.GetInstance();
BoundDecisionDagNode uniqifyDagNode(BoundDecisionDagNode node) => uniqueNodes.GetOrAdd(node, node);
_ = uniqifyDagNode(defaultDecision);
for (int i = sortedStates.Length - 1; i >= 0; i--)
{
var state = sortedStates[i];
if (state.Cases.Count == 0)
{
state.Dag = defaultDecision;
continue;
}
StateForCase first = state.Cases[0];
RoslynDebug.Assert(!(first.RemainingTests is Tests.False));
if (first.PatternIsSatisfied)
{
if (first.IsFullyMatched)
{
// there is no when clause we need to evaluate
state.Dag = finalState(first.Syntax, first.CaseLabel, first.Bindings);
}
else
{
RoslynDebug.Assert(state.TrueBranch == null);
RoslynDebug.Assert(state.FalseBranch is { });
// The final state here does not need bindings, as they will be performed before evaluating the when clause (see below)
BoundDecisionDagNode whenTrue = finalState(first.Syntax, first.CaseLabel, default);