-
Notifications
You must be signed in to change notification settings - Fork 516
Expand file tree
/
Copy pathCSharpParser.cs
More file actions
10180 lines (8895 loc) · 380 KB
/
CSharpParser.cs
File metadata and controls
10180 lines (8895 loc) · 380 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2026 the original author or authors.
* <p>
* Licensed under the Moderne Source Available License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* https://docs.moderne.io/licensing/moderne-source-available-license
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using OpenRewrite.Core;
using OpenRewrite.Java;
namespace OpenRewrite.CSharp;
/// <summary>
/// Parses C# source code into an LST using Roslyn.
/// </summary>
public class CSharpParser
{
private bool _charsetBomMarked;
public CompilationUnit Parse(string source, string sourcePath = "source.cs",
SemanticModel? semanticModel = null, bool charsetBomMarked = false)
{
_charsetBomMarked = charsetBomMarked;
var symbols = PreprocessorSourceTransformer.ExtractSymbols(source);
if (symbols.Count == 0)
return ParseSingle(source, sourcePath, semanticModel);
return ParseMulti(source, sourcePath, semanticModel, symbols);
}
/// <summary>
/// Parses source with configuration-derived preprocessor symbol sets.
/// Delegates to Parse which uses full 2^N permutations of file-referenced symbols,
/// ensuring all conditional branches (including #else) are covered.
/// MSBuild config sets alone may not cover all branches — e.g., if all configs
/// define DEBUG, the #else branch would be lost.
/// </summary>
public CompilationUnit ParseWithConfigurations(string source, string sourcePath,
SemanticModel? semanticModel, List<HashSet<string>> configSymbolSets,
bool charsetBomMarked = false)
{
return Parse(source, sourcePath, semanticModel, charsetBomMarked);
}
private CompilationUnit ParseMultiWithSymbolSets(string source, string sourcePath,
SemanticModel? semanticModel, List<HashSet<string>> symbolSets)
{
var directiveLines = PreprocessorSourceTransformer.GetDirectivePositions(source);
// Build mapping from line number to directive index for ghost comment emission
var directiveLineToIndex = new Dictionary<int, int>();
for (int idx = 0; idx < directiveLines.Count; idx++)
directiveLineToIndex[directiveLines[idx].LineNumber] = idx;
// Generate permutations from the provided symbol sets
var permutations = new List<(string CleanSource, HashSet<string> DefinedSymbols)>();
foreach (var symbolSet in symbolSets)
{
var cleanSource = PreprocessorSourceTransformer.Transform(source, symbolSet, directiveLineToIndex);
permutations.Add((cleanSource, symbolSet));
}
// Deduplicate by clean source
permutations = permutations
.GroupBy(p => p.CleanSource)
.Select(g => g.First())
.ToList();
if (permutations.Count <= 1)
{
return ParseSingle(source, sourcePath, semanticModel);
}
PreprocessorSourceTransformer.ComputeActiveBranchIndices(directiveLines, permutations);
var branches = new List<JRightPadded<CompilationUnit>>();
for (int i = 0; i < permutations.Count; i++)
{
var (cleanSource, definedSymbols) = permutations[i];
bool isPrimary = i == 0;
CompilationUnit cu;
if (isPrimary && semanticModel != null)
{
// Preserve parse options from the original tree to avoid "Inconsistent syntax tree features"
var parseOptions = semanticModel.SyntaxTree.Options as CSharpParseOptions;
parseOptions = parseOptions?.WithPreprocessorSymbols(Array.Empty<string>());
var syntaxTree = CSharpSyntaxTree.ParseText(cleanSource, options: parseOptions, path: sourcePath);
var compilation = semanticModel.Compilation.ReplaceSyntaxTree(
semanticModel.SyntaxTree, syntaxTree);
var newSemanticModel = compilation.GetSemanticModel(syntaxTree);
cu = ParseSingle(cleanSource, sourcePath, newSemanticModel);
}
else
{
cu = ParseSingle(cleanSource, sourcePath, null);
}
cu = (CompilationUnit)DirectiveBoundaryInjector.Inject(cu);
cu = cu.WithMarkers(cu.Markers.Add(new ConditionalBranchMarker(Guid.NewGuid(), definedSymbols.ToList())));
branches.Add(new JRightPadded<CompilationUnit>(cu, Space.Empty, Markers.Empty));
}
var directive = new ConditionalDirective(
Guid.NewGuid(),
Space.Empty,
Markers.Empty,
directiveLines,
branches
);
var primaryCu = branches[0].Element;
return new CompilationUnit(
Guid.NewGuid(),
Space.Empty,
Markers.Empty,
primaryCu.SourcePath,
"UTF-8",
_charsetBomMarked,
null,
null,
new List<JRightPadded<Statement>> { new(directive, Space.Empty, Markers.Empty) },
Space.Empty
);
}
private CompilationUnit ParseSingle(string source, string sourcePath, SemanticModel? semanticModel)
{
if (semanticModel != null)
{
var root = semanticModel.SyntaxTree.GetCompilationUnitRoot();
var visitor = new CSharpParserVisitor(source, semanticModel, _charsetBomMarked);
var cu = visitor.VisitCompilationUnit(root);
// Override source path since the semantic model's tree has the absolute path
// from MSBuildWorkspace, but we want the relative path
if (cu.SourcePath != sourcePath)
cu = cu.WithSourcePath(sourcePath);
return cu;
}
else
{
var syntaxTree = CSharpSyntaxTree.ParseText(source, path: sourcePath);
var root = syntaxTree.GetCompilationUnitRoot();
var visitor = new CSharpParserVisitor(source, charsetBomMarked: _charsetBomMarked);
return visitor.VisitCompilationUnit(root);
}
}
private CompilationUnit ParseMulti(string source, string sourcePath,
SemanticModel? semanticModel, HashSet<string> symbols)
{
var directiveLines = PreprocessorSourceTransformer.GetDirectivePositions(source);
// Build mapping from line number to directive index for ghost comment emission
var directiveLineToIndex = new Dictionary<int, int>();
for (int idx = 0; idx < directiveLines.Count; idx++)
directiveLineToIndex[directiveLines[idx].LineNumber] = idx;
var permutations = PreprocessorSourceTransformer.GenerateUniquePermutations(
source, symbols, directiveLineToIndex);
PreprocessorSourceTransformer.ComputeActiveBranchIndices(directiveLines, permutations);
var branches = new List<JRightPadded<CompilationUnit>>();
for (int i = 0; i < permutations.Count; i++)
{
var (cleanSource, definedSymbols) = permutations[i];
bool isPrimary = i == 0;
CompilationUnit cu;
if (isPrimary && semanticModel != null)
{
// Preserve parse options from the original tree to avoid "Inconsistent syntax tree features"
var parseOptions = semanticModel.SyntaxTree.Options as CSharpParseOptions;
parseOptions = parseOptions?.WithPreprocessorSymbols(Array.Empty<string>());
var syntaxTree = CSharpSyntaxTree.ParseText(cleanSource, options: parseOptions, path: sourcePath);
var compilation = semanticModel.Compilation.ReplaceSyntaxTree(
semanticModel.SyntaxTree, syntaxTree);
var newSemanticModel = compilation.GetSemanticModel(syntaxTree);
cu = ParseSingle(cleanSource, sourcePath, newSemanticModel);
}
else
{
cu = ParseSingle(cleanSource, sourcePath, null);
}
// Convert ghost comments in whitespace to DirectiveBoundaryMarker markers
cu = (CompilationUnit)DirectiveBoundaryInjector.Inject(cu);
// Add ConditionalBranchMarker to identify this as a branch
cu = cu.WithMarkers(cu.Markers.Add(new ConditionalBranchMarker(Guid.NewGuid(), definedSymbols.ToList())));
branches.Add(new JRightPadded<CompilationUnit>(cu, Space.Empty, Markers.Empty));
}
var directive = new ConditionalDirective(
Guid.NewGuid(),
Space.Empty,
Markers.Empty,
directiveLines,
branches
);
// Outer shell CompilationUnit wrapping the ConditionalDirective.
// EOF is Space.Empty because the ConditionalDirective printer handles
// everything including the trailing content from branch outputs.
var primaryCu = branches[0].Element;
return new CompilationUnit(
Guid.NewGuid(),
Space.Empty,
Markers.Empty,
primaryCu.SourcePath,
"UTF-8",
_charsetBomMarked,
null,
null,
new List<JRightPadded<Statement>> { new(directive, Space.Empty, Markers.Empty) },
Space.Empty
);
}
}
/// <summary>
/// Converts Roslyn syntax trees to OpenRewrite LST.
/// </summary>
internal class CSharpParserVisitor : CSharpSyntaxVisitor<J>
{
private readonly string _source;
private int _cursor;
private readonly SemanticModel? _semanticModel;
private readonly CSharpTypeMapping? _typeMapping;
private readonly bool _charsetBomMarked;
private readonly Dictionary<string, Space> _spaceCache = new();
/// <summary>
/// Space before a statement-terminating semicolon, set by statement visitors and
/// consumed by block/container parsers into JRightPadded.After.
/// </summary>
private Space _pendingSemicolonSpace = Space.Empty;
public CSharpParserVisitor(string source, SemanticModel? semanticModel = null,
bool charsetBomMarked = false)
{
_source = source;
_cursor = 0;
_semanticModel = semanticModel;
_typeMapping = semanticModel != null ? new CSharpTypeMapping(semanticModel) : null;
_charsetBomMarked = charsetBomMarked;
}
/// <summary>
/// Visits a pattern node, wrapping Statement results (e.g. VariableDeclarations from declaration patterns)
/// in StatementExpression so they can appear in Expression/Pattern contexts.
/// </summary>
private Expression VisitPatternAsExpression(SyntaxNode node)
{
var result = Visit(node);
if (result is Expression expr) return expr;
if (result is Statement stmt)
return new StatementExpression(Guid.NewGuid(), Space.Empty, Markers.Empty, stmt);
throw new InvalidOperationException(
$"Expected Expression or Statement from pattern but got {result?.GetType().Name} " +
$"[node: {node.GetType().Name}, kind: {node.Kind()}, text: {node}]");
}
public override J? Visit(SyntaxNode? node)
{
try
{
return base.Visit(node);
}
catch (InvalidOperationException e) when (e.Message.StartsWith("Expected Expression but got"))
{
var snippet = node?.ToString() ?? "<null>";
if (snippet.Length > 200) snippet = snippet.Substring(0, 200) + "...";
throw new InvalidOperationException(
$"{e.Message} [node: {node?.GetType().Name}, kind: {node?.Kind()}, text: {snippet}]", e);
}
}
public new CompilationUnit VisitCompilationUnit(CompilationUnitSyntax node)
{
var members = new List<JRightPadded<Statement>>();
// Process directives at the very start of the file (before any usings/members)
// These would otherwise be absorbed into the CompilationUnit prefix
var leadingDirectives = ProcessGapDirectives(node.SpanStart);
foreach (var d in leadingDirectives)
members.Add(new JRightPadded<Statement>(d, Space.Empty, Markers.Empty));
// If leading directives were found, don't extract prefix — the trailing
// whitespace after the last directive naturally becomes the next member's prefix
var prefix = leadingDirectives.Count > 0 ? Space.Empty : ExtractPrefix(node);
// Handle extern alias directives — added as members
foreach (var externAlias in node.Externs)
{
var visited = VisitExternAliasDirective(externAlias);
if (visited is Statement stmt)
{
members.Add(PadStatement(stmt));
}
}
// Handle using directives
foreach (var usingDirective in node.Usings)
{
foreach (var d in ProcessGapDirectives(usingDirective.SpanStart))
members.Add(new JRightPadded<Statement>(d, Space.Empty, Markers.Empty));
var visited = VisitUsingDirective(usingDirective);
members.Add(PadStatement(visited));
}
// Handle assembly/module-level attributes — added as members
foreach (var attrList in node.AttributeLists)
{
var visited = VisitAttributeList(attrList);
if (visited is Statement attrStmt)
{
members.Add(PadStatement(attrStmt));
}
}
// Handle top-level statements and type declarations
foreach (var member in node.Members)
{
foreach (var d in ProcessGapDirectives(member.SpanStart))
members.Add(new JRightPadded<Statement>(d, Space.Empty, Markers.Empty));
var visited = Visit(member);
if (visited is Statement stmt)
{
members.Add(PadStatement(stmt));
}
// For file-scoped namespaces, the type declarations are children of the
// namespace node, not of the CompilationUnit. Visit them here so they
// appear as top-level members in the OpenRewrite AST.
if (member is FileScopedNamespaceDeclarationSyntax fsns)
{
foreach (var fsExtern in fsns.Externs)
{
var fsExVisited = VisitExternAliasDirective(fsExtern);
if (fsExVisited is Statement fsExStmt)
{
members.Add(PadStatement(fsExStmt));
}
}
foreach (var fsUsing in fsns.Usings)
{
foreach (var d in ProcessGapDirectives(fsUsing.SpanStart))
members.Add(new JRightPadded<Statement>(d, Space.Empty, Markers.Empty));
var fsUVisited = VisitUsingDirective(fsUsing);
members.Add(PadStatement(fsUVisited));
}
foreach (var nsMember in fsns.Members)
{
foreach (var d in ProcessGapDirectives(nsMember.SpanStart))
members.Add(new JRightPadded<Statement>(d, Space.Empty, Markers.Empty));
var nsVisited = Visit(nsMember);
if (nsVisited is Statement nsStmt)
{
members.Add(PadStatement(nsStmt));
}
}
}
}
// Process trailing directives before EOF
foreach (var d in ProcessGapDirectives(_source.Length))
members.Add(new JRightPadded<Statement>(d, Space.Empty, Markers.Empty));
var eof = ExtractRemaining();
return new CompilationUnit(
Guid.NewGuid(),
prefix,
Markers.Empty,
node.SyntaxTree.FilePath ?? "source.cs",
"UTF-8",
_charsetBomMarked,
null,
null,
members,
eof
);
}
public override J VisitGlobalStatement(GlobalStatementSyntax node)
{
return Visit(node.Statement)!;
}
public new UsingDirective VisitUsingDirective(UsingDirectiveSyntax node)
{
var prefix = ExtractPrefix(node);
// Handle 'global' keyword
bool isGlobal = node.GlobalKeyword.IsKind(SyntaxKind.GlobalKeyword);
Space globalAfter = Space.Empty;
if (isGlobal)
{
_cursor = node.GlobalKeyword.Span.End;
globalAfter = ExtractSpaceBefore(node.UsingKeyword);
}
// Skip 'using' keyword
_cursor = node.UsingKeyword.Span.End;
// Handle 'static' keyword
bool isStatic = node.StaticKeyword.IsKind(SyntaxKind.StaticKeyword);
Space staticBefore = Space.Empty;
if (isStatic)
{
staticBefore = ExtractSpaceBefore(node.StaticKeyword);
_cursor = node.StaticKeyword.Span.End;
}
// Handle 'unsafe' keyword (C# 12+)
bool isUnsafe = node.UnsafeKeyword.IsKind(SyntaxKind.UnsafeKeyword);
Space unsafeBefore = Space.Empty;
if (isUnsafe)
{
unsafeBefore = ExtractSpaceBefore(node.UnsafeKeyword);
_cursor = node.UnsafeKeyword.Span.End;
}
// Handle alias
JRightPadded<Identifier>? alias = null;
if (node.Alias != null)
{
var aliasPrefix = ExtractPrefix(node.Alias.Name);
_cursor = node.Alias.Name.Identifier.Span.End;
var aliasName = new Identifier(
Guid.NewGuid(),
aliasPrefix,
Markers.Empty,
[],
node.Alias.Name.Identifier.Text,
null,
null
);
var aliasAfter = ExtractSpaceBefore(node.Alias.EqualsToken);
_cursor = node.Alias.EqualsToken.Span.End;
alias = new JRightPadded<Identifier>(aliasName, aliasAfter, Markers.Empty);
}
// Parse namespace or type
var namespaceOrType = VisitType(node.NamespaceOrType);
// Capture space before semicolon into _pendingSemicolonSpace
_pendingSemicolonSpace = ExtractSpaceBefore(node.SemicolonToken);
_cursor = node.SemicolonToken.Span.End;
return new UsingDirective(
Guid.NewGuid(),
prefix,
Markers.Empty,
new JRightPadded<bool>(isGlobal, globalAfter, Markers.Empty),
new JLeftPadded<bool>(staticBefore, isStatic),
new JLeftPadded<bool>(unsafeBefore, isUnsafe),
alias,
namespaceOrType!
);
}
public override J VisitFileScopedNamespaceDeclaration(FileScopedNamespaceDeclarationSyntax node)
{
var prefix = ExtractPrefix(node);
// Skip 'namespace' keyword
_cursor = node.NamespaceKeyword.Span.End;
// Parse the namespace name (use VisitType to handle qualified names)
var name = VisitType(node.Name);
if (name is not Expression nameExpr)
{
throw new InvalidOperationException($"Expected Expression for namespace name but got {name?.GetType().Name}");
}
// Capture space before semicolon into _pendingSemicolonSpace
_pendingSemicolonSpace = ExtractSpaceBefore(node.SemicolonToken);
_cursor = node.SemicolonToken.Span.End;
return new Package(
Guid.NewGuid(),
prefix,
Markers.Empty,
nameExpr,
[] // No annotations for C# namespaces
);
}
public override J VisitNamespaceDeclaration(NamespaceDeclarationSyntax node)
{
var prefix = ExtractPrefix(node);
// Skip 'namespace' keyword
_cursor = node.NamespaceKeyword.Span.End;
// Parse the namespace name (use VisitType to handle qualified names)
var name = VisitType(node.Name);
if (name is not Expression nameExpr)
{
throw new InvalidOperationException($"Expected Expression for namespace name but got {name?.GetType().Name}");
}
// Get space before open brace
var nameAfter = ExtractSpaceBefore(node.OpenBraceToken);
_cursor = node.OpenBraceToken.Span.End;
// Parse members (extern aliases, using directives, types, nested namespaces)
var members = new List<JRightPadded<Statement>>();
// Parse extern alias directives within the namespace — added as members
foreach (var externAlias in node.Externs)
{
var visited = VisitExternAliasDirective(externAlias);
if (visited is Statement stmt)
{
members.Add(PadStatement(stmt));
}
}
// Handle using directives within the namespace
foreach (var usingDirective in node.Usings)
{
foreach (var d in ProcessGapDirectives(usingDirective.SpanStart))
members.Add(new JRightPadded<Statement>(d, Space.Empty, Markers.Empty));
var visited = VisitUsingDirective(usingDirective);
members.Add(PadStatement(visited));
}
// Then handle member declarations (types, nested namespaces)
foreach (var member in node.Members)
{
foreach (var d in ProcessGapDirectives(member.SpanStart))
members.Add(new JRightPadded<Statement>(d, Space.Empty, Markers.Empty));
var visited = Visit(member);
if (visited is Statement stmt)
{
members.Add(PadStatement(stmt));
}
}
// Process trailing directives before close brace
foreach (var d in ProcessGapDirectives(node.CloseBraceToken.SpanStart))
members.Add(new JRightPadded<Statement>(d, Space.Empty, Markers.Empty));
// Get space before close brace
var end = ExtractSpaceBefore(node.CloseBraceToken);
_cursor = node.CloseBraceToken.Span.End;
return new NamespaceDeclaration(
Guid.NewGuid(),
prefix,
Markers.Empty,
new JRightPadded<Expression>(nameExpr, nameAfter, Markers.Empty),
members,
end
);
}
public override J VisitBlock(BlockSyntax node)
{
var prefix = ExtractPrefix(node);
// Skip past the open brace
_cursor = node.OpenBraceToken.Span.End;
var statements = new List<JRightPadded<Statement>>();
foreach (var stmt in node.Statements)
{
foreach (var d in ProcessGapDirectives(stmt.SpanStart))
statements.Add(new JRightPadded<Statement>(d, Space.Empty, Markers.Empty));
var visited = Visit(stmt);
if (visited is Statement s)
{
statements.Add(PadStatement(s));
}
}
// Process trailing directives before close brace
foreach (var d in ProcessGapDirectives(node.CloseBraceToken.SpanStart))
statements.Add(new JRightPadded<Statement>(d, Space.Empty, Markers.Empty));
// Extract space before close brace
var end = ExtractSpaceBefore(node.CloseBraceToken);
_cursor = node.CloseBraceToken.Span.End;
return new Block(
Guid.NewGuid(),
prefix,
Markers.Empty,
new JRightPadded<bool>(false, Space.Empty, Markers.Empty),
statements,
end
);
}
public override J VisitClassDeclaration(ClassDeclarationSyntax node)
{
return VisitTypeDeclaration(node);
}
public override J VisitInterfaceDeclaration(InterfaceDeclarationSyntax node)
{
return VisitTypeDeclaration(node);
}
public override J VisitStructDeclaration(StructDeclarationSyntax node)
{
return AddClassDeclMarker(VisitTypeDeclaration(node), new Struct(Guid.NewGuid()));
}
public override J VisitRecordDeclaration(RecordDeclarationSyntax node)
{
var result = VisitTypeDeclaration(node);
// For record struct, add Struct marker (KindType is already Record)
if (node.ClassOrStructKeyword.IsKind(SyntaxKind.StructKeyword))
{
return AddClassDeclMarker(result, new Struct(Guid.NewGuid()));
}
// For "record class" (explicit class keyword), add RecordClass marker
if (node.ClassOrStructKeyword.IsKind(SyntaxKind.ClassKeyword))
{
return AddClassDeclMarker(result, new RecordClass(Guid.NewGuid()));
}
return result;
}
/// <summary>
/// Adds a marker to the ClassDeclaration, handling the case where it may be
/// wrapped in an AnnotatedStatement (when the type has attribute lists).
/// </summary>
private static J AddClassDeclMarker(J result, Marker marker)
{
if (result is AnnotatedStatement annotated)
{
var classDecl = (ClassDeclaration)annotated.Statement;
return annotated.WithStatement(classDecl.WithMarkers(classDecl.Markers.Add(marker)));
}
var cd = (ClassDeclaration)result;
return cd.WithMarkers(cd.Markers.Add(marker));
}
public override J VisitEnumDeclaration(EnumDeclarationSyntax node)
{
var prefix = ExtractPrefix(node);
// Parse attribute lists
var attributeLists = new List<AttributeList>();
foreach (var attrList in node.AttributeLists)
{
attributeLists.Add((AttributeList)Visit(attrList)!);
}
// Parse modifiers
var modifiers = new List<Modifier>();
foreach (var mod in node.Modifiers)
{
var modPrefix = ExtractSpaceBefore(mod);
_cursor = mod.Span.End;
modifiers.Add(CreateModifier(modPrefix, mod));
}
// 'enum' keyword prefix stored as left padding of name
var enumPrefix = ExtractSpaceBefore(node.EnumKeyword);
_cursor = node.EnumKeyword.Span.End;
// Parse the name
var namePrefix = ExtractSpaceBefore(node.Identifier);
_cursor = node.Identifier.Span.End;
var name = new Identifier(
Guid.NewGuid(),
namePrefix,
Markers.Empty,
[],
node.Identifier.Text,
_typeMapping?.ClassType(node),
null
);
// Parse base list (underlying type like : byte)
JLeftPadded<TypeTree>? baseType = null;
if (node.BaseList != null)
{
var colonPrefix = ExtractSpaceBefore(node.BaseList.ColonToken);
_cursor = node.BaseList.ColonToken.Span.End;
if (node.BaseList.Types.Count > 0)
{
var bt = (TypeTree)Visit(node.BaseList.Types[0].Type)!;
baseType = new JLeftPadded<TypeTree>(colonPrefix, bt);
}
}
// Parse members
var membersPrefix = ExtractSpaceBefore(node.OpenBraceToken);
_cursor = node.OpenBraceToken.Span.End;
JContainer<Expression>? members = null;
if (node.Members.Count > 0)
{
var memberList = new List<JRightPadded<Expression>>();
for (int i = 0; i < node.Members.Count; i++)
{
var member = node.Members[i];
var memberJ = (Expression)VisitEnumMemberDeclaration(member);
Space afterSpace;
var markers = Markers.Empty;
if (i < node.Members.Count - 1)
{
// Non-last element: consume separator
var separator = node.Members.GetSeparator(i);
afterSpace = ExtractSpaceBefore(separator);
_cursor = separator.Span.End;
}
else if (node.Members.SeparatorCount > i)
{
// Last element with trailing comma
var separator = node.Members.GetSeparator(i);
afterSpace = ExtractSpaceBefore(separator);
_cursor = separator.Span.End;
var suffix = ExtractSpaceBefore(node.CloseBraceToken);
markers = markers.Add(new TrailingComma(Guid.NewGuid(), suffix));
}
else
{
// Last element without trailing comma
afterSpace = ExtractSpaceBefore(node.CloseBraceToken);
}
memberList.Add(new JRightPadded<Expression>(memberJ, afterSpace, markers));
}
members = new JContainer<Expression>(membersPrefix, memberList, Markers.Empty);
}
else
{
members = new JContainer<Expression>(membersPrefix, [], Markers.Empty);
}
_cursor = node.CloseBraceToken.Span.End;
// Handle trailing semicolon (e.g., `enum Color { ... };`)
var enumMarkers = Markers.Empty;
if (node.SemicolonToken.Span.Length > 0)
{
SkipTo(node.SemicolonToken.SpanStart);
SkipToken(node.SemicolonToken);
enumMarkers = Markers.Build([new Semicolon(Guid.NewGuid())]);
}
return new EnumDeclaration(
Guid.NewGuid(),
prefix,
enumMarkers,
attributeLists.Count > 0 ? attributeLists : null,
modifiers,
new JLeftPadded<Identifier>(enumPrefix, name),
baseType,
members
);
}
public override J VisitEnumMemberDeclaration(EnumMemberDeclarationSyntax node)
{
var prefix = ExtractPrefix(node);
// Parse attribute lists
var attributeLists = new List<AttributeList>();
foreach (var attrList in node.AttributeLists)
{
attributeLists.Add((AttributeList)Visit(attrList)!);
}
var namePrefix = ExtractSpaceBefore(node.Identifier);
_cursor = node.Identifier.Span.End;
var enumMemberVarType = _typeMapping?.VariableType(node);
var name = new Identifier(
Guid.NewGuid(),
namePrefix,
Markers.Empty,
[],
node.Identifier.Text,
enumMemberVarType?.Type,
enumMemberVarType
);
JLeftPadded<Expression>? initializer = null;
if (node.EqualsValue != null)
{
var equalsPrefix = ExtractSpaceBefore(node.EqualsValue.EqualsToken);
_cursor = node.EqualsValue.EqualsToken.Span.End;
var valueExpr = Visit(node.EqualsValue.Value);
if (valueExpr is Expression expr)
{
initializer = new JLeftPadded<Expression>(equalsPrefix, expr);
}
}
return new EnumMemberDeclaration(
Guid.NewGuid(),
prefix,
Markers.Empty,
attributeLists,
name,
initializer
);
}
private J VisitTypeDeclaration(TypeDeclarationSyntax node)
{
var prefix = ExtractPrefix(node);
// Parse attribute lists
var attributeLists = new List<AttributeList>();
foreach (var attrList in node.AttributeLists)
{
attributeLists.Add((AttributeList)Visit(attrList)!);
}
// Parse modifiers
var modifiers = new List<Modifier>();
foreach (var mod in node.Modifiers)
{
var modPrefix = ExtractSpaceBefore(mod);
_cursor = mod.Span.End;
modifiers.Add(CreateModifier(modPrefix, mod));
}
// Parse the 'class'/'interface'/'struct'/'record' keyword
var kindPrefix = ExtractSpaceBefore(node.Keyword);
_cursor = node.Keyword.Span.End;
// For record declarations, also skip the optional 'class' or 'struct' keyword
// (record, record class, record struct)
if (node is RecordDeclarationSyntax recordDecl &&
!recordDecl.ClassOrStructKeyword.IsKind(SyntaxKind.None))
{
_cursor = recordDecl.ClassOrStructKeyword.Span.End;
}
var kind = new ClassDeclaration.Kind(
Guid.NewGuid(),
kindPrefix,
Markers.Empty,
[],
MapClassKind(node.Keyword.Kind())
);
// Parse the name
var namePrefix = ExtractSpaceBefore(node.Identifier);
_cursor = node.Identifier.Span.End;
var name = new Identifier(
Guid.NewGuid(),
namePrefix,
Markers.Empty,
[],
node.Identifier.Text,
_typeMapping?.ClassType(node),
null
);
// Parse type parameters (generics) - just the <T, U> angle brackets
JContainer<TypeParameter>? typeParameters = null;
if (node.TypeParameterList != null)
{
typeParameters = ParseTypeParameterList(node.TypeParameterList);
}
// Parse primary constructor (C# 12)
// Following Kotlin pattern: synthesize a MethodDeclaration and add it to the body
MethodDeclaration? primaryConstructorMethod = null;
if (node.ParameterList != null)
{
primaryConstructorMethod = ParsePrimaryConstructor(node.ParameterList);
}
// Parse base list (inheritance)
// In C#, the base list is: `: Base, IFoo, IBar`
// We map this to: Extends = first type, Implements = remaining types
JLeftPadded<TypeTree>? extends = null;
JContainer<TypeTree>? implements = null;
if (node.BaseList != null)
{
var colonPrefix = ExtractSpaceBefore(node.BaseList.ColonToken);
_cursor = node.BaseList.ColonToken.Span.End;
var baseTypes = node.BaseList.Types;
if (baseTypes.Count > 0)
{
// First base type goes into Extends
// colonPrefix = space before `:`, the type's prefix = space after `:`
var firstTypeTree = (TypeTree?)Visit(baseTypes[0].Type);
if (firstTypeTree == null)
{
throw new InvalidOperationException(
$"Visit returned null for base type at index 0: " +
$"Type={baseTypes[0].Type.GetType().Name}, " +
$"Kind={baseTypes[0].Type.Kind()}, " +
$"Text='{baseTypes[0].Type}'");
}
firstTypeTree = WrapWithArguments(firstTypeTree, baseTypes[0]);
extends = new JLeftPadded<TypeTree>(colonPrefix, firstTypeTree);
// Remaining types go into Implements
if (baseTypes.Count > 1)
{
// Get space before first comma for container's Before
var firstSeparator = baseTypes.GetSeparator(0);
var containerBefore = ExtractSpaceBefore(firstSeparator);
_cursor = firstSeparator.Span.End;
var implementsList = new List<JRightPadded<TypeTree>>();
for (var i = 1; i < baseTypes.Count; i++)
{
var typeTree = (TypeTree?)Visit(baseTypes[i].Type);
if (typeTree == null)
{
throw new InvalidOperationException(
$"Visit returned null for base type at index {i}: " +
$"Type={baseTypes[i].Type.GetType().Name}, " +
$"Kind={baseTypes[i].Type.Kind()}, " +
$"Text='{baseTypes[i].Type}'");
}
typeTree = WrapWithArguments(typeTree, baseTypes[i]);
// After space is before the next comma, or empty for the last element
Space afterSpace;
if (i < baseTypes.Count - 1)
{
var separator = baseTypes.GetSeparator(i);
afterSpace = ExtractSpaceBefore(separator);
_cursor = separator.Span.End;
}
else
{
afterSpace = Space.Empty;
}
implementsList.Add(new JRightPadded<TypeTree>(typeTree, afterSpace, Markers.Empty));
}
implements = new JContainer<TypeTree>(containerBefore, implementsList, Markers.Empty);
}
}
}
// Now merge constraint clauses into type parameters (after base list + primary constructor
// so cursor is in correct position since constraints appear last in source text)
if (typeParameters != null && node.ConstraintClauses.Count > 0)
{
typeParameters = MergeConstraintClauses(typeParameters, node.ConstraintClauses);
}
else if (node.TypeParameterList == null && node.ConstraintClauses.Count > 0)
{
// Non-generic type with where clauses — create a synthetic empty type parameter container
// and merge constraints into it. Mark as implicit so the printer skips <>.
typeParameters = new JContainer<TypeParameter>(Space.Empty, [],
Markers.Build([new ImplicitTypeParameters(Guid.NewGuid())]));
typeParameters = MergeConstraintClauses(typeParameters, node.ConstraintClauses);
}
// Parse the body (check for semicolon-terminated records first)
Block body;
bool trailingSemicolon = false;
// Types can end with semicolon instead of braces: record Person(string Name); interface C;
// Check if this is a semicolon-terminated type (semicolon present AND no open brace)
if (node.SemicolonToken.Span.Length > 0 &&
node.OpenBraceToken.Span.Length == 0)
{
// Semicolon-terminated type declaration (no braces)
var semicolonPrefix = ExtractSpaceBefore(node.SemicolonToken);
_cursor = node.SemicolonToken.Span.End;
body = new Block(
Guid.NewGuid(),
semicolonPrefix,
Markers.Build([new Semicolon(Guid.NewGuid())]),
new JRightPadded<bool>(false, Space.Empty, Markers.Empty),
[],
Space.Empty