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