* MonoTouch/MonoPInvokeCallbackAttribute.cs: Added.
[mono.git] / mcs / mcs / class.cs
index b9b0e45bb16883a3d0c85766539252601a0746e2..48f22136149bce66ca18c110956166f26d44644c 100644 (file)
 // Copyright 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
 // Copyright 2004-2008 Novell, Inc
 //
-//
-//  2002-10-11  Miguel de Icaza  <miguel@ximian.com>
-//
-//     * class.cs: Following the comment from 2002-09-26 to AddMethod, I
-//     have fixed a remaining problem: not every AddXXXX was adding a
-//     fully qualified name.  
-//
-//     Now everyone registers a fully qualified name in the DeclSpace as
-//     being defined instead of the partial name.  
-//
-//     Downsides: we are slower than we need to be due to the excess
-//     copies and the names being registered this way.  
-//
-//     The reason for this is that we currently depend (on the corlib
-//     bootstrap for instance) that types are fully qualified, because
-//     we dump all the types in the namespace, and we should really have
-//     types inserted into the proper namespace, so we can only store the
-//     basenames in the defined_names array.
-//
-//
+
 using System;
 using System.Collections;
 using System.Collections.Specialized;
@@ -152,17 +133,17 @@ namespace Mono.CSharp {
                                                continue;
 
                                        Operator o = operators [i];
-                                       Report.Error (216, o.Location,
+                                       container.Report.Error (216, o.Location,
                                                "The operator `{0}' requires a matching operator `{1}' to also be defined",
                                                o.GetSignatureForError (), Operator.GetName (o.GetMatchingOperator ()));
                                }
 
-                               if (has_equality_or_inequality && Report.WarningLevel > 2) {
+                               if (has_equality_or_inequality && container.Report.WarningLevel > 2) {
                                        if (container.Methods == null || !container.HasEquals)
-                                               Report.Warning (660, 2, container.Location, "`{0}' defines operator == or operator != but does not override Object.Equals(object o)", container.GetSignatureForError ());
+                                               container.Report.Warning (660, 2, container.Location, "`{0}' defines operator == or operator != but does not override Object.Equals(object o)", container.GetSignatureForError ());
  
                                        if (container.Methods == null || !container.HasGetHashCode)
-                                               Report.Warning (661, 2, container.Location, "`{0}' defines operator == or operator != but does not override Object.GetHashCode()", container.GetSignatureForError ());
+                                               container.Report.Warning (661, 2, container.Location, "`{0}' defines operator == or operator != but does not override Object.GetHashCode()", container.GetSignatureForError ());
                                }
                        }
 
@@ -173,6 +154,80 @@ namespace Mono.CSharp {
                        }
                }
 
