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