2006-07-29 Marek Safar <marek.safar@seznam.cz>
[mono.git] / mcs / gmcs / ecore.cs
1 //
2 // ecore.cs: Core of the Expression representation for the intermediate tree.
3 //
4 // Author:
5 //   Miguel de Icaza (miguel@ximian.com)
6 //   Marek Safar (marek.safar@seznam.cz)
7 //
8 // (C) 2001, 2002, 2003 Ximian, Inc.
9 //
10 //
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         /// <remarks>
21         ///   The ExprClass class contains the is used to pass the 
22         ///   classification of an expression (value, variable, namespace,
23         ///   type, method group, property access, event access, indexer access,
24         ///   nothing).
25         /// </remarks>
26         public enum ExprClass : byte {
27                 Invalid,
28                 
29                 Value,
30                 Variable,
31                 Namespace,
32                 Type,
33                 MethodGroup,
34                 PropertyAccess,
35                 EventAccess,
36                 IndexerAccess,
37                 Nothing, 
38         }
39
40         /// <remarks>
41         ///   This is used to tell Resolve in which types of expressions we're
42         ///   interested.
43         /// </remarks>
44         [Flags]
45         public enum ResolveFlags {
46                 // Returns Value, Variable, PropertyAccess, EventAccess or IndexerAccess.
47                 VariableOrValue         = 1,
48
49                 // Returns a type expression.
50                 Type                    = 2,
51
52                 // Returns a method group.
53                 MethodGroup             = 4,
54
55                 // Mask of all the expression class flags.
56                 MaskExprClass           = 7,
57
58                 // Disable control flow analysis while resolving the expression.
59                 // This is used when resolving the instance expression of a field expression.
60                 DisableFlowAnalysis     = 8,
61
62                 // Set if this is resolving the first part of a MemberAccess.
63                 Intermediate            = 16,
64
65                 // Disable control flow analysis _of struct_ while resolving the expression.
66                 // This is used when resolving the instance expression of a field expression.
67                 DisableStructFlowAnalysis       = 32,
68
69         }
70
71         //
72         // This is just as a hint to AddressOf of what will be done with the
73         // address.
74         [Flags]
75         public enum AddressOp {
76                 Store = 1,
77                 Load  = 2,
78                 LoadStore = 3
79         };
80         
81         /// <summary>
82         ///   This interface is implemented by variables
83         /// </summary>
84         public interface IMemoryLocation {
85                 /// <summary>
86                 ///   The AddressOf method should generate code that loads
87                 ///   the address of the object and leaves it on the stack.
88                 ///
89                 ///   The `mode' argument is used to notify the expression
90                 ///   of whether this will be used to read from the address or
91                 ///   write to the address.
92                 ///
93                 ///   This is just a hint that can be used to provide good error
94                 ///   reporting, and should have no other side effects. 
95                 /// </summary>
96                 void AddressOf (EmitContext ec, AddressOp mode);
97         }
98
99         /// <summary>
100         ///   This interface is implemented by variables
101         /// </summary>
102         public interface IVariable {
103                 VariableInfo VariableInfo {
104                         get;
105                 }
106
107                 bool VerifyFixed ();
108         }
109
110         /// <remarks>
111         ///   Base class for expressions
112         /// </remarks>
113         public abstract class Expression {
114                 public ExprClass eclass;
115                 protected Type type;
116                 protected Location loc;
117                 
118                 public Type Type {
119                         get { return type; }
120                         set { type = value; }
121                 }
122
123                 public virtual Location Location {
124                         get { return loc; }
125                 }
126
127                 /// <summary>
128                 ///   Utility wrapper routine for Error, just to beautify the code
129                 /// </summary>
130                 public void Error (int error, string s)
131                 {
132                         Report.Error (error, loc, s);
133                 }
134
135                 // Not nice but we have broken hierarchy.
136                 public virtual void CheckMarshalByRefAccess ()
137                 {
138                 }
139
140                 public virtual bool GetAttributableValue (Type valueType, out object value)
141                 {
142                         Attribute.Error_AttributeArgumentNotValid (loc);
143                         value = null;
144                         return false;
145                 }
146
147                 public virtual string GetSignatureForError ()
148                 {
149                         return TypeManager.CSharpName (type);
150                 }
151
152                 public static bool IsAccessorAccessible (Type invocation_type, MethodInfo mi, out bool must_do_cs1540_check)
153                 {
154                         MethodAttributes ma = mi.Attributes & MethodAttributes.MemberAccessMask;
155
156                         must_do_cs1540_check = false; // by default we do not check for this
157
158                         if (ma == MethodAttributes.Public)
159                                 return true;
160                         
161                         //
162                         // If only accessible to the current class or children
163                         //
164                         if (ma == MethodAttributes.Private)
165                                 return TypeManager.IsPrivateAccessible (invocation_type, mi.DeclaringType) ||
166                                         TypeManager.IsNestedChildOf (invocation_type, mi.DeclaringType);
167
168                         if (mi.DeclaringType.Assembly == invocation_type.Assembly ||
169                                         TypeManager.IsFriendAssembly (mi.DeclaringType.Assembly)) {
170                                 if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamORAssem)
171                                         return true;
172                         } else {
173                                 if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamANDAssem)
174                                         return false;
175                         }
176
177                         // Family and FamANDAssem require that we derive.
178                         // FamORAssem requires that we derive if in different assemblies.
179                         if (!TypeManager.IsNestedFamilyAccessible (invocation_type, mi.DeclaringType))
180                                 return false;
181
182                         if (!TypeManager.IsNestedChildOf (invocation_type, mi.DeclaringType))
183                                 must_do_cs1540_check = true;
184
185                         return true;
186                 }
187
188                 /// <summary>
189                 ///   Performs semantic analysis on the Expression
190                 /// </summary>
191                 ///
192                 /// <remarks>
193                 ///   The Resolve method is invoked to perform the semantic analysis
194                 ///   on the node.
195                 ///
196                 ///   The return value is an expression (it can be the
197                 ///   same expression in some cases) or a new
198                 ///   expression that better represents this node.
199                 ///   
200                 ///   For example, optimizations of Unary (LiteralInt)
201                 ///   would return a new LiteralInt with a negated
202                 ///   value.
203                 ///   
204                 ///   If there is an error during semantic analysis,
205                 ///   then an error should be reported (using Report)
206                 ///   and a null value should be returned.
207                 ///   
208                 ///   There are two side effects expected from calling
209                 ///   Resolve(): the the field variable "eclass" should
210                 ///   be set to any value of the enumeration
211                 ///   `ExprClass' and the type variable should be set
212                 ///   to a valid type (this is the type of the
213                 ///   expression).
214                 /// </remarks>
215                 public abstract Expression DoResolve (EmitContext ec);
216
217                 public virtual Expression DoResolveLValue (EmitContext ec, Expression right_side)
218                 {
219                         return null;
220                 }
221
222                 //
223                 // This is used if the expression should be resolved as a type or namespace name.
224                 // the default implementation fails.   
225                 //
226                 public virtual FullNamedExpression ResolveAsTypeStep (IResolveContext ec,  bool silent)
227                 {
228                         return null;
229                 }
230
231                 //
232                 // This is used to resolve the expression as a type, a null
233                 // value will be returned if the expression is not a type
234                 // reference
235                 //
236                 public virtual TypeExpr ResolveAsTypeTerminal (IResolveContext ec, bool silent)
237                 {
238                         TypeExpr te = ResolveAsBaseTerminal (ec, silent);
239                         if (te == null)
240                                 return null;
241
242                         ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (te.Type);
243                         if (obsolete_attr != null && !ec.IsInObsoleteScope) {
244                                 AttributeTester.Report_ObsoleteMessage (obsolete_attr, te.GetSignatureForError (), Location);
245                         }
246
247                         // Constrains don't need to be checked for overrides
248                         GenericMethod gm = ec.DeclContainer as GenericMethod;
249                         if (gm != null && (gm.ModFlags & Modifiers.OVERRIDE) != 0) {
250                                 te.loc = loc;
251                                 return te;
252                         }
253
254                         ConstructedType ct = te as ConstructedType;
255                         if ((ct != null) && !ct.CheckConstraints (ec))
256                                 return null;
257
258                         return te;
259                 }
260
261                 public TypeExpr ResolveAsBaseTerminal (IResolveContext ec, bool silent)
262                 {
263                         int errors = Report.Errors;
264
265                         FullNamedExpression fne = ResolveAsTypeStep (ec, silent);
266
267                         if (fne == null){
268                                 if (!silent && errors == Report.Errors)
269                                         Report.Error (118, loc, "Expecting a type.");
270                                 return null;
271                         }
272
273                         if (fne.eclass != ExprClass.Type) {
274                                 if (!silent && errors == Report.Errors)
275                                         fne.Error_UnexpectedKind (null, "type", loc);
276                                 return null;
277                         }
278
279                         TypeExpr te = fne as TypeExpr;
280
281                         if (!te.CheckAccessLevel (ec.DeclContainer)) {
282                                 Report.SymbolRelatedToPreviousError (te.Type);
283                                 ErrorIsInaccesible (loc, TypeManager.CSharpName (te.Type));
284                                 return null;
285                         }
286
287                         te.loc = loc;
288                         return te;
289                 }
290
291                 public static void ErrorIsInaccesible (Location loc, string name)
292                 {
293                         Report.Error (122, loc, "`{0}' is inaccessible due to its protection level", name);
294                 }
295
296                 protected static void Error_CannotAccessProtected (Location loc, MemberInfo m, Type qualifier, Type container)
297                 {
298                         Report.Error (1540, loc, "Cannot access protected member `{0}' via a qualifier of type `{1}';"
299                                 + " the qualifier must be of type `{2}' (or derived from it)", 
300                                 TypeManager.GetFullNameSignature (m),
301                                 TypeManager.CSharpName (qualifier),
302                                 TypeManager.CSharpName (container));
303
304                 }
305
306                 public virtual void Error_ValueCannotBeConverted (Location loc, Type target, bool expl)
307                 {
308                         if (Type.FullName == target.FullName){
309                                 Report.ExtraInformation (loc,
310                                         String.Format (
311                                         "The type {0} has two conflicting definitions, one comes from {1} and the other from {2}",
312                                         Type.FullName, Type.Assembly.FullName, target.Assembly.FullName));
313                                                          
314                         }
315
316                         if (expl) {
317                                 Report.Error (30, loc, "Cannot convert type `{0}' to `{1}'",
318                                         GetSignatureForError (), TypeManager.CSharpName (target));
319                                 return;
320                         }
321                         
322                         Expression e = (this is EnumConstant) ? ((EnumConstant)this).Child : this;
323                         bool b = Convert.ExplicitNumericConversion (e, target) != null;
324
325                         if (b || Convert.ExplicitReferenceConversionExists (Type, target) || Convert.ExplicitUnsafe (e, target) != null) {
326                                 Report.Error (266, loc, "Cannot implicitly convert type `{0}' to `{1}'. An explicit conversion exists (are you missing a cast?)",
327                                         TypeManager.CSharpName (Type), TypeManager.CSharpName (target));
328                                 return;
329                         }
330
331                         if (Type != TypeManager.string_type && this is Constant && !(this is NullCast)) {
332                                 Report.Error (31, loc, "Constant value `{0}' cannot be converted to a `{1}'",
333                                         GetSignatureForError (), TypeManager.CSharpName (target));
334                                 return;
335                         }
336
337                         Report.Error (29, loc, "Cannot implicitly convert type {0} to `{1}'",
338                                 Type == TypeManager.anonymous_method_type ?
339                                 "anonymous method" : "`" + GetSignatureForError () + "'",
340                                 TypeManager.CSharpName (target));
341                 }
342
343                 protected static void Error_TypeDoesNotContainDefinition (Location loc, Type type, string name)
344                 {
345                         Report.Error (117, loc, "`{0}' does not contain a definition for `{1}'",
346                                 TypeManager.CSharpName (type), name);
347                 }
348
349                 ResolveFlags ExprClassToResolveFlags
350                 {
351                         get {
352                                 switch (eclass) {
353                                         case ExprClass.Type:
354                                         case ExprClass.Namespace:
355                                                 return ResolveFlags.Type;
356
357                                         case ExprClass.MethodGroup:
358                                                 return ResolveFlags.MethodGroup;
359
360                                         case ExprClass.Value:
361                                         case ExprClass.Variable:
362                                         case ExprClass.PropertyAccess:
363                                         case ExprClass.EventAccess:
364                                         case ExprClass.IndexerAccess:
365                                                 return ResolveFlags.VariableOrValue;
366
367                                         default:
368                                                 throw new Exception ("Expression " + GetType () +
369                                                         " ExprClass is Invalid after resolve");
370                                 }
371                         }
372                 }
373                
374                 /// <summary>
375                 ///   Resolves an expression and performs semantic analysis on it.
376                 /// </summary>
377                 ///
378                 /// <remarks>
379                 ///   Currently Resolve wraps DoResolve to perform sanity
380                 ///   checking and assertion checking on what we expect from Resolve.
381                 /// </remarks>
382                 public Expression Resolve (EmitContext ec, ResolveFlags flags)
383                 {
384                         if ((flags & ResolveFlags.MaskExprClass) == ResolveFlags.Type) 
385                                 return ResolveAsTypeStep (ec, false);
386
387                         bool do_flow_analysis = ec.DoFlowAnalysis;
388                         bool omit_struct_analysis = ec.OmitStructFlowAnalysis;
389                         if ((flags & ResolveFlags.DisableFlowAnalysis) != 0)
390                                 do_flow_analysis = false;
391                         if ((flags & ResolveFlags.DisableStructFlowAnalysis) != 0)
392                                 omit_struct_analysis = true;
393
394                         Expression e;
395                         using (ec.WithFlowAnalysis (do_flow_analysis, omit_struct_analysis)) {
396                                 if (this is SimpleName) {
397                                         bool intermediate = (flags & ResolveFlags.Intermediate) == ResolveFlags.Intermediate;
398                                         e = ((SimpleName) this).DoResolve (ec, intermediate);
399                                 } else {
400                                         e = DoResolve (ec);
401                                 }
402                         }
403
404                         if (e == null)
405                                 return null;
406
407                         if ((flags & e.ExprClassToResolveFlags) == 0) {
408                                 e.Error_UnexpectedKind (flags, loc);
409                                 return null;
410                         }
411
412                         if (e.type == null && !(e is Namespace)) {
413                                 throw new Exception (
414                                         "Expression " + e.GetType () +
415                                         " did not set its type after Resolve\n" +
416                                         "called from: " + this.GetType ());
417                         }
418
419                         return e;
420                 }
421
422                 /// <summary>
423                 ///   Resolves an expression and performs semantic analysis on it.
424                 /// </summary>
425                 public Expression Resolve (EmitContext ec)
426                 {
427                         Expression e = Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
428
429                         if (e != null && e.eclass == ExprClass.MethodGroup && RootContext.Version == LanguageVersion.ISO_1) {
430                                 ((MethodGroupExpr) e).ReportUsageError ();
431                                 return null;
432                         }
433                         return e;
434                 }
435
436                 public Constant ResolveAsConstant (EmitContext ec, MemberCore mc)
437                 {
438                         Expression e = Resolve (ec);
439                         if (e == null)
440                                 return null;
441
442                         Constant c = e as Constant;
443                         if (c != null)
444                                 return c;
445
446                         Type constant_type = null;
447                         if (mc is MemberBase) {
448                                 constant_type = ((MemberBase)mc).MemberType;
449                         }
450
451                         Const.Error_ExpressionMustBeConstant (constant_type, loc, mc.GetSignatureForError ());
452                         return null;
453                 }
454
455                 /// <summary>
456                 ///   Resolves an expression for LValue assignment
457                 /// </summary>
458                 ///
459                 /// <remarks>
460                 ///   Currently ResolveLValue wraps DoResolveLValue to perform sanity
461                 ///   checking and assertion checking on what we expect from Resolve
462                 /// </remarks>
463                 public Expression ResolveLValue (EmitContext ec, Expression right_side, Location loc)
464                 {
465                         int errors = Report.Errors;
466                         bool out_access = right_side == EmptyExpression.OutAccess;
467
468                         Expression e = DoResolveLValue (ec, right_side);
469
470                         if (e != null && out_access && !(e is IMemoryLocation)) {
471                                 // FIXME: There's no problem with correctness, the 'Expr = null' handles that.
472                                 //        Enabling this 'throw' will "only" result in deleting useless code elsewhere,
473
474                                 //throw new InternalErrorException ("ResolveLValue didn't return an IMemoryLocation: " +
475                                 //                                e.GetType () + " " + e.GetSignatureForError ());
476                                 e = null;
477                         }
478
479                         if (e == null) {
480                                 if (errors == Report.Errors) {
481                                         if (out_access)
482                                                 Report.Error (1510, loc, "A ref or out argument must be an assignable variable");
483                                         else
484                                                 Report.Error (131, loc, "The left-hand side of an assignment or mutating operation must be a variable, property or indexer");
485                                 }
486                                 return null;
487                         }
488
489                         if (e.eclass == ExprClass.Invalid)
490                                 throw new Exception ("Expression " + e + " ExprClass is Invalid after resolve");
491
492                         if (e.eclass == ExprClass.MethodGroup) {
493                                 ((MethodGroupExpr) e).ReportUsageError ();
494                                 return null;
495                         }
496
497                         if ((e.type == null) && !(e is ConstructedType))
498                                 throw new Exception ("Expression " + e + " did not set its type after Resolve");
499
500                         return e;
501                 }
502
503                 /// <summary>
504                 ///   Emits the code for the expression
505                 /// </summary>
506                 ///
507                 /// <remarks>
508                 ///   The Emit method is invoked to generate the code
509                 ///   for the expression.  
510                 /// </remarks>
511                 public abstract void Emit (EmitContext ec);
512
513                 public virtual void EmitBranchable (EmitContext ec, Label target, bool onTrue)
514                 {
515                         Emit (ec);
516                         ec.ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
517                 }
518
519                 /// <summary>
520                 ///   Protected constructor.  Only derivate types should
521                 ///   be able to be created
522                 /// </summary>
523
524                 protected Expression ()
525                 {
526                         eclass = ExprClass.Invalid;
527                         type = null;
528                 }
529
530                 /// <summary>
531                 ///   Returns a literalized version of a literal FieldInfo
532                 /// </summary>
533                 ///
534                 /// <remarks>
535                 ///   The possible return values are:
536                 ///      IntConstant, UIntConstant
537                 ///      LongLiteral, ULongConstant
538                 ///      FloatConstant, DoubleConstant
539                 ///      StringConstant
540                 ///
541                 ///   The value returned is already resolved.
542                 /// </remarks>
543                 public static Constant Constantify (object v, Type t)
544                 {
545                         if (t == TypeManager.int32_type)
546                                 return new IntConstant ((int) v, Location.Null);
547                         else if (t == TypeManager.uint32_type)
548                                 return new UIntConstant ((uint) v, Location.Null);
549                         else if (t == TypeManager.int64_type)
550                                 return new LongConstant ((long) v, Location.Null);
551                         else if (t == TypeManager.uint64_type)
552                                 return new ULongConstant ((ulong) v, Location.Null);
553                         else if (t == TypeManager.float_type)
554                                 return new FloatConstant ((float) v, Location.Null);
555                         else if (t == TypeManager.double_type)
556                                 return new DoubleConstant ((double) v, Location.Null);
557                         else if (t == TypeManager.string_type)
558                                 return new StringConstant ((string) v, Location.Null);
559                         else if (t == TypeManager.short_type)
560                                 return new ShortConstant ((short)v, Location.Null);
561                         else if (t == TypeManager.ushort_type)
562                                 return new UShortConstant ((ushort)v, Location.Null);
563                         else if (t == TypeManager.sbyte_type)
564                                 return new SByteConstant ((sbyte)v, Location.Null);
565                         else if (t == TypeManager.byte_type)
566                                 return new ByteConstant ((byte)v, Location.Null);
567                         else if (t == TypeManager.char_type)
568                                 return new CharConstant ((char)v, Location.Null);
569                         else if (t == TypeManager.bool_type)
570                                 return new BoolConstant ((bool) v, Location.Null);
571                         else if (t == TypeManager.decimal_type)
572                                 return new DecimalConstant ((decimal) v, Location.Null);
573                         else if (TypeManager.IsEnumType (t)){
574                                 Type real_type = TypeManager.TypeToCoreType (v.GetType ());
575                                 if (real_type == t)
576                                         real_type = System.Enum.GetUnderlyingType (real_type);
577
578                                 Constant e = Constantify (v, real_type);
579
580                                 return new EnumConstant (e, t);
581                         } else if (v == null && !TypeManager.IsValueType (t))
582                                 return new NullLiteral (Location.Null);
583                         else
584                                 throw new Exception ("Unknown type for constant (" + t +
585                                                      "), details: " + v);
586                 }
587
588                 /// <summary>
589                 ///   Returns a fully formed expression after a MemberLookup
590                 /// </summary>
591                 /// 
592                 public static Expression ExprClassFromMemberInfo (Type containerType, MemberInfo mi, Location loc)
593                 {
594                         if (mi is EventInfo)
595                                 return new EventExpr ((EventInfo) mi, loc);
596                         else if (mi is FieldInfo)
597                                 return new FieldExpr ((FieldInfo) mi, loc);
598                         else if (mi is PropertyInfo)
599                                 return new PropertyExpr (containerType, (PropertyInfo) mi, loc);
600                         else if (mi is Type){
601                                 return new TypeExpression ((System.Type) mi, loc);
602                         }
603
604                         return null;
605                 }
606
607                 protected static ArrayList almostMatchedMembers = new ArrayList (4);
608
609                 //
610                 // FIXME: Probably implement a cache for (t,name,current_access_set)?
611                 //
612                 // This code could use some optimizations, but we need to do some
613                 // measurements.  For example, we could use a delegate to `flag' when
614                 // something can not any longer be a method-group (because it is something
615                 // else).
616                 //
617                 // Return values:
618                 //     If the return value is an Array, then it is an array of
619                 //     MethodBases
620                 //   
621                 //     If the return value is an MemberInfo, it is anything, but a Method
622                 //
623                 //     null on error.
624                 //
625                 // FIXME: When calling MemberLookup inside an `Invocation', we should pass
626                 // the arguments here and have MemberLookup return only the methods that
627                 // match the argument count/type, unlike we are doing now (we delay this
628                 // decision).
629                 //
630                 // This is so we can catch correctly attempts to invoke instance methods
631                 // from a static body (scan for error 120 in ResolveSimpleName).
632                 //
633                 //
634                 // FIXME: Potential optimization, have a static ArrayList
635                 //
636
637                 public static Expression MemberLookup (Type container_type, Type queried_type, string name,
638                                                        MemberTypes mt, BindingFlags bf, Location loc)
639                 {
640                         return MemberLookup (container_type, null, queried_type, name, mt, bf, loc);
641                 }
642
643                 //
644                 // Lookup type `queried_type' for code in class `container_type' with a qualifier of
645                 // `qualifier_type' or null to lookup members in the current class.
646                 //
647
648                 public static Expression MemberLookup (Type container_type,
649                                                        Type qualifier_type, Type queried_type,
650                                                        string name, MemberTypes mt,
651                                                        BindingFlags bf, Location loc)
652                 {
653                         almostMatchedMembers.Clear ();
654
655                         MemberInfo [] mi = TypeManager.MemberLookup (container_type, qualifier_type,
656                                                                      queried_type, mt, bf, name, almostMatchedMembers);
657
658                         if (mi == null)
659                                 return null;
660
661                         if (mi.Length > 1) {
662                                 MemberInfo non_method = null;
663                                 ArrayList methods = new ArrayList (2);
664                                 foreach (MemberInfo m in mi) {
665                                         if (m is MethodBase) {
666                                                 methods.Add (m);
667                                                 continue;
668                                         }
669
670                                         if (non_method == null) {
671                                                 non_method = m;
672                                                 continue;
673                                         }
674
675                                         Report.SymbolRelatedToPreviousError (m);
676                                         Report.SymbolRelatedToPreviousError (non_method);
677                                         Report.Error (229, loc, "Ambiguity between `{0}' and `{1}'",
678                                                 TypeManager.GetFullNameSignature (m), TypeManager.GetFullNameSignature (non_method));
679                                         return null;
680                                 }
681
682                                 if (non_method != null) {
683                                         MethodBase method = (MethodBase)methods[0];
684                                         Report.SymbolRelatedToPreviousError (method);
685                                         Report.SymbolRelatedToPreviousError (non_method);
686                                         Report.Warning (467, 2, loc, "Ambiguity between method `{0}' and non-method `{1}'. Using method `{0}'",
687                                                 TypeManager.CSharpSignature (method), TypeManager.GetFullNameSignature (non_method));
688                                 }
689
690                                 return new MethodGroupExpr (methods, loc);
691                         }
692
693                         if (mi [0] is MethodBase)
694                                 return new MethodGroupExpr (mi, loc);
695
696                         return ExprClassFromMemberInfo (container_type, mi [0], loc);
697                 }
698
699                 public const MemberTypes AllMemberTypes =
700                         MemberTypes.Constructor |
701                         MemberTypes.Event       |
702                         MemberTypes.Field       |
703                         MemberTypes.Method      |
704                         MemberTypes.NestedType  |
705                         MemberTypes.Property;
706                 
707                 public const BindingFlags AllBindingFlags =
708                         BindingFlags.Public |
709                         BindingFlags.Static |
710                         BindingFlags.Instance;
711
712                 public static Expression MemberLookup (Type container_type, Type queried_type,
713                                                        string name, Location loc)
714                 {
715                         return MemberLookup (container_type, null, queried_type, name,
716                                              AllMemberTypes, AllBindingFlags, loc);
717                 }
718
719                 public static Expression MemberLookup (Type container_type, Type qualifier_type,
720                                                        Type queried_type, string name, Location loc)
721                 {
722                         return MemberLookup (container_type, qualifier_type, queried_type,
723                                              name, AllMemberTypes, AllBindingFlags, loc);
724                 }
725
726                 public static Expression MethodLookup (EmitContext ec, Type queried_type,
727                                                        string name, Location loc)
728                 {
729                         return MemberLookup (ec.ContainerType, null, queried_type, name,
730                                              MemberTypes.Method, AllBindingFlags, loc);
731                 }
732
733                 /// <summary>
734                 ///   This is a wrapper for MemberLookup that is not used to "probe", but
735                 ///   to find a final definition.  If the final definition is not found, we
736                 ///   look for private members and display a useful debugging message if we
737                 ///   find it.
738                 /// </summary>
739                 public static Expression MemberLookupFinal (EmitContext ec, Type qualifier_type,
740                                                             Type queried_type, string name, Location loc)
741                 {
742                         return MemberLookupFinal (ec, qualifier_type, queried_type, name,
743                                                   AllMemberTypes, AllBindingFlags, loc);
744                 }
745
746                 public static Expression MemberLookupFinal (EmitContext ec, Type qualifier_type,
747                                                             Type queried_type, string name,
748                                                             MemberTypes mt, BindingFlags bf,
749                                                             Location loc)
750                 {
751                         Expression e;
752
753                         int errors = Report.Errors;
754
755                         e = MemberLookup (ec.ContainerType, qualifier_type, queried_type, name, mt, bf, loc);
756
757                         if (e == null && errors == Report.Errors)
758                                 // No errors were reported by MemberLookup, but there was an error.
759                                 MemberLookupFailed (ec.ContainerType, qualifier_type, queried_type, name, null, true, loc);
760
761                         return e;
762                 }
763
764                 public static void MemberLookupFailed (Type container_type, Type qualifier_type,
765                                                        Type queried_type, string name,
766                                                        string class_name, bool complain_if_none_found, 
767                                                        Location loc)
768                 {
769                         if (almostMatchedMembers.Count != 0) {
770                                 for (int i = 0; i < almostMatchedMembers.Count; ++i) {
771                                         MemberInfo m = (MemberInfo) almostMatchedMembers [i];
772                                         for (int j = 0; j < i; ++j) {
773                                                 if (m == almostMatchedMembers [j]) {
774                                                         m = null;
775                                                         break;
776                                                 }
777                                         }
778                                         if (m == null)
779                                                 continue;
780                                         
781                                         Type declaring_type = m.DeclaringType;
782                                         
783                                         Report.SymbolRelatedToPreviousError (m);
784                                         if (qualifier_type == null) {
785                                                 Report.Error (38, loc, "Cannot access a nonstatic member of outer type `{0}' via nested type `{1}'",
786                                                               TypeManager.CSharpName (m.DeclaringType),
787                                                               TypeManager.CSharpName (container_type));
788                                                 
789                                         } else if (qualifier_type != container_type &&
790                                                    TypeManager.IsNestedFamilyAccessible (container_type, declaring_type)) {
791                                                 // Although a derived class can access protected members of
792                                                 // its base class it cannot do so through an instance of the
793                                                 // base class (CS1540).  If the qualifier_type is a base of the
794                                                 // ec.ContainerType and the lookup succeeds with the latter one,
795                                                 // then we are in this situation.
796                                                 Error_CannotAccessProtected (loc, m, qualifier_type, container_type);
797                                         } else {
798                                                 Report.SymbolRelatedToPreviousError (m);
799                                                 ErrorIsInaccesible (loc, TypeManager.GetFullNameSignature (m));
800                                         }
801                                 }
802                                 almostMatchedMembers.Clear ();
803                                 return;
804                         }
805
806                         MemberInfo[] lookup = null;
807                         if (queried_type == null) {
808                                 class_name = "global::";
809                         } else {
810                                 lookup = TypeManager.MemberLookup (queried_type, null, queried_type,
811                                         AllMemberTypes, AllBindingFlags |
812                                         BindingFlags.NonPublic, name, null);
813                         }
814
815                         if (lookup == null) {
816                                 if (!complain_if_none_found)
817                                         return;
818
819                                 if (class_name != null)
820                                         Report.Error (103, loc, "The name `{0}' does not exist in the context of `{1}'",
821                                                 name, class_name);
822                                 else
823                                         Error_TypeDoesNotContainDefinition (loc, queried_type, name);
824                                 return;
825                         }
826
827                         if (TypeManager.MemberLookup (queried_type, null, queried_type,
828                                                       AllMemberTypes, AllBindingFlags |
829                                                       BindingFlags.NonPublic, name, null) == null) {
830                                 if ((lookup.Length == 1) && (lookup [0] is Type)) {
831                                         Type t = (Type) lookup [0];
832
833                                         Report.Error (305, loc,
834                                                       "Using the generic type `{0}' " +
835                                                       "requires {1} type arguments",
836                                                       TypeManager.CSharpName (t),
837                                                       TypeManager.GetNumberOfTypeArguments (t).ToString ());
838                                         return;
839                                 }
840                         }
841
842                         MemberList ml = TypeManager.FindMembers (queried_type, MemberTypes.Constructor,
843                                                                  BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly, null, null);
844                         if (name == ".ctor" && ml.Count == 0)
845                         {
846                                 Report.Error (143, loc, "The type `{0}' has no constructors defined", TypeManager.CSharpName (queried_type));
847                                 return;
848                         }
849
850                         Report.SymbolRelatedToPreviousError (lookup [0]);
851                         ErrorIsInaccesible (loc, TypeManager.GetFullNameSignature (lookup [0]));
852                 }
853
854                 /// <summary>
855                 ///   Returns an expression that can be used to invoke operator true
856                 ///   on the expression if it exists.
857                 /// </summary>
858                 static public Expression GetOperatorTrue (EmitContext ec, Expression e, Location loc)
859                 {
860                         return GetOperatorTrueOrFalse (ec, e, true, loc);
861                 }
862
863                 /// <summary>
864                 ///   Returns an expression that can be used to invoke operator false
865                 ///   on the expression if it exists.
866                 /// </summary>
867                 static public Expression GetOperatorFalse (EmitContext ec, Expression e, Location loc)
868                 {
869                         return GetOperatorTrueOrFalse (ec, e, false, loc);
870                 }
871
872                 static Expression GetOperatorTrueOrFalse (EmitContext ec, Expression e, bool is_true, Location loc)
873                 {
874                         MethodBase method;
875                         Expression operator_group;
876
877                         if (TypeManager.IsNullableType (e.Type))
878                                 return new Nullable.OperatorTrueOrFalse (e, is_true, loc).Resolve (ec);
879
880                         operator_group = MethodLookup (ec, e.Type, is_true ? "op_True" : "op_False", loc);
881                         if (operator_group == null)
882                                 return null;
883
884                         ArrayList arguments = new ArrayList ();
885                         arguments.Add (new Argument (e, Argument.AType.Expression));
886                         method = Invocation.OverloadResolve (
887                                 ec, (MethodGroupExpr) operator_group, arguments, false, loc);
888
889                         if (method == null)
890                                 return null;
891
892                         return new StaticCallExpr ((MethodInfo) method, arguments, loc);
893                 }
894
895                 /// <summary>
896                 ///   Resolves the expression `e' into a boolean expression: either through
897                 ///   an implicit conversion, or through an `operator true' invocation
898                 /// </summary>
899                 public static Expression ResolveBoolean (EmitContext ec, Expression e, Location loc)
900                 {
901                         e = e.Resolve (ec);
902                         if (e == null)
903                                 return null;
904
905                         if (e.Type == TypeManager.bool_type)
906                                 return e;
907
908                         Expression converted = Convert.ImplicitConversion (ec, e, TypeManager.bool_type, Location.Null);
909
910                         if (converted != null)
911                                 return converted;
912
913                         //
914                         // If no implicit conversion to bool exists, try using `operator true'
915                         //
916                         converted = Expression.GetOperatorTrue (ec, e, loc);
917                         if (converted == null){
918                                 e.Error_ValueCannotBeConverted (loc, TypeManager.bool_type, false);
919                                 return null;
920                         }
921                         return converted;
922                 }
923                 
924                 public virtual string ExprClassName
925                 {
926                         get {
927                                 switch (eclass){
928                                         case ExprClass.Invalid:
929                                                 return "Invalid";
930                                         case ExprClass.Value:
931                                                 return "value";
932                                         case ExprClass.Variable:
933                                                 return "variable";
934                                         case ExprClass.Namespace:
935                                                 return "namespace";
936                                         case ExprClass.Type:
937                                                 return "type";
938                                         case ExprClass.MethodGroup:
939                                                 return "method group";
940                                         case ExprClass.PropertyAccess:
941                                                 return "property access";
942                                         case ExprClass.EventAccess:
943                                                 return "event access";
944                                         case ExprClass.IndexerAccess:
945                                                 return "indexer access";
946                                         case ExprClass.Nothing:
947                                                 return "null";
948                                 }
949                                 throw new Exception ("Should not happen");
950                         }
951                 }
952                 
953                 /// <summary>
954                 ///   Reports that we were expecting `expr' to be of class `expected'
955                 /// </summary>
956                 public void Error_UnexpectedKind (DeclSpace ds, string expected, Location loc)
957                 {
958                         Error_UnexpectedKind (ds, expected, ExprClassName, loc);
959                 }
960
961                 public void Error_UnexpectedKind (DeclSpace ds, string expected, string was, Location loc)
962                 {
963                         string name = GetSignatureForError ();
964                         if (ds != null)
965                                 name = ds.GetSignatureForError () + '.' + name;
966
967                         Report.Error (118, loc, "`{0}' is a `{1}' but a `{2}' was expected",
968                               name, was, expected);
969                 }
970
971                 public void Error_UnexpectedKind (ResolveFlags flags, Location loc)
972                 {
973                         string [] valid = new string [4];
974                         int count = 0;
975
976                         if ((flags & ResolveFlags.VariableOrValue) != 0) {
977                                 valid [count++] = "variable";
978                                 valid [count++] = "value";
979                         }
980
981                         if ((flags & ResolveFlags.Type) != 0)
982                                 valid [count++] = "type";
983
984                         if ((flags & ResolveFlags.MethodGroup) != 0)
985                                 valid [count++] = "method group";
986
987                         if (count == 0)
988                                 valid [count++] = "unknown";
989
990                         StringBuilder sb = new StringBuilder (valid [0]);
991                         for (int i = 1; i < count - 1; i++) {
992                                 sb.Append ("', `");
993                                 sb.Append (valid [i]);
994                         }
995                         if (count > 1) {
996                                 sb.Append ("' or `");
997                                 sb.Append (valid [count - 1]);
998                         }
999
1000                         Report.Error (119, loc, 
1001                                 "Expression denotes a `{0}', where a `{1}' was expected", ExprClassName, sb.ToString ());
1002                 }
1003                 
1004                 public static void UnsafeError (Location loc)
1005                 {
1006                         Report.Error (214, loc, "Pointers and fixed size buffers may only be used in an unsafe context");
1007                 }
1008
1009                 //
1010                 // Load the object from the pointer.  
1011                 //
1012                 public static void LoadFromPtr (ILGenerator ig, Type t)
1013                 {
1014                         if (t == TypeManager.int32_type)
1015                                 ig.Emit (OpCodes.Ldind_I4);
1016                         else if (t == TypeManager.uint32_type)
1017                                 ig.Emit (OpCodes.Ldind_U4);
1018                         else if (t == TypeManager.short_type)
1019                                 ig.Emit (OpCodes.Ldind_I2);
1020                         else if (t == TypeManager.ushort_type)
1021                                 ig.Emit (OpCodes.Ldind_U2);
1022                         else if (t == TypeManager.char_type)
1023                                 ig.Emit (OpCodes.Ldind_U2);
1024                         else if (t == TypeManager.byte_type)
1025                                 ig.Emit (OpCodes.Ldind_U1);
1026                         else if (t == TypeManager.sbyte_type)
1027                                 ig.Emit (OpCodes.Ldind_I1);
1028                         else if (t == TypeManager.uint64_type)
1029                                 ig.Emit (OpCodes.Ldind_I8);
1030                         else if (t == TypeManager.int64_type)
1031                                 ig.Emit (OpCodes.Ldind_I8);
1032                         else if (t == TypeManager.float_type)
1033                                 ig.Emit (OpCodes.Ldind_R4);
1034                         else if (t == TypeManager.double_type)
1035                                 ig.Emit (OpCodes.Ldind_R8);
1036                         else if (t == TypeManager.bool_type)
1037                                 ig.Emit (OpCodes.Ldind_I1);
1038                         else if (t == TypeManager.intptr_type)
1039                                 ig.Emit (OpCodes.Ldind_I);
1040                         else if (TypeManager.IsEnumType (t)) {
1041                                 if (t == TypeManager.enum_type)
1042                                         ig.Emit (OpCodes.Ldind_Ref);
1043                                 else
1044                                         LoadFromPtr (ig, TypeManager.EnumToUnderlying (t));
1045                         } else if (t.IsValueType || t.IsGenericParameter)
1046                                 ig.Emit (OpCodes.Ldobj, t);
1047                         else if (t.IsPointer)
1048                                 ig.Emit (OpCodes.Ldind_I);
1049                         else
1050                                 ig.Emit (OpCodes.Ldind_Ref);
1051                 }
1052
1053                 //
1054                 // The stack contains the pointer and the value of type `type'
1055                 //
1056                 public static void StoreFromPtr (ILGenerator ig, Type type)
1057                 {
1058                         if (TypeManager.IsEnumType (type))
1059                                 type = TypeManager.EnumToUnderlying (type);
1060                         if (type == TypeManager.int32_type || type == TypeManager.uint32_type)
1061                                 ig.Emit (OpCodes.Stind_I4);
1062                         else if (type == TypeManager.int64_type || type == TypeManager.uint64_type)
1063                                 ig.Emit (OpCodes.Stind_I8);
1064                         else if (type == TypeManager.char_type || type == TypeManager.short_type ||
1065                                  type == TypeManager.ushort_type)
1066                                 ig.Emit (OpCodes.Stind_I2);
1067                         else if (type == TypeManager.float_type)
1068                                 ig.Emit (OpCodes.Stind_R4);
1069                         else if (type == TypeManager.double_type)
1070                                 ig.Emit (OpCodes.Stind_R8);
1071                         else if (type == TypeManager.byte_type || type == TypeManager.sbyte_type ||
1072                                  type == TypeManager.bool_type)
1073                                 ig.Emit (OpCodes.Stind_I1);
1074                         else if (type == TypeManager.intptr_type)
1075                                 ig.Emit (OpCodes.Stind_I);
1076                         else if (type.IsValueType || type.IsGenericParameter)
1077                                 ig.Emit (OpCodes.Stobj, type);
1078                         else
1079                                 ig.Emit (OpCodes.Stind_Ref);
1080                 }
1081                 
1082                 //
1083                 // Returns the size of type `t' if known, otherwise, 0
1084                 //
1085                 public static int GetTypeSize (Type t)
1086                 {
1087                         t = TypeManager.TypeToCoreType (t);
1088                         if (t == TypeManager.int32_type ||
1089                             t == TypeManager.uint32_type ||
1090                             t == TypeManager.float_type)
1091                                 return 4;
1092                         else if (t == TypeManager.int64_type ||
1093                                  t == TypeManager.uint64_type ||
1094                                  t == TypeManager.double_type)
1095                                 return 8;
1096                         else if (t == TypeManager.byte_type ||
1097                                  t == TypeManager.sbyte_type ||
1098                                  t == TypeManager.bool_type)    
1099                                 return 1;
1100                         else if (t == TypeManager.short_type ||
1101                                  t == TypeManager.char_type ||
1102                                  t == TypeManager.ushort_type)
1103                                 return 2;
1104                         else if (t == TypeManager.decimal_type)
1105                                 return 16;
1106                         else
1107                                 return 0;
1108                 }
1109
1110                 public static void Error_NegativeArrayIndex (Location loc)
1111                 {
1112                         Report.Error (248, loc, "Cannot create an array with a negative size");
1113                 }
1114
1115                 protected void Error_CannotCallAbstractBase (string name)
1116                 {
1117                         Report.Error (205, loc, "Cannot call an abstract base member `{0}'", name);
1118                 }
1119                 
1120                 //
1121                 // Converts `source' to an int, uint, long or ulong.
1122                 //
1123                 public Expression ExpressionToArrayArgument (EmitContext ec, Expression source, Location loc)
1124                 {
1125                         Expression target;
1126                         
1127                         using (ec.With (EmitContext.Flags.CheckState, true)) {
1128                                 target = Convert.ImplicitConversion (ec, source, TypeManager.int32_type, loc);
1129                                 if (target == null)
1130                                         target = Convert.ImplicitConversion (ec, source, TypeManager.uint32_type, loc);
1131                                 if (target == null)
1132                                         target = Convert.ImplicitConversion (ec, source, TypeManager.int64_type, loc);
1133                                 if (target == null)
1134                                         target = Convert.ImplicitConversion (ec, source, TypeManager.uint64_type, loc);
1135
1136                                 if (target == null) {
1137                                         source.Error_ValueCannotBeConverted (loc, TypeManager.int32_type, false);
1138                                         return null;
1139                                 }
1140                         }
1141
1142                         //
1143                         // Only positive constants are allowed at compile time
1144                         //
1145                         if (target is Constant){
1146                                 if (target is IntConstant){
1147                                         if (((IntConstant) target).Value < 0){
1148                                                 Error_NegativeArrayIndex (loc);
1149                                                 return null;
1150                                         }
1151                                 }
1152
1153                                 if (target is LongConstant){
1154                                         if (((LongConstant) target).Value < 0){
1155                                                 Error_NegativeArrayIndex (loc);
1156                                                 return null;
1157                                         }
1158                                 }
1159                                 
1160                         }
1161
1162                         return target;
1163                 }
1164                 
1165         }
1166
1167         /// <summary>
1168         ///   This is just a base class for expressions that can
1169         ///   appear on statements (invocations, object creation,
1170         ///   assignments, post/pre increment and decrement).  The idea
1171         ///   being that they would support an extra Emition interface that
1172         ///   does not leave a result on the stack.
1173         /// </summary>
1174         public abstract class ExpressionStatement : Expression {
1175
1176                 public virtual ExpressionStatement ResolveStatement (EmitContext ec)
1177                 {
1178                         Expression e = Resolve (ec);
1179                         if (e == null)
1180                                 return null;
1181
1182                         ExpressionStatement es = e as ExpressionStatement;
1183                         if (es == null)
1184                                 Error (201, "Only assignment, call, increment, decrement and new object " +
1185                                        "expressions can be used as a statement");
1186
1187                         return es;
1188                 }
1189
1190                 /// <summary>
1191                 ///   Requests the expression to be emitted in a `statement'
1192                 ///   context.  This means that no new value is left on the
1193                 ///   stack after invoking this method (constrasted with
1194                 ///   Emit that will always leave a value on the stack).
1195                 /// </summary>
1196                 public abstract void EmitStatement (EmitContext ec);
1197         }
1198
1199         /// <summary>
1200         ///   This kind of cast is used to encapsulate the child
1201         ///   whose type is child.Type into an expression that is
1202         ///   reported to return "return_type".  This is used to encapsulate
1203         ///   expressions which have compatible types, but need to be dealt
1204         ///   at higher levels with.
1205         ///
1206         ///   For example, a "byte" expression could be encapsulated in one
1207         ///   of these as an "unsigned int".  The type for the expression
1208         ///   would be "unsigned int".
1209         ///
1210         /// </summary>
1211         public class EmptyCast : Expression {
1212                 protected readonly Expression child;
1213
1214                 public EmptyCast (Expression child, Type return_type)
1215                 {
1216                         eclass = child.eclass;
1217                         loc = child.Location;
1218                         type = return_type;
1219                         this.child = child;
1220                 }
1221
1222                 public override Expression DoResolve (EmitContext ec)
1223                 {
1224                         // This should never be invoked, we are born in fully
1225                         // initialized state.
1226
1227                         return this;
1228                 }
1229
1230                 public override void Emit (EmitContext ec)
1231                 {
1232                         child.Emit (ec);
1233                 }
1234
1235                 public override bool GetAttributableValue (Type valueType, out object value)
1236                 {
1237                         return child.GetAttributableValue (valueType, out value);
1238                 }
1239
1240         }
1241         /// <summary>
1242         ///     This is a numeric cast to a Decimal
1243         /// </summary>
1244         public class CastToDecimal : EmptyCast {
1245
1246                 MethodInfo conversion_operator;
1247
1248                 public CastToDecimal (Expression child)
1249                         : this (child, false)
1250                 {
1251                 }
1252
1253                 public CastToDecimal (Expression child, bool find_explicit)
1254                         : base (child, TypeManager.decimal_type)
1255                 {
1256                         conversion_operator = GetConversionOperator (find_explicit);
1257
1258                         if (conversion_operator == null)
1259                                 throw new InternalErrorException ("Outer conversion routine is out of sync");
1260                 }
1261
1262                 // Returns the implicit operator that converts from
1263                 // 'child.Type' to System.Decimal.
1264                 MethodInfo GetConversionOperator (bool find_explicit)
1265                 {
1266                         string operator_name = find_explicit ? "op_Explicit" : "op_Implicit";
1267                         
1268                         MemberInfo [] mi = TypeManager.MemberLookup (type, type, type, MemberTypes.Method,
1269                                 BindingFlags.Static | BindingFlags.Public, operator_name, null);
1270
1271                         foreach (MethodInfo oper in mi) {
1272                                 ParameterData pd = TypeManager.GetParameterData (oper);
1273
1274                                 if (pd.ParameterType (0) == child.Type && oper.ReturnType == type)
1275                                         return oper;
1276                         }
1277
1278                         return null;
1279                 }
1280                 public override void Emit (EmitContext ec)
1281                 {
1282                         ILGenerator ig = ec.ig;
1283                         child.Emit (ec);
1284
1285                         ig.Emit (OpCodes.Call, conversion_operator);
1286                 }
1287         }
1288
1289         /// <summary>
1290         ///     This is an explicit numeric cast from a Decimal
1291         /// </summary>
1292         public class CastFromDecimal : EmptyCast
1293         {
1294                 static IDictionary operators;
1295
1296                 public CastFromDecimal (Expression child, Type return_type)
1297                         : base (child, return_type)
1298                 {
1299                         if (child.Type != TypeManager.decimal_type)
1300                                 throw new InternalErrorException (
1301                                         "The expected type is Decimal, instead it is " + child.Type.FullName);
1302                 }
1303
1304                 // Returns the explicit operator that converts from an
1305                 // express of type System.Decimal to 'type'.
1306                 public Expression Resolve ()
1307                 {
1308                         if (operators == null) {
1309                                  MemberInfo[] all_oper = TypeManager.MemberLookup (TypeManager.decimal_type,
1310                                         TypeManager.decimal_type, TypeManager.decimal_type, MemberTypes.Method,
1311                                         BindingFlags.Static | BindingFlags.Public, "op_Explicit", null);
1312
1313                                 operators = new System.Collections.Specialized.HybridDictionary ();
1314                                 foreach (MethodInfo oper in all_oper) {
1315                                         ParameterData pd = TypeManager.GetParameterData (oper);
1316                                         if (pd.ParameterType (0) == TypeManager.decimal_type)
1317                                                 operators.Add (oper.ReturnType, oper);
1318                                 }
1319                         }
1320
1321                         return operators.Contains (type) ? this : null;
1322                 }
1323
1324                 public override void Emit (EmitContext ec)
1325                 {
1326                         ILGenerator ig = ec.ig;
1327                         child.Emit (ec);
1328
1329                         ig.Emit (OpCodes.Call, (MethodInfo)operators [type]);
1330                 }
1331         }
1332
1333         //
1334         // We need to special case this since an empty cast of
1335         // a NullLiteral is still a Constant
1336         //
1337         public class NullCast : Constant {
1338                 public Constant child;
1339                                 
1340                 public NullCast (Constant child, Type return_type):
1341                         base (Location.Null)
1342                 {
1343                         eclass = child.eclass;
1344                         type = return_type;
1345                         this.child = child;
1346                 }
1347
1348                 override public string AsString ()
1349                 {
1350                         return "null";
1351                 }
1352
1353                 public override object GetValue ()
1354                 {
1355                         return null;
1356                 }
1357
1358                 public override Expression DoResolve (EmitContext ec)
1359                 {
1360                         // This should never be invoked, we are born in fully
1361                         // initialized state.
1362
1363                         return this;
1364                 }
1365
1366                 public override void Emit (EmitContext ec)
1367                 {
1368                         child.Emit (ec);
1369                 }
1370
1371                 public override Constant Increment ()
1372                 {
1373                         throw new NotSupportedException ();
1374                 }
1375
1376                 public override bool IsDefaultValue {
1377                         get {
1378                                 return true;
1379                         }
1380                 }
1381
1382                 public override bool IsNegative {
1383                         get {
1384                                 return false;
1385                         }
1386                 }
1387
1388                 public override Constant Reduce (bool inCheckedContext, Type target_type)
1389                 {
1390                         if (type == target_type)
1391                                 return child.Reduce (inCheckedContext, target_type);
1392
1393                         return null;
1394                 }
1395
1396         }
1397
1398
1399         /// <summary>
1400         ///  This class is used to wrap literals which belong inside Enums
1401         /// </summary>
1402         public class EnumConstant : Constant {
1403                 public Constant Child;
1404
1405                 public EnumConstant (Constant child, Type enum_type):
1406                         base (child.Location)
1407                 {
1408                         eclass = child.eclass;
1409                         this.Child = child;
1410                         type = enum_type;
1411                 }
1412                 
1413                 public override Expression DoResolve (EmitContext ec)
1414                 {
1415                         // This should never be invoked, we are born in fully
1416                         // initialized state.
1417
1418                         return this;
1419                 }
1420
1421                 public override void Emit (EmitContext ec)
1422                 {
1423                         Child.Emit (ec);
1424                 }
1425
1426                 public override bool GetAttributableValue (Type valueType, out object value)
1427                 {
1428                         value = GetTypedValue ();
1429                         return true;
1430                 }
1431
1432                 public override string GetSignatureForError()
1433                 {
1434                         return TypeManager.CSharpName (Type);
1435                 }
1436
1437                 public override object GetValue ()
1438                 {
1439                         return Child.GetValue ();
1440                 }
1441
1442                 public override object GetTypedValue ()
1443                 {
1444                         // FIXME: runtime is not ready to work with just emited enums
1445                         if (!RootContext.StdLib) {
1446                                 return Child.GetValue ();
1447                         }
1448
1449                         return System.Enum.ToObject (type, Child.GetValue ());
1450                 }
1451                 
1452                 public override string AsString ()
1453                 {
1454                         return Child.AsString ();
1455                 }
1456
1457                 public override DoubleConstant ConvertToDouble ()
1458                 {
1459                         return Child.ConvertToDouble ();
1460                 }
1461
1462                 public override FloatConstant ConvertToFloat ()
1463                 {
1464                         return Child.ConvertToFloat ();
1465                 }
1466
1467                 public override ULongConstant ConvertToULong ()
1468                 {
1469                         return Child.ConvertToULong ();
1470                 }
1471
1472                 public override LongConstant ConvertToLong ()
1473                 {
1474                         return Child.ConvertToLong ();
1475                 }
1476
1477                 public override UIntConstant ConvertToUInt ()
1478                 {
1479                         return Child.ConvertToUInt ();
1480                 }
1481
1482                 public override IntConstant ConvertToInt ()
1483                 {
1484                         return Child.ConvertToInt ();
1485                 }
1486
1487                 public override Constant Increment()
1488                 {
1489                         return new EnumConstant (Child.Increment (), type);
1490                 }
1491
1492                 public override bool IsDefaultValue {
1493                         get {
1494                                 return Child.IsDefaultValue;
1495                         }
1496                 }
1497
1498                 public override bool IsZeroInteger {
1499                         get { return Child.IsZeroInteger; }
1500                 }
1501
1502                 public override bool IsNegative {
1503                         get {
1504                                 return Child.IsNegative;
1505                         }
1506                 }
1507
1508                 public override Constant Reduce(bool inCheckedContext, Type target_type)
1509                 {
1510                         if (Child.Type == target_type)
1511                                 return Child;
1512
1513                         return Child.Reduce (inCheckedContext, target_type);
1514                 }
1515
1516                 public override Constant ToType (Type type, Location loc)
1517                 {
1518                         if (Type == type) {
1519                                 // This is workaround of mono bug. It can be removed when the latest corlib spreads enough
1520                                 if (TypeManager.IsEnumType (type.UnderlyingSystemType))
1521                                         return this;
1522
1523                                 if (type.UnderlyingSystemType != Child.Type)
1524                                         Child = Child.ToType (type.UnderlyingSystemType, loc);
1525                                 return this;
1526                         }
1527
1528                         if (!Convert.ImplicitStandardConversionExists (this, type)){
1529                                 Error_ValueCannotBeConverted (loc, type, false);
1530                                 return null;
1531                         }
1532
1533                         return Child.ToType (type, loc);
1534                 }
1535
1536         }
1537
1538         /// <summary>
1539         ///   This kind of cast is used to encapsulate Value Types in objects.
1540         ///
1541         ///   The effect of it is to box the value type emitted by the previous
1542         ///   operation.
1543         /// </summary>
1544         public class BoxedCast : EmptyCast {
1545
1546                 public BoxedCast (Expression expr, Type target_type)
1547                         : base (expr, target_type)
1548                 {
1549                         eclass = ExprClass.Value;
1550                 }
1551                 
1552                 public override Expression DoResolve (EmitContext ec)
1553                 {
1554                         // This should never be invoked, we are born in fully
1555                         // initialized state.
1556
1557                         return this;
1558                 }
1559
1560                 public override void Emit (EmitContext ec)
1561                 {
1562                         base.Emit (ec);
1563                         
1564                         ec.ig.Emit (OpCodes.Box, child.Type);
1565                 }
1566         }
1567
1568         public class UnboxCast : EmptyCast {
1569                 public UnboxCast (Expression expr, Type return_type)
1570                         : base (expr, return_type)
1571                 {
1572                 }
1573
1574                 public override Expression DoResolve (EmitContext ec)
1575                 {
1576                         // This should never be invoked, we are born in fully
1577                         // initialized state.
1578
1579                         return this;
1580                 }
1581
1582                 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
1583                 {
1584                         if (right_side == EmptyExpression.LValueMemberAccess || right_side == EmptyExpression.LValueMemberOutAccess)
1585                                 Report.Error (445, loc, "Cannot modify the result of an unboxing conversion");
1586                         return base.DoResolveLValue (ec, right_side);
1587                 }
1588
1589                 public override void Emit (EmitContext ec)
1590                 {
1591                         Type t = type;
1592                         ILGenerator ig = ec.ig;
1593                         
1594                         base.Emit (ec);
1595                         if (t.IsGenericParameter || t.IsGenericType && t.IsValueType)
1596                                 ig.Emit (OpCodes.Unbox_Any, t);
1597                         else {
1598                                 ig.Emit (OpCodes.Unbox, t);
1599
1600                                 LoadFromPtr (ig, t);
1601                         }
1602                 }
1603         }
1604         
1605         /// <summary>
1606         ///   This is used to perform explicit numeric conversions.
1607         ///
1608         ///   Explicit numeric conversions might trigger exceptions in a checked
1609         ///   context, so they should generate the conv.ovf opcodes instead of
1610         ///   conv opcodes.
1611         /// </summary>
1612         public class ConvCast : EmptyCast {
1613                 public enum Mode : byte {
1614                         I1_U1, I1_U2, I1_U4, I1_U8, I1_CH,
1615                         U1_I1, U1_CH,
1616                         I2_I1, I2_U1, I2_U2, I2_U4, I2_U8, I2_CH,
1617                         U2_I1, U2_U1, U2_I2, U2_CH,
1618                         I4_I1, I4_U1, I4_I2, I4_U2, I4_U4, I4_U8, I4_CH,
1619                         U4_I1, U4_U1, U4_I2, U4_U2, U4_I4, U4_CH,
1620                         I8_I1, I8_U1, I8_I2, I8_U2, I8_I4, I8_U4, I8_U8, I8_CH,
1621                         U8_I1, U8_U1, U8_I2, U8_U2, U8_I4, U8_U4, U8_I8, U8_CH,
1622                         CH_I1, CH_U1, CH_I2,
1623                         R4_I1, R4_U1, R4_I2, R4_U2, R4_I4, R4_U4, R4_I8, R4_U8, R4_CH,
1624                         R8_I1, R8_U1, R8_I2, R8_U2, R8_I4, R8_U4, R8_I8, R8_U8, R8_CH, R8_R4
1625                 }
1626
1627                 Mode mode;
1628                 
1629                 public ConvCast (Expression child, Type return_type, Mode m)
1630                         : base (child, return_type)
1631                 {
1632                         mode = m;
1633                 }
1634
1635                 public override Expression DoResolve (EmitContext ec)
1636                 {
1637                         // This should never be invoked, we are born in fully
1638                         // initialized state.
1639
1640                         return this;
1641                 }
1642
1643                 public override string ToString ()
1644                 {
1645                         return String.Format ("ConvCast ({0}, {1})", mode, child);
1646                 }
1647                 
1648                 public override void Emit (EmitContext ec)
1649                 {
1650                         ILGenerator ig = ec.ig;
1651                         
1652                         base.Emit (ec);
1653
1654                         if (ec.CheckState){
1655                                 switch (mode){
1656                                 case Mode.I1_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1657                                 case Mode.I1_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1658                                 case Mode.I1_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1659                                 case Mode.I1_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1660                                 case Mode.I1_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1661
1662                                 case Mode.U1_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1663                                 case Mode.U1_CH: /* nothing */ break;
1664
1665                                 case Mode.I2_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1666                                 case Mode.I2_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1667                                 case Mode.I2_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1668                                 case Mode.I2_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1669                                 case Mode.I2_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1670                                 case Mode.I2_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1671
1672                                 case Mode.U2_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1673                                 case Mode.U2_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1674                                 case Mode.U2_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1675                                 case Mode.U2_CH: /* nothing */ break;
1676
1677                                 case Mode.I4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1678                                 case Mode.I4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1679                                 case Mode.I4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1680                                 case Mode.I4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1681                                 case Mode.I4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1682                                 case Mode.I4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1683                                 case Mode.I4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1684
1685                                 case Mode.U4_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1686                                 case Mode.U4_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1687                                 case Mode.U4_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1688                                 case Mode.U4_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1689                                 case Mode.U4_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1690                                 case Mode.U4_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1691
1692                                 case Mode.I8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1693                                 case Mode.I8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1694                                 case Mode.I8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1695                                 case Mode.I8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1696                                 case Mode.I8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1697                                 case Mode.I8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1698                                 case Mode.I8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1699                                 case Mode.I8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1700
1701                                 case Mode.U8_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1702                                 case Mode.U8_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1703                                 case Mode.U8_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1704                                 case Mode.U8_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1705                                 case Mode.U8_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
1706                                 case Mode.U8_U4: ig.Emit (OpCodes.Conv_Ovf_U4_Un); break;
1707                                 case Mode.U8_I8: ig.Emit (OpCodes.Conv_Ovf_I8_Un); break;
1708                                 case Mode.U8_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
1709
1710                                 case Mode.CH_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
1711                                 case Mode.CH_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
1712                                 case Mode.CH_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
1713
1714                                 case Mode.R4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1715                                 case Mode.R4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1716                                 case Mode.R4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1717                                 case Mode.R4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1718                                 case Mode.R4_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1719                                 case Mode.R4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1720                                 case Mode.R4_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1721                                 case Mode.R4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1722                                 case Mode.R4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1723
1724                                 case Mode.R8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
1725                                 case Mode.R8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
1726                                 case Mode.R8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
1727                                 case Mode.R8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1728                                 case Mode.R8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
1729                                 case Mode.R8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
1730                                 case Mode.R8_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
1731                                 case Mode.R8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
1732                                 case Mode.R8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
1733                                 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1734                                 }
1735                         } else {
1736                                 switch (mode){
1737                                 case Mode.I1_U1: ig.Emit (OpCodes.Conv_U1); break;
1738                                 case Mode.I1_U2: ig.Emit (OpCodes.Conv_U2); break;
1739                                 case Mode.I1_U4: ig.Emit (OpCodes.Conv_U4); break;
1740                                 case Mode.I1_U8: ig.Emit (OpCodes.Conv_I8); break;
1741                                 case Mode.I1_CH: ig.Emit (OpCodes.Conv_U2); break;
1742
1743                                 case Mode.U1_I1: ig.Emit (OpCodes.Conv_I1); break;
1744                                 case Mode.U1_CH: ig.Emit (OpCodes.Conv_U2); break;
1745
1746                                 case Mode.I2_I1: ig.Emit (OpCodes.Conv_I1); break;
1747                                 case Mode.I2_U1: ig.Emit (OpCodes.Conv_U1); break;
1748                                 case Mode.I2_U2: ig.Emit (OpCodes.Conv_U2); break;
1749                                 case Mode.I2_U4: ig.Emit (OpCodes.Conv_U4); break;
1750                                 case Mode.I2_U8: ig.Emit (OpCodes.Conv_I8); break;
1751                                 case Mode.I2_CH: ig.Emit (OpCodes.Conv_U2); break;
1752
1753                                 case Mode.U2_I1: ig.Emit (OpCodes.Conv_I1); break;
1754                                 case Mode.U2_U1: ig.Emit (OpCodes.Conv_U1); break;
1755                                 case Mode.U2_I2: ig.Emit (OpCodes.Conv_I2); break;
1756                                 case Mode.U2_CH: /* nothing */ break;
1757
1758                                 case Mode.I4_I1: ig.Emit (OpCodes.Conv_I1); break;
1759                                 case Mode.I4_U1: ig.Emit (OpCodes.Conv_U1); break;
1760                                 case Mode.I4_I2: ig.Emit (OpCodes.Conv_I2); break;
1761                                 case Mode.I4_U4: /* nothing */ break;
1762                                 case Mode.I4_U2: ig.Emit (OpCodes.Conv_U2); break;
1763                                 case Mode.I4_U8: ig.Emit (OpCodes.Conv_I8); break;
1764                                 case Mode.I4_CH: ig.Emit (OpCodes.Conv_U2); break;
1765
1766                                 case Mode.U4_I1: ig.Emit (OpCodes.Conv_I1); break;
1767                                 case Mode.U4_U1: ig.Emit (OpCodes.Conv_U1); break;
1768                                 case Mode.U4_I2: ig.Emit (OpCodes.Conv_I2); break;
1769                                 case Mode.U4_U2: ig.Emit (OpCodes.Conv_U2); break;
1770                                 case Mode.U4_I4: /* nothing */ break;
1771                                 case Mode.U4_CH: ig.Emit (OpCodes.Conv_U2); break;
1772
1773                                 case Mode.I8_I1: ig.Emit (OpCodes.Conv_I1); break;
1774                                 case Mode.I8_U1: ig.Emit (OpCodes.Conv_U1); break;
1775                                 case Mode.I8_I2: ig.Emit (OpCodes.Conv_I2); break;
1776                                 case Mode.I8_U2: ig.Emit (OpCodes.Conv_U2); break;
1777                                 case Mode.I8_I4: ig.Emit (OpCodes.Conv_I4); break;
1778                                 case Mode.I8_U4: ig.Emit (OpCodes.Conv_U4); break;
1779                                 case Mode.I8_U8: /* nothing */ break;
1780                                 case Mode.I8_CH: ig.Emit (OpCodes.Conv_U2); break;
1781
1782                                 case Mode.U8_I1: ig.Emit (OpCodes.Conv_I1); break;
1783                                 case Mode.U8_U1: ig.Emit (OpCodes.Conv_U1); break;
1784                                 case Mode.U8_I2: ig.Emit (OpCodes.Conv_I2); break;
1785                                 case Mode.U8_U2: ig.Emit (OpCodes.Conv_U2); break;
1786                                 case Mode.U8_I4: ig.Emit (OpCodes.Conv_I4); break;
1787                                 case Mode.U8_U4: ig.Emit (OpCodes.Conv_U4); break;
1788                                 case Mode.U8_I8: /* nothing */ break;
1789                                 case Mode.U8_CH: ig.Emit (OpCodes.Conv_U2); break;
1790
1791                                 case Mode.CH_I1: ig.Emit (OpCodes.Conv_I1); break;
1792                                 case Mode.CH_U1: ig.Emit (OpCodes.Conv_U1); break;
1793                                 case Mode.CH_I2: ig.Emit (OpCodes.Conv_I2); break;
1794
1795                                 case Mode.R4_I1: ig.Emit (OpCodes.Conv_I1); break;
1796                                 case Mode.R4_U1: ig.Emit (OpCodes.Conv_U1); break;
1797                                 case Mode.R4_I2: ig.Emit (OpCodes.Conv_I2); break;
1798                                 case Mode.R4_U2: ig.Emit (OpCodes.Conv_U2); break;
1799                                 case Mode.R4_I4: ig.Emit (OpCodes.Conv_I4); break;
1800                                 case Mode.R4_U4: ig.Emit (OpCodes.Conv_U4); break;
1801                                 case Mode.R4_I8: ig.Emit (OpCodes.Conv_I8); break;
1802                                 case Mode.R4_U8: ig.Emit (OpCodes.Conv_U8); break;
1803                                 case Mode.R4_CH: ig.Emit (OpCodes.Conv_U2); break;
1804
1805                                 case Mode.R8_I1: ig.Emit (OpCodes.Conv_I1); break;
1806                                 case Mode.R8_U1: ig.Emit (OpCodes.Conv_U1); break;
1807                                 case Mode.R8_I2: ig.Emit (OpCodes.Conv_I2); break;
1808                                 case Mode.R8_U2: ig.Emit (OpCodes.Conv_U2); break;
1809                                 case Mode.R8_I4: ig.Emit (OpCodes.Conv_I4); break;
1810                                 case Mode.R8_U4: ig.Emit (OpCodes.Conv_U4); break;
1811                                 case Mode.R8_I8: ig.Emit (OpCodes.Conv_I8); break;
1812                                 case Mode.R8_U8: ig.Emit (OpCodes.Conv_U8); break;
1813                                 case Mode.R8_CH: ig.Emit (OpCodes.Conv_U2); break;
1814                                 case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
1815                                 }
1816                         }
1817                 }
1818         }
1819         
1820         public class OpcodeCast : EmptyCast {
1821                 OpCode op, op2;
1822                 bool second_valid;
1823                 
1824                 public OpcodeCast (Expression child, Type return_type, OpCode op)
1825                         : base (child, return_type)
1826                         
1827                 {
1828                         this.op = op;
1829                         second_valid = false;
1830                 }
1831
1832                 public OpcodeCast (Expression child, Type return_type, OpCode op, OpCode op2)
1833                         : base (child, return_type)
1834                         
1835                 {
1836                         this.op = op;
1837                         this.op2 = op2;
1838                         second_valid = true;
1839                 }
1840
1841                 public override Expression DoResolve (EmitContext ec)
1842                 {
1843                         // This should never be invoked, we are born in fully
1844                         // initialized state.
1845
1846                         return this;
1847                 }
1848
1849                 public override void Emit (EmitContext ec)
1850                 {
1851                         base.Emit (ec);
1852                         ec.ig.Emit (op);
1853
1854                         if (second_valid)
1855                                 ec.ig.Emit (op2);
1856                 }                       
1857         }
1858
1859         /// <summary>
1860         ///   This kind of cast is used to encapsulate a child and cast it
1861         ///   to the class requested
1862         /// </summary>
1863         public class ClassCast : EmptyCast {
1864                 public ClassCast (Expression child, Type return_type)
1865                         : base (child, return_type)
1866                         
1867                 {
1868                 }
1869
1870                 public override Expression DoResolve (EmitContext ec)
1871                 {
1872                         // This should never be invoked, we are born in fully
1873                         // initialized state.
1874
1875                         return this;
1876                 }
1877
1878                 public override void Emit (EmitContext ec)
1879                 {
1880                         base.Emit (ec);
1881
1882                         if (child.Type.IsGenericParameter)
1883                                 ec.ig.Emit (OpCodes.Box, child.Type);
1884
1885                         if (type.IsGenericParameter)
1886                                 ec.ig.Emit (OpCodes.Unbox_Any, type);
1887                         else
1888                                 ec.ig.Emit (OpCodes.Castclass, type);
1889                 }
1890         }
1891         
1892         /// <summary>
1893         ///   SimpleName expressions are formed of a single word and only happen at the beginning 
1894         ///   of a dotted-name.
1895         /// </summary>
1896         public class SimpleName : Expression {
1897                 public string Name;
1898                 public readonly TypeArguments Arguments;
1899                 bool in_transit;
1900
1901                 public SimpleName (string name, Location l)
1902                 {
1903                         Name = name;
1904                         loc = l;
1905                 }
1906
1907                 public SimpleName (string name, TypeArguments args, Location l)
1908                 {
1909                         Name = name;
1910                         Arguments = args;
1911                         loc = l;
1912                 }
1913
1914                 public SimpleName (string name, TypeParameter[] type_params, Location l)
1915                 {
1916                         Name = name;
1917                         loc = l;
1918
1919                         Arguments = new TypeArguments (l);
1920                         foreach (TypeParameter type_param in type_params)
1921                                 Arguments.Add (new TypeParameterExpr (type_param, l));
1922                 }
1923
1924                 public static string RemoveGenericArity (string name)
1925                 {
1926                         int start = 0;
1927                         StringBuilder sb = new StringBuilder ();
1928                         while (start < name.Length) {
1929                                 int pos = name.IndexOf ('`', start);
1930                                 if (pos < 0) {
1931                                         sb.Append (name.Substring (start));
1932                                         break;
1933                                 }
1934
1935                                 sb.Append (name.Substring (start, pos-start));
1936
1937                                 pos++;
1938                                 while ((pos < name.Length) && Char.IsNumber (name [pos]))
1939                                         pos++;
1940
1941                                 start = pos;
1942                         }
1943
1944                         return sb.ToString ();
1945                 }
1946
1947                 public SimpleName GetMethodGroup ()
1948                 {
1949                         return new SimpleName (RemoveGenericArity (Name), Arguments, loc);
1950                 }
1951
1952                 public static void Error_ObjectRefRequired (EmitContext ec, Location l, string name)
1953                 {
1954                         if (ec.IsFieldInitializer)
1955                                 Report.Error (236, l,
1956                                         "A field initializer cannot reference the nonstatic field, method, or property `{0}'",
1957                                         name);
1958                         else
1959                                 Report.Error (
1960                                         120, l, "`{0}': An object reference is required for the nonstatic field, method or property",
1961                                         name);
1962                 }
1963
1964                 public bool IdenticalNameAndTypeName (EmitContext ec, Expression resolved_to, Location loc)
1965                 {
1966                         return resolved_to != null && resolved_to.Type != null && 
1967                                 resolved_to.Type.Name == Name &&
1968                                 (ec.DeclContainer.LookupType (Name, loc, /* ignore_cs0104 = */ true) != null);
1969                 }
1970
1971                 public override Expression DoResolve (EmitContext ec)
1972                 {
1973                         return SimpleNameResolve (ec, null, false);
1974                 }
1975
1976                 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
1977                 {
1978                         return SimpleNameResolve (ec, right_side, false);
1979                 }
1980                 
1981
1982                 public Expression DoResolve (EmitContext ec, bool intermediate)
1983                 {
1984                         return SimpleNameResolve (ec, null, intermediate);
1985                 }
1986
1987                 private bool IsNestedChild (Type t, Type parent)
1988                 {
1989                         if (parent == null)
1990                                 return false;
1991
1992                         while (parent != null) {
1993                                 parent = TypeManager.DropGenericTypeArguments (parent);
1994                                 if (TypeManager.IsNestedChildOf (t, parent))
1995                                         return true;
1996
1997                                 parent = parent.BaseType;
1998                         }
1999
2000                         return false;
2001                 }
2002
2003                 FullNamedExpression ResolveNested (IResolveContext ec, Type t)
2004                 {
2005                         if (!t.IsGenericTypeDefinition)
2006                                 return null;
2007
2008                         DeclSpace ds = ec.DeclContainer;
2009                         while (ds != null) {
2010                                 if (IsNestedChild (t, ds.TypeBuilder))
2011                                         break;
2012
2013                                 ds = ds.Parent;
2014                         }
2015
2016                         if (ds == null)
2017                                 return null;
2018
2019                         Type[] gen_params = t.GetGenericArguments ();
2020
2021                         int arg_count = Arguments != null ? Arguments.Count : 0;
2022
2023                         for (; (ds != null) && ds.IsGeneric; ds = ds.Parent) {
2024                                 if (arg_count + ds.CountTypeParameters == gen_params.Length) {
2025                                         TypeArguments new_args = new TypeArguments (loc);
2026                                         foreach (TypeParameter param in ds.TypeParameters)
2027                                                 new_args.Add (new TypeParameterExpr (param, loc));
2028
2029                                         if (Arguments != null)
2030                                                 new_args.Add (Arguments);
2031
2032                                         return new ConstructedType (t, new_args, loc);
2033                                 }
2034                         }
2035
2036                         return null;
2037                 }
2038
2039                 public override FullNamedExpression ResolveAsTypeStep (IResolveContext ec, bool silent)
2040                 {
2041                         FullNamedExpression fne = ec.DeclContainer.LookupGeneric (Name, loc);
2042                         if (fne != null)
2043                                 return fne.ResolveAsTypeStep (ec, silent);
2044
2045                         int errors = Report.Errors;
2046                         fne = ec.DeclContainer.LookupType (Name, loc, /*ignore_cs0104=*/ false);
2047
2048                         if (fne != null) {
2049                                 if (fne.Type == null)
2050                                         return fne;
2051
2052                                 FullNamedExpression nested = ResolveNested (ec, fne.Type);
2053                                 if (nested != null)
2054                                         return nested.ResolveAsTypeStep (ec, false);
2055
2056                                 if (Arguments != null) {
2057                                         ConstructedType ct = new ConstructedType (fne, Arguments, loc);
2058                                         return ct.ResolveAsTypeStep (ec, false);
2059                                 }
2060
2061                                 return fne;
2062                         }
2063
2064                         if (silent || errors != Report.Errors)
2065                                 return null;
2066
2067                         MemberCore mc = ec.DeclContainer.GetDefinition (Name);
2068                         if (mc != null) {
2069                                 Error_UnexpectedKind (ec.DeclContainer, "type", GetMemberType (mc), loc);
2070                                 return null;
2071                         }
2072
2073                         string ns = ec.DeclContainer.NamespaceEntry.NS.Name;
2074                         string fullname = (ns.Length > 0) ? ns + "." + Name : Name;
2075                         foreach (Assembly a in RootNamespace.Global.Assemblies) {
2076                                 Type type = a.GetType (fullname);
2077                                 if (type != null) {
2078                                         Report.SymbolRelatedToPreviousError (type);
2079                                         Expression.ErrorIsInaccesible (loc, fullname);
2080                                         return null;
2081                                 }
2082                         }
2083
2084                         NamespaceEntry.Error_NamespaceNotFound (loc, Name);
2085                         return null;
2086                 }
2087
2088                 // TODO: I am still not convinced about this. If someone else will need it
2089                 // implement this as virtual property in MemberCore hierarchy
2090                 string GetMemberType (MemberCore mc)
2091                 {
2092                         if (mc is PropertyBase)
2093                                 return "property";
2094                         if (mc is Indexer)
2095                                 return "indexer";
2096                         if (mc is FieldBase)
2097                                 return "field";
2098                         if (mc is MethodCore)
2099                                 return "method";
2100                         if (mc is EnumMember)
2101                                 return "enum";
2102
2103                         return "type";
2104                 }
2105
2106                 Expression SimpleNameResolve (EmitContext ec, Expression right_side, bool intermediate)
2107                 {
2108                         if (in_transit)
2109                                 return null;
2110                         in_transit = true;
2111
2112                         Expression e = DoSimpleNameResolve (ec, right_side, intermediate);
2113                         if (e == null)
2114                                 return null;
2115
2116                         if (ec.CurrentBlock == null || ec.CurrentBlock.CheckInvariantMeaningInBlock (Name, e, Location))
2117                                 return e;
2118
2119                         return null;
2120                 }
2121
2122                 /// <remarks>
2123                 ///   7.5.2: Simple Names. 
2124                 ///
2125                 ///   Local Variables and Parameters are handled at
2126                 ///   parse time, so they never occur as SimpleNames.
2127                 ///
2128                 ///   The `intermediate' flag is used by MemberAccess only
2129                 ///   and it is used to inform us that it is ok for us to 
2130                 ///   avoid the static check, because MemberAccess might end
2131                 ///   up resolving the Name as a Type name and the access as
2132                 ///   a static type access.
2133                 ///
2134                 ///   ie: Type Type; .... { Type.GetType (""); }
2135                 ///
2136                 ///   Type is both an instance variable and a Type;  Type.GetType
2137                 ///   is the static method not an instance method of type.
2138                 /// </remarks>
2139                 Expression DoSimpleNameResolve (EmitContext ec, Expression right_side, bool intermediate)
2140                 {
2141                         Expression e = null;
2142
2143                         //
2144                         // Stage 1: Performed by the parser (binding to locals or parameters).
2145                         //
2146                         Block current_block = ec.CurrentBlock;
2147                         if (current_block != null){
2148                                 LocalInfo vi = current_block.GetLocalInfo (Name);
2149                                 if (vi != null){
2150                                         if (Arguments != null) {
2151                                                 Report.Error (307, loc,
2152                                                               "The variable `{0}' cannot be used with type arguments",
2153                                                               Name);
2154                                                 return null;
2155                                         }
2156
2157                                         LocalVariableReference var = new LocalVariableReference (ec.CurrentBlock, Name, loc);
2158                                         if (right_side != null) {
2159                                                 return var.ResolveLValue (ec, right_side, loc);
2160                                         } else {
2161                                                 ResolveFlags rf = ResolveFlags.VariableOrValue;
2162                                                 if (intermediate)
2163                                                         rf |= ResolveFlags.DisableFlowAnalysis;
2164                                                 return var.Resolve (ec, rf);
2165                                         }
2166                                 }
2167
2168                                 ParameterReference pref = current_block.Toplevel.GetParameterReference (Name, loc);
2169                                 if (pref != null) {
2170                                         if (Arguments != null) {
2171                                                 Report.Error (307, loc,
2172                                                               "The variable `{0}' cannot be used with type arguments",
2173                                                               Name);
2174                                                 return null;
2175                                         }
2176
2177                                         if (right_side != null)
2178                                                 return pref.ResolveLValue (ec, right_side, loc);
2179                                         else
2180                                                 return pref.Resolve (ec);
2181                                 }
2182                         }
2183                         
2184                         //
2185                         // Stage 2: Lookup members 
2186                         //
2187
2188                         DeclSpace lookup_ds = ec.DeclContainer;
2189                         Type almost_matched_type = null;
2190                         ArrayList almost_matched = null;
2191                         do {
2192                                 if (lookup_ds.TypeBuilder == null)
2193                                         break;
2194
2195                                 e = MemberLookup (ec.ContainerType, lookup_ds.TypeBuilder, Name, loc);
2196                                 if (e != null)
2197                                         break;
2198
2199                                 if (almost_matched == null && almostMatchedMembers.Count > 0) {
2200                                         almost_matched_type = lookup_ds.TypeBuilder;
2201                                         almost_matched = (ArrayList) almostMatchedMembers.Clone ();
2202                                 }
2203
2204                                 lookup_ds =lookup_ds.Parent;
2205                         } while (lookup_ds != null);
2206
2207                         if (e == null && ec.ContainerType != null)
2208                                 e = MemberLookup (ec.ContainerType, ec.ContainerType, Name, loc);
2209
2210                         if (e == null) {
2211                                 if (almost_matched == null && almostMatchedMembers.Count > 0) {
2212                                         almost_matched_type = ec.ContainerType;
2213                                         almost_matched = (ArrayList) almostMatchedMembers.Clone ();
2214                                 }
2215                                 e = ResolveAsTypeStep (ec, true);
2216                         }
2217
2218                         if (e == null) {
2219                                 if (almost_matched != null)
2220                                         almostMatchedMembers = almost_matched;
2221                                 if (almost_matched_type == null)
2222                                         almost_matched_type = ec.ContainerType;
2223                                 MemberLookupFailed (ec.ContainerType, null, almost_matched_type, ((SimpleName) this).Name, ec.DeclContainer.Name, true, loc);
2224                                 return null;
2225                         }
2226
2227                         if (e is TypeExpr) {
2228                                 if (Arguments == null)
2229                                         return e;
2230
2231                                 ConstructedType ct = new ConstructedType (
2232                                         (FullNamedExpression) e, Arguments, loc);
2233                                 return ct.ResolveAsTypeStep (ec, false);
2234                         }
2235
2236                         if (e is MemberExpr) {
2237                                 MemberExpr me = (MemberExpr) e;
2238
2239                                 Expression left;
2240                                 if (me.IsInstance) {
2241                                         if (ec.IsStatic || ec.IsFieldInitializer) {
2242                                                 //
2243                                                 // Note that an MemberExpr can be both IsInstance and IsStatic.
2244                                                 // An unresolved MethodGroupExpr can contain both kinds of methods
2245                                                 // and each predicate is true if the MethodGroupExpr contains
2246                                                 // at least one of that kind of method.
2247                                                 //
2248
2249                                                 if (!me.IsStatic &&
2250                                                     (!intermediate || !IdenticalNameAndTypeName (ec, me, loc))) {
2251                                                         Error_ObjectRefRequired (ec, loc, me.GetSignatureForError ());
2252                                                         return EmptyExpression.Null;
2253                                                 }
2254
2255                                                 //
2256                                                 // Pass the buck to MemberAccess and Invocation.
2257                                                 //
2258                                                 left = EmptyExpression.Null;
2259                                         } else {
2260                                                 left = ec.GetThis (loc);
2261                                         }
2262                                 } else {
2263                                         left = new TypeExpression (ec.ContainerType, loc);
2264                                 }
2265
2266                                 e = me.ResolveMemberAccess (ec, left, loc, null);
2267                                 if (e == null)
2268                                         return null;
2269
2270                                 me = e as MemberExpr;
2271                                 if (me == null)
2272                                         return e;
2273
2274                                 if (Arguments != null) {
2275                                         MethodGroupExpr mg = me as MethodGroupExpr;
2276                                         if (mg == null)
2277                                                 return null;
2278
2279                                         return mg.ResolveGeneric (ec, Arguments);
2280                                 }
2281
2282                                 if (!me.IsStatic &&
2283                                     TypeManager.IsNestedFamilyAccessible (me.InstanceExpression.Type, me.DeclaringType) &&
2284                                     me.InstanceExpression.Type != me.DeclaringType &&
2285                                     !TypeManager.IsFamilyAccessible (me.InstanceExpression.Type, me.DeclaringType) &&
2286                                     (!intermediate || !IdenticalNameAndTypeName (ec, e, loc))) {
2287                                         Report.Error (38, loc, "Cannot access a nonstatic member of outer type `{0}' via nested type `{1}'",
2288                                                 TypeManager.CSharpName (me.DeclaringType), TypeManager.CSharpName (me.InstanceExpression.Type));
2289                                         return null;
2290                                 }
2291
2292                                 return (right_side != null)
2293                                         ? me.DoResolveLValue (ec, right_side)
2294                                         : me.DoResolve (ec);
2295                         }
2296
2297                         return e;
2298                 }
2299                 
2300                 public override void Emit (EmitContext ec)
2301                 {
2302                         //
2303                         // If this is ever reached, then we failed to
2304                         // find the name as a namespace
2305                         //
2306
2307                         Error (103, "The name `" + Name +
2308                                "' does not exist in the class `" +
2309                                ec.DeclContainer.Name + "'");
2310                 }
2311
2312                 public override string ToString ()
2313                 {
2314                         return Name;
2315                 }
2316
2317                 public override string GetSignatureForError ()
2318                 {
2319                         return Name;
2320                 }
2321         }
2322
2323         /// <summary>
2324         ///   Represents a namespace or a type.  The name of the class was inspired by
2325         ///   section 10.8.1 (Fully Qualified Names).
2326         /// </summary>
2327         public abstract class FullNamedExpression : Expression {
2328                 public override FullNamedExpression ResolveAsTypeStep (IResolveContext ec, bool silent)
2329                 {
2330                         return this;
2331                 }
2332
2333                 public abstract string FullName {
2334                         get;
2335                 }
2336         }
2337         
2338         /// <summary>
2339         ///   Expression that evaluates to a type
2340         /// </summary>
2341         public abstract class TypeExpr : FullNamedExpression {
2342                 override public FullNamedExpression ResolveAsTypeStep (IResolveContext ec, bool silent)
2343                 {
2344                         TypeExpr t = DoResolveAsTypeStep (ec);
2345                         if (t == null)
2346                                 return null;
2347
2348                         eclass = ExprClass.Type;
2349                         return t;
2350                 }
2351
2352                 override public Expression DoResolve (EmitContext ec)
2353                 {
2354                         return ResolveAsTypeTerminal (ec, false);
2355                 }
2356
2357                 override public void Emit (EmitContext ec)
2358                 {
2359                         throw new Exception ("Should never be called");
2360                 }
2361
2362                 public virtual bool CheckAccessLevel (DeclSpace ds)
2363                 {
2364                         return ds.CheckAccessLevel (Type);
2365                 }
2366
2367                 public virtual bool AsAccessible (DeclSpace ds, int flags)
2368                 {
2369                         return ds.AsAccessible (Type, flags);
2370                 }
2371
2372                 public virtual bool IsClass {
2373                         get { return Type.IsClass; }
2374                 }
2375
2376                 public virtual bool IsValueType {
2377                         get { return Type.IsValueType; }
2378                 }
2379
2380                 public virtual bool IsInterface {
2381                         get { return Type.IsInterface; }
2382                 }
2383
2384                 public virtual bool IsSealed {
2385                         get { return Type.IsSealed; }
2386                 }
2387
2388                 public virtual bool CanInheritFrom ()
2389                 {
2390                         if (Type == TypeManager.enum_type ||
2391                             (Type == TypeManager.value_type && RootContext.StdLib) ||
2392                             Type == TypeManager.multicast_delegate_type ||
2393                             Type == TypeManager.delegate_type ||
2394                             Type == TypeManager.array_type)
2395                                 return false;
2396
2397                         return true;
2398                 }
2399
2400                 protected abstract TypeExpr DoResolveAsTypeStep (IResolveContext ec);
2401
2402                 public abstract string Name {
2403                         get;
2404                 }
2405
2406                 public override bool Equals (object obj)
2407                 {
2408                         TypeExpr tobj = obj as TypeExpr;
2409                         if (tobj == null)
2410                                 return false;
2411
2412                         return Type == tobj.Type;
2413                 }
2414
2415                 public override int GetHashCode ()
2416                 {
2417                         return Type.GetHashCode ();
2418                 }
2419                 
2420                 public override string ToString ()
2421                 {
2422                         return Name;
2423                 }
2424         }
2425
2426         /// <summary>
2427         ///   Fully resolved Expression that already evaluated to a type
2428         /// </summary>
2429         public class TypeExpression : TypeExpr {
2430                 public TypeExpression (Type t, Location l)
2431                 {
2432                         Type = t;
2433                         eclass = ExprClass.Type;
2434                         loc = l;
2435                 }
2436
2437                 protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
2438                 {
2439                         return this;
2440                 }
2441
2442                 public override TypeExpr ResolveAsTypeTerminal (IResolveContext ec, bool silent)
2443                 {
2444                         return this;
2445                 }
2446
2447                 public override string Name {
2448                         get { return Type.ToString (); }
2449                 }
2450
2451                 public override string FullName {
2452                         get { return Type.FullName; }
2453                 }
2454         }
2455
2456         /// <summary>
2457         ///   Used to create types from a fully qualified name.  These are just used
2458         ///   by the parser to setup the core types.  A TypeLookupExpression is always
2459         ///   classified as a type.
2460         /// </summary>
2461         public sealed class TypeLookupExpression : TypeExpr {
2462                 readonly string name;
2463                 
2464                 public TypeLookupExpression (string name)
2465                 {
2466                         this.name = name;
2467                         eclass = ExprClass.Type;
2468                 }
2469
2470                 public override TypeExpr ResolveAsTypeTerminal (IResolveContext ec, bool silent)
2471                 {
2472                         // It's null for corlib compilation only
2473                         if (type == null)
2474                                 return DoResolveAsTypeStep (ec);
2475
2476                         return this;
2477                 }
2478
2479                 static readonly char [] dot_array = { '.' };
2480                 protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
2481                 {
2482                         // If name is of the form `N.I', first lookup `N', then search a member `I' in it.
2483                         string rest = null;
2484                         string lookup_name = name;
2485                         int pos = name.IndexOf ('.');
2486                         if (pos >= 0) {
2487                                 rest = name.Substring (pos + 1);
2488                                 lookup_name = name.Substring (0, pos);
2489                         }
2490
2491                         FullNamedExpression resolved = RootNamespace.Global.Lookup (ec.DeclContainer, lookup_name, Location.Null);
2492
2493                         if (resolved != null && rest != null) {
2494                                 // Now handle the rest of the the name.
2495                                 string [] elements = rest.Split (dot_array);
2496                                 string element;
2497                                 int count = elements.Length;
2498                                 int i = 0;
2499                                 while (i < count && resolved != null && resolved is Namespace) {
2500                                         Namespace ns = resolved as Namespace;
2501                                         element = elements [i++];
2502                                         lookup_name += "." + element;
2503                                         resolved = ns.Lookup (ec.DeclContainer, element, Location.Null);
2504                                 }
2505
2506                                 if (resolved != null && resolved is TypeExpr) {
2507                                         Type t = ((TypeExpr) resolved).Type;
2508                                         while (t != null) {
2509                                                 if (!ec.DeclContainer.CheckAccessLevel (t)) {
2510                                                         resolved = null;
2511                                                         lookup_name = t.FullName;
2512                                                         break;
2513                                                 }
2514                                                 if (i == count) {
2515                                                         type = t;
2516                                                         return this;
2517                                                 }
2518                                                 t = TypeManager.GetNestedType (t, elements [i++]);
2519                                         }
2520                                 }
2521                         }
2522
2523                         if (resolved == null) {
2524                                 NamespaceEntry.Error_NamespaceNotFound (loc, lookup_name);
2525                                 return null;
2526                         }
2527
2528                         if (!(resolved is TypeExpr)) {
2529                                 resolved.Error_UnexpectedKind (ec.DeclContainer, "type", loc);
2530                                 return null;
2531                         }
2532
2533                         type = resolved.Type;
2534                         return this;
2535                 }
2536
2537                 public override string Name {
2538                         get { return name; }
2539                 }
2540
2541                 public override string FullName {
2542                         get { return name; }
2543                 }
2544         }
2545
2546         /// <summary>
2547         ///   Represents an "unbound generic type", ie. typeof (Foo<>).
2548         ///   See 14.5.11.
2549         /// </summary>
2550         public class UnboundTypeExpression : TypeExpr
2551         {
2552                 MemberName name;
2553
2554                 public UnboundTypeExpression (MemberName name, Location l)
2555                 {
2556                         this.name = name;
2557                         loc = l;
2558                 }
2559
2560                 protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
2561                 {
2562                         Expression expr;
2563                         if (name.Left != null) {
2564                                 Expression lexpr = name.Left.GetTypeExpression ();
2565                                 expr = new MemberAccess (lexpr, name.Basename);
2566                         } else {
2567                                 expr = new SimpleName (name.Basename, loc);
2568                         }
2569
2570                         FullNamedExpression fne = expr.ResolveAsTypeStep (ec, false);
2571                         if (fne == null)
2572                                 return null;
2573
2574                         type = fne.Type;
2575                         return new TypeExpression (type, loc);
2576                 }
2577
2578                 public override string Name {
2579                         get { return name.FullName; }
2580                 }
2581
2582                 public override string FullName {
2583                         get { return name.FullName; }
2584                 }
2585         }
2586
2587         public class TypeAliasExpression : TypeExpr {
2588                 FullNamedExpression alias;
2589                 TypeExpr texpr;
2590                 TypeArguments args;
2591                 string name;
2592
2593                 public TypeAliasExpression (FullNamedExpression alias, TypeArguments args, Location l)
2594                 {
2595                         this.alias = alias;
2596                         this.args = args;
2597                         loc = l;
2598
2599                         eclass = ExprClass.Type;
2600                         if (args != null)
2601                                 name = alias.FullName + "<" + args.ToString () + ">";
2602                         else
2603                                 name = alias.FullName;
2604                 }
2605
2606                 public override string Name {
2607                         get { return alias.FullName; }
2608                 }
2609
2610                 public override string FullName {
2611                         get { return name; }
2612                 }
2613
2614                 protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
2615                 {
2616                         texpr = alias.ResolveAsTypeTerminal (ec, false);
2617                         if (texpr == null)
2618                                 return null;
2619
2620                         Type type = texpr.Type;
2621                         int num_args = TypeManager.GetNumberOfTypeArguments (type);
2622
2623                         if (args != null) {
2624                                 if (num_args == 0) {
2625                                         Report.Error (308, loc,
2626                                                       "The non-generic type `{0}' cannot " +
2627                                                       "be used with type arguments.",
2628                                                       TypeManager.CSharpName (type));
2629                                         return null;
2630                                 }
2631
2632                                 ConstructedType ctype = new ConstructedType (type, args, loc);
2633                                 return ctype.ResolveAsTypeTerminal (ec, false);
2634                         } else if (num_args > 0) {
2635                                 Report.Error (305, loc,
2636                                               "Using the generic type `{0}' " +
2637                                               "requires {1} type arguments",
2638                                               TypeManager.CSharpName (type), num_args.ToString ());
2639                                 return null;
2640                         }
2641
2642                         return texpr;
2643                 }
2644
2645                 public override bool CheckAccessLevel (DeclSpace ds)
2646                 {
2647                         return texpr.CheckAccessLevel (ds);
2648                 }
2649
2650                 public override bool AsAccessible (DeclSpace ds, int flags)
2651                 {
2652                         return texpr.AsAccessible (ds, flags);
2653                 }
2654
2655                 public override bool IsClass {
2656                         get { return texpr.IsClass; }
2657                 }
2658
2659                 public override bool IsValueType {
2660                         get { return texpr.IsValueType; }
2661                 }
2662
2663                 public override bool IsInterface {
2664                         get { return texpr.IsInterface; }
2665                 }
2666
2667                 public override bool IsSealed {
2668                         get { return texpr.IsSealed; }
2669                 }
2670         }
2671
2672         /// <summary>
2673         ///   This class denotes an expression which evaluates to a member
2674         ///   of a struct or a class.
2675         /// </summary>
2676         public abstract class MemberExpr : Expression
2677         {
2678                 /// <summary>
2679                 ///   The name of this member.
2680                 /// </summary>
2681                 public abstract string Name {
2682                         get;
2683                 }
2684
2685                 /// <summary>
2686                 ///   Whether this is an instance member.
2687                 /// </summary>
2688                 public abstract bool IsInstance {
2689                         get;
2690                 }
2691
2692                 /// <summary>
2693                 ///   Whether this is a static member.
2694                 /// </summary>
2695                 public abstract bool IsStatic {
2696                         get;
2697                 }
2698
2699                 /// <summary>
2700                 ///   The type which declares this member.
2701                 /// </summary>
2702                 public abstract Type DeclaringType {
2703                         get;
2704                 }
2705
2706                 /// <summary>
2707                 ///   The instance expression associated with this member, if it's a
2708                 ///   non-static member.
2709                 /// </summary>
2710                 public Expression InstanceExpression;
2711
2712                 public static void error176 (Location loc, string name)
2713                 {
2714                         Report.Error (176, loc, "Static member `{0}' cannot be accessed " +
2715                                       "with an instance reference, qualify it with a type name instead", name);
2716                 }
2717
2718                 // TODO: possible optimalization
2719                 // Cache resolved constant result in FieldBuilder <-> expression map
2720                 public virtual Expression ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
2721                                                                SimpleName original)
2722                 {
2723                         //
2724                         // Precondition:
2725                         //   original == null || original.Resolve (...) ==> left
2726                         //
2727
2728                         if (left is TypeExpr) {
2729                                 if (!IsStatic) {
2730                                         SimpleName.Error_ObjectRefRequired (ec, loc, GetSignatureForError ());
2731                                         return null;
2732                                 }
2733
2734                                 return this;
2735                         }
2736                                 
2737                         if (!IsInstance) {
2738                                 if (original != null && original.IdenticalNameAndTypeName (ec, left, loc))
2739                                         return this;
2740
2741                                 error176 (loc, GetSignatureForError ());
2742                                 return null;
2743                         }
2744
2745                         InstanceExpression = left;
2746
2747                         return this;
2748                 }
2749
2750                 protected void EmitInstance (EmitContext ec, bool prepare_for_load)
2751                 {
2752                         if (IsStatic)
2753                                 return;
2754
2755                         if (InstanceExpression == EmptyExpression.Null) {
2756                                 SimpleName.Error_ObjectRefRequired (ec, loc, GetSignatureForError ());
2757                                 return;
2758                         }
2759                                 
2760                         if (InstanceExpression.Type.IsValueType) {
2761                                 if (InstanceExpression is IMemoryLocation) {
2762                                         ((IMemoryLocation) InstanceExpression).AddressOf (ec, AddressOp.LoadStore);
2763                                 } else {
2764                                         LocalTemporary t = new LocalTemporary (InstanceExpression.Type);
2765                                         InstanceExpression.Emit (ec);
2766                                         t.Store (ec);
2767                                         t.AddressOf (ec, AddressOp.Store);
2768                                 }
2769                         } else
2770                                 InstanceExpression.Emit (ec);
2771
2772                         if (prepare_for_load)
2773                                 ec.ig.Emit (OpCodes.Dup);
2774                 }
2775         }
2776
2777         /// <summary>
2778         ///   MethodGroup Expression.
2779         ///  
2780         ///   This is a fully resolved expression that evaluates to a type
2781         /// </summary>
2782         public class MethodGroupExpr : MemberExpr {
2783                 public MethodBase [] Methods;
2784                 bool has_type_arguments = false;
2785                 bool identical_type_name = false;
2786                 bool is_base;
2787                 
2788                 public MethodGroupExpr (MemberInfo [] mi, Location l)
2789                 {
2790                         Methods = new MethodBase [mi.Length];
2791                         mi.CopyTo (Methods, 0);
2792                         eclass = ExprClass.MethodGroup;
2793                         type = TypeManager.object_type;
2794                         loc = l;
2795                 }
2796
2797                 public MethodGroupExpr (ArrayList list, Location l)
2798                 {
2799                         Methods = new MethodBase [list.Count];
2800
2801                         try {
2802                                 list.CopyTo (Methods, 0);
2803                         } catch {
2804                                 foreach (MemberInfo m in list){
2805                                         if (!(m is MethodBase)){
2806                                                 Console.WriteLine ("Name " + m.Name);
2807                                                 Console.WriteLine ("Found a: " + m.GetType ().FullName);
2808                                         }
2809                                 }
2810                                 throw;
2811                         }
2812
2813                         loc = l;
2814                         eclass = ExprClass.MethodGroup;
2815                         type = TypeManager.object_type;
2816                 }
2817
2818                 public override Type DeclaringType {
2819                         get {
2820                                 //
2821                                 // We assume that the top-level type is in the end
2822                                 //
2823                                 return Methods [Methods.Length - 1].DeclaringType;
2824                                 //return Methods [0].DeclaringType;
2825                         }
2826                 }
2827
2828                 public bool HasTypeArguments {
2829                         get {
2830                                 return has_type_arguments;
2831                         }
2832
2833                         set {
2834                                 has_type_arguments = value;
2835                         }
2836                 }
2837
2838                 public bool IdenticalTypeName {
2839                         get {
2840                                 return identical_type_name;
2841                         }
2842
2843                         set {
2844                                 identical_type_name = value;
2845                         }
2846                 }
2847
2848                 public bool IsBase {
2849                         get {
2850                                 return is_base;
2851                         }
2852                         set {
2853                                 is_base = value;
2854                         }
2855                 }
2856
2857                 public override string GetSignatureForError ()
2858                 {
2859                         return TypeManager.CSharpSignature (Methods [0]);
2860                 }
2861
2862                 public override string Name {
2863                         get {
2864                                 return Methods [0].Name;
2865                         }
2866                 }
2867
2868                 public override bool IsInstance {
2869                         get {
2870                                 foreach (MethodBase mb in Methods)
2871                                         if (!mb.IsStatic)
2872                                                 return true;
2873
2874                                 return false;
2875                         }
2876                 }
2877
2878                 public override bool IsStatic {
2879                         get {
2880                                 foreach (MethodBase mb in Methods)
2881                                         if (mb.IsStatic)
2882                                                 return true;
2883
2884                                 return false;
2885                         }
2886                 }
2887
2888                 public override Expression ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
2889                                                                 SimpleName original)
2890                 {
2891                         if (!(left is TypeExpr) &&
2892                             original != null && original.IdenticalNameAndTypeName (ec, left, loc))
2893                                 IdenticalTypeName = true;
2894
2895                         return base.ResolveMemberAccess (ec, left, loc, original);
2896                 }
2897                 
2898                 override public Expression DoResolve (EmitContext ec)
2899                 {
2900                         if (!IsInstance)
2901                                 InstanceExpression = null;
2902
2903                         if (InstanceExpression != null) {
2904                                 InstanceExpression = InstanceExpression.DoResolve (ec);
2905                                 if (InstanceExpression == null)
2906                                         return null;
2907                         }
2908
2909                         return this;
2910                 }
2911
2912                 public void ReportUsageError ()
2913                 {
2914                         Report.Error (654, loc, "Method `" + DeclaringType + "." +
2915                                       Name + "()' is referenced without parentheses");
2916                 }
2917
2918                 override public void Emit (EmitContext ec)
2919                 {
2920                         ReportUsageError ();
2921                 }
2922
2923                 bool RemoveMethods (bool keep_static)
2924                 {
2925                         ArrayList smethods = new ArrayList ();
2926
2927                         foreach (MethodBase mb in Methods){
2928                                 if (mb.IsStatic == keep_static)
2929                                         smethods.Add (mb);
2930                         }
2931
2932                         if (smethods.Count == 0)
2933                                 return false;
2934
2935                         Methods = new MethodBase [smethods.Count];
2936                         smethods.CopyTo (Methods, 0);
2937
2938                         return true;
2939                 }
2940                 
2941                 /// <summary>
2942                 ///   Removes any instance methods from the MethodGroup, returns
2943                 ///   false if the resulting set is empty.
2944                 /// </summary>
2945                 public bool RemoveInstanceMethods ()
2946                 {
2947                         return RemoveMethods (true);
2948                 }
2949
2950                 /// <summary>
2951                 ///   Removes any static methods from the MethodGroup, returns
2952                 ///   false if the resulting set is empty.
2953                 /// </summary>
2954                 public bool RemoveStaticMethods ()
2955                 {
2956                         return RemoveMethods (false);
2957                 }
2958
2959                 public Expression ResolveGeneric (EmitContext ec, TypeArguments args)
2960                 {
2961                         if (args.Resolve (ec) == false)
2962                                 return null;
2963
2964                         Type[] atypes = args.Arguments;
2965
2966                         int first_count = 0;
2967                         MethodInfo first = null;
2968
2969                         ArrayList list = new ArrayList ();
2970                         foreach (MethodBase mb in Methods) {
2971                                 MethodInfo mi = mb as MethodInfo;
2972                                 if ((mi == null) || !mi.IsGenericMethod)
2973                                         continue;
2974
2975                                 Type[] gen_params = mi.GetGenericArguments ();
2976
2977                                 if (first == null) {
2978                                         first = mi;
2979                                         first_count = gen_params.Length;
2980                                 }
2981
2982                                 if (gen_params.Length != atypes.Length)
2983                                         continue;
2984
2985                                 list.Add (mi.MakeGenericMethod (atypes));
2986                         }
2987
2988                         if (list.Count > 0) {
2989                                 MethodGroupExpr new_mg = new MethodGroupExpr (list, Location);
2990                                 new_mg.InstanceExpression = InstanceExpression;
2991                                 new_mg.HasTypeArguments = true;
2992                                 new_mg.IsBase = IsBase;
2993                                 return new_mg;
2994                         }
2995
2996                         if (first != null)
2997                                 Report.Error (
2998                                         305, loc, "Using the generic method `{0}' " +
2999                                         "requires {1} type arguments", Name,
3000                                         first_count.ToString ());
3001                         else
3002                                 Report.Error (
3003                                         308, loc, "The non-generic method `{0}' " +
3004                                         "cannot be used with type arguments", Name);
3005
3006                         return null;
3007                 }
3008         }
3009
3010         /// <summary>
3011         ///   Fully resolved expression that evaluates to a Field
3012         /// </summary>
3013         public class FieldExpr : MemberExpr, IAssignMethod, IMemoryLocation, IVariable {
3014                 public readonly FieldInfo FieldInfo;
3015                 VariableInfo variable_info;
3016                 
3017                 LocalTemporary temp;
3018                 bool prepared;
3019                 bool in_initializer;
3020
3021                 public FieldExpr (FieldInfo fi, Location l, bool in_initializer):
3022                         this (fi, l)
3023                 {
3024                         this.in_initializer = in_initializer;
3025                 }
3026                 
3027                 public FieldExpr (FieldInfo fi, Location l)
3028                 {
3029                         FieldInfo = fi;
3030                         eclass = ExprClass.Variable;
3031                         type = TypeManager.TypeToCoreType (fi.FieldType);
3032                         loc = l;
3033                 }
3034
3035                 public override string Name {
3036                         get {
3037                                 return FieldInfo.Name;
3038                         }
3039                 }
3040
3041                 public override bool IsInstance {
3042                         get {
3043                                 return !FieldInfo.IsStatic;
3044                         }
3045                 }
3046
3047                 public override bool IsStatic {
3048                         get {
3049                                 return FieldInfo.IsStatic;
3050                         }
3051                 }
3052
3053                 public override Type DeclaringType {
3054                         get {
3055                                 return FieldInfo.DeclaringType;
3056                         }
3057                 }
3058
3059                 public override string GetSignatureForError ()
3060                 {
3061                         return TypeManager.GetFullNameSignature (FieldInfo);
3062                 }
3063
3064                 public VariableInfo VariableInfo {
3065                         get {
3066                                 return variable_info;
3067                         }
3068                 }
3069
3070                 public override Expression ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
3071                                                                 SimpleName original)
3072                 {
3073                         FieldInfo fi = TypeManager.GetGenericFieldDefinition (FieldInfo);
3074
3075                         Type t = fi.FieldType;
3076
3077                         if (fi.IsLiteral || (fi.IsInitOnly && t == TypeManager.decimal_type)) {
3078                                 IConstant ic = TypeManager.GetConstant (fi);
3079                                 if (ic == null) {
3080                                         if (fi.IsLiteral) {
3081                                                 ic = new ExternalConstant (fi);
3082                                         } else {
3083                                                 ic = ExternalConstant.CreateDecimal (fi);
3084                                                 if (ic == null) {
3085                                                         return base.ResolveMemberAccess (ec, left, loc, original);
3086                                                 }
3087                                         }
3088                                         TypeManager.RegisterConstant (fi, ic);
3089                                 }
3090
3091                                 bool left_is_type = left is TypeExpr;
3092                                 if (!left_is_type && (original == null || !original.IdenticalNameAndTypeName (ec, left, loc))) {
3093                                         Report.SymbolRelatedToPreviousError (FieldInfo);
3094                                         error176 (loc, TypeManager.GetFullNameSignature (FieldInfo));
3095                                         return null;
3096                                 }
3097
3098                                 if (ic.ResolveValue ()) {
3099                                         if (!ec.IsInObsoleteScope)
3100                                                 ic.CheckObsoleteness (loc);
3101                                 }
3102
3103                                 return ic.Value;
3104                         }
3105                         
3106                         if (t.IsPointer && !ec.InUnsafe) {
3107                                 UnsafeError (loc);
3108                                 return null;
3109                         }
3110
3111                         return base.ResolveMemberAccess (ec, left, loc, original);
3112                 }
3113
3114                 override public Expression DoResolve (EmitContext ec)
3115                 {
3116                         return DoResolve (ec, false, false);
3117                 }
3118
3119                 Expression DoResolve (EmitContext ec, bool lvalue_instance, bool out_access)
3120                 {
3121                         if (!FieldInfo.IsStatic){
3122                                 if (InstanceExpression == null){
3123                                         //
3124                                         // This can happen when referencing an instance field using
3125                                         // a fully qualified type expression: TypeName.InstanceField = xxx
3126                                         // 
3127                                         SimpleName.Error_ObjectRefRequired (ec, loc, GetSignatureForError ());
3128                                         return null;
3129                                 }
3130
3131                                 // Resolve the field's instance expression while flow analysis is turned
3132                                 // off: when accessing a field "a.b", we must check whether the field
3133                                 // "a.b" is initialized, not whether the whole struct "a" is initialized.
3134
3135                                 if (lvalue_instance) {
3136                                         using (ec.With (EmitContext.Flags.DoFlowAnalysis, false)) {
3137                                                 Expression right_side =
3138                                                         out_access ? EmptyExpression.LValueMemberOutAccess : EmptyExpression.LValueMemberAccess;
3139                                                 InstanceExpression = InstanceExpression.ResolveLValue (ec, right_side, loc);
3140                                         }
3141                                 } else {
3142                                         ResolveFlags rf = ResolveFlags.VariableOrValue | ResolveFlags.DisableFlowAnalysis;
3143                                         InstanceExpression = InstanceExpression.Resolve (ec, rf);
3144                                 }
3145
3146                                 if (InstanceExpression == null)
3147                                         return null;
3148
3149                                 InstanceExpression.CheckMarshalByRefAccess ();
3150                         }
3151
3152                         if (!in_initializer && !ec.IsFieldInitializer) {
3153                                 ObsoleteAttribute oa;
3154                                 FieldBase f = TypeManager.GetField (FieldInfo);
3155                                 if (f != null) {
3156                                         if (!ec.IsInObsoleteScope)
3157                                                 f.CheckObsoleteness (loc);
3158                                 
3159                                         // To be sure that type is external because we do not register generated fields
3160                                 } else if (!(FieldInfo.DeclaringType is TypeBuilder)) {                                
3161                                         oa = AttributeTester.GetMemberObsoleteAttribute (FieldInfo);
3162                                         if (oa != null)
3163                                                 AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (FieldInfo), loc);
3164                                 }
3165                         }
3166
3167                         AnonymousContainer am = ec.CurrentAnonymousMethod;
3168                         if (am != null){
3169                                 if (!FieldInfo.IsStatic){
3170                                         if (!am.IsIterator && (ec.TypeContainer is Struct)){
3171                                                 Report.Error (1673, loc,
3172                                                 "Anonymous methods inside structs cannot access instance members of `{0}'. Consider copying `{0}' to a local variable outside the anonymous method and using the local instead",
3173                                                         "this");
3174                                                 return null;
3175                                         }
3176                                         if ((am.ContainerAnonymousMethod == null) && (InstanceExpression is This))
3177                                                 ec.CaptureField (this);
3178                                 }
3179                         }
3180                         
3181                         // If the instance expression is a local variable or parameter.
3182                         IVariable var = InstanceExpression as IVariable;
3183                         if ((var == null) || (var.VariableInfo == null))
3184                                 return this;
3185
3186                         VariableInfo vi = var.VariableInfo;
3187                         if (!vi.IsFieldAssigned (ec, FieldInfo.Name, loc))
3188                                 return null;
3189
3190                         variable_info = vi.GetSubStruct (FieldInfo.Name);
3191                         return this;
3192                 }
3193
3194                 static readonly int [] codes = {
3195                         191,    // instance, write access
3196                         192,    // instance, out access
3197                         198,    // static, write access
3198                         199,    // static, out access
3199                         1648,   // member of value instance, write access
3200                         1649,   // member of value instance, out access
3201                         1650,   // member of value static, write access
3202                         1651    // member of value static, out access
3203                 };
3204
3205                 static readonly string [] msgs = {
3206                         /*0191*/ "A readonly field `{0}' cannot be assigned to (except in a constructor or a variable initializer)",
3207                         /*0192*/ "A readonly field `{0}' cannot be passed ref or out (except in a constructor)",
3208                         /*0198*/ "A static readonly field `{0}' cannot be assigned to (except in a static constructor or a variable initializer)",
3209                         /*0199*/ "A static readonly field `{0}' cannot be passed ref or out (except in a static constructor)",
3210                         /*1648*/ "Members of readonly field `{0}' cannot be modified (except in a constructor or a variable initializer)",
3211                         /*1649*/ "Members of readonly field `{0}' cannot be passed ref or out (except in a constructor)",
3212                         /*1650*/ "Fields of static readonly field `{0}' cannot be assigned to (except in a static constructor or a variable initializer)",
3213                         /*1651*/ "Fields of static readonly field `{0}' cannot be passed ref or out (except in a static constructor)"
3214                 };
3215
3216                 // The return value is always null.  Returning a value simplifies calling code.
3217                 Expression Report_AssignToReadonly (Expression right_side)
3218                 {
3219                         int i = 0;
3220                         if (right_side == EmptyExpression.OutAccess || right_side == EmptyExpression.LValueMemberOutAccess)
3221                                 i += 1;
3222                         if (IsStatic)
3223                                 i += 2;
3224                         if (right_side == EmptyExpression.LValueMemberAccess || right_side == EmptyExpression.LValueMemberOutAccess)
3225                                 i += 4;
3226                         Report.Error (codes [i], loc, msgs [i], GetSignatureForError ());
3227
3228                         return null;
3229                 }
3230                 
3231                 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3232                 {
3233                         IVariable var = InstanceExpression as IVariable;
3234                         if ((var != null) && (var.VariableInfo != null))
3235                                 var.VariableInfo.SetFieldAssigned (ec, FieldInfo.Name);
3236
3237                         bool lvalue_instance = !FieldInfo.IsStatic && FieldInfo.DeclaringType.IsValueType;
3238                         bool out_access = right_side == EmptyExpression.OutAccess || right_side == EmptyExpression.LValueMemberOutAccess;
3239
3240                         Expression e = DoResolve (ec, lvalue_instance, out_access);
3241
3242                         if (e == null)
3243                                 return null;
3244
3245                         FieldBase fb = TypeManager.GetField (FieldInfo);
3246                         if (fb != null)
3247                                 fb.SetAssigned ();
3248
3249                         if (FieldInfo.IsInitOnly) {
3250                                 // InitOnly fields can only be assigned in constructors or initializers
3251                                 if (!ec.IsFieldInitializer && !ec.IsConstructor)
3252                                         return Report_AssignToReadonly (right_side);
3253
3254                                 if (ec.IsConstructor) {
3255                                         Type ctype = ec.TypeContainer.CurrentType;
3256                                         if (ctype == null)
3257                                                 ctype = ec.ContainerType;
3258
3259                                         // InitOnly fields cannot be assigned-to in a different constructor from their declaring type
3260                                         if (!TypeManager.IsEqual (ctype, FieldInfo.DeclaringType))
3261                                                 return Report_AssignToReadonly (right_side);
3262                                         // static InitOnly fields cannot be assigned-to in an instance constructor
3263                                         if (IsStatic && !ec.IsStatic)
3264                                                 return Report_AssignToReadonly (right_side);
3265                                         // instance constructors can't modify InitOnly fields of other instances of the same type
3266                                         if (!IsStatic && !(InstanceExpression is This))
3267                                                 return Report_AssignToReadonly (right_side);
3268                                 }
3269                         }
3270
3271                         if (right_side == EmptyExpression.OutAccess &&
3272                             !IsStatic && !(InstanceExpression is This) && DeclaringType.IsSubclassOf (TypeManager.mbr_type)) {
3273                                 Report.SymbolRelatedToPreviousError (DeclaringType);
3274                                 Report.Warning (197, 1, loc,
3275                                                 "Passing `{0}' as ref or out or taking its address may cause a runtime exception because it is a field of a marshal-by-reference class",
3276                                                 GetSignatureForError ());
3277                         }
3278
3279                         return this;
3280                 }
3281
3282                 public override void CheckMarshalByRefAccess ()
3283                 {
3284                         if (!IsStatic && Type.IsValueType && !(InstanceExpression is This) && DeclaringType.IsSubclassOf (TypeManager.mbr_type)) {
3285                                 Report.SymbolRelatedToPreviousError (DeclaringType);
3286                                 Report.Warning (1690, 1, loc, "Cannot call methods, properties, or indexers on `{0}' because it is a value type member of a marshal-by-reference class",
3287                                                 GetSignatureForError ());
3288                         }
3289                 }
3290
3291                 public bool VerifyFixed ()
3292                 {
3293                         IVariable variable = InstanceExpression as IVariable;
3294                         // A variable of the form V.I is fixed when V is a fixed variable of a struct type.
3295                         // We defer the InstanceExpression check after the variable check to avoid a 
3296                         // separate null check on InstanceExpression.
3297                         return variable != null && InstanceExpression.Type.IsValueType && variable.VerifyFixed ();
3298                 }
3299
3300                 public override int GetHashCode ()
3301                 {
3302                         return FieldInfo.GetHashCode ();
3303                 }
3304
3305                 public override bool Equals (object obj)
3306                 {
3307                         FieldExpr fe = obj as FieldExpr;
3308                         if (fe == null)
3309                                 return false;
3310
3311                         if (FieldInfo != fe.FieldInfo)
3312                                 return false;
3313
3314                         if (InstanceExpression == null || fe.InstanceExpression == null)
3315                                 return true;
3316
3317                         return InstanceExpression.Equals (fe.InstanceExpression);
3318                 }
3319                 
3320                 public void Emit (EmitContext ec, bool leave_copy)
3321                 {
3322                         ILGenerator ig = ec.ig;
3323                         bool is_volatile = false;
3324
3325                         FieldBase f = TypeManager.GetField (FieldInfo);
3326                         if (f != null){
3327                                 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
3328                                         is_volatile = true;
3329
3330                                 f.SetMemberIsUsed ();
3331                         }
3332                         
3333                         if (FieldInfo.IsStatic){
3334                                 if (is_volatile)
3335                                         ig.Emit (OpCodes.Volatile);
3336                                 
3337                                 ig.Emit (OpCodes.Ldsfld, FieldInfo);
3338                         } else {
3339                                 if (!prepared)
3340                                         EmitInstance (ec, false);
3341
3342                                 if (is_volatile)
3343                                         ig.Emit (OpCodes.Volatile);
3344
3345                                 IFixedBuffer ff = AttributeTester.GetFixedBuffer (FieldInfo);
3346                                 if (ff != null)
3347                                 {
3348                                         ig.Emit (OpCodes.Ldflda, FieldInfo);
3349                                         ig.Emit (OpCodes.Ldflda, ff.Element);
3350                                 }
3351                                 else {
3352                                         ig.Emit (OpCodes.Ldfld, FieldInfo);
3353                                 }
3354                         }
3355
3356                         if (leave_copy) {
3357                                 ec.ig.Emit (OpCodes.Dup);
3358                                 if (!FieldInfo.IsStatic) {
3359                                         temp = new LocalTemporary (this.Type);
3360                                         temp.Store (ec);
3361                                 }
3362                         }
3363                 }
3364
3365                 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3366                 {
3367                         FieldAttributes fa = FieldInfo.Attributes;
3368                         bool is_static = (fa & FieldAttributes.Static) != 0;
3369                         bool is_readonly = (fa & FieldAttributes.InitOnly) != 0;
3370                         ILGenerator ig = ec.ig;
3371                         prepared = prepare_for_load;
3372
3373                         if (is_readonly && !ec.IsConstructor){
3374                                 Report_AssignToReadonly (source);
3375                                 return;
3376                         }
3377
3378                         EmitInstance (ec, prepare_for_load);
3379
3380                         source.Emit (ec);
3381                         if (leave_copy) {
3382                                 ec.ig.Emit (OpCodes.Dup);
3383                                 if (!FieldInfo.IsStatic) {
3384                                         temp = new LocalTemporary (this.Type);
3385                                         temp.Store (ec);
3386                                 }
3387                         }
3388
3389                         FieldBase f = TypeManager.GetField (FieldInfo);
3390                         if (f != null){
3391                                 if ((f.ModFlags & Modifiers.VOLATILE) != 0)
3392                                         ig.Emit (OpCodes.Volatile);
3393                                         
3394                                 f.SetAssigned ();
3395                         }
3396
3397                         if (is_static)
3398                                 ig.Emit (OpCodes.Stsfld, FieldInfo);
3399                         else 
3400                                 ig.Emit (OpCodes.Stfld, FieldInfo);
3401                         
3402                         if (temp != null)
3403                                 temp.Emit (ec);
3404                 }
3405
3406                 public override void Emit (EmitContext ec)
3407                 {
3408                         Emit (ec, false);
3409                 }
3410
3411                 public void AddressOf (EmitContext ec, AddressOp mode)
3412                 {
3413                         ILGenerator ig = ec.ig;
3414
3415                         FieldBase f = TypeManager.GetField (FieldInfo);
3416                         if (f != null){
3417                                 if ((f.ModFlags & Modifiers.VOLATILE) != 0){
3418                                         Report.Warning (420, 1, loc, "`{0}': A volatile fields cannot be passed using a ref or out parameter",
3419                                                         f.GetSignatureForError ());
3420                                         return;
3421                                 }
3422                                         
3423                                 if ((mode & AddressOp.Store) != 0)
3424                                         f.SetAssigned ();
3425                                 if ((mode & AddressOp.Load) != 0)
3426                                         f.SetMemberIsUsed ();
3427                         }
3428
3429                         //
3430                         // Handle initonly fields specially: make a copy and then
3431                         // get the address of the copy.
3432                         //
3433                         bool need_copy;
3434                         if (FieldInfo.IsInitOnly){
3435                                 need_copy = true;
3436                                 if (ec.IsConstructor){
3437                                         if (FieldInfo.IsStatic){
3438                                                 if (ec.IsStatic)
3439                                                         need_copy = false;
3440                                         } else
3441                                                 need_copy = false;
3442                                 }
3443                         } else
3444                                 need_copy = false;
3445                         
3446                         if (need_copy){
3447                                 LocalBuilder local;
3448                                 Emit (ec);
3449                                 local = ig.DeclareLocal (type);
3450                                 ig.Emit (OpCodes.Stloc, local);
3451                                 ig.Emit (OpCodes.Ldloca, local);
3452                                 return;
3453                         }
3454
3455
3456                         if (FieldInfo.IsStatic){
3457                                 ig.Emit (OpCodes.Ldsflda, FieldInfo);
3458                         } else {
3459                                 if (!prepared)
3460                                         EmitInstance (ec, false);
3461                                 ig.Emit (OpCodes.Ldflda, FieldInfo);
3462                         }
3463                 }
3464         }
3465
3466         //
3467         // A FieldExpr whose address can not be taken
3468         //
3469         public class FieldExprNoAddress : FieldExpr, IMemoryLocation {
3470                 public FieldExprNoAddress (FieldInfo fi, Location loc) : base (fi, loc)
3471                 {
3472                 }
3473                 
3474                 public new void AddressOf (EmitContext ec, AddressOp mode)
3475                 {
3476                         Report.Error (-215, "Report this: Taking the address of a remapped parameter not supported");
3477                 }
3478         }
3479         
3480         /// <summary>
3481         ///   Expression that evaluates to a Property.  The Assign class
3482         ///   might set the `Value' expression if we are in an assignment.
3483         ///
3484         ///   This is not an LValue because we need to re-write the expression, we
3485         ///   can not take data from the stack and store it.  
3486         /// </summary>
3487         public class PropertyExpr : MemberExpr, IAssignMethod {
3488                 public readonly PropertyInfo PropertyInfo;
3489
3490                 //
3491                 // This is set externally by the  `BaseAccess' class
3492                 //
3493                 public bool IsBase;
3494                 MethodInfo getter, setter;
3495                 bool is_static;
3496
3497                 bool resolved;
3498                 
3499                 LocalTemporary temp;
3500                 bool prepared;
3501
3502                 internal static PtrHashtable AccessorTable = new PtrHashtable (); 
3503
3504                 public PropertyExpr (Type containerType, PropertyInfo pi, Location l)
3505                 {
3506                         PropertyInfo = pi;
3507                         eclass = ExprClass.PropertyAccess;
3508                         is_static = false;
3509                         loc = l;
3510
3511                         type = TypeManager.TypeToCoreType (pi.PropertyType);
3512
3513                         ResolveAccessors (containerType);
3514                 }
3515
3516                 public override string Name {
3517                         get {
3518                                 return PropertyInfo.Name;
3519                         }
3520                 }
3521
3522                 public override bool IsInstance {
3523                         get {
3524                                 return !is_static;
3525                         }
3526                 }
3527
3528                 public override bool IsStatic {
3529                         get {
3530                                 return is_static;
3531                         }
3532                 }
3533                 
3534                 public override Type DeclaringType {
3535                         get {
3536                                 return PropertyInfo.DeclaringType;
3537                         }
3538                 }
3539
3540                 public override string GetSignatureForError ()
3541                 {
3542                         return TypeManager.GetFullNameSignature (PropertyInfo);
3543                 }
3544
3545                 void FindAccessors (Type invocation_type)
3546                 {
3547                         const BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic |
3548                                 BindingFlags.Static | BindingFlags.Instance |
3549                                 BindingFlags.DeclaredOnly;
3550
3551                         Type current = PropertyInfo.DeclaringType;
3552                         for (; current != null; current = current.BaseType) {
3553                                 MemberInfo[] group = TypeManager.MemberLookup (
3554                                         invocation_type, invocation_type, current,
3555                                         MemberTypes.Property, flags, PropertyInfo.Name, null);
3556
3557                                 if (group == null)
3558                                         continue;
3559
3560                                 if (group.Length != 1)
3561                                         // Oooops, can this ever happen ?
3562                                         return;
3563
3564                                 PropertyInfo pi = (PropertyInfo) group [0];
3565
3566                                 if (getter == null)
3567                                         getter = pi.GetGetMethod (true);
3568
3569                                 if (setter == null)
3570                                         setter = pi.GetSetMethod (true);
3571
3572                                 MethodInfo accessor = getter != null ? getter : setter;
3573
3574                                 if (!accessor.IsVirtual)
3575                                         return;
3576                         }
3577                 }
3578
3579                 //
3580                 // We also perform the permission checking here, as the PropertyInfo does not
3581                 // hold the information for the accessibility of its setter/getter
3582                 //
3583                 // TODO: can use TypeManager.GetProperty to boost performance
3584                 void ResolveAccessors (Type containerType)
3585                 {
3586                         FindAccessors (containerType);
3587
3588                         if (getter != null) {
3589                                 MethodBase the_getter = TypeManager.DropGenericMethodArguments (getter);
3590                                 IMethodData md = TypeManager.GetMethod (the_getter);
3591                                 if (md != null)
3592                                         md.SetMemberIsUsed ();
3593
3594                                 AccessorTable [getter] = PropertyInfo;
3595                                 is_static = getter.IsStatic;
3596                         }
3597
3598                         if (setter != null) {
3599                                 MethodBase the_setter = TypeManager.DropGenericMethodArguments (setter);
3600                                 IMethodData md = TypeManager.GetMethod (the_setter);
3601                                 if (md != null)
3602                                         md.SetMemberIsUsed ();
3603
3604                                 AccessorTable [setter] = PropertyInfo;
3605                                 is_static = setter.IsStatic;
3606                         }
3607                 }
3608
3609                 bool InstanceResolve (EmitContext ec, bool lvalue_instance, bool must_do_cs1540_check)
3610                 {
3611                         if (is_static) {
3612                                 InstanceExpression = null;
3613                                 return true;
3614                         }
3615
3616                         if (InstanceExpression == null) {
3617                                 SimpleName.Error_ObjectRefRequired (ec, loc, GetSignatureForError ());
3618                                 return false;
3619                         }
3620
3621                         if (lvalue_instance)
3622                                 InstanceExpression = InstanceExpression.ResolveLValue (ec, EmptyExpression.LValueMemberAccess, loc);
3623                         else
3624                                 InstanceExpression = InstanceExpression.DoResolve (ec);
3625                         if (InstanceExpression == null)
3626                                 return false;
3627
3628                         InstanceExpression.CheckMarshalByRefAccess ();
3629
3630                         if (must_do_cs1540_check && InstanceExpression != EmptyExpression.Null &&
3631                             InstanceExpression.Type != ec.ContainerType &&
3632                             ec.ContainerType.IsSubclassOf (PropertyInfo.DeclaringType) &&
3633                             !InstanceExpression.Type.IsSubclassOf (ec.ContainerType)) {
3634                                 Error_CannotAccessProtected (loc, PropertyInfo, InstanceExpression.Type, ec.ContainerType);
3635                                 return false;
3636                         }
3637
3638                         return true;
3639                 }
3640
3641                 void Error_PropertyNotFound (MethodInfo mi, bool getter)
3642                 {
3643                         // TODO: correctly we should compare arguments but it will lead to bigger changes
3644                         if (mi is MethodBuilder) {
3645                                 Error_TypeDoesNotContainDefinition (loc, PropertyInfo.DeclaringType, Name);
3646                                 return;
3647                         }
3648
3649                         StringBuilder sig = new StringBuilder (TypeManager.CSharpName (mi.DeclaringType));
3650                         sig.Append ('.');
3651                         ParameterData iparams = TypeManager.GetParameterData (mi);
3652                         sig.Append (getter ? "get_" : "set_");
3653                         sig.Append (Name);
3654                         sig.Append (iparams.GetSignatureForError ());
3655
3656                         Report.SymbolRelatedToPreviousError (mi);
3657                         Report.Error (1546, loc, "Property `{0}' is not supported by the C# language. Try to call the accessor method `{1}' directly",
3658                                 Name, sig.ToString ());
3659                 }
3660                 
3661                 override public Expression DoResolve (EmitContext ec)
3662                 {
3663                         if (resolved)
3664                                 return this;
3665
3666                         if (getter != null){
3667                                 if (TypeManager.GetParameterData (getter).Count != 0){
3668                                         Error_PropertyNotFound (getter, true);
3669                                         return null;
3670                                 }
3671                         }
3672
3673                         if (getter == null){
3674                                 //
3675                                 // The following condition happens if the PropertyExpr was
3676                                 // created, but is invalid (ie, the property is inaccessible),
3677                                 // and we did not want to embed the knowledge about this in
3678                                 // the caller routine.  This only avoids double error reporting.
3679                                 //
3680                                 if (setter == null)
3681                                         return null;
3682
3683                                 if (InstanceExpression != EmptyExpression.Null) {
3684                                         Report.Error (154, loc, "The property or indexer `{0}' cannot be used in this context because it lacks the `get' accessor",
3685                                                 TypeManager.GetFullNameSignature (PropertyInfo));
3686                                         return null;
3687                                 }
3688                         } 
3689
3690                         bool must_do_cs1540_check = false;
3691                         if (getter != null &&
3692                             !IsAccessorAccessible (ec.ContainerType, getter, out must_do_cs1540_check)) {
3693                                 PropertyBase.PropertyMethod pm = TypeManager.GetMethod (getter) as PropertyBase.PropertyMethod;
3694                                 if (pm != null && pm.HasCustomAccessModifier) {
3695                                         Report.SymbolRelatedToPreviousError (pm);
3696                                         Report.Error (271, loc, "The property or indexer `{0}' cannot be used in this context because the get accessor is inaccessible",
3697                                                 TypeManager.CSharpSignature (getter));
3698                                 }
3699                                 else {
3700                                         Report.SymbolRelatedToPreviousError (getter);
3701                                         ErrorIsInaccesible (loc, TypeManager.CSharpSignature (getter));
3702                                 }
3703                                 return null;
3704                         }
3705                         
3706                         if (!InstanceResolve (ec, false, must_do_cs1540_check))
3707                                 return null;
3708
3709                         //
3710                         // Only base will allow this invocation to happen.
3711                         //
3712                         if (IsBase && getter.IsAbstract) {
3713                                 Error_CannotCallAbstractBase (TypeManager.GetFullNameSignature (PropertyInfo));
3714                                 return null;
3715                         }
3716
3717                         if (PropertyInfo.PropertyType.IsPointer && !ec.InUnsafe){
3718                                 UnsafeError (loc);
3719                                 return null;
3720                         }
3721
3722                         resolved = true;
3723
3724                         return this;
3725                 }
3726
3727                 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
3728                 {
3729                         if (right_side == EmptyExpression.OutAccess) {
3730                                 Report.Error (206, loc, "A property or indexer `{0}' may not be passed as an out or ref parameter",
3731                                               GetSignatureForError ());
3732                                 return null;
3733                         }
3734
3735                         if (right_side == EmptyExpression.LValueMemberAccess || right_side == EmptyExpression.LValueMemberOutAccess) {
3736                                 Report.Error (1612, loc, "Cannot modify the return value of `{0}' because it is not a variable",
3737                                               GetSignatureForError ());
3738                                 return null;
3739                         }
3740
3741                         if (setter == null){
3742                                 //
3743                                 // The following condition happens if the PropertyExpr was
3744                                 // created, but is invalid (ie, the property is inaccessible),
3745                                 // and we did not want to embed the knowledge about this in
3746                                 // the caller routine.  This only avoids double error reporting.
3747                                 //
3748                                 if (getter == null)
3749                                         return null;
3750                                 Report.Error (200, loc, "Property or indexer `{0}' cannot be assigned to (it is read only)",
3751                                               GetSignatureForError ());
3752                                 return null;
3753                         }
3754
3755                         if (TypeManager.GetParameterData (setter).Count != 1){
3756                                 Error_PropertyNotFound (setter, false);
3757                                 return null;
3758                         }
3759
3760                         bool must_do_cs1540_check;
3761                         if (!IsAccessorAccessible (ec.ContainerType, setter, out must_do_cs1540_check)) {
3762                                 PropertyBase.PropertyMethod pm = TypeManager.GetMethod (setter) as PropertyBase.PropertyMethod;
3763                                 if (pm != null && pm.HasCustomAccessModifier) {
3764                                         Report.SymbolRelatedToPreviousError (pm);
3765                                         Report.Error (272, loc, "The property or indexer `{0}' cannot be used in this context because the set accessor is inaccessible",
3766                                                 TypeManager.CSharpSignature (setter));
3767                                 }
3768                                 else {
3769                                         Report.SymbolRelatedToPreviousError (setter);
3770                                         ErrorIsInaccesible (loc, TypeManager.CSharpSignature (setter));
3771                                 }
3772                                 return null;
3773                         }
3774                         
3775                         if (!InstanceResolve (ec, PropertyInfo.DeclaringType.IsValueType, must_do_cs1540_check))
3776                                 return null;
3777                         
3778                         //
3779                         // Only base will allow this invocation to happen.
3780                         //
3781                         if (IsBase && setter.IsAbstract){
3782                                 Error_CannotCallAbstractBase (TypeManager.GetFullNameSignature (PropertyInfo));
3783                                 return null;
3784                         }
3785
3786                         return this;
3787                 }
3788                 
3789                 public override void Emit (EmitContext ec)
3790                 {
3791                         Emit (ec, false);
3792                 }
3793                 
3794                 public void Emit (EmitContext ec, bool leave_copy)
3795                 {
3796                         //
3797                         // Special case: length of single dimension array property is turned into ldlen
3798                         //
3799                         if ((getter == TypeManager.system_int_array_get_length) ||
3800                             (getter == TypeManager.int_array_get_length)){
3801                                 Type iet = InstanceExpression.Type;
3802
3803                                 //
3804                                 // System.Array.Length can be called, but the Type does not
3805                                 // support invoking GetArrayRank, so test for that case first
3806                                 //
3807                                 if (iet != TypeManager.array_type && (iet.GetArrayRank () == 1)) {
3808                                         if (!prepared)
3809                                                 EmitInstance (ec, false);
3810                                         ec.ig.Emit (OpCodes.Ldlen);
3811                                         ec.ig.Emit (OpCodes.Conv_I4);
3812                                         return;
3813                                 }
3814                         }
3815
3816                         Invocation.EmitCall (ec, IsBase, IsStatic, InstanceExpression, getter, null, loc, prepared, false);
3817                         
3818                         if (leave_copy) {
3819                                 ec.ig.Emit (OpCodes.Dup);
3820                                 if (!is_static) {
3821                                         temp = new LocalTemporary (this.Type);
3822                                         temp.Store (ec);
3823                                 }
3824                         }
3825                 }
3826
3827                 //
3828                 // Implements the IAssignMethod interface for assignments
3829                 //
3830                 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
3831                 {
3832                         Expression my_source = source;
3833
3834                         prepared = prepare_for_load;
3835                         
3836                         if (prepared) {
3837                                 source.Emit (ec);
3838                                 if (leave_copy) {
3839                                         ec.ig.Emit (OpCodes.Dup);
3840                                         if (!is_static) {
3841                                                 temp = new LocalTemporary (this.Type);
3842                                                 temp.Store (ec);
3843                                         }
3844                                 }
3845                         } else if (leave_copy) {
3846                                 source.Emit (ec);
3847                                 if (!is_static) {
3848                                         temp = new LocalTemporary (this.Type);
3849                                         temp.Store (ec);
3850                                 }
3851                                 my_source = temp;
3852                         }
3853                         
3854                         ArrayList args = new ArrayList (1);
3855                         args.Add (new Argument (my_source, Argument.AType.Expression));
3856                         
3857                         Invocation.EmitCall (ec, IsBase, IsStatic, InstanceExpression, setter, args, loc, false, prepared);
3858                         
3859                         if (temp != null)
3860                                 temp.Emit (ec);
3861                 }
3862         }
3863
3864         /// <summary>
3865         ///   Fully resolved expression that evaluates to an Event
3866         /// </summary>
3867         public class EventExpr : MemberExpr {
3868                 public readonly EventInfo EventInfo;
3869
3870                 bool is_static;
3871                 MethodInfo add_accessor, remove_accessor;
3872
3873                 internal static PtrHashtable AccessorTable = new PtrHashtable (); 
3874                 
3875                 public EventExpr (EventInfo ei, Location loc)
3876                 {
3877                         EventInfo = ei;
3878                         this.loc = loc;
3879                         eclass = ExprClass.EventAccess;
3880
3881                         add_accessor = TypeManager.GetAddMethod (ei);
3882                         remove_accessor = TypeManager.GetRemoveMethod (ei);
3883                         if (add_accessor != null)
3884                                 AccessorTable [add_accessor] = ei;
3885                         if (remove_accessor != null)
3886                                 AccessorTable [remove_accessor] = ei;
3887                         
3888                         if (add_accessor.IsStatic || remove_accessor.IsStatic)
3889                                 is_static = true;
3890
3891                         if (EventInfo is MyEventBuilder){
3892                                 MyEventBuilder eb = (MyEventBuilder) EventInfo;
3893                                 type = eb.EventType;
3894                                 eb.SetUsed ();
3895                         } else
3896                                 type = EventInfo.EventHandlerType;
3897                 }
3898
3899                 public override string Name {
3900                         get {
3901                                 return EventInfo.Name;
3902                         }
3903                 }
3904
3905                 public override bool IsInstance {
3906                         get {
3907                                 return !is_static;
3908                         }
3909                 }
3910
3911                 public override bool IsStatic {
3912                         get {
3913                                 return is_static;
3914                         }
3915                 }
3916
3917                 public override Type DeclaringType {
3918                         get {
3919                                 return EventInfo.DeclaringType;
3920                         }
3921                 }
3922
3923                 public override Expression ResolveMemberAccess (EmitContext ec, Expression left, Location loc,
3924                                                                 SimpleName original)
3925                 {
3926                         //
3927                         // If the event is local to this class, we transform ourselves into a FieldExpr
3928                         //
3929
3930                         if (EventInfo.DeclaringType == ec.ContainerType ||
3931                             TypeManager.IsNestedChildOf(ec.ContainerType, EventInfo.DeclaringType)) {
3932                                 MemberInfo mi = TypeManager.GetPrivateFieldOfEvent (EventInfo);
3933
3934                                 if (mi != null) {
3935                                         MemberExpr ml = (MemberExpr) ExprClassFromMemberInfo (ec.ContainerType, mi, loc);
3936
3937                                         if (ml == null) {
3938                                                 Report.Error (-200, loc, "Internal error!!");
3939                                                 return null;
3940                                         }
3941
3942                                         InstanceExpression = null;
3943                                 
3944                                         return ml.ResolveMemberAccess (ec, left, loc, original);
3945                                 }
3946                         }
3947
3948                         return base.ResolveMemberAccess (ec, left, loc, original);
3949                 }
3950
3951
3952                 bool InstanceResolve (EmitContext ec, bool must_do_cs1540_check)
3953                 {
3954                         if (is_static) {
3955                                 InstanceExpression = null;
3956                                 return true;
3957                         }
3958
3959                         if (InstanceExpression == null) {
3960                                 SimpleName.Error_ObjectRefRequired (ec, loc, GetSignatureForError ());
3961                                 return false;
3962                         }
3963
3964                         InstanceExpression = InstanceExpression.DoResolve (ec);
3965                         if (InstanceExpression == null)
3966                                 return false;
3967
3968                         //
3969                         // This is using the same mechanism as the CS1540 check in PropertyExpr.
3970                         // However, in the Event case, we reported a CS0122 instead.
3971                         //
3972                         if (must_do_cs1540_check && InstanceExpression != EmptyExpression.Null &&
3973                             InstanceExpression.Type != ec.ContainerType &&
3974                             ec.ContainerType.IsSubclassOf (InstanceExpression.Type)) {
3975                                 Report.SymbolRelatedToPreviousError (EventInfo);
3976                                 ErrorIsInaccesible (loc, TypeManager.CSharpSignature (EventInfo));
3977                                 return false;
3978                         }
3979
3980                         return true;
3981                 }
3982
3983                 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
3984                 {
3985                         return DoResolve (ec);
3986                 }
3987
3988                 public override Expression DoResolve (EmitContext ec)
3989                 {
3990                         bool must_do_cs1540_check;
3991                         if (!(IsAccessorAccessible (ec.ContainerType, add_accessor, out must_do_cs1540_check) &&
3992                               IsAccessorAccessible (ec.ContainerType, remove_accessor, out must_do_cs1540_check))) {
3993                                 Report.SymbolRelatedToPreviousError (EventInfo);
3994                                 ErrorIsInaccesible (loc, TypeManager.CSharpSignature (EventInfo));
3995                                 return null;
3996                         }
3997
3998                         if (!InstanceResolve (ec, must_do_cs1540_check))
3999                                 return null;
4000                         
4001                         return this;
4002                 }               
4003
4004                 public override void Emit (EmitContext ec)
4005                 {
4006                         if (InstanceExpression is This)
4007                                 Report.Error (79, loc, "The event `{0}' can only appear on the left hand side of += or -=", GetSignatureForError ());
4008                         else
4009                                 Report.Error (70, loc, "The event `{0}' can only appear on the left hand side of += or -= "+
4010                                               "(except on the defining type)", Name);
4011                 }
4012
4013                 public override string GetSignatureForError ()
4014                 {
4015                         return TypeManager.CSharpSignature (EventInfo);
4016                 }
4017
4018                 public void EmitAddOrRemove (EmitContext ec, Expression source)
4019                 {
4020                         BinaryDelegate source_del = (BinaryDelegate) source;
4021                         Expression handler = source_del.Right;
4022                         
4023                         Argument arg = new Argument (handler, Argument.AType.Expression);
4024                         ArrayList args = new ArrayList ();
4025                                 
4026                         args.Add (arg);
4027                         
4028                         if (source_del.IsAddition)
4029                                 Invocation.EmitCall (
4030                                         ec, false, IsStatic, InstanceExpression, add_accessor, args, loc);
4031                         else
4032                                 Invocation.EmitCall (
4033                                         ec, false, IsStatic, InstanceExpression, remove_accessor, args, loc);
4034                 }
4035         }
4036
4037         
4038         public class TemporaryVariable : Expression, IMemoryLocation
4039         {
4040                 LocalInfo li;
4041                 
4042                 public TemporaryVariable (Type type, Location loc)
4043                 {
4044                         this.type = type;
4045                         this.loc = loc;
4046                         eclass = ExprClass.Value;
4047                 }
4048                 
4049                 public override Expression DoResolve (EmitContext ec)
4050                 {
4051                         if (li != null)
4052                                 return this;
4053                         
4054                         TypeExpr te = new TypeExpression (type, loc);
4055                         li = ec.CurrentBlock.AddTemporaryVariable (te, loc);
4056                         if (!li.Resolve (ec))
4057                                 return null;
4058                         
4059                         AnonymousContainer am = ec.CurrentAnonymousMethod;
4060                         if ((am != null) && am.IsIterator)
4061                                 ec.CaptureVariable (li);
4062                         
4063                         return this;
4064                 }
4065                 
4066                 public override void Emit (EmitContext ec)
4067                 {
4068                         ILGenerator ig = ec.ig;
4069                         
4070                         if (li.FieldBuilder != null) {
4071                                 ig.Emit (OpCodes.Ldarg_0);
4072                                 ig.Emit (OpCodes.Ldfld, li.FieldBuilder);
4073                         } else {
4074                                 ig.Emit (OpCodes.Ldloc, li.LocalBuilder);
4075                         }
4076                 }
4077                 
4078                 public void EmitLoadAddress (EmitContext ec)
4079                 {
4080                         ILGenerator ig = ec.ig;
4081                         
4082                         if (li.FieldBuilder != null) {
4083                                 ig.Emit (OpCodes.Ldarg_0);
4084                                 ig.Emit (OpCodes.Ldflda, li.FieldBuilder);
4085                         } else {
4086                                 ig.Emit (OpCodes.Ldloca, li.LocalBuilder);
4087                         }
4088                 }
4089                 
4090                 public void Store (EmitContext ec, Expression right_side)
4091                 {
4092                         if (li.FieldBuilder != null)
4093                                 ec.ig.Emit (OpCodes.Ldarg_0);
4094                         
4095                         right_side.Emit (ec);
4096                         if (li.FieldBuilder != null) {
4097                                 ec.ig.Emit (OpCodes.Stfld, li.FieldBuilder);
4098                         } else {
4099                                 ec.ig.Emit (OpCodes.Stloc, li.LocalBuilder);
4100                         }
4101                 }
4102                 
4103                 public void EmitThis (EmitContext ec)
4104                 {
4105                         if (li.FieldBuilder != null) {
4106                                 ec.ig.Emit (OpCodes.Ldarg_0);
4107                         }
4108                 }
4109                 
4110                 public void EmitStore (ILGenerator ig)
4111                 {
4112                         if (li.FieldBuilder != null)
4113                                 ig.Emit (OpCodes.Stfld, li.FieldBuilder);
4114                         else
4115                                 ig.Emit (OpCodes.Stloc, li.LocalBuilder);
4116                 }
4117                 
4118                 public void AddressOf (EmitContext ec, AddressOp mode)
4119                 {
4120                         EmitLoadAddress (ec);
4121                 }
4122         }
4123         
4124 }