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