Welcome to mirror list, hosted at ThFree Co, Russian Federation.

CodeDomConvertVisitor.cs « OutputVisitor « ICSharpCode.NRefactory.CSharp - github.com/xamarin/NRefactory.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 298c303cb61187bb8631a4fa04429e44c91df1da (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
// 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.

#if !NET6_0

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 ?? SpecialType.UnknownType));
				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 ?? SpecialType.UnknownType));
				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:
					return new CodeBinaryOperatorExpression(
						new CodePrimitiveExpression(0),
						CodeBinaryOperatorType.Subtract,
						Convert(unaryOperatorExpression.Expression));
				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);
		}
		
		CodeObject IAstVisitor<CodeObject>.VisitSwitchSection(SwitchSection switchSection)
		{
			throw new NotSupportedException();
		}
		
		CodeObject IAstVisitor<CodeObject>.VisitCaseLabel(CaseLabel caseLabel)
		{
			throw new NotSupportedException();
		}
		
		CodeObject IAstVisitor<CodeObject>.VisitThrowStatement(ThrowStatement throwStatement)
		{
			return new CodeThrowExceptionStatement(Convert(throwStatement.Expression));
		}
		
		CodeObject IAstVisitor<CodeObject>.VisitTryCatchStatement(TryCatchStatement tryCatchStatement)
		{
			List<CodeCatchClause> catchClauses = new List<CodeCatchClause>();
			foreach (var catchClause in tryCatchStatement.CatchClauses) {
				catchClauses.Add(new CodeCatchClause(catchClause.VariableName, Convert(catchClause.Type), ConvertBlock(catchClause.Body)));
			}
			return new CodeTryCatchFinallyStatement(
				ConvertBlock(tryCatchStatement.TryBlock),
				catchClauses.ToArray(),
				ConvertBlock(tryCatchStatement.FinallyBlock));
		}
		
		CodeObject IAstVisitor<CodeObject>.VisitCatchClause(CatchClause catchClause)
		{
			throw new NotSupportedException();
		}
		
		CodeObject IAstVisitor<CodeObject>.VisitUncheckedStatement(UncheckedStatement uncheckedStatement)
		{
			return MakeSnippetStatement(uncheckedStatement);
		}
		
		CodeObject IAstVisitor<CodeObject>.VisitUnsafeStatement(UnsafeStatement unsafeStatement)
		{
			return MakeSnippetStatement(unsafeStatement);
		}
		
		CodeObject IAstVisitor<CodeObject>.VisitUsingStatement(UsingStatement usingStatement)
		{
			return MakeSnippetStatement(usingStatement);
		}
		
		CodeObject IAstVisitor<CodeObject>.VisitVariableDeclarationStatement(VariableDeclarationStatement variableDeclarationStatement)
		{
			if (variableDeclarationStatement.Variables.Count != 1)
				return MakeSnippetStatement(variableDeclarationStatement);
			VariableInitializer vi = variableDeclarationStatement.Variables.Single();
			return new CodeVariableDeclarationStatement(
				Convert(variableDeclarationStatement.Type),
				vi.Name,
				ConvertVariableInitializer(vi.Initializer, variableDeclarationStatement.Type));
		}
		
		CodeExpression ConvertVariableInitializer(Expression expr, AstType type)
		{
			ArrayInitializerExpression aie = expr as ArrayInitializerExpression;
			if (aie != null) {
				return new CodeArrayCreateExpression(Convert(type), Convert(aie.Elements));
			} else {
				return Convert(expr);
			}
		}
		
		CodeObject IAstVisitor<CodeObject>.VisitWhileStatement(WhileStatement whileStatement)
		{
			return new CodeIterationStatement(EmptyStatement(), Convert(whileStatement.Condition), EmptyStatement(), ConvertEmbeddedStatement(whileStatement.EmbeddedStatement));
		}
		
		CodeObject IAstVisitor<CodeObject>.VisitYieldBreakStatement(YieldBreakStatement yieldBreakStatement)
		{
			return MakeSnippetStatement(yieldBreakStatement);
		}
		
		CodeObject IAstVisitor<CodeObject>.VisitYieldReturnStatement(YieldReturnStatement yieldStatement)
		{
			return MakeSnippetStatement(yieldStatement);
		}
		
		CodeObject IAstVisitor<CodeObject>.VisitAccessor(Accessor accessor)
		{
			throw new NotSupportedException();
		}
		
		CodeObject IAstVisitor<CodeObject>.VisitConstructorDeclaration(ConstructorDeclaration constructorDeclaration)
		{
			CodeConstructor ctor = new CodeConstructor();
			ctor.Attributes = ConvertMemberAttributes(constructorDeclaration.Modifiers, SymbolKind.Constructor);
			ctor.CustomAttributes.AddRange(Convert(constructorDeclaration.Attributes));
			if (constructorDeclaration.Initializer.ConstructorInitializerType == ConstructorInitializerType.This) {
				ctor.ChainedConstructorArgs.AddRange(Convert(constructorDeclaration.Initializer.Arguments));
			} else {
				ctor.BaseConstructorArgs.AddRange(Convert(constructorDeclaration.Initializer.Arguments));
			}
			ctor.Parameters.AddRange(Convert(constructorDeclaration.Parameters));
			
			ctor.Statements.AddRange(ConvertBlock(constructorDeclaration.Body));
			return ctor;
		}
		
		CodeObject IAstVisitor<CodeObject>.VisitConstructorInitializer(ConstructorInitializer constructorInitializer)
		{
			throw new NotSupportedException();
		}
		
		CodeObject IAstVisitor<CodeObject>.VisitDestructorDeclaration(DestructorDeclaration destructorDeclaration)
		{
			return new CodeSnippetTypeMember(MakeSnippet(destructorDeclaration));
		}
		
		CodeObject IAstVisitor<CodeObject>.VisitEnumMemberDeclaration(EnumMemberDeclaration enumMemberDeclaration)
		{
			TypeDeclaration td = enumMemberDeclaration.Parent as TypeDeclaration;
			CodeMemberField f = new CodeMemberField(td != null ? td.Name : "Enum", enumMemberDeclaration.Name);
			f.Attributes = MemberAttributes.Public | MemberAttributes.Static;
			f.CustomAttributes.AddRange(Convert(enumMemberDeclaration.Attributes));
			f.InitExpression = Convert(enumMemberDeclaration.Initializer);
			return f;
		}
		
		CodeObject IAstVisitor<CodeObject>.VisitEventDeclaration(EventDeclaration eventDeclaration)
		{
			foreach (VariableInitializer vi in eventDeclaration.Variables) {
				if (!vi.Initializer.IsNull) {
					AddTypeMember(new CodeSnippetTypeMember(MakeSnippet(eventDeclaration)));
					continue;
				}
				
				CodeMemberEvent e = new CodeMemberEvent();
				e.Attributes = ConvertMemberAttributes(eventDeclaration.Modifiers, SymbolKind.Event);
				e.CustomAttributes.AddRange(Convert(eventDeclaration.Attributes));
				e.Name = vi.Name;
				e.Type = Convert(eventDeclaration.ReturnType);
				AddTypeMember(e);
			}
			return null;
		}
		
		CodeObject IAstVisitor<CodeObject>.VisitCustomEventDeclaration(CustomEventDeclaration customEventDeclaration)
		{
			return new CodeSnippetTypeMember(MakeSnippet(customEventDeclaration));
		}
		
		CodeObject IAstVisitor<CodeObject>.VisitFieldDeclaration(FieldDeclaration fieldDeclaration)
		{
			foreach (VariableInitializer vi in fieldDeclaration.Variables) {
				CodeMemberField f = new CodeMemberField(Convert(fieldDeclaration.ReturnType), vi.Name);
				f.Attributes = ConvertMemberAttributes(fieldDeclaration.Modifiers, SymbolKind.Field);
				f.CustomAttributes.AddRange(Convert(fieldDeclaration.Attributes));
				f.InitExpression = ConvertVariableInitializer(vi.Initializer, fieldDeclaration.ReturnType);
				AddTypeMember(f);
			}
			return null;
		}
		
		CodeObject IAstVisitor<CodeObject>.VisitIndexerDeclaration(IndexerDeclaration indexerDeclaration)
		{
			CodeMemberProperty p = new CodeMemberProperty();
			p.Attributes = ConvertMemberAttributes(indexerDeclaration.Modifiers, SymbolKind.Indexer);
			p.CustomAttributes.AddRange(Convert(indexerDeclaration.Attributes));
			p.Name = "Items";
			p.PrivateImplementationType = Convert(indexerDeclaration.PrivateImplementationType);
			p.Parameters.AddRange(Convert(indexerDeclaration.Parameters));
			p.Type = Convert(indexerDeclaration.ReturnType);
			
			if (!indexerDeclaration.Getter.IsNull) {
				p.HasGet = true;
				p.GetStatements.AddRange(ConvertBlock(indexerDeclaration.Getter.Body));
			}
			if (!indexerDeclaration.Setter.IsNull) {
				p.HasSet = true;
				p.SetStatements.AddRange(ConvertBlock(indexerDeclaration.Setter.Body));
			}
			return p;
		}
		
		CodeObject IAstVisitor<CodeObject>.VisitMethodDeclaration(MethodDeclaration methodDeclaration)
		{
			CodeMemberMethod m = new CodeMemberMethod();
			m.Attributes = ConvertMemberAttributes(methodDeclaration.Modifiers, SymbolKind.Method);
			
			m.CustomAttributes.AddRange(Convert(methodDeclaration.Attributes.Where(a => a.AttributeTarget != "return")));
			m.ReturnTypeCustomAttributes.AddRange(Convert(methodDeclaration.Attributes.Where(a => a.AttributeTarget == "return")));
			
			m.ReturnType = Convert(methodDeclaration.ReturnType);
			m.PrivateImplementationType = Convert(methodDeclaration.PrivateImplementationType);
			m.Name = methodDeclaration.Name;
			m.TypeParameters.AddRange(ConvertTypeParameters(methodDeclaration.TypeParameters, methodDeclaration.Constraints));
			m.Parameters.AddRange(Convert(methodDeclaration.Parameters));
			
			m.Statements.AddRange(ConvertBlock(methodDeclaration.Body));
			return m;
		}
		
		CodeObject IAstVisitor<CodeObject>.VisitOperatorDeclaration(OperatorDeclaration operatorDeclaration)
		{
			CodeMemberMethod m = new CodeMemberMethod();
			m.Attributes = ConvertMemberAttributes(operatorDeclaration.Modifiers, SymbolKind.Method);
			
			m.CustomAttributes.AddRange(Convert(operatorDeclaration.Attributes.Where(a => a.AttributeTarget != "return")));
			m.ReturnTypeCustomAttributes.AddRange(Convert(operatorDeclaration.Attributes.Where(a => a.AttributeTarget == "return")));
			
			m.ReturnType = Convert(operatorDeclaration.ReturnType);
			m.Name = operatorDeclaration.Name;
			m.Parameters.AddRange(Convert(operatorDeclaration.Parameters));
			
			m.Statements.AddRange(ConvertBlock(operatorDeclaration.Body));
			return m;
		}
		
		CodeObject IAstVisitor<CodeObject>.VisitParameterDeclaration(ParameterDeclaration parameterDeclaration)
		{
			var p = new CodeParameterDeclarationExpression(Convert(parameterDeclaration.Type), parameterDeclaration.Name);
			p.CustomAttributes.AddRange(Convert(parameterDeclaration.Attributes));
			switch (parameterDeclaration.ParameterModifier) {
				case ParameterModifier.Ref:
					p.Direction = System.CodeDom.FieldDirection.Ref;
					break;
				case ParameterModifier.Out:
					p.Direction = System.CodeDom.FieldDirection.Out;
					break;
			}
			return p;
		}
		
		CodeParameterDeclarationExpression[] Convert(IEnumerable<ParameterDeclaration> parameters)
		{
			List<CodeParameterDeclarationExpression> result = new List<CodeParameterDeclarationExpression>();
			foreach (ParameterDeclaration pd in parameters) {
				CodeParameterDeclarationExpression pde = pd.AcceptVisitor(this) as CodeParameterDeclarationExpression;
				if (pde != null)
					result.Add(pde);
			}
			return result.ToArray();
		}
		
		CodeObject IAstVisitor<CodeObject>.VisitPropertyDeclaration(PropertyDeclaration propertyDeclaration)
		{
			CodeMemberProperty p = new CodeMemberProperty();
			p.Attributes = ConvertMemberAttributes(propertyDeclaration.Modifiers, SymbolKind.Property);
			p.CustomAttributes.AddRange(Convert(propertyDeclaration.Attributes));
			p.Name = propertyDeclaration.Name;
			p.PrivateImplementationType = Convert(propertyDeclaration.PrivateImplementationType);
			p.Type = Convert(propertyDeclaration.ReturnType);
			
			if (!propertyDeclaration.Getter.IsNull) {
				p.HasGet = true;
				p.GetStatements.AddRange(ConvertBlock(propertyDeclaration.Getter.Body));
			}
			if (!propertyDeclaration.Setter.IsNull) {
				p.HasSet = true;
				p.SetStatements.AddRange(ConvertBlock(propertyDeclaration.Setter.Body));
			}
			return p;
		}
		
		CodeObject IAstVisitor<CodeObject>.VisitVariableInitializer(VariableInitializer variableInitializer)
		{
			throw new NotSupportedException(); // should be handled by the parent node
		}
		
		CodeObject IAstVisitor<CodeObject>.VisitFixedFieldDeclaration(FixedFieldDeclaration fixedFieldDeclaration)
		{
			return new CodeSnippetTypeMember(MakeSnippet(fixedFieldDeclaration));
		}
		
		CodeObject IAstVisitor<CodeObject>.VisitFixedVariableInitializer(FixedVariableInitializer fixedVariableInitializer)
		{
			throw new NotSupportedException(); // should be handled by the parent node
		}
		
		CodeObject IAstVisitor<CodeObject>.VisitSyntaxTree(SyntaxTree syntaxTree)
		{
			CodeCompileUnit cu = new CodeCompileUnit();
			var globalImports = new List<CodeNamespaceImport> ();
			foreach (AstNode node in syntaxTree.Children) {
				CodeObject o = node.AcceptVisitor(this);
				
				CodeNamespace ns = o as CodeNamespace;
				if (ns != null) {
					cu.Namespaces.Add(ns);
				}
				CodeTypeDeclaration td = o as CodeTypeDeclaration;
				if (td != null) {
					cu.Namespaces.Add(new CodeNamespace() { Types = { td } });
				}
				
				var import = o as CodeNamespaceImport;
				if (import != null)
					globalImports.Add (import);
			}
			foreach (var gi in globalImports) {
				for (int j = 0; j < cu.Namespaces.Count; j++) {
					var cn = cu.Namespaces [j];
					bool found = cn.Imports
						.Cast<CodeNamespaceImport> ()
						.Any (ns => ns.Namespace == gi.Namespace);
					if (!found)
						cn.Imports.Add (gi);
				}
			}
			return cu;
		}
		
		CodeObject IAstVisitor<CodeObject>.VisitSimpleType(SimpleType simpleType)
		{
			if (UseFullyQualifiedTypeNames) {
				IType type = Resolve(simpleType).Type;
				if (type.Kind != TypeKind.Unknown)
					return Convert(type);
			}
			var tr = new CodeTypeReference(simpleType.Identifier);
			tr.TypeArguments.AddRange(Convert(simpleType.TypeArguments));
			return tr;
		}
		
		CodeObject IAstVisitor<CodeObject>.VisitMemberType(MemberType memberType)
		{
			if (memberType.IsDoubleColon && new SimpleType("global").IsMatch(memberType.Target)) {
				var tr = new CodeTypeReference(memberType.MemberName, CodeTypeReferenceOptions.GlobalReference);
				tr.TypeArguments.AddRange(Convert(memberType.TypeArguments));
				return tr;
			}
			if (UseFullyQualifiedTypeNames || memberType.IsDoubleColon) {
				IType type = Resolve(memberType).Type;
				if (type.Kind != TypeKind.Unknown)
					return Convert(type);
			}
			CodeTypeReference target = Convert(memberType.Target);
			if (target == null)
				return null;
			target.BaseType = target.BaseType + "." + memberType.MemberName;
			target.TypeArguments.AddRange(Convert(memberType.TypeArguments));
			return target;
		}
		
		CodeObject IAstVisitor<CodeObject>.VisitComposedType(ComposedType composedType)
		{
			CodeTypeReference typeRef = Convert(composedType.BaseType);
			if (typeRef == null)
				return null;
			if (composedType.HasNullableSpecifier) {
				typeRef = new CodeTypeReference("System.Nullable") { TypeArguments = { typeRef } };
			}
			foreach (ArraySpecifier s in composedType.ArraySpecifiers.Reverse()) {
				typeRef = new CodeTypeReference(typeRef, s.Dimensions);
			}
			return typeRef;
		}
		
		CodeObject IAstVisitor<CodeObject>.VisitArraySpecifier(ArraySpecifier arraySpecifier)
		{
			throw new NotSupportedException(); // handled by parent node
		}
		
		CodeObject IAstVisitor<CodeObject>.VisitPrimitiveType(PrimitiveType primitiveType)
		{
			KnownTypeCode typeCode = primitiveType.KnownTypeCode;
			if (typeCode != KnownTypeCode.None) {
				KnownTypeReference ktr = KnownTypeReference.Get(typeCode);
				return new CodeTypeReference(ktr.Namespace + "." + ktr.Name);
			}
			return new CodeTypeReference(primitiveType.Keyword);
		}
		
		CodeObject IAstVisitor<CodeObject>.VisitComment (Comment comment)
		{
			return new CodeComment (comment.Content, comment.CommentType == CommentType.Documentation);
		}

		CodeObject IAstVisitor<CodeObject>.VisitNewLine(NewLineNode newLineNode)
		{
			return null;
		}

		CodeObject IAstVisitor<CodeObject>.VisitWhitespace(WhitespaceNode whitespaceNode)
		{
			return null;
		}

		CodeObject IAstVisitor<CodeObject>.VisitText(TextNode textNode)
		{
			throw new NotSupportedException();
		}

		CodeObject IAstVisitor<CodeObject>.VisitPreProcessorDirective (PreProcessorDirective preProcessorDirective)
		{
			return new CodeComment ("#" + preProcessorDirective.Type.ToString ().ToLowerInvariant ());
		}
		
		CodeObject IAstVisitor<CodeObject>.VisitTypeParameterDeclaration(TypeParameterDeclaration typeParameterDeclaration)
		{
			throw new NotSupportedException(); // type parameters and constraints are handled together
		}
		
		CodeObject IAstVisitor<CodeObject>.VisitConstraint(Constraint constraint)
		{
			throw new NotSupportedException();
		}
		
		CodeTypeParameter[] ConvertTypeParameters(IEnumerable<TypeParameterDeclaration> typeParameters, IEnumerable<Constraint> constraints)
		{
			List<CodeTypeParameter> result = new List<CodeTypeParameter>();
			foreach (TypeParameterDeclaration tpDecl in typeParameters) {
				CodeTypeParameter tp = new CodeTypeParameter(tpDecl.Name);
				tp.CustomAttributes.AddRange(Convert(tpDecl.Attributes));
				foreach (Constraint constraint in constraints) {
					if (constraint.TypeParameter.Identifier == tp.Name) {
						foreach (AstType baseType in constraint.BaseTypes) {
							if (baseType is PrimitiveType && ((PrimitiveType)baseType).Keyword == "new") {
								tp.HasConstructorConstraint = true;
							} else {
								CodeTypeReference tr = Convert(baseType);
								if (tr != null)
									tp.Constraints.Add(tr);
							}
						}
					}
				}
				result.Add(tp);
			}
			return result.ToArray();
		}
		
		CodeObject IAstVisitor<CodeObject>.VisitCSharpTokenNode(CSharpTokenNode cSharpTokenNode)
		{
			return null;
		}
		
		CodeObject IAstVisitor<CodeObject>.VisitIdentifier(Identifier identifier)
		{
			return null;
		}
		
		CodeObject IAstVisitor<CodeObject>.VisitPatternPlaceholder(AstNode placeholder, Pattern pattern)
		{
			return null;
		}
		
		CodeObject IAstVisitor<CodeObject>.VisitDocumentationReference(DocumentationReference documentationReference)
		{
			return null;
		}
	}
}

#endif