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

NRefactoryExpressionEvaluatorVisitor.cs « Mono.Debugging.Evaluation « Mono.Debugging - github.com/mono/debugger-libs.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 6c662f6c1e32c20d8bff6ea20eaed7ff1422ff93 (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
//
// NRefactoryExpressionEvaluatorVisitor.cs
//
// Author: Jeffrey Stedfast <jeff@xamarin.com>
//
// Copyright (c) 2013 Xamarin Inc.
//
// 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.Linq;
using System.Reflection;
using System.Collections.Generic;

using Mono.Debugging.Client;

using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;

namespace Mono.Debugging.Evaluation
{
	public class NRefactoryExpressionEvaluatorVisitor : CSharpSyntaxVisitor<ValueReference>
	{
		readonly Dictionary<string, ValueReference> userVariables;
		readonly EvaluationOptions options;
		readonly EvaluationContext ctx;
		readonly object expectedType;
		readonly string expression;

		public NRefactoryExpressionEvaluatorVisitor (EvaluationContext ctx, string expression, object expectedType, Dictionary<string,ValueReference> userVariables)
		{
			this.ctx = ctx;
			this.expression = expression;
			this.expectedType = expectedType;
			this.userVariables = userVariables;
			this.options = ctx.Options;
		}

		static Exception ParseError (string message, params object[] args)
		{
			return new EvaluatorException (message, args);
		}

		static Exception NotSupported ()
		{
			return new NotSupportedExpressionException ();
		}

		static string ResolveTypeName (SyntaxNode type)
		{
			string name = type.ToString ();
			if (name.StartsWith ("global::", StringComparison.Ordinal))
				name = name.Substring ("global::".Length);
			return name;
		}

		static long GetInteger (object val)
		{
			try {
				return Convert.ToInt64 (val);
			} catch {
				throw ParseError ("Expected integer value.");
			}
		}

		long ConvertToInt64 (object val)
		{
			if (val is IntPtr)
				return ((IntPtr) val).ToInt64 ();

			if (ctx.Adapter.IsEnum (ctx, val)) {
				var type = ctx.Adapter.GetType (ctx, "System.Int64");
				var result = ctx.Adapter.Cast (ctx, val, type);

				return (long) ctx.Adapter.TargetObjectToObject (ctx, result);
			}

			return Convert.ToInt64 (val);
		}

		static Type GetCommonOperationType (object v1, object v2)
		{
			if (v1 is double || v2 is double)
				return typeof (double);

			if (v1 is float || v2 is float)
				return typeof (double);

			return typeof (long);
		}

		static Type GetCommonType (object v1, object v2)
		{
			var t1 = Type.GetTypeCode (v1.GetType ());
			var t2 = Type.GetTypeCode (v2.GetType ());
			if (t1 < TypeCode.Int32 && t2 < TypeCode.Int32)
				return typeof (int);

			switch ((TypeCode) Math.Max ((int) t1, (int) t2)) {
			case TypeCode.Byte: return typeof (byte);
			case TypeCode.Decimal: return typeof (decimal);
			case TypeCode.Double: return typeof (double);
			case TypeCode.Int16: return typeof (short);
			case TypeCode.Int32: return typeof (int);
			case TypeCode.Int64: return typeof (long);
			case TypeCode.SByte: return typeof (sbyte);
			case TypeCode.Single: return typeof (float);
			case TypeCode.UInt16: return typeof (ushort);
			case TypeCode.UInt32: return typeof (uint);
			case TypeCode.UInt64: return typeof (ulong);
			default: throw new Exception (((TypeCode) Math.Max ((int) t1, (int) t2)).ToString ());
			}
		}

		static object EvaluateOperation (SyntaxKind op, double v1, double v2)
		{
			switch (op) {
			case SyntaxKind.AddExpression: return v1 + v2;
			case SyntaxKind.DivideExpression: return v1 / v2;
			case SyntaxKind.MultiplyExpression: return v1 * v2;
			case SyntaxKind.SubtractExpression: return v1 - v2;
			case SyntaxKind.GreaterThanExpression: return v1 > v2;
			case SyntaxKind.GreaterThanOrEqualExpression: return v1 >= v2;
			case SyntaxKind.LessThanExpression: return v1 < v2;
			case SyntaxKind.LessThanOrEqualExpression: return v1 <= v2;
			case SyntaxKind.EqualsExpression: return v1 == v2;
			case SyntaxKind.NotEqualsExpression: return v1 != v2;
			default: throw ParseError ("Invalid binary operator.");
			}
		}

		static object EvaluateOperation (SyntaxKind op, long v1, long v2)
		{
			switch (op) {
			case SyntaxKind.AddExpression: return v1 + v2;
			case SyntaxKind.BitwiseAndExpression: return v1 & v2;
			case SyntaxKind.BitwiseOrExpression: return v1 | v2;
			case SyntaxKind.ExclusiveOrExpression: return v1 ^ v2;
			case SyntaxKind.DivideExpression: return v1 / v2;
			case SyntaxKind.ModuloExpression: return v1 % v2;
			case SyntaxKind.MultiplyExpression: return v1 * v2;
			case SyntaxKind.LeftShiftExpression: return v1 << (int) v2;
			case SyntaxKind.RightShiftExpression: return v1 >> (int) v2;
			case SyntaxKind.SubtractExpression: return v1 - v2;
			case SyntaxKind.GreaterThanExpression: return v1 > v2;
			case SyntaxKind.GreaterThanOrEqualExpression: return v1 >= v2;
			case SyntaxKind.LessThanExpression: return v1 < v2;
			case SyntaxKind.LessThanOrEqualExpression: return v1 <= v2;
			case SyntaxKind.EqualsExpression: return v1 == v2;
			case SyntaxKind.NotEqualsExpression: return v1 != v2;
			default: throw ParseError ("Invalid binary operator.");
			}
		}

		static bool CheckReferenceEquality (EvaluationContext ctx, object v1, object v2)
		{
			if (v1 == null && v2 == null)
				return true;

			if (v1 == null || v2 == null)
				return false;

			object objectType = ctx.Adapter.GetType (ctx, "System.Object");
			object[] argTypes = { objectType, objectType };
			object[] args = { v1, v2 };

			object result = ctx.Adapter.RuntimeInvoke (ctx, objectType, null, "ReferenceEquals", argTypes, args);
			var literal = LiteralValueReference.CreateTargetObjectLiteral (ctx, "result", result);

			return (bool) literal.ObjectValue;
		}

		static bool CheckEquality (EvaluationContext ctx, bool negate, object type1, object type2, object targetVal1, object targetVal2, object val1, object val2)
		{
			if (val1 == null && val2 == null)
				return !negate;

			if (val1 == null || val2 == null)
				return negate;

			string method = negate ? "op_Inequality" : "op_Equality";
			object[] argTypes = { type1, type2 };
			object target, targetType;
			object[] args;

			if (ctx.Adapter.HasMethod (ctx, type1, method, argTypes, BindingFlags.Public | BindingFlags.Static)) {
				args = new [] { targetVal1, targetVal2 };
				targetType = type1;
				target = null;
				negate = false;
			} else if (ctx.Adapter.HasMethod (ctx, type2, method, argTypes, BindingFlags.Public | BindingFlags.Static)) {
				args = new [] { targetVal1, targetVal2 };
				targetType = type2;
				target = null;
				negate = false;
			} else {
				method = ctx.Adapter.IsValueType (type1) ? "Equals" : "ReferenceEquals";
				targetType = ctx.Adapter.GetType (ctx, "System.Object");
				argTypes = new [] { targetType, targetType };
				args = new [] { targetVal1, targetVal2 };
				target = null;
			}

			object result = ctx.Adapter.RuntimeInvoke (ctx, targetType, target, method, argTypes, args);
			var literal = LiteralValueReference.CreateTargetObjectLiteral (ctx, "result", result);
			bool retval = (bool) literal.ObjectValue;

			return negate ? !retval : retval;
		}

		static ValueReference EvaluateOverloadedOperator (EvaluationContext ctx, string expression, SyntaxKind op, object type1, object type2, object targetVal1, object targetVal2, object val1, object val2)
		{
			object[] args = new [] { targetVal1, targetVal2 };
			object[] argTypes = { type1, type2 };
			object targetType = null;
			string methodName = null;

			switch (op) {
			case SyntaxKind.BitwiseAndExpression:         methodName = "op_BitwiseAnd"; break;
			case SyntaxKind.BitwiseOrExpression:          methodName = "op_BitwiseOr"; break;
			case SyntaxKind.ExclusiveOrExpression:        methodName = "op_ExclusiveOr"; break;
			case SyntaxKind.GreaterThanExpression:        methodName = "op_GreaterThan"; break;
			case SyntaxKind.GreaterThanOrEqualExpression: methodName = "op_GreaterThanOrEqual"; break;
			case SyntaxKind.EqualsExpression:             methodName = "op_Equality"; break;
			case SyntaxKind.NotEqualsExpression:          methodName = "op_Inequality"; break;
			case SyntaxKind.LessThanExpression:           methodName = "op_LessThan"; break;
			case SyntaxKind.LessThanOrEqualExpression:    methodName = "op_LessThanOrEqual"; break;
			case SyntaxKind.AddExpression:                methodName = "op_Addition"; break;
			case SyntaxKind.SubtractExpression:           methodName = "op_Subtraction"; break;
			case SyntaxKind.MultiplyExpression:           methodName = "op_Multiply"; break;
			case SyntaxKind.DivideExpression:             methodName = "op_Division"; break;
			case SyntaxKind.ModuloExpression:             methodName = "op_Modulus"; break;
			case SyntaxKind.LeftShiftExpression:          methodName = "op_LeftShift"; break;
			case SyntaxKind.RightShiftExpression:         methodName = "op_RightShift"; break;
			}

			if (methodName == null)
				throw ParseError ("Invalid operands in binary operator.");

			if (ctx.Adapter.HasMethod (ctx, type1, methodName, argTypes, BindingFlags.Public | BindingFlags.Static)) {
				targetType = type1;
			} else if (ctx.Adapter.HasMethod (ctx, type2, methodName, argTypes, BindingFlags.Public | BindingFlags.Static)) {
				targetType = type2;
			} else {
				throw ParseError ("Invalid operands in binary operator.");
			}

			object result = ctx.Adapter.RuntimeInvoke (ctx, targetType, null, methodName, argTypes, args);

			return LiteralValueReference.CreateTargetObjectLiteral (ctx, expression, result);
		}

		ValueReference EvaluateBinaryOperatorExpression (SyntaxKind op, ValueReference left, ExpressionSyntax rightExp)
		{
			if (op == SyntaxKind.LogicalAndExpression) {
				var val = left.ObjectValue;
				if (!(val is bool))
					throw ParseError ("Left operand of logical And must be a boolean.");

				if (!(bool) val)
					return LiteralValueReference.CreateObjectLiteral (ctx, expression, false);

				var vr = Visit (rightExp);
				if (vr == null || ctx.Adapter.GetTypeName (ctx, vr.Type) != "System.Boolean")
					throw ParseError ("Right operand of logical And must be a boolean.");

				return vr;
			}

			if (op == SyntaxKind.LogicalOrExpression) {
				var val = left.ObjectValue;
				if (!(val is bool))
					throw ParseError ("Left operand of logical Or must be a boolean.");

				if ((bool) val)
					return LiteralValueReference.CreateObjectLiteral (ctx, expression, true);

				var vr = Visit (rightExp);
				if (vr == null || ctx.Adapter.GetTypeName (ctx, vr.Type) != "System.Boolean")
					throw ParseError ("Right operand of logical Or must be a boolean.");

				return vr;
			}

			var right = Visit (rightExp);
			var targetVal1 = left.Value;
			var targetVal2 = right.Value;
			var type1 = ctx.Adapter.GetValueType (ctx, targetVal1);
			var type2 = ctx.Adapter.GetValueType (ctx, targetVal2);
			var val1 = left.ObjectValue;
			var val2 = right.ObjectValue;
			object res = null;

			if (ctx.Adapter.IsNullableType (ctx, type1) && ctx.Adapter.NullableHasValue (ctx, type1, val1)) {
				if (val2 == null) {
					if (op == SyntaxKind.EqualsExpression)
						return LiteralValueReference.CreateObjectLiteral (ctx, expression, false);
					if (op == SyntaxKind.NotEqualsExpression)
						return LiteralValueReference.CreateObjectLiteral (ctx, expression, true);
				}

				ValueReference nullable = ctx.Adapter.NullableGetValue (ctx, type1, val1);
				targetVal1 = nullable.Value;
				val1 = nullable.ObjectValue;
				type1 = nullable.Type;
			}

			if (ctx.Adapter.IsNullableType (ctx, type2) && ctx.Adapter.NullableHasValue (ctx, type2, val2)) {
				if (val1 == null) {
					if (op == SyntaxKind.EqualsExpression)
						return LiteralValueReference.CreateObjectLiteral (ctx, expression, false);
					if (op == SyntaxKind.NotEqualsExpression)
						return LiteralValueReference.CreateObjectLiteral (ctx, expression, true);
				}

				ValueReference nullable = ctx.Adapter.NullableGetValue (ctx, type2, val2);
				targetVal2 = nullable.Value;
				val2 = nullable.ObjectValue;
				type2 = nullable.Type;
			}

			if (val1 is string || val2 is string) {
				switch (op) {
				case SyntaxKind.AddExpression:
					if (val1 != null && val2 != null) {
						if (!(val1 is string))
							val1 = ctx.Adapter.CallToString (ctx, targetVal1);

						if (!(val2 is string))
							val2 = ctx.Adapter.CallToString (ctx, targetVal2);

						res = (string) val1 + (string) val2;
					} else if (val1 != null) {
						res = val1.ToString ();
					} else if (val2 != null) {
						res = val2.ToString ();
					}

					return LiteralValueReference.CreateObjectLiteral (ctx, expression, res);
				case SyntaxKind.EqualsExpression:
					if ((val1 == null || val1 is string) && (val2 == null || val2 is string))
						return LiteralValueReference.CreateObjectLiteral (ctx, expression, ((string) val1) == ((string) val2));
					break;
				case SyntaxKind.NotEqualsExpression:
					if ((val1 == null || val1 is string) && (val2 == null || val2 is string))
						return LiteralValueReference.CreateObjectLiteral (ctx, expression, ((string) val1) != ((string) val2));
					break;
				}
			}

			if (val1 == null || (!ctx.Adapter.IsPrimitive (ctx, targetVal1) && !ctx.Adapter.IsEnum (ctx, targetVal1))) {
				switch (op) {
				case SyntaxKind.EqualsExpression:
					return LiteralValueReference.CreateObjectLiteral (ctx, expression, CheckEquality (ctx, false, type1, type2, targetVal1, targetVal2, val1, val2));
				case SyntaxKind.NotEqualsExpression:
					return LiteralValueReference.CreateObjectLiteral (ctx, expression, CheckEquality (ctx, true, type1, type2, targetVal1, targetVal2, val1, val2));
				default:
					if (val1 != null && val2 != null)
						return EvaluateOverloadedOperator (ctx, expression, op, type1, type2, targetVal1, targetVal2, val1, val2);
					break;
				}
			}

			if ((val1 is bool) && (val2 is bool)) {
				switch (op) {
				case SyntaxKind.ExclusiveOrExpression:
					return LiteralValueReference.CreateObjectLiteral (ctx, expression, (bool) val1 ^ (bool) val2);
				case SyntaxKind.EqualsExpression:
					return LiteralValueReference.CreateObjectLiteral (ctx, expression, (bool) val1 == (bool) val2);
				case SyntaxKind.NotEqualsExpression:
					return LiteralValueReference.CreateObjectLiteral (ctx, expression, (bool) val1 != (bool) val2);
				}
			}

			if (val1 == null || val2 == null || (val1 is bool) || (val2 is bool))
				throw ParseError ("Invalid operands in binary operator.");

			var commonType = GetCommonOperationType (val1, val2);

			if (commonType == typeof (double)) {
				double v1, v2;

				try {
					v1 = Convert.ToDouble (val1);
					v2 = Convert.ToDouble (val2);
				} catch {
					throw ParseError ("Invalid operands in binary operator.");
				}

				res = EvaluateOperation (op, v1, v2);
			} else {
				var v1 = ConvertToInt64 (val1);
				var v2 = ConvertToInt64 (val2);

				res = EvaluateOperation (op, v1, v2);
			}

			if (!(res is bool) && !(res is string)) {
				if (ctx.Adapter.IsEnum (ctx, targetVal1)) {
					object tval = ctx.Adapter.Cast (ctx, ctx.Adapter.CreateValue (ctx, res), ctx.Adapter.GetValueType (ctx, targetVal1));
					return LiteralValueReference.CreateTargetObjectLiteral (ctx, expression, tval);
				}

				if (ctx.Adapter.IsEnum (ctx, targetVal2)) {
					object tval = ctx.Adapter.Cast (ctx, ctx.Adapter.CreateValue (ctx, res), ctx.Adapter.GetValueType (ctx, targetVal2));
					return LiteralValueReference.CreateTargetObjectLiteral (ctx, expression, tval);
				}

				var targetType = GetCommonType (val1, val2);

				if (targetType != typeof (IntPtr))
					res = Convert.ChangeType (res, targetType);
				else
					res = new IntPtr ((long) res);
			}

			return LiteralValueReference.CreateObjectLiteral (ctx, expression, res);
		}

		//static string ResolveType (EvaluationContext ctx, TypeReferenceExpression mre, List<object> args)
		//{
		//	var memberType = mre.Type as MemberType;

		//	if (memberType != null) {
		//		var name = memberType.MemberName;

		//		if (memberType.TypeArguments.Count > 0) {
		//			name += "`" + memberType.TypeArguments.Count;

		//			foreach (var arg in memberType.TypeArguments) {
		//				var resolved = arg.Resolve (ctx);

		//				if (resolved == null)
		//					return null;

		//				args.Add (resolved);
		//			}
		//		}

		//		return name;
		//	}

		//	return mre.ToString ();
		//}

		static string ResolveType (EvaluationContext ctx, MemberAccessExpressionSyntax mre, List<object> args)
		{
			string parent, name;

			if (mre.Expression is MemberAccessExpressionSyntax mae) {
				parent = ResolveType (ctx, mae, args);
			} else /* TODO?
			    if (mre.Expression is TypeReferenceExpression) {
				parent = ResolveType (ctx, (TypeReferenceExpression) mre.Target, args);
			} else */if (mre.Expression is IdentifierNameSyntax id) {
				parent = id.Identifier.ValueText;
			} else {
				return null;
			}

			name = parent + "." + mre.Name.Identifier.ValueText;
			/*
			if (mre.TypeArguments.Count > 0) {
				name += "`" + mre.TypeArguments.Count;

				foreach (var arg in mre.TypeArguments) {
					var resolved = arg.Resolve (ctx);

					if (resolved == null)
						return null;

					args.Add (resolved);
				}
			}*/

			return name;
		}

		static object ResolveType (EvaluationContext ctx, MemberAccessExpressionSyntax mre)
		{
			var args = new List<object> ();
			var name = ResolveType (ctx, mre, args);

			if (name == null)
				return null;

			if (args.Count > 0)
				return ctx.Adapter.GetType (ctx, name, args.ToArray ());

			return ctx.Adapter.GetType (ctx, name);
		}

		static ValueReference ResolveTypeValueReference (EvaluationContext ctx, MemberAccessExpressionSyntax mre)
		{
			object resolved = ResolveType (ctx, mre);

			if (resolved != null) {
				ctx.Adapter.ForceLoadType (ctx, resolved);

				return new TypeValueReference (ctx, resolved);
			}

			throw ParseError ("Could not resolve type: {0}", mre);
		}

		//static ValueReference ResolveTypeValueReference (EvaluationContext ctx, AstType type)
		//{
		//	object resolved = type.Resolve (ctx);

		//	if (resolved != null) {
		//		ctx.Adapter.ForceLoadType (ctx, resolved);

		//		return new TypeValueReference (ctx, resolved);
		//	}

		//	throw ParseError ("Could not resolve type: {0}", ResolveTypeName (type));
		//}

		static object[] UpdateDelayedTypes (object[] types, Tuple<int, object>[] updates, ref bool alreadyUpdated)
		{
			if (alreadyUpdated || types == null || updates == null || types.Length < updates.Length || updates.Length == 0)
				return types;

			for (int x = 0; x < updates.Length; x++) {
				int index = updates[x].Item1;
				types[index] = updates[x].Item2;
			}
			alreadyUpdated = true;
			return types;
		}

		#region IAstVisitor implementation
		public override ValueReference VisitArrayCreationExpression (ArrayCreationExpressionSyntax node)
		{
			var type = Visit(node.Type.ElementType);
			if (type == null)
				throw ParseError ("Invalid type in array creation.");
			var lengths = new int [node.Initializer.Expressions.Count];
			for (int i = 0; i < lengths.Length; i++) {
				lengths [i] = (int)Convert.ChangeType (Visit(node.Initializer.Expressions[i]).ObjectValue, typeof (int));
			}
			var array = ctx.Adapter.CreateArray (ctx, type.Type, lengths);
			if (node.Initializer.Expressions.Count > 0) {
				var arrayAdaptor = ctx.Adapter.CreateArrayAdaptor (ctx, array);
				int index = 0;
				foreach (var el in LinearElements(node.Initializer.Expressions)) {
					arrayAdaptor.SetElement (new int [] { index++ },  Visit(el).Value);
				}
			}
			return LiteralValueReference.CreateTargetObjectLiteral (ctx, expression, array);
		}

		IEnumerable<ExpressionSyntax> LinearElements (SeparatedSyntaxList<ExpressionSyntax> elements)
		{
			foreach (var el in elements) {
				if (el is ArrayCreationExpressionSyntax arrCre)
					foreach (var el2 in LinearElements (arrCre.Initializer.Expressions)) {
						yield return el2;
					} else
					yield return el;
			}
		}

		public override ValueReference VisitAssignmentExpression (AssignmentExpressionSyntax node)
		{
			if (!options.AllowMethodEvaluation)
				throw new ImplicitEvaluationDisabledException ();

			var left = Visit (node.Left);

			if (node.Kind () == SyntaxKind.SimpleAssignmentExpression) {
				var right = Visit (node.Right);
				if (left is UserVariableReference) {
					left.Value = right.Value;
				} else {
					var castedValue = ctx.Adapter.TryCast (ctx, right.Value, left.Type);
					left.Value = castedValue;
				}
			} else {
				SyntaxKind op;

				switch (node.Kind ()) {
				case SyntaxKind.AddAssignmentExpression:         op = SyntaxKind.AddExpression; break;
				case SyntaxKind.SubtractAssignmentExpression:    op = SyntaxKind.SubtractExpression; break;
				case SyntaxKind.MultiplyAssignmentExpression:    op = SyntaxKind.MultiplyExpression; break;
				case SyntaxKind.DivideAssignmentExpression:      op = SyntaxKind.DivideExpression; break;
				case SyntaxKind.ModuloAssignmentExpression:      op = SyntaxKind.ModuloExpression; break;
				case SyntaxKind.LeftShiftAssignmentExpression:   op = SyntaxKind.LeftShiftExpression; break;
				case SyntaxKind.RightShiftAssignmentExpression:  op = SyntaxKind.RightShiftExpression; break;
				case SyntaxKind.AndAssignmentExpression:         op = SyntaxKind.BitwiseAndExpression; break;
				case SyntaxKind.OrAssignmentExpression:          op = SyntaxKind.BitwiseOrExpression; break;
				case SyntaxKind.ExclusiveOrAssignmentExpression: op = SyntaxKind.ExclusiveOrExpression; break;
				default: throw ParseError ("Invalid operator in assignment.");
				}

				var result = EvaluateBinaryOperatorExpression (op, left, node.Right);
				left.Value = result.Value;
			}

			return left;
		}

		public override ValueReference VisitBaseExpression (BaseExpressionSyntax node)
		{
			var self = ctx.Adapter.GetThisReference (ctx);

			if (self != null)
				return LiteralValueReference.CreateTargetBaseObjectLiteral (ctx, expression, self.Value);

			throw ParseError ("'base' reference not available in static methods.");
		}

		public override ValueReference VisitBinaryExpression (BinaryExpressionSyntax node)
		{
			if (node.IsKind (SyntaxKind.AsExpression)) {
				var type = Visit (node.Right) as TypeValueReference;
				if (type == null)
					throw ParseError ("Invalid type in cast.");

				var val = Visit (node.Left);
				var result = ctx.Adapter.TryCast (ctx, val.Value, type.Type);

				if (result == null)
					return new NullValueReference (ctx, type.Type);

				return LiteralValueReference.CreateTargetObjectLiteral (ctx, expression, result, type.Type);
			}
			if (node.IsKind (SyntaxKind.IsExpression)) {
				var type = (Visit (node.Right) as TypeValueReference)?.Type;
				if (type == null)
					throw ParseError ("Invalid type in 'is' expression.");
				if (ctx.Adapter.IsNullableType (ctx, type))
					type = ctx.Adapter.GetGenericTypeArguments (ctx, type).Single ();
				var val = Visit (node.Left).Value;
				if (ctx.Adapter.IsNull (ctx, val))
					return LiteralValueReference.CreateObjectLiteral (ctx, expression, false);
				var valueIsPrimitive = ctx.Adapter.IsPrimitive (ctx, val);
				var typeIsPrimitive = ctx.Adapter.IsPrimitiveType (type);
				if (valueIsPrimitive != typeIsPrimitive)
					return LiteralValueReference.CreateObjectLiteral (ctx, expression, false);
				if (typeIsPrimitive)
					return LiteralValueReference.CreateObjectLiteral (ctx, expression, ctx.Adapter.GetTypeName (ctx, type) == ctx.Adapter.GetValueTypeName (ctx, val));
				return LiteralValueReference.CreateObjectLiteral (ctx, expression, ctx.Adapter.TryCast (ctx, val, type) != null);
			}

			var left = this.Visit (node.Left);

			return EvaluateBinaryOperatorExpression (node.Kind (), left, node.Right);
		}

		public override ValueReference VisitCastExpression (CastExpressionSyntax node)
		{
			var type = Visit(node.Type) as TypeValueReference;
			if (type == null)
				throw ParseError ("Invalid type in cast.");

			var val = Visit(node.Expression);
			object result = ctx.Adapter.TryCast (ctx, val.Value, type.Type);
			if (result == null)
				throw ParseError ("Invalid cast.");

			return LiteralValueReference.CreateTargetObjectLiteral (ctx, expression, result, type.Type);
		}

		public override ValueReference VisitCheckedExpression (CheckedExpressionSyntax node)
		{
			throw NotSupported ();
		}

		public override ValueReference VisitConditionalExpression (ConditionalExpressionSyntax node)
		{
			ValueReference val = Visit(node.Condition);
			if (val is TypeValueReference)
				throw NotSupported ();

			if ((bool)val.ObjectValue)
				return Visit (node.WhenTrue);;

			return Visit (node.WhenFalse);
		}

		public override ValueReference VisitDefaultExpression (DefaultExpressionSyntax node)
		{
			var type = Visit(node.Type) as TypeValueReference;
			if (type == null)
				throw ParseError ("Invalid type in 'default' expression.");

			if (ctx.Adapter.IsClass (ctx, type.Type))
				return LiteralValueReference.CreateTargetObjectLiteral (ctx, expression, ctx.Adapter.CreateNullValue (ctx, type.Type), type.Type);

			if (ctx.Adapter.IsValueType (type.Type))
				return LiteralValueReference.CreateTargetObjectLiteral (ctx, expression, ctx.Adapter.CreateValue (ctx, type.Type, new object [0]), type.Type);

			switch (ctx.Adapter.GetTypeName (ctx, type.Type)) {
			case "System.Boolean": return LiteralValueReference.CreateObjectLiteral (ctx, expression, false);
			case "System.Char": return LiteralValueReference.CreateObjectLiteral (ctx, expression, '\0');
			case "System.Byte": return LiteralValueReference.CreateObjectLiteral (ctx, expression, (byte) 0);
			case "System.SByte": return LiteralValueReference.CreateObjectLiteral (ctx, expression, (sbyte) 0);
			case "System.Int16": return LiteralValueReference.CreateObjectLiteral (ctx, expression, (short) 0);
			case "System.UInt16": return LiteralValueReference.CreateObjectLiteral (ctx, expression, (ushort) 0);
			case "System.Int32": return LiteralValueReference.CreateObjectLiteral (ctx, expression, (int) 0);
			case "System.UInt32": return LiteralValueReference.CreateObjectLiteral (ctx, expression, (uint) 0);
			case "System.Int64": return LiteralValueReference.CreateObjectLiteral (ctx, expression, (long) 0);
			case "System.UInt64": return LiteralValueReference.CreateObjectLiteral (ctx, expression, (ulong) 0);
			case "System.Decimal": return LiteralValueReference.CreateObjectLiteral (ctx, expression, (decimal) 0);
			case "System.Single": return LiteralValueReference.CreateObjectLiteral (ctx, expression, (float) 0);
			case "System.Double": return LiteralValueReference.CreateObjectLiteral (ctx, expression, (double) 0);
			default: throw new Exception ($"Unexpected type {ctx.Adapter.GetTypeName (ctx, type.Type)}");
			}
		}

		public override ValueReference VisitIdentifierName (IdentifierNameSyntax node)
		{
			var name = node.Identifier.ValueText;

			if (name == "__EXCEPTION_OBJECT__")
				return ctx.Adapter.GetCurrentException (ctx);

			// Look in user defined variables

			ValueReference userVar;
			if (userVariables.TryGetValue (name, out userVar))
				return userVar;

			// Look in variables

			ValueReference var = ctx.Adapter.GetLocalVariable (ctx, name);
			if (var != null)
				return var;

			// Look in parameters

			var = ctx.Adapter.GetParameter (ctx, name);
			if (var != null)
				return var;

			// Look in instance fields and properties

			ValueReference self = ctx.Adapter.GetThisReference (ctx);

			if (self != null) {
				// check for fields and properties in this instance

				// first try if current type has field or property
				var = ctx.Adapter.GetMember (ctx, self, ctx.Adapter.GetEnclosingType (ctx), self.Value, name);
				if (var != null)
					return var;
				
				var = ctx.Adapter.GetMember (ctx, self, self.Type, self.Value, name);
				if (var != null)
					return var;
			}

			// Look in static fields & properties of the enclosing type and all parent types

			object type = ctx.Adapter.GetEnclosingType (ctx);
			object vtype = type;

			while (vtype != null) {
				// check for static fields and properties
				var = ctx.Adapter.GetMember (ctx, null, vtype, null, name);
				if (var != null)
					return var;

				vtype = ctx.Adapter.GetParentType (ctx, vtype);
			}

			// Look in types

			vtype = ctx.Adapter.GetType (ctx, name);
			if (vtype != null)
				return new TypeValueReference (ctx, vtype);

			if (self == null && ctx.Adapter.HasMember (ctx, type, name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)) {
				string message = string.Format ("An object reference is required for the non-static field, method, or property '{0}.{1}'.",
				                                ctx.Adapter.GetDisplayTypeName (ctx, type), name);
				throw ParseError (message);
			}

			throw ParseError ("Unknown identifier: {0}", name);
		}

		public override ValueReference VisitElementAccessExpression (ElementAccessExpressionSyntax node)
		{
			int n = 0;

			var target = Visit(node.Expression);
			if (target is TypeValueReference)
				throw NotSupported ();

			if (ctx.Adapter.IsArray (ctx, target.Value)) {
				int[] indexes = new int [node.ArgumentList.Arguments.Count];

				foreach (var arg in node.ArgumentList.Arguments) {
					var index = Visit(arg);
					indexes[n++] = (int) Convert.ChangeType (index.ObjectValue, typeof (int));
				}

				return new ArrayValueReference (ctx, target.Value, indexes);
			}

			object[] args = new object [node.ArgumentList.Arguments.Count];
			foreach (var arg in node.ArgumentList.Arguments)
				args[n++] = Visit (arg).Value;

			var indexer = ctx.Adapter.GetIndexerReference (ctx, target.Value, target.Type, args);
			if (indexer == null)
				throw NotSupported ();

			return indexer;
		}

		string ResolveMethodName (SyntaxNode invocationExpression, out object[] typeArgs)
		{
			if (invocationExpression is IdentifierNameSyntax id) {
				typeArgs = null;
				return id.Identifier.ValueText;
			}
			if (invocationExpression is GenericNameSyntax gns) {
				if (gns.Arity > 0) {
					var args = new List<object> ();

					foreach (var arg in gns.TypeArgumentList.Arguments) {
						var type = Visit(arg);
						args.Add (type.Type);
					}

					typeArgs = args.ToArray ();
				} else {
					typeArgs = null;
				}
				return gns.Identifier.ValueText;
			}

			typeArgs = null;
			return invocationExpression.ToString ();
		}

		public override ValueReference VisitInvocationExpression (InvocationExpressionSyntax node)
		{
			if (!options.AllowMethodEvaluation)
				throw new ImplicitEvaluationDisabledException ();

			bool invokeBaseMethod = false;
			bool allArgTypesAreResolved = true;
			ValueReference target = null;
			string methodName;

			var types = new object [node.ArgumentList.Arguments.Count];
			var args = new object [node.ArgumentList.Arguments.Count];
			object[] typeArgs = null;
			int n = 0;

			foreach (var arg in node.ArgumentList.Arguments) {
				var vref = this.Visit (arg);
				args[n] = vref.Value;
				types[n] = ctx.Adapter.GetValueType (ctx, args[n]);

				if (ctx.Adapter.IsDelayedType (ctx, types[n]))
					allArgTypesAreResolved = false;
				n++;
			}
			object vtype = null;
			Tuple<int, object>[] resolvedLambdaTypes;

			if (node.Expression is MemberAccessExpressionSyntax field) {
				target = Visit (field.Expression);
				if (field.Expression is BaseExpressionSyntax)
					invokeBaseMethod = true;
				methodName = ResolveMethodName (field, out typeArgs);
			} else if (node.Expression is IdentifierNameSyntax method) {
				var vref = ctx.Adapter.GetThisReference (ctx);

				methodName = ResolveMethodName (method, out typeArgs);

				if (vref != null && ctx.Adapter.HasMethod (ctx, vref.Type, methodName, typeArgs, types, BindingFlags.Instance)) {
					vtype = ctx.Adapter.GetEnclosingType (ctx);
					// There is an instance method for 'this', although it may not have an exact signature match. Check it now.
					if (ctx.Adapter.HasMethod (ctx, vref.Type, methodName, typeArgs, types, BindingFlags.Instance)) {
						target = vref;
					} else {
						// There isn't an instance method with exact signature match.
						// If there isn't a static method, then use the instance method,
						// which will report the signature match error when invoked
						if (!ctx.Adapter.HasMethod (ctx, vtype, methodName, typeArgs, types, BindingFlags.Static))
							target = vref;
					}
				} else {
					if (ctx.Adapter.HasMethod (ctx, ctx.Adapter.GetEnclosingType (ctx), methodName, types, BindingFlags.Instance))
						throw new EvaluatorException ("Cannot invoke an instance method from a static method.");
					target = null;
				}
			} else {
				throw NotSupported ();
			}

			if (vtype == null)
				vtype = target != null ? target.Type : ctx.Adapter.GetEnclosingType (ctx);
			object vtarget = (target is TypeValueReference) || target == null ? null : target.Value;

			var hasMethod = ctx.Adapter.HasMethod (ctx, vtype, methodName, typeArgs, types, BindingFlags.Instance | BindingFlags.Static, out resolvedLambdaTypes);
			if (hasMethod)
				types = UpdateDelayedTypes (types, resolvedLambdaTypes, ref allArgTypesAreResolved);

			if (invokeBaseMethod) {
				vtype = ctx.Adapter.GetBaseType (ctx, vtype);
			} else if (target != null && !hasMethod) {
				// Look for LINQ extension methods...
				var linq = ctx.Adapter.GetType (ctx, "System.Linq.Enumerable");
				if (linq != null) {
					object[] xtypeArgs = typeArgs;

					if (xtypeArgs == null) {
						// try to infer the generic type arguments from the type of the object...
						object xtype = vtype;
						while (xtype != null && !ctx.Adapter.IsGenericType (ctx, xtype))
							xtype = ctx.Adapter.GetBaseType (ctx, xtype);

						if (xtype != null)
							xtypeArgs = ctx.Adapter.GetTypeArgs (ctx, xtype);
					}

					if (xtypeArgs == null && ctx.Adapter.IsArray (ctx, vtarget)) {
						xtypeArgs = new object [] { ctx.Adapter.CreateArrayAdaptor (ctx, vtarget).ElementType };
					}

					if (xtypeArgs != null) {
						var xtypes = new object[types.Length + 1];
						Array.Copy (types, 0, xtypes, 1, types.Length);
						xtypes[0] = vtype;

						var xargs = new object[args.Length + 1];
						Array.Copy (args, 0, xargs, 1, args.Length);
						xargs[0] = vtarget;

						if (ctx.Adapter.HasMethod (ctx, linq, methodName, xtypeArgs, xtypes, BindingFlags.Static, out resolvedLambdaTypes)) {
							vtarget = null;
							vtype = linq;

							typeArgs = xtypeArgs;
							types = UpdateDelayedTypes (xtypes, resolvedLambdaTypes, ref allArgTypesAreResolved);
							args = xargs;
						}
					}
				}
			}

			if (!allArgTypesAreResolved) {
				// TODO: Show detailed error message for why lambda types were not
				// resolved. Major causes are:
				// 1. there is no matched method
				// 2. matched method exists, but the lambda body has some invalid
				// expressions and does not compile
				throw NotSupported ();
			}

			object result = ctx.Adapter.RuntimeInvoke (ctx, vtype, vtarget, methodName, typeArgs, types, args);
			if (result != null)
				return LiteralValueReference.CreateTargetObjectLiteral (ctx, expression, result);

			return LiteralValueReference.CreateVoidReturnLiteral (ctx, expression);
		}


		public override ValueReference VisitSimpleLambdaExpression (SimpleLambdaExpressionSyntax node)
		{
			if (node.AsyncKeyword != null)
				throw NotSupported ();

			var parent = node.Parent;
			while (parent != null && parent is ParenthesizedExpressionSyntax)
				parent = parent.Parent;

			if (parent is InvocationExpressionSyntax || parent is CastExpressionSyntax) {
				var writer = new System.IO.StringWriter ();
				var visitor = new LambdaBodyOutputVisitor (ctx, userVariables, writer);
				visitor.Visit (node);
				var body = writer.ToString ();
				var values = visitor.GetLocalValues ();
				object val = ctx.Adapter.CreateDelayedLambdaValue (ctx, body, values);
				if (val != null)
					return LiteralValueReference.CreateTargetObjectLiteral (ctx, expression, val);
			}

			throw NotSupported ();
		}


		public override ValueReference VisitMemberAccessExpression (MemberAccessExpressionSyntax node)
		{
			if (node.Name is GenericNameSyntax gns)
				return ResolveTypeValueReference (ctx, node);

			var target = Visit (node.Expression);
			var member = target.GetChild (node.Name.Identifier.ValueText, ctx.Options);

			if (member == null) {
				if (!(target is TypeValueReference)) {
					if (ctx.Adapter.IsNull (ctx, target.Value))
						throw new EvaluatorException ("{0} is null", target.Name);
				}

				throw ParseError ("Unknown member: {0}", node.Name.Identifier.ValueText);
			}

			return member;
		}

		public override ValueReference VisitLiteralExpression (LiteralExpressionSyntax node)
		{
			if (node.Kind() == SyntaxKind.NullLiteralExpression)
				return new NullValueReference (ctx, ctx.Adapter.GetType (ctx, "System.Object"));
			return base.VisitLiteralExpression (node);
		}

		public override ValueReference VisitObjectCreationExpression (ObjectCreationExpressionSyntax node)
		{
			var type = Visit(node.Type) as TypeValueReference;
			var args = new List<object> ();

			foreach (var arg in node.ArgumentList.Arguments) {
				var val = Visit(arg);
				args.Add (val != null ? val.Value : null);
			}

			return LiteralValueReference.CreateTargetObjectLiteral (ctx, expression, ctx.Adapter.CreateValue (ctx, type.Type, args.ToArray ()));
		}

		public override ValueReference VisitParenthesizedExpression (ParenthesizedExpressionSyntax node)
		{
			return Visit (node.Expression);
		}

		public override ValueReference VisitPredefinedType (PredefinedTypeSyntax node)
		{
			string longName = "";
			switch (node.Keyword.Value) {
            case "bool":    longName = "System.Boolean"; break;
            case "byte":    longName = "System.Byte"; break;
            case "sbyte":   longName = "System.SByte"; break;
            case "char":    longName = "System.Char"; break;
            case "decimal": longName = "System.Decimal"; break;
            case "double":  longName = "System.Double"; break;
            case "float":   longName = "System.Single"; break;
            case "int":     longName = "System.Int32"; break;
            case "uint":    longName = "System.UInt32"; break;
            case "nint":    longName = "System.IntPtr"; break;
            case "nuint":   longName = "System.UIntPtr"; break;
            case "long":    longName = "System.Int64"; break;
            case "ulong":   longName = "System.UInt64"; break;
            case "short":   longName = "System.Int16"; break;
            case "ushort":  longName = "System.UInt16"; break;
            case "object":  longName = "System.Object"; break;
            case "string":  longName = "System.String"; break;
            case "dynamic": longName = "System.Object"; break;
            default: throw new ArgumentException($"Unknown type {node.Keyword.Value}");
			}
			var type = ctx.Adapter.GetType(ctx, longName);
			return new TypeValueReference (ctx, type);
		}

		public override ValueReference VisitThisExpression (ThisExpressionSyntax node)
		{
			var self = ctx.Adapter.GetThisReference (ctx);

			if (self == null)
				throw ParseError ("'this' reference not available in the current evaluation context.");

			return self;
		}

		public override ValueReference VisitTypeOfExpression (TypeOfExpressionSyntax node)
		{
			var name = ResolveTypeName (node.Type);
			var type = node.Type.Resolve (ctx);

			if (type == null)
				throw ParseError ("Could not load type: {0}", name);

			object result = ctx.Adapter.CreateTypeObject (ctx, type);
			if (result == null)
				throw NotSupported ();

			return LiteralValueReference.CreateTargetObjectLiteral (ctx, name, result);
		}

		//public ValueReference VisitTypeReferenceExpression(TypeReferenceExpression typeReferenceExpression)
		//{
		//	var type = typeReferenceExpression.Type.Resolve(ctx);

		//	if (type != null)
		//	{
		//		ctx.Adapter.ForceLoadType(ctx, type);

		//		return new TypeValueReference(ctx, type);
		//	}

		//	var name = ResolveTypeName(typeReferenceExpression.Type);

		//	// Assume it is a namespace.
		//	return new NamespaceValueReference(ctx, name);
		//}

		public override ValueReference VisitPostfixUnaryExpression (PostfixUnaryExpressionSyntax node)
		{
			var vref = Visit (node.Operand);
			var val = vref.ObjectValue;
			object newVal;
			long num;

			switch (node.Kind ()) {
			case SyntaxKind.PostDecrementExpression:
				if (val is decimal) {
					newVal = ((decimal)val) - 1;
				} else if (val is double) {
					newVal = ((double)val) - 1;
				} else if (val is float) {
					newVal = ((float)val) - 1;
				} else {
					num = GetInteger (val) - 1;
					newVal = Convert.ChangeType (num, val.GetType ());
				}
				vref.Value = ctx.Adapter.CreateValue (ctx, newVal);
				break;
			case SyntaxKind.PostIncrementExpression:
				if (val is decimal) {
					newVal = ((decimal)val) + 1;
				} else if (val is double) {
					newVal = ((double)val) + 1;
				} else if (val is float) {
					newVal = ((float)val) + 1;
				} else {
					num = GetInteger (val) + 1;
					newVal = Convert.ChangeType (num, val.GetType ());
				}
				vref.Value = ctx.Adapter.CreateValue (ctx, newVal);
				break;
			default:
				throw NotSupported ();
			}

			return LiteralValueReference.CreateObjectLiteral (ctx, expression, val);
		}

		public override ValueReference VisitPrefixUnaryExpression (PrefixUnaryExpressionSyntax node)
		{
			var vref = Visit (node.Operand);
			var val = vref.ObjectValue;
			object newVal;
			long num;

			switch (node.Kind ()) {
			case SyntaxKind.BitwiseNotExpression:
				num = ~GetInteger (val);
				val = Convert.ChangeType (num, val.GetType ());
				break;
			case SyntaxKind.UnaryMinusExpression:
				if (val is decimal) {
					val = -(decimal)val;
				} else if (val is double) {
					val = -(double)val;
				} else if (val is float) {
					val = -(float)val;
				} else {
					num = -GetInteger (val);
					val = Convert.ChangeType (num, val.GetType ());
				}
				break;
			case SyntaxKind.LogicalNotExpression:
				if (!(val is bool))
					throw ParseError ("Expected boolean type in Not operator.");

				val = !(bool)val;
				break;
			case SyntaxKind.PreDecrementExpression:
				if (val is decimal) {
					val = ((decimal)val) - 1;
				} else if (val is double) {
					val = ((double)val) - 1;
				} else if (val is float) {
					val = ((float)val) - 1;
				} else {
					num = GetInteger (val) - 1;
					val = Convert.ChangeType (num, val.GetType ());
				}
				vref.Value = ctx.Adapter.CreateValue (ctx, val);
				break;
			case SyntaxKind.PreIncrementExpression:
				if (val is decimal) {
					val = ((decimal)val) + 1;
				} else if (val is double) {
					val = ((double)val) + 1;
				} else if (val is float) {
					val = ((float)val) + 1;
				} else {
					num = GetInteger (val) + 1;
					val = Convert.ChangeType (num, val.GetType ());
				}
				vref.Value = ctx.Adapter.CreateValue (ctx, val);
				break;
			case SyntaxKind.UnaryPlusExpression:
				break;
			default:
				throw NotSupported ();
			}

			return LiteralValueReference.CreateObjectLiteral (ctx, expression, val);
		}

		public override ValueReference VisitArgument (ArgumentSyntax node)
		{
			//public void MethodWithTypeGenericArgsEval()
			//{
			//	var a = new A("Just A");
			//	var wrappedA = new Wrapper<A>(new A("wrappedA"));
			//	var genericClass = new GenericClass<A>(new A("Constructor arg A"));
			//	//genericClass.BaseMethodWithClassTArg (wrappedA);
			//	//genericClass.RetMethodWithClassTArg (a)
			//	Console.WriteLine("Break for MethodWithTypeGenericArgsEval");/*ba6350e5-7149-4cc2-a4cf-8a54c635eb38*/
			//}

			//class GenericBaseClass<TBaseClassArg>
			//               {
			//                   public readonly TBaseClassArg myArg;

			//                   public GenericBaseClass(TBaseClassArg arg)
			//                   {
			//                       myArg = arg;
			//                   }

			//                   public TBaseClassArg BaseMethodWithClassTArg(TBaseClassArg arg)
			//                   {
			//                       return arg;
			//                   }
			//               }

			//var baseMethodEval = Eval("genericClass.BaseMethodWithClassTArg (wrappedA)");
			//Assert.NotNull(baseMethodEval);
			//Assert.AreEqual("{Wrapper(wrappedA)}", baseMethodEval.Value)
			return base.VisitArgument (node);
		}

		public override ValueReference DefaultVisit (SyntaxNode node)
		{
			if (node is LiteralExpressionSyntax syntax)
			{
				return LiteralValueReference.CreateObjectLiteral(ctx, expression, syntax.Token.Value);
			}
			throw NotSupported();
		}
		#endregion
	}
}