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