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