-
Notifications
You must be signed in to change notification settings - Fork 222
/
CSharpControlFlowGraphBuilder.cs
1398 lines (1101 loc) · 60.3 KB
/
CSharpControlFlowGraphBuilder.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
/*
* SonarAnalyzer for .NET
* Copyright (C) 2015-2023 SonarSource SA
* mailto: contact AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using SonarAnalyzer.CFG.Helpers;
namespace SonarAnalyzer.CFG.Sonar
{
public sealed class CSharpControlFlowGraphBuilder : AbstractControlFlowGraphBuilder
{
private const int SupportedExpressionNodeCountLimit = 500;
private readonly Stack<Block> breakTarget = new Stack<Block>();
private readonly Stack<Block> continueTargets = new Stack<Block>();
private readonly Stack<Dictionary<object, List<JumpBlock>>> switchGotoJumpBlocks = new Stack<Dictionary<object, List<JumpBlock>>>();
private readonly Dictionary<string, List<JumpBlock>> gotoJumpBlocks = new Dictionary<string, List<JumpBlock>>();
private readonly Dictionary<string, JumpBlock> labeledStatements = new Dictionary<string, JumpBlock>();
private static readonly object GotoDefaultEntry = new object();
private static readonly object GotoNullEntry = new object();
public CSharpControlFlowGraphBuilder(SyntaxNode node, SemanticModel semanticModel)
: base(node, semanticModel)
{
}
#region Fix jump statements
protected override void PostProcessGraph()
{
FixJumps(this.gotoJumpBlocks, this.labeledStatements.ToDictionary(e => e.Key, e => (Block)e.Value));
}
private void FixJumps<TLabel>(Dictionary<TLabel, List<JumpBlock>> jumpsToFix,
Dictionary<TLabel, Block> collectedJumpTargets)
{
foreach (var jumpToFix in jumpsToFix)
{
if (!collectedJumpTargets.ContainsKey(jumpToFix.Key))
{
throw new InvalidOperationException("Jump to non-existent location");
}
foreach (var jumpBlock in jumpToFix.Value)
{
reversedBlocks.Remove(jumpBlock.SuccessorBlock);
jumpBlock.SuccessorBlock = collectedJumpTargets[jumpToFix.Key];
}
}
}
#endregion Fix jump statements
#region Top level Build*
protected override Block Build(SyntaxNode node, Block currentBlock)
{
Block block = null;
if (node is StatementSyntax statement)
{
block = BuildStatement(statement, currentBlock);
}
else if (node is ArrowExpressionClauseSyntax arrowExpression)
{
block = BuildExpression(arrowExpression.Expression, currentBlock);
}
else if (node is ExpressionSyntax expression)
{
block = BuildExpression(expression, currentBlock);
}
if (block == null)
{
throw new ArgumentException("Neither a statement, nor an expression", nameof(node));
}
if (node.Parent is ConstructorDeclarationSyntax constructorDeclaration &&
constructorDeclaration.Initializer != null)
{
block = BuildConstructorInitializer(constructorDeclaration.Initializer, block);
}
return block;
}
private Block BuildConstructorInitializer(ConstructorInitializerSyntax initializer, Block currentBlock)
{
currentBlock.ReversedInstructions.Add(initializer);
var arguments = initializer.ArgumentList == null
? Enumerable.Empty<ExpressionSyntax>()
: initializer.ArgumentList.Arguments.Select(a => a.Expression);
return BuildExpressions(arguments, currentBlock);
}
private Block BuildStatement(StatementSyntax statement, Block currentBlock)
{
switch (statement.Kind())
{
case SyntaxKind.Block:
return BuildBlock((BlockSyntax)statement, currentBlock);
case SyntaxKind.ExpressionStatement:
return BuildExpression(((ExpressionStatementSyntax)statement).Expression, currentBlock);
case SyntaxKind.LocalDeclarationStatement:
return BuildVariableDeclaration(((LocalDeclarationStatementSyntax)statement).Declaration,
currentBlock);
case SyntaxKind.IfStatement:
return BuildIfStatement((IfStatementSyntax)statement, currentBlock);
case SyntaxKind.WhileStatement:
return BuildWhileStatement((WhileStatementSyntax)statement, currentBlock);
case SyntaxKind.DoStatement:
return BuildDoStatement((DoStatementSyntax)statement, currentBlock);
case SyntaxKind.ForStatement:
return BuildForStatement((ForStatementSyntax)statement, currentBlock);
case SyntaxKind.ForEachStatement:
return BuildForEachStatement((ForEachStatementSyntax)statement, currentBlock);
case SyntaxKindEx.ForEachVariableStatement:
return BuildForEachVariableStatement((ForEachVariableStatementSyntaxWrapper)statement, currentBlock);
case SyntaxKind.LockStatement:
return BuildLockStatement((LockStatementSyntax)statement, currentBlock);
case SyntaxKind.UsingStatement:
return BuildUsingStatement((UsingStatementSyntax)statement, currentBlock);
case SyntaxKind.FixedStatement:
return BuildFixedStatement((FixedStatementSyntax)statement, currentBlock);
case SyntaxKind.UncheckedStatement:
case SyntaxKind.CheckedStatement:
return BuildCheckedStatement((CheckedStatementSyntax)statement, currentBlock);
case SyntaxKind.UnsafeStatement:
return BuildUnsafeStatement((UnsafeStatementSyntax)statement, currentBlock);
case SyntaxKind.ReturnStatement:
return BuildReturnStatement((ReturnStatementSyntax)statement, currentBlock);
case SyntaxKind.YieldBreakStatement:
return BuildYieldBreakStatement((YieldStatementSyntax)statement, currentBlock);
case SyntaxKind.ThrowStatement:
return BuildThrowStatement((ThrowStatementSyntax)statement, currentBlock);
case SyntaxKind.YieldReturnStatement:
return BuildYieldReturnStatement((YieldStatementSyntax)statement, currentBlock);
case SyntaxKind.EmptyStatement:
return currentBlock;
case SyntaxKind.BreakStatement:
return BuildBreakStatement((BreakStatementSyntax)statement, currentBlock);
case SyntaxKind.ContinueStatement:
return BuildContinueStatement((ContinueStatementSyntax)statement, currentBlock);
case SyntaxKind.SwitchStatement:
return BuildSwitchStatement((SwitchStatementSyntax)statement, currentBlock);
case SyntaxKind.GotoCaseStatement:
return BuildGotoCaseStatement((GotoStatementSyntax)statement, currentBlock);
case SyntaxKind.GotoDefaultStatement:
return BuildGotoDefaultStatement((GotoStatementSyntax)statement, currentBlock);
case SyntaxKind.GotoStatement:
return BuildGotoStatement((GotoStatementSyntax)statement, currentBlock);
case SyntaxKind.LabeledStatement:
return BuildLabeledStatement((LabeledStatementSyntax)statement, currentBlock);
case SyntaxKind.TryStatement:
return BuildTryStatement((TryStatementSyntax)statement, currentBlock);
case SyntaxKindEx.LocalFunctionStatement:
return currentBlock;
case SyntaxKind.GlobalStatement:
throw new NotSupportedException($"{statement.Kind()}");
default:
throw new NotSupportedException($"{statement.Kind()}");
}
}
private Block BuildExpression(ExpressionSyntax expression, Block currentBlock)
{
if (expression == null)
{
return currentBlock;
}
if (IsTooComplex(expression))
{
throw new NotSupportedException("Too complex expression");
}
switch (expression.Kind())
{
case SyntaxKind.SimpleAssignmentExpression:
return BuildSimpleAssignmentExpression((AssignmentExpressionSyntax)expression, currentBlock);
case SyntaxKindEx.CoalesceAssignmentExpression:
return BuildCoalesceAssignmentExpression((AssignmentExpressionSyntax)expression, currentBlock);
case SyntaxKind.OrAssignmentExpression:
case SyntaxKind.AndAssignmentExpression:
case SyntaxKind.ExclusiveOrAssignmentExpression:
case SyntaxKind.SubtractAssignmentExpression:
case SyntaxKind.AddAssignmentExpression:
case SyntaxKind.DivideAssignmentExpression:
case SyntaxKind.MultiplyAssignmentExpression:
case SyntaxKind.ModuloAssignmentExpression:
case SyntaxKind.LeftShiftAssignmentExpression:
case SyntaxKind.RightShiftAssignmentExpression:
return BuildAssignmentExpression((AssignmentExpressionSyntax)expression, currentBlock);
case SyntaxKind.LessThanExpression:
case SyntaxKind.LessThanOrEqualExpression:
case SyntaxKind.GreaterThanExpression:
case SyntaxKind.GreaterThanOrEqualExpression:
case SyntaxKind.EqualsExpression:
case SyntaxKind.NotEqualsExpression:
case SyntaxKind.BitwiseOrExpression:
case SyntaxKind.BitwiseAndExpression:
case SyntaxKind.ExclusiveOrExpression:
case SyntaxKind.SubtractExpression:
case SyntaxKind.AddExpression:
case SyntaxKind.DivideExpression:
case SyntaxKind.MultiplyExpression:
case SyntaxKind.ModuloExpression:
case SyntaxKind.LeftShiftExpression:
case SyntaxKind.RightShiftExpression:
return BuildBinaryExpression((BinaryExpressionSyntax)expression, currentBlock);
case SyntaxKind.LogicalNotExpression:
case SyntaxKind.BitwiseNotExpression:
case SyntaxKind.UnaryMinusExpression:
case SyntaxKind.UnaryPlusExpression:
case SyntaxKind.PreIncrementExpression:
case SyntaxKind.PreDecrementExpression:
case SyntaxKind.AddressOfExpression:
case SyntaxKind.PointerIndirectionExpression:
{
var parent = (PrefixUnaryExpressionSyntax)expression;
return BuildSimpleNestedExpression(parent, currentBlock, parent.Operand);
}
case SyntaxKind.PostIncrementExpression:
case SyntaxKind.PostDecrementExpression:
{
var parent = (PostfixUnaryExpressionSyntax)expression;
return BuildSimpleNestedExpression(parent, currentBlock, parent.Operand);
}
case SyntaxKind.IdentifierName:
case SyntaxKind.GenericName:
case SyntaxKind.AliasQualifiedName:
case SyntaxKind.QualifiedName:
case SyntaxKind.CharacterLiteralExpression:
case SyntaxKind.StringLiteralExpression:
case SyntaxKind.NumericLiteralExpression:
case SyntaxKind.TrueLiteralExpression:
case SyntaxKind.FalseLiteralExpression:
case SyntaxKind.NullLiteralExpression:
case SyntaxKind.ThisExpression:
case SyntaxKind.BaseExpression:
case SyntaxKind.DefaultExpression:
case SyntaxKindEx.DefaultLiteralExpression:
case SyntaxKind.SizeOfExpression:
case SyntaxKind.TypeOfExpression:
case SyntaxKind.PredefinedType:
case SyntaxKind.NullableType:
case SyntaxKind.OmittedArraySizeExpression:
case SyntaxKind.AnonymousMethodExpression:
case SyntaxKind.ParenthesizedLambdaExpression:
case SyntaxKind.SimpleLambdaExpression:
case SyntaxKind.QueryExpression:
case SyntaxKind.ArgListExpression:
case SyntaxKindEx.RangeExpression:
case SyntaxKindEx.IndexExpression:
currentBlock.ReversedInstructions.Add(expression);
return currentBlock;
case SyntaxKind.PointerType:
return BuildExpression(((PointerTypeSyntax)expression).ElementType, currentBlock);
case SyntaxKind.ParenthesizedExpression:
return BuildExpression(((ParenthesizedExpressionSyntax)expression).Expression, currentBlock);
case SyntaxKind.AwaitExpression:
{
var parent = (AwaitExpressionSyntax)expression;
return BuildSimpleNestedExpression(parent, currentBlock, parent.Expression);
}
case SyntaxKind.CheckedExpression:
case SyntaxKind.UncheckedExpression:
{
var parent = (CheckedExpressionSyntax)expression;
return BuildSimpleNestedExpression(parent, currentBlock, parent.Expression);
}
case SyntaxKind.AsExpression:
case SyntaxKind.IsExpression:
{
var parent = (BinaryExpressionSyntax)expression;
return BuildSimpleNestedExpression(parent, currentBlock, parent.Left);
}
case SyntaxKind.CastExpression:
{
var parent = (CastExpressionSyntax)expression;
return BuildSimpleNestedExpression(parent, currentBlock, parent.Expression);
}
case SyntaxKind.InterpolatedStringExpression:
return BuildInterpolatedStringExpression((InterpolatedStringExpressionSyntax)expression,
currentBlock);
case SyntaxKind.InvocationExpression:
return BuildInvocationExpression((InvocationExpressionSyntax)expression, currentBlock);
case SyntaxKind.AnonymousObjectCreationExpression:
return BuildAnonymousObjectCreationExpression((AnonymousObjectCreationExpressionSyntax)expression,
currentBlock);
case SyntaxKind.ObjectCreationExpression:
return BuildObjectCreationExpression((ObjectCreationExpressionSyntax)expression, currentBlock);
case SyntaxKind.ElementAccessExpression:
return BuildElementAccessExpression((ElementAccessExpressionSyntax)expression, currentBlock);
case SyntaxKind.ImplicitElementAccess:
return BuildImplicitElementAccessExpression((ImplicitElementAccessSyntax)expression, currentBlock);
case SyntaxKind.LogicalAndExpression:
return BuildLogicalAndExpression((BinaryExpressionSyntax)expression, currentBlock);
case SyntaxKind.LogicalOrExpression:
return BuildLogicalOrExpression((BinaryExpressionSyntax)expression, currentBlock);
case SyntaxKind.ArrayCreationExpression:
return BuildArrayCreationExpression((ArrayCreationExpressionSyntax)expression, currentBlock);
case SyntaxKind.ImplicitArrayCreationExpression:
{
var parent = (ImplicitArrayCreationExpressionSyntax)expression;
var initializerBlock = BuildExpression(parent.Initializer, currentBlock);
initializerBlock.ReversedInstructions.Add(parent);
return initializerBlock;
}
case SyntaxKind.StackAllocArrayCreationExpression:
{
var parent = (StackAllocArrayCreationExpressionSyntax)expression;
return BuildSimpleNestedExpression(parent, currentBlock, parent.Type, parent.Initializer());
}
case SyntaxKindEx.ImplicitStackAllocArrayCreationExpression:
{
var parent = (ImplicitStackAllocArrayCreationExpressionSyntaxWrapper)expression;
return BuildSimpleNestedExpression(parent, currentBlock, parent.Initializer);
}
case SyntaxKind.SimpleMemberAccessExpression:
case SyntaxKind.PointerMemberAccessExpression:
{
var parent = (MemberAccessExpressionSyntax)expression;
return BuildSimpleNestedExpression(parent, currentBlock, parent.Expression);
}
case SyntaxKind.ObjectInitializerExpression:
case SyntaxKind.ArrayInitializerExpression:
case SyntaxKind.CollectionInitializerExpression:
case SyntaxKind.ComplexElementInitializerExpression:
{
var parent = (InitializerExpressionSyntax)expression;
return BuildSimpleNestedExpression(parent, currentBlock, parent.Expressions);
}
case SyntaxKind.MakeRefExpression:
{
var parent = (MakeRefExpressionSyntax)expression;
return BuildSimpleNestedExpression(parent, currentBlock, parent.Expression);
}
case SyntaxKind.RefTypeExpression:
{
var parent = (RefTypeExpressionSyntax)expression;
return BuildSimpleNestedExpression(parent, currentBlock, parent.Expression);
}
case SyntaxKind.RefValueExpression:
{
var parent = (RefValueExpressionSyntax)expression;
return BuildSimpleNestedExpression(parent, currentBlock, parent.Expression);
}
case SyntaxKind.ArrayType:
return BuildArrayType((ArrayTypeSyntax)expression, currentBlock);
case SyntaxKind.CoalesceExpression:
return BuildCoalesceExpression((BinaryExpressionSyntax)expression, currentBlock);
case SyntaxKind.ConditionalExpression:
return BuildConditionalExpression((ConditionalExpressionSyntax)expression, currentBlock);
// these look strange in the CFG:
case SyntaxKind.ConditionalAccessExpression:
return BuildConditionalAccessExpression((ConditionalAccessExpressionSyntax)expression, currentBlock);
case SyntaxKind.MemberBindingExpression:
{
var parent = (MemberBindingExpressionSyntax)expression;
return BuildSimpleNestedExpression(parent, currentBlock, parent.Name);
}
case SyntaxKind.ElementBindingExpression:
{
var parent = (ElementBindingExpressionSyntax)expression;
return BuildSimpleNestedExpression(parent, currentBlock,
parent.ArgumentList?.Arguments.Select(a => a.Expression));
}
case SyntaxKindEx.IsPatternExpression:
var isPatternExpression = (IsPatternExpressionSyntaxWrapper)expression;
currentBlock = BuildIsPatternExpression(isPatternExpression, currentBlock);
return BuildExpression(isPatternExpression.Expression, currentBlock);
case SyntaxKindEx.ThrowExpression:
var throwExpression = (ThrowExpressionSyntaxWrapper)expression;
return BuildJumpToExitStatement(throwExpression, currentBlock, throwExpression.Expression);
case SyntaxKindEx.DeclarationExpression:
currentBlock.ReversedInstructions.Add(expression);
return currentBlock;
case SyntaxKindEx.RefExpression:
{
var parent = (RefExpressionSyntaxWrapper)expression;
return BuildSimpleNestedExpression(parent, currentBlock, parent.Expression);
}
case SyntaxKindEx.SwitchExpression:
return BuildSwitchExpression((SwitchExpressionSyntaxWrapper)expression, currentBlock);
case SyntaxKindEx.TupleExpression:
return BuildTupleExpression((TupleExpressionSyntaxWrapper)expression, currentBlock);
default:
throw new NotSupportedException($"{expression.Kind()}");
}
}
private static bool IsTooComplex(SyntaxNode node)
{
var count = 0; // Limit descending for performance reasons
// The evaluation doesn't descend into the content of lambda expression. We need to tolerate these for Razor Layout pages.
return node.DescendantNodes(x => ++count < SupportedExpressionNodeCountLimit && !IsLambda(x)).Count() >= SupportedExpressionNodeCountLimit;
static bool IsLambda(SyntaxNode node) =>
node is LambdaExpressionSyntax;
}
#endregion Top level Build*
#region Build*
#region Build statements
private Block BuildStatements(IEnumerable<StatementSyntax> statements, Block currentBlock)
{
foreach (var statement in statements.Reverse())
{
currentBlock = BuildStatement(statement, currentBlock);
}
return currentBlock;
}
private Block BuildExpressions(IEnumerable<ExpressionSyntax> expressions, Block currentBlock)
{
foreach (var expression in expressions.Reverse())
{
currentBlock = BuildExpression(expression, currentBlock);
}
return currentBlock;
}
#region Build label, goto, goto case, goto default
private Block BuildLabeledStatement(LabeledStatementSyntax labeledStatement, Block currentBlock)
{
var statementBlock = BuildStatement(labeledStatement.Statement, currentBlock);
var jumpBlock = CreateJumpBlock(labeledStatement, statementBlock);
this.labeledStatements[labeledStatement.Identifier.ValueText] = jumpBlock;
return CreateBlock(jumpBlock);
}
private Block BuildTryStatement(TryStatementSyntax tryStatement, Block currentBlock)
{
// successor - either finally of next block after try statement
var catchSuccessor = currentBlock;
var hasFinally = tryStatement.Finally?.Block != null;
if (hasFinally)
{
var finallySuccessors = new List<Block>();
finallySuccessors.Add(CreateBlock(catchSuccessor));
finallySuccessors.Add(CreateBlock(this.exitTarget.Peek()));
// Create a finally block that can either go to try-finally successor (happy path) or exit target (exceptional path)
catchSuccessor = BuildBlock(tryStatement.Finally.Block, CreateBranchBlock(tryStatement.Finally, finallySuccessors));
// This finally block becomes current exit target stack in case we have a return inside the try/catch block
this.exitTarget.Push(catchSuccessor);
}
var catchBlocks = tryStatement.Catches
.Reverse()
.Select(catchClause =>
{
Block catchBlock = BuildBlock(catchClause.Block, CreateBlock(catchSuccessor));
if (catchClause.Filter?.FilterExpression != null)
{
catchBlock = BuildExpression(catchClause.Filter.FilterExpression,
CreateBinaryBranchBlock(catchClause.Filter, catchBlock, catchSuccessor));
}
return catchBlock;
})
.ToList();
// If there is a catch with no Exception filter or equivalent we don't want to
// join the tryStatement start/end blocks with the exit block because all
// exceptions will be caught before going to finally
var areAllExceptionsCaught = tryStatement.Catches.Any(CSharpSyntaxHelper.IsCatchingAllExceptions);
// try end
var tryEndStatementConnections = catchBlocks.ToList();
tryEndStatementConnections.Add(catchSuccessor); // happy path, no exceptions thrown
if (!areAllExceptionsCaught) // unexpected exception thrown, go to exit (through finally if present)
{
tryEndStatementConnections.Add(this.exitTarget.Peek());
}
Block tryBody;
if (tryStatement.Block.Statements.Any(s => s.IsKind(SyntaxKind.ReturnStatement)))
{
// there is a return inside the `try`, thus a JumpBlock directly to the finally or exit will be created
var returnBlock = BuildBlock(tryStatement.Block, catchSuccessor);
var connections = new List<Block>();
connections.Add(returnBlock);
// if an exception is thrown, it will reach the `catch` blocks
connections.AddRange(catchBlocks);
tryBody = CreateBranchBlock(tryStatement, connections);
}
else
{
tryBody = BuildBlock(tryStatement.Block, CreateBranchBlock(tryStatement,
tryEndStatementConnections.Distinct()));
}
// if this try is inside another try, the `beforeTryBlock` must have edges to the outer catch & finally blocks
Block beforeTryBlock;
if (currentBlock is BranchBlock possibleOuterTry &&
possibleOuterTry.BranchingNode.IsKind(SyntaxKind.TryStatement))
{
var beforeTryConnections = possibleOuterTry.SuccessorBlocks.ToList();
beforeTryConnections.Add(tryBody);
beforeTryBlock = CreateBranchBlock(tryStatement, beforeTryConnections.Distinct());
}
else
{
// otherwise, what happens before the try is not handled by any catch or finally
beforeTryBlock = CreateBlock(tryBody);
}
if (hasFinally)
{
this.exitTarget.Pop();
}
return beforeTryBlock;
}
private Block BuildGotoDefaultStatement(GotoStatementSyntax statement, Block currentBlock)
{
if (this.switchGotoJumpBlocks.Count == 0)
{
throw new InvalidOperationException("goto default; outside a switch");
}
var jumpBlock = CreateJumpBlock(statement, CreateTemporaryBlock(), currentBlock);
var currentJumpBlocks = this.switchGotoJumpBlocks.Peek();
if (!currentJumpBlocks.ContainsKey(GotoDefaultEntry))
{
currentJumpBlocks.Add(GotoDefaultEntry, new List<JumpBlock>());
}
currentJumpBlocks[GotoDefaultEntry].Add(jumpBlock);
return jumpBlock;
}
private Block BuildGotoCaseStatement(GotoStatementSyntax statement, Block currentBlock)
{
if (this.switchGotoJumpBlocks.Count == 0)
{
throw new InvalidOperationException("goto case; outside a switch");
}
var jumpBlock = CreateJumpBlock(statement, CreateTemporaryBlock(), currentBlock);
var currentJumpBlocks = this.switchGotoJumpBlocks.Peek();
var indexer = GetCaseIndexer(statement.Expression);
if (!currentJumpBlocks.ContainsKey(indexer))
{
currentJumpBlocks.Add(indexer, new List<JumpBlock>());
}
currentJumpBlocks[indexer].Add(jumpBlock);
return jumpBlock;
}
private Block BuildGotoStatement(GotoStatementSyntax statement, Block currentBlock)
{
var jumpBlock = CreateJumpBlock(statement, CreateTemporaryBlock(), currentBlock);
if (!(statement.Expression is IdentifierNameSyntax identifier))
{
throw new InvalidOperationException("goto with no identifier");
}
if (!this.gotoJumpBlocks.ContainsKey(identifier.Identifier.ValueText))
{
this.gotoJumpBlocks.Add(identifier.Identifier.ValueText, new List<JumpBlock>());
}
this.gotoJumpBlocks[identifier.Identifier.ValueText].Add(jumpBlock);
return jumpBlock;
}
#endregion Build label, goto, goto case, goto default
#region Build switch
private Block BuildSwitchStatement(SwitchStatementSyntax switchStatement, Block currentBlock)
{
var caseBlocksByValue = new Dictionary<object, Block>();
this.breakTarget.Push(currentBlock);
this.switchGotoJumpBlocks.Push(new Dictionary<object, List<JumpBlock>>());
// Default section is always evaluated last, we are handling it first because
// the CFG is built in reverse order
var defaultSection = switchStatement.Sections.FirstOrDefault(ContainsDefaultLabel);
var defaultSectionBlock = currentBlock;
if (defaultSection != null)
{
defaultSectionBlock = BuildStatements(defaultSection.Statements, CreateBlock(currentBlock));
caseBlocksByValue[GotoDefaultEntry] = defaultSectionBlock; // All "goto default;" will jump to this block
}
var currentSectionBlock = defaultSectionBlock;
foreach (var section in switchStatement.Sections.Reverse())
{
Block sectionBlock;
if (defaultSection != null && section == defaultSection)
{
// Skip the default section if it contains a single default label; we already handled it
if (section.Labels.Count == 1)
{
continue;
}
sectionBlock = defaultSectionBlock;
}
else
{
sectionBlock = BuildStatements(section.Statements, CreateBlock(currentBlock));
}
foreach (var label in section.Labels.Reverse())
{
// Handle C#7 pattern matching case Block
if (CasePatternSwitchLabelSyntaxWrapper.IsInstance(label))
{
var casePatternSwitchLabel = (CasePatternSwitchLabelSyntaxWrapper)label;
currentSectionBlock = BuildCasePattern(casePatternSwitchLabel,
trueSuccessor: sectionBlock, falseSuccessor: currentSectionBlock);
}
else if (label is CaseSwitchLabelSyntax simpleCaseLabel)
{
currentSectionBlock = BuildExpression(switchStatement.Expression, CreateBinaryBranchBlock(simpleCaseLabel,
sectionBlock, currentSectionBlock));
var key = GetCaseIndexer(simpleCaseLabel.Value);
caseBlocksByValue[key] = sectionBlock;
}
}
}
this.breakTarget.Pop();
var gotosToFix = this.switchGotoJumpBlocks.Pop();
FixJumps(gotosToFix, caseBlocksByValue);
var switchBlock = CreateBranchBlock(switchStatement, new[] { currentSectionBlock });
return BuildExpression(switchStatement.Expression, switchBlock);
bool ContainsDefaultLabel(SwitchSectionSyntax s) =>
s.Labels.Any(l => l.IsKind(SyntaxKind.DefaultSwitchLabel));
}
private Block BuildSwitchExpression(SwitchExpressionSyntaxWrapper switchExpressionSyntax, Block currentBlock)
{
var currentArmBlock = currentBlock;
for (var index = switchExpressionSyntax.Arms.Count - 1; index >= 0; index--)
{
var arm = switchExpressionSyntax.Arms[index];
var isLast = index == switchExpressionSyntax.Arms.Count - 1;
var armBlock = BuildExpression(arm.Expression, CreateBlock(currentBlock));
currentArmBlock = BuildArmBranch(arm, armBlock, currentArmBlock, isLast);
if (!isLast)
{
currentArmBlock = BuildExpression(switchExpressionSyntax.GoverningExpression, currentArmBlock);
}
}
return currentArmBlock;
}
private Block BuildArmBranch(SwitchExpressionArmSyntaxWrapper switchExpressionArmSyntax, Block trueSuccessor, Block falseSuccessor, bool isLast)
{
var newTrueSuccessor = CreateWhenCloseNewTrueSuccessor(switchExpressionArmSyntax.WhenClause, trueSuccessor, falseSuccessor);
var currentBlock = CreateCurrentBlock(switchExpressionArmSyntax, newTrueSuccessor, falseSuccessor, isLast);
currentBlock = BuildPatternExpression(switchExpressionArmSyntax.Pattern, currentBlock);
return currentBlock;
}
private Block CreateCurrentBlock(SwitchExpressionArmSyntaxWrapper switchExpressionArmSyntax, Block trueSuccessor, Block falseSuccessor, bool isLast) =>
isLast
? trueSuccessor
: (Block)CreateBinaryBranchBlock(switchExpressionArmSyntax, trueSuccessor, falseSuccessor);
private Block BuildCasePattern(CasePatternSwitchLabelSyntaxWrapper casePatternSwitchLabel,
Block trueSuccessor, Block falseSuccessor)
{
var newTrueSuccessor = CreateWhenCloseNewTrueSuccessor(casePatternSwitchLabel.WhenClause, trueSuccessor, falseSuccessor);
var currentBlock = CreateBinaryBranchBlock(casePatternSwitchLabel, newTrueSuccessor, falseSuccessor);
currentBlock.ReversedInstructions.Add(casePatternSwitchLabel.Pattern);
return currentBlock;
}
private Block CreateWhenCloseNewTrueSuccessor(WhenClauseSyntaxWrapper whenClauseSyntax, Block trueSuccessor, Block falseSuccessor) =>
whenClauseSyntax.SyntaxNode != null
? BuildCondition(whenClauseSyntax.Condition, trueSuccessor, falseSuccessor)
: trueSuccessor;
private object GetCaseIndexer(ExpressionSyntax expression)
{
var constValue = semanticModel.GetConstantValue(expression);
if (!constValue.HasValue)
{
throw new InvalidOperationException("Expression has no constant value");
}
var indexer = constValue.Value;
if (indexer == null)
{
indexer = GotoNullEntry;
}
return indexer;
}
#endregion Build switch
#region Build jumps: break, continue, return, throw, yield break
private Block BuildBreakStatement(BreakStatementSyntax breakStatement, Block currentBlock)
{
if (this.breakTarget.Count == 0)
{
throw new InvalidOperationException("break; outside a loop");
}
var target = this.breakTarget.Peek();
if (currentBlock is BranchBlock possibleTryBlock &&
possibleTryBlock.BranchingNode.IsKind(SyntaxKind.TryStatement))
{
var newSuccessors = possibleTryBlock.SuccessorBlocks.ToList();
newSuccessors.Add(target);
var branchBlock = CreateBranchBlock(possibleTryBlock.BranchingNode, newSuccessors);
return branchBlock;
}
return CreateJumpBlock(breakStatement, target, currentBlock);
}
private Block BuildContinueStatement(ContinueStatementSyntax continueStatement, Block currentBlock)
{
if (this.continueTargets.Count == 0)
{
throw new InvalidOperationException("continue; outside a loop");
}
var target = this.continueTargets.Peek();
return CreateJumpBlock(continueStatement, target, currentBlock);
}
private Block BuildReturnStatement(ReturnStatementSyntax returnStatement, Block currentBlock)
{
return BuildJumpToExitStatement(returnStatement, currentBlock, returnStatement.Expression);
}
private Block BuildThrowStatement(ThrowStatementSyntax throwStatement, Block currentBlock)
{
return BuildJumpToExitStatement(throwStatement, currentBlock, throwStatement.Expression);
}
private Block BuildYieldBreakStatement(YieldStatementSyntax yieldBreakStatement, Block currentBlock)
{
return BuildJumpToExitStatement(yieldBreakStatement, currentBlock);
}
private Block BuildYieldReturnStatement(YieldStatementSyntax yieldReturnStatement, Block currentBlock)
{
return BuildExpression(yieldReturnStatement.Expression, CreateJumpBlock(yieldReturnStatement, currentBlock, currentBlock));
}
private Block BuildJumpToExitStatement(StatementSyntax statement, Block currentBlock, ExpressionSyntax expression = null)
{
// When there is a `throw` inside a `try`, and there is a `catch` with a filter,
// the `throw` block should point to both the `catch` and the `exit` blocks.
if (currentBlock.SuccessorBlocks.Any(b => b is BinaryBranchBlock x && x.BranchingNode.IsKind(SyntaxKind.CatchFilterClause)) &&
currentBlock.SuccessorBlocks.Contains(this.exitTarget.Peek()))
{
return BuildExpression(expression, currentBlock);
}
return BuildExpression(expression, CreateJumpBlock(statement, this.exitTarget.Peek(), currentBlock));
}
private Block BuildJumpToExitStatement(ExpressionSyntax expression, Block currentBlock, ExpressionSyntax innerExpression)
{
return BuildExpression(innerExpression, CreateJumpBlock(expression, this.exitTarget.Peek(), currentBlock));
}
#endregion Build jumps: break, continue, return, throw, yield break
#region Build lock, using, fixed, unsafe checked statements
private Block BuildLockStatement(LockStatementSyntax lockStatement, Block currentBlock)
{
var lockStatementBlock = BuildStatement(lockStatement.Statement, CreateBlock(currentBlock));
return BuildExpression(lockStatement.Expression, CreateLockBlock(lockStatement, lockStatementBlock));
}
private Block BuildUsingStatement(UsingStatementSyntax usingStatement, Block currentBlock)
{
var usingStatementBlock = BuildStatement(usingStatement.Statement, CreateUsingFinalizerBlock(usingStatement, currentBlock));
var usingBlock = CreateJumpBlock(usingStatement, usingStatementBlock);
return usingStatement.Expression != null
? BuildExpression(usingStatement.Expression, usingBlock)
: BuildVariableDeclaration(usingStatement.Declaration, usingBlock);
}
private Block BuildFixedStatement(FixedStatementSyntax fixedStatement, Block currentBlock)
{
var fixedStatementBlock = BuildStatement(fixedStatement.Statement, CreateBlock(currentBlock));
return BuildVariableDeclaration(fixedStatement.Declaration, CreateJumpBlock(fixedStatement, fixedStatementBlock));
}
private Block BuildUnsafeStatement(UnsafeStatementSyntax statement, Block currentBlock)
{
var unsafeStatement = BuildStatement(statement.Block, CreateBlock(currentBlock));
return CreateJumpBlock(statement, unsafeStatement);
}
private Block BuildCheckedStatement(CheckedStatementSyntax statement, Block currentBlock)
{
var statementBlock = BuildStatement(statement.Block, CreateBlock(currentBlock));
return CreateJumpBlock(statement, statementBlock);
}
#endregion Build lock, using, fixed, unsafe checked statements
#region Build loops - do, for, foreach, while
private Block BuildDoStatement(DoStatementSyntax doStatement, Block currentBlock)
{
//// while (A) { B; }
var conditionBlockTemp = CreateTemporaryBlock();
var conditionBlock = BuildCondition(doStatement.Condition, conditionBlockTemp, currentBlock); // A
this.breakTarget.Push(currentBlock);
this.continueTargets.Push(conditionBlock);
var loopBody = BuildStatement(doStatement.Statement, CreateBlock(conditionBlock)); // B
conditionBlockTemp.SuccessorBlock = loopBody;
this.breakTarget.Pop();
this.continueTargets.Pop();
return CreateBlock(loopBody);
}
private Block BuildForStatement(ForStatementSyntax forStatement, Block currentBlock)
{
//// for (A; B; C) { D; }
var tempLoopBlock = CreateTemporaryBlock();
var incrementorBlock = BuildExpressions(forStatement.Incrementors, CreateBlock(tempLoopBlock)); // C
this.breakTarget.Push(currentBlock);
this.continueTargets.Push(incrementorBlock);
var forBlock = BuildStatement(forStatement.Statement, CreateBlock(incrementorBlock)); // D
this.breakTarget.Pop();
this.continueTargets.Pop();
var conditionBlock = BuildExpression(forStatement.Condition,
CreateBinaryBranchBlock(forStatement, forBlock, currentBlock)); // B
tempLoopBlock.SuccessorBlock = conditionBlock;
Block forInitializer = AddBlock(new ForInitializerBlock(forStatement, conditionBlock)); // A
if (forStatement.Declaration != null)
{
forInitializer = BuildVariableDeclaration(forStatement.Declaration, forInitializer);
}
forInitializer = BuildExpressions(forStatement.Initializers, forInitializer);
return forInitializer;
}
private Block BuildForEachVariableStatement(ForEachVariableStatementSyntaxWrapper foreachStatement, Block currentBlock)
=> BuildForEachStatement(foreachStatement, foreachStatement.Statement, foreachStatement.Expression, currentBlock);
private Block BuildForEachStatement(ForEachStatementSyntax foreachStatement, Block currentBlock)
=> BuildForEachStatement(foreachStatement, foreachStatement.Statement, foreachStatement.Expression, currentBlock);
private Block BuildForEachStatement(StatementSyntax foreachStatement, StatementSyntax foreachBodyStatement, ExpressionSyntax foreachExpression, Block currentBlock)
{
var temp = CreateTemporaryBlock();
this.breakTarget.Push(currentBlock);