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