Add more incomplete statements to AST. Fixes #4361.
[mono.git] / mcs / mcs / method.cs
index 7c7e12e10858008c4526f82f1abd9d05550b1ffe..b00f3f0bc070abffdff2e929894e7c3ac819c229 100644 (file)
@@ -9,17 +9,17 @@
 //
 // Copyright 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
 // Copyright 2004-2008 Novell, Inc
+// Copyright 2011 Xamarin Inc.
 //
 
 using System;
 using System.Collections.Generic;
-using System.Reflection;
-using System.Reflection.Emit;
-using System.Runtime.CompilerServices;
-using System.Runtime.InteropServices;
 using System.Security;
 using System.Security.Permissions;
 using System.Text;
+using System.Linq;
+using Mono.CompilerServices.SymbolWriter;
+using System.Runtime.CompilerServices;
 
 #if NET_2_1
 using XmlElement = System.Object;
@@ -27,38 +27,57 @@ using XmlElement = System.Object;
 using System.Xml;
 #endif
 
-using Mono.CompilerServices.SymbolWriter;
+#if STATIC
+using MetaType = IKVM.Reflection.Type;
+using SecurityType = System.Collections.Generic.List<IKVM.Reflection.Emit.CustomAttributeBuilder>;
+using IKVM.Reflection;
+using IKVM.Reflection.Emit;
+#else
+using MetaType = System.Type;
+using SecurityType = System.Collections.Generic.Dictionary<System.Security.Permissions.SecurityAction, System.Security.PermissionSet>;
+using System.Reflection;
+using System.Reflection.Emit;
+#endif
 
 namespace Mono.CSharp {
 
-       public abstract class MethodCore : InterfaceMemberBase
+       public abstract class MethodCore : InterfaceMemberBase, IParametersMember
        {
-               public readonly ParametersCompiled Parameters;
+               protected ParametersCompiled parameters;
                protected ToplevelBlock block;
                protected MethodSpec spec;
 
-               public MethodCore (DeclSpace parent, GenericMethod generic,
-                       FullNamedExpression type, Modifiers mod, Modifiers allowed_mod,
+               public MethodCore (TypeDefinition parent, FullNamedExpression type, Modifiers mod, Modifiers allowed_mod,
                        MemberName name, Attributes attrs, ParametersCompiled parameters)
-                       : base (parent, generic, type, mod, allowed_mod, name, attrs)
+                       : base (parent, type, mod, allowed_mod, name, attrs)
                {
-                       Parameters = parameters;
+                       this.parameters = parameters;
+               }
+
+               public override Variance ExpectedMemberTypeVariance {
+                       get {
+                               return Variance.Covariant;
+                       }
                }
 
                //
                //  Returns the System.Type array for the parameters of this method
                //
-               public Type [] ParameterTypes {
+               public TypeSpec [] ParameterTypes {
                        get {
-                               return Parameters.Types;
+                               return parameters.Types;
                        }
                }
 
                public ParametersCompiled ParameterInfo {
                        get {
-                               return Parameters;
+                               return parameters;
                        }
                }
+
+               AParametersCollection IParametersMember.Parameters {
+                       get { return parameters; }
+               }
                
                public ToplevelBlock Block {
                        get {
@@ -72,7 +91,7 @@ namespace Mono.CSharp {
 
                public CallingConventions CallingConventions {
                        get {
-                               CallingConventions cc = Parameters.CallingConvention;
+                               CallingConventions cc = parameters.CallingConvention;
                                if (!IsInterface)
                                        if ((ModFlags & Modifiers.STATIC) == 0)
                                                cc |= CallingConventions.HasThis;
@@ -83,54 +102,69 @@ namespace Mono.CSharp {
                        }
                }
 
+               protected override bool CheckOverrideAgainstBase (MemberSpec base_member)
+               {
+                       bool res = base.CheckOverrideAgainstBase (base_member);
+
+                       //
+                       // Check that the permissions are not being changed
+                       //
+                       if (!CheckAccessModifiers (this, base_member)) {
+                               Error_CannotChangeAccessModifiers (this, base_member);
+                               res = false;
+                       }
+
+                       return res;
+               }
+
                protected override bool CheckBase ()
                {
                        // Check whether arguments were correct.
-                       if (!DefineParameters (Parameters))
+                       if (!DefineParameters (parameters))
                                return false;
 
                        return base.CheckBase ();
                }
 
                //
-               // Returns a string that represents the signature for this 
-               // member which should be used in XML documentation.
+               //   Represents header string for documentation comment.
                //
-               public override string GetDocCommentName (DeclSpace ds)
+               public override string DocCommentHeader 
                {
-                       return DocUtil.GetMethodDocCommentName (this, Parameters, ds);
+                       get { return "M:"; }
                }
 
-               //
-               // Raised (and passed an XmlElement that contains the comment)
-               // when GenerateDocComment is writing documentation expectedly.
-               //
-               // FIXME: with a few effort, it could be done with XmlReader,
-               // that means removal of DOM use.
-               //
-               internal override void OnGenerateDocComment (XmlElement el)
+               public override void Emit ()
                {
-                       DocUtil.OnMethodGenerateDocComment (this, el, Report);
-               }
+                       if ((ModFlags & Modifiers.COMPILER_GENERATED) == 0) {
+                               parameters.CheckConstraints (this);
+                       }
 
-               //
-               //   Represents header string for documentation comment.
-               //
-               public override string DocCommentHeader 
-               {
-                       get { return "M:"; }
+                       base.Emit ();
                }
 
                public override bool EnableOverloadChecks (MemberCore overload)
                {
-                       if (overload is MethodCore || overload is AbstractPropertyEventMethod) {
+                       if (overload is MethodCore) {
                                caching_flags |= Flags.MethodOverloadsExist;
                                return true;
                        }
 
+                       if (overload is AbstractPropertyEventMethod)
+                               return true;
+
                        return base.EnableOverloadChecks (overload);
                }
 
+               public override string GetSignatureForDocumentation ()
+               {
+                       string s = base.GetSignatureForDocumentation ();
+                       if (MemberName.Arity > 0)
+                               s += "``" + MemberName.Arity.ToString ();
+
+                       return s + parameters.GetSignatureForDocumentation ();
+               }
+
                public MethodSpec Spec {
                        get { return spec; }
                }
@@ -140,74 +174,84 @@ namespace Mono.CSharp {
                        if (!base.VerifyClsCompliance ())
                                return false;
 
-                       if (Parameters.HasArglist) {
+                       if (parameters.HasArglist) {
                                Report.Warning (3000, 1, Location, "Methods with variable arguments are not CLS-compliant");
                        }
 
-                       if (!AttributeTester.IsClsCompliant (MemberType)) {
+                       if (member_type != null && !member_type.IsCLSCompliant ()) {
                                Report.Warning (3002, 1, Location, "Return type of `{0}' is not CLS-compliant",
                                        GetSignatureForError ());
                        }
 
-                       Parameters.VerifyClsCompliance (this);
+                       parameters.VerifyClsCompliance (this);
                        return true;
                }
        }
 
-       interface IGenericMethodDefinition : IMemberDefinition
+       public interface IGenericMethodDefinition : IMemberDefinition
        {
-               MethodInfo MakeGenericMethod (Type[] targs);
+               TypeParameterSpec[] TypeParameters { get; }
+               int TypeParametersCount { get; }
+
+//             MethodInfo MakeGenericMethod (TypeSpec[] targs);
        }
 
-       public class MethodSpec : MemberSpec
+       public sealed class MethodSpec : MemberSpec, IParametersMember
        {
-               MethodBase metaInfo;
-               readonly AParametersCollection parameters;
+               MethodBase metaInfo, inflatedMetaInfo;
+               AParametersCollection parameters;
+               TypeSpec returnType;
+
+               TypeSpec[] targs;
+               TypeParameterSpec[] constraints;
 
-               public MethodSpec (MemberKind kind, IMemberDefinition details, MethodBase info, AParametersCollection parameters, Modifiers modifiers)
-                       : base (kind, details, info.Name, modifiers)
+               public MethodSpec (MemberKind kind, TypeSpec declaringType, IMemberDefinition details, TypeSpec returnType,
+                       MethodBase info, AParametersCollection parameters, Modifiers modifiers)
+                       : base (kind, declaringType, details, modifiers)
                {
-                       this.MetaInfo = info;
+                       this.metaInfo = info;
                        this.parameters = parameters;
+                       this.returnType = returnType;
                }
 
-               public override Type DeclaringType {
+               #region Properties
+
+               public override int Arity {
                        get {
-                               return MetaInfo.DeclaringType;
+                               return IsGeneric ? GenericDefinition.TypeParametersCount : 0;
                        }
                }
 
-               public Type[] GetGenericArguments ()
-               {
-                       return MetaInfo.GetGenericArguments ();
-               }
-
-               public MethodSpec Inflate (Type[] targs)
-               {
-                       // TODO: Only create MethodSpec and inflate parameters, defer the call for later
-                       var mb = ((IGenericMethodDefinition) definition).MakeGenericMethod (targs);
+               public TypeParameterSpec[] Constraints {
+                       get {
+                               if (constraints == null && IsGeneric)
+                                       constraints = GenericDefinition.TypeParameters;
 
-                       // TODO: Does not work on .NET
-                       var par = TypeManager.GetParameterData (mb);
+                               return constraints;
+                       }
+               }
 
-                       return new MethodSpec (Kind, definition, mb, par, Modifiers);
+               public bool IsConstructor {
+                       get {
+                               return Kind == MemberKind.Constructor;
+                       }
                }
 
-               public bool IsAbstract {
+               public IGenericMethodDefinition GenericDefinition {
                        get {
-                               return (Modifiers & Modifiers.ABSTRACT) != 0;
+                               return (IGenericMethodDefinition) definition;
                        }
                }
 
-               public bool IsConstructor {
+               public bool IsExtensionMethod {
                        get {
-                               return MetaInfo.IsConstructor;
+                               return IsStatic && parameters.HasExtensionMethodType;
                        }
                }
 
-               public bool IsGenericMethod {
+               public bool IsSealed {
                        get {
-                               return MetaInfo.IsGenericMethod;
+                               return (Modifiers & Modifiers.SEALED) != 0;
                        }
                }
 
@@ -218,24 +262,249 @@ namespace Mono.CSharp {
                        }
                }
 
-               public MethodBase MetaInfo {
+               public bool IsReservedMethod {
                        get {
-                               return metaInfo;
+                               return Kind == MemberKind.Operator || IsAccessor;
                        }
-                       set {
-                               metaInfo = value;
+               }
+
+               TypeSpec IInterfaceMemberSpec.MemberType {
+                       get {
+                               return returnType;
                        }
                }
 
                public AParametersCollection Parameters {
-                       get { return parameters; }
+                       get { 
+                               return parameters;
+                       }
+               }
+
+               public TypeSpec ReturnType {
+                       get {
+                               return returnType;
+                       }
                }
 
-               public Type ReturnType {
+               public TypeSpec[] TypeArguments {
                        get {
-                               return IsConstructor ?
-                                       TypeManager.void_type : ((MethodInfo) MetaInfo).ReturnType;
+                               return targs;
+                       }
+               }
+
+               #endregion
+
+               public MethodSpec GetGenericMethodDefinition ()
+               {
+                       if (!IsGeneric && !DeclaringType.IsGeneric)
+                               return this;
+
+                       return MemberCache.GetMember (declaringType, this);
+               }
+
+               public MethodBase GetMetaInfo ()
+               {
+                       //
+                       // inflatedMetaInfo is extra field needed for cases where we
+                       // inflate method but another nested type can later inflate
+                       // again (the cache would be build with inflated metaInfo) and
+                       // TypeBuilder can work with method definitions only
+                       //
+                       if (inflatedMetaInfo == null) {
+                               if ((state & StateFlags.PendingMetaInflate) != 0) {
+                                       var dt_meta = DeclaringType.GetMetaInfo ();
+
+                                       if (DeclaringType.IsTypeBuilder) {
+                                               if (IsConstructor)
+                                                       inflatedMetaInfo = TypeBuilder.GetConstructor (dt_meta, (ConstructorInfo) metaInfo);
+                                               else
+                                                       inflatedMetaInfo = TypeBuilder.GetMethod (dt_meta, (MethodInfo) metaInfo);
+                                       } else {
+#if STATIC
+                                               // it should not be reached
+                                               throw new NotImplementedException ();
+#else
+                                               inflatedMetaInfo = MethodInfo.GetMethodFromHandle (metaInfo.MethodHandle, dt_meta.TypeHandle);
+#endif
+                                       }
+
+                                       state &= ~StateFlags.PendingMetaInflate;
+                               } else {
+                                       inflatedMetaInfo = metaInfo;
+                               }
+                       }
+
+                       if ((state & StateFlags.PendingMakeMethod) != 0) {
+                               var sre_targs = new MetaType[targs.Length];
+                               for (int i = 0; i < sre_targs.Length; ++i)
+                                       sre_targs[i] = targs[i].GetMetaInfo ();
+
+                               inflatedMetaInfo = ((MethodInfo) inflatedMetaInfo).MakeGenericMethod (sre_targs);
+                               state &= ~StateFlags.PendingMakeMethod;
+                       }
+
+                       return inflatedMetaInfo;
+               }
+
+               public override string GetSignatureForDocumentation ()
+               {
+                       string name;
+                       switch (Kind) {
+                       case MemberKind.Constructor:
+                               name = "#ctor";
+                               break;
+                       case MemberKind.Method:
+                               if (Arity > 0)
+                                       name = Name + "``" + Arity.ToString ();
+                               else
+                                       name = Name;
+
+                               break;
+                       default:
+                               name = Name;
+                               break;
+                       }
+
+                       name = DeclaringType.GetSignatureForDocumentation () + "." + name + parameters.GetSignatureForDocumentation ();
+                       if (Kind == MemberKind.Operator) {
+                               var op = Operator.GetType (Name).Value;
+                               if (op == Operator.OpType.Explicit || op == Operator.OpType.Implicit) {
+                                       name += "~" + ReturnType.GetSignatureForDocumentation ();
+                               }
+                       }
+
+                       return name;
+               }
+
+               public override string GetSignatureForError ()
+               {
+                       string name;
+                       if (IsConstructor) {
+                               name = DeclaringType.GetSignatureForError () + "." + DeclaringType.Name;
+                       } else if (Kind == MemberKind.Operator) {
+                               var op = Operator.GetType (Name).Value;
+                               if (op == Operator.OpType.Implicit || op == Operator.OpType.Explicit) {
+                                       name = DeclaringType.GetSignatureForError () + "." + Operator.GetName (op) + " operator " + returnType.GetSignatureForError ();
+                               } else {
+                                       name = DeclaringType.GetSignatureForError () + ".operator " + Operator.GetName (op);
+                               }
+                       } else if (IsAccessor) {
+                               int split = Name.IndexOf ('_');
+                               name = Name.Substring (split + 1);
+                               var postfix = Name.Substring (0, split);
+                               if (split == 3) {
+                                       var pc = parameters.Count;
+                                       if (pc > 0 && postfix == "get") {
+                                               name = "this" + parameters.GetSignatureForError ("[", "]", pc);
+                                       } else if (pc > 1 && postfix == "set") {
+                                               name = "this" + parameters.GetSignatureForError ("[", "]", pc - 1);
+                                       }
+                               }
+
+                               return DeclaringType.GetSignatureForError () + "." + name + "." + postfix;
+                       } else {
+                               name = base.GetSignatureForError ();
+                               if (targs != null)
+                                       name += "<" + TypeManager.CSharpName (targs) + ">";
+                               else if (IsGeneric)
+                                       name += "<" + TypeManager.CSharpName (GenericDefinition.TypeParameters) + ">";
+                       }
+
+                       return name + parameters.GetSignatureForError ();
+               }
+
+               public override MemberSpec InflateMember (TypeParameterInflator inflator)
+               {
+                       var ms = (MethodSpec) base.InflateMember (inflator);
+                       ms.inflatedMetaInfo = null;
+                       ms.returnType = inflator.Inflate (returnType);
+                       ms.parameters = parameters.Inflate (inflator);
+                       if (IsGeneric)
+                               ms.constraints = TypeParameterSpec.InflateConstraints (inflator, Constraints);
+
+                       return ms;
+               }
+
+               public MethodSpec MakeGenericMethod (IMemberContext context, params TypeSpec[] targs)
+               {
+                       if (targs == null)
+                               throw new ArgumentNullException ();
+// TODO MemberCache
+//                     if (generic_intances != null && generic_intances.TryGetValue (targs, out ginstance))
+//                             return ginstance;
+
+                       //if (generic_intances == null)
+                       //    generic_intances = new Dictionary<TypeSpec[], Method> (TypeSpecArrayComparer.Default);
+
+                       var inflator = new TypeParameterInflator (context, DeclaringType, GenericDefinition.TypeParameters, targs);
+
+                       var inflated = (MethodSpec) MemberwiseClone ();
+                       inflated.declaringType = inflator.TypeInstance;
+                       inflated.returnType = inflator.Inflate (returnType);
+                       inflated.parameters = parameters.Inflate (inflator);
+                       inflated.targs = targs;
+                       inflated.constraints = TypeParameterSpec.InflateConstraints (inflator, constraints ?? GenericDefinition.TypeParameters);
+                       inflated.state |= StateFlags.PendingMakeMethod;
+
+                       //                      if (inflated.parent == null)
+                       //                              inflated.parent = parent;
+
+                       //generic_intances.Add (targs, inflated);
+                       return inflated;
+               }
+
+               public MethodSpec Mutate (TypeParameterMutator mutator)
+               {
+                       var targs = TypeArguments;
+                       if (targs != null)
+                               targs = mutator.Mutate (targs);
+
+                       var decl = DeclaringType;
+                       if (DeclaringType.IsGenericOrParentIsGeneric) {
+                               decl = mutator.Mutate (decl);
                        }
+
+                       if (targs == TypeArguments && decl == DeclaringType)
+                               return this;
+
+                       var ms = (MethodSpec) MemberwiseClone ();
+                       if (decl != DeclaringType) {
+                               ms.inflatedMetaInfo = null;
+                               ms.declaringType = decl;
+                               ms.state |= StateFlags.PendingMetaInflate;
+                       }
+
+                       if (targs != null) {
+                               ms.targs = targs;
+                               ms.state |= StateFlags.PendingMakeMethod;
+                       }
+
+                       return ms;
+               }
+
+               public override List<TypeSpec> ResolveMissingDependencies ()
+               {
+                       var missing = returnType.ResolveMissingDependencies ();
+                       foreach (var pt in parameters.Types) {
+                               var m = pt.GetMissingDependencies ();
+                               if (m == null)
+                                       continue;
+
+                               if (missing == null)
+                                       missing = new List<TypeSpec> ();
+
+                               missing.AddRange (m);
+                       }
+
+                       return missing;                 
+               }
+
+               public void SetMetaInfo (MethodInfo info)
+               {
+                       if (this.metaInfo != null)
+                               throw new InternalErrorException ("MetaInfo reset");
+
+                       this.metaInfo = info;
                }
        }
 
@@ -243,34 +512,35 @@ namespace Mono.CSharp {
        {
                public MethodBuilder MethodBuilder;
                ReturnParameter return_attributes;
-               Dictionary<SecurityAction, PermissionSet> declarative_security;
+               SecurityType declarative_security;
                protected MethodData MethodData;
 
-               static string[] attribute_targets = new string [] { "method", "return" };
+               static readonly string[] attribute_targets = new string [] { "method", "return" };
 
-               protected MethodOrOperator (DeclSpace parent, GenericMethod generic, FullNamedExpression type, Modifiers mod,
-                               Modifiers allowed_mod, MemberName name,
+               protected MethodOrOperator (TypeDefinition parent, FullNamedExpression type, Modifiers mod, Modifiers allowed_mod, MemberName name,
                                Attributes attrs, ParametersCompiled parameters)
-                       : base (parent, generic, type, mod, allowed_mod, name,
-                                       attrs, parameters)
+                       : base (parent, type, mod, allowed_mod, name, attrs, parameters)
                {
                }
 
-               public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
+               public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
                {
                        if (a.Target == AttributeTargets.ReturnValue) {
                                if (return_attributes == null)
                                        return_attributes = new ReturnParameter (this, MethodBuilder, Location);
 
-                               return_attributes.ApplyAttributeBuilder (a, cb, pa);
+                               return_attributes.ApplyAttributeBuilder (a, ctor, cdata, pa);
                                return;
                        }
 
-                       if (a.IsInternalMethodImplAttribute) {
-                               is_external_implementation = true;
-                       }
+                       if (a.Type == pa.MethodImpl) {
+                               if ((ModFlags & Modifiers.ASYNC) != 0 && (a.GetMethodImplOptions () & MethodImplOptions.Synchronized) != 0) {
+                                       Report.Error (4015, a.Location, "`{0}': Async methods cannot use `MethodImplOptions.Synchronized'",
+                                               GetSignatureForError ());
+                               }
 
-                       if (a.Type == pa.DllImport) {
+                               is_external_implementation = a.IsInternalCall ();
+                       } else if (a.Type == pa.DllImport) {
                                const Modifiers 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'");
@@ -279,14 +549,12 @@ namespace Mono.CSharp {
                        }
 
                        if (a.IsValidSecurityAttribute ()) {
-                               if (declarative_security == null)
-                                       declarative_security = new Dictionary<SecurityAction, PermissionSet> ();
-                               a.ExtractSecurityPermissionSet (declarative_security);
+                               a.ExtractSecurityPermissionSet (ctor, ref declarative_security);
                                return;
                        }
 
                        if (MethodBuilder != null)
-                               MethodBuilder.SetCustomAttribute (cb);
+                               MethodBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
                }
 
                public override AttributeTargets AttributeTargets {
@@ -297,28 +565,12 @@ namespace Mono.CSharp {
 
                protected override bool CheckForDuplications ()
                {
-                       string name = GetFullName (MemberName);
-                       if (MemberName.IsGeneric)
-                               name = MemberName.MakeName (name, MemberName.TypeArguments);
-
-                       return Parent.MemberCache.CheckExistingMembersOverloads (this, name, Parameters, Report);
+                       return Parent.MemberCache.CheckExistingMembersOverloads (this, parameters);
                }
 
-               public virtual EmitContext CreateEmitContext (ILGenerator ig)
+               public virtual EmitContext CreateEmitContext (ILGenerator ig, SourceMethodBuilder sourceMethod)
                {
-                       return new EmitContext (
-                               this, ig, MemberType);
-               }
-
-               protected override bool ResolveMemberType ()
-               {
-                       if (GenericMethod != null) {
-                               MethodBuilder = Parent.TypeBuilder.DefineMethod (GetFullName (MemberName), flags);
-                               if (!GenericMethod.Define (this))
-                                       return false;
-                       }
-
-                       return base.ResolveMemberType ();
+                       return new EmitContext (this, ig, MemberType, sourceMethod);
                }
 
                public override bool Define ()
@@ -329,15 +581,6 @@ namespace Mono.CSharp {
                        if (!CheckBase ())
                                return false;
 
-                       if (block != null && block.IsIterator && !(Parent is IteratorStorey)) {
-                               //
-                               // Current method is turned into automatically generated
-                               // wrapper which creates an instance of iterator
-                               //
-                               Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags, Compiler);
-                               ModFlags |= Modifiers.DEBUGGER_HIDDEN;
-                       }
-
                        MemberKind kind;
                        if (this is Operator)
                                kind = MemberKind.Operator;
@@ -352,30 +595,35 @@ namespace Mono.CSharp {
 
                                // Add to member cache only when a partial method implementation has not been found yet
                                if ((caching_flags & Flags.PartialDefinitionExists) == 0) {
-                                       MethodBase mb = new PartialMethodDefinitionInfo (this);
+//                                     MethodBase mb = new PartialMethodDefinitionInfo (this);
+
+                                       spec = new MethodSpec (kind, Parent.Definition, this, ReturnType, null, parameters, ModFlags);
+                                       if (MemberName.Arity > 0) {
+                                               spec.IsGeneric = true;
+
+                                               // TODO: Have to move DefineMethod after Define (ideally to Emit)
+                                               throw new NotImplementedException ("Generic partial methods");
+                                       }
 
-                                       spec = new MethodSpec (kind, this, mb, Parameters, ModFlags);
-                                       Parent.MemberCache.AddMember (mb, spec);
-                                       TypeManager.AddMethod (mb, this);
+                                       Parent.MemberCache.AddMember (spec);
                                }
 
                                return true;
                        }
 
                        MethodData = new MethodData (
-                               this, ModFlags, flags, this, MethodBuilder, GenericMethod, base_method);
+                               this, ModFlags, flags, this, MethodBuilder, base_method);
 
-                       if (!MethodData.Define (Parent.PartialContainer, GetFullName (MemberName), Report))
+                       if (!MethodData.Define (Parent.PartialContainer, GetFullName (MemberName)))
                                return false;
                                        
                        MethodBuilder = MethodData.MethodBuilder;
 
-                       spec = new MethodSpec (kind, this, MethodBuilder, Parameters, ModFlags);
-
-                       if (TypeManager.IsGenericMethod (MethodBuilder))
-                               Parent.MemberCache.AddGenericMember (MethodBuilder, this);
+                       spec = new MethodSpec (kind, Parent.Definition, this, ReturnType, MethodBuilder, parameters, ModFlags);
+                       if (MemberName.Arity > 0)
+                               spec.IsGeneric = true;
                        
-                       Parent.MemberCache.AddMember (MethodBuilder, spec);
+                       Parent.MemberCache.AddMember (this, MethodBuilder.Name, spec);
 
                        return true;
                }
@@ -387,9 +635,9 @@ namespace Mono.CSharp {
                        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) {
+                               for (int i = 0; i < parameters.Count; ++i) {
+                                       IParameterData p = parameters.FixedParameters [i];
+                                       if ((p.ModFlags & Parameter.Modifier.OUT) != 0) {
                                                Report.Error (752, Location, "`{0}': A partial method parameters cannot use `out' modifier",
                                                        GetSignatureForError ());
                                        }
@@ -404,33 +652,24 @@ namespace Mono.CSharp {
                {
                        base.DoMemberTypeDependentChecks ();
 
-                       if (!TypeManager.IsGenericParameter (MemberType)) {
-                               if (MemberType.IsAbstract && MemberType.IsSealed) {
-                                       Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
-                               }
+                       if (MemberType.IsStatic) {
+                               Error_StaticReturnType ();
                        }
                }
 
                public override void Emit ()
                {
                        if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
-                               PredefinedAttributes.Get.CompilerGenerated.EmitAttribute (MethodBuilder);
+                               Module.PredefinedAttributes.CompilerGenerated.EmitAttribute (MethodBuilder);
                        if ((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0)
-                               PredefinedAttributes.Get.DebuggerHidden.EmitAttribute (MethodBuilder);
+                               Module.PredefinedAttributes.DebuggerHidden.EmitAttribute (MethodBuilder);
 
-                       if (TypeManager.IsDynamicType (ReturnType)) {
+                       if (ReturnType.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
                                return_attributes = new ReturnParameter (this, MethodBuilder, Location);
-                               PredefinedAttributes.Get.Dynamic.EmitAttribute (return_attributes.Builder);
-                       } else {
-                               var trans_flags = TypeManager.HasDynamicTypeUsed (ReturnType);
-                               if (trans_flags != null) {
-                                       var pa = PredefinedAttributes.Get.DynamicTransform;
-                                       if (pa.Constructor != null || pa.ResolveConstructor (Location, TypeManager.bool_type.MakeArrayType ())) {
-                                               return_attributes = new ReturnParameter (this, MethodBuilder, Location);
-                                               return_attributes.Builder.SetCustomAttribute (
-                                                       new CustomAttributeBuilder (pa.Constructor, new object [] { trans_flags }));
-                                       }
-                               }
+                               Module.PredefinedAttributes.Dynamic.EmitAttribute (return_attributes.Builder);
+                       } else if (ReturnType.HasDynamicElement) {
+                               return_attributes = new ReturnParameter (this, MethodBuilder, Location);
+                               Module.PredefinedAttributes.Dynamic.EmitAttribute (return_attributes.Builder, ReturnType, Location);
                        }
 
                        if (OptAttributes != null)
@@ -438,17 +677,23 @@ namespace Mono.CSharp {
 
                        if (declarative_security != null) {
                                foreach (var de in declarative_security) {
+#if STATIC
+                                       MethodBuilder.__AddDeclarativeSecurity (de);
+#else
                                        MethodBuilder.AddDeclarativeSecurity (de.Key, de.Value);
+#endif
                                }
                        }
 
-                       if (MethodData != null)
-                               MethodData.Emit (Parent);
+                       if (type_expr != null)
+                               ConstraintChecker.Check (this, member_type, type_expr.Location);
 
                        base.Emit ();
 
+                       if (MethodData != null)
+                               MethodData.Emit (Parent);
+
                        Block = null;
-                       MethodData = null;
                }
 
                protected void Error_ConditionalAttributeIsNotValid ()
@@ -478,7 +723,13 @@ namespace Mono.CSharp {
 
                #region IMethodData Members
 
-               public Type ReturnType {
+               bool IMethodData.IsAccessor {
+                       get {
+                               return false;
+                       }
+               }
+
+               public TypeSpec ReturnType {
                        get {
                                return MemberType;
                        }
@@ -493,202 +744,172 @@ namespace Mono.CSharp {
                /// <summary>
                /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
                /// </summary>
-               public bool IsExcluded () {
-                       if ((caching_flags & Flags.Excluded_Undetected) == 0)
-                               return (caching_flags & Flags.Excluded) != 0;
+               public override string[] ConditionalConditions ()
+               {
+                       if ((caching_flags & (Flags.Excluded_Undetected | Flags.Excluded)) == 0)
+                               return null;
+
+                       if ((ModFlags & Modifiers.PARTIAL) != 0 && (caching_flags & Flags.Excluded) != 0)
+                               return new string [0];
 
                        caching_flags &= ~Flags.Excluded_Undetected;
+                       string[] conditions;
 
                        if (base_method == null) {
                                if (OptAttributes == null)
-                                       return false;
-
-                               Attribute[] attrs = OptAttributes.SearchMulti (PredefinedAttributes.Get.Conditional);
+                                       return null;
 
+                               Attribute[] attrs = OptAttributes.SearchMulti (Module.PredefinedAttributes.Conditional);
                                if (attrs == null)
-                                       return false;
-
-                               foreach (Attribute a in attrs) {
-                                       string condition = a.GetConditionalAttributeValue ();
-                                       if (condition == null)
-                                               return false;
-
-                                       if (Location.CompilationUnit.IsConditionalDefined (condition))
-                                               return false;
-                               }
-
-                               caching_flags |= Flags.Excluded;
-                               return true;
-                       }
+                                       return null;
 
-                       IMethodData md = TypeManager.GetMethod (TypeManager.DropGenericMethodArguments (base_method));
-                       if (md == null) {
-                               if (AttributeTester.IsConditionalMethodExcluded (base_method, Location)) {
-                                       caching_flags |= Flags.Excluded;
-                                       return true;
-                               }
-                               return false;
+                               conditions = new string[attrs.Length];
+                               for (int i = 0; i < conditions.Length; ++i)
+                                       conditions[i] = attrs[i].GetConditionalAttributeValue ();
+                       } else {
+                               conditions = base_method.MemberDefinition.ConditionalConditions();
                        }
 
-                       if (md.IsExcluded ()) {
+                       if (conditions != null)
                                caching_flags |= Flags.Excluded;
-                               return true;
-                       }
-                       return false;
-               }
 
-               GenericMethod IMethodData.GenericMethod {
-                       get {
-                               return GenericMethod;
-                       }
+                       return conditions;
                }
 
-               public virtual void EmitExtraSymbolInfo (SourceMethod source)
-               { }
-
                #endregion
 
+               public override void WriteDebugSymbol (MonoSymbolFile file)
+               {
+                       if (MethodData != null)
+                               MethodData.WriteDebugSymbol (file);
+               }
        }
 
-       public class SourceMethod : IMethodDef
+       public class Method : MethodOrOperator, IGenericMethodDefinition
        {
-               MethodBase method;
-               SourceMethodBuilder builder;
+               Method partialMethodImplementation;
 
-               protected SourceMethod (DeclSpace parent, MethodBase method, ICompileUnit file)
+               public Method (TypeDefinition parent, FullNamedExpression return_type, Modifiers mod, MemberName name, ParametersCompiled parameters, Attributes attrs)
+                       : base (parent, return_type, mod,
+                               parent.PartialContainer.Kind == MemberKind.Interface ? AllowedModifiersInterface :
+                               parent.PartialContainer.Kind == MemberKind.Struct ? AllowedModifiersStruct | Modifiers.ASYNC :
+                               AllowedModifiersClass | Modifiers.ASYNC,
+                               name, attrs, parameters)
                {
-                       this.method = method;
-                       
-                       builder = SymbolWriter.OpenMethod (file, parent.NamespaceEntry.SymbolFileID, this);
                }
 
-               public string Name {
-                       get { return method.Name; }
+               protected Method (TypeDefinition parent, FullNamedExpression return_type, Modifiers mod, Modifiers amod,
+                                       MemberName name, ParametersCompiled parameters, Attributes attrs)
+                       : base (parent, return_type, mod, amod, name, attrs, parameters)
+               {
                }
 
-               public int Token {
+               #region Properties
+
+               public override TypeParameters CurrentTypeParameters {
                        get {
-                               if (method is MethodBuilder)
-                                       return ((MethodBuilder) method).GetToken ().Token;
-                               else if (method is ConstructorBuilder)
-                                       return ((ConstructorBuilder) method).GetToken ().Token;
-                               else
-                                       throw new NotSupportedException ();
+                               return MemberName.TypeParameters;
                        }
                }
 
-               public void CloseMethod ()
-               {
-                       SymbolWriter.CloseMethod ();
+               public TypeParameterSpec[] TypeParameters {
+                       get {
+                               return CurrentTypeParameters.Types;
+                       }
+               }
+
+               public int TypeParametersCount {
+                       get {
+                               return CurrentTypeParameters == null ? 0 : CurrentTypeParameters.Count;
+                       }
                }
 
-               public void SetRealMethodName (string name)
+#endregion
+
+               public override void Accept (StructuralVisitor visitor)
                {
-                       if (builder != null)
-                               builder.SetRealMethodName (name);
+                       visitor.Visit (this);
                }
 
-               public static SourceMethod Create (DeclSpace parent, MethodBase method, Block block)
+               public static Method Create (TypeDefinition parent, FullNamedExpression returnType, Modifiers mod,
+                                  MemberName name, ParametersCompiled parameters, Attributes attrs, bool hasConstraints)
                {
-                       if (!SymbolWriter.HasSymbolWriter)
-                               return null;
-                       if (block == null)
-                               return null;
+                       var m = new Method (parent, returnType, mod, name, parameters, attrs);
 
-                       Location start_loc = block.StartLocation;
-                       if (start_loc.IsNull)
-                               return null;
+                       if (hasConstraints && ((mod & Modifiers.OVERRIDE) != 0 || m.IsExplicitImpl)) {
+                               m.Report.Error (460, m.Location,
+                                       "`{0}': Cannot specify constraints for overrides and explicit interface implementation methods",
+                                       m.GetSignatureForError ());
+                       }
 
-                       ICompileUnit compile_unit = start_loc.CompilationUnit;
-                       if (compile_unit == null)
-                               return null;
+                       if ((mod & Modifiers.PARTIAL) != 0) {
+                               const Modifiers invalid_partial_mod = Modifiers.AccessibilityMask | Modifiers.ABSTRACT | Modifiers.EXTERN |
+                                       Modifiers.NEW | Modifiers.OVERRIDE | Modifiers.SEALED | Modifiers.VIRTUAL;
 
-                       return new SourceMethod (parent, method, compile_unit);
-               }
-       }
+                               if ((mod & invalid_partial_mod) != 0) {
+                                       m.Report.Error (750, m.Location,
+                                               "A partial method cannot define access modifier or any of abstract, extern, new, override, sealed, or virtual modifiers");
+                                       mod &= ~invalid_partial_mod;
+                               }
 
-       public class Method : MethodOrOperator, IGenericMethodDefinition
-       {
-               /// <summary>
-               ///   Modifiers allowed in a class declaration
-               /// </summary>
-               const Modifiers AllowedModifiers =
-                       Modifiers.NEW |
-                       Modifiers.PUBLIC |
-                       Modifiers.PROTECTED |
-                       Modifiers.INTERNAL |
-                       Modifiers.PRIVATE |
-                       Modifiers.STATIC |
-                       Modifiers.VIRTUAL |
-                       Modifiers.SEALED |
-                       Modifiers.OVERRIDE |
-                       Modifiers.ABSTRACT |
-                       Modifiers.UNSAFE |
-                       Modifiers.EXTERN;
+                               if ((parent.ModFlags & Modifiers.PARTIAL) == 0) {
+                                       m.Report.Error (751, m.Location, 
+                                               "A partial method must be declared within a partial class or partial struct");
+                               }
+                       }
 
-               const Modifiers AllowedInterfaceModifiers = 
-                       Modifiers.NEW | Modifiers.UNSAFE;
+                       if ((mod & Modifiers.STATIC) == 0 && parameters.HasExtensionMethodType) {
+                               m.Report.Error (1105, m.Location, "`{0}': Extension methods must be declared static",
+                                       m.GetSignatureForError ());
+                       }
 
-               Method partialMethodImplementation;
 
-               public Method (DeclSpace parent, GenericMethod generic,
-                              FullNamedExpression return_type, Modifiers mod,
-                              MemberName name, ParametersCompiled parameters, Attributes attrs)
-                       : base (parent, generic, return_type, mod,
-                               parent.PartialContainer.Kind == MemberKind.Interface ? AllowedInterfaceModifiers : AllowedModifiers,
-                               name, attrs, parameters)
-               {
+                       return m;
                }
 
-               protected Method (DeclSpace parent, FullNamedExpression return_type, Modifiers mod, Modifiers amod,
-                                       MemberName name, ParametersCompiled parameters, Attributes attrs)
-                       : base (parent, null, return_type, mod, amod, name, attrs, parameters)
-               {
-               }
-               
                public override string GetSignatureForError()
                {
-                       return base.GetSignatureForError () + Parameters.GetSignatureForError ();
+                       return base.GetSignatureForError () + parameters.GetSignatureForError ();
                }
 
                void Error_DuplicateEntryPoint (Method b)
                {
                        Report.Error (17, b.Location,
                                "Program `{0}' has more than one entry point defined: `{1}'",
-                               CodeGen.FileName, b.GetSignatureForError ());
+                               b.Module.Builder.ScopeName, b.GetSignatureForError ());
                }
 
                bool IsEntryPoint ()
                {
-                       if (ReturnType != TypeManager.void_type &&
-                               ReturnType != TypeManager.int32_type)
+                       if (ReturnType.Kind != MemberKind.Void && ReturnType.BuiltinType != BuiltinTypeSpec.Type.Int)
                                return false;
 
-                       if (Parameters.Count == 0)
+                       if (parameters.IsEmpty)
                                return true;
 
-                       if (Parameters.Count > 1)
+                       if (parameters.Count > 1)
                                return false;
 
-                       Type t = Parameters.Types [0];
-                       return t.IsArray && t.GetArrayRank () == 1 &&
-                                       TypeManager.GetElementType (t) == TypeManager.string_type &&
-                                       (Parameters[0].ModFlags & ~Parameter.Modifier.PARAMS) == Parameter.Modifier.NONE;
+                       var ac = parameters.Types [0] as ArrayContainer;
+                       return ac != null && ac.Rank == 1 && ac.Element.BuiltinType == BuiltinTypeSpec.Type.String &&
+                                       (parameters[0].ModFlags & Parameter.Modifier.RefOutMask) == 0;
                }
 
-               public override FullNamedExpression LookupNamespaceOrType (string name, Location loc, bool ignore_cs0104)
+               public override FullNamedExpression LookupNamespaceOrType (string name, int arity, LookupMode mode, Location loc)
                {
-                       TypeParameter[] tp = CurrentTypeParameters;
-                       if (tp != null) {
-                               TypeParameter t = TypeParameter.FindTypeParameter (tp, name);
-                               if (t != null)
-                                       return new TypeParameterExpr (t, loc);
+                       if (arity == 0) {
+                               var tp = CurrentTypeParameters;
+                               if (tp != null) {
+                                       TypeParameter t = tp.Find (name);
+                                       if (t != null)
+                                               return new TypeParameterExpr (t, loc);
+                               }
                        }
 
-                       return base.LookupNamespaceOrType (name, loc, ignore_cs0104);
+                       return base.LookupNamespaceOrType (name, arity, mode, loc);
                }
 
-               public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
+               public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
                {
                        if (a.Type == pa.Conditional) {
                                if (IsExplicitImpl) {
@@ -696,13 +917,13 @@ namespace Mono.CSharp {
                                        return;
                                }
 
-                               if (ReturnType != TypeManager.void_type) {
-                                       Report.Error (578, Location, "Conditional not valid on `{0}' because its return type is not void", GetSignatureForError ());
+                               if ((ModFlags & Modifiers.OVERRIDE) != 0) {
+                                       Report.Error (243, Location, "Conditional not valid on `{0}' because it is an override method", GetSignatureForError ());
                                        return;
                                }
 
-                               if ((ModFlags & Modifiers.OVERRIDE) != 0) {
-                                       Report.Error (243, Location, "Conditional not valid on `{0}' because it is an override method", GetSignatureForError ());
+                               if (ReturnType.Kind != MemberKind.Void) {
+                                       Report.Error (578, Location, "Conditional not valid on `{0}' because its return type is not void", GetSignatureForError ());
                                        return;
                                }
 
@@ -718,8 +939,8 @@ namespace Mono.CSharp {
                                        return;
                                }
 
-                               for (int i = 0; i < Parameters.Count; ++i) {
-                                       if (Parameters.FixedParameters [i].ModFlags == Parameter.Modifier.OUT) {
+                               for (int i = 0; i < parameters.Count; ++i) {
+                                       if ((parameters.FixedParameters [i].ModFlags & Parameter.Modifier.OUT) != 0) {
                                                Report.Error (685, Location, "Conditional method `{0}' cannot have an out parameter", GetSignatureForError ());
                                                return;
                                        }
@@ -731,55 +952,198 @@ namespace Mono.CSharp {
                                return;
                        }
 
-                       base.ApplyAttributeBuilder (a, cb, pa);
+                       base.ApplyAttributeBuilder (a, ctor, cdata, pa);
                }
 
-               protected override bool CheckForDuplications ()
-               {
-                       if (!base.CheckForDuplications ())
-                               return false;
+               void CreateTypeParameters ()
+               {
+                       var tparams = MemberName.TypeParameters;
+                       string[] snames = new string[MemberName.Arity];
+                       var parent_tparams = Parent.TypeParametersAll;
 
-                       var ar = Parent.PartialContainer.Properties;
-                       if (ar != null) {
-                               for (int i = 0; i < ar.Count; ++i) {
-                                       PropertyBase pb = (PropertyBase) ar [i];
-                                       if (pb.AreAccessorsDuplicateImplementation (this))
-                                               return false;
+                       for (int i = 0; i < snames.Length; i++) {
+                               string type_argument_name = tparams[i].MemberName.Name;
+
+                               if (block == null) {
+                                       int idx = parameters.GetParameterIndexByName (type_argument_name);
+                                       if (idx >= 0) {
+                                               var b = block;
+                                               if (b == null)
+                                                       b = new ToplevelBlock (Compiler, Location);
+
+                                               b.Error_AlreadyDeclaredTypeParameter (type_argument_name, parameters[i].Location);
+                                       }
+                               } else {
+                                       INamedBlockVariable variable = null;
+                                       block.GetLocalName (type_argument_name, block, ref variable);
+                                       if (variable != null)
+                                               variable.Block.Error_AlreadyDeclaredTypeParameter (type_argument_name, variable.Location);
                                }
-                       }
 
-                       ar = Parent.PartialContainer.Indexers;
-                       if (ar != null) {
-                               for (int i = 0; i < ar.Count; ++i) {
-                                       PropertyBase pb = (PropertyBase) ar [i];
-                                       if (pb.AreAccessorsDuplicateImplementation (this))
-                                               return false;
+                               if (parent_tparams != null) {
+                                       var tp = parent_tparams.Find (type_argument_name);
+                                       if (tp != null) {
+                                               tparams[i].WarningParentNameConflict (tp);
+                                       }
                                }
+
+                               snames[i] = type_argument_name;
                        }
 
-                       return true;
+                       GenericTypeParameterBuilder[] gen_params = MethodBuilder.DefineGenericParameters (snames);
+                       tparams.Define (gen_params, null, 0, Parent);
                }
 
-               protected override bool CheckBase ()
+               protected virtual void DefineTypeParameters ()
                {
-                       if (!base.CheckBase ())
-                               return false;
+                       var tparams = CurrentTypeParameters;
+
+                       TypeParameterSpec[] base_tparams = null;
+                       TypeParameterSpec[] base_decl_tparams = TypeParameterSpec.EmptyTypes;
+                       TypeSpec[] base_targs = TypeSpec.EmptyTypes;
+                       if (((ModFlags & Modifiers.OVERRIDE) != 0 || IsExplicitImpl)) {
+                               if (base_method != null) {
+                                       base_tparams = base_method.GenericDefinition.TypeParameters;
+                               
+                                       if (base_method.DeclaringType.IsGeneric) {
+                                               base_decl_tparams = base_method.DeclaringType.MemberDefinition.TypeParameters;
+
+                                               var base_type_parent = CurrentType;
+                                               while (base_type_parent.BaseType != base_method.DeclaringType) {
+                                                       base_type_parent = base_type_parent.BaseType;
+                                               }
+
+                                               base_targs = base_type_parent.BaseType.TypeArguments;
+                                       }
+
+                                       if (base_method.IsGeneric) {
+                                               ObsoleteAttribute oa;
+                                               foreach (var base_tp in base_tparams) {
+                                                       oa = base_tp.BaseType.GetAttributeObsolete ();
+                                                       if (oa != null) {
+                                                               AttributeTester.Report_ObsoleteMessage (oa, base_tp.BaseType.GetSignatureForError (), Location, Report);
+                                                       }
+
+                                                       if (base_tp.InterfacesDefined != null) {
+                                                               foreach (var iface in base_tp.InterfacesDefined) {
+                                                                       oa = iface.GetAttributeObsolete ();
+                                                                       if (oa != null) {
+                                                                               AttributeTester.Report_ObsoleteMessage (oa, iface.GetSignatureForError (), Location, Report);
+                                                                       }
+                                                               }
+                                                       }
+                                               }
 
-                       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));
+                                               if (base_decl_tparams.Length != 0) {
+                                                       base_decl_tparams = base_decl_tparams.Concat (base_tparams).ToArray ();
+                                                       base_targs = base_targs.Concat (tparams.Types).ToArray ();
+                                               } else {
+                                                       base_decl_tparams = base_tparams;
+                                                       base_targs = tparams.Types;
+                                               }
+                                       }
+                               } else if (MethodData.implementing != null) {
+                                       base_tparams = MethodData.implementing.GenericDefinition.TypeParameters;
+                                       if (MethodData.implementing.DeclaringType.IsGeneric) {
+                                               base_decl_tparams = MethodData.implementing.DeclaringType.MemberDefinition.TypeParameters;
+                                               foreach (var iface in Parent.CurrentType.Interfaces) {
+                                                       if (iface == MethodData.implementing.DeclaringType) {
+                                                               base_targs = iface.TypeArguments;
+                                                               break;
+                                                       }
+                                               }
+                                       }
+                               }
                        }
 
-                       return true;
+                       for (int i = 0; i < tparams.Count; ++i) {
+                               var tp = tparams[i];
+
+                               if (!tp.ResolveConstraints (this))
+                                       continue;
+
+                               //
+                               // Copy base constraints for override/explicit methods
+                               //
+                               if (base_tparams != null) {
+                                       var base_tparam = base_tparams[i];
+                                       var local_tparam = tp.Type;
+                                       local_tparam.SpecialConstraint = base_tparam.SpecialConstraint;
+
+                                       var inflator = new TypeParameterInflator (this, CurrentType, base_decl_tparams, base_targs);
+                                       base_tparam.InflateConstraints (inflator, local_tparam);
+
+                                       //
+                                       // Check all type argument constraints for possible collision or unification
+                                       // introduced by inflating inherited constraints in this context
+                                       //
+                                       // Conflict example:
+                                       //
+                                       // class A<T> { virtual void Foo<U> () where U : class, T {} }
+                                       // class B : A<int> { override void Foo<U> {} }
+                                       //
+                                       var local_tparam_targs = local_tparam.TypeArguments;
+                                       if (local_tparam_targs != null) {
+                                               for (int ii = 0; ii < local_tparam_targs.Length; ++ii) {
+                                                       var ta = local_tparam_targs [ii];
+                                                       if (!ta.IsClass && !ta.IsStruct)
+                                                               continue;
+
+                                                       TypeSpec[] unique_tparams = null;
+                                                       for (int iii = ii + 1; iii < local_tparam_targs.Length; ++iii) {
+                                                               //
+                                                               // Remove any identical or unified constraint types
+                                                               //
+                                                               var tparam_checked = local_tparam_targs[iii];
+                                                               if (TypeSpecComparer.IsEqual (ta, tparam_checked) || TypeSpec.IsBaseClass (ta, tparam_checked, false)) {
+                                                                       unique_tparams = new TypeSpec[local_tparam_targs.Length - 1];
+                                                                       Array.Copy (local_tparam_targs, 0, unique_tparams, 0, iii);
+                                                                       Array.Copy (local_tparam_targs, iii + 1, unique_tparams, iii, local_tparam_targs.Length - iii - 1);
+                                                               } else if (!TypeSpec.IsBaseClass (tparam_checked, ta, false)) {
+                                                                       Constraints.Error_ConflictingConstraints (this, local_tparam, ta, tparam_checked, Location);
+                                                               }
+                                                       }
+
+                                                       if (unique_tparams != null) {
+                                                               local_tparam_targs = unique_tparams;
+                                                               local_tparam.TypeArguments = local_tparam_targs;
+                                                               continue;
+                                                       }
+
+                                                       Constraints.CheckConflictingInheritedConstraint (local_tparam, ta, this, Location);
+                                               }
+                                       }
+
+                                       continue;
+                               }
+                       }
+
+                       if (base_tparams == null && MethodData != null && MethodData.implementing != null) {
+                               CheckImplementingMethodConstraints (Parent, spec, MethodData.implementing);
+                       }
                }
 
-               public override TypeParameter[] CurrentTypeParameters {
-                       get {
-                               if (GenericMethod != null)
-                                       return GenericMethod.CurrentTypeParameters;
+               public static bool CheckImplementingMethodConstraints (TypeContainer container, MethodSpec method, MethodSpec baseMethod)
+               {
+                       var tparams = method.Constraints;
+                       var base_tparams = baseMethod.Constraints;
+                       for (int i = 0; i < tparams.Length; ++i) {
+                               if (!tparams[i].HasSameConstraintsImplementation (base_tparams[i])) {
+                                       container.Compiler.Report.SymbolRelatedToPreviousError (method);
+                                       container.Compiler.Report.SymbolRelatedToPreviousError (baseMethod);
 
-                               return null;
+                                       // Using container location because the interface can be implemented
+                                       // by base class
+                                       container.Compiler.Report.Error (425, container.Location,
+                                               "The constraints for type parameter `{0}' of method `{1}' must match the constraints for type parameter `{2}' of interface method `{3}'. Consider using an explicit interface implementation instead",
+                                               tparams[i].GetSignatureForError (), method.GetSignatureForError (),
+                                               base_tparams[i].GetSignatureForError (), baseMethod.GetSignatureForError ());
+                                       return false;
+                               }
                        }
+
+                       return true;
                }
 
                //
@@ -787,47 +1151,76 @@ namespace Mono.CSharp {
                //
                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 (member_type.Kind == MemberKind.Void && parameters.IsEmpty && MemberName.Arity == 0 && MemberName.Name == Destructor.MetadataName) {
+                               Report.Warning (465, 1, Location,
+                                       "Introducing `Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?");
+                       }
+
                        if (partialMethodImplementation != null && IsPartialDefinition)
                                MethodBuilder = partialMethodImplementation.MethodBuilder;
 
-                       if (RootContext.StdLib && TypeManager.IsSpecialType (ReturnType)) {
+                       if (Compiler.Settings.StdLib && ReturnType.IsSpecialRuntimeType) {
                                Error1599 (Location, ReturnType, Report);
                                return false;
                        }
 
-                       if (base_method != null && (ModFlags & Modifiers.NEW) == 0) {
-                               if (Parameters.Count == 1 && ParameterTypes [0] == TypeManager.object_type && Name == "Equals")
-                                       Parent.PartialContainer.Mark_HasEquals ();
-                               else if (Parameters.IsEmpty && Name == "GetHashCode")
-                                       Parent.PartialContainer.Mark_HasGetHashCode ();
+                       if (CurrentTypeParameters == null) {
+                               if (base_method != null && !IsExplicitImpl) {
+                                       if (parameters.Count == 1 && ParameterTypes[0].BuiltinType == BuiltinTypeSpec.Type.Object && MemberName.Name == "Equals")
+                                               Parent.PartialContainer.Mark_HasEquals ();
+                                       else if (parameters.IsEmpty && MemberName.Name == "GetHashCode")
+                                               Parent.PartialContainer.Mark_HasGetHashCode ();
+                               }
+                                       
+                       } else {
+                               DefineTypeParameters ();
+                       }
+
+                       if (block != null) {
+                               if (block.IsIterator) {
+                                       //
+                                       // Current method is turned into automatically generated
+                                       // wrapper which creates an instance of iterator
+                                       //
+                                       Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
+                                       ModFlags |= Modifiers.DEBUGGER_HIDDEN;
+                               }
+
+                               if ((ModFlags & Modifiers.ASYNC) != 0) {
+                                       if (ReturnType.Kind != MemberKind.Void &&
+                                               ReturnType != Module.PredefinedTypes.Task.TypeSpec &&
+                                               !ReturnType.IsGenericTask) {
+                                               Report.Error (1983, Location, "The return type of an async method must be void, Task, or Task<T>");
+                                       }
+
+                                       block = (ToplevelBlock) block.ConvertToAsyncTask (this, Parent.PartialContainer, parameters, ReturnType, Location);
+                                       ModFlags |= Modifiers.DEBUGGER_HIDDEN;
+                               }
                        }
 
                        if ((ModFlags & Modifiers.STATIC) == 0)
                                return true;
 
-                       if (Parameters.HasExtensionMethodType) {
-                               if (Parent.PartialContainer.IsStaticClass && !Parent.IsGeneric) {
+                       if (parameters.HasExtensionMethodType) {
+                               if (Parent.PartialContainer.IsStatic && !Parent.IsGenericOrParentIsGeneric) {
                                        if (!Parent.IsTopLevel)
                                                Report.Error (1109, Location, "`{0}': Extension methods cannot be defined in a nested class",
                                                        GetSignatureForError ());
 
-                                       PredefinedAttribute pa = PredefinedAttributes.Get.Extension;
+                                       PredefinedAttribute pa = Module.PredefinedAttributes.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",
+                                                       "`{0}': Extension methods require `System.Runtime.CompilerServices.ExtensionAttribute' type to be available. Are you missing an assembly reference?",
                                                        GetSignatureForError ());
                                        }
 
                                        ModFlags |= Modifiers.METHOD_EXTENSION;
                                        Parent.PartialContainer.ModFlags |= Modifiers.METHOD_EXTENSION;
-                                       CodeGen.Assembly.HasExtensionMethods = true;
+                                       Spec.DeclaringType.SetExtensionMethodContainer ();
+                                       Parent.Module.HasExtensionMethod = true;
                                } else {
                                        Report.Error (1106, Location, "`{0}': Extension methods must be defined in a non-generic static class",
                                                GetSignatureForError ());
@@ -837,22 +1230,22 @@ namespace Mono.CSharp {
                        //
                        // This is used to track the Entry Point,
                        //
-                       if (RootContext.NeedsEntryPoint &&
-                               Name == "Main" &&
-                               (RootContext.MainClass == null ||
-                               RootContext.MainClass == Parent.TypeBuilder.FullName)){
+                       var settings = Compiler.Settings;
+                       if (settings.NeedsEntryPoint && MemberName.Name == "Main" && (settings.MainClass == null || settings.MainClass == Parent.TypeBuilder.FullName)) {
                                if (IsEntryPoint ()) {
-
-                                       if (RootContext.EntryPoint == null) {
-                                               if (Parent.IsGeneric || MemberName.IsGeneric) {
+                                       if (Parent.DeclaringAssembly.EntryPoint == null) {
+                                               if (Parent.IsGenericOrParentIsGeneric || MemberName.IsGeneric) {
                                                        Report.Warning (402, 4, Location, "`{0}': an entry point cannot be generic or in a generic type",
                                                                GetSignatureForError ());
+                                               } else if ((ModFlags & Modifiers.ASYNC) != 0) {
+                                                       Report.Error (4009, Location, "`{0}': an entry point cannot be async method",
+                                                               GetSignatureForError ());
                                                } else {
                                                        SetIsUsed ();
-                                                       RootContext.EntryPoint = this;
+                                                       Parent.DeclaringAssembly.EntryPoint = this;
                                                }
                                        } else {
-                                               Error_DuplicateEntryPoint (RootContext.EntryPoint);
+                                               Error_DuplicateEntryPoint (Parent.DeclaringAssembly.EntryPoint);
                                                Error_DuplicateEntryPoint (this);
                                        }
                                } else {
@@ -870,24 +1263,34 @@ namespace Mono.CSharp {
                public override void Emit ()
                {
                        try {
-                               Report.Debug (64, "METHOD EMIT", this, MethodBuilder, Location, Block, MethodData);
                                if (IsPartialDefinition) {
                                        //
                                        // Use partial method implementation builder for partial method declaration attributes
                                        //
                                        if (partialMethodImplementation != null) {
                                                MethodBuilder = partialMethodImplementation.MethodBuilder;
-                                               return;
                                        }
-                               } else if ((ModFlags & Modifiers.PARTIAL) != 0 && (caching_flags & Flags.PartialDefinitionExists) == 0) {
+
+                                       return;
+                               }
+                               
+                               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 ());
                                }
 
+                               if (CurrentTypeParameters != null) {
+                                       for (int i = 0; i < CurrentTypeParameters.Count; ++i) {
+                                               var tp = CurrentTypeParameters [i];
+                                               tp.CheckGenericConstraints (false);
+                                               tp.Emit ();
+                                       }
+                               }
+
                                base.Emit ();
                                
                                if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
-                                       PredefinedAttributes.Get.Extension.EmitAttribute (MethodBuilder);
+                                       Module.PredefinedAttributes.Extension.EmitAttribute (MethodBuilder);
                        } catch {
                                Console.WriteLine ("Internal compiler error at {0}: exception caught while emitting {1}",
                                                   Location, MethodBuilder);
@@ -897,39 +1300,25 @@ namespace Mono.CSharp {
 
                public override bool EnableOverloadChecks (MemberCore overload)
                {
-                       // TODO: It can be deleted when members will be defined in correct order
-                       if (overload is Operator)
-                               return overload.EnableOverloadChecks (this);
-
                        if (overload is Indexer)
                                return false;
 
                        return base.EnableOverloadChecks (overload);
                }
 
-               public static void Error1599 (Location loc, Type t, Report Report)
+               public static void Error1599 (Location loc, TypeSpec t, Report Report)
                {
                        Report.Error (1599, loc, "Method or delegate cannot return type `{0}'", TypeManager.CSharpName (t));
                }
 
-               protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
+               protected override bool ResolveMemberType ()
                {
-                       MethodInfo mi = (MethodInfo) Parent.PartialContainer.BaseCache.FindMemberToOverride (
-                               Parent.TypeBuilder, Name, Parameters, GenericMethod, false);
-
-                       if (mi == null)
-                               return null;
-
-                       if (mi.IsSpecialName)
-                               return null;
-
-                       base_ret_type = TypeManager.TypeToCoreType (mi.ReturnType);
-                       return mi;
-               }
+                       if (CurrentTypeParameters != null) {
+                               MethodBuilder = Parent.TypeBuilder.DefineMethod (GetFullName (MemberName), flags);
+                               CreateTypeParameters ();
+                       }
 
-               public MethodInfo MakeGenericMethod (Type[] targs)
-               {
-                       return MethodBuilder.MakeGenericMethod (targs);
+                       return base.ResolveMemberType ();
                }
 
                public void SetPartialDefinition (Method methodDefinition)
@@ -938,9 +1327,9 @@ namespace Mono.CSharp {
                        methodDefinition.partialMethodImplementation = this;
 
                        // Ensure we are always using method declaration parameters
-                       for (int i = 0; i < methodDefinition.Parameters.Count; ++i ) {
-                               Parameters [i].Name = methodDefinition.Parameters [i].Name;
-                               Parameters [i].DefaultValue = methodDefinition.Parameters [i].DefaultValue;
+                       for (int i = 0; i < methodDefinition.parameters.Count; ++i ) {
+                               parameters [i].Name = methodDefinition.parameters [i].Name;
+                               parameters [i].DefaultValue = methodDefinition.parameters [i].DefaultValue;
                        }
 
                        if (methodDefinition.attributes == null)
@@ -952,26 +1341,12 @@ namespace Mono.CSharp {
                                attributes.Attrs.AddRange (methodDefinition.attributes.Attrs);
                        }
                }
-
-               protected override bool VerifyClsCompliance ()
-               {
-                       if (!base.VerifyClsCompliance ())
-                               return false;
-
-                       if (!Parameters.IsEmpty) {
-                               var al = Parent.PartialContainer.MemberCache.Members [Name];
-                               if (al.Count > 1)
-                                       MemberCache.VerifyClsParameterConflict (al, this, MethodBuilder, Report);
-                       }
-
-                       return true;
-               }
        }
 
        public abstract class ConstructorInitializer : ExpressionStatement
        {
                Arguments argument_list;
-               MethodGroupExpr base_constructor_group;
+               MethodSpec base_ctor;
 
                public ConstructorInitializer (Arguments argument_list, Location loc)
                {
@@ -985,6 +1360,11 @@ namespace Mono.CSharp {
                        }
                }
 
+               public override bool ContainsEmitWithAwait ()
+               {
+                       throw new NotSupportedException ();
+               }
+
                public override Expression CreateExpressionTree (ResolveContext ec)
                {
                        throw new NotSupportedException ("ET");
@@ -994,84 +1374,68 @@ namespace Mono.CSharp {
                {
                        eclass = ExprClass.Value;
 
-                       // TODO: ec.GetSignatureForError ()
-                       ConstructorBuilder caller_builder = ((Constructor) ec.MemberContext).ConstructorBuilder;
-
-                       if (argument_list != null) {
-                               bool dynamic;
+                       // FIXME: Hack
+                       var caller_builder = (Constructor) ec.MemberContext;
 
-                               //
-                               // Spec mandates that constructor initializer will not have `this' access
-                               //
-                               using (ec.Set (ResolveContext.Options.BaseInitializer)) {
+                       //
+                       // Spec mandates that constructor initializer will not have `this' access
+                       //
+                       using (ec.Set (ResolveContext.Options.BaseInitializer)) {
+                               if (argument_list != null) {
+                                       bool dynamic;
                                        argument_list.Resolve (ec, out dynamic);
-                               }
 
-                               if (dynamic) {
-                                       ec.Report.Error (1975, loc,
-                                               "The constructor call cannot be dynamically dispatched within constructor initializer");
+                                       if (dynamic) {
+                                               ec.Report.Error (1975, loc,
+                                                       "The constructor call cannot be dynamically dispatched within constructor initializer");
 
-                                       return null;
+                                               return null;
+                                       }
                                }
-                       }
 
-                       type = ec.CurrentType;
-                       if (this is ConstructorBaseInitializer) {
-                               if (ec.CurrentType.BaseType == null)
-                                       return this;
+                               type = ec.CurrentType;
+                               if (this is ConstructorBaseInitializer) {
+                                       if (ec.CurrentType.BaseType == null)
+                                               return this;
 
-                               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 this;
+                                       type = ec.CurrentType.BaseType;
+                                       if (ec.CurrentType.IsStruct) {
+                                               ec.Report.Error (522, loc,
+                                                       "`{0}': Struct constructors cannot call base constructors", caller_builder.GetSignatureForError ());
+                                               return this;
+                                       }
+                               } else {
+                                       //
+                                       // It is legal to have "this" initializers that take no arguments
+                                       // in structs, they are just no-ops.
+                                       //
+                                       // struct D { public D (int a) : this () {}
+                                       //
+                                       if (ec.CurrentType.IsStruct && argument_list == null)
+                                               return this;
                                }
-                       } else {
-                               //
-                               // It is legal to have "this" initializers that take no arguments
-                               // in structs, they are just no-ops.
-                               //
-                               // struct D { public D (int a) : this () {}
-                               //
-                               if (TypeManager.IsStruct (ec.CurrentType) && argument_list == null)
-                                       return this;                    
-                       }
 
-                       base_constructor_group = MemberLookupFinal (
-                               ec, null, type, ConstructorBuilder.ConstructorName, MemberTypes.Constructor,
-                               BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
-                               loc) as MethodGroupExpr;
-                       
-                       if (base_constructor_group == null)
-                               return this;
-                       
-                       base_constructor_group = base_constructor_group.OverloadResolve (
-                               ec, ref argument_list, false, loc);
-                       
-                       if (base_constructor_group == null)
-                               return this;
-
-                       if (!ec.IsStatic)
-                               base_constructor_group.InstanceExpression = ec.GetThis (loc);
-                       
-                       var base_ctor = base_constructor_group.BestCandidate;
-
-                       if (base_ctor.MetaInfo == caller_builder){
-                               ec.Report.Error (516, loc, "Constructor `{0}' cannot call itself", TypeManager.CSharpSignature (caller_builder));
+                               base_ctor = ConstructorLookup (ec, type, ref argument_list, loc);
                        }
-                                               
+       
+                       // TODO MemberCache: Does it work for inflated types ?
+                       if (base_ctor == caller_builder.Spec){
+                               ec.Report.Error (516, loc, "Constructor `{0}' cannot call itself",
+                                       caller_builder.GetSignatureForError ());
+                       }
+
                        return this;
                }
 
                public override void Emit (EmitContext ec)
                {
                        // It can be null for static initializers
-                       if (base_constructor_group == null)
+                       if (base_ctor == null)
                                return;
                        
-                       ec.Mark (loc);
-
-                       base_constructor_group.EmitCall (ec, argument_list);
+                       var call = new CallEmitter ();
+                       call.InstanceExpression = new CompilerGeneratedThis (type, loc); 
+                       call.EmitPredefined (ec, base_ctor, argument_list);
                }
 
                public override void EmitStatement (EmitContext ec)
@@ -1101,11 +1465,13 @@ namespace Mono.CSharp {
                }
        }
        
-       public class Constructor : MethodCore, IMethodData {
+       public class Constructor : MethodCore, IMethodData
+       {
                public ConstructorBuilder ConstructorBuilder;
                public ConstructorInitializer Initializer;
-               Dictionary<SecurityAction, PermissionSet> declarative_security;
+               SecurityType declarative_security;
                bool has_compliant_args;
+               SourceMethodBuilder debug_builder;
 
                // <summary>
                //   Modifiers allowed for a constructor.
@@ -1121,24 +1487,30 @@ namespace Mono.CSharp {
 
                static readonly string[] attribute_targets = new string [] { "method" };
 
-               //
-               // The spec claims that static is not permitted, but
-               // my very own code has static constructors.
-               //
-               public Constructor (DeclSpace parent, string name, Modifiers mod, Attributes attrs, ParametersCompiled args,
-                                   ConstructorInitializer init, Location loc)
-                       : base (parent, null, null, mod, AllowedModifiers,
-                               new MemberName (name, loc), attrs, args)
+               public static readonly string ConstructorName = ".ctor";
+               public static readonly string TypeConstructorName = ".cctor";
+
+               public Constructor (TypeDefinition parent, string name, Modifiers mod, Attributes attrs, ParametersCompiled args, Location loc)
+                       : base (parent, null, mod, AllowedModifiers, new MemberName (name, loc), attrs, args)
                {
-                       Initializer = init;
                }
 
                public bool HasCompliantArgs {
-                       get { return has_compliant_args; }
+                       get {
+                               return has_compliant_args;
+                       }
                }
 
                public override AttributeTargets AttributeTargets {
-                       get { return AttributeTargets.Constructor; }
+                       get {
+                               return AttributeTargets.Constructor;
+                       }
+               }
+
+               bool IMethodData.IsAccessor {
+                   get {
+                       return false;
+                   }
                }
 
                //
@@ -1147,57 +1519,59 @@ namespace Mono.CSharp {
                public bool IsDefault ()
                {
                        if ((ModFlags & Modifiers.STATIC) != 0)
-                               return Parameters.IsEmpty;
-                       
-                       return Parameters.IsEmpty &&
+                               return parameters.IsEmpty;
+
+                       return parameters.IsEmpty &&
                                        (Initializer is ConstructorBaseInitializer) &&
                                        (Initializer.Arguments == null);
                }
 
-               public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
+               public override void Accept (StructuralVisitor visitor)
+               {
+                       visitor.Visit (this);
+               }
+
+               public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
                {
                        if (a.IsValidSecurityAttribute ()) {
-                               if (declarative_security == null) {
-                                       declarative_security = new Dictionary<SecurityAction, PermissionSet> ();
-                               }
-                               a.ExtractSecurityPermissionSet (declarative_security);
+                               a.ExtractSecurityPermissionSet (ctor, ref declarative_security);
                                return;
                        }
 
-                       if (a.IsInternalMethodImplAttribute) {
-                               is_external_implementation = true;
+                       if (a.Type == pa.MethodImpl) {
+                               is_external_implementation = a.IsInternalCall ();
                        }
 
-                       ConstructorBuilder.SetCustomAttribute (cb);
+                       ConstructorBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
                }
 
                protected override bool CheckBase ()
                {
                        if ((ModFlags & Modifiers.STATIC) != 0) {
-                               if (!Parameters.IsEmpty) {
+                               if (!parameters.IsEmpty) {
                                        Report.Error (132, Location, "`{0}': The static constructor must be parameterless",
                                                GetSignatureForError ());
                                        return false;
                                }
 
+                               if ((caching_flags & Flags.MethodOverloadsExist) != 0)
+                                       Parent.MemberCache.CheckExistingMembersOverloads (this, parameters);
+
                                // the rest can be ignored
                                return true;
                        }
 
                        // Check whether arguments were correct.
-                       if (!DefineParameters (Parameters))
+                       if (!DefineParameters (parameters))
                                return false;
 
                        if ((caching_flags & Flags.MethodOverloadsExist) != 0)
-                               Parent.MemberCache.CheckExistingMembersOverloads (this, ConstructorInfo.ConstructorName,
-                                       Parameters, Report);
+                               Parent.MemberCache.CheckExistingMembersOverloads (this, parameters);
 
-                       if (Parent.PartialContainer.Kind == MemberKind.Struct) {
-                               if (Parameters.Count == 0) {
-                                       Report.Error (568, Location, 
-                                               "Structs cannot contain explicit parameterless constructors");
-                                       return false;
-                               }
+                       if (Parent.PartialContainer.Kind == MemberKind.Struct && parameters.IsEmpty) {
+                               Report.Error (568, Location, 
+                                       "Structs cannot contain explicit parameterless constructors");
+                               return false;
                        }
 
                        CheckProtectedModifier ();
@@ -1213,27 +1587,6 @@ namespace Mono.CSharp {
                        if (ConstructorBuilder != null)
                                return true;
 
-                       MethodAttributes ca = (MethodAttributes.RTSpecialName |
-                                              MethodAttributes.SpecialName);
-                       
-                       if ((ModFlags & Modifiers.STATIC) != 0) {
-                               ca |= MethodAttributes.Static | MethodAttributes.Private;
-                       } else {
-                               ca |= MethodAttributes.HideBySig;
-
-                               if ((ModFlags & Modifiers.PUBLIC) != 0)
-                                       ca |= MethodAttributes.Public;
-                               else if ((ModFlags & Modifiers.PROTECTED) != 0){
-                                       if ((ModFlags & Modifiers.INTERNAL) != 0)
-                                               ca |= MethodAttributes.FamORAssem;
-                                       else 
-                                               ca |= MethodAttributes.Family;
-                               } else if ((ModFlags & Modifiers.INTERNAL) != 0)
-                                       ca |= MethodAttributes.Assembly;
-                               else
-                                       ca |= MethodAttributes.Private;
-                       }
-
                        if (!CheckAbstractAndExtern (block != null))
                                return false;
                        
@@ -1241,27 +1594,20 @@ namespace Mono.CSharp {
                        if (!CheckBase ())
                                return false;
 
+                       var ca = ModifiersExtensions.MethodAttr (ModFlags) | MethodAttributes.RTSpecialName | MethodAttributes.SpecialName;
+
                        ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
                                ca, CallingConventions,
-                               Parameters.GetEmitTypes ());
-
-                       spec = new MethodSpec (MemberKind.Constructor, this, ConstructorBuilder, Parameters, ModFlags);
+                               parameters.GetMetaInfo ());
 
-                       if (Parent.PartialContainer.IsComImport) {
-                               if (!IsDefault ()) {
-                                       Report.Error (669, Location, "`{0}': A class with the ComImport attribute cannot have a user-defined constructor",
-                                               Parent.GetSignatureForError ());
-                               }
-                               ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall);
-                       }
+                       spec = new MethodSpec (MemberKind.Constructor, Parent.Definition, this, Compiler.BuiltinTypes.Void, ConstructorBuilder, parameters, ModFlags);
                        
-                       Parent.MemberCache.AddMember (ConstructorBuilder, spec);
-                       TypeManager.AddMethod (ConstructorBuilder, this);
+                       Parent.MemberCache.AddMember (spec);
                        
                        // It's here only to report an error
                        if (block != null && block.IsIterator) {
-                               member_type = TypeManager.void_type;
-                               Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags, Compiler);
+                               member_type = Compiler.BuiltinTypes.Void;
+                               Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
                        }
 
                        return true;
@@ -1272,83 +1618,104 @@ namespace Mono.CSharp {
                //
                public override void Emit ()
                {
+                       if (Parent.PartialContainer.IsComImport) {
+                               if (!IsDefault ()) {
+                                       Report.Error (669, Location, "`{0}': A class with the ComImport attribute cannot have a user-defined constructor",
+                                               Parent.GetSignatureForError ());
+                               }
+
+                               // Set as internal implementation and reset block data
+                               // to ensure no IL is generated
+                               ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall);
+                               block = null;
+                       }
+
                        if ((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0)
-                               PredefinedAttributes.Get.DebuggerHidden.EmitAttribute (ConstructorBuilder);
+                               Module.PredefinedAttributes.DebuggerHidden.EmitAttribute (ConstructorBuilder);
 
                        if (OptAttributes != null)
                                OptAttributes.Emit ();
 
                        base.Emit ();
+                       parameters.ApplyAttributes (this, ConstructorBuilder);
+
+
+                       BlockContext bc = new BlockContext (this, block, Compiler.BuiltinTypes.Void);
+                       bc.Set (ResolveContext.Options.ConstructorScope);
 
                        //
                        // If we use a "this (...)" constructor initializer, then
                        // do not emit field initializers, they are initialized in the other constructor
                        //
-                       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)
+                       if (!(Initializer is ConstructorThisInitializer))
                                Parent.PartialContainer.ResolveFieldInitializers (bc);
 
                        if (block != null) {
-                               // If this is a non-static `struct' constructor and doesn't have any
-                               // initializer, it must initialize all of the struct's fields.
-                               if ((Parent.PartialContainer.Kind == MemberKind.Struct) &&
-                                       ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
-                                       block.AddThisVariable (Parent, Location);
-
-                               if (block != null && (ModFlags & Modifiers.STATIC) == 0){
-                                       if (Parent.PartialContainer.Kind == MemberKind.Class && Initializer == null)
-                                               Initializer = new GeneratedBaseInitializer (Location);
+                               if (!IsStatic) {
+                                       if (Initializer == null) {
+                                               if (Parent.PartialContainer.Kind == MemberKind.Struct) {
+                                                       //
+                                                       // If this is a non-static `struct' constructor and doesn't have any
+                                                       // initializer, it must initialize all of the struct's fields.
+                                                       //
+                                                       block.AddThisVariable (bc);
+                                               } else if (Parent.PartialContainer.Kind == MemberKind.Class) {
+                                                       Initializer = new GeneratedBaseInitializer (Location);
+                                               }
+                                       }
 
                                        if (Initializer != null) {
+                                               //
+                                               // mdb format does not support reqions. Try to workaround this by emitting the
+                                               // sequence point at initializer. Any breakpoint at constructor header should
+                                               // be adjusted to this sequence point as it's the next one which follows.
+                                               //
                                                block.AddScopeStatement (new StatementExpression (Initializer));
                                        }
-                               }
-                       }
-
-                       Parameters.ApplyAttributes (ConstructorBuilder);
-
-                       SourceMethod source = SourceMethod.Create (Parent, ConstructorBuilder, block);
+                               }
 
-                       if (block != null) {
-                               if (block.Resolve (null, bc, Parameters, this)) {
-                                       EmitContext ec = new EmitContext (this, ConstructorBuilder.GetILGenerator (), bc.ReturnType);
+                               if (block.Resolve (null, bc, this)) {
+                                       debug_builder = Parent.CreateMethodSymbolEntry ();
+                                       EmitContext ec = new EmitContext (this, ConstructorBuilder.GetILGenerator (), bc.ReturnType, debug_builder);
                                        ec.With (EmitContext.Options.ConstructorScope, true);
 
-                                       if (!ec.HasReturnLabel && bc.HasReturnLabel) {
-                                               ec.ReturnLabel = bc.ReturnLabel;
-                                               ec.HasReturnLabel = true;
-                                       }
-
                                        block.Emit (ec);
                                }
                        }
 
-                       if (source != null)
-                               source.CloseMethod ();
-
                        if (declarative_security != null) {
                                foreach (var de in declarative_security) {
+#if STATIC
+                                       ConstructorBuilder.__AddDeclarativeSecurity (de);
+#else
                                        ConstructorBuilder.AddDeclarativeSecurity (de.Key, de.Value);
+#endif
                                }
                        }
 
                        block = null;
                }
 
-               // Is never override
-               protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
+               protected override MemberSpec FindBaseMember (out MemberSpec bestCandidate, ref bool overrides)
                {
+                       // Is never override
+                       bestCandidate = null;
                        return null;
                }
 
+               public override string GetCallerMemberName ()
+               {
+                       return IsStatic ? TypeConstructorName : ConstructorName;
+               }
+
+               public override string GetSignatureForDocumentation ()
+               {
+                       return Parent.GetSignatureForDocumentation () + ".#ctor" + parameters.GetSignatureForDocumentation ();
+               }
+
                public override string GetSignatureForError()
                {
-                       return base.GetSignatureForError () + Parameters.GetSignatureForError ();
+                       return base.GetSignatureForError () + parameters.GetSignatureForError ();
                }
 
                public override string[] ValidAttributeTargets {
@@ -1362,24 +1729,34 @@ namespace Mono.CSharp {
                        if (!base.VerifyClsCompliance () || !IsExposedFromAssembly ()) {
                                return false;
                        }
-                       
-                       if (!Parameters.IsEmpty) {
-                               var al = Parent.MemberCache.Members [ConstructorInfo.ConstructorName];
-                               if (al.Count > 2)
-                                       MemberCache.VerifyClsParameterConflict (al, this, ConstructorBuilder, Report);
-                               if (TypeManager.IsSubclassOf (Parent.TypeBuilder, TypeManager.attribute_type)) {
-                                       foreach (Type param in Parameters.Types) {
-                                               if (param.IsArray) {
-                                                       return true;
-                                               }
+
+                       if (!parameters.IsEmpty && Parent.Definition.IsAttribute) {
+                               foreach (TypeSpec param in parameters.Types) {
+                                       if (param.IsArray) {
+                                               return true;
                                        }
                                }
                        }
+
                        has_compliant_args = true;
                        return true;
                }
 
+               public override void WriteDebugSymbol (MonoSymbolFile file)
+               {
+                       if (debug_builder == null)
+                               return;
+
+                       var token = ConstructorBuilder.GetToken ();
+                       int t = token.Token;
+#if STATIC
+                       if (token.IsPseudoToken)
+                               t = Module.Builder.ResolvePseudoToken (t);
+#endif
+
+                       debug_builder.DefineMethod (file, t);
+               }
+
                #region IMethodData Members
 
                public MemberName MethodName {
@@ -1388,71 +1765,54 @@ namespace Mono.CSharp {
                        }
                }
 
-               public Type ReturnType {
+               public TypeSpec ReturnType {
                        get {
                                return MemberType;
                        }
                }
 
-               public EmitContext CreateEmitContext (ILGenerator ig)
+               EmitContext IMethodData.CreateEmitContext (ILGenerator ig, SourceMethodBuilder sourceMethod)
                {
                        throw new NotImplementedException ();
                }
 
-               public bool IsExcluded()
-               {
-                       return false;
-               }
-
-               GenericMethod IMethodData.GenericMethod {
-                       get {
-                               return null;
-                       }
-               }
-
-               void IMethodData.EmitExtraSymbolInfo (SourceMethod source)
-               { }
-
                #endregion
        }
 
        /// <summary>
        /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
        /// </summary>
-       public interface IMethodData
+       public interface IMethodData : IMemberContext
        {
                CallingConventions CallingConventions { get; }
                Location Location { get; }
                MemberName MethodName { get; }
-               Type ReturnType { get; }
-               GenericMethod GenericMethod { get; }
+               TypeSpec ReturnType { get; }
                ParametersCompiled ParameterInfo { get; }
+               MethodSpec Spec { get; }
+               bool IsAccessor { get; }
 
                Attributes OptAttributes { get; }
                ToplevelBlock Block { get; set; }
 
-               EmitContext CreateEmitContext (ILGenerator ig);
-               ObsoleteAttribute GetObsoleteAttribute ();
-               string GetSignatureForError ();
-               bool IsExcluded ();
-               bool IsClsComplianceRequired ();
-               void SetIsUsed ();
-               void EmitExtraSymbolInfo (SourceMethod source);
+               EmitContext CreateEmitContext (ILGenerator ig, SourceMethodBuilder sourceMethod);
        }
 
        //
        // Encapsulates most of the Method's state
        //
-       public class MethodData {
+       public class MethodData
+       {
+#if !STATIC
                static FieldInfo methodbuilder_attrs_field;
-               public readonly IMethodData method;
+#endif
 
-               public readonly GenericMethod GenericMethod;
+               public readonly IMethodData method;
 
                //
                // Are we implementing an interface ?
                //
-               public MethodInfo implementing;
+               public MethodSpec implementing;
 
                //
                // Protected data.
@@ -1460,17 +1820,18 @@ namespace Mono.CSharp {
                protected InterfaceMemberBase member;
                protected Modifiers modifiers;
                protected MethodAttributes flags;
-               protected Type declaring_type;
-               protected MethodInfo parent_method;
+               protected TypeSpec declaring_type;
+               protected MethodSpec parent_method;
+               SourceMethodBuilder debug_builder;
 
-               MethodBuilder builder = null;
+               MethodBuilder builder;
                public MethodBuilder MethodBuilder {
                        get {
                                return builder;
                        }
                }
 
-               public Type DeclaringType {
+               public TypeSpec DeclaringType {
                        get {
                                return declaring_type;
                        }
@@ -1489,71 +1850,73 @@ namespace Mono.CSharp {
                public MethodData (InterfaceMemberBase member,
                                   Modifiers modifiers, MethodAttributes flags, 
                                   IMethodData method, MethodBuilder builder,
-                                  GenericMethod generic, MethodInfo parent_method)
+                                  MethodSpec parent_method)
                        : this (member, modifiers, flags, method)
                {
                        this.builder = builder;
-                       this.GenericMethod = generic;
                        this.parent_method = parent_method;
                }
 
-               public bool Define (DeclSpace parent, string method_full_name, Report Report)
+               public bool Define (TypeDefinition container, string method_full_name)
                {
-                       string name = method.MethodName.Basename;
-
-                       TypeContainer container = parent.PartialContainer;
-
                        PendingImplementation pending = container.PendingImplementations;
-                       if (pending != null){
-                               implementing = pending.IsInterfaceMethod (name, member.InterfaceType, this);
+                       MethodSpec ambig_iface_method;
+                       bool optional = false;
+
+                       if (pending != null) {
+                               implementing = pending.IsInterfaceMethod (method.MethodName, member.InterfaceType, this, out ambig_iface_method, ref optional);
 
-                               if (member.InterfaceType != null){
-                                       if (implementing == null){
+                               if (member.InterfaceType != null) {
+                                       if (implementing == null) {
                                                if (member is PropertyBase) {
-                                                       Report.Error (550, method.Location, "`{0}' is an accessor not found in interface member `{1}{2}'",
-                                                                     method.GetSignatureForError (), TypeManager.CSharpName (member.InterfaceType),
-                                                                     member.GetSignatureForError ().Substring (member.GetSignatureForError ().LastIndexOf ('.')));
+                                                       container.Compiler.Report.Error (550, method.Location,
+                                                               "`{0}' is an accessor not found in interface member `{1}{2}'",
+                                                                         method.GetSignatureForError (), TypeManager.CSharpName (member.InterfaceType),
+                                                                         member.GetSignatureForError ().Substring (member.GetSignatureForError ().LastIndexOf ('.')));
 
                                                } else {
-                                                       Report.Error (539, method.Location,
-                                                                     "`{0}.{1}' in explicit interface declaration is not a member of interface",
-                                                                     TypeManager.CSharpName (member.InterfaceType), member.ShortName);
+                                                       container.Compiler.Report.Error (539, method.Location,
+                                                                         "`{0}.{1}' in explicit interface declaration is not a member of interface",
+                                                                         TypeManager.CSharpName (member.InterfaceType), member.ShortName);
                                                }
                                                return false;
                                        }
-                                       if (implementing.IsSpecialName && !(method is AbstractPropertyEventMethod)) {
-                                               Report.SymbolRelatedToPreviousError (implementing);
-                                               Report.Error (683, method.Location, "`{0}' explicit method implementation cannot implement `{1}' because it is an accessor",
+                                       if (implementing.IsAccessor && !method.IsAccessor) {
+                                               container.Compiler.Report.SymbolRelatedToPreviousError (implementing);
+                                               container.Compiler.Report.Error (683, method.Location,
+                                                       "`{0}' explicit method implementation cannot implement `{1}' because it is an accessor",
                                                        member.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
                                                return false;
                                        }
                                } else {
                                        if (implementing != null) {
-                                               AbstractPropertyEventMethod prop_method = method as AbstractPropertyEventMethod;
-                                               if (prop_method == null) {
-                                                       if (TypeManager.IsSpecialMethod (implementing)) {
-                                                               Report.SymbolRelatedToPreviousError (implementing);
-                                                               Report.Error (470, method.Location, "Method `{0}' cannot implement interface accessor `{1}.{2}'",
-                                                                       method.GetSignatureForError (), TypeManager.CSharpSignature (implementing),
-                                                                       implementing.Name.StartsWith ("get_") ? "get" : "set");
+                                               if (!method.IsAccessor) {
+                                                       if (implementing.IsAccessor) {
+                                                               container.Compiler.Report.SymbolRelatedToPreviousError (implementing);
+                                                               container.Compiler.Report.Error (470, method.Location,
+                                                                       "Method `{0}' cannot implement interface accessor `{1}'",
+                                                                       method.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
                                                        }
                                                } else if (implementing.DeclaringType.IsInterface) {
-                                                       if (!implementing.IsSpecialName) {
-                                                               Report.SymbolRelatedToPreviousError (implementing);
-                                                               Report.Error (686, method.Location, "Accessor `{0}' cannot implement interface member `{1}' for type `{2}'. Use an explicit interface implementation",
+                                                       if (!implementing.IsAccessor) {
+                                                               container.Compiler.Report.SymbolRelatedToPreviousError (implementing);
+                                                               container.Compiler.Report.Error (686, method.Location,
+                                                                       "Accessor `{0}' cannot implement interface member `{1}' for type `{2}'. Use an explicit interface implementation",
                                                                        method.GetSignatureForError (), TypeManager.CSharpSignature (implementing), container.GetSignatureForError ());
-                                                               return false;
-                                                       }
-                                                       PropertyBase.PropertyMethod pm = prop_method as PropertyBase.PropertyMethod;
-                                                       if (pm != null && pm.HasCustomAccessModifier && (pm.ModFlags & Modifiers.PUBLIC) == 0) {
-                                                               Report.SymbolRelatedToPreviousError (implementing);
-                                                               Report.Error (277, method.Location, "Accessor `{0}' must be declared public to implement interface member `{1}'",
-                                                                       method.GetSignatureForError (), TypeManager.CSharpSignature (implementing, true));
-                                                               return false;
+                                                       } else {
+                                                               PropertyBase.PropertyMethod pm = method as PropertyBase.PropertyMethod;
+                                                               if (pm != null && pm.HasCustomAccessModifier && (pm.ModFlags & Modifiers.PUBLIC) == 0) {
+                                                                       container.Compiler.Report.SymbolRelatedToPreviousError (implementing);
+                                                                       container.Compiler.Report.Error (277, method.Location,
+                                                                               "Accessor `{0}' must be declared public to implement interface member `{1}'",
+                                                                               method.GetSignatureForError (), implementing.GetSignatureForError ());
+                                                               }
                                                        }
                                                }
                                        }
                                }
+                       } else {
+                               ambig_iface_method = null;
                        }
 
                        //
@@ -1561,35 +1924,44 @@ namespace Mono.CSharp {
                        // explicit implementations, make sure we are private.
                        //
                        if (implementing != null){
-                               //
-                               // Setting null inside this block will trigger a more
-                               // verbose error reporting for missing interface implementations
-                               //
-                               // The "candidate" function has been flagged already
-                               // but it wont get cleared
-                               //
-                               if (member.IsExplicitImpl){
-                                       if (method.ParameterInfo.HasParams && !TypeManager.GetParameterData (implementing).HasParams) {
-                                               Report.SymbolRelatedToPreviousError (implementing);
-                                               Report.Error (466, method.Location, "`{0}': the explicit interface implementation cannot introduce the params modifier",
+                               if (member.IsExplicitImpl) {
+                                       if (method.ParameterInfo.HasParams && !implementing.Parameters.HasParams) {
+                                               container.Compiler.Report.SymbolRelatedToPreviousError (implementing);
+                                               container.Compiler.Report.Error (466, method.Location,
+                                                       "`{0}': the explicit interface implementation cannot introduce the params modifier",
+                                                       method.GetSignatureForError ());
+                                       }
+
+                                       if (ambig_iface_method != null) {
+                                               container.Compiler.Report.SymbolRelatedToPreviousError (ambig_iface_method);
+                                               container.Compiler.Report.SymbolRelatedToPreviousError (implementing);
+                                               container.Compiler.Report.Warning (473, 2, method.Location,
+                                                       "Explicit interface implementation `{0}' matches more than one interface member. Consider using a non-explicit implementation instead",
                                                        method.GetSignatureForError ());
-                                               return false;
                                        }
                                } else {
+                                       //
+                                       // Setting implementin to null inside this block will trigger a more
+                                       // verbose error reporting for missing interface implementations
+                                       //
                                        if (implementing.DeclaringType.IsInterface) {
                                                //
                                                // If this is an interface method implementation,
                                                // check for public accessibility
                                                //
-                                               if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public)
-                                               {
+                                               if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public) {
+                                                       implementing = null;
+                                               } else if (optional && (container.Interfaces == null || Array.IndexOf (container.Interfaces, implementing.DeclaringType) < 0)) {
+                                                       //
+                                                       // We are not implementing interface when base class already implemented it
+                                                       //
                                                        implementing = null;
                                                }
-                                       } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
+                                       } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private) {
                                                // We may never be private.
                                                implementing = null;
 
-                                       } else if ((modifiers & Modifiers.OVERRIDE) == 0){
+                                       } else if ((modifiers & Modifiers.OVERRIDE) == 0) {
                                                //
                                                // We may be protected if we're overriding something.
                                                //
@@ -1613,17 +1985,27 @@ namespace Mono.CSharp {
                                // When implementing interface methods, set NewSlot
                                // unless, we are overwriting a method.
                                //
-                               if (implementing.DeclaringType.IsInterface){
-                                       if ((modifiers & Modifiers.OVERRIDE) == 0)
-                                               flags |= MethodAttributes.NewSlot;
+                               if ((modifiers & Modifiers.OVERRIDE) == 0 && implementing.DeclaringType.IsInterface) {
+                                       flags |= MethodAttributes.NewSlot;
                                }
-                               flags |=
-                                       MethodAttributes.Virtual |
-                                       MethodAttributes.HideBySig;
+
+                               flags |= MethodAttributes.Virtual | MethodAttributes.HideBySig;
 
                                // Set Final unless we're virtual, abstract or already overriding a method.
                                if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
                                        flags |= MethodAttributes.Final;
+
+                               //
+                               // clear the pending implementation flag (requires explicit methods to be defined first)
+                               //
+                               pending.ImplementMethod (method.MethodName,
+                                       member.InterfaceType, this, member.IsExplicitImpl, out ambig_iface_method, ref optional);
+
+                               //
+                               // Update indexer accessor name to match implementing abstract accessor
+                               //
+                               if (!implementing.DeclaringType.IsInterface && !member.IsExplicitImpl && implementing.IsAccessor)
+                                       method_full_name = implementing.MemberDefinition.Name;
                        }
 
                        DefineMethodBuilder (container, method_full_name, method.ParameterInfo);
@@ -1631,26 +2013,13 @@ namespace Mono.CSharp {
                        if (builder == null)
                                return false;
 
-                       if (container.CurrentType != null)
-                               declaring_type = container.CurrentType;
-                       else
-                               declaring_type = container.TypeBuilder;
+//                     if (container.CurrentType != null)
+//                             declaring_type = container.CurrentType;
+//                     else
+                               declaring_type = container.Definition;
 
                        if (implementing != null && member.IsExplicitImpl) {
-                                       container.TypeBuilder.DefineMethodOverride (builder, implementing);
-                       }
-
-                       TypeManager.AddMethod (builder, method);
-
-                       if (GenericMethod != null) {
-                               bool is_override = member.IsExplicitImpl |
-                                       ((modifiers & Modifiers.OVERRIDE) != 0);
-
-                               if (implementing != null)
-                                       parent_method = implementing;
-
-                               if (!GenericMethod.DefineType (GenericMethod, builder, parent_method, is_override))
-                                       return false;
+                               container.TypeBuilder.DefineMethodOverride (builder, (MethodInfo) implementing.GetMetaInfo ());
                        }
 
                        return true;
@@ -1660,13 +2029,15 @@ namespace Mono.CSharp {
                /// <summary>
                /// Create the MethodBuilder for the method 
                /// </summary>
-               void DefineMethodBuilder (TypeContainer container, string method_name, ParametersCompiled param)
+               void DefineMethodBuilder (TypeDefinition container, string method_name, ParametersCompiled param)
                {
+                       var return_type = method.ReturnType.GetMetaInfo ();
+                       var p_types = param.GetMetaInfo ();
+
                        if (builder == null) {
                                builder = container.TypeBuilder.DefineMethod (
                                        method_name, flags, method.CallingConventions,
-                                       method.ReturnType,
-                                       param.GetEmitTypes ());
+                                       return_type, p_types);
                                return;
                        }
 
@@ -1674,9 +2045,12 @@ namespace Mono.CSharp {
                        // Generic method has been already defined to resolve method parameters
                        // correctly when they use type parameters
                        //
-                       builder.SetParameters (param.GetEmitTypes ());
-                       builder.SetReturnType (method.ReturnType);
+                       builder.SetParameters (p_types);
+                       builder.SetReturnType (return_type);
                        if (builder.Attributes != flags) {
+#if STATIC
+                               builder.__SetAttributes (flags);
+#else
                                try {
                                        if (methodbuilder_attrs_field == null)
                                                methodbuilder_attrs_field = typeof (MethodBuilder).GetField ("attrs", BindingFlags.NonPublic | BindingFlags.Instance);
@@ -1684,46 +2058,44 @@ namespace Mono.CSharp {
                                } catch {
                                        container.Compiler.Report.RuntimeMissingSupport (method.Location, "Generic method MethodAttributes");
                                }
+#endif
                        }
                }
 
                //
                // Emits the code
                // 
-               public void Emit (DeclSpace parent)
+               public void Emit (TypeDefinition parent)
                {
-                       method.ParameterInfo.ApplyAttributes (MethodBuilder);
-
-                       if (GenericMethod != null)
-                               GenericMethod.EmitAttributes ();
+                       var mc = (IMemberContext) method;
 
-                       //
-                       // clear the pending implementation flag
-                       //
-                       if (implementing != null)
-                               parent.PartialContainer.PendingImplementations.ImplementMethod (method.MethodName.Basename,
-                                       member.InterfaceType, this, member.IsExplicitImpl);
-
-                       SourceMethod source = SourceMethod.Create (parent, MethodBuilder, method.Block);
+                       method.ParameterInfo.ApplyAttributes (mc, MethodBuilder);
 
                        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;
-                                       }
+                               BlockContext bc = new BlockContext (mc, block, method.ReturnType);
+                               if (block.Resolve (null, bc, method)) {
+                                       debug_builder = member.Parent.CreateMethodSymbolEntry ();
+                                       EmitContext ec = method.CreateEmitContext (MethodBuilder.GetILGenerator (), debug_builder);
 
                                        block.Emit (ec);
                                }
                        }
+               }
 
-                       if (source != null) {
-                               method.EmitExtraSymbolInfo (source);
-                               source.CloseMethod ();
-                       }
+               public void WriteDebugSymbol (MonoSymbolFile file)
+               {
+                       if (debug_builder == null)
+                               return;
+
+                       var token = builder.GetToken ();
+                       int t = token.Token;
+#if STATIC
+                       if (token.IsPseudoToken)
+                               t = member.Module.Builder.ResolvePseudoToken (t);
+#endif
+
+                       debug_builder.DefineMethod (file, t);
                }
        }
 
@@ -1737,59 +2109,66 @@ namespace Mono.CSharp {
 
                public static readonly string MetadataName = "Finalize";
 
-               public Destructor (DeclSpace parent, Modifiers mod, ParametersCompiled parameters, Attributes attrs, Location l)
-                       : base (parent, null, TypeManager.system_void_expr, mod, AllowedModifiers,
-                               new MemberName (MetadataName, l), attrs, parameters)
+               public Destructor (TypeDefinition parent, Modifiers mod, ParametersCompiled parameters, Attributes attrs, Location l)
+                       : base (parent, null, mod, AllowedModifiers, new MemberName (MetadataName, l), attrs, parameters)
                {
                        ModFlags &= ~Modifiers.PRIVATE;
                        ModFlags |= Modifiers.PROTECTED | Modifiers.OVERRIDE;
                }
 
-               public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
+               public override void Accept (StructuralVisitor visitor)
+               {
+                       visitor.Visit (this);
+               }
+
+               public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
                {
                        if (a.Type == pa.Conditional) {
                                Error_ConditionalAttributeIsNotValid ();
                                return;
                        }
 
-                       base.ApplyAttributeBuilder (a, cb, pa);
+                       base.ApplyAttributeBuilder (a, ctor, cdata, pa);
                }
 
                protected override bool CheckBase ()
                {
-                       if (!base.CheckBase ())
-                               return false;
-
-                       if (Parent.PartialContainer.BaseCache == null)
-                               return true;
+                       // Don't check base, destructors have special syntax
+                       return true;
+               }
 
-                       Type base_type = Parent.PartialContainer.BaseCache.Container.Type;
+               public override void Emit()
+               {
+                       var base_type = Parent.PartialContainer.BaseType;
                        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 ();
+                               var base_dtor = MemberCache.FindMember (base_type,
+                                       new MemberFilter (MetadataName, 0, MemberKind.Destructor, null, null), BindingRestriction.InstanceOnly) as MethodSpec;
 
-                               method_expr.IsBase = true;
-                               method_expr.InstanceExpression = new CompilerGeneratedThis (Parent.TypeBuilder, Location);
+                               if (base_dtor == null)
+                                       throw new NotImplementedException ();
 
-                               ToplevelBlock new_block = new ToplevelBlock (Compiler, Block.StartLocation);
-                               new_block.EndLocation = Block.EndLocation;
+                               MethodGroupExpr method_expr = MethodGroupExpr.CreatePredefined (base_dtor, base_type, Location);
+                               method_expr.InstanceExpression = new BaseThis (base_type, Location);
 
-                               Block finaly_block = new ExplicitBlock (new_block, Location, Location);
-                               Block try_block = new Block (new_block, block);
+                               var try_block = new ExplicitBlock (block, block.StartLocation, block.EndLocation) {
+                                       IsCompilerGenerated = true
+                               };
+                               var finaly_block = new ExplicitBlock (block, Location, Location) {
+                                       IsCompilerGenerated = true
+                               };
 
                                //
                                // 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));
+                               finaly_block.AddStatement (new StatementExpression (new Invocation (method_expr, new Arguments (0)), Location.Null));
 
-                               block = new_block;
+                               var tf = new TryFinally (try_block, finaly_block, Location);
+                               block.WrapIntoDestructor (tf, try_block);
                        }
 
-                       return true;
+                       base.Emit ();
                }
 
                public override string GetSignatureForError ()
@@ -1797,9 +2176,10 @@ namespace Mono.CSharp {
                        return Parent.GetSignatureForError () + ".~" + Parent.MemberName.Name + "()";
                }
 
-               protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
+               protected override bool ResolveMemberType ()
                {
-                       return null;
+                       member_type = Compiler.BuiltinTypes.Void;
+                       return true;
                }
 
                public override string[] ValidAttributeTargets {
@@ -1814,36 +2194,21 @@ namespace Mono.CSharp {
        public abstract class AbstractPropertyEventMethod : MemberCore, IMethodData {
                protected MethodData method_data;
                protected ToplevelBlock block;
-               protected Dictionary<SecurityAction, PermissionSet> declarative_security;
-
-               // 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;
+               protected SecurityType declarative_security;
 
                protected readonly string prefix;
 
                ReturnParameter return_attributes;
 
-               public AbstractPropertyEventMethod (PropertyBasedMember member, string prefix)
-                       : base (member.Parent, SetupName (prefix, member, member.Location), null)
-               {
-                       this.prefix = prefix;
-                       IsDummy = true;
-               }
-
-               public AbstractPropertyEventMethod (InterfaceMemberBase member, Accessor accessor,
-                                                   string prefix)
-                       : base (member.Parent, SetupName (prefix, member, accessor.Location),
-                               accessor.Attributes)
+               public AbstractPropertyEventMethod (InterfaceMemberBase member, string prefix, Attributes attrs, Location loc)
+                       : base (member.Parent, SetupName (prefix, member, loc), attrs)
                {
                        this.prefix = prefix;
-                       this.block = accessor.Block;
                }
 
                static MemberName SetupName (string prefix, InterfaceMemberBase member, Location loc)
                {
-                       return new MemberName (member.MemberName.Left, prefix + member.ShortName, loc);
+                       return new MemberName (member.MemberName.Left, prefix + member.ShortName, member.MemberName.ExplicitInterface, loc);
                }
 
                public void UpdateName (InterfaceMemberBase member)
@@ -1869,19 +2234,14 @@ namespace Mono.CSharp {
                        }
                }
 
-               public EmitContext CreateEmitContext (ILGenerator ig)
+               public EmitContext CreateEmitContext (ILGenerator ig, SourceMethodBuilder sourceMethod)
                {
-                       return new EmitContext (this, ig, ReturnType);
+                       return new EmitContext (this, ig, ReturnType, sourceMethod);
                }
 
-               public bool IsExcluded ()
-               {
-                       return false;
-               }
-
-               GenericMethod IMethodData.GenericMethod {
+               public bool IsAccessor {
                        get {
-                               return null;
+                               return true;
                        }
                }
 
@@ -1891,18 +2251,18 @@ namespace Mono.CSharp {
                        }
                }
 
-               public Type[] ParameterTypes { 
+               public TypeSpec[] ParameterTypes { 
                        get {
                                return ParameterInfo.Types;
                        }
                }
 
                public abstract ParametersCompiled ParameterInfo { get ; }
-               public abstract Type ReturnType { get; }
+               public abstract TypeSpec ReturnType { get; }
 
                #endregion
 
-               public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
+               public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
                {
                        if (a.Type == pa.CLSCompliant || a.Type == pa.Obsolete || a.Type == pa.Conditional) {
                                Report.Error (1667, a.Location,
@@ -1912,14 +2272,12 @@ namespace Mono.CSharp {
                        }
 
                        if (a.IsValidSecurityAttribute ()) {
-                               if (declarative_security == null)
-                                       declarative_security = new Dictionary<SecurityAction, PermissionSet> ();
-                               a.ExtractSecurityPermissionSet (declarative_security);
+                               a.ExtractSecurityPermissionSet (ctor, ref declarative_security);
                                return;
                        }
 
                        if (a.Target == AttributeTargets.Method) {
-                               method_data.MethodBuilder.SetCustomAttribute (cb);
+                               method_data.MethodBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
                                return;
                        }
 
@@ -1927,14 +2285,14 @@ namespace Mono.CSharp {
                                if (return_attributes == null)
                                        return_attributes = new ReturnParameter (this, method_data.MethodBuilder, Location);
 
-                               return_attributes.ApplyAttributeBuilder (a, cb, pa);
+                               return_attributes.ApplyAttributeBuilder (a, ctor, cdata, pa);
                                return;
                        }
 
-                       ApplyToExtraTarget (a, cb, pa);
+                       ApplyToExtraTarget (a, ctor, cdata, pa);
                }
 
-               protected virtual void ApplyToExtraTarget (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
+               protected virtual void ApplyToExtraTarget (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
                {
                        throw new NotSupportedException ("You forgot to define special attribute target handling");
                }
@@ -1945,28 +2303,21 @@ namespace Mono.CSharp {
                        throw new NotSupportedException ();
                }
 
-               public virtual void Emit (DeclSpace parent)
+               public virtual void Emit (TypeDefinition parent)
                {
                        method_data.Emit (parent);
 
                        if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
-                               PredefinedAttributes.Get.CompilerGenerated.EmitAttribute (method_data.MethodBuilder);
+                               Module.PredefinedAttributes.CompilerGenerated.EmitAttribute (method_data.MethodBuilder);
                        if (((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0))
-                               PredefinedAttributes.Get.DebuggerHidden.EmitAttribute (method_data.MethodBuilder);
+                               Module.PredefinedAttributes.DebuggerHidden.EmitAttribute (method_data.MethodBuilder);
 
-                       if (TypeManager.IsDynamicType (ReturnType)) {
+                       if (ReturnType.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
                                return_attributes = new ReturnParameter (this, method_data.MethodBuilder, Location);
-                               PredefinedAttributes.Get.Dynamic.EmitAttribute (return_attributes.Builder);
-                       } else {
-                               var trans_flags = TypeManager.HasDynamicTypeUsed (ReturnType);
-                               if (trans_flags != null) {
-                                       var pa = PredefinedAttributes.Get.DynamicTransform;
-                                       if (pa.Constructor != null || pa.ResolveConstructor (Location, TypeManager.bool_type.MakeArrayType ())) {
-                                               return_attributes = new ReturnParameter (this, method_data.MethodBuilder, Location);
-                                               return_attributes.Builder.SetCustomAttribute (
-                                                       new CustomAttributeBuilder (pa.Constructor, new object [] { trans_flags }));
-                                       }
-                               }
+                               Module.PredefinedAttributes.Dynamic.EmitAttribute (return_attributes.Builder);
+                       } else if (ReturnType.HasDynamicElement) {
+                               return_attributes = new ReturnParameter (this, method_data.MethodBuilder, Location);
+                               Module.PredefinedAttributes.Dynamic.EmitAttribute (return_attributes.Builder, ReturnType, Location);
                        }
 
                        if (OptAttributes != null)
@@ -1974,7 +2325,11 @@ namespace Mono.CSharp {
 
                        if (declarative_security != null) {
                                foreach (var de in declarative_security) {
+#if STATIC
+                                       method_data.MethodBuilder.__AddDeclarativeSecurity (de);
+#else
                                        method_data.MethodBuilder.AddDeclarativeSecurity (de.Key, de.Value);
+#endif
                                }
                        }
 
@@ -1983,50 +2338,39 @@ namespace Mono.CSharp {
 
                public override bool EnableOverloadChecks (MemberCore overload)
                {
+                       if (overload is MethodCore) {
+                               caching_flags |= Flags.MethodOverloadsExist;
+                               return true;
+                       }
+
                        // This can only happen with indexers and it will
                        // be catched as indexer difference
                        if (overload is AbstractPropertyEventMethod)
                                return true;
 
-                       if (overload is MethodCore) {
-                               caching_flags |= Flags.MethodOverloadsExist;
-                               return true;
-                       }
                        return false;
                }
 
-               public override bool IsClsComplianceRequired()
+               public override string GetCallerMemberName ()
                {
-                       return false;
+                       return base.GetCallerMemberName ().Substring (prefix.Length);
                }
 
-               public bool IsDuplicateImplementation (MethodCore method)
+               public override string GetSignatureForDocumentation ()
                {
-                       if (!MemberName.Equals (method.MemberName))
-                               return false;
-
-                       Type[] param_types = method.ParameterTypes;
-
-                       if (param_types == null || param_types.Length != ParameterTypes.Length)
-                               return false;
-
-                       for (int i = 0; i < param_types.Length; i++)
-                               if (param_types [i] != ParameterTypes [i])
-                                       return false;
-
-                       Report.SymbolRelatedToPreviousError (method);
-                       Report.Error (82, Location, "A member `{0}' is already reserved",
-                               method.GetSignatureForError ());
-                       return true;
+                       // should not be called
+                       throw new NotSupportedException ();
                }
 
-               public override bool IsUsed {
-                       get {
-                               if (IsDummy)
-                                       return false;
+               public override bool IsClsComplianceRequired()
+               {
+                       return false;
+               }
 
-                               return base.IsUsed;
-                       }
+               public override void WriteDebugSymbol (MonoSymbolFile file)
+               {
+                       if (method_data != null)
+                               method_data.WriteDebugSymbol (file);
                }
 
                public MethodSpec Spec { get; protected set; }
@@ -2037,9 +2381,6 @@ namespace Mono.CSharp {
                public override string DocCommentHeader {
                        get { throw new InvalidOperationException ("Unexpected attempt to get doc comment from " + this.GetType () + "."); }
                }
-
-               void IMethodData.EmitExtraSymbolInfo (SourceMethod source)
-               { }
        }
 
        public class Operator : MethodOrOperator {
@@ -2125,25 +2466,28 @@ namespace Mono.CSharp {
                        names [(int) OpType.Implicit] = new string [] { "implicit", "op_Implicit" };
                        names [(int) OpType.Explicit] = new string [] { "explicit", "op_Explicit" };
                }
-               
-               public Operator (DeclSpace parent, OpType type, FullNamedExpression ret_type,
-                                Modifiers mod_flags, ParametersCompiled parameters,
+
+               public Operator (TypeDefinition parent, OpType type, FullNamedExpression ret_type, Modifiers mod_flags, ParametersCompiled parameters,
                                 ToplevelBlock block, Attributes attrs, Location loc)
-                       : base (parent, null, ret_type, mod_flags, AllowedModifiers,
-                               new MemberName (GetMetadataName (type), loc), attrs, parameters)
+                       : base (parent, ret_type, mod_flags, AllowedModifiers, new MemberName (GetMetadataName (type), loc), attrs, parameters)
                {
                        OperatorType = type;
                        Block = block;
                }
 
-               public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
+               public override void Accept (StructuralVisitor visitor)
+               {
+                       visitor.Visit (this);
+               }
+
+               public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
                {
                        if (a.Type == pa.Conditional) {
                                Error_ConditionalAttributeIsNotValid ();
                                return;
                        }
 
-                       base.ApplyAttributeBuilder (a, cb, pa);
+                       base.ApplyAttributeBuilder (a, ctor, cdata, pa);
                }
                
                public override bool Define ()
@@ -2156,87 +2500,91 @@ namespace Mono.CSharp {
                        if (!base.Define ())
                                return false;
 
+                       if (block != null && block.IsIterator) {
+                               //
+                               // Current method is turned into automatically generated
+                               // wrapper which creates an instance of iterator
+                               //
+                               Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
+                               ModFlags |= Modifiers.DEBUGGER_HIDDEN;
+                       }
+
                        // imlicit and explicit operator of same types are not allowed
                        if (OperatorType == OpType.Explicit)
-                               Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Implicit), Parameters, Report);
+                               Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Implicit), parameters);
                        else if (OperatorType == OpType.Implicit)
-                               Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Explicit), Parameters, Report);
+                               Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Explicit), parameters);
 
-                       Type declaring_type = MethodData.DeclaringType;
-                       Type return_type = MemberType;
-                       Type first_arg_type = ParameterTypes [0];
+                       TypeSpec declaring_type = Parent.CurrentType;
+                       TypeSpec return_type = MemberType;
+                       TypeSpec first_arg_type = ParameterTypes [0];
                        
-                       Type first_arg_type_unwrap = first_arg_type;
-                       if (TypeManager.IsNullableType (first_arg_type))
-                               first_arg_type_unwrap = TypeManager.TypeToCoreType (TypeManager.GetTypeArguments (first_arg_type) [0]);
+                       TypeSpec first_arg_type_unwrap = first_arg_type;
+                       if (first_arg_type.IsNullableType)
+                               first_arg_type_unwrap = Nullable.NullableInfo.GetUnderlyingType (first_arg_type);
                        
-                       Type return_type_unwrap = return_type;
-                       if (TypeManager.IsNullableType (return_type))
-                               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;
-                       }
+                       TypeSpec return_type_unwrap = return_type;
+                       if (return_type.IsNullableType)
+                               return_type_unwrap = Nullable.NullableInfo.GetUnderlyingType (return_type);
 
                        //
                        // Rules for conversion operators
                        //
                        if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
-                               if (first_arg_type_unwrap == return_type_unwrap && first_arg_type_unwrap == declaring_type){
+                               if (first_arg_type_unwrap == return_type_unwrap && first_arg_type_unwrap == declaring_type) {
                                        Report.Error (555, Location,
                                                "User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type");
                                        return false;
                                }
-                               
-                               Type conv_type;
-                               if (TypeManager.IsEqual (declaring_type, return_type) || declaring_type == return_type_unwrap) {
+
+                               TypeSpec conv_type;
+                               if (declaring_type == return_type || declaring_type == return_type_unwrap) {
                                        conv_type = first_arg_type;
-                               } else if (TypeManager.IsEqual (declaring_type, first_arg_type) || declaring_type == first_arg_type_unwrap) {
+                               } else if (declaring_type == first_arg_type || declaring_type == first_arg_type_unwrap) {
                                        conv_type = return_type;
                                } else {
-                                       Report.Error (556, Location, 
+                                       Report.Error (556, Location,
                                                "User-defined conversion must convert to or from the enclosing type");
                                        return false;
                                }
 
-                               //
-                               // Because IsInterface and IsClass are not supported
-                               //
-                               if (!TypeManager.IsGenericParameter (conv_type)) {
-                                       if (conv_type.IsInterface) {
-                                               Report.Error (552, Location, "User-defined conversion `{0}' cannot convert to or from an interface type",
+                               if (conv_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
+                                       Report.Error (1964, Location,
+                                               "User-defined conversion `{0}' cannot convert to or from the dynamic type",
+                                               GetSignatureForError ());
+
+                                       return false;
+                               }
+
+                               if (conv_type.IsInterface) {
+                                       Report.Error (552, Location, "User-defined conversion `{0}' cannot convert to or from an interface type",
+                                               GetSignatureForError ());
+                                       return false;
+                               }
+
+                               if (conv_type.IsClass) {
+                                       if (TypeSpec.IsBaseClass (declaring_type, conv_type, true)) {
+                                               Report.Error (553, Location, "User-defined conversion `{0}' cannot convert to or from a base class",
                                                        GetSignatureForError ());
                                                return false;
                                        }
 
-                                       if (conv_type.IsClass) {
-                                               if (TypeManager.IsSubclassOf (declaring_type, conv_type)) {
-                                                       Report.Error (553, Location, "User-defined conversion `{0}' cannot convert to or from a base class",
-                                                               GetSignatureForError ());
-                                                       return false;
-                                               }
-
-                                               if (TypeManager.IsSubclassOf (conv_type, declaring_type)) {
-                                                       Report.Error (554, Location, "User-defined conversion `{0}' cannot convert to or from a derived class",
-                                                               GetSignatureForError ());
-                                                       return false;
-                                               }
+                                       if (TypeSpec.IsBaseClass (conv_type, declaring_type, false)) {
+                                               Report.Error (554, Location, "User-defined conversion `{0}' cannot convert to or from a derived class",
+                                                       GetSignatureForError ());
+                                               return false;
                                        }
                                }
                        } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
-                               if (first_arg_type != declaring_type || Parameters.Types [1] != TypeManager.int32_type) {
+                               if (first_arg_type != declaring_type || parameters.Types[1].BuiltinType != BuiltinTypeSpec.Type.Int) {
                                        Report.Error (564, Location, "Overloaded shift operator must have the type of the first operand be the containing type, and the type of the second operand must be int");
                                        return false;
                                }
-                       } else if (Parameters.Count == 1) {
+                       } else if (parameters.Count == 1) {
                                // Checks for Unary operators
 
                                if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
-                                       if (return_type != declaring_type && !TypeManager.IsSubclassOf (return_type, declaring_type)) {
+                                       if (return_type != declaring_type && !TypeSpec.IsBaseClass (return_type, declaring_type, false)) {
                                                Report.Error (448, Location,
                                                        "The return type for ++ or -- operator must be the containing type or derived from the containing type");
                                                return false;
@@ -2247,15 +2595,15 @@ namespace Mono.CSharp {
                                                return false;
                                        }
                                }
-                               
-                               if (!TypeManager.IsEqual (first_arg_type_unwrap, declaring_type)){
+
+                               if (first_arg_type_unwrap != declaring_type) {
                                        Report.Error (562, Location,
                                                "The parameter type of a unary operator must be the containing type");
                                        return false;
                                }
-                               
+
                                if (OperatorType == OpType.True || OperatorType == OpType.False) {
-                                       if (return_type != TypeManager.bool_type){
+                                       if (return_type.BuiltinType != BuiltinTypeSpec.Type.Bool) {
                                                Report.Error (
                                                        215, Location,
                                                        "The return type of operator True or False " +
@@ -2263,15 +2611,15 @@ namespace Mono.CSharp {
                                                return false;
                                        }
                                }
-                               
-                       } else if (!TypeManager.IsEqual (first_arg_type_unwrap, declaring_type)) {
+
+                       } else if (first_arg_type_unwrap != declaring_type) {
                                // Checks for Binary operators
 
-                               var second_arg_type = ParameterTypes [1];
-                               if (TypeManager.IsNullableType (second_arg_type))
-                                       second_arg_type = TypeManager.TypeToCoreType (TypeManager.GetTypeArguments (second_arg_type) [0]);
+                               var second_arg_type = ParameterTypes[1];
+                               if (second_arg_type.IsNullableType)
+                                       second_arg_type = Nullable.NullableInfo.GetUnderlyingType (second_arg_type);
 
-                               if (!TypeManager.IsEqual (second_arg_type, declaring_type)) {
+                               if (second_arg_type != declaring_type) {
                                        Report.Error (563, Location,
                                                "One of the parameters of a binary operator must be the containing type");
                                        return false;
@@ -2290,9 +2638,10 @@ namespace Mono.CSharp {
                        return true;
                }
 
-               // Operator cannot be override
-               protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
+               protected override MemberSpec FindBaseMember (out MemberSpec bestCandidate, ref bool overrides)
                {
+                       // Operator cannot be override
+                       bestCandidate = null;
                        return null;
                }
 
@@ -2358,141 +2707,31 @@ namespace Mono.CSharp {
                        }
                }
 
+               public override string GetSignatureForDocumentation ()
+               {
+                       string s = base.GetSignatureForDocumentation ();
+                       if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
+                               s = s + "~" + ReturnType.GetSignatureForDocumentation ();
+                       }
+
+                       return s;
+               }
+
                public override string GetSignatureForError ()
                {
                        StringBuilder sb = new StringBuilder ();
                        if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
                                sb.AppendFormat ("{0}.{1} operator {2}",
-                                       Parent.GetSignatureForError (), GetName (OperatorType), type_name.GetSignatureForError ());
+                                       Parent.GetSignatureForError (), GetName (OperatorType),
+                                       member_type == null ? type_expr.GetSignatureForError () : member_type.GetSignatureForError ());
                        }
                        else {
                                sb.AppendFormat ("{0}.operator {1}", Parent.GetSignatureForError (), GetName (OperatorType));
                        }
 
-                       sb.Append (Parameters.GetSignatureForError ());
+                       sb.Append (parameters.GetSignatureForError ());
                        return sb.ToString ();
                }
        }
-
-       //
-       // This is used to compare method signatures
-       //
-       struct MethodSignature {
-               public string Name;
-               public Type RetType;
-               public Type [] Parameters;
-               
-               /// <summary>
-               ///    This delegate is used to extract methods which have the
-               ///    same signature as the argument
-               /// </summary>
-               public static MemberFilter method_signature_filter = new MemberFilter (MemberSignatureCompare);
-               
-               public MethodSignature (string name, Type ret_type, Type [] parameters)
-               {
-                       Name = name;
-                       RetType = ret_type;
-
-                       if (parameters == null)
-                               Parameters = Type.EmptyTypes;
-                       else
-                               Parameters = parameters;
-               }
-
-               public override string ToString ()
-               {
-                       string pars = "";
-                       if (Parameters.Length != 0){
-                               System.Text.StringBuilder sb = new System.Text.StringBuilder ();
-                               for (int i = 0; i < Parameters.Length; i++){
-                                       sb.Append (Parameters [i]);
-                                       if (i+1 < Parameters.Length)
-                                               sb.Append (", ");
-                               }
-                               pars = sb.ToString ();
-                       }
-
-                       return String.Format ("{0} {1} ({2})", RetType, Name, pars);
-               }
-               
-               public override int GetHashCode ()
-               {
-                       return Name.GetHashCode ();
-               }
-
-               public override bool Equals (Object o)
-               {
-                       MethodSignature other = (MethodSignature) o;
-
-                       if (other.Name != Name)
-                               return false;
-
-                       if (other.RetType != RetType)
-                               return false;
-                       
-                       if (Parameters == null){
-                               if (other.Parameters == null)
-                                       return true;
-                               return false;
-                       }
-
-                       if (other.Parameters == null)
-                               return false;
-                       
-                       int c = Parameters.Length;
-                       if (other.Parameters.Length != c)
-                               return false;
-
-                       for (int i = 0; i < c; i++)
-                               if (other.Parameters [i] != Parameters [i])
-                                       return false;
-
-                       return true;
-               }
-
-               static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
-               {
-                       MethodSignature sig = (MethodSignature) filter_criteria;
-
-                       if (m.Name != sig.Name)
-                               return false;
-
-                       Type ReturnType;
-                       MethodInfo mi = m as MethodInfo;
-                       PropertyInfo pi = m as PropertyInfo;
-
-                       if (mi != null)
-                               ReturnType = mi.ReturnType;
-                       else if (pi != null)
-                               ReturnType = pi.PropertyType;
-                       else
-                               return false;
-
-                       //
-                       // we use sig.RetType == null to mean `do not check the
-                       // method return value.  
-                       //
-                       if (sig.RetType != null) {
-                               if (!TypeManager.IsEqual (ReturnType, sig.RetType))
-                                       return false;
-                       }
-
-                       Type [] args;
-                       if (mi != null)
-                               args = TypeManager.GetParameterData (mi).Types;
-                       else
-                               args = TypeManager.GetParameterData (pi).Types;
-                       Type [] sigp = sig.Parameters;
-
-                       if (args.Length != sigp.Length)
-                               return false;
-
-                       for (int i = args.Length - 1; i >= 0; i--)
-                               if (!TypeManager.IsEqual (args [i], sigp [i]))
-                                       return false;
-
-                       return true;
-               }
-       }
 }