This repository was archived by the owner on Oct 16, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 805
Expand file tree
/
Copy pathCodeDomConvertVisitor.cs
More file actions
1449 lines (1278 loc) · 52.6 KB
/
CodeDomConvertVisitor.cs
File metadata and controls
1449 lines (1278 loc) · 52.6 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 (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.CodeDom;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using ICSharpCode.NRefactory.CSharp.Refactoring;
using ICSharpCode.NRefactory.CSharp.Resolver;
using ICSharpCode.NRefactory.CSharp.TypeSystem;
using ICSharpCode.NRefactory.PatternMatching;
using ICSharpCode.NRefactory.Semantics;
using ICSharpCode.NRefactory.TypeSystem;
namespace ICSharpCode.NRefactory.CSharp
{
/// <summary>
/// Converts from C# AST to CodeDom.
/// </summary>
/// <remarks>
/// The conversion is intended for use in the SharpDevelop forms designer.
/// </remarks>
public class CodeDomConvertVisitor : IAstVisitor<CodeObject>
{
CSharpAstResolver resolver;
/// <summary>
/// Gets/Sets whether the visitor should convert short type names into
/// fully qualified type names.
/// The default is <c>false</c>.
/// </summary>
public bool UseFullyQualifiedTypeNames { get; set; }
/// <summary>
/// Gets whether the visitor is allowed to produce snippet nodes for
/// code that cannot be converted.
/// The default is <c>true</c>. If this property is set to <c>false</c>,
/// unconvertible code will throw a NotSupportedException.
/// </summary>
public bool AllowSnippetNodes { get; set; }
public CodeDomConvertVisitor()
{
this.AllowSnippetNodes = true;
}
/// <summary>
/// Converts a syntax tree to CodeDom.
/// </summary>
/// <param name="syntaxTree">The input syntax tree.</param>
/// <param name="compilation">The current compilation.</param>
/// <param name="unresolvedFile">CSharpUnresolvedFile, used for resolving.</param>
/// <returns>Converted CodeCompileUnit</returns>
/// <remarks>
/// This conversion process requires a resolver because it needs to distinguish field/property/event references etc.
/// </remarks>
public CodeCompileUnit Convert(ICompilation compilation, SyntaxTree syntaxTree, CSharpUnresolvedFile unresolvedFile)
{
if (syntaxTree == null)
throw new ArgumentNullException("syntaxTree");
if (compilation == null)
throw new ArgumentNullException("compilation");
CSharpAstResolver resolver = new CSharpAstResolver(compilation, syntaxTree, unresolvedFile);
return (CodeCompileUnit)Convert(syntaxTree, resolver);
}
/// <summary>
/// Converts a C# AST node to CodeDom.
/// </summary>
/// <param name="node">The input node.</param>
/// <param name="resolver">The AST resolver.</param>
/// <returns>The node converted into CodeDom</returns>
/// <remarks>
/// This conversion process requires a resolver because it needs to distinguish field/property/event references etc.
/// </remarks>
public CodeObject Convert(AstNode node, CSharpAstResolver resolver)
{
if (node == null)
throw new ArgumentNullException("node");
if (resolver == null)
throw new ArgumentNullException("resolver");
try {
this.resolver = resolver;
return node.AcceptVisitor(this);
} finally {
this.resolver = null;
}
}
ResolveResult Resolve(AstNode node)
{
if (resolver == null)
return ErrorResolveResult.UnknownError;
else
return resolver.Resolve(node);
}
CodeExpression Convert(Expression expr)
{
return (CodeExpression)expr.AcceptVisitor(this);
}
CodeExpression[] Convert(IEnumerable<Expression> expressions)
{
List<CodeExpression> result = new List<CodeExpression>();
foreach (Expression expr in expressions) {
CodeExpression e = Convert(expr);
if (e != null)
result.Add(e);
}
return result.ToArray();
}
CodeTypeReference Convert(AstType type)
{
return (CodeTypeReference)type.AcceptVisitor(this);
}
CodeTypeReference[] Convert(IEnumerable<AstType> types)
{
List<CodeTypeReference> result = new List<CodeTypeReference>();
foreach (AstType type in types) {
CodeTypeReference e = Convert(type);
if (e != null)
result.Add(e);
}
return result.ToArray();
}
public CodeTypeReference Convert(IType type)
{
if (type.Kind == TypeKind.Array) {
ArrayType a = (ArrayType)type;
return new CodeTypeReference(Convert(a.ElementType), a.Dimensions);
} else if (type is ParameterizedType) {
var pt = (ParameterizedType)type;
return new CodeTypeReference(pt.GetDefinition().ReflectionName, pt.TypeArguments.Select(Convert).ToArray());
} else {
return new CodeTypeReference(type.ReflectionName);
}
}
CodeStatement Convert(Statement stmt)
{
return (CodeStatement)stmt.AcceptVisitor(this);
}
CodeStatement[] ConvertBlock(BlockStatement block)
{
List<CodeStatement> result = new List<CodeStatement>();
foreach (Statement stmt in block.Statements) {
if (stmt is EmptyStatement)
continue;
CodeStatement s = Convert(stmt);
if (s != null)
result.Add(s);
}
return result.ToArray();
}
CodeStatement[] ConvertEmbeddedStatement(Statement embeddedStatement)
{
BlockStatement block = embeddedStatement as BlockStatement;
if (block != null) {
return ConvertBlock(block);
} else if (embeddedStatement is EmptyStatement) {
return new CodeStatement[0];
}
CodeStatement s = Convert(embeddedStatement);
if (s != null)
return new CodeStatement[] { s };
else
return new CodeStatement[0];
}
string MakeSnippet(AstNode node)
{
if (!AllowSnippetNodes)
throw new NotSupportedException();
StringWriter w = new StringWriter();
CSharpOutputVisitor v = new CSharpOutputVisitor(w, FormattingOptionsFactory.CreateMono ());
node.AcceptVisitor(v);
return w.ToString();
}
/// <summary>
/// Converts an expression by storing it as C# snippet.
/// This is used for expressions that cannot be represented in CodeDom.
/// </summary>
CodeSnippetExpression MakeSnippetExpression(Expression expr)
{
return new CodeSnippetExpression(MakeSnippet(expr));
}
CodeSnippetStatement MakeSnippetStatement(Statement stmt)
{
return new CodeSnippetStatement(MakeSnippet(stmt));
}
CodeObject IAstVisitor<CodeObject>.VisitNullNode(AstNode nullNode)
{
return null;
}
CodeObject IAstVisitor<CodeObject>.VisitErrorNode(AstNode errorNode)
{
return null;
}
CodeObject IAstVisitor<CodeObject>.VisitAnonymousMethodExpression(AnonymousMethodExpression anonymousMethodExpression)
{
return MakeSnippetExpression(anonymousMethodExpression);
}
CodeObject IAstVisitor<CodeObject>.VisitUndocumentedExpression(UndocumentedExpression undocumentedExpression)
{
return MakeSnippetExpression(undocumentedExpression);
}
CodeObject IAstVisitor<CodeObject>.VisitArrayCreateExpression(ArrayCreateExpression arrayCreateExpression)
{
CodeArrayCreateExpression ace = new CodeArrayCreateExpression();
int dimensions = arrayCreateExpression.Arguments.Count;
int nestingDepth = arrayCreateExpression.AdditionalArraySpecifiers.Count;
if (dimensions > 0)
nestingDepth++;
if (nestingDepth > 1 || dimensions > 1) {
// CodeDom does not support jagged or multi-dimensional arrays
return MakeSnippetExpression(arrayCreateExpression);
}
if (arrayCreateExpression.Type.IsNull) {
ace.CreateType = Convert(Resolve(arrayCreateExpression).Type);
} else {
ace.CreateType = Convert(arrayCreateExpression.Type);
}
if (arrayCreateExpression.Arguments.Count == 1) {
ace.SizeExpression = Convert(arrayCreateExpression.Arguments.Single());
}
ace.Initializers.AddRange(Convert(arrayCreateExpression.Initializer.Elements));
return ace;
}
CodeObject IAstVisitor<CodeObject>.VisitArrayInitializerExpression(ArrayInitializerExpression arrayInitializerExpression)
{
// Array initializers should be handled by the parent node
return MakeSnippetExpression(arrayInitializerExpression);
}
CodeObject IAstVisitor<CodeObject>.VisitAsExpression(AsExpression asExpression)
{
return MakeSnippetExpression(asExpression);
}
CodeObject IAstVisitor<CodeObject>.VisitAssignmentExpression(AssignmentExpression assignmentExpression)
{
// assignments are only supported as statements, not as expressions
return MakeSnippetExpression(assignmentExpression);
}
CodeObject IAstVisitor<CodeObject>.VisitBaseReferenceExpression(BaseReferenceExpression baseReferenceExpression)
{
return new CodeBaseReferenceExpression();
}
CodeObject IAstVisitor<CodeObject>.VisitBinaryOperatorExpression(BinaryOperatorExpression binaryOperatorExpression)
{
CodeBinaryOperatorType op;
switch (binaryOperatorExpression.Operator) {
case BinaryOperatorType.BitwiseAnd:
op = CodeBinaryOperatorType.BitwiseAnd;
break;
case BinaryOperatorType.BitwiseOr:
op = CodeBinaryOperatorType.BitwiseOr;
break;
case BinaryOperatorType.ConditionalAnd:
op = CodeBinaryOperatorType.BooleanAnd;
break;
case BinaryOperatorType.ConditionalOr:
op = CodeBinaryOperatorType.BooleanOr;
break;
case BinaryOperatorType.GreaterThan:
op = CodeBinaryOperatorType.GreaterThan;
break;
case BinaryOperatorType.GreaterThanOrEqual:
op = CodeBinaryOperatorType.GreaterThanOrEqual;
break;
case BinaryOperatorType.LessThan:
op = CodeBinaryOperatorType.LessThan;
break;
case BinaryOperatorType.LessThanOrEqual:
op = CodeBinaryOperatorType.LessThanOrEqual;
break;
case BinaryOperatorType.Add:
op = CodeBinaryOperatorType.Add;
break;
case BinaryOperatorType.Subtract:
op = CodeBinaryOperatorType.Subtract;
break;
case BinaryOperatorType.Multiply:
op = CodeBinaryOperatorType.Multiply;
break;
case BinaryOperatorType.Divide:
op = CodeBinaryOperatorType.Divide;
break;
case BinaryOperatorType.Modulus:
op = CodeBinaryOperatorType.Modulus;
break;
case BinaryOperatorType.Equality:
case BinaryOperatorType.InEquality:
OperatorResolveResult rr = Resolve(binaryOperatorExpression) as OperatorResolveResult;
if (rr != null && rr.GetChildResults().Any(cr => cr.Type.IsReferenceType == true)) {
if (binaryOperatorExpression.Operator == BinaryOperatorType.Equality)
op = CodeBinaryOperatorType.IdentityEquality;
else
op = CodeBinaryOperatorType.IdentityInequality;
} else {
if (binaryOperatorExpression.Operator == BinaryOperatorType.Equality) {
op = CodeBinaryOperatorType.ValueEquality;
} else {
// CodeDom is retarded and does not support ValueInequality, so we'll simulate it using
// ValueEquality and Not... but CodeDom doesn't have Not either, so we use
// '(a == b) == false'
return new CodeBinaryOperatorExpression(
new CodeBinaryOperatorExpression(
Convert(binaryOperatorExpression.Left),
CodeBinaryOperatorType.ValueEquality,
Convert(binaryOperatorExpression.Right)
),
CodeBinaryOperatorType.ValueEquality,
new CodePrimitiveExpression(false)
);
}
}
break;
default:
// not supported: xor, shift, null coalescing
return MakeSnippetExpression(binaryOperatorExpression);
}
return new CodeBinaryOperatorExpression(Convert(binaryOperatorExpression.Left), op, Convert(binaryOperatorExpression.Right));
}
CodeObject IAstVisitor<CodeObject>.VisitCastExpression(CastExpression castExpression)
{
return new CodeCastExpression(Convert(castExpression.Type), Convert(castExpression.Expression));
}
CodeObject IAstVisitor<CodeObject>.VisitCheckedExpression(CheckedExpression checkedExpression)
{
return MakeSnippetExpression(checkedExpression);
}
CodeObject IAstVisitor<CodeObject>.VisitConditionalExpression(ConditionalExpression conditionalExpression)
{
return MakeSnippetExpression(conditionalExpression);
}
CodeObject IAstVisitor<CodeObject>.VisitDefaultValueExpression(DefaultValueExpression defaultValueExpression)
{
return new CodeDefaultValueExpression(Convert(defaultValueExpression.Type));
}
CodeObject IAstVisitor<CodeObject>.VisitDirectionExpression(DirectionExpression directionExpression)
{
System.CodeDom.FieldDirection direction;
if (directionExpression.FieldDirection == FieldDirection.Out) {
direction = System.CodeDom.FieldDirection.Out;
} else {
direction = System.CodeDom.FieldDirection.Ref;
}
return new CodeDirectionExpression(direction, Convert(directionExpression.Expression));
}
CodeObject IAstVisitor<CodeObject>.VisitIdentifierExpression(IdentifierExpression identifierExpression)
{
ResolveResult rr = Resolve(identifierExpression);
LocalResolveResult lrr = rr as LocalResolveResult;
if (lrr != null && lrr.IsParameter) {
if (lrr.Variable.Name == "value" && identifierExpression.Ancestors.Any(a => a is Accessor)) {
return new CodePropertySetValueReferenceExpression();
} else {
return new CodeArgumentReferenceExpression(lrr.Variable.Name);
}
}
MemberResolveResult mrr = rr as MemberResolveResult;
if (mrr != null) {
return HandleMemberReference(null, identifierExpression.Identifier, identifierExpression.TypeArguments, mrr);
}
TypeResolveResult trr = rr as TypeResolveResult;
if (trr != null) {
CodeTypeReference typeRef;
if (UseFullyQualifiedTypeNames) {
typeRef = Convert(trr.Type);
} else {
typeRef = new CodeTypeReference(identifierExpression.Identifier);
typeRef.TypeArguments.AddRange(Convert(identifierExpression.TypeArguments));
}
return new CodeTypeReferenceExpression(typeRef);
}
MethodGroupResolveResult mgrr = rr as MethodGroupResolveResult;
if (mgrr != null || identifierExpression.TypeArguments.Any()) {
return new CodeMethodReferenceExpression(new CodeThisReferenceExpression(), identifierExpression.Identifier, Convert(identifierExpression.TypeArguments));
}
return new CodeVariableReferenceExpression(identifierExpression.Identifier);
}
CodeObject IAstVisitor<CodeObject>.VisitIndexerExpression(IndexerExpression indexerExpression)
{
if (Resolve(indexerExpression) is ArrayAccessResolveResult)
return new CodeArrayIndexerExpression(Convert(indexerExpression.Target), Convert(indexerExpression.Arguments));
else
return new CodeIndexerExpression(Convert(indexerExpression.Target), Convert(indexerExpression.Arguments));
}
CodeObject IAstVisitor<CodeObject>.VisitInvocationExpression(InvocationExpression invocationExpression)
{
MemberResolveResult rr = Resolve(invocationExpression) as MemberResolveResult;
CSharpInvocationResolveResult csRR = rr as CSharpInvocationResolveResult;
if (csRR != null && csRR.IsDelegateInvocation) {
return new CodeDelegateInvokeExpression(Convert(invocationExpression.Target), Convert(invocationExpression.Arguments));
}
Expression methodExpr = invocationExpression.Target;
while (methodExpr is ParenthesizedExpression)
methodExpr = ((ParenthesizedExpression)methodExpr).Expression;
CodeMethodReferenceExpression mr = null;
MemberReferenceExpression mre = methodExpr as MemberReferenceExpression;
if (mre != null) {
mr = new CodeMethodReferenceExpression(Convert(mre.Target), mre.MemberName, Convert(mre.TypeArguments));
}
IdentifierExpression id = methodExpr as IdentifierExpression;
if (id != null) {
CodeExpression target;
if (rr != null && rr.Member.IsStatic)
target = new CodeTypeReferenceExpression(Convert(rr.Member.DeclaringType));
else
target = new CodeThisReferenceExpression();
mr = new CodeMethodReferenceExpression(target, id.Identifier, Convert(id.TypeArguments));
}
if (mr != null)
return new CodeMethodInvokeExpression(mr, Convert(invocationExpression.Arguments));
else
return MakeSnippetExpression(invocationExpression);
}
CodeObject IAstVisitor<CodeObject>.VisitIsExpression(IsExpression isExpression)
{
return MakeSnippetExpression(isExpression);
}
CodeObject IAstVisitor<CodeObject>.VisitLambdaExpression(LambdaExpression lambdaExpression)
{
return MakeSnippetExpression(lambdaExpression);
}
CodeObject IAstVisitor<CodeObject>.VisitMemberReferenceExpression(MemberReferenceExpression memberReferenceExpression)
{
CodeExpression target = Convert(memberReferenceExpression.Target);
ResolveResult rr = Resolve(memberReferenceExpression);
MemberResolveResult mrr = rr as MemberResolveResult;
TypeResolveResult trr = rr as TypeResolveResult;
if (mrr != null) {
return HandleMemberReference(target, memberReferenceExpression.MemberName, memberReferenceExpression.TypeArguments, mrr);
} else if (trr != null) {
return new CodeTypeReferenceExpression(Convert(trr.Type));
} else {
if (memberReferenceExpression.TypeArguments.Any() || rr is MethodGroupResolveResult) {
return new CodeMethodReferenceExpression(target, memberReferenceExpression.MemberName, Convert(memberReferenceExpression.TypeArguments));
} else {
return new CodePropertyReferenceExpression(target, memberReferenceExpression.MemberName);
}
}
}
CodeExpression HandleMemberReference(CodeExpression target, string identifier, AstNodeCollection<AstType> typeArguments, MemberResolveResult mrr)
{
if (target == null) {
if (mrr.Member.IsStatic)
target = new CodeTypeReferenceExpression(Convert(mrr.Member.DeclaringType));
else
target = new CodeThisReferenceExpression();
}
if (mrr.Member is IField) {
return new CodeFieldReferenceExpression(target, identifier);
} else if (mrr.Member is IMethod) {
return new CodeMethodReferenceExpression(target, identifier, Convert(typeArguments));
} else if (mrr.Member is IEvent) {
return new CodeEventReferenceExpression(target, identifier);
} else {
return new CodePropertyReferenceExpression(target, identifier);
}
}
CodeObject IAstVisitor<CodeObject>.VisitNamedArgumentExpression(NamedArgumentExpression namedArgumentExpression)
{
return MakeSnippetExpression(namedArgumentExpression);
}
CodeObject IAstVisitor<CodeObject>.VisitNamedExpression(NamedExpression namedExpression)
{
return MakeSnippetExpression(namedExpression);
}
CodeObject IAstVisitor<CodeObject>.VisitNullReferenceExpression(NullReferenceExpression nullReferenceExpression)
{
return new CodePrimitiveExpression(null);
}
CodeObject IAstVisitor<CodeObject>.VisitObjectCreateExpression(ObjectCreateExpression objectCreateExpression)
{
if (!objectCreateExpression.Initializer.IsNull)
return MakeSnippetExpression(objectCreateExpression);
return new CodeObjectCreateExpression(Convert(objectCreateExpression.Type), Convert(objectCreateExpression.Arguments));
}
CodeObject IAstVisitor<CodeObject>.VisitAnonymousTypeCreateExpression(AnonymousTypeCreateExpression anonymousTypeCreateExpression)
{
return MakeSnippetExpression(anonymousTypeCreateExpression);
}
CodeObject IAstVisitor<CodeObject>.VisitParenthesizedExpression(ParenthesizedExpression parenthesizedExpression)
{
// CodeDom generators will insert parentheses where necessary
return Convert(parenthesizedExpression.Expression);
}
CodeObject IAstVisitor<CodeObject>.VisitPointerReferenceExpression(PointerReferenceExpression pointerReferenceExpression)
{
return MakeSnippetExpression(pointerReferenceExpression);
}
CodeObject IAstVisitor<CodeObject>.VisitPrimitiveExpression(PrimitiveExpression primitiveExpression)
{
return new CodePrimitiveExpression(primitiveExpression.Value);
}
CodeObject IAstVisitor<CodeObject>.VisitSizeOfExpression(SizeOfExpression sizeOfExpression)
{
return MakeSnippetExpression(sizeOfExpression);
}
CodeObject IAstVisitor<CodeObject>.VisitStackAllocExpression(StackAllocExpression stackAllocExpression)
{
return MakeSnippetExpression(stackAllocExpression);
}
CodeObject IAstVisitor<CodeObject>.VisitThisReferenceExpression(ThisReferenceExpression thisReferenceExpression)
{
return new CodeThisReferenceExpression();
}
CodeObject IAstVisitor<CodeObject>.VisitTypeOfExpression(TypeOfExpression typeOfExpression)
{
return new CodeTypeOfExpression(Convert(typeOfExpression.Type));
}
CodeObject IAstVisitor<CodeObject>.VisitTypeReferenceExpression(TypeReferenceExpression typeReferenceExpression)
{
return new CodeTypeReferenceExpression(Convert(typeReferenceExpression.Type));
}
CodeObject IAstVisitor<CodeObject>.VisitUnaryOperatorExpression(UnaryOperatorExpression unaryOperatorExpression)
{
switch (unaryOperatorExpression.Operator) {
case UnaryOperatorType.Not:
return new CodeBinaryOperatorExpression(
Convert(unaryOperatorExpression.Expression),
CodeBinaryOperatorType.ValueEquality,
new CodePrimitiveExpression(false));
case UnaryOperatorType.Minus:
//HACK: workaround for CodeDomSerializerBase::ExecuteMathOperator()
string source = unaryOperatorExpression.Expression.ToString();
switch (source[source.Length-1]) {
case 'F':
float fVal = float.Parse(source.Substring(0, source.Length-1));
return new CodeBinaryOperatorExpression(
new CodePrimitiveExpression(-fVal),
CodeBinaryOperatorType.Add,
new CodePrimitiveExpression(0));
case 'D':
double dVal = double.Parse(source.Substring(0, source.Length-1));
return new CodeBinaryOperatorExpression(
new CodePrimitiveExpression(-dVal),
CodeBinaryOperatorType.Add,
new CodePrimitiveExpression(0));
default:
long lVal = long.Parse(source);
return new CodeBinaryOperatorExpression(
new CodePrimitiveExpression(-lVal),
CodeBinaryOperatorType.Add,
new CodePrimitiveExpression(0));
}
case UnaryOperatorType.Plus:
return Convert(unaryOperatorExpression.Expression);
default:
return MakeSnippetExpression(unaryOperatorExpression);
}
}
CodeObject IAstVisitor<CodeObject>.VisitUncheckedExpression(UncheckedExpression uncheckedExpression)
{
return MakeSnippetExpression(uncheckedExpression);
}
CodeObject IAstVisitor<CodeObject>.VisitQueryExpression(QueryExpression queryExpression)
{
return MakeSnippetExpression(queryExpression);
}
CodeObject IAstVisitor<CodeObject>.VisitQueryContinuationClause(QueryContinuationClause queryContinuationClause)
{
throw new NotSupportedException();
}
CodeObject IAstVisitor<CodeObject>.VisitQueryFromClause(QueryFromClause queryFromClause)
{
throw new NotSupportedException();
}
CodeObject IAstVisitor<CodeObject>.VisitQueryLetClause(QueryLetClause queryLetClause)
{
throw new NotSupportedException();
}
CodeObject IAstVisitor<CodeObject>.VisitQueryWhereClause(QueryWhereClause queryWhereClause)
{
throw new NotSupportedException();
}
CodeObject IAstVisitor<CodeObject>.VisitQueryJoinClause(QueryJoinClause queryJoinClause)
{
throw new NotSupportedException();
}
CodeObject IAstVisitor<CodeObject>.VisitQueryOrderClause(QueryOrderClause queryOrderClause)
{
throw new NotSupportedException();
}
CodeObject IAstVisitor<CodeObject>.VisitQueryOrdering(QueryOrdering queryOrdering)
{
throw new NotSupportedException();
}
CodeObject IAstVisitor<CodeObject>.VisitQuerySelectClause(QuerySelectClause querySelectClause)
{
throw new NotSupportedException();
}
CodeObject IAstVisitor<CodeObject>.VisitQueryGroupClause(QueryGroupClause queryGroupClause)
{
throw new NotSupportedException();
}
CodeObject IAstVisitor<CodeObject>.VisitAttribute(Attribute attribute)
{
throw new NotSupportedException();
}
CodeObject IAstVisitor<CodeObject>.VisitAttributeSection(AttributeSection attributeSection)
{
throw new NotSupportedException();
}
CodeAttributeDeclaration Convert(Attribute attribute)
{
var attr = new CodeAttributeDeclaration(Convert(attribute.Type));
foreach (Expression expr in attribute.Arguments) {
NamedExpression ne = expr as NamedExpression;
if (ne != null)
attr.Arguments.Add(new CodeAttributeArgument(ne.Name, Convert(ne.Expression)));
else
attr.Arguments.Add(new CodeAttributeArgument(Convert(expr)));
}
return attr;
}
CodeAttributeDeclaration[] Convert(IEnumerable<AttributeSection> attributeSections)
{
List<CodeAttributeDeclaration> result = new List<CodeAttributeDeclaration>();
foreach (AttributeSection section in attributeSections) {
foreach (Attribute attr in section.Attributes) {
CodeAttributeDeclaration attrDecl = Convert(attr);
if (attrDecl != null)
result.Add(attrDecl);
}
}
return result.ToArray();
}
CodeObject IAstVisitor<CodeObject>.VisitDelegateDeclaration(DelegateDeclaration delegateDeclaration)
{
CodeTypeDelegate d = new CodeTypeDelegate(delegateDeclaration.Name);
d.Attributes = ConvertMemberAttributes(delegateDeclaration.Modifiers, SymbolKind.TypeDefinition);
d.CustomAttributes.AddRange(Convert(delegateDeclaration.Attributes));
d.ReturnType = Convert(delegateDeclaration.ReturnType);
d.Parameters.AddRange(Convert(delegateDeclaration.Parameters));
d.TypeParameters.AddRange(ConvertTypeParameters(delegateDeclaration.TypeParameters, delegateDeclaration.Constraints));
return d;
}
MemberAttributes ConvertMemberAttributes(Modifiers modifiers, SymbolKind symbolKind)
{
MemberAttributes a = 0;
if ((modifiers & Modifiers.Abstract) != 0)
a |= MemberAttributes.Abstract;
if ((modifiers & Modifiers.Sealed) != 0)
a |= MemberAttributes.Final;
if (symbolKind != SymbolKind.TypeDefinition && (modifiers & (Modifiers.Abstract | Modifiers.Override | Modifiers.Virtual)) == 0)
a |= MemberAttributes.Final;
if ((modifiers & Modifiers.Static) != 0)
a |= MemberAttributes.Static;
if ((modifiers & Modifiers.Override) != 0)
a |= MemberAttributes.Override;
if ((modifiers & Modifiers.Const) != 0)
a |= MemberAttributes.Const;
if ((modifiers & Modifiers.New) != 0)
a |= MemberAttributes.New;
if ((modifiers & Modifiers.Public) != 0)
a |= MemberAttributes.Public;
else if ((modifiers & (Modifiers.Protected | Modifiers.Internal)) == (Modifiers.Protected | Modifiers.Internal))
a |= MemberAttributes.FamilyOrAssembly;
else if ((modifiers & Modifiers.Protected) != 0)
a |= MemberAttributes.Family;
else if ((modifiers & Modifiers.Internal) != 0)
a |= MemberAttributes.Assembly;
else if ((modifiers & Modifiers.Private) != 0)
a |= MemberAttributes.Private;
return a;
}
CodeObject IAstVisitor<CodeObject>.VisitNamespaceDeclaration(NamespaceDeclaration namespaceDeclaration)
{
CodeNamespace ns = new CodeNamespace(namespaceDeclaration.Name);
foreach (AstNode node in namespaceDeclaration.Members) {
CodeObject r = node.AcceptVisitor(this);
CodeNamespaceImport import = r as CodeNamespaceImport;
if (import != null)
ns.Imports.Add(import);
CodeTypeDeclaration typeDecl = r as CodeTypeDeclaration;
if (typeDecl != null)
ns.Types.Add(typeDecl);
}
return ns;
}
Stack<CodeTypeDeclaration> typeStack = new Stack<CodeTypeDeclaration>();
CodeObject IAstVisitor<CodeObject>.VisitTypeDeclaration(TypeDeclaration typeDeclaration)
{
//bool isNestedType = typeStack.Count > 0;
CodeTypeDeclaration typeDecl = new CodeTypeDeclaration(typeDeclaration.Name);
typeDecl.Attributes = ConvertMemberAttributes(typeDeclaration.Modifiers, SymbolKind.TypeDefinition);
typeDecl.CustomAttributes.AddRange(Convert(typeDeclaration.Attributes));
switch (typeDeclaration.ClassType) {
case ClassType.Struct:
typeDecl.IsStruct = true;
break;
case ClassType.Interface:
typeDecl.IsInterface = true;
break;
case ClassType.Enum:
typeDecl.IsEnum = true;
break;
default:
typeDecl.IsClass = true;
break;
}
typeDecl.IsPartial = (typeDeclaration.Modifiers & Modifiers.Partial) == Modifiers.Partial;
typeDecl.BaseTypes.AddRange(Convert(typeDeclaration.BaseTypes));
typeDecl.TypeParameters.AddRange(ConvertTypeParameters(typeDeclaration.TypeParameters, typeDeclaration.Constraints));
typeStack.Push(typeDecl);
foreach (var member in typeDeclaration.Members) {
CodeTypeMember m = member.AcceptVisitor(this) as CodeTypeMember;
if (m != null)
typeDecl.Members.Add(m);
}
typeStack.Pop();
return typeDecl;
}
void AddTypeMember(CodeTypeMember member)
{
if (typeStack.Count != 0)
typeStack.Peek().Members.Add(member);
}
CodeObject IAstVisitor<CodeObject>.VisitUsingAliasDeclaration(UsingAliasDeclaration usingAliasDeclaration)
{
return new CodeSnippetTypeMember(MakeSnippet(usingAliasDeclaration));
}
CodeObject IAstVisitor<CodeObject>.VisitUsingDeclaration(UsingDeclaration usingDeclaration)
{
return new CodeNamespaceImport(usingDeclaration.Namespace);
}
CodeObject IAstVisitor<CodeObject>.VisitExternAliasDeclaration(ExternAliasDeclaration externAliasDeclaration)
{
return new CodeSnippetTypeMember(MakeSnippet(externAliasDeclaration));
}
CodeObject IAstVisitor<CodeObject>.VisitBlockStatement(BlockStatement blockStatement)
{
return new CodeConditionStatement(new CodePrimitiveExpression(true), ConvertBlock(blockStatement));
}
CodeObject IAstVisitor<CodeObject>.VisitBreakStatement(BreakStatement breakStatement)
{
return MakeSnippetStatement(breakStatement);
}
CodeObject IAstVisitor<CodeObject>.VisitCheckedStatement(CheckedStatement checkedStatement)
{
return MakeSnippetStatement(checkedStatement);
}
CodeObject IAstVisitor<CodeObject>.VisitContinueStatement(ContinueStatement continueStatement)
{
return MakeSnippetStatement(continueStatement);
}
CodeObject IAstVisitor<CodeObject>.VisitDoWhileStatement(DoWhileStatement doWhileStatement)
{
// do { } while (expr);
//
// emulate with:
// for (bool _do = true; _do; _do = expr) {}
string varName = "_do" + doWhileStatement.Ancestors.OfType<DoWhileStatement>().Count();
return new CodeIterationStatement(
new CodeVariableDeclarationStatement(typeof(bool), varName, new CodePrimitiveExpression(true)),
new CodeVariableReferenceExpression(varName),
new CodeAssignStatement(new CodeVariableReferenceExpression(varName), Convert(doWhileStatement.Condition)),
ConvertEmbeddedStatement(doWhileStatement.EmbeddedStatement)
);
}
CodeObject IAstVisitor<CodeObject>.VisitEmptyStatement(EmptyStatement emptyStatement)
{
return EmptyStatement();
}
CodeStatement EmptyStatement()
{
return new CodeExpressionStatement(new CodeObjectCreateExpression(new CodeTypeReference(typeof(object))));
}
CodeObject IAstVisitor<CodeObject>.VisitExpressionStatement(ExpressionStatement expressionStatement)
{
AssignmentExpression assignment = expressionStatement.Expression as AssignmentExpression;
if (assignment != null && assignment.Operator == AssignmentOperatorType.Assign) {
return new CodeAssignStatement(Convert(assignment.Left), Convert(assignment.Right));
} else if (assignment != null && CanBeDuplicatedForCompoundAssignment(assignment.Left)) {
CodeBinaryOperatorType op;
switch (assignment.Operator) {
case AssignmentOperatorType.Add:
op = CodeBinaryOperatorType.Add;
break;
case AssignmentOperatorType.Subtract:
op = CodeBinaryOperatorType.Subtract;
break;
case AssignmentOperatorType.Multiply:
op = CodeBinaryOperatorType.Multiply;
break;
case AssignmentOperatorType.Divide:
op = CodeBinaryOperatorType.Divide;
break;
case AssignmentOperatorType.Modulus:
op = CodeBinaryOperatorType.Modulus;
break;
case AssignmentOperatorType.BitwiseAnd:
op = CodeBinaryOperatorType.BitwiseAnd;
break;
case AssignmentOperatorType.BitwiseOr:
op = CodeBinaryOperatorType.BitwiseOr;
break;
default:
return MakeSnippetStatement(expressionStatement);
}
var cboe = new CodeBinaryOperatorExpression(Convert(assignment.Left), op, Convert(assignment.Right));
return new CodeAssignStatement(Convert(assignment.Left), cboe);
}
UnaryOperatorExpression unary = expressionStatement.Expression as UnaryOperatorExpression;
if (unary != null && CanBeDuplicatedForCompoundAssignment(unary.Expression)) {
var op = unary.Operator;
if (op == UnaryOperatorType.Increment || op == UnaryOperatorType.PostIncrement) {
var cboe = new CodeBinaryOperatorExpression(Convert(unary.Expression), CodeBinaryOperatorType.Add, new CodePrimitiveExpression(1));
return new CodeAssignStatement(Convert(unary.Expression), cboe);
} else if (op == UnaryOperatorType.Decrement || op == UnaryOperatorType.PostDecrement) {
var cboe = new CodeBinaryOperatorExpression(Convert(unary.Expression), CodeBinaryOperatorType.Subtract, new CodePrimitiveExpression(1));
return new CodeAssignStatement(Convert(unary.Expression), cboe);
}
}
if (assignment != null && assignment.Operator == AssignmentOperatorType.Add) {
var rr = Resolve(assignment.Left);
if (!rr.IsError && rr.Type.Kind == TypeKind.Delegate) {
var expr = (MemberReferenceExpression)assignment.Left;
var memberRef = (CodeEventReferenceExpression)HandleMemberReference(Convert(expr.Target), expr.MemberName, expr.TypeArguments, (MemberResolveResult)rr);
return new CodeAttachEventStatement(memberRef, Convert(assignment.Right));
}
}
return new CodeExpressionStatement(Convert(expressionStatement.Expression));
}
bool CanBeDuplicatedForCompoundAssignment(Expression expr)
{
return expr is IdentifierExpression;
}
CodeObject IAstVisitor<CodeObject>.VisitFixedStatement(FixedStatement fixedStatement)
{
return MakeSnippetStatement(fixedStatement);
}
CodeObject IAstVisitor<CodeObject>.VisitForeachStatement(ForeachStatement foreachStatement)
{
return MakeSnippetStatement(foreachStatement);
}
CodeObject IAstVisitor<CodeObject>.VisitForStatement(ForStatement forStatement)
{
if (forStatement.Initializers.Count != 1 || forStatement.Iterators.Count != 1)
return MakeSnippetStatement(forStatement);
return new CodeIterationStatement(
Convert(forStatement.Initializers.Single()),
Convert(forStatement.Condition),
Convert(forStatement.Iterators.Single()),
ConvertEmbeddedStatement(forStatement.EmbeddedStatement)
);
}
CodeObject IAstVisitor<CodeObject>.VisitGotoCaseStatement(GotoCaseStatement gotoCaseStatement)
{
return MakeSnippetStatement(gotoCaseStatement);
}
CodeObject IAstVisitor<CodeObject>.VisitGotoDefaultStatement(GotoDefaultStatement gotoDefaultStatement)
{
return MakeSnippetStatement(gotoDefaultStatement);
}
CodeObject IAstVisitor<CodeObject>.VisitGotoStatement(GotoStatement gotoStatement)
{
return new CodeGotoStatement(gotoStatement.Label);
}
CodeObject IAstVisitor<CodeObject>.VisitIfElseStatement(IfElseStatement ifElseStatement)
{
return new CodeConditionStatement(
Convert(ifElseStatement.Condition),
ConvertEmbeddedStatement(ifElseStatement.TrueStatement),
ConvertEmbeddedStatement(ifElseStatement.FalseStatement));
}
CodeObject IAstVisitor<CodeObject>.VisitLabelStatement(LabelStatement labelStatement)
{
return new CodeLabeledStatement(labelStatement.Label);
}
CodeObject IAstVisitor<CodeObject>.VisitLockStatement(LockStatement lockStatement)
{
return MakeSnippetStatement(lockStatement);
}
CodeObject IAstVisitor<CodeObject>.VisitReturnStatement(ReturnStatement returnStatement)
{
return new CodeMethodReturnStatement(Convert(returnStatement.Expression));
}
CodeObject IAstVisitor<CodeObject>.VisitSwitchStatement(SwitchStatement switchStatement)
{
return MakeSnippetStatement(switchStatement);
}