Initial import of the Generic MCS tree.
[mono.git] / mcs / gmcs / 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.GetElementType (expr.Type);
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 (TypeManager.GetElementType (t));
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 (TypeManager.GetElementType (op_type));
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 = TypeManager.GetElementType (t);
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 = TypeManager.GetElementType (ct);
4201
4202                                 if (best_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
4203                                         if (expanded_form)
4204                                                 bt = TypeManager.GetElementType (bt);
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 = TypeManager.GetElementType (pd.ParameterType (pd_count - 1));
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,
4411                                                                                        a.Expr, pd.ParameterType (i)))
4412                                                         return false;
4413                                         }
4414                                         
4415                                         if ((a_mod & Parameter.Modifier.ISBYREF) != 0) {
4416                                                 Type pt = pd.ParameterType (i);
4417
4418                                                 if (!pt.IsByRef)
4419                                                         pt = TypeManager.GetReferenceType (pt);
4420
4421                                                 if (pt != a.Type)
4422                                                         return false;
4423                                         }
4424                                 } else
4425                                         return false;
4426                         }
4427
4428                         return true;
4429                 }
4430                 
4431                 
4432
4433                 /// <summary>
4434                 ///   Find the Applicable Function Members (7.4.2.1)
4435                 ///
4436                 ///   me: Method Group expression with the members to select.
4437                 ///       it might contain constructors or methods (or anything
4438                 ///       that maps to a method).
4439                 ///
4440                 ///   Arguments: ArrayList containing resolved Argument objects.
4441                 ///
4442                 ///   loc: The location if we want an error to be reported, or a Null
4443                 ///        location for "probing" purposes.
4444                 ///
4445                 ///   Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
4446                 ///            that is the best match of me on Arguments.
4447                 ///
4448                 /// </summary>
4449                 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
4450                                                           ArrayList Arguments, Location loc)
4451                 {
4452                         MethodBase method = null;
4453                         Type applicable_type = null;
4454                         int argument_count;
4455                         ArrayList candidates = new ArrayList ();
4456
4457                         //
4458                         // First we construct the set of applicable methods
4459                         //
4460
4461                         //
4462                         // We start at the top of the type hierarchy and
4463                         // go down to find applicable methods
4464                         //
4465                         applicable_type = me.DeclaringType;
4466
4467                         bool found_applicable = false;
4468                         foreach (MethodBase candidate in me.Methods) {
4469                                 Type decl_type = candidate.DeclaringType;
4470
4471                                 //
4472                                 // If we have already found an applicable method
4473                                 // we eliminate all base types (Section 14.5.5.1)
4474                                 //
4475                                 if (decl_type != applicable_type &&
4476                                     (applicable_type.IsSubclassOf (decl_type) ||
4477                                      TypeManager.ImplementsInterface (applicable_type, decl_type)) &&
4478                                     found_applicable)
4479                                                 continue;
4480
4481
4482                                 // Check if candidate is applicable (section 14.4.2.1)
4483                                 if (!IsApplicable (ec, Arguments, candidate))
4484                                         continue;
4485
4486                                 
4487                                 candidates.Add (candidate);
4488                                 applicable_type = candidate.DeclaringType;
4489                                 found_applicable = true;
4490
4491                         }
4492
4493
4494                         //
4495                         // Now we actually find the best method
4496                         //
4497                         foreach (MethodBase candidate in candidates) {
4498                                 int x = BetterFunction (ec, Arguments, candidate, method, false, loc);
4499                                 
4500                                 if (x == 0)
4501                                         continue;
4502                                 
4503                                 method = candidate;
4504                         }
4505
4506
4507                         if (Arguments == null)
4508                                 argument_count = 0;
4509                         else
4510                                 argument_count = Arguments.Count;
4511                         
4512                         //
4513                         // Now we see if we can find params functions,
4514                         // applicable in their expanded form since if
4515                         // they were applicable in their normal form,
4516                         // they would have been selected above anyways
4517                         //
4518                         bool chose_params_expanded = false;
4519                         
4520                         if (method == null) {
4521                                 candidates = new ArrayList ();
4522                                 foreach (MethodBase candidate in me.Methods){
4523                                         if (!IsParamsMethodApplicable (ec, Arguments, candidate))
4524                                                 continue;
4525
4526                                         candidates.Add (candidate);
4527
4528                                         int x = BetterFunction (ec, Arguments, candidate, method, true, loc);
4529                                         if (x == 0)
4530                                                 continue;
4531
4532                                         method = candidate; 
4533                                         chose_params_expanded = true;
4534                                 }
4535                         }
4536
4537                         if (method == null) {
4538                                 //
4539                                 // Okay so we have failed to find anything so we
4540                                 // return by providing info about the closest match
4541                                 //
4542                                 for (int i = 0; i < me.Methods.Length; ++i) {
4543
4544                                         MethodBase c = (MethodBase) me.Methods [i];
4545                                         ParameterData pd = GetParameterData (c);
4546
4547                                         if (pd.Count != argument_count)
4548                                                 continue;
4549
4550                                         VerifyArgumentsCompat (ec, Arguments, argument_count, c, false,
4551                                                                null, loc);
4552                                 }
4553
4554                                 if (!Location.IsNull (loc)) {
4555                                         string report_name = me.Name;
4556                                         if (report_name == ".ctor")
4557                                                 report_name = me.DeclaringType.ToString ();
4558                                         
4559                                         Error_WrongNumArguments (loc, report_name, argument_count);
4560                                 }
4561                                 
4562                                 return null;
4563                         }
4564
4565                         //
4566                         // Now check that there are no ambiguities i.e the selected method
4567                         // should be better than all the others
4568                         //
4569
4570                         foreach (MethodBase candidate in candidates){
4571                                 if (candidate == method)
4572                                         continue;
4573
4574                                 //
4575                                 // If a normal method is applicable in
4576                                 // the sense that it has the same
4577                                 // number of arguments, then the
4578                                 // expanded params method is never
4579                                 // applicable so we debar the params
4580                                 // method.
4581                                 //
4582
4583                                 if (IsParamsMethodApplicable (ec, Arguments, candidate) &&
4584                                     IsApplicable (ec, Arguments, method))
4585                                         continue;
4586                                         
4587                                 int x = BetterFunction (ec, Arguments, method, candidate,
4588                                                         chose_params_expanded, loc);
4589
4590                                 if (x != 1) {
4591                                         Report.Error (
4592                                                 121, loc,
4593                                                 "Ambiguous call when selecting function due to implicit casts");
4594                                         return null;
4595                                 }
4596                         }
4597
4598                         //
4599                         // And now check if the arguments are all
4600                         // compatible, perform conversions if
4601                         // necessary etc. and return if everything is
4602                         // all right
4603                         //
4604
4605                         if (!VerifyArgumentsCompat (ec, Arguments, argument_count, method,
4606                                                    chose_params_expanded, null, loc))
4607                                 return null;
4608
4609                         return method;
4610                 }
4611
4612                 static void Error_WrongNumArguments (Location loc, String name, int arg_count)
4613                 {
4614                         Report.Error (1501, loc,
4615                                       "No overload for method `" + name + "' takes `" +
4616                                       arg_count + "' arguments");
4617                 }
4618
4619                 static void Error_InvalidArguments (Location loc, int idx, MethodBase method,
4620                                                     Type delegate_type, string arg_sig, string par_desc)
4621                 {
4622                         if (delegate_type == null) 
4623                                 Report.Error (1502, loc,
4624                                               "The best overloaded match for method '" +
4625                                               FullMethodDesc (method) +
4626                                               "' has some invalid arguments");
4627                         else
4628                                 Report.Error (1594, loc,
4629                                               "Delegate '" + delegate_type.ToString () +
4630                                               "' has some invalid arguments.");
4631                         Report.Error (1503, loc,
4632                                       String.Format ("Argument {0}: Cannot convert from '{1}' to '{2}'",
4633                                                      idx, arg_sig, par_desc));
4634                 }
4635                 
4636                 public static bool VerifyArgumentsCompat (EmitContext ec, ArrayList Arguments,
4637                                                           int argument_count,
4638                                                           MethodBase method, 
4639                                                           bool chose_params_expanded,
4640                                                           Type delegate_type,
4641                                                           Location loc)
4642                 {
4643                         ParameterData pd = GetParameterData (method);
4644                         int pd_count = pd.Count;
4645                         
4646                         for (int j = 0; j < argument_count; j++) {
4647                                 Argument a = (Argument) Arguments [j];
4648                                 Expression a_expr = a.Expr;
4649                                 Type parameter_type = pd.ParameterType (j);
4650                                 Parameter.Modifier pm = pd.ParameterModifier (j);
4651                                 
4652                                 if (pm == Parameter.Modifier.PARAMS){
4653                                         Parameter.Modifier am = a.GetParameterModifier ();
4654
4655                                         if ((pm & ~Parameter.Modifier.PARAMS) != a.GetParameterModifier ()) {
4656                                                 if (!Location.IsNull (loc))
4657                                                         Error_InvalidArguments (
4658                                                                 loc, j, method, delegate_type,
4659                                                                 Argument.FullDesc (a), pd.ParameterDesc (j));
4660                                                 return false;
4661                                         }
4662
4663                                         if (chose_params_expanded)
4664                                                 parameter_type = TypeManager.GetElementType (parameter_type);
4665                                 } else {
4666                                         //
4667                                         // Check modifiers
4668                                         //
4669                                         if (pd.ParameterModifier (j) != a.GetParameterModifier ()){
4670                                                 if (!Location.IsNull (loc))
4671                                                         Error_InvalidArguments (
4672                                                                 loc, j, method, delegate_type,
4673                                                                 Argument.FullDesc (a), pd.ParameterDesc (j));
4674                                                 return false;
4675                                         }
4676                                 }
4677
4678                                 //
4679                                 // Check Type
4680                                 //
4681                                 if (a.Type != parameter_type){
4682                                         Expression conv;
4683                                         
4684                                         conv = Convert.ImplicitConversion (ec, a_expr, parameter_type, loc);
4685
4686                                         if (conv == null) {
4687                                                 Console.WriteLine ("GAA: {0} {1} {2}",
4688                                                                    pd.ParameterType (j),
4689                                                                    pd.ParameterType (j).Assembly == CodeGen.AssemblyBuilder,
4690                                                                    method.DeclaringType.Assembly == CodeGen.AssemblyBuilder);
4691
4692                                                 if (!Location.IsNull (loc)) 
4693                                                         Error_InvalidArguments (
4694                                                                 loc, j, method, delegate_type,
4695                                                                 Argument.FullDesc (a), pd.ParameterDesc (j));
4696                                                 return false;
4697                                         }
4698                                         
4699                                         //
4700                                         // Update the argument with the implicit conversion
4701                                         //
4702                                         if (a_expr != conv)
4703                                                 a.Expr = conv;
4704                                 }
4705
4706                                 Parameter.Modifier a_mod = a.GetParameterModifier () &
4707                                         ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4708                                 Parameter.Modifier p_mod = pd.ParameterModifier (j) &
4709                                         ~(Parameter.Modifier.OUT | Parameter.Modifier.REF);
4710                                 
4711                                 if (a_mod != p_mod &&
4712                                     pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS) {
4713                                         if (!Location.IsNull (loc)) {
4714                                                 Console.WriteLine ("A:P: " + a.GetParameterModifier ());
4715                                                 Console.WriteLine ("PP:: " + pd.ParameterModifier (j));
4716                                                 Console.WriteLine ("PT:  " + parameter_type.IsByRef);
4717                                                 Report.Error (1502, loc,
4718                                                        "The best overloaded match for method '" + FullMethodDesc (method)+
4719                                                        "' has some invalid arguments");
4720                                                 Report.Error (1503, loc,
4721                                                        "Argument " + (j+1) +
4722                                                        ": Cannot convert from '" + Argument.FullDesc (a) 
4723                                                        + "' to '" + pd.ParameterDesc (j) + "'");
4724                                         }
4725                                         
4726                                         return false;
4727                                 }
4728                         }
4729
4730                         return true;
4731                 }
4732
4733                 public override Expression DoResolve (EmitContext ec)
4734                 {
4735                         //
4736                         // First, resolve the expression that is used to
4737                         // trigger the invocation
4738                         //
4739                         if (expr is BaseAccess)
4740                                 is_base = true;
4741
4742                         Expression old = expr;
4743                         
4744                         expr = expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
4745                         if (expr == null)
4746                                 return null;
4747
4748                         if (!(expr is MethodGroupExpr)) {
4749                                 Type expr_type = expr.Type;
4750
4751                                 if (expr_type != null){
4752                                         bool IsDelegate = TypeManager.IsDelegateType (expr_type);
4753                                         if (IsDelegate)
4754                                                 return (new DelegateInvocation (
4755                                                         this.expr, Arguments, loc)).Resolve (ec);
4756                                 }
4757                         }
4758
4759                         if (!(expr is MethodGroupExpr)){
4760                                 expr.Error_UnexpectedKind (ResolveFlags.MethodGroup);
4761                                 return null;
4762                         }
4763
4764                         //
4765                         // Next, evaluate all the expressions in the argument list
4766                         //
4767                         if (Arguments != null){
4768                                 foreach (Argument a in Arguments){
4769                                         if (!a.Resolve (ec, loc))
4770                                                 return null;
4771                                 }
4772                         }
4773
4774                         MethodGroupExpr mg = (MethodGroupExpr) expr;
4775                         method = OverloadResolve (ec, mg, Arguments, loc);
4776
4777                         if (method == null){
4778                                 Error (-6,
4779                                        "Could not find any applicable function for this argument list");
4780                                 return null;
4781                         }
4782
4783                         MethodInfo mi = method as MethodInfo;
4784                         if (mi != null) {
4785                                 type = TypeManager.TypeToCoreType (mi.ReturnType);
4786                                 if (!mi.IsStatic && !mg.IsExplicitImpl && (mg.InstanceExpression == null))
4787                                         SimpleName.Error_ObjectRefRequired (ec, loc, mi.Name);
4788                         }
4789
4790                         if (type.IsPointer){
4791                                 if (!ec.InUnsafe){
4792                                         UnsafeError (loc);
4793                                         return null;
4794                                 }
4795                         }
4796                         
4797                         //
4798                         // Only base will allow this invocation to happen.
4799                         //
4800                         if (is_base && method.IsAbstract){
4801                                 Report.Error (205, loc, "Cannot call an abstract base member: " +
4802                                               FullMethodDesc (method));
4803                                 return null;
4804                         }
4805
4806                         if ((method.Attributes & MethodAttributes.SpecialName) != 0){
4807                                 if (TypeManager.IsSpecialMethod (method))
4808                                         Report.Error (571, loc, method.Name + ": can not call operator or accessor");
4809                         }
4810                         
4811                         eclass = ExprClass.Value;
4812                         return this;
4813                 }
4814
4815                 // <summary>
4816                 //   Emits the list of arguments as an array
4817                 // </summary>
4818                 static void EmitParams (EmitContext ec, int idx, ArrayList arguments)
4819                 {
4820                         ILGenerator ig = ec.ig;
4821                         int count = arguments.Count - idx;
4822                         Argument a = (Argument) arguments [idx];
4823                         Type t = a.Expr.Type;
4824                         string array_type = t.FullName + "[]";
4825                         LocalBuilder array;
4826
4827                         array = ig.DeclareLocal (TypeManager.LookupType (array_type));
4828                         IntConstant.EmitInt (ig, count);
4829                         ig.Emit (OpCodes.Newarr, TypeManager.TypeToCoreType (t));
4830                         ig.Emit (OpCodes.Stloc, array);
4831
4832                         int top = arguments.Count;
4833                         for (int j = idx; j < top; j++){
4834                                 a = (Argument) arguments [j];
4835                                 
4836                                 ig.Emit (OpCodes.Ldloc, array);
4837                                 IntConstant.EmitInt (ig, j - idx);
4838
4839                                 bool is_stobj;
4840                                 OpCode op = ArrayAccess.GetStoreOpcode (t, out is_stobj);
4841                                 if (is_stobj)
4842                                         ig.Emit (OpCodes.Ldelema, t);
4843
4844                                 a.Emit (ec);
4845
4846                                 if (is_stobj)
4847                                         ig.Emit (OpCodes.Stobj, t);
4848                                 else
4849                                         ig.Emit (op);
4850                         }
4851                         ig.Emit (OpCodes.Ldloc, array);
4852                 }
4853                 
4854                 /// <summary>
4855                 ///   Emits a list of resolved Arguments that are in the arguments
4856                 ///   ArrayList.
4857                 /// 
4858                 ///   The MethodBase argument might be null if the
4859                 ///   emission of the arguments is known not to contain
4860                 ///   a `params' field (for example in constructors or other routines
4861                 ///   that keep their arguments in this structure)
4862                 /// </summary>
4863                 public static void EmitArguments (EmitContext ec, MethodBase mb, ArrayList arguments)
4864                 {
4865                         ParameterData pd;
4866                         if (mb != null)
4867                                 pd = GetParameterData (mb);
4868                         else
4869                                 pd = null;
4870
4871                         //
4872                         // If we are calling a params method with no arguments, special case it
4873                         //
4874                         if (arguments == null){
4875                                 if (pd != null && pd.Count > 0 &&
4876                                     pd.ParameterModifier (0) == Parameter.Modifier.PARAMS){
4877                                         ILGenerator ig = ec.ig;
4878
4879                                         IntConstant.EmitInt (ig, 0);
4880                                         ig.Emit (OpCodes.Newarr, TypeManager.GetElementType (pd.ParameterType (0)));
4881                                 }
4882
4883                                 return;
4884                         }
4885
4886                         int top = arguments.Count;
4887
4888                         for (int i = 0; i < top; i++){
4889                                 Argument a = (Argument) arguments [i];
4890
4891                                 if (pd != null){
4892                                         if (pd.ParameterModifier (i) == Parameter.Modifier.PARAMS){
4893                                                 //
4894                                                 // Special case if we are passing the same data as the
4895                                                 // params argument, do not put it in an array.
4896                                                 //
4897                                                 if (pd.ParameterType (i) == a.Type)
4898                                                         a.Emit (ec);
4899                                                 else
4900                                                         EmitParams (ec, i, arguments);
4901                                                 return;
4902                                         }
4903                                 }
4904                                             
4905                                 a.Emit (ec);
4906                         }
4907
4908                         if (pd != null && pd.Count > top &&
4909                             pd.ParameterModifier (top) == Parameter.Modifier.PARAMS){
4910                                 ILGenerator ig = ec.ig;
4911
4912                                 IntConstant.EmitInt (ig, 0);
4913                                 ig.Emit (OpCodes.Newarr, TypeManager.GetElementType (pd.ParameterType (top)));
4914                         }
4915                 }
4916
4917                 /// <remarks>
4918                 ///   is_base tells whether we want to force the use of the `call'
4919                 ///   opcode instead of using callvirt.  Call is required to call
4920                 ///   a specific method, while callvirt will always use the most
4921                 ///   recent method in the vtable.
4922                 ///
4923                 ///   is_static tells whether this is an invocation on a static method
4924                 ///
4925                 ///   instance_expr is an expression that represents the instance
4926                 ///   it must be non-null if is_static is false.
4927                 ///
4928                 ///   method is the method to invoke.
4929                 ///
4930                 ///   Arguments is the list of arguments to pass to the method or constructor.
4931                 /// </remarks>
4932                 public static void EmitCall (EmitContext ec, bool is_base,
4933                                              bool is_static, Expression instance_expr,
4934                                              MethodBase method, ArrayList Arguments, Location loc)
4935                 {
4936                         ILGenerator ig = ec.ig;
4937                         bool struct_call = false;
4938
4939                         Type decl_type = method.DeclaringType;
4940
4941                         if (!RootContext.StdLib) {
4942                                 // Replace any calls to the system's System.Array type with calls to
4943                                 // the newly created one.
4944                                 if (method == TypeManager.system_int_array_get_length)
4945                                         method = TypeManager.int_array_get_length;
4946                                 else if (method == TypeManager.system_int_array_get_rank)
4947                                         method = TypeManager.int_array_get_rank;
4948                                 else if (method == TypeManager.system_object_array_clone)
4949                                         method = TypeManager.object_array_clone;
4950                                 else if (method == TypeManager.system_int_array_get_length_int)
4951                                         method = TypeManager.int_array_get_length_int;
4952                                 else if (method == TypeManager.system_int_array_get_lower_bound_int)
4953                                         method = TypeManager.int_array_get_lower_bound_int;
4954                                 else if (method == TypeManager.system_int_array_get_upper_bound_int)
4955                                         method = TypeManager.int_array_get_upper_bound_int;
4956                                 else if (method == TypeManager.system_void_array_copyto_array_int)
4957                                         method = TypeManager.void_array_copyto_array_int;
4958                         }
4959
4960                         //
4961                         // This checks the `ConditionalAttribute' on the method, and the
4962                         // ObsoleteAttribute
4963                         //
4964                         TypeManager.MethodFlags flags = TypeManager.GetMethodFlags (method, loc);
4965                         if ((flags & TypeManager.MethodFlags.IsObsoleteError) != 0)
4966                                 return;
4967                         if ((flags & TypeManager.MethodFlags.ShouldIgnore) != 0)
4968                                 return;
4969                         
4970                         if (!is_static){
4971                                 if (decl_type.IsValueType)
4972                                         struct_call = true;
4973                                 //
4974                                 // If this is ourselves, push "this"
4975                                 //
4976                                 if (instance_expr == null){
4977                                         ig.Emit (OpCodes.Ldarg_0);
4978                                 } else {
4979                                         //
4980                                         // Push the instance expression
4981                                         //
4982                                         if (instance_expr.Type.IsValueType){
4983                                                 //
4984                                                 // Special case: calls to a function declared in a 
4985                                                 // reference-type with a value-type argument need
4986                                                 // to have their value boxed.  
4987
4988                                                 struct_call = true;
4989                                                 if (decl_type.IsValueType){
4990                                                         //
4991                                                         // If the expression implements IMemoryLocation, then
4992                                                         // we can optimize and use AddressOf on the
4993                                                         // return.
4994                                                         //
4995                                                         // If not we have to use some temporary storage for
4996                                                         // it.
4997                                                         if (instance_expr is IMemoryLocation){
4998                                                                 ((IMemoryLocation)instance_expr).
4999                                                                         AddressOf (ec, AddressOp.LoadStore);
5000                                                         }
5001                                                         else {
5002                                                                 Type t = instance_expr.Type;
5003                                                                 
5004                                                                 instance_expr.Emit (ec);
5005                                                                 LocalBuilder temp = ig.DeclareLocal (t);
5006                                                                 ig.Emit (OpCodes.Stloc, temp);
5007                                                                 ig.Emit (OpCodes.Ldloca, temp);
5008                                                         }
5009                                                 } else {
5010                                                         instance_expr.Emit (ec);
5011                                                         ig.Emit (OpCodes.Box, instance_expr.Type);
5012                                                 } 
5013                                         } else
5014                                                 instance_expr.Emit (ec);
5015                                 }
5016                         }
5017
5018                         EmitArguments (ec, method, Arguments);
5019
5020                         if (is_static || struct_call || is_base){
5021                                 if (method is MethodInfo) {
5022                                         ig.Emit (OpCodes.Call, (MethodInfo) method);
5023                                 } else
5024                                         ig.Emit (OpCodes.Call, (ConstructorInfo) method);
5025                         } else {
5026                                 if (method is MethodInfo)
5027                                         ig.Emit (OpCodes.Callvirt, (MethodInfo) method);
5028                                 else
5029                                         ig.Emit (OpCodes.Callvirt, (ConstructorInfo) method);
5030                         }
5031                 }
5032                 
5033                 public override void Emit (EmitContext ec)
5034                 {
5035                         MethodGroupExpr mg = (MethodGroupExpr) this.expr;
5036
5037                         EmitCall (ec, is_base, method.IsStatic, mg.InstanceExpression, method, Arguments, loc);
5038                 }
5039                 
5040                 public override void EmitStatement (EmitContext ec)
5041                 {
5042                         Emit (ec);
5043
5044                         // 
5045                         // Pop the return value if there is one
5046                         //
5047                         if (method is MethodInfo){
5048                                 Type ret = ((MethodInfo)method).ReturnType;
5049                                 if (TypeManager.TypeToCoreType (ret) != TypeManager.void_type)
5050                                         ec.ig.Emit (OpCodes.Pop);
5051                         }
5052                 }
5053         }
5054
5055         public class InvocationOrCast : ExpressionStatement
5056         {
5057                 Expression expr;
5058                 Expression argument;
5059
5060                 public InvocationOrCast (Expression expr, Expression argument, Location loc)
5061                 {
5062                         this.expr = expr;
5063                         this.argument = argument;
5064                         this.loc = loc;
5065                 }
5066
5067                 public override Expression DoResolve (EmitContext ec)
5068                 {
5069                         //
5070                         // First try to resolve it as a cast.
5071                         //
5072                         type = ec.DeclSpace.ResolveType (expr, true, loc);
5073                         if (type != null) {
5074                                 Cast cast = new Cast (new TypeExpr (type, loc), argument, loc);
5075                                 return cast.Resolve (ec);
5076                         }
5077
5078                         //
5079                         // This can either be a type or a delegate invocation.
5080                         // Let's just resolve it and see what we'll get.
5081                         //
5082                         expr = expr.Resolve (ec, ResolveFlags.Type | ResolveFlags.VariableOrValue);
5083                         if (expr == null)
5084                                 return null;
5085
5086                         //
5087                         // Ok, so it's a Cast.
5088                         //
5089                         if (expr.eclass == ExprClass.Type) {
5090                                 Cast cast = new Cast (new TypeExpr (expr.Type, loc), argument, loc);
5091                                 return cast.Resolve (ec);
5092                         }
5093
5094                         //
5095                         // It's a delegate invocation.
5096                         //
5097                         if (!TypeManager.IsDelegateType (expr.Type)) {
5098                                 Error (149, "Method name expected");
5099                                 return null;
5100                         }
5101
5102                         ArrayList args = new ArrayList ();
5103                         args.Add (new Argument (argument, Argument.AType.Expression));
5104                         DelegateInvocation invocation = new DelegateInvocation (expr, args, loc);
5105                         return invocation.Resolve (ec);
5106                 }
5107
5108                 void error201 ()
5109                 {
5110                         Error (201, "Only assignment, call, increment, decrement and new object " +
5111                                "expressions can be used as a statement");
5112                 }
5113
5114                 public override ExpressionStatement ResolveStatement (EmitContext ec)
5115                 {
5116                         //
5117                         // First try to resolve it as a cast.
5118                         //
5119                         type = ec.DeclSpace.ResolveType (expr, true, loc);
5120                         if (type != null) {
5121                                 error201 ();
5122                                 return null;
5123                         }
5124
5125                         //
5126                         // This can either be a type or a delegate invocation.
5127                         // Let's just resolve it and see what we'll get.
5128                         //
5129                         expr = expr.Resolve (ec, ResolveFlags.Type | ResolveFlags.VariableOrValue);
5130                         if ((expr == null) || (expr.eclass == ExprClass.Type)) {
5131                                 error201 ();
5132                                 return null;
5133                         }
5134
5135                         //
5136                         // It's a delegate invocation.
5137                         //
5138                         if (!TypeManager.IsDelegateType (expr.Type)) {
5139                                 Error (149, "Method name expected");
5140                                 return null;
5141                         }
5142
5143                         ArrayList args = new ArrayList ();
5144                         args.Add (new Argument (argument, Argument.AType.Expression));
5145                         DelegateInvocation invocation = new DelegateInvocation (expr, args, loc);
5146                         return invocation.ResolveStatement (ec);
5147                 }
5148
5149                 public override void Emit (EmitContext ec)
5150                 {
5151                         throw new Exception ("Cannot happen");
5152                 }
5153
5154                 public override void EmitStatement (EmitContext ec)
5155                 {
5156                         throw new Exception ("Cannot happen");
5157                 }
5158         }
5159
5160         //
5161         // This class is used to "disable" the code generation for the
5162         // temporary variable when initializing value types.
5163         //
5164         class EmptyAddressOf : EmptyExpression, IMemoryLocation {
5165                 public void AddressOf (EmitContext ec, AddressOp Mode)
5166                 {
5167                         // nothing
5168                 }
5169         }
5170         
5171         /// <summary>
5172         ///    Implements the new expression 
5173         /// </summary>
5174         public class New : ExpressionStatement, IMemoryLocation {
5175                 public readonly ArrayList Arguments;
5176                 public readonly Expression RequestedType;
5177
5178                 MethodBase method = null;
5179
5180                 //
5181                 // If set, the new expression is for a value_target, and
5182                 // we will not leave anything on the stack.
5183                 //
5184                 Expression value_target;
5185                 bool value_target_set = false;
5186                 
5187                 public New (Expression requested_type, ArrayList arguments, Location l)
5188                 {
5189                         RequestedType = requested_type;
5190                         Arguments = arguments;
5191                         loc = l;
5192                 }
5193
5194                 public bool SetValueTypeVariable (Expression value)
5195                 {
5196                         value_target = value;
5197                         value_target_set = true;
5198                         if (!(value_target is IMemoryLocation)){
5199                                 Error_UnexpectedKind ("variable");
5200                                 return false;
5201                         }
5202                         return true;
5203                 }
5204
5205                 //
5206                 // This function is used to disable the following code sequence for
5207                 // value type initialization:
5208                 //
5209                 // AddressOf (temporary)
5210                 // Construct/Init
5211                 // LoadTemporary
5212                 //
5213                 // Instead the provide will have provided us with the address on the
5214                 // stack to store the results.
5215                 //
5216                 static Expression MyEmptyExpression;
5217                 
5218                 public void DisableTemporaryValueType ()
5219                 {
5220                         if (MyEmptyExpression == null)
5221                                 MyEmptyExpression = new EmptyAddressOf ();
5222
5223                         //
5224                         // To enable this, look into:
5225                         // test-34 and test-89 and self bootstrapping.
5226                         //
5227                         // For instance, we can avoid a copy by using `newobj'
5228                         // instead of Call + Push-temp on value types.
5229 //                      value_target = MyEmptyExpression;
5230                 }
5231
5232                 public override Expression DoResolve (EmitContext ec)
5233                 {
5234                         //
5235                         // The New DoResolve might be called twice when initializing field
5236                         // expressions (see EmitFieldInitializers, the call to
5237                         // GetInitializerExpression will perform a resolve on the expression,
5238                         // and later the assign will trigger another resolution
5239                         //
5240                         // This leads to bugs (#37014)
5241                         //
5242                         if (type != null)
5243                                 return this;
5244                         
5245                         type = ec.DeclSpace.ResolveType (RequestedType, false, loc);
5246                         
5247                         if (type == null)
5248                                 return null;
5249                         
5250                         bool IsDelegate = TypeManager.IsDelegateType (type);
5251                         
5252                         if (IsDelegate)
5253                                 return (new NewDelegate (type, Arguments, loc)).Resolve (ec);
5254
5255                         if (type.IsInterface || type.IsAbstract){
5256                                 Error (144, "It is not possible to create instances of interfaces or abstract classes");
5257                                 return null;
5258                         }
5259                         
5260                         bool is_struct = type.IsValueType;
5261                         eclass = ExprClass.Value;
5262
5263                         //
5264                         // SRE returns a match for .ctor () on structs (the object constructor), 
5265                         // so we have to manually ignore it.
5266                         //
5267                         if (is_struct && Arguments == null)
5268                                 return this;
5269                         
5270                         Expression ml;
5271                         ml = MemberLookupFinal (ec, null, type, ".ctor",
5272                                                 MemberTypes.Constructor,
5273                                                 AllBindingFlags | BindingFlags.DeclaredOnly, loc);
5274
5275                         if (ml == null)
5276                                 return null;
5277                         
5278                         if (! (ml is MethodGroupExpr)){
5279                                 if (!is_struct){
5280                                         ml.Error_UnexpectedKind ("method group");
5281                                         return null;
5282                                 }
5283                         }
5284
5285                         if (ml != null) {
5286                                 if (Arguments != null){
5287                                         foreach (Argument a in Arguments){
5288                                                 if (!a.Resolve (ec, loc))
5289                                                         return null;
5290                                         }
5291                                 }
5292
5293                                 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml, Arguments, loc);
5294                                 
5295                         }
5296
5297                         if (method == null) { 
5298                                 if (!is_struct || Arguments.Count > 0) {
5299                                         Error (1501, String.Format (
5300                                             "New invocation: Can not find a constructor in `{0}' for this argument list",
5301                                             TypeManager.CSharpName (type)));
5302                                         return null;
5303                                 }
5304                         }
5305
5306                         return this;
5307                 }
5308
5309                 //
5310                 // This DoEmit can be invoked in two contexts:
5311                 //    * As a mechanism that will leave a value on the stack (new object)
5312                 //    * As one that wont (init struct)
5313                 //
5314                 // You can control whether a value is required on the stack by passing
5315                 // need_value_on_stack.  The code *might* leave a value on the stack
5316                 // so it must be popped manually
5317                 //
5318                 // If we are dealing with a ValueType, we have a few
5319                 // situations to deal with:
5320                 //
5321                 //    * The target is a ValueType, and we have been provided
5322                 //      the instance (this is easy, we are being assigned).
5323                 //
5324                 //    * The target of New is being passed as an argument,
5325                 //      to a boxing operation or a function that takes a
5326                 //      ValueType.
5327                 //
5328                 //      In this case, we need to create a temporary variable
5329                 //      that is the argument of New.
5330                 //
5331                 // Returns whether a value is left on the stack
5332                 //
5333                 bool DoEmit (EmitContext ec, bool need_value_on_stack)
5334                 {
5335                         bool is_value_type = type.IsValueType;
5336                         ILGenerator ig = ec.ig;
5337
5338                         if (is_value_type){
5339                                 IMemoryLocation ml;
5340
5341                                 // Allow DoEmit() to be called multiple times.
5342                                 // We need to create a new LocalTemporary each time since
5343                                 // you can't share LocalBuilders among ILGeneators.
5344                                 if (!value_target_set)
5345                                         value_target = new LocalTemporary (ec, type);
5346
5347                                 ml = (IMemoryLocation) value_target;
5348                                 ml.AddressOf (ec, AddressOp.Store);
5349                         }
5350
5351                         if (method != null)
5352                                 Invocation.EmitArguments (ec, method, Arguments);
5353
5354                         if (is_value_type){
5355                                 if (method == null)
5356                                         ig.Emit (OpCodes.Initobj, type);
5357                                 else 
5358                                         ig.Emit (OpCodes.Call, (ConstructorInfo) method);
5359                                 if (need_value_on_stack){
5360                                         value_target.Emit (ec);
5361                                         return true;
5362                                 }
5363                                 return false;
5364                         } else {
5365                                 ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
5366                                 return true;
5367                         }
5368                 }
5369
5370                 public override void Emit (EmitContext ec)
5371                 {
5372                         DoEmit (ec, true);
5373                 }
5374                 
5375                 public override void EmitStatement (EmitContext ec)
5376                 {
5377                         if (DoEmit (ec, false))
5378                                 ec.ig.Emit (OpCodes.Pop);
5379                 }
5380
5381                 public void AddressOf (EmitContext ec, AddressOp Mode)
5382                 {
5383                         if (!type.IsValueType){
5384                                 //
5385                                 // We throw an exception.  So far, I believe we only need to support
5386                                 // value types:
5387                                 // foreach (int j in new StructType ())
5388                                 // see bug 42390
5389                                 //
5390                                 throw new Exception ("AddressOf should not be used for classes");
5391                         }
5392
5393                         if (!value_target_set)
5394                                 value_target = new LocalTemporary (ec, type);
5395                                         
5396                         IMemoryLocation ml = (IMemoryLocation) value_target;
5397                         ml.AddressOf (ec, AddressOp.Store);
5398                         if (method != null)
5399                                 Invocation.EmitArguments (ec, method, Arguments);
5400
5401                         if (method == null)
5402                                 ec.ig.Emit (OpCodes.Initobj, type);
5403                         else 
5404                                 ec.ig.Emit (OpCodes.Call, (ConstructorInfo) method);
5405                         
5406                         ((IMemoryLocation) value_target).AddressOf (ec, Mode);
5407                 }
5408         }
5409
5410         /// <summary>
5411         ///   14.5.10.2: Represents an array creation expression.
5412         /// </summary>
5413         ///
5414         /// <remarks>
5415         ///   There are two possible scenarios here: one is an array creation
5416         ///   expression that specifies the dimensions and optionally the
5417         ///   initialization data and the other which does not need dimensions
5418         ///   specified but where initialization data is mandatory.
5419         /// </remarks>
5420         public class ArrayCreation : ExpressionStatement {
5421                 Expression requested_base_type;
5422                 ArrayList initializers;
5423
5424                 //
5425                 // The list of Argument types.
5426                 // This is used to construct the `newarray' or constructor signature
5427                 //
5428                 ArrayList arguments;
5429
5430                 //
5431                 // Method used to create the array object.
5432                 //
5433                 MethodBase new_method = null;
5434                 
5435                 Type array_element_type;
5436                 Type underlying_type;
5437                 bool is_one_dimensional = false;
5438                 bool is_builtin_type = false;
5439                 bool expect_initializers = false;
5440                 int num_arguments = 0;
5441                 int dimensions = 0;
5442                 string rank;
5443
5444                 ArrayList array_data;
5445
5446                 Hashtable bounds;
5447
5448                 //
5449                 // The number of array initializers that we can handle
5450                 // via the InitializeArray method - through EmitStaticInitializers
5451                 //
5452                 int num_automatic_initializers;
5453
5454                 const int max_automatic_initializers = 6;
5455                 
5456                 public ArrayCreation (Expression requested_base_type, ArrayList exprs, string rank, ArrayList initializers, Location l)
5457                 {
5458                         this.requested_base_type = requested_base_type;
5459                         this.initializers = initializers;
5460                         this.rank = rank;
5461                         loc = l;
5462
5463                         arguments = new ArrayList ();
5464
5465                         foreach (Expression e in exprs) {
5466                                 arguments.Add (new Argument (e, Argument.AType.Expression));
5467                                 num_arguments++;
5468                         }
5469                 }
5470
5471                 public ArrayCreation (Expression requested_base_type, string rank, ArrayList initializers, Location l)
5472                 {
5473                         this.requested_base_type = requested_base_type;
5474                         this.initializers = initializers;
5475                         this.rank = rank;
5476                         loc = l;
5477
5478                         //this.rank = rank.Substring (0, rank.LastIndexOf ("["));
5479                         //
5480                         //string tmp = rank.Substring (rank.LastIndexOf ("["));
5481                         //
5482                         //dimensions = tmp.Length - 1;
5483                         expect_initializers = true;
5484                 }
5485
5486                 public Expression FormArrayType (Expression base_type, int idx_count, string rank)
5487                 {
5488                         StringBuilder sb = new StringBuilder (rank);
5489                         
5490                         sb.Append ("[");
5491                         for (int i = 1; i < idx_count; i++)
5492                                 sb.Append (",");
5493                         
5494                         sb.Append ("]");
5495
5496                         return new ComposedCast (base_type, sb.ToString (), loc);
5497                 }
5498
5499                 void Error_IncorrectArrayInitializer ()
5500                 {
5501                         Error (178, "Incorrectly structured array initializer");
5502                 }
5503                 
5504                 public bool CheckIndices (EmitContext ec, ArrayList probe, int idx, bool specified_dims)
5505                 {
5506                         if (specified_dims) { 
5507                                 Argument a = (Argument) arguments [idx];
5508                                 
5509                                 if (!a.Resolve (ec, loc))
5510                                         return false;
5511                                 
5512                                 if (!(a.Expr is Constant)) {
5513                                         Error (150, "A constant value is expected");
5514                                         return false;
5515                                 }
5516                                 
5517                                 int value = (int) ((Constant) a.Expr).GetValue ();
5518                                 
5519                                 if (value != probe.Count) {
5520                                         Error_IncorrectArrayInitializer ();
5521                                         return false;
5522                                 }
5523                                 
5524                                 bounds [idx] = value;
5525                         }
5526
5527                         int child_bounds = -1;
5528                         foreach (object o in probe) {
5529                                 if (o is ArrayList) {
5530                                         int current_bounds = ((ArrayList) o).Count;
5531                                         
5532                                         if (child_bounds == -1) 
5533                                                 child_bounds = current_bounds;
5534
5535                                         else if (child_bounds != current_bounds){
5536                                                 Error_IncorrectArrayInitializer ();
5537                                                 return false;
5538                                         }
5539                                         if (specified_dims && (idx + 1 >= arguments.Count)){
5540                                                 Error (623, "Array initializers can only be used in a variable or field initializer, try using the new expression");
5541                                                 return false;
5542                                         }
5543                                         
5544                                         bool ret = CheckIndices (ec, (ArrayList) o, idx + 1, specified_dims);
5545                                         if (!ret)
5546                                                 return false;
5547                                 } else {
5548                                         if (child_bounds != -1){
5549                                                 Error_IncorrectArrayInitializer ();
5550                                                 return false;
5551                                         }
5552                                         
5553                                         Expression tmp = (Expression) o;
5554                                         tmp = tmp.Resolve (ec);
5555                                         if (tmp == null)
5556                                                 continue;
5557
5558                                         // Console.WriteLine ("I got: " + tmp);
5559                                         // Handle initialization from vars, fields etc.
5560
5561                                         Expression conv = Convert.ImplicitConversionRequired (
5562                                                 ec, tmp, underlying_type, loc);
5563                                         
5564                                         if (conv == null) 
5565                                                 return false;
5566
5567                                         if (conv is StringConstant)
5568                                                 array_data.Add (conv);
5569                                         else if (conv is Constant) {
5570                                                 array_data.Add (conv);
5571                                                 num_automatic_initializers++;
5572                                         } else
5573                                                 array_data.Add (conv);
5574                                 }
5575                         }
5576
5577                         return true;
5578                 }
5579                 
5580                 public void UpdateIndices (EmitContext ec)
5581                 {
5582                         int i = 0;
5583                         for (ArrayList probe = initializers; probe != null;) {
5584                                 if (probe.Count > 0 && probe [0] is ArrayList) {
5585                                         Expression e = new IntConstant (probe.Count);
5586                                         arguments.Add (new Argument (e, Argument.AType.Expression));
5587
5588                                         bounds [i++] =  probe.Count;
5589                                         
5590                                         probe = (ArrayList) probe [0];
5591                                         
5592                                 } else {
5593                                         Expression e = new IntConstant (probe.Count);
5594                                         arguments.Add (new Argument (e, Argument.AType.Expression));
5595
5596                                         bounds [i++] = probe.Count;
5597                                         probe = null;
5598                                 }
5599                         }
5600
5601                 }
5602                 
5603                 public bool ValidateInitializers (EmitContext ec, Type array_type)
5604                 {
5605                         if (initializers == null) {
5606                                 if (expect_initializers)
5607                                         return false;
5608                                 else
5609                                         return true;
5610                         }
5611                         
5612                         if (underlying_type == null)
5613                                 return false;
5614                         
5615                         //
5616                         // We use this to store all the date values in the order in which we
5617                         // will need to store them in the byte blob later
5618                         //
5619                         array_data = new ArrayList ();
5620                         bounds = new Hashtable ();
5621                         
5622                         bool ret;
5623
5624                         if (arguments != null) {
5625                                 ret = CheckIndices (ec, initializers, 0, true);
5626                                 return ret;
5627                         } else {
5628                                 arguments = new ArrayList ();
5629
5630                                 ret = CheckIndices (ec, initializers, 0, false);
5631                                 
5632                                 if (!ret)
5633                                         return false;
5634                                 
5635                                 UpdateIndices (ec);
5636                                 
5637                                 if (arguments.Count != dimensions) {
5638                                         Error_IncorrectArrayInitializer ();
5639                                         return false;
5640                                 }
5641
5642                                 return ret;
5643                         }
5644                 }
5645
5646                 void Error_NegativeArrayIndex ()
5647                 {
5648                         Error (284, "Can not create array with a negative size");
5649                 }
5650                 
5651                 //
5652                 // Converts `source' to an int, uint, long or ulong.
5653                 //
5654                 Expression ExpressionToArrayArgument (EmitContext ec, Expression source)
5655                 {
5656                         Expression target;
5657                         
5658                         bool old_checked = ec.CheckState;
5659                         ec.CheckState = true;
5660                         
5661                         target = Convert.ImplicitConversion (ec, source, TypeManager.int32_type, loc);
5662                         if (target == null){
5663                                 target = Convert.ImplicitConversion (ec, source, TypeManager.uint32_type, loc);
5664                                 if (target == null){
5665                                         target = Convert.ImplicitConversion (ec, source, TypeManager.int64_type, loc);
5666                                         if (target == null){
5667                                                 target = Convert.ImplicitConversion (ec, source, TypeManager.uint64_type, loc);
5668                                                 if (target == null)
5669                                                         Convert.Error_CannotImplicitConversion (loc, source.Type, TypeManager.int32_type);
5670                                         }
5671                                 }
5672                         } 
5673                         ec.CheckState = old_checked;
5674
5675                         //
5676                         // Only positive constants are allowed at compile time
5677                         //
5678                         if (target is Constant){
5679                                 if (target is IntConstant){
5680                                         if (((IntConstant) target).Value < 0){
5681                                                 Error_NegativeArrayIndex ();
5682                                                 return null;
5683                                         }
5684                                 }
5685
5686                                 if (target is LongConstant){
5687                                         if (((LongConstant) target).Value < 0){
5688                                                 Error_NegativeArrayIndex ();
5689                                                 return null;
5690                                         }
5691                                 }
5692                                 
5693                         }
5694
5695                         return target;
5696                 }
5697
5698                 //
5699                 // Creates the type of the array
5700                 //
5701                 bool LookupType (EmitContext ec)
5702                 {
5703                         StringBuilder array_qualifier = new StringBuilder (rank);
5704
5705                         //
5706                         // `In the first form allocates an array instace of the type that results
5707                         // from deleting each of the individual expression from the expression list'
5708                         //
5709                         if (num_arguments > 0) {
5710                                 array_qualifier.Append ("[");
5711                                 for (int i = num_arguments-1; i > 0; i--)
5712                                         array_qualifier.Append (",");
5713                                 array_qualifier.Append ("]");                           
5714                         }
5715
5716                         //
5717                         // Lookup the type
5718                         //
5719                         Expression array_type_expr;
5720                         array_type_expr = new ComposedCast (requested_base_type, array_qualifier.ToString (), loc);
5721                         type = ec.DeclSpace.ResolveType (array_type_expr, false, loc);
5722
5723                         if (type == null)
5724                                 return false;
5725
5726                         underlying_type = type;
5727                         if (underlying_type.IsArray)
5728                                 underlying_type = TypeManager.GetElementType (underlying_type);
5729                         dimensions = type.GetArrayRank ();
5730
5731                         return true;
5732                 }
5733                 
5734                 public override Expression DoResolve (EmitContext ec)
5735                 {
5736                         int arg_count;
5737
5738                         if (!LookupType (ec))
5739                                 return null;
5740                         
5741                         //
5742                         // First step is to validate the initializers and fill
5743                         // in any missing bits
5744                         //
5745                         if (!ValidateInitializers (ec, type))
5746                                 return null;
5747
5748                         if (arguments == null)
5749                                 arg_count = 0;
5750                         else {
5751                                 arg_count = arguments.Count;
5752                                 foreach (Argument a in arguments){
5753                                         if (!a.Resolve (ec, loc))
5754                                                 return null;
5755
5756                                         Expression real_arg = ExpressionToArrayArgument (ec, a.Expr, loc);
5757                                         if (real_arg == null)
5758                                                 return null;
5759
5760                                         a.Expr = real_arg;
5761                                 }
5762                         }
5763                         
5764                         array_element_type = TypeManager.GetElementType (type);
5765
5766                         if (arg_count == 1) {
5767                                 is_one_dimensional = true;
5768                                 eclass = ExprClass.Value;
5769                                 return this;
5770                         }
5771
5772                         is_builtin_type = TypeManager.IsBuiltinType (type);
5773
5774                         if (is_builtin_type) {
5775                                 Expression ml;
5776                                 
5777                                 ml = MemberLookup (ec, type, ".ctor", MemberTypes.Constructor,
5778                                                    AllBindingFlags, loc);
5779                                 
5780                                 if (!(ml is MethodGroupExpr)) {
5781                                         ml.Error_UnexpectedKind ("method group");
5782                                         return null;
5783                                 }
5784                                 
5785                                 if (ml == null) {
5786                                         Error (-6, "New invocation: Can not find a constructor for " +
5787                                                       "this argument list");
5788                                         return null;
5789                                 }
5790                                 
5791                                 new_method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml, arguments, loc);
5792
5793                                 if (new_method == null) {
5794                                         Error (-6, "New invocation: Can not find a constructor for " +
5795                                                       "this argument list");
5796                                         return null;
5797                                 }
5798                                 
5799                                 eclass = ExprClass.Value;
5800                                 return this;
5801                         } else {
5802                                 ModuleBuilder mb = CodeGen.ModuleBuilder;
5803                                 ArrayList args = new ArrayList ();
5804                                 
5805                                 if (arguments != null) {
5806                                         for (int i = 0; i < arg_count; i++)
5807                                                 args.Add (TypeManager.int32_type);
5808                                 }
5809                                 
5810                                 Type [] arg_types = null;
5811
5812                                 if (args.Count > 0)
5813                                         arg_types = new Type [args.Count];
5814                                 
5815                                 args.CopyTo (arg_types, 0);
5816                                 
5817                                 new_method = mb.GetArrayMethod (type, ".ctor", CallingConventions.HasThis, null,
5818                                                             arg_types);
5819
5820                                 if (new_method == null) {
5821                                         Error (-6, "New invocation: Can not find a constructor for " +
5822                                                       "this argument list");
5823                                         return null;
5824                                 }
5825                                 
5826                                 eclass = ExprClass.Value;
5827                                 return this;
5828                         }
5829                 }
5830
5831                 public static byte [] MakeByteBlob (ArrayList array_data, Type underlying_type, Location loc)
5832                 {
5833                         int factor;
5834                         byte [] data;
5835                         byte [] element;
5836                         int count = array_data.Count;
5837
5838                         if (underlying_type.IsEnum)
5839                                 underlying_type = TypeManager.EnumToUnderlying (underlying_type);
5840                         
5841                         factor = GetTypeSize (underlying_type);
5842                         if (factor == 0)
5843                                 throw new Exception ("unrecognized type in MakeByteBlob: " + underlying_type);
5844
5845                         data = new byte [(count * factor + 4) & ~3];
5846                         int idx = 0;
5847                         
5848                         for (int i = 0; i < count; ++i) {
5849                                 object v = array_data [i];
5850
5851                                 if (v is EnumConstant)
5852                                         v = ((EnumConstant) v).Child;
5853                                 
5854                                 if (v is Constant && !(v is StringConstant))
5855                                         v = ((Constant) v).GetValue ();
5856                                 else {
5857                                         idx += factor;
5858                                         continue;
5859                                 }
5860                                 
5861                                 if (underlying_type == TypeManager.int64_type){
5862                                         if (!(v is Expression)){
5863                                                 long val = (long) v;
5864                                                 
5865                                                 for (int j = 0; j < factor; ++j) {
5866                                                         data [idx + j] = (byte) (val & 0xFF);
5867                                                         val = (val >> 8);
5868                                                 }
5869                                         }
5870                                 } else if (underlying_type == TypeManager.uint64_type){
5871                                         if (!(v is Expression)){
5872                                                 ulong val = (ulong) v;
5873
5874                                                 for (int j = 0; j < factor; ++j) {
5875                                                         data [idx + j] = (byte) (val & 0xFF);
5876                                                         val = (val >> 8);
5877                                                 }
5878                                         }
5879                                 } else if (underlying_type == TypeManager.float_type) {
5880                                         if (!(v is Expression)){
5881                                                 element = BitConverter.GetBytes ((float) v);
5882                                                         
5883                                                 for (int j = 0; j < factor; ++j)
5884                                                         data [idx + j] = element [j];
5885                                         }
5886                                 } else if (underlying_type == TypeManager.double_type) {
5887                                         if (!(v is Expression)){
5888                                                 element = BitConverter.GetBytes ((double) v);
5889
5890                                                 for (int j = 0; j < factor; ++j)
5891                                                         data [idx + j] = element [j];
5892                                         }
5893                                 } else if (underlying_type == TypeManager.char_type){
5894                                         if (!(v is Expression)){
5895                                                 int val = (int) ((char) v);
5896                                                 
5897                                                 data [idx] = (byte) (val & 0xff);
5898                                                 data [idx+1] = (byte) (val >> 8);
5899                                         }
5900                                 } else if (underlying_type == TypeManager.short_type){
5901                                         if (!(v is Expression)){
5902                                                 int val = (int) ((short) v);
5903                                         
5904                                                 data [idx] = (byte) (val & 0xff);
5905                                                 data [idx+1] = (byte) (val >> 8);
5906                                         }
5907                                 } else if (underlying_type == TypeManager.ushort_type){
5908                                         if (!(v is Expression)){
5909                                                 int val = (int) ((ushort) v);
5910                                         
5911                                                 data [idx] = (byte) (val & 0xff);
5912                                                 data [idx+1] = (byte) (val >> 8);
5913                                         }
5914                                 } else if (underlying_type == TypeManager.int32_type) {
5915                                         if (!(v is Expression)){
5916                                                 int val = (int) v;
5917                                         
5918                                                 data [idx]   = (byte) (val & 0xff);
5919                                                 data [idx+1] = (byte) ((val >> 8) & 0xff);
5920                                                 data [idx+2] = (byte) ((val >> 16) & 0xff);
5921                                                 data [idx+3] = (byte) (val >> 24);
5922                                         }
5923                                 } else if (underlying_type == TypeManager.uint32_type) {
5924                                         if (!(v is Expression)){
5925                                                 uint val = (uint) v;
5926                                         
5927                                                 data [idx]   = (byte) (val & 0xff);
5928                                                 data [idx+1] = (byte) ((val >> 8) & 0xff);
5929                                                 data [idx+2] = (byte) ((val >> 16) & 0xff);
5930                                                 data [idx+3] = (byte) (val >> 24);
5931                                         }
5932                                 } else if (underlying_type == TypeManager.sbyte_type) {
5933                                         if (!(v is Expression)){
5934                                                 sbyte val = (sbyte) v;
5935                                                 data [idx] = (byte) val;
5936                                         }
5937                                 } else if (underlying_type == TypeManager.byte_type) {
5938                                         if (!(v is Expression)){
5939                                                 byte val = (byte) v;
5940                                                 data [idx] = (byte) val;
5941                                         }
5942                                 } else if (underlying_type == TypeManager.bool_type) {
5943                                         if (!(v is Expression)){
5944                                                 bool val = (bool) v;
5945                                                 data [idx] = (byte) (val ? 1 : 0);
5946                                         }
5947                                 } else if (underlying_type == TypeManager.decimal_type){
5948                                         if (!(v is Expression)){
5949                                                 int [] bits = Decimal.GetBits ((decimal) v);
5950                                                 int p = idx;
5951
5952                                                 // FIXME: For some reason, this doesn't work on the MS runtime.
5953                                                 int [] nbits = new int [4];
5954                                                 nbits [0] = bits [3];
5955                                                 nbits [1] = bits [2];
5956                                                 nbits [2] = bits [0];
5957                                                 nbits [3] = bits [1];
5958                                                 
5959                                                 for (int j = 0; j < 4; j++){
5960                                                         data [p++] = (byte) (nbits [j] & 0xff);
5961                                                         data [p++] = (byte) ((nbits [j] >> 8) & 0xff);
5962                                                         data [p++] = (byte) ((nbits [j] >> 16) & 0xff);
5963                                                         data [p++] = (byte) (nbits [j] >> 24);
5964                                                 }
5965                                         }
5966                                 } else
5967                                         throw new Exception ("Unrecognized type in MakeByteBlob: " + underlying_type);
5968
5969                                 idx += factor;
5970                         }
5971
5972                         return data;
5973                 }
5974
5975                 //
5976                 // Emits the initializers for the array
5977                 //
5978                 void EmitStaticInitializers (EmitContext ec, bool is_expression)
5979                 {
5980                         //
5981                         // First, the static data
5982                         //
5983                         FieldBuilder fb;
5984                         ILGenerator ig = ec.ig;
5985                         
5986                         byte [] data = MakeByteBlob (array_data, underlying_type, loc);
5987
5988                         fb = RootContext.MakeStaticData (data);
5989
5990                         if (is_expression)
5991                                 ig.Emit (OpCodes.Dup);
5992                         ig.Emit (OpCodes.Ldtoken, fb);
5993                         ig.Emit (OpCodes.Call,
5994                                  TypeManager.void_initializearray_array_fieldhandle);
5995                 }
5996                 
5997                 //
5998                 // Emits pieces of the array that can not be computed at compile
5999                 // time (variables and string locations).
6000                 //
6001                 // This always expect the top value on the stack to be the array
6002                 //
6003                 void EmitDynamicInitializers (EmitContext ec, bool is_expression)
6004                 {
6005                         ILGenerator ig = ec.ig;
6006                         int dims = bounds.Count;
6007                         int [] current_pos = new int [dims];
6008                         int top = array_data.Count;
6009                         LocalBuilder temp = ig.DeclareLocal (type);
6010
6011                         ig.Emit (OpCodes.Stloc, temp);
6012
6013                         MethodInfo set = null;
6014
6015                         if (dims != 1){
6016                                 Type [] args;
6017                                 ModuleBuilder mb = null;
6018                                 mb = CodeGen.ModuleBuilder;
6019                                 args = new Type [dims + 1];
6020
6021                                 int j;
6022                                 for (j = 0; j < dims; j++)
6023                                         args [j] = TypeManager.int32_type;
6024
6025                                 args [j] = array_element_type;
6026                                 
6027                                 set = mb.GetArrayMethod (
6028                                         type, "Set",
6029                                         CallingConventions.HasThis | CallingConventions.Standard,
6030                                         TypeManager.void_type, args);
6031                         }
6032                         
6033                         for (int i = 0; i < top; i++){
6034
6035                                 Expression e = null;
6036
6037                                 if (array_data [i] is Expression)
6038                                         e = (Expression) array_data [i];
6039
6040                                 if (e != null) {
6041                                         //
6042                                         // Basically we do this for string literals and
6043                                         // other non-literal expressions
6044                                         //
6045                                         if (e is EnumConstant){
6046                                                 e = ((EnumConstant) e).Child;
6047                                         }
6048                                         
6049                                         if (e is StringConstant || e is DecimalConstant || !(e is Constant) ||
6050                                             num_automatic_initializers <= max_automatic_initializers) {
6051                                                 Type etype = e.Type;
6052                                                 
6053                                                 ig.Emit (OpCodes.Ldloc, temp);
6054
6055                                                 for (int idx = 0; idx < dims; idx++) 
6056                                                         IntConstant.EmitInt (ig, current_pos [idx]);
6057
6058                                                 //
6059                                                 // If we are dealing with a struct, get the
6060                                                 // address of it, so we can store it.
6061                                                 //
6062                                                 if ((dims == 1) &&
6063                                                     etype.IsSubclassOf (TypeManager.value_type) &&
6064                                                     (!TypeManager.IsBuiltinType (etype) ||
6065                                                      etype == TypeManager.decimal_type)) {
6066                                                         if (e is New){
6067                                                                 New n = (New) e;
6068
6069                                                                 //
6070                                                                 // Let new know that we are providing
6071                                                                 // the address where to store the results
6072                                                                 //
6073                                                                 n.DisableTemporaryValueType ();
6074                                                         }
6075
6076                                                         ig.Emit (OpCodes.Ldelema, etype);
6077                                                 }
6078
6079                                                 e.Emit (ec);
6080
6081                                                 if (dims == 1)
6082                                                         ArrayAccess.EmitStoreOpcode (ig, array_element_type);
6083                                                 else 
6084                                                         ig.Emit (OpCodes.Call, set);
6085                                                 
6086                                         }
6087                                 }
6088                                 
6089                                 //
6090                                 // Advance counter
6091                                 //
6092                                 for (int j = dims - 1; j >= 0; j--){
6093                                         current_pos [j]++;
6094                                         if (current_pos [j] < (int) bounds [j])
6095                                                 break;
6096                                         current_pos [j] = 0;
6097                                 }
6098                         }
6099
6100                         if (is_expression)
6101                                 ig.Emit (OpCodes.Ldloc, temp);
6102                 }
6103
6104                 void EmitArrayArguments (EmitContext ec)
6105                 {
6106                         ILGenerator ig = ec.ig;
6107                         
6108                         foreach (Argument a in arguments) {
6109                                 Type atype = a.Type;
6110                                 a.Emit (ec);
6111
6112                                 if (atype == TypeManager.uint64_type)
6113                                         ig.Emit (OpCodes.Conv_Ovf_U4);
6114                                 else if (atype == TypeManager.int64_type)
6115                                         ig.Emit (OpCodes.Conv_Ovf_I4);
6116                         }
6117                 }
6118                 
6119                 void DoEmit (EmitContext ec, bool is_statement)
6120                 {
6121                         ILGenerator ig = ec.ig;
6122                         
6123                         EmitArrayArguments (ec);
6124                         if (is_one_dimensional)
6125                                 ig.Emit (OpCodes.Newarr, array_element_type);
6126                         else {
6127                                 if (is_builtin_type) 
6128                                         ig.Emit (OpCodes.Newobj, (ConstructorInfo) new_method);
6129                                 else 
6130                                         ig.Emit (OpCodes.Newobj, (MethodInfo) new_method);
6131                         }
6132                         
6133                         if (initializers != null){
6134                                 //
6135                                 // FIXME: Set this variable correctly.
6136                                 // 
6137                                 bool dynamic_initializers = true;
6138
6139                                 if (underlying_type != TypeManager.string_type &&
6140                                     underlying_type != TypeManager.decimal_type &&
6141                                     underlying_type != TypeManager.object_type) {
6142                                         if (num_automatic_initializers > max_automatic_initializers)
6143                                                 EmitStaticInitializers (ec, dynamic_initializers || !is_statement);
6144                                 }
6145                                 
6146                                 if (dynamic_initializers)
6147                                         EmitDynamicInitializers (ec, !is_statement);
6148                         }
6149                 }
6150                 
6151                 public override void Emit (EmitContext ec)
6152                 {
6153                         DoEmit (ec, false);
6154                 }
6155
6156                 public override void EmitStatement (EmitContext ec)
6157                 {
6158                         DoEmit (ec, true);
6159                 }
6160
6161                 public object EncodeAsAttribute ()
6162                 {
6163                         if (!is_one_dimensional){
6164                                 Report.Error (-211, Location, "attribute can not encode multi-dimensional arrays");
6165                                 return null;
6166                         }
6167
6168                         if (array_data == null){
6169                                 Report.Error (-212, Location, "array should be initialized when passing it to an attribute");
6170                                 return null;
6171                         }
6172                         
6173                         object [] ret = new object [array_data.Count];
6174                         int i = 0;
6175                         foreach (Expression e in array_data){
6176                                 object v;
6177                                 
6178                                 if (e is NullLiteral)
6179                                         v = null;
6180                                 else {
6181                                         if (!Attribute.GetAttributeArgumentExpression (e, Location, out v))
6182                                                 return null;
6183                                 }
6184                                 ret [i++] = v;
6185                         }
6186                         return ret;
6187                 }
6188         }
6189         
6190         /// <summary>
6191         ///   Represents the `this' construct
6192         /// </summary>
6193         public class This : Expression, IAssignMethod, IMemoryLocation, IVariable {
6194
6195                 Block block;
6196                 VariableInfo variable_info;
6197                 
6198                 public This (Block block, Location loc)
6199                 {
6200                         this.loc = loc;
6201                         this.block = block;
6202                 }
6203
6204                 public This (Location loc)
6205                 {
6206                         this.loc = loc;
6207                 }
6208
6209                 public VariableInfo VariableInfo {
6210                         get { return variable_info; }
6211                 }
6212
6213                 public bool VerifyFixed (bool is_expression)
6214                 {
6215                         return variable_info.LocalInfo.IsFixed;
6216                 }
6217
6218                 public bool ResolveBase (EmitContext ec)
6219                 {
6220                         eclass = ExprClass.Variable;
6221                         type = ec.ContainerType;
6222
6223                         if (ec.IsStatic) {
6224                                 Error (26, "Keyword this not valid in static code");
6225                                 return false;
6226                         }
6227
6228                         if ((block != null) && (block.ThisVariable != null))
6229                                 variable_info = block.GetVariableInfo (block.ThisVariable);
6230
6231                         return true;
6232                 }
6233
6234                 public override Expression DoResolve (EmitContext ec)
6235                 {
6236                         if (!ResolveBase (ec))
6237                                 return null;
6238
6239                         if ((variable_info != null) && !variable_info.IsAssigned (ec)) {
6240                                 Error (188, "The this object cannot be used before all " +
6241                                        "of its fields are assigned to");
6242                                 variable_info.SetAssigned (ec);
6243                                 return this;
6244                         }
6245
6246                         if (ec.IsFieldInitializer) {
6247                                 Error (27, "Keyword `this' can't be used outside a constructor, " +
6248                                        "a method or a property.");
6249                                 return null;
6250                         }
6251
6252                         return this;
6253                 }
6254
6255                 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
6256                 {
6257                         if (!ResolveBase (ec))
6258                                 return null;
6259
6260                         if (variable_info != null)
6261                                 variable_info.SetAssigned (ec);
6262                         
6263                         if (ec.TypeContainer is Class){
6264                                 Error (1604, "Cannot assign to `this'");
6265                                 return null;
6266                         }
6267
6268                         return this;
6269                 }
6270
6271                 public override void Emit (EmitContext ec)
6272                 {
6273                         ILGenerator ig = ec.ig;
6274                         
6275                         ig.Emit (OpCodes.Ldarg_0);
6276                         if (ec.TypeContainer is Struct)
6277                                 ig.Emit (OpCodes.Ldobj, type);
6278                 }
6279
6280                 public void EmitAssign (EmitContext ec, Expression source)
6281                 {
6282                         ILGenerator ig = ec.ig;
6283                         
6284                         if (ec.TypeContainer is Struct){
6285                                 ig.Emit (OpCodes.Ldarg_0);
6286                                 source.Emit (ec);
6287                                 ig.Emit (OpCodes.Stobj, type);
6288                         } else {
6289                                 source.Emit (ec);
6290                                 ig.Emit (OpCodes.Starg, 0);
6291                         }
6292                 }
6293
6294                 public void AddressOf (EmitContext ec, AddressOp mode)
6295                 {
6296                         ec.ig.Emit (OpCodes.Ldarg_0);
6297
6298                         // FIMXE
6299                         // FIGURE OUT WHY LDARG_S does not work
6300                         //
6301                         // consider: struct X { int val; int P { set { val = value; }}}
6302                         //
6303                         // Yes, this looks very bad. Look at `NOTAS' for
6304                         // an explanation.
6305                         // ec.ig.Emit (OpCodes.Ldarga_S, (byte) 0);
6306                 }
6307         }
6308
6309         /// <summary>
6310         ///   Implements the typeof operator
6311         /// </summary>
6312         public class TypeOf : Expression {
6313                 public readonly Expression QueriedType;
6314                 Type typearg;
6315                 
6316                 public TypeOf (Expression queried_type, Location l)
6317                 {
6318                         QueriedType = queried_type;
6319                         loc = l;
6320                 }
6321
6322                 public override Expression DoResolve (EmitContext ec)
6323                 {
6324                         typearg = ec.DeclSpace.ResolveType (QueriedType, false, loc);
6325
6326                         if (typearg == null)
6327                                 return null;
6328
6329                         if (typearg == TypeManager.void_type) {
6330                                 Error (673, "System.Void cannot be used from C# - " +
6331                                        "use typeof (void) to get the void type object");
6332                                 return null;
6333                         }
6334
6335                         type = TypeManager.type_type;
6336                         eclass = ExprClass.Type;
6337                         return this;
6338                 }
6339
6340                 public override void Emit (EmitContext ec)
6341                 {
6342                         ec.ig.Emit (OpCodes.Ldtoken, typearg);
6343                         ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
6344                 }
6345
6346                 public Type TypeArg { 
6347                         get { return typearg; }
6348                 }
6349         }
6350
6351         /// <summary>
6352         ///   Implements the `typeof (void)' operator
6353         /// </summary>
6354         public class TypeOfVoid : Expression {
6355                 public TypeOfVoid (Location l)
6356                 {
6357                         loc = l;
6358                 }
6359
6360                 public override Expression DoResolve (EmitContext ec)
6361                 {
6362                         type = TypeManager.type_type;
6363                         eclass = ExprClass.Type;
6364                         return this;
6365                 }
6366
6367                 public override void Emit (EmitContext ec)
6368                 {
6369                         ec.ig.Emit (OpCodes.Ldtoken, TypeManager.void_type);
6370                         ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
6371                 }
6372
6373                 public Type TypeArg { 
6374                         get { return TypeManager.void_type; }
6375                 }
6376         }
6377
6378         /// <summary>
6379         ///   Implements the sizeof expression
6380         /// </summary>
6381         public class SizeOf : Expression {
6382                 public Expression QueriedType;
6383                 Type type_queried;
6384                 
6385                 public SizeOf (Expression queried_type, Location l)
6386                 {
6387                         this.QueriedType = queried_type;
6388                         loc = l;
6389                 }
6390
6391                 public override Expression DoResolve (EmitContext ec)
6392                 {
6393                         if (!ec.InUnsafe) {
6394                                 Report.Error (
6395                                         233, loc, "Sizeof may only be used in an unsafe context " +
6396                                         "(consider using System.Runtime.InteropServices.Marshal.Sizeof");
6397                                 return null;
6398                         }
6399                                 
6400                         QueriedType = ec.DeclSpace.ResolveTypeExpr (QueriedType, false, loc);
6401                         if (QueriedType == null || QueriedType.Type == null)
6402                                 return null;
6403
6404                         if (QueriedType is TypeParameterExpr){
6405                                 ((TypeParameterExpr)QueriedType).Error_CannotUseAsUnmanagedType (loc);
6406                                 return null;
6407                         }
6408                         
6409                         if (!TypeManager.IsUnmanagedType (type_queried)){
6410                                 Report.Error (208, loc, "Cannot take the size of an unmanaged type (" + TypeManager.CSharpName (type_queried) + ")");
6411                                 return null;
6412                         }
6413                         
6414                         type = TypeManager.int32_type;
6415                         eclass = ExprClass.Value;
6416                         return this;
6417                 }
6418
6419                 public override void Emit (EmitContext ec)
6420                 {
6421                         int size = GetTypeSize (type_queried);
6422
6423                         if (size == 0)
6424                                 ec.ig.Emit (OpCodes.Sizeof, type_queried);
6425                         else
6426                                 IntConstant.EmitInt (ec.ig, size);
6427                 }
6428         }
6429
6430         /// <summary>
6431         ///   Implements the member access expression
6432         /// </summary>
6433         public class MemberAccess : Expression {
6434                 public readonly string Identifier;
6435                 Expression expr;
6436                 
6437                 public MemberAccess (Expression expr, string id, Location l)
6438                 {
6439                         this.expr = expr;
6440                         Identifier = id;
6441                         loc = l;
6442                 }
6443
6444                 public Expression Expr {
6445                         get {
6446                                 return expr;
6447                         }
6448                 }
6449
6450                 static void error176 (Location loc, string name)
6451                 {
6452                         Report.Error (176, loc, "Static member `" +
6453                                       name + "' cannot be accessed " +
6454                                       "with an instance reference, qualify with a " +
6455                                       "type name instead");
6456                 }
6457
6458                 static bool IdenticalNameAndTypeName (EmitContext ec, Expression left_original, Location loc)
6459                 {
6460                         if (left_original == null)
6461                                 return false;
6462
6463                         if (!(left_original is SimpleName))
6464                                 return false;
6465
6466                         SimpleName sn = (SimpleName) left_original;
6467
6468                         Type t = RootContext.LookupType (ec.DeclSpace, sn.Name, true, loc);
6469                         if (t != null)
6470                                 return true;
6471
6472                         return false;
6473                 }
6474                 
6475                 public static Expression ResolveMemberAccess (EmitContext ec, Expression member_lookup,
6476                                                               Expression left, Location loc,
6477                                                               Expression left_original)
6478                 {
6479                         bool left_is_type, left_is_explicit;
6480
6481                         // If `left' is null, then we're called from SimpleNameResolve and this is
6482                         // a member in the currently defining class.
6483                         if (left == null) {
6484                                 left_is_type = ec.IsStatic || ec.IsFieldInitializer;
6485                                 left_is_explicit = false;
6486
6487                                 // Implicitly default to `this' unless we're static.
6488                                 if (!ec.IsStatic && !ec.IsFieldInitializer && !ec.InEnumContext)
6489                                         left = ec.GetThis (loc);
6490                         } else {
6491                                 left_is_type = left is TypeExpr;
6492                                 left_is_explicit = true;
6493                         }
6494
6495                         if (member_lookup is FieldExpr){
6496                                 FieldExpr fe = (FieldExpr) member_lookup;
6497                                 FieldInfo fi = fe.FieldInfo;
6498                                 Type decl_type = fi.DeclaringType;
6499
6500                                 if (fi is FieldBuilder) {
6501                                         Const c = TypeManager.LookupConstant ((FieldBuilder) fi);
6502                                         
6503                                         if (c != null) {
6504                                                 object o = c.LookupConstantValue ();
6505                                                 if (o == null)
6506                                                         return null;
6507                                                 
6508                                                 object real_value = ((Constant) c.Expr).GetValue ();
6509
6510                                                 return Constantify (real_value, fi.FieldType);
6511                                         }
6512                                 }
6513
6514                                 if (fi.IsLiteral) {
6515                                         Type t = fi.FieldType;
6516                                         
6517                                         object o;
6518
6519                                         if (fi is FieldBuilder)
6520                                                 o = TypeManager.GetValue ((FieldBuilder) fi);
6521                                         else
6522                                                 o = fi.GetValue (fi);
6523                                         
6524                                         if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
6525                                                 if (left_is_explicit && !left_is_type &&
6526                                                     !IdenticalNameAndTypeName (ec, left_original, loc)) {
6527                                                         error176 (loc, fe.FieldInfo.Name);
6528                                                         return null;
6529                                                 }                                       
6530                                                 
6531                                                 Expression enum_member = MemberLookup (
6532                                                         ec, decl_type, "value__", MemberTypes.Field,
6533                                                         AllBindingFlags, loc); 
6534
6535                                                 Enum en = TypeManager.LookupEnum (decl_type);
6536
6537                                                 Constant c;
6538                                                 if (en != null)
6539                                                         c = Constantify (o, en.UnderlyingType);
6540                                                 else 
6541                                                         c = Constantify (o, enum_member.Type);
6542                                                 
6543                                                 return new EnumConstant (c, decl_type);
6544                                         }
6545                                         
6546                                         Expression exp = Constantify (o, t);
6547
6548                                         if (left_is_explicit && !left_is_type) {
6549                                                 error176 (loc, fe.FieldInfo.Name);
6550                                                 return null;
6551                                         }
6552                                         
6553                                         return exp;
6554                                 }
6555
6556                                 if (fi.FieldType.IsPointer && !ec.InUnsafe){
6557                                         UnsafeError (loc);
6558                                         return null;
6559                                 }
6560                         }
6561
6562                         if (member_lookup is EventExpr) {
6563                                 EventExpr ee = (EventExpr) member_lookup;
6564                                 
6565                                 //
6566                                 // If the event is local to this class, we transform ourselves into
6567                                 // a FieldExpr
6568                                 //
6569
6570                                 if (ee.EventInfo.DeclaringType == ec.ContainerType) {
6571                                         MemberInfo mi = GetFieldFromEvent (ee);
6572
6573                                         if (mi == null) {
6574                                                 //
6575                                                 // If this happens, then we have an event with its own
6576                                                 // accessors and private field etc so there's no need
6577                                                 // to transform ourselves.
6578                                                 //
6579                                                 return ee;
6580                                         }
6581
6582                                         Expression ml = ExprClassFromMemberInfo (ec, mi, loc);
6583                                         
6584                                         if (ml == null) {
6585                                                 Report.Error (-200, loc, "Internal error!!");
6586                                                 return null;
6587                                         }
6588
6589                                         if (!left_is_explicit)
6590                                                 left = null;
6591                                         
6592                                         return ResolveMemberAccess (ec, ml, left, loc, left_original);
6593                                 }
6594                         }
6595
6596                         if (member_lookup is IMemberExpr) {
6597                                 IMemberExpr me = (IMemberExpr) member_lookup;
6598
6599                                 if (left_is_type){
6600                                         MethodGroupExpr mg = me as MethodGroupExpr;
6601                                         if ((mg != null) && left_is_explicit && left.Type.IsInterface)
6602                                                 mg.IsExplicitImpl = left_is_explicit;
6603
6604                                         if (!me.IsStatic){
6605                                                 if ((ec.IsFieldInitializer || ec.IsStatic) &&
6606                                                     IdenticalNameAndTypeName (ec, left_original, loc))
6607                                                         return member_lookup;
6608
6609                                                 SimpleName.Error_ObjectRefRequired (ec, loc, me.Name);
6610                                                 return null;
6611                                         }
6612
6613                                 } else {
6614                                         if (!me.IsInstance){
6615                                                 if (IdenticalNameAndTypeName (ec, left_original, loc))
6616                                                         return member_lookup;
6617
6618                                                 if (left_is_explicit) {
6619                                                         error176 (loc, me.Name);
6620                                                         return null;
6621                                                 }
6622                                         }
6623
6624                                         //
6625                                         // Since we can not check for instance objects in SimpleName,
6626                                         // becaue of the rule that allows types and variables to share
6627                                         // the name (as long as they can be de-ambiguated later, see 
6628                                         // IdenticalNameAndTypeName), we have to check whether left 
6629                                         // is an instance variable in a static context
6630                                         //
6631                                         // However, if the left-hand value is explicitly given, then
6632                                         // it is already our instance expression, so we aren't in
6633                                         // static context.
6634                                         //
6635
6636                                         if (ec.IsStatic && !left_is_explicit && left is IMemberExpr){
6637                                                 IMemberExpr mexp = (IMemberExpr) left;
6638
6639                                                 if (!mexp.IsStatic){
6640                                                         SimpleName.Error_ObjectRefRequired (ec, loc, mexp.Name);
6641                                                         return null;
6642                                                 }
6643                                         }
6644
6645                                         me.InstanceExpression = left;
6646                                 }
6647
6648                                 return member_lookup;
6649                         }
6650
6651                         Console.WriteLine ("Left is: " + left);
6652                         Report.Error (-100, loc, "Support for [" + member_lookup + "] is not present yet");
6653                         Environment.Exit (0);
6654                         return null;
6655                 }
6656                 
6657                 public Expression DoResolve (EmitContext ec, Expression right_side, ResolveFlags flags)
6658                 {
6659                         if (type != null)
6660                                 throw new Exception ();
6661
6662                         //
6663                         // Resolve the expression with flow analysis turned off, we'll do the definite
6664                         // assignment checks later.  This is because we don't know yet what the expression
6665                         // will resolve to - it may resolve to a FieldExpr and in this case we must do the
6666                         // definite assignment check on the actual field and not on the whole struct.
6667                         //
6668
6669                         Expression original = expr;
6670                         expr = expr.Resolve (ec, flags | ResolveFlags.DisableFlowAnalysis);
6671                         if (expr == null)
6672                                 return null;
6673
6674                         if (expr is SimpleName){
6675                                 SimpleName child_expr = (SimpleName) expr;
6676
6677                                 Expression new_expr = new SimpleName (child_expr.Name, Identifier, loc);
6678
6679                                 return new_expr.Resolve (ec, flags);
6680                         }
6681                                         
6682                         //
6683                         // TODO: I mailed Ravi about this, and apparently we can get rid
6684                         // of this and put it in the right place.
6685                         // 
6686                         // Handle enums here when they are in transit.
6687                         // Note that we cannot afford to hit MemberLookup in this case because
6688                         // it will fail to find any members at all
6689                         //
6690
6691                         int errors = Report.Errors;
6692                         
6693                         Type expr_type = expr.Type;
6694                         if (expr is TypeExpr){
6695                                 if (!ec.DeclSpace.CheckAccessLevel (expr_type)){
6696                                         Error (122, "`" + expr_type + "' " +
6697                                                "is inaccessible because of its protection level");
6698                                         return null;
6699                                 }
6700
6701                                 if (expr_type == TypeManager.enum_type || expr_type.IsSubclassOf (TypeManager.enum_type)){
6702                                         Enum en = TypeManager.LookupEnum (expr_type);
6703
6704                                         if (en != null) {
6705                                                 object value = en.LookupEnumValue (ec, Identifier, loc);
6706                                                 
6707                                                 if (value != null){
6708                                                         Constant c = Constantify (value, en.UnderlyingType);
6709                                                         return new EnumConstant (c, expr_type);
6710                                                 }
6711                                         }
6712                                 }
6713                         }
6714                         
6715                         if (expr_type.IsPointer){
6716                                 Error (23, "The `.' operator can not be applied to pointer operands (" +
6717                                        TypeManager.CSharpName (expr_type) + ")");
6718                                 return null;
6719                         }
6720
6721                         Expression member_lookup;
6722                         member_lookup = MemberLookupFinal (ec, expr_type, expr_type, Identifier, loc);
6723                         if (member_lookup == null)
6724                                 return null;
6725
6726                         if (member_lookup is TypeExpr) {
6727                                 if (!(expr is TypeExpr) && !(expr is SimpleName)) {
6728                                         Error (572, "Can't reference type `" + Identifier + "' through an expression; try `" +
6729                                                member_lookup.Type + "' instead");
6730                                         return null;
6731                                 }
6732
6733                                 return member_lookup;
6734                         }
6735                         
6736                         member_lookup = ResolveMemberAccess (ec, member_lookup, expr, loc, original);
6737                         if (member_lookup == null)
6738                                 return null;
6739
6740                         // The following DoResolve/DoResolveLValue will do the definite assignment
6741                         // check.
6742
6743                         if (right_side != null)
6744                                 member_lookup = member_lookup.DoResolveLValue (ec, right_side);
6745                         else
6746                                 member_lookup = member_lookup.DoResolve (ec);
6747
6748                         return member_lookup;
6749                 }
6750
6751                 public override Expression DoResolve (EmitContext ec)
6752                 {
6753                         return DoResolve (ec, null, ResolveFlags.VariableOrValue |
6754                                           ResolveFlags.SimpleName | ResolveFlags.Type);
6755                 }
6756
6757                 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
6758                 {
6759                         return DoResolve (ec, right_side, ResolveFlags.VariableOrValue |
6760                                           ResolveFlags.SimpleName | ResolveFlags.Type);
6761                 }
6762
6763                 public override Expression ResolveAsTypeStep (EmitContext ec)
6764                 {
6765                         string fname = null;
6766                         MemberAccess full_expr = this;
6767                         while (full_expr != null) {
6768                                 if (fname != null)
6769                                         fname = String.Concat (full_expr.Identifier, ".", fname);
6770                                 else
6771                                         fname = full_expr.Identifier;
6772
6773                                 if (full_expr.Expr is SimpleName) {
6774                                         string full_name = String.Concat (((SimpleName) full_expr.Expr).Name, ".", fname);
6775                                         Type fully_qualified = ec.DeclSpace.FindType (loc, full_name);
6776                                         if (fully_qualified != null)
6777                                                 return new TypeExpr (fully_qualified, loc);
6778                                 }
6779
6780                                 full_expr = full_expr.Expr as MemberAccess;
6781                         }
6782
6783                         Expression new_expr = expr.ResolveAsTypeStep (ec);
6784
6785                         if (new_expr == null)
6786                                 return null;
6787
6788                         if (new_expr is SimpleName){
6789                                 SimpleName child_expr = (SimpleName) new_expr;
6790                                 
6791                                 new_expr = new SimpleName (child_expr.Name, Identifier, loc);
6792
6793                                 return new_expr.ResolveAsTypeStep (ec);
6794                         }
6795
6796                         Type expr_type = new_expr.Type;
6797                       
6798                         if (expr_type.IsPointer){
6799                                 Error (23, "The `.' operator can not be applied to pointer operands (" +
6800                                        TypeManager.CSharpName (expr_type) + ")");
6801                                 return null;
6802                         }
6803                         
6804                         Expression member_lookup;
6805                         member_lookup = MemberLookupFinal (ec, expr_type, expr_type, Identifier, loc);
6806                         if (member_lookup == null)
6807                                 return null;
6808
6809                         if (member_lookup is TypeExpr){
6810                                 member_lookup.Resolve (ec, ResolveFlags.Type);
6811                                 return member_lookup;
6812                         } 
6813
6814                         return null;                    
6815                 }
6816
6817                 public override void Emit (EmitContext ec)
6818                 {
6819                         throw new Exception ("Should not happen");
6820                 }
6821
6822                 public override string ToString ()
6823                 {
6824                         return expr + "." + Identifier;
6825                 }
6826         }
6827
6828         /// <summary>
6829         ///   Implements checked expressions
6830         /// </summary>
6831         public class CheckedExpr : Expression {
6832
6833                 public Expression Expr;
6834
6835                 public CheckedExpr (Expression e, Location l)
6836                 {
6837                         Expr = e;
6838                         loc = l;
6839                 }
6840
6841                 public override Expression DoResolve (EmitContext ec)
6842                 {
6843                         bool last_check = ec.CheckState;
6844                         bool last_const_check = ec.ConstantCheckState;
6845
6846                         ec.CheckState = true;
6847                         ec.ConstantCheckState = true;
6848                         Expr = Expr.Resolve (ec);
6849                         ec.CheckState = last_check;
6850                         ec.ConstantCheckState = last_const_check;
6851                         
6852                         if (Expr == null)
6853                                 return null;
6854
6855                         if (Expr is Constant)
6856                                 return Expr;
6857                         
6858                         eclass = Expr.eclass;
6859                         type = Expr.Type;
6860                         return this;
6861                 }
6862
6863                 public override void Emit (EmitContext ec)
6864                 {
6865                         bool last_check = ec.CheckState;
6866                         bool last_const_check = ec.ConstantCheckState;
6867                         
6868                         ec.CheckState = true;
6869                         ec.ConstantCheckState = true;
6870                         Expr.Emit (ec);
6871                         ec.CheckState = last_check;
6872                         ec.ConstantCheckState = last_const_check;
6873                 }
6874                 
6875         }
6876
6877         /// <summary>
6878         ///   Implements the unchecked expression
6879         /// </summary>
6880         public class UnCheckedExpr : Expression {
6881
6882                 public Expression Expr;
6883
6884                 public UnCheckedExpr (Expression e, Location l)
6885                 {
6886                         Expr = e;
6887                         loc = l;
6888                 }
6889
6890                 public override Expression DoResolve (EmitContext ec)
6891                 {
6892                         bool last_check = ec.CheckState;
6893                         bool last_const_check = ec.ConstantCheckState;
6894
6895                         ec.CheckState = false;
6896                         ec.ConstantCheckState = false;
6897                         Expr = Expr.Resolve (ec);
6898                         ec.CheckState = last_check;
6899                         ec.ConstantCheckState = last_const_check;
6900
6901                         if (Expr == null)
6902                                 return null;
6903
6904                         if (Expr is Constant)
6905                                 return Expr;
6906                         
6907                         eclass = Expr.eclass;
6908                         type = Expr.Type;
6909                         return this;
6910                 }
6911
6912                 public override void Emit (EmitContext ec)
6913                 {
6914                         bool last_check = ec.CheckState;
6915                         bool last_const_check = ec.ConstantCheckState;
6916                         
6917                         ec.CheckState = false;
6918                         ec.ConstantCheckState = false;
6919                         Expr.Emit (ec);
6920                         ec.CheckState = last_check;
6921                         ec.ConstantCheckState = last_const_check;
6922                 }
6923                 
6924         }
6925
6926         /// <summary>
6927         ///   An Element Access expression.
6928         ///
6929         ///   During semantic analysis these are transformed into 
6930         ///   IndexerAccess, ArrayAccess or a PointerArithmetic.
6931         /// </summary>
6932         public class ElementAccess : Expression {
6933                 public ArrayList  Arguments;
6934                 public Expression Expr;
6935                 
6936                 public ElementAccess (Expression e, ArrayList e_list, Location l)
6937                 {
6938                         Expr = e;
6939
6940                         loc  = l;
6941                         
6942                         if (e_list == null)
6943                                 return;
6944                         
6945                         Arguments = new ArrayList ();
6946                         foreach (Expression tmp in e_list)
6947                                 Arguments.Add (new Argument (tmp, Argument.AType.Expression));
6948                         
6949                 }
6950
6951                 bool CommonResolve (EmitContext ec)
6952                 {
6953                         Expr = Expr.Resolve (ec);
6954
6955                         if (Expr == null) 
6956                                 return false;
6957
6958                         if (Arguments == null)
6959                                 return false;
6960
6961                         foreach (Argument a in Arguments){
6962                                 if (!a.Resolve (ec, loc))
6963                                         return false;
6964                         }
6965
6966                         return true;
6967                 }
6968
6969                 Expression MakePointerAccess ()
6970                 {
6971                         Type t = Expr.Type;
6972
6973                         if (t == TypeManager.void_ptr_type){
6974                                 Error (242, "The array index operation is not valid for void pointers");
6975                                 return null;
6976                         }
6977                         if (Arguments.Count != 1){
6978                                 Error (196, "A pointer must be indexed by a single value");
6979                                 return null;
6980                         }
6981                         Expression p;
6982
6983                         p = new PointerArithmetic (true, Expr, ((Argument)Arguments [0]).Expr, t, loc);
6984                         return new Indirection (p, loc);
6985                 }
6986                 
6987                 public override Expression DoResolve (EmitContext ec)
6988                 {
6989                         if (!CommonResolve (ec))
6990                                 return null;
6991
6992                         //
6993                         // We perform some simple tests, and then to "split" the emit and store
6994                         // code we create an instance of a different class, and return that.
6995                         //
6996                         // I am experimenting with this pattern.
6997                         //
6998                         Type t = Expr.Type;
6999
7000                         if (t == TypeManager.array_type){
7001                                 Report.Error (21, loc, "Cannot use indexer on System.Array");
7002                                 return null;
7003                         }
7004                         
7005                         if (t.IsArray)
7006                                 return (new ArrayAccess (this, loc)).Resolve (ec);
7007                         else if (t.IsPointer)
7008                                 return MakePointerAccess ();
7009                         else
7010                                 return (new IndexerAccess (this, loc)).Resolve (ec);
7011                 }
7012
7013                 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7014                 {
7015                         if (!CommonResolve (ec))
7016                                 return null;
7017
7018                         Type t = Expr.Type;
7019                         if (t.IsArray)
7020                                 return (new ArrayAccess (this, loc)).ResolveLValue (ec, right_side);
7021                         else if (t.IsPointer)
7022                                 return MakePointerAccess ();
7023                         else
7024                                 return (new IndexerAccess (this, loc)).ResolveLValue (ec, right_side);
7025                 }
7026                 
7027                 public override void Emit (EmitContext ec)
7028                 {
7029                         throw new Exception ("Should never be reached");
7030                 }
7031         }
7032
7033         /// <summary>
7034         ///   Implements array access 
7035         /// </summary>
7036         public class ArrayAccess : Expression, IAssignMethod, IMemoryLocation {
7037                 //
7038                 // Points to our "data" repository
7039                 //
7040                 ElementAccess ea;
7041
7042                 LocalTemporary [] cached_locations;
7043                 
7044                 public ArrayAccess (ElementAccess ea_data, Location l)
7045                 {
7046                         ea = ea_data;
7047                         eclass = ExprClass.Variable;
7048                         loc = l;
7049                 }
7050
7051                 public override Expression DoResolve (EmitContext ec)
7052                 {
7053                         ExprClass eclass = ea.Expr.eclass;
7054
7055 #if false
7056                         // As long as the type is valid
7057                         if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
7058                               eclass == ExprClass.Value)) {
7059                                 ea.Expr.Error_UnexpectedKind ("variable or value");
7060                                 return null;
7061                         }
7062 #endif
7063
7064                         Type t = ea.Expr.Type;
7065                         if (t.GetArrayRank () != ea.Arguments.Count){
7066                                 ea.Error (22,
7067                                           "Incorrect number of indexes for array " +
7068                                           " expected: " + t.GetArrayRank () + " got: " +
7069                                           ea.Arguments.Count);
7070                                 return null;
7071                         }
7072
7073                         type = TypeManager.GetElementType (t);
7074                         if (type.IsPointer && !ec.InUnsafe){
7075                                 UnsafeError (ea.Location);
7076                                 return null;
7077                         }
7078
7079                         foreach (Argument a in ea.Arguments){
7080                                 Type argtype = a.Type;
7081
7082                                 if (argtype == TypeManager.int32_type ||
7083                                     argtype == TypeManager.uint32_type ||
7084                                     argtype == TypeManager.int64_type ||
7085                                     argtype == TypeManager.uint64_type)
7086                                         continue;
7087
7088                                 //
7089                                 // Mhm.  This is strage, because the Argument.Type is not the same as
7090                                 // Argument.Expr.Type: the value changes depending on the ref/out setting.
7091                                 //
7092                                 // Wonder if I will run into trouble for this.
7093                                 //
7094                                 a.Expr = ExpressionToArrayArgument (ec, a.Expr, ea.Location);
7095                                 if (a.Expr == null)
7096                                         return null;
7097                         }
7098                         
7099                         eclass = ExprClass.Variable;
7100
7101                         return this;
7102                 }
7103
7104                 /// <summary>
7105                 ///    Emits the right opcode to load an object of Type `t'
7106                 ///    from an array of T
7107                 /// </summary>
7108                 static public void EmitLoadOpcode (ILGenerator ig, Type type)
7109                 {
7110                         if (type == TypeManager.byte_type || type == TypeManager.bool_type)
7111                                 ig.Emit (OpCodes.Ldelem_U1);
7112                         else if (type == TypeManager.sbyte_type)
7113                                 ig.Emit (OpCodes.Ldelem_I1);
7114                         else if (type == TypeManager.short_type)
7115                                 ig.Emit (OpCodes.Ldelem_I2);
7116                         else if (type == TypeManager.ushort_type || type == TypeManager.char_type)
7117                                 ig.Emit (OpCodes.Ldelem_U2);
7118                         else if (type == TypeManager.int32_type)
7119                                 ig.Emit (OpCodes.Ldelem_I4);
7120                         else if (type == TypeManager.uint32_type)
7121                                 ig.Emit (OpCodes.Ldelem_U4);
7122                         else if (type == TypeManager.uint64_type)
7123                                 ig.Emit (OpCodes.Ldelem_I8);
7124                         else if (type == TypeManager.int64_type)
7125                                 ig.Emit (OpCodes.Ldelem_I8);
7126                         else if (type == TypeManager.float_type)
7127                                 ig.Emit (OpCodes.Ldelem_R4);
7128                         else if (type == TypeManager.double_type)
7129                                 ig.Emit (OpCodes.Ldelem_R8);
7130                         else if (type == TypeManager.intptr_type)
7131                                 ig.Emit (OpCodes.Ldelem_I);
7132                         else if (type.IsValueType){
7133                                 ig.Emit (OpCodes.Ldelema, type);
7134                                 ig.Emit (OpCodes.Ldobj, type);
7135                         } else 
7136                                 ig.Emit (OpCodes.Ldelem_Ref);
7137                 }
7138
7139                 /// <summary>
7140                 ///    Emits the right opcode to store an object of Type `t'
7141                 ///    from an array of T.  
7142                 /// </summary>
7143                 static public void EmitStoreOpcode (ILGenerator ig, Type t)
7144                 {
7145                         bool is_stobj;
7146                         OpCode op = GetStoreOpcode (t, out is_stobj);
7147                         if (is_stobj)
7148                                 ig.Emit (OpCodes.Stobj, t);
7149                         else
7150                                 ig.Emit (op);
7151                 }
7152
7153                 /// <summary>
7154                 ///    Returns the right opcode to store an object of Type `t'
7155                 ///    from an array of T.  
7156                 /// </summary>
7157                 static public OpCode GetStoreOpcode (Type t, out bool is_stobj)
7158                 {
7159                         //Console.WriteLine (new System.Diagnostics.StackTrace ());
7160                         is_stobj = false;
7161                         t = TypeManager.TypeToCoreType (t);
7162                         if (TypeManager.IsEnumType (t) && t != TypeManager.enum_type)
7163                                 t = TypeManager.EnumToUnderlying (t);
7164                         if (t == TypeManager.byte_type || t == TypeManager.sbyte_type ||
7165                             t == TypeManager.bool_type)
7166                                 return OpCodes.Stelem_I1;
7167                         else if (t == TypeManager.short_type || t == TypeManager.ushort_type ||
7168                                  t == TypeManager.char_type)
7169                                 return OpCodes.Stelem_I2;
7170                         else if (t == TypeManager.int32_type || t == TypeManager.uint32_type)
7171                                 return OpCodes.Stelem_I4;
7172                         else if (t == TypeManager.int64_type || t == TypeManager.uint64_type)
7173                                 return OpCodes.Stelem_I8;
7174                         else if (t == TypeManager.float_type)
7175                                 return OpCodes.Stelem_R4;
7176                         else if (t == TypeManager.double_type)
7177                                 return OpCodes.Stelem_R8;
7178                         else if (t == TypeManager.intptr_type) {
7179                                 is_stobj = true;
7180                                 return OpCodes.Stobj;
7181                         } else if (t.IsValueType) {
7182                                 is_stobj = true;
7183                                 return OpCodes.Stobj;
7184                         } else
7185                                 return OpCodes.Stelem_Ref;
7186                 }
7187
7188                 MethodInfo FetchGetMethod ()
7189                 {
7190                         ModuleBuilder mb = CodeGen.ModuleBuilder;
7191                         int arg_count = ea.Arguments.Count;
7192                         Type [] args = new Type [arg_count];
7193                         MethodInfo get;
7194                         
7195                         for (int i = 0; i < arg_count; i++){
7196                                 //args [i++] = a.Type;
7197                                 args [i] = TypeManager.int32_type;
7198                         }
7199                         
7200                         get = mb.GetArrayMethod (
7201                                 ea.Expr.Type, "Get",
7202                                 CallingConventions.HasThis |
7203                                 CallingConventions.Standard,
7204                                 type, args);
7205                         return get;
7206                 }
7207                                 
7208
7209                 MethodInfo FetchAddressMethod ()
7210                 {
7211                         ModuleBuilder mb = CodeGen.ModuleBuilder;
7212                         int arg_count = ea.Arguments.Count;
7213                         Type [] args = new Type [arg_count];
7214                         MethodInfo address;
7215                         Type ret_type;
7216                         
7217                         ret_type = TypeManager.GetReferenceType (type);
7218                         
7219                         for (int i = 0; i < arg_count; i++){
7220                                 //args [i++] = a.Type;
7221                                 args [i] = TypeManager.int32_type;
7222                         }
7223                         
7224                         address = mb.GetArrayMethod (
7225                                 ea.Expr.Type, "Address",
7226                                 CallingConventions.HasThis |
7227                                 CallingConventions.Standard,
7228                                 ret_type, args);
7229
7230                         return address;
7231                 }
7232
7233                 //
7234                 // Load the array arguments into the stack.
7235                 //
7236                 // If we have been requested to cache the values (cached_locations array
7237                 // initialized), then load the arguments the first time and store them
7238                 // in locals.  otherwise load from local variables.
7239                 //
7240                 void LoadArrayAndArguments (EmitContext ec)
7241                 {
7242                         ILGenerator ig = ec.ig;
7243                         
7244                         if (cached_locations == null){
7245                                 ea.Expr.Emit (ec);
7246                                 foreach (Argument a in ea.Arguments){
7247                                         Type argtype = a.Expr.Type;
7248                                         
7249                                         a.Expr.Emit (ec);
7250                                         
7251                                         if (argtype == TypeManager.int64_type)
7252                                                 ig.Emit (OpCodes.Conv_Ovf_I);
7253                                         else if (argtype == TypeManager.uint64_type)
7254                                                 ig.Emit (OpCodes.Conv_Ovf_I_Un);
7255                                 }
7256                                 return;
7257                         }
7258
7259                         if (cached_locations [0] == null){
7260                                 cached_locations [0] = new LocalTemporary (ec, ea.Expr.Type);
7261                                 ea.Expr.Emit (ec);
7262                                 ig.Emit (OpCodes.Dup);
7263                                 cached_locations [0].Store (ec);
7264                                 
7265                                 int j = 1;
7266                                 
7267                                 foreach (Argument a in ea.Arguments){
7268                                         Type argtype = a.Expr.Type;
7269                                         
7270                                         cached_locations [j] = new LocalTemporary (ec, TypeManager.intptr_type /* a.Expr.Type */);
7271                                         a.Expr.Emit (ec);
7272                                         if (argtype == TypeManager.int64_type)
7273                                                 ig.Emit (OpCodes.Conv_Ovf_I);
7274                                         else if (argtype == TypeManager.uint64_type)
7275                                                 ig.Emit (OpCodes.Conv_Ovf_I_Un);
7276
7277                                         ig.Emit (OpCodes.Dup);
7278                                         cached_locations [j].Store (ec);
7279                                         j++;
7280                                 }
7281                                 return;
7282                         }
7283
7284                         foreach (LocalTemporary lt in cached_locations)
7285                                 lt.Emit (ec);
7286                 }
7287
7288                 public new void CacheTemporaries (EmitContext ec)
7289                 {
7290                         cached_locations = new LocalTemporary [ea.Arguments.Count + 1];
7291                 }
7292                 
7293                 public override void Emit (EmitContext ec)
7294                 {
7295                         int rank = ea.Expr.Type.GetArrayRank ();
7296                         ILGenerator ig = ec.ig;
7297
7298                         LoadArrayAndArguments (ec);
7299                         
7300                         if (rank == 1)
7301                                 EmitLoadOpcode (ig, type);
7302                         else {
7303                                 MethodInfo method;
7304                                 
7305                                 method = FetchGetMethod ();
7306                                 ig.Emit (OpCodes.Call, method);
7307                         }
7308                 }
7309
7310                 public void EmitAssign (EmitContext ec, Expression source)
7311                 {
7312                         int rank = ea.Expr.Type.GetArrayRank ();
7313                         ILGenerator ig = ec.ig;
7314                         Type t = source.Type;
7315
7316                         LoadArrayAndArguments (ec);
7317
7318                         //
7319                         // The stobj opcode used by value types will need
7320                         // an address on the stack, not really an array/array
7321                         // pair
7322                         //
7323                         if (rank == 1){
7324                                 if (t == TypeManager.enum_type || t == TypeManager.decimal_type ||
7325                                     (t.IsSubclassOf (TypeManager.value_type) && !TypeManager.IsEnumType (t) && !TypeManager.IsBuiltinType (t)))
7326                                         ig.Emit (OpCodes.Ldelema, t);
7327                         }
7328                         
7329                         source.Emit (ec);
7330
7331                         if (rank == 1)
7332                                 EmitStoreOpcode (ig, t);
7333                         else {
7334                                 ModuleBuilder mb = CodeGen.ModuleBuilder;
7335                                 int arg_count = ea.Arguments.Count;
7336                                 Type [] args = new Type [arg_count + 1];
7337                                 MethodInfo set;
7338                                 
7339                                 for (int i = 0; i < arg_count; i++){
7340                                         //args [i++] = a.Type;
7341                                         args [i] = TypeManager.int32_type;
7342                                 }
7343
7344                                 args [arg_count] = type;
7345                                 
7346                                 set = mb.GetArrayMethod (
7347                                         ea.Expr.Type, "Set",
7348                                         CallingConventions.HasThis |
7349                                         CallingConventions.Standard,
7350                                         TypeManager.void_type, args);
7351                                 
7352                                 ig.Emit (OpCodes.Call, set);
7353                         }
7354                 }
7355
7356                 public void AddressOf (EmitContext ec, AddressOp mode)
7357                 {
7358                         int rank = ea.Expr.Type.GetArrayRank ();
7359                         ILGenerator ig = ec.ig;
7360
7361                         LoadArrayAndArguments (ec);
7362
7363                         if (rank == 1){
7364                                 ig.Emit (OpCodes.Ldelema, type);
7365                         } else {
7366                                 MethodInfo address = FetchAddressMethod ();
7367                                 ig.Emit (OpCodes.Call, address);
7368                         }
7369                 }
7370         }
7371
7372         
7373         class Indexers {
7374                 public ArrayList properties;
7375                 static Hashtable map;
7376
7377                 static Indexers ()
7378                 {
7379                         map = new Hashtable ();
7380                 }
7381
7382                 Indexers ()
7383                 {
7384                         properties = new ArrayList ();
7385                 }
7386                                 
7387                 void Append (MemberInfo [] mi)
7388                 {
7389                         foreach (PropertyInfo property in mi){
7390                                 MethodInfo get, set;
7391                                 
7392                                 get = property.GetGetMethod (true);
7393                                 set = property.GetSetMethod (true);
7394                                 properties.Add (new Pair (get, set));
7395                         }
7396                 }
7397
7398                 static private MemberInfo [] GetIndexersForTypeOrInterface (Type caller_type, Type lookup_type)
7399                 {
7400                         string p_name = TypeManager.IndexerPropertyName (lookup_type);
7401
7402                         MemberInfo [] mi = TypeManager.MemberLookup (
7403                                 caller_type, caller_type, lookup_type, MemberTypes.Property,
7404                                 BindingFlags.Public | BindingFlags.Instance |
7405                                 BindingFlags.DeclaredOnly, p_name);
7406
7407                         if (mi == null || mi.Length == 0)
7408                                 return null;
7409
7410                         return mi;
7411                 }
7412                 
7413                 static public Indexers GetIndexersForType (Type caller_type, Type lookup_type, Location loc) 
7414                 {
7415                         Indexers ix = (Indexers) map [lookup_type];
7416                         
7417                         if (ix != null)
7418                                 return ix;
7419
7420                         Type copy = lookup_type;
7421                         while (copy != TypeManager.object_type && copy != null){
7422                                 MemberInfo [] mi = GetIndexersForTypeOrInterface (caller_type, copy);
7423
7424                                 if (mi != null){
7425                                         if (ix == null)
7426                                                 ix = new Indexers ();
7427
7428                                         ix.Append (mi);
7429                                 }
7430                                         
7431                                 copy = copy.BaseType;
7432                         }
7433
7434                         return ix;
7435                 }
7436         }
7437
7438         /// <summary>
7439         ///   Expressions that represent an indexer call.
7440         /// </summary>
7441         public class IndexerAccess : Expression, IAssignMethod {
7442                 //
7443                 // Points to our "data" repository
7444                 //
7445                 MethodInfo get, set;
7446                 ArrayList set_arguments;
7447                 bool is_base_indexer;
7448
7449                 protected Type indexer_type;
7450                 protected Type current_type;
7451                 protected Expression instance_expr;
7452                 protected ArrayList arguments;
7453                 
7454                 public IndexerAccess (ElementAccess ea, Location loc)
7455                         : this (ea.Expr, false, loc)
7456                 {
7457                         this.arguments = ea.Arguments;
7458                 }
7459
7460                 protected IndexerAccess (Expression instance_expr, bool is_base_indexer,
7461                                          Location loc)
7462                 {
7463                         this.instance_expr = instance_expr;
7464                         this.is_base_indexer = is_base_indexer;
7465                         this.eclass = ExprClass.Value;
7466                         this.loc = loc;
7467                 }
7468
7469                 protected virtual bool CommonResolve (EmitContext ec)
7470                 {
7471                         indexer_type = instance_expr.Type;
7472                         current_type = ec.ContainerType;
7473
7474                         return true;
7475                 }
7476
7477                 public override Expression DoResolve (EmitContext ec)
7478                 {
7479                         ArrayList AllGetters = new ArrayList();
7480                         if (!CommonResolve (ec))
7481                                 return null;
7482
7483                         //
7484                         // Step 1: Query for all `Item' *properties*.  Notice
7485                         // that the actual methods are pointed from here.
7486                         //
7487                         // This is a group of properties, piles of them.  
7488
7489                         bool found_any = false, found_any_getters = false;
7490                         Type lookup_type = indexer_type;
7491
7492                         Indexers ilist;
7493                         ilist = Indexers.GetIndexersForType (current_type, lookup_type, loc);
7494                         if (ilist != null) {
7495                                 found_any = true;
7496                                 if (ilist.properties != null) {
7497                                         foreach (Pair o in ilist.properties) {
7498                                                 if (o.First != null)
7499                                                         AllGetters.Add(o.First);
7500                                         }
7501                                 }
7502                         }
7503
7504                         if (AllGetters.Count > 0) {
7505                                 found_any_getters = true;
7506                                 get = (MethodInfo) Invocation.OverloadResolve (
7507                                         ec, new MethodGroupExpr (AllGetters, loc), arguments, loc);
7508                         }
7509
7510                         if (!found_any) {
7511                                 Report.Error (21, loc,
7512                                               "Type `" + TypeManager.CSharpName (indexer_type) +
7513                                               "' does not have any indexers defined");
7514                                 return null;
7515                         }
7516
7517                         if (!found_any_getters) {
7518                                 Error (154, "indexer can not be used in this context, because " +
7519                                        "it lacks a `get' accessor");
7520                                 return null;
7521                         }
7522
7523                         if (get == null) {
7524                                 Error (1501, "No Overload for method `this' takes `" +
7525                                        arguments.Count + "' arguments");
7526                                 return null;
7527                         }
7528
7529                         //
7530                         // Only base will allow this invocation to happen.
7531                         //
7532                         if (get.IsAbstract && this is BaseIndexerAccess){
7533                                 Report.Error (205, loc, "Cannot call an abstract base indexer: " + Invocation.FullMethodDesc (get));
7534                                 return null;
7535                         }
7536
7537                         type = get.ReturnType;
7538                         if (type.IsPointer && !ec.InUnsafe){
7539                                 UnsafeError (loc);
7540                                 return null;
7541                         }
7542                         
7543                         eclass = ExprClass.IndexerAccess;
7544                         return this;
7545                 }
7546
7547                 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7548                 {
7549                         ArrayList AllSetters = new ArrayList();
7550                         if (!CommonResolve (ec))
7551                                 return null;
7552
7553                         Type right_type = right_side.Type;
7554
7555                         bool found_any = false, found_any_setters = false;
7556
7557                         Indexers ilist = Indexers.GetIndexersForType (current_type, indexer_type, loc);
7558                         if (ilist != null) {
7559                                 found_any = true;
7560                                 if (ilist.properties != null) {
7561                                         foreach (Pair o in ilist.properties) {
7562                                                 if (o.Second != null)
7563                                                         AllSetters.Add(o.Second);
7564                                         }
7565                                 }
7566                         }
7567                         if (AllSetters.Count > 0) {
7568                                 found_any_setters = true;
7569                                 set_arguments = (ArrayList) arguments.Clone ();
7570                                 set_arguments.Add (new Argument (right_side, Argument.AType.Expression));
7571                                 set = (MethodInfo) Invocation.OverloadResolve (
7572                                         ec, new MethodGroupExpr (AllSetters, loc),
7573                                         set_arguments, loc);
7574                         }
7575
7576                         if (!found_any) {
7577                                 Report.Error (21, loc,
7578                                               "Type `" + TypeManager.CSharpName (indexer_type) +
7579                                               "' does not have any indexers defined");
7580                                 return null;
7581                         }
7582
7583                         if (!found_any_setters) {
7584                                 Error (154, "indexer can not be used in this context, because " +
7585                                        "it lacks a `set' accessor");
7586                                 return null;
7587                         }
7588
7589                         if (set == null) {
7590                                 Error (1501, "No Overload for method `this' takes `" +
7591                                        arguments.Count + "' arguments");
7592                                 return null;
7593                         }
7594
7595                         //
7596                         // Only base will allow this invocation to happen.
7597                         //
7598                         if (set.IsAbstract && this is BaseIndexerAccess){
7599                                 Report.Error (205, loc, "Cannot call an abstract base indexer: " + Invocation.FullMethodDesc (set));
7600                                 return null;
7601                         }
7602
7603                         //
7604                         // Now look for the actual match in the list of indexers to set our "return" type
7605                         //
7606                         type = TypeManager.void_type;   // default value
7607                         foreach (Pair t in ilist.properties){
7608                                 if (t.Second == set){
7609                                         if (t.First != null)
7610                                                 type = ((MethodInfo) t.First).ReturnType;
7611                                         break;
7612                                 }
7613                         }
7614                         
7615                         eclass = ExprClass.IndexerAccess;
7616                         return this;
7617                 }
7618                 
7619                 public override void Emit (EmitContext ec)
7620                 {
7621                         Invocation.EmitCall (ec, is_base_indexer, false, instance_expr, get, arguments, loc);
7622                 }
7623
7624                 //
7625                 // source is ignored, because we already have a copy of it from the
7626                 // LValue resolution and we have already constructed a pre-cached
7627                 // version of the arguments (ea.set_arguments);
7628                 //
7629                 public void EmitAssign (EmitContext ec, Expression source)
7630                 {
7631                         Invocation.EmitCall (ec, is_base_indexer, false, instance_expr, set, set_arguments, loc);
7632                 }
7633         }
7634
7635         /// <summary>
7636         ///   The base operator for method names
7637         /// </summary>
7638         public class BaseAccess : Expression {
7639                 string member;
7640                 
7641                 public BaseAccess (string member, Location l)
7642                 {
7643                         this.member = member;
7644                         loc = l;
7645                 }
7646
7647                 public override Expression DoResolve (EmitContext ec)
7648                 {
7649                         Expression c = CommonResolve (ec);
7650
7651                         if (c == null)
7652                                 return null;
7653
7654                         //
7655                         // MethodGroups use this opportunity to flag an error on lacking ()
7656                         //
7657                         if (!(c is MethodGroupExpr))
7658                                 return c.Resolve (ec);
7659                         return c;
7660                 }
7661
7662                 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
7663                 {
7664                         Expression c = CommonResolve (ec);
7665
7666                         if (c == null)
7667                                 return null;
7668
7669                         //
7670                         // MethodGroups use this opportunity to flag an error on lacking ()
7671                         //
7672                         if (! (c is MethodGroupExpr))
7673                                 return c.DoResolveLValue (ec, right_side);
7674
7675                         return c;
7676                 }
7677
7678                 Expression CommonResolve (EmitContext ec)
7679                 {
7680                         Expression member_lookup;
7681                         Type current_type = ec.ContainerType;
7682                         Type base_type = current_type.BaseType;
7683                         Expression e;
7684
7685                         if (ec.IsStatic){
7686                                 Error (1511, "Keyword base is not allowed in static method");
7687                                 return null;
7688                         }
7689                         
7690                         member_lookup = MemberLookup (ec, ec.ContainerType, null, base_type, member,
7691                                                       AllMemberTypes, AllBindingFlags, loc);
7692                         if (member_lookup == null) {
7693                                 MemberLookupFailed (ec, base_type, base_type, member, null, loc);
7694                                 return null;
7695                         }
7696
7697                         Expression left;
7698                         
7699                         if (ec.IsStatic)
7700                                 left = new TypeExpr (base_type, loc);
7701                         else
7702                                 left = ec.GetThis (loc);
7703                         
7704                         e = MemberAccess.ResolveMemberAccess (ec, member_lookup, left, loc, null);
7705
7706                         if (e is PropertyExpr){
7707                                 PropertyExpr pe = (PropertyExpr) e;
7708
7709                                 pe.IsBase = true;
7710                         }
7711
7712                         return e;
7713                 }
7714
7715                 public override void Emit (EmitContext ec)
7716                 {
7717                         throw new Exception ("Should never be called"); 
7718                 }
7719         }
7720
7721         /// <summary>
7722         ///   The base indexer operator
7723         /// </summary>
7724         public class BaseIndexerAccess : IndexerAccess {
7725                 public BaseIndexerAccess (ArrayList args, Location loc)
7726                         : base (null, true, loc)
7727                 {
7728                         arguments = new ArrayList ();
7729                         foreach (Expression tmp in args)
7730                                 arguments.Add (new Argument (tmp, Argument.AType.Expression));
7731                 }
7732
7733                 protected override bool CommonResolve (EmitContext ec)
7734                 {
7735                         instance_expr = ec.GetThis (loc);
7736
7737                         current_type = ec.ContainerType.BaseType;
7738                         indexer_type = current_type;
7739
7740                         foreach (Argument a in arguments){
7741                                 if (!a.Resolve (ec, loc))
7742                                         return false;
7743                         }
7744
7745                         return true;
7746                 }
7747         }
7748         
7749         /// <summary>
7750         ///   This class exists solely to pass the Type around and to be a dummy
7751         ///   that can be passed to the conversion functions (this is used by
7752         ///   foreach implementation to typecast the object return value from
7753         ///   get_Current into the proper type.  All code has been generated and
7754         ///   we only care about the side effect conversions to be performed
7755         ///
7756         ///   This is also now used as a placeholder where a no-action expression
7757         ///   is needed (the `New' class).
7758         /// </summary>
7759         public class EmptyExpression : Expression {
7760                 public EmptyExpression ()
7761                 {
7762                         type = TypeManager.object_type;
7763                         eclass = ExprClass.Value;
7764                         loc = Location.Null;
7765                 }
7766
7767                 public EmptyExpression (Type t)
7768                 {
7769                         type = t;
7770                         eclass = ExprClass.Value;
7771                         loc = Location.Null;
7772                 }
7773                 
7774                 public override Expression DoResolve (EmitContext ec)
7775                 {
7776                         return this;
7777                 }
7778
7779                 public override void Emit (EmitContext ec)
7780                 {
7781                         // nothing, as we only exist to not do anything.
7782                 }
7783
7784                 //
7785                 // This is just because we might want to reuse this bad boy
7786                 // instead of creating gazillions of EmptyExpressions.
7787                 // (CanImplicitConversion uses it)
7788                 //
7789                 public void SetType (Type t)
7790                 {
7791                         type = t;
7792                 }
7793         }
7794
7795         public class UserCast : Expression {
7796                 MethodBase method;
7797                 Expression source;
7798                 
7799                 public UserCast (MethodInfo method, Expression source, Location l)
7800                 {
7801                         this.method = method;
7802                         this.source = source;
7803                         type = method.ReturnType;
7804                         eclass = ExprClass.Value;
7805                         loc = l;
7806                 }
7807
7808                 public override Expression DoResolve (EmitContext ec)
7809                 {
7810                         //
7811                         // We are born fully resolved
7812                         //
7813                         return this;
7814                 }
7815
7816                 public override void Emit (EmitContext ec)
7817                 {
7818                         ILGenerator ig = ec.ig;
7819
7820                         source.Emit (ec);
7821                         
7822                         if (method is MethodInfo)
7823                                 ig.Emit (OpCodes.Call, (MethodInfo) method);
7824                         else
7825                                 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
7826
7827                 }
7828         }
7829
7830         // <summary>
7831         //   This class is used to "construct" the type during a typecast
7832         //   operation.  Since the Type.GetType class in .NET can parse
7833         //   the type specification, we just use this to construct the type
7834         //   one bit at a time.
7835         // </summary>
7836         public class ComposedCast : Expression {
7837                 Expression left;
7838                 string dim;
7839                 
7840                 public ComposedCast (Expression left, string dim, Location l)
7841                 {
7842                         this.left = left;
7843                         this.dim = dim;
7844                         loc = l;
7845                 }
7846
7847                 public override Expression ResolveAsTypeStep (EmitContext ec)
7848                 {
7849                         Type ltype = ec.DeclSpace.ResolveType (left, false, loc);
7850                         if (ltype == null)
7851                                 return null;
7852
7853                         //
7854                         // ltype.Fullname is already fully qualified, so we can skip
7855                         // a lot of probes, and go directly to TypeManager.LookupType
7856                         //
7857                         string cname = ltype.FullName + dim;
7858                         type = TypeManager.LookupTypeDirect (cname);
7859                         if (type == null){
7860                                 //
7861                                 // For arrays of enumerations we are having a problem
7862                                 // with the direct lookup.  Need to investigate.
7863                                 //
7864                                 // For now, fall back to the full lookup in that case.
7865                                 //
7866                                 type = RootContext.LookupType (
7867                                         ec.DeclSpace, cname, false, loc);
7868
7869                                 if (type == null)
7870                                         return null;
7871                         }
7872
7873                         if (!ec.ResolvingTypeTree){
7874                                 //
7875                                 // If the above flag is set, this is being invoked from the ResolveType function.
7876                                 // Upper layers take care of the type validity in this context.
7877                                 //
7878                         if (!ec.InUnsafe && type.IsPointer){
7879                                 UnsafeError (loc);
7880                                 return null;
7881                         }
7882                         }
7883                         
7884                         eclass = ExprClass.Type;
7885                         return this;
7886                 }
7887
7888                 public override Expression DoResolve (EmitContext ec)
7889                 {
7890                         return ResolveAsTypeStep (ec);
7891                 }
7892
7893                 public override void Emit (EmitContext ec)
7894                 {
7895                         throw new Exception ("This should never be called");
7896                 }
7897
7898                 public override string ToString ()
7899                 {
7900                         return left + dim;
7901                 }
7902         }
7903
7904         //
7905         // This class is used to represent the address of an array, used
7906         // only by the Fixed statement, this is like the C "&a [0]" construct.
7907         //
7908         public class ArrayPtr : Expression {
7909                 Expression array;
7910                 
7911                 public ArrayPtr (Expression array, Location l)
7912                 {
7913                         Type array_type = TypeManager.GetElementType (array.Type);
7914
7915                         this.array = array;
7916
7917                         type = TypeManager.GetPointerType (array_type);
7918                         eclass = ExprClass.Value;
7919                         loc = l;
7920                 }
7921
7922                 public override void Emit (EmitContext ec)
7923                 {
7924                         ILGenerator ig = ec.ig;
7925                         
7926                         array.Emit (ec);
7927                         IntLiteral.EmitInt (ig, 0);
7928                         ig.Emit (OpCodes.Ldelema, TypeManager.GetElementType (array.Type));
7929                 }
7930
7931                 public override Expression DoResolve (EmitContext ec)
7932                 {
7933                         //
7934                         // We are born fully resolved
7935                         //
7936                         return this;
7937                 }
7938         }
7939
7940         //
7941         // Used by the fixed statement
7942         //
7943         public class StringPtr : Expression {
7944                 LocalBuilder b;
7945                 
7946                 public StringPtr (LocalBuilder b, Location l)
7947                 {
7948                         this.b = b;
7949                         eclass = ExprClass.Value;
7950                         type = TypeManager.char_ptr_type;
7951                         loc = l;
7952                 }
7953
7954                 public override Expression DoResolve (EmitContext ec)
7955                 {
7956                         // This should never be invoked, we are born in fully
7957                         // initialized state.
7958
7959                         return this;
7960                 }
7961
7962                 public override void Emit (EmitContext ec)
7963                 {
7964                         ILGenerator ig = ec.ig;
7965
7966                         ig.Emit (OpCodes.Ldloc, b);
7967                         ig.Emit (OpCodes.Conv_I);
7968                         ig.Emit (OpCodes.Call, TypeManager.int_get_offset_to_string_data);
7969                         ig.Emit (OpCodes.Add);
7970                 }
7971         }
7972         
7973         //
7974         // Implements the `stackalloc' keyword
7975         //
7976         public class StackAlloc : Expression {
7977                 Type otype;
7978                 Expression t;
7979                 Expression count;
7980                 
7981                 public StackAlloc (Expression type, Expression count, Location l)
7982                 {
7983                         t = type;
7984                         this.count = count;
7985                         loc = l;
7986                 }
7987
7988                 public override Expression DoResolve (EmitContext ec)
7989                 {
7990                         count = count.Resolve (ec);
7991                         if (count == null)
7992                                 return null;
7993                         
7994                         if (count.Type != TypeManager.int32_type){
7995                                 count = Convert.ImplicitConversionRequired (ec, count, TypeManager.int32_type, loc);
7996                                 if (count == null)
7997                                         return null;
7998                         }
7999
8000                         if (ec.InCatch || ec.InFinally){
8001                                 Error (255,
8002                                               "stackalloc can not be used in a catch or finally block");
8003                                 return null;
8004                         }
8005
8006                         otype = ec.DeclSpace.ResolveType (t, false, loc);
8007
8008                         if (otype == null)
8009                                 return null;
8010
8011                         if (!TypeManager.VerifyUnManaged (otype, loc))
8012                                 return null;
8013
8014                         type = TypeManager.GetPointerType (otype);
8015                         eclass = ExprClass.Value;
8016
8017                         return this;
8018                 }
8019
8020                 public override void Emit (EmitContext ec)
8021                 {
8022                         int size = GetTypeSize (otype);
8023                         ILGenerator ig = ec.ig;
8024                                 
8025                         if (size == 0)
8026                                 ig.Emit (OpCodes.Sizeof, otype);
8027                         else
8028                                 IntConstant.EmitInt (ig, size);
8029                         count.Emit (ec);
8030                         ig.Emit (OpCodes.Mul);
8031                         ig.Emit (OpCodes.Localloc);
8032                 }
8033         }
8034 }