+               //
+               // Different context is needed when resolving type container base
+               // types. Type names come from the parent scope but type parameter
+               // names from the container scope.
+               //
+               struct BaseContext : IMemberContext
+               {
+                       TypeContainer tc;
+
+                       public BaseContext (TypeContainer tc)
+                       {
+                               this.tc = tc;
+                       }
+
+                       #region IMemberContext Members
+
+                       public CompilerContext Compiler {
+                               get { return tc.Compiler; }
+                       }
+
+                       public Type CurrentType {
+                               get { return tc.Parent.CurrentType; }
+                       }
+
+                       public TypeParameter[] CurrentTypeParameters {
+                               get { return tc.PartialContainer.CurrentTypeParameters; }
+                       }
+
+                       public TypeContainer CurrentTypeDefinition {
+                               get { return tc.Parent.CurrentTypeDefinition; }
+                       }
+
+                       public bool IsObsolete {
+                               get { return tc.IsObsolete; }
+                       }
+
+                       public bool IsUnsafe {
+                               get { return tc.IsUnsafe; }
+                       }
+
+                       public bool IsStatic {
+                               get { return tc.IsStatic; }
+                       }
+
+                       public string GetSignatureForError ()
+                       {
+                               throw new NotImplementedException ();
+                       }
+
+                       public ExtensionMethodGroupExpr LookupExtensionMethod (Type extensionType, string name, Location loc)
+                       {
+                               return null;
+                       }
+
+                       public FullNamedExpression LookupNamespaceAlias (string name)
+                       {
+                               return tc.Parent.LookupNamespaceAlias (name);
+                       }
+
+                       public FullNamedExpression LookupNamespaceOrType (string name, Location loc, bool ignore_cs0104)
+                       {
+                               TypeParameter[] tp = CurrentTypeParameters;
+                               if (tp != null) {
+                                       TypeParameter t = TypeParameter.FindTypeParameter (tp, name);
+                                       if (t != null)
+                                               return new TypeParameterExpr (t, loc);
+                               }
+
+                               return tc.Parent.LookupNamespaceOrType (name, loc, ignore_cs0104);
+                       }
+
+                       #endregion
+               }
+
                [Flags]
                enum CachedMethods
                {
@@ -201,7 +256,7 @@ namespace Mono.CSharp {
                protected MemberCoreArrayList instance_constructors;
 
                // Holds the list of fields
-               MemberCoreArrayList fields;
+               protected MemberCoreArrayList fields;
 
                // Holds a list of fields that have initializers
                protected ArrayList initialized_fields;
@@ -248,11 +303,10 @@ namespace Mono.CSharp {
                TypeExpr base_type;
                TypeExpr[] iface_exprs;
                Type GenericType;
+               GenericTypeParameterBuilder[] nested_gen_params;
 
                protected ArrayList type_bases;
 
-               bool members_resolved;
-               bool members_resolved_ok;
                protected bool members_defined;
                bool members_defined_ok;
 
@@ -267,6 +321,7 @@ namespace Mono.CSharp {
 
                private bool seen_normal_indexers = false;
                private string indexer_name = DefaultIndexerName;
+               protected bool requires_delayed_unmanagedtype_check;
 
                private CachedMethods cached_method;
 
@@ -291,7 +346,7 @@ namespace Mono.CSharp {
 
                public bool AddMember (MemberCore symbol)
                {
-                       return AddToContainer (symbol, symbol.MemberName.MethodName);
+                       return AddToContainer (symbol, symbol.MemberName.Basename);
                }
 
                protected virtual bool AddMemberType (DeclSpace ds)
@@ -426,10 +481,9 @@ namespace Mono.CSharp {
 
                }
                
-               public void AddMethod (Method method)
+               public void AddMethod (MethodOrOperator method)
                {
-                       MemberName mn = method.MemberName;
-                       if (!AddToContainer (method, mn.IsGeneric ? mn.Basename : mn.MethodName))
+                       if (!AddToContainer (method, method.MemberName.Basename))
                                return;
                        
                        if (methods == null)
@@ -443,10 +497,6 @@ namespace Mono.CSharp {
 
                public void AddConstructor (Constructor c)
                {
-                       if (c.Name != MemberName.Name) {
-                               Report.Error (1520, c.Location, "Class, struct, or interface method must have a return type");
-                       }
-
                        bool is_static = (c.ModFlags & Modifiers.STATIC) != 0;
                        if (!AddToContainer (c, is_static ?
                                ConstructorBuilder.ConstructorName : ConstructorBuilder.TypeConstructorName))
@@ -569,16 +619,16 @@ namespace Mono.CSharp {
                        compiler_generated.Add (c);
                }
 
-               public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
+               public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
                {
-                       if (a.Type == TypeManager.default_member_type) {
+                       if (a.Type == pa.DefaultMember) {
                                if (Indexers != null) {
                                        Report.Error (646, a.Location, "Cannot specify the `DefaultMember' attribute on type containing an indexer");
                                        return;
                                }
                        }
                        
-                       base.ApplyAttributeBuilder (a, cb);
+                       base.ApplyAttributeBuilder (a, cb, pa);
                } 
 
                public override AttributeTargets AttributeTargets {
@@ -667,10 +717,10 @@ namespace Mono.CSharp {
 
                public bool IsComImport {
                        get {
-                               if (OptAttributes == null || TypeManager.comimport_attr_type == null)
+                               if (OptAttributes == null)
                                        return false;
 
-                               return OptAttributes.Contains (TypeManager.comimport_attr_type);
+                               return OptAttributes.Contains (PredefinedAttributes.Get.ComImport);
                        }
                }
 
@@ -691,7 +741,7 @@ namespace Mono.CSharp {
                        }
                }
 
-               public void ResolveFieldInitializers (EmitContext ec)
+               public void ResolveFieldInitializers (BlockContext ec)
                {
                        if (partial_parts != null) {
                                foreach (TypeContainer part in partial_parts) {
@@ -701,7 +751,7 @@ namespace Mono.CSharp {
                        DoResolveFieldInitializers (ec);
                }
 
-               void DoResolveFieldInitializers (EmitContext ec)
+               void DoResolveFieldInitializers (BlockContext ec)
                {
                        if (ec.IsStatic) {
                                if (initialized_static_fields == null)
@@ -757,33 +807,6 @@ namespace Mono.CSharp {
                        }
                }
 
-               //
-               // Emits the instance field initializers
-               //
-               public bool EmitFieldInitializers (EmitContext ec)
-               {
-                       if (partial_parts != null) {
-                               foreach (TypeContainer part in partial_parts)
-                                       part.EmitFieldInitializers (ec);
-                       }
-
-                       ArrayList fields;
-                       
-                       if (ec.IsStatic){
-                               fields = initialized_static_fields;
-                       } else {
-                               fields = initialized_fields;
-                       }
-
-                       if (fields == null)
-                               return true;
-
-                       foreach (FieldInitializer f in fields) {
-                               f.EmitStatement (ec);
-                       }
-                       return true;
-               }
-               
                public override string DocComment {
                        get {
                                return comment;
@@ -833,6 +856,7 @@ namespace Mono.CSharp {
 
                        int count = type_bases.Count;
                        TypeExpr [] ifaces = null;
+                       IMemberContext base_context = new BaseContext (this);
                        for (int i = 0, j = 0; i < count; i++){
                                FullNamedExpression fne = (FullNamedExpression) type_bases [i];
 
@@ -841,12 +865,16 @@ namespace Mono.CSharp {
                                // it does ObsoleteAttribute and constraint checks which require
                                // base type to be set
                                //
-                               TypeExpr fne_resolved = fne.ResolveAsBaseTerminal (this, false);
+                               TypeExpr fne_resolved = fne.ResolveAsBaseTerminal (base_context, false);
                                if (fne_resolved == null)
                                        continue;
 
                                if (i == 0 && Kind == Kind.Class && !fne_resolved.Type.IsInterface) {
-                                       base_class = fne_resolved;
+                                       if (fne_resolved is DynamicTypeExpr)
+                                               Report.Error (1965, Location, "Class `{0}' cannot derive from the dynamic type",
+                                                       GetSignatureForError ());
+                                       else
+                                               base_class = fne_resolved;
                                        continue;
                                }
 
@@ -862,7 +890,7 @@ namespace Mono.CSharp {
                                                }
                                        }
 
-                                       if (Kind == Kind.Interface && !fne_resolved.AsAccessible (this)) {
+                                       if (Kind == Kind.Interface && !IsAccessibleAs (fne_resolved.Type)) {
                                                Report.Error (61, fne.Location,
                                                        "Inconsistent accessibility: base interface `{0}' is less accessible than interface `{1}'",
                                                        fne_resolved.GetSignatureForError (), GetSignatureForError ());
@@ -899,7 +927,7 @@ namespace Mono.CSharp {
                                        if (base_class == TypeManager.system_object_expr)
                                                base_class = new_base_class;
                                        else {
-                                               if (new_base_class != null && !new_base_class.Equals (base_class)) {
+                                               if (new_base_class != null && !TypeManager.IsEqual (new_base_class.Type, base_class.Type)) {
                                                        Report.SymbolRelatedToPreviousError (base_class.Location, "");
                                                        Report.Error (263, part.Location,
                                                                "Partial declarations of `{0}' must not specify different base classes",
@@ -967,6 +995,8 @@ namespace Mono.CSharp {
                                        default_parent = TypeManager.value_type;
                                else if (Kind == Kind.Enum)
                                        default_parent = TypeManager.enum_type;
+                               else if (Kind == Kind.Delegate)
+                                       default_parent = TypeManager.multicast_delegate_type;
 
                                //
                                // Sets .size to 1 for structs with no instance fields
@@ -974,11 +1004,12 @@ namespace Mono.CSharp {
                                int type_size = Kind == Kind.Struct && first_nonstatic_field == null ? 1 : 0;
 
                                if (IsTopLevel){
-                                       if (TypeManager.NamespaceClash (Name, Location)) {
+                                       if (GlobalRootNamespace.Instance.IsNamespace (Name)) {
+                                               Report.Error (519, Location, "`{0}' clashes with a predefined namespace", Name);
                                                return false;
                                        }
 
-                                       ModuleBuilder builder = CodeGen.Module.Builder;
+                                       ModuleBuilder builder = Module.Builder;
                                        TypeBuilder = builder.DefineType (
                                                Name, TypeAttr, default_parent, type_size);
                                } else {
@@ -994,19 +1025,30 @@ namespace Mono.CSharp {
 
                        TypeManager.AddUserType (this);
 
-#if GMCS_SOURCE
                        if (IsGeneric) {
                                string[] param_names = new string [TypeParameters.Length];
                                for (int i = 0; i < TypeParameters.Length; i++)
                                        param_names [i] = TypeParameters [i].Name;
 
+#if GMCS_SOURCE
                                GenericTypeParameterBuilder[] gen_params = TypeBuilder.DefineGenericParameters (param_names);
 
-                               int offset = CountTypeParameters - CurrentTypeParameters.Length;
+                               int offset = CountTypeParameters;
+                               if (CurrentTypeParameters != null)
+                                       offset -= CurrentTypeParameters.Length;
+
+                               if (offset > 0) {
+                                       nested_gen_params = new GenericTypeParameterBuilder [offset];
+                                       Array.Copy (gen_params, nested_gen_params, offset);
+                               }
+
                                for (int i = offset; i < gen_params.Length; i++)
                                        CurrentTypeParameters [i - offset].Define (gen_params [i]);
-                       }
+#else
+                               nested_gen_params = null;
+                               throw new NotSupportedException ();
 #endif
+                       }
 
                        return true;
                }
@@ -1028,7 +1070,7 @@ namespace Mono.CSharp {
                        // Let's do it as soon as possible, since code below can call DefineType() on classes
                        // that depend on us to be populated before they are.
                        //
-                       if (!(this is CompilerGeneratedClass))
+                       if (!(this is CompilerGeneratedClass) && !(this is Delegate))
                                RootContext.RegisterOrder (this); 
 
                        if (!CheckRecursiveDefinition (this))
@@ -1110,11 +1152,6 @@ namespace Mono.CSharp {
                                return null;
                        }
 
-                       if (!ResolveMembers ()) {
-                               error = true;
-                               return null;
-                       }
-
                        if (!DefineNestedTypes ()) {
                                error = true;
                                return null;
@@ -1123,37 +1160,6 @@ namespace Mono.CSharp {
                        return TypeBuilder;
                }
 
-               bool ResolveMembers ()
-               {
-                       if (members_resolved)
-                               return members_resolved_ok;
-
-                       members_resolved_ok = DoResolveMembers ();
-                       members_resolved = true;
-
-                       return members_resolved_ok;
-               }
-
-               protected virtual bool DoResolveMembers ()
-               {
-                       if (methods != null) {
-                               foreach (Method method in methods) {
-                                       if (!method.ResolveMembers ())
-                                               return false;
-                               }
-                       }
-
-                       // TODO: this is not really needed
-                       if (operators != null) {
-                               foreach (Operator o in operators) {
-                                       if (!o.ResolveMembers ())
-                                               return false;
-                               }
-                       }
-
-                       return true;
-               }
-
                public override void SetParameterInfo (ArrayList constraints_list)
                {
                        base.SetParameterInfo (constraints_list);
@@ -1174,9 +1180,9 @@ namespace Mono.CSharp {
 
                void UpdateTypeParameterConstraints (TypeContainer part)
                {
-                       TypeParameter[] current_params = CurrentTypeParameters;
+                       TypeParameter[] current_params = type_params;
                        for (int i = 0; i < current_params.Length; i++) {
-                               Constraints c = part.CurrentTypeParameters [i].Constraints;
+                               Constraints c = part.type_params [i].Constraints;
                                if (c == null)
                                        continue;
 
@@ -1206,12 +1212,6 @@ namespace Mono.CSharp {
 
                protected virtual bool DoResolveType ()
                {
-                       if ((base_type != null) &&
-                           (base_type.ResolveAsTypeTerminal (this, false) == null)) {
-                               error = true;
-                               return false;
-                       }
-
                        if (!IsGeneric)
                                return true;
 
@@ -1219,34 +1219,46 @@ namespace Mono.CSharp {
                                throw new InternalErrorException ();
 
                        TypeExpr current_type = null;
-
-                       foreach (TypeParameter type_param in CurrentTypeParameters) {
-                               if (!type_param.Resolve (this)) {
-                                       error = true;
-                                       return false;
+                       if (CurrentTypeParameters != null) {
+                               foreach (TypeParameter type_param in CurrentTypeParameters) {
+                                       if (!type_param.Resolve (this)) {
+                                               error = true;
+                                               return false;
+                                       }
                                }
-                       }
 
-                       if (partial_parts != null && is_generic) {
-                               foreach (TypeContainer part in partial_parts)
-                                       UpdateTypeParameterConstraints (part);
+                               if (partial_parts != null) {
+                                       foreach (TypeContainer part in partial_parts)
+                                               UpdateTypeParameterConstraints (part);
+                               }
                        }
 
-                       foreach (TypeParameter type_param in TypeParameters) {
-                               if (!type_param.DefineType (this)) {
-                                       error = true;
-                                       return false;
+                       for (int i = 0; i < TypeParameters.Length; ++i) {
+                               //
+                               // FIXME: Same should be done for delegates
+                               // TODO: Quite ugly way how to propagate constraints to
+                               // nested types
+                               //
+                               if (nested_gen_params != null && i < nested_gen_params.Length) {
+                                       TypeParameters [i].SetConstraints (nested_gen_params [i]);
+                               } else {
+                                       if (!TypeParameters [i].DefineType (this)) {
+                                               error = true;
+                                               return false;
+                                       }
                                }
                        }
 
-                       current_type = new ConstructedType (TypeBuilder, TypeParameters, Location);
+                       // TODO: Very strange, why not simple make generic type from
+                       // current type parameters
+                       current_type = new GenericTypeExpr (this, Location);
                        current_type = current_type.ResolveAsTypeTerminal (this, false);
                        if (current_type == null) {
                                error = true;
                                return false;
                        }
 
-                       CurrentType = current_type.Type;
+                       currentType = current_type.Type;
                        return true;
                }
 
@@ -1311,6 +1323,12 @@ namespace Mono.CSharp {
                        return true;
                }
 
+               public override TypeParameter[] CurrentTypeParameters {
+                       get {
+                               return PartialContainer.type_params;
+                       }
+               }
+
                /// <summary>
                ///   Populates our TypeBuilder with fields and methods
                /// </summary>
@@ -1330,25 +1348,34 @@ namespace Mono.CSharp {
                        if (iface_exprs != null) {
                                foreach (TypeExpr iface in iface_exprs) {
                                        ObsoleteAttribute oa = AttributeTester.GetObsoleteAttribute (iface.Type);
-                                       if ((oa != null) && !IsInObsoleteScope)
+                                       if ((oa != null) && !IsObsolete)
                                                AttributeTester.Report_ObsoleteMessage (
-                                                       oa, iface.GetSignatureForError (), Location);
+                                                       oa, iface.GetSignatureForError (), Location, Report);
 
-                                       ConstructedType ct = iface as ConstructedType;
-                                       if ((ct != null) && !ct.CheckConstraints (this))
-                                               return false;
+                                       GenericTypeExpr ct = iface as GenericTypeExpr;
+                                       if (ct != null) {
+                                               // TODO: passing `this' is wrong, should be base type iface instead
+                                               TypeManager.CheckTypeVariance (ct.Type, Variance.Covariant, this);
+
+                                               if (!ct.CheckConstraints (this))
+                                                       return false;
+                                       }
                                }
                        }
 
                        if (base_type != null) {
                                ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (base_type.Type);
-                               if (obsolete_attr != null && !IsInObsoleteScope)
-                                       AttributeTester.Report_ObsoleteMessage (obsolete_attr, base_type.GetSignatureForError (), Location);
+                               if (obsolete_attr != null && !IsObsolete)
+                                       AttributeTester.Report_ObsoleteMessage (obsolete_attr, base_type.GetSignatureForError (), Location, Report);
 
-                               ConstructedType ct = base_type as ConstructedType;
+                               GenericTypeExpr ct = base_type as GenericTypeExpr;
                                if ((ct != null) && !ct.CheckConstraints (this))
                                        return false;
                                
+                               TypeContainer baseContainer = TypeManager.LookupTypeContainer(base_type.Type);
+                               if (baseContainer != null)
+                                       baseContainer.Define();                         
+                               
                                member_cache = new MemberCache (base_type.Type, this);
                        } else if (Kind == Kind.Interface) {
                                member_cache = new MemberCache (null, this);
@@ -1391,6 +1418,14 @@ namespace Mono.CSharp {
 
                        if (Kind == Kind.Struct || Kind == Kind.Class) {
                                pending = PendingImplementation.GetPendingImplementations (this);
+
+                               if (requires_delayed_unmanagedtype_check) {
+                                       requires_delayed_unmanagedtype_check = false;
+                                       foreach (FieldBase f in fields) {
+                                               if (f.MemberType != null && f.MemberType.IsPointer)
+                                                       TypeManager.VerifyUnManaged (f.MemberType, f.Location);
+                                       }
+                               }
                        }
                
                        //
@@ -1412,15 +1447,13 @@ namespace Mono.CSharp {
                                GenericType = CurrentType;
                        }
 
-#if GMCS_SOURCE
                        //
                        // FIXME: This hack is needed because member cache does not work
                        // with generic types, we rely on runtime to inflate dynamic types.
                        // TODO: This hack requires member cache refactoring to be removed
                        //
-                       if (TypeBuilder.IsGenericType)
+                       if (TypeManager.IsGenericType (TypeBuilder))
                                member_cache = new MemberCache (this);
-#endif                 
 
                        return true;
                }
@@ -1472,23 +1505,12 @@ namespace Mono.CSharp {
                        if (!seen_normal_indexers)
                                return;
 
-                       if (TypeManager.default_member_ctor == null) {
-                               if (TypeManager.default_member_type == null) {
-                                       TypeManager.default_member_type = TypeManager.CoreLookupType (
-                                               "System.Reflection", "DefaultMemberAttribute", Kind.Class, true);
-
-                                       if (TypeManager.default_member_type == null)
-                                               return;
-                               }
-
-                               TypeManager.default_member_ctor = TypeManager.GetPredefinedConstructor (
-                                       TypeManager.default_member_type, Location, TypeManager.string_type);
-
-                               if (TypeManager.default_member_ctor == null)
-                                       return;
-                       }
+                       PredefinedAttribute pa = PredefinedAttributes.Get.DefaultMember;
+                       if (pa.Constructor == null &&
+                               !pa.ResolveConstructor (Location, TypeManager.string_type))
+                               return;
 
-                       CustomAttributeBuilder cb = new CustomAttributeBuilder (TypeManager.default_member_ctor, new string [] { IndexerName });
+                       CustomAttributeBuilder cb = new CustomAttributeBuilder (pa.Constructor, new string [] { IndexerName });
                        TypeBuilder.SetCustomAttribute (cb);
                }
 
@@ -1771,7 +1793,7 @@ namespace Mono.CSharp {
                                if (methods != null) {
                                        int len = methods.Count;
                                        for (int i = 0; i < len; i++) {
-                                               Method m = (Method) methods [i];
+                                               MethodOrOperator m = (MethodOrOperator) methods [i];
                                                
                                                if ((m.ModFlags & modflags) == 0)
                                                        continue;
@@ -1972,7 +1994,7 @@ namespace Mono.CSharp {
                                                if (cb != null && filter (cb, criteria) == true) {
                                                        if (members == null)
                                                                members = new ArrayList ();
-                                                       
+
                                                        members.Add (cb);
                                                }
                                        }
@@ -2042,7 +2064,7 @@ namespace Mono.CSharp {
                        return;
                }
 
-               static void CheckMemberUsage (MemberCoreArrayList al, string member_type)
+               void CheckMemberUsage (MemberCoreArrayList al, string member_type)
                {
                        if (al == null)
                                return;
@@ -2193,7 +2215,7 @@ namespace Mono.CSharp {
 
                        if (methods != null) {
                                for (int i = 0; i < methods.Count; ++i)
-                                       ((Method) methods [i]).Emit ();
+                                       ((MethodOrOperator) methods [i]).Emit ();
                        }
                        
                        if (fields != null)
@@ -2207,7 +2229,7 @@ namespace Mono.CSharp {
                        }
 
                        if (pending != null)
-                               pending.VerifyPendingMethods ();
+                               pending.VerifyPendingMethods (Report);
 
                        if (Report.Errors > 0)
                                return;
@@ -2254,6 +2276,7 @@ namespace Mono.CSharp {
                                foreach (CompilerGeneratedClass c in compiler_generated)
                                        c.CloseType ();
                        
+                       PartialContainer = null;
                        types = null;
                        properties = null;
                        delegates = null;
@@ -2302,7 +2325,7 @@ namespace Mono.CSharp {
 
                        if (Kind == Kind.Struct){
                                if ((flags & va) != 0){
-                                       Modifiers.Error_InvalidModifier (mc.Location, "virtual or abstract");
+                                       Modifiers.Error_InvalidModifier (mc.Location, "virtual or abstract", Report);
                                        ok = false;
                                }
                        }
@@ -2537,7 +2560,7 @@ namespace Mono.CSharp {
                //
                internal override void GenerateDocComment (DeclSpace ds)
                {
-                       DocUtil.GenerateTypeDocComment (this, ds);
+                       DocUtil.GenerateTypeDocComment (this, ds, Report);
                }
 
                public override string DocCommentHeader {
@@ -2571,15 +2594,18 @@ namespace Mono.CSharp {
                        if (name == MemberName.Name) {
                                if (symbol is TypeParameter) {
                                        Report.Error (694, symbol.Location,
-                                                     "Type parameter `{0}' has same name as " +
-                                                     "containing type, or method", name);
+                                               "Type parameter `{0}' has same name as containing type, or method",
+                                               symbol.GetSignatureForError ());
                                        return false;
                                }
 
-                               Report.SymbolRelatedToPreviousError (this);
-                               Report.Error (542, symbol.Location, "`{0}': member names cannot be the same as their enclosing type",
-                                       symbol.GetSignatureForError ());
-                               return false;
+                               InterfaceMemberBase imb = symbol as InterfaceMemberBase;
+                               if (imb == null || !imb.IsExplicitImpl) {
+                                       Report.SymbolRelatedToPreviousError (this);
+                                       Report.Error (542, symbol.Location, "`{0}': member names cannot be the same as their enclosing type",
+                                               symbol.GetSignatureForError ());
+                                       return false;
+                               }
                        }
 
                        return base.AddToContainer (symbol, name);
@@ -2599,7 +2625,7 @@ namespace Mono.CSharp {
                        }
                }
 
-               public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
+               public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
                {
                        if (a.IsValidSecurityAttribute ()) {
                                if (declarative_security == null)
@@ -2609,14 +2635,14 @@ namespace Mono.CSharp {
                                return;
                        }
 
-                       if (a.Type == TypeManager.struct_layout_attribute_type) {
+                       if (a.Type == pa.StructLayout) {
                                PartialContainer.HasStructLayout = true;
 
                                if (a.GetLayoutKindValue () == LayoutKind.Explicit)
                                        PartialContainer.HasExplicitLayout = true;
                        }
 
-                       base.ApplyAttributeBuilder (a, cb);
+                       base.ApplyAttributeBuilder (a, cb, pa);
                }
 
                /// <summary>
@@ -2636,12 +2662,12 @@ namespace Mono.CSharp {
                        }
 
                        Constructor c = new Constructor (this, MemberName.Name, mods,
-                               Parameters.EmptyReadOnlyParameters,
+                               null, ParametersCompiled.EmptyReadOnlyParameters,
                                new GeneratedBaseInitializer (Location),
                                Location);
                        
                        AddConstructor (c);
-                       c.Block = new ToplevelBlock (null, Location);
+                       c.Block = new ToplevelBlock (Compiler, ParametersCompiled.EmptyReadOnlyParameters, Location);
                }
 
                public override bool Define ()
@@ -2674,7 +2700,17 @@ namespace Mono.CSharp {
 
                public override ExtensionMethodGroupExpr LookupExtensionMethod (Type extensionType, string name, Location loc)
                {
-                       return NamespaceEntry.LookupExtensionMethod (extensionType, this, name, loc);
+                       DeclSpace top_level = Parent;
+                       if (top_level != null) {
+                               while (top_level.Parent != null)
+                                       top_level = top_level.Parent;
+
+                               ArrayList candidates = NamespaceEntry.NS.LookupExtensionMethod (extensionType, this, name);
+                               if (candidates != null)
+                                       return new ExtensionMethodGroupExpr (candidates, NamespaceEntry, extensionType, loc);
+                       }
+
+                       return NamespaceEntry.LookupExtensionMethod (extensionType, name, loc);
                }
 
                protected override TypeAttributes TypeAttr {
@@ -2708,7 +2744,7 @@ namespace Mono.CSharp {
                        : base (ns, parent, name, attrs, Kind.Class)
                {
                        int accmods = Parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
-                       this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, Location);
+                       this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, Location, Report);
 
                        if (IsStatic && RootContext.Version == LanguageVersion.ISO_1) {
                                Report.FeatureIsNotAvailable (Location, "static classes");
@@ -2723,27 +2759,26 @@ namespace Mono.CSharp {
                        base.AddBasesForPart (part, bases);
                }
 
-               public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
+               public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
                {
-                       if (a.Type == TypeManager.attribute_usage_type) {
+                       if (a.Type == pa.AttributeUsage) {
                                if (!TypeManager.IsAttributeType (BaseType) &&
                                        TypeBuilder.FullName != "System.Attribute") {
                                        Report.Error (641, a.Location, "Attribute `{0}' is only valid on classes derived from System.Attribute", a.GetSignatureForError ());
                                }
                        }
 
-                       if (a.Type == TypeManager.conditional_attribute_type && !TypeManager.IsAttributeType (BaseType)) {
+                       if (a.Type == pa.Conditional && !TypeManager.IsAttributeType (BaseType)) {
                                Report.Error (1689, a.Location, "Attribute `System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes");
                                return;
                        }
 
-                       if (a.Type == TypeManager.comimport_attr_type && TypeManager.guid_attr_type != null &&
-                               !attributes.Contains (TypeManager.guid_attr_type)) {
-                                       a.Error_MissingGuidAttribute ();
-                                       return;
+                       if (a.Type == pa.ComImport && !attributes.Contains (pa.Guid)) {
+                               a.Error_MissingGuidAttribute ();
+                               return;
                        }
 
-                       if (a.Type == TypeManager.extension_attribute_type) {
+                       if (a.Type == pa.Extension) {
                                a.Error_MisusedExtensionAttribute ();
                                return;
                        }
@@ -2751,7 +2786,7 @@ namespace Mono.CSharp {
                        if (AttributeTester.IsAttributeExcluded (a.Type, Location))
                                return;
 
-                       base.ApplyAttributeBuilder (a, cb);
+                       base.ApplyAttributeBuilder (a, cb, pa);
                }
 
                public override AttributeTargets AttributeTargets {
@@ -2831,10 +2866,8 @@ namespace Mono.CSharp {
                {
                        base.Emit ();
 
-#if GMCS_SOURCE
                        if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
-                               TypeBuilder.SetCustomAttribute (TypeManager.extension_attribute_attr);
-#endif                 
+                               PredefinedAttributes.Get.Extension.EmitAttribute (TypeBuilder);
                }
 
                protected override TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
@@ -2847,7 +2880,7 @@ namespace Mono.CSharp {
                                else if (Name != "System.Object")
                                        base_class = TypeManager.system_object_expr;
                        } else {
-                               if (Kind == Kind.Class && base_class is TypeParameterExpr){
+                               if (Kind == Kind.Class && TypeManager.IsGenericParameter (base_class.Type)){
                                        Report.Error (
                                                689, base_class.Location,
                                                "Cannot derive from `{0}' because it is a type parameter",
@@ -2867,7 +2900,7 @@ namespace Mono.CSharp {
                                                Report.Error (709, Location, "`{0}': Cannot derive from static class `{1}'",
                                                        GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
                                        } else {
-                                               Report.Error (509, Location, "`{0}': cannot derive from sealed class `{1}'",
+                                               Report.Error (509, Location, "`{0}': cannot derive from sealed type `{1}'",
                                                        GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
                                        }
                                        return ifaces;
@@ -2879,7 +2912,7 @@ namespace Mono.CSharp {
                                        return ifaces;
                                }
 
-                               if (!base_class.AsAccessible (this)) {
+                               if (!IsAccessibleAs (base_class.Type)) {
                                        Report.SymbolRelatedToPreviousError (base_class.Type);
                                        Report.Error (60, Location, "Inconsistent accessibility: base class `{0}' is less accessible than class `{1}'", 
                                                TypeManager.CSharpName (base_class.Type), GetSignatureForError ());
@@ -2915,11 +2948,7 @@ namespace Mono.CSharp {
                        if (OptAttributes == null)
                                return false;
 
-                       if (TypeManager.conditional_attribute_type == null)
-                               return false;
-
-                       Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type);
-
+                       Attribute[] attrs = OptAttributes.SearchMulti (PredefinedAttributes.Get.Conditional);
                        if (attrs == null)
                                return false;
 
@@ -2933,12 +2962,6 @@ namespace Mono.CSharp {
                        return true;
                }
 
-               bool IsStatic {
-                       get {
-                               return (ModFlags & Modifiers.STATIC) != 0;
-                       }
-               }
-
                //
                // FIXME: How do we deal with the user specifying a different
                // layout?
@@ -2954,6 +2977,9 @@ namespace Mono.CSharp {
        }
 
        public sealed class Struct : ClassOrStruct {
+
+               bool is_unmanaged, has_unmanaged_check_done;
+
                // <summary>
                //   Modifiers allowed in a struct declaration
                // </summary>
@@ -2976,21 +3002,21 @@ namespace Mono.CSharp {
                        else
                                accmods = Modifiers.PRIVATE;
                        
-                       this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, Location);
+                       this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, Location, Report);
 
                        this.ModFlags |= Modifiers.SEALED;
                }
 
-               public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
+               public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
                {
-                       base.ApplyAttributeBuilder (a, cb);
+                       base.ApplyAttributeBuilder (a, cb, pa);
 
                        //
                        // When struct constains fixed fixed and struct layout has explicitly
                        // set CharSet, its value has to be propagated to compiler generated
                        // fixed field types
                        //
-                       if (a.Type == TypeManager.struct_layout_attribute_type && Fields != null && a.HasField ("CharSet")) {
+                       if (a.Type == pa.StructLayout && Fields != null && a.HasField ("CharSet")) {
                                for (int i = 0; i < Fields.Count; ++i) {
                                        FixedField ff = Fields [i] as FixedField;
                                        if (ff != null)
@@ -3005,6 +3031,48 @@ namespace Mono.CSharp {
                        }
                }
 
+               public override bool IsUnmanagedType ()
+               {
+                       if (fields == null)
+                               return true;
+
+                       if (requires_delayed_unmanagedtype_check)
+                               return true;
+
+                       if (has_unmanaged_check_done)
+                               return is_unmanaged;
+
+                       has_unmanaged_check_done = true;
+
+                       foreach (FieldBase f in fields) {
+                               if ((f.ModFlags & Modifiers.STATIC) != 0)
+                                       continue;
+
+                               // It can happen when recursive unmanaged types are defined
+                               // struct S { S* s; }
+                               Type mt = f.MemberType;
+                               if (mt == null) {
+                                       has_unmanaged_check_done = false;
+                                       requires_delayed_unmanagedtype_check = true;
+                                       return true;
+                               }
+
+                               // TODO: Remove when pointer types are under mcs control
+                               while (mt.IsPointer)
+                                       mt = TypeManager.GetElementType (mt);
+                               if (TypeManager.IsEqual (mt, TypeBuilder))
+                                       continue;
+
+                               if (TypeManager.IsUnmanagedType (mt))
+                                       continue;
+
+                               return false;
+                       }
+
+                       is_unmanaged = true;
+                       return true;
+               }
+
                protected override TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
                {
                        TypeExpr[] ifaces = base.ResolveBaseTypes (out base_class);
@@ -3032,8 +3100,7 @@ namespace Mono.CSharp {
                        get {
                                const TypeAttributes DefaultTypeAttributes =
                                        TypeAttributes.SequentialLayout |
-                                       TypeAttributes.Sealed |
-                                       TypeAttributes.BeforeFieldInit;
+                                       TypeAttributes.Sealed;
 
                                return base.TypeAttr | DefaultTypeAttributes;
                        }
@@ -3078,17 +3145,17 @@ namespace Mono.CSharp {
                        else
                                accmods = Modifiers.PRIVATE;
 
-                       this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, name.Location);
+                       this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, name.Location, Report);
                }
 
-               public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
+               public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
                {
-                       if (a.Type == TypeManager.comimport_attr_type && TypeManager.guid_attr_type != null &&
-                               !attributes.Contains (TypeManager.guid_attr_type)) {
-                                       a.Error_MissingGuidAttribute ();
-                                       return;
+                       if (a.Type == pa.ComImport && !attributes.Contains (pa.Guid)) {
+                               a.Error_MissingGuidAttribute ();
+                               return;
                        }
-                       base.ApplyAttributeBuilder (a, cb);
+
+                       base.ApplyAttributeBuilder (a, cb, pa);
                }
 
 
@@ -3157,12 +3224,12 @@ namespace Mono.CSharp {
 
        public abstract class MethodCore : InterfaceMemberBase
        {
-               public readonly Parameters Parameters;
+               public readonly ParametersCompiled Parameters;
                protected ToplevelBlock block;
 
                public MethodCore (DeclSpace parent, GenericMethod generic,
                        FullNamedExpression type, int mod, int allowed_mod,
-                       MemberName name, Attributes attrs, Parameters parameters)
+                       MemberName name, Attributes attrs, ParametersCompiled parameters)
                        : base (parent, generic, type, mod, allowed_mod, name, attrs)
                {
                        Parameters = parameters;
@@ -3177,8 +3244,7 @@ namespace Mono.CSharp {
                        }
                }
 
-               public Parameters ParameterInfo
-               {
+               public ParametersCompiled ParameterInfo {
                        get {
                                return Parameters;
                        }
@@ -3194,29 +3260,26 @@ namespace Mono.CSharp {
                        }
                }
 
+               public CallingConventions CallingConventions {
+                       get {
+                               CallingConventions cc = Parameters.CallingConvention;
+                               if (!IsInterface)
+                                       if ((ModFlags & Modifiers.STATIC) == 0)
+                                               cc |= CallingConventions.HasThis;
+
+                               // FIXME: How is `ExplicitThis' used in C#?
+                       
+                               return cc;
+                       }
+               }
+
                protected override bool CheckBase ()
                {
                        // Check whether arguments were correct.
                        if (!DefineParameters (Parameters))
                                return false;
 
-                       if ((caching_flags & Flags.MethodOverloadsExist) != 0) {
-                               if (!Parent.MemberCache.CheckExistingMembersOverloads (this,
-                                       MemberName.IsGeneric ? MemberName.Basename : MemberName.MethodName, Parameters))
-                                       return false;
-
-                               // TODO: Find a better way how to check reserved accessors collision
-                               Method m = this as Method;
-                               if (m != null) {
-                                       if (!m.CheckForDuplications ())
-                                               return false;
-                               }
-                       }
-
-                       if (!base.CheckBase ())
-                               return false;
-
-                       return true;
+                       return base.CheckBase ();
                }
 
                //
@@ -3237,7 +3300,7 @@ namespace Mono.CSharp {
                //
                internal override void OnGenerateDocComment (XmlElement el)
                {
-                       DocUtil.OnMethodGenerateDocComment (this, el);
+                       DocUtil.OnMethodGenerateDocComment (this, el, Report);
                }
 
                //
@@ -3255,7 +3318,7 @@ namespace Mono.CSharp {
                                return true;
                        }
 
-                       return false;
+                       return base.EnableOverloadChecks (overload);
                }
 
                protected override bool VerifyClsCompliance ()
@@ -3319,6 +3382,9 @@ namespace Mono.CSharp {
                {
                        if (!base.CheckBase ())
                                return false;
+
+                       if ((caching_flags & Flags.MethodOverloadsExist) != 0)
+                               CheckForDuplications ();
                        
                        if (IsExplicitImpl)
                                return true;
@@ -3342,13 +3408,13 @@ namespace Mono.CSharp {
                                if ((ModFlags & Modifiers.OVERRIDE) != 0) {
                                        ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (base_method);
                                        if (oa != null) {
-                                               if (OptAttributes == null || TypeManager.obsolete_attribute_type == null || !OptAttributes.Contains (TypeManager.obsolete_attribute_type)) {
+                                               if (OptAttributes == null || !OptAttributes.Contains (PredefinedAttributes.Get.Obsolete)) {
                                                        Report.SymbolRelatedToPreviousError (base_method);
                                                                Report.Warning (672, 1, Location, "Member `{0}' overrides obsolete member `{1}'. Add the Obsolete attribute to `{0}'",
                                                                        GetSignatureForError (), TypeManager.CSharpSignature (base_method));
                                                }
                                        } else {
-                                               if (OptAttributes != null && TypeManager.obsolete_attribute_type != null && OptAttributes.Contains (TypeManager.obsolete_attribute_type)) {
+                                               if (OptAttributes != null && OptAttributes.Contains (PredefinedAttributes.Get.Obsolete)) {
                                                        Report.SymbolRelatedToPreviousError (base_method);
                                                        Report.Warning (809, 1, Location, "Obsolete member `{0}' overrides non-obsolete member `{1}'",
                                                                GetSignatureForError (), TypeManager.CSharpSignature (base_method));
@@ -3394,6 +3460,12 @@ namespace Mono.CSharp {
                        return true;
                }
 
+               protected virtual bool CheckForDuplications ()
+               {
+                       return Parent.MemberCache.CheckExistingMembersOverloads (
+                               this, GetFullName (MemberName), ParametersCompiled.EmptyReadOnlyParameters, Report);
+               }
+
                //
                // Performs various checks on the MethodInfo `mb' regarding the modifier flags
                // that have been defined.
@@ -3407,6 +3479,7 @@ namespace Mono.CSharp {
 
                        if ((ModFlags & Modifiers.OVERRIDE) != 0){
                                if (!(base_method.IsAbstract || base_method.IsVirtual)){
+                                       Report.SymbolRelatedToPreviousError (base_method);
                                        Report.Error (506, Location,
                                                "`{0}': cannot override inherited member `{1}' because it is not marked virtual, abstract or override",
                                                 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
@@ -3447,12 +3520,17 @@ namespace Mono.CSharp {
                        }
 
                        if ((ModFlags & Modifiers.NEW) == 0) {
-                               if ((ModFlags & Modifiers.OVERRIDE) == 0 && Name != "Finalize") {
+                               if ((ModFlags & Modifiers.OVERRIDE) == 0) {
                                        ModFlags |= Modifiers.NEW;
                                        Report.SymbolRelatedToPreviousError (base_method);
                                        if (!IsInterface && (base_method.IsVirtual || base_method.IsAbstract)) {
                                                Report.Warning (114, 2, Location, "`{0}' hides inherited member `{1}'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword",
                                                        GetSignatureForError (), TypeManager.CSharpSignature (base_method));
+                                               if (base_method.IsAbstract){
+                                                       Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
+                                                                     GetSignatureForError (), TypeManager.CSharpSignature (base_method));
+                                                       ok = false;
+                                               }
                                        } else {
                                                Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
                                                        GetSignatureForError (), TypeManager.CSharpSignature (base_method));
@@ -3504,82 +3582,21 @@ namespace Mono.CSharp {
                        }
                }
 
-               protected bool DefineParameters (Parameters parameters)
+               public override bool Define ()
                {
-                       IResolveContext rc = GenericMethod == null ? this : (IResolveContext)ds;
-
-                       if (!parameters.Resolve (rc))
-                               return false;
+                       if (IsInterface) {
+                               ModFlags = Modifiers.PUBLIC | Modifiers.ABSTRACT |
+                                       Modifiers.VIRTUAL | (ModFlags & (Modifiers.UNSAFE | Modifiers.NEW));
 
-                       bool error = false;
-                       for (int i = 0; i < parameters.Count; ++i) {
-                               Parameter p = parameters [i];
-                               if (p.CheckAccessibility (this))
-                                       continue;
+                               flags = MethodAttributes.Public |
+                                       MethodAttributes.Abstract |
+                                       MethodAttributes.HideBySig |
+                                       MethodAttributes.NewSlot |
+                                       MethodAttributes.Virtual;
+                       } else {
+                               Parent.PartialContainer.MethodModifiersValid (this);
 
-                               Type t = parameters.Types [i];
-                               Report.SymbolRelatedToPreviousError (t);
-                               if (this is Indexer)
-                                       Report.Error (55, Location,
-                                                     "Inconsistent accessibility: parameter type `{0}' is less accessible than indexer `{1}'",
-                                                     TypeManager.CSharpName (t), GetSignatureForError ());
-                               else if (this is Operator)
-                                       Report.Error (57, Location,
-                                                     "Inconsistent accessibility: parameter type `{0}' is less accessible than operator `{1}'",
-                                                     TypeManager.CSharpName (t), GetSignatureForError ());
-                               else
-                                       Report.Error (51, Location,
-                                               "Inconsistent accessibility: parameter type `{0}' is less accessible than method `{1}'",
-                                               TypeManager.CSharpName (t), GetSignatureForError ());
-                               error = true;
-                       }
-                       return !error;
-               }
-
-               protected override bool DoDefine()
-               {
-                       if (!base.DoDefine ())
-                               return false;
-
-                       if (IsExplicitImpl) {
-                               TypeExpr texpr = MemberName.Left.GetTypeExpression ().ResolveAsTypeTerminal (this, false);
-                               if (texpr == null)
-                                       return false;
-
-                               InterfaceType = texpr.Type;
-
-                               if (!InterfaceType.IsInterface) {
-                                       Report.Error (538, Location, "`{0}' in explicit interface declaration is not an interface", TypeManager.CSharpName (InterfaceType));
-                                       return false;
-                               }
-                               
-                               if (!Parent.PartialContainer.VerifyImplements (this))
-                                       return false;
-                               
-                       }
-                       return true;
-               }
-
-               protected bool DoDefineBase ()
-               {
-                       if (Name == null)
-                               throw new InternalErrorException ();
-
-                       if (IsInterface) {
-                               ModFlags = Modifiers.PUBLIC |
-                                       Modifiers.ABSTRACT |
-                                       Modifiers.VIRTUAL | (ModFlags & Modifiers.UNSAFE) | (ModFlags & Modifiers.NEW);
-
-                               flags = MethodAttributes.Public |
-                                       MethodAttributes.Abstract |
-                                       MethodAttributes.HideBySig |
-                                       MethodAttributes.NewSlot |
-                                       MethodAttributes.Virtual;
-                       } else {
-                               if (!Parent.PartialContainer.MethodModifiersValid (this))
-                                       return false;
-
-                               flags = Modifiers.MethodAttr (ModFlags);
+                               flags = Modifiers.MethodAttr (ModFlags);
                        }
 
                        if (IsExplicitImpl) {
@@ -3590,38 +3607,93 @@ namespace Mono.CSharp {
                                if ((ModFlags & Modifiers.PARTIAL) != 0) {
                                        Report.Error (754, Location, "A partial method `{0}' cannot explicitly implement an interface",
                                                GetSignatureForError ());
-                                       return false;
                                }
 
                                InterfaceType = iface_texpr.Type;
 
                                if (!InterfaceType.IsInterface) {
-                                       Report.Error (538, Location, "'{0}' in explicit interface declaration is not an interface", TypeManager.CSharpName (InterfaceType));
-                                       return false;
+                                       Report.SymbolRelatedToPreviousError (InterfaceType);
+                                       Report.Error (538, Location, "The type `{0}' in explicit interface declaration is not an interface",
+                                               TypeManager.CSharpName (InterfaceType));
+                               } else {
+                                       Parent.PartialContainer.VerifyImplements (this);
                                }
 
-                               if (!Parent.PartialContainer.VerifyImplements (this))
-                                       return false;
-                               
-                               Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
+                               Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location, Report);
                        }
 
-                       return true;
+                       return base.Define ();
+               }
+
+               protected bool DefineParameters (ParametersCompiled parameters)
+               {
+                       if (!parameters.Resolve (this))
+                               return false;
+
+                       bool error = false;
+                       for (int i = 0; i < parameters.Count; ++i) {
+                               Parameter p = parameters [i];
+
+                               if (p.HasDefaultValue && (IsExplicitImpl || this is Operator || (this is Indexer && parameters.Count == 1)))
+                                       p.Warning_UselessOptionalParameter (Report);
+
+                               if (p.CheckAccessibility (this))
+                                       continue;
+
+                               Type t = parameters.Types [i];
+                               Report.SymbolRelatedToPreviousError (t);
+                               if (this is Indexer)
+                                       Report.Error (55, Location,
+                                                     "Inconsistent accessibility: parameter type `{0}' is less accessible than indexer `{1}'",
+                                                     TypeManager.CSharpName (t), GetSignatureForError ());
+                               else if (this is Operator)
+                                       Report.Error (57, Location,
+                                                     "Inconsistent accessibility: parameter type `{0}' is less accessible than operator `{1}'",
+                                                     TypeManager.CSharpName (t), GetSignatureForError ());
+                               else
+                                       Report.Error (51, Location,
+                                               "Inconsistent accessibility: parameter type `{0}' is less accessible than method `{1}'",
+                                               TypeManager.CSharpName (t), GetSignatureForError ());
+                               error = true;
+                       }
+                       return !error;
                }
 
                public override void Emit()
                {
                        // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
-                       // We are more strict than Microsoft and report CS0626 as error
+                       // We are more strict than csc and report this as an error because SRE does not allow emit that
                        if ((ModFlags & Modifiers.EXTERN) != 0 && !is_external_implementation) {
-                               Report.Error (626, Location,
-                                       "`{0}' is marked as an external but has no DllImport attribute. Consider adding a DllImport attribute to specify the external implementation",
-                                       GetSignatureForError ());
+                               if (this is Constructor) {
+                                       Report.Error (824, Location,
+                                               "Constructor `{0}' is marked `external' but has no external implementation specified", GetSignatureForError ());
+                               } else {
+                                       Report.Error (626, Location,
+                                               "`{0}' is marked as an external but has no DllImport attribute. Consider adding a DllImport attribute to specify the external implementation",
+                                               GetSignatureForError ());
+                               }
                        }
 
                        base.Emit ();
                }
 
+               public override bool EnableOverloadChecks (MemberCore overload)
+               {
+                       //
+                       // Two members can differ in their explicit interface
+                       // type parameter only
+                       //
+                       InterfaceMemberBase imb = overload as InterfaceMemberBase;
+                       if (imb != null && imb.IsExplicitImpl) {
+                               if (IsExplicitImpl) {
+                                       caching_flags |= Flags.MethodOverloadsExist;
+                               }
+                               return true;
+                       }
+
+                       return IsExplicitImpl;
+               }
+
                protected void Error_CannotChangeAccessModifiers (Location loc, MemberInfo base_method, MethodAttributes ma, string suffix)
                {
                        Report.SymbolRelatedToPreviousError (base_method);
@@ -3657,12 +3729,23 @@ namespace Mono.CSharp {
                        set { SetMemberName (new MemberName (MemberName.Left, value, Location)); }
                }
                
+               //
+               // Returns full metadata method name
+               //
                public string GetFullName (MemberName name)
                {
                        if (!IsExplicitImpl)
                                return name.Name;
 
-                       return InterfaceType.FullName.Replace ('+', '.') + "." + name.Name;
+                       //
+                       // When dealing with explicit members a full interface type
+                       // name is added to member name to avoid possible name conflicts
+                       //
+                       // We use CSharpName which gets us full name with benefit of
+                       // replacing predefined names which saves some space and name
+                       // is still unique
+                       //
+                       return TypeManager.CSharpName (InterfaceType) + "." + name.Name;
                }
 
                protected override bool VerifyClsCompliance ()
@@ -3702,19 +3785,19 @@ namespace Mono.CSharp {
 
                protected MethodOrOperator (DeclSpace parent, GenericMethod generic, FullNamedExpression type, int mod,
                                int allowed_mod, MemberName name,
-                               Attributes attrs, Parameters parameters)
+                               Attributes attrs, ParametersCompiled parameters)
                        : base (parent, generic, type, mod, allowed_mod, name,
                                        attrs, parameters)
                {
                }
 
-               public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
+               public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
                {
                        if (a.Target == AttributeTargets.ReturnValue) {
                                if (return_attributes == null)
                                        return_attributes = new ReturnParameter (MethodBuilder, Location);
 
-                               return_attributes.ApplyAttributeBuilder (a, cb);
+                               return_attributes.ApplyAttributeBuilder (a, cb, pa);
                                return;
                        }
 
@@ -3722,7 +3805,7 @@ namespace Mono.CSharp {
                                is_external_implementation = true;
                        }
 
-                       if (a.Type == TypeManager.dllimport_type) {
+                       if (a.Type == pa.DllImport) {
                                const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
                                if ((ModFlags & extern_static) != extern_static) {
                                        Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
@@ -3747,54 +3830,39 @@ namespace Mono.CSharp {
                        }
                }
 
-               public virtual EmitContext CreateEmitContext (DeclSpace tc, ILGenerator ig)
+               protected override bool CheckForDuplications ()
                {
-                       return new EmitContext (
-                               this, tc, this.ds, Location, ig, MemberType, ModFlags, false);
+                       string name = GetFullName (MemberName);
+                       if (MemberName.IsGeneric)
+                               name = MemberName.MakeName (name, MemberName.TypeArguments);
+
+                       return Parent.MemberCache.CheckExistingMembersOverloads (this, name, Parameters, Report);
                }
 
-               protected bool DefineGenericMethod ()
+               public virtual EmitContext CreateEmitContext (ILGenerator ig)
                {
-                       if (!DoDefineBase ())
-                               return false;
+                       return new EmitContext (
+                               this, ig, MemberType);
+               }
 
+               protected override bool ResolveMemberType ()
+               {
 #if GMCS_SOURCE
                        if (GenericMethod != null) {
                                MethodBuilder = Parent.TypeBuilder.DefineMethod (GetFullName (MemberName), flags);
-                               if (!GenericMethod.Define (MethodBuilder))
+                               if (!GenericMethod.Define (this))
                                        return false;
                        }
 #endif
 
-                       return true;
-               }
-
-               public bool ResolveMembers ()
-               {
-                       if (!DefineGenericMethod ())
-                               return false;
-
-                       return true;
+                       return base.ResolveMemberType ();
                }
 
                public override bool Define ()
                {
-                       if (!DoDefine ())
-                               return false;
-
-                       if (!CheckAbstractAndExtern (block != null))
+                       if (!base.Define ())
                                return false;
 
-                       if ((ModFlags & Modifiers.PARTIAL) != 0) {
-                               for (int i = 0; i < Parameters.Count; ++i ) {
-                                       if (Parameters.FixedParameters [i].ModFlags == Parameter.Modifier.OUT) {
-                                               Report.Error (752, Location, "`{0}': A partial method parameters cannot use `out' modifier",
-                                                       GetSignatureForError ());
-                                               return false;
-                                       }
-                               }
-                       }
-
                        if (!CheckBase ())
                                return false;
 
@@ -3803,7 +3871,7 @@ namespace Mono.CSharp {
                                // Current method is turned into automatically generated
                                // wrapper which creates an instance of iterator
                                //
-                               Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
+                               Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags, Compiler);
                                ModFlags |= Modifiers.DEBUGGER_HIDDEN;
                        }
 
@@ -3823,36 +3891,62 @@ namespace Mono.CSharp {
                        MethodData = new MethodData (
                                this, ModFlags, flags, this, MethodBuilder, GenericMethod, base_method);
 
-                       if (!MethodData.Define (Parent.PartialContainer, GetFullName (MemberName)))
+                       if (!MethodData.Define (Parent.PartialContainer, GetFullName (MemberName), Report))
                                return false;
                                        
                        MethodBuilder = MethodData.MethodBuilder;
 
-#if GMCS_SOURCE                                                
-                       if (MethodBuilder.IsGenericMethod)
+                       if (TypeManager.IsGenericMethod (MethodBuilder))
                                Parent.MemberCache.AddGenericMember (MethodBuilder, this);
-#endif                 
                        
                        Parent.MemberCache.AddMember (MethodBuilder, this);
 
+                       return true;
+               }
+
+               protected override void DoMemberTypeIndependentChecks ()
+               {
+                       base.DoMemberTypeIndependentChecks ();
+
+                       CheckAbstractAndExtern (block != null);
+
+                       if ((ModFlags & Modifiers.PARTIAL) != 0) {
+                               for (int i = 0; i < Parameters.Count; ++i) {
+                                       IParameterData p = Parameters.FixedParameters [i];
+                                       if (p.ModFlags == Parameter.Modifier.OUT) {
+                                               Report.Error (752, Location, "`{0}': A partial method parameters cannot use `out' modifier",
+                                                       GetSignatureForError ());
+                                       }
+
+                                       if (p.HasDefaultValue && IsPartialImplementation)
+                                               ((Parameter) p).Warning_UselessOptionalParameter (Report);
+                               }
+                       }
+               }
+
+               protected override void DoMemberTypeDependentChecks ()
+               {
+                       base.DoMemberTypeDependentChecks ();
+
                        if (!TypeManager.IsGenericParameter (MemberType)) {
                                if (MemberType.IsAbstract && MemberType.IsSealed) {
                                        Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
-                                       return false;
                                }
                        }
-
-                       return true;
                }
 
                public override void Emit ()
                {
-#if GMCS_SOURCE                        
                        if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
-                               MethodBuilder.SetCustomAttribute (TypeManager.GetCompilerGeneratedAttribute (Location));
+                               PredefinedAttributes.Get.CompilerGenerated.EmitAttribute (MethodBuilder);
                        if ((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0)
-                               MethodBuilder.SetCustomAttribute (TypeManager.GetDebuggerHiddenAttribute (Location));
-#endif
+                               PredefinedAttributes.Get.DebuggerHidden.EmitAttribute (MethodBuilder);
+
+                       if (TypeManager.IsDynamicType (ReturnType)) {
+                               return_attributes = new ReturnParameter (MethodBuilder, Location);
+                               return_attributes.EmitPredefined (PredefinedAttributes.Get.Dynamic, Location);
+                       }
+
                        if (OptAttributes != null)
                                OptAttributes.Emit ();
 
@@ -3862,7 +3956,13 @@ namespace Mono.CSharp {
                                }
                        }
 
+                       if (MethodData != null)
+                               MethodData.Emit (Parent);
+
                        base.Emit ();
+
+                       Block = null;
+                       MethodData = null;
                }
 
                protected void Error_ConditionalAttributeIsNotValid ()
@@ -3892,19 +3992,6 @@ namespace Mono.CSharp {
 
                #region IMethodData Members
 
-               public CallingConventions CallingConventions {
-                       get {
-                               CallingConventions cc = Parameters.CallingConvention;
-                               if (!IsInterface)
-                                       if ((ModFlags & Modifiers.STATIC) == 0)
-                                               cc |= CallingConventions.HasThis;
-
-                               // FIXME: How is `ExplicitThis' used in C#?
-                       
-                               return cc;
-                       }
-               }
-
                public Type ReturnType {
                        get {
                                return MemberType;
@@ -3917,21 +4004,6 @@ namespace Mono.CSharp {
                        }
                }
 
-               protected override bool CheckBase ()
-               {
-                       if (!base.CheckBase ())
-                               return false;
-
-                       // TODO: Destructor should derive from MethodCore
-                       if (base_method != null && (ModFlags & Modifiers.OVERRIDE) != 0 && Name == "Finalize" &&
-                               base_method.DeclaringType == TypeManager.object_type && !(this is Destructor)) {
-                               Report.Error (249, Location, "Do not override object.Finalize. Instead, provide a destructor");
-                               return false;
-                       }
-
-                       return true;
-               }
-
                /// <summary>
                /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
                /// </summary>
@@ -3945,10 +4017,7 @@ namespace Mono.CSharp {
                                if (OptAttributes == null)
                                        return false;
 
-                               if (TypeManager.conditional_attribute_type == null)
-                                       return false;
-
-                               Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type);
+                               Attribute[] attrs = OptAttributes.SearchMulti (PredefinedAttributes.Get.Conditional);
 
                                if (attrs == null)
                                        return false;
@@ -4074,9 +4143,11 @@ namespace Mono.CSharp {
                const int AllowedInterfaceModifiers =
                        Modifiers.NEW | Modifiers.UNSAFE;
 
+               Method partialMethodImplementation;
+
                public Method (DeclSpace parent, GenericMethod generic,
                               FullNamedExpression return_type, int mod,
-                              MemberName name, Parameters parameters, Attributes attrs)
+                              MemberName name, ParametersCompiled parameters, Attributes attrs)
                        : base (parent, generic, return_type, mod,
                                parent.PartialContainer.Kind == Kind.Interface ? AllowedInterfaceModifiers : AllowedModifiers,
                                name, attrs, parameters)
@@ -4084,7 +4155,7 @@ namespace Mono.CSharp {
                }
 
                protected Method (DeclSpace parent, FullNamedExpression return_type, int mod, int amod,
-                                       MemberName name, Parameters parameters, Attributes attrs)
+                                       MemberName name, ParametersCompiled parameters, Attributes attrs)
                        : base (parent, null, return_type, mod, amod, name, attrs, parameters)
                {
                }
@@ -4094,11 +4165,11 @@ namespace Mono.CSharp {
                        return base.GetSignatureForError () + Parameters.GetSignatureForError ();
                }
 
-               void Error_DuplicateEntryPoint (MethodInfo b, Location location)
+               void Error_DuplicateEntryPoint (Method b)
                {
-                       Report.Error (17, location,
+                       Report.Error (17, b.Location,
                                "Program `{0}' has more than one entry point defined: `{1}'",
-                               CodeGen.FileName, TypeManager.CSharpSignature(b));
+                               CodeGen.FileName, b.GetSignatureForError ());
                }
 
                bool IsEntryPoint ()
@@ -4119,9 +4190,21 @@ namespace Mono.CSharp {
                                        (Parameters[0].ModFlags & ~Parameter.Modifier.PARAMS) == Parameter.Modifier.NONE;
                }
 
-               public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
+               public override FullNamedExpression LookupNamespaceOrType (string name, Location loc, bool ignore_cs0104)
+               {
+                       TypeParameter[] tp = CurrentTypeParameters;
+                       if (tp != null) {
+                               TypeParameter t = TypeParameter.FindTypeParameter (tp, name);
+                               if (t != null)
+                                       return new TypeParameterExpr (t, loc);
+                       }
+
+                       return base.LookupNamespaceOrType (name, loc, ignore_cs0104);
+               }
+
+               public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
                {
-                       if (a.Type == TypeManager.conditional_attribute_type) {
+                       if (a.Type == pa.Conditional) {
                                if (IsExplicitImpl) {
                                        Error_ConditionalAttributeIsNotValid ();
                                        return;
@@ -4157,16 +4240,19 @@ namespace Mono.CSharp {
                                }
                        }
 
-                       if (a.Type == TypeManager.extension_attribute_type) {
+                       if (a.Type == pa.Extension) {
                                a.Error_MisusedExtensionAttribute ();
                                return;
                        }
 
-                       base.ApplyAttributeBuilder (a, cb);
+                       base.ApplyAttributeBuilder (a, cb, pa);
                }
 
-               public bool CheckForDuplications ()
+               protected override bool CheckForDuplications ()
                {
+                       if (!base.CheckForDuplications ())
+                               return false;
+
                        ArrayList ar = Parent.PartialContainer.Properties;
                        if (ar != null) {
                                for (int i = 0; i < ar.Count; ++i) {
@@ -4188,24 +4274,48 @@ namespace Mono.CSharp {
                        return true;
                }
 
+               protected override bool CheckBase ()
+               {
+                       if (!base.CheckBase ())
+                               return false;
+
+                       if (base_method != null && (ModFlags & Modifiers.OVERRIDE) != 0 && Name == Destructor.MetadataName) {
+                               Report.Error (249, Location, "Do not override `{0}'. Use destructor syntax instead",
+                                       TypeManager.CSharpSignature (base_method));
+                       }
+
+                       return true;
+               }
+
+               public override TypeParameter[] CurrentTypeParameters {
+                       get {
+                               if (GenericMethod != null)
+                                       return GenericMethod.CurrentTypeParameters;
+
+                               return null;
+                       }
+               }
+
                //
                // Creates the type
                //
                public override bool Define ()
                {
+                       if (type_name == TypeManager.system_void_expr && Parameters.IsEmpty && Name == Destructor.MetadataName) {
+                               Report.Warning (465, 1, Location, "Introducing `Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?");
+                       }
+
                        if (!base.Define ())
                                return false;
 
+                       if (partialMethodImplementation != null && IsPartialDefinition)
+                               MethodBuilder = partialMethodImplementation.MethodBuilder;
+
                        if (RootContext.StdLib && TypeManager.IsSpecialType (ReturnType)) {
-                               Error1599 (Location, ReturnType);
+                               Error1599 (Location, ReturnType, Report);
                                return false;
                        }
 
-                       if (ReturnType == TypeManager.void_type && Parameters.Count == 0 && 
-                               Name == "Finalize" && !(this is Destructor)) {
-                               Report.Warning (465, 1, Location, "Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?");
-                       }
-
                        if (base_method != null && (ModFlags & Modifiers.NEW) == 0) {
                                if (Parameters.Count == 1 && ParameterTypes [0] == TypeManager.object_type && Name == "Equals")
                                        Parent.PartialContainer.Mark_HasEquals ();
@@ -4217,25 +4327,20 @@ namespace Mono.CSharp {
                                return true;
 
                        if (Parameters.HasExtensionMethodType) {
-                               if (Parent.IsStaticClass && !Parent.IsGeneric) {
+                               if (Parent.PartialContainer.IsStaticClass && !Parent.IsGeneric) {
                                        if (!Parent.IsTopLevel)
                                                Report.Error (1109, Location, "`{0}': Extension methods cannot be defined in a nested class",
                                                        GetSignatureForError ());
 
-                                       if (TypeManager.extension_attribute_type == null) {
+                                       PredefinedAttribute pa = PredefinedAttributes.Get.Extension;
+                                       if (!pa.IsDefined) {
                                                Report.Error (1110, Location,
                                                        "`{0}': Extension methods cannot be declared without a reference to System.Core.dll assembly. Add the assembly reference or remove `this' modifer from the first parameter",
                                                        GetSignatureForError ());
-                                       } else if (TypeManager.extension_attribute_attr == null) {
-                                               ConstructorInfo ci = TypeManager.GetPredefinedConstructor (
-                                                       TypeManager.extension_attribute_type, Location, System.Type.EmptyTypes);
-
-                                               if (ci != null)
-                                                       TypeManager.extension_attribute_attr = new CustomAttributeBuilder (ci, new object [0]);
                                        }
 
                                        ModFlags |= Modifiers.METHOD_EXTENSION;
-                                       Parent.ModFlags |= Modifiers.METHOD_EXTENSION;
+                                       Parent.PartialContainer.ModFlags |= Modifiers.METHOD_EXTENSION;
                                        CodeGen.Assembly.HasExtensionMethods = true;
                                } else {
                                        Report.Error (1106, Location, "`{0}': Extension methods must be defined in a non-generic static class",
@@ -4257,15 +4362,12 @@ namespace Mono.CSharp {
                                                        Report.Warning (402, 4, Location, "`{0}': an entry point cannot be generic or in a generic type",
                                                                GetSignatureForError ());
                                                } else {
-                                                       IMethodData md = TypeManager.GetMethod (MethodBuilder);
-                                                       md.SetMemberIsUsed ();
-
-                                                       RootContext.EntryPoint = MethodBuilder;
-                                                       RootContext.EntryPointLocation = Location;
+                                                       SetMemberIsUsed ();
+                                                       RootContext.EntryPoint = this;
                                                }
                                        } else {
-                                               Error_DuplicateEntryPoint (RootContext.EntryPoint, RootContext.EntryPointLocation);
-                                               Error_DuplicateEntryPoint (MethodBuilder, Location);
+                                               Error_DuplicateEntryPoint (RootContext.EntryPoint);
+                                               Error_DuplicateEntryPoint (this);
                                        }
                                } else {
                                        Report.Warning (28, 4, Location, "`{0}' has the wrong signature to be an entry point",
@@ -4285,28 +4387,21 @@ namespace Mono.CSharp {
                                Report.Debug (64, "METHOD EMIT", this, MethodBuilder, Location, Block, MethodData);
                                if (IsPartialDefinition) {
                                        //
-                                       // Do attribute checks only when partial implementation does not exist
+                                       // Use partial method implementation builder for partial method declaration attributes
                                        //
-                                       if (MethodBuilder == null)
-                                               base.Emit ();
-
-                                       return;
-                               }
-
-                               if ((ModFlags & Modifiers.PARTIAL) != 0 && (caching_flags & Flags.PartialDefinitionExists) == 0)
+                                       if (partialMethodImplementation != null) {
+                                               MethodBuilder = partialMethodImplementation.MethodBuilder;
+                                               return;
+                                       }
+                               } else if ((ModFlags & Modifiers.PARTIAL) != 0 && (caching_flags & Flags.PartialDefinitionExists) == 0) {
                                        Report.Error (759, Location, "A partial method `{0}' implementation is missing a partial method declaration",
                                                GetSignatureForError ());
+                               }
 
-                               MethodData.Emit (Parent);
                                base.Emit ();
                                
-#if GMCS_SOURCE                                
                                if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
-                                       MethodBuilder.SetCustomAttribute (TypeManager.extension_attribute_attr);
-#endif
-
-                               Block = null;
-                               MethodData = null;
+                                       PredefinedAttributes.Get.Extension.EmitAttribute (MethodBuilder);
                        } catch {
                                Console.WriteLine ("Internal compiler error at {0}: exception caught while emitting {1}",
                                                   Location, MethodBuilder);
@@ -4326,7 +4421,7 @@ namespace Mono.CSharp {
                        return base.EnableOverloadChecks (overload);
                }
 
-               public static void Error1599 (Location loc, Type t)
+               public static void Error1599 (Location loc, Type t, Report Report)
                {
                        Report.Error (1599, loc, "Method or delegate cannot return type `{0}'", TypeManager.CSharpName (t));
                }
@@ -4349,7 +4444,12 @@ namespace Mono.CSharp {
                public void SetPartialDefinition (Method methodDefinition)
                {
                        caching_flags |= Flags.PartialDefinitionExists;
-                       methodDefinition.MethodBuilder = MethodBuilder;
+                       methodDefinition.partialMethodImplementation = this;
+
+                       for (int i = 0; i < methodDefinition.Parameters.Count; ++i ) {
+                               Parameters [i].DefaultValue = methodDefinition.Parameters [i].DefaultValue;
+                       }
+
                        if (methodDefinition.attributes == null)
                                return;
 
@@ -4365,10 +4465,10 @@ namespace Mono.CSharp {
                        if (!base.VerifyClsCompliance ())
                                return false;
 
-                       if (ParameterInfo.Count > 0) {
+                       if (!Parameters.IsEmpty) {
                                ArrayList al = (ArrayList)Parent.PartialContainer.MemberCache.Members [Name];
                                if (al.Count > 1)
-                                       MemberCache.VerifyClsParameterConflict (al, this, MethodBuilder);
+                                       MemberCache.VerifyClsParameterConflict (al, this, MethodBuilder, Report);
                        }
 
                        return true;
@@ -4377,44 +4477,59 @@ namespace Mono.CSharp {
 
        public abstract class ConstructorInitializer : ExpressionStatement
        {
-               ArrayList argument_list;
+               Arguments argument_list;
                MethodGroupExpr base_constructor_group;
-               
-               public ConstructorInitializer (ArrayList argument_list, Location loc)
+
+               public ConstructorInitializer (Arguments argument_list, Location loc)
                {
                        this.argument_list = argument_list;
                        this.loc = loc;
                }
 
-               public ArrayList Arguments {
+               public Arguments Arguments {
                        get {
                                return argument_list;
                        }
                }
 
-               public override Expression CreateExpressionTree (EmitContext ec)
+               public override Expression CreateExpressionTree (ResolveContext ec)
                {
                        throw new NotSupportedException ("ET");
                }
 
-               public bool Resolve (ConstructorBuilder caller_builder, EmitContext ec)
+               public override Expression DoResolve (ResolveContext ec)
                {
-                       if (argument_list != null){
-                               foreach (Argument a in argument_list){
-                                       if (!a.Resolve (ec, loc))
-                                               return false;
+                       eclass = ExprClass.Value;
+
+                       // TODO: ec.GetSignatureForError ()
+                       ConstructorBuilder caller_builder = ((Constructor) ec.MemberContext).ConstructorBuilder;
+
+                       if (argument_list != null) {
+                               bool dynamic;
+
+                               //
+                               // Spec mandates that constructor initializer will not have `this' access
+                               //
+                               using (ec.Set (ResolveContext.Options.BaseInitializer)) {
+                                       argument_list.Resolve (ec, out dynamic);
+                               }
+
+                               if (dynamic) {
+                                       SimpleName ctor = new SimpleName (ConstructorBuilder.ConstructorName, loc);
+                                       return new DynamicInvocation (ctor, argument_list, loc).Resolve (ec) as ExpressionStatement;
                                }
                        }
 
+                       type = ec.CurrentType;
                        if (this is ConstructorBaseInitializer) {
-                               if (ec.ContainerType.BaseType == null)
-                                       return true;
+                               if (ec.CurrentType.BaseType == null)
+                                       return this;
 
-                               type = ec.ContainerType.BaseType;
-                               if (ec.ContainerType.IsValueType) {
-                                       Report.Error (522, loc,
+                               type = ec.CurrentType.BaseType;
+                               if (TypeManager.IsStruct (ec.CurrentType)) {
+                                       ec.Report.Error (522, loc,
                                                "`{0}': Struct constructors cannot call base constructors", TypeManager.CSharpSignature (caller_builder));
-                                       return false;
+                                       return this;
                                }
                        } else {
                                //
@@ -4423,10 +4538,8 @@ namespace Mono.CSharp {
                                //
                                // struct D { public D (int a) : this () {}
                                //
-                               if (ec.ContainerType.IsValueType && argument_list == null)
-                                       return true;
-                               
-                               type = ec.ContainerType;
+                               if (TypeManager.IsStruct (ec.CurrentType) && argument_list == null)
+                                       return this;                    
                        }
 
                        base_constructor_group = MemberLookupFinal (
@@ -4435,26 +4548,24 @@ namespace Mono.CSharp {
                                loc) as MethodGroupExpr;
                        
                        if (base_constructor_group == null)
-                               return false;
+                               return this;
                        
                        base_constructor_group = base_constructor_group.OverloadResolve (
                                ec, ref argument_list, false, loc);
                        
                        if (base_constructor_group == null)
-                               return false;
+                               return this;
+
+                       if (!ec.IsStatic)
+                               base_constructor_group.InstanceExpression = ec.GetThis (loc);
                        
                        ConstructorInfo base_ctor = (ConstructorInfo)base_constructor_group;
-                       
+
                        if (base_ctor == caller_builder){
-                               Report.Error (516, loc, "Constructor `{0}' cannot call itself", TypeManager.CSharpSignature (caller_builder));
+                               ec.Report.Error (516, loc, "Constructor `{0}' cannot call itself", TypeManager.CSharpSignature (caller_builder));
                        }
                                                
-                       return true;
-               }
-
-               public override Expression DoResolve (EmitContext ec)
-               {
-                       throw new NotSupportedException ();
+                       return this;
                }
 
                public override void Emit (EmitContext ec)
@@ -4464,9 +4575,7 @@ namespace Mono.CSharp {
                                return;
                        
                        ec.Mark (loc);
-                       if (!ec.IsStatic)
-                               base_constructor_group.InstanceExpression = ec.GetThis (loc);
-                       
+
                        base_constructor_group.EmitCall (ec, argument_list);
                }
 
@@ -4477,7 +4586,7 @@ namespace Mono.CSharp {
        }
 
        public class ConstructorBaseInitializer : ConstructorInitializer {
-               public ConstructorBaseInitializer (ArrayList argument_list, Location l) :
+               public ConstructorBaseInitializer (Arguments argument_list, Location l) :
                        base (argument_list, l)
                {
                }
@@ -4491,7 +4600,7 @@ namespace Mono.CSharp {
        }
 
        public class ConstructorThisInitializer : ConstructorInitializer {
-               public ConstructorThisInitializer (ArrayList argument_list, Location l) :
+               public ConstructorThisInitializer (Arguments argument_list, Location l) :
                        base (argument_list, l)
                {
                }
@@ -4521,10 +4630,10 @@ namespace Mono.CSharp {
                // The spec claims that static is not permitted, but
                // my very own code has static constructors.
                //
-               public Constructor (DeclSpace parent, string name, int mod, Parameters args,
+               public Constructor (DeclSpace parent, string name, int mod, Attributes attrs, ParametersCompiled args,
                                    ConstructorInitializer init, Location loc)
                        : base (parent, null, null, mod, AllowedModifiers,
-                               new MemberName (name, loc), null, args)
+                               new MemberName (name, loc), attrs, args)
                {
                        Initializer = init;
                }
@@ -4550,7 +4659,7 @@ namespace Mono.CSharp {
                                        (Initializer.Arguments == null);
                }
 
-               public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
+               public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
                {
                        if (a.IsValidSecurityAttribute ()) {
                                if (declarative_security == null) {
@@ -4585,8 +4694,8 @@ namespace Mono.CSharp {
                                return false;
 
                        if ((caching_flags & Flags.MethodOverloadsExist) != 0)
-                               Parent.MemberCache.CheckExistingMembersOverloads (this, ConstructorBuilder.ConstructorName,
-                                       Parameters);
+                               Parent.MemberCache.CheckExistingMembersOverloads (this, ConstructorInfo.ConstructorName,
+                                       Parameters, Report);
 
                        if (Parent.PartialContainer.Kind == Kind.Struct) {
                                if (Parameters.Count == 0) {
@@ -4645,7 +4754,6 @@ namespace Mono.CSharp {
                                if (!IsDefault ()) {
                                        Report.Error (669, Location, "`{0}': A class with the ComImport attribute cannot have a user-defined constructor",
                                                Parent.GetSignatureForError ());
-                                       return false;
                                }
                                ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall);
                        }
@@ -4656,7 +4764,7 @@ namespace Mono.CSharp {
                        // It's here only to report an error
                        if (block != null && block.IsIterator) {
                                member_type = TypeManager.void_type;
-                               Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
+                               Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags, Compiler);
                        }
 
                        return true;
@@ -4668,15 +4776,13 @@ namespace Mono.CSharp {
                public override void Emit ()
                {
                        if ((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0)
-                               ConstructorBuilder.SetCustomAttribute (TypeManager.GetDebuggerHiddenAttribute (Location));
+                               PredefinedAttributes.Get.DebuggerHidden.EmitAttribute (ConstructorBuilder);
 
                        if (OptAttributes != null)
                                OptAttributes.Emit ();
 
                        base.Emit ();
 
-                       EmitContext ec = CreateEmitContext (null, null);
-
                        //
                        // If we use a "this (...)" constructor initializer, then
                        // do not emit field initializers, they are initialized in the other constructor
@@ -4684,8 +4790,11 @@ namespace Mono.CSharp {
                        bool emit_field_initializers = ((ModFlags & Modifiers.STATIC) != 0) ||
                                !(Initializer is ConstructorThisInitializer);
 
+                       BlockContext bc = new BlockContext (this, block, TypeManager.void_type);
+                       bc.Set (ResolveContext.Options.ConstructorScope);
+
                        if (emit_field_initializers)
-                               Parent.PartialContainer.ResolveFieldInitializers (ec);
+                               Parent.PartialContainer.ResolveFieldInitializers (bc);
 
                        if (block != null) {
                                // If this is a non-static `struct' constructor and doesn't have any
@@ -4694,44 +4803,32 @@ namespace Mono.CSharp {
                                        ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
                                        block.AddThisVariable (Parent, Location);
 
-                               if (!block.ResolveMeta (ec, ParameterInfo))
-                                       block = null;
-
                                if (block != null && (ModFlags & Modifiers.STATIC) == 0){
                                        if (Parent.PartialContainer.Kind == Kind.Class && Initializer == null)
                                                Initializer = new GeneratedBaseInitializer (Location);
 
-                                       //
-                                       // Spec mandates that Initializers will not have `this' access
-                                       //
                                        if (Initializer != null) {
-                                               ec.IsStatic = true;
-                                               Initializer.Resolve (ConstructorBuilder, ec);
-                                               ec.IsStatic = false;
                                                block.AddScopeStatement (new StatementExpression (Initializer));
                                        }
                                }
                        }
 
                        Parameters.ApplyAttributes (ConstructorBuilder);
-                       
-                       SourceMethod source = null;
-                       if (block == null)
-                               ec.OmitDebuggingInfo = true;
-                       else
-                               source = SourceMethod.Create (Parent, ConstructorBuilder, block);
 
-                       bool unreachable = false;
-                       if (block != null) {
-                               if (!ec.ResolveTopBlock (null, block, ParameterInfo, this, out unreachable))
-                                       return;
+                       SourceMethod source = SourceMethod.Create (Parent, ConstructorBuilder, block);
 
-                               ec.EmitMeta (block);
+                       if (block != null) {
+                               if (block.Resolve (null, bc, Parameters, this)) {
+                                       EmitContext ec = new EmitContext (this, ConstructorBuilder.GetILGenerator (), bc.ReturnType);
+                                       ec.With (EmitContext.Options.ConstructorScope, true);
 
-                               if (Report.Errors > 0)
-                                       return;
+                                       if (!ec.HasReturnLabel && bc.HasReturnLabel) {
+                                               ec.ReturnLabel = bc.ReturnLabel;
+                                               ec.HasReturnLabel = true;
+                                       }
 
-                               ec.EmitResolvedTopBlock (block, unreachable);
+                                       block.Emit (ec);
+                               }
                        }
 
                        if (source != null)
@@ -4769,10 +4866,10 @@ namespace Mono.CSharp {
                                return false;
                        }
                        
-                       if (ParameterInfo.Count > 0) {
-                               ArrayList al = (ArrayList)Parent.MemberCache.Members [".ctor"];
+                       if (!Parameters.IsEmpty) {
+                               ArrayList al = (ArrayList)Parent.MemberCache.Members [ConstructorInfo.ConstructorName];
                                if (al.Count > 2)
-                                       MemberCache.VerifyClsParameterConflict (al, this, ConstructorBuilder);
+                                       MemberCache.VerifyClsParameterConflict (al, this, ConstructorBuilder, Report);
  
                                if (TypeManager.IsSubclassOf (Parent.TypeBuilder, TypeManager.attribute_type)) {
                                        foreach (Type param in Parameters.Types) {
@@ -4788,20 +4885,6 @@ namespace Mono.CSharp {
 
                #region IMethodData Members
 
-               public System.Reflection.CallingConventions CallingConventions {
-                       get {
-                               CallingConventions cc = Parameters.CallingConvention;
-
-                               if (Parent.PartialContainer.Kind == Kind.Class)
-                                       if ((ModFlags & Modifiers.STATIC) == 0)
-                                               cc |= CallingConventions.HasThis;
-
-                               // FIXME: How is `ExplicitThis' used in C#?
-                       
-                               return cc;
-                       }
-               }
-
                public MemberName MethodName {
                        get {
                                return MemberName;
@@ -4814,12 +4897,9 @@ namespace Mono.CSharp {
                        }
                }
 
-               public EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
+               public EmitContext CreateEmitContext (ILGenerator ig)
                {
-                       ILGenerator ig_ = ConstructorBuilder.GetILGenerator ();
-                       EmitContext ec = new EmitContext (this, Parent, Location, ig_, TypeManager.void_type, ModFlags, true);
-                       ec.CurrentBlock = block;
-                       return ec;
+                       throw new NotImplementedException ();
                }
 
                public bool IsExcluded()
@@ -4849,12 +4929,12 @@ namespace Mono.CSharp {
                MemberName MethodName { get; }
                Type ReturnType { get; }
                GenericMethod GenericMethod { get; }
-               Parameters ParameterInfo { get; }
+               ParametersCompiled ParameterInfo { get; }
 
                Attributes OptAttributes { get; }
                ToplevelBlock Block { get; set; }
 
-               EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig);
+               EmitContext CreateEmitContext (ILGenerator ig);
                ObsoleteAttribute GetObsoleteAttribute ();
                string GetSignatureForError ();
                bool IsExcluded ();
@@ -4867,9 +4947,7 @@ namespace Mono.CSharp {
        // Encapsulates most of the Method's state
        //
        public class MethodData {
-#if GMCS_SOURCE
                static FieldInfo methodbuilder_attrs_field;
-#endif
                public readonly IMethodData method;
 
                public readonly GenericMethod GenericMethod;
@@ -4922,7 +5000,7 @@ namespace Mono.CSharp {
                        this.parent_method = parent_method;
                }
 
-               public bool Define (DeclSpace parent, string method_full_name)
+               public bool Define (DeclSpace parent, string method_full_name, Report Report)
                {
                        string name = method.MethodName.Basename;
 
@@ -5061,15 +5139,8 @@ namespace Mono.CSharp {
                        else
                                declaring_type = container.TypeBuilder;
 
-                       if (implementing != null){
-                               //
-                               // clear the pending implemntation flag
-                               //
-                               pending.ImplementMethod (name, member.InterfaceType, this, member.IsExplicitImpl);
-
-                               if (member.IsExplicitImpl)
-                                       container.TypeBuilder.DefineMethodOverride (
-                                               builder, implementing);
+                       if (implementing != null && member.IsExplicitImpl) {
+                                       container.TypeBuilder.DefineMethodOverride (builder, implementing);
                        }
 
                        TypeManager.AddMethod (builder, method);
@@ -5081,8 +5152,7 @@ namespace Mono.CSharp {
                                if (implementing != null)
                                        parent_method = implementing;
 
-                               EmitContext ec = method.CreateEmitContext (container, null);
-                               if (!GenericMethod.DefineType (ec, builder, parent_method, is_override))
+                               if (!GenericMethod.DefineType (GenericMethod, builder, parent_method, is_override))
                                        return false;
                        }
 
@@ -5093,12 +5163,13 @@ namespace Mono.CSharp {
                /// <summary>
                /// Create the MethodBuilder for the method 
                /// </summary>
-               void DefineMethodBuilder (TypeContainer container, string method_name, Parameters param)
+               void DefineMethodBuilder (TypeContainer container, string method_name, ParametersCompiled param)
                {
                        if (builder == null) {
                                builder = container.TypeBuilder.DefineMethod (
                                        method_name, flags, method.CallingConventions,
-                                       method.ReturnType, param.GetEmitTypes ());
+                                       TypeManager.TypeToReflectionType (method.ReturnType),
+                                       param.GetEmitTypes ());
                                return;
                        }
 
@@ -5109,19 +5180,16 @@ namespace Mono.CSharp {
                        //
                        builder.SetParameters (param.GetEmitTypes ());
                        builder.SetReturnType (method.ReturnType);
-
+#endif
                        if (builder.Attributes != flags) {
                                try {
                                        if (methodbuilder_attrs_field == null)
                                                methodbuilder_attrs_field = typeof (MethodBuilder).GetField ("attrs", BindingFlags.NonPublic | BindingFlags.Instance);
                                        methodbuilder_attrs_field.SetValue (builder, flags);
                                } catch {
-                                       Report.RuntimeMissingSupport (method.Location, "Generic method MethodAttributes");
+                                       RootContext.ToplevelTypes.Compiler.Report.RuntimeMissingSupport (method.Location, "Generic method MethodAttributes");
                                }
                        }
-#else
-                       throw new InternalErrorException ();
-#endif
                }
 
                //
@@ -5129,102 +5197,106 @@ namespace Mono.CSharp {
                // 
                public void Emit (DeclSpace parent)
                {
-                       ToplevelBlock block = method.Block;
-
-                       EmitContext ec;
-                       if (block != null)
-                               ec = method.CreateEmitContext (parent, builder.GetILGenerator ());
-                       else
-                               ec = method.CreateEmitContext (parent, null);
-
                        method.ParameterInfo.ApplyAttributes (MethodBuilder);
 
                        if (GenericMethod != null)
                                GenericMethod.EmitAttributes ();
 
-                       SourceMethod source = SourceMethod.Create (parent, MethodBuilder, method.Block);
-
-                       //
-                       // Handle destructors specially
                        //
-                       // FIXME: This code generates buggy code
+                       // clear the pending implementation flag
                        //
-                       if (member is Destructor)
-                               EmitDestructor (ec, block);
-                       else
-                               ec.EmitTopBlock (method, block);
+                       if (implementing != null)
+                               parent.PartialContainer.PendingImplementations.ImplementMethod (method.MethodName.Basename,
+                                       member.InterfaceType, this, member.IsExplicitImpl);
 
-                       if (source != null) {
-                               method.EmitExtraSymbolInfo (source);
-                               source.CloseMethod ();
-                       }
-               }
-
-               void EmitDestructor (EmitContext ec, ToplevelBlock block)
-               {
-                       ILGenerator ig = ec.ig;
-                       
-                       Label finish = ig.DefineLabel ();
+                       SourceMethod source = SourceMethod.Create (parent, MethodBuilder, method.Block);
 
-                       block.SetDestructor ();
-                       
-                       ig.BeginExceptionBlock ();
-                       ec.ReturnLabel = finish;
-                       ec.HasReturnLabel = true;
-                       ec.EmitTopBlock (method, block);
-                       
-                       // ig.MarkLabel (finish);
-                       ig.BeginFinallyBlock ();
-                       
-                       if (ec.ContainerType.BaseType != null) {
-                               Expression member_lookup = Expression.MemberLookup (
-                                       ec.ContainerType.BaseType, null, ec.ContainerType.BaseType,
-                                       "Finalize", MemberTypes.Method, Expression.AllBindingFlags, method.Location);
+                       ToplevelBlock block = method.Block;
+                       if (block != null) {
+                               BlockContext bc = new BlockContext ((IMemberContext) method, block, method.ReturnType);
+                               if (block.Resolve (null, bc, method.ParameterInfo, method)) {
+                                       EmitContext ec = method.CreateEmitContext (MethodBuilder.GetILGenerator ());
+                                       if (!ec.HasReturnLabel && bc.HasReturnLabel) {
+                                               ec.ReturnLabel = bc.ReturnLabel;
+                                               ec.HasReturnLabel = true;
+                                       }
 
-                               if (member_lookup != null){
-                                       MethodGroupExpr base_destructor = ((MethodGroupExpr) member_lookup);
-                               
-                                       ig.Emit (OpCodes.Ldarg_0);
-                                       ig.Emit (OpCodes.Call, (MethodInfo) base_destructor.Methods [0]);
+                                       block.Emit (ec);
                                }
                        }
-                       
-                       ig.EndExceptionBlock ();
-                       //ig.MarkLabel (ec.ReturnLabel);
-                       ig.Emit (OpCodes.Ret);
+
+                       if (source != null) {
+                               method.EmitExtraSymbolInfo (source);
+                               source.CloseMethod ();
+                       }
                }
        }
 
-       // TODO: Should derive from MethodCore
-       public class Destructor : Method
+       public class Destructor : MethodOrOperator
        {
                const int AllowedModifiers =
                        Modifiers.UNSAFE |
                        Modifiers.EXTERN;
 
-               static string[] attribute_targets = new string [] { "method" };
+               static readonly string[] attribute_targets = new string [] { "method" };
+
+               public static readonly string MetadataName = "Finalize";
 
-               public Destructor (DeclSpace parent, FullNamedExpression return_type, int mod,
-                                  string name, Parameters parameters, Attributes attrs,
-                                  Location l)
-                       : base (parent, return_type, mod, AllowedModifiers, new MemberName (name, l),
-                               parameters, attrs)
+               public Destructor (DeclSpace parent, int mod, ParametersCompiled parameters, Attributes attrs, Location l)
+                       : base (parent, null, TypeManager.system_void_expr, mod, AllowedModifiers,
+                               new MemberName (MetadataName, l), attrs, parameters)
                {
                        ModFlags &= ~Modifiers.PRIVATE;
-                       if (!RootContext.StdLib && parent.Name == "System.Object")
-                               ModFlags |= Modifiers.PROTECTED | Modifiers.VIRTUAL;
-                       else
-                               ModFlags |= Modifiers.PROTECTED | Modifiers.OVERRIDE;
+                       ModFlags |= Modifiers.PROTECTED;
                }
 
-               public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
+               public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
                {
-                       if (a.Type == TypeManager.conditional_attribute_type) {
+                       if (a.Type == pa.Conditional) {
                                Error_ConditionalAttributeIsNotValid ();
                                return;
                        }
 
-                       base.ApplyAttributeBuilder (a, cb);
+                       base.ApplyAttributeBuilder (a, cb, pa);
+               }
+
+               protected override bool CheckBase ()
+               {
+                       flags |= MethodAttributes.Virtual;
+
+                       if (!base.CheckBase ())
+                               return false;
+
+                       if (Parent.PartialContainer.BaseCache == null)
+                               return true;
+
+                       Type base_type = Parent.PartialContainer.BaseCache.Container.Type;
+                       if (base_type != null && Block != null) {
+                               MethodGroupExpr method_expr = Expression.MethodLookup (Parent.Module.Compiler, Parent.TypeBuilder, base_type, MetadataName, Location);
+                               if (method_expr == null)
+                                       throw new NotImplementedException ();
+
+                               method_expr.IsBase = true;
+                               method_expr.InstanceExpression = new CompilerGeneratedThis (Parent.TypeBuilder, Location);
+
+                               ToplevelBlock new_block = new ToplevelBlock (Compiler, Block.StartLocation);
+                               new_block.EndLocation = Block.EndLocation;
+
+                               Block finaly_block = new ExplicitBlock (new_block, Location, Location);
+                               Block try_block = new Block (new_block, block);
+
+                               //
+                               // 0-size arguments to avoid CS0250 error
+                               // TODO: Should use AddScopeStatement or something else which emits correct
+                               // debugger scope
+                               //
+                               finaly_block.AddStatement (new StatementExpression (new Invocation (method_expr, new Arguments (0))));
+                               new_block.AddStatement (new TryFinally (try_block, finaly_block, Location));
+
+                               block = new_block;
+                       }
+
+                       return true;
                }
 
                public override string GetSignatureForError ()
@@ -5232,6 +5304,11 @@ namespace Mono.CSharp {
                        return Parent.GetSignatureForError () + ".~" + Parent.MemberName.Name + "()";
                }
 
+               protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
+               {
+                       return null;
+               }
+
                public override string[] ValidAttributeTargets {
                        get {
                                return attribute_targets;
@@ -5239,32 +5316,14 @@ namespace Mono.CSharp {
                }
        }
        
-       abstract public class MemberBase : MemberCore {
+       public abstract class MemberBase : MemberCore
+       {
                protected FullNamedExpression type_name;
+               protected Type member_type;
+
                public readonly DeclSpace ds;
                public readonly GenericMethod GenericMethod;
 
-               //
-               // The type of this property / indexer / event
-               //
-               protected Type member_type;
-               public Type MemberType {
-                       get {
-                               // TODO: Who wrote this, ResolveAsTypeTerminal can have side effects
-                               if (member_type == null && type_name != null) {
-                                       IResolveContext rc = GenericMethod == null ? this : (IResolveContext)ds;
-                                       type_name = type_name.ResolveAsTypeTerminal (rc, false);
-                                       if (type_name != null) {
-                                               member_type = type_name.Type;
-                                       }
-                               }
-                               return member_type;
-                       }
-               }
-
-               //
-               // The constructor is only exposed to our children
-               //
                protected MemberBase (DeclSpace parent, GenericMethod generic,
                                      FullNamedExpression type, int mod, int allowed_mod, int def_mod,
                                      MemberName name, Attributes attrs)
@@ -5272,31 +5331,46 @@ namespace Mono.CSharp {
                {
                        this.ds = generic != null ? generic : (DeclSpace) parent;
                        this.type_name = type;
-                       ModFlags = Modifiers.Check (allowed_mod, mod, def_mod, Location);
+                       ModFlags = Modifiers.Check (allowed_mod, mod, def_mod, Location, Report);
                        GenericMethod = generic;
                        if (GenericMethod != null)
                                GenericMethod.ModFlags = ModFlags;
                }
 
-               protected virtual bool CheckBase ()
+               //
+               // Main member define entry
+               //
+               public override bool Define ()
                {
-                       CheckProtectedModifier ();
+                       DoMemberTypeIndependentChecks ();
+
+                       //
+                       // Returns false only when type resolution failed
+                       //
+                       if (!ResolveMemberType ())
+                               return false;
 
+                       DoMemberTypeDependentChecks ();
                        return true;
                }
 
-               protected virtual bool DoDefine ()
+               //
+               // Any type_name independent checks
+               //
+               protected virtual void DoMemberTypeIndependentChecks ()
                {
-                       if (MemberType == null)
-                               return false;
-
-                       if ((Parent.ModFlags & Modifiers.SEALED) != 0 && 
-                               (ModFlags & (Modifiers.VIRTUAL|Modifiers.ABSTRACT)) != 0) {
-                                       Report.Error (549, Location, "New virtual member `{0}' is declared in a sealed class `{1}'",
-                                               GetSignatureForError (), Parent.GetSignatureForError ());
-                                       return false;
+                       if ((Parent.ModFlags & Modifiers.SEALED) != 0 &&
+                               (ModFlags & (Modifiers.VIRTUAL | Modifiers.ABSTRACT)) != 0) {
+                               Report.Error (549, Location, "New virtual member `{0}' is declared in a sealed class `{1}'",
+                                       GetSignatureForError (), Parent.GetSignatureForError ());
                        }
-                       
+               }
+
+               //
+               // Any type_name dependent checks
+               //
+               protected virtual void DoMemberTypeDependentChecks ()
+               {
                        // verify accessibility
                        if (!IsAccessibleAs (MemberType)) {
                                Report.SymbolRelatedToPreviousError (MemberType);
@@ -5327,18 +5401,47 @@ namespace Mono.CSharp {
                                                      TypeManager.CSharpName (MemberType) + "' is less " +
                                                      "accessible than field `" + GetSignatureForError () + "'");
                                }
+                       }
+
+                       Variance variance = this is Event ? Variance.Contravariant : Variance.Covariant;
+                       TypeManager.CheckTypeVariance (MemberType, variance, this);
+               }
+
+               protected bool IsTypePermitted ()
+               {
+                       if (TypeManager.IsSpecialType (MemberType)) {
+                               Report.Error (610, Location, "Field or property cannot be of type `{0}'", TypeManager.CSharpName (MemberType));
                                return false;
                        }
+                       return true;
+               }
+
+               protected virtual bool CheckBase ()
+               {
+                       CheckProtectedModifier ();
 
                        return true;
                }
 
-               protected bool IsTypePermitted ()
+               public Type MemberType {
+                       get { return member_type; }
+               }
+
+               protected virtual bool ResolveMemberType ()
                {
-                       if (TypeManager.IsSpecialType (MemberType)) {
-                               Report.Error (610, Location, "Field or property cannot be of type `{0}'", TypeManager.CSharpName (MemberType));
+                       if (member_type != null)
+                               throw new InternalErrorException ("Multi-resolve");
+
+                       TypeExpr te = type_name.ResolveAsTypeTerminal (this, false);
+                       if (te == null)
                                return false;
-                       }
+                       
+                       //
+                       // Replace original type name, error reporting can use fully resolved name
+                       //
+                       type_name = te;
+
+                       member_type = te.Type;
                        return true;
                }
        }
@@ -5373,9 +5476,9 @@ namespace Mono.CSharp {
                        }
                }
 
-               public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
+               public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
                {
-                       if (a.Type == TypeManager.field_offset_attribute_type) {
+                       if (a.Type == pa.FieldOffset) {
                                status |= Status.HAS_OFFSET;
 
                                if (!Parent.PartialContainer.HasExplicitLayout) {
@@ -5390,14 +5493,14 @@ namespace Mono.CSharp {
                        }
 
 #if NET_2_0
-                       if (a.Type == TypeManager.fixed_buffer_attr_type) {
+                       if (a.Type == pa.FixedBuffer) {
                                Report.Error (1716, Location, "Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute. Use the 'fixed' field modifier instead");
                                return;
                        }
 #endif
 
 #if !NET_2_0
-                       if (a.Type == TypeManager.marshal_as_attr_type) {
+                       if (a.Type == pa.MarshalAs) {
                                UnmanagedMarshal marshal = a.GetMarshal (this);
                                if (marshal != null) {
                                        FieldBuilder.SetMarshal (marshal);
@@ -5426,7 +5529,7 @@ namespace Mono.CSharp {
                                return true;
                        }
  
-                       if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0) {
+                       if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE | Modifiers.BACKING_FIELD)) == 0) {
                                Report.SymbolRelatedToPreviousError (conflict_symbol);
                                Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
                                        GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
@@ -5435,29 +5538,19 @@ namespace Mono.CSharp {
                        return true;
                }
 
-               public override bool Define()
+               protected override void DoMemberTypeDependentChecks ()
                {
-                       if (MemberType == null || member_type == null)
-                               return false;
+                       base.DoMemberTypeDependentChecks ();
 
                        if (TypeManager.IsGenericParameter (MemberType))
-                               return true;
+                               return;
 
                        if (MemberType.IsSealed && MemberType.IsAbstract) {
-                               Error_VariableOfStaticClass (Location, GetSignatureForError (), MemberType);
-                               return false;
+                               Error_VariableOfStaticClass (Location, GetSignatureForError (), MemberType, Report);
                        }
 
-                       if (!CheckBase ())
-                               return false;
-
-                       if (!DoDefine ())
-                               return false;
-
-                       if (!IsTypePermitted ())
-                               return false;
-
-                       return true;
+                       CheckBase ();
+                       IsTypePermitted ();
                }
 
                //
@@ -5469,10 +5562,11 @@ namespace Mono.CSharp {
 
                public override void Emit ()
                {
-#if GMCS_SOURCE
+                       if (TypeManager.IsDynamicType (member_type))
+                               PredefinedAttributes.Get.Dynamic.EmitAttribute (FieldBuilder);
+
                        if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
-                               FieldBuilder.SetCustomAttribute (TypeManager.GetCompilerGeneratedAttribute (Location));
-#endif
+                               PredefinedAttributes.Get.CompilerGenerated.EmitAttribute (FieldBuilder);
 
                        if (OptAttributes != null) {
                                OptAttributes.Emit ();
@@ -5485,7 +5579,7 @@ namespace Mono.CSharp {
                        base.Emit ();
                }
 
-               public static void Error_VariableOfStaticClass (Location loc, string variable_name, Type static_class)
+               public static void Error_VariableOfStaticClass (Location loc, string variable_name, Type static_class, Report Report)
                {
                        Report.SymbolRelatedToPreviousError (static_class);
                        Report.Error (723, loc, "`{0}': cannot declare variables of static types",
@@ -5599,9 +5693,6 @@ namespace Mono.CSharp {
 
                public override bool Define()
                {
-                       if (!Parent.IsInUnsafeScope)
-                               Expression.UnsafeError (Location);
-
                        if (!base.Define ())
                                return false;
 
@@ -5612,7 +5703,7 @@ namespace Mono.CSharp {
                        
                        // Create nested fixed buffer container
                        string name = String.Format ("<{0}>__FixedBuffer{1}", Name, GlobalCounter++);
-                       fixed_buffer_type = Parent.TypeBuilder.DefineNestedType (name, CodeGen.Module.DefaultCharSetType |
+                       fixed_buffer_type = Parent.TypeBuilder.DefineNestedType (name, Parent.Module.DefaultCharSetType |
                                TypeAttributes.NestedPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit, TypeManager.value_type);
                        
                        element = fixed_buffer_type.DefineField (FixedElementName, MemberType, FieldAttributes.Public);
@@ -5625,19 +5716,27 @@ namespace Mono.CSharp {
                        return true;
                }
 
-               public override void Emit()
+               protected override void DoMemberTypeIndependentChecks ()
                {
+                       base.DoMemberTypeIndependentChecks ();
+
+                       if (!Parent.IsUnsafe)
+                               Expression.UnsafeError (Report, Location);
+
                        if (Parent.PartialContainer.Kind != Kind.Struct) {
                                Report.Error (1642, Location, "`{0}': Fixed size buffer fields may only be members of structs",
                                        GetSignatureForError ());
                        }
+               }
 
-                       EmitContext ec = new EmitContext (this, Parent, Location, null, TypeManager.void_type, ModFlags);
-                       Constant c = size_expr.ResolveAsConstant (ec, this);
+               public override void Emit()
+               {
+                       ResolveContext rc = new ResolveContext (this);
+                       Constant c = size_expr.ResolveAsConstant (rc, this);
                        if (c == null)
                                return;
                        
-                       IntConstant buffer_size_const = c.ImplicitConversionRequired (ec, TypeManager.int32_type, Location) as IntConstant;
+                       IntConstant buffer_size_const = c.ImplicitConversionRequired (rc, TypeManager.int32_type, Location) as IntConstant;
                        if (buffer_size_const == null)
                                return;
 
@@ -5659,53 +5758,27 @@ namespace Mono.CSharp {
                        buffer_size *= type_size;
                        EmitFieldSize (buffer_size);
 
-#if GMCS_SOURCE
-                       //
-                       // Emit compiler generated fixed buffer type attribute
-                       //
-                       CustomAttributeBuilder cab = TypeManager.unsafe_value_type_attr;
-                       if (cab == null) {
-                               Type attr_type = TypeManager.CoreLookupType (
-                                       "System.Runtime.CompilerServices", "UnsafeValueTypeAttribute", Kind.Class, true);
-
-                               if (attr_type != null) {
-                                       ConstructorInfo ci = TypeManager.GetPredefinedConstructor (attr_type, Location);
-                                       if (ci != null) {
-                                               cab = new CustomAttributeBuilder (ci, new object [0]);
-                                               TypeManager.unsafe_value_type_attr = cab;
-                                       }
-                               }
-                       }
+                       PredefinedAttributes.Get.UnsafeValueType.EmitAttribute (fixed_buffer_type);
 
-                       if (cab != null)
-                               fixed_buffer_type.SetCustomAttribute (cab);
-#endif
                        base.Emit ();
                }
 
                void EmitFieldSize (int buffer_size)
                {
-                       if (TypeManager.struct_layout_attribute_type == null) {
-                               TypeManager.struct_layout_attribute_type = TypeManager.CoreLookupType (
-                                       "System.Runtime.InteropServices", "StructLayoutAttribute", Kind.Class, true);
+                       CustomAttributeBuilder cab;
+                       PredefinedAttribute pa;
 
-                               if (TypeManager.struct_layout_attribute_type == null)
+                       pa = PredefinedAttributes.Get.StructLayout;
+                       if (pa.Constructor == null &&
+                               !pa.ResolveConstructor (Location, TypeManager.short_type))
                                        return;
-                       }
 
+                       // TODO: It's not cleared
                        if (fi == null)
-                               fi = new FieldInfo [] { TypeManager.struct_layout_attribute_type.GetField ("Size") };
-
-                       object [] fi_val = new object [] { buffer_size };
+                               fi = new FieldInfo[] { pa.Type.GetField ("Size") };
 
-                       if (TypeManager.struct_layout_attribute_ctor == null) {
-                               TypeManager.struct_layout_attribute_ctor = TypeManager.GetPredefinedConstructor (
-                                       TypeManager.struct_layout_attribute_type, Location, TypeManager.short_type);
-                               if (TypeManager.struct_layout_attribute_ctor == null)
-                                       return;
-                       }
-
-                       CustomAttributeBuilder cab = new CustomAttributeBuilder (TypeManager.struct_layout_attribute_ctor,
+                       object[] fi_val = new object[] { buffer_size };
+                       cab = new CustomAttributeBuilder (pa.Constructor,
                                ctor_args, fi, fi_val);
                        fixed_buffer_type.SetCustomAttribute (cab);
                        
@@ -5713,25 +5786,14 @@ namespace Mono.CSharp {
                        // Don't emit FixedBufferAttribute attribute for private types
                        //
                        if ((ModFlags & Modifiers.PRIVATE) != 0)
-                               return; 
-
-                       if (TypeManager.fixed_buffer_attr_ctor == null) {
-                               if (TypeManager.fixed_buffer_attr_type == null) {
-                                       TypeManager.fixed_buffer_attr_type = TypeManager.CoreLookupType (
-                                               "System.Runtime.CompilerServices", "FixedBufferAttribute", Kind.Class, true);
-
-                                       if (TypeManager.fixed_buffer_attr_type == null)
-                                               return;
-                               }
+                               return;
 
-                               TypeManager.fixed_buffer_attr_ctor = TypeManager.GetPredefinedConstructor (TypeManager.fixed_buffer_attr_type,
-                                       Location, TypeManager.type_type, TypeManager.int32_type);
-                               
-                               if (TypeManager.fixed_buffer_attr_ctor == null)
-                                       return;
-                       }
+                       pa = PredefinedAttributes.Get.FixedBuffer;
+                       if (pa.Constructor == null &&
+                               !pa.ResolveConstructor (Location, TypeManager.type_type, TypeManager.int32_type))
+                               return;
 
-                       cab = new CustomAttributeBuilder (TypeManager.fixed_buffer_attr_ctor, new object [] { MemberType, buffer_size });
+                       cab = new CustomAttributeBuilder (pa.Constructor, new object[] { MemberType, buffer_size });
                        FieldBuilder.SetCustomAttribute (cab);
                }
 
@@ -5797,10 +5859,9 @@ namespace Mono.CSharp {
                        Modifiers.UNSAFE |
                        Modifiers.READONLY;
 
-               public Field (DeclSpace parent, FullNamedExpression type, int mod, string name,
-                             Attributes attrs, Location loc)
-                       : base (parent, type, mod, AllowedModifiers, new MemberName (name, loc),
-                               attrs)
+               public Field (DeclSpace parent, FullNamedExpression type, int mod, MemberName name,
+                             Attributes attrs)
+                       : base (parent, type, mod, AllowedModifiers, name, attrs)
                {
                }
 
@@ -5809,14 +5870,15 @@ namespace Mono.CSharp {
                        if (TypeManager.IsReferenceType (MemberType))
                                return true;
 
-                       if (MemberType.IsEnum)
-                               return true;
-
                        if (MemberType == TypeManager.bool_type || MemberType == TypeManager.char_type ||
                                MemberType == TypeManager.sbyte_type || MemberType == TypeManager.byte_type ||
                                MemberType == TypeManager.short_type || MemberType == TypeManager.ushort_type ||
                                MemberType == TypeManager.int32_type || MemberType == TypeManager.uint32_type ||
-                               MemberType == TypeManager.float_type)
+                               MemberType == TypeManager.float_type ||
+                               MemberType == TypeManager.intptr_type || MemberType == TypeManager.uintptr_type)
+                               return true;
+
+                       if (TypeManager.IsEnumType (MemberType))
                                return true;
 
                        return false;
@@ -5854,24 +5916,12 @@ namespace Mono.CSharp {
                        if (!base.Define ())
                                return false;
 
-                       if ((ModFlags & Modifiers.VOLATILE) != 0){
-                               if (!CanBeVolatile ()) {
-                                       Report.Error (677, Location, "`{0}': A volatile field cannot be of the type `{1}'",
-                                               GetSignatureForError (), TypeManager.CSharpName (MemberType));
-                               }
-
-                               if ((ModFlags & Modifiers.READONLY) != 0){
-                                       Report.Error (678, Location, "`{0}': A field cannot be both volatile and readonly",
-                                               GetSignatureForError ());
-                               }
-                       }
-
                        try {
 #if GMCS_SOURCE
                                Type[] required_modifier = null;
                                if ((ModFlags & Modifiers.VOLATILE) != 0) {
                                        if (TypeManager.isvolatile_type == null)
-                                               TypeManager.isvolatile_type = TypeManager.CoreLookupType (
+                                               TypeManager.isvolatile_type = TypeManager.CoreLookupType (Compiler,
                                                        "System.Runtime.CompilerServices", "IsVolatile", Kind.Class, true);
 
                                        if (TypeManager.isvolatile_type != null)
@@ -5884,7 +5934,11 @@ namespace Mono.CSharp {
                                FieldBuilder = Parent.TypeBuilder.DefineField (
                                        Name, MemberType, Modifiers.FieldAttr (ModFlags));
 #endif
-                               Parent.MemberCache.AddMember (FieldBuilder, this);
+                               // Don't cache inaccessible fields
+                               if ((ModFlags & Modifiers.BACKING_FIELD) == 0) {
+                                       Parent.MemberCache.AddMember (FieldBuilder, this);
+                               }
+
                                TypeManager.RegisterFieldBase (FieldBuilder, this);
                        }
                        catch (ArgumentException) {
@@ -5903,15 +5957,21 @@ namespace Mono.CSharp {
                        return true;
                }
 
-               public override string GetSignatureForError ()
+               protected override void DoMemberTypeDependentChecks ()
                {
-                       string s = base.GetSignatureForError ();
-                       if ((ModFlags & Modifiers.BACKING_FIELD) == 0)
-                               return s;
+                       base.DoMemberTypeDependentChecks ();
+
+                       if ((ModFlags & Modifiers.VOLATILE) != 0) {
+                               if (!CanBeVolatile ()) {
+                                       Report.Error (677, Location, "`{0}': A volatile field cannot be of the type `{1}'",
+                                               GetSignatureForError (), TypeManager.CSharpName (MemberType));
+                               }
 
-                       // Undecorate name mangling
-                       int l = s.LastIndexOf ('>');
-                       return s.Substring (0, l).Remove (s.LastIndexOf ('<'), 1);
+                               if ((ModFlags & Modifiers.READONLY) != 0) {
+                                       Report.Error (678, Location, "`{0}': A field cannot be both volatile and readonly",
+                                               GetSignatureForError ());
+                               }
+                       }
                }
 
                protected override bool VerifyClsCompliance ()
@@ -5944,15 +6004,15 @@ namespace Mono.CSharp {
                public Attributes Attributes;
                public Location Location;
                public int ModFlags;
-               public Parameters Parameters;
+               public ParametersCompiled Parameters;
                
-               public Accessor (ToplevelBlock b, int mod, Attributes attrs, Parameters p, Location loc)
+               public Accessor (ToplevelBlock b, int mod, Attributes attrs, ParametersCompiled p, Location loc)
                {
                        Block = b;
                        Attributes = attrs;
                        Location = loc;
                        Parameters = p;
-                       ModFlags = Modifiers.Check (AllowedModifiers, mod, 0, loc);
+                       ModFlags = Modifiers.Check (AllowedModifiers, mod, 0, loc, RootContext.ToplevelTypes.Compiler.Report);
                }
        }
 
@@ -5963,7 +6023,7 @@ namespace Mono.CSharp {
                protected ToplevelBlock block;
                protected ListDictionary declarative_security;
 
-               // The accessor are created event if they are not wanted.
+               // The accessor are created even if they are not wanted.
                // But we need them because their names are reserved.
                // Field says whether accessor will be emited or not
                public readonly bool IsDummy;
@@ -6016,6 +6076,11 @@ namespace Mono.CSharp {
                        }
                }
 
+               public EmitContext CreateEmitContext (ILGenerator ig)
+               {
+                       return new EmitContext (this, ig, ReturnType);
+               }
+
                public bool IsExcluded ()
                {
                        return false;
@@ -6039,16 +6104,14 @@ namespace Mono.CSharp {
                        }
                }
 
-               public abstract Parameters ParameterInfo { get ; }
+               public abstract ParametersCompiled ParameterInfo { get ; }
                public abstract Type ReturnType { get; }
-               public abstract EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig);
 
                #endregion
 
-               public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
+               public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
                {
-                       if (a.Type == TypeManager.cls_compliant_attribute_type || a.Type == TypeManager.obsolete_attribute_type ||
-                                       a.Type == TypeManager.conditional_attribute_type) {
+                       if (a.Type == pa.CLSCompliant || a.Type == pa.Obsolete || a.Type == pa.Conditional) {
                                Report.Error (1667, a.Location,
                                        "Attribute `{0}' is not valid on property or event accessors. It is valid on `{1}' declarations only",
                                        TypeManager.CSharpName (a.Type), a.GetValidTargets ());
@@ -6071,14 +6134,14 @@ namespace Mono.CSharp {
                                if (return_attributes == null)
                                        return_attributes = new ReturnParameter (method_data.MethodBuilder, Location);
 
-                               return_attributes.ApplyAttributeBuilder (a, cb);
+                               return_attributes.ApplyAttributeBuilder (a, cb, pa);
                                return;
                        }
 
-                       ApplyToExtraTarget (a, cb);
+                       ApplyToExtraTarget (a, cb, pa);
                }
 
-               virtual protected void ApplyToExtraTarget (Attribute a, CustomAttributeBuilder cb)
+               protected virtual void ApplyToExtraTarget (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
                {
                        throw new NotSupportedException ("You forgot to define special attribute target handling");
                }
@@ -6089,16 +6152,20 @@ namespace Mono.CSharp {
                        throw new NotSupportedException ();
                }
 
-               public void Emit (DeclSpace parent)
+               public virtual void Emit (DeclSpace parent)
                {
-                       EmitMethod (parent);
+                       method_data.Emit (parent);
 
-#if GMCS_SOURCE                        
                        if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
-                               method_data.MethodBuilder.SetCustomAttribute (TypeManager.GetCompilerGeneratedAttribute (Location));
+                               PredefinedAttributes.Get.CompilerGenerated.EmitAttribute (method_data.MethodBuilder);
                        if (((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0))
-                               method_data.MethodBuilder.SetCustomAttribute (TypeManager.GetDebuggerHiddenAttribute (Location));
-#endif                 
+                               PredefinedAttributes.Get.DebuggerHidden.EmitAttribute (method_data.MethodBuilder);
+
+                       if (TypeManager.IsDynamicType (ReturnType)) {
+                               return_attributes = new ReturnParameter (method_data.MethodBuilder, Location);
+                               return_attributes.EmitPredefined (PredefinedAttributes.Get.Dynamic, Location);
+                       }
+
                        if (OptAttributes != null)
                                OptAttributes.Emit ();
 
@@ -6111,11 +6178,6 @@ namespace Mono.CSharp {
                        block = null;
                }
 
-               protected virtual void EmitMethod (DeclSpace parent)
-               {
-                       method_data.Emit (parent);
-               }
-
                public override bool EnableOverloadChecks (MemberCore overload)
                {
                        // This can only happen with indexers and it will
@@ -6205,7 +6267,7 @@ namespace Mono.CSharp {
                                
                                method_data = new MethodData (method, ModFlags, flags, this);
 
-                               if (!method_data.Define (parent, method.GetFullName (MemberName)))
+                               if (!method_data.Define (parent, method.GetFullName (MemberName), Report))
                                        return null;
 
                                return method_data.MethodBuilder;
@@ -6217,9 +6279,9 @@ namespace Mono.CSharp {
                                }
                        }
 
-                       public override Parameters ParameterInfo {
+                       public override ParametersCompiled ParameterInfo {
                                get {
-                                       return Parameters.EmptyReadOnlyParameters;
+                                       return ParametersCompiled.EmptyReadOnlyParameters;
                                }
                        }
 
@@ -6234,12 +6296,12 @@ namespace Mono.CSharp {
 
                        static string[] attribute_targets = new string [] { "method", "param", "return" };
                        ImplicitParameter param_attr;
-                       protected Parameters parameters;
+                       protected ParametersCompiled parameters;
 
                        public SetMethod (PropertyBase method) :
                                base (method, "set_")
                        {
-                               parameters = new Parameters (
+                               parameters = new ParametersCompiled (
                                        new Parameter (method.type_name, "value", Parameter.Modifier.NONE, null, Location));
                        }
 
@@ -6249,20 +6311,20 @@ namespace Mono.CSharp {
                                this.parameters = accessor.Parameters;
                        }
 
-                       protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
+                       protected override void ApplyToExtraTarget (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
                        {
                                if (a.Target == AttributeTargets.Parameter) {
                                        if (param_attr == null)
                                                param_attr = new ImplicitParameter (method_data.MethodBuilder);
 
-                                       param_attr.ApplyAttributeBuilder (a, cb);
+                                       param_attr.ApplyAttributeBuilder (a, cb, pa);
                                        return;
                                }
 
-                               base.ApplyAttributeBuilder (a, cb);
+                               base.ApplyAttributeBuilder (a, cb, pa);
                        }
 
-                       public override Parameters ParameterInfo {
+                       public override ParametersCompiled ParameterInfo {
                            get {
                                return parameters;
                            }
@@ -6270,7 +6332,8 @@ namespace Mono.CSharp {
 
                        public override MethodBuilder Define (DeclSpace parent)
                        {
-                               parameters.Resolve (ResolveContext);
+                               parameters.Resolve (this);
+                               
                                base.Define (parent);
 
                                if (IsDummy)
@@ -6278,7 +6341,7 @@ namespace Mono.CSharp {
 
                                method_data = new MethodData (method, ModFlags, flags, this);
 
-                               if (!method_data.Define (parent, method.GetFullName (MemberName)))
+                               if (!method_data.Define (parent, method.GetFullName (MemberName), Report))
                                        return null;
 
                                return method_data.MethodBuilder;
@@ -6323,13 +6386,13 @@ namespace Mono.CSharp {
                                }
                        }
 
-                       public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
+                       public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
                        {
                                if (a.IsInternalMethodImplAttribute) {
                                        method.is_external_implementation = true;
                                }
 
-                               base.ApplyAttributeBuilder (a, cb);
+                               base.ApplyAttributeBuilder (a, cb, pa);
                        }
 
                        public override AttributeTargets AttributeTargets {
@@ -6348,7 +6411,7 @@ namespace Mono.CSharp {
                                CheckForDuplications ();
 
                                if (IsDummy) {
-                                       if (method.InterfaceType != null && method.IsExplicitImpl) {
+                                       if (method.InterfaceType != null && parent.PartialContainer.PendingImplementations != null) {
                                                MethodInfo mi = parent.PartialContainer.PendingImplementations.IsInterfaceMethod (
                                                        MethodName.Name, method.InterfaceType, new MethodData (method, ModFlags, flags, this));
                                                if (mi != null) {
@@ -6387,23 +6450,21 @@ namespace Mono.CSharp {
                                CheckAbstractAndExtern (block != null);
 
                                if (block != null && block.IsIterator)
-                                       Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
+                                       Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags, Compiler);
 
                                return null;
                        }
 
-                       public bool HasCustomAccessModifier
-                       {
+                       public bool HasCustomAccessModifier {
                                get {
                                        return (ModFlags & Modifiers.PROPERTY_CUSTOM) != 0;
                                }
                        }
 
-                       public override EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
-                       {
-                               return new EmitContext (this,
-                                       ds, method.ds, method.Location, ig, ReturnType,
-                                       method.ModFlags, false);
+                       public PropertyBase Property {
+                               get {
+                                       return method;
+                               }
                        }
 
                        public override ObsoleteAttribute GetObsoleteAttribute ()
@@ -6441,12 +6502,12 @@ namespace Mono.CSharp {
                                }
                        }
 
-                       protected bool CheckForDuplications () 
+                       protected bool CheckForDuplications ()
                        {
                                if ((caching_flags & Flags.MethodOverloadsExist) == 0)
                                        return true;
 
-                               return Parent.MemberCache.CheckExistingMembersOverloads (this, Name, ParameterInfo);
+                               return Parent.MemberCache.CheckExistingMembersOverloads (this, Name, ParameterInfo, Report);
                        }
                }
 
@@ -6464,7 +6525,7 @@ namespace Mono.CSharp {
                         this.define_set_first = define_set_first;
                }
 
-               public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
+               public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
                {
                        if (a.HasSecurityAttribute) {
                                a.Error_InvalidSecurityParent ();
@@ -6480,21 +6541,24 @@ namespace Mono.CSharp {
                        }
                }
 
-               public override bool Define ()
+               protected override void DoMemberTypeDependentChecks ()
                {
-                       if (!DoDefine ())
-                               return false;
+                       base.DoMemberTypeDependentChecks ();
 
-                       if (!IsTypePermitted ())
-                               return false;
+                       IsTypePermitted ();
+#if MS_COMPATIBLE
+                       if (MemberType.IsGenericParameter)
+                               return;
+#endif
 
-                       return true;
+                       if ((MemberType.Attributes & Class.StaticClassAttribute) == Class.StaticClassAttribute) {
+                               Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
+                       }
                }
 
-               protected override bool DoDefine ()
+               protected override void DoMemberTypeIndependentChecks ()
                {
-                       if (!base.DoDefine ())
-                               return false;
+                       base.DoMemberTypeIndependentChecks ();
 
                        //
                        // Accessors modifiers check
@@ -6503,7 +6567,6 @@ namespace Mono.CSharp {
                                (Set.ModFlags & Modifiers.Accessibility) != 0) {
                                Report.Error (274, Location, "`{0}': Cannot specify accessibility modifiers for both accessors of the property or indexer",
                                                GetSignatureForError ());
-                               return false;
                        }
 
                        if ((ModFlags & Modifiers.OVERRIDE) == 0 && 
@@ -6512,20 +6575,7 @@ namespace Mono.CSharp {
                                Report.Error (276, Location, 
                                              "`{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor",
                                              GetSignatureForError ());
-                               return false;
-                       }
-
-#if MS_COMPATIBLE
-                       if (MemberType.IsGenericParameter)
-                               return true;
-#endif
-
-                       if ((MemberType.Attributes & Class.StaticClassAttribute) == Class.StaticClassAttribute) {
-                               Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
-                               return false;
                        }
-
-                       return true;
                }
 
                bool DefineGet ()
@@ -6617,8 +6667,13 @@ namespace Mono.CSharp {
                        // case, we do not actually emit the ".property", so there is nowhere to
                        // put the attribute
                        //
-                       if (PropertyBuilder != null && OptAttributes != null)
-                               OptAttributes.Emit ();
+                       if (PropertyBuilder != null) {
+                               if (OptAttributes != null)
+                                       OptAttributes.Emit ();
+
+                               if (TypeManager.IsDynamicType (member_type))
+                                       PredefinedAttributes.Get.Dynamic.EmitAttribute (PropertyBuilder);
+                       }
 
                        if (!Get.IsDummy)
                                Get.Emit (Parent);
@@ -6669,7 +6724,26 @@ namespace Mono.CSharp {
                }
        }
                        
-       public class Property : PropertyBase {
+       public class Property : PropertyBase
+       {
+               public sealed class BackingField : Field
+               {
+                       readonly Property property;
+
+                       public BackingField (Property p)
+                               : base (p.Parent, p.type_name,
+                               Modifiers.BACKING_FIELD | Modifiers.COMPILER_GENERATED | Modifiers.PRIVATE | (p.ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE)),
+                               new MemberName ("<" + p.GetFullName (p.MemberName) + ">k__BackingField", p.Location), null)
+                       {
+                               this.property = p;
+                       }
+
+                       public override string GetSignatureForError ()
+                       {
+                               return property.GetSignatureForError ();
+                       }
+               }
+
                const int AllowedModifiers =
                        Modifiers.NEW |
                        Modifiers.PUBLIC |
@@ -6687,28 +6761,6 @@ namespace Mono.CSharp {
                const int AllowedInterfaceModifiers =
                        Modifiers.NEW;
 
-               void CreateAutomaticProperty (Block block, Accessor get_block, Accessor set_block)
-               {
-                       // Make the field
-                       Field field = new Field (
-                               Parent, type_name,
-                               Modifiers.BACKING_FIELD | Modifiers.PRIVATE | (ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE)),
-                           "<" + Name + ">k__BackingField", null, Location);
-                       ((TypeContainer)Parent).PartialContainer.AddField (field);
-
-                       // Make get block
-                       get_block.Block = new ToplevelBlock (block, null, Location);
-                       Return r = new Return (new SimpleName(field.Name, Location), Location);
-                       get_block.Block.AddStatement (r);
-                       get_block.ModFlags |= Modifiers.COMPILER_GENERATED;
-
-                       // Make set block
-                       set_block.Block = new ToplevelBlock (block, set_block.Parameters, Location);
-                       Assign a = new SimpleAssign (new SimpleName (field.Name, Location), new SimpleName ("value", Location));
-                       set_block.Block.AddStatement (new StatementExpression(a));
-                       set_block.ModFlags |= Modifiers.COMPILER_GENERATED;
-               }
-
                public Property (DeclSpace parent, FullNamedExpression type, int mod,
                                 MemberName name, Attributes attrs, Accessor get_block,
                                 Accessor set_block, bool define_set_first)
@@ -6724,15 +6776,6 @@ namespace Mono.CSharp {
                                parent.PartialContainer.Kind == Kind.Interface ? AllowedInterfaceModifiers : AllowedModifiers,
                                name, attrs, define_set_first)
                {
-                       if (!IsInterface && (mod & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0 &&
-                               get_block != null && get_block.Block == null &&
-                               set_block != null && set_block.Block == null) {
-                               if (RootContext.Version <= LanguageVersion.ISO_2)
-                                       Report.FeatureIsNotAvailable (Location, "automatically implemented properties");
-                               
-                               CreateAutomaticProperty (current_block, get_block, set_block);
-                       }
-
                        if (get_block == null)
                                Get = new GetMethod (this);
                        else
@@ -6742,18 +6785,52 @@ namespace Mono.CSharp {
                                Set = new SetMethod (this);
                        else
                                Set = new SetMethod (this, set_block);
+
+                       if (!IsInterface && (mod & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0 &&
+                               get_block != null && get_block.Block == null &&
+                               set_block != null && set_block.Block == null) {
+                               if (RootContext.Version <= LanguageVersion.ISO_2)
+                                       Report.FeatureIsNotAvailable (Location, "automatically implemented properties");
+
+                               Get.ModFlags |= Modifiers.COMPILER_GENERATED;
+                               Set.ModFlags |= Modifiers.COMPILER_GENERATED;
+                       }
                }
 
-               public override bool Define ()
+               void CreateAutomaticProperty ()
                {
-                       if (!DoDefineBase ())
-                               return false;
+                       // Create backing field
+                       Field field = new BackingField (this);
+                       if (!field.Define ())
+                               return;
+
+                       Parent.PartialContainer.AddField (field);
+
+                       FieldExpr fe = new FieldExpr (field.FieldBuilder, Location);
+                       if ((field.ModFlags & Modifiers.STATIC) == 0)
+                               fe.InstanceExpression = new CompilerGeneratedThis (fe.Type, Location);
+
+                       // Create get block
+                       Get.Block = new ToplevelBlock (Compiler, ParametersCompiled.EmptyReadOnlyParameters, Location);
+                       Return r = new Return (fe, Location);
+                       Get.Block.AddStatement (r);
 
+                       // Create set block
+                       Set.Block = new ToplevelBlock (Compiler, Set.ParameterInfo, Location);
+                       Assign a = new SimpleAssign (fe, new SimpleName ("value", Location));
+                       Set.Block.AddStatement (new StatementExpression (a));
+               }
+
+               public override bool Define ()
+               {
                        if (!base.Define ())
                                return false;
 
                        flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
 
+                       if ((Get.ModFlags & Modifiers.COMPILER_GENERATED) != 0)
+                               CreateAutomaticProperty ();
+
                        if (!DefineAccessors ())
                                return false;
 
@@ -6794,7 +6871,7 @@ namespace Mono.CSharp {
                protected override PropertyInfo ResolveBaseProperty ()
                {
                        return Parent.PartialContainer.BaseCache.FindMemberToOverride (
-                               Parent.TypeBuilder, Name, Parameters.EmptyReadOnlyParameters, null, true) as PropertyInfo;
+                               Parent.TypeBuilder, Name, ParametersCompiled.EmptyReadOnlyParameters, null, true) as PropertyInfo;
                }
        }
 
@@ -6970,29 +7047,17 @@ namespace Mono.CSharp {
                sealed class AddDelegateMethod: AEventPropertyAccessor
                {
                        public AddDelegateMethod (Event method, Accessor accessor):
-                               base (method, accessor, "add_")
+                               base (method, accessor, AddPrefix)
                        {
                        }
-
-                       protected override MethodInfo DelegateMethodInfo {
-                               get {
-                                       return TypeManager.delegate_combine_delegate_delegate;
-                               }
-                       }
                }
 
                sealed class RemoveDelegateMethod: AEventPropertyAccessor
                {
                        public RemoveDelegateMethod (Event method, Accessor accessor):
-                               base (method, accessor, "remove_")
+                               base (method, accessor, RemovePrefix)
                        {
                        }
-
-                       protected override MethodInfo DelegateMethodInfo {
-                               get {
-                                       return TypeManager.delegate_remove_delegate_delegate;
-                               }
-                       }
                }
 
 
@@ -7034,65 +7099,54 @@ namespace Mono.CSharp {
                        {
                        }
 
-                       protected override void EmitMethod(DeclSpace parent)
+                       public override void Emit (DeclSpace parent)
                        {
-                               if ((method.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
-                                       return;
-
-                               MethodBuilder mb = method_data.MethodBuilder;
-                               ILGenerator ig = mb.GetILGenerator ();
+                               if ((method.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0) {
+                                       if (parent is Class) {
+                                               MethodBuilder mb = method_data.MethodBuilder;
+                                               mb.SetImplementationFlags (mb.GetMethodImplementationFlags () | MethodImplAttributes.Synchronized);
+                                       }
 
-                               // TODO: because we cannot use generics yet
-                               FieldInfo field_info = ((EventField)method).FieldBuilder;
+                                       // TODO: because we cannot use generics yet
+                                       FieldInfo field_info = ((EventField) method).BackingField.FieldBuilder;
+                                       FieldExpr f_expr = new FieldExpr (field_info, Location);
+                                       if ((method.ModFlags & Modifiers.STATIC) == 0)
+                                               f_expr.InstanceExpression = new CompilerGeneratedThis (field_info.FieldType, Location);
 
-                               if (parent is Class) {
-                                       mb.SetImplementationFlags (mb.GetMethodImplementationFlags () | MethodImplAttributes.Synchronized);
-                               }
-                               
-                               if ((method.ModFlags & Modifiers.STATIC) != 0) {
-                                       ig.Emit (OpCodes.Ldsfld, field_info);
-                                       ig.Emit (OpCodes.Ldarg_0);
-                                       ig.Emit (OpCodes.Call, DelegateMethodInfo);
-                                       ig.Emit (OpCodes.Castclass, method.MemberType);
-                                       ig.Emit (OpCodes.Stsfld, field_info);
-                               } else {
-                                       ig.Emit (OpCodes.Ldarg_0);
-                                       ig.Emit (OpCodes.Ldarg_0);
-                                       ig.Emit (OpCodes.Ldfld, field_info);
-                                       ig.Emit (OpCodes.Ldarg_1);
-                                       ig.Emit (OpCodes.Call, DelegateMethodInfo);
-                                       ig.Emit (OpCodes.Castclass, method.MemberType);
-                                       ig.Emit (OpCodes.Stfld, field_info);
+                                       block = new ToplevelBlock (Compiler, ParameterInfo, Location);
+                                       block.AddStatement (new StatementExpression (
+                                               new CompoundAssign (Operation,
+                                                       f_expr,
+                                                       block.GetParameterReference (ParameterInfo[0].Name, Location))));
                                }
-                               ig.Emit (OpCodes.Ret);
+
+                               base.Emit (parent);
                        }
+
+                       protected abstract Binary.Operator Operation { get; }
                }
 
                sealed class AddDelegateMethod: EventFieldAccessor
                {
                        public AddDelegateMethod (Event method):
-                               base (method, "add_")
+                               base (method, AddPrefix)
                        {
                        }
 
-                       protected override MethodInfo DelegateMethodInfo {
-                               get {
-                                       return TypeManager.delegate_combine_delegate_delegate;
-                               }
+                       protected override Binary.Operator Operation {
+                               get { return Binary.Operator.Addition; }
                        }
                }
 
                sealed class RemoveDelegateMethod: EventFieldAccessor
                {
                        public RemoveDelegateMethod (Event method):
-                               base (method, "remove_")
+                               base (method, RemovePrefix)
                        {
                        }
 
-                       protected override MethodInfo DelegateMethodInfo {
-                               get {
-                                       return TypeManager.delegate_remove_delegate_delegate;
-                               }
+                       protected override Binary.Operator Operation {
+                               get { return Binary.Operator.Subtraction; }
                        }
                }
 
@@ -7100,7 +7154,7 @@ namespace Mono.CSharp {
                static readonly string[] attribute_targets = new string [] { "event", "field", "method" };
                static readonly string[] attribute_targets_interface = new string[] { "event", "method" };
 
-               public FieldBuilder FieldBuilder;
+               public Field BackingField;
                public Expression Initializer;
 
                public EventField (DeclSpace parent, FullNamedExpression type, int mod_flags, MemberName name, Attributes attrs)
@@ -7110,22 +7164,22 @@ namespace Mono.CSharp {
                        Remove = new RemoveDelegateMethod (this);
                }
 
-               public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
+               public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
                {
                        if (a.Target == AttributeTargets.Field) {
-                               FieldBuilder.SetCustomAttribute (cb);
+                               BackingField.ApplyAttributeBuilder (a, cb, pa);
                                return;
                        }
 
                        if (a.Target == AttributeTargets.Method) {
                                int errors = Report.Errors;
-                               Add.ApplyAttributeBuilder (a, cb);
+                               Add.ApplyAttributeBuilder (a, cb, pa);
                                if (errors == Report.Errors)
-                                       Remove.ApplyAttributeBuilder (a, cb);
+                                       Remove.ApplyAttributeBuilder (a, cb, pa);
                                return;
                        }
 
-                       base.ApplyAttributeBuilder (a, cb);
+                       base.ApplyAttributeBuilder (a, cb, pa);
                }
 
                public override bool Define()
@@ -7133,41 +7187,50 @@ namespace Mono.CSharp {
                        if (!base.Define ())
                                return false;
 
-                       if (IsInterface)
+                       if (Initializer != null && (ModFlags & Modifiers.ABSTRACT) != 0) {
+                               Report.Error (74, Location, "`{0}': abstract event cannot have an initializer",
+                                       GetSignatureForError ());
+                       }
+
+                       if (!HasBackingField) {
+                               SetMemberIsUsed ();
                                return true;
+                       }
 
                        // FIXME: We are unable to detect whether generic event is used because
                        // we are using FieldExpr instead of EventExpr for event access in that
                        // case.  When this issue will be fixed this hack can be removed.
                        if (TypeManager.IsGenericType (MemberType))
-                               SetMemberIsUsed();
+                               SetMemberIsUsed ();
 
                        if (Add.IsInterfaceImplementation)
                                SetMemberIsUsed ();
 
-                       FieldBuilder = Parent.TypeBuilder.DefineField (
-                               Name, MemberType,
-                               FieldAttributes.Private | ((ModFlags & Modifiers.STATIC) != 0 ? FieldAttributes.Static : 0));
                        TypeManager.RegisterEventField (EventBuilder, this);
 
-                       if (Initializer != null) {
-                               if (((ModFlags & Modifiers.ABSTRACT) != 0)) {
-                                       Report.Error (74, Location, "`{0}': abstract event cannot have an initializer",
-                                               GetSignatureForError ());
-                                       return false;
-                               }
+                       BackingField = new Field (Parent,
+                               new TypeExpression (MemberType, Location),
+                               Modifiers.BACKING_FIELD | Modifiers.COMPILER_GENERATED | Modifiers.PRIVATE | (ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE)),
+                               MemberName, null);
 
-                               ((TypeContainer) Parent).RegisterFieldForInitialization (this,
-                                       new FieldInitializer (FieldBuilder, Initializer, this));
-                       }
+                       Parent.PartialContainer.AddField (BackingField);
+                       BackingField.Initializer = Initializer;
+                       BackingField.ModFlags &= ~Modifiers.COMPILER_GENERATED;
 
-                       return true;
+                       // Call define because we passed fields definition
+                       return BackingField.Define ();
+               }
+
+               bool HasBackingField {
+                       get {
+                               return !IsInterface && (ModFlags & Modifiers.ABSTRACT) == 0;
+                       }
                }
 
                public override string[] ValidAttributeTargets 
                {
                        get {
-                               return IsInterface ? attribute_targets_interface : attribute_targets;
+                               return HasBackingField ? attribute_targets : attribute_targets_interface;
                        }
                }
        }
@@ -7180,6 +7243,9 @@ namespace Mono.CSharp {
 
                        static readonly string[] attribute_targets = new string [] { "method", "param", "return" };
 
+                       public const string AddPrefix = "add_";
+                       public const string RemovePrefix = "remove_";
+
                        protected AEventAccessor (Event method, string prefix)
                                : base (method, prefix)
                        {
@@ -7198,26 +7264,26 @@ namespace Mono.CSharp {
                                get { return method_data.implementing != null; }
                        }
 
-                       public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
+                       public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
                        {
                                if (a.IsInternalMethodImplAttribute) {
                                        method.is_external_implementation = true;
                                }
 
-                               base.ApplyAttributeBuilder (a, cb);
+                               base.ApplyAttributeBuilder (a, cb, pa);
                        }
 
-                       protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
+                       protected override void ApplyToExtraTarget (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
                        {
                                if (a.Target == AttributeTargets.Parameter) {
                                        if (param_attr == null)
                                                param_attr = new ImplicitParameter (method_data.MethodBuilder);
 
-                                       param_attr.ApplyAttributeBuilder (a, cb);
+                                       param_attr.ApplyAttributeBuilder (a, cb, pa);
                                        return;
                                }
 
-                               base.ApplyAttributeBuilder (a, cb);
+                               base.ApplyAttributeBuilder (a, cb, pa);
                        }
 
                        public override AttributeTargets AttributeTargets {
@@ -7236,7 +7302,7 @@ namespace Mono.CSharp {
                                method_data = new MethodData (method, method.ModFlags,
                                        method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
 
-                               if (!method_data.Define (parent, method.GetFullName (MemberName)))
+                               if (!method_data.Define (parent, method.GetFullName (MemberName), Report))
                                        return null;
 
                                MethodBuilder mb = method_data.MethodBuilder;
@@ -7244,21 +7310,12 @@ namespace Mono.CSharp {
                                return mb;
                        }
 
-                       protected abstract MethodInfo DelegateMethodInfo { get; }
-
                        public override Type ReturnType {
                                get {
                                        return TypeManager.void_type;
                                }
                        }
 
-                       public override EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
-                       {
-                               return new EmitContext (
-                                       this, method.Parent, Location, ig, ReturnType,
-                                       method.ModFlags, false);
-                       }
-
                        public override ObsoleteAttribute GetObsoleteAttribute ()
                        {
                                return method.GetObsoleteAttribute ();
@@ -7270,7 +7327,7 @@ namespace Mono.CSharp {
                                }
                        }
 
-                       public override Parameters ParameterInfo {
+                       public override ParametersCompiled ParameterInfo {
                                get {
                                        return method.parameters;
                                }
@@ -7299,7 +7356,7 @@ namespace Mono.CSharp {
                public MyEventBuilder     EventBuilder;
                public MethodBuilder AddBuilder, RemoveBuilder;
 
-               Parameters parameters;
+               ParametersCompiled parameters;
 
                protected Event (DeclSpace parent, FullNamedExpression type, int mod_flags, MemberName name, Attributes attrs)
                        : base (parent, null, type, mod_flags,
@@ -7308,7 +7365,7 @@ namespace Mono.CSharp {
                {
                }
 
-               public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
+               public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
                {
                        if ((a.HasSecurityAttribute)) {
                                a.Error_InvalidSecurityParent ();
@@ -7331,18 +7388,14 @@ namespace Mono.CSharp {
 
                public override bool Define ()
                {
-                       if (!DoDefineBase ())
-                               return false;
-
-                       if (!DoDefine ())
+                       if (!base.Define ())
                                return false;
 
                        if (!TypeManager.IsDelegateType (MemberType)) {
                                Report.Error (66, Location, "`{0}': event must be of a delegate type", GetSignatureForError ());
-                               return false;
                        }
 
-                       parameters = Parameters.CreateFullyResolved (
+                       parameters = ParametersCompiled.CreateFullyResolved (
                                new Parameter (null, "value", Parameter.Modifier.NONE, null, Location), MemberType);
 
                        if (!CheckBase ())
@@ -7420,7 +7473,7 @@ namespace Mono.CSharp {
        {
                public class GetIndexerMethod : GetMethod
                {
-                       Parameters parameters;
+                       ParametersCompiled parameters;
 
                        public GetIndexerMethod (Indexer method):
                                base (method)
@@ -7436,7 +7489,7 @@ namespace Mono.CSharp {
 
                        public override MethodBuilder Define (DeclSpace parent)
                        {
-                               parameters.Resolve (ResolveContext);
+                               parameters.Resolve (this);
                                return base.Define (parent);
                        }
                        
@@ -7450,7 +7503,7 @@ namespace Mono.CSharp {
                                return false;
                        }                       
 
-                       public override Parameters ParameterInfo {
+                       public override ParametersCompiled ParameterInfo {
                                get {
                                        return parameters;
                                }
@@ -7462,7 +7515,7 @@ namespace Mono.CSharp {
                        public SetIndexerMethod (Indexer method):
                                base (method)
                        {
-                               parameters = Parameters.MergeGenerated (method.parameters, false, parameters [0], null);
+                               parameters = ParametersCompiled.MergeGenerated (method.parameters, false, parameters [0], null);
                        }
 
                        public SetIndexerMethod (PropertyBase method, Accessor accessor):
@@ -7498,10 +7551,10 @@ namespace Mono.CSharp {
                const int AllowedInterfaceModifiers =
                        Modifiers.NEW;
 
-               public readonly Parameters parameters;
+               public readonly ParametersCompiled parameters;
 
                public Indexer (DeclSpace parent, FullNamedExpression type, MemberName name, int mod,
-                               Parameters parameters, Attributes attrs,
+                               ParametersCompiled parameters, Attributes attrs,
                                Accessor get_block, Accessor set_block, bool define_set_first)
                        : base (parent, type, mod,
                                parent.PartialContainer.Kind == Kind.Interface ? AllowedInterfaceModifiers : AllowedModifiers,
@@ -7519,20 +7572,22 @@ namespace Mono.CSharp {
                        else
                                Set = new SetIndexerMethod (this, set_block);
                }
+
+               protected override bool CheckForDuplications ()
+               {
+                       return Parent.MemberCache.CheckExistingMembersOverloads (this, GetFullName (MemberName), parameters, Report);
+               }
                
                public override bool Define ()
                {
-                       if (!DoDefineBase ())
-                               return false;
-
                        if (!base.Define ())
                                return false;
 
                        if (!DefineParameters (parameters))
                                return false;
 
-                       if (OptAttributes != null && TypeManager.indexer_name_type != null) {
-                               Attribute indexer_attr = OptAttributes.Search (TypeManager.indexer_name_type);
+                       if (OptAttributes != null) {
+                               Attribute indexer_attr = OptAttributes.Search (PredefinedAttributes.Get.IndexerName);
                                if (indexer_attr != null) {
                                        // Remove the attribute from the list because it is not emitted
                                        OptAttributes.Attrs.Remove (indexer_attr);
@@ -7568,11 +7623,6 @@ namespace Mono.CSharp {
                                !Parent.PartialContainer.AddMember (Get) || !Parent.PartialContainer.AddMember (Set))
                                return false;
 
-                       if ((caching_flags & Flags.MethodOverloadsExist) != 0) {
-                               if (!Parent.MemberCache.CheckExistingMembersOverloads (this, Name, parameters))
-                                       return false;
-                       }
-
                        flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
                        
                        if (!DefineAccessors ())
@@ -7609,7 +7659,7 @@ namespace Mono.CSharp {
                                return true;
                        }
 
-                       return false;
+                       return base.EnableOverloadChecks (overload);
                }
 
                public override string GetDocCommentName (DeclSpace ds)
@@ -7731,23 +7781,23 @@ namespace Mono.CSharp {
                }
                
                public Operator (DeclSpace parent, OpType type, FullNamedExpression ret_type,
-                                int mod_flags, Parameters parameters,
+                                int mod_flags, ParametersCompiled parameters,
                                 ToplevelBlock block, Attributes attrs, Location loc)
                        : base (parent, null, ret_type, mod_flags, AllowedModifiers,
-                               new MemberName ("op_" + type.ToString(), loc), attrs, parameters)
+                               new MemberName (GetMetadataName (type), loc), attrs, parameters)
                {
                        OperatorType = type;
                        Block = block;
                }
 
-               public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb
+               public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
                {
-                       if (a.Type == TypeManager.conditional_attribute_type) {
+                       if (a.Type == pa.Conditional) {
                                Error_ConditionalAttributeIsNotValid ();
                                return;
                        }
 
-                       base.ApplyAttributeBuilder (a, cb);
+                       base.ApplyAttributeBuilder (a, cb, pa);
                }
                
                public override bool Define ()
@@ -7755,7 +7805,6 @@ namespace Mono.CSharp {
                        const int RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
                        if ((ModFlags & RequiredModifiers) != RequiredModifiers){
                                Report.Error (558, Location, "User-defined operator `{0}' must be declared static and public", GetSignatureForError ());
-                               return false;
                        }
 
                        if (!base.Define ())
@@ -7763,9 +7812,9 @@ namespace Mono.CSharp {
 
                        // imlicit and explicit operator of same types are not allowed
                        if (OperatorType == OpType.Explicit)
-                               Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Implicit), Parameters);
+                               Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Implicit), Parameters, Report);
                        else if (OperatorType == OpType.Implicit)
-                               Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Explicit), Parameters);
+                               Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Explicit), Parameters, Report);
 
                        Type declaring_type = MethodData.DeclaringType;
                        Type return_type = MemberType;
@@ -7773,11 +7822,19 @@ namespace Mono.CSharp {
                        
                        Type first_arg_type_unwrap = first_arg_type;
                        if (TypeManager.IsNullableType (first_arg_type))
-                               first_arg_type_unwrap = TypeManager.GetTypeArguments (first_arg_type) [0];
+                               first_arg_type_unwrap = TypeManager.TypeToCoreType (TypeManager.GetTypeArguments (first_arg_type) [0]);
                        
                        Type return_type_unwrap = return_type;
                        if (TypeManager.IsNullableType (return_type))
-                               return_type_unwrap = TypeManager.GetTypeArguments (return_type) [0];                    
+                               return_type_unwrap = TypeManager.TypeToCoreType (TypeManager.GetTypeArguments (return_type) [0]);
+
+                       if (TypeManager.IsDynamicType (return_type) || TypeManager.IsDynamicType (first_arg_type)) {
+                               Report.Error (1964, Location,
+                                       "User-defined operator `{0}' cannot convert to or from the dynamic type",
+                                       GetSignatureForError ());
+
+                               return false;
+                       }
 
                        //
                        // Rules for conversion operators
@@ -7877,41 +7934,14 @@ namespace Mono.CSharp {
                        return true;
                }
 
-               protected override bool DoDefine ()
+               protected override bool ResolveMemberType ()
                {
-                       if (!base.DoDefine ())
+                       if (!base.ResolveMemberType ())
                                return false;
 
                        flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
                        return true;
                }
-               
-               public override void Emit ()
-               {
-                       base.Emit ();
-
-                       Parameters.ApplyAttributes (MethodBuilder);
-
-                       //
-                       // abstract or extern methods have no bodies
-                       //
-                       if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
-                               return;
-                       
-                       EmitContext ec;
-                       if ((flags & MethodAttributes.PinvokeImpl) == 0)
-                               ec = CreateEmitContext (Parent, MethodBuilder.GetILGenerator ());
-                       else
-                               ec = CreateEmitContext (Parent, null);
-                       
-                       SourceMethod source = SourceMethod.Create (Parent, MethodBuilder, Block);
-                       ec.EmitTopBlock (this, Block);
-
-                       if (source != null)
-                               source.CloseMethod ();
-
-                       Block = null;
-               }
 
                // Operator cannot be override
                protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
@@ -7950,24 +7980,24 @@ namespace Mono.CSharp {
                public OpType GetMatchingOperator ()
                {
                        switch (OperatorType) {
-                               case OpType.Equality:
-                                       return OpType.Inequality;
-                               case OpType.Inequality:
-                                       return OpType.Equality;
-                               case OpType.True:
-                                       return OpType.False;
-                               case OpType.False:
-                                       return OpType.True;
-                               case OpType.GreaterThan:
-                                       return OpType.LessThan;
-                               case OpType.LessThan:
-                                       return OpType.GreaterThan;
-                               case OpType.GreaterThanOrEqual:
-                                       return OpType.LessThanOrEqual;
-                               case OpType.LessThanOrEqual:
-                                       return OpType.GreaterThanOrEqual;
-                               default:
-                                       return OpType.TOP;
+                       case OpType.Equality:
+                               return OpType.Inequality;
+                       case OpType.Inequality:
+                               return OpType.Equality;
+                       case OpType.True:
+                               return OpType.False;
+                       case OpType.False:
+                               return OpType.True;
+                       case OpType.GreaterThan:
+                               return OpType.LessThan;
+                       case OpType.LessThan:
+                               return OpType.GreaterThan;
+                       case OpType.GreaterThanOrEqual:
+                               return OpType.LessThanOrEqual;
+                       case OpType.LessThanOrEqual:
+                               return OpType.GreaterThanOrEqual;
+                       default:
+                               return OpType.TOP;
                        }
                }