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