Repository navigation
Expand file tree
/
Copy pathLuaSyntaxNodeTransform.cs
More file actions
3244 lines (2950 loc) · 144 KB
/
Copy pathLuaSyntaxNodeTransform.cs
File metadata and controls
3244 lines (2950 loc) · 144 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 2017 YANG Huan ([email protected]).
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
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 System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.Contracts;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis;
using CSharpLua.LuaAst;
namespace CSharpLua {
public sealed partial class LuaSyntaxNodeTransform : CSharpSyntaxVisitor<LuaSyntaxNode> {
private const int kStringConstInlineCount = 15;
private sealed class MethodInfo {
public IMethodSymbol Symbol { get; }
public IList<LuaExpressionSyntax> RefOrOutParameters { get; }
public MethodInfo(IMethodSymbol symbol) {
Symbol = symbol;
RefOrOutParameters = Array.Empty<LuaExpressionSyntax>();
}
public MethodInfo(IMethodSymbol symbol, IList<LuaExpressionSyntax> refOrOutParameters) {
Symbol = symbol;
RefOrOutParameters = refOrOutParameters;
}
}
internal sealed class TypeDeclarationInfo {
public INamedTypeSymbol TypeSymbol { get; }
public LuaTypeDeclarationSyntax TypeDeclaration { get; }
public TypeDeclarationInfo(INamedTypeSymbol typeSymbol, LuaTypeDeclarationSyntax luaTypeDeclarationSyntax) {
TypeSymbol = typeSymbol;
TypeDeclaration = luaTypeDeclarationSyntax;
}
public bool CheckTypeName(INamedTypeSymbol getNameTypeSymbol, out LuaIdentifierNameSyntax name) {
if (getNameTypeSymbol.Equals(TypeSymbol)) {
TypeDeclaration.IsClassUsed = true;
name = LuaIdentifierNameSyntax.Class;
return true;
}
name = null;
return false;
}
}
private LuaSyntaxGenerator generator_;
private SemanticModel semanticModel_;
private Stack<LuaCompilationUnitSyntax> compilationUnits_ = new Stack<LuaCompilationUnitSyntax>();
private Stack<TypeDeclarationInfo> typeDeclarations_ = new Stack<TypeDeclarationInfo>();
private Stack<LuaFunctionExpressionSyntax> functions_ = new Stack<LuaFunctionExpressionSyntax>();
private Stack<MethodInfo> methodInfos_ = new Stack<MethodInfo>();
private Stack<LuaBlockSyntax> blocks_ = new Stack<LuaBlockSyntax>();
private Stack<LuaIfStatementSyntax> ifStatements_ = new Stack<LuaIfStatementSyntax>();
private Stack<LuaSwitchAdapterStatementSyntax> switchs_ = new Stack<LuaSwitchAdapterStatementSyntax>();
private int inheritNameNodeCounter_;
public bool IsGetInheritTypeName => inheritNameNodeCounter_ > 0;
public bool IsNoneGenericTypeCounter => generator_.IsNoneGenericTypeCounter;
private static readonly Dictionary<string, string> operatorTokenMapps_ = new Dictionary<string, string>() {
["!="] = LuaSyntaxNode.Tokens.NotEquals,
["!"] = LuaSyntaxNode.Tokens.Not,
["&&"] = LuaSyntaxNode.Tokens.And,
["||"] = LuaSyntaxNode.Tokens.Or,
["??"] = LuaSyntaxNode.Tokens.Or,
["^"] = LuaSyntaxNode.Tokens.BitXor,
};
public LuaSyntaxNodeTransform(LuaSyntaxGenerator generator, SemanticModel semanticModel) {
generator_ = generator;
semanticModel_ = semanticModel;
}
private XmlMetaProvider XmlMetaProvider {
get {
return generator_.XmlMetaProvider;
}
}
private static string GetOperatorToken(SyntaxToken operatorToken) {
string token = operatorToken.ValueText;
return operatorTokenMapps_.GetOrDefault(token, token);
}
private static string GetOperatorToken(string token) {
return operatorTokenMapps_.GetOrDefault(token, token);
}
private bool IsLuaNewest {
get {
return generator_.Setting.IsNewest;
}
}
private LuaCompilationUnitSyntax CurCompilationUnit {
get {
return compilationUnits_.Peek();
}
}
private LuaTypeDeclarationSyntax CurType {
get {
return typeDeclarations_.Peek().TypeDeclaration;
}
}
private INamedTypeSymbol CurTypeSymbol {
get {
return typeDeclarations_.Peek().TypeSymbol;
}
}
internal TypeDeclarationInfo CurTypeDeclaration {
get {
return typeDeclarations_.Count > 0 ? typeDeclarations_.Peek() : null;
}
}
private LuaFunctionExpressionSyntax CurFunction {
get {
return functions_.Peek();
}
}
private LuaFunctionExpressionSyntax CurFunctionOrNull {
get {
return functions_.Count > 0 ? functions_.Peek() : null;
}
}
private MethodInfo CurMethodInfoOrNull {
get {
return methodInfos_.Count > 0 ? methodInfos_.Peek() : null;
}
}
private void PushFunction(LuaFunctionExpressionSyntax function) {
functions_.Push(function);
++localMappingCounter_;
}
private void PopFunction() {
functions_.Pop();
--localMappingCounter_;
if (localMappingCounter_ == 0) {
localReservedNames_.Clear();
}
}
private LuaBlockSyntax CurBlock {
get {
return blocks_.Peek();
}
}
private LuaBlockSyntax CurBlockOrNull {
get {
return blocks_.Count > 0 ? blocks_.Peek() : null;
}
}
public override LuaSyntaxNode VisitCompilationUnit(CompilationUnitSyntax node) {
LuaCompilationUnitSyntax compilationUnit = new LuaCompilationUnitSyntax(node.SyntaxTree.FilePath);
compilationUnits_.Push(compilationUnit);
var statements = VisitTriviaAndNode(node, node.Members, false);
foreach (var statement in statements) {
if (statement is LuaTypeDeclarationSyntax typeDeclaration) {
var ns = new LuaNamespaceDeclarationSyntax(LuaIdentifierNameSyntax.Empty);
ns.AddStatement(typeDeclaration);
compilationUnit.AddStatement(ns);
} else {
compilationUnit.AddStatement(statement);
}
}
compilationUnits_.Pop();
return compilationUnit;
}
public override LuaSyntaxNode VisitNamespaceDeclaration(NamespaceDeclarationSyntax node) {
var symbol = semanticModel_.GetDeclaredSymbol(node);
bool isContained = node.Parent.IsKind(SyntaxKind.NamespaceDeclaration);
string name = generator_.GetNamespaceDefineName(symbol, node);
LuaNamespaceDeclarationSyntax namespaceDeclaration = new LuaNamespaceDeclarationSyntax(new LuaIdentifierNameSyntax(name), isContained);
var statements = VisitTriviaAndNode(node, node.Members);
namespaceDeclaration.AddStatements(statements);
return namespaceDeclaration;
}
private void BuildTypeMembers(LuaTypeDeclarationSyntax typeDeclaration, TypeDeclarationSyntax node) {
if (!node.IsKind(SyntaxKind.InterfaceDeclaration)) {
foreach (var nestedTypeDeclaration in node.Members.Where(i => i.Kind().IsTypeDeclaration())) {
var luaNestedTypeDeclaration = (LuaTypeDeclarationSyntax)nestedTypeDeclaration.Accept(this);
typeDeclaration.AddNestedTypeDeclaration(luaNestedTypeDeclaration);
}
foreach (var member in node.Members.Where(i => !i.Kind().IsTypeDeclaration())) {
member.Accept(this);
}
}
}
private void CheckBaseTypeGenericKind(ref bool hasExtendSelf, INamedTypeSymbol typeSymbol, BaseTypeSyntax baseType) {
if (!hasExtendSelf) {
if (baseType.IsKind(SyntaxKind.SimpleBaseType)) {
var baseNode = (SimpleBaseTypeSyntax)baseType;
if (baseNode.Type.IsKind(SyntaxKind.GenericName)) {
var baseGenericNameNode = (GenericNameSyntax)baseNode.Type;
var baseTypeSymbol = (INamedTypeSymbol)semanticModel_.GetTypeInfo(baseGenericNameNode).Type;
hasExtendSelf = Utility.IsExtendSelf(typeSymbol, baseTypeSymbol);
}
}
}
}
private LuaSpeaicalGenericType CheckSpeaicalGenericArgument(INamedTypeSymbol typeSymbol) {
var interfaceType = typeSymbol.Interfaces.FirstOrDefault(i => i.IsGenericIEnumerableType());
if (interfaceType != null) {
bool isBaseImplementation = typeSymbol.BaseType != null && typeSymbol.BaseType.AllInterfaces.Any(i => i.IsGenericIEnumerableType());
if (!isBaseImplementation) {
var argumentType = interfaceType.TypeArguments.First();
var typeName = GetTypeName(argumentType);
return new LuaSpeaicalGenericType() {
Name = LuaIdentifierNameSyntax.GenericT,
Value = typeName,
IsLazy = argumentType.Kind != SymbolKind.TypeParameter && argumentType.IsFromCode(),
};
}
}
return null;
}
private List<LuaIdentifierNameSyntax> GetBaseCopyFields(BaseTypeSyntax baseType) {
if (baseType != null) {
var baseTypeSymbol = semanticModel_.GetTypeInfo(baseType.Type).Type;
if (baseTypeSymbol.TypeKind == TypeKind.Class && baseTypeSymbol.SpecialType != SpecialType.System_Object) {
if (baseTypeSymbol.IsMemberExists("Finalize", true)) {
return new List<LuaIdentifierNameSyntax>() { LuaIdentifierNameSyntax.__GC };
}
}
}
return null;
}
private bool IsBaseTypeNotSystemObject(LuaExpressionSyntax baseTypeExpression) {
return !(baseTypeExpression is LuaIdentifierNameSyntax name && name.ValueText == LuaIdentifierNameSyntax.Object.ValueText);
}
private void BuildTypeDeclaration(INamedTypeSymbol typeSymbol, TypeDeclarationSyntax node, LuaTypeDeclarationSyntax typeDeclaration) {
typeDeclarations_.Push(new TypeDeclarationInfo(typeSymbol, typeDeclaration));
var comments = BuildDocumentationComment(node);
typeDeclaration.AddDocument(comments);
var attributes = BuildAttributes(node.AttributeLists);
typeDeclaration.AddClassAttributes(attributes);
BuildTypeParameters(typeSymbol, node, typeDeclaration);
if (node.BaseList != null) {
bool hasExtendSelf = false;
var baseTypes = new List<LuaExpressionSyntax>();
foreach (var baseType in node.BaseList.Types) {
var baseTypeName = BuildInheritTypeName(baseType);
if (IsBaseTypeNotSystemObject(baseTypeName)) {
baseTypes.Add(baseTypeName);
CheckBaseTypeGenericKind(ref hasExtendSelf, typeSymbol, baseType);
}
}
if (baseTypes.Count > 0) {
var genericArgument = CheckSpeaicalGenericArgument(typeSymbol);
var baseCopyFields = GetBaseCopyFields(node.BaseList.Types.FirstOrDefault());
typeDeclaration.AddBaseTypes(baseTypes, genericArgument, baseCopyFields);
if (hasExtendSelf && !typeSymbol.HasStaticCtor()) {
typeDeclaration.SetStaticCtorEmpty();
}
}
}
BuildTypeMembers(typeDeclaration, node);
CheckTypeDeclaration(typeSymbol, typeDeclaration);
typeDeclarations_.Pop();
CurCompilationUnit.AddTypeDeclarationCount();
}
private void CheckTypeDeclaration(INamedTypeSymbol typeSymbol, LuaTypeDeclarationSyntax typeDeclaration) {
if (typeDeclaration.IsNoneCtros) {
var bseTypeSymbol = typeSymbol.BaseType;
if (bseTypeSymbol != null) {
bool isNeedCallBase;
if (typeDeclaration.IsInitStatementExists) {
isNeedCallBase = bseTypeSymbol.IsExplicitCtorExists();
} else {
isNeedCallBase = generator_.HasStaticCtor(bseTypeSymbol) || bseTypeSymbol.Constructors.Count() > 1;
}
if (isNeedCallBase) {
var baseCtorInvoke = BuildCallBaseConstructor(typeSymbol);
if (baseCtorInvoke != null) {
LuaConstructorAdapterExpressionSyntax function = new LuaConstructorAdapterExpressionSyntax();
function.AddParameter(LuaIdentifierNameSyntax.This);
function.AddStatement(baseCtorInvoke);
typeDeclaration.AddCtor(function, false);
}
}
}
} else if (typeSymbol.IsValueType) {
LuaConstructorAdapterExpressionSyntax function = new LuaConstructorAdapterExpressionSyntax();
function.AddParameter(LuaIdentifierNameSyntax.This);
typeDeclaration.AddCtor(function, true);
}
if (typeSymbol.IsValueType) {
TryAddStructDefaultMethod(typeSymbol, typeDeclaration);
}
if (typeDeclaration.IsIgnoreExport) {
generator_.AddIgnoreExportType(typeSymbol);
}
}
private INamedTypeSymbol VisitTypeDeclaration(INamedTypeSymbol typeSymbol, TypeDeclarationSyntax node, LuaTypeDeclarationSyntax typeDeclaration) {
if (node.Modifiers.IsPartial()) {
if (typeSymbol.DeclaringSyntaxReferences.Length > 1) {
generator_.AddPartialTypeDeclaration(typeSymbol, node, typeDeclaration, CurCompilationUnit);
typeDeclaration.IsPartialMark = true;
} else {
BuildTypeDeclaration(typeSymbol, node, typeDeclaration);
}
} else {
BuildTypeDeclaration(typeSymbol, node, typeDeclaration);
}
return typeSymbol;
}
internal void AcceptPartialType(PartialTypeDeclaration major, List<PartialTypeDeclaration> typeDeclarations) {
compilationUnits_.Push(major.CompilationUnit);
typeDeclarations_.Push(new TypeDeclarationInfo(major.Symbol, major.TypeDeclaration));
List<LuaExpressionSyntax> attributes = new List<LuaExpressionSyntax>();
foreach (var typeDeclaration in typeDeclarations) {
semanticModel_ = generator_.GetSemanticModel(typeDeclaration.Node.SyntaxTree);
var document = BuildDocumentationComment(typeDeclaration.Node);
major.TypeDeclaration.AddDocument(document);
var expressions = BuildAttributes(typeDeclaration.Node.AttributeLists);
attributes.AddRange(expressions);
}
major.TypeDeclaration.AddClassAttributes(attributes);
BuildTypeParameters(major.Symbol, major.Node, major.TypeDeclaration);
List<BaseTypeSyntax> baseTypes = new List<BaseTypeSyntax>();
HashSet<ITypeSymbol> baseSymbols = new HashSet<ITypeSymbol>();
foreach (var typeDeclaration in typeDeclarations) {
if (typeDeclaration.Node.BaseList != null) {
foreach (var baseTypeSyntax in typeDeclaration.Node.BaseList.Types) {
var semanticModel = generator_.GetSemanticModel(baseTypeSyntax.SyntaxTree);
var baseTypeSymbol = semanticModel.GetTypeInfo(baseTypeSyntax.Type).Type;
if (baseSymbols.Add(baseTypeSymbol)) {
baseTypes.Add(baseTypeSyntax);
}
}
}
}
if (baseTypes.Count > 0) {
if (baseTypes.Count > 1) {
var baseTypeIndex = baseTypes.FindIndex(generator_.IsBaseType);
if (baseTypeIndex > 0) {
var baseType = baseTypes[baseTypeIndex];
baseTypes.RemoveAt(baseTypeIndex);
baseTypes.Insert(0, baseType);
}
}
bool hasExtendSelf = false;
List<LuaExpressionSyntax> baseTypeExpressions = new List<LuaExpressionSyntax>();
foreach (var baseType in baseTypes) {
semanticModel_ = generator_.GetSemanticModel(baseType.SyntaxTree);
var baseTypeName = BuildInheritTypeName(baseType);
if (IsBaseTypeNotSystemObject(baseTypeName)) {
baseTypeExpressions.Add(baseTypeName);
CheckBaseTypeGenericKind(ref hasExtendSelf, major.Symbol, baseType);
}
}
if (baseTypeExpressions.Count > 0) {
var genericArgument = CheckSpeaicalGenericArgument(major.Symbol);
var baseCopyFields = GetBaseCopyFields(baseTypes.FirstOrDefault());
major.TypeDeclaration.AddBaseTypes(baseTypeExpressions, genericArgument, baseCopyFields);
if (hasExtendSelf && !major.Symbol.HasStaticCtor()) {
major.TypeDeclaration.SetStaticCtorEmpty();
}
}
}
foreach (var typeDeclaration in typeDeclarations) {
semanticModel_ = generator_.GetSemanticModel(typeDeclaration.Node.SyntaxTree);
BuildTypeMembers(major.TypeDeclaration, typeDeclaration.Node);
}
CheckTypeDeclaration(major.Symbol, major.TypeDeclaration);
typeDeclarations_.Pop();
compilationUnits_.Pop();
major.TypeDeclaration.IsPartialMark = false;
major.CompilationUnit.AddTypeDeclarationCount();
}
private void GetTypeDeclarationName(BaseTypeDeclarationSyntax typeDeclaration, out LuaIdentifierNameSyntax name, out INamedTypeSymbol typeSymbol) {
typeSymbol = semanticModel_.GetDeclaredSymbol(typeDeclaration);
name = generator_.GetTypeDeclarationName(typeSymbol);
}
public override LuaSyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node) {
GetTypeDeclarationName(node, out var name, out var typeSymbol);
LuaClassDeclarationSyntax classDeclaration = new LuaClassDeclarationSyntax(name);
VisitTypeDeclaration(typeSymbol, node, classDeclaration);
return classDeclaration;
}
public override LuaSyntaxNode VisitStructDeclaration(StructDeclarationSyntax node) {
GetTypeDeclarationName(node, out var name, out var typeSymbol);
LuaStructDeclarationSyntax structDeclaration = new LuaStructDeclarationSyntax(name);
VisitTypeDeclaration(typeSymbol, node, structDeclaration);
return structDeclaration;
}
public override LuaSyntaxNode VisitInterfaceDeclaration(InterfaceDeclarationSyntax node) {
GetTypeDeclarationName(node, out var name, out var typeSymbol);
LuaInterfaceDeclarationSyntax interfaceDeclaration = new LuaInterfaceDeclarationSyntax(name);
var symbol = VisitTypeDeclaration(typeSymbol, node, interfaceDeclaration);
return interfaceDeclaration;
}
public override LuaSyntaxNode VisitEnumDeclaration(EnumDeclarationSyntax node) {
GetTypeDeclarationName(node, out var name, out var typeSymbol);
LuaEnumDeclarationSyntax enumDeclaration = new LuaEnumDeclarationSyntax(typeSymbol.ToString(), name, CurCompilationUnit);
typeDeclarations_.Push(new TypeDeclarationInfo(typeSymbol, enumDeclaration));
var document = BuildDocumentationComment(node);
enumDeclaration.AddDocument(document);
foreach (var member in node.Members) {
var statement = (LuaKeyValueTableItemSyntax)member.Accept(this);
enumDeclaration.Add(statement);
}
typeDeclarations_.Pop();
generator_.AddEnumDeclaration(typeSymbol, enumDeclaration);
return enumDeclaration;
}
public override LuaSyntaxNode VisitDelegateDeclaration(DelegateDeclarationSyntax node) {
return LuaStatementSyntax.Empty;
}
private void VisitYield(TypeSyntax returnType, LuaFunctionExpressionSyntax function) {
Contract.Assert(function.HasYield);
var retrurnTypeSymbol = semanticModel_.GetTypeInfo(returnType).Type;
string name = LuaSyntaxNode.Tokens.Yield + retrurnTypeSymbol.Name;
var memberAccess = new LuaMemberAccessExpressionSyntax(LuaIdentifierNameSyntax.System, new LuaIdentifierNameSyntax(name));
var invokeExpression = new LuaInvocationExpressionSyntax(memberAccess);
var wrapFunction = new LuaFunctionExpressionSyntax();
var parameters = function.ParameterList.Parameters;
wrapFunction.ParameterList.Parameters.AddRange(parameters);
wrapFunction.AddStatements(function.Body.Statements);
invokeExpression.AddArgument(wrapFunction);
if (returnType.IsKind(SyntaxKind.GenericName)) {
var genericNameSyntax = (GenericNameSyntax)returnType;
var typeName = genericNameSyntax.TypeArgumentList.Arguments.First();
var expression = (LuaExpressionSyntax)typeName.Accept(this);
invokeExpression.AddArgument(expression);
} else {
invokeExpression.AddArgument(LuaIdentifierNameSyntax.Object);
}
invokeExpression.ArgumentList.Arguments.AddRange(parameters.Select(i => new LuaArgumentSyntax(i.Identifier)));
var returnStatement = new LuaReturnStatementSyntax(invokeExpression);
function.Body.Statements.Clear();
function.AddStatement(returnStatement);
}
private void VisitAsync(bool returnsVoid, TypeSyntax returnType, LuaFunctionExpressionSyntax function) {
var memberAccess = new LuaMemberAccessExpressionSyntax(LuaIdentifierNameSyntax.System, LuaIdentifierNameSyntax.Async);
var invokeExpression = new LuaInvocationExpressionSyntax(memberAccess);
var wrapFunction = new LuaFunctionExpressionSyntax();
var parameters = function.ParameterList.Parameters;
wrapFunction.AddParameter(LuaIdentifierNameSyntax.Async);
wrapFunction.ParameterList.Parameters.AddRange(parameters);
wrapFunction.AddStatements(function.Body.Statements);
invokeExpression.AddArgument(wrapFunction);
invokeExpression.AddArgument(returnsVoid ? LuaIdentifierNameSyntax.True : LuaIdentifierNameSyntax.Nil);
invokeExpression.ArgumentList.Arguments.AddRange(parameters.Select(i => new LuaArgumentSyntax(i.Identifier)));
function.Body.Statements.Clear();
if (returnsVoid) {
function.AddStatement(invokeExpression);
} else {
function.AddStatement(new LuaReturnStatementSyntax(invokeExpression));
}
}
private sealed class MethodDeclarationResult {
public IMethodSymbol Symbol;
public LuaFunctionExpressionSyntax Function;
public bool IsPrivate;
public LuaIdentifierNameSyntax Name;
public LuaDocumentStatement Document;
}
private MethodDeclarationResult BuildMethodDeclaration(
CSharpSyntaxNode node,
SyntaxList<AttributeListSyntax> attributeLists,
ParameterListSyntax parameterList,
TypeParameterListSyntax typeParameterList,
BlockSyntax body,
ArrowExpressionClauseSyntax expressionBody,
TypeSyntax returnType) {
IMethodSymbol symbol = (IMethodSymbol)semanticModel_.GetDeclaredSymbol(node);
List<LuaExpressionSyntax> refOrOutParameters = new List<LuaExpressionSyntax>();
MethodInfo methodInfo = new MethodInfo(symbol, refOrOutParameters);
methodInfos_.Push(methodInfo);
LuaIdentifierNameSyntax methodName;
if (symbol.MethodKind == MethodKind.LocalFunction) {
methodName = new LuaIdentifierNameSyntax(symbol.Name);
CheckLocalVariableName(ref methodName, node);
} else {
methodName = GetMemberName(symbol);
}
LuaFunctionExpressionSyntax function = new LuaFunctionExpressionSyntax();
PushFunction(function);
var document = BuildDocumentationComment(node);
bool isPrivate = symbol.IsPrivate() && symbol.ExplicitInterfaceImplementations.IsEmpty;
if (!symbol.IsStatic) {
function.AddParameter(LuaIdentifierNameSyntax.This);
if (isPrivate) {
if (generator_.IsForcePublicSymbol(symbol) || generator_.IsMonoBehaviourSpeicalMethod(symbol)) {
isPrivate = false;
}
}
} else if (symbol.IsMainEntryPoint()) {
isPrivate = false;
bool success = generator_.SetMainEntryPoint(symbol);
if (!success) {
throw new CompilationErrorException(node, "has more than one entry point");
}
} else if (isPrivate && generator_.IsForcePublicSymbol(symbol)) {
isPrivate = false;
}
if (!symbol.IsPrivate()) {
var attributes = BuildAttributes(attributeLists);
CurType.AddMethodAttributes(methodName, attributes);
}
foreach (var parameterNode in parameterList.Parameters) {
var parameter = (LuaParameterSyntax)parameterNode.Accept(this);
function.AddParameter(parameter);
if (parameterNode.Modifiers.IsOutOrRef()) {
refOrOutParameters.Add(parameter.Identifier);
}
}
if (typeParameterList != null) {
var typeParameters = (LuaParameterListSyntax)typeParameterList.Accept(this);
function.AddParameters(typeParameters.Parameters);
}
if (body != null) {
LuaBlockSyntax block = (LuaBlockSyntax)body.Accept(this);
function.AddStatements(block.Statements);
} else {
blocks_.Push(function.Body);
var expression = (LuaExpressionSyntax)expressionBody.Accept(this);
blocks_.Pop();
if (symbol.ReturnsVoid) {
function.AddStatement(expression.ToStatement());
} else {
function.AddStatement(new LuaReturnStatementSyntax(expression));
}
}
if (function.HasYield) {
VisitYield(returnType, function);
} else if (symbol.IsAsync) {
VisitAsync(symbol.ReturnsVoid, returnType, function);
} else {
if (symbol.ReturnsVoid && refOrOutParameters.Count > 0) {
var returnStatement = new LuaMultipleReturnStatementSyntax();
returnStatement.Expressions.AddRange(refOrOutParameters);
function.AddStatement(returnStatement);
}
}
PopFunction();
methodInfos_.Pop();
return new MethodDeclarationResult {
Symbol = symbol,
Name = methodName,
Function = function,
IsPrivate = isPrivate,
Document = document,
};
}
public override LuaSyntaxNode VisitMethodDeclaration(MethodDeclarationSyntax node) {
if (!node.Modifiers.IsAbstract() && !node.Modifiers.IsExtern()) {
var result = BuildMethodDeclaration(node, node.AttributeLists, node.ParameterList, node.TypeParameterList, node.Body, node.ExpressionBody, node.ReturnType);
CurType.AddMethod(result.Name, result.Function, result.IsPrivate, result.Document);
return result.Function;
}
return base.VisitMethodDeclaration(node);
}
private static LuaExpressionSyntax GetPredefinedValueTypeDefaultValue(ITypeSymbol typeSymbol) {
switch (typeSymbol.SpecialType) {
case SpecialType.None: {
if (typeSymbol.TypeKind == TypeKind.Enum) {
return LuaIdentifierLiteralExpressionSyntax.Zero;
} else if (typeSymbol.IsTimeSpanType()) {
return BuildDefaultValue(LuaIdentifierNameSyntax.TimeSpan);
}
return null;
}
case SpecialType.System_Boolean: {
return new LuaIdentifierLiteralExpressionSyntax(LuaIdentifierNameSyntax.False);
}
case SpecialType.System_Char: {
return new LuaCharacterLiteralExpression(default(char));
}
case SpecialType.System_SByte:
case SpecialType.System_Byte:
case SpecialType.System_Int16:
case SpecialType.System_UInt16:
case SpecialType.System_Int32:
case SpecialType.System_UInt32:
case SpecialType.System_Int64:
case SpecialType.System_UInt64: {
return LuaIdentifierLiteralExpressionSyntax.Zero;
}
case SpecialType.System_Single:
case SpecialType.System_Double: {
return LuaIdentifierLiteralExpressionSyntax.ZeroFloat;
}
case SpecialType.System_DateTime: {
return BuildDefaultValue(LuaIdentifierNameSyntax.DateTime);
}
default:
return null;
}
}
private LuaIdentifierNameSyntax GetTempIdentifier(SyntaxNode node) {
int index = CurFunction.TempIndex++;
string name = LuaSyntaxNode.TempIdentifiers.GetOrDefault(index);
if (name == null) {
throw new CompilationErrorException(node, $"Your code is startling,{LuaSyntaxNode.TempIdentifiers.Length} temporary variables is not enough");
}
return new LuaIdentifierNameSyntax(name);
}
private static LuaInvocationExpressionSyntax BuildDefaultValue(LuaExpressionSyntax typeExpression) {
return new LuaInvocationExpressionSyntax(LuaIdentifierNameSyntax.SystemDefault, typeExpression);
}
private void VisitBaseFieldDeclarationSyntax(BaseFieldDeclarationSyntax node) {
if (!node.Modifiers.IsConst()) {
bool isStatic = node.Modifiers.IsStatic();
bool isPrivate = node.Modifiers.IsPrivate();
bool isReadOnly = node.Modifiers.IsReadOnly();
var type = node.Declaration.Type;
ITypeSymbol typeSymbol = (ITypeSymbol)semanticModel_.GetSymbolInfo(type).Symbol;
bool isImmutable = typeSymbol.IsImmutable();
foreach (var variable in node.Declaration.Variables) {
var variableSymbol = semanticModel_.GetDeclaredSymbol(variable);
if (node.IsKind(SyntaxKind.EventFieldDeclaration)) {
var eventSymbol = (IEventSymbol)variableSymbol;
if (!IsEventFiled(eventSymbol)) {
var eventName = GetMemberName(eventSymbol);
var innerName = AddInnerName(eventSymbol);
LuaExpressionSyntax valueExpression = GetFieldValueExpression(type, typeSymbol, variable.Initializer?.Value, out bool valueIsLiteral, out var statements);
LuaExpressionSyntax typeExpression = null;
if (isStatic) {
typeExpression = GetTypeName(eventSymbol.ContainingType);
}
CurType.AddEvent(eventName, innerName, valueExpression, isImmutable && valueIsLiteral, isStatic, isPrivate, typeExpression, statements);
continue;
}
} else {
if (!isStatic && isPrivate) {
var fieldSymbol = (IFieldSymbol)variableSymbol;
if (fieldSymbol.IsProtobufNetSpecialField(out string name)) {
AddField(new LuaIdentifierNameSyntax(name), typeSymbol, type, variable.Initializer?.Value, isImmutable, isStatic, isPrivate, isReadOnly, node.AttributeLists);
continue;
}
}
}
if (isPrivate && generator_.IsForcePublicSymbol(variableSymbol)) {
isPrivate = false;
}
LuaIdentifierNameSyntax fieldName = GetMemberName(variableSymbol);
AddField(fieldName, typeSymbol, type, variable.Initializer?.Value, isImmutable, isStatic, isPrivate, isReadOnly, node.AttributeLists);
}
} else {
bool isPrivate = node.Modifiers.IsPrivate();
var type = node.Declaration.Type;
ITypeSymbol typeSymbol = (ITypeSymbol)semanticModel_.GetSymbolInfo(type).Symbol;
if (typeSymbol.SpecialType == SpecialType.System_String) {
foreach (var variable in node.Declaration.Variables) {
var constValue = semanticModel_.GetConstantValue(variable.Initializer.Value);
Contract.Assert(constValue.HasValue);
string v = (string)constValue.Value;
if (v.Length > kStringConstInlineCount) {
var variableSymbol = semanticModel_.GetDeclaredSymbol(variable);
if (isPrivate && generator_.IsForcePublicSymbol(variableSymbol)) {
isPrivate = false;
}
LuaIdentifierNameSyntax fieldName = GetMemberName(variableSymbol);
AddField(fieldName, typeSymbol, type, variable.Initializer.Value, true, true, isPrivate, true, node.AttributeLists);
}
}
}
}
}
public override LuaSyntaxNode VisitFieldDeclaration(FieldDeclarationSyntax node) {
VisitBaseFieldDeclarationSyntax(node);
return base.VisitFieldDeclaration(node);
}
private LuaExpressionSyntax GetFieldValueExpression(TypeSyntax type, ITypeSymbol typeSymbol, ExpressionSyntax expression, out bool valueIsLiteral, out List<LuaStatementSyntax> statements) {
LuaExpressionSyntax valueExpression = null;
valueIsLiteral = false;
statements = null;
if (expression != null && !expression.IsKind(SyntaxKind.NullLiteralExpression)) {
var function = new LuaFunctionExpressionSyntax();
PushFunction(function);
blocks_.Push(function.Body);
valueExpression = (LuaExpressionSyntax)expression.Accept(this);
blocks_.Pop();
PopFunction();
if (function.Body.Statements.Count > 0) {
statements = function.Body.Statements;
}
valueIsLiteral = expression is LiteralExpressionSyntax;
}
if (valueExpression == null) {
if (typeSymbol.IsValueType && !typeSymbol.IsNullableType()) {
LuaExpressionSyntax defalutValue = GetPredefinedValueTypeDefaultValue(typeSymbol);
if (defalutValue != null) {
valueExpression = defalutValue;
valueIsLiteral = true;
} else {
valueExpression = GetDefaultValueExpression(typeSymbol);
}
}
}
return valueExpression;
}
private void AddField(LuaIdentifierNameSyntax name, ITypeSymbol typeSymbol, TypeSyntax type, ExpressionSyntax expression, bool isImmutable, bool isStatic, bool isPrivate, bool isReadOnly, SyntaxList<AttributeListSyntax> attributeLists) {
if (!(isStatic && isPrivate)) {
var attributes = BuildAttributes(attributeLists);
CurType.AddFieldAttributes(name, attributes);
}
LuaExpressionSyntax valueExpression = GetFieldValueExpression(type, typeSymbol, expression, out bool valueIsLiteral, out var statements);
CurType.AddField(name, valueExpression, isImmutable && valueIsLiteral, isStatic, isPrivate, isReadOnly, statements);
}
public override LuaSyntaxNode VisitPropertyDeclaration(PropertyDeclarationSyntax node) {
if (!node.Modifiers.IsAbstract()) {
var symbol = semanticModel_.GetDeclaredSymbol(node);
if (symbol.IsProtobufNetSpecialProperty()) {
return null;
}
bool isStatic = symbol.IsStatic;
bool isPrivate = symbol.IsPrivate();
bool hasGet = false;
bool hasSet = false;
if (isPrivate && generator_.IsForcePublicSymbol(symbol)) {
isPrivate = false;
}
LuaIdentifierNameSyntax propertyName = GetMemberName(symbol);
if (node.AccessorList != null) {
foreach (var accessor in node.AccessorList.Accessors) {
if (accessor.Body != null || accessor.ExpressionBody != null) {
bool isGet = accessor.IsKind(SyntaxKind.GetAccessorDeclaration);
LuaFunctionExpressionSyntax functionExpression = new LuaFunctionExpressionSyntax();
if (!isStatic) {
functionExpression.AddParameter(LuaIdentifierNameSyntax.This);
}
PushFunction(functionExpression);
if (accessor.Body != null) {
var block = (LuaBlockSyntax)accessor.Body.Accept(this);
functionExpression.AddStatements(block.Statements);
} else {
blocks_.Push(functionExpression.Body);
var bodyExpression = (LuaExpressionSyntax)accessor.ExpressionBody.Accept(this);
blocks_.Pop();
if (isGet) {
functionExpression.AddStatement(new LuaReturnStatementSyntax(bodyExpression));
} else {
functionExpression.AddStatement(bodyExpression);
}
}
PopFunction();
LuaPropertyOrEventIdentifierNameSyntax name = new LuaPropertyOrEventIdentifierNameSyntax(true, propertyName);
CurType.AddMethod(name, functionExpression, isPrivate);
if (isGet) {
Contract.Assert(!hasGet);
hasGet = true;
} else {
Contract.Assert(!hasSet);
functionExpression.AddParameter(LuaIdentifierNameSyntax.Value);
name.IsGetOrAdd = false;
hasSet = true;
}
if (!isPrivate) {
var attributes = BuildAttributes(accessor.AttributeLists);
CurType.AddMethodAttributes(name, attributes);
}
}
}
} else {
Contract.Assert(!hasGet);
LuaPropertyOrEventIdentifierNameSyntax name = new LuaPropertyOrEventIdentifierNameSyntax(true, propertyName);
LuaFunctionExpressionSyntax functionExpression = new LuaFunctionExpressionSyntax();
PushFunction(functionExpression);
blocks_.Push(functionExpression.Body);
var expression = (LuaExpressionSyntax)node.ExpressionBody.Accept(this);
blocks_.Pop();
PopFunction();
if (!isStatic) {
functionExpression.AddParameter(LuaIdentifierNameSyntax.This);
}
LuaReturnStatementSyntax returnStatement = new LuaReturnStatementSyntax(expression);
functionExpression.AddStatement(returnStatement);
CurType.AddMethod(name, functionExpression, isPrivate);
hasGet = true;
}
if (!hasGet && !hasSet) {
ITypeSymbol typeSymbol = symbol.Type;
bool isImmutable = typeSymbol.IsImmutable();
bool isField = IsPropertyField(semanticModel_.GetDeclaredSymbol(node));
if (isField) {
bool isReadOnly = IsReadOnlyProperty(node);
AddField(propertyName, typeSymbol, node.Type, node.Initializer?.Value, isImmutable, isStatic, isPrivate, isReadOnly, node.AttributeLists);
} else {
if (!isPrivate) {
var attributes = BuildAttributes(node.AttributeLists);
CurType.AddFieldAttributes(propertyName, attributes);
}
LuaIdentifierNameSyntax innerName = AddInnerName(symbol);
LuaExpressionSyntax valueExpression = GetFieldValueExpression(node.Type, typeSymbol, node.Initializer?.Value, out bool valueIsLiteral, out var statements);
LuaExpressionSyntax typeExpression = null;
if (isStatic) {
typeExpression = GetTypeName(symbol.ContainingType);
}
CurType.AddProperty(propertyName, innerName, valueExpression, isImmutable && valueIsLiteral, isStatic, isPrivate, typeExpression, statements);
}
} else {
if (!isPrivate) {
var attributes = BuildAttributes(node.AttributeLists);
CurType.AddFieldAttributes(propertyName, attributes);
}
}
}
return base.VisitPropertyDeclaration(node);
}
private bool IsReadOnlyProperty(PropertyDeclarationSyntax node) {
return node.AccessorList.Accessors.Count == 1 && node.AccessorList.Accessors[0].Body == null;
}
public override LuaSyntaxNode VisitEventDeclaration(EventDeclarationSyntax node) {
if (!node.Modifiers.IsAbstract()) {
var symbol = semanticModel_.GetDeclaredSymbol(node);
bool isStatic = symbol.IsStatic;
bool isPrivate = symbol.IsPrivate();
LuaIdentifierNameSyntax eventName = GetMemberName(symbol);
foreach (var accessor in node.AccessorList.Accessors) {
LuaFunctionExpressionSyntax functionExpression = new LuaFunctionExpressionSyntax();
if (!isStatic) {
functionExpression.AddParameter(LuaIdentifierNameSyntax.This);
}
functionExpression.AddParameter(LuaIdentifierNameSyntax.Value);
PushFunction(functionExpression);
var block = (LuaBlockSyntax)accessor.Body.Accept(this);
PopFunction();
functionExpression.AddStatements(block.Statements);
LuaPropertyOrEventIdentifierNameSyntax name = new LuaPropertyOrEventIdentifierNameSyntax(false, eventName);
CurType.AddMethod(name, functionExpression, isPrivate);
if (accessor.IsKind(SyntaxKind.RemoveAccessorDeclaration)) {
name.IsGetOrAdd = false;
}
if (!isPrivate) {
var attributes = BuildAttributes(accessor.AttributeLists);
CurType.AddMethodAttributes(name, attributes);
}
}
}
return base.VisitEventDeclaration(node);
}
public override LuaSyntaxNode VisitEventFieldDeclaration(EventFieldDeclarationSyntax node) {
VisitBaseFieldDeclarationSyntax(node);
return base.VisitEventFieldDeclaration(node);
}
public override LuaSyntaxNode VisitEnumMemberDeclaration(EnumMemberDeclarationSyntax node) {
IFieldSymbol symbol = semanticModel_.GetDeclaredSymbol(node);
Contract.Assert(symbol.HasConstantValue);
LuaIdentifierNameSyntax identifier = new LuaIdentifierNameSyntax(node.Identifier.ValueText);
var value = new LuaIdentifierLiteralExpressionSyntax(symbol.ConstantValue.ToString());
return new LuaKeyValueTableItemSyntax(new LuaTableLiteralKeySyntax(identifier), value);
}
public override LuaSyntaxNode VisitIndexerDeclaration(IndexerDeclarationSyntax node) {
if (!node.Modifiers.IsAbstract()) {
var symbol = semanticModel_.GetDeclaredSymbol(node);
bool isPrivate = symbol.IsPrivate();
LuaIdentifierNameSyntax indexName = GetMemberName(symbol);
var parameterList = (LuaParameterListSyntax)node.ParameterList.Accept(this);
void Fill(Action<LuaFunctionExpressionSyntax, LuaPropertyOrEventIdentifierNameSyntax> action) {
LuaFunctionExpressionSyntax function = new LuaFunctionExpressionSyntax();
function.AddParameter(LuaIdentifierNameSyntax.This);
function.ParameterList.Parameters.AddRange(parameterList.Parameters);
LuaPropertyOrEventIdentifierNameSyntax name = new LuaPropertyOrEventIdentifierNameSyntax(true, indexName);
PushFunction(function);
action(function, name);
PopFunction();
CurType.AddMethod(name, function, isPrivate);
}
if (node.AccessorList != null) {
foreach (var accessor in node.AccessorList.Accessors) {
Fill((function, name) => {
bool isGet = accessor.IsKind(SyntaxKind.GetAccessorDeclaration);
if (accessor.Body != null) {
var block = (LuaBlockSyntax)accessor.Body.Accept(this);
function.AddStatements(block.Statements);
} else {
var bodyExpression = (LuaExpressionSyntax)accessor.ExpressionBody.Accept(this);
if (isGet) {
function.AddStatement(new LuaReturnStatementSyntax(bodyExpression));
} else {
function.AddStatement(bodyExpression);
}
}
if (!isGet) {
function.AddParameter(LuaIdentifierNameSyntax.Value);
name.IsGetOrAdd = false;
}
});
}
} else {
Fill((function, name) => {
var bodyExpression = (LuaExpressionSyntax)node.ExpressionBody.Accept(this);
function.AddStatement(bodyExpression);
});
}
}
return base.VisitIndexerDeclaration(node);
}