This repository has been archived by the owner on Dec 13, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathRoslynGenerator.cs
3301 lines (2862 loc) · 138 KB
/
RoslynGenerator.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
using FogCreek.Wasabi.AST;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using SF = Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
namespace FogCreek.Wasabi.CodeGenerators
{
public class RoslynException : InvalidOperationException
{
public RoslynException(string message) : base(message) { }
}
public partial class RoslynGenerator : IVisitor, ICodeGenVisitor
{
CompilationUnitSyntax currentCodeFile;
TypeDeclarationSyntax currentType;
NamespaceDeclarationSyntax currentNS;
List<StatementSyntax> currentBlock;
List<SyntaxTrivia> currentTrivia = new List<SyntaxTrivia>();
CFunction currentAccessor;
private const string RETURN_VARIABLE = "returnValue";
private const string globalTypeName = "Global";
public RoslynGenerator()
{
Acceptor = this;
}
ExpressionSyntax expression;
ExpressionSyntax Visit(CNode node)
{
node.Accept(Acceptor);
if (node is CExpression && expression == null)
throw new RoslynException("did not generate expression");
return expression;
}
bool inResumeNext = false;
bool errObjectDeclared = false;
int _befores = 0;
int Before()
{
if (inResumeNext)
{
return ++_befores;
}
return -1;
}
void After(int i, StatementSyntax stmt)
{
if (i == -1)
{
currentBlock.Add(stmt);
return;
}
if (_befores != i)
throw new RoslynException("mismatched before/after");
currentBlock.Add(SF.TryStatement()
.WithBlock(SF.Block(stmt))
.WithCatches(SF.SingletonList(
SF.CatchClause(
SF.CatchDeclaration(SafeIdentifierName("System.Exception"), SafeIdentifier("e")),
null,
SF.Block(SF.ParseStatement("Err.LoadFromException(e);"))))));
}
StatementSyntax OnErrorFlowControl(StatementSyntax flow, bool startedInResumeNext)
{
if (!startedInResumeNext)
return flow;
var err = SafeIdentifierName("Err");
var loadFromExceptionArgs = SF.ArgumentList(SF.SeparatedList(new[] { SF.Argument(SafeIdentifierName("e")) }));
StatementSyntax loadFromException = SF.ExpressionStatement(SF.InvocationExpression(SF.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, err, SafeIdentifierName("LoadFromException")), loadFromExceptionArgs));
var accessResume = SF.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, err, SafeIdentifierName("Resume"));
var catchStatements = new StatementSyntax[] {
SF.ExpressionStatement(Assign(accessResume, Literal(inResumeNext))),
inResumeNext ? loadFromException : SF.ThrowStatement()
};
CatchClauseSyntax _catch = SF.CatchClause(SF.CatchDeclaration(SafeIdentifierName("System.Exception"), SafeIdentifier("e")), null, SF.Block(catchStatements));
return SF.TryStatement(flow as BlockSyntax ?? SF.Block(flow), SF.SingletonList(_catch), null);
}
#region IVisitor Members
private void VisitBlock(CStatementBlock statements)
{
foreach (var node in statements)
{
Visit(node);
}
}
void IVisitor.VisitBlock(CStatementBlock statements)
{
VisitBlock(statements);
}
void IVisitor.VisitAssignment(CAssignment assign)
{
int next = Before();
ExpressionSyntax left = Visit(assign.Target);
if (left is InvocationExpressionSyntax)
throw new NotImplementedException("Invoke in assignment");
After(next, AddComments(SF.ExpressionStatement(Assign(left, Visit(assign.Source)))));
}
private T AddComments<T>(T stmt) where T : SyntaxNode
{
return AddComments<T>(stmt, GetComments());
}
private static T AddComments<T>(T stmt, SyntaxTriviaList trivia) where T : SyntaxNode
{
return stmt.WithLeadingTrivia(trivia.AddRange(stmt.GetLeadingTrivia()));
}
private BlockSyntax TrailingComments(BlockSyntax block)
{
return block.WithCloseBraceToken(block.CloseBraceToken.WithLeadingTrivia(GetComments().AddRange(block.CloseBraceToken.LeadingTrivia)));
}
private SyntaxTriviaList GetComments()
{
var triviaList = SF.TriviaList(currentTrivia.ToArray());
currentTrivia.Clear();
return triviaList;
}
void IVisitor.VisitCase(CCase ccase)
{
throw new NotImplementedException("use RoslynGenerator.VisitCases instead of Visit(CStatementBlock)");
}
private IEnumerable<SwitchSectionSyntax> VisitCases(CStatementBlock cases)
{
var labels = new List<SwitchLabelSyntax>();
foreach (var stmt in cases)
{
if (stmt is CNewline) continue;
if (stmt is CComment) { Visit(stmt); continue; }
var @case = (CCase)stmt;
if (@case.IsElseCase) { labels.Add(SF.DefaultSwitchLabel()); }
else { labels.Add(SF.CaseSwitchLabel(Visit(@case.Value))); }
if (@case.Statements != null)
{
var comments = GetComments();
currentBlock = new List<StatementSyntax>();
Visit(@case.Statements);
currentBlock.Add(SF.BreakStatement());
yield return AddComments(SF.SwitchSection(SF.List(labels), SF.List(currentBlock)), comments);
labels.Clear();
currentBlock = null;
}
}
if (labels.Count > 0)
yield return AddComments(SF.SwitchSection(SF.List(labels), SF.SingletonList<StatementSyntax>(SF.BreakStatement())));
}
void IVisitor.VisitInterface(CInterface iface)
{
VisitClass(iface, SyntaxKind.InterfaceDeclaration);
}
void IVisitor.VisitEnum(CEnum eration)
{
var oldNS = currentNS;
var typeName = eration.RawShortName;
currentNS = LoadNamespace(eration.RawNameSpace);
var leadingTrivia = GetComments();
var members = new List<EnumMemberDeclarationSyntax>();
foreach (CClassConst classMember in eration.DirectClassMemberIterator)
{
members.Add(SF.EnumMemberDeclaration(classMember.RawName)
.WithEqualsValue(SF.EqualsValueClause(Visit(classMember.Constant.Value))));
}
var enumDecl = SF.EnumDeclaration(
attributeLists: GenerateAttributes(eration),
modifiers: SF.TokenList(GetTypeVisibility(eration)),
identifier: SafeIdentifier(typeName),
baseList: null,
members: SF.SeparatedList(members, Enumerable.Repeat(SF.Token(SyntaxKind.CommaToken), members.Count)));
currentCodeFile = currentCodeFile.ReplaceNode(currentNS, currentNS.AddMembers(AddComments(enumDecl, leadingTrivia)));
currentNS = oldNS;
}
void IVisitor.VisitClass(CClass cclas)
{
VisitClass(cclas, SyntaxKind.ClassDeclaration);
}
private NamespaceDeclarationSyntax LoadNamespace(string nsName = null)
{
if (string.IsNullOrEmpty(nsName)) nsName = Compiler.Current.DefaultNamespace.RawValue;
var ns = currentCodeFile.Members.OfType<NamespaceDeclarationSyntax>().SingleOrDefault(nds => nds.Name.ToString() == nsName);
if (ns != null) return ns;
currentCodeFile = currentCodeFile.AddMembers(SF.NamespaceDeclaration(SF.ParseName(nsName)));
return LoadNamespace(nsName);
}
private void VisitClass(CClass cclas, SyntaxKind kind)
{
var oldType = currentType;
var typeName = cclas.RawShortName;
var oldNS = currentNS;
currentNS = LoadNamespace(cclas.RawNameSpace);
var comments = GetComments();
switch (kind)
{
case SyntaxKind.ClassDeclaration:
currentType = SF.ClassDeclaration(typeName);
break;
case SyntaxKind.InterfaceDeclaration:
currentType = SF.InterfaceDeclaration(typeName);
break;
default: throw new NotImplementedException("VisitClass " + kind);
}
var baseList = SF.BaseList();
if (!cclas.IsEnum && !cclas.IsInterface)
{
var @base = GetType(cclas.BaseClass);
var pts = @base as PredefinedTypeSyntax;
if (pts == null || pts.Keyword.Kind() != SyntaxKind.ObjectKeyword)
{
baseList = baseList.AddTypes(SF.SimpleBaseType(@base));
}
}
foreach (CTypeRef iface in cclas.Interfaces)
baseList = baseList.AddTypes(SF.SimpleBaseType(GetType(iface)));
if (baseList.Types.Count > 0)
{
currentType = currentType.WithBaseList(baseList);
}
var modifiers = SF.TokenList(GetTypeVisibility(cclas));
if (cclas.IsAbstract)
modifiers = modifiers.Add(SF.Token(SyntaxKind.AbstractKeyword));
if (cclas.IsSealed)
modifiers = modifiers.Add(SF.Token(SyntaxKind.SealedKeyword));
currentType = currentType.WithModifiers(modifiers);
if (cclas.Constructor == null && !cclas.IsInterface)
{
var cons = SF.ConstructorDeclaration(typeName).WithModifiers(SF.TokenList(SF.Token(SyntaxKind.PublicKeyword)));
cons = InitializeFields(cclas, cons);
if (cons.Body.Statements.Count > 0)
{
currentType = currentType.AddMember(cons);
}
}
InitializeStaticFields(cclas);
foreach (CMember member in cclas.DirectMemberIterator)
InternalGenerateMember(cclas, member);
foreach (CMember explicitMember in cclas.ExplicitInterfaceIterator)
InternalGenerateMember(cclas, explicitMember);
foreach (CMember classMember in cclas.DirectClassMemberIterator)
InternalGenerateMember(cclas, classMember);
currentType = currentType.WithAttributeLists(GenerateAttributes(cclas));
currentType = AddComments(currentType, comments);
currentCodeFile = currentCodeFile.ReplaceNode(currentNS, currentNS.AddMembers(currentType));
currentType = oldType;
currentNS = oldNS;
}
private CClass optionalattr;
private SyntaxList<AttributeListSyntax> GenerateAttributes(IAttributed iAttributed, IEnumerable<AttributeSyntax> prelude = null)
{
if (optionalattr == null)
optionalattr = CProgram.Global.FindClass("WasabiOptionalAttribute");
var attrs = new List<AttributeSyntax>();
if (prelude != null)
attrs.AddRange(prelude);
attrs.AddRange(GenerateAttributesInternal(iAttributed));
if (iAttributed is CProgram)
{
return SF.List(attrs.Select(NicerAttr).Select(attr => SF.AttributeList(SF.AttributeTargetSpecifier(SF.Token(SyntaxKind.AssemblyKeyword)), SF.SingletonSeparatedList(attr))));
}
return SF.List(attrs.Select(NicerAttr).Select(attr => SF.AttributeList(SF.SingletonSeparatedList(attr))));
}
private static AttributeSyntax NicerAttr(AttributeSyntax attr)
{
if (attr.ArgumentList != null && attr.ArgumentList.Arguments.Count == 0)
attr = attr.WithArgumentList(null);
var name = attr.Name.ToString();
if (name.EndsWith("Attribute")) attr = attr.WithName(SF.IdentifierName(name.Remove(name.Length - "Attribute".Length)));
return attr;
}
private IEnumerable<AttributeSyntax> GenerateAttributesInternal(IAttributed iAttributed)
{
foreach (CAttribute myAttr in iAttributed.Attributes)
{
if (myAttr.Type.ActualType == optionalattr)
{
// Wasabi generates [System.Runtime.InteropServices.OptionalAttribute] for Wasabi optionals
// automatically elsewhere, so don't generate redundant [WasabiOptional] on them.
}
else if (myAttr.Type.TypeName.RawValue == "System.Attribute")
{
// ignore typechecker's customattributes; they are handled elsewhere
}
else if (myAttr.Type.TypeName.RawValue == "System.ParamArrayAttribute")
{
// C# will generate these at compile time
}
else
{
var attrParams = SF.AttributeArgumentList(SF.SeparatedList(
myAttr.Parameters.Unnamed.Select(n => SF.AttributeArgument(Visit(n))).Union(
myAttr.Parameters.Named.Select(named_node =>
SF.AttributeArgument(Visit(named_node.Value))
.WithNameEquals(SF.NameEquals(myAttr.Type.ActualType.LookupMember(named_node.Key).RawName))
))));
var ts = GetType(myAttr.Type);
yield return SF.Attribute(ts as NameSyntax, attrParams);
}
}
}
private void InternalGenerateMember(CClass cclas, CMember member)
{
HackyGetMemberComments(cclas, member);
switch (member.MemberType)
{
case "field":
CVariable var = (CVariable)member.Declared[0];
var comments = GetComments();
string field_name = var.Name.RawValue;
var field_vis = GetVisibility(member);
if (var.Attributes.contains("converttoproperty"))
{
var prop_vis = field_vis;
string prop_name = field_name;
// Rename and hide original field
field_name = "m_" + field_name;
field_vis = member.IsStatic ?
SF.TokenList(SF.Token(SyntaxKind.StaticKeyword), SF.Token(SyntaxKind.PrivateKeyword)) :
SF.TokenList(SF.Token(SyntaxKind.PrivateKeyword));
// Generate a property where the field should have been
var prop = SF.PropertyDeclaration(
GetType(var.Type),
prop_name)
.WithModifiers(prop_vis);
CParameters gl_gs_params = var.Attributes.getList("converttoproperty")[0].Parameters;
string gls = "gl";
if (gl_gs_params.Unnamed.Count == 1)
gls = gl_gs_params.Unnamed[0].Token.Value;
gls = gls.ToLower();
var accessorList = SF.AccessorList();
// "return this.field;"
if (gls.Contains("g"))
{
accessorList = accessorList.AddAccessors(
SF.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration,
SF.Block(
SF.ReturnStatement(SF.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression,
createThisOrStaticExpression(member.IsStatic, var.ContainingClass), SafeIdentifierName(field_name))))));
}
// "this.field = value;"
if (gls.Contains("l") || gls.Contains("s"))
{
accessorList = accessorList.AddAccessors(
SF.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration,
SF.Block(SF.ExpressionStatement(
Assign(
SF.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression,
createThisOrStaticExpression(member.IsStatic, var.ContainingClass), SafeIdentifierName(field_name)),
SafeIdentifierName("value"))))));
}
prop = prop.WithAccessorList(accessorList);
currentType = currentType.AddMember(AddComments(prop, comments));
comments = SF.TriviaList();
}
FieldDeclarationSyntax field = PossiblyInitializedField(var, field_name)
.WithModifiers(field_vis)
.WithAttributeLists(GenerateAttributes(var));
currentType = currentType.AddMember(AddComments(field, comments));
break;
case "property":
InternalGenerateProperty(cclas, (CProperty)member);
break;
case "method":
CFunction funx = ((CMethod)member).Function;
Visit(funx);
break;
case "const":
Visit(((CClassConst)member).Constant);
break;
case "override":
CMemberOverload cmo = (CMemberOverload)member;
foreach (CMember memb in cmo.Overloads)
InternalGenerateMember(cclas, memb);
break;
default:
throw new NotImplementedException("InternalGenerateMember of a " + member.MemberType);
}
}
private void HackyGetMemberComments(CClass cclas, CMember member)
{
var stmts = cclas.Statements;
var ixStmt = stmts.IndexOf(member);
var comments = new List<CComment>();
for (var ixComment = ixStmt - 1; ixComment >= 0; ixComment--)
{
var comment = stmts[ixComment] as CComment;
if (comment == null) break;
comments.Insert(0, comment);
}
foreach (CComment comment in comments)
{
Visit(comment);
}
}
private FieldDeclarationSyntax PossiblyInitializedField(CVariable var, string name)
{
if ((var.Initializer != null || var.IsArray) && IsSimpleEnough(var))
{
return FieldDeclaration(GetType(var.Type), name, VisitVariableInitializer(var));
}
else
{
return SimpleFieldDeclaration(GetType(var.Type), SafeIdentifier(name));
}
}
private static bool IsSimpleEnough(CVariable var)
{
if (var.IsArray && var.Initializer == null) return true;
return IsSimpleEnough(var.Initializer);
}
private static bool IsSimpleEnough(CExpression exp)
{
while (true)
{
if (exp is CThisAccess) return false;
if (exp is CConstantExpression) return true;
var cmu = exp as CMathUnary;
var cast = exp as CCast;
var access = exp as CAccess;
var cbo = exp as CBinaryOperator;
var concat = exp as CConcat;
if (cmu != null) { exp = cmu.Operand; }
else if (cast != null) { exp = cast.InnerExpression; }
else if (access != null)
{
if (access.ReferenceTarget is CConst) return true;
var cnew = access as CNew;
if (cnew != null)
{
if (cnew.Type.ActualType.CecilType == null && cnew.Type.ActualType.Constructor != null) return false;
return cnew.Parameters.Unnamed.Cast<CExpression>().All(IsSimpleEnough) && cnew.Parameters.Named.Select(kvp => kvp.Value).Cast<CExpression>().All(IsSimpleEnough);
}
var token = access.Token;
var cda = access as CDefaultAccess;
if (cda != null)
{
var target = cda.TargetAccess;
token = target.ReferenceToken;
if (target.IsRootAccess)
{
// Inlined globals are allowed
var inlinedGlobals = new[] { "array", "dictionary", "ismissing" };
if (inlinedGlobals.Contains(target.ReferenceToken.Value) || target.ReferenceToken.Value == "utcnow" || target.ReferenceToken.Value == "join")
{
return cda.Parameters.Unnamed.Cast<CExpression>().All(IsSimpleEnough) && cda.Parameters.Named.Select(kvp => kvp.Value).Cast<CExpression>().All(IsSimpleEnough);
}
}
}
var cma = access as CMemberAccess;
if (cma != null)
{
var lhsAccess = cma.MemberSource as CAccess;
var klass = lhsAccess.ReferenceTarget as CClass;
if (klass == null) return false;
var rhs = cma.ReferenceTarget as CProperty;
return rhs == null;
}
var notNullableInvalid = new[] { "vbinvaliddate", "vbinvalidint", "vbinvaliddouble" };
if (access.GetType() == typeof(CAccess) && notNullableInvalid.Contains(access.Token.Value))
{
return true;
}
return false;
}
else if (cbo != null) { return IsSimpleEnough(cbo.Left) && IsSimpleEnough(cbo.Right); }
else if (concat != null) { return IsSimpleEnough(concat.Left) && IsSimpleEnough(concat.Right); }
else { return false; }
}
}
private void InternalGenerateProperty(CClass cclas, CProperty cprop)
{
var comments = GetComments();
BasePropertyDeclarationSyntax property;
if (cprop.GetAccessor.Arguments.Count > 0)
{
if (cprop != cclas.DefaultMember)
throw new RoslynException("Type checker should have raised an error");
var indexer = SF.IndexerDeclaration(GetType(cprop.Type));
if (cprop.GetAccessor.Arguments.Count > 0)
{
indexer = indexer.WithParameterList(SF.BracketedParameterList(AddArguments(cprop.GetAccessor.Arguments)));
}
property = indexer;
}
else
{
property = SF.PropertyDeclaration(GetType(cprop.Type), cprop.GetAccessor.RawName);
}
if (cprop.HasExplicitInterface)
{
property = property.WithExplicitInterfaceSpecifier(
SF.ExplicitInterfaceSpecifier(SafeIdentifierName(cprop.ExplicitInterfaceName)));
if (cprop.IsStatic)
property = property.WithModifiers(SF.TokenList(SF.Token(SyntaxKind.StaticKeyword)));
else
property = property.WithModifiers(SF.TokenList());
}
else
{
property = property.WithModifiers(GetVisibility(cprop));
}
var oldBlock = currentBlock;
currentAccessor = cprop.GetAccessor;
var oldDeferredMembers = deferredMembersFunction;
deferredMembersFunction = new List<MemberDeclarationSyntax>();
var generateBodies = !cprop.GetAccessor.Abstract && !cprop.GetAccessor.InInterface;
var accessorList = SF.AccessorList(SF.SingletonList(GenerateAccessor(cprop.GetAccessor, SyntaxKind.GetAccessorDeclaration, generateBodies)));
if (cprop.GetAccessor.InInterface)
property = property.WithModifiers(SF.TokenList());
else if (cprop.GetAccessor.Abstract)
property = property.WithModifiers(property.Modifiers.Add(SF.Token(SyntaxKind.AbstractKeyword)));
else if (cprop.GetAccessor.Override)
property = property.WithModifiers(property.Modifiers.Add(SF.Token(SyntaxKind.OverrideKeyword)));
else if (cprop.GetAccessor.Virtual)
property = property.WithModifiers(property.Modifiers.Add(SF.Token(SyntaxKind.VirtualKeyword)));
for (int i = 1; i < 3; i++)
{
CFunction func = (CFunction)cprop.Declared[i];
if (func != null)
{
func.Arguments[func.Arguments.Count - 1].IndexerValueArgument = true;
currentAccessor = func;
accessorList = accessorList.AddAccessors(GenerateAccessor(func, SyntaxKind.SetAccessorDeclaration, generateBodies));
}
}
property = property.WithAccessorList(accessorList);
currentType = currentType.WithMembers(currentType.Members.Add(AddComments(property, comments)).AddRange(deferredMembersFunction));
currentAccessor = null;
currentBlock = oldBlock;
deferredMembersFunction = oldDeferredMembers;
}
private AccessorDeclarationSyntax GenerateAccessor(CFunction cFunction, SyntaxKind kind, bool generateBodies)
{
var comments = GetComments();
AccessorDeclarationSyntax acc;
if (generateBodies)
{
currentBlock = new List<StatementSyntax>();
AddMethodBody(cFunction);
acc = SF.AccessorDeclaration(kind, SF.Block(currentBlock));
}
else
{
acc = SF.AccessorDeclaration(kind).WithSemicolonToken(SF.Token(SyntaxKind.SemicolonToken));
}
return AddComments(acc, comments);
}
private static SyntaxTokenList GetVisibility(IHasVisibility member)
{
SyntaxTokenList attribs;
switch (member.Visibility)
{
case TokenTypes.visPrivate:
attribs = SF.TokenList(SF.Token(SyntaxKind.PrivateKeyword));
break;
case TokenTypes.visProtected:
attribs = SF.TokenList(SF.Token(SyntaxKind.ProtectedKeyword));
break;
case TokenTypes.visPublic:
attribs = SF.TokenList(SF.Token(SyntaxKind.PublicKeyword));
break;
case TokenTypes.visInternal:
attribs = SF.TokenList(SF.Token(SyntaxKind.InternalKeyword));
break;
default:
throw new RoslynException("Invalid visibility: " + member.Visibility.ToString());
}
if (member.IsStatic)
attribs = attribs.Add(SF.Token(SyntaxKind.StaticKeyword));
return attribs;
}
private static SyntaxToken GetTypeVisibility(IHasVisibility member)
{
switch (member.Visibility)
{
case TokenTypes.visPublic:
return SF.Token(SyntaxKind.PublicKeyword);
case TokenTypes.visPrivate:
return SF.Token(SyntaxKind.InternalKeyword);
case TokenTypes.visInternal:
case TokenTypes.visProtected:
default:
throw new RoslynException("Invalid type visibility: " + member.Visibility.ToString());
}
}
private static IEnumerable<SyntaxToken> GetAccessLevel(CFunction func)
{
if (func.Abstract)
yield return SF.Token(SyntaxKind.AbstractKeyword);
else if (func.Virtual)
yield return SF.Token(SyntaxKind.VirtualKeyword);
else if (func.Override)
yield return SF.Token(SyntaxKind.OverrideKeyword);
else
yield break;
}
private ConstructorDeclarationSyntax InitializeFields(CClass klass, ConstructorDeclarationSyntax cons)
{
var stmts = FieldInitializers(klass.DirectMemberIterator, SF.ThisExpression());
return cons.WithBody(SF.Block(stmts));
}
private void InitializeStaticFields(CClass klass)
{
var stmts = FieldInitializers(klass.DirectClassMemberIterator, GetType(klass.Type));
if (stmts.Count > 0)
{
var staticConstructor = SF.ConstructorDeclaration(klass.RawShortName).WithModifiers(SF.TokenList(SF.Token(SyntaxKind.StaticKeyword)));
currentType = currentType.AddMember(staticConstructor.WithBody(SF.Block(stmts)));
}
}
private List<StatementSyntax> FieldInitializers(IEnumerable<CMember> members, ExpressionSyntax thisOrStatic)
{
var stmts = new List<StatementSyntax>();
foreach (var f in members.Where(m => m.MemberType == "field").Cast<CField>())
{
string field_name = f.Variable.Name.RawValue;
if (f.Variable.Attributes.contains("converttoproperty"))
field_name = "m_" + field_name;
if ((f.Variable.Initializer != null || f.Variable.IsArray) && !IsSimpleEnough(f.Variable))
{
stmts.Add(SF.ExpressionStatement(Assign(
SF.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression,
thisOrStatic, SafeIdentifierName(field_name)),
VisitVariableInitializer(f.Variable))));
}
}
return stmts;
}
const string xmlCommentStart = "''";
void IVisitor.VisitComment(CComment comment)
{
var text = comment.Text;
var slashies = "//";
if (text.StartsWith(xmlCommentStart))
{
text = text.Substring(xmlCommentStart.Length);
slashies = "///";
}
currentTrivia.Add(SF.Comment(slashies + text));
}
void IVisitor.VisitConcat(CConcat concat)
{
ExpressionSyntax left = Visit(concat.Left), right = Visit(concat.Right);
// the weirdness with precedence here is because, when `int ix = 5`,
// "a" + ix + 1 => "a51"
// but we desire:
// "a" + (ix + 1) => "a6"
// Also, note that
// "a" + ix - 1
// is not valid C#.
expression = SF.BinaryExpression(
SyntaxKind.AddExpression,
Parenthesize(left, concat.Left is CConcat ? Precedence.Additive : Precedence.Primary),
Parenthesize(right, concat.Right is CConcat ? Precedence.Additive : Precedence.Primary));
}
// increasing order of precedence
enum Precedence
{
AssignmentAndLambda = 1,
Conditional,
NullCoalescing,
ConditionalOr, // ||
ConditionalAnd, // &&
LogicalOr, // |
LogicalXor, // ^
LogicalAnd, // &
Equality,
RelationalAndTypeTesting,
Shift,
Additive,
Mutliplicative,
Unary,
Primary,
NotAnOperator = 99999
}
static Precedence GetPrecedence(ExpressionSyntax exp)
{
if (exp is ParenthesizedLambdaExpressionSyntax) return Precedence.AssignmentAndLambda;
if (exp is SimpleLambdaExpressionSyntax) return Precedence.AssignmentAndLambda;
if (exp is ConditionalExpressionSyntax) return Precedence.Conditional;
if (exp is CastExpressionSyntax) return Precedence.Unary;
if (exp is PrefixUnaryExpressionSyntax) return Precedence.Unary;
if (exp is MemberAccessExpressionSyntax) return Precedence.Primary;
if (exp is InvocationExpressionSyntax) return Precedence.Primary;
if (exp is ElementAccessExpressionSyntax) return Precedence.Primary;
if (exp is PostfixUnaryExpressionSyntax) return Precedence.Primary;
if (exp is ObjectCreationExpressionSyntax) return Precedence.Primary;
if (exp is ArrayCreationExpressionSyntax) return Precedence.Primary;
if (exp is DefaultExpressionSyntax) return Precedence.Primary;
if (exp is ParenthesizedExpressionSyntax) return Precedence.Primary;
if (exp is LiteralExpressionSyntax) return Precedence.NotAnOperator;
if (exp is IdentifierNameSyntax) return Precedence.NotAnOperator;
if (exp is ThisExpressionSyntax) return Precedence.NotAnOperator;
if (exp is BaseExpressionSyntax) return Precedence.NotAnOperator;
if (exp is PredefinedTypeSyntax) return Precedence.NotAnOperator;
if (exp is BinaryExpressionSyntax) return GetPrecedence(((BinaryExpressionSyntax)exp).Kind());
throw new NotImplementedException(exp.GetType().ToString());
}
static Precedence GetPrecedence(SyntaxKind kind)
{
// from https://msdn.microsoft.com/en-us/library/6a71f45d.aspx
switch (kind)
{
case SyntaxKind.MultiplyExpression:
case SyntaxKind.DivideExpression:
case SyntaxKind.ModuloExpression:
return Precedence.Mutliplicative;
case SyntaxKind.AddExpression:
case SyntaxKind.SubtractExpression:
return Precedence.Additive;
case SyntaxKind.LeftShiftExpression:
case SyntaxKind.RightShiftExpression:
return Precedence.Shift;
case SyntaxKind.LessThanExpression:
case SyntaxKind.GreaterThanExpression:
case SyntaxKind.LessThanOrEqualExpression:
case SyntaxKind.GreaterThanOrEqualExpression:
case SyntaxKind.IsExpression:
case SyntaxKind.AsExpression:
return Precedence.RelationalAndTypeTesting;
case SyntaxKind.EqualsExpression:
case SyntaxKind.NotEqualsExpression:
return Precedence.Equality;
case SyntaxKind.BitwiseAndExpression:
return Precedence.LogicalAnd;
case SyntaxKind.ExclusiveOrExpression:
return Precedence.LogicalXor;
case SyntaxKind.BitwiseOrExpression:
return Precedence.LogicalOr;
case SyntaxKind.LogicalAndExpression:
return Precedence.ConditionalAnd;
case SyntaxKind.LogicalOrExpression:
return Precedence.ConditionalOr;
case SyntaxKind.CoalesceExpression:
return Precedence.NullCoalescing;
default: throw new NotImplementedException(kind.ToString());
}
}
static BinaryExpressionSyntax BinaryExpression(SyntaxKind kind, ExpressionSyntax left, ExpressionSyntax right)
{
return SF.BinaryExpression(
kind,
Parenthesize(left, GetPrecedence(kind)),
Parenthesize(right, GetPrecedence(kind)));
}
static PrefixUnaryExpressionSyntax PrefixUnaryExpression(SyntaxKind kind, ExpressionSyntax operand)
{
return SF.PrefixUnaryExpression(kind, Parenthesize(operand, Precedence.Unary));
}
static ExpressionSyntax Not(ExpressionSyntax testExpression)
{
var binexp = testExpression as BinaryExpressionSyntax;
if (binexp == null)
{
var parexp = testExpression as ParenthesizedExpressionSyntax;
if (parexp != null)
{
binexp = parexp.Expression as BinaryExpressionSyntax;
}
}
if (binexp != null)
{
// try to simplify it
BinaryExpressionSyntax inverted = null;
if (binexp.OperatorToken.IsKind(SyntaxKind.EqualsEqualsToken))
inverted = binexp.WithOperatorToken(SF.Token(SyntaxKind.ExclamationEqualsToken));
else if (binexp.OperatorToken.IsKind(SyntaxKind.ExclamationEqualsToken))
inverted = binexp.WithOperatorToken(SF.Token(SyntaxKind.EqualsEqualsToken));
if (inverted != null)
{
if (testExpression is ParenthesizedExpressionSyntax)
return SF.ParenthesizedExpression(inverted);
else return inverted;
}
}
return PrefixUnaryExpression(SyntaxKind.LogicalNotExpression, testExpression);
}
static CastExpressionSyntax Cast(TypeSyntax type, ExpressionSyntax inner)
{
return SF.CastExpression(type, Parenthesize(inner, Precedence.Unary));
}
void IVisitor.VisitConst(CConst cconst)
{
var type = GetType(cconst.Value.Type);
if (currentFunction != null)
{
var lvar = SF.VariableDeclaration(type, SF.SingletonSeparatedList(SF.VariableDeclarator(SafeIdentifier(cconst.RawName), null,
SF.EqualsValueClause(Visit(cconst.Value)))));
varsFunction = varsFunction.Add(AddComments(SF.LocalDeclarationStatement(lvar).AddModifiers(SF.Token(SyntaxKind.ConstKeyword))));
}
else
{
var field = FieldDeclaration(type, cconst.RawName, Visit(cconst.Value))
.WithModifiers(SF.TokenList(SF.Token(SyntaxKind.PublicKeyword), SF.Token(SyntaxKind.ConstKeyword)))
.WithAttributeLists(GenerateAttributes(cconst));
field = AddComments(field);
currentType = currentType.AddMember(field);
}
}
void IVisitor.VisitDim(CDim dim)
{
foreach (CVariable var in dim.Variables)
{
Visit(var);
}
}
Lazy<string> labelDo;
void IVisitor.VisitDo(CDo cdo)
{
bool inResume = inResumeNext;
var comments = GetComments();
var testExpression = Visit(cdo.Condition);
if (cdo.IsDoUntil)
{
// "Do Until X" === "Do While Not X"
testExpression = Not(testExpression);
}
var block = currentBlock;
var oldDo = labelDo;
labelDo = ExitLabel("__doExit");
currentBlock = new List<StatementSyntax>();
Visit(cdo.Statements);
StatementSyntax loop;
if (cdo.IsPostConditionLoop)
{
loop = SF.DoStatement(SF.Block(currentBlock), testExpression);
}
else
{
loop = SF.WhileStatement(testExpression, SF.Block(currentBlock));
}
loop = AddComments(loop, comments);
AddLabeledStatement(block, OnErrorFlowControl(loop, inResume), labelDo);
currentBlock = block;
labelDo = oldDo;
}
private static void AddLabeledStatement(List<StatementSyntax> block, StatementSyntax stmt, Lazy<string> label)
{
if (stmt is BlockSyntax)
{
block.AddRange(((BlockSyntax)stmt).Statements);
}
else
{
block.Add(stmt);
}
if (label.IsValueCreated)
{
block.Add(SF.LabeledStatement(label.Value, SF.EmptyStatement()));
}
}
private Dictionary<string, uint> labelNumbers = new Dictionary<string, uint>();
/// <summary> generate a function-unique identifier for jump targets, temporary variables, etc.</summary>
private string Label(string labelType)
{
uint i;
if (!labelNumbers.TryGetValue(labelType, out i))
{
i = 0;
}
try
{
if (i == 0) return labelType;
return labelType + i;
}
finally
{
labelNumbers[labelType] = ++i;
}
}
Lazy<string> innermostExit;