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