2003-07-21 Martin Baulig <martin@ximian.com>
[mono.git] / mcs / mcs / expression.cs
1 //
2 // expression.cs: Expression representation for the IL tree.
3 //
4 // Author:
5 //   Miguel de Icaza (miguel@ximian.com)
6 //
7 // (C) 2001 Ximian, Inc.
8 //
9 //
10 #define USE_OLD
11
12 namespace Mono.CSharp {
13         using System;
14         using System.Collections;
15         using System.Reflection;
16         using System.Reflection.Emit;
17         using System.Text;
18
19         /// <summary>
20         ///   This is just a helper class, it is generated by Unary, UnaryMutator
21         ///   when an overloaded method has been found.  It just emits the code for a
22         ///   static call.
23         /// </summary>
24         public class StaticCallExpr : ExpressionStatement {
25                 ArrayList args;
26                 MethodInfo mi;
27
28                 public StaticCallExpr (MethodInfo m, ArrayList a, Location l)
29                 {
30                         mi = m;
31                         args = a;
32
33                         type = m.ReturnType;
34                         eclass = ExprClass.Value;
35                         loc = l;
36                 }
37
38                 public override Expression DoResolve (EmitContext ec)
39                 {
40                         //
41                         // We are born fully resolved
42                         //
43                         return this;
44                 }
45
46                 public override void Emit (EmitContext ec)
47                 {
48                         if (args != null) 
49                                 Invocation.EmitArguments (ec, mi, args);
50
51                         ec.ig.Emit (OpCodes.Call, mi);
52                         return;
53                 }
54                 
55                 static public Expression MakeSimpleCall (EmitContext ec, MethodGroupExpr mg,
56                                                          Expression e, Location loc)
57                 {
58                         ArrayList args;
59                         MethodBase method;
60                         
61                         args = new ArrayList (1);
62                         Argument a = new Argument (e, Argument.AType.Expression);
63
64                         // We need to resolve the arguments before sending them in !
65                         if (!a.Resolve (ec, loc))
66                                 return null;
67
68                         args.Add (a);
69                         method = Invocation.OverloadResolve (ec, (MethodGroupExpr) mg, args, loc);
70
71                         if (method == null)
72                                 return null;
73
74                         return new StaticCallExpr ((MethodInfo) method, args, loc);
75                 }
76
77                 public override void EmitStatement (EmitContext ec)
78                 {
79                         Emit (ec);
80                         if (TypeManager.TypeToCoreType (type) != TypeManager.void_type)
81                                 ec.ig.Emit (OpCodes.Pop);
82                 }
83         }
84         
85         /// <summary>
86         ///   Unary expressions.  
87         /// </summary>
88         ///
89         /// <remarks>
90         ///   Unary implements unary expressions.   It derives from
91         ///   ExpressionStatement becuase the pre/post increment/decrement
92         ///   operators can be used in a statement context.
93         /// </remarks>
94         public class Unary : Expression {
95                 public enum Operator : byte {
96                         UnaryPlus, UnaryNegation, LogicalNot, OnesComplement,
97                         Indirection, AddressOf,  TOP
98                 }
99
100                 public Operator Oper;
101                 public Expression Expr;
102                 
103                 public Unary (Operator op, Expression expr, Location loc)
104                 {
105                         this.Oper = op;
106                         this.Expr = expr;
107                         this.loc = loc;
108                 }
109
110                 /// <summary>
111                 ///   Returns a stringified representation of the Operator
112                 /// </summary>
113                 static public string OperName (Operator oper)
114                 {
115                         switch (oper){
116                         case Operator.UnaryPlus:
117                                 return "+";
118                         case Operator.UnaryNegation:
119                                 return "-";
120                         case Operator.LogicalNot:
121                                 return "!";
122                         case Operator.OnesComplement:
123                                 return "~";
124                         case Operator.AddressOf:
125                                 return "&";
126                         case Operator.Indirection:
127                                 return "*";
128                         }
129
130                         return oper.ToString ();
131                 }
132
133                 public static readonly string [] oper_names;
134
135                 static Unary ()
136                 {
137                         oper_names = new string [(int)Operator.TOP];
138
139                         oper_names [(int) Operator.UnaryPlus] = "op_UnaryPlus";
140                         oper_names [(int) Operator.UnaryNegation] = "op_UnaryNegation";
141                         oper_names [(int) Operator.LogicalNot] = "op_LogicalNot";
142                         oper_names [(int) Operator.OnesComplement] = "op_OnesComplement";
143                         oper_names [(int) Operator.Indirection] = "op_Indirection";
144                         oper_names [(int) Operator.AddressOf] = "op_AddressOf";
145                 }
146
147                 void Error23 (Type t)
148                 {
149                         Error (
150                                 23, "Operator " + OperName (Oper) +
151                                 " cannot be applied to operand of type `" +
152                                 TypeManager.CSharpName (t) + "'");
153                 }
154
155                 /// <remarks>
156                 ///   The result has been already resolved:
157                 ///
158                 ///   FIXME: a minus constant -128 sbyte cant be turned into a
159                 ///   constant byte.
160                 /// </remarks>
161                 static Expression TryReduceNegative (Constant expr)
162                 {
163                         Expression e = null;
164
165                         if (expr is IntConstant)
166                                 e = new IntConstant (-((IntConstant) expr).Value);
167                         else if (expr is UIntConstant){
168                                 uint value = ((UIntConstant) expr).Value;
169
170                                 if (value < 2147483649)
171                                         return new IntConstant (-(int)value);
172                                 else
173                                         e = new LongConstant (-value);
174                         }
175                         else if (expr is LongConstant)
176                                 e = new LongConstant (-((LongConstant) expr).Value);
177                         else if (expr is ULongConstant){
178                                 ulong value = ((ULongConstant) expr).Value;
179
180                                 if (value < 9223372036854775809)
181                                         return new LongConstant(-(long)value);
182                         }
183                         else if (expr is FloatConstant)
184                                 e = new FloatConstant (-((FloatConstant) expr).Value);
185                         else if (expr is DoubleConstant)
186                                 e = new DoubleConstant (-((DoubleConstant) expr).Value);
187                         else if (expr is DecimalConstant)
188                                 e = new DecimalConstant (-((DecimalConstant) expr).Value);
189                         else if (expr is ShortConstant)
190                                 e = new IntConstant (-((ShortConstant) expr).Value);
191                         else if (expr is UShortConstant)
192                                 e = new IntConstant (-((UShortConstant) expr).Value);
193                         return e;
194                 }
195
196                 // <summary>
197                 //   This routine will attempt to simplify the unary expression when the
198                 //   argument is a constant.  The result is returned in `result' and the
199                 //   function returns true or false depending on whether a reduction
200                 //   was performed or not
201                 // </summary>
202                 bool Reduce (EmitContext ec, Constant e, out Expression result)
203                 {
204                         Type expr_type = e.Type;
205                         
206                         switch (Oper){
207                         case Operator.UnaryPlus:
208                                 result = e;
209                                 return true;
210                                 
211                         case Operator.UnaryNegation:
212                                 result = TryReduceNegative (e);
213                                 return true;
214                                 
215                         case Operator.LogicalNot:
216                                 if (expr_type != TypeManager.bool_type) {
217                                         result = null;
218                                         Error23 (expr_type);
219                                         return false;
220                                 }
221                                 
222                                 BoolConstant b = (BoolConstant) e;
223                                 result = new BoolConstant (!(b.Value));
224                                 return true;
225                                 
226                         case Operator.OnesComplement:
227                                 if (!((expr_type == TypeManager.int32_type) ||
228                                       (expr_type == TypeManager.uint32_type) ||
229                                       (expr_type == TypeManager.int64_type) ||
230                                       (expr_type == TypeManager.uint64_type) ||
231                                       (expr_type.IsSubclassOf (TypeManager.enum_type)))){
232
233                                         result = null;
234                                         if (Convert.ImplicitConversionExists (ec, e, TypeManager.int32_type)){
235                                                 result = new Cast (new TypeExpr (TypeManager.int32_type, loc), e, loc);
236                                                 result = result.Resolve (ec);
237                                         } else if (Convert.ImplicitConversionExists (ec, e, TypeManager.uint32_type)){
238                                                 result = new Cast (new TypeExpr (TypeManager.uint32_type, loc), e, loc);
239                                                 result = result.Resolve (ec);
240                                         } else if (Convert.ImplicitConversionExists (ec, e, TypeManager.int64_type)){
241                                                 result = new Cast (new TypeExpr (TypeManager.int64_type, loc), e, loc);
242                                                 result = result.Resolve (ec);
243                                         } else if (Convert.ImplicitConversionExists (ec, e, TypeManager.uint64_type)){
244                                                 result = new Cast (new TypeExpr (TypeManager.uint64_type, loc), e, loc);
245                                                 result = result.Resolve (ec);
246                                         }
247
248                                         if (result == null || !(result is Constant)){
249                                                 result = null;
250                                                 Error23 (expr_type);
251                                                 return false;
252                                         }
253
254                                         expr_type = result.Type;
255                                         e = (Constant) result;
256                                 }
257
258                                 if (e is EnumConstant){
259                                         EnumConstant enum_constant = (EnumConstant) e;
260                                         Expression reduced;
261                                         
262                                         if (Reduce (ec, enum_constant.Child, out reduced)){
263                                                 result = new EnumConstant ((Constant) reduced, enum_constant.Type);
264                                                 return true;
265                                         } else {
266                                                 result = null;
267                                                 return false;
268                                         }
269                                 }
270
271                                 if (expr_type == TypeManager.int32_type){
272                                         result = new IntConstant (~ ((IntConstant) e).Value);
273                                 } else if (expr_type == TypeManager.uint32_type){
274                                         result = new UIntConstant (~ ((UIntConstant) e).Value);
275                                 } else if (expr_type == TypeManager.int64_type){
276                                         result = new LongConstant (~ ((LongConstant) e).Value);
277                                 } else if (expr_type == TypeManager.uint64_type){
278                                         result = new ULongConstant (~ ((ULongConstant) e).Value);
279                                 } else {
280                                         result = null;
281                                         Error23 (expr_type);
282                                         return false;
283                                 }
284                                 return true;
285
286                         case Operator.AddressOf:
287                                 result = this;
288                                 return false;
289
290                         case Operator.Indirection:
291                                 result = this;
292                                 return false;
293                         }
294                         throw new Exception ("Can not constant fold: " + Oper.ToString());
295                 }
296
297                 Expression ResolveOperator (EmitContext ec)
298                 {
299                         Type expr_type = Expr.Type;
300
301                         //
302                         // Step 1: Perform Operator Overload location
303                         //
304                         Expression mg;
305                         string op_name;
306                         
307                         op_name = oper_names [(int) Oper];
308
309                         mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
310                         
311                         if (mg != null) {
312                                 Expression e = StaticCallExpr.MakeSimpleCall (
313                                         ec, (MethodGroupExpr) mg, Expr, loc);
314
315                                 if (e == null){
316                                         Error23 (expr_type);
317                                         return null;
318                                 }
319                                 
320                                 return e;
321                         }
322
323                         // Only perform numeric promotions on:
324                         // +, - 
325
326                         if (expr_type == null)
327                                 return null;
328                         
329                         //
330                         // Step 2: Default operations on CLI native types.
331                         //
332
333                         // Attempt to use a constant folding operation.
334                         if (Expr is Constant){
335                                 Expression result;
336                                 
337                                 if (Reduce (ec, (Constant) Expr, out result))
338                                         return result;
339                         }
340
341                         switch (Oper){
342                         case Operator.LogicalNot:
343                                 if (expr_type != TypeManager.bool_type) {
344                                         Expr = ResolveBoolean (ec, Expr, loc);
345                                         if (Expr == null){
346                                                 Error23 (expr_type);
347                                                 return null;
348                                         }
349                                 }
350                                 
351                                 type = TypeManager.bool_type;
352                                 return this;
353
354                         case Operator.OnesComplement:
355                                 if (!((expr_type == TypeManager.int32_type) ||
356                                       (expr_type == TypeManager.uint32_type) ||
357                                       (expr_type == TypeManager.int64_type) ||
358                                       (expr_type == TypeManager.uint64_type) ||
359                                       (expr_type.IsSubclassOf (TypeManager.enum_type)))){
360                                         Expression e;
361
362                                         e = Convert.ImplicitConversion (ec, Expr, TypeManager.int32_type, loc);
363                                         if (e != null){
364                                                 type = TypeManager.int32_type;
365                                                 return this;
366                                         }
367                                         e = Convert.ImplicitConversion (ec, Expr, TypeManager.uint32_type, loc);
368                                         if (e != null){
369                                                 type = TypeManager.uint32_type;
370                                                 return this;
371                                         }
372                                         e = Convert.ImplicitConversion (ec, Expr, TypeManager.int64_type, loc);
373                                         if (e != null){
374                                                 type = TypeManager.int64_type;
375                                                 return this;
376                                         }
377                                         e = Convert.ImplicitConversion (ec, Expr, TypeManager.uint64_type, loc);
378                                         if (e != null){
379                                                 type = TypeManager.uint64_type;
380                                                 return this;
381                                         }
382                                         Error23 (expr_type);
383                                         return null;
384                                 }
385                                 type = expr_type;
386                                 return this;
387
388                         case Operator.AddressOf:
389                                 if (Expr.eclass != ExprClass.Variable){
390                                         Error (211, "Cannot take the address of non-variables");
391                                         return null;
392                                 }
393                                 
394                                 if (!ec.InUnsafe) {
395                                         UnsafeError (loc); 
396                                         return null;
397                                 }
398                                 
399                                 if (!TypeManager.VerifyUnManaged (Expr.Type, loc)){
400                                         return null;
401                                 }
402
403                                 IVariable variable = Expr as IVariable;
404                                 if (!ec.InFixedInitializer && ((variable == null) || !variable.VerifyFixed (false))) {
405                                         Error (212, "You can only take the address of an unfixed expression inside " +
406                                                "of a fixed statement initializer");
407                                         return null;
408                                 }
409
410                                 // According to the specs, a variable is considered definitely assigned if you take
411                                 // its address.
412                                 if ((variable != null) && (variable.VariableInfo != null))
413                                         variable.VariableInfo.SetAssigned (ec);
414
415                                 type = TypeManager.GetPointerType (Expr.Type);
416                                 return this;
417
418                         case Operator.Indirection:
419                                 if (!ec.InUnsafe){
420                                         UnsafeError (loc);
421                                         return null;
422                                 }
423                                 
424                                 if (!expr_type.IsPointer){
425                                         Error (193, "The * or -> operator can only be applied to pointers");
426                                         return null;
427                                 }
428                                 
429                                 //
430                                 // We create an Indirection expression, because
431                                 // it can implement the IMemoryLocation.
432                                 // 
433                                 return new Indirection (Expr, loc);
434                         
435                         case Operator.UnaryPlus:
436                                 //
437                                 // A plus in front of something is just a no-op, so return the child.
438                                 //
439                                 return Expr;
440
441                         case Operator.UnaryNegation:
442                                 //
443                                 // Deals with -literals
444                                 // int     operator- (int x)
445                                 // long    operator- (long x)
446                                 // float   operator- (float f)
447                                 // double  operator- (double d)
448                                 // decimal operator- (decimal d)
449                                 //
450                                 Expression expr = null;
451
452                                 //
453                                 // transform - - expr into expr
454                                 //
455                                 if (Expr is Unary){
456                                         Unary unary = (Unary) Expr;
457                                         
458                                         if (unary.Oper == Operator.UnaryNegation)
459                                                 return unary.Expr;
460                                 }
461
462                                 //
463                                 // perform numeric promotions to int,
464                                 // long, double.
465                                 //
466                                 //
467                                 // The following is inneficient, because we call
468                                 // ImplicitConversion too many times.
469                                 //
470                                 // It is also not clear if we should convert to Float
471                                 // or Double initially.
472                                 //
473                                 if (expr_type == TypeManager.uint32_type){
474                                         //
475                                         // FIXME: handle exception to this rule that
476                                         // permits the int value -2147483648 (-2^31) to
477                                         // bt wrote as a decimal interger literal
478                                         //
479                                         type = TypeManager.int64_type;
480                                         Expr = Convert.ImplicitConversion (ec, Expr, type, loc);
481                                         return this;
482                                 }
483
484                                 if (expr_type == TypeManager.uint64_type){
485                                         //
486                                         // FIXME: Handle exception of `long value'
487                                         // -92233720368547758087 (-2^63) to be wrote as
488                                         // decimal integer literal.
489                                         //
490                                         Error23 (expr_type);
491                                         return null;
492                                 }
493
494                                 if (expr_type == TypeManager.float_type){
495                                         type = expr_type;
496                                         return this;
497                                 }
498                                 
499                                 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.int32_type, loc);
500                                 if (expr != null){
501                                         Expr = expr;
502                                         type = expr.Type;
503                                         return this;
504                                 } 
505
506                                 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.int64_type, loc);
507                                 if (expr != null){
508                                         Expr = expr;
509                                         type = expr.Type;
510                                         return this;
511                                 }
512
513                                 expr = Convert.ImplicitConversion (ec, Expr, TypeManager.double_type, loc);
514                                 if (expr != null){
515                                         Expr = expr;
516                                         type = expr.Type;
517                                         return this;
518                                 }
519                                 
520                                 Error23 (expr_type);
521                                 return null;
522                         }
523
524                         Error (187, "No such operator '" + OperName (Oper) + "' defined for type '" +
525                                TypeManager.CSharpName (expr_type) + "'");
526                         return null;
527                 }
528
529                 public override Expression DoResolve (EmitContext ec)
530                 {
531                         if (Oper == Operator.AddressOf)
532                                 Expr = Expr.ResolveLValue (ec, new EmptyExpression ());
533                         else
534                                 Expr = Expr.Resolve (ec);
535                         
536                         if (Expr == null)
537                                 return null;
538
539                         eclass = ExprClass.Value;
540                         return ResolveOperator (ec);
541                 }
542
543                 public override void Emit (EmitContext ec)
544                 {
545                         ILGenerator ig = ec.ig;
546                         Type expr_type = Expr.Type;
547                         
548                         switch (Oper) {
549                         case Operator.UnaryPlus:
550                                 throw new Exception ("This should be caught by Resolve");
551                                 
552                         case Operator.UnaryNegation:
553                                 Expr.Emit (ec);
554                                 ig.Emit (OpCodes.Neg);
555                                 break;
556                                 
557                         case Operator.LogicalNot:
558                                 Expr.Emit (ec);
559                                 ig.Emit (OpCodes.Ldc_I4_0);
560                                 ig.Emit (OpCodes.Ceq);
561                                 break;
562                                 
563                         case Operator.OnesComplement:
564                                 Expr.Emit (ec);
565                                 ig.Emit (OpCodes.Not);
566                                 break;
567                                 
568                         case Operator.AddressOf:
569                                 ((IMemoryLocation)Expr).AddressOf (ec, AddressOp.LoadStore);
570                                 break;
571                                 
572                         default:
573                                 throw new Exception ("This should not happen: Operator = "
574                                                      + Oper.ToString ());
575                         }
576                 }
577
578                 /// <summary>
579                 ///   This will emit the child expression for `ec' avoiding the logical
580                 ///   not.  The parent will take care of changing brfalse/brtrue
581                 /// </summary>
582                 public void EmitLogicalNot (EmitContext ec)
583                 {
584                         if (Oper != Operator.LogicalNot)
585                                 throw new Exception ("EmitLogicalNot can only be called with !expr");
586
587                         Expr.Emit (ec);
588                 }
589
590                 public override string ToString ()
591                 {
592                         return "Unary (" + Oper + ", " + Expr + ")";
593                 }
594                 
595         }
596
597         //
598         // Unary operators are turned into Indirection expressions
599         // after semantic analysis (this is so we can take the address
600         // of an indirection).
601         //
602         public class Indirection : Expression, IMemoryLocation, IAssignMethod {
603                 Expression expr;
604                 LocalTemporary temporary;
605                 bool have_temporary;
606                 
607                 public Indirection (Expression expr, Location l)
608                 {
609                         this.expr = expr;
610                         this.type = TypeManager.TypeToCoreType (expr.Type.GetElementType ());
611                         eclass = ExprClass.Variable;
612                         loc = l;
613                 }
614
615                 void LoadExprValue (EmitContext ec)
616                 {
617                 }
618                 
619                 public override void Emit (EmitContext ec)
620                 {
621                         ILGenerator ig = ec.ig;
622
623                         if (temporary != null){
624                                 if (have_temporary){
625                                         temporary.Emit (ec);
626                                         return;
627                                 }
628                                 expr.Emit (ec);
629                                 ec.ig.Emit (OpCodes.Dup);
630                                 temporary.Store (ec);
631                                 have_temporary = true;
632                         } else
633                                 expr.Emit (ec);
634                         
635                         LoadFromPtr (ig, Type);
636                 }
637
638                 public void EmitAssign (EmitContext ec, Expression source)
639                 {
640                         if (temporary != null){
641                                 if (have_temporary)
642                                         temporary.Emit (ec);
643                                 else {
644                                         expr.Emit (ec);
645                                         ec.ig.Emit (OpCodes.Dup);
646                                         temporary.Store (ec);
647                                         have_temporary = true;
648                                 }
649                         } else 
650                                 expr.Emit (ec);
651
652                         source.Emit (ec);
653                         StoreFromPtr (ec.ig, type);
654                 }
655                 
656                 public void AddressOf (EmitContext ec, AddressOp Mode)
657                 {
658                         if (temporary != null){
659                                 if (have_temporary){
660                                         temporary.Emit (ec);
661                                         return;
662                                 }
663                                 expr.Emit (ec);
664                                 ec.ig.Emit (OpCodes.Dup);
665                                 temporary.Store (ec);
666                                 have_temporary = true;
667                         } else
668                                 expr.Emit (ec);
669                 }
670
671                 public override Expression DoResolve (EmitContext ec)
672                 {
673                         //
674                         // Born fully resolved
675                         //
676                         return this;
677                 }
678
679                 public new void CacheTemporaries (EmitContext ec)
680                 {
681                         temporary = new LocalTemporary (ec, type);
682                 }
683
684                 public override string ToString ()
685                 {
686                         return "*(" + expr + ")";
687                 }
688         }
689         
690         /// <summary>
691         ///   Unary Mutator expressions (pre and post ++ and --)
692         /// </summary>
693         ///
694         /// <remarks>
695         ///   UnaryMutator implements ++ and -- expressions.   It derives from
696         ///   ExpressionStatement becuase the pre/post increment/decrement
697         ///   operators can be used in a statement context.
698         ///
699         /// FIXME: Idea, we could split this up in two classes, one simpler
700         /// for the common case, and one with the extra fields for more complex
701         /// classes (indexers require temporary access;  overloaded require method)
702         ///
703         /// </remarks>
704         public class UnaryMutator : ExpressionStatement {
705                 [Flags]
706                 public enum Mode : byte {
707                         IsIncrement    = 0,
708                         IsDecrement    = 1,
709                         IsPre          = 0,
710                         IsPost         = 2,
711                         
712                         PreIncrement   = 0,
713                         PreDecrement   = IsDecrement,
714                         PostIncrement  = IsPost,
715                         PostDecrement  = IsPost | IsDecrement
716                 }
717                 
718                 Mode mode;
719                 Expression expr;
720                 LocalTemporary temp_storage;
721
722                 //
723                 // This is expensive for the simplest case.
724                 //
725                 Expression method;
726                         
727                 public UnaryMutator (Mode m, Expression e, Location l)
728                 {
729                         mode = m;
730                         loc = l;
731                         expr = e;
732                 }
733
734                 static string OperName (Mode mode)
735                 {
736                         return (mode == Mode.PreIncrement || mode == Mode.PostIncrement) ?
737                                 "++" : "--";
738                 }
739                 
740                 void Error23 (Type t)
741                 {
742                         Error (
743                                 23, "Operator " + OperName (mode) + 
744                                 " cannot be applied to operand of type `" +
745                                 TypeManager.CSharpName (t) + "'");
746                 }
747
748                 /// <summary>
749                 ///   Returns whether an object of type `t' can be incremented
750                 ///   or decremented with add/sub (ie, basically whether we can
751                 ///   use pre-post incr-decr operations on it, but it is not a
752                 ///   System.Decimal, which we require operator overloading to catch)
753                 /// </summary>
754                 static bool IsIncrementableNumber (Type t)
755                 {
756                         return (t == TypeManager.sbyte_type) ||
757                                 (t == TypeManager.byte_type) ||
758                                 (t == TypeManager.short_type) ||
759                                 (t == TypeManager.ushort_type) ||
760                                 (t == TypeManager.int32_type) ||
761                                 (t == TypeManager.uint32_type) ||
762                                 (t == TypeManager.int64_type) ||
763                                 (t == TypeManager.uint64_type) ||
764                                 (t == TypeManager.char_type) ||
765                                 (t.IsSubclassOf (TypeManager.enum_type)) ||
766                                 (t == TypeManager.float_type) ||
767                                 (t == TypeManager.double_type) ||
768                                 (t.IsPointer && t != TypeManager.void_ptr_type);
769                 }
770
771                 Expression ResolveOperator (EmitContext ec)
772                 {
773                         Type expr_type = expr.Type;
774
775                         //
776                         // Step 1: Perform Operator Overload location
777                         //
778                         Expression mg;
779                         string op_name;
780                         
781                         if (mode == Mode.PreIncrement || mode == Mode.PostIncrement)
782                                 op_name = "op_Increment";
783                         else 
784                                 op_name = "op_Decrement";
785
786                         mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
787
788                         if (mg == null && expr_type.BaseType != null)
789                                 mg = MemberLookup (ec, expr_type.BaseType, op_name,
790                                                    MemberTypes.Method, AllBindingFlags, loc);
791                         
792                         if (mg != null) {
793                                 method = StaticCallExpr.MakeSimpleCall (
794                                         ec, (MethodGroupExpr) mg, expr, loc);
795
796                                 type = method.Type;
797                                 return this;
798                         }
799
800                         //
801                         // The operand of the prefix/postfix increment decrement operators
802                         // should be an expression that is classified as a variable,
803                         // a property access or an indexer access
804                         //
805                         type = expr_type;
806                         if (expr.eclass == ExprClass.Variable){
807                                 if (IsIncrementableNumber (expr_type) ||
808                                     expr_type == TypeManager.decimal_type){
809                                         return this;
810                                 }
811                         } else if (expr.eclass == ExprClass.IndexerAccess){
812                                 IndexerAccess ia = (IndexerAccess) expr;
813                                 
814                                 temp_storage = new LocalTemporary (ec, expr.Type);
815                                 
816                                 expr = ia.ResolveLValue (ec, temp_storage);
817                                 if (expr == null)
818                                         return null;
819
820                                 return this;
821                         } else if (expr.eclass == ExprClass.PropertyAccess){
822                                 PropertyExpr pe = (PropertyExpr) expr;
823
824                                 if (pe.VerifyAssignable ())
825                                         return this;
826
827                                 return null;
828                         } else {
829                                 expr.Error_UnexpectedKind ("variable, indexer or property access");
830                                 return null;
831                         }
832
833                         Error (187, "No such operator '" + OperName (mode) + "' defined for type '" +
834                                TypeManager.CSharpName (expr_type) + "'");
835                         return null;
836                 }
837
838                 public override Expression DoResolve (EmitContext ec)
839                 {
840                         expr = expr.Resolve (ec);
841                         
842                         if (expr == null)
843                                 return null;
844
845                         eclass = ExprClass.Value;
846                         return ResolveOperator (ec);
847                 }
848
849                 static int PtrTypeSize (Type t)
850                 {
851                         return GetTypeSize (t.GetElementType ());
852                 }
853
854                 //
855                 // Loads the proper "1" into the stack based on the type, then it emits the
856                 // opcode for the operation requested
857                 //
858                 void LoadOneAndEmitOp (EmitContext ec, Type t)
859                 {
860                         //
861                         // Measure if getting the typecode and using that is more/less efficient
862                         // that comparing types.  t.GetTypeCode() is an internal call.
863                         //
864                         ILGenerator ig = ec.ig;
865                                                      
866                         if (t == TypeManager.uint64_type || t == TypeManager.int64_type)
867                                 LongConstant.EmitLong (ig, 1);
868                         else if (t == TypeManager.double_type)
869                                 ig.Emit (OpCodes.Ldc_R8, 1.0);
870                         else if (t == TypeManager.float_type)
871                                 ig.Emit (OpCodes.Ldc_R4, 1.0F);
872                         else if (t.IsPointer){
873                                 int n = PtrTypeSize (t);
874                                 
875                                 if (n == 0)
876                                         ig.Emit (OpCodes.Sizeof, t);
877                                 else
878                                         IntConstant.EmitInt (ig, n);
879                         } else 
880                                 ig.Emit (OpCodes.Ldc_I4_1);
881
882                         //
883                         // Now emit the operation
884                         //
885                         if (ec.CheckState){
886                                 if (t == TypeManager.int32_type ||
887                                     t == TypeManager.int64_type){
888                                         if ((mode & Mode.IsDecrement) != 0)
889                                                 ig.Emit (OpCodes.Sub_Ovf);
890                                         else
891                                                 ig.Emit (OpCodes.Add_Ovf);
892                                 } else if (t == TypeManager.uint32_type ||
893                                            t == TypeManager.uint64_type){
894                                         if ((mode & Mode.IsDecrement) != 0)
895                                                 ig.Emit (OpCodes.Sub_Ovf_Un);
896                                         else
897                                                 ig.Emit (OpCodes.Add_Ovf_Un);
898                                 } else {
899                                         if ((mode & Mode.IsDecrement) != 0)
900                                                 ig.Emit (OpCodes.Sub_Ovf);
901                                         else
902                                                 ig.Emit (OpCodes.Add_Ovf);
903                                 }
904                         } else {
905                                 if ((mode & Mode.IsDecrement) != 0)
906                                         ig.Emit (OpCodes.Sub);
907                                 else
908                                         ig.Emit (OpCodes.Add);
909                         }
910
911                         if (t == TypeManager.sbyte_type){
912                                 if (ec.CheckState)
913                                         ig.Emit (OpCodes.Conv_Ovf_I1);
914                                 else
915                                         ig.Emit (OpCodes.Conv_I1);
916                         } else if (t == TypeManager.byte_type){
917                                 if (ec.CheckState)
918                                         ig.Emit (OpCodes.Conv_Ovf_U1);
919                                 else
920                                         ig.Emit (OpCodes.Conv_U1);
921                         } else if (t == TypeManager.short_type){
922                                 if (ec.CheckState)
923                                         ig.Emit (OpCodes.Conv_Ovf_I2);
924                                 else
925                                         ig.Emit (OpCodes.Conv_I2);
926                         } else if (t == TypeManager.ushort_type || t == TypeManager.char_type){
927                                 if (ec.CheckState)
928                                         ig.Emit (OpCodes.Conv_Ovf_U2);
929                                 else
930                                         ig.Emit (OpCodes.Conv_U2);
931                         }
932                         
933                 }
934
935                 static EmptyExpression empty_expr;
936                 
937                 void EmitCode (EmitContext ec, bool is_expr)
938                 {
939                         ILGenerator ig = ec.ig;
940                         IAssignMethod ia = (IAssignMethod) expr;
941                         Type expr_type = expr.Type;
942
943                         ia.CacheTemporaries (ec);
944
945                         if (temp_storage == null){
946                                 //
947                                 // Temporary improvement: if we are dealing with something that does
948                                 // not require complicated instance setup, avoid using a temporary
949                                 //
950                                 // For now: only localvariables when not remapped
951                                 //
952
953                                 if (method == null && 
954                                     (expr is LocalVariableReference && ec.RemapToProxy == false) ||
955                                     (expr is FieldExpr && ((FieldExpr) expr).FieldInfo.IsStatic)){
956                                         if (empty_expr == null)
957                                                 empty_expr = new EmptyExpression ();
958                                         
959                                         switch (mode){
960                                         case Mode.PreIncrement:
961                                         case Mode.PreDecrement:
962                                                 expr.Emit (ec);
963                                         
964                                                 LoadOneAndEmitOp (ec, expr_type);
965                                                 if (is_expr)
966                                                         ig.Emit (OpCodes.Dup);
967                                                 ia.EmitAssign (ec, empty_expr);
968                                                 break;
969                                                 
970                                         case Mode.PostIncrement:
971                                         case Mode.PostDecrement:
972                                                 expr.Emit (ec);
973                                                 if (is_expr)
974                                                         ig.Emit (OpCodes.Dup);
975                                                 
976                                                 LoadOneAndEmitOp (ec, expr_type);
977                                                 ia.EmitAssign (ec, empty_expr);
978                                                 break;
979                                         }
980                                         return;
981                                 }
982                                 temp_storage = new LocalTemporary (ec, expr_type);
983                         }
984                         
985                         switch (mode){
986                         case Mode.PreIncrement:
987                         case Mode.PreDecrement:
988                                 if (method == null){
989                                         expr.Emit (ec);
990                                         
991                                         LoadOneAndEmitOp (ec, expr_type);
992                                 } else 
993                                         method.Emit (ec);
994                                 
995                                 temp_storage.Store (ec);
996                                 ia.EmitAssign (ec, temp_storage);
997                                 if (is_expr)
998                                         temp_storage.Emit (ec);
999                                 break;
1000                                 
1001                         case Mode.PostIncrement:
1002                         case Mode.PostDecrement:
1003                                 if (is_expr)
1004                                         expr.Emit (ec);
1005                                 
1006                                 if (method == null){
1007                                         if (!is_expr)
1008                                                 expr.Emit (ec);
1009                                         else
1010                                                 ig.Emit (OpCodes.Dup);
1011                                         
1012                                         LoadOneAndEmitOp (ec, expr_type);
1013                                 } else {
1014                                         method.Emit (ec);
1015                                 }
1016                                 
1017                                 temp_storage.Store (ec);
1018                                 ia.EmitAssign (ec, temp_storage);
1019                                 break;
1020                         }
1021                 }
1022
1023                 public override void Emit (EmitContext ec)
1024                 {
1025                         EmitCode (ec, true);
1026                         
1027                 }
1028                 
1029                 public override void EmitStatement (EmitContext ec)
1030                 {
1031                         EmitCode (ec, false);
1032                 }
1033
1034         }
1035
1036         /// <summary>
1037         ///   Base class for the `Is' and `As' classes. 
1038         /// </summary>
1039         ///
1040         /// <remarks>
1041         ///   FIXME: Split this in two, and we get to save the `Operator' Oper
1042         ///   size. 
1043         /// </remarks>
1044         public abstract class Probe : Expression {
1045                 public readonly Expression ProbeType;
1046                 protected Expression expr;
1047                 protected Type probe_type;
1048                 
1049                 public Probe (Expression expr, Expression probe_type, Location l)
1050                 {
1051                         ProbeType = probe_type;
1052                         loc = l;
1053                         this.expr = expr;
1054                 }
1055
1056                 public Expression Expr {
1057                         get {
1058                                 return expr;
1059                         }
1060                 }
1061
1062                 public override Expression DoResolve (EmitContext ec)
1063                 {
1064                         probe_type = ec.DeclSpace.ResolveType (ProbeType, false, loc);
1065
1066                         if (probe_type == null)
1067                                 return null;
1068
1069                         expr = expr.Resolve (ec);
1070                         
1071                         return this;
1072                 }
1073         }
1074
1075         /// <summary>
1076         ///   Implementation of the `is' operator.
1077         /// </summary>
1078         public class Is : Probe {
1079                 public Is (Expression expr, Expression probe_type, Location l)
1080                         : base (expr, probe_type, l)
1081                 {
1082                 }
1083
1084                 enum Action {
1085                         AlwaysTrue, AlwaysNull, AlwaysFalse, LeaveOnStack, Probe
1086                 }
1087
1088                 Action action;
1089                 
1090                 public override void Emit (EmitContext ec)
1091                 {
1092                         ILGenerator ig = ec.ig;
1093
1094                         expr.Emit (ec);
1095
1096                         switch (action){
1097                         case Action.AlwaysFalse:
1098                                 ig.Emit (OpCodes.Pop);
1099                                 IntConstant.EmitInt (ig, 0);
1100                                 return;
1101                         case Action.AlwaysTrue:
1102                                 ig.Emit (OpCodes.Pop);
1103                                 IntConstant.EmitInt (ig, 1);
1104                                 return;
1105                         case Action.LeaveOnStack:
1106                                 // the `e != null' rule.
1107                                 ig.Emit (OpCodes.Ldnull);
1108                                 ig.Emit (OpCodes.Ceq);
1109                                 ig.Emit (OpCodes.Ldc_I4_0);
1110                                 ig.Emit (OpCodes.Ceq);
1111                                 return;
1112                         case Action.Probe:
1113                                 ig.Emit (OpCodes.Isinst, probe_type);
1114                                 ig.Emit (OpCodes.Ldnull);
1115                                 ig.Emit (OpCodes.Cgt_Un);
1116                                 return;
1117                         }
1118                         throw new Exception ("never reached");
1119                 }
1120
1121                 public override Expression DoResolve (EmitContext ec)
1122                 {
1123                         Expression e = base.DoResolve (ec);
1124
1125                         if ((e == null) || (expr == null))
1126                                 return null;
1127
1128                         Type etype = expr.Type;
1129                         bool warning_always_matches = false;
1130                         bool warning_never_matches = false;
1131
1132                         type = TypeManager.bool_type;
1133                         eclass = ExprClass.Value;
1134
1135                         //
1136                         // First case, if at compile time, there is an implicit conversion
1137                         // then e != null (objects) or true (value types)
1138                         //
1139                         e = Convert.ImplicitConversionStandard (ec, expr, probe_type, loc);
1140                         if (e != null){
1141                                 expr = e;
1142                                 if (etype.IsValueType)
1143                                         action = Action.AlwaysTrue;
1144                                 else
1145                                         action = Action.LeaveOnStack;
1146
1147                                 warning_always_matches = true;
1148                         } else if (Convert.ExplicitReferenceConversionExists (etype, probe_type)){
1149                                 //
1150                                 // Second case: explicit reference convresion
1151                                 //
1152                                 if (expr is NullLiteral)
1153                                         action = Action.AlwaysFalse;
1154                                 else
1155                                         action = Action.Probe;
1156                         } else {
1157                                 action = Action.AlwaysFalse;
1158                                 warning_never_matches = true;
1159                         }
1160                         
1161                         if (RootContext.WarningLevel >= 1){
1162                                 if (warning_always_matches)
1163                                         Warning (183, "The expression is always of type `" +
1164                                                  TypeManager.CSharpName (probe_type) + "'");
1165                                 else if (warning_never_matches){
1166                                         if (!(probe_type.IsInterface || expr.Type.IsInterface))
1167                                                 Warning (184,
1168                                                          "The expression is never of type `" +
1169                                                          TypeManager.CSharpName (probe_type) + "'");
1170                                 }
1171                         }
1172
1173                         return this;
1174                 }                               
1175         }
1176
1177         /// <summary>
1178         ///   Implementation of the `as' operator.
1179         /// </summary>
1180         public class As : Probe {
1181                 public As (Expression expr, Expression probe_type, Location l)
1182                         : base (expr, probe_type, l)
1183                 {
1184                 }
1185
1186                 bool do_isinst = false;
1187                 
1188                 public override void Emit (EmitContext ec)
1189                 {
1190                         ILGenerator ig = ec.ig;
1191
1192                         expr.Emit (ec);
1193
1194                         if (do_isinst)
1195                                 ig.Emit (OpCodes.Isinst, probe_type);
1196                 }
1197
1198                 static void Error_CannotConvertType (Type source, Type target, Location loc)
1199                 {
1200                         Report.Error (
1201                                 39, loc, "as operator can not convert from `" +
1202                                 TypeManager.CSharpName (source) + "' to `" +
1203                                 TypeManager.CSharpName (target) + "'");
1204                 }
1205                 
1206                 public override Expression DoResolve (EmitContext ec)
1207                 {
1208                         Expression e = base.DoResolve (ec);
1209
1210                         if (e == null)
1211                                 return null;
1212
1213                         type = probe_type;
1214                         eclass = ExprClass.Value;
1215                         Type etype = expr.Type;
1216
1217                         if (TypeManager.IsValueType (probe_type)){
1218                                 Report.Error (77, loc, "The as operator should be used with a reference type only (" +
1219                                               TypeManager.CSharpName (probe_type) + " is a value type");
1220                                 return null;
1221                         
1222                         }
1223                         
1224                         e = Convert.ImplicitConversion (ec, expr, probe_type, loc);
1225                         if (e != null){
1226                                 expr = e;
1227                                 do_isinst = false;
1228                                 return this;
1229                         }
1230
1231                         if (Convert.ExplicitReferenceConversionExists (etype, probe_type)){
1232                                 do_isinst = true;
1233                                 return this;
1234                         }
1235
1236                         Error_CannotConvertType (etype, probe_type, loc);
1237                         return null;
1238                 }                               
1239         }
1240         
1241         /// <summary>
1242         ///   This represents a typecast in the source language.
1243         ///
1244         ///   FIXME: Cast expressions have an unusual set of parsing
1245         ///   rules, we need to figure those out.
1246         /// </summary>
1247         public class Cast : Expression {
1248                 Expression target_type;
1249                 Expression expr;
1250                         
1251                 public Cast (Expression cast_type, Expression expr, Location loc)
1252                 {
1253                         this.target_type = cast_type;
1254                         this.expr = expr;
1255                         this.loc = loc;
1256                 }
1257
1258                 public Expression TargetType {
1259                         get {
1260                                 return target_type;
1261                         }
1262                 }
1263
1264                 public Expression Expr {
1265                         get {
1266                                 return expr;
1267                         }
1268                         set {
1269                                 expr = value;
1270                         }
1271                 }
1272
1273                 bool CheckRange (EmitContext ec, long value, Type type, long min, long max)
1274                 {
1275                         if (!ec.ConstantCheckState)
1276                                 return true;
1277
1278                         if ((value < min) || (value > max)) {
1279                                 Error (221, "Constant value `" + value + "' cannot be converted " +
1280                                        "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1281                                        "syntax to override)");
1282                                 return false;
1283                         }
1284
1285                         return true;
1286                 }
1287
1288                 bool CheckRange (EmitContext ec, ulong value, Type type, ulong max)
1289                 {
1290                         if (!ec.ConstantCheckState)
1291                                 return true;
1292
1293                         if (value > max) {
1294                                 Error (221, "Constant value `" + value + "' cannot be converted " +
1295                                        "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1296                                        "syntax to override)");
1297                                 return false;
1298                         }
1299
1300                         return true;
1301                 }
1302
1303                 bool CheckUnsigned (EmitContext ec, long value, Type type)
1304                 {
1305                         if (!ec.ConstantCheckState)
1306                                 return true;
1307
1308                         if (value < 0) {
1309                                 Error (221, "Constant value `" + value + "' cannot be converted " +
1310                                        "to a `" + TypeManager.CSharpName (type) + "' (use `unchecked' " +
1311                                        "syntax to override)");
1312                                 return false;
1313                         }
1314
1315                         return true;
1316                 }
1317
1318                 /// <summary>
1319                 ///   Attempts to do a compile-time folding of a constant cast.
1320                 /// </summary>
1321                 Expression TryReduce (EmitContext ec, Type target_type)
1322                 {
1323                         Expression real_expr = expr;
1324                         if (real_expr is EnumConstant)
1325                                 real_expr = ((EnumConstant) real_expr).Child;
1326                                 
1327                         if (real_expr is ByteConstant){
1328                                 byte v = ((ByteConstant) real_expr).Value;
1329         
1330                                 if (target_type == TypeManager.sbyte_type) {
1331                                         if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1332                                                 return null;
1333                                         return new SByteConstant ((sbyte) v);
1334                                 }
1335                                 if (target_type == TypeManager.short_type)
1336                                         return new ShortConstant ((short) v);
1337                                 if (target_type == TypeManager.ushort_type)
1338                                         return new UShortConstant ((ushort) v);
1339                                 if (target_type == TypeManager.int32_type)
1340                                         return new IntConstant ((int) v);
1341                                 if (target_type == TypeManager.uint32_type)
1342                                         return new UIntConstant ((uint) v);
1343                                 if (target_type == TypeManager.int64_type)
1344                                         return new LongConstant ((long) v);
1345                                 if (target_type == TypeManager.uint64_type)
1346                                         return new ULongConstant ((ulong) v);
1347                                 if (target_type == TypeManager.float_type)
1348                                         return new FloatConstant ((float) v);
1349                                 if (target_type == TypeManager.double_type)
1350                                         return new DoubleConstant ((double) v);
1351                                 if (target_type == TypeManager.char_type)
1352                                         return new CharConstant ((char) v);
1353                                 if (target_type == TypeManager.decimal_type)
1354                                         return new DecimalConstant ((decimal) v);
1355                         }
1356                         if (real_expr is SByteConstant){
1357                                 sbyte v = ((SByteConstant) real_expr).Value;
1358         
1359                                 if (target_type == TypeManager.byte_type) {
1360                                         if (!CheckUnsigned (ec, v, target_type))
1361                                                 return null;
1362                                         return new ByteConstant ((byte) v);
1363                                 }
1364                                 if (target_type == TypeManager.short_type)
1365                                         return new ShortConstant ((short) v);
1366                                 if (target_type == TypeManager.ushort_type) {
1367                                         if (!CheckUnsigned (ec, v, target_type))
1368                                                 return null;
1369                                         return new UShortConstant ((ushort) v);
1370                                 } if (target_type == TypeManager.int32_type)
1371                                         return new IntConstant ((int) v);
1372                                 if (target_type == TypeManager.uint32_type) {
1373                                         if (!CheckUnsigned (ec, v, target_type))
1374                                                 return null;
1375                                         return new UIntConstant ((uint) v);
1376                                 } if (target_type == TypeManager.int64_type)
1377                                         return new LongConstant ((long) v);
1378                                 if (target_type == TypeManager.uint64_type) {
1379                                         if (!CheckUnsigned (ec, v, target_type))
1380                                                 return null;
1381                                         return new ULongConstant ((ulong) v);
1382                                 }
1383                                 if (target_type == TypeManager.float_type)
1384                                         return new FloatConstant ((float) v);
1385                                 if (target_type == TypeManager.double_type)
1386                                         return new DoubleConstant ((double) v);
1387                                 if (target_type == TypeManager.char_type) {
1388                                         if (!CheckUnsigned (ec, v, target_type))
1389                                                 return null;
1390                                         return new CharConstant ((char) v);
1391                                 }
1392                                 if (target_type == TypeManager.decimal_type)
1393                                         return new DecimalConstant ((decimal) v);
1394                         }
1395                         if (real_expr is ShortConstant){
1396                                 short v = ((ShortConstant) real_expr).Value;
1397         
1398                                 if (target_type == TypeManager.byte_type) {
1399                                         if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1400                                                 return null;
1401                                         return new ByteConstant ((byte) v);
1402                                 }
1403                                 if (target_type == TypeManager.sbyte_type) {
1404                                         if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1405                                                 return null;
1406                                         return new SByteConstant ((sbyte) v);
1407                                 }
1408                                 if (target_type == TypeManager.ushort_type) {
1409                                         if (!CheckUnsigned (ec, v, target_type))
1410                                                 return null;
1411                                         return new UShortConstant ((ushort) v);
1412                                 }
1413                                 if (target_type == TypeManager.int32_type)
1414                                         return new IntConstant ((int) v);
1415                                 if (target_type == TypeManager.uint32_type) {
1416                                         if (!CheckUnsigned (ec, v, target_type))
1417                                                 return null;
1418                                         return new UIntConstant ((uint) v);
1419                                 }
1420                                 if (target_type == TypeManager.int64_type)
1421                                         return new LongConstant ((long) v);
1422                                 if (target_type == TypeManager.uint64_type) {
1423                                         if (!CheckUnsigned (ec, v, target_type))
1424                                                 return null;
1425                                         return new ULongConstant ((ulong) v);
1426                                 }
1427                                 if (target_type == TypeManager.float_type)
1428                                         return new FloatConstant ((float) v);
1429                                 if (target_type == TypeManager.double_type)
1430                                         return new DoubleConstant ((double) v);
1431                                 if (target_type == TypeManager.char_type) {
1432                                         if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1433                                                 return null;
1434                                         return new CharConstant ((char) v);
1435                                 }
1436                                 if (target_type == TypeManager.decimal_type)
1437                                         return new DecimalConstant ((decimal) v);
1438                         }
1439                         if (real_expr is UShortConstant){
1440                                 ushort v = ((UShortConstant) real_expr).Value;
1441         
1442                                 if (target_type == TypeManager.byte_type) {
1443                                         if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1444                                                 return null;
1445                                         return new ByteConstant ((byte) v);
1446                                 }
1447                                 if (target_type == TypeManager.sbyte_type) {
1448                                         if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1449                                                 return null;
1450                                         return new SByteConstant ((sbyte) v);
1451                                 }
1452                                 if (target_type == TypeManager.short_type) {
1453                                         if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1454                                                 return null;
1455                                         return new ShortConstant ((short) v);
1456                                 }
1457                                 if (target_type == TypeManager.int32_type)
1458                                         return new IntConstant ((int) v);
1459                                 if (target_type == TypeManager.uint32_type)
1460                                         return new UIntConstant ((uint) v);
1461                                 if (target_type == TypeManager.int64_type)
1462                                         return new LongConstant ((long) v);
1463                                 if (target_type == TypeManager.uint64_type)
1464                                         return new ULongConstant ((ulong) v);
1465                                 if (target_type == TypeManager.float_type)
1466                                         return new FloatConstant ((float) v);
1467                                 if (target_type == TypeManager.double_type)
1468                                         return new DoubleConstant ((double) v);
1469                                 if (target_type == TypeManager.char_type) {
1470                                         if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1471                                                 return null;
1472                                         return new CharConstant ((char) v);
1473                                 }
1474                                 if (target_type == TypeManager.decimal_type)
1475                                         return new DecimalConstant ((decimal) v);
1476                         }
1477                         if (real_expr is IntConstant){
1478                                 int v = ((IntConstant) real_expr).Value;
1479         
1480                                 if (target_type == TypeManager.byte_type) {
1481                                         if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1482                                                 return null;
1483                                         return new ByteConstant ((byte) v);
1484                                 }
1485                                 if (target_type == TypeManager.sbyte_type) {
1486                                         if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1487                                                 return null;
1488                                         return new SByteConstant ((sbyte) v);
1489                                 }
1490                                 if (target_type == TypeManager.short_type) {
1491                                         if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1492                                                 return null;
1493                                         return new ShortConstant ((short) v);
1494                                 }
1495                                 if (target_type == TypeManager.ushort_type) {
1496                                         if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1497                                                 return null;
1498                                         return new UShortConstant ((ushort) v);
1499                                 }
1500                                 if (target_type == TypeManager.uint32_type) {
1501                                         if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1502                                                 return null;
1503                                         return new UIntConstant ((uint) v);
1504                                 }
1505                                 if (target_type == TypeManager.int64_type)
1506                                         return new LongConstant ((long) v);
1507                                 if (target_type == TypeManager.uint64_type) {
1508                                         if (!CheckUnsigned (ec, v, target_type))
1509                                                 return null;
1510                                         return new ULongConstant ((ulong) v);
1511                                 }
1512                                 if (target_type == TypeManager.float_type)
1513                                         return new FloatConstant ((float) v);
1514                                 if (target_type == TypeManager.double_type)
1515                                         return new DoubleConstant ((double) v);
1516                                 if (target_type == TypeManager.char_type) {
1517                                         if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1518                                                 return null;
1519                                         return new CharConstant ((char) v);
1520                                 }
1521                                 if (target_type == TypeManager.decimal_type)
1522                                         return new DecimalConstant ((decimal) v);
1523                         }
1524                         if (real_expr is UIntConstant){
1525                                 uint v = ((UIntConstant) real_expr).Value;
1526         
1527                                 if (target_type == TypeManager.byte_type) {
1528                                         if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1529                                                 return null;
1530                                         return new ByteConstant ((byte) v);
1531                                 }
1532                                 if (target_type == TypeManager.sbyte_type) {
1533                                         if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1534                                                 return null;
1535                                         return new SByteConstant ((sbyte) v);
1536                                 }
1537                                 if (target_type == TypeManager.short_type) {
1538                                         if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1539                                                 return null;
1540                                         return new ShortConstant ((short) v);
1541                                 }
1542                                 if (target_type == TypeManager.ushort_type) {
1543                                         if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1544                                                 return null;
1545                                         return new UShortConstant ((ushort) v);
1546                                 }
1547                                 if (target_type == TypeManager.int32_type) {
1548                                         if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1549                                                 return null;
1550                                         return new IntConstant ((int) v);
1551                                 }
1552                                 if (target_type == TypeManager.int64_type)
1553                                         return new LongConstant ((long) v);
1554                                 if (target_type == TypeManager.uint64_type)
1555                                         return new ULongConstant ((ulong) v);
1556                                 if (target_type == TypeManager.float_type)
1557                                         return new FloatConstant ((float) v);
1558                                 if (target_type == TypeManager.double_type)
1559                                         return new DoubleConstant ((double) v);
1560                                 if (target_type == TypeManager.char_type) {
1561                                         if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1562                                                 return null;
1563                                         return new CharConstant ((char) v);
1564                                 }
1565                                 if (target_type == TypeManager.decimal_type)
1566                                         return new DecimalConstant ((decimal) v);
1567                         }
1568                         if (real_expr is LongConstant){
1569                                 long v = ((LongConstant) real_expr).Value;
1570         
1571                                 if (target_type == TypeManager.byte_type) {
1572                                         if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1573                                                 return null;
1574                                         return new ByteConstant ((byte) v);
1575                                 }
1576                                 if (target_type == TypeManager.sbyte_type) {
1577                                         if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1578                                                 return null;
1579                                         return new SByteConstant ((sbyte) v);
1580                                 }
1581                                 if (target_type == TypeManager.short_type) {
1582                                         if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1583                                                 return null;
1584                                         return new ShortConstant ((short) v);
1585                                 }
1586                                 if (target_type == TypeManager.ushort_type) {
1587                                         if (!CheckRange (ec, v, target_type, UInt16.MinValue, UInt16.MaxValue))
1588                                                 return null;
1589                                         return new UShortConstant ((ushort) v);
1590                                 }
1591                                 if (target_type == TypeManager.int32_type) {
1592                                         if (!CheckRange (ec, v, target_type, Int32.MinValue, Int32.MaxValue))
1593                                                 return null;
1594                                         return new IntConstant ((int) v);
1595                                 }
1596                                 if (target_type == TypeManager.uint32_type) {
1597                                         if (!CheckRange (ec, v, target_type, UInt32.MinValue, UInt32.MaxValue))
1598                                                 return null;
1599                                         return new UIntConstant ((uint) v);
1600                                 }
1601                                 if (target_type == TypeManager.uint64_type) {
1602                                         if (!CheckUnsigned (ec, v, target_type))
1603                                                 return null;
1604                                         return new ULongConstant ((ulong) v);
1605                                 }
1606                                 if (target_type == TypeManager.float_type)
1607                                         return new FloatConstant ((float) v);
1608                                 if (target_type == TypeManager.double_type)
1609                                         return new DoubleConstant ((double) v);
1610                                 if (target_type == TypeManager.char_type) {
1611                                         if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1612                                                 return null;
1613                                         return new CharConstant ((char) v);
1614                                 }
1615                                 if (target_type == TypeManager.decimal_type)
1616                                         return new DecimalConstant ((decimal) v);
1617                         }
1618                         if (real_expr is ULongConstant){
1619                                 ulong v = ((ULongConstant) real_expr).Value;
1620         
1621                                 if (target_type == TypeManager.byte_type) {
1622                                         if (!CheckRange (ec, v, target_type, Byte.MaxValue))
1623                                                 return null;
1624                                         return new ByteConstant ((byte) v);
1625                                 }
1626                                 if (target_type == TypeManager.sbyte_type) {
1627                                         if (!CheckRange (ec, v, target_type, (ulong) SByte.MaxValue))
1628                                                 return null;
1629                                         return new SByteConstant ((sbyte) v);
1630                                 }
1631                                 if (target_type == TypeManager.short_type) {
1632                                         if (!CheckRange (ec, v, target_type, (ulong) Int16.MaxValue))
1633                                                 return null;
1634                                         return new ShortConstant ((short) v);
1635                                 }
1636                                 if (target_type == TypeManager.ushort_type) {
1637                                         if (!CheckRange (ec, v, target_type, UInt16.MaxValue))
1638                                                 return null;
1639                                         return new UShortConstant ((ushort) v);
1640                                 }
1641                                 if (target_type == TypeManager.int32_type) {
1642                                         if (!CheckRange (ec, v, target_type, Int32.MaxValue))
1643                                                 return null;
1644                                         return new IntConstant ((int) v);
1645                                 }
1646                                 if (target_type == TypeManager.uint32_type) {
1647                                         if (!CheckRange (ec, v, target_type, UInt32.MaxValue))
1648                                                 return null;
1649                                         return new UIntConstant ((uint) v);
1650                                 }
1651                                 if (target_type == TypeManager.int64_type) {
1652                                         if (!CheckRange (ec, v, target_type, (ulong) Int64.MaxValue))
1653                                                 return null;
1654                                         return new LongConstant ((long) v);
1655                                 }
1656                                 if (target_type == TypeManager.float_type)
1657                                         return new FloatConstant ((float) v);
1658                                 if (target_type == TypeManager.double_type)
1659                                         return new DoubleConstant ((double) v);
1660                                 if (target_type == TypeManager.char_type) {
1661                                         if (!CheckRange (ec, v, target_type, Char.MaxValue))
1662                                                 return null;
1663                                         return new CharConstant ((char) v);
1664                                 }
1665                                 if (target_type == TypeManager.decimal_type)
1666                                         return new DecimalConstant ((decimal) v);
1667                         }
1668                         if (real_expr is FloatConstant){
1669                                 float v = ((FloatConstant) real_expr).Value;
1670         
1671                                 if (target_type == TypeManager.byte_type)
1672                                         return new ByteConstant ((byte) v);
1673                                 if (target_type == TypeManager.sbyte_type)
1674                                         return new SByteConstant ((sbyte) v);
1675                                 if (target_type == TypeManager.short_type)
1676                                         return new ShortConstant ((short) v);
1677                                 if (target_type == TypeManager.ushort_type)
1678                                         return new UShortConstant ((ushort) v);
1679                                 if (target_type == TypeManager.int32_type)
1680                                         return new IntConstant ((int) v);
1681                                 if (target_type == TypeManager.uint32_type)
1682                                         return new UIntConstant ((uint) v);
1683                                 if (target_type == TypeManager.int64_type)
1684                                         return new LongConstant ((long) v);
1685                                 if (target_type == TypeManager.uint64_type)
1686                                         return new ULongConstant ((ulong) v);
1687                                 if (target_type == TypeManager.double_type)
1688                                         return new DoubleConstant ((double) v);
1689                                 if (target_type == TypeManager.char_type)
1690                                         return new CharConstant ((char) v);
1691                                 if (target_type == TypeManager.decimal_type)
1692                                         return new DecimalConstant ((decimal) v);
1693                         }
1694                         if (real_expr is DoubleConstant){
1695                                 double v = ((DoubleConstant) real_expr).Value;
1696         
1697                                 if (target_type == TypeManager.byte_type)
1698                                         return new ByteConstant ((byte) v);
1699                                 if (target_type == TypeManager.sbyte_type)
1700                                         return new SByteConstant ((sbyte) v);
1701                                 if (target_type == TypeManager.short_type)
1702                                         return new ShortConstant ((short) v);
1703                                 if (target_type == TypeManager.ushort_type)
1704                                         return new UShortConstant ((ushort) v);
1705                                 if (target_type == TypeManager.int32_type)
1706                                         return new IntConstant ((int) v);
1707                                 if (target_type == TypeManager.uint32_type)
1708                                         return new UIntConstant ((uint) v);
1709                                 if (target_type == TypeManager.int64_type)
1710                                         return new LongConstant ((long) v);
1711                                 if (target_type == TypeManager.uint64_type)
1712                                         return new ULongConstant ((ulong) v);
1713                                 if (target_type == TypeManager.float_type)
1714                                         return new FloatConstant ((float) v);
1715                                 if (target_type == TypeManager.char_type)
1716                                         return new CharConstant ((char) v);
1717                                 if (target_type == TypeManager.decimal_type)
1718                                         return new DecimalConstant ((decimal) v);
1719                         }
1720
1721                         if (real_expr is CharConstant){
1722                                 char v = ((CharConstant) real_expr).Value;
1723                                 
1724                                 if (target_type == TypeManager.byte_type) {
1725                                         if (!CheckRange (ec, v, target_type, Byte.MinValue, Byte.MaxValue))
1726                                                 return null;
1727                                         return new ByteConstant ((byte) v);
1728                                 }
1729                                 if (target_type == TypeManager.sbyte_type) {
1730                                         if (!CheckRange (ec, v, target_type, SByte.MinValue, SByte.MaxValue))
1731                                                 return null;
1732                                         return new SByteConstant ((sbyte) v);
1733                                 }
1734                                 if (target_type == TypeManager.short_type) {
1735                                         if (!CheckRange (ec, v, target_type, Int16.MinValue, Int16.MaxValue))
1736                                                 return null;
1737                                         return new ShortConstant ((short) v);
1738                                 }
1739                                 if (target_type == TypeManager.int32_type)
1740                                         return new IntConstant ((int) v);
1741                                 if (target_type == TypeManager.uint32_type)
1742                                         return new UIntConstant ((uint) v);
1743                                 if (target_type == TypeManager.int64_type)
1744                                         return new LongConstant ((long) v);
1745                                 if (target_type == TypeManager.uint64_type)
1746                                         return new ULongConstant ((ulong) v);
1747                                 if (target_type == TypeManager.float_type)
1748                                         return new FloatConstant ((float) v);
1749                                 if (target_type == TypeManager.double_type)
1750                                         return new DoubleConstant ((double) v);
1751                                 if (target_type == TypeManager.char_type) {
1752                                         if (!CheckRange (ec, v, target_type, Char.MinValue, Char.MaxValue))
1753                                                 return null;
1754                                         return new CharConstant ((char) v);
1755                                 }
1756                                 if (target_type == TypeManager.decimal_type)
1757                                         return new DecimalConstant ((decimal) v);
1758                         }
1759
1760                         return null;
1761                 }
1762                 
1763                 public override Expression DoResolve (EmitContext ec)
1764                 {
1765                         expr = expr.Resolve (ec);
1766                         if (expr == null)
1767                                 return null;
1768
1769                         int errors = Report.Errors;
1770
1771                         type = ec.DeclSpace.ResolveType (target_type, false, Location);
1772                         
1773                         if (type == null)
1774                                 return null;
1775
1776                         eclass = ExprClass.Value;
1777
1778                         if (expr is Constant){
1779                                 Expression e = TryReduce (ec, type);
1780
1781                                 if (e != null)
1782                                         return e;
1783                         }
1784
1785                         expr = Convert.ExplicitConversion (ec, expr, type, loc);
1786                         return expr;
1787                 }
1788
1789                 public override void Emit (EmitContext ec)
1790                 {
1791                         //
1792                         // This one will never happen
1793                         //
1794                         throw new Exception ("Should not happen");
1795                 }
1796         }
1797
1798         /// <summary>
1799         ///   Binary operators
1800         /// </summary>
1801         public class Binary : Expression {
1802                 public enum Operator : byte {
1803                         Multiply, Division, Modulus,
1804                         Addition, Subtraction,
1805                         LeftShift, RightShift,
1806                         LessThan, GreaterThan, LessThanOrEqual, GreaterThanOrEqual, 
1807                         Equality, Inequality,
1808                         BitwiseAnd,
1809                         ExclusiveOr,
1810                         BitwiseOr,
1811                         LogicalAnd,
1812                         LogicalOr,
1813                         TOP
1814                 }
1815
1816                 Operator oper;
1817                 Expression left, right;
1818
1819                 //
1820                 // After resolution, method might contain the operator overload
1821                 // method.
1822                 //
1823                 protected MethodBase method;
1824                 ArrayList  Arguments;
1825
1826                 bool DelegateOperation;
1827
1828                 // This must be kept in sync with Operator!!!
1829                 public static readonly string [] oper_names;
1830                 
1831                 static Binary ()
1832                 {
1833                         oper_names = new string [(int) Operator.TOP];
1834
1835                         oper_names [(int) Operator.Multiply] = "op_Multiply";
1836                         oper_names [(int) Operator.Division] = "op_Division";
1837                         oper_names [(int) Operator.Modulus] = "op_Modulus";
1838                         oper_names [(int) Operator.Addition] = "op_Addition";
1839                         oper_names [(int) Operator.Subtraction] = "op_Subtraction";
1840                         oper_names [(int) Operator.LeftShift] = "op_LeftShift";
1841                         oper_names [(int) Operator.RightShift] = "op_RightShift";
1842                         oper_names [(int) Operator.LessThan] = "op_LessThan";
1843                         oper_names [(int) Operator.GreaterThan] = "op_GreaterThan";
1844                         oper_names [(int) Operator.LessThanOrEqual] = "op_LessThanOrEqual";
1845                         oper_names [(int) Operator.GreaterThanOrEqual] = "op_GreaterThanOrEqual";
1846                         oper_names [(int) Operator.Equality] = "op_Equality";
1847                         oper_names [(int) Operator.Inequality] = "op_Inequality";
1848                         oper_names [(int) Operator.BitwiseAnd] = "op_BitwiseAnd";
1849                         oper_names [(int) Operator.BitwiseOr] = "op_BitwiseOr";
1850                         oper_names [(int) Operator.ExclusiveOr] = "op_ExclusiveOr";
1851                         oper_names [(int) Operator.LogicalOr] = "op_LogicalOr";
1852                         oper_names [(int) Operator.LogicalAnd] = "op_LogicalAnd";
1853                 }
1854
1855                 public Binary (Operator oper, Expression left, Expression right, Location loc)
1856                 {
1857                         this.oper = oper;
1858                         this.left = left;
1859                         this.right = right;
1860                         this.loc = loc;
1861                 }
1862
1863                 public Operator Oper {
1864                         get {
1865                                 return oper;
1866                         }
1867                         set {
1868                                 oper = value;
1869                         }
1870                 }
1871                 
1872                 public Expression Left {
1873                         get {
1874                                 return left;
1875                         }
1876                         set {
1877                                 left = value;
1878                         }
1879                 }
1880
1881                 public Expression Right {
1882                         get {
1883                                 return right;
1884                         }
1885                         set {
1886                                 right = value;
1887                         }
1888                 }
1889
1890
1891                 /// <summary>
1892                 ///   Returns a stringified representation of the Operator
1893                 /// </summary>
1894                 static string OperName (Operator oper)
1895                 {
1896                         switch (oper){
1897                         case Operator.Multiply:
1898                                 return "*";
1899                         case Operator.Division:
1900                                 return "/";
1901                         case Operator.Modulus:
1902                                 return "%";
1903                         case Operator.Addition:
1904                                 return "+";
1905                         case Operator.Subtraction:
1906                                 return "-";
1907                         case Operator.LeftShift:
1908                                 return "<<";
1909                         case Operator.RightShift:
1910                                 return ">>";
1911                         case Operator.LessThan:
1912                                 return "<";
1913                         case Operator.GreaterThan:
1914                                 return ">";
1915                         case Operator.LessThanOrEqual:
1916                                 return "<=";
1917                         case Operator.GreaterThanOrEqual:
1918                                 return ">=";
1919                         case Operator.Equality:
1920                                 return "==";
1921                         case Operator.Inequality:
1922                                 return "!=";
1923                         case Operator.BitwiseAnd:
1924                                 return "&";
1925                         case Operator.BitwiseOr:
1926                                 return "|";
1927                         case Operator.ExclusiveOr:
1928                                 return "^";
1929                         case Operator.LogicalOr:
1930                                 return "||";
1931                         case Operator.LogicalAnd:
1932                                 return "&&";
1933                         }
1934
1935                         return oper.ToString ();
1936                 }
1937
1938                 public override string ToString ()
1939                 {
1940                         return "operator " + OperName (oper) + "(" + left.ToString () + ", " +
1941                                 right.ToString () + ")";
1942                 }
1943                 
1944                 Expression ForceConversion (EmitContext ec, Expression expr, Type target_type)
1945                 {
1946                         if (expr.Type == target_type)
1947                                 return expr;
1948
1949                         return Convert.ImplicitConversion (ec, expr, target_type, loc);
1950                 }
1951
1952                 public static void Error_OperatorAmbiguous (Location loc, Operator oper, Type l, Type r)
1953                 {
1954                         Report.Error (
1955                                 34, loc, "Operator `" + OperName (oper) 
1956                                 + "' is ambiguous on operands of type `"
1957                                 + TypeManager.CSharpName (l) + "' "
1958                                 + "and `" + TypeManager.CSharpName (r)
1959                                 + "'");
1960                 }
1961
1962                 bool IsOfType (EmitContext ec, Type l, Type r, Type t, bool check_user_conversions)
1963                 {
1964                         if ((l == t) || (r == t))
1965                                 return true;
1966
1967                         if (!check_user_conversions)
1968                                 return false;
1969
1970                         if (Convert.ImplicitUserConversionExists (ec, l, t))
1971                                 return true;
1972                         else if (Convert.ImplicitUserConversionExists (ec, r, t))
1973                                 return true;
1974                         else
1975                                 return false;
1976                 }
1977
1978                 //
1979                 // Note that handling the case l == Decimal || r == Decimal
1980                 // is taken care of by the Step 1 Operator Overload resolution.
1981                 //
1982                 // If `check_user_conv' is true, we also check whether a user-defined conversion
1983                 // exists.  Note that we only need to do this if both arguments are of a user-defined
1984                 // type, otherwise ConvertImplict() already finds the user-defined conversion for us,
1985                 // so we don't explicitly check for performance reasons.
1986                 //
1987                 bool DoNumericPromotions (EmitContext ec, Type l, Type r, bool check_user_conv)
1988                 {
1989                         if (IsOfType (ec, l, r, TypeManager.double_type, check_user_conv)){
1990                                 //
1991                                 // If either operand is of type double, the other operand is
1992                                 // conveted to type double.
1993                                 //
1994                                 if (r != TypeManager.double_type)
1995                                         right = Convert.ImplicitConversion (ec, right, TypeManager.double_type, loc);
1996                                 if (l != TypeManager.double_type)
1997                                         left = Convert.ImplicitConversion (ec, left, TypeManager.double_type, loc);
1998                                 
1999                                 type = TypeManager.double_type;
2000                         } else if (IsOfType (ec, l, r, TypeManager.float_type, check_user_conv)){
2001                                 //
2002                                 // if either operand is of type float, the other operand is
2003                                 // converted to type float.
2004                                 //
2005                                 if (r != TypeManager.double_type)
2006                                         right = Convert.ImplicitConversion (ec, right, TypeManager.float_type, loc);
2007                                 if (l != TypeManager.double_type)
2008                                         left = Convert.ImplicitConversion (ec, left, TypeManager.float_type, loc);
2009                                 type = TypeManager.float_type;
2010                         } else if (IsOfType (ec, l, r, TypeManager.uint64_type, check_user_conv)){
2011                                 Expression e;
2012                                 Type other;
2013                                 //
2014                                 // If either operand is of type ulong, the other operand is
2015                                 // converted to type ulong.  or an error ocurrs if the other
2016                                 // operand is of type sbyte, short, int or long
2017                                 //
2018                                 if (l == TypeManager.uint64_type){
2019                                         if (r != TypeManager.uint64_type){
2020                                                 if (right is IntConstant){
2021                                                         IntConstant ic = (IntConstant) right;
2022                                                         
2023                                                         e = Convert.TryImplicitIntConversion (l, ic);
2024                                                         if (e != null)
2025                                                                 right = e;
2026                                                 } else if (right is LongConstant){
2027                                                         long ll = ((LongConstant) right).Value;
2028
2029                                                         if (ll > 0)
2030                                                                 right = new ULongConstant ((ulong) ll);
2031                                                 } else {
2032                                                         e = Convert.ImplicitNumericConversion (ec, right, l, loc);
2033                                                         if (e != null)
2034                                                                 right = e;
2035                                                 }
2036                                         }
2037                                         other = right.Type;
2038                                 } else {
2039                                         if (left is IntConstant){
2040                                                 e = Convert.TryImplicitIntConversion (r, (IntConstant) left);
2041                                                 if (e != null)
2042                                                         left = e;
2043                                         } else if (left is LongConstant){
2044                                                 long ll = ((LongConstant) left).Value;
2045                                                 
2046                                                 if (ll > 0)
2047                                                         left = new ULongConstant ((ulong) ll);
2048                                         } else {
2049                                                 e = Convert.ImplicitNumericConversion (ec, left, r, loc);
2050                                                 if (e != null)
2051                                                         left = e;
2052                                         }
2053                                         other = left.Type;
2054                                 }
2055
2056                                 if ((other == TypeManager.sbyte_type) ||
2057                                     (other == TypeManager.short_type) ||
2058                                     (other == TypeManager.int32_type) ||
2059                                     (other == TypeManager.int64_type))
2060                                         Error_OperatorAmbiguous (loc, oper, l, r);
2061                                 type = TypeManager.uint64_type;
2062                         } else if (IsOfType (ec, l, r, TypeManager.int64_type, check_user_conv)){
2063                                 //
2064                                 // If either operand is of type long, the other operand is converted
2065                                 // to type long.
2066                                 //
2067                                 if (l != TypeManager.int64_type)
2068                                         left = Convert.ImplicitConversion (ec, left, TypeManager.int64_type, loc);
2069                                 if (r != TypeManager.int64_type)
2070                                         right = Convert.ImplicitConversion (ec, right, TypeManager.int64_type, loc);
2071                                 
2072                                 type = TypeManager.int64_type;
2073                         } else if (IsOfType (ec, l, r, TypeManager.uint32_type, check_user_conv)){
2074                                 //
2075                                 // If either operand is of type uint, and the other
2076                                 // operand is of type sbyte, short or int, othe operands are
2077                                 // converted to type long.
2078                                 //
2079                                 Type other = null;
2080                                 
2081                                 if (l == TypeManager.uint32_type){
2082                                         if (right is IntConstant){
2083                                                 IntConstant ic = (IntConstant) right;
2084                                                 int val = ic.Value;
2085                                                 
2086                                                 if (val >= 0){
2087                                                         right = new UIntConstant ((uint) val);
2088                                                         type = l;
2089                                                         
2090                                                         return true;
2091                                                 }
2092                                         }
2093                                         other = r;
2094                                 } else if (r == TypeManager.uint32_type){
2095                                         if (left is IntConstant){
2096                                                 IntConstant ic = (IntConstant) left;
2097                                                 int val = ic.Value;
2098                                                 
2099                                                 if (val >= 0){
2100                                                         left = new UIntConstant ((uint) val);
2101                                                         type = r;
2102                                                         return true;
2103                                                 }
2104                                         }
2105                                         
2106                                         other = l;
2107                                 }
2108
2109                                 if ((other == TypeManager.sbyte_type) ||
2110                                     (other == TypeManager.short_type) ||
2111                                     (other == TypeManager.int32_type)){
2112                                         left = ForceConversion (ec, left, TypeManager.int64_type);
2113                                         right = ForceConversion (ec, right, TypeManager.int64_type);
2114                                         type = TypeManager.int64_type;
2115                                 } else {
2116                                         //
2117                                         // if either operand is of type uint, the other
2118                                         // operand is converd to type uint
2119                                         //
2120                                         left = ForceConversion (ec, left, TypeManager.uint32_type);
2121                                         right = ForceConversion (ec, right, TypeManager.uint32_type);
2122                                         type = TypeManager.uint32_type;
2123                                 } 
2124                         } else if (l == TypeManager.decimal_type || r == TypeManager.decimal_type){
2125                                 if (l != TypeManager.decimal_type)
2126                                         left = Convert.ImplicitConversion (ec, left, TypeManager.decimal_type, loc);
2127
2128                                 if (r != TypeManager.decimal_type)
2129                                         right = Convert.ImplicitConversion (ec, right, TypeManager.decimal_type, loc);
2130                                 type = TypeManager.decimal_type;
2131                         } else {
2132                                 left = ForceConversion (ec, left, TypeManager.int32_type);
2133                                 right = ForceConversion (ec, right, TypeManager.int32_type);
2134
2135                                 type = TypeManager.int32_type;
2136                         }
2137
2138                         return (left != null) && (right != null);
2139                 }
2140
2141                 static public void Error_OperatorCannotBeApplied (Location loc, string name, Type l, Type r)
2142                 {
2143                         Report.Error (19, loc,
2144                                "Operator " + name + " cannot be applied to operands of type `" +
2145                                TypeManager.CSharpName (l) + "' and `" +
2146                                TypeManager.CSharpName (r) + "'");
2147                 }
2148                 
2149                 void Error_OperatorCannotBeApplied ()
2150                 {
2151                         Error_OperatorCannotBeApplied (loc, OperName (oper), left.Type, right.Type);
2152                 }
2153
2154                 static bool is_32_or_64 (Type t)
2155                 {
2156                         return (t == TypeManager.int32_type || t == TypeManager.uint32_type ||
2157                                 t == TypeManager.int64_type || t == TypeManager.uint64_type);
2158                 }
2159
2160                 static bool is_unsigned (Type t)
2161                 {
2162                         return (t == TypeManager.uint32_type || t == TypeManager.uint64_type ||
2163                                 t == TypeManager.short_type || t == TypeManager.byte_type);
2164                 }
2165
2166                 static bool is_user_defined (Type t)
2167                 {
2168                         if (t.IsSubclassOf (TypeManager.value_type) &&
2169                             (!TypeManager.IsBuiltinType (t) || t == TypeManager.decimal_type))
2170                                 return true;
2171                         else
2172                                 return false;
2173                 }
2174                                         
2175                 Expression CheckShiftArguments (EmitContext ec)
2176                 {
2177                         Expression e;
2178                         Type l = left.Type;
2179                         Type r = right.Type;
2180
2181                         e = ForceConversion (ec, right, TypeManager.int32_type);
2182                         if (e == null){
2183                                 Error_OperatorCannotBeApplied ();
2184                                 return null;
2185                         }
2186                         right = e;
2187
2188                         if (((e = Convert.ImplicitConversion (ec, left, TypeManager.int32_type, loc)) != null) ||
2189                             ((e = Convert.ImplicitConversion (ec, left, TypeManager.uint32_type, loc)) != null) ||
2190                             ((e = Convert.ImplicitConversion (ec, left, TypeManager.int64_type, loc)) != null) ||
2191                             ((e = Convert.ImplicitConversion (ec, left, TypeManager.uint64_type, loc)) != null)){
2192                                 left = e;
2193                                 type = e.Type;
2194
2195                                 return this;
2196                         }
2197                         Error_OperatorCannotBeApplied ();
2198                         return null;
2199                 }
2200
2201                 Expression ResolveOperator (EmitContext ec)
2202                 {
2203                         Type l = left.Type;
2204                         Type r = right.Type;
2205
2206                         bool overload_failed = false;
2207
2208                         //
2209                         // Special cases: string comapred to null
2210                         //
2211                         if (oper == Operator.Equality || oper == Operator.Inequality){
2212                                 if ((l == TypeManager.string_type && (right is NullLiteral)) ||
2213                                     (r == TypeManager.string_type && (left is NullLiteral))){
2214                                         Type = TypeManager.bool_type;
2215                                         
2216                                         return this;
2217                                 }
2218                         }
2219
2220                         //
2221                         // Do not perform operator overload resolution when both sides are
2222                         // built-in types
2223                         //
2224                         if (!(TypeManager.IsCLRType (l) && TypeManager.IsCLRType (r))){
2225                                 //
2226                                 // Step 1: Perform Operator Overload location
2227                                 //
2228                                 Expression left_expr, right_expr;
2229                                 
2230                                 string op = oper_names [(int) oper];
2231                                 
2232                                 MethodGroupExpr union;
2233                                 left_expr = MemberLookup (ec, l, op, MemberTypes.Method, AllBindingFlags, loc);
2234                                 if (r != l){
2235                                         right_expr = MemberLookup (
2236                                                 ec, r, op, MemberTypes.Method, AllBindingFlags, loc);
2237                                         union = Invocation.MakeUnionSet (left_expr, right_expr, loc);
2238                                 } else
2239                                         union = (MethodGroupExpr) left_expr;
2240                                 
2241                                 if (union != null) {
2242                                         Arguments = new ArrayList ();
2243                                         Arguments.Add (new Argument (left, Argument.AType.Expression));
2244                                         Arguments.Add (new Argument (right, Argument.AType.Expression));
2245                                         
2246                                         method = Invocation.OverloadResolve (ec, union, Arguments, Location.Null);
2247                                         if (method != null) {
2248                                                 MethodInfo mi = (MethodInfo) method;
2249                                                 
2250                                                 type = mi.ReturnType;
2251                                                 return this;
2252                                         } else {
2253                                                 overload_failed = true;
2254                                         }
2255                                 }
2256                         }
2257                         
2258                         //
2259                         // Step 2: Default operations on CLI native types.
2260                         //
2261
2262                         //
2263                         // Step 0: String concatenation (because overloading will get this wrong)
2264                         //
2265                         if (oper == Operator.Addition){
2266                                 //
2267                                 // If any of the arguments is a string, cast to string
2268                                 //
2269                                 
2270                                 if (l == TypeManager.string_type){
2271                                         
2272                                         if (r == TypeManager.void_type) {
2273                                                 Error_OperatorCannotBeApplied ();
2274                                                 return null;
2275                                         }
2276                                         
2277                                         if (r == TypeManager.string_type){
2278                                                 if (left is Constant && right is Constant){
2279                                                         StringConstant ls = (StringConstant) left;
2280                                                         StringConstant rs = (StringConstant) right;
2281                                                         
2282                                                         return new StringConstant (
2283                                                                 ls.Value + rs.Value);
2284                                                 }
2285
2286                                                 if (left is Binary){
2287                                                         Binary b = (Binary) left;
2288
2289                                                         //
2290                                                         // Call String.Concat (string, string, string) or
2291                                                         // String.Concat (string, string, string, string)
2292                                                         // if possible.
2293                                                         //
2294                                                         if (b.oper == Operator.Addition &&
2295                                                             (b.method == TypeManager.string_concat_string_string ||
2296                                                              b.method == TypeManager.string_concat_string_string_string)){
2297                                                                 ArrayList bargs = b.Arguments;
2298                                                                 int count = bargs.Count;
2299                                                                 
2300                                                                 if (count == 2){
2301                                                                         Arguments = bargs;
2302                                                                         Arguments.Add (new Argument (right, Argument.AType.Expression));
2303                                                                         type = TypeManager.string_type;
2304                                                                         method = TypeManager.string_concat_string_string_string;
2305                                                                         
2306                                                                         return this;
2307                                                                 } else if (count == 3){
2308                                                                         Arguments = bargs;
2309                                                                         Arguments.Add (new Argument (right, Argument.AType.Expression));
2310                                                                         type = TypeManager.string_type;
2311                                                                         method = TypeManager.string_concat_string_string_string_string;                                                                 
2312                                                                         return this;
2313                                                                 }
2314                                                         }
2315                                                 }
2316
2317                                                 // string + string
2318                                                 method = TypeManager.string_concat_string_string;
2319                                         } else {
2320                                                 // string + object
2321                                                 method = TypeManager.string_concat_object_object;
2322                                                 right = Convert.ImplicitConversion (
2323                                                         ec, right, TypeManager.object_type, loc);
2324                                                 if (right == null){
2325                                                         Error_OperatorCannotBeApplied (loc, OperName (oper), l, r);
2326                                                         return null;
2327                                                 }
2328                                         }
2329                                         type = TypeManager.string_type;
2330
2331                                         Arguments = new ArrayList ();
2332                                         Arguments.Add (new Argument (left, Argument.AType.Expression));
2333                                         Arguments.Add (new Argument (right, Argument.AType.Expression));
2334
2335                                         return this;
2336                                         
2337                                 } else if (r == TypeManager.string_type){
2338                                         // object + string
2339
2340                                         if (l == TypeManager.void_type) {
2341                                                 Error_OperatorCannotBeApplied ();
2342                                                 return null;
2343                                         }
2344                                         
2345                                         method = TypeManager.string_concat_object_object;
2346                                         left = Convert.ImplicitConversion (ec, left, TypeManager.object_type, loc);
2347                                         if (left == null){
2348                                                 Error_OperatorCannotBeApplied (loc, OperName (oper), l, r);
2349                                                 return null;
2350                                         }
2351                                         Arguments = new ArrayList ();
2352                                         Arguments.Add (new Argument (left, Argument.AType.Expression));
2353                                         Arguments.Add (new Argument (right, Argument.AType.Expression));
2354
2355                                         type = TypeManager.string_type;
2356
2357                                         return this;
2358                                 }
2359
2360                                 //
2361                                 // Transform a + ( - b) into a - b
2362                                 //
2363                                 if (right is Unary){
2364                                         Unary right_unary = (Unary) right;
2365
2366                                         if (right_unary.Oper == Unary.Operator.UnaryNegation){
2367                                                 oper = Operator.Subtraction;
2368                                                 right = right_unary.Expr;
2369                                                 r = right.Type;
2370                                         }
2371                                 }
2372                         }
2373
2374                         if (oper == Operator.Equality || oper == Operator.Inequality){
2375                                 if (l == TypeManager.bool_type || r == TypeManager.bool_type){
2376                                         if (r != TypeManager.bool_type || l != TypeManager.bool_type){
2377                                                 Error_OperatorCannotBeApplied ();
2378                                                 return null;
2379                                         }
2380                                         
2381                                         type = TypeManager.bool_type;
2382                                         return this;
2383                                 }
2384
2385                                 //
2386                                 // operator != (object a, object b)
2387                                 // operator == (object a, object b)
2388                                 //
2389                                 // For this to be used, both arguments have to be reference-types.
2390                                 // Read the rationale on the spec (14.9.6)
2391                                 //
2392                                 // Also, if at compile time we know that the classes do not inherit
2393                                 // one from the other, then we catch the error there.
2394                                 //
2395                                 if (!(l.IsValueType || r.IsValueType)){
2396                                         type = TypeManager.bool_type;
2397
2398                                         if (l == r)
2399                                                 return this;
2400                                         
2401                                         if (l.IsSubclassOf (r) || r.IsSubclassOf (l))
2402                                                 return this;
2403
2404                                         //
2405                                         // Also, a standard conversion must exist from either one
2406                                         //
2407                                         if (!(Convert.ImplicitStandardConversionExists (left, r) ||
2408                                               Convert.ImplicitStandardConversionExists (right, l))){
2409                                                 Error_OperatorCannotBeApplied ();
2410                                                 return null;
2411                                         }
2412                                         //
2413                                         // We are going to have to convert to an object to compare
2414                                         //
2415                                         if (l != TypeManager.object_type)
2416                                                 left = new EmptyCast (left, TypeManager.object_type);
2417                                         if (r != TypeManager.object_type)
2418                                                 right = new EmptyCast (right, TypeManager.object_type);
2419
2420                                         //
2421                                         // FIXME: CSC here catches errors cs254 and cs252
2422                                         //
2423                                         return this;
2424                                 }
2425
2426                                 //
2427                                 // One of them is a valuetype, but the other one is not.
2428                                 //
2429                                 if (!l.IsValueType || !r.IsValueType) {
2430                                         Error_OperatorCannotBeApplied ();
2431                                         return null;
2432                                 }
2433                         }
2434
2435                         // Only perform numeric promotions on:
2436                         // +, -, *, /, %, &, |, ^, ==, !=, <, >, <=, >=
2437                         //
2438                         if (oper == Operator.Addition || oper == Operator.Subtraction) {
2439                                 if (l.IsSubclassOf (TypeManager.delegate_type) &&
2440                                     r.IsSubclassOf (TypeManager.delegate_type)) {
2441                                         
2442                                         Arguments = new ArrayList ();
2443                                         Arguments.Add (new Argument (left, Argument.AType.Expression));
2444                                         Arguments.Add (new Argument (right, Argument.AType.Expression));
2445                                         
2446                                         if (oper == Operator.Addition)
2447                                                 method = TypeManager.delegate_combine_delegate_delegate;
2448                                         else
2449                                                 method = TypeManager.delegate_remove_delegate_delegate;
2450
2451                                         if (l != r) {
2452                                                 Error_OperatorCannotBeApplied ();
2453                                                 return null;
2454                                         }
2455
2456                                         DelegateOperation = true;
2457                                         type = l;
2458                                         return this;
2459                                 }
2460
2461                                 //
2462                                 // Pointer arithmetic:
2463                                 //
2464                                 // T* operator + (T* x, int y);
2465                                 // T* operator + (T* x, uint y);
2466                                 // T* operator + (T* x, long y);
2467                                 // T* operator + (T* x, ulong y);
2468                                 //
2469                                 // T* operator + (int y,   T* x);
2470                                 // T* operator + (uint y,  T *x);
2471                                 // T* operator + (long y,  T *x);
2472                                 // T* operator + (ulong y, T *x);
2473                                 //
2474                                 // T* operator - (T* x, int y);
2475                                 // T* operator - (T* x, uint y);
2476                                 // T* operator - (T* x, long y);
2477                                 // T* operator - (T* x, ulong y);
2478                                 //
2479                                 // long operator - (T* x, T *y)
2480                                 //
2481                                 if (l.IsPointer){
2482                                         if (r.IsPointer && oper == Operator.Subtraction){
2483                                                 if (r == l)
2484                                                         return new PointerArithmetic (
2485                                                                 false, left, right, TypeManager.int64_type,
2486                                                                 loc);
2487                                         } else if (is_32_or_64 (r))
2488                                                 return new PointerArithmetic (
2489                                                         oper == Operator.Addition, left, right, l, loc);
2490                                 } else if (r.IsPointer && is_32_or_64 (l) && oper == Operator.Addition)
2491                                         return new PointerArithmetic (
2492                                                 true, right, left, r, loc);
2493                         }
2494                         
2495                         //
2496                         // Enumeration operators
2497                         //
2498                         bool lie = TypeManager.IsEnumType (l);
2499                         bool rie = TypeManager.IsEnumType (r);
2500                         if (lie || rie){
2501                                 Expression temp;
2502
2503                                 // U operator - (E e, E f)
2504                                 if (lie && rie && oper == Operator.Subtraction){
2505                                         if (l == r){
2506                                                 type = TypeManager.EnumToUnderlying (l);
2507                                                 return this;
2508                                         } 
2509                                         Error_OperatorCannotBeApplied ();
2510                                         return null;
2511                                 }
2512                                         
2513                                 //
2514                                 // operator + (E e, U x)
2515                                 // operator - (E e, U x)
2516                                 //
2517                                 if (oper == Operator.Addition || oper == Operator.Subtraction){
2518                                         Type enum_type = lie ? l : r;
2519                                         Type other_type = lie ? r : l;
2520                                         Type underlying_type = TypeManager.EnumToUnderlying (enum_type);
2521 ;
2522                                         
2523                                         if (underlying_type != other_type){
2524                                                 Error_OperatorCannotBeApplied ();
2525                                                 return null;
2526                                         }
2527
2528                                         type = enum_type;
2529                                         return this;
2530                                 }
2531                                 
2532                                 if (!rie){
2533                                         temp = Convert.ImplicitConversion (ec, right, l, loc);
2534                                         if (temp != null)
2535                                                 right = temp;
2536                                         else {
2537                                                 Error_OperatorCannotBeApplied ();
2538                                                 return null;
2539                                         }
2540                                 } if (!lie){
2541                                         temp = Convert.ImplicitConversion (ec, left, r, loc);
2542                                         if (temp != null){
2543                                                 left = temp;
2544                                                 l = r;
2545                                         } else {
2546                                                 Error_OperatorCannotBeApplied ();
2547                                                 return null;
2548                                         }
2549                                 }
2550
2551                                 if (oper == Operator.Equality || oper == Operator.Inequality ||
2552                                     oper == Operator.LessThanOrEqual || oper == Operator.LessThan ||
2553                                     oper == Operator.GreaterThanOrEqual || oper == Operator.GreaterThan){
2554                                         if (left.Type != right.Type){
2555                                                 Error_OperatorCannotBeApplied ();
2556                                                 return null;
2557                                         }
2558                                         type = TypeManager.bool_type;
2559                                         return this;
2560                                 }
2561
2562                                 if (oper == Operator.BitwiseAnd ||
2563                                     oper == Operator.BitwiseOr ||
2564                                     oper == Operator.ExclusiveOr){
2565                                         type = l;
2566                                         return this;
2567                                 }
2568                                 Error_OperatorCannotBeApplied ();
2569                                 return null;
2570                         }
2571                         
2572                         if (oper == Operator.LeftShift || oper == Operator.RightShift)
2573                                 return CheckShiftArguments (ec);
2574
2575                         if (oper == Operator.LogicalOr || oper == Operator.LogicalAnd){
2576                                 if (l == TypeManager.bool_type && r == TypeManager.bool_type) {
2577                                         type = TypeManager.bool_type;
2578                                         return this;
2579                                 }
2580
2581                                 if (l != r) {
2582                                         Error_OperatorCannotBeApplied ();
2583                                         return null;
2584                                 }
2585
2586                                 Expression e = new ConditionalLogicalOperator (
2587                                         oper == Operator.LogicalAnd, left, right, l, loc);
2588                                 return e.Resolve (ec);
2589                         } 
2590
2591                         //
2592                         // operator & (bool x, bool y)
2593                         // operator | (bool x, bool y)
2594                         // operator ^ (bool x, bool y)
2595                         //
2596                         if (l == TypeManager.bool_type && r == TypeManager.bool_type){
2597                                 if (oper == Operator.BitwiseAnd ||
2598                                     oper == Operator.BitwiseOr ||
2599                                     oper == Operator.ExclusiveOr){
2600                                         type = l;
2601                                         return this;
2602                                 }
2603                         }
2604                         
2605                         //
2606                         // Pointer comparison
2607                         //
2608                         if (l.IsPointer && r.IsPointer){
2609                                 if (oper == Operator.Equality || oper == Operator.Inequality ||
2610                                     oper == Operator.LessThan || oper == Operator.LessThanOrEqual ||
2611                                     oper == Operator.GreaterThan || oper == Operator.GreaterThanOrEqual){
2612                                         type = TypeManager.bool_type;
2613                                         return this;
2614                                 }
2615                         }
2616                         
2617                         //
2618                         // We are dealing with numbers
2619                         //
2620                         if (overload_failed){
2621                                 Error_OperatorCannotBeApplied ();
2622                                 return null;
2623                         }
2624
2625                         //
2626                         // This will leave left or right set to null if there is an error
2627                         //
2628                         bool check_user_conv = is_user_defined (l) && is_user_defined (r);
2629                         DoNumericPromotions (ec, l, r, check_user_conv);
2630                         if (left == null || right == null){
2631                                 Error_OperatorCannotBeApplied (loc, OperName (oper), l, r);
2632                                 return null;
2633                         }
2634
2635                         //
2636                         // reload our cached types if required
2637                         //
2638                         l = left.Type;
2639                         r = right.Type;
2640                         
2641                         if (oper == Operator.BitwiseAnd ||
2642                             oper == Operator.BitwiseOr ||
2643                             oper == Operator.ExclusiveOr){
2644                                 if (l == r){
2645                                         if (!((l == TypeManager.int32_type) ||
2646                                               (l == TypeManager.uint32_type) ||
2647                                               (l == TypeManager.short_type) ||
2648                                               (l == TypeManager.ushort_type) ||
2649                                               (l == TypeManager.int64_type) ||
2650                                               (l == TypeManager.uint64_type)))
2651                                                 type = l;
2652                                 } else {
2653                                         Error_OperatorCannotBeApplied ();
2654                                         return null;
2655                                 }
2656                         }
2657
2658                         if (oper == Operator.Equality ||
2659                             oper == Operator.Inequality ||
2660                             oper == Operator.LessThanOrEqual ||
2661                             oper == Operator.LessThan ||
2662                             oper == Operator.GreaterThanOrEqual ||
2663                             oper == Operator.GreaterThan){
2664                                 type = TypeManager.bool_type;
2665                         }
2666
2667                         return this;
2668                 }
2669
2670                 public override Expression DoResolve (EmitContext ec)
2671                 {
2672                         left = left.Resolve (ec);
2673                         right = right.Resolve (ec);
2674
2675                         if (left == null || right == null)
2676                                 return null;
2677
2678                         eclass = ExprClass.Value;
2679
2680                         Constant rc = right as Constant;
2681                         Constant lc = left as Constant;
2682
2683                         if (rc != null & lc != null){
2684                                 Expression e = ConstantFold.BinaryFold (
2685                                         ec, oper, lc, rc, loc);
2686                                         if (e != null)
2687                                                 return e;
2688                         }
2689
2690                         return ResolveOperator (ec);
2691                 }
2692
2693                 /// <remarks>
2694                 ///   EmitBranchable is called from Statement.EmitBoolExpression in the
2695                 ///   context of a conditional bool expression.  This function will return
2696                 ///   false if it is was possible to use EmitBranchable, or true if it was.
2697                 ///
2698                 ///   The expression's code is generated, and we will generate a branch to `target'
2699                 ///   if the resulting expression value is equal to isTrue
2700                 /// </remarks>
2701                 public bool EmitBranchable (EmitContext ec, Label target, bool onTrue)
2702                 {
2703                         if (method != null)
2704                                 return false;
2705
2706                         ILGenerator ig = ec.ig;
2707
2708                         //
2709                         // This is more complicated than it looks, but its just to avoid
2710                         // duplicated tests: basically, we allow ==, !=, >, <, >= and <=
2711                         // but on top of that we want for == and != to use a special path
2712                         // if we are comparing against null
2713                         //
2714                         if (oper == Operator.Equality || oper == Operator.Inequality){
2715                                 bool my_on_true = oper == Operator.Inequality ? onTrue : !onTrue;
2716
2717                                 if (left is NullLiteral){
2718                                         right.Emit (ec);
2719                                         if (my_on_true)
2720                                                 ig.Emit (OpCodes.Brtrue, target);
2721                                         else
2722                                                 ig.Emit (OpCodes.Brfalse, target);
2723                                         return true;
2724                                 } else if (right is NullLiteral){
2725                                         left.Emit (ec);
2726                                         if (my_on_true)
2727                                                 ig.Emit (OpCodes.Brtrue, target);
2728                                         else
2729                                                 ig.Emit (OpCodes.Brfalse, target);
2730                                         return true;
2731                                 } else if (left is BoolConstant){
2732                                         right.Emit (ec);
2733                                         if (my_on_true != ((BoolConstant) left).Value)
2734                                                 ig.Emit (OpCodes.Brtrue, target);
2735                                         else
2736                                                 ig.Emit (OpCodes.Brfalse, target);
2737                                         return true;
2738                                 } else if (right is BoolConstant){
2739                                         left.Emit (ec);
2740                                         if (my_on_true != ((BoolConstant) right).Value)
2741                                                 ig.Emit (OpCodes.Brtrue, target);
2742                                         else
2743                                                 ig.Emit (OpCodes.Brfalse, target);
2744                                         return true;
2745                                 }
2746
2747                         } else if (oper == Operator.LogicalAnd){
2748                                 if (left is Binary){
2749                                         Binary left_binary = (Binary) left;
2750
2751                                         if (onTrue){
2752                                                 Label tests_end = ig.DefineLabel ();
2753                                                 
2754                                                 if (left_binary.EmitBranchable (ec, tests_end, false)){
2755                                                         if (right is Binary){
2756                                                                 Binary right_binary = (Binary) right;
2757
2758                                                                 if (right_binary.EmitBranchable (ec, target, true)){
2759                                                                         ig.MarkLabel (tests_end);
2760                                                                         return true;
2761                                                                 }
2762                                                         }
2763                                                         right.Emit (ec);
2764                                                         ig.Emit (OpCodes.Brtrue, target);
2765                                                         ig.MarkLabel (tests_end);
2766                                                         return true;
2767                                                 }
2768                                         } else {
2769                                                 if (left_binary.EmitBranchable (ec, target, false)){
2770                                                         if (right is Binary){
2771                                                                 Binary right_binary = (Binary) right;
2772                                                                 
2773                                                                 if (right_binary.EmitBranchable (ec, target, false))
2774                                                                         return true;
2775                                                         }
2776                                                         right.Emit (ec);
2777                                                         if (onTrue)
2778                                                                 ig.Emit (OpCodes.Brtrue, target);
2779                                                         else
2780                                                                 ig.Emit (OpCodes.Brfalse, target);
2781                                                         return true;
2782                                                 }
2783                                         }
2784                                         //
2785                                         // Give up, and let the regular Emit work, but we could
2786                                         // also optimize the left-non-Branchable, but-right-Branchable
2787                                         //
2788                                 }
2789                                 return false;
2790                         } else if (oper == Operator.LogicalOr){
2791                                 if (left is Binary){
2792                                         Binary left_binary = (Binary) left;
2793
2794                                         if (onTrue){
2795                                                 if (left_binary.EmitBranchable (ec, target, true)){
2796                                                         if (right is Binary){
2797                                                                 Binary right_binary = (Binary) right;
2798                                                                 
2799                                                                 if (right_binary.EmitBranchable (ec, target, true))
2800                                                                         return true;
2801                                                         }
2802                                                         right.Emit (ec);
2803                                                         ig.Emit (OpCodes.Brtrue, target);
2804                                                         return true;
2805                                                 }
2806                                                 
2807                                                 //
2808                                                 // Give up, and let the regular Emit work, but we could
2809                                                 // also optimize the left-non-Branchable, but-right-Branchable
2810                                                 //
2811                                         } else {
2812                                                 Label tests_end = ig.DefineLabel ();
2813                                                 
2814                                                 if (left_binary.EmitBranchable (ec, tests_end, true)){
2815                                                         if (right is Binary){
2816                                                                 Binary right_binary = (Binary) right;
2817
2818                                                                 if (right_binary.EmitBranchable (ec, target, false)){
2819                                                                         ig.MarkLabel (tests_end);
2820                                                                         return true;
2821                                                                 }
2822                                                         }
2823                                                         right.Emit (ec);
2824                                                         ig.Emit (OpCodes.Brfalse, target);
2825                                                         ig.MarkLabel (tests_end);
2826                                                         return true;
2827                                                 }
2828                                         }
2829                                 }
2830                                 
2831                                 return false;
2832                         } else if (!(oper == Operator.LessThan ||
2833                                 oper == Operator.GreaterThan ||
2834                                 oper == Operator.LessThanOrEqual ||
2835                                 oper == Operator.GreaterThanOrEqual))
2836                                 return false;
2837                         
2838                         left.Emit (ec);
2839                         right.Emit (ec);
2840
2841                         Type t = left.Type;
2842                         bool isUnsigned = is_unsigned (t);
2843
2844                         switch (oper){
2845                         case Operator.Equality:
2846                                 if (onTrue)
2847                                         ig.Emit (OpCodes.Beq, target);
2848                                 else
2849                                         ig.Emit (OpCodes.Bne_Un, target);
2850                                 break;
2851
2852                         case Operator.Inequality:
2853                                 if (onTrue)
2854                                         ig.Emit (OpCodes.Bne_Un, target);
2855                                 else
2856                                         ig.Emit (OpCodes.Beq, target);
2857                                 break;
2858
2859                         case Operator.LessThan:
2860                                 if (onTrue)
2861                                         if (isUnsigned)
2862                                                 ig.Emit (OpCodes.Blt_Un, target);
2863                                         else
2864                                                 ig.Emit (OpCodes.Blt, target);
2865                                 else
2866                                         if (isUnsigned)
2867                                                 ig.Emit (OpCodes.Bge_Un, target);
2868                                         else
2869                                                 ig.Emit (OpCodes.Bge, target);
2870                                 break;
2871
2872                         case Operator.GreaterThan:
2873                                 if (onTrue)
2874                                         if (isUnsigned)
2875                                                 ig.Emit (OpCodes.Bgt_Un, target);
2876                                         else
2877                                                 ig.Emit (OpCodes.Bgt, target);
2878                                 else
2879                                         if (isUnsigned)
2880                                                 ig.Emit (OpCodes.Ble_Un, target);
2881                                         else
2882                                                 ig.Emit (OpCodes.Ble, target);
2883                                 break;
2884
2885                         case Operator.LessThanOrEqual:
2886                                 if (t == TypeManager.double_type || t == TypeManager.float_type)
2887                                         isUnsigned = true;
2888
2889                                 if (onTrue)
2890                                         if (isUnsigned)
2891                                                 ig.Emit (OpCodes.Ble_Un, target);
2892                                         else
2893                                                 ig.Emit (OpCodes.Ble, target);
2894                                 else
2895                                         if (isUnsigned)
2896                                                 ig.Emit (OpCodes.Bgt_Un, target);
2897                                         else
2898                                                 ig.Emit (OpCodes.Bgt, target);
2899                                 break;
2900
2901
2902                         case Operator.GreaterThanOrEqual:
2903                                 if (t == TypeManager.double_type || t == TypeManager.float_type)
2904                                         isUnsigned = true;
2905                                 if (onTrue)
2906                                         if (isUnsigned)
2907                                                 ig.Emit (OpCodes.Bge_Un, target);
2908                                         else
2909                                                 ig.Emit (OpCodes.Bge, target);
2910                                 else
2911                                         if (isUnsigned)
2912                                                 ig.Emit (OpCodes.Blt_Un, target);
2913                                         else
2914                                                 ig.Emit (OpCodes.Blt, target);
2915                                 break;
2916
2917                         default:
2918                                 return false;
2919                         }
2920                         
2921                         return true;
2922                 }
2923                 
2924                 public override void Emit (EmitContext ec)
2925                 {
2926                         ILGenerator ig = ec.ig;
2927                         Type l = left.Type;
2928                         Type r = right.Type;
2929                         OpCode opcode;
2930
2931                         if (method != null) {
2932
2933                                 // Note that operators are static anyway
2934                                 
2935                                 if (Arguments != null) 
2936                                         Invocation.EmitArguments (ec, method, Arguments);
2937                                 
2938                                 if (method is MethodInfo)
2939                                         ig.Emit (OpCodes.Call, (MethodInfo) method);
2940                                 else
2941                                         ig.Emit (OpCodes.Call, (ConstructorInfo) method);
2942
2943                                 if (DelegateOperation)
2944                                         ig.Emit (OpCodes.Castclass, type);
2945                                         
2946                                 return;
2947                         }
2948
2949                         //
2950                         // Handle short-circuit operators differently
2951                         // than the rest
2952                         //
2953                         if (oper == Operator.LogicalAnd){
2954                                 Label load_zero = ig.DefineLabel ();
2955                                 Label end = ig.DefineLabel ();
2956                                 bool process = true;
2957
2958                                 if (left is Binary){
2959                                         Binary left_binary = (Binary) left;
2960
2961                                         if (left_binary.EmitBranchable (ec, load_zero, false)){
2962                                                 right.Emit (ec);
2963                                                 ig.Emit (OpCodes.Br, end);
2964                                                 process = false;
2965                                         }
2966                                 }
2967
2968                                 if (process){
2969                                         left.Emit (ec);
2970                                         ig.Emit (OpCodes.Brfalse, load_zero);
2971                                         right.Emit (ec);
2972                                         ig.Emit (OpCodes.Br, end);
2973                                 }
2974                                 ig.MarkLabel (load_zero);
2975                                 ig.Emit (OpCodes.Ldc_I4_0);
2976                                 ig.MarkLabel (end);
2977                                 return;
2978                         } else if (oper == Operator.LogicalOr){
2979                                 Label load_one = ig.DefineLabel ();
2980                                 Label end = ig.DefineLabel ();
2981                                 bool process = true;
2982                                 
2983                                 if (left is Binary){
2984                                         Binary left_binary = (Binary) left;
2985
2986                                         if (left_binary.EmitBranchable (ec, load_one, true)){
2987                                                 right.Emit (ec);
2988                                                 ig.Emit (OpCodes.Br, end);
2989                                                 process = false;
2990                                         } 
2991                                 }
2992
2993                                 if (process){
2994                                         left.Emit (ec);
2995                                         ig.Emit (OpCodes.Brtrue, load_one);
2996                                         right.Emit (ec);
2997                                         ig.Emit (OpCodes.Br, end);
2998                                 }
2999                                 ig.MarkLabel (load_one);
3000                                 ig.Emit (OpCodes.Ldc_I4_1);
3001                                 ig.MarkLabel (end);
3002                                 return;
3003                         }
3004                         
3005                         left.Emit (ec);
3006                         right.Emit (ec);
3007
3008                         bool isUnsigned = is_unsigned (left.Type);
3009
3010                         switch (oper){
3011                         case Operator.Multiply:
3012                                 if (ec.CheckState){
3013                                         if (l == TypeManager.int32_type || l == TypeManager.int64_type)
3014                                                 opcode = OpCodes.Mul_Ovf;
3015                                         else if (isUnsigned)
3016                                                 opcode = OpCodes.Mul_Ovf_Un;
3017                                         else
3018                                                 opcode = OpCodes.Mul;
3019                                 } else
3020                                         opcode = OpCodes.Mul;
3021
3022                                 break;
3023
3024                         case Operator.Division:
3025                                 if (isUnsigned)
3026                                         opcode = OpCodes.Div_Un;
3027                                 else
3028                                         opcode = OpCodes.Div;
3029                                 break;
3030
3031                         case Operator.Modulus:
3032                                 if (isUnsigned)
3033                                         opcode = OpCodes.Rem_Un;
3034                                 else
3035                                         opcode = OpCodes.Rem;
3036                                 break;
3037
3038                         case Operator.Addition:
3039                                 if (ec.CheckState){
3040                                         if (l == TypeManager.int32_type || l == TypeManager.int64_type)
3041                                                 opcode = OpCodes.Add_Ovf;
3042                                         else if (isUnsigned)
3043                                                 opcode = OpCodes.Add_Ovf_Un;
3044                                         else
3045                                                 opcode = OpCodes.Add;
3046                                 } else
3047                                         opcode = OpCodes.Add;
3048                                 break;
3049
3050                         case Operator.Subtraction:
3051                                 if (ec.CheckState){
3052                                         if (l == TypeManager.int32_type || l == TypeManager.int64_type)
3053                                                 opcode = OpCodes.Sub_Ovf;
3054                                         else if (isUnsigned)
3055                                                 opcode = OpCodes.Sub_Ovf_Un;
3056                                         else
3057                                                 opcode = OpCodes.Sub;
3058                                 } else
3059                                         opcode = OpCodes.Sub;
3060                                 break;
3061
3062                         case Operator.RightShift:
3063                                 if (isUnsigned)
3064                                         opcode = OpCodes.Shr_Un;
3065                                 else
3066                                         opcode = OpCodes.Shr;
3067                                 break;
3068                                 
3069                         case Operator.LeftShift:
3070                                 opcode = OpCodes.Shl;
3071                                 break;
3072
3073                         case Operator.Equality:
3074                                 opcode = OpCodes.Ceq;
3075                                 break;
3076
3077                         case Operator.Inequality:
3078                                 ig.Emit (OpCodes.Ceq);
3079                                 ig.Emit (OpCodes.Ldc_I4_0);
3080                                 
3081                                 opcode = OpCodes.Ceq;
3082                                 break;
3083
3084                         case Operator.LessThan:
3085                                 if (isUnsigned)
3086                                         opcode = OpCodes.Clt_Un;
3087                                 else
3088                                         opcode = OpCodes.Clt;
3089                                 break;
3090
3091                         case Operator.GreaterThan:
3092                                 if (isUnsigned)
3093                                         opcode = OpCodes.Cgt_Un;
3094                                 else
3095                                         opcode = OpCodes.Cgt;
3096                                 break;
3097
3098                         case Operator.LessThanOrEqual:
3099                                 Type lt = left.Type;
3100                                 
3101                                 if (isUnsigned || (lt == TypeManager.double_type || lt == TypeManager.float_type))
3102                                         ig.Emit (OpCodes.Cgt_Un);
3103                                 else
3104                                         ig.Emit (OpCodes.Cgt);
3105                                 ig.Emit (OpCodes.Ldc_I4_0);
3106                                 
3107                                 opcode = OpCodes.Ceq;
3108                                 break;
3109
3110                         case Operator.GreaterThanOrEqual:
3111                                 Type le = left.Type;
3112                                 
3113                                 if (isUnsigned || (le == TypeManager.double_type || le == TypeManager.float_type))
3114                                         ig.Emit (OpCodes.Clt_Un);
3115                                 else
3116                                         ig.Emit (OpCodes.Clt);
3117                                 
3118                                 ig.Emit (OpCodes.Ldc_I4_1);
3119                                 
3120                                 opcode = OpCodes.Sub;
3121                                 break;
3122
3123                         case Operator.BitwiseOr:
3124                                 opcode = OpCodes.Or;
3125                                 break;
3126
3127                         case Operator.BitwiseAnd:
3128                                 opcode = OpCodes.And;
3129                                 break;
3130
3131                         case Operator.ExclusiveOr:
3132                                 opcode = OpCodes.Xor;
3133                                 break;
3134
3135                         default:
3136                                 throw new Exception ("This should not happen: Operator = "
3137                                                      + oper.ToString ());
3138                         }
3139
3140                         ig.Emit (opcode);
3141                 }
3142
3143                 public bool IsBuiltinOperator {
3144                         get {
3145                                 return method == null;
3146                         }
3147                 }
3148         }
3149
3150         //
3151         // User-defined conditional logical operator
3152         public class ConditionalLogicalOperator : Expression {
3153                 Expression left, right;
3154                 bool is_and;
3155
3156                 public ConditionalLogicalOperator (bool is_and, Expression left, Expression right, Type t, Location loc)
3157                 {
3158                         type = t;
3159                         eclass = ExprClass.Value;
3160                         this.loc = loc;
3161                         this.left = left;
3162                         this.right = right;
3163                         this.is_and = is_and;
3164                 }
3165
3166                 protected void Error19 ()
3167                 {
3168                         Binary.Error_OperatorCannotBeApplied (loc, is_and ? "&&" : "||", type, type);
3169                 }
3170
3171                 protected void Error218 ()
3172                 {
3173                         Error (218, "The type ('" + TypeManager.CSharpName (type) + "') must contain " +
3174                                "declarations of operator true and operator false");
3175                 }
3176
3177                 Expression op_true, op_false, op;
3178
3179                 public override Expression DoResolve (EmitContext ec)
3180                 {
3181                         MethodInfo method;
3182                         Expression operator_group;
3183
3184                         operator_group = MethodLookup (ec, type, is_and ? "op_BitwiseAnd" : "op_BitwiseOr", loc);
3185                         if (operator_group == null) {
3186                                 Error19 ();
3187                                 return null;
3188                         }
3189
3190                         ArrayList arguments = new ArrayList ();
3191                         arguments.Add (new Argument (left, Argument.AType.Expression));
3192                         arguments.Add (new Argument (right, Argument.AType.Expression));
3193                         method = Invocation.OverloadResolve (ec, (MethodGroupExpr) operator_group, arguments, loc) as MethodInfo;
3194                         if ((method == null) || (method.ReturnType != type)) {
3195                                 Error19 ();
3196                                 return null;
3197                         }
3198
3199                         op = new StaticCallExpr (method, arguments, loc);
3200
3201                         op_true = GetOperatorTrue (ec, left, loc);
3202                         op_false = GetOperatorFalse (ec, left, loc);
3203                         if ((op_true == null) || (op_false == null)) {
3204                                 Error218 ();
3205                                 return null;
3206                         }
3207
3208                         return this;
3209                 }
3210
3211                 public override void Emit (EmitContext ec)
3212                 {
3213                         ILGenerator ig = ec.ig;
3214                         Label false_target = ig.DefineLabel ();
3215                         Label end_target = ig.DefineLabel ();
3216
3217                         ig.Emit (OpCodes.Nop);
3218
3219                         Statement.EmitBoolExpression (ec, is_and ? op_false : op_true, false_target, false);
3220                         left.Emit (ec);
3221                         ig.Emit (OpCodes.Br, end_target);
3222                         ig.MarkLabel (false_target);
3223                         op.Emit (ec);
3224                         ig.MarkLabel (end_target);
3225
3226                         ig.Emit (OpCodes.Nop);
3227                 }
3228         }
3229
3230         public class PointerArithmetic : Expression {
3231                 Expression left, right;
3232                 bool is_add;
3233
3234                 //
3235                 // We assume that `l' is always a pointer
3236                 //
3237                 public PointerArithmetic (bool is_addition, Expression l, Expression r, Type t, Location loc)
3238                 {
3239                         type = t;
3240                         eclass = ExprClass.Variable;
3241                         this.loc = loc;
3242                         left = l;
3243                         right = r;
3244                         is_add = is_addition;
3245                 }
3246
3247                 public override Expression DoResolve (EmitContext ec)
3248                 {
3249                         //
3250                         // We are born fully resolved
3251                         //
3252                         return this;
3253                 }
3254
3255                 public override void Emit (EmitContext ec)
3256                 {
3257                         Type op_type = left.Type;
3258                         ILGenerator ig = ec.ig;
3259                         int size = GetTypeSize (op_type.GetElementType ());
3260                         Type rtype = right.Type;
3261                         
3262                         if (rtype.IsPointer){
3263                                 //
3264                                 // handle (pointer - pointer)
3265                                 //
3266                                 left.Emit (ec);
3267                                 right.Emit (ec);
3268                                 ig.Emit (OpCodes.Sub);
3269
3270                                 if (size != 1){
3271                                         if (size == 0)
3272                                                 ig.Emit (OpCodes.Sizeof, op_type);
3273                                         else 
3274                                                 IntLiteral.EmitInt (ig, size);
3275                                         ig.Emit (OpCodes.Div);
3276                                 }
3277                                 ig.Emit (OpCodes.Conv_I8);
3278                         } else {
3279                                 //
3280                                 // handle + and - on (pointer op int)
3281                                 //
3282                                 left.Emit (ec);
3283                                 ig.Emit (OpCodes.Conv_I);
3284                                 right.Emit (ec);
3285                                 if (size != 1){
3286                                         if (size == 0)
3287                                                 ig.Emit (OpCodes.Sizeof, op_type);
3288                                         else 
3289                                                 IntLiteral.EmitInt (ig, size);
3290                                         if (rtype == TypeManager.int64_type)
3291                                                 ig.Emit (OpCodes.Conv_I8);
3292                                         else if (rtype == TypeManager.uint64_type)
3293                                                 ig.Emit (OpCodes.Conv_U8);
3294                                         ig.Emit (OpCodes.Mul);
3295                                         ig.Emit (OpCodes.Conv_I);
3296                                 }
3297                                 if (is_add)
3298                                         ig.Emit (OpCodes.Add);
3299                                 else
3300                                         ig.Emit (OpCodes.Sub);
3301                         }
3302                 }
3303         }
3304         
3305         /// <summary>
3306         ///   Implements the ternary conditional operator (?:)
3307         /// </summary>
3308         public class Conditional : Expression {
3309                 Expression expr, trueExpr, falseExpr;
3310                 
3311                 public Conditional (Expression expr, Expression trueExpr, Expression falseExpr, Location l)
3312                 {
3313                         this.expr = expr;
3314                         this.trueExpr = trueExpr;
3315                         this.falseExpr = falseExpr;
3316                         this.loc = l;
3317                 }
3318
3319                 public Expression Expr {
3320                         get {
3321                                 return expr;
3322                         }
3323                 }
3324
3325                 public Expression TrueExpr {
3326                         get {
3327                                 return trueExpr;
3328                         }
3329                 }
3330
3331                 public Expression FalseExpr {
3332                         get {
3333                                 return falseExpr;
3334                         }
3335                 }
3336
3337                 public override Expression DoResolve (EmitContext ec)
3338                 {
3339                         expr = expr.Resolve (ec);
3340
3341                         if (expr == null)
3342                                 return null;
3343                         
3344                         if (expr.Type != TypeManager.bool_type){
3345                                 expr = Expression.ResolveBoolean (
3346                                         ec, expr, loc);
3347                                 
3348                                 if (expr == null)
3349                                         return null;
3350                         }
3351                         
3352                         trueExpr = trueExpr.Resolve (ec);
3353                         falseExpr = falseExpr.Resolve (ec);
3354
3355                         if (trueExpr == null || falseExpr == null)
3356                                 return null;
3357
3358                         eclass = ExprClass.Value;
3359                         if (trueExpr.Type == falseExpr.Type)
3360                                 type = trueExpr.Type;
3361                         else {
3362                                 Expression conv;
3363                                 Type true_type = trueExpr.Type;
3364                                 Type false_type = falseExpr.Type;
3365
3366                                 if (trueExpr is NullLiteral){
3367                                         type = false_type;
3368                                         return this;
3369                                 } else if (falseExpr is NullLiteral){
3370                                         type = true_type;
3371                                         return this;
3372                                 }
3373                                 
3374                                 //
3375                                 // First, if an implicit conversion exists from trueExpr
3376                                 // to falseExpr, then the result type is of type falseExpr.Type
3377                                 //
3378                                 conv = Convert.ImplicitConversion (ec, trueExpr, false_type, loc);
3379                                 if (conv != null){
3380                                         //
3381                                         // Check if both can convert implicitl to each other's type
3382                                         //
3383                                         if (Convert.ImplicitConversion (ec, falseExpr, true_type, loc) != null){
3384                                                 Error (172,
3385                                                        "Can not compute type of conditional expression " +
3386                                                        "as `" + TypeManager.CSharpName (trueExpr.Type) +
3387                                                        "' and `" + TypeManager.CSharpName (falseExpr.Type) +
3388                                                        "' convert implicitly to each other");
3389                                                 return null;
3390                                         }
3391                                         type = false_type;
3392                                         trueExpr = conv;
3393                                 } else if ((conv = Convert.ImplicitConversion(ec, falseExpr, true_type,loc))!= null){
3394                                         type = true_type;
3395                                         falseExpr = conv;
3396                                 } else {
3397                                         Error (173, "The type of the conditional expression can " +
3398                                                "not be computed because there is no implicit conversion" +
3399                                                " from `" + TypeManager.CSharpName (trueExpr.Type) + "'" +
3400                                                " and `" + TypeManager.CSharpName (falseExpr.Type) + "'");
3401                                         return null;
3402                                 }
3403                         }
3404
3405                         if (expr is BoolConstant){
3406                                 BoolConstant bc = (BoolConstant) expr;
3407
3408                                 if (bc.Value)
3409                                         return trueExpr;
3410                                 else
3411                                         return falseExpr;
3412                         }
3413
3414                         return this;
3415                 }
3416
3417                 public override void Emit (EmitContext ec)
3418                 {
3419                         ILGenerator ig = ec.ig;
3420                         Label false_target = ig.DefineLabel ();
3421                         Label end_target = ig.DefineLabel ();
3422
3423                         Statement.EmitBoolExpression (ec, expr, false_target, false);
3424                         trueExpr.Emit (ec);
3425                         ig.Emit (OpCodes.Br, end_target);
3426                         ig.MarkLabel (false_target);
3427                         falseExpr.Emit (ec);
3428                         ig.MarkLabel (end_target);
3429                 }
3430
3431         }
3432
3433         /// <summary>
3434         ///   Local variables
3435         /// </summary>
3436         public class LocalVariableReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
3437                 public readonly string Name;
3438                 public readonly Block Block;
3439                 LocalInfo local_info;
3440                 VariableInfo variable_info;
3441                 bool is_readonly;
3442                 
3443                 public LocalVariableReference (Block block, string name, Location l)
3444                 {
3445                         Block = block;
3446                         Name = name;
3447                         loc = l;
3448                         eclass = ExprClass.Variable;
3449                 }
3450
3451                 // Setting `is_readonly' to false will allow you to create a writable
3452                 // reference to a read-only variable.  This is used by foreach and using.
3453                 public LocalVariableReference (Block block, string name, Location l,
3454                                                LocalInfo local_info, bool is_readonly)
3455                         : this (block, name, l)
3456                 {
3457                         this.local_info = local_info;
3458                         this.is_readonly = is_readonly;
3459                 }
3460
3461                 public VariableInfo VariableInfo {
3462                         get { return variable_info; }
3463                 }
3464
3465                 public bool IsReadOnly {
3466                         get {
3467                                 return is_readonly;
3468                         }
3469                 }
3470
3471                 protected void DoResolveBase (EmitContext ec)
3472                 {
3473                         if (local_info == null) {
3474                                 local_info = Block.GetLocalInfo (Name);
3475                                 is_readonly = local_info.ReadOnly;
3476                         }
3477
3478                         variable_info = Block.GetVariableInfo (local_info);
3479                         type = local_info.VariableType;
3480                 }
3481                 
3482                 public override Expression DoResolve (EmitContext ec)
3483                 {
3484                         DoResolveBase (ec);
3485
3486                         Expression e = Block.GetConstantExpression (Name);
3487                         if (e != null) {
3488                                 local_info.Used = true;
3489                                 eclass = ExprClass.Value;
3490                                 return e;
3491                         }
3492
3493                         if ((variable_info != null) && !variable_info.IsAssigned (ec, loc))
3494                                 return null;
3495
3496                         return this;
3497                 }
3498
3499                 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3500                 {
3501                         DoResolveBase (ec);
3502
3503                         if (variable_info != null)
3504                                 variable_info.SetAssigned (ec);
3505
3506                         Expression e = DoResolve (ec);
3507
3508                         if (e == null)
3509                                 return null;
3510
3511                         if (is_readonly){
3512                                 Error (1604, "cannot assign to `" + Name + "' because it is readonly");
3513                                 return null;
3514                         }
3515                         
3516                         return this;
3517                 }
3518
3519                 public bool VerifyFixed (bool is_expression)
3520                 {
3521                         return !is_expression || local_info.IsFixed;
3522                 }
3523
3524                 public override void Emit (EmitContext ec)
3525                 {
3526                         ILGenerator ig = ec.ig;
3527
3528                         if (local_info.LocalBuilder == null){
3529                                 ig.Emit (OpCodes.Ldarg_0);
3530                                 ig.Emit (OpCodes.Ldfld, local_info.FieldBuilder);
3531                         } else 
3532                                 ig.Emit (OpCodes.Ldloc, local_info.LocalBuilder);
3533                         
3534                         local_info.Used = true;
3535                 }
3536                 
3537                 public void EmitAssign (EmitContext ec, Expression source)
3538                 {
3539                         ILGenerator ig = ec.ig;
3540
3541                         local_info.Assigned = true;
3542
3543                         if (local_info.LocalBuilder == null){
3544                                 ig.Emit (OpCodes.Ldarg_0);
3545                                 source.Emit (ec);
3546                                 ig.Emit (OpCodes.Stfld, local_info.FieldBuilder);
3547                         } else {
3548                                 source.Emit (ec);
3549                                 ig.Emit (OpCodes.Stloc, local_info.LocalBuilder);
3550                         }
3551                 }
3552                 
3553                 public void AddressOf (EmitContext ec, AddressOp mode)
3554                 {
3555                         ILGenerator ig = ec.ig;
3556                         
3557                         if (local_info.LocalBuilder == null){
3558                                 ig.Emit (OpCodes.Ldarg_0);
3559                                 ig.Emit (OpCodes.Ldflda, local_info.FieldBuilder);
3560                         } else
3561                                 ig.Emit (OpCodes.Ldloca, local_info.LocalBuilder);
3562                 }
3563
3564                 public override string ToString ()
3565                 {
3566                         return String.Format ("{0} ({1}:{2})", GetType (), Name, loc);
3567                 }
3568         }
3569
3570         /// <summary>
3571         ///   This represents a reference to a parameter in the intermediate
3572         ///   representation.
3573         /// </summary>
3574         public class ParameterReference : Expression, IAssignMethod, IMemoryLocation, IVariable {
3575                 Parameters pars;
3576                 String name;
3577                 int idx;
3578                 Block block;
3579                 VariableInfo vi;
3580                 public Parameter.Modifier mod;
3581                 public bool is_ref, is_out;
3582                 
3583                 public ParameterReference (Parameters pars, Block block, int idx, string name, Location loc)
3584                 {
3585                         this.pars = pars;
3586                         this.block = block;
3587                         this.idx  = idx;
3588                         this.name = name;
3589                         this.loc = loc;
3590                         eclass = ExprClass.Variable;
3591                 }
3592
3593                 public VariableInfo VariableInfo {
3594                         get { return vi; }
3595                 }
3596
3597                 public bool VerifyFixed (bool is_expression)
3598                 {
3599                         return !is_expression;
3600                 }
3601
3602                 public bool IsAssigned (EmitContext ec, Location loc)
3603                 {
3604                         if (!ec.DoFlowAnalysis || !is_out ||
3605                             ec.CurrentBranching.IsAssigned (vi))
3606                                 return true;
3607
3608                         Report.Error (165, loc,
3609                                       "Use of unassigned parameter `" + name + "'");
3610                         return false;
3611                 }
3612
3613                 public bool IsFieldAssigned (EmitContext ec, string field_name, Location loc)
3614                 {
3615                         if (!ec.DoFlowAnalysis || !is_out ||
3616                             ec.CurrentBranching.IsFieldAssigned (vi, field_name))
3617                                 return true;
3618
3619                         Report.Error (170, loc,
3620                                       "Use of possibly unassigned field `" + field_name + "'");
3621                         return false;
3622                 }
3623
3624                 public void SetAssigned (EmitContext ec)
3625                 {
3626                         if (is_out && ec.DoFlowAnalysis)
3627                                 ec.CurrentBranching.SetAssigned (vi);
3628                 }
3629
3630                 public void SetFieldAssigned (EmitContext ec, string field_name)
3631                 {
3632                         if (is_out && ec.DoFlowAnalysis)
3633                                 ec.CurrentBranching.SetFieldAssigned (vi, field_name);
3634                 }
3635
3636                 protected void DoResolveBase (EmitContext ec)
3637                 {
3638                         type = pars.GetParameterInfo (ec.DeclSpace, idx, out mod);
3639                         is_ref = (mod & Parameter.Modifier.ISBYREF) != 0;
3640                         is_out = (mod & Parameter.Modifier.OUT) != 0;
3641                         eclass = ExprClass.Variable;
3642
3643                         if (is_out)
3644                                 vi = block.ParameterMap [idx];
3645                 }
3646
3647                 //
3648                 // Notice that for ref/out parameters, the type exposed is not the
3649                 // same type exposed externally.
3650                 //
3651                 // for "ref int a":
3652                 //   externally we expose "int&"
3653                 //   here we expose       "int".
3654                 //
3655                 // We record this in "is_ref".  This means that the type system can treat
3656                 // the type as it is expected, but when we generate the code, we generate
3657                 // the alternate kind of code.
3658                 //
3659                 public override Expression DoResolve (EmitContext ec)
3660                 {
3661                         DoResolveBase (ec);
3662
3663                         if (is_out && ec.DoFlowAnalysis && !IsAssigned (ec, loc))
3664                                 return null;
3665
3666                         return this;
3667                 }
3668
3669                 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3670                 {
3671                         DoResolveBase (ec);
3672
3673                         SetAssigned (ec);
3674
3675                         return this;
3676                 }
3677
3678                 static public void EmitLdArg (ILGenerator ig, int x)
3679                 {
3680                         if (x <= 255){
3681                                 switch (x){
3682                                 case 0: ig.Emit (OpCodes.Ldarg_0); break;
3683                                 case 1: ig.Emit (OpCodes.Ldarg_1); break;
3684                                 case 2: ig.Emit (OpCodes.Ldarg_2); break;
3685                                 case 3: ig.Emit (OpCodes.Ldarg_3); break;
3686                                 default: ig.Emit (OpCodes.Ldarg_S, (byte) x); break;
3687                                 }
3688                         } else
3689                                 ig.Emit (OpCodes.Ldarg, x);
3690                 }
3691                 
3692                 //
3693                 // This method is used by parameters that are references, that are
3694                 // being passed as references:  we only want to pass the pointer (that
3695                 // is already stored in the parameter, not the address of the pointer,
3696                 // and not the value of the variable).
3697                 //
3698                 public void EmitLoad (EmitContext ec)
3699                 {
3700                         ILGenerator ig = ec.ig;
3701                         int arg_idx = idx;
3702
3703                         if (!ec.IsStatic)
3704                                 arg_idx++;
3705
3706                         EmitLdArg (ig, arg_idx);
3707                 }
3708                 
3709                 public override void Emit (EmitContext ec)
3710                 {
3711                         ILGenerator ig = ec.ig;
3712                         
3713                         if (ec.RemapToProxy){
3714                                 ig.Emit (OpCodes.Ldarg_0);
3715                                 ec.EmitArgument (idx);
3716                                 return;
3717                         }
3718                         
3719                         int arg_idx = idx;
3720
3721                         if (!ec.IsStatic)
3722                                 arg_idx++;
3723
3724                         EmitLdArg (ig, arg_idx);
3725
3726                         if (!is_ref)
3727                                 return;
3728
3729                         //
3730                         // If we are a reference, we loaded on the stack a pointer
3731                         // Now lets load the real value
3732                         //
3733                         LoadFromPtr (ig, type);
3734                 }
3735
3736                 public void EmitAssign (EmitContext ec, Expression source)
3737                 {
3738                         ILGenerator ig = ec.ig;
3739                         
3740                         if (ec.RemapToProxy){
3741                                 ig.Emit (OpCodes.Ldarg_0);
3742                                 source.Emit (ec);
3743                                 ec.EmitStoreArgument (idx);
3744                                 return;
3745                         }
3746                         
3747                         int arg_idx = idx;
3748
3749                         if (!ec.IsStatic)
3750                                 arg_idx++;
3751
3752                         if (is_ref)
3753                                 EmitLdArg (ig, arg_idx);
3754                         
3755                         source.Emit (ec);
3756
3757                         if (is_ref)
3758                                 StoreFromPtr (ig, type);
3759                         else {
3760                                 if (arg_idx <= 255)
3761                                         ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
3762                                 else
3763                                         ig.Emit (OpCodes.Starg, arg_idx);
3764                         }
3765                 }
3766
3767                 public void AddressOf (EmitContext ec, AddressOp mode)
3768                 {
3769                         if (ec.RemapToProxy){
3770                                 Report.Error (-1, "Report this: Taking the address of a remapped parameter not supported");
3771                                 return;
3772                         }
3773                         
3774                         int arg_idx = idx;
3775
3776                         if (!ec.IsStatic)
3777                                 arg_idx++;
3778
3779                         if (is_ref){
3780                                 if (arg_idx <= 255)
3781                                         ec.ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
3782                                 else
3783                                         ec.ig.Emit (OpCodes.Ldarg, arg_idx);
3784                         } else {
3785                                 if (arg_idx <= 255)
3786                                         ec.ig.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
3787                                 else
3788                                         ec.ig.Emit (OpCodes.Ldarga, arg_idx);
3789                         }
3790                 }
3791
3792         }
3793         
3794         /// <summary>
3795         ///   Used for arguments to New(), Invocation()
3796         /// </summary>
3797         public class Argument {
3798                 public enum AType : byte {
3799                         Expression,
3800                         Ref,
3801                         Out
3802                 };
3803
3804                 public readonly AType ArgType;
3805                 public Expression Expr;
3806                 
3807                 public Argument (Expression expr, AType type)
3808                 {
3809                         this.Expr = expr;
3810                         this.ArgType = type;
3811                 }
3812
3813                 public Type Type {
3814                         get {
3815                                 if (ArgType == AType.Ref || ArgType == AType.Out)
3816                                         return TypeManager.GetReferenceType (Expr.Type);
3817                                 else
3818                                         return Expr.Type;
3819                         }
3820                 }
3821
3822                 public Parameter.Modifier GetParameterModifier ()
3823                 {
3824                         switch (ArgType) {
3825                         case AType.Out:
3826                                 return Parameter.Modifier.OUT | Parameter.Modifier.ISBYREF;
3827
3828                         case AType.Ref:
3829                                 return Parameter.Modifier.REF | Parameter.Modifier.ISBYREF;
3830
3831                         default:
3832                                 return Parameter.Modifier.NONE;
3833                         }
3834                 }
3835
3836                 public static string FullDesc (Argument a)
3837                 {
3838                         return (a.ArgType == AType.Ref ? "ref " :
3839                                 (a.ArgType == AType.Out ? "out " : "")) +
3840                                 TypeManager.CSharpName (a.Expr.Type);
3841                 }
3842
3843                 public bool ResolveMethodGroup (EmitContext ec, Location loc)
3844                 {
3845                         // FIXME: csc doesn't report any error if you try to use `ref' or
3846                         //        `out' in a delegate creation expression.
3847                         Expr = Expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
3848                         if (Expr == null)
3849                                 return false;
3850
3851                         return true;
3852                 }
3853                 
3854                 public bool Resolve (EmitContext ec, Location loc)
3855                 {
3856                         if (ArgType == AType.Ref) {
3857                                 Expr = Expr.Resolve (ec);
3858                                 if (Expr == null)
3859                                         return false;
3860
3861                                 Expr = Expr.ResolveLValue (ec, Expr);
3862                         } else if (ArgType == AType.Out)
3863                                 Expr = Expr.ResolveLValue (ec, new EmptyExpression ());
3864                         else
3865                                 Expr = Expr.Resolve (ec);
3866
3867                         if (Expr == null)
3868                                 return false;
3869
3870                         if (ArgType == AType.Expression)
3871                                 return true;
3872
3873                         if (Expr.eclass != ExprClass.Variable){
3874                                 //
3875                                 // We just probe to match the CSC output
3876                                 //
3877                                 if (Expr.eclass == ExprClass.PropertyAccess ||
3878                                     Expr.eclass == ExprClass.IndexerAccess){
3879                                         Report.Error (
3880                                                 206, loc,
3881                                                 "A property or indexer can not be passed as an out or ref " +
3882                                                 "parameter");
3883                                 } else {
3884                                         Report.Error (
3885                                                 1510, loc,
3886                                                 "An lvalue is required as an argument to out or ref");
3887                                 }
3888                                 return false;
3889                         }
3890                                 
3891                         return true;
3892                 }
3893
3894                 public void Emit (EmitContext ec)
3895                 {
3896                         //
3897                         // Ref and Out parameters need to have their addresses taken.
3898                         //
3899                         // ParameterReferences might already be references, so we want
3900                         // to pass just the value
3901                         //
3902                         if (ArgType == AType.Ref || ArgType == AType.Out){
3903                                 AddressOp mode = AddressOp.Store;
3904
3905                                 if (ArgType == AType.Ref)
3906                                         mode |= AddressOp.Load;
3907                                 
3908                                 if (Expr is ParameterReference){
3909                                         ParameterReference pr = (ParameterReference) Expr;
3910
3911                                         if (pr.is_ref)
3912                                                 pr.EmitLoad (ec);
3913                                         else {
3914                                                 
3915                                                 pr.AddressOf (ec, mode);
3916                                         }
3917                                 } else
3918                                         ((IMemoryLocation)Expr).AddressOf (ec, mode);
3919                         } else
3920                                 Expr.Emit (ec);
3921                 }
3922         }
3923
3924         /// <summary>
3925         ///   Invocation of methods or delegates.
3926         /// </summary>
3927         public class Invocation : ExpressionStatement {
3928                 public readonly ArrayList Arguments;
3929
3930                 Expression expr;
3931                 MethodBase method = null;
3932                 bool is_base;
3933                 
3934                 static Hashtable method_parameter_cache;
3935
3936                 static Invocation ()
3937                 {
3938                         method_parameter_cache = new PtrHashtable ();
3939                 }
3940                         
3941                 //
3942                 // arguments is an ArrayList, but we do not want to typecast,
3943                 // as it might be null.
3944                 //
3945                 // FIXME: only allow expr to be a method invocation or a
3946                 // delegate invocation (7.5.5)
3947                 //
3948                 public Invocation (Expression expr, ArrayList arguments, Location l)
3949                 {
3950                         this.expr = expr;
3951                         Arguments = arguments;
3952                         loc = l;
3953                 }
3954
3955                 public Expression Expr {
3956                         get {
3957                                 return expr;
3958                         }
3959                 }
3960
3961                 /// <summary>
3962                 ///   Returns the Parameters (a ParameterData interface) for the
3963                 ///   Method `mb'
3964                 /// </summary>
3965                 public static ParameterData GetParameterData (MethodBase mb)
3966                 {
3967                         object pd = method_parameter_cache [mb];
3968                         object ip;
3969                         
3970                         if (pd != null)
3971                                 return (ParameterData) pd;
3972
3973                         
3974                         ip = TypeManager.LookupParametersByBuilder (mb);
3975                         if (ip != null){
3976                                 method_parameter_cache [mb] = ip;
3977
3978                                 return (ParameterData) ip;
3979                         } else {
3980                                 ParameterInfo [] pi = mb.GetParameters ();
3981                                 ReflectionParameters rp = new ReflectionParameters (pi);
3982                                 method_parameter_cache [mb] = rp;
3983
3984                                 return (ParameterData) rp;
3985                         }
3986                 }
3987
3988                 /// <summary>
3989                 ///  Determines "better conversion" as specified in 7.4.2.3
3990                 ///  Returns : 1 if a->p is better
3991                 ///            0 if a->q or neither is better 
3992                 /// </summary>
3993                 static int BetterConversion (EmitContext ec, Argument a, Type p, Type q, Location loc)
3994                 {
3995                         Type argument_type = a.Type;
3996                         Expression argument_expr = a.Expr;
3997
3998                         if (argument_type == null)
3999                                 throw new Exception ("Expression of type " + a.Expr + " does not resolve its type");
4000
4001                         //
4002                         // This is a special case since csc behaves this way. I can't find
4003                         // it anywhere in the spec but oh well ...
4004                         //
4005                         if (argument_expr is NullLiteral && p == TypeManager.string_type && q == TypeManager.object_type)
4006                                 return 1;
4007                         else if (argument_expr is NullLiteral && p == TypeManager.object_type && q == TypeManager.string_type)
4008                                 return 0;
4009                         
4010                         if (p == q)
4011                                 return 0;
4012                         
4013                         if (argument_type == p)
4014                                 return 1;
4015
4016                         if (argument_type == q)
4017                                 return 0;
4018
4019                         //
4020                         // Now probe whether an implicit constant expression conversion
4021                         // can be used.
4022                         //
4023                         // An implicit constant expression conversion permits the following
4024                         // conversions:
4025                         //
4026                         //    * A constant-expression of type `int' can be converted to type
4027                         //      sbyte, byute, short, ushort, uint, ulong provided the value of
4028                         //      of the expression is withing the range of the destination type.
4029                         //
4030                         //    * A constant-expression of type long can be converted to type
4031                         //      ulong, provided the value of the constant expression is not negative
4032                         //
4033                         // FIXME: Note that this assumes that constant folding has
4034                         // taken place.  We dont do constant folding yet.
4035                         //
4036
4037                         if (argument_expr is IntConstant){
4038                                 IntConstant ei = (IntConstant) argument_expr;
4039                                 int value = ei.Value;
4040
4041                                 if (p == TypeManager.sbyte_type){
4042                                         if (value >= SByte.MinValue && value <= SByte.MaxValue)
4043                                                 return 1;
4044                                 } else if (p == TypeManager.byte_type){
4045                                         if (q == TypeManager.sbyte_type &&
4046                                             value >= SByte.MinValue && value <= SByte.MaxValue)
4047                                                 return 0;
4048                                         else if (Byte.MinValue >= 0 && value <= Byte.MaxValue)
4049                                                 return 1;
4050                                 } else if (p == TypeManager.short_type){
4051                                         if (value >= Int16.MinValue && value <= Int16.MaxValue)
4052                                                 return 1;
4053                                 } else if (p == TypeManager.ushort_type){
4054                                         if (q == TypeManager.short_type &&
4055                                             value >= Int16.MinValue && value <= Int16.MaxValue)
4056                                                 return 0;
4057                                         else if (value >= UInt16.MinValue && value <= UInt16.MaxValue)
4058                                                 return 1;
4059                                 } else if (p == TypeManager.int32_type){
4060                                         if (value >= Int32.MinValue && value <= Int32.MaxValue)
4061                                                 return 1;
4062                                 } else if (p == TypeManager.uint32_type){
4063                                         //
4064                                         // we can optimize this case: a positive int32
4065                                         // always fits on a uint32
4066                                         //
4067                                         if (value >= 0)
4068                                                 return 1;
4069                                 } else if (p == TypeManager.uint64_type){
4070                                         //
4071                                         // we can optimize this case: a positive int32
4072                                         // always fits on a uint64
4073                                         //
4074                                         if (q == TypeManager.int64_type)
4075                                                 return 0;
4076                                         else if (value >= 0)
4077                                                 return 1;
4078                                 } else if (p == TypeManager.int64_type){
4079                                         return 1;
4080                                 }
4081                         } else if (argument_type == TypeManager.int64_type && argument_expr is LongConstant){
4082                                 LongConstant lc = (LongConstant) argument_expr;
4083                                 
4084                                 if (p == TypeManager.uint64_type){
4085                                         if (lc.Value > 0)
4086                                                 return 1;
4087                                 }
4088                         }
4089
4090                         if (q == null) {
4091                                 Expression tmp = Convert.ImplicitConversion (ec, argument_expr, p, loc);
4092                                 
4093                                 if (tmp != null)
4094                                         return 1;
4095                                 else
4096                                         return 0;
4097                         }
4098
4099                         Expression p_tmp = new EmptyExpression (p);
4100                         Expression q_tmp = new EmptyExpression (q);
4101                         
4102                         if (Convert.ImplicitConversionExists (ec, p_tmp, q) == true &&
4103                             Convert.ImplicitConversionExists (ec, q_tmp, p) == false)
4104                                 return 1;
4105
4106                         if (p == TypeManager.sbyte_type)
4107                                 if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
4108                                     q == TypeManager.uint32_type || q == TypeManager.uint64_type)
4109                                         return 1;
4110
4111                         if (p == TypeManager.short_type)
4112                                 if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
4113                                     q == TypeManager.uint64_type)
4114                                         return 1;
4115
4116                         if (p == TypeManager.int32_type)
4117                                 if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
4118                                         return 1;
4119
4120                         if (p == TypeManager.int64_type)
4121                                 if (q == TypeManager.uint64_type)
4122                                         return 1;
4123
4124                         return 0;
4125                 }
4126                 
4127                 /// <summary>
4128                 ///  Determines "Better function"
4129                 /// </summary>
4130                 /// <remarks>
4131                 ///    and returns an integer indicating :
4132                 ///    0 if candidate ain't better
4133                 ///    1 if candidate is better than the current best match
4134                 /// </remarks>
4135                 static int BetterFunction (EmitContext ec, ArrayList args,
4136                                            MethodBase candidate, MethodBase best,
4137                                            bool expanded_form, Location loc)
4138                 {
4139                         ParameterData candidate_pd = GetParameterData (candidate);
4140                         ParameterData best_pd;
4141                         int argument_count;
4142                 
4143                         if (args == null)
4144                                 argument_count = 0;
4145                         else
4146                                 argument_count = args.Count;
4147
4148                         int cand_count = candidate_pd.Count;
4149
4150                         if (cand_count == 0 && argument_count == 0)
4151                                 return 1;
4152
4153                         if (candidate_pd.ParameterModifier (cand_count - 1) != Parameter.Modifier.PARAMS)
4154                                 if (cand_count != argument_count)
4155                                         return 0;
4156                         
4157                         if (best == null) {
4158                                 int x = 0;
4159
4160                                 if (argument_count == 0 && cand_count == 1 &&
4161                                     candidate_pd.ParameterModifier (cand_count - 1) == Parameter.Modifier.PARAMS)
4162                                         return 1;
4163                                 
4164                                 for (int j = argument_count; j > 0;) {
4165                                         j--;
4166
4167                                         Argument a = (Argument) args [j];
4168                                         Type t = candidate_pd.ParameterType (j);
4169
4170                                         if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
4171                                                 if (expanded_form)
4172                                                         t = t.GetElementType ();
4173
4174                                         x = BetterConversion (ec, a, t, null, loc);
4175                                         
4176                                         if (x <= 0)
4177                                                 break;
4178                                 }
4179
4180                                 if (x > 0)
4181                                         return 1;
4182                                 else
4183                                         return 0;
4184                         }
4185
4186                         best_pd = GetParameterData (best);
4187
4188                         int rating1 = 0, rating2 = 0;
4189                         
4190                         for (int j = 0; j < argument_count; ++j) {
4191                                 int x, y;
4192                                 
4193                                 Argument a = (Argument) args [j];
4194
4195                                 Type ct = candidate_pd.ParameterType (j);
4196                                 Type bt = best_pd.ParameterType (j);
4197
4198                                 if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
4199                                         if (expanded_form)
4200                                                 ct = ct.GetElementType ();
4201
4202                                 if (best_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
4203                                         if (expanded_form)
4204                                                 bt = bt.GetElementType ();
4205                                 
4206                                 x = BetterConversion (ec, a, ct, bt, loc);
4207                                 y = BetterConversion (ec, a, bt, ct, loc);
4208
4209                                 if (x < y)
4210                                         return 0;
4211                                 
4212                                 rating1 += x;
4213                                 rating2 += y;
4214                         }
4215
4216                         if (rating1 > rating2)
4217                                 return 1;
4218                         else
4219                                 return 0;
4220                 }
4221
4222                 public static string FullMethodDesc (MethodBase mb)
4223                 {
4224                         string ret_type = "";
4225
4226                         if (mb is MethodInfo)
4227                                 ret_type = TypeManager.CSharpName (((MethodInfo) mb).ReturnType);
4228                         
4229                         StringBuilder sb = new StringBuilder (ret_type);
4230                         sb.Append (" ");
4231                         sb.Append (mb.ReflectedType.ToString ());
4232                         sb.Append (".");
4233                         sb.Append (mb.Name);
4234                         
4235                         ParameterData pd = GetParameterData (mb);
4236
4237                         int count = pd.Count;
4238                         sb.Append (" (");
4239                         
4240                         for (int i = count; i > 0; ) {
4241                                 i--;
4242
4243                                 sb.Append (pd.ParameterDesc (count - i - 1));
4244                                 if (i != 0)
4245                                         sb.Append (", ");
4246                         }
4247                         
4248                         sb.Append (")");
4249                         return sb.ToString ();
4250                 }
4251
4252                 public static MethodGroupExpr MakeUnionSet (Expression mg1, Expression mg2, Location loc)
4253                 {
4254                         MemberInfo [] miset;
4255                         MethodGroupExpr union;
4256
4257                         if (mg1 == null){
4258                                 if (mg2 == null)
4259                                         return null;
4260                                 return (MethodGroupExpr) mg2;
4261                         } else {
4262                                 if (mg2 == null)
4263                                         return (MethodGroupExpr) mg1;
4264                         }
4265                         
4266                         MethodGroupExpr left_set = null, right_set = null;
4267                         int length1 = 0, length2 = 0;
4268                         
4269                         left_set = (MethodGroupExpr) mg1;
4270                         length1 = left_set.Methods.Length;
4271                         
4272                         right_set = (MethodGroupExpr) mg2;
4273                         length2 = right_set.Methods.Length;
4274                         
4275                         ArrayList common = new ArrayList ();
4276
4277                         foreach (MethodBase l in left_set.Methods){
4278                                 foreach (MethodBase r in right_set.Methods){
4279                                         if (l != r)
4280                                                 continue;
4281                                         common.Add (r);
4282                                         break;
4283                                 }
4284                         }
4285                         
4286                         miset = new MemberInfo [length1 + length2 - common.Count];
4287                         left_set.Methods.CopyTo (miset, 0);
4288                         
4289                         int k = length1;
4290
4291                         foreach (MemberInfo mi in right_set.Methods){
4292                                 if (!common.Contains (mi))
4293                                         miset [k++] = mi;
4294                         }
4295                         
4296                         union = new MethodGroupExpr (miset, loc);
4297                         
4298                         return union;
4299                 }
4300
4301                 /// <summary>
4302                 ///  Determines is the candidate method, if a params method, is applicable
4303                 ///  in its expanded form to the given set of arguments
4304                 /// </summary>
4305                 static bool IsParamsMethodApplicable (EmitContext ec, ArrayList arguments, MethodBase candidate)
4306                 {
4307                         int arg_count;
4308                         
4309                         if (arguments == null)
4310                                 arg_count = 0;
4311                         else
4312                                 arg_count = arguments.Count;
4313                         
4314                         ParameterData pd = GetParameterData (candidate);
4315                         
4316                         int pd_count = pd.Count;
4317
4318                         if (pd_count == 0)
4319                                 return false;
4320                         
4321                         if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
4322                                 return false;
4323                         
4324                         if (pd_count - 1 > arg_count)
4325                                 return false;
4326                         
4327                         if (pd_count == 1 && arg_count == 0)
4328                                 return true;
4329
4330                         //
4331                         // If we have come this far, the case which remains is when the number of parameters
4332                         // is less than or equal to the argument count.
4333                         //
4334                         for (int i = 0; i < pd_count - 1; ++i) {
4335
4336                                 Argument a = (Argument) arguments [i];
4337
4338                                 Parameter.Modifier a_mod = a.GetParameterModifier () &
4339                                         ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4340                                 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
4341                                         ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4342
4343                                 if (a_mod == p_mod) {
4344
4345                                         if (a_mod == Parameter.Modifier.NONE)
4346                                                 if (!Convert.ImplicitConversionExists (ec, a.Expr, pd.ParameterType (i)))
4347                                                         return false;
4348                                                                                 
4349                                         if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
4350                                                 Type pt = pd.ParameterType (i);
4351
4352                                                 if (!pt.IsByRef)
4353                                                         pt = TypeManager.GetReferenceType (pt);
4354                                                 
4355                                                 if (pt != a.Type)
4356                                                         return false;
4357                                         }
4358                                 } else
4359                                         return false;
4360                                 
4361                         }
4362
4363                         Type element_type = pd.ParameterType (pd_count - 1).GetElementType ();
4364
4365                         for (int i = pd_count - 1; i < arg_count; i++) {
4366                                 Argument a = (Argument) arguments [i];
4367                                 
4368                                 if (!Convert.ImplicitStandardConversionExists (a.Expr, element_type))
4369                                         return false;
4370                         }
4371                         
4372                         return true;
4373                 }
4374
4375                 /// <summary>
4376                 ///  Determines if the candidate method is applicable (section 14.4.2.1)
4377                 ///  to the given set of arguments
4378                 /// </summary>
4379                 static bool IsApplicable (EmitContext ec, ArrayList arguments, MethodBase candidate)
4380                 {
4381                         int arg_count;
4382
4383                         if (arguments == null)
4384                                 arg_count = 0;
4385                         else
4386                                 arg_count = arguments.Count;
4387
4388
4389                         ParameterData pd = GetParameterData (candidate);
4390
4391                         int pd_count = pd.Count;
4392
4393                         if (arg_count != pd.Count)
4394                                 return false;
4395                         
4396                         for (int i = arg_count; i > 0; ) {
4397                                 i--;
4398
4399                                 Argument a = (Argument) arguments [i];
4400
4401                                 Parameter.Modifier a_mod = a.GetParameterModifier () &
4402                                         ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4403                                 Parameter.Modifier p_mod = pd.ParameterModifier (i) &
4404                                         ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4405
4406
4407                                 if (a_mod == p_mod ||
4408                                     (a_mod == Parameter.Modifier.NONE && p_mod == Parameter.Modifier.PARAMS)) {
4409                                         if (a_mod == Parameter.Modifier.NONE)
4410                                                 if (!Convert.ImplicitConversionExists (ec, a.Expr, pd.ParameterType (i)))
4411                                                         return false;
4412                                         
4413                                         if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
4414                                                 Type pt = pd.ParameterType (i);
4415
4416                                                 if (!pt.IsByRef)
4417                                                         pt = TypeManager.GetReferenceType (pt);
4418
4419                                                 if (pt != a.Type)
4420                                                         return false;
4421                                         }
4422                                 } else
4423                                         return false;
4424                         }
4425
4426                         return true;
4427                 }
4428                 
4429                 
4430
4431                 /// <summary>
4432                 ///   Find the Applicable Function Members (7.4.2.1)
4433                 ///
4434                 ///   me: Method Group expression with the members to select.
4435                 ///       it might contain constructors or methods (or anything
4436                 ///       that maps to a method).
4437                 ///
4438                 ///   Arguments: ArrayList containing resolved Argument objects.
4439                 ///
4440                 ///   loc: The location if we want an error to be reported, or a Null
4441                 ///        location for "probing" purposes.
4442                 ///
4443                 ///   Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
4444                 ///            that is the best match of me on Arguments.
4445                 ///
4446                 /// </summary>
4447                 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
4448                                                           ArrayList Arguments, Location loc)
4449                 {
4450                         MethodBase method = null;
4451                         Type current_type = null;
4452                         int argument_count;
4453                         ArrayList candidates = new ArrayList ();
4454                         
4455
4456                         foreach (MethodBase candidate in me.Methods){
4457                                 int x;
4458
4459                                 // If we're going one level higher in the class hierarchy, abort if
4460                                 // we already found an applicable method.
4461                                 if (candidate.DeclaringType != current_type) {
4462                                         current_type = candidate.DeclaringType;
4463                                         if (method != null)
4464                                                 break;
4465                                 }
4466
4467                                 // Check if candidate is applicable (section 14.4.2.1)
4468                                 if (!IsApplicable (ec, Arguments, candidate))
4469                                         continue;
4470
4471                                 candidates.Add (candidate);
4472                                 x = BetterFunction (ec, Arguments, candidate, method, false, loc);
4473                                 
4474                                 if (x == 0)
4475                                         continue;
4476
4477                                 method = candidate;
4478                         }
4479
4480                         if (Arguments == null)
4481                                 argument_count = 0;
4482                         else
4483                                 argument_count = Arguments.Count;
4484                         
4485                         //
4486                         // Now we see if we can find params functions, applicable in their expanded form
4487                         // since if they were applicable in their normal form, they would have been selected
4488                         // above anyways
4489                         //
4490                         bool chose_params_expanded = false;
4491                         
4492                         if (method == null) {
4493                                 candidates = new ArrayList ();
4494                                 foreach (MethodBase candidate in me.Methods){
4495                                         if (!IsParamsMethodApplicable (ec, Arguments, candidate))
4496                                                 continue;
4497
4498                                         candidates.Add (candidate);
4499
4500                                         int x = BetterFunction (ec, Arguments, candidate, method, true, loc);
4501                                         if (x == 0)
4502                                                 continue;
4503
4504                                         method = candidate; 
4505                                         chose_params_expanded = true;
4506                                 }
4507                         }
4508
4509                         if (method == null) {
4510                                 //
4511                                 // Okay so we have failed to find anything so we
4512                                 // return by providing info about the closest match
4513                                 //
4514                                 for (int i = 0; i < me.Methods.Length; ++i) {
4515
4516                                         MethodBase c = (MethodBase) me.Methods [i];
4517                                         ParameterData pd = GetParameterData (c);
4518
4519                                         if (pd.Count != argument_count)
4520                                                 continue;
4521
4522                                         VerifyArgumentsCompat (ec, Arguments, argument_count, c, false,
4523                                                                null, loc);
4524                                 }
4525
4526                                 if (!Location.IsNull (loc)) {
4527                                         string report_name = me.Name;
4528                                         if (report_name == ".ctor")
4529                                                 report_name = me.DeclaringType.ToString ();
4530                                         
4531                                         Error_WrongNumArguments (loc, report_name, argument_count);
4532                                 }
4533                                 
4534                                 return null;
4535                         }
4536
4537                         //
4538                         // Now check that there are no ambiguities i.e the selected method
4539                         // should be better than all the others
4540                         //
4541
4542                         foreach (MethodBase candidate in candidates){
4543                                 if (candidate == method)
4544                                         continue;
4545
4546                                 //
4547                                 // If a normal method is applicable in the sense that it has the same
4548                                 // number of arguments, then the expanded params method is never applicable
4549                                 // so we debar the params method.
4550                                 //
4551                                 if (IsParamsMethodApplicable (ec, Arguments, candidate) &&
4552                                     IsApplicable (ec, Arguments, method))
4553                                         continue;
4554                                         
4555                                 int x = BetterFunction (ec, Arguments, method, candidate,
4556                                                         chose_params_expanded, loc);
4557
4558                                 if (x != 1) {
4559                                         Report.Error (
4560                                                 121, loc,
4561                                                 "Ambiguous call when selecting function due to implicit casts");
4562                                         return null;
4563                                 }
4564                         }
4565
4566                         //
4567                         // And now check if the arguments are all compatible, perform conversions
4568                         // if necessary etc. and return if everything is all right
4569                         //
4570
4571                         if (!VerifyArgumentsCompat (ec, Arguments, argument_count, method,
4572                                                    chose_params_expanded, null, loc))
4573                                 return null;
4574
4575                         return method;
4576                 }
4577
4578                 static void Error_WrongNumArguments (Location loc, String name, int arg_count)
4579                 {
4580                         Report.Error (1501, loc,
4581                                       "No overload for method `" + name + "' takes `" +
4582                                       arg_count + "' arguments");
4583                 }
4584
4585                 static void Error_InvalidArguments (Location loc, int idx, MethodBase method,
4586                                                     Type delegate_type, string arg_sig, string par_desc)
4587                 {
4588                         if (delegate_type == null) 
4589                                 Report.Error (1502, loc,
4590                                               "The best overloaded match for method '" +
4591                                               FullMethodDesc (method) +
4592                                               "' has some invalid arguments");
4593                         else
4594                                 Report.Error (1594, loc,
4595                                               "Delegate '" + delegate_type.ToString () +
4596                                               "' has some invalid arguments.");
4597                         Report.Error (1503, loc,
4598                                       String.Format ("Argument {0}: Cannot convert from '{1}' to '{2}'",
4599                                                      idx, arg_sig, par_desc));
4600                 }
4601                 
4602                 public static bool VerifyArgumentsCompat (EmitContext ec, ArrayList Arguments,
4603                                                           int argument_count,
4604                                                           MethodBase method, 
4605                                                           bool chose_params_expanded,
4606                                                           Type delegate_type,
4607                                                           Location loc)
4608                 {
4609                         ParameterData pd = GetParameterData (method);
4610                         int pd_count = pd.Count;
4611                         
4612                         for (int j = 0; j < argument_count; j++) {
4613                                 Argument a = (Argument) Arguments [j];
4614                                 Expression a_expr = a.Expr;
4615                                 Type parameter_type = pd.ParameterType (j);
4616                                 Parameter.Modifier pm = pd.ParameterModifier (j);
4617                                 
4618                                 if (pm == Parameter.Modifier.PARAMS){
4619                                         Parameter.Modifier am = a.GetParameterModifier ();
4620
4621                                         if ((pm & ~Parameter.Modifier.PARAMS) != a.GetParameterModifier ()) {
4622                                                 if (!Location.IsNull (loc))
4623                                                         Error_InvalidArguments (
4624                                                                 loc, j, method, delegate_type,
4625                                                                 Argument.FullDesc (a), pd.ParameterDesc (j));
4626                                                 return false;
4627                                         }
4628
4629                                         if (chose_params_expanded)
4630                                                 parameter_type = TypeManager.TypeToCoreType (parameter_type.GetElementType ());
4631                                 } else {
4632                                         //
4633                                         // Check modifiers
4634                                         //
4635                                         if (pd.ParameterModifier (j) != a.GetParameterModifier ()){
4636                                                 if (!Location.IsNull (loc))
4637                                                         Error_InvalidArguments (
4638                                                                 loc, j, method, delegate_type,
4639                                                                 Argument.FullDesc (a), pd.ParameterDesc (j));
4640                                                 return false;
4641                                         }
4642                                 }
4643
4644                                 //
4645                                 // Check Type
4646                                 //
4647                                 if (a.Type != parameter_type){
4648                                         Expression conv;
4649                                         
4650                                         conv = Convert.ImplicitConversion (ec, a_expr, parameter_type, loc);
4651
4652                                         if (conv == null) {
4653                                                 if (!Location.IsNull (loc)) 
4654                                                         Error_InvalidArguments (
4655                                                                 loc, j, method, delegate_type,
4656                                                                 Argument.FullDesc (a), pd.ParameterDesc (j));
4657                                                 return false;
4658                                         }
4659                                         
4660                                         //
4661                                         // Update the argument with the implicit conversion
4662                                         //
4663                                         if (a_expr != conv)
4664                                                 a.Expr = conv;
4665                                 }
4666
4667                                 Parameter.Modifier a_mod = a.GetParameterModifier () &
4668                                         ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4669                                 Parameter.Modifier p_mod = pd.ParameterModifier (j) &
4670                                         ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4671                                 
4672                                 if (a_mod != p_mod &&
4673                                     pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS) {
4674                                         if (!Location.IsNull (loc)) {
4675                                                 Console.WriteLine ("A:P: " + a.GetParameterModifier ());
4676                                                 Console.WriteLine ("PP:: " + pd.ParameterModifier (j));
4677                                                 Console.WriteLine ("PT:  " + parameter_type.IsByRef);
4678                                                 Report.Error (1502, loc,
4679                                                        "The best overloaded match for method '" + FullMethodDesc (method)+
4680                                                        "' has some invalid arguments");
4681                                                 Report.Error (1503, loc,
4682                                                        "Argument " + (j+1) +
4683                                                        ": Cannot convert from '" + Argument.FullDesc (a) 
4684                                                        + "' to '" + pd.ParameterDesc (j) + "'");
4685                                         }
4686                                         
4687                                         return false;
4688                                 }
4689                         }
4690
4691                         return true;
4692                 }
4693
4694                 public override Expression DoResolve (EmitContext ec)
4695                 {
4696                         //
4697                         // First, resolve the expression that is used to
4698                         // trigger the invocation
4699                         //
4700                         if (expr is BaseAccess)
4701                                 is_base = true;
4702
4703                         Expression old = expr;
4704                         
4705                         expr = expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
4706                         if (expr == null)
4707                                 return null;
4708
4709                         if (!(expr is MethodGroupExpr)) {
4710                                 Type expr_type = expr.Type;
4711
4712                                 if (expr_type != null){
4713                                         bool IsDelegate = TypeManager.IsDelegateType (expr_type);
4714                                         if (IsDelegate)
4715                                                 return (new DelegateInvocation (
4716                                                         this.expr, Arguments, loc)).Resolve (ec);
4717                                 }
4718                         }
4719
4720                         if (!(expr is MethodGroupExpr)){
4721                                 expr.Error_UnexpectedKind (ResolveFlags.MethodGroup);
4722                                 return null;
4723                         }
4724
4725                         //
4726                         // Next, evaluate all the expressions in the argument list
4727                         //
4728                         if (Arguments != null){
4729                                 foreach (Argument a in Arguments){
4730                                         if (!a.Resolve (ec, loc))
4731                                                 return null;
4732                                 }
4733                         }
4734
4735                         MethodGroupExpr mg = (MethodGroupExpr) expr;
4736                         method = OverloadResolve (ec, mg, Arguments, loc);
4737
4738                         if (method == null){
4739                                 Error (-6,
4740                                        "Could not find any applicable function for this argument list");
4741                                 return null;
4742                         }
4743
4744                         MethodInfo mi = method as MethodInfo;
4745                         if (mi != null) {
4746                                 type = TypeManager.TypeToCoreType (mi.ReturnType);
4747                                 if (!mi.IsStatic && !mg.IsExplicitImpl && (mg.InstanceExpression == null))
4748                                         SimpleName.Error_ObjectRefRequired (ec, loc, mi.Name);
4749                         }
4750
4751                         if (type.IsPointer){
4752                                 if (!ec.InUnsafe){
4753                                         UnsafeError (loc);
4754                                         return null;
4755                                 }
4756                         }
4757                         
4758                         //
4759                         // Only base will allow this invocation to happen.
4760                         //
4761                         if (is_base && method.IsAbstract){
4762                                 Report.Error (205, loc, "Cannot call an abstract base member: " +
4763                                               FullMethodDesc (method));
4764                                 return null;
4765                         }
4766
4767                         if ((method.Attributes & MethodAttributes.SpecialName) != 0){
4768                                 if (TypeManager.IsSpecialMethod (method))
4769                                         Report.Error (571, loc, method.Name + ": can not call operator or accessor");
4770                         }
4771                         
4772                         eclass = ExprClass.Value;
4773                         return this;
4774                 }
4775
4776                 // <summary>
4777                 //   Emits the list of arguments as an array
4778                 // </summary>
4779                 static void EmitParams (EmitContext ec, int idx, ArrayList arguments)
4780                 {
4781                         ILGenerator ig = ec.ig;
4782                         int count = arguments.Count - idx;
4783                         Argument a = (Argument) arguments [idx];
4784                         Type t = a.Expr.Type;
4785                         string array_type = t.FullName + "[]";
4786                         LocalBuilder array;
4787
4788                         array = ig.DeclareLocal (TypeManager.LookupType (array_type));
4789                         IntConstant.EmitInt (ig, count);
4790                         ig.Emit (OpCodes.Newarr, TypeManager.TypeToCoreType (t));
4791                         ig.Emit (OpCodes.Stloc, array);
4792
4793                         int top = arguments.Count;
4794                         for (int j = idx; j < top; j++){
4795                                 a = (Argument) arguments [j];
4796                                 
4797                                 ig.Emit (OpCodes.Ldloc, array);
4798                                 IntConstant.EmitInt (ig, j - idx);
4799
4800                                 bool is_stobj;
4801                                 OpCode op = ArrayAccess.GetStoreOpcode (t, out is_stobj);
4802                                 if (is_stobj)
4803                                         ig.Emit (OpCodes.Ldelema, t);
4804
4805                                 a.Emit (ec);
4806
4807                                 if (is_stobj)
4808                                         ig.Emit (OpCodes.Stobj, t);
4809                                 else
4810                                         ig.Emit (op);
4811                         }
4812                         ig.Emit (OpCodes.Ldloc, array);
4813                 }
4814                 
4815                 /// <summary>
4816                 ///   Emits a list of resolved Arguments that are in the arguments
4817                 ///   ArrayList.
4818                 /// 
4819                 ///   The MethodBase argument might be null if the
4820                 ///   emission of the arguments is known not to contain
4821                 ///   a `params' field (for example in constructors or other routines
4822                 ///   that keep their arguments in this structure)
4823                 /// </summary>
4824                 public static void EmitArguments (EmitContext ec, MethodBase mb, ArrayList arguments)
4825                 {
4826                         ParameterData pd;
4827                         if (mb != null)
4828                                 pd = GetParameterData (mb);
4829                         else
4830                                 pd = null;
4831
4832                         //
4833                         // If we are calling a params method with no arguments, special case it
4834                         //
4835                         if (arguments == null){
4836                                 if (pd != null && pd.Count > 0 &&
4837                                     pd.ParameterModifier (0) == Parameter.Modifier.PARAMS){
4838                                         ILGenerator ig = ec.ig;
4839
4840                                         IntConstant.EmitInt (ig, 0);
4841                                         ig.Emit (OpCodes.Newarr, pd.ParameterType (0).GetElementType ());
4842                                 }
4843
4844                                 return;
4845                         }
4846
4847                         int top = arguments.Count;
4848
4849                         for (int i = 0; i < top; i++){
4850                                 Argument a = (Argument) arguments [i];
4851
4852                                 if (pd != null){
4853                                         if (pd.ParameterModifier (i) == Parameter.Modifier.PARAMS){
4854                                                 //
4855                                                 // Special case if we are passing the same data as the
4856                                                 // params argument, do not put it in an array.
4857                                                 //
4858                                                 if (pd.ParameterType (i) == a.Type)
4859                                                         a.Emit (ec);
4860                                                 else
4861                                                         EmitParams (ec, i, arguments);
4862                                                 return;
4863                                         }
4864                                 }
4865                                             
4866                                 a.Emit (ec);
4867                         }
4868
4869                         if (pd != null && pd.Count > top &&
4870                             pd.ParameterModifier (top) == Parameter.Modifier.PARAMS){
4871                                 ILGenerator ig = ec.ig;
4872
4873                                 IntConstant.EmitInt (ig, 0);
4874                                 ig.Emit (OpCodes.Newarr, pd.ParameterType (top).GetElementType ());
4875                         }
4876                 }
4877
4878                 /// <remarks>
4879                 ///   is_base tells whether we want to force the use of the `call'
4880                 ///   opcode instead of using callvirt.  Call is required to call
4881                 ///   a specific method, while callvirt will always use the most
4882                 ///   recent method in the vtable.
4883                 ///
4884                 ///   is_static tells whether this is an invocation on a static method
4885                 ///
4886                 ///   instance_expr is an expression that represents the instance
4887                 ///   it must be non-null if is_static is false.
4888                 ///
4889                 ///   method is the method to invoke.
4890                 ///
4891                 ///   Arguments is the list of arguments to pass to the method or constructor.
4892                 /// </remarks>
4893                 public static void EmitCall (EmitContext ec, bool is_base,
4894                                              bool is_static, Expression instance_expr,
4895                                              MethodBase method, ArrayList Arguments, Location loc)
4896                 {
4897                         ILGenerator ig = ec.ig;
4898                         bool struct_call = false;
4899
4900                         Type decl_type = method.DeclaringType;
4901
4902                         if (!RootContext.StdLib) {
4903                                 // Replace any calls to the system's System.Array type with calls to
4904                                 // the newly created one.
4905                                 if (method == TypeManager.system_int_array_get_length)
4906                                         method = TypeManager.int_array_get_length;
4907                                 else if (method == TypeManager.system_int_array_get_rank)
4908                                         method = TypeManager.int_array_get_rank;
4909                                 else if (method == TypeManager.system_object_array_clone)
4910                                         method = TypeManager.object_array_clone;
4911                                 else if (method == TypeManager.system_int_array_get_length_int)
4912                                         method = TypeManager.int_array_get_length_int;
4913                                 else if (method == TypeManager.system_int_array_get_lower_bound_int)
4914                                         method = TypeManager.int_array_get_lower_bound_int;
4915                                 else if (method == TypeManager.system_int_array_get_upper_bound_int)
4916                                         method = TypeManager.int_array_get_upper_bound_int;
4917                                 else if (method == TypeManager.system_void_array_copyto_array_int)
4918                                         method = TypeManager.void_array_copyto_array_int;
4919                         }
4920
4921                         //
4922                         // This checks the `ConditionalAttribute' on the method, and the
4923                         // ObsoleteAttribute
4924                         //
4925                         TypeManager.MethodFlags flags = TypeManager.GetMethodFlags (method, loc);
4926                         if ((flags & TypeManager.MethodFlags.IsObsoleteError) != 0)
4927                                 return;
4928                         if ((flags & TypeManager.MethodFlags.ShouldIgnore) != 0)
4929                                 return;
4930                         
4931                         if (!is_static){
4932                                 if (decl_type.IsValueType)
4933                                         struct_call = true;
4934                                 //
4935                                 // If this is ourselves, push "this"
4936                                 //
4937                                 if (instance_expr == null){
4938                                         ig.Emit (OpCodes.Ldarg_0);
4939                                 } else {
4940                                         //
4941                                         // Push the instance expression
4942                                         //
4943                                         if (instance_expr.Type.IsValueType){
4944                                                 //
4945                                                 // Special case: calls to a function declared in a 
4946                                                 // reference-type with a value-type argument need
4947                                                 // to have their value boxed.  
4948
4949                                                 struct_call = true;
4950                                                 if (decl_type.IsValueType){
4951                                                         //
4952                                                         // If the expression implements IMemoryLocation, then
4953                                                         // we can optimize and use AddressOf on the
4954                                                         // return.
4955                                                         //
4956                                                         // If not we have to use some temporary storage for
4957                                                         // it.
4958                                                         if (instance_expr is IMemoryLocation){
4959                                                                 ((IMemoryLocation)instance_expr).
4960                                                                         AddressOf (ec, AddressOp.LoadStore);
4961                                                         }
4962                                                         else {
4963                                                                 Type t = instance_expr.Type;
4964                                                                 
4965                                                                 instance_expr.Emit (ec);
4966                                                                 LocalBuilder temp = ig.DeclareLocal (t);
4967                                                                 ig.Emit (OpCodes.Stloc, temp);
4968                                                                 ig.Emit (OpCodes.Ldloca, temp);
4969                                                         }
4970                                                 } else {
4971                                                         instance_expr.Emit (ec);
4972                                                         ig.Emit (OpCodes.Box, instance_expr.Type);
4973                                                 } 
4974                                         } else
4975                                                 instance_expr.Emit (ec);
4976                                 }
4977                         }
4978
4979                         EmitArguments (ec, method, Arguments);
4980
4981                         if (is_static || struct_call || is_base){
4982                                 if (method is MethodInfo) {
4983                                         ig.Emit (OpCodes.Call, (MethodInfo) method);
4984                                 } else
4985                                         ig.Emit (OpCodes.Call, (ConstructorInfo) method);
4986                         } else {
4987                                 if (method is MethodInfo)
4988                                         ig.Emit (OpCodes.Callvirt, (MethodInfo) method);
4989                                 else
4990                                         ig.Emit (OpCodes.Callvirt, (ConstructorInfo) method);
4991                         }
4992                 }
4993                 
4994                 public override void Emit (EmitContext ec)
4995                 {
4996                         MethodGroupExpr mg = (MethodGroupExpr) this.expr;
4997
4998                         EmitCall (ec, is_base, method.IsStatic, mg.InstanceExpression, method, Arguments, loc);
4999                 }
5000                 
5001                 public override void EmitStatement (EmitContext ec)
5002                 {
5003                         Emit (ec);
5004
5005                         // 
5006                         // Pop the return value if there is one
5007                         //
5008                         if (method is MethodInfo){
5009                                 Type ret = ((MethodInfo)method).ReturnType;
5010                                 if (TypeManager.TypeToCoreType (ret) != TypeManager.void_type)
5011                                         ec.ig.Emit (OpCodes.Pop);
5012                         }
5013                 }
5014         }
5015
5016         //
5017         // This class is used to "disable" the code generation for the
5018         // temporary variable when initializing value types.
5019         //
5020         class EmptyAddressOf : EmptyExpression, IMemoryLocation {
5021                 public void AddressOf (EmitContext ec, AddressOp Mode)
5022                 {
5023                         // nothing
5024                 }
5025         }
5026         
5027         /// <summary>
5028         ///    Implements the new expression 
5029         /// </summary>
5030         public class New : ExpressionStatement, IMemoryLocation {
5031                 public readonly ArrayList Arguments;
5032                 public readonly Expression RequestedType;
5033
5034                 MethodBase method = null;
5035
5036                 //
5037                 // If set, the new expression is for a value_target, and
5038                 // we will not leave anything on the stack.
5039                 //
5040                 Expression value_target;
5041                 bool value_target_set = false;
5042                 
5043                 public New (Expression requested_type, ArrayList arguments, Location l)
5044                 {
5045                         RequestedType = requested_type;
5046                         Arguments = arguments;
5047                         loc = l;
5048                 }
5049
5050                 public bool SetValueTypeVariable (Expression value)
5051                 {
5052                         value_target = value;
5053                         value_target_set = true;
5054                         if (!(value_target is IMemoryLocation)){
5055                                 Error_UnexpectedKind ("variable");
5056                                 return false;
5057                         }
5058                         return true;
5059                 }
5060
5061                 //
5062                 // This function is used to disable the following code sequence for
5063                 // value type initialization:
5064                 //
5065                 // AddressOf (temporary)
5066                 // Construct/Init
5067                 // LoadTemporary
5068                 //
5069                 // Instead the provide will have provided us with the address on the
5070                 // stack to store the results.
5071                 //
5072                 static Expression MyEmptyExpression;
5073                 
5074                 public void DisableTemporaryValueType ()
5075                 {
5076                         if (MyEmptyExpression == null)
5077                                 MyEmptyExpression = new EmptyAddressOf ();
5078
5079                         //
5080                         // To enable this, look into:
5081                         // test-34 and test-89 and self bootstrapping.
5082                         //
5083                         // For instance, we can avoid a copy by using `newobj'
5084                         // instead of Call + Push-temp on value types.
5085 //                      value_target = MyEmptyExpression;
5086                 }
5087
5088                 public override Expression DoResolve (EmitContext ec)
5089                 {
5090                         //
5091                         // The New DoResolve might be called twice when initializing field
5092                         // expressions (see EmitFieldInitializers, the call to
5093                         // GetInitializerExpression will perform a resolve on the expression,
5094                         // and later the assign will trigger another resolution
5095                         //
5096                         // This leads to bugs (#37014)
5097                         //
5098                         if (type != null)
5099                                 return this;
5100                         
5101                         type = ec.DeclSpace.ResolveType (RequestedType, false, loc);
5102                         
5103                         if (type == null)
5104                                 return null;
5105                         
5106                         bool IsDelegate = TypeManager.IsDelegateType (type);
5107                         
5108                         if (IsDelegate)
5109                                 return (new NewDelegate (type, Arguments, loc)).Resolve (ec);
5110
5111                         if (type.IsInterface || type.IsAbstract){
5112                                 Error (144, "It is not possible to create instances of interfaces or abstract classes");
5113                                 return null;
5114                         }
5115                         
5116                         bool is_struct = type.IsValueType;
5117                         eclass = ExprClass.Value;
5118
5119                         //
5120                         // SRE returns a match for .ctor () on structs (the object constructor), 
5121                         // so we have to manually ignore it.
5122                         //
5123                         if (is_struct && Arguments == null)
5124                                 return this;
5125                         
5126                         Expression ml;
5127                         ml = MemberLookupFinal (ec, null, type, ".ctor",
5128                                                 MemberTypes.Constructor,
5129                                                 AllBindingFlags | BindingFlags.DeclaredOnly, loc);
5130
5131                         if (ml == null)
5132                                 return null;
5133                         
5134                         if (! (ml is MethodGroupExpr)){
5135                                 if (!is_struct){
5136                                         ml.Error_UnexpectedKind ("method group");
5137                                         return null;
5138                                 }
5139                         }
5140
5141                         if (ml != null) {
5142                                 if (Arguments != null){
5143                                         foreach (Argument a in Arguments){
5144                                                 if (!a.Resolve (ec, loc))
5145                                                         return null;
5146                                         }
5147                                 }
5148
5149                                 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml, Arguments, loc);
5150                                 
5151                         }
5152
5153                         if (method == null) { 
5154                                 if (!is_struct || Arguments.Count > 0) {
5155                                         Error (1501, String.Format (
5156                                             "New invocation: Can not find a constructor in `{0}' for this argument list",
5157                                             TypeManager.CSharpName (type)));
5158                                         return null;
5159                                 }
5160                         }
5161
5162                         return this;
5163                 }
5164
5165                 //
5166                 // This DoEmit can be invoked in two contexts:
5167                 //    * As a mechanism that will leave a value on the stack (new object)
5168                 //    * As one that wont (init struct)
5169                 //
5170                 // You can control whether a value is required on the stack by passing
5171                 // need_value_on_stack.  The code *might* leave a value on the stack
5172                 // so it must be popped manually
5173                 //
5174                 // If we are dealing with a ValueType, we have a few
5175                 // situations to deal with:
5176                 //
5177                 //    * The target is a ValueType, and we have been provided
5178                 //      the instance (this is easy, we are being assigned).
5179                 //
5180                 //    * The target of New is being passed as an argument,
5181                 //      to a boxing operation or a function that takes a
5182                 //      ValueType.
5183                 //
5184                 //      In this case, we need to create a temporary variable
5185                 //      that is the argument of New.
5186                 //
5187                 // Returns whether a value is left on the stack
5188                 //
5189                 bool DoEmit (EmitContext ec, bool need_value_on_stack)
5190                 {
5191                         bool is_value_type = type.IsValueType;
5192                         ILGenerator ig = ec.ig;
5193
5194                         if (is_value_type){
5195                                 IMemoryLocation ml;
5196
5197                                 // Allow DoEmit() to be called multiple times.
5198                                 // We need to create a new LocalTemporary each time since
5199                                 // you can't share LocalBuilders among ILGeneators.
5200                                 if (!value_target_set)
5201                                         value_target = new LocalTemporary (ec, type);
5202
5203                                 ml = (IMemoryLocation) value_target;
5204                                 ml.AddressOf (ec, AddressOp.Store);
5205                         }
5206
5207                         if (method != null)
5208                                 Invocation.EmitArguments (ec, method, Arguments);
5209
5210                         if (is_value_type){
5211                                 if (method == null)
5212                                         ig.Emit (OpCodes.Initobj, type);
5213                                 else 
5214                                         ig.Emit (OpCodes.Call, (ConstructorInfo) method);
5215                                 if (need_value_on_stack){
5216                                         value_target.Emit (ec);
5217                                         return true;
5218                                 }
5219                                 return false;
5220                         } else {
5221                                 ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
5222                                 return true;
5223                         }
5224                 }
5225
5226                 public override void Emit (EmitContext ec)
5227                 {
5228                         DoEmit (ec, true);
5229                 }
5230                 
5231                 public override void EmitStatement (EmitContext ec)
5232                 {
5233                         if (DoEmit (ec, false))
5234                                 ec.ig.Emit (OpCodes.Pop);
5235                 }
5236
5237                 public void AddressOf (EmitContext ec, AddressOp Mode)
5238                 {
5239                         if (!type.IsValueType){
5240                                 //
5241                                 // We throw an exception.  So far, I believe we only need to support
5242                                 // value types:
5243                                 // foreach (int j in new StructType ())
5244                                 // see bug 42390
5245                                 //
5246                                 throw new Exception ("AddressOf should not be used for classes");
5247                         }
5248
5249                         if (!value_target_set)
5250                                 value_target = new LocalTemporary (ec, type);
5251                                         
5252                         IMemoryLocation ml = (IMemoryLocation) value_target;
5253                         ml.AddressOf (ec, AddressOp.Store);
5254                         if (method != null)
5255                                 Invocation.EmitArguments (ec, method, Arguments);
5256
5257                         if (method == null)
5258                                 ec.ig.Emit (OpCodes.Initobj, type);
5259                         else 
5260                                 ec.ig.Emit (OpCodes.Call, (ConstructorInfo) method);
5261                         
5262                         ((IMemoryLocation) value_target).AddressOf (ec, Mode);
5263                 }
5264         }
5265
5266         /// <summary>
5267         ///   14.5.10.2: Represents an array creation expression.
5268         /// </summary>
5269         ///
5270         /// <remarks>
5271         ///   There are two possible scenarios here: one is an array creation
5272         ///   expression that specifies the dimensions and optionally the
5273         ///   initialization data and the other which does not need dimensions
5274         ///   specified but where initialization data is mandatory.
5275         /// </remarks>
5276         public class ArrayCreation : ExpressionStatement {
5277                 Expression requested_base_type;
5278                 ArrayList initializers;
5279
5280                 //
5281                 // The list of Argument types.
5282                 // This is used to construct the `newarray' or constructor signature
5283                 //
5284                 ArrayList arguments;
5285
5286                 //
5287                 // Method used to create the array object.
5288                 //
5289                 MethodBase new_method = null;
5290                 
5291                 Type array_element_type;
5292                 Type underlying_type;
5293                 bool is_one_dimensional = false;
5294                 bool is_builtin_type = false;
5295                 bool expect_initializers = false;
5296                 int num_arguments = 0;
5297                 int dimensions = 0;
5298                 string rank;
5299
5300                 ArrayList array_data;
5301
5302                 Hashtable bounds;
5303
5304                 //
5305                 // The number of array initializers that we can handle
5306                 // via the InitializeArray method - through EmitStaticInitializers
5307                 //
5308                 int num_automatic_initializers;
5309
5310                 const int max_automatic_initializers = 6;
5311                 
5312                 public ArrayCreation (Expression requested_base_type, ArrayList exprs, string rank, ArrayList initializers, Location l)
5313                 {
5314                         this.requested_base_type = requested_base_type;
5315                         this.initializers = initializers;
5316                         this.rank = rank;
5317                         loc = l;
5318
5319                         arguments = new ArrayList ();
5320
5321                         foreach (Expression e in exprs) {
5322                                 arguments.Add (new Argument (e, Argument.AType.Expression));
5323                                 num_arguments++;
5324                         }
5325                 }
5326
5327                 public ArrayCreation (Expression requested_base_type, string rank, ArrayList initializers, Location l)
5328                 {
5329                         this.requested_base_type = requested_base_type;
5330                         this.initializers = initializers;
5331                         this.rank = rank;
5332                         loc = l;
5333
5334                         //this.rank = rank.Substring (0, rank.LastIndexOf ("["));
5335                         //
5336                         //string tmp = rank.Substring (rank.LastIndexOf ("["));
5337                         //
5338                         //dimensions = tmp.Length - 1;
5339                         expect_initializers = true;
5340                 }
5341
5342                 public Expression FormArrayType (Expression base_type, int idx_count, string rank)
5343                 {
5344                         StringBuilder sb = new StringBuilder (rank);
5345                         
5346                         sb.Append ("[");
5347                         for (int i = 1; i < idx_count; i++)
5348                                 sb.Append (",");
5349                         
5350                         sb.Append ("]");
5351
5352                         return new ComposedCast (base_type, sb.ToString (), loc);
5353                 }
5354
5355                 void Error_IncorrectArrayInitializer ()
5356                 {
5357                         Error (178, "Incorrectly structured array initializer");
5358                 }
5359                 
5360                 public bool CheckIndices (EmitContext ec, ArrayList probe, int idx, bool specified_dims)
5361                 {
5362                         if (specified_dims) { 
5363                                 Argument a = (Argument) arguments [idx];
5364                                 
5365                                 if (!a.Resolve (ec, loc))
5366                                         return false;
5367                                 
5368                                 if (!(a.Expr is Constant)) {
5369                                         Error (150, "A constant value is expected");
5370                                         return false;
5371                                 }
5372                                 
5373                                 int value = (int) ((Constant) a.Expr).GetValue ();
5374                                 
5375                                 if (value != probe.Count) {
5376                                         Error_IncorrectArrayInitializer ();
5377                                         return false;
5378                                 }
5379                                 
5380                                 bounds [idx] = value;
5381                         }
5382
5383                         int child_bounds = -1;
5384                         foreach (object o in probe) {
5385                                 if (o is ArrayList) {
5386                                         int current_bounds = ((ArrayList) o).Count;
5387                                         
5388                                         if (child_bounds == -1) 
5389                                                 child_bounds = current_bounds;
5390
5391                                         else if (child_bounds != current_bounds){
5392                                                 Error_IncorrectArrayInitializer ();
5393                                                 return false;
5394                                         }
5395                                         if (specified_dims && (idx + 1 >= arguments.Count)){
5396                                                 Error (623, "Array initializers can only be used in a variable or field initializer, try using the new expression");
5397                                                 return false;
5398                                         }
5399                                         
5400                                         bool ret = CheckIndices (ec, (ArrayList) o, idx + 1, specified_dims);
5401                                         if (!ret)
5402                                                 return false;
5403                                 } else {
5404                                         if (child_bounds != -1){
5405                                                 Error_IncorrectArrayInitializer ();
5406                                                 return false;
5407                                         }
5408                                         
5409                                         Expression tmp = (Expression) o;
5410                                         tmp = tmp.Resolve (ec);
5411                                         if (tmp == null)
5412                                                 continue;
5413
5414                                         // Console.WriteLine ("I got: " + tmp);
5415                                         // Handle initialization from vars, fields etc.
5416
5417                                         Expression conv = Convert.ImplicitConversionRequired (
5418                                                 ec, tmp, underlying_type, loc);
5419                                         
5420                                         if (conv == null) 
5421                                                 return false;
5422
5423                                         if (conv is StringConstant)
5424                                                 array_data.Add (conv);
5425                                         else if (conv is Constant) {
5426                                                 array_data.Add (conv);
5427                                                 num_automatic_initializers++;
5428                                         } else
5429                                                 array_data.Add (conv);
5430                                 }
5431                         }
5432
5433                         return true;
5434                 }
5435                 
5436                 public void UpdateIndices (EmitContext ec)
5437                 {
5438                         int i = 0;
5439                         for (ArrayList probe = initializers; probe != null;) {
5440                                 if (probe.Count > 0 && probe [0] is ArrayList) {
5441                                         Expression e = new IntConstant (probe.Count);
5442                                         arguments.Add (new Argument (e, Argument.AType.Expression));
5443
5444                                         bounds [i++] =  probe.Count;
5445                                         
5446                                         probe = (ArrayList) probe [0];
5447                                         
5448                                 } else {
5449                                         Expression e = new IntConstant (probe.Count);
5450                                         arguments.Add (new Argument (e, Argument.AType.Expression));
5451
5452                                         bounds [i++] = probe.Count;
5453                                         probe = null;
5454                                 }
5455                         }
5456
5457                 }
5458                 
5459                 public bool ValidateInitializers (EmitContext ec, Type array_type)
5460                 {
5461                         if (initializers == null) {
5462                                 if (expect_initializers)
5463                                         return false;
5464                                 else
5465                                         return true;
5466                         }
5467                         
5468                         if (underlying_type == null)
5469                                 return false;
5470                         
5471                         //
5472                         // We use this to store all the date values in the order in which we
5473                         // will need to store them in the byte blob later
5474                         //
5475                         array_data = new ArrayList ();
5476                         bounds = new Hashtable ();
5477                         
5478                         bool ret;
5479
5480                         if (arguments != null) {
5481                                 ret = CheckIndices (ec, initializers, 0, true);
5482                                 return ret;
5483                         } else {
5484                                 arguments = new ArrayList ();
5485
5486                                 ret = CheckIndices (ec, initializers, 0, false);
5487                                 
5488                                 if (!ret)
5489                                         return false;
5490                                 
5491                                 UpdateIndices (ec);
5492                                 
5493                                 if (arguments.Count != dimensions) {
5494                                         Error_IncorrectArrayInitializer ();
5495                                         return false;
5496                                 }
5497
5498                                 return ret;
5499                         }
5500                 }
5501
5502                 void Error_NegativeArrayIndex ()
5503                 {
5504                         Error (284, "Can not create array with a negative size");
5505                 }
5506                 
5507                 //
5508                 // Converts `source' to an int, uint, long or ulong.
5509                 //
5510                 Expression ExpressionToArrayArgument (EmitContext ec, Expression source)
5511                 {
5512                         Expression target;
5513                         
5514                         bool old_checked = ec.CheckState;
5515                         ec.CheckState = true;
5516                         
5517                         target = Convert.ImplicitConversion (ec, source, TypeManager.int32_type, loc);
5518                         if (target == null){
5519                                 target = Convert.ImplicitConversion (ec, source, TypeManager.uint32_type, loc);
5520                                 if (target == null){
5521                                         target = Convert.ImplicitConversion (ec, source, TypeManager.int64_type, loc);
5522                                         if (target == null){
5523                                                 target = Convert.ImplicitConversion (ec, source, TypeManager.uint64_type, loc);
5524                                                 if (target == null)
5525                                                         Convert.Error_CannotImplicitConversion (loc, source.Type, TypeManager.int32_type);
5526                                         }
5527                                 }
5528                         } 
5529                         ec.CheckState = old_checked;
5530
5531                         //
5532                         // Only positive constants are allowed at compile time
5533                         //
5534                         if (target is Constant){
5535                                 if (target is IntConstant){
5536                                         if (((IntConstant) target).Value < 0){
5537                                                 Error_NegativeArrayIndex ();
5538                                                 return null;
5539                                         }
5540                                 }
5541
5542                                 if (target is LongConstant){
5543                                         if (((LongConstant) target).Value < 0){
5544                                                 Error_NegativeArrayIndex ();
5545                                                 return null;
5546                                         }
5547                                 }
5548                                 
5549                         }
5550
5551                         return target;
5552                 }
5553
5554                 //
5555                 // Creates the type of the array
5556                 //
5557                 bool LookupType (EmitContext ec)
5558                 {
5559                         StringBuilder array_qualifier = new StringBuilder (rank);
5560
5561                         //
5562                         // `In the first form allocates an array instace of the type that results
5563                         // from deleting each of the individual expression from the expression list'
5564                         //
5565                         if (num_arguments > 0) {
5566                                 array_qualifier.Append ("[");
5567                                 for (int i = num_arguments-1; i > 0; i--)
5568                                         array_qualifier.Append (",");
5569                                 array_qualifier.Append ("]");                           
5570                         }
5571
5572                         //
5573                         // Lookup the type
5574                         //
5575                         Expression array_type_expr;
5576                         array_type_expr = new ComposedCast (requested_base_type, array_qualifier.ToString (), loc);
5577                         type = ec.DeclSpace.ResolveType (array_type_expr, false, loc);
5578
5579                         if (type == null)
5580                                 return false;
5581
5582                         underlying_type = type;
5583                         if (underlying_type.IsArray)
5584                                 underlying_type = TypeManager.TypeToCoreType (underlying_type.GetElementType ());
5585                         dimensions = type.GetArrayRank ();
5586
5587                         return true;
5588                 }
5589                 
5590                 public override Expression DoResolve (EmitContext ec)
5591                 {
5592                         int arg_count;
5593
5594                         if (!LookupType (ec))
5595                                 return null;
5596                         
5597                         //
5598                         // First step is to validate the initializers and fill
5599                         // in any missing bits
5600                         //
5601                         if (!ValidateInitializers (ec, type))
5602                                 return null;
5603
5604                         if (arguments == null)
5605                                 arg_count = 0;
5606                         else {
5607                                 arg_count = arguments.Count;
5608                                 foreach (Argument a in arguments){
5609                                         if (!a.Resolve (ec, loc))
5610                                                 return null;
5611
5612                                         Expression real_arg = ExpressionToArrayArgument (ec, a.Expr, loc);
5613                                         if (real_arg == null)
5614                                                 return null;
5615
5616                                         a.Expr = real_arg;
5617                                 }
5618                         }
5619                         
5620                         array_element_type = TypeManager.TypeToCoreType (type.GetElementType ());
5621
5622                         if (arg_count == 1) {
5623                                 is_one_dimensional = true;
5624                                 eclass = ExprClass.Value;
5625                                 return this;
5626                         }
5627
5628                         is_builtin_type = TypeManager.IsBuiltinType (type);
5629
5630                         if (is_builtin_type) {
5631                                 Expression ml;
5632                                 
5633                                 ml = MemberLookup (ec, type, ".ctor", MemberTypes.Constructor,
5634                                                    AllBindingFlags, loc);
5635                                 
5636                                 if (!(ml is MethodGroupExpr)) {
5637                                         ml.Error_UnexpectedKind ("method group");
5638                                         return null;
5639                                 }
5640                                 
5641                                 if (ml == null) {
5642                                         Error (-6, "New invocation: Can not find a constructor for " +
5643                                                       "this argument list");
5644                                         return null;
5645                                 }
5646                                 
5647                                 new_method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml, arguments, loc);
5648
5649                                 if (new_method == null) {
5650                                         Error (-6, "New invocation: Can not find a constructor for " +
5651                                                       "this argument list");
5652                                         return null;
5653                                 }
5654                                 
5655                                 eclass = ExprClass.Value;
5656                                 return this;
5657                         } else {
5658                                 ModuleBuilder mb = CodeGen.ModuleBuilder;
5659                                 ArrayList args = new ArrayList ();
5660                                 
5661                                 if (arguments != null) {
5662                                         for (int i = 0; i < arg_count; i++)
5663                                                 args.Add (TypeManager.int32_type);
5664                                 }
5665                                 
5666                                 Type [] arg_types = null;
5667
5668                                 if (args.Count > 0)
5669                                         arg_types = new Type [args.Count];
5670                                 
5671                                 args.CopyTo (arg_types, 0);
5672                                 
5673                                 new_method = mb.GetArrayMethod (type, ".ctor", CallingConventions.HasThis, null,
5674                                                             arg_types);
5675
5676                                 if (new_method == null) {
5677                                         Error (-6, "New invocation: Can not find a constructor for " +
5678                                                       "this argument list");
5679                                         return null;
5680                                 }
5681                                 
5682                                 eclass = ExprClass.Value;
5683                                 return this;
5684                         }
5685                 }
5686
5687                 public static byte [] MakeByteBlob (ArrayList array_data, Type underlying_type, Location loc)
5688                 {
5689                         int factor;
5690                         byte [] data;
5691                         byte [] element;
5692                         int count = array_data.Count;
5693
5694                         if (underlying_type.IsEnum)
5695                                 underlying_type = TypeManager.EnumToUnderlying (underlying_type);
5696                         
5697                         factor = GetTypeSize (underlying_type);
5698                         if (factor == 0)
5699                                 throw new Exception ("unrecognized type in MakeByteBlob: " + underlying_type);
5700
5701                         data = new byte [(count * factor + 4) & ~3];
5702                         int idx = 0;
5703                         
5704                         for (int i = 0; i < count; ++i) {
5705                                 object v = array_data [i];
5706
5707                                 if (v is EnumConstant)
5708                                         v = ((EnumConstant) v).Child;
5709                                 
5710                                 if (v is Constant && !(v is StringConstant))
5711                                         v = ((Constant) v).GetValue ();
5712                                 else {
5713                                         idx += factor;
5714                                         continue;
5715                                 }
5716                                 
5717                                 if (underlying_type == TypeManager.int64_type){
5718                                         if (!(v is Expression)){
5719                                                 long val = (long) v;
5720                                                 
5721                                                 for (int j = 0; j < factor; ++j) {
5722                                                         data [idx + j] = (byte) (val & 0xFF);
5723                                                         val = (val >> 8);
5724                                                 }
5725                                         }
5726                                 } else if (underlying_type == TypeManager.uint64_type){
5727                                         if (!(v is Expression)){
5728                                                 ulong val = (ulong) v;
5729
5730                                                 for (int j = 0; j < factor; ++j) {
5731                                                         data [idx + j] = (byte) (val & 0xFF);
5732                                                         val = (val >> 8);
5733                                                 }
5734                                         }
5735                                 } else if (underlying_type == TypeManager.float_type) {
5736                                         if (!(v is Expression)){
5737                                                 element = BitConverter.GetBytes ((float) v);
5738                                                         
5739                                                 for (int j = 0; j < factor; ++j)
5740                                                         data [idx + j] = element [j];
5741                                         }
5742                                 } else if (underlying_type == TypeManager.double_type) {
5743                                         if (!(v is Expression)){
5744                                                 element = BitConverter.GetBytes ((double) v);
5745
5746                                                 for (int j = 0; j < factor; ++j)
5747                                                         data [idx + j] = element [j];
5748                                         }
5749                                 } else if (underlying_type == TypeManager.char_type){
5750                                         if (!(v is Expression)){
5751                                                 int val = (int) ((char) v);
5752                                                 
5753                                                 data [idx] = (byte) (val & 0xff);
5754                                                 data [idx+1] = (byte) (val >> 8);
5755                                         }
5756                                 } else if (underlying_type == TypeManager.short_type){
5757                                         if (!(v is Expression)){
5758                                                 int val = (int) ((short) v);
5759                                         
5760                                                 data [idx] = (byte) (val & 0xff);
5761                                                 data [idx+1] = (byte) (val >> 8);
5762                                         }
5763                                 } else if (underlying_type == TypeManager.ushort_type){
5764                                         if (!(v is Expression)){
5765                                                 int val = (int) ((ushort) v);
5766                                         
5767                                                 data [idx] = (byte) (val & 0xff);
5768                                                 data [idx+1] = (byte) (val >> 8);
5769                                         }
5770                                 } else if (underlying_type == TypeManager.int32_type) {
5771                                         if (!(v is Expression)){
5772                                                 int val = (int) v;
5773                                         
5774                                                 data [idx]   = (byte) (val & 0xff);
5775                                                 data [idx+1] = (byte) ((val >> 8) & 0xff);
5776                                                 data [idx+2] = (byte) ((val >> 16) & 0xff);
5777                                                 data [idx+3] = (byte) (val >> 24);
5778                                         }
5779                                 } else if (underlying_type == TypeManager.uint32_type) {
5780                                         if (!(v is Expression)){
5781                                                 uint val = (uint) v;
5782                                         
5783                                                 data [idx]   = (byte) (val & 0xff);
5784                                                 data [idx+1] = (byte) ((val >> 8) & 0xff);
5785                                                 data [idx+2] = (byte) ((val >> 16) & 0xff);
5786                                                 data [idx+3] = (byte) (val >> 24);
5787                                         }
5788                                 } else if (underlying_type == TypeManager.sbyte_type) {
5789                                         if (!(v is Expression)){
5790                                                 sbyte val = (sbyte) v;
5791                                                 data [idx] = (byte) val;
5792                                         }
5793                                 } else if (underlying_type == TypeManager.byte_type) {
5794                                         if (!(v is Expression)){
5795                                                 byte val = (byte) v;
5796                                                 data [idx] = (byte) val;
5797                                         }
5798                                 } else if (underlying_type == TypeManager.bool_type) {
5799                                         if (!(v is Expression)){
5800                                                 bool val = (bool) v;
5801                                                 data [idx] = (byte) (val ? 1 : 0);
5802                                         }
5803                                 } else if (underlying_type == TypeManager.decimal_type){
5804                                         if (!(v is Expression)){
5805                                                 int [] bits = Decimal.GetBits ((decimal) v);
5806                                                 int p = idx;
5807
5808                                                 // FIXME: For some reason, this doesn't work on the MS runtime.
5809                                                 int [] nbits = new int [4];
5810                                                 nbits [0] = bits [3];
5811                                                 nbits [1] = bits [2];
5812                                                 nbits [2] = bits [0];
5813                                                 nbits [3] = bits [1];
5814                                                 
5815                                                 for (int j = 0; j < 4; j++){
5816                                                         data [p++] = (byte) (nbits [j] & 0xff);
5817                                                         data [p++] = (byte) ((nbits [j] >> 8) & 0xff);
5818                                                         data [p++] = (byte) ((nbits [j] >> 16) & 0xff);
5819                                                         data [p++] = (byte) (nbits [j] >> 24);
5820                                                 }
5821                                         }
5822                                 } else
5823                                         throw new Exception ("Unrecognized type in MakeByteBlob: " + underlying_type);
5824
5825                                 idx += factor;
5826                         }
5827
5828                         return data;
5829                 }
5830
5831                 //
5832                 // Emits the initializers for the array
5833                 //
5834                 void EmitStaticInitializers (EmitContext ec, bool is_expression)
5835                 {
5836                         //
5837                         // First, the static data
5838                         //
5839                         FieldBuilder fb;
5840                         ILGenerator ig = ec.ig;
5841                         
5842                         byte [] data = MakeByteBlob (array_data, underlying_type, loc);
5843
5844                         fb = RootContext.MakeStaticData (data);
5845
5846                         if (is_expression)
5847                                 ig.Emit (OpCodes.Dup);
5848                         ig.Emit (OpCodes.Ldtoken, fb);
5849                         ig.Emit (OpCodes.Call,
5850                                  TypeManager.void_initializearray_array_fieldhandle);
5851                 }
5852                 
5853                 //
5854                 // Emits pieces of the array that can not be computed at compile
5855                 // time (variables and string locations).
5856                 //
5857                 // This always expect the top value on the stack to be the array
5858                 //
5859                 void EmitDynamicInitializers (EmitContext ec, bool is_expression)
5860                 {
5861                         ILGenerator ig = ec.ig;
5862                         int dims = bounds.Count;
5863                         int [] current_pos = new int [dims];
5864                         int top = array_data.Count;
5865                         LocalBuilder temp = ig.DeclareLocal (type);
5866
5867                         ig.Emit (OpCodes.Stloc, temp);
5868
5869                         MethodInfo set = null;
5870
5871                         if (dims != 1){
5872                                 Type [] args;
5873                                 ModuleBuilder mb = null;
5874                                 mb = CodeGen.ModuleBuilder;
5875                                 args = new Type [dims + 1];
5876
5877                                 int j;
5878                                 for (j = 0; j < dims; j++)
5879                                         args [j] = TypeManager.int32_type;
5880
5881                                 args [j] = array_element_type;
5882                                 
5883                                 set = mb.GetArrayMethod (
5884                                         type, "Set",
5885                                         CallingConventions.HasThis | CallingConventions.Standard,
5886                                         TypeManager.void_type, args);
5887                         }
5888                         
5889                         for (int i = 0; i < top; i++){
5890
5891                                 Expression e = null;
5892
5893                                 if (array_data [i] is Expression)
5894                                         e = (Expression) array_data [i];
5895
5896                                 if (e != null) {
5897                                         //
5898                                         // Basically we do this for string literals and
5899                                         // other non-literal expressions
5900                                         //
5901                                         if (e is EnumConstant){
5902                                                 e = ((EnumConstant) e).Child;
5903                                         }
5904                                         
5905                                         if (e is StringConstant || e is DecimalConstant || !(e is Constant) ||
5906                                             num_automatic_initializers <= max_automatic_initializers) {
5907                                                 Type etype = e.Type;
5908                                                 
5909                                                 ig.Emit (OpCodes.Ldloc, temp);
5910
5911                                                 for (int idx = 0; idx < dims; idx++) 
5912                                                         IntConstant.EmitInt (ig, current_pos [idx]);
5913
5914                                                 //
5915                                                 // If we are dealing with a struct, get the
5916                                                 // address of it, so we can store it.
5917                                                 //
5918                                                 if ((dims == 1) &&
5919                                                     etype.IsSubclassOf (TypeManager.value_type) &&
5920                                                     (!TypeManager.IsBuiltinType (etype) ||
5921                                                      etype == TypeManager.decimal_type)) {
5922                                                         if (e is New){
5923                                                                 New n = (New) e;
5924
5925                                                                 //
5926                                                                 // Let new know that we are providing
5927                                                                 // the address where to store the results
5928                                                                 //
5929                                                                 n.DisableTemporaryValueType ();
5930                                                         }
5931
5932                                                         ig.Emit (OpCodes.Ldelema, etype);
5933                                                 }
5934
5935                                                 e.Emit (ec);
5936
5937                                                 if (dims == 1)
5938                                                         ArrayAccess.EmitStoreOpcode (ig, array_element_type);
5939                                                 else 
5940                                                         ig.Emit (OpCodes.Call, set);
5941                                                 
5942                                         }
5943                                 }
5944                                 
5945                                 //
5946                                 // Advance counter
5947                                 //
5948                                 for (int j = dims - 1; j >= 0; j--){
5949                                         current_pos [j]++;
5950                                         if (current_pos [j] < (int) bounds [j])
5951                                                 break;
5952                                         current_pos [j] = 0;
5953                                 }
5954                         }
5955
5956                         if (is_expression)
5957                                 ig.Emit (OpCodes.Ldloc, temp);
5958                 }
5959
5960                 void EmitArrayArguments (EmitContext ec)
5961                 {
5962                         ILGenerator ig = ec.ig;
5963                         
5964                         foreach (Argument a in arguments) {
5965                                 Type atype = a.Type;
5966                                 a.Emit (ec);
5967
5968                                 if (atype == TypeManager.uint64_type)
5969                                         ig.Emit (OpCodes.Conv_Ovf_U4);
5970                                 else if (atype == TypeManager.int64_type)
5971                                         ig.Emit (OpCodes.Conv_Ovf_I4);
5972                         }
5973                 }
5974                 
5975                 void DoEmit (EmitContext ec, bool is_statement)
5976                 {
5977                         ILGenerator ig = ec.ig;
5978                         
5979                         EmitArrayArguments (ec);
5980                         if (is_one_dimensional)
5981                                 ig.Emit (OpCodes.Newarr, array_element_type);
5982                         else {
5983                                 if (is_builtin_type) 
5984                                         ig.Emit (OpCodes.Newobj, (ConstructorInfo) new_method);
5985                                 else 
5986                                         ig.Emit (OpCodes.Newobj, (MethodInfo) new_method);
5987                         }
5988                         
5989                         if (initializers != null){
5990                                 //
5991                                 // FIXME: Set this variable correctly.
5992                                 // 
5993                                 bool dynamic_initializers = true;
5994
5995                                 if (underlying_type != TypeManager.string_type &&
5996                                     underlying_type != TypeManager.decimal_type &&
5997                                     underlying_type != TypeManager.object_type) {
5998                                         if (num_automatic_initializers > max_automatic_initializers)
5999                                                 EmitStaticInitializers (ec, dynamic_initializers || !is_statement);
6000                                 }
6001                                 
6002                                 if (dynamic_initializers)
6003                                         EmitDynamicInitializers (ec, !is_statement);
6004                         }
6005                 }
6006                 
6007                 public override void Emit (EmitContext ec)
6008                 {
6009                         DoEmit (ec, false);
6010                 }
6011
6012                 public override void EmitStatement (EmitContext ec)
6013                 {
6014                         DoEmit (ec, true);
6015                 }
6016
6017                 public object EncodeAsAttribute ()
6018                 {
6019                         if (!is_one_dimensional){
6020                                 Report.Error (-211, Location, "attribute can not encode multi-dimensional arrays");
6021                                 return null;
6022                         }
6023
6024                         if (array_data == null){
6025                                 Report.Error (-212, Location, "array should be initialized when passing it to an attribute");
6026                                 return null;
6027                         }
6028                         
6029                         object [] ret = new object [array_data.Count];
6030                         int i = 0;
6031                         foreach (Expression e in array_data){
6032                                 object v;
6033                                 
6034                                 if (e is NullLiteral)
6035                                         v = null;
6036                                 else {
6037                                         if (!Attribute.GetAttributeArgumentExpression (e, Location, out v))
6038                                                 return null;
6039                                 }
6040                                 ret [i++] = v;
6041                         }
6042                         return ret;
6043                 }
6044         }
6045         
6046         /// <summary>
6047         ///   Represents the `this' construct
6048         /// </summary>
6049         public class This : Expression, IAssignMethod, IMemoryLocation, IVariable {
6050
6051                 Block block;
6052                 VariableInfo variable_info;
6053                 
6054                 public This (Block block, Location loc)
6055                 {
6056                         this.loc = loc;
6057                         this.block = block;
6058                 }
6059
6060                 public This (Location loc)
6061                 {
6062                         this.loc = loc;
6063                 }
6064
6065                 public VariableInfo VariableInfo {
6066                         get { return variable_info; }
6067                 }
6068
6069                 public bool VerifyFixed (bool is_expression)
6070                 {
6071                         return variable_info.LocalInfo.IsFixed;
6072                 }
6073
6074                 public bool ResolveBase (EmitContext ec)
6075                 {
6076                         eclass = ExprClass.Variable;
6077                         type = ec.ContainerType;
6078
6079                         if (ec.IsStatic) {
6080                                 Error (26, "Keyword this not valid in static code");
6081                                 return false;
6082                         }
6083
6084                         if ((block != null) && (block.ThisVariable != null))
6085                                 variable_info = block.GetVariableInfo (block.ThisVariable);
6086
6087                         return true;
6088                 }
6089
6090                 public override Expression DoResolve (EmitContext ec)
6091                 {
6092                         if (!ResolveBase (ec))
6093                                 return null;
6094
6095                         if ((variable_info != null) && !variable_info.IsAssigned (ec)) {
6096                                 Error (188, "The this object cannot be used before all " +
6097                                        "of its fields are assigned to");
6098                                 variable_info.SetAssigned (ec);
6099                                 return this;
6100                         }
6101
6102                         if (ec.IsFieldInitializer) {
6103                                 Error (27, "Keyword `this' can't be used outside a constructor, " +
6104                                        "a method or a property.");
6105                                 return null;
6106                         }
6107
6108                         return this;
6109                 }
6110
6111                 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
6112                 {
6113                         if (!ResolveBase (ec))
6114                                 return null;
6115
6116                         if (variable_info != null)
6117                                 variable_info.SetAssigned (ec);
6118                         
6119                         if (ec.TypeContainer is Class){
6120                                 Error (1604, "Cannot assign to `this'");
6121                                 return null;
6122                         }
6123
6124                         return this;
6125                 }
6126
6127                 public override void Emit (EmitContext ec)
6128                 {
6129                         ILGenerator ig = ec.ig;
6130                         
6131                         ig.Emit (OpCodes.Ldarg_0);
6132                         if (ec.TypeContainer is Struct)
6133                                 ig.Emit (OpCodes.Ldobj, type);
6134                 }
6135
6136                 public void EmitAssign (EmitContext ec, Expression source)
6137                 {
6138                         ILGenerator ig = ec.ig;
6139                         
6140                         if (ec.TypeContainer is Struct){
6141                                 ig.Emit (OpCodes.Ldarg_0);
6142                                 source.Emit (ec);
6143                                 ig.Emit (OpCodes.Stobj, type);
6144                         } else {
6145                                 source.Emit (ec);
6146                                 ig.Emit (OpCodes.Starg, 0);
6147                         }
6148                 }
6149
6150                 public void AddressOf (EmitContext ec, AddressOp mode)
6151                 {
6152                         ec.ig.Emit (OpCodes.Ldarg_0);
6153
6154                         // FIMXE
6155                         // FIGURE OUT WHY LDARG_S does not work
6156                         //
6157                         // consider: struct X { int val; int P { set { val = value; }}}
6158                         //
6159                         // Yes, this looks very bad. Look at `NOTAS' for
6160                         // an explanation.
6161                         // ec.ig.Emit (OpCodes.Ldarga_S, (byte) 0);
6162                 }
6163         }
6164
6165         /// <summary>
6166         ///   Implements the typeof operator
6167         /// </summary>
6168         public class TypeOf : Expression {
6169                 public readonly Expression QueriedType;
6170                 Type typearg;
6171                 
6172                 public TypeOf (Expression queried_type, Location l)
6173                 {
6174                         QueriedType = queried_type;
6175                         loc = l;
6176                 }
6177
6178                 public override Expression DoResolve (EmitContext ec)
6179                 {
6180                         typearg = ec.DeclSpace.ResolveType (QueriedType, false, loc);
6181
6182                         if (typearg == null)
6183                                 return null;
6184
6185                         if (typearg == TypeManager.void_type) {
6186                                 Error (673, "System.Void cannot be used from C# - " +
6187                                        "use typeof (void) to get the void type object");
6188                                 return null;
6189                         }
6190
6191                         type = TypeManager.type_type;
6192                         eclass = ExprClass.Type;
6193                         return this;
6194                 }
6195
6196                 public override void Emit (EmitContext ec)
6197                 {
6198                         ec.ig.Emit (OpCodes.Ldtoken, typearg);
6199                         ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
6200                 }
6201
6202                 public Type TypeArg { 
6203                         get { return typearg; }
6204                 }
6205         }
6206
6207         /// <summary>
6208         ///   Implements the `typeof (void)' operator
6209         /// </summary>
6210         public class TypeOfVoid : Expression {
6211                 public TypeOfVoid (Location l)
6212                 {
6213                         loc = l;
6214                 }
6215
6216                 public override Expression DoResolve (EmitContext ec)
6217                 {
6218                         type = TypeManager.type_type;
6219                         eclass = ExprClass.Type;
6220                         return this;
6221                 }
6222
6223                 public override void Emit (EmitContext ec)
6224                 {
6225                         ec.ig.Emit (OpCodes.Ldtoken, TypeManager.void_type);
6226                         ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
6227                 }
6228
6229                 public Type TypeArg { 
6230                         get { return TypeManager.void_type; }
6231                 }
6232         }
6233
6234         /// <summary>
6235         ///   Implements the sizeof expression
6236         /// </summary>
6237         public class SizeOf : Expression {
6238                 public readonly Expression QueriedType;
6239                 Type type_queried;
6240                 
6241                 public SizeOf (Expression queried_type, Location l)
6242                 {
6243                         this.QueriedType = queried_type;
6244                         loc = l;
6245                 }
6246
6247                 public override Expression DoResolve (EmitContext ec)
6248                 {
6249                         if (!ec.InUnsafe) {
6250                                 Report.Error (
6251                                         233, loc, "Sizeof may only be used in an unsafe context " +
6252                                         "(consider using System.Runtime.InteropServices.Marshal.Sizeof");
6253                                 return null;
6254                         }
6255                                 
6256                         type_queried = ec.DeclSpace.ResolveType (QueriedType, false, loc);
6257                         if (type_queried == null)
6258                                 return null;
6259
6260                         if (!TypeManager.IsUnmanagedType (type_queried)){
6261                                 Report.Error (208, loc, "Cannot take the size of an unmanaged type (" + TypeManager.CSharpName (type_queried) + ")");
6262                                 return null;
6263                         }
6264                         
6265                         type = TypeManager.int32_type;
6266                         eclass = ExprClass.Value;
6267                         return this;
6268                 }
6269
6270                 public override void Emit (EmitContext ec)
6271                 {
6272                         int size = GetTypeSize (type_queried);
6273
6274                         if (size == 0)
6275                                 ec.ig.Emit (OpCodes.Sizeof, type_queried);
6276                         else
6277                                 IntConstant.EmitInt (ec.ig, size);
6278                 }
6279         }
6280
6281         /// <summary>
6282         ///   Implements the member access expression
6283         /// </summary>
6284         public class MemberAccess : Expression {
6285                 public readonly string Identifier;
6286                 Expression expr;
6287                 
6288                 public MemberAccess (Expression expr, string id, Location l)
6289                 {
6290                         this.expr = expr;
6291                         Identifier = id;
6292                         loc = l;
6293                 }
6294
6295                 public Expression Expr {
6296                         get {
6297                                 return expr;
6298                         }
6299                 }
6300
6301                 static void error176 (Location loc, string name)
6302                 {
6303                         Report.Error (176, loc, "Static member `" +
6304                                       name + "' cannot be accessed " +
6305                                       "with an instance reference, qualify with a " +
6306                                       "type name instead");
6307                 }
6308
6309                 static bool IdenticalNameAndTypeName (EmitContext ec, Expression left_original, Location loc)
6310                 {
6311                         if (left_original == null)
6312                                 return false;
6313
6314                         if (!(left_original is SimpleName))
6315                                 return false;
6316
6317                         SimpleName sn = (SimpleName) left_original;
6318
6319                         Type t = RootContext.LookupType (ec.DeclSpace, sn.Name, true, loc);
6320                         if (t != null)
6321                                 return true;
6322
6323                         return false;
6324                 }
6325                 
6326                 public static Expression ResolveMemberAccess (EmitContext ec, Expression member_lookup,
6327                                                               Expression left, Location loc,
6328                                                               Expression left_original)
6329                 {
6330                         bool left_is_type, left_is_explicit;
6331
6332                         // If `left' is null, then we're called from SimpleNameResolve and this is
6333                         // a member in the currently defining class.
6334                         if (left == null) {
6335                                 left_is_type = ec.IsStatic || ec.IsFieldInitializer;
6336                                 left_is_explicit = false;
6337
6338                                 // Implicitly default to `this' unless we're static.
6339                                 if (!ec.IsStatic && !ec.IsFieldInitializer && !ec.InEnumContext)
6340                                         left = ec.GetThis (loc);
6341                         } else {
6342                                 left_is_type = left is TypeExpr;
6343                                 left_is_explicit = true;
6344                         }
6345
6346                         if (member_lookup is FieldExpr){
6347                                 FieldExpr fe = (FieldExpr) member_lookup;
6348                                 FieldInfo fi = fe.FieldInfo;
6349                                 Type decl_type = fi.DeclaringType;
6350
6351                                 if (fi is FieldBuilder) {
6352                                         Const c = TypeManager.LookupConstant ((FieldBuilder) fi);
6353                                         
6354                                         if (c != null) {
6355                                                 object o = c.LookupConstantValue ();
6356                                                 if (o == null)
6357                                                         return null;
6358                                                 
6359                                                 object real_value = ((Constant) c.Expr).GetValue ();
6360
6361                                                 return Constantify (real_value, fi.FieldType);
6362                                         }
6363                                 }
6364
6365                                 if (fi.IsLiteral) {
6366                                         Type t = fi.FieldType;
6367                                         
6368                                         object o;
6369
6370                                         if (fi is FieldBuilder)
6371                                                 o = TypeManager.GetValue ((FieldBuilder) fi);
6372                                         else
6373                                                 o = fi.GetValue (fi);
6374                                         
6375                                         if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
6376                                                 if (left_is_explicit && !left_is_type &&
6377                                                     !IdenticalNameAndTypeName (ec, left_original, loc)) {
6378                                                         error176 (loc, fe.FieldInfo.Name);
6379                                                         return null;
6380                                                 }                                       
6381                                                 
6382                                                 Expression enum_member = MemberLookup (
6383                                                         ec, decl_type, "value__", MemberTypes.Field,
6384                                                         AllBindingFlags, loc); 
6385
6386                                                 Enum en = TypeManager.LookupEnum (decl_type);
6387
6388                                                 Constant c;
6389                                                 if (en != null)
6390                                                         c = Constantify (o, en.UnderlyingType);
6391                                                 else 
6392                                                         c = Constantify (o, enum_member.Type);
6393                                                 
6394                                                 return new EnumConstant (c, decl_type);
6395                                         }
6396                                         
6397                                         Expression exp = Constantify (o, t);
6398
6399                                         if (left_is_explicit && !left_is_type) {
6400                                                 error176 (loc, fe.FieldInfo.Name);
6401                                                 return null;
6402                                         }
6403                                         
6404                                         return exp;
6405                                 }
6406
6407                                 if (fi.FieldType.IsPointer && !ec.InUnsafe){
6408                                         UnsafeError (loc);
6409                                         return null;
6410                                 }
6411                         }
6412
6413                         if (member_lookup is EventExpr) {
6414                                 EventExpr ee = (EventExpr) member_lookup;
6415                                 
6416                                 //
6417                                 // If the event is local to this class, we transform ourselves into
6418                                 // a FieldExpr
6419                                 //
6420
6421                                 if (ee.EventInfo.DeclaringType == ec.ContainerType) {
6422                                         MemberInfo mi = GetFieldFromEvent (ee);
6423
6424                                         if (mi == null) {
6425                                                 //
6426                                                 // If this happens, then we have an event with its own
6427                                                 // accessors and private field etc so there's no need
6428                                                 // to transform ourselves.
6429                                                 //
6430                                                 return ee;
6431                                         }
6432
6433                                         Expression ml = ExprClassFromMemberInfo (ec, mi, loc);
6434                                         
6435                                         if (ml == null) {
6436                                                 Report.Error (-200, loc, "Internal error!!");
6437                                                 return null;
6438                                         }
6439
6440                                         if (!left_is_explicit)
6441                                                 left = null;
6442                                         
6443                                         return ResolveMemberAccess (ec, ml, left, loc, left_original);
6444                                 }
6445                         }
6446
6447                         if (member_lookup is IMemberExpr) {
6448                                 IMemberExpr me = (IMemberExpr) member_lookup;
6449
6450                                 if (left_is_type){
6451                                         MethodGroupExpr mg = me as MethodGroupExpr;
6452                                         if ((mg != null) && left_is_explicit && left.Type.IsInterface)
6453                                                 mg.IsExplicitImpl = left_is_explicit;
6454
6455                                         if (!me.IsStatic){
6456                                                 if ((ec.IsFieldInitializer || ec.IsStatic) &&
6457                                                     IdenticalNameAndTypeName (ec, left_original, loc))
6458                                                         return member_lookup;
6459
6460                                                 SimpleName.Error_ObjectRefRequired (ec, loc, me.Name);
6461                                                 return null;
6462                                         }
6463
6464                                 } else {
6465                                         if (!me.IsInstance){
6466                                                 if (IdenticalNameAndTypeName (ec, left_original, loc))
6467                                                         return member_lookup;
6468
6469                                                 if (left_is_explicit) {
6470                                                         error176 (loc, me.Name);
6471                                                         return null;
6472                                                 }
6473                                         }
6474
6475                                         //
6476                                         // Since we can not check for instance objects in SimpleName,
6477                                         // becaue of the rule that allows types and variables to share
6478                                         // the name (as long as they can be de-ambiguated later, see 
6479                                         // IdenticalNameAndTypeName), we have to check whether left 
6480                                         // is an instance variable in a static context
6481                                         //
6482                                         // However, if the left-hand value is explicitly given, then
6483                                         // it is already our instance expression, so we aren't in
6484                                         // static context.
6485                                         //
6486
6487                                         if (ec.IsStatic && !left_is_explicit && left is IMemberExpr){
6488                                                 IMemberExpr mexp = (IMemberExpr) left;
6489
6490                                                 if (!mexp.IsStatic){
6491                                                         SimpleName.Error_ObjectRefRequired (ec, loc, mexp.Name);
6492                                                         return null;
6493                                                 }
6494                                         }
6495
6496                                         me.InstanceExpression = left;
6497                                 }
6498
6499                                 return member_lookup;
6500                         }
6501
6502                         Console.WriteLine ("Left is: " + left);
6503                         Report.Error (-100, loc, "Support for [" + member_lookup + "] is not present yet");
6504                         Environment.Exit (0);
6505                         return null;
6506                 }
6507                 
6508                 public Expression DoResolve (EmitContext ec, Expression right_side, ResolveFlags flags)
6509                 {
6510                         if (type != null)
6511                                 throw new Exception ();
6512
6513                         //
6514                         // Resolve the expression with flow analysis turned off, we'll do the definite
6515                         // assignment checks later.  This is because we don't know yet what the expression
6516                         // will resolve to - it may resolve to a FieldExpr and in this case we must do the
6517                         // definite assignment check on the actual field and not on the whole struct.
6518                         //
6519
6520                         Expression original = expr;
6521                         expr = expr.Resolve (ec, flags | ResolveFlags.DisableFlowAnalysis);
6522                         if (expr == null)
6523                                 return null;
6524
6525                         if (expr is SimpleName){
6526                                 SimpleName child_expr = (SimpleName) expr;
6527
6528                                 Expression new_expr = new SimpleName (child_expr.Name, Identifier, loc);
6529
6530                                 return new_expr.Resolve (ec, flags);
6531                         }
6532                                         
6533                         //
6534                         // TODO: I mailed Ravi about this, and apparently we can get rid
6535                         // of this and put it in the right place.
6536                         // 
6537                         // Handle enums here when they are in transit.
6538                         // Note that we cannot afford to hit MemberLookup in this case because
6539                         // it will fail to find any members at all
6540                         //
6541
6542                         int errors = Report.Errors;
6543                         
6544                         Type expr_type = expr.Type;
6545                         if (expr is TypeExpr){
6546                                 if (!ec.DeclSpace.CheckAccessLevel (expr_type)){
6547                                         Error (122, "`" + expr_type + "' " +
6548                                                "is inaccessible because of its protection level");
6549                                         return null;
6550                                 }
6551
6552                                 if (expr_type == TypeManager.enum_type || expr_type.IsSubclassOf (TypeManager.enum_type)){
6553                                         Enum en = TypeManager.LookupEnum (expr_type);
6554
6555                                         if (en != null) {
6556                                                 object value = en.LookupEnumValue (ec, Identifier, loc);
6557                                                 
6558                                                 if (value != null){
6559                                                         Constant c = Constantify (value, en.UnderlyingType);
6560                                                         return new EnumConstant (c, expr_type);
6561                                                 }
6562                                         }
6563                                 }
6564                         }
6565                         
6566                         if (expr_type.IsPointer){
6567                                 Error (23, "The `.' operator can not be applied to pointer operands (" +
6568                                        TypeManager.CSharpName (expr_type) + ")");
6569                                 return null;
6570                         }
6571
6572                         Expression member_lookup;
6573                         member_lookup = MemberLookupFinal (ec, expr_type, expr_type, Identifier, loc);
6574                         if (member_lookup == null)
6575                                 return null;
6576
6577                         if (member_lookup is TypeExpr) {
6578                                 if (!(expr is TypeExpr) && !(expr is SimpleName)) {
6579                                         Error (572, "Can't reference type `" + Identifier + "' through an expression; try `" +
6580                                                member_lookup.Type + "' instead");
6581                                         return null;
6582                                 }
6583
6584                                 return member_lookup;
6585                         }
6586                         
6587                         member_lookup = ResolveMemberAccess (ec, member_lookup, expr, loc, original);
6588                         if (member_lookup == null)
6589                                 return null;
6590
6591                         // The following DoResolve/DoResolveLValue will do the definite assignment
6592                         // check.
6593
6594                         if (right_side != null)
6595                                 member_lookup = member_lookup.DoResolveLValue (ec, right_side);
6596                         else
6597                                 member_lookup = member_lookup.DoResolve (ec);
6598
6599                         return member_lookup;
6600                 }
6601
6602                 public override Expression DoResolve (EmitContext ec)
6603                 {
6604                         return DoResolve (ec, null, ResolveFlags.VariableOrValue |
6605                                           ResolveFlags.SimpleName | ResolveFlags.Type);
6606                 }
6607
6608                 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
6609                 {
6610                         return DoResolve (ec, right_side, ResolveFlags.VariableOrValue |
6611                                           ResolveFlags.SimpleName | ResolveFlags.Type);
6612                 }
6613
6614                 public override Expression ResolveAsTypeStep (EmitContext ec)
6615                 {
6616                         string fname = null;
6617                         MemberAccess full_expr = this;
6618                         while (full_expr != null) {
6619                                 if (fname != null)
6620                                         fname = String.Concat (full_expr.Identifier, ".", fname);
6621                                 else
6622                                         fname = full_expr.Identifier;
6623
6624                                 if (full_expr.Expr is SimpleName) {
6625                                         string full_name = String.Concat (((SimpleName) full_expr.Expr).Name, ".", fname);
6626                                         Type fully_qualified = ec.DeclSpace.FindType (loc, full_name);
6627                                         if (fully_qualified != null)
6628                                                 return new TypeExpr (fully_qualified, loc);
6629                                 }
6630
6631                                 full_expr = full_expr.Expr as MemberAccess;
6632                         }
6633
6634                         Expression new_expr = expr.ResolveAsTypeStep (ec);
6635
6636                         if (new_expr == null)
6637                                 return null;
6638
6639                         if (new_expr is SimpleName){
6640                                 SimpleName child_expr = (SimpleName) new_expr;
6641                                 
6642                                 new_expr = new SimpleName (child_expr.Name, Identifier, loc);
6643
6644                                 return new_expr.ResolveAsTypeStep (ec);
6645                         }
6646
6647                         Type expr_type = new_expr.Type;
6648                       
6649                         if (expr_type.IsPointer){
6650                                 Error (23, "The `.' operator can not be applied to pointer operands (" +
6651                                        TypeManager.CSharpName (expr_type) + ")");
6652                                 return null;
6653                         }
6654                         
6655                         Expression member_lookup;
6656                         member_lookup = MemberLookupFinal (ec, expr_type, expr_type, Identifier, loc);
6657                         if (member_lookup == null)
6658                                 return null;
6659
6660                         if (member_lookup is TypeExpr){
6661                                 member_lookup.Resolve (ec, ResolveFlags.Type);
6662                                 return member_lookup;
6663                         } 
6664
6665                         return null;                    
6666                 }
6667
6668                 public override void Emit (EmitContext ec)
6669                 {
6670                         throw new Exception ("Should not happen");
6671                 }
6672
6673                 public override string ToString ()
6674                 {
6675                         return expr + "." + Identifier;
6676                 }
6677         }
6678
6679         /// <summary>
6680         ///   Implements checked expressions
6681         /// </summary>
6682         public class CheckedExpr : Expression {
6683
6684                 public Expression Expr;
6685
6686                 public CheckedExpr (Expression e, Location l)
6687                 {
6688                         Expr = e;
6689                         loc = l;
6690                 }
6691
6692                 public override Expression DoResolve (EmitContext ec)
6693                 {
6694                         bool last_check = ec.CheckState;
6695                         bool last_const_check = ec.ConstantCheckState;
6696
6697                         ec.CheckState = true;
6698                         ec.ConstantCheckState = true;
6699                         Expr = Expr.Resolve (ec);
6700                         ec.CheckState = last_check;
6701                         ec.ConstantCheckState = last_const_check;
6702                         
6703                         if (Expr == null)
6704                                 return null;
6705
6706                         if (Expr is Constant)
6707                                 return Expr;
6708                         
6709                         eclass = Expr.eclass;
6710                         type = Expr.Type;
6711                         return this;
6712                 }
6713
6714                 public override void Emit (EmitContext ec)
6715                 {
6716                         bool last_check = ec.CheckState;
6717                         bool last_const_check = ec.ConstantCheckState;
6718                         
6719                         ec.CheckState = true;
6720                         ec.ConstantCheckState = true;
6721                         Expr.Emit (ec);
6722                         ec.CheckState = last_check;
6723                         ec.ConstantCheckState = last_const_check;
6724                 }
6725                 
6726         }
6727
6728         /// <summary>
6729         ///   Implements the unchecked expression
6730         /// </summary>
6731         public class UnCheckedExpr : Expression {
6732
6733                 public Expression Expr;
6734
6735                 public UnCheckedExpr (Expression e, Location l)
6736                 {
6737                         Expr = e;
6738                         loc = l;
6739                 }
6740
6741                 public override Expression DoResolve (EmitContext ec)
6742                 {
6743                         bool last_check = ec.CheckState;
6744                         bool last_const_check = ec.ConstantCheckState;
6745
6746                         ec.CheckState = false;
6747                         ec.ConstantCheckState = false;
6748                         Expr = Expr.Resolve (ec);
6749                         ec.CheckState = last_check;
6750                         ec.ConstantCheckState = last_const_check;
6751
6752                         if (Expr == null)
6753                                 return null;
6754
6755                         if (Expr is Constant)
6756                                 return Expr;
6757                         
6758                         eclass = Expr.eclass;
6759                         type = Expr.Type;
6760                         return this;
6761                 }
6762
6763                 public override void Emit (EmitContext ec)
6764                 {
6765                         bool last_check = ec.CheckState;
6766                         bool last_const_check = ec.ConstantCheckState;
6767                         
6768                         ec.CheckState = false;
6769                         ec.ConstantCheckState = false;
6770                         Expr.Emit (ec);
6771                         ec.CheckState = last_check;
6772                         ec.ConstantCheckState = last_const_check;
6773                 }
6774                 
6775         }
6776
6777         /// <summary>
6778         ///   An Element Access expression.
6779         ///
6780         ///   During semantic analysis these are transformed into 
6781         ///   IndexerAccess, ArrayAccess or a PointerArithmetic.
6782         /// </summary>
6783         public class ElementAccess : Expression {
6784                 public ArrayList  Arguments;
6785                 public Expression Expr;
6786                 
6787                 public ElementAccess (Expression e, ArrayList e_list, Location l)
6788                 {
6789                         Expr = e;
6790
6791                         loc  = l;
6792                         
6793                         if (e_list == null)
6794                                 return;
6795                         
6796                         Arguments = new ArrayList ();
6797                         foreach (Expression tmp in e_list)
6798                                 Arguments.Add (new Argument (tmp, Argument.AType.Expression));
6799                         
6800                 }
6801
6802                 bool CommonResolve (EmitContext ec)
6803                 {
6804                         Expr = Expr.Resolve (ec);
6805
6806                         if (Expr == null) 
6807                                 return false;
6808
6809                         if (Arguments == null)
6810                                 return false;
6811
6812                         foreach (Argument a in Arguments){
6813                                 if (!a.Resolve (ec, loc))
6814                                         return false;
6815                         }
6816
6817                         return true;
6818                 }
6819
6820                 Expression MakePointerAccess ()
6821                 {
6822                         Type t = Expr.Type;
6823
6824                         if (t == TypeManager.void_ptr_type){
6825                                 Error (242, "The array index operation is not valid for void pointers");
6826                                 return null;
6827                         }
6828                         if (Arguments.Count != 1){
6829                                 Error (196, "A pointer must be indexed by a single value");
6830                                 return null;
6831                         }
6832                         Expression p;
6833
6834                         p = new PointerArithmetic (true, Expr, ((Argument)Arguments [0]).Expr, t, loc);
6835                         return new Indirection (p, loc);
6836                 }
6837                 
6838                 public override Expression DoResolve (EmitContext ec)
6839                 {
6840                         if (!CommonResolve (ec))
6841                                 return null;
6842
6843                         //
6844                         // We perform some simple tests, and then to "split" the emit and store
6845                         // code we create an instance of a different class, and return that.
6846                         //
6847                         // I am experimenting with this pattern.
6848                         //
6849                         Type t = Expr.Type;
6850
6851                         if (t == TypeManager.array_type){
6852                                 Report.Error (21, loc, "Cannot use indexer on System.Array");
6853                                 return null;
6854                         }
6855                         
6856                         if (t.IsArray)
6857                                 return (new ArrayAccess (this, loc)).Resolve (ec);
6858                         else if (t.IsPointer)
6859                                 return MakePointerAccess ();
6860                         else
6861                                 return (new IndexerAccess (this, loc)).Resolve (ec);
6862                 }
6863
6864                 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
6865                 {
6866                         if (!CommonResolve (ec))
6867                                 return null;
6868
6869                         Type t = Expr.Type;
6870                         if (t.IsArray)
6871                                 return (new ArrayAccess (this, loc)).ResolveLValue (ec, right_side);
6872                         else if (t.IsPointer)
6873                                 return MakePointerAccess ();
6874                         else
6875                                 return (new IndexerAccess (this, loc)).ResolveLValue (ec, right_side);
6876                 }
6877                 
6878                 public override void Emit (EmitContext ec)
6879                 {
6880                         throw new Exception ("Should never be reached");
6881                 }
6882         }
6883
6884         /// <summary>
6885         ///   Implements array access 
6886         /// </summary>
6887         public class ArrayAccess : Expression, IAssignMethod, IMemoryLocation {
6888                 //
6889                 // Points to our "data" repository
6890                 //
6891                 ElementAccess ea;
6892
6893                 LocalTemporary [] cached_locations;
6894                 
6895                 public ArrayAccess (ElementAccess ea_data, Location l)
6896                 {
6897                         ea = ea_data;
6898                         eclass = ExprClass.Variable;
6899                         loc = l;
6900                 }
6901
6902                 public override Expression DoResolve (EmitContext ec)
6903                 {
6904                         ExprClass eclass = ea.Expr.eclass;
6905
6906 #if false
6907                         // As long as the type is valid
6908                         if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
6909                               eclass == ExprClass.Value)) {
6910                                 ea.Expr.Error_UnexpectedKind ("variable or value");
6911                                 return null;
6912                         }
6913 #endif
6914
6915                         Type t = ea.Expr.Type;
6916                         if (t.GetArrayRank () != ea.Arguments.Count){
6917                                 ea.Error (22,
6918                                           "Incorrect number of indexes for array " +
6919                                           " expected: " + t.GetArrayRank () + " got: " +
6920                                           ea.Arguments.Count);
6921                                 return null;
6922                         }
6923                         type = TypeManager.TypeToCoreType (t.GetElementType ());
6924                         if (type.IsPointer && !ec.InUnsafe){
6925                                 UnsafeError (ea.Location);
6926                                 return null;
6927                         }
6928
6929                         foreach (Argument a in ea.Arguments){
6930                                 Type argtype = a.Type;
6931
6932                                 if (argtype == TypeManager.int32_type ||
6933                                     argtype == TypeManager.uint32_type ||
6934                                     argtype == TypeManager.int64_type ||
6935                                     argtype == TypeManager.uint64_type)
6936                                         continue;
6937
6938                                 //
6939                                 // Mhm.  This is strage, because the Argument.Type is not the same as
6940                                 // Argument.Expr.Type: the value changes depending on the ref/out setting.
6941                                 //
6942                                 // Wonder if I will run into trouble for this.
6943                                 //
6944                                 a.Expr = ExpressionToArrayArgument (ec, a.Expr, ea.Location);
6945                                 if (a.Expr == null)
6946                                         return null;
6947                         }
6948                         
6949                         eclass = ExprClass.Variable;
6950
6951                         return this;
6952                 }
6953
6954                 /// <summary>
6955                 ///    Emits the right opcode to load an object of Type `t'
6956                 ///    from an array of T
6957                 /// </summary>
6958                 static public void EmitLoadOpcode (ILGenerator ig, Type type)
6959                 {
6960                         if (type == TypeManager.byte_type || type == TypeManager.bool_type)
6961                                 ig.Emit (OpCodes.Ldelem_U1);
6962                         else if (type == TypeManager.sbyte_type)
6963                                 ig.Emit (OpCodes.Ldelem_I1);
6964                         else if (type == TypeManager.short_type)
6965                                 ig.Emit (OpCodes.Ldelem_I2);
6966                         else if (type == TypeManager.ushort_type || type == TypeManager.char_type)
6967                                 ig.Emit (OpCodes.Ldelem_U2);
6968                         else if (type == TypeManager.int32_type)
6969                                 ig.Emit (OpCodes.Ldelem_I4);
6970                         else if (type == TypeManager.uint32_type)
6971                                 ig.Emit (OpCodes.Ldelem_U4);
6972                         else if (type == TypeManager.uint64_type)
6973                                 ig.Emit (OpCodes.Ldelem_I8);
6974                         else if (type == TypeManager.int64_type)
6975                                 ig.Emit (OpCodes.Ldelem_I8);
6976                         else if (type == TypeManager.float_type)
6977                                 ig.Emit (OpCodes.Ldelem_R4);
6978                         else if (type == TypeManager.double_type)
6979                                 ig.Emit (OpCodes.Ldelem_R8);
6980                         else if (type == TypeManager.intptr_type)
6981                                 ig.Emit (OpCodes.Ldelem_I);
6982                         else if (type.IsValueType){
6983                                 ig.Emit (OpCodes.Ldelema, type);
6984                                 ig.Emit (OpCodes.Ldobj, type);
6985                         } else 
6986                                 ig.Emit (OpCodes.Ldelem_Ref);
6987                 }
6988
6989                 /// <summary>
6990                 ///    Emits the right opcode to store an object of Type `t'
6991                 ///    from an array of T.  
6992                 /// </summary>
6993                 static public void EmitStoreOpcode (ILGenerator ig, Type t)
6994                 {
6995                         bool is_stobj;
6996                         OpCode op = GetStoreOpcode (t, out is_stobj);
6997                         if (is_stobj)
6998                                 ig.Emit (OpCodes.Stobj, t);
6999                         else
7000                                 ig.Emit (op);
7001                 }
7002
7003                 /// <summary>
7004                 ///    Returns the right opcode to store an object of Type `t'
7005                 ///    from an array of T.  
7006                 /// </summary>
7007                 static public OpCode GetStoreOpcode (Type t, out bool is_stobj)
7008                 {
7009                         //Console.WriteLine (new System.Diagnostics.StackTrace ());
7010                         is_stobj = false;
7011                         t = TypeManager.TypeToCoreType (t);
7012                         if (TypeManager.IsEnumType (t) && t != TypeManager.enum_type)
7013                                 t = TypeManager.EnumToUnderlying (t);
7014                         if (t == TypeManager.byte_type || t == TypeManager.sbyte_type ||
7015                             t == TypeManager.bool_type)
7016                                 return OpCodes.Stelem_I1;
7017                         else if (t == TypeManager.short_type || t == TypeManager.ushort_type ||
7018                                  t == TypeManager.char_type)
7019                                 return OpCodes.Stelem_I2;
7020                         else if (t == TypeManager.int32_type || t == TypeManager.uint32_type)
7021                                 return OpCodes.Stelem_I4;
7022                         else if (t == TypeManager.int64_type || t == TypeManager.uint64_type)
7023                                 return OpCodes.Stelem_I8;
7024                         else if (t == TypeManager.float_type)
7025                                 return OpCodes.Stelem_R4;
7026                         else if (t == TypeManager.double_type)
7027                                 return OpCodes.Stelem_R8;
7028                         else if (t == TypeManager.intptr_type) {
7029                                 is_stobj = true;
7030                                 return OpCodes.Stobj;
7031                         } else if (t.IsValueType) {
7032                                 is_stobj = true;
7033                                 return OpCodes.Stobj;
7034                         } else
7035                                 return OpCodes.Stelem_Ref;
7036                 }
7037
7038                 MethodInfo FetchGetMethod ()
7039                 {
7040                         ModuleBuilder mb = CodeGen.ModuleBuilder;
7041                         int arg_count = ea.Arguments.Count;
7042                         Type [] args = new Type [arg_count];
7043                         MethodInfo get;
7044                         
7045                         for (int i = 0; i < arg_count; i++){
7046                                 //args [i++] = a.Type;
7047                                 args [i] = TypeManager.int32_type;
7048                         }
7049                         
7050                         get = mb.GetArrayMethod (
7051                                 ea.Expr.Type, "Get",
7052                                 CallingConventions.HasThis |
7053                                 CallingConventions.Standard,
7054                                 type, args);
7055                         return get;
7056                 }
7057                                 
7058
7059                 MethodInfo FetchAddressMethod ()
7060                 {
7061                         ModuleBuilder mb = CodeGen.ModuleBuilder;
7062                         int arg_count = ea.Arguments.Count;
7063                         Type [] args = new Type [arg_count];
7064                         MethodInfo address;
7065                         Type ret_type;
7066                         
7067                         ret_type = TypeManager.GetReferenceType (type);
7068                         
7069                         for (int i = 0; i < arg_count; i++){
7070                                 //args [i++] = a.Type;
7071                                 args [i] = TypeManager.int32_type;
7072                         }
7073                         
7074                         address = mb.GetArrayMethod (
7075                                 ea.Expr.Type, "Address",
7076                                 CallingConventions.HasThis |
7077                                 CallingConventions.Standard,
7078                                 ret_type, args);
7079
7080                         return address;
7081                 }
7082
7083                 //
7084                 // Load the array arguments into the stack.
7085                 //
7086                 // If we have been requested to cache the values (cached_locations array
7087                 // initialized), then load the arguments the first time and store them
7088                 // in locals.  otherwise load from local variables.
7089                 //
7090                 void LoadArrayAndArguments (EmitContext ec)
7091                 {
7092                         ILGenerator ig = ec.ig;
7093                         
7094                         if (cached_locations == null){
7095                                 ea.Expr.Emit (ec);
7096                                 foreach (Argument a in ea.Arguments){
7097                                         Type argtype = a.Expr.Type;
7098                                         
7099                                         a.Expr.Emit (ec);
7100                                         
7101                                         if (argtype == TypeManager.int64_type)
7102                                                 ig.Emit (OpCodes.Conv_Ovf_I);
7103                                         else if (argtype == TypeManager.uint64_type)
7104                                                 ig.Emit (OpCodes.Conv_Ovf_I_Un);
7105                                 }
7106                                 return;
7107                         }
7108
7109                         if (cached_locations [0] == null){
7110                                 cached_locations [0] = new LocalTemporary (ec, ea.Expr.Type);
7111                                 ea.Expr.Emit (ec);
7112                                 ig.Emit (OpCodes.Dup);
7113                                 cached_locations [0].Store (ec);
7114                                 
7115                                 int j = 1;
7116                                 
7117                                 foreach (Argument a in ea.Arguments){
7118                                         Type argtype = a.Expr.Type;
7119                                         
7120                                         cached_locations [j] = new LocalTemporary (ec, TypeManager.intptr_type /* a.Expr.Type */);
7121                                         a.Expr.Emit (ec);
7122                                         if (argtype == TypeManager.int64_type)
7123                                                 ig.Emit (OpCodes.Conv_Ovf_I);
7124                                         else if (argtype == TypeManager.uint64_type)
7125                                                 ig.Emit (OpCodes.Conv_Ovf_I_Un);
7126
7127                                         ig.Emit (OpCodes.Dup);
7128                                         cached_locations [j].Store (ec);
7129                                         j++;
7130                                 }
7131                                 return;
7132                         }
7133
7134                         foreach (LocalTemporary lt in cached_locations)
7135                                 lt.Emit (ec);
7136                 }
7137
7138                 public new void CacheTemporaries (EmitContext ec)
7139                 {
7140                         cached_locations = new LocalTemporary [ea.Arguments.Count + 1];
7141                 }
7142                 
7143                 public override void Emit (EmitContext ec)
7144                 {
7145                         int rank = ea.Expr.Type.GetArrayRank ();
7146                         ILGenerator ig = ec.ig;
7147
7148                         LoadArrayAndArguments (ec);
7149                         
7150                         if (rank == 1)
7151                                 EmitLoadOpcode (ig, type);
7152                         else {
7153                                 MethodInfo method;
7154                                 
7155                                 method = FetchGetMethod ();
7156                                 ig.Emit (OpCodes.Call, method);
7157                         }
7158                 }
7159
7160                 public void EmitAssign (EmitContext ec, Expression source)
7161                 {
7162                         int rank = ea.Expr.Type.GetArrayRank ();
7163                         ILGenerator ig = ec.ig;
7164                         Type t = source.Type;
7165
7166                         LoadArrayAndArguments (ec);
7167
7168                         //
7169                         // The stobj opcode used by value types will need
7170                         // an address on the stack, not really an array/array
7171                         // pair
7172                         //
7173                         if (rank == 1){
7174                                 if (t == TypeManager.enum_type || t == TypeManager.decimal_type ||
7175                                     (t.IsSubclassOf (TypeManager.value_type) && !TypeManager.IsEnumType (t) && !TypeManager.IsBuiltinType (t)))
7176                                         ig.Emit (OpCodes.Ldelema, t);
7177                         }
7178                         
7179                         source.Emit (ec);
7180
7181                         if (rank == 1)
7182                                 EmitStoreOpcode (ig, t);
7183                         else {
7184                                 ModuleBuilder mb = CodeGen.ModuleBuilder;
7185                                 int arg_count = ea.Arguments.Count;
7186                                 Type [] args = new Type [arg_count + 1];
7187                                 MethodInfo set;
7188                                 
7189                                 for (int i = 0; i < arg_count; i++){
7190                                         //args [i++] = a.Type;
7191                                         args [i] = TypeManager.int32_type;
7192                                 }
7193
7194                                 args [arg_count] = type;
7195                                 
7196                                 set = mb.GetArrayMethod (
7197                                         ea.Expr.Type, "Set",
7198                                         CallingConventions.HasThis |
7199                                         CallingConventions.Standard,
7200                                         TypeManager.void_type, args);
7201                                 
7202                                 ig.Emit (OpCodes.Call, set);
7203                         }
7204                 }
7205
7206                 public void AddressOf (EmitContext ec, AddressOp mode)
7207                 {
7208                         int rank = ea.Expr.Type.GetArrayRank ();
7209                         ILGenerator ig = ec.ig;
7210
7211                         LoadArrayAndArguments (ec);
7212
7213                         if (rank == 1){
7214                                 ig.Emit (OpCodes.Ldelema, type);
7215                         } else {
7216                                 MethodInfo address = FetchAddressMethod ();
7217                                 ig.Emit (OpCodes.Call, address);
7218                         }
7219                 }
7220         }
7221
7222         
7223         class Indexers {
7224                 public ArrayList properties;
7225                 static Hashtable map;
7226
7227                 static Indexers ()
7228                 {
7229                         map = new Hashtable ();
7230                 }
7231
7232                 Indexers ()
7233                 {
7234                         properties = new ArrayList ();
7235                 }
7236                                 
7237                 void Append (MemberInfo [] mi)
7238                 {
7239                         foreach (PropertyInfo property in mi){
7240                                 MethodInfo get, set;
7241                                 
7242                                 get = property.GetGetMethod (true);
7243                                 set = property.GetSetMethod (true);
7244                                 properties.Add (new Pair (get, set));
7245                         }
7246                 }
7247
7248                 static private MemberInfo [] GetIndexersForTypeOrInterface (Type caller_type, Type lookup_type)
7249                 {
7250                         string p_name = TypeManager.IndexerPropertyName (lookup_type);
7251
7252                         MemberInfo [] mi = TypeManager.MemberLookup (
7253                                 caller_type, caller_type, lookup_type, MemberTypes.Property,
7254                                 BindingFlags.Public | BindingFlags.Instance |
7255                                 BindingFlags.DeclaredOnly, p_name);
7256
7257                         if (mi == null || mi.Length == 0)
7258                                 return null;
7259
7260                         return mi;
7261                 }
7262                 
7263                 static public Indexers GetIndexersForType (Type caller_type, Type lookup_type, Location loc) 
7264                 {
7265                         Indexers ix = (Indexers) map [lookup_type];
7266                         
7267                         if (ix != null)
7268                                 return ix;
7269
7270                         Type copy = lookup_type;
7271                         while (copy != TypeManager.object_type && copy != null){
7272                                 MemberInfo [] mi = GetIndexersForTypeOrInterface (caller_type, copy);
7273
7274                                 if (mi != null){
7275                                         if (ix == null)
7276                                                 ix = new Indexers ();
7277
7278                                         ix.Append (mi);
7279                                 }
7280                                         
7281                                 copy = copy.BaseType;
7282                         }
7283
7284                         return ix;
7285                 }
7286         }
7287
7288         /// <summary>
7289         ///   Expressions that represent an indexer call.
7290         /// </summary>
7291         public class IndexerAccess : Expression, IAssignMethod {
7292                 //
7293                 // Points to our "data" repository
7294                 //
7295                 MethodInfo get, set;
7296                 ArrayList set_arguments;
7297                 bool is_base_indexer;
7298
7299                 protected Type indexer_type;
7300                 protected Type current_type;
7301                 protected Expression instance_expr;
7302                 protected ArrayList arguments;
7303                 
7304                 public IndexerAccess (ElementAccess ea, Location loc)
7305                         : this (ea.Expr, false, loc)
7306                 {
7307                         this.arguments = ea.Arguments;
7308                 }
7309
7310                 protected IndexerAccess (Expression instance_expr, bool is_base_indexer,
7311                                          Location loc)
7312                 {
7313                         this.instance_expr = instance_expr;
7314                         this.is_base_indexer = is_base_indexer;
7315                         this.eclass = ExprClass.Value;
7316                         this.loc = loc;
7317                 }
7318
7319                 protected virtual bool CommonResolve (EmitContext ec)
7320                 {
7321                         indexer_type = instance_expr.Type;
7322                         current_type = ec.ContainerType;
7323
7324                         return true;
7325                 }
7326
7327                 public override Expression DoResolve (EmitContext ec)
7328                 {
7329                         ArrayList AllGetters = new ArrayList();
7330                         if (!CommonResolve (ec))
7331                                 return null;
7332
7333                         //
7334                         // Step 1: Query for all `Item' *properties*.  Notice
7335                         // that the actual methods are pointed from here.
7336                         //
7337                         // This is a group of properties, piles of them.  
7338
7339                         bool found_any = false, found_any_getters = false;
7340                         Type lookup_type = indexer_type;
7341
7342                         Indexers ilist;
7343                         ilist = Indexers.GetIndexersForType (current_type, lookup_type, loc);
7344                         if (ilist != null) {
7345                                 found_any = true;
7346                                 if (ilist.properties != null) {
7347                                         foreach (Pair o in ilist.properties) {
7348                                                 if (o.First != null)
7349                                                         AllGetters.Add(o.First);
7350                                         }
7351                                 }
7352                         }
7353
7354                         if (AllGetters.Count > 0) {
7355                                 found_any_getters = true;
7356                                 get = (MethodInfo) Invocation.OverloadResolve (
7357                                         ec, new MethodGroupExpr (AllGetters, loc), arguments, loc);
7358                         }
7359
7360                         if (!found_any) {
7361                                 Report.Error (21, loc,
7362                                               "Type `" + TypeManager.CSharpName (indexer_type) +
7363                                               "' does not have any indexers defined");
7364                                 return null;
7365                         }
7366
7367                         if (!found_any_getters) {
7368                                 Error (154, "indexer can not be used in this context, because " +
7369                                        "it lacks a `get' accessor");
7370                                 return null;
7371                         }
7372
7373                         if (get == null) {
7374                                 Error (1501, "No Overload for method `this' takes `" +
7375                                        arguments.Count + "' arguments");
7376                                 return null;
7377                         }
7378
7379                         //
7380                         // Only base will allow this invocation to happen.
7381                         //
7382                         if (get.IsAbstract && this is BaseIndexerAccess){
7383                                 Report.Error (205, loc, "Cannot call an abstract base indexer: " + Invocation.FullMethodDesc (get));
7384                                 return null;
7385                         }
7386
7387                         type = get.ReturnType;
7388                         if (type.IsPointer && !ec.InUnsafe){
7389                                 UnsafeError (loc);
7390                                 return null;
7391                         }
7392                         
7393                         eclass = ExprClass.IndexerAccess;
7394                         return this;
7395                 }
7396
7397                 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7398                 {
7399                         ArrayList AllSetters = new ArrayList();
7400                         if (!CommonResolve (ec))
7401                                 return null;
7402
7403                         Type right_type = right_side.Type;
7404
7405                         bool found_any = false, found_any_setters = false;
7406
7407                         Indexers ilist = Indexers.GetIndexersForType (current_type, indexer_type, loc);
7408                         if (ilist != null) {
7409                                 found_any = true;
7410                                 if (ilist.properties != null) {
7411                                         foreach (Pair o in ilist.properties) {
7412                                                 if (o.Second != null)
7413                                                         AllSetters.Add(o.Second);
7414                                         }
7415                                 }
7416                         }
7417                         if (AllSetters.Count > 0) {
7418                                 found_any_setters = true;
7419                                 set_arguments = (ArrayList) arguments.Clone ();
7420                                 set_arguments.Add (new Argument (right_side, Argument.AType.Expression));
7421                                 set = (MethodInfo) Invocation.OverloadResolve (
7422                                         ec, new MethodGroupExpr (AllSetters, loc),
7423                                         set_arguments, loc);
7424                         }
7425
7426                         if (!found_any) {
7427                                 Report.Error (21, loc,
7428                                               "Type `" + TypeManager.CSharpName (indexer_type) +
7429                                               "' does not have any indexers defined");
7430                                 return null;
7431                         }
7432
7433                         if (!found_any_setters) {
7434                                 Error (154, "indexer can not be used in this context, because " +
7435                                        "it lacks a `set' accessor");
7436                                 return null;
7437                         }
7438
7439                         if (set == null) {
7440                                 Error (1501, "No Overload for method `this' takes `" +
7441                                        arguments.Count + "' arguments");
7442                                 return null;
7443                         }
7444
7445                         //
7446                         // Only base will allow this invocation to happen.
7447                         //
7448                         if (set.IsAbstract && this is BaseIndexerAccess){
7449                                 Report.Error (205, loc, "Cannot call an abstract base indexer: " + Invocation.FullMethodDesc (set));
7450                                 return null;
7451                         }
7452
7453                         //
7454                         // Now look for the actual match in the list of indexers to set our "return" type
7455                         //
7456                         type = TypeManager.void_type;   // default value
7457                         foreach (Pair t in ilist.properties){
7458                                 if (t.Second == set){
7459                                         if (t.First != null)
7460                                                 type = ((MethodInfo) t.First).ReturnType;
7461                                         break;
7462                                 }
7463                         }
7464                         
7465                         eclass = ExprClass.IndexerAccess;
7466                         return this;
7467                 }
7468                 
7469                 public override void Emit (EmitContext ec)
7470                 {
7471                         Invocation.EmitCall (ec, is_base_indexer, false, instance_expr, get, arguments, loc);
7472                 }
7473
7474                 //
7475                 // source is ignored, because we already have a copy of it from the
7476                 // LValue resolution and we have already constructed a pre-cached
7477                 // version of the arguments (ea.set_arguments);
7478                 //
7479                 public void EmitAssign (EmitContext ec, Expression source)
7480                 {
7481                         Invocation.EmitCall (ec, is_base_indexer, false, instance_expr, set, set_arguments, loc);
7482                 }
7483         }
7484
7485         /// <summary>
7486         ///   The base operator for method names
7487         /// </summary>
7488         public class BaseAccess : Expression {
7489                 string member;
7490                 
7491                 public BaseAccess (string member, Location l)
7492                 {
7493                         this.member = member;
7494                         loc = l;
7495                 }
7496
7497                 public override Expression DoResolve (EmitContext ec)
7498                 {
7499                         Expression c = CommonResolve (ec);
7500
7501                         if (c == null)
7502                                 return null;
7503
7504                         //
7505                         // MethodGroups use this opportunity to flag an error on lacking ()
7506                         //
7507                         if (!(c is MethodGroupExpr))
7508                                 return c.Resolve (ec);
7509                         return c;
7510                 }
7511
7512                 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7513                 {
7514                         Expression c = CommonResolve (ec);
7515
7516                         if (c == null)
7517                                 return null;
7518
7519                         //
7520                         // MethodGroups use this opportunity to flag an error on lacking ()
7521                         //
7522                         if (! (c is MethodGroupExpr))
7523                                 return c.DoResolveLValue (ec, right_side);
7524
7525                         return c;
7526                 }
7527
7528                 Expression CommonResolve (EmitContext ec)
7529                 {
7530                         Expression member_lookup;
7531                         Type current_type = ec.ContainerType;
7532                         Type base_type = current_type.BaseType;
7533                         Expression e;
7534
7535                         if (ec.IsStatic){
7536                                 Error (1511, "Keyword base is not allowed in static method");
7537                                 return null;
7538                         }
7539                         
7540                         member_lookup = MemberLookup (ec, ec.ContainerType, null, base_type, member,
7541                                                       AllMemberTypes, AllBindingFlags, loc);
7542                         if (member_lookup == null) {
7543                                 MemberLookupFailed (ec, base_type, base_type, member, null, loc);
7544                                 return null;
7545                         }
7546
7547                         Expression left;
7548                         
7549                         if (ec.IsStatic)
7550                                 left = new TypeExpr (base_type, loc);
7551                         else
7552                                 left = ec.GetThis (loc);
7553                         
7554                         e = MemberAccess.ResolveMemberAccess (ec, member_lookup, left, loc, null);
7555
7556                         if (e is PropertyExpr){
7557                                 PropertyExpr pe = (PropertyExpr) e;
7558
7559                                 pe.IsBase = true;
7560                         }
7561
7562                         return e;
7563                 }
7564
7565                 public override void Emit (EmitContext ec)
7566                 {
7567                         throw new Exception ("Should never be called"); 
7568                 }
7569         }
7570
7571         /// <summary>
7572         ///   The base indexer operator
7573         /// </summary>
7574         public class BaseIndexerAccess : IndexerAccess {
7575                 public BaseIndexerAccess (ArrayList args, Location loc)
7576                         : base (null, true, loc)
7577                 {
7578                         arguments = new ArrayList ();
7579                         foreach (Expression tmp in args)
7580                                 arguments.Add (new Argument (tmp, Argument.AType.Expression));
7581                 }
7582
7583                 protected override bool CommonResolve (EmitContext ec)
7584                 {
7585                         instance_expr = ec.GetThis (loc);
7586
7587                         current_type = ec.ContainerType.BaseType;
7588                         indexer_type = current_type;
7589
7590                         foreach (Argument a in arguments){
7591                                 if (!a.Resolve (ec, loc))
7592                                         return false;
7593                         }
7594
7595                         return true;
7596                 }
7597         }
7598         
7599         /// <summary>
7600         ///   This class exists solely to pass the Type around and to be a dummy
7601         ///   that can be passed to the conversion functions (this is used by
7602         ///   foreach implementation to typecast the object return value from
7603         ///   get_Current into the proper type.  All code has been generated and
7604         ///   we only care about the side effect conversions to be performed
7605         ///
7606         ///   This is also now used as a placeholder where a no-action expression
7607         ///   is needed (the `New' class).
7608         /// </summary>
7609         public class EmptyExpression : Expression {
7610                 public EmptyExpression ()
7611                 {
7612                         type = TypeManager.object_type;
7613                         eclass = ExprClass.Value;
7614                         loc = Location.Null;
7615                 }
7616
7617                 public EmptyExpression (Type t)
7618                 {
7619                         type = t;
7620                         eclass = ExprClass.Value;
7621                         loc = Location.Null;
7622                 }
7623                 
7624                 public override Expression DoResolve (EmitContext ec)
7625                 {
7626                         return this;
7627                 }
7628
7629                 public override void Emit (EmitContext ec)
7630                 {
7631                         // nothing, as we only exist to not do anything.
7632                 }
7633
7634                 //
7635                 // This is just because we might want to reuse this bad boy
7636                 // instead of creating gazillions of EmptyExpressions.
7637                 // (CanImplicitConversion uses it)
7638                 //
7639                 public void SetType (Type t)
7640                 {
7641                         type = t;
7642                 }
7643         }
7644
7645         public class UserCast : Expression {
7646                 MethodBase method;
7647                 Expression source;
7648                 
7649                 public UserCast (MethodInfo method, Expression source, Location l)
7650                 {
7651                         this.method = method;
7652                         this.source = source;
7653                         type = method.ReturnType;
7654                         eclass = ExprClass.Value;
7655                         loc = l;
7656                 }
7657
7658                 public override Expression DoResolve (EmitContext ec)
7659                 {
7660                         //
7661                         // We are born fully resolved
7662                         //
7663                         return this;
7664                 }
7665
7666                 public override void Emit (EmitContext ec)
7667                 {
7668                         ILGenerator ig = ec.ig;
7669
7670                         source.Emit (ec);
7671                         
7672                         if (method is MethodInfo)
7673                                 ig.Emit (OpCodes.Call, (MethodInfo) method);
7674                         else
7675                                 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
7676
7677                 }
7678         }
7679
7680         // <summary>
7681         //   This class is used to "construct" the type during a typecast
7682         //   operation.  Since the Type.GetType class in .NET can parse
7683         //   the type specification, we just use this to construct the type
7684         //   one bit at a time.
7685         // </summary>
7686         public class ComposedCast : Expression {
7687                 Expression left;
7688                 string dim;
7689                 
7690                 public ComposedCast (Expression left, string dim, Location l)
7691                 {
7692                         this.left = left;
7693                         this.dim = dim;
7694                         loc = l;
7695                 }
7696
7697                 public override Expression ResolveAsTypeStep (EmitContext ec)
7698                 {
7699                         Type ltype = ec.DeclSpace.ResolveType (left, false, loc);
7700                         if (ltype == null)
7701                                 return null;
7702
7703                         //
7704                         // ltype.Fullname is already fully qualified, so we can skip
7705                         // a lot of probes, and go directly to TypeManager.LookupType
7706                         //
7707                         string cname = ltype.FullName + dim;
7708                         type = TypeManager.LookupTypeDirect (cname);
7709                         if (type == null){
7710                                 //
7711                                 // For arrays of enumerations we are having a problem
7712                                 // with the direct lookup.  Need to investigate.
7713                                 //
7714                                 // For now, fall back to the full lookup in that case.
7715                                 //
7716                                 type = RootContext.LookupType (
7717                                         ec.DeclSpace, cname, false, loc);
7718
7719                                 if (type == null)
7720                                         return null;
7721                         }
7722
7723                         if (!ec.ResolvingTypeTree){
7724                                 //
7725                                 // If the above flag is set, this is being invoked from the ResolveType function.
7726                                 // Upper layers take care of the type validity in this context.
7727                                 //
7728                         if (!ec.InUnsafe && type.IsPointer){
7729                                 UnsafeError (loc);
7730                                 return null;
7731                         }
7732                         }
7733                         
7734                         eclass = ExprClass.Type;
7735                         return this;
7736                 }
7737
7738                 public override Expression DoResolve (EmitContext ec)
7739                 {
7740                         return ResolveAsTypeStep (ec);
7741                 }
7742
7743                 public override void Emit (EmitContext ec)
7744                 {
7745                         throw new Exception ("This should never be called");
7746                 }
7747
7748                 public override string ToString ()
7749                 {
7750                         return left + dim;
7751                 }
7752         }
7753
7754         //
7755         // This class is used to represent the address of an array, used
7756         // only by the Fixed statement, this is like the C "&a [0]" construct.
7757         //
7758         public class ArrayPtr : Expression {
7759                 Expression array;
7760                 
7761                 public ArrayPtr (Expression array, Location l)
7762                 {
7763                         Type array_type = array.Type.GetElementType ();
7764
7765                         this.array = array;
7766
7767                         type = TypeManager.GetPointerType (array_type);
7768                         eclass = ExprClass.Value;
7769                         loc = l;
7770                 }
7771
7772                 public override void Emit (EmitContext ec)
7773                 {
7774                         ILGenerator ig = ec.ig;
7775                         
7776                         array.Emit (ec);
7777                         IntLiteral.EmitInt (ig, 0);
7778                         ig.Emit (OpCodes.Ldelema, array.Type.GetElementType ());
7779                 }
7780
7781                 public override Expression DoResolve (EmitContext ec)
7782                 {
7783                         //
7784                         // We are born fully resolved
7785                         //
7786                         return this;
7787                 }
7788         }
7789
7790         //
7791         // Used by the fixed statement
7792         //
7793         public class StringPtr : Expression {
7794                 LocalBuilder b;
7795                 
7796                 public StringPtr (LocalBuilder b, Location l)
7797                 {
7798                         this.b = b;
7799                         eclass = ExprClass.Value;
7800                         type = TypeManager.char_ptr_type;
7801                         loc = l;
7802                 }
7803
7804                 public override Expression DoResolve (EmitContext ec)
7805                 {
7806                         // This should never be invoked, we are born in fully
7807                         // initialized state.
7808
7809                         return this;
7810                 }
7811
7812                 public override void Emit (EmitContext ec)
7813                 {
7814                         ILGenerator ig = ec.ig;
7815
7816                         ig.Emit (OpCodes.Ldloc, b);
7817                         ig.Emit (OpCodes.Conv_I);
7818                         ig.Emit (OpCodes.Call, TypeManager.int_get_offset_to_string_data);
7819                         ig.Emit (OpCodes.Add);
7820                 }
7821         }
7822         
7823         //
7824         // Implements the `stackalloc' keyword
7825         //
7826         public class StackAlloc : Expression {
7827                 Type otype;
7828                 Expression t;
7829                 Expression count;
7830                 
7831                 public StackAlloc (Expression type, Expression count, Location l)
7832                 {
7833                         t = type;
7834                         this.count = count;
7835                         loc = l;
7836                 }
7837
7838                 public override Expression DoResolve (EmitContext ec)
7839                 {
7840                         count = count.Resolve (ec);
7841                         if (count == null)
7842                                 return null;
7843                         
7844                         if (count.Type != TypeManager.int32_type){
7845                                 count = Convert.ImplicitConversionRequired (ec, count, TypeManager.int32_type, loc);
7846                                 if (count == null)
7847                                         return null;
7848                         }
7849
7850                         if (ec.InCatch || ec.InFinally){
7851                                 Error (255,
7852                                               "stackalloc can not be used in a catch or finally block");
7853                                 return null;
7854                         }
7855
7856                         otype = ec.DeclSpace.ResolveType (t, false, loc);
7857
7858                         if (otype == null)
7859                                 return null;
7860
7861                         if (!TypeManager.VerifyUnManaged (otype, loc))
7862                                 return null;
7863
7864                         type = TypeManager.GetPointerType (otype);
7865                         eclass = ExprClass.Value;
7866
7867                         return this;
7868                 }
7869
7870                 public override void Emit (EmitContext ec)
7871                 {
7872                         int size = GetTypeSize (otype);
7873                         ILGenerator ig = ec.ig;
7874                                 
7875                         if (size == 0)
7876                                 ig.Emit (OpCodes.Sizeof, otype);
7877                         else
7878                                 IntConstant.EmitInt (ig, size);
7879                         count.Emit (ec);
7880                         ig.Emit (OpCodes.Mul);
7881                         ig.Emit (OpCodes.Localloc);
7882                 }
7883         }
7884 }