2001-12-23 Miguel de Icaza <miguel@ximian.com>
[mono.git] / mcs / mcs / expression.cs
1 //
2 // expression.cs: Expression representation for the IL tree.
3 //
4 // Author:
5 //   Miguel de Icaza (miguel@ximian.com)
6 //
7 // (C) 2001 Ximian, Inc.
8 //
9 //
10 #define USE_OLD
11
12 namespace Mono.CSharp {
13         using System;
14         using System.Collections;
15         using System.Diagnostics;
16         using System.Reflection;
17         using System.Reflection.Emit;
18         using System.Text;
19
20         /// <summary>
21         ///   This is just a helper class, it is generated by Unary, UnaryMutator
22         ///   when an overloaded method has been found.  It just emits the code for a
23         ///   static call.
24         /// </summary>
25         public class StaticCallExpr : ExpressionStatement {
26                 ArrayList args;
27                 MethodInfo mi;
28
29                 StaticCallExpr (MethodInfo m, ArrayList a)
30                 {
31                         mi = m;
32                         args = a;
33
34                         type = m.ReturnType;
35                         eclass = ExprClass.Value;
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                         args.Add (new Argument (e, Argument.AType.Expression));
63                         method = Invocation.OverloadResolve (ec, (MethodGroupExpr) mg, args, loc);
64
65                         if (method == null)
66                                 return null;
67
68                         return new StaticCallExpr ((MethodInfo) method, args);
69                 }
70
71                 public override void EmitStatement (EmitContext ec)
72                 {
73                         Emit (ec);
74                         if (type != TypeManager.void_type)
75                                 ec.ig.Emit (OpCodes.Pop);
76                 }
77         }
78         
79         /// <summary>
80         ///   Unary expressions.  
81         /// </summary>
82         ///
83         /// <remarks>
84         ///   Unary implements unary expressions.   It derives from
85         ///   ExpressionStatement becuase the pre/post increment/decrement
86         ///   operators can be used in a statement context.
87         /// </remarks>
88         public class Unary : Expression {
89                 public enum Operator : byte {
90                         UnaryPlus, UnaryNegation, LogicalNot, OnesComplement,
91                         Indirection, AddressOf,  TOP
92                 }
93
94                 Operator   oper;
95                 Expression expr;
96                 Location   loc;
97                 
98                 public Unary (Operator op, Expression expr, Location loc)
99                 {
100                         this.oper = op;
101                         this.expr = expr;
102                         this.loc = loc;
103                 }
104
105                 public Expression Expr {
106                         get {
107                                 return expr;
108                         }
109
110                         set {
111                                 expr = value;
112                         }
113                 }
114
115                 public Operator Oper {
116                         get {
117                                 return oper;
118                         }
119
120                         set {
121                                 oper = value;
122                         }
123                 }
124
125                 /// <summary>
126                 ///   Returns a stringified representation of the Operator
127                 /// </summary>
128                 string OperName ()
129                 {
130                         switch (oper){
131                         case Operator.UnaryPlus:
132                                 return "+";
133                         case Operator.UnaryNegation:
134                                 return "-";
135                         case Operator.LogicalNot:
136                                 return "!";
137                         case Operator.OnesComplement:
138                                 return "~";
139                         case Operator.AddressOf:
140                                 return "&";
141                         case Operator.Indirection:
142                                 return "*";
143                         }
144
145                         return oper.ToString ();
146                 }
147
148                 static string [] oper_names;
149
150                 static Unary ()
151                 {
152                         oper_names = new string [(int)Operator.TOP];
153
154                         oper_names [(int) Operator.UnaryPlus] = "op_UnaryPlus";
155                         oper_names [(int) Operator.UnaryNegation] = "op_UnaryNegation";
156                         oper_names [(int) Operator.LogicalNot] = "op_LogicalNot";
157                         oper_names [(int) Operator.OnesComplement] = "op_OnesComplement";
158                         oper_names [(int) Operator.Indirection] = "op_Indirection";
159                         oper_names [(int) Operator.AddressOf] = "op_AddressOf";
160                 }
161
162                 void error23 (Type t)
163                 {
164                         Report.Error (
165                                 23, loc, "Operator " + OperName () +
166                                 " cannot be applied to operand of type `" +
167                                 TypeManager.CSharpName (t) + "'");
168                 }
169
170                 /// <remarks>
171                 ///   The result has been already resolved:
172                 ///
173                 ///   FIXME: a minus constant -128 sbyte cant be turned into a
174                 ///   constant byte.
175                 /// </remarks>
176                 static Expression TryReduceNegative (Expression expr)
177                 {
178                         Expression e = null;
179                         
180                         if (expr is IntConstant)
181                                 e = new IntConstant (-((IntConstant) expr).Value);
182                         else if (expr is UIntConstant)
183                                 e = new LongConstant (-((UIntConstant) expr).Value);
184                         else if (expr is LongConstant)
185                                 e = new LongConstant (-((LongConstant) expr).Value);
186                         else if (expr is FloatConstant)
187                                 e = new FloatConstant (-((FloatConstant) expr).Value);
188                         else if (expr is DoubleConstant)
189                                 e = new DoubleConstant (-((DoubleConstant) expr).Value);
190                         else if (expr is DecimalConstant)
191                                 e = new DecimalConstant (-((DecimalConstant) expr).Value);
192                         else if (expr is ShortConstant)
193                                 e = new IntConstant (-((ShortConstant) expr).Value);
194                         else if (expr is UShortConstant)
195                                 e = new IntConstant (-((UShortConstant) expr).Value);
196
197                         return e;
198                 }
199                 
200                 Expression Reduce (EmitContext ec, Expression e)
201                 {
202                         Type expr_type = e.Type;
203                         
204                         switch (oper){
205                         case Operator.UnaryPlus:
206                                 return e;
207                                 
208                         case Operator.UnaryNegation:
209                                 return TryReduceNegative (e);
210                                 
211                         case Operator.LogicalNot:
212                                 if (expr_type != TypeManager.bool_type) {
213                                         error23 (expr_type);
214                                         return null;
215                                 }
216                                 
217                                 BoolConstant b = (BoolConstant) e;
218                                 return new BoolConstant (!(b.Value));
219                                 
220                         case Operator.OnesComplement:
221                                 if (!((expr_type == TypeManager.int32_type) ||
222                                       (expr_type == TypeManager.uint32_type) ||
223                                       (expr_type == TypeManager.int64_type) ||
224                                       (expr_type == TypeManager.uint64_type) ||
225                                       (expr_type.IsSubclassOf (TypeManager.enum_type)))){
226                                         error23 (expr_type);
227                                         return null;
228                                 }
229
230                                 if (e is EnumConstant){
231                                         EnumConstant enum_constant = (EnumConstant) e;
232                                         
233                                         Expression reduced = Reduce (ec, enum_constant.Child);
234
235                                         return new EnumConstant ((Constant) reduced, enum_constant.Type);
236                                 }
237
238                                 if (expr_type == TypeManager.int32_type)
239                                         return new IntConstant (~ ((IntConstant) e).Value);
240                                 if (expr_type == TypeManager.uint32_type)
241                                         return new UIntConstant (~ ((UIntConstant) e).Value);
242                                 if (expr_type == TypeManager.int64_type)
243                                         return new LongConstant (~ ((LongConstant) e).Value);
244                                 if (expr_type == TypeManager.uint64_type)
245                                         return new ULongConstant (~ ((ULongConstant) e).Value);
246
247                                 throw new Exception (
248                                         "FIXME: Implement constant OnesComplement of:" +
249                                         expr_type);
250                         }
251                         throw new Exception ("Can not constant fold");
252                 }
253
254                 Expression ResolveOperator (EmitContext ec)
255                 {
256                         Type expr_type = expr.Type;
257
258                         //
259                         // Step 1: Perform Operator Overload location
260                         //
261                         Expression mg;
262                         string op_name;
263                         
264                         op_name = oper_names [(int) oper];
265
266                         mg = MemberLookup (ec, expr_type, op_name, false, loc);
267                         
268                         if (mg == null && expr_type.BaseType != null)
269                                 mg = MemberLookup (ec, expr_type.BaseType, op_name, false, loc);
270                         
271                         if (mg != null) {
272                                 Expression e = StaticCallExpr.MakeSimpleCall (
273                                         ec, (MethodGroupExpr) mg, expr, loc);
274
275                                 if (e == null){
276                                         error23 (expr_type);
277                                         return null;
278                                 }
279                                 
280                                 return e;
281                         }
282
283                         // Only perform numeric promotions on:
284                         // +, - 
285
286                         if (expr_type == null)
287                                 return null;
288                         
289                         //
290                         // Step 2: Default operations on CLI native types.
291                         //
292                         if (expr is Constant)
293                                 return Reduce (ec, expr);
294
295                         if (oper == Operator.LogicalNot){
296                                 if (expr_type != TypeManager.bool_type) {
297                                         error23 (expr.Type);
298                                         return null;
299                                 }
300                                 
301                                 type = TypeManager.bool_type;
302                                 return this;
303                         }
304
305                         if (oper == Operator.OnesComplement) {
306                                 if (!((expr_type == TypeManager.int32_type) ||
307                                       (expr_type == TypeManager.uint32_type) ||
308                                       (expr_type == TypeManager.int64_type) ||
309                                       (expr_type == TypeManager.uint64_type) ||
310                                       (expr_type.IsSubclassOf (TypeManager.enum_type)))){
311                                         error23 (expr.Type);
312                                         return null;
313                                 }
314                                 type = expr_type;
315                                 return this;
316                         }
317
318                         if (oper == Operator.UnaryPlus) {
319                                 //
320                                 // A plus in front of something is just a no-op, so return the child.
321                                 //
322                                 return expr;
323                         }
324
325                         //
326                         // Deals with -literals
327                         // int     operator- (int x)
328                         // long    operator- (long x)
329                         // float   operator- (float f)
330                         // double  operator- (double d)
331                         // decimal operator- (decimal d)
332                         //
333                         if (oper == Operator.UnaryNegation){
334                                 //
335                                 // Fold a "- Constant" into a negative constant
336                                 //
337                         
338                                 Expression e = null;
339
340                                 //
341                                 // Not a constant we can optimize, perform numeric 
342                                 // promotions to int, long, double.
343                                 //
344                                 //
345                                 // The following is inneficient, because we call
346                                 // ConvertImplicit too many times.
347                                 //
348                                 // It is also not clear if we should convert to Float
349                                 // or Double initially.
350                                 //
351                                 if (expr_type == TypeManager.uint32_type){
352                                         //
353                                         // FIXME: handle exception to this rule that
354                                         // permits the int value -2147483648 (-2^31) to
355                                         // bt wrote as a decimal interger literal
356                                         //
357                                         type = TypeManager.int64_type;
358                                         expr = ConvertImplicit (ec, expr, type, loc);
359                                         return this;
360                                 }
361
362                                 if (expr_type == TypeManager.uint64_type){
363                                         //
364                                         // FIXME: Handle exception of `long value'
365                                         // -92233720368547758087 (-2^63) to be wrote as
366                                         // decimal integer literal.
367                                         //
368                                         error23 (expr_type);
369                                         return null;
370                                 }
371
372                                 e = ConvertImplicit (ec, expr, TypeManager.int32_type, loc);
373                                 if (e != null){
374                                         expr = e;
375                                         type = e.Type;
376                                         return this;
377                                 } 
378
379                                 e = ConvertImplicit (ec, expr, TypeManager.int64_type, loc);
380                                 if (e != null){
381                                         expr = e;
382                                         type = e.Type;
383                                         return this;
384                                 }
385
386                                 e = ConvertImplicit (ec, expr, TypeManager.double_type, loc);
387                                 if (e != null){
388                                         expr = e;
389                                         type = e.Type;
390                                         return this;
391                                 }
392
393                                 error23 (expr_type);
394                                 return null;
395                         }
396
397                         if (oper == Operator.AddressOf){
398                                 if (expr.eclass != ExprClass.Variable){
399                                         Error (211, loc, "Cannot take the address of non-variables");
400                                         return null;
401                                 }
402                                 type = Type.GetType (expr.Type.ToString () + "*");
403
404                                 return this;
405                         }
406                         
407                         Error (187, loc, "No such operator '" + OperName () + "' defined for type '" +
408                                TypeManager.CSharpName (expr_type) + "'");
409                         return null;
410                 }
411
412                 public override Expression DoResolve (EmitContext ec)
413                 {
414                         expr = expr.Resolve (ec);
415                         
416                         if (expr == null)
417                                 return null;
418
419                         eclass = ExprClass.Value;
420                         return ResolveOperator (ec);
421                 }
422
423                 public override void Emit (EmitContext ec)
424                 {
425                         ILGenerator ig = ec.ig;
426                         Type expr_type = expr.Type;
427                         
428                         switch (oper) {
429                         case Operator.UnaryPlus:
430                                 throw new Exception ("This should be caught by Resolve");
431                                 
432                         case Operator.UnaryNegation:
433                                 expr.Emit (ec);
434                                 ig.Emit (OpCodes.Neg);
435                                 break;
436                                 
437                         case Operator.LogicalNot:
438                                 expr.Emit (ec);
439                                 ig.Emit (OpCodes.Ldc_I4_0);
440                                 ig.Emit (OpCodes.Ceq);
441                                 break;
442                                 
443                         case Operator.OnesComplement:
444                                 expr.Emit (ec);
445                                 ig.Emit (OpCodes.Not);
446                                 break;
447                                 
448                         case Operator.AddressOf:
449                                 ((IMemoryLocation)expr).AddressOf (ec);
450                                 break;
451                                 
452                         case Operator.Indirection:
453                                 throw new Exception ("Not implemented yet");
454                                 
455                         default:
456                                 throw new Exception ("This should not happen: Operator = "
457                                                      + oper.ToString ());
458                         }
459                 }
460
461                 /// <summary>
462                 ///   This will emit the child expression for `ec' avoiding the logical
463                 ///   not.  The parent will take care of changing brfalse/brtrue
464                 /// </summary>
465                 public void EmitLogicalNot (EmitContext ec)
466                 {
467                         if (oper != Operator.LogicalNot)
468                                 throw new Exception ("EmitLogicalNot can only be called with !expr");
469
470                         expr.Emit (ec);
471                 }
472                 
473         }
474
475         /// <summary>
476         ///   Unary Mutator expressions (pre and post ++ and --)
477         /// </summary>
478         ///
479         /// <remarks>
480         ///   UnaryMutator implements ++ and -- expressions.   It derives from
481         ///   ExpressionStatement becuase the pre/post increment/decrement
482         ///   operators can be used in a statement context.
483         ///
484         /// FIXME: Idea, we could split this up in two classes, one simpler
485         /// for the common case, and one with the extra fields for more complex
486         /// classes (indexers require temporary access;  overloaded require method)
487         ///
488         /// Maybe we should have classes PreIncrement, PostIncrement, PreDecrement,
489         /// PostDecrement, that way we could save the `Mode' byte as well.  
490         /// </remarks>
491         public class UnaryMutator : ExpressionStatement {
492                 public enum Mode : byte {
493                         PreIncrement, PreDecrement, PostIncrement, PostDecrement
494                 }
495                 
496                 Mode mode;
497                 Location loc;
498                 Expression expr;
499                 LocalTemporary temp_storage;
500
501                 //
502                 // This is expensive for the simplest case.
503                 //
504                 Expression method;
505                         
506                 public UnaryMutator (Mode m, Expression e, Location l)
507                 {
508                         mode = m;
509                         loc = l;
510                         expr = e;
511                 }
512
513                 string OperName ()
514                 {
515                         return (mode == Mode.PreIncrement || mode == Mode.PostIncrement) ?
516                                 "++" : "--";
517                 }
518                 
519                 void error23 (Type t)
520                 {
521                         Report.Error (
522                                 23, loc, "Operator " + OperName () + 
523                                 " cannot be applied to operand of type `" +
524                                 TypeManager.CSharpName (t) + "'");
525                 }
526
527                 /// <summary>
528                 ///   Returns whether an object of type `t' can be incremented
529                 ///   or decremented with add/sub (ie, basically whether we can
530                 ///   use pre-post incr-decr operations on it, but it is not a
531                 ///   System.Decimal, which we require operator overloading to catch)
532                 /// </summary>
533                 static bool IsIncrementableNumber (Type t)
534                 {
535                         return (t == TypeManager.sbyte_type) ||
536                                 (t == TypeManager.byte_type) ||
537                                 (t == TypeManager.short_type) ||
538                                 (t == TypeManager.ushort_type) ||
539                                 (t == TypeManager.int32_type) ||
540                                 (t == TypeManager.uint32_type) ||
541                                 (t == TypeManager.int64_type) ||
542                                 (t == TypeManager.uint64_type) ||
543                                 (t == TypeManager.char_type) ||
544                                 (t.IsSubclassOf (TypeManager.enum_type)) ||
545                                 (t == TypeManager.float_type) ||
546                                 (t == TypeManager.double_type);
547                 }
548
549                 Expression ResolveOperator (EmitContext ec)
550                 {
551                         Type expr_type = expr.Type;
552
553                         //
554                         // Step 1: Perform Operator Overload location
555                         //
556                         Expression mg;
557                         string op_name;
558                         
559                         if (mode == Mode.PreIncrement || mode == Mode.PostIncrement)
560                                 op_name = "op_Increment";
561                         else 
562                                 op_name = "op_Decrement";
563
564                         mg = MemberLookup (ec, expr_type, op_name, false, loc);
565
566                         if (mg == null && expr_type.BaseType != null)
567                                 mg = MemberLookup (ec, expr_type.BaseType, op_name, false, loc);
568                         
569                         if (mg != null) {
570                                 method = StaticCallExpr.MakeSimpleCall (
571                                         ec, (MethodGroupExpr) mg, expr, loc);
572
573                                 type = method.Type;
574                                 return this;
575                         }
576
577                         //
578                         // The operand of the prefix/postfix increment decrement operators
579                         // should be an expression that is classified as a variable,
580                         // a property access or an indexer access
581                         //
582                         type = expr_type;
583                         if (expr.eclass == ExprClass.Variable){
584                                 if (IsIncrementableNumber (expr_type) ||
585                                     expr_type == TypeManager.decimal_type){
586                                         return this;
587                                 }
588                         } else if (expr.eclass == ExprClass.IndexerAccess){
589                                 IndexerAccess ia = (IndexerAccess) expr;
590                                 
591                                 temp_storage = new LocalTemporary (ec, expr.Type);
592                                 
593                                 expr = ia.ResolveLValue (ec, temp_storage);
594                                 if (expr == null)
595                                         return null;
596
597                                 return this;
598                         } else if (expr.eclass == ExprClass.PropertyAccess){
599                                 PropertyExpr pe = (PropertyExpr) expr;
600
601                                 if (pe.VerifyAssignable ())
602                                         return this;
603
604                                 return null;
605                         } else {
606                                 report118 (loc, expr, "variable, indexer or property access");
607                                 return null;
608                         }
609
610                         Error (187, loc, "No such operator '" + OperName () + "' defined for type '" +
611                                TypeManager.CSharpName (expr_type) + "'");
612                         return null;
613                 }
614
615                 public override Expression DoResolve (EmitContext ec)
616                 {
617                         expr = expr.Resolve (ec);
618                         
619                         if (expr == null)
620                                 return null;
621
622                         eclass = ExprClass.Value;
623                         return ResolveOperator (ec);
624                 }
625                 
626
627                 //
628                 // FIXME: We need some way of avoiding the use of temp_storage
629                 // for some types of storage (parameters, local variables,
630                 // static fields) and single-dimension array access.
631                 //
632                 void EmitCode (EmitContext ec, bool is_expr)
633                 {
634                         ILGenerator ig = ec.ig;
635                         IAssignMethod ia = (IAssignMethod) expr;
636
637                         if (temp_storage == null)
638                                 temp_storage = new LocalTemporary (ec, expr.Type);
639                         
640                         switch (mode){
641                         case Mode.PreIncrement:
642                         case Mode.PreDecrement:
643                                 if (method == null){
644                                         expr.Emit (ec);
645
646                                         ig.Emit (OpCodes.Ldc_I4_1);
647                                 
648                                         if (mode == Mode.PreDecrement)
649                                                 ig.Emit (OpCodes.Sub);
650                                         else
651                                                 ig.Emit (OpCodes.Add);
652                                 } else
653                                         method.Emit (ec);
654                                 
655                                 temp_storage.Store (ec);
656                                 ia.EmitAssign (ec, temp_storage);
657                                 if (is_expr)
658                                         temp_storage.Emit (ec);
659                                 break;
660                                 
661                         case Mode.PostIncrement:
662                         case Mode.PostDecrement:
663                                 if (is_expr)
664                                         expr.Emit (ec);
665                                 
666                                 if (method == null){
667                                         if (!is_expr)
668                                                 expr.Emit (ec);
669                                         else
670                                                 ig.Emit (OpCodes.Dup);
671
672                                         ig.Emit (OpCodes.Ldc_I4_1);
673                                 
674                                         if (mode == Mode.PostDecrement)
675                                                 ig.Emit (OpCodes.Sub);
676                                         else
677                                                 ig.Emit (OpCodes.Add);
678                                 } else {
679                                         method.Emit (ec);
680                                 }
681                                 
682                                 temp_storage.Store (ec);
683                                 ia.EmitAssign (ec, temp_storage);
684                                 break;
685                         }
686                 }
687
688                 public override void Emit (EmitContext ec)
689                 {
690                         EmitCode (ec, true);
691                         
692                 }
693                 
694                 public override void EmitStatement (EmitContext ec)
695                 {
696                         EmitCode (ec, false);
697                 }
698
699         }
700
701         /// <summary>
702         ///   Base class for the `Is' and `As' classes. 
703         /// </summary>
704         ///
705         /// <remarks>
706         ///   FIXME: Split this in two, and we get to save the `Operator' Oper
707         ///   size. 
708         /// </remarks>
709         public abstract class Probe : Expression {
710                 public readonly string ProbeType;
711                 protected Expression expr;
712                 protected Type probe_type;
713                 Location loc;
714                 
715                 public Probe (Expression expr, string probe_type, Location l)
716                 {
717                         ProbeType = probe_type;
718                         loc = l;
719                         this.expr = expr;
720                 }
721
722                 public Expression Expr {
723                         get {
724                                 return expr;
725                         }
726                 }
727
728                 public override Expression DoResolve (EmitContext ec)
729                 {
730                         probe_type = RootContext.LookupType (ec.TypeContainer, ProbeType, false, loc);
731
732                         if (probe_type == null)
733                                 return null;
734
735                         expr = expr.Resolve (ec);
736                         
737                         return this;
738                 }
739         }
740
741         /// <summary>
742         ///   Implementation of the `is' operator.
743         /// </summary>
744         public class Is : Probe {
745                 public Is (Expression expr, string probe_type, Location l)
746                         : base (expr, probe_type, l)
747                 {
748                 }
749
750                 public override void Emit (EmitContext ec)
751                 {
752                         ILGenerator ig = ec.ig;
753                         
754                         expr.Emit (ec);
755                         
756                         ig.Emit (OpCodes.Isinst, probe_type);
757                         ig.Emit (OpCodes.Ldnull);
758                         ig.Emit (OpCodes.Cgt_Un);
759                 }
760
761                 public override Expression DoResolve (EmitContext ec)
762                 {
763                         Expression e = base.DoResolve (ec);
764
765                         if (e == null)
766                                 return null;
767
768                         type = TypeManager.bool_type;
769                         eclass = ExprClass.Value;
770
771                         return this;
772                 }                               
773         }
774
775         /// <summary>
776         ///   Implementation of the `as' operator.
777         /// </summary>
778         public class As : Probe {
779                 public As (Expression expr, string probe_type, Location l)
780                         : base (expr, probe_type, l)
781                 {
782                 }
783
784                 public override void Emit (EmitContext ec)
785                 {
786                         ILGenerator ig = ec.ig;
787
788                         expr.Emit (ec);
789                         ig.Emit (OpCodes.Isinst, probe_type);
790                 }
791
792                 public override Expression DoResolve (EmitContext ec)
793                 {
794                         Expression e = base.DoResolve (ec);
795
796                         if (e == null)
797                                 return null;
798
799                         type = probe_type;
800                         eclass = ExprClass.Value;
801
802                         return this;
803                 }                               
804         }
805         
806         /// <summary>
807         ///   This represents a typecast in the source language.
808         ///
809         ///   FIXME: Cast expressions have an unusual set of parsing
810         ///   rules, we need to figure those out.
811         /// </summary>
812         public class Cast : Expression {
813                 Expression target_type;
814                 Expression expr;
815                 Location   loc;
816                         
817                 public Cast (Expression cast_type, Expression expr, Location loc)
818                 {
819                         this.target_type = cast_type;
820                         this.expr = expr;
821                         this.loc = loc;
822                 }
823
824                 public Expression TargetType {
825                         get {
826                                 return target_type;
827                         }
828                 }
829
830                 public Expression Expr {
831                         get {
832                                 return expr;
833                         }
834                         set {
835                                 expr = value;
836                         }
837                 }
838
839                 /// <summary>
840                 ///   Attempts to do a compile-time folding of a constant cast.
841                 /// </summary>
842                 Expression TryReduce (EmitContext ec, Type target_type)
843                 {
844                         if (expr is ByteConstant){
845                                 byte v = ((ByteConstant) expr).Value;
846         
847                                 if (target_type == TypeManager.sbyte_type)
848                                         return new SByteConstant ((sbyte) v);
849                                 if (target_type == TypeManager.short_type)
850                                         return new ShortConstant ((short) v);
851                                 if (target_type == TypeManager.ushort_type)
852                                         return new UShortConstant ((ushort) v);
853                                 if (target_type == TypeManager.int32_type)
854                                         return new IntConstant ((int) v);
855                                 if (target_type == TypeManager.uint32_type)
856                                         return new UIntConstant ((uint) v);
857                                 if (target_type == TypeManager.int64_type)
858                                         return new LongConstant ((long) v);
859                                 if (target_type == TypeManager.uint64_type)
860                                         return new ULongConstant ((ulong) v);
861                                 if (target_type == TypeManager.float_type)
862                                         return new FloatConstant ((float) v);
863                                 if (target_type == TypeManager.double_type)
864                                         return new DoubleConstant ((double) v);
865                         }
866                         if (expr is SByteConstant){
867                                 sbyte v = ((SByteConstant) expr).Value;
868         
869                                 if (target_type == TypeManager.byte_type)
870                                         return new ByteConstant ((byte) v);
871                                 if (target_type == TypeManager.short_type)
872                                         return new ShortConstant ((short) v);
873                                 if (target_type == TypeManager.ushort_type)
874                                         return new UShortConstant ((ushort) v);
875                                 if (target_type == TypeManager.int32_type)
876                                         return new IntConstant ((int) v);
877                                 if (target_type == TypeManager.uint32_type)
878                                         return new UIntConstant ((uint) v);
879                                 if (target_type == TypeManager.int64_type)
880                                         return new LongConstant ((long) v);
881                                 if (target_type == TypeManager.uint64_type)
882                                         return new ULongConstant ((ulong) v);
883                                 if (target_type == TypeManager.float_type)
884                                         return new FloatConstant ((float) v);
885                                 if (target_type == TypeManager.double_type)
886                                         return new DoubleConstant ((double) v);
887                         }
888                         if (expr is ShortConstant){
889                                 short v = ((ShortConstant) expr).Value;
890         
891                                 if (target_type == TypeManager.byte_type)
892                                         return new ByteConstant ((byte) v);
893                                 if (target_type == TypeManager.sbyte_type)
894                                         return new SByteConstant ((sbyte) v);
895                                 if (target_type == TypeManager.ushort_type)
896                                         return new UShortConstant ((ushort) v);
897                                 if (target_type == TypeManager.int32_type)
898                                         return new IntConstant ((int) v);
899                                 if (target_type == TypeManager.uint32_type)
900                                         return new UIntConstant ((uint) v);
901                                 if (target_type == TypeManager.int64_type)
902                                         return new LongConstant ((long) v);
903                                 if (target_type == TypeManager.uint64_type)
904                                         return new ULongConstant ((ulong) v);
905                                 if (target_type == TypeManager.float_type)
906                                         return new FloatConstant ((float) v);
907                                 if (target_type == TypeManager.double_type)
908                                         return new DoubleConstant ((double) v);
909                         }
910                         if (expr is UShortConstant){
911                                 ushort v = ((UShortConstant) expr).Value;
912         
913                                 if (target_type == TypeManager.byte_type)
914                                         return new ByteConstant ((byte) v);
915                                 if (target_type == TypeManager.sbyte_type)
916                                         return new SByteConstant ((sbyte) v);
917                                 if (target_type == TypeManager.short_type)
918                                         return new ShortConstant ((short) v);
919                                 if (target_type == TypeManager.int32_type)
920                                         return new IntConstant ((int) v);
921                                 if (target_type == TypeManager.uint32_type)
922                                         return new UIntConstant ((uint) v);
923                                 if (target_type == TypeManager.int64_type)
924                                         return new LongConstant ((long) v);
925                                 if (target_type == TypeManager.uint64_type)
926                                         return new ULongConstant ((ulong) v);
927                                 if (target_type == TypeManager.float_type)
928                                         return new FloatConstant ((float) v);
929                                 if (target_type == TypeManager.double_type)
930                                         return new DoubleConstant ((double) v);
931                         }
932                         if (expr is IntConstant){
933                                 int v = ((IntConstant) expr).Value;
934         
935                                 if (target_type == TypeManager.byte_type)
936                                         return new ByteConstant ((byte) v);
937                                 if (target_type == TypeManager.sbyte_type)
938                                         return new SByteConstant ((sbyte) v);
939                                 if (target_type == TypeManager.short_type)
940                                         return new ShortConstant ((short) v);
941                                 if (target_type == TypeManager.ushort_type)
942                                         return new UShortConstant ((ushort) v);
943                                 if (target_type == TypeManager.uint32_type)
944                                         return new UIntConstant ((uint) v);
945                                 if (target_type == TypeManager.int64_type)
946                                         return new LongConstant ((long) v);
947                                 if (target_type == TypeManager.uint64_type)
948                                         return new ULongConstant ((ulong) v);
949                                 if (target_type == TypeManager.float_type)
950                                         return new FloatConstant ((float) v);
951                                 if (target_type == TypeManager.double_type)
952                                         return new DoubleConstant ((double) v);
953                         }
954                         if (expr is UIntConstant){
955                                 uint v = ((UIntConstant) expr).Value;
956         
957                                 if (target_type == TypeManager.byte_type)
958                                         return new ByteConstant ((byte) v);
959                                 if (target_type == TypeManager.sbyte_type)
960                                         return new SByteConstant ((sbyte) v);
961                                 if (target_type == TypeManager.short_type)
962                                         return new ShortConstant ((short) v);
963                                 if (target_type == TypeManager.ushort_type)
964                                         return new UShortConstant ((ushort) v);
965                                 if (target_type == TypeManager.int32_type)
966                                         return new IntConstant ((int) v);
967                                 if (target_type == TypeManager.int64_type)
968                                         return new LongConstant ((long) v);
969                                 if (target_type == TypeManager.uint64_type)
970                                         return new ULongConstant ((ulong) v);
971                                 if (target_type == TypeManager.float_type)
972                                         return new FloatConstant ((float) v);
973                                 if (target_type == TypeManager.double_type)
974                                         return new DoubleConstant ((double) v);
975                         }
976                         if (expr is LongConstant){
977                                 long v = ((LongConstant) expr).Value;
978         
979                                 if (target_type == TypeManager.byte_type)
980                                         return new ByteConstant ((byte) v);
981                                 if (target_type == TypeManager.sbyte_type)
982                                         return new SByteConstant ((sbyte) v);
983                                 if (target_type == TypeManager.short_type)
984                                         return new ShortConstant ((short) v);
985                                 if (target_type == TypeManager.ushort_type)
986                                         return new UShortConstant ((ushort) v);
987                                 if (target_type == TypeManager.int32_type)
988                                         return new IntConstant ((int) v);
989                                 if (target_type == TypeManager.uint32_type)
990                                         return new UIntConstant ((uint) v);
991                                 if (target_type == TypeManager.uint64_type)
992                                         return new ULongConstant ((ulong) v);
993                                 if (target_type == TypeManager.float_type)
994                                         return new FloatConstant ((float) v);
995                                 if (target_type == TypeManager.double_type)
996                                         return new DoubleConstant ((double) v);
997                         }
998                         if (expr is ULongConstant){
999                                 ulong v = ((ULongConstant) expr).Value;
1000         
1001                                 if (target_type == TypeManager.byte_type)
1002                                         return new ByteConstant ((byte) v);
1003                                 if (target_type == TypeManager.sbyte_type)
1004                                         return new SByteConstant ((sbyte) v);
1005                                 if (target_type == TypeManager.short_type)
1006                                         return new ShortConstant ((short) v);
1007                                 if (target_type == TypeManager.ushort_type)
1008                                         return new UShortConstant ((ushort) v);
1009                                 if (target_type == TypeManager.int32_type)
1010                                         return new IntConstant ((int) v);
1011                                 if (target_type == TypeManager.uint32_type)
1012                                         return new UIntConstant ((uint) v);
1013                                 if (target_type == TypeManager.int64_type)
1014                                         return new LongConstant ((long) v);
1015                                 if (target_type == TypeManager.float_type)
1016                                         return new FloatConstant ((float) v);
1017                                 if (target_type == TypeManager.double_type)
1018                                         return new DoubleConstant ((double) v);
1019                         }
1020                         if (expr is FloatConstant){
1021                                 float v = ((FloatConstant) expr).Value;
1022         
1023                                 if (target_type == TypeManager.byte_type)
1024                                         return new ByteConstant ((byte) v);
1025                                 if (target_type == TypeManager.sbyte_type)
1026                                         return new SByteConstant ((sbyte) v);
1027                                 if (target_type == TypeManager.short_type)
1028                                         return new ShortConstant ((short) v);
1029                                 if (target_type == TypeManager.ushort_type)
1030                                         return new UShortConstant ((ushort) v);
1031                                 if (target_type == TypeManager.int32_type)
1032                                         return new IntConstant ((int) v);
1033                                 if (target_type == TypeManager.uint32_type)
1034                                         return new UIntConstant ((uint) v);
1035                                 if (target_type == TypeManager.int64_type)
1036                                         return new LongConstant ((long) v);
1037                                 if (target_type == TypeManager.uint64_type)
1038                                         return new ULongConstant ((ulong) v);
1039                                 if (target_type == TypeManager.double_type)
1040                                         return new DoubleConstant ((double) v);
1041                         }
1042                         if (expr is DoubleConstant){
1043                                 double v = ((DoubleConstant) expr).Value;
1044         
1045                                 if (target_type == TypeManager.byte_type)
1046                                         return new ByteConstant ((byte) v);
1047                                 if (target_type == TypeManager.sbyte_type)
1048                                         return new SByteConstant ((sbyte) v);
1049                                 if (target_type == TypeManager.short_type)
1050                                         return new ShortConstant ((short) v);
1051                                 if (target_type == TypeManager.ushort_type)
1052                                         return new UShortConstant ((ushort) v);
1053                                 if (target_type == TypeManager.int32_type)
1054                                         return new IntConstant ((int) v);
1055                                 if (target_type == TypeManager.uint32_type)
1056                                         return new UIntConstant ((uint) v);
1057                                 if (target_type == TypeManager.int64_type)
1058                                         return new LongConstant ((long) v);
1059                                 if (target_type == TypeManager.uint64_type)
1060                                         return new ULongConstant ((ulong) v);
1061                                 if (target_type == TypeManager.float_type)
1062                                         return new FloatConstant ((float) v);
1063                         }
1064
1065                         return null;
1066                 }
1067                 
1068                 public override Expression DoResolve (EmitContext ec)
1069                 {
1070                         expr = expr.Resolve (ec);
1071                         if (expr == null)
1072                                 return null;
1073
1074                         target_type = target_type.Resolve (ec);
1075                         if (target_type == null)
1076                                 return null;
1077
1078                         if (target_type.eclass != ExprClass.Type){
1079                                 report118 (loc, target_type, "class");
1080                                 return null;
1081                         }
1082                         
1083                         type = target_type.Type;
1084                         eclass = ExprClass.Value;
1085                         
1086                         if (type == null)
1087                                 return null;
1088
1089                         if (expr is Constant){
1090                                 Expression e = TryReduce (ec, type);
1091
1092                                 if (e != null)
1093                                         return e;
1094                         }
1095                         
1096                         expr = ConvertExplicit (ec, expr, type, loc);
1097                         return expr;
1098                 }
1099
1100                 public override void Emit (EmitContext ec)
1101                 {
1102                         //
1103                         // This one will never happen
1104                         //
1105                         throw new Exception ("Should not happen");
1106                 }
1107         }
1108
1109         /// <summary>
1110         ///   Binary operators
1111         /// </summary>
1112         public class Binary : Expression {
1113                 public enum Operator : byte {
1114                         Multiply, Division, Modulus,
1115                         Addition, Subtraction,
1116                         LeftShift, RightShift,
1117                         LessThan, GreaterThan, LessThanOrEqual, GreaterThanOrEqual, 
1118                         Equality, Inequality,
1119                         BitwiseAnd,
1120                         ExclusiveOr,
1121                         BitwiseOr,
1122                         LogicalAnd,
1123                         LogicalOr
1124                 }
1125
1126                 Operator oper;
1127                 Expression left, right;
1128                 MethodBase method;
1129                 ArrayList  Arguments;
1130                 Location   loc;
1131                 
1132
1133                 public Binary (Operator oper, Expression left, Expression right, Location loc)
1134                 {
1135                         this.oper = oper;
1136                         this.left = left;
1137                         this.right = right;
1138                         this.loc = loc;
1139                 }
1140
1141                 public Operator Oper {
1142                         get {
1143                                 return oper;
1144                         }
1145                         set {
1146                                 oper = value;
1147                         }
1148                 }
1149                 
1150                 public Expression Left {
1151                         get {
1152                                 return left;
1153                         }
1154                         set {
1155                                 left = value;
1156                         }
1157                 }
1158
1159                 public Expression Right {
1160                         get {
1161                                 return right;
1162                         }
1163                         set {
1164                                 right = value;
1165                         }
1166                 }
1167
1168
1169                 /// <summary>
1170                 ///   Returns a stringified representation of the Operator
1171                 /// </summary>
1172                 string OperName ()
1173                 {
1174                         switch (oper){
1175                         case Operator.Multiply:
1176                                 return "*";
1177                         case Operator.Division:
1178                                 return "/";
1179                         case Operator.Modulus:
1180                                 return "%";
1181                         case Operator.Addition:
1182                                 return "+";
1183                         case Operator.Subtraction:
1184                                 return "-";
1185                         case Operator.LeftShift:
1186                                 return "<<";
1187                         case Operator.RightShift:
1188                                 return ">>";
1189                         case Operator.LessThan:
1190                                 return "<";
1191                         case Operator.GreaterThan:
1192                                 return ">";
1193                         case Operator.LessThanOrEqual:
1194                                 return "<=";
1195                         case Operator.GreaterThanOrEqual:
1196                                 return ">=";
1197                         case Operator.Equality:
1198                                 return "==";
1199                         case Operator.Inequality:
1200                                 return "!=";
1201                         case Operator.BitwiseAnd:
1202                                 return "&";
1203                         case Operator.BitwiseOr:
1204                                 return "|";
1205                         case Operator.ExclusiveOr:
1206                                 return "^";
1207                         case Operator.LogicalOr:
1208                                 return "||";
1209                         case Operator.LogicalAnd:
1210                                 return "&&";
1211                         }
1212
1213                         return oper.ToString ();
1214                 }
1215
1216                 Expression ForceConversion (EmitContext ec, Expression expr, Type target_type)
1217                 {
1218                         if (expr.Type == target_type)
1219                                 return expr;
1220
1221                         return ConvertImplicit (ec, expr, target_type, new Location (-1));
1222                 }
1223                 
1224                 //
1225                 // Note that handling the case l == Decimal || r == Decimal
1226                 // is taken care of by the Step 1 Operator Overload resolution.
1227                 //
1228                 bool DoNumericPromotions (EmitContext ec, Type l, Type r)
1229                 {
1230                         if (l == TypeManager.double_type || r == TypeManager.double_type){
1231                                 //
1232                                 // If either operand is of type double, the other operand is
1233                                 // conveted to type double.
1234                                 //
1235                                 if (r != TypeManager.double_type)
1236                                         right = ConvertImplicit (ec, right, TypeManager.double_type, loc);
1237                                 if (l != TypeManager.double_type)
1238                                         left = ConvertImplicit (ec, left, TypeManager.double_type, loc);
1239                                 
1240                                 type = TypeManager.double_type;
1241                         } else if (l == TypeManager.float_type || r == TypeManager.float_type){
1242                                 //
1243                                 // if either operand is of type float, th eother operand is
1244                                 // converd to type float.
1245                                 //
1246                                 if (r != TypeManager.double_type)
1247                                         right = ConvertImplicit (ec, right, TypeManager.float_type, loc);
1248                                 if (l != TypeManager.double_type)
1249                                         left = ConvertImplicit (ec, left, TypeManager.float_type, loc);
1250                                 type = TypeManager.float_type;
1251                         } else if (l == TypeManager.uint64_type || r == TypeManager.uint64_type){
1252                                 Expression e;
1253                                 Type other;
1254                                 //
1255                                 // If either operand is of type ulong, the other operand is
1256                                 // converted to type ulong.  or an error ocurrs if the other
1257                                 // operand is of type sbyte, short, int or long
1258                                 //
1259                                 
1260                                 if (l == TypeManager.uint64_type){
1261                                         if (r != TypeManager.uint64_type){
1262                                                 if (right is IntConstant){
1263                                                         e = TryImplicitIntConversion(l, (IntConstant) right);
1264                                                         if (e != null)
1265                                                                 right = e;
1266                                                 } else if (right is LongConstant){
1267                                                         long ll = ((LongConstant) right).Value;
1268
1269                                                         if (ll > 0)
1270                                                                 right = new ULongConstant ((ulong) ll);
1271                                                 }
1272                                         }
1273                                         other = right.Type;
1274                                 } else {
1275                                         if (left is IntConstant){
1276                                                 e = TryImplicitIntConversion (r, (IntConstant) left);
1277                                                 if (e != null)
1278                                                         left = e;
1279                                         } else if (left is LongConstant){
1280                                                 long ll = ((LongConstant) left).Value;
1281
1282                                                 if (ll > 0)
1283                                                         left = new ULongConstant ((ulong) ll);
1284                                         }
1285                                         other = left.Type;
1286                                 }
1287
1288                                 if ((other == TypeManager.sbyte_type) ||
1289                                     (other == TypeManager.short_type) ||
1290                                     (other == TypeManager.int32_type) ||
1291                                     (other == TypeManager.int64_type)){
1292                                         string oper = OperName ();
1293                                         
1294                                         Error (34, loc, "Operator `" + OperName ()
1295                                                + "' is ambiguous on operands of type `"
1296                                                + TypeManager.CSharpName (l) + "' "
1297                                                + "and `" + TypeManager.CSharpName (r)
1298                                                + "'");
1299                                 }
1300                                 type = TypeManager.uint64_type;
1301                         } else if (l == TypeManager.int64_type || r == TypeManager.int64_type){
1302                                 //
1303                                 // If either operand is of type long, the other operand is converted
1304                                 // to type long.
1305                                 //
1306                                 if (l != TypeManager.int64_type)
1307                                         left = ConvertImplicit (ec, left, TypeManager.int64_type, loc);
1308                                 if (r != TypeManager.int64_type)
1309                                         right = ConvertImplicit (ec, right, TypeManager.int64_type, loc);
1310
1311                                 type = TypeManager.int64_type;
1312                         } else if (l == TypeManager.uint32_type || r == TypeManager.uint32_type){
1313                                 //
1314                                 // If either operand is of type uint, and the other
1315                                 // operand is of type sbyte, short or int, othe operands are
1316                                 // converted to type long.
1317                                 //
1318                                 Type other = null;
1319                                 
1320                                 if (l == TypeManager.uint32_type)
1321                                         other = r;
1322                                 else if (r == TypeManager.uint32_type)
1323                                         other = l;
1324
1325                                 if ((other == TypeManager.sbyte_type) ||
1326                                     (other == TypeManager.short_type) ||
1327                                     (other == TypeManager.int32_type)){
1328                                         left = ForceConversion (ec, left, TypeManager.int64_type);
1329                                         right = ForceConversion (ec, right, TypeManager.int64_type);
1330                                         type = TypeManager.int64_type;
1331                                 } else {
1332                                         //
1333                                         // if either operand is of type uint, the other
1334                                         // operand is converd to type uint
1335                                         //
1336                                         left = ForceConversion (ec, left, TypeManager.uint32_type);
1337                                         right = ForceConversion (ec, right, TypeManager.uint32_type);
1338                                         type = TypeManager.uint32_type;
1339                                 } 
1340                         } else if (l == TypeManager.decimal_type || r == TypeManager.decimal_type){
1341                                 if (l != TypeManager.decimal_type)
1342                                         left = ConvertImplicit (ec, left, TypeManager.decimal_type, loc);
1343                                 if (r != TypeManager.decimal_type)
1344                                         right = ConvertImplicit (ec, right, TypeManager.decimal_type, loc);
1345
1346                                 type = TypeManager.decimal_type;
1347                         } else {
1348                                 Expression l_tmp, r_tmp;
1349
1350                                 l_tmp = ForceConversion (ec, left, TypeManager.int32_type);
1351                                 if (l_tmp == null)
1352                                         return false;
1353                                 
1354                                 r_tmp = ForceConversion (ec, right, TypeManager.int32_type);
1355                                 if (r_tmp == null)
1356                                         return false;
1357
1358                                 left = l_tmp;
1359                                 right = r_tmp;
1360                                 
1361                                 type = TypeManager.int32_type;
1362                         }
1363
1364                         return true;
1365                 }
1366
1367                 void error19 ()
1368                 {
1369                         Error (19, loc,
1370                                "Operator " + OperName () + " cannot be applied to operands of type `" +
1371                                TypeManager.CSharpName (left.Type) + "' and `" +
1372                                TypeManager.CSharpName (right.Type) + "'");
1373                                                      
1374                 }
1375                 
1376                 Expression CheckShiftArguments (EmitContext ec)
1377                 {
1378                         Expression e;
1379                         Type l = left.Type;
1380                         Type r = right.Type;
1381
1382                         e = ForceConversion (ec, right, TypeManager.int32_type);
1383                         if (e == null){
1384                                 error19 ();
1385                                 return null;
1386                         }
1387                         right = e;
1388
1389                         if (((e = ConvertImplicit (ec, left, TypeManager.int32_type, loc)) != null) ||
1390                             ((e = ConvertImplicit (ec, left, TypeManager.uint32_type, loc)) != null) ||
1391                             ((e = ConvertImplicit (ec, left, TypeManager.int64_type, loc)) != null) ||
1392                             ((e = ConvertImplicit (ec, left, TypeManager.uint64_type, loc)) != null)){
1393                                 left = e;
1394                                 type = e.Type;
1395
1396                                 return this;
1397                         }
1398                         error19 ();
1399                         return null;
1400                 }
1401                 
1402                 Expression ResolveOperator (EmitContext ec)
1403                 {
1404                         Type l = left.Type;
1405                         Type r = right.Type;
1406
1407                         //
1408                         // Step 1: Perform Operator Overload location
1409                         //
1410                         Expression left_expr, right_expr;
1411                         
1412                         string op = "op_" + oper;
1413
1414                         left_expr = MemberLookup (ec, l, op, false, loc);
1415                         if (left_expr == null && l.BaseType != null)
1416                                 left_expr = MemberLookup (ec, l.BaseType, op, false, loc);
1417                         
1418                         right_expr = MemberLookup (ec, r, op, false, loc);
1419                         if (right_expr == null && r.BaseType != null)
1420                                 right_expr = MemberLookup (ec, r.BaseType, op, false, loc);
1421                         
1422                         MethodGroupExpr union = Invocation.MakeUnionSet (left_expr, right_expr);
1423                         
1424                         if (union != null) {
1425                                 Arguments = new ArrayList ();
1426                                 Arguments.Add (new Argument (left, Argument.AType.Expression));
1427                                 Arguments.Add (new Argument (right, Argument.AType.Expression));
1428
1429                                 method = Invocation.OverloadResolve (ec, union, Arguments, loc);
1430                                 if (method != null) {
1431                                         MethodInfo mi = (MethodInfo) method;
1432                                         type = mi.ReturnType;
1433                                         return this;
1434                                 } else {
1435                                         error19 ();
1436                                         return null;
1437                                 }
1438                         }       
1439
1440                         //
1441                         // Step 2: Default operations on CLI native types.
1442                         //
1443
1444                         // Only perform numeric promotions on:
1445                         // +, -, *, /, %, &, |, ^, ==, !=, <, >, <=, >=
1446                         //
1447                         if (oper == Operator.Addition){
1448                                 //
1449                                 // If any of the arguments is a string, cast to string
1450                                 //
1451                                 if (l == TypeManager.string_type){
1452                                         if (r == TypeManager.string_type){
1453                                                 if (left is Constant && right is Constant){
1454                                                         StringConstant ls = (StringConstant) left;
1455                                                         StringConstant rs = (StringConstant) right;
1456                                                         
1457                                                         return new StringConstant (
1458                                                                 ls.Value + rs.Value);
1459                                                 }
1460                                                 
1461                                                 // string + string
1462                                                 method = TypeManager.string_concat_string_string;
1463                                         } else {
1464                                                 // string + object
1465                                                 method = TypeManager.string_concat_object_object;
1466                                                 right = ConvertImplicit (ec, right,
1467                                                                          TypeManager.object_type, loc);
1468                                         }
1469                                         type = TypeManager.string_type;
1470
1471                                         Arguments = new ArrayList ();
1472                                         Arguments.Add (new Argument (left, Argument.AType.Expression));
1473                                         Arguments.Add (new Argument (right, Argument.AType.Expression));
1474
1475                                         return this;
1476                                         
1477                                 } else if (r == TypeManager.string_type){
1478                                         // object + string
1479                                         method = TypeManager.string_concat_object_object;
1480                                         Arguments = new ArrayList ();
1481                                         Arguments.Add (new Argument (left, Argument.AType.Expression));
1482                                         Arguments.Add (new Argument (right, Argument.AType.Expression));
1483
1484                                         left = ConvertImplicit (ec, left, TypeManager.object_type, loc);
1485                                         type = TypeManager.string_type;
1486
1487                                         return this;
1488                                 }
1489
1490                                 if (l.IsSubclassOf (TypeManager.delegate_type) &&
1491                                     r.IsSubclassOf (TypeManager.delegate_type)) {
1492
1493                                         Arguments = new ArrayList ();
1494                                         Arguments.Add (new Argument (left, Argument.AType.Expression));
1495                                         Arguments.Add (new Argument (right, Argument.AType.Expression));
1496                                         
1497                                         method = TypeManager.delegate_combine_delegate_delegate;
1498
1499                                         type = l;
1500
1501                                         return this;
1502                                 }
1503                         }
1504                         
1505                         //
1506                         // Enumeration operators
1507                         //
1508                         bool lie = TypeManager.IsEnumType (l);
1509                         bool rie = TypeManager.IsEnumType (r);
1510                         if (lie || rie){
1511                                 Expression temp;
1512
1513                                 if (!rie){
1514                                         temp = ConvertImplicit (ec, right, l, loc);
1515                                         if (temp != null)
1516                                                 right = temp;
1517                                 } if (!lie){
1518                                         temp = ConvertImplicit (ec, left, r, loc);
1519                                         if (temp != null){
1520                                                 left = temp;
1521                                                 l = r;
1522                                         }
1523                                 }
1524                                 
1525                                 if (oper == Operator.Equality || oper == Operator.Inequality ||
1526                                     oper == Operator.LessThanOrEqual || oper == Operator.LessThan ||
1527                                     oper == Operator.GreaterThanOrEqual || oper == Operator.GreaterThan){
1528                                         type = TypeManager.bool_type;
1529                                         return this;
1530                                 }
1531
1532                                 if (oper == Operator.BitwiseAnd ||
1533                                     oper == Operator.BitwiseOr ||
1534                                     oper == Operator.ExclusiveOr){
1535                                         type = l;
1536                                         return this;
1537                                 }
1538                         }
1539                         
1540                         if (oper == Operator.LeftShift || oper == Operator.RightShift)
1541                                 return CheckShiftArguments (ec);
1542
1543                         if (oper == Operator.LogicalOr || oper == Operator.LogicalAnd){
1544                                 if (l != TypeManager.bool_type || r != TypeManager.bool_type){
1545                                         error19 ();
1546                                         return null;
1547                                 }
1548
1549                                 type = TypeManager.bool_type;
1550                                 return this;
1551                         } 
1552
1553                         if (oper == Operator.Equality || oper == Operator.Inequality){
1554                                 if (l == TypeManager.bool_type || r == TypeManager.bool_type){
1555                                         if (r != TypeManager.bool_type || l != TypeManager.bool_type){
1556                                                 error19 ();
1557                                                 return null;
1558                                         }
1559                                         
1560                                         type = TypeManager.bool_type;
1561                                         return this;
1562                                 }
1563
1564                                 //
1565                                 // operator != (object a, object b)
1566                                 // operator == (object a, object b)
1567                                 //
1568                                 // For this to be used, both arguments have to be reference-types.
1569                                 // Read the rationale on the spec (14.9.6)
1570                                 //
1571                                 // Also, if at compile time we know that the classes do not inherit
1572                                 // one from the other, then we catch the error there.
1573                                 //
1574                                 if (!(l.IsValueType || r.IsValueType)){
1575                                         type = TypeManager.bool_type;
1576
1577                                         if (l == r)
1578                                                 return this;
1579                                         
1580                                         if (l.IsSubclassOf (r) || r.IsSubclassOf (l))
1581                                                 return this;
1582                                 }
1583                         }
1584
1585                         //
1586                         // We are dealing with numbers
1587                         //
1588
1589                         if (!DoNumericPromotions (ec, l, r)){
1590                                 error19 ();
1591                                 return null;
1592                         }
1593
1594                         if (left == null || right == null)
1595                                 return null;
1596
1597                         //
1598                         // reload our cached types if required
1599                         //
1600                         l = left.Type;
1601                         r = right.Type;
1602                         
1603                         if (oper == Operator.BitwiseAnd ||
1604                             oper == Operator.BitwiseOr ||
1605                             oper == Operator.ExclusiveOr){
1606                                 if (l == r){
1607                                         if (!((l == TypeManager.int32_type) ||
1608                                               (l == TypeManager.uint32_type) ||
1609                                               (l == TypeManager.int64_type) ||
1610                                               (l == TypeManager.uint64_type)))
1611                                                 type = l;
1612                                 } else {
1613                                         error19 ();
1614                                         return null;
1615                                 }
1616                         }
1617
1618                         if (oper == Operator.Equality ||
1619                             oper == Operator.Inequality ||
1620                             oper == Operator.LessThanOrEqual ||
1621                             oper == Operator.LessThan ||
1622                             oper == Operator.GreaterThanOrEqual ||
1623                             oper == Operator.GreaterThan){
1624                                 type = TypeManager.bool_type;
1625                         }
1626
1627                         return this;
1628                 }
1629
1630                 /// <summary>
1631                 ///   Constant expression reducer for binary operations
1632                 /// </summary>
1633                 public Expression ConstantFold (EmitContext ec)
1634                 {
1635                         object l = ((Constant) left).GetValue ();
1636                         object r = ((Constant) right).GetValue ();
1637                         
1638                         if (l is string && r is string)
1639                                 return new StringConstant ((string) l + (string) r);
1640
1641                         Type result_type = null;
1642
1643                         //
1644                         // Enumerator folding
1645                         //
1646                         if (left.Type == right.Type && left is EnumConstant)
1647                                 result_type = left.Type;
1648
1649                         switch (oper){
1650                         case Operator.BitwiseOr:
1651                                 if ((l is int) && (r is int)){
1652                                         IntConstant v;
1653                                         int res = (int)l | (int)r;
1654                                         
1655                                         v = new IntConstant (res);
1656                                         if (result_type == null)
1657                                                 return v;
1658                                         else
1659                                                 return new EnumConstant (v, result_type);
1660                                 }
1661                                 break;
1662                                 
1663                         case Operator.BitwiseAnd:
1664                                 if ((l is int) && (r is int)){
1665                                         IntConstant v;
1666                                         int res = (int)l & (int)r;
1667                                         
1668                                         v = new IntConstant (res);
1669                                         if (result_type == null)
1670                                                 return v;
1671                                         else
1672                                                 return new EnumConstant (v, result_type);
1673                                 }
1674                                 break;
1675                         }
1676                                         
1677                         return null;
1678                 }
1679                 
1680                 public override Expression DoResolve (EmitContext ec)
1681                 {
1682                         left = left.Resolve (ec);
1683                         right = right.Resolve (ec);
1684
1685                         if (left == null || right == null)
1686                                 return null;
1687
1688                         if (left.Type == null)
1689                                 throw new Exception (
1690                                         "Resolve returned non null, but did not set the type! (" +
1691                                         left + ") at Line: " + loc.Row);
1692                         if (right.Type == null)
1693                                 throw new Exception (
1694                                         "Resolve returned non null, but did not set the type! (" +
1695                                         right + ") at Line: "+ loc.Row);
1696
1697                         eclass = ExprClass.Value;
1698
1699                         if (left is Constant && right is Constant){
1700                                 //
1701                                 // This is temporary until we do the full folding
1702                                 //
1703                                 Expression e = ConstantFold (ec);
1704                                 if (e != null)
1705                                         return e;
1706                         }
1707
1708                         return ResolveOperator (ec);
1709                 }
1710
1711                 public bool IsBranchable ()
1712                 {
1713                         if (oper == Operator.Equality ||
1714                             oper == Operator.Inequality ||
1715                             oper == Operator.LessThan ||
1716                             oper == Operator.GreaterThan ||
1717                             oper == Operator.LessThanOrEqual ||
1718                             oper == Operator.GreaterThanOrEqual){
1719                                 return true;
1720                         } else
1721                                 return false;
1722                 }
1723
1724                 /// <summary>
1725                 ///   This entry point is used by routines that might want
1726                 ///   to emit a brfalse/brtrue after an expression, and instead
1727                 ///   they could use a more compact notation.
1728                 ///
1729                 ///   Typically the code would generate l.emit/r.emit, followed
1730                 ///   by the comparission and then a brtrue/brfalse.  The comparissions
1731                 ///   are sometimes inneficient (there are not as complete as the branches
1732                 ///   look for the hacks in Emit using double ceqs).
1733                 ///
1734                 ///   So for those cases we provide EmitBranchable that can emit the
1735                 ///   branch with the test
1736                 /// </summary>
1737                 public void EmitBranchable (EmitContext ec, int target)
1738                 {
1739                         OpCode opcode;
1740                         bool close_target = false;
1741                         ILGenerator ig = ec.ig;
1742                                 
1743                         //
1744                         // short-circuit operators
1745                         //
1746                         if (oper == Operator.LogicalAnd){
1747                                 left.Emit (ec);
1748                                 ig.Emit (OpCodes.Brfalse, target);
1749                                 right.Emit (ec);
1750                                 ig.Emit (OpCodes.Brfalse, target);
1751                         } else if (oper == Operator.LogicalOr){
1752                                 left.Emit (ec);
1753                                 ig.Emit (OpCodes.Brtrue, target);
1754                                 right.Emit (ec);
1755                                 ig.Emit (OpCodes.Brfalse, target);
1756                         }
1757                                 
1758                         left.Emit (ec);
1759                         right.Emit (ec);
1760                         
1761                         switch (oper){
1762                         case Operator.Equality:
1763                                 if (close_target)
1764                                         opcode = OpCodes.Beq_S;
1765                                 else
1766                                         opcode = OpCodes.Beq;
1767                                 break;
1768
1769                         case Operator.Inequality:
1770                                 if (close_target)
1771                                         opcode = OpCodes.Bne_Un_S;
1772                                 else
1773                                         opcode = OpCodes.Bne_Un;
1774                                 break;
1775
1776                         case Operator.LessThan:
1777                                 if (close_target)
1778                                         opcode = OpCodes.Blt_S;
1779                                 else
1780                                         opcode = OpCodes.Blt;
1781                                 break;
1782
1783                         case Operator.GreaterThan:
1784                                 if (close_target)
1785                                         opcode = OpCodes.Bgt_S;
1786                                 else
1787                                         opcode = OpCodes.Bgt;
1788                                 break;
1789
1790                         case Operator.LessThanOrEqual:
1791                                 if (close_target)
1792                                         opcode = OpCodes.Ble_S;
1793                                 else
1794                                         opcode = OpCodes.Ble;
1795                                 break;
1796
1797                         case Operator.GreaterThanOrEqual:
1798                                 if (close_target)
1799                                         opcode = OpCodes.Bge_S;
1800                                 else
1801                                         opcode = OpCodes.Ble;
1802                                 break;
1803
1804                         default:
1805                                 throw new Exception ("EmitBranchable called on non-EmitBranchable operator: "
1806                                                      + oper.ToString ());
1807                         }
1808
1809                         ig.Emit (opcode, target);
1810                 }
1811                 
1812                 public override void Emit (EmitContext ec)
1813                 {
1814                         ILGenerator ig = ec.ig;
1815                         Type l = left.Type;
1816                         Type r = right.Type;
1817                         OpCode opcode;
1818
1819                         if (method != null) {
1820
1821                                 // Note that operators are static anyway
1822                                 
1823                                 if (Arguments != null) 
1824                                         Invocation.EmitArguments (ec, method, Arguments);
1825                                 
1826                                 if (method is MethodInfo)
1827                                         ig.Emit (OpCodes.Call, (MethodInfo) method);
1828                                 else
1829                                         ig.Emit (OpCodes.Call, (ConstructorInfo) method);
1830
1831                                 return;
1832                         }
1833
1834                         //
1835                         // Handle short-circuit operators differently
1836                         // than the rest
1837                         //
1838                         if (oper == Operator.LogicalAnd){
1839                                 Label load_zero = ig.DefineLabel ();
1840                                 Label end = ig.DefineLabel ();
1841                                 
1842                                 left.Emit (ec);
1843                                 ig.Emit (OpCodes.Brfalse, load_zero);
1844                                 right.Emit (ec);
1845                                 ig.Emit (OpCodes.Br, end);
1846                                 ig.MarkLabel (load_zero);
1847                                 ig.Emit (OpCodes.Ldc_I4_0);
1848                                 ig.MarkLabel (end);
1849                                 return;
1850                         } else if (oper == Operator.LogicalOr){
1851                                 Label load_one = ig.DefineLabel ();
1852                                 Label end = ig.DefineLabel ();
1853                                 
1854                                 left.Emit (ec);
1855                                 ig.Emit (OpCodes.Brtrue, load_one);
1856                                 right.Emit (ec);
1857                                 ig.Emit (OpCodes.Br, end);
1858                                 ig.MarkLabel (load_one);
1859                                 ig.Emit (OpCodes.Ldc_I4_1);
1860                                 ig.MarkLabel (end);
1861                                 return;
1862                         }
1863                         
1864                         left.Emit (ec);
1865                         right.Emit (ec);
1866
1867                         switch (oper){
1868                         case Operator.Multiply:
1869                                 if (ec.CheckState){
1870                                         if (l == TypeManager.int32_type || l == TypeManager.int64_type)
1871                                                 opcode = OpCodes.Mul_Ovf;
1872                                         else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
1873                                                 opcode = OpCodes.Mul_Ovf_Un;
1874                                         else
1875                                                 opcode = OpCodes.Mul;
1876                                 } else
1877                                         opcode = OpCodes.Mul;
1878
1879                                 break;
1880
1881                         case Operator.Division:
1882                                 if (l == TypeManager.uint32_type || l == TypeManager.uint64_type)
1883                                         opcode = OpCodes.Div_Un;
1884                                 else
1885                                         opcode = OpCodes.Div;
1886                                 break;
1887
1888                         case Operator.Modulus:
1889                                 if (l == TypeManager.uint32_type || l == TypeManager.uint64_type)
1890                                         opcode = OpCodes.Rem_Un;
1891                                 else
1892                                         opcode = OpCodes.Rem;
1893                                 break;
1894
1895                         case Operator.Addition:
1896                                 if (ec.CheckState){
1897                                         if (l == TypeManager.int32_type || l == TypeManager.int64_type)
1898                                                 opcode = OpCodes.Add_Ovf;
1899                                         else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
1900                                                 opcode = OpCodes.Add_Ovf_Un;
1901                                         else
1902                                                 opcode = OpCodes.Mul;
1903                                 } else
1904                                         opcode = OpCodes.Add;
1905                                 break;
1906
1907                         case Operator.Subtraction:
1908                                 if (ec.CheckState){
1909                                         if (l == TypeManager.int32_type || l == TypeManager.int64_type)
1910                                                 opcode = OpCodes.Sub_Ovf;
1911                                         else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
1912                                                 opcode = OpCodes.Sub_Ovf_Un;
1913                                         else
1914                                                 opcode = OpCodes.Sub;
1915                                 } else
1916                                         opcode = OpCodes.Sub;
1917                                 break;
1918
1919                         case Operator.RightShift:
1920                                 opcode = OpCodes.Shr;
1921                                 break;
1922                                 
1923                         case Operator.LeftShift:
1924                                 opcode = OpCodes.Shl;
1925                                 break;
1926
1927                         case Operator.Equality:
1928                                 opcode = OpCodes.Ceq;
1929                                 break;
1930
1931                         case Operator.Inequality:
1932                                 ec.ig.Emit (OpCodes.Ceq);
1933                                 ec.ig.Emit (OpCodes.Ldc_I4_0);
1934                                 
1935                                 opcode = OpCodes.Ceq;
1936                                 break;
1937
1938                         case Operator.LessThan:
1939                                 opcode = OpCodes.Clt;
1940                                 break;
1941
1942                         case Operator.GreaterThan:
1943                                 opcode = OpCodes.Cgt;
1944                                 break;
1945
1946                         case Operator.LessThanOrEqual:
1947                                 ec.ig.Emit (OpCodes.Cgt);
1948                                 ec.ig.Emit (OpCodes.Ldc_I4_0);
1949                                 
1950                                 opcode = OpCodes.Ceq;
1951                                 break;
1952
1953                         case Operator.GreaterThanOrEqual:
1954                                 ec.ig.Emit (OpCodes.Clt);
1955                                 ec.ig.Emit (OpCodes.Ldc_I4_1);
1956                                 
1957                                 opcode = OpCodes.Sub;
1958                                 break;
1959
1960                         case Operator.BitwiseOr:
1961                                 opcode = OpCodes.Or;
1962                                 break;
1963
1964                         case Operator.BitwiseAnd:
1965                                 opcode = OpCodes.And;
1966                                 break;
1967
1968                         case Operator.ExclusiveOr:
1969                                 opcode = OpCodes.Xor;
1970                                 break;
1971
1972                         default:
1973                                 throw new Exception ("This should not happen: Operator = "
1974                                                      + oper.ToString ());
1975                         }
1976
1977                         ig.Emit (opcode);
1978                 }
1979         }
1980
1981         /// <summary>
1982         ///   Implements the ternary conditiona operator (?:)
1983         /// </summary>
1984         public class Conditional : Expression {
1985                 Expression expr, trueExpr, falseExpr;
1986                 Location loc;
1987                 
1988                 public Conditional (Expression expr, Expression trueExpr, Expression falseExpr, Location l)
1989                 {
1990                         this.expr = expr;
1991                         this.trueExpr = trueExpr;
1992                         this.falseExpr = falseExpr;
1993                         this.loc = l;
1994                 }
1995
1996                 public Expression Expr {
1997                         get {
1998                                 return expr;
1999                         }
2000                 }
2001
2002                 public Expression TrueExpr {
2003                         get {
2004                                 return trueExpr;
2005                         }
2006                 }
2007
2008                 public Expression FalseExpr {
2009                         get {
2010                                 return falseExpr;
2011                         }
2012                 }
2013
2014                 public override Expression DoResolve (EmitContext ec)
2015                 {
2016                         expr = expr.Resolve (ec);
2017
2018                         if (expr.Type != TypeManager.bool_type)
2019                                 expr = Expression.ConvertImplicitRequired (
2020                                         ec, expr, TypeManager.bool_type, loc);
2021                         
2022                         trueExpr = trueExpr.Resolve (ec);
2023                         falseExpr = falseExpr.Resolve (ec);
2024
2025                         if (expr == null || trueExpr == null || falseExpr == null)
2026                                 return null;
2027
2028                         if (trueExpr.Type == falseExpr.Type)
2029                                 type = trueExpr.Type;
2030                         else {
2031                                 Expression conv;
2032
2033                                 //
2034                                 // First, if an implicit conversion exists from trueExpr
2035                                 // to falseExpr, then the result type is of type falseExpr.Type
2036                                 //
2037                                 conv = ConvertImplicit (ec, trueExpr, falseExpr.Type, loc);
2038                                 if (conv != null){
2039                                         type = falseExpr.Type;
2040                                         trueExpr = conv;
2041                                 } else if ((conv = ConvertImplicit(ec, falseExpr,trueExpr.Type,loc))!= null){
2042                                         type = trueExpr.Type;
2043                                         falseExpr = conv;
2044                                 } else {
2045                                         Error (173, loc, "The type of the conditional expression can " +
2046                                                "not be computed because there is no implicit conversion" +
2047                                                " from `" + TypeManager.CSharpName (trueExpr.Type) + "'" +
2048                                                " and `" + TypeManager.CSharpName (falseExpr.Type) + "'");
2049                                         return null;
2050                                 }
2051                         }
2052
2053                         if (expr is BoolConstant){
2054                                 BoolConstant bc = (BoolConstant) expr;
2055
2056                                 if (bc.Value)
2057                                         return trueExpr;
2058                                 else
2059                                         return falseExpr;
2060                         }
2061
2062                         eclass = ExprClass.Value;
2063                         return this;
2064                 }
2065
2066                 public override void Emit (EmitContext ec)
2067                 {
2068                         ILGenerator ig = ec.ig;
2069                         Label false_target = ig.DefineLabel ();
2070                         Label end_target = ig.DefineLabel ();
2071
2072                         expr.Emit (ec);
2073                         ig.Emit (OpCodes.Brfalse, false_target);
2074                         trueExpr.Emit (ec);
2075                         ig.Emit (OpCodes.Br, end_target);
2076                         ig.MarkLabel (false_target);
2077                         falseExpr.Emit (ec);
2078                         ig.MarkLabel (end_target);
2079                 }
2080
2081         }
2082
2083         /// <summary>
2084         ///   Local variables
2085         /// </summary>
2086         public class LocalVariableReference : Expression, IAssignMethod, IMemoryLocation {
2087                 public readonly string Name;
2088                 public readonly Block Block;
2089                 Location loc;
2090                 VariableInfo variable_info;
2091                 
2092                 public LocalVariableReference (Block block, string name, Location l)
2093                 {
2094                         Block = block;
2095                         Name = name;
2096                         loc = l;
2097                         eclass = ExprClass.Variable;
2098                 }
2099
2100                 public VariableInfo VariableInfo {
2101                         get {
2102                                 if (variable_info == null)
2103                                         variable_info = Block.GetVariableInfo (Name);
2104                                 return variable_info;
2105                         }
2106                 }
2107                 
2108                 public override Expression DoResolve (EmitContext ec)
2109                 {
2110                         VariableInfo vi = VariableInfo;
2111
2112                         if (Block.IsConstant (Name)) {
2113                                 Expression e = Block.GetConstantExpression (Name);
2114
2115                                 e = e.Resolve (ec);
2116                                 if (e == null)  
2117                                         return null;
2118
2119                                 if (!(e is Constant)) {
2120                                         Report.Error (150, loc, "A constant value is expected");
2121                                         return null;
2122                                 }
2123
2124                                 vi.Used = true;
2125                                 return e;
2126                         }
2127
2128                         type = vi.VariableType;
2129                         return this;
2130                 }
2131
2132                 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
2133                 {
2134                         Expression e = DoResolve (ec);
2135
2136                         if (e == null)
2137                                 return null;
2138
2139                         VariableInfo vi = VariableInfo;
2140                         
2141                         if (vi.ReadOnly){
2142                                 if (vi.Assigned){
2143                                         Report.Error (
2144                                                 1604, loc,
2145                                                 "cannot assign to `" + Name + "' because it is readonly");
2146                                         return null;
2147                                 }
2148                         }
2149                         
2150                         return this;
2151                 }
2152
2153                 public override void Emit (EmitContext ec)
2154                 {
2155                         VariableInfo vi = VariableInfo;
2156                         ILGenerator ig = ec.ig;
2157                         int idx = vi.Idx;
2158
2159                         vi.Used = true;
2160
2161                         switch (idx){
2162                         case 0:
2163                                 ig.Emit (OpCodes.Ldloc_0);
2164                                 break;
2165                                 
2166                         case 1:
2167                                 ig.Emit (OpCodes.Ldloc_1);
2168                                 break;
2169                                 
2170                         case 2:
2171                                 ig.Emit (OpCodes.Ldloc_2);
2172                                 break;
2173                                 
2174                         case 3:
2175                                 ig.Emit (OpCodes.Ldloc_3);
2176                                 break;
2177                                 
2178                         default:
2179                                 if (idx <= 255)
2180                                         ig.Emit (OpCodes.Ldloc_S, (byte) idx);
2181                                 else
2182                                         ig.Emit (OpCodes.Ldloc, idx);
2183                                 break;
2184                         }
2185                 }
2186                 
2187                 public static void Store (ILGenerator ig, int idx)
2188                 {
2189                         switch (idx){
2190                         case 0:
2191                                 ig.Emit (OpCodes.Stloc_0);
2192                                 break;
2193                                 
2194                         case 1:
2195                                 ig.Emit (OpCodes.Stloc_1);
2196                                 break;
2197                                 
2198                         case 2:
2199                                 ig.Emit (OpCodes.Stloc_2);
2200                                 break;
2201                                 
2202                         case 3:
2203                                 ig.Emit (OpCodes.Stloc_3);
2204                                 break;
2205                                 
2206                         default:
2207                                 if (idx <= 255)
2208                                         ig.Emit (OpCodes.Stloc_S, (byte) idx);
2209                                 else
2210                                         ig.Emit (OpCodes.Stloc, idx);
2211                                 break;
2212                         }
2213                 }
2214
2215                 public void EmitAssign (EmitContext ec, Expression source)
2216                 {
2217                         ILGenerator ig = ec.ig;
2218                         VariableInfo vi = VariableInfo;
2219
2220                         vi.Assigned = true;
2221
2222                         source.Emit (ec);
2223                         
2224                         // Funny seems the code below generates optimal code for us, but
2225                         // seems to take too long to generate what we need.
2226                         // ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
2227
2228                         Store (ig, vi.Idx);
2229                 }
2230                 
2231                 public void AddressOf (EmitContext ec)
2232                 {
2233                         VariableInfo vi = VariableInfo;
2234                         int idx = vi.Idx;
2235
2236                         vi.Used = true;
2237                         vi.Assigned = true;
2238                         
2239                         if (idx <= 255)
2240                                 ec.ig.Emit (OpCodes.Ldloca_S, (byte) idx);
2241                         else
2242                                 ec.ig.Emit (OpCodes.Ldloca, idx);
2243                 }
2244         }
2245
2246         /// <summary>
2247         ///   This represents a reference to a parameter in the intermediate
2248         ///   representation.
2249         /// </summary>
2250         public class ParameterReference : Expression, IAssignMethod, IMemoryLocation {
2251                 Parameters pars;
2252                 String name;
2253                 int idx;
2254                 bool is_ref;
2255                 
2256                 public ParameterReference (Parameters pars, int idx, string name)
2257                 {
2258                         this.pars = pars;
2259                         this.idx  = idx;
2260                         this.name = name;
2261                         eclass = ExprClass.Variable;
2262                 }
2263
2264                 //
2265                 // Notice that for ref/out parameters, the type exposed is not the
2266                 // same type exposed externally.
2267                 //
2268                 // for "ref int a":
2269                 //   externally we expose "int&"
2270                 //   here we expose       "int".
2271                 //
2272                 // We record this in "is_ref".  This means that the type system can treat
2273                 // the type as it is expected, but when we generate the code, we generate
2274                 // the alternate kind of code.
2275                 //
2276                 public override Expression DoResolve (EmitContext ec)
2277                 {
2278                         type = pars.GetParameterInfo (ec.TypeContainer, idx, out is_ref);
2279                         eclass = ExprClass.Variable;
2280                         
2281                         return this;
2282                 }
2283
2284                 public override void Emit (EmitContext ec)
2285                 {
2286                         ILGenerator ig = ec.ig;
2287                         int arg_idx = idx;
2288
2289                         if (!ec.IsStatic)
2290                                 arg_idx++;
2291                         
2292                         if (arg_idx <= 255)
2293                                 ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
2294                         else
2295                                 ig.Emit (OpCodes.Ldarg, arg_idx);
2296
2297                         if (!is_ref)
2298                                 return;
2299
2300                         //
2301                         // If we are a reference, we loaded on the stack a pointer
2302                         // Now lets load the real value
2303                         //
2304
2305                         if (type == TypeManager.int32_type)
2306                                 ig.Emit (OpCodes.Ldind_I4);
2307                         else if (type == TypeManager.uint32_type)
2308                                 ig.Emit (OpCodes.Ldind_U4);
2309                         else if (type == TypeManager.int64_type || type == TypeManager.uint64_type)
2310                                 ig.Emit (OpCodes.Ldind_I8);
2311                         else if (type == TypeManager.char_type)
2312                                 ig.Emit (OpCodes.Ldind_U2);
2313                         else if (type == TypeManager.short_type)
2314                                 ig.Emit (OpCodes.Ldind_I2);
2315                         else if (type == TypeManager.ushort_type)
2316                                 ig.Emit (OpCodes.Ldind_U2);
2317                         else if (type == TypeManager.float_type)
2318                                 ig.Emit (OpCodes.Ldind_R4);
2319                         else if (type == TypeManager.double_type)
2320                                 ig.Emit (OpCodes.Ldind_R8);
2321                         else if (type == TypeManager.byte_type)
2322                                 ig.Emit (OpCodes.Ldind_U1);
2323                         else if (type == TypeManager.sbyte_type)
2324                                 ig.Emit (OpCodes.Ldind_I1);
2325                         else if (type == TypeManager.intptr_type)
2326                                 ig.Emit (OpCodes.Ldind_I);
2327                         else
2328                                 ig.Emit (OpCodes.Ldind_Ref);
2329                 }
2330
2331                 public void EmitAssign (EmitContext ec, Expression source)
2332                 {
2333                         ILGenerator ig = ec.ig;
2334                         int arg_idx = idx;
2335
2336                         if (!ec.IsStatic)
2337                                 arg_idx++;
2338
2339                         if (is_ref){
2340                                 // Load the pointer
2341                                 if (arg_idx <= 255)
2342                                         ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
2343                                 else
2344                                         ig.Emit (OpCodes.Ldarg, arg_idx);
2345                         }
2346                         
2347                         source.Emit (ec);
2348
2349                         if (is_ref){
2350                                 if (type == TypeManager.int32_type || type == TypeManager.uint32_type)
2351                                         ig.Emit (OpCodes.Stind_I4);
2352                                 else if (type == TypeManager.int64_type || type == TypeManager.uint64_type)
2353                                         ig.Emit (OpCodes.Stind_I8);
2354                                 else if (type == TypeManager.char_type || type == TypeManager.short_type ||
2355                                         type == TypeManager.ushort_type)
2356                                         ig.Emit (OpCodes.Stind_I2);
2357                                 else if (type == TypeManager.float_type)
2358                                         ig.Emit (OpCodes.Stind_R4);
2359                                 else if (type == TypeManager.double_type)
2360                                         ig.Emit (OpCodes.Stind_R8);
2361                                 else if (type == TypeManager.byte_type || type == TypeManager.sbyte_type)
2362                                         ig.Emit (OpCodes.Stind_I1);
2363                                 else if (type == TypeManager.intptr_type)
2364                                         ig.Emit (OpCodes.Stind_I);
2365                                 else
2366                                         ig.Emit (OpCodes.Stind_Ref);
2367                         } else {
2368                                 if (arg_idx <= 255)
2369                                         ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
2370                                 else
2371                                         ig.Emit (OpCodes.Starg, arg_idx);
2372                         }
2373                         
2374                 }
2375
2376                 public void AddressOf (EmitContext ec)
2377                 {
2378                         int arg_idx = idx;
2379
2380                         if (!ec.IsStatic)
2381                                 arg_idx++;
2382
2383                         if (arg_idx <= 255)
2384                                 ec.ig.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
2385                         else
2386                                 ec.ig.Emit (OpCodes.Ldarga, arg_idx);
2387                 }
2388         }
2389         
2390         /// <summary>
2391         ///   Used for arguments to New(), Invocation()
2392         /// </summary>
2393         public class Argument {
2394                 public enum AType : byte {
2395                         Expression,
2396                         Ref,
2397                         Out
2398                 };
2399
2400                 public readonly AType ArgType;
2401                 public Expression expr;
2402                 
2403                 public Argument (Expression expr, AType type)
2404                 {
2405                         this.expr = expr;
2406                         this.ArgType = type;
2407                 }
2408
2409                 public Expression Expr {
2410                         get {
2411                                 return expr;
2412                         }
2413
2414                         set {
2415                                 expr = value;
2416                         }
2417                 }
2418
2419                 public Type Type {
2420                         get {
2421                                 return expr.Type;
2422                         }
2423                 }
2424
2425                 public Parameter.Modifier GetParameterModifier ()
2426                 {
2427                         if (ArgType == AType.Ref)
2428                                 return Parameter.Modifier.REF;
2429
2430                         if (ArgType == AType.Out)
2431                                 return Parameter.Modifier.OUT;
2432
2433                         return Parameter.Modifier.NONE;
2434                 }
2435
2436                 public static string FullDesc (Argument a)
2437                 {
2438                         return (a.ArgType == AType.Ref ? "ref " :
2439                                 (a.ArgType == AType.Out ? "out " : "")) +
2440                                 TypeManager.CSharpName (a.Expr.Type);
2441                 }
2442                 
2443                 public bool Resolve (EmitContext ec, Location loc)
2444                 {
2445                         expr = expr.Resolve (ec);
2446
2447                         if (ArgType == AType.Expression)
2448                                 return expr != null;
2449
2450                         if (expr.eclass != ExprClass.Variable){
2451                                 Report.Error (206, loc,
2452                                               "A property or indexer can not be passed as an out or ref " +
2453                                               "parameter");
2454                                 return false;
2455                         }
2456                                 
2457                         return expr != null;
2458                 }
2459
2460                 public void Emit (EmitContext ec)
2461                 {
2462                         if (ArgType == AType.Ref || ArgType == AType.Out)
2463                                 ((IMemoryLocation)expr).AddressOf (ec);
2464                         else
2465                                 expr.Emit (ec);
2466                 }
2467         }
2468
2469         /// <summary>
2470         ///   Invocation of methods or delegates.
2471         /// </summary>
2472         public class Invocation : ExpressionStatement {
2473                 public readonly ArrayList Arguments;
2474                 Location loc;
2475
2476                 Expression expr;
2477                 MethodBase method = null;
2478                         
2479                 static Hashtable method_parameter_cache;
2480
2481                 static Invocation ()
2482                 {
2483                         method_parameter_cache = new PtrHashtable ();
2484                 }
2485                         
2486                 //
2487                 // arguments is an ArrayList, but we do not want to typecast,
2488                 // as it might be null.
2489                 //
2490                 // FIXME: only allow expr to be a method invocation or a
2491                 // delegate invocation (7.5.5)
2492                 //
2493                 public Invocation (Expression expr, ArrayList arguments, Location l)
2494                 {
2495                         this.expr = expr;
2496                         Arguments = arguments;
2497                         loc = l;
2498                 }
2499
2500                 public Expression Expr {
2501                         get {
2502                                 return expr;
2503                         }
2504                 }
2505
2506                 /// <summary>
2507                 ///   Returns the Parameters (a ParameterData interface) for the
2508                 ///   Method `mb'
2509                 /// </summary>
2510                 public static ParameterData GetParameterData (MethodBase mb)
2511                 {
2512                         object pd = method_parameter_cache [mb];
2513                         object ip;
2514                         
2515                         if (pd != null)
2516                                 return (ParameterData) pd;
2517
2518                         
2519                         ip = TypeManager.LookupParametersByBuilder (mb);
2520                         if (ip != null){
2521                                 method_parameter_cache [mb] = ip;
2522
2523                                 return (ParameterData) ip;
2524                         } else {
2525                                 ParameterInfo [] pi = mb.GetParameters ();
2526                                 ReflectionParameters rp = new ReflectionParameters (pi);
2527                                 method_parameter_cache [mb] = rp;
2528
2529                                 return (ParameterData) rp;
2530                         }
2531                 }
2532
2533                 /// <summary>
2534                 ///   Tells whether a user defined conversion from Type `from' to
2535                 ///   Type `to' exists.
2536                 ///
2537                 ///   FIXME: we could implement a cache here. 
2538                 /// </summary>
2539                 static bool ConversionExists (EmitContext ec, Type from, Type to, Location loc)
2540                 {
2541                         // Locate user-defined implicit operators
2542
2543                         Expression mg;
2544                         
2545                         mg = MemberLookup (ec, to, "op_Implicit", false, loc);
2546
2547                         if (mg != null) {
2548                                 MethodGroupExpr me = (MethodGroupExpr) mg;
2549                                 
2550                                 for (int i = me.Methods.Length; i > 0;) {
2551                                         i--;
2552                                         MethodBase mb = me.Methods [i];
2553                                         ParameterData pd = GetParameterData (mb);
2554                                         
2555                                         if (from == pd.ParameterType (0))
2556                                                 return true;
2557                                 }
2558                         }
2559
2560                         mg = MemberLookup (ec, from, "op_Implicit", false, loc);
2561
2562                         if (mg != null) {
2563                                 MethodGroupExpr me = (MethodGroupExpr) mg;
2564
2565                                 for (int i = me.Methods.Length; i > 0;) {
2566                                         i--;
2567                                         MethodBase mb = me.Methods [i];
2568                                         MethodInfo mi = (MethodInfo) mb;
2569                                         
2570                                         if (mi.ReturnType == to)
2571                                                 return true;
2572                                 }
2573                         }
2574                         
2575                         return false;
2576                 }
2577                 
2578                 /// <summary>
2579                 ///  Determines "better conversion" as specified in 7.4.2.3
2580                 ///  Returns : 1 if a->p is better
2581                 ///            0 if a->q or neither is better 
2582                 /// </summary>
2583                 static int BetterConversion (EmitContext ec, Argument a, Type p, Type q, bool use_standard,
2584                                              Location loc)
2585                 {
2586                         Type argument_type = a.Type;
2587                         Expression argument_expr = a.Expr;
2588
2589                         if (argument_type == null)
2590                                 throw new Exception ("Expression of type " + a.Expr + " does not resolve its type");
2591
2592                         if (p == q)
2593                                 return 0;
2594                         
2595                         if (argument_type == p)
2596                                 return 1;
2597
2598                         if (argument_type == q)
2599                                 return 0;
2600
2601                         //
2602                         // Now probe whether an implicit constant expression conversion
2603                         // can be used.
2604                         //
2605                         // An implicit constant expression conversion permits the following
2606                         // conversions:
2607                         //
2608                         //    * A constant-expression of type `int' can be converted to type
2609                         //      sbyte, byute, short, ushort, uint, ulong provided the value of
2610                         //      of the expression is withing the range of the destination type.
2611                         //
2612                         //    * A constant-expression of type long can be converted to type
2613                         //      ulong, provided the value of the constant expression is not negative
2614                         //
2615                         // FIXME: Note that this assumes that constant folding has
2616                         // taken place.  We dont do constant folding yet.
2617                         //
2618
2619                         if (argument_expr is IntConstant){
2620                                 IntConstant ei = (IntConstant) argument_expr;
2621                                 int value = ei.Value;
2622                                 
2623                                 if (p == TypeManager.sbyte_type){
2624                                         if (value >= SByte.MinValue && value <= SByte.MaxValue)
2625                                                 return 1;
2626                                 } else if (p == TypeManager.byte_type){
2627                                         if (Byte.MinValue >= 0 && value <= Byte.MaxValue)
2628                                                 return 1;
2629                                 } else if (p == TypeManager.short_type){
2630                                         if (value >= Int16.MinValue && value <= Int16.MaxValue)
2631                                                 return 1;
2632                                 } else if (p == TypeManager.ushort_type){
2633                                         if (value >= UInt16.MinValue && value <= UInt16.MaxValue)
2634                                                 return 1;
2635                                 } else if (p == TypeManager.uint32_type){
2636                                         //
2637                                         // we can optimize this case: a positive int32
2638                                         // always fits on a uint32
2639                                         //
2640                                         if (value >= 0)
2641                                                 return 1;
2642                                 } else if (p == TypeManager.uint64_type){
2643                                         //
2644                                         // we can optimize this case: a positive int32
2645                                         // always fits on a uint64
2646                                         //
2647                                         if (value >= 0)
2648                                                 return 1;
2649                                 }
2650                         } else if (argument_type == TypeManager.int64_type && argument_expr is LongConstant){
2651                                 LongConstant lc = (LongConstant) argument_expr;
2652                                 
2653                                 if (p == TypeManager.uint64_type){
2654                                         if (lc.Value > 0)
2655                                                 return 1;
2656                                 }
2657                         }
2658
2659                         if (q == null) {
2660
2661                                 Expression tmp;
2662
2663                                 if (use_standard)
2664                                         tmp = ConvertImplicitStandard (ec, argument_expr, p, loc);
2665                                 else
2666                                         tmp = ConvertImplicit (ec, argument_expr, p, loc);
2667
2668                                 if (tmp != null)
2669                                         return 1;
2670                                 else
2671                                         return 0;
2672
2673                         }
2674
2675                         if (ConversionExists (ec, p, q, loc) == true &&
2676                             ConversionExists (ec, q, p, loc) == false)
2677                                 return 1;
2678
2679                         if (p == TypeManager.sbyte_type)
2680                                 if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
2681                                     q == TypeManager.uint32_type || q == TypeManager.uint64_type)
2682                                         return 1;
2683
2684                         if (p == TypeManager.short_type)
2685                                 if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
2686                                     q == TypeManager.uint64_type)
2687                                         return 1;
2688
2689                         if (p == TypeManager.int32_type)
2690                                 if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
2691                                         return 1;
2692
2693                         if (p == TypeManager.int64_type)
2694                                 if (q == TypeManager.uint64_type)
2695                                         return 1;
2696
2697                         return 0;
2698                 }
2699                 
2700                 /// <summary>
2701                 ///  Determines "Better function"
2702                 /// </summary>
2703                 /// <remarks>
2704                 ///    and returns an integer indicating :
2705                 ///    0 if candidate ain't better
2706                 ///    1 if candidate is better than the current best match
2707                 /// </remarks>
2708                 static int BetterFunction (EmitContext ec, ArrayList args,
2709                                            MethodBase candidate, MethodBase best,
2710                                            bool use_standard, Location loc)
2711                 {
2712                         ParameterData candidate_pd = GetParameterData (candidate);
2713                         ParameterData best_pd;
2714                         int argument_count;
2715
2716                         if (args == null)
2717                                 argument_count = 0;
2718                         else
2719                                 argument_count = args.Count;
2720
2721                         if (candidate_pd.Count == 0 && argument_count == 0)
2722                                 return 1;
2723
2724                         if (best == null) {
2725                                 if (candidate_pd.Count == argument_count) {
2726                                         int x = 0;
2727                                         for (int j = argument_count; j > 0;) {
2728                                                 j--;
2729                                                 
2730                                                 Argument a = (Argument) args [j];
2731                                                 
2732                                                 x = BetterConversion (
2733                                                         ec, a, candidate_pd.ParameterType (j), null,
2734                                                         use_standard, loc);
2735                                                 
2736                                                 if (x <= 0)
2737                                                         break;
2738                                         }
2739                                         
2740                                         if (x > 0)
2741                                                 return 1;
2742                                         else
2743                                                 return 0;
2744                                         
2745                                 } else
2746                                         return 0;
2747                         }
2748
2749                         best_pd = GetParameterData (best);
2750
2751                         if (candidate_pd.Count == argument_count && best_pd.Count == argument_count) {
2752                                 int rating1 = 0, rating2 = 0;
2753                                 
2754                                 for (int j = argument_count; j > 0;) {
2755                                         j--;
2756                                         int x, y;
2757                                         
2758                                         Argument a = (Argument) args [j];
2759
2760                                         x = BetterConversion (ec, a, candidate_pd.ParameterType (j),
2761                                                               best_pd.ParameterType (j), use_standard, loc);
2762                                         y = BetterConversion (ec, a, best_pd.ParameterType (j),
2763                                                               candidate_pd.ParameterType (j), use_standard,
2764                                                               loc);
2765                                         
2766                                         rating1 += x;
2767                                         rating2 += y;
2768                                 }
2769
2770                                 if (rating1 > rating2)
2771                                         return 1;
2772                                 else
2773                                         return 0;
2774                         } else
2775                                 return 0;
2776                         
2777                 }
2778
2779                 public static string FullMethodDesc (MethodBase mb)
2780                 {
2781                         StringBuilder sb = new StringBuilder (mb.Name);
2782                         ParameterData pd = GetParameterData (mb);
2783
2784                         int count = pd.Count;
2785                         sb.Append (" (");
2786                         
2787                         for (int i = count; i > 0; ) {
2788                                 i--;
2789
2790                                 sb.Append (pd.ParameterDesc (count - i - 1));
2791                                 if (i != 0)
2792                                         sb.Append (", ");
2793                         }
2794                         
2795                         sb.Append (")");
2796                         return sb.ToString ();
2797                 }
2798
2799                 public static MethodGroupExpr MakeUnionSet (Expression mg1, Expression mg2)
2800                 {
2801                         MemberInfo [] miset;
2802                         MethodGroupExpr union;
2803                         
2804                         if (mg1 != null && mg2 != null) {
2805                                 
2806                                 MethodGroupExpr left_set = null, right_set = null;
2807                                 int length1 = 0, length2 = 0;
2808                                 
2809                                 left_set = (MethodGroupExpr) mg1;
2810                                 length1 = left_set.Methods.Length;
2811                                 
2812                                 right_set = (MethodGroupExpr) mg2;
2813                                 length2 = right_set.Methods.Length;
2814
2815                                 ArrayList common = new ArrayList ();
2816                                 
2817                                 for (int i = 0; i < left_set.Methods.Length; i++) {
2818                                         for (int j = 0; j < right_set.Methods.Length; j++) {
2819                                                 if (left_set.Methods [i] == right_set.Methods [j]) 
2820                                                         common.Add (left_set.Methods [i]);
2821                                         }
2822                                 }
2823                                 
2824                                 miset = new MemberInfo [length1 + length2 - common.Count];
2825
2826                                 left_set.Methods.CopyTo (miset, 0);
2827
2828                                 int k = 0;
2829                                 
2830                                 for (int j = 0; j < right_set.Methods.Length; j++)
2831                                         if (!common.Contains (right_set.Methods [j]))
2832                                                 miset [length1 + k++] = right_set.Methods [j];
2833                                 
2834                                 union = new MethodGroupExpr (miset);
2835
2836                                 return union;
2837
2838                         } else if (mg1 == null && mg2 != null) {
2839                                 
2840                                 MethodGroupExpr me = (MethodGroupExpr) mg2; 
2841                                 
2842                                 miset = new MemberInfo [me.Methods.Length];
2843                                 me.Methods.CopyTo (miset, 0);
2844
2845                                 union = new MethodGroupExpr (miset);
2846                                 
2847                                 return union;
2848
2849                         } else if (mg2 == null && mg1 != null) {
2850                                 
2851                                 MethodGroupExpr me = (MethodGroupExpr) mg1; 
2852                                 
2853                                 miset = new MemberInfo [me.Methods.Length];
2854                                 me.Methods.CopyTo (miset, 0);
2855
2856                                 union = new MethodGroupExpr (miset);
2857                                 
2858                                 return union;
2859                         }
2860                         
2861                         return null;
2862                 }
2863
2864                 /// <summary>
2865                 ///  Determines is the candidate method, if a params method, is applicable
2866                 ///  in its expanded form to the given set of arguments
2867                 /// </summary>
2868                 static bool IsParamsMethodApplicable (ArrayList arguments, MethodBase candidate)
2869                 {
2870                         int arg_count;
2871                         
2872                         if (arguments == null)
2873                                 arg_count = 0;
2874                         else
2875                                 arg_count = arguments.Count;
2876                         
2877                         ParameterData pd = GetParameterData (candidate);
2878                         
2879                         int pd_count = pd.Count;
2880
2881                         if (pd_count == 0)
2882                                 return false;
2883                         
2884                         if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
2885                                 return false;
2886
2887                         if (pd_count - 1 > arg_count)
2888                                 return false;
2889
2890                         // If we have come this far, the case which remains is when the number of parameters
2891                         // is less than or equal to the argument count. So, we now check if the element type
2892                         // of the params array is compatible with each argument type
2893                         //
2894
2895                         Type element_type = pd.ParameterType (pd_count - 1).GetElementType ();
2896
2897                         for (int i = pd_count - 1; i < arg_count - 1; i++) {
2898                                 Argument a = (Argument) arguments [i];
2899                                 if (!StandardConversionExists (a.Type, element_type))
2900                                         return false;
2901                         }
2902                         
2903                         return true;
2904                 }
2905
2906                 /// <summary>
2907                 ///  Determines if the candidate method is applicable (section 14.4.2.1)
2908                 ///  to the given set of arguments
2909                 /// </summary>
2910                 static bool IsApplicable (ArrayList arguments, MethodBase candidate)
2911                 {
2912                         int arg_count;
2913
2914                         if (arguments == null)
2915                                 arg_count = 0;
2916                         else
2917                                 arg_count = arguments.Count;
2918
2919                         ParameterData pd = GetParameterData (candidate);
2920
2921                         int pd_count = pd.Count;
2922
2923                         if (arg_count != pd.Count)
2924                                 return false;
2925
2926                         for (int i = arg_count; i > 0; ) {
2927                                 i--;
2928
2929                                 Argument a = (Argument) arguments [i];
2930
2931                                 Parameter.Modifier a_mod = a.GetParameterModifier ();
2932                                 Parameter.Modifier p_mod = pd.ParameterModifier (i);
2933
2934                                 if (a_mod == p_mod) {
2935                                         
2936                                         if (a_mod == Parameter.Modifier.NONE)
2937                                                 if (!StandardConversionExists (a.Type, pd.ParameterType (i)))
2938                                                         return false;
2939                                         
2940                                         if (a_mod == Parameter.Modifier.REF ||
2941                                             a_mod == Parameter.Modifier.OUT)
2942                                                 if (pd.ParameterType (i) != a.Type)
2943                                                         return false;
2944                                 } else
2945                                         return false;
2946                         }
2947
2948                         return true;
2949                 }
2950                 
2951                 
2952
2953                 /// <summary>
2954                 ///   Find the Applicable Function Members (7.4.2.1)
2955                 ///
2956                 ///   me: Method Group expression with the members to select.
2957                 ///       it might contain constructors or methods (or anything
2958                 ///       that maps to a method).
2959                 ///
2960                 ///   Arguments: ArrayList containing resolved Argument objects.
2961                 ///
2962                 ///   loc: The location if we want an error to be reported, or a Null
2963                 ///        location for "probing" purposes.
2964                 ///
2965                 ///   use_standard: controls whether OverloadResolve should use the 
2966                 ///   ConvertImplicit or ConvertImplicitStandard during overload resolution.
2967                 ///
2968                 ///   Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
2969                 ///            that is the best match of me on Arguments.
2970                 ///
2971                 /// </summary>
2972                 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
2973                                                           ArrayList Arguments, Location loc,
2974                                                           bool use_standard)
2975                 {
2976                         ArrayList afm = new ArrayList ();
2977                         int best_match_idx = -1;
2978                         MethodBase method = null;
2979                         int argument_count;
2980                         ArrayList candidates = new ArrayList ();
2981                         
2982                         for (int i = me.Methods.Length; i > 0; ){
2983                                 i--;
2984                                 MethodBase candidate  = me.Methods [i];
2985                                 int x;
2986
2987                                 // Check if candidate is applicable (section 14.4.2.1)
2988                                 if (!IsApplicable (Arguments, candidate))
2989                                         continue;
2990
2991                                 candidates.Add (candidate);
2992                                 x = BetterFunction (ec, Arguments, candidate, method, use_standard, loc);
2993                                 
2994                                 if (x == 0)
2995                                         continue;
2996                                 else {
2997                                         best_match_idx = i;
2998                                         method = me.Methods [best_match_idx];
2999                                 }
3000                         }
3001
3002                         if (Arguments == null)
3003                                 argument_count = 0;
3004                         else
3005                                 argument_count = Arguments.Count;
3006                         
3007                         //
3008                         // Now we see if we can find params functions, applicable in their expanded form
3009                         // since if they were applicable in their normal form, they would have been selected
3010                         // above anyways
3011                         //
3012                         if (best_match_idx == -1) {
3013
3014                                 for (int i = me.Methods.Length; i > 0; ) {
3015                                         i--;
3016                                         MethodBase candidate = me.Methods [i];
3017
3018                                         if (IsParamsMethodApplicable (Arguments, candidate)) {
3019                                                 best_match_idx = i;
3020                                                 method = me.Methods [best_match_idx];
3021                                                 break;
3022                                         }
3023                                 }
3024                         }
3025
3026                         //
3027                         // Now we see if we can at least find a method with the same number of arguments
3028                         //
3029                         ParameterData pd;
3030                         int method_count = 0;
3031
3032                         if (best_match_idx == -1) {
3033                                 
3034                                 for (int i = me.Methods.Length; i > 0;) {
3035                                         i--;
3036                                         MethodBase mb = me.Methods [i];
3037                                         pd = GetParameterData (mb);
3038                                         
3039                                         if (pd.Count == argument_count) {
3040                                                 best_match_idx = i;
3041                                                 method = me.Methods [best_match_idx];
3042                                                 method_count++;
3043                                         } else
3044                                                 continue;
3045                                 }
3046                         }
3047
3048                         if (method == null)
3049                                 return null;
3050
3051                         //
3052                         // Now check that there are no ambiguities i.e the selected method
3053                         // should be better than all the others
3054                         //
3055
3056                         for (int i = candidates.Count; i > 0; ) {
3057                                 i--;
3058                                 MethodBase candidate = (MethodBase) candidates [i];
3059                                 int x;
3060
3061                                 if (candidate == method)
3062                                         continue;
3063
3064                                 x = BetterFunction (ec, Arguments, method, candidate, use_standard, loc);
3065                                 
3066                                 if (x != 1) {
3067                                         Report.Error (
3068                                                 121, loc,
3069                                                 "Ambiguous call when selecting function due to implicit casts");
3070                                         return null;
3071                                 }
3072                         }
3073
3074                         
3075                         // And now convert implicitly, each argument to the required type
3076                         
3077                         pd = GetParameterData (method);
3078                         int pd_count = pd.Count;
3079
3080                         for (int j = 0; j < argument_count; j++) {
3081                                 Argument a = (Argument) Arguments [j];
3082                                 Expression a_expr = a.Expr;
3083                                 Type parameter_type = pd.ParameterType (j);
3084
3085                                 //
3086                                 // Note that we need to compare against the element type
3087                                 // when we have a params method
3088                                 //
3089                                 if (pd.ParameterModifier (pd_count - 1) == Parameter.Modifier.PARAMS) {
3090                                         if (j >= pd_count - 1) 
3091                                                 parameter_type = pd.ParameterType (pd_count - 1).GetElementType ();
3092                                 }
3093
3094                                 if (a.Type != parameter_type){
3095                                         Expression conv;
3096                                         
3097                                         if (use_standard)
3098                                                 conv = ConvertImplicitStandard (
3099                                                         ec, a_expr, parameter_type, Location.Null);
3100                                         else
3101                                                 conv = ConvertImplicit (
3102                                                         ec, a_expr, parameter_type, Location.Null);
3103
3104                                         if (conv == null) {
3105                                                 if (!Location.IsNull (loc)) {
3106                                                         Error (1502, loc,
3107                                                                "The best overloaded match for method '" +
3108                                                                FullMethodDesc (method) +
3109                                                                "' has some invalid arguments");
3110                                                         Error (1503, loc,
3111                                                          "Argument " + (j+1) +
3112                                                          ": Cannot convert from '" + Argument.FullDesc (a) 
3113                                                          + "' to '" + pd.ParameterDesc (j) + "'");
3114                                                 }
3115                                                 return null;
3116                                         }
3117                                         
3118                         
3119                                         
3120                                         //
3121                                         // Update the argument with the implicit conversion
3122                                         //
3123                                         if (a_expr != conv)
3124                                                 a.Expr = conv;
3125
3126                                         // FIXME : For the case of params methods, we need to actually instantiate
3127                                         // an array and initialize it with the argument values etc etc.
3128
3129                                 }
3130                                 
3131                                 if (a.GetParameterModifier () != pd.ParameterModifier (j) &&
3132                                     pd.ParameterModifier (j) != Parameter.Modifier.PARAMS) {
3133                                         if (!Location.IsNull (loc)) {
3134                                                 Error (1502, loc,
3135                                                        "The best overloaded match for method '" + FullMethodDesc (method)+
3136                                                        "' has some invalid arguments");
3137                                                 Error (1503, loc,
3138                                                        "Argument " + (j+1) +
3139                                                        ": Cannot convert from '" + Argument.FullDesc (a) 
3140                                                        + "' to '" + pd.ParameterDesc (j) + "'");
3141                                         }
3142                                         return null;
3143                                 }
3144                                 
3145                                 
3146                         }
3147                         
3148                         return method;
3149                 }
3150                 
3151                 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
3152                                                           ArrayList Arguments, Location loc)
3153                 {
3154                         return OverloadResolve (ec, me, Arguments, loc, false);
3155                 }
3156                         
3157                 public override Expression DoResolve (EmitContext ec)
3158                 {
3159                         //
3160                         // First, resolve the expression that is used to
3161                         // trigger the invocation
3162                         //
3163                         expr = expr.Resolve (ec);
3164                         if (expr == null)
3165                                 return null;
3166
3167                         if (!(expr is MethodGroupExpr)) {
3168                                 Type expr_type = expr.Type;
3169
3170                                 if (expr_type != null){
3171                                         bool IsDelegate = TypeManager.IsDelegateType (expr_type);
3172                                         if (IsDelegate)
3173                                                 return (new DelegateInvocation (
3174                                                         this.expr, Arguments, loc)).Resolve (ec);
3175                                 }
3176                         }
3177
3178                         if (!(expr is MethodGroupExpr)){
3179                                 report118 (loc, this.expr, "method group");
3180                                 return null;
3181                         }
3182
3183                         //
3184                         // Next, evaluate all the expressions in the argument list
3185                         //
3186                         if (Arguments != null){
3187                                 for (int i = Arguments.Count; i > 0;){
3188                                         --i;
3189                                         Argument a = (Argument) Arguments [i];
3190
3191                                         if (!a.Resolve (ec, loc))
3192                                                 return null;
3193                                 }
3194                         }
3195
3196                         method = OverloadResolve (ec, (MethodGroupExpr) this.expr, Arguments, loc);
3197
3198                         if (method == null){
3199                                 Error (-6, loc,
3200                                        "Could not find any applicable function for this argument list");
3201                                 return null;
3202                         }
3203
3204                         if (method is MethodInfo)
3205                                 type = ((MethodInfo)method).ReturnType;
3206
3207                         eclass = ExprClass.Value;
3208                         return this;
3209                 }
3210
3211                 // <summary>
3212                 //   Emits the list of arguments as an array
3213                 // </summary>
3214                 static void EmitParams (EmitContext ec, int idx, ArrayList arguments)
3215                 {
3216                         ILGenerator ig = ec.ig;
3217                         int count = arguments.Count - idx;
3218                         Argument a = (Argument) arguments [idx];
3219                         Type t = a.expr.Type;
3220                         string array_type = t.FullName + "[]";
3221                         LocalBuilder array;
3222                         
3223                         array = ig.DeclareLocal (Type.GetType (array_type));
3224                         IntConstant.EmitInt (ig, count);
3225                         ig.Emit (OpCodes.Newarr, t);
3226                         ig.Emit (OpCodes.Stloc, array);
3227
3228                         int top = arguments.Count;
3229                         for (int j = idx; j < top; j++){
3230                                 a = (Argument) arguments [j];
3231                                 
3232                                 ig.Emit (OpCodes.Ldloc, array);
3233                                 IntConstant.EmitInt (ig, j - idx);
3234                                 a.Emit (ec);
3235                                 
3236                                 ArrayAccess.EmitStoreOpcode (ig, t);
3237                         }
3238                         ig.Emit (OpCodes.Ldloc, array);
3239                 }
3240                 
3241                 /// <summary>
3242                 ///   Emits a list of resolved Arguments that are in the arguments
3243                 ///   ArrayList.
3244                 /// 
3245                 ///   The MethodBase argument might be null if the
3246                 ///   emission of the arguments is known not to contain
3247                 ///   a `params' field (for example in constructors or other routines
3248                 ///   that keep their arguments in this structure
3249                 /// </summary>
3250                 public static void EmitArguments (EmitContext ec, MethodBase mb, ArrayList arguments)
3251                 {
3252                         ParameterData pd = null;
3253                         int top;
3254
3255                         if (arguments != null)
3256                                 top = arguments.Count;
3257                         else
3258                                 top = 0;
3259
3260                         if (mb != null)
3261                                  pd = GetParameterData (mb);
3262
3263                         for (int i = 0; i < top; i++){
3264                                 Argument a = (Argument) arguments [i];
3265
3266                                 if (pd != null){
3267                                         if (pd.ParameterModifier (i) == Parameter.Modifier.PARAMS){
3268                                                 EmitParams (ec, i, arguments);
3269                                                 return;
3270                                         }
3271                                 }
3272                                             
3273                                 a.Emit (ec);
3274                         }
3275                 }
3276
3277                 public static void EmitCall (EmitContext ec,
3278                                              bool is_static, Expression instance_expr,
3279                                              MethodBase method, ArrayList Arguments)
3280                 {
3281                         ILGenerator ig = ec.ig;
3282                         bool struct_call = false;
3283                                 
3284                         if (!is_static){
3285                                 //
3286                                 // If this is ourselves, push "this"
3287                                 //
3288                                 if (instance_expr == null){
3289                                         ig.Emit (OpCodes.Ldarg_0);
3290                                 } else {
3291                                         //
3292                                         // Push the instance expression
3293                                         //
3294                                         if (instance_expr.Type.IsSubclassOf (TypeManager.value_type)){
3295
3296                                                 struct_call = true;
3297
3298                                                 //
3299                                                 // If the expression implements IMemoryLocation, then
3300                                                 // we can optimize and use AddressOf on the
3301                                                 // return.
3302                                                 //
3303                                                 // If not we have to use some temporary storage for
3304                                                 // it.
3305                                                 if (instance_expr is IMemoryLocation)
3306                                                         ((IMemoryLocation) instance_expr).AddressOf (ec);
3307                                                 else {
3308                                                         Type t = instance_expr.Type;
3309                                                         
3310                                                         instance_expr.Emit (ec);
3311                                                         LocalBuilder temp = ig.DeclareLocal (t);
3312                                                         ig.Emit (OpCodes.Stloc, temp);
3313                                                         ig.Emit (OpCodes.Ldloca, temp);
3314                                                 }
3315                                         } else 
3316                                                 instance_expr.Emit (ec);
3317                                 }
3318                         }
3319
3320                         if (Arguments != null)
3321                                 EmitArguments (ec, method, Arguments);
3322
3323                         if (is_static || struct_call){
3324                                 if (method is MethodInfo)
3325                                         ig.Emit (OpCodes.Call, (MethodInfo) method);
3326                                 else
3327                                         ig.Emit (OpCodes.Call, (ConstructorInfo) method);
3328                         } else {
3329                                 if (method is MethodInfo)
3330                                         ig.Emit (OpCodes.Callvirt, (MethodInfo) method);
3331                                 else
3332                                         ig.Emit (OpCodes.Callvirt, (ConstructorInfo) method);
3333                         }
3334                 }
3335                 
3336                 public override void Emit (EmitContext ec)
3337                 {
3338                         MethodGroupExpr mg = (MethodGroupExpr) this.expr;
3339                         EmitCall (ec, method.IsStatic, mg.InstanceExpression, method, Arguments);
3340                 }
3341                 
3342                 public override void EmitStatement (EmitContext ec)
3343                 {
3344                         Emit (ec);
3345
3346                         // 
3347                         // Pop the return value if there is one
3348                         //
3349                         if (method is MethodInfo){
3350                                 if (((MethodInfo)method).ReturnType != TypeManager.void_type)
3351                                         ec.ig.Emit (OpCodes.Pop);
3352                         }
3353                 }
3354         }
3355
3356         /// <summary>
3357         ///    Implements the new expression 
3358         /// </summary>
3359         public class New : ExpressionStatement {
3360                 public readonly ArrayList Arguments;
3361                 public readonly string    RequestedType;
3362
3363                 Location loc;
3364                 MethodBase method = null;
3365
3366                 //
3367                 // If set, the new expression is for a value_target, and
3368                 // we will not leave anything on the stack.
3369                 //
3370                 Expression value_target;
3371                 
3372                 public New (string requested_type, ArrayList arguments, Location l)
3373                 {
3374                         RequestedType = requested_type;
3375                         Arguments = arguments;
3376                         loc = l;
3377                 }
3378
3379                 public Expression ValueTypeVariable {
3380                         get {
3381                                 return value_target;
3382                         }
3383
3384                         set {
3385                                 value_target = value;
3386                         }
3387                 }
3388
3389                 public override Expression DoResolve (EmitContext ec)
3390                 {
3391                         type = RootContext.LookupType (ec.TypeContainer, RequestedType, false, loc);
3392                         
3393                         if (type == null)
3394                                 return null;
3395                         
3396                         bool IsDelegate = TypeManager.IsDelegateType (type);
3397                         
3398                         if (IsDelegate)
3399                                 return (new NewDelegate (type, Arguments, loc)).Resolve (ec);
3400                         
3401                         bool is_struct = false;
3402                         is_struct = type.IsSubclassOf (TypeManager.value_type);
3403                         eclass = ExprClass.Value;
3404
3405                         //
3406                         // SRE returns a match for .ctor () on structs (the object constructor), 
3407                         // so we have to manually ignore it.
3408                         //
3409                         if (is_struct && Arguments == null)
3410                                 return this;
3411                         
3412                         Expression ml;
3413                         ml = MemberLookup (ec, type, ".ctor", false,
3414                                            MemberTypes.Constructor, AllBindingFlags, loc);
3415                         
3416                         if (! (ml is MethodGroupExpr)){
3417                                 if (!is_struct){
3418                                         report118 (loc, ml, "method group");
3419                                         return null;
3420                                 }
3421                         }
3422                         
3423                         if (ml != null) {
3424                                 if (Arguments != null){
3425                                         for (int i = Arguments.Count; i > 0;){
3426                                                 --i;
3427                                                 Argument a = (Argument) Arguments [i];
3428                                                 
3429                                                 if (!a.Resolve (ec, loc))
3430                                                         return null;
3431                                         }
3432                                 }
3433                                 
3434                                 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml,
3435                                                                      Arguments, loc);
3436                         }
3437                         
3438                         if (method == null && !is_struct) {
3439                                 Error (-6, loc,
3440                                        "New invocation: Can not find a constructor for " +
3441                                        "this argument list");
3442                                 return null;
3443                         }
3444                         return this;
3445                 }
3446
3447                 //
3448                 // This DoEmit can be invoked in two contexts:
3449                 //    * As a mechanism that will leave a value on the stack (new object)
3450                 //    * As one that wont (init struct)
3451                 //
3452                 // You can control whether a value is required on the stack by passing
3453                 // need_value_on_stack.  The code *might* leave a value on the stack
3454                 // so it must be popped manually
3455                 //
3456                 // If we are dealing with a ValueType, we have a few
3457                 // situations to deal with:
3458                 //
3459                 //    * The target is a ValueType, and we have been provided
3460                 //      the instance (this is easy, we are being assigned).
3461                 //
3462                 //    * The target of New is being passed as an argument,
3463                 //      to a boxing operation or a function that takes a
3464                 //      ValueType.
3465                 //
3466                 //      In this case, we need to create a temporary variable
3467                 //      that is the argument of New.
3468                 //
3469                 // Returns whether a value is left on the stack
3470                 //
3471                 bool DoEmit (EmitContext ec, bool need_value_on_stack)
3472                 {
3473                         if (method == null){
3474                                 IMemoryLocation ml;
3475
3476                                 if (value_target == null)
3477                                         value_target = new LocalTemporary (ec, type);
3478                                                 
3479                                 ml = (IMemoryLocation) value_target;
3480                                 ml.AddressOf (ec);
3481                         } else {
3482                                 Invocation.EmitArguments (ec, method, Arguments);
3483                                 ec.ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
3484                                 return true;
3485                         }
3486
3487                         //
3488                         // It must be a value type, sanity check
3489                         //
3490                         if (value_target != null){
3491                                 ec.ig.Emit (OpCodes.Initobj, type);
3492
3493                                 if (need_value_on_stack){
3494                                         value_target.Emit (ec);
3495                                         return true;
3496                                 }
3497                                 return false;
3498                         }
3499
3500                         throw new Exception ("No method and no value type");
3501                 }
3502
3503                 public override void Emit (EmitContext ec)
3504                 {
3505                         DoEmit (ec, true);
3506                 }
3507                 
3508                 public override void EmitStatement (EmitContext ec)
3509                 {
3510                         if (DoEmit (ec, false))
3511                                 ec.ig.Emit (OpCodes.Pop);
3512                 }
3513         }
3514
3515         /// <summary>
3516         ///   Represents an array creation expression.
3517         /// </summary>
3518         ///
3519         /// <remarks>
3520         ///   There are two possible scenarios here: one is an array creation
3521         ///   expression that specifies the dimensions and optionally the
3522         ///   initialization data and the other which does not need dimensions
3523         ///   specified but where initialization data is mandatory.
3524         /// </remarks>
3525         public class ArrayCreation : ExpressionStatement {
3526                 string RequestedType;
3527                 string Rank;
3528                 ArrayList Initializers;
3529                 Location  loc;
3530                 ArrayList Arguments;
3531                 
3532                 MethodBase method = null;
3533                 Type array_element_type;
3534                 bool IsOneDimensional = false;
3535                 bool IsBuiltinType = false;
3536                 bool ExpectInitializers = false;
3537
3538                 int dimensions = 0;
3539                 Type underlying_type;
3540
3541                 ArrayList ArrayData;
3542
3543                 Hashtable Bounds;
3544
3545                 public ArrayCreation (string requested_type, ArrayList exprs,
3546                                       string rank, ArrayList initializers, Location l)
3547                 {
3548                         RequestedType = requested_type;
3549                         Rank          = rank;
3550                         Initializers  = initializers;
3551                         loc = l;
3552
3553                         Arguments = new ArrayList ();
3554
3555                         foreach (Expression e in exprs)
3556                                 Arguments.Add (new Argument (e, Argument.AType.Expression));
3557
3558                 }
3559
3560                 public ArrayCreation (string requested_type, string rank, ArrayList initializers, Location l)
3561                 {
3562                         RequestedType = requested_type;
3563                         Initializers = initializers;
3564                         loc = l;
3565
3566                         Rank = rank.Substring (0, rank.LastIndexOf ("["));
3567
3568                         string tmp = rank.Substring (rank.LastIndexOf ("["));
3569
3570                         dimensions = tmp.Length - 1;
3571                         ExpectInitializers = true;
3572                 }
3573
3574                 public static string FormArrayType (string base_type, int idx_count, string rank)
3575                 {
3576                         StringBuilder sb = new StringBuilder (base_type);
3577
3578                         sb.Append (rank);
3579                         
3580                         sb.Append ("[");
3581                         for (int i = 1; i < idx_count; i++)
3582                                 sb.Append (",");
3583                         sb.Append ("]");
3584                         
3585                         return sb.ToString ();
3586                 }
3587
3588                 public static string FormElementType (string base_type, int idx_count, string rank)
3589                 {
3590                         StringBuilder sb = new StringBuilder (base_type);
3591                         
3592                         sb.Append ("[");
3593                         for (int i = 1; i < idx_count; i++)
3594                                 sb.Append (",");
3595                         sb.Append ("]");
3596
3597                         sb.Append (rank);
3598
3599                         string val = sb.ToString ();
3600
3601                         return val.Substring (0, val.LastIndexOf ("["));
3602                 }
3603
3604                 void error178 ()
3605                 {
3606                         Report.Error (178, loc, "Incorrectly structured array initializer");
3607                 }
3608                 
3609                 public bool CheckIndices (EmitContext ec, ArrayList probe, int idx, bool specified_dims)
3610                 {
3611                         if (specified_dims) { 
3612                                 Argument a = (Argument) Arguments [idx];
3613                                 
3614                                 if (!a.Resolve (ec, loc))
3615                                         return false;
3616                                 
3617                                 if (!(a.Expr is Constant)) {
3618                                         Report.Error (150, loc, "A constant value is expected");
3619                                         return false;
3620                                 }
3621                                 
3622                                 int value = (int) ((Constant) a.Expr).GetValue ();
3623                                 
3624                                 if (value != probe.Count) {
3625                                         error178 ();
3626                                         return false;
3627                                 }
3628                                 
3629                                 Bounds [idx] = value;
3630                         }
3631                         
3632                         foreach (object o in probe) {
3633                                 if (o is ArrayList) {
3634                                         bool ret = CheckIndices (ec, (ArrayList) o, idx + 1, specified_dims);
3635                                         if (!ret)
3636                                                 return false;
3637                                 } else {
3638                                         Expression tmp = (Expression) o;
3639                                         tmp = tmp.Resolve (ec);
3640                                         if (tmp == null)
3641                                                 continue;
3642                                         
3643                                         // Handle initialization from vars, fields etc.
3644
3645                                         Expression conv = ConvertImplicitRequired (
3646                                                 ec, tmp, underlying_type, loc);
3647                                         
3648                                         if (conv == null) 
3649                                                 return false;
3650
3651                                         if (conv is StringConstant)
3652                                                 ArrayData.Add (conv);
3653                                         else if (conv is Constant)
3654                                                 ArrayData.Add (((Constant) conv).GetValue ());
3655                                         else
3656                                                 ArrayData.Add (conv);
3657                                 }
3658                         }
3659
3660                         return true;
3661                 }
3662                 
3663                 public void UpdateIndices (EmitContext ec)
3664                 {
3665                         int i = 0;
3666                         for (ArrayList probe = Initializers; probe != null;) {
3667                                 
3668                                 if (probe [0] is ArrayList) {
3669                                         Expression e = new IntConstant (probe.Count);
3670                                         Arguments.Add (new Argument (e, Argument.AType.Expression));
3671
3672                                         Bounds [i++] =  probe.Count;
3673                                         
3674                                         probe = (ArrayList) probe [0];
3675                                         
3676                                 } else {
3677                                         Expression e = new IntConstant (probe.Count);
3678                                         Arguments.Add (new Argument (e, Argument.AType.Expression));
3679
3680                                         Bounds [i++] = probe.Count;
3681                                         probe = null;
3682                                 }
3683                         }
3684
3685                 }
3686                 
3687                 public bool ValidateInitializers (EmitContext ec)
3688                 {
3689                         if (Initializers == null) {
3690                                 if (ExpectInitializers)
3691                                         return false;
3692                                 else
3693                                         return true;
3694                         }
3695                         
3696                         underlying_type = RootContext.LookupType (
3697                                 ec.TypeContainer, RequestedType, false, loc);
3698                         
3699                         //
3700                         // We use this to store all the date values in the order in which we
3701                         // will need to store them in the byte blob later
3702                         //
3703                         ArrayData = new ArrayList ();
3704                         Bounds = new Hashtable ();
3705                         
3706                         bool ret;
3707
3708                         if (Arguments != null) {
3709                                 ret = CheckIndices (ec, Initializers, 0, true);
3710                                 return ret;
3711                                 
3712                         } else {
3713                                 Arguments = new ArrayList ();
3714
3715                                 ret = CheckIndices (ec, Initializers, 0, false);
3716                                 
3717                                 if (!ret)
3718                                         return false;
3719                                 
3720                                 UpdateIndices (ec);
3721                                 
3722                                 if (Arguments.Count != dimensions) {
3723                                         error178 ();
3724                                         return false;
3725                                 }
3726
3727                                 return ret;
3728                         }
3729                 }
3730                 
3731                 public override Expression DoResolve (EmitContext ec)
3732                 {
3733                         int arg_count;
3734
3735                         if (!ValidateInitializers (ec))
3736                                 return null;
3737
3738                         if (Arguments == null)
3739                                 arg_count = 0;
3740                         else {
3741                                 arg_count = Arguments.Count;
3742                                 for (int i = arg_count; i > 0;){
3743                                         --i;
3744                                         Argument a = (Argument) Arguments [i];
3745                                         
3746                                         if (!a.Resolve (ec, loc))
3747                                                 return null;
3748                                 }
3749                         }
3750                         
3751                         string array_type = FormArrayType (RequestedType, arg_count, Rank);
3752                         string element_type = FormElementType (RequestedType, arg_count, Rank);
3753
3754                         type = RootContext.LookupType (ec.TypeContainer, array_type, false, loc);
3755                         
3756                         array_element_type = RootContext.LookupType (
3757                                 ec.TypeContainer, element_type, false, loc);
3758                         
3759                         if (type == null)
3760                                 return null;
3761                         
3762                         if (arg_count == 1) {
3763                                 IsOneDimensional = true;
3764                                 eclass = ExprClass.Value;
3765                                 return this;
3766                         }
3767
3768                         IsBuiltinType = TypeManager.IsBuiltinType (type);
3769                         
3770                         if (IsBuiltinType) {
3771                                 
3772                                 Expression ml;
3773                                 
3774                                 ml = MemberLookup (ec, type, ".ctor", false, MemberTypes.Constructor,
3775                                                    AllBindingFlags, loc);
3776                                 
3777                                 if (!(ml is MethodGroupExpr)){
3778                                         report118 (loc, ml, "method group");
3779                                         return null;
3780                                 }
3781                                 
3782                                 if (ml == null) {
3783                                         Report.Error (-6, loc, "New invocation: Can not find a constructor for " +
3784                                                       "this argument list");
3785                                         return null;
3786                                 }
3787                                 
3788                                 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml, Arguments, loc);
3789                                 
3790                                 if (method == null) {
3791                                         Report.Error (-6, loc, "New invocation: Can not find a constructor for " +
3792                                                       "this argument list");
3793                                         return null;
3794                                 }
3795                                 
3796                                 eclass = ExprClass.Value;
3797                                 return this;
3798                                 
3799                         } else {
3800                                 ModuleBuilder mb = RootContext.ModuleBuilder;
3801
3802                                 ArrayList args = new ArrayList ();
3803                                 if (Arguments != null){
3804                                         for (int i = arg_count; i > 0;){
3805                                                 --i;
3806                                                 Argument a = (Argument) Arguments [i];
3807                                                 
3808                                                 args.Add (a.Type);
3809                                         }
3810                                 }
3811                                 
3812                                 Type [] arg_types = null;
3813                                 
3814                                 if (args.Count > 0)
3815                                         arg_types = new Type [args.Count];
3816                                 
3817                                 args.CopyTo (arg_types, 0);
3818                                 
3819                                 method = mb.GetArrayMethod (type, ".ctor", CallingConventions.HasThis, null,
3820                                                             arg_types);
3821                                 
3822                                 if (method == null) {
3823                                         Report.Error (-6, loc, "New invocation: Can not find a constructor for " +
3824                                                       "this argument list");
3825                                         return null;
3826                                 }
3827                                 
3828                                 eclass = ExprClass.Value;
3829                                 return this;
3830                                 
3831                         }
3832                 }
3833
3834                 public static byte [] MakeByteBlob (ArrayList ArrayData, Type underlying_type, Location loc)
3835                 {
3836                         int factor;
3837                         byte [] data;
3838
3839                         int count = ArrayData.Count;
3840
3841                         if (underlying_type == TypeManager.int32_type ||
3842                             underlying_type == TypeManager.uint32_type ||
3843                             underlying_type == TypeManager.float_type)
3844                                 factor = 4;
3845                         else if (underlying_type == TypeManager.int64_type ||
3846                                  underlying_type == TypeManager.uint64_type ||
3847                                  underlying_type == TypeManager.double_type)
3848                                 factor = 8;
3849                         else if (underlying_type == TypeManager.byte_type ||
3850                                  underlying_type == TypeManager.sbyte_type ||
3851                                  underlying_type == TypeManager.bool_type)      
3852                                 factor = 1;
3853                         else if (underlying_type == TypeManager.short_type ||
3854                                  underlying_type == TypeManager.char_type ||
3855                                  underlying_type == TypeManager.ushort_type)
3856                                 factor = 2;
3857                         else {
3858                                 Report.Error (-100, loc, "Unhandled type in MakeByteBlob!!");
3859                                 return null;
3860                         }
3861
3862                         data = new byte [count * factor];
3863                         int idx = 0;
3864                         
3865                         for (int i = 0; i < count; ++i) {
3866                                 object v = ArrayData [i];
3867
3868                                 if (v is EnumConstant)
3869                                         v = ((EnumConstant) v).Child;
3870
3871                                 if (underlying_type == TypeManager.int64_type ||
3872                                     underlying_type == TypeManager.uint64_type){
3873                                         long val = 0;
3874                                         if (!(v is Expression))
3875                                                 val = (long) v;
3876
3877                                         for (int j = 0; j < factor; ++j) {
3878                                                 data [idx + j] = (byte) (val & 0xFF);
3879                                                 val = (val >> 8);
3880                                         }
3881                                 } else if (underlying_type == TypeManager.float_type) {
3882 #if __MonoCS__
3883 #else
3884                                         unsafe {
3885                                                 float val = 0;
3886
3887                                                 if (!(v is Expression))
3888                                                         val = (float) v;
3889
3890                                                 byte *ptr = (byte *) &val;
3891                                                 
3892                                                 for (int j = 0; j < factor; ++j)
3893                                                         data [idx + j] = (byte) ptr [j];
3894                                         }
3895 #endif
3896                                 } else if (underlying_type == TypeManager.double_type) {
3897 #if __MonoCS__
3898 #else
3899                                         unsafe {
3900                                                 double val = 0;
3901
3902                                                 if (!(v is Expression))
3903                                                         val = (double) v;
3904
3905                                                 byte *ptr = (byte *) &val;
3906                                                 
3907                                                 for (int j = 0; j < factor; ++j)
3908                                                         data [idx + j] = (byte) ptr [j];
3909                                         }
3910 #endif
3911                                 } else if (underlying_type == TypeManager.char_type){
3912                                         int val = (char) 0;
3913
3914                                         if (!(v is Expression))
3915                                                 v = (int) ((char) v);
3916                                         
3917                                         data [idx] = (byte) (val & 0xff);
3918                                         data [idx+1] = (byte) (val >> 8);
3919
3920                                 } else if (underlying_type == TypeManager.int32_type) {
3921                                         int val = 0;
3922                                         
3923                                         if (!(v is Expression))
3924                                                 val = (int) v;
3925                                         
3926                                         data [idx]   = (byte) (val & 0xff);
3927                                         data [idx+1] = (byte) ((val >> 8) & 0xff);
3928                                         data [idx+2] = (byte) ((val >> 16) & 0xff);
3929                                         data [idx+3] = (byte) (val >> 24);
3930                                 } else
3931                                         throw new Exception ("Unrecognized type in MakeByteBlob");
3932
3933                                 idx += factor;
3934                         }
3935
3936                         return data;
3937                 }
3938
3939                 //
3940                 // Emits the initializers for the array
3941                 //
3942                 void EmitStaticInitializers (EmitContext ec, bool is_expression)
3943                 {
3944                         //
3945                         // First, the static data
3946                         //
3947                         FieldBuilder fb;
3948                         ILGenerator ig = ec.ig;
3949                         
3950                         byte [] data = MakeByteBlob (ArrayData, underlying_type, loc);
3951                         
3952                         if (data != null) {
3953                                 fb = RootContext.MakeStaticData (data);
3954                                 
3955                                 if (is_expression)
3956                                         ig.Emit (OpCodes.Dup);
3957                                 ig.Emit (OpCodes.Ldtoken, fb);
3958                                 ig.Emit (OpCodes.Call,
3959                                          TypeManager.void_initializearray_array_fieldhandle);
3960                         }
3961                 }
3962                 
3963                 //
3964                 // Emits pieces of the array that can not be computed at compile
3965                 // time (variables and string locations).
3966                 //
3967                 // This always expect the top value on the stack to be the array
3968                 //
3969                 void EmitDynamicInitializers (EmitContext ec, bool is_expression)
3970                 {
3971                         ILGenerator ig = ec.ig;
3972                         int dims = Bounds.Count;
3973                         int [] current_pos = new int [dims];
3974                         int top = ArrayData.Count;
3975                         LocalBuilder temp = ig.DeclareLocal (type);
3976
3977                         ig.Emit (OpCodes.Stloc, temp);
3978
3979                         MethodInfo set = null;
3980
3981                         if (dims != 1){
3982                                 Type [] args;
3983                                 ModuleBuilder mb = null;
3984                                 mb = RootContext.ModuleBuilder;
3985                                 args = new Type [dims + 1];
3986
3987                                 int j;
3988                                 for (j = 0; j < dims; j++)
3989                                         args [j] = TypeManager.int32_type;
3990
3991                                 args [j] = array_element_type;
3992                                 
3993                                 set = mb.GetArrayMethod (
3994                                         type, "Set",
3995                                         CallingConventions.HasThis | CallingConventions.Standard,
3996                                         TypeManager.void_type, args);
3997                         }
3998                         
3999                         for (int i = 0; i < top; i++){
4000
4001                                 Expression e = null;
4002
4003                                 if (ArrayData [i] is Expression)
4004                                         e = (Expression) ArrayData [i];
4005
4006                                 if (e != null) {
4007                                         //
4008                                         // Basically we do this for string literals and
4009                                         // other non-literal expressions
4010                                         //
4011                                         if (e is StringConstant || !(e is Constant)) {
4012
4013                                                 ig.Emit (OpCodes.Ldloc, temp);
4014
4015                                                 for (int idx = dims; idx > 0; ) {
4016                                                         idx--;
4017                                                         IntConstant.EmitInt (ig, current_pos [idx]);
4018                                                 }
4019
4020                                                 e.Emit (ec);
4021                                                 
4022                                                 if (dims == 1)
4023                                                         ArrayAccess.EmitStoreOpcode (ig, array_element_type);
4024                                                 else 
4025                                                         ig.Emit (OpCodes.Call, set);
4026                                                 
4027                                         }
4028                                 }
4029                                 
4030                                 //
4031                                 // Advance counter
4032                                 //
4033                                 for (int j = 0; j < dims; j++){
4034                                         current_pos [j]++;
4035                                         if (current_pos [j] < (int) Bounds [j])
4036                                                 break;
4037                                         current_pos [j] = 0;
4038                                 }
4039                         }
4040
4041                         if (is_expression)
4042                                 ig.Emit (OpCodes.Ldloc, temp);
4043                 }
4044
4045                 void DoEmit (EmitContext ec, bool is_statement)
4046                 {
4047                         ILGenerator ig = ec.ig;
4048                         
4049                         if (IsOneDimensional) {
4050                                 Invocation.EmitArguments (ec, null, Arguments);
4051                                 ig.Emit (OpCodes.Newarr, array_element_type);
4052                                 
4053                         } else {
4054                                 Invocation.EmitArguments (ec, null, Arguments);
4055
4056                                 if (IsBuiltinType)
4057                                         ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
4058                                 else
4059                                         ig.Emit (OpCodes.Newobj, (MethodInfo) method);
4060                         }
4061
4062                         if (Initializers != null){
4063                                 //
4064                                 // FIXME: Set this variable correctly.
4065                                 // 
4066                                 bool dynamic_initializers = true;
4067
4068                                 if (underlying_type != TypeManager.string_type &&
4069                                     underlying_type != TypeManager.object_type)
4070                                         EmitStaticInitializers (ec, dynamic_initializers || !is_statement);
4071                                 
4072                                 if (dynamic_initializers)
4073                                         EmitDynamicInitializers (ec, !is_statement);
4074                         }
4075                 }
4076                 
4077                 public override void Emit (EmitContext ec)
4078                 {
4079                         DoEmit (ec, false);
4080                 }
4081
4082                 public override void EmitStatement (EmitContext ec)
4083                 {
4084                         DoEmit (ec, true);
4085                 }
4086                 
4087         }
4088         
4089         /// <summary>
4090         ///   Represents the `this' construct
4091         /// </summary>
4092         public class This : Expression, IAssignMethod, IMemoryLocation {
4093                 Location loc;
4094                 
4095                 public This (Location loc)
4096                 {
4097                         this.loc = loc;
4098                 }
4099
4100                 public override Expression DoResolve (EmitContext ec)
4101                 {
4102                         eclass = ExprClass.Variable;
4103                         type = ec.TypeContainer.TypeBuilder;
4104
4105                         if (ec.IsStatic){
4106                                 Report.Error (26, loc,
4107                                               "Keyword this not valid in static code");
4108                                 return null;
4109                         }
4110                         
4111                         return this;
4112                 }
4113
4114                 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
4115                 {
4116                         DoResolve (ec);
4117                         
4118                         if (ec.TypeContainer is Class){
4119                                 Report.Error (1604, loc, "Cannot assign to `this'");
4120                                 return null;
4121                         }
4122
4123                         return this;
4124                 }
4125
4126                 public override void Emit (EmitContext ec)
4127                 {
4128                         ec.ig.Emit (OpCodes.Ldarg_0);
4129                 }
4130
4131                 public void EmitAssign (EmitContext ec, Expression source)
4132                 {
4133                         source.Emit (ec);
4134                         ec.ig.Emit (OpCodes.Starg, 0);
4135                 }
4136
4137                 public void AddressOf (EmitContext ec)
4138                 {
4139                         ec.ig.Emit (OpCodes.Ldarg_0);
4140
4141                         // FIMXE
4142                         // FIGURE OUT WHY LDARG_S does not work
4143                         //
4144                         // consider: struct X { int val; int P { set { val = value; }}}
4145                         //
4146                         // Yes, this looks very bad. Look at `NOTAS' for
4147                         // an explanation.
4148                         // ec.ig.Emit (OpCodes.Ldarga_S, (byte) 0);
4149                 }
4150         }
4151
4152         /// <summary>
4153         ///   Implements the typeof operator
4154         /// </summary>
4155         public class TypeOf : Expression {
4156                 public readonly string QueriedType;
4157                 Type typearg;
4158                 Location loc;
4159                 
4160                 public TypeOf (string queried_type, Location l)
4161                 {
4162                         QueriedType = queried_type;
4163                         loc = l;
4164                 }
4165
4166                 public override Expression DoResolve (EmitContext ec)
4167                 {
4168                         typearg = RootContext.LookupType (
4169                                 ec.TypeContainer, QueriedType, false, loc);
4170
4171                         if (typearg == null)
4172                                 return null;
4173
4174                         type = TypeManager.type_type;
4175                         eclass = ExprClass.Type;
4176                         return this;
4177                 }
4178
4179                 public override void Emit (EmitContext ec)
4180                 {
4181                         ec.ig.Emit (OpCodes.Ldtoken, typearg);
4182                         ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
4183                 }
4184         }
4185
4186         /// <summary>
4187         ///   Implements the sizeof expression
4188         /// </summary>
4189         public class SizeOf : Expression {
4190                 public readonly string QueriedType;
4191                 
4192                 public SizeOf (string queried_type)
4193                 {
4194                         this.QueriedType = queried_type;
4195                 }
4196
4197                 public override Expression DoResolve (EmitContext ec)
4198                 {
4199                         // FIXME: Implement;
4200                         throw new Exception ("Unimplemented");
4201                         // return this;
4202                 }
4203
4204                 public override void Emit (EmitContext ec)
4205                 {
4206                         throw new Exception ("Implement me");
4207                 }
4208         }
4209
4210         /// <summary>
4211         ///   Implements the member access expression
4212         /// </summary>
4213         public class MemberAccess : Expression {
4214                 public readonly string Identifier;
4215                 Expression expr;
4216                 Expression member_lookup;
4217                 Location loc;
4218                 
4219                 public MemberAccess (Expression expr, string id, Location l)
4220                 {
4221                         this.expr = expr;
4222                         Identifier = id;
4223                         loc = l;
4224                 }
4225
4226                 public Expression Expr {
4227                         get {
4228                                 return expr;
4229                         }
4230                 }
4231
4232                 static void error176 (Location loc, string name)
4233                 {
4234                         Report.Error (176, loc, "Static member `" +
4235                                       name + "' cannot be accessed " +
4236                                       "with an instance reference, qualify with a " +
4237                                       "type name instead");
4238                 }
4239
4240 #if USE_OLD
4241                 public static Expression ResolveMemberAccess (EmitContext ec, Expression member_lookup,
4242                                                               Expression left, Location loc)
4243                 {
4244                         //
4245                         // Method Groups
4246                         //
4247                         if (member_lookup is MethodGroupExpr){
4248                                 MethodGroupExpr mg = (MethodGroupExpr) member_lookup;
4249
4250 #if SHOW_METHOD_GROUPS
4251                                 Console.WriteLine ("Method Groups:");
4252                                 foreach (MethodInfo mi in mg.Methods){
4253                                         Console.WriteLine ("  " + mi.DeclaringType + "/" + mi.Name +
4254                                                            " " + mi.IsStatic);
4255                                 }
4256 #endif
4257                                 
4258                                 //
4259                                 // Type.MethodGroup
4260                                 //
4261                                 if (left is TypeExpr){
4262                                         if (!mg.RemoveInstanceMethods ()){
4263                                                 SimpleName.Error120 (loc, mg.Methods [0].Name); 
4264                                                 return null;
4265                                         }
4266
4267                                         return member_lookup;
4268                                 }
4269
4270                                 //
4271                                 // Instance.MethodGroup
4272                                 //
4273                                 if (!mg.RemoveStaticMethods ()){
4274                                         error176 (loc, mg.Methods [0].Name);
4275                                         return null;
4276                                 }
4277                                 
4278                                 mg.InstanceExpression = left;
4279                                         
4280                                 return member_lookup;
4281                         }
4282
4283                         if (member_lookup is FieldExpr){
4284                                 FieldExpr fe = (FieldExpr) member_lookup;
4285                                 FieldInfo fi = fe.FieldInfo;
4286
4287                                 if (fi is FieldBuilder) {
4288                                         Const c = TypeManager.LookupConstant ((FieldBuilder) fi);
4289                                         
4290                                         if (c != null) {
4291                                                 object o = c.LookupConstantValue (ec);
4292                                                 return Constantify (o, fi.FieldType);
4293                                         }
4294                                 }
4295
4296                                 if (fi.IsLiteral) {
4297                                         Type t = fi.FieldType;
4298                                         Type decl_type = fi.DeclaringType;
4299                                         object o;
4300
4301                                         if (fi is FieldBuilder)
4302                                                 o = TypeManager.GetValue ((FieldBuilder) fi);
4303                                         else
4304                                                 o = fi.GetValue (fi);
4305                                         
4306                                         if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
4307                                                 Expression enum_member = MemberLookup (ec, decl_type, "value__",
4308                                                                                        false, loc); 
4309
4310                                                 Enum en = TypeManager.LookupEnum (decl_type);
4311
4312                                                 Constant c;
4313                                                 if (en != null)
4314                                                         c = Constantify (o, en.UnderlyingType);
4315                                                 else 
4316                                                         c = Constantify (o, enum_member.Type);
4317                                                 
4318                                                 return new EnumConstant (c, decl_type);
4319                                         }
4320                                         
4321                                         Expression exp = Constantify (o, t);
4322
4323                                         if (!(left is TypeExpr)) {
4324                                                 error176 (loc, fe.FieldInfo.Name);
4325                                                 return null;
4326                                         }
4327                                         
4328                                         return exp;
4329                                 }
4330                                 
4331                                 if (left is TypeExpr){
4332                                         if (!fe.FieldInfo.IsStatic){
4333                                                 error176 (loc, fe.FieldInfo.Name);
4334                                                 return null;
4335                                         }
4336                                         return member_lookup;
4337                                 } else {
4338                                         if (fe.FieldInfo.IsStatic){
4339                                                 error176 (loc, fe.FieldInfo.Name);
4340                                                 return null;
4341                                         }
4342                                         fe.InstanceExpression = left;
4343
4344                                         return fe;
4345                                 }
4346                         }
4347
4348                         if (member_lookup is PropertyExpr){
4349                                 PropertyExpr pe = (PropertyExpr) member_lookup;
4350
4351                                 if (left is TypeExpr){
4352                                         if (!pe.IsStatic){
4353                                                 SimpleName.Error120 (loc, pe.PropertyInfo.Name);
4354                                                 return null;
4355                                         }
4356                                         return pe;
4357                                 } else {
4358                                         if (pe.IsStatic){
4359                                                 error176 (loc, pe.PropertyInfo.Name);
4360                                                 return null;
4361                                         }
4362                                         pe.InstanceExpression = left;
4363                                         
4364                                         return pe;
4365                                 }
4366                         }
4367
4368                         if (member_lookup is EventExpr) {
4369
4370                                 EventExpr ee = (EventExpr) member_lookup;
4371                                 
4372                                 //
4373                                 // If the event is local to this class, we transform ourselves into
4374                                 // a FieldExpr
4375                                 //
4376
4377                                 Expression ml = MemberLookup (ec, ec.TypeContainer.TypeBuilder, ee.EventInfo.Name,
4378                                                               true, MemberTypes.Event, AllBindingFlags, loc);
4379
4380                                 if (ml != null) {
4381                                         MemberInfo mi = ec.TypeContainer.GetFieldFromEvent ((EventExpr) ml);
4382
4383                                         ml = ExprClassFromMemberInfo (ec, mi, loc);
4384                                         
4385                                         if (ml == null) {
4386                                                 Report.Error (-200, loc, "Internal error!!");
4387                                                 return null;
4388                                         }
4389
4390                                         return ResolveMemberAccess (ec, ml, left, loc);
4391                                 }
4392
4393                                 if (left is TypeExpr) {
4394                                         if (!ee.IsStatic) {
4395                                                 SimpleName.Error120 (loc, ee.EventInfo.Name);
4396                                                 return null;
4397                                         }
4398
4399                                         return ee;
4400
4401                                 } else {
4402                                         if (ee.IsStatic) {
4403                                                 error176 (loc, ee.EventInfo.Name);
4404                                                 return null;
4405                                         }
4406
4407                                         ee.InstanceExpression = left;
4408
4409                                         return ee;
4410                                 }
4411                         }
4412
4413                         if (member_lookup is TypeExpr){
4414                                 member_lookup.Resolve (ec);
4415                                 return member_lookup;
4416                         }
4417                         
4418                         Console.WriteLine ("Left is: " + left);
4419                         Report.Error (-100, loc, "Support for [" + member_lookup + "] is not present yet");
4420                         Environment.Exit (0);
4421                         return null;
4422                 }
4423                 
4424                 public override Expression DoResolve (EmitContext ec)
4425                 {
4426                         //
4427                         // We are the sole users of ResolveWithSimpleName (ie, the only
4428                         // ones that can cope with it
4429                         //
4430                         expr = expr.ResolveWithSimpleName (ec);
4431
4432                         if (expr == null)
4433                                 return null;
4434
4435                         if (expr is SimpleName){
4436                                 SimpleName child_expr = (SimpleName) expr;
4437                                 
4438                                 expr = new SimpleName (child_expr.Name + "." + Identifier, loc);
4439
4440                                 return expr.ResolveWithSimpleName (ec);
4441                         }
4442                                         
4443                         //
4444                         // Handle enums here when they are in transit.
4445                         // Note that we cannot afford to hit MemberLookup in this case because
4446                         // it will fail to find any members at all
4447                         //
4448
4449                         Type expr_type = expr.Type;
4450                         if (expr_type.IsSubclassOf (TypeManager.enum_type)) {
4451                                 
4452                                 Enum en = TypeManager.LookupEnum (expr_type);
4453                                 
4454                                 if (en != null) {
4455                                         object value = en.LookupEnumValue (ec, Identifier, loc);
4456
4457                                         if (value == null)
4458                                                 return null;
4459                                         
4460                                         Constant c = Constantify (value, en.UnderlyingType);
4461                                         return new EnumConstant (c, expr_type);
4462                                 }
4463                         }
4464
4465                         member_lookup = MemberLookup (ec, expr.Type, Identifier, false, loc);
4466
4467                         if (member_lookup == null)
4468                                 return null;
4469
4470                         return ResolveMemberAccess (ec, member_lookup, expr, loc);
4471                 }
4472
4473 #else
4474
4475                 //
4476                 // This code is more conformant to the spec (it follows it step by step),
4477                 // but it has not been tested yet, and there is nothing here that is not
4478                 // caught by the above code.  But it might be a better foundation to improve
4479                 // on in the future
4480                 //
4481                 public ResolveTypeMemberAccess (EmitContext ec, Expression member_lookup,
4482                                                 Expression left, Location loc)
4483                 {
4484                         if (member_lookup is TypeExpr){
4485                                 member_lookup.Resolve (ec);
4486                                 return member_lookup;
4487                         }
4488                         
4489                         if (member_lookup is MethodGroupExpr){
4490                                 if (!mg.RemoveStaticMethods ()){
4491                                         SimpleName.Error120 (loc, mg.Methods [0].Name); 
4492                                         return null;
4493                                 }
4494                                 
4495                                 return member_lookup;
4496                         }
4497                         
4498                         if (member_lookup is PropertyExpr){
4499                                 PropertyExpr pe = (PropertyExpr) member_lookup;
4500                                         
4501                                         if (!pe.IsStatic){
4502                                                 SimpleName.Error120 (loc, pe.PropertyInfo.Name);
4503                                                 return null;
4504                                         }
4505                                         return pe;
4506                         }
4507                         
4508                         if (member_lookup is FieldExpr){
4509                                 FieldExpr fe = (FieldExpr) member_lookup;
4510                                 FieldInfo fi = fe.FieldInfo;
4511                                 
4512                                 if (fi is FieldBuilder) {
4513                                         Const c = TypeManager.LookupConstant ((FieldBuilder) fi);
4514                                         
4515                                         if (c != null) {
4516                                                 object o = c.LookupConstantValue (ec);
4517                                                 return Constantify (o, fi.FieldType);
4518                                         }
4519                                 }
4520                                 
4521                                 if (fi.IsLiteral) {
4522                                         Type t = fi.FieldType;
4523                                         Type decl_type = fi.DeclaringType;
4524                                         object o;
4525                                         
4526                                         if (fi is FieldBuilder)
4527                                                 o = TypeManager.GetValue ((FieldBuilder) fi);
4528                                         else
4529                                                 o = fi.GetValue (fi);
4530                                         
4531                                         if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
4532                                                 Expression enum_member = MemberLookup (
4533                                                         ec, decl_type, "value__",
4534                                                         false, loc); 
4535                                                 
4536                                                 Enum en = TypeManager.LookupEnum (decl_type);
4537                                                 
4538                                                 Constant c;
4539                                                 if (en != null)
4540                                                         c = Constantify (o, en.UnderlyingType);
4541                                                 else 
4542                                                         c = Constantify (o, enum_member.Type);
4543                                                 
4544                                                 return new EnumConstant (c, decl_type);
4545                                         }
4546                                         
4547                                         Expression exp = Constantify (o, t);
4548                                         
4549                                         return exp;
4550                                 }
4551
4552                                 if (!fe.FieldInfo.IsStatic){
4553                                         error176 (loc, fe.FieldInfo.Name);
4554                                         return null;
4555                                 }
4556                                 return member_lookup;
4557                         }
4558
4559                         if (member_lookup is EventExpr){
4560
4561                                 EventExpr ee = (EventExpr) member_lookup;
4562                                 
4563                                 //
4564                                 // If the event is local to this class, we transform ourselves into
4565                                 // a FieldExpr
4566                                 //
4567
4568                                 Expression ml = MemberLookup (
4569                                         ec, ec.TypeContainer.TypeBuilder, ee.EventInfo.Name,
4570                                         true, MemberTypes.Event, AllBindingFlags, loc);
4571
4572                                 if (ml != null) {
4573                                         MemberInfo mi = ec.TypeContainer.GetFieldFromEvent ((EventExpr) ml);
4574
4575                                         ml = ExprClassFromMemberInfo (ec, mi, loc);
4576                                         
4577                                         if (ml == null) {
4578                                                 Report.Error (-200, loc, "Internal error!!");
4579                                                 return null;
4580                                         }
4581
4582                                         return ResolveMemberAccess (ec, ml, left, loc);
4583                                 }
4584
4585                                 if (!ee.IsStatic) {
4586                                         SimpleName.Error120 (loc, ee.EventInfo.Name);
4587                                         return null;
4588                                 }
4589                                 
4590                                 return ee;
4591                         }
4592
4593                         Console.WriteLine ("Left is: " + left);
4594                         Report.Error (-100, loc, "Support for [" + member_lookup + "] is not present yet");
4595                         Environment.Exit (0);
4596
4597                         return null;
4598                 }
4599                 
4600                 public ResolveInstanceMemberAccess (EmitContext ec, Expression member_lookup,
4601                                                     Expression left, Location loc)
4602                 {
4603                         if (member_lookup is MethodGroupExpr){
4604                                 //
4605                                 // Instance.MethodGroup
4606                                 //
4607                                 if (!mg.RemoveStaticMethods ()){
4608                                         error176 (loc, mg.Methods [0].Name);
4609                                         return null;
4610                                 }
4611                                 
4612                                 mg.InstanceExpression = left;
4613                                         
4614                                 return member_lookup;
4615                         }
4616
4617                         if (member_lookup is PropertyExpr){
4618                                 PropertyExpr pe = (PropertyExpr) member_lookup;
4619
4620                                 if (pe.IsStatic){
4621                                         error176 (loc, pe.PropertyInfo.Name);
4622                                         return null;
4623                                 }
4624                                 pe.InstanceExpression = left;
4625                                 
4626                                 return pe;
4627                         }
4628
4629                         Type left_type = left.type;
4630
4631                         if (left_type.IsValueType){
4632                         } else {
4633                                 
4634                         }
4635                 }
4636                 
4637                 public override Expression DoResolve (EmitContext ec)
4638                 {
4639                         //
4640                         // We are the sole users of ResolveWithSimpleName (ie, the only
4641                         // ones that can cope with it
4642                         //
4643                         expr = expr.ResolveWithSimpleName (ec);
4644
4645                         if (expr == null)
4646                                 return null;
4647
4648                         if (expr is SimpleName){
4649                                 SimpleName child_expr = (SimpleName) expr;
4650                                 
4651                                 expr = new SimpleName (child_expr.Name + "." + Identifier, loc);
4652
4653                                 return expr.ResolveWithSimpleName (ec);
4654                         }
4655
4656                         //
4657                         // Handle enums here when they are in transit.
4658                         // Note that we cannot afford to hit MemberLookup in this case because
4659                         // it will fail to find any members at all (Why?)
4660                         //
4661
4662                         Type expr_type = expr.Type;
4663                         if (expr_type.IsSubclassOf (TypeManager.enum_type)) {
4664                                 
4665                                 Enum en = TypeManager.LookupEnum (expr_type);
4666                                 
4667                                 if (en != null) {
4668                                         object value = en.LookupEnumValue (ec, Identifier, loc);
4669
4670                                         if (value == null)
4671                                                 return null;
4672                                         
4673                                         Constant c = Constantify (value, en.UnderlyingType);
4674                                         return new EnumConstant (c, expr_type);
4675                                 }
4676                         }
4677
4678                         member_lookup = MemberLookup (ec, expr.Type, Identifier, false, loc);
4679
4680                         if (member_lookup == null)
4681                                 return null;
4682
4683                         if (expr is TypeExpr)
4684                                 return ResolveTypeMemberAccess (ec, member_lookup, expr, loc);
4685                         else
4686                                 return ResolveInstanceMemberAccess (ec, member_lookup, expr, loc);
4687                 }
4688 #endif
4689                 public override void Emit (EmitContext ec)
4690                 {
4691                         throw new Exception ("Should not happen I think");
4692                 }
4693         }
4694
4695         /// <summary>
4696         ///   Implements checked expressions
4697         /// </summary>
4698         public class CheckedExpr : Expression {
4699
4700                 public Expression Expr;
4701
4702                 public CheckedExpr (Expression e)
4703                 {
4704                         Expr = e;
4705                 }
4706
4707                 public override Expression DoResolve (EmitContext ec)
4708                 {
4709                         Expr = Expr.Resolve (ec);
4710
4711                         if (Expr == null)
4712                                 return null;
4713
4714                         eclass = Expr.eclass;
4715                         type = Expr.Type;
4716                         return this;
4717                 }
4718
4719                 public override void Emit (EmitContext ec)
4720                 {
4721                         bool last_check = ec.CheckState;
4722                         
4723                         ec.CheckState = true;
4724                         Expr.Emit (ec);
4725                         ec.CheckState = last_check;
4726                 }
4727                 
4728         }
4729
4730         /// <summary>
4731         ///   Implements the unchecked expression
4732         /// </summary>
4733         public class UnCheckedExpr : Expression {
4734
4735                 public Expression Expr;
4736
4737                 public UnCheckedExpr (Expression e)
4738                 {
4739                         Expr = e;
4740                 }
4741
4742                 public override Expression DoResolve (EmitContext ec)
4743                 {
4744                         Expr = Expr.Resolve (ec);
4745
4746                         if (Expr == null)
4747                                 return null;
4748
4749                         eclass = Expr.eclass;
4750                         type = Expr.Type;
4751                         return this;
4752                 }
4753
4754                 public override void Emit (EmitContext ec)
4755                 {
4756                         bool last_check = ec.CheckState;
4757                         
4758                         ec.CheckState = false;
4759                         Expr.Emit (ec);
4760                         ec.CheckState = last_check;
4761                 }
4762                 
4763         }
4764
4765         /// <summary>
4766         ///   An Element Access expression.
4767         ///
4768         ///   During semantic analysis these are transformed into 
4769         ///   IndexerAccess or ArrayAccess 
4770         /// </summary>
4771         public class ElementAccess : Expression {
4772                 public ArrayList  Arguments;
4773                 public Expression Expr;
4774                 public Location   loc;
4775                 
4776                 public ElementAccess (Expression e, ArrayList e_list, Location l)
4777                 {
4778                         Expr = e;
4779
4780                         loc  = l;
4781                         
4782                         if (e_list == null)
4783                                 return;
4784                         
4785                         Arguments = new ArrayList ();
4786                         foreach (Expression tmp in e_list)
4787                                 Arguments.Add (new Argument (tmp, Argument.AType.Expression));
4788                         
4789                 }
4790
4791                 bool CommonResolve (EmitContext ec)
4792                 {
4793                         Expr = Expr.Resolve (ec);
4794
4795                         if (Expr == null) 
4796                                 return false;
4797
4798                         if (Arguments == null)
4799                                 return false;
4800
4801                         for (int i = Arguments.Count; i > 0;){
4802                                 --i;
4803                                 Argument a = (Argument) Arguments [i];
4804                                 
4805                                 if (!a.Resolve (ec, loc))
4806                                         return false;
4807                         }
4808
4809                         return true;
4810                 }
4811                                 
4812                 public override Expression DoResolve (EmitContext ec)
4813                 {
4814                         if (!CommonResolve (ec))
4815                                 return null;
4816
4817                         //
4818                         // We perform some simple tests, and then to "split" the emit and store
4819                         // code we create an instance of a different class, and return that.
4820                         //
4821                         // I am experimenting with this pattern.
4822                         //
4823                         if (Expr.Type.IsSubclassOf (TypeManager.array_type))
4824                                 return (new ArrayAccess (this)).Resolve (ec);
4825                         else
4826                                 return (new IndexerAccess (this)).Resolve (ec);
4827                 }
4828
4829                 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
4830                 {
4831                         if (!CommonResolve (ec))
4832                                 return null;
4833
4834                         if (Expr.Type.IsSubclassOf (TypeManager.array_type))
4835                                 return (new ArrayAccess (this)).ResolveLValue (ec, right_side);
4836                         else
4837                                 return (new IndexerAccess (this)).ResolveLValue (ec, right_side);
4838                 }
4839                 
4840                 public override void Emit (EmitContext ec)
4841                 {
4842                         throw new Exception ("Should never be reached");
4843                 }
4844         }
4845
4846         /// <summary>
4847         ///   Implements array access 
4848         /// </summary>
4849         public class ArrayAccess : Expression, IAssignMethod, IMemoryLocation {
4850                 //
4851                 // Points to our "data" repository
4852                 //
4853                 ElementAccess ea;
4854                 
4855                 public ArrayAccess (ElementAccess ea_data)
4856                 {
4857                         ea = ea_data;
4858                         eclass = ExprClass.Variable;
4859                 }
4860
4861                 public override Expression DoResolve (EmitContext ec)
4862                 {
4863                         if (ea.Expr.eclass != ExprClass.Variable) {
4864                                 report118 (ea.loc, ea.Expr, "variable");
4865                                 return null;
4866                         }
4867
4868                         Type t = ea.Expr.Type;
4869
4870                         if (t.GetArrayRank () != ea.Arguments.Count){
4871                                 Report.Error (22, ea.loc,
4872                                               "Incorrect number of indexes for array " +
4873                                               " expected: " + t.GetArrayRank () + " got: " +
4874                                               ea.Arguments.Count);
4875                                 return null;
4876                         }
4877                         type = t.GetElementType ();
4878                         eclass = ExprClass.Variable;
4879
4880                         return this;
4881                 }
4882
4883                 /// <summary>
4884                 ///    Emits the right opcode to load an object of Type `t'
4885                 ///    from an array of T
4886                 /// </summary>
4887                 static public void EmitLoadOpcode (ILGenerator ig, Type type)
4888                 {
4889                         if (type == TypeManager.byte_type)
4890                                 ig.Emit (OpCodes.Ldelem_I1);
4891                         else if (type == TypeManager.sbyte_type)
4892                                 ig.Emit (OpCodes.Ldelem_U1);
4893                         else if (type == TypeManager.short_type)
4894                                 ig.Emit (OpCodes.Ldelem_I2);
4895                         else if (type == TypeManager.ushort_type)
4896                                 ig.Emit (OpCodes.Ldelem_U2);
4897                         else if (type == TypeManager.int32_type)
4898                                 ig.Emit (OpCodes.Ldelem_I4);
4899                         else if (type == TypeManager.uint32_type)
4900                                 ig.Emit (OpCodes.Ldelem_U4);
4901                         else if (type == TypeManager.uint64_type)
4902                                 ig.Emit (OpCodes.Ldelem_I8);
4903                         else if (type == TypeManager.int64_type)
4904                                 ig.Emit (OpCodes.Ldelem_I8);
4905                         else if (type == TypeManager.float_type)
4906                                 ig.Emit (OpCodes.Ldelem_R4);
4907                         else if (type == TypeManager.double_type)
4908                                 ig.Emit (OpCodes.Ldelem_R8);
4909                         else if (type == TypeManager.intptr_type)
4910                                 ig.Emit (OpCodes.Ldelem_I);
4911                         else if (type.IsValueType)
4912                                 ig.Emit (OpCodes.Ldelema, type);
4913                         else 
4914                                 ig.Emit (OpCodes.Ldelem_Ref);
4915                 }
4916
4917                 /// <summary>
4918                 ///    Emits the right opcode to store an object of Type `t'
4919                 ///    from an array of T.  
4920                 /// </summary>
4921                 static public void EmitStoreOpcode (ILGenerator ig, Type t)
4922                 {
4923                         if (t == TypeManager.byte_type || t == TypeManager.sbyte_type)
4924                                 ig.Emit (OpCodes.Stelem_I1);
4925                         else if (t == TypeManager.short_type || t == TypeManager.ushort_type)
4926                                 ig.Emit (OpCodes.Stelem_I2);
4927                         else if (t == TypeManager.int32_type || t == TypeManager.uint32_type)
4928                                 ig.Emit (OpCodes.Stelem_I4);
4929                         else if (t == TypeManager.int64_type || t == TypeManager.uint64_type)
4930                                 ig.Emit (OpCodes.Stelem_I8);
4931                         else if (t == TypeManager.float_type)
4932                                 ig.Emit (OpCodes.Stelem_R4);
4933                         else if (t == TypeManager.double_type)
4934                                 ig.Emit (OpCodes.Stelem_R8);
4935                         else if (t == TypeManager.intptr_type)
4936                                 ig.Emit (OpCodes.Stelem_I);
4937                         else
4938                                 ig.Emit (OpCodes.Stelem_Ref);
4939                 }
4940
4941                 MethodInfo FetchGetMethod ()
4942                 {
4943                         ModuleBuilder mb = RootContext.ModuleBuilder;
4944                         Type [] args = new Type [ea.Arguments.Count];
4945                         MethodInfo get;
4946                         
4947                         int i = 0;
4948                                 
4949                         foreach (Argument a in ea.Arguments)
4950                                 args [i++] = a.Type;
4951                         
4952                         get = mb.GetArrayMethod (
4953                                 ea.Expr.Type, "Get",
4954                                 CallingConventions.HasThis |
4955                                 CallingConventions.Standard,
4956                                 type, args);
4957                         return get;
4958                 }
4959                                 
4960
4961                 MethodInfo FetchAddressMethod ()
4962                 {
4963                         ModuleBuilder mb = RootContext.ModuleBuilder;
4964                         Type [] args = new Type [ea.Arguments.Count];
4965                         MethodInfo address;
4966                         string ptr_type_name;
4967                         Type ret_type;
4968                         int i = 0;
4969                         
4970                         ptr_type_name = type.FullName + "&";
4971                         ret_type = Type.GetType (ptr_type_name);
4972                         
4973                         //
4974                         // It is a type defined by the source code we are compiling
4975                         //
4976                         if (ret_type == null){
4977                                 ret_type = mb.GetType (ptr_type_name);
4978                         }
4979                         
4980                         foreach (Argument a in ea.Arguments)
4981                                 args [i++] = a.Type;
4982                         
4983                         address = mb.GetArrayMethod (
4984                                 ea.Expr.Type, "Address",
4985                                 CallingConventions.HasThis |
4986                                 CallingConventions.Standard,
4987                                 ret_type, args);
4988
4989                         return address;
4990                 }
4991                 
4992                 public override void Emit (EmitContext ec)
4993                 {
4994                         int rank = ea.Expr.Type.GetArrayRank ();
4995                         ILGenerator ig = ec.ig;
4996
4997                         ea.Expr.Emit (ec);
4998
4999                         foreach (Argument a in ea.Arguments)
5000                                 a.Expr.Emit (ec);
5001
5002                         if (rank == 1)
5003                                 EmitLoadOpcode (ig, type);
5004                         else {
5005                                 MethodInfo method;
5006                                 
5007                                 method = FetchGetMethod ();
5008                                 ig.Emit (OpCodes.Call, method);
5009                         }
5010                 }
5011
5012                 public void EmitAssign (EmitContext ec, Expression source)
5013                 {
5014                         int rank = ea.Expr.Type.GetArrayRank ();
5015                         ILGenerator ig = ec.ig;
5016
5017                         ea.Expr.Emit (ec);
5018
5019                         foreach (Argument a in ea.Arguments)
5020                                 a.Expr.Emit (ec);
5021
5022                         source.Emit (ec);
5023
5024                         Type t = source.Type;
5025
5026                         if (rank == 1)
5027                                 EmitStoreOpcode (ig, t);
5028                         else {
5029                                 ModuleBuilder mb = RootContext.ModuleBuilder;
5030                                 Type [] args = new Type [ea.Arguments.Count + 1];
5031                                 MethodInfo set;
5032                                 
5033                                 int i = 0;
5034                                 
5035                                 foreach (Argument a in ea.Arguments)
5036                                         args [i++] = a.Type;
5037
5038                                 args [i] = type;
5039                                 
5040                                 set = mb.GetArrayMethod (
5041                                         ea.Expr.Type, "Set",
5042                                         CallingConventions.HasThis |
5043                                         CallingConventions.Standard,
5044                                         TypeManager.void_type, args);
5045                                 
5046                                 ig.Emit (OpCodes.Call, set);
5047                         }
5048                 }
5049
5050                 public void AddressOf (EmitContext ec)
5051                 {
5052                         int rank = ea.Expr.Type.GetArrayRank ();
5053                         ILGenerator ig = ec.ig;
5054                         
5055                         ea.Expr.Emit (ec);
5056
5057                         foreach (Argument a in ea.Arguments)
5058                                 a.Expr.Emit (ec);
5059
5060                         if (rank == 1){
5061                                 ig.Emit (OpCodes.Ldelema, type);
5062                         } else {
5063                                 MethodInfo address = FetchAddressMethod ();
5064                                 ig.Emit (OpCodes.Call, address);
5065                         }
5066                 }
5067         }
5068
5069         
5070         class Indexers {
5071                 public ArrayList getters, setters;
5072                 static Hashtable map;
5073
5074                 static Indexers ()
5075                 {
5076                         map = new Hashtable ();
5077                 }
5078
5079                 Indexers (MemberInfo [] mi)
5080                 {
5081                         foreach (PropertyInfo property in mi){
5082                                 MethodInfo get, set;
5083                                 
5084                                 get = property.GetGetMethod (true);
5085                                 if (get != null){
5086                                         if (getters == null)
5087                                                 getters = new ArrayList ();
5088
5089                                         getters.Add (get);
5090                                 }
5091                                 
5092                                 set = property.GetSetMethod (true);
5093                                 if (set != null){
5094                                         if (setters == null)
5095                                                 setters = new ArrayList ();
5096                                         setters.Add (set);
5097                                 }
5098                         }
5099                 }
5100                 
5101                 static public Indexers GetIndexersForType (Type t, TypeManager tm, Location loc) 
5102                 {
5103                         Indexers ix = (Indexers) map [t];
5104                         string p_name = TypeManager.IndexerPropertyName (t);
5105                         
5106                         if (ix != null)
5107                                 return ix;
5108
5109                         MemberInfo [] mi = tm.FindMembers (
5110                                 t, MemberTypes.Property,
5111                                 BindingFlags.Public | BindingFlags.Instance,
5112                                 Type.FilterName, p_name);
5113
5114                         if (mi == null || mi.Length == 0){
5115                                 Report.Error (21, loc,
5116                                               "Type `" + TypeManager.CSharpName (t) + "' does not have " +
5117                                               "any indexers defined");
5118                                 return null;
5119                         }
5120                         
5121                         ix = new Indexers (mi);
5122                         map [t] = ix;
5123
5124                         return ix;
5125                 }
5126         }
5127
5128         /// <summary>
5129         ///   Expressions that represent an indexer call.
5130         /// </summary>
5131         public class IndexerAccess : Expression, IAssignMethod {
5132                 //
5133                 // Points to our "data" repository
5134                 //
5135                 ElementAccess ea;
5136                 MethodInfo get, set;
5137                 Indexers ilist;
5138                 ArrayList set_arguments;
5139                 
5140                 public IndexerAccess (ElementAccess ea_data)
5141                 {
5142                         ea = ea_data;
5143                         eclass = ExprClass.Value;
5144                 }
5145
5146                 public override Expression DoResolve (EmitContext ec)
5147                 {
5148                         Type indexer_type = ea.Expr.Type;
5149                         
5150                         //
5151                         // Step 1: Query for all `Item' *properties*.  Notice
5152                         // that the actual methods are pointed from here.
5153                         //
5154                         // This is a group of properties, piles of them.  
5155
5156                         if (ilist == null)
5157                                 ilist = Indexers.GetIndexersForType (
5158                                         indexer_type, RootContext.TypeManager, ea.loc);
5159
5160
5161                         //
5162                         // Step 2: find the proper match
5163                         //
5164                         if (ilist != null && ilist.getters != null && ilist.getters.Count > 0)
5165                                 get = (MethodInfo) Invocation.OverloadResolve (
5166                                         ec, new MethodGroupExpr (ilist.getters), ea.Arguments, ea.loc);
5167
5168                         if (get == null){
5169                                 Report.Error (154, ea.loc,
5170                                               "indexer can not be used in this context, because " +
5171                                               "it lacks a `get' accessor");
5172                                 return null;
5173                         }
5174
5175                         type = get.ReturnType;
5176                         eclass = ExprClass.IndexerAccess;
5177                         return this;
5178                 }
5179
5180                 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
5181                 {
5182                         Type indexer_type = ea.Expr.Type;
5183                         Type right_type = right_side.Type;
5184
5185                         if (ilist == null)
5186                                 ilist = Indexers.GetIndexersForType (
5187                                         indexer_type, RootContext.TypeManager, ea.loc);
5188
5189                         if (ilist != null && ilist.setters != null && ilist.setters.Count > 0){
5190                                 set_arguments = (ArrayList) ea.Arguments.Clone ();
5191                                 set_arguments.Add (new Argument (right_side, Argument.AType.Expression));
5192
5193                                 set = (MethodInfo) Invocation.OverloadResolve (
5194                                         ec, new MethodGroupExpr (ilist.setters), set_arguments, ea.loc);
5195                         }
5196                         
5197                         if (set == null){
5198                                 Report.Error (200, ea.loc,
5199                                               "indexer X.this [" + TypeManager.CSharpName (right_type) +
5200                                               "] lacks a `set' accessor");
5201                                         return null;
5202                         }
5203
5204                         type = TypeManager.void_type;
5205                         eclass = ExprClass.IndexerAccess;
5206                         return this;
5207                 }
5208                 
5209                 public override void Emit (EmitContext ec)
5210                 {
5211                         Invocation.EmitCall (ec, false, ea.Expr, get, ea.Arguments);
5212                 }
5213
5214                 //
5215                 // source is ignored, because we already have a copy of it from the
5216                 // LValue resolution and we have already constructed a pre-cached
5217                 // version of the arguments (ea.set_arguments);
5218                 //
5219                 public void EmitAssign (EmitContext ec, Expression source)
5220                 {
5221                         Invocation.EmitCall (ec, false, ea.Expr, set, set_arguments);
5222                 }
5223         }
5224
5225         /// <summary>
5226         ///   The base operator for method names
5227         /// </summary>
5228         public class BaseAccess : Expression {
5229                 string member;
5230                 Location loc;
5231                 
5232                 public BaseAccess (string member, Location l)
5233                 {
5234                         this.member = member;
5235                         loc = l;
5236                 }
5237
5238                 public override Expression DoResolve (EmitContext ec)
5239                 {
5240                         Expression member_lookup;
5241                         Type current_type = ec.TypeContainer.TypeBuilder;
5242                         Type base_type = current_type.BaseType;
5243                         
5244                         member_lookup = MemberLookup (ec, base_type, member, false, loc);
5245                         if (member_lookup == null)
5246                                 return null;
5247
5248                         Expression left;
5249                         
5250                         if (ec.IsStatic)
5251                                 left = new TypeExpr (base_type);
5252                         else
5253                                 left = new This (loc).Resolve (ec);
5254                         
5255                         return MemberAccess.ResolveMemberAccess (ec, member_lookup, left, loc);
5256                 }
5257
5258                 public override void Emit (EmitContext ec)
5259                 {
5260                         throw new Exception ("Should never be called"); 
5261                 }
5262         }
5263
5264         /// <summary>
5265         ///   The base indexer operator
5266         /// </summary>
5267         public class BaseIndexerAccess : Expression {
5268                 ArrayList Arguments;
5269
5270                 public BaseIndexerAccess (ArrayList args)
5271                 {
5272                         Arguments = args;
5273                 }
5274
5275                 public override Expression DoResolve (EmitContext ec)
5276                 {
5277                         // FIXME: Implement;
5278                         throw new Exception ("Unimplemented");
5279                         // return this;
5280                 }
5281
5282                 public override void Emit (EmitContext ec)
5283                 {
5284                         throw new Exception ("Unimplemented");
5285                 }
5286         }
5287         
5288         /// <summary>
5289         ///   This class exists solely to pass the Type around and to be a dummy
5290         ///   that can be passed to the conversion functions (this is used by
5291         ///   foreach implementation to typecast the object return value from
5292         ///   get_Current into the proper type.  All code has been generated and
5293         ///   we only care about the side effect conversions to be performed
5294         /// </summary>
5295         public class EmptyExpression : Expression {
5296                 public EmptyExpression ()
5297                 {
5298                         type = TypeManager.object_type;
5299                         eclass = ExprClass.Value;
5300                 }
5301
5302                 public EmptyExpression (Type t)
5303                 {
5304                         type = t;
5305                         eclass = ExprClass.Value;
5306                 }
5307                 
5308                 public override Expression DoResolve (EmitContext ec)
5309                 {
5310                         return this;
5311                 }
5312
5313                 public override void Emit (EmitContext ec)
5314                 {
5315                         // nothing, as we only exist to not do anything.
5316                 }
5317
5318                 //
5319                 // This is just because we might want to reuse this bad boy
5320                 // instead of creating gazillions of EmptyExpressions.
5321                 // (CanConvertImplicit uses it)
5322                 //
5323                 public void SetType (Type t)
5324                 {
5325                         type = t;
5326                 }
5327         }
5328
5329         public class UserCast : Expression {
5330                 MethodBase method;
5331                 Expression source;
5332                 
5333                 public UserCast (MethodInfo method, Expression source)
5334                 {
5335                         this.method = method;
5336                         this.source = source;
5337                         type = method.ReturnType;
5338                         eclass = ExprClass.Value;
5339                 }
5340
5341                 public override Expression DoResolve (EmitContext ec)
5342                 {
5343                         //
5344                         // We are born fully resolved
5345                         //
5346                         return this;
5347                 }
5348
5349                 public override void Emit (EmitContext ec)
5350                 {
5351                         ILGenerator ig = ec.ig;
5352
5353                         source.Emit (ec);
5354                         
5355                         if (method is MethodInfo)
5356                                 ig.Emit (OpCodes.Call, (MethodInfo) method);
5357                         else
5358                                 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
5359
5360                 }
5361
5362         }
5363
5364         // <summary>
5365         //   This class is used to "construct" the type during a typecast
5366         //   operation.  Since the Type.GetType class in .NET can parse
5367         //   the type specification, we just use this to construct the type
5368         //   one bit at a time.
5369         // </summary>
5370         public class ComposedCast : Expression {
5371                 Expression left;
5372                 string dim;
5373                 Location loc;
5374                 
5375                 public ComposedCast (Expression left, string dim, Location l)
5376                 {
5377                         this.left = left;
5378                         this.dim = dim;
5379                         loc = l;
5380                 }
5381
5382                 public override Expression DoResolve (EmitContext ec)
5383                 {
5384                         left = left.Resolve (ec);
5385                         if (left == null)
5386                                 return null;
5387
5388                         if (left.eclass != ExprClass.Type){
5389                                 report118 (loc, left, "type");
5390                                 return null;
5391                         }
5392                         
5393                         type = RootContext.LookupType (
5394                                 ec.TypeContainer, left.Type.FullName + dim, false, loc);
5395                         if (type == null)
5396                                 return null;
5397
5398                         eclass = ExprClass.Type;
5399                         return this;
5400                 }
5401
5402                 public override void Emit (EmitContext ec)
5403                 {
5404                         throw new Exception ("This should never be called");
5405                 }
5406         }
5407 }