[Socket] Improved ConnectAsync
[mono.git] / mcs / mcs / anonymous.cs
index bb5082616f87abf47192b2f9c56baa6d50634c17..47abe0127f85a1a36a6a04609b555e9af115980b 100644 (file)
 //
 
 using System;
-using System.Text;
 using System.Collections.Generic;
+
+#if STATIC
+using IKVM.Reflection;
+using IKVM.Reflection.Emit;
+#else
 using System.Reflection;
 using System.Reflection.Emit;
+#endif
 
 namespace Mono.CSharp {
 
        public abstract class CompilerGeneratedClass : Class
        {
-               public static string MakeName (string host, string typePrefix, string name, int id)
-               {
-                       return "<" + host + ">" + typePrefix + "__" + name + id.ToString ("X");
-               }
-               
-               protected CompilerGeneratedClass (DeclSpace parent, MemberName name, Modifiers mod)
+               protected CompilerGeneratedClass (TypeContainer parent, MemberName name, Modifiers mod)
                        : base (parent.NamespaceEntry, parent, name, mod | Modifiers.COMPILER_GENERATED, null)
                {
                }
@@ -34,30 +34,32 @@ namespace Mono.CSharp {
                        if (HasMembersDefined)
                                throw new InternalErrorException ("Helper class already defined!");
                }
-       }
 
-       //
-       // Anonymous method storey is created when an anonymous method uses
-       // variable or parameter from outer scope. They are then hoisted to
-       // anonymous method storey (captured)
-       //
-       public class AnonymousMethodStorey : CompilerGeneratedClass
-       {
-               struct StoreyFieldPair
+               protected static MemberName MakeMemberName (MemberBase host, string name, int unique_id, TypeParameter[] tparams, Location loc)
                {
-                       public readonly AnonymousMethodStorey Storey;
-                       public readonly Field Field;
-
-                       public StoreyFieldPair (AnonymousMethodStorey storey, Field field)
-                       {
-                               this.Storey = storey;
-                               this.Field = field;
+                       string host_name = host == null ? null : host.Name;
+                       string tname = MakeName (host_name, "c", name, unique_id);
+                       TypeArguments args = null;
+                       if (tparams != null) {
+                               args = new TypeArguments ();
+                               foreach (TypeParameter tparam in tparams)
+                                       args.Add (new TypeParameterName (tparam.Name, null, loc));
                        }
+
+                       return new MemberName (tname, args, loc);
+               }
+
+               public static string MakeName (string host, string typePrefix, string name, int id)
+               {
+                       return "<" + host + ">" + typePrefix + "__" + name + id.ToString ("X");
                }
+       }
 
-               sealed class HoistedGenericField : Field
+       public class HoistedStoreyClass : CompilerGeneratedClass
+       {
+               public sealed class HoistedField : Field
                {
-                       public HoistedGenericField (DeclSpace parent, FullNamedExpression type, Modifiers mod, string name,
+                       public HoistedField (HoistedStoreyClass parent, FullNamedExpression type, Modifiers mod, string name,
                                  Attributes attrs, Location loc)
                                : base (parent, type, mod, new MemberName (name, loc), attrs)
                        {
@@ -68,7 +70,7 @@ namespace Mono.CSharp {
                                if (!base.ResolveMemberType ())
                                        return false;
 
-                               AnonymousMethodStorey parent = ((AnonymousMethodStorey) Parent).GetGenericStorey ();
+                               HoistedStoreyClass parent = ((HoistedStoreyClass) Parent).GetGenericStorey ();
                                if (parent != null && parent.Mutator != null)
                                        member_type = parent.Mutator.Mutate (MemberType);
 
@@ -76,6 +78,77 @@ namespace Mono.CSharp {
                        }
                }
 
+               protected TypeParameterMutator mutator;
+
+               public HoistedStoreyClass (TypeContainer parent, MemberName name, TypeParameter[] tparams, Modifiers mod)
+                       : base (parent, name, mod | Modifiers.PRIVATE)
+               {
+                       if (tparams != null) {
+                               type_params = new TypeParameter[tparams.Length];
+                               var src = new TypeParameterSpec[tparams.Length];
+                               var dst = new TypeParameterSpec[tparams.Length];
+
+                               for (int i = 0; i < type_params.Length; ++i) {
+                                       type_params[i] = tparams[i].CreateHoistedCopy (this, spec);
+
+                                       src[i] = tparams[i].Type;
+                                       dst[i] = type_params[i].Type;
+                               }
+
+                               // A copy is not enough, inflate any type parameter constraints
+                               // using a new type parameters
+                               var inflator = new TypeParameterInflator (this, null, src, dst);
+                               for (int i = 0; i < type_params.Length; ++i) {
+                                       src[i].InflateConstraints (inflator, dst[i]);
+                               }
+
+                               mutator = new TypeParameterMutator (tparams, type_params);
+                       }
+               }
+
+               #region Properties
+
+               public TypeParameterMutator Mutator {
+                       get {
+                               return mutator;
+                       }
+                       set {
+                               mutator = value;
+                       }
+               }
+
+               #endregion
+
+               public HoistedStoreyClass GetGenericStorey ()
+               {
+                       DeclSpace storey = this;
+                       while (storey != null && storey.CurrentTypeParameters == null)
+                               storey = storey.Parent;
+
+                       return storey as HoistedStoreyClass;
+               }
+       }
+
+
+       //
+       // Anonymous method storey is created when an anonymous method uses
+       // variable or parameter from outer scope. They are then hoisted to
+       // anonymous method storey (captured)
+       //
+       public class AnonymousMethodStorey : HoistedStoreyClass
+       {
+               struct StoreyFieldPair
+               {
+                       public readonly AnonymousMethodStorey Storey;
+                       public readonly Field Field;
+
+                       public StoreyFieldPair (AnonymousMethodStorey storey, Field field)
+                       {
+                               this.Storey = storey;
+                               this.Field = field;
+                       }
+               }
+
                //
                // Needed to delay hoisted _this_ initialization. When an anonymous
                // method is used inside ctor and _this_ is hoisted, base ctor has to
@@ -122,36 +195,12 @@ namespace Mono.CSharp {
                // Local variable which holds this storey instance
                public LocalTemporary Instance;
 
-               TypeParameterMutator mutator;
-
-               public AnonymousMethodStorey (Block block, TypeContainer parent, MemberBase host, GenericMethod generic, string name)
-                       : base (parent, MakeMemberName (host, name, generic, block.StartLocation), Modifiers.PRIVATE | Modifiers.SEALED)
+               public AnonymousMethodStorey (Block block, TypeContainer parent, MemberBase host, TypeParameter[] tparams, string name)
+                       : base (parent, MakeMemberName (host, name, unique_id, tparams, block.StartLocation),
+                               tparams, Modifiers.SEALED)
                {
-                       Parent = parent;
                        OriginalSourceBlock = block;
                        ID = unique_id++;
-
-                       if (generic != null) {
-                               var hoisted_tparams = generic.CurrentTypeParameters;
-                               type_params = new TypeParameter [hoisted_tparams.Length];
-                               for (int i = 0; i < type_params.Length; ++i) {
-                                       type_params[i] = hoisted_tparams[i].CreateHoistedCopy (spec);
-                               }
-                       }
-               }
-
-               static MemberName MakeMemberName (MemberBase host, string name, GenericMethod generic, Location loc)
-               {
-                       string host_name = host == null ? null : host.Name;
-                       string tname = MakeName (host_name, "c", name, unique_id);
-                       TypeArguments args = null;
-                       if (generic != null) {
-                               args = new TypeArguments ();
-                               foreach (TypeParameter tparam in generic.CurrentTypeParameters)
-                                       args.Add (new TypeParameterName (tparam.Name, null, loc));
-                       }
-
-                       return new MemberName (tname, args, loc);
                }
 
                public void AddCapturedThisField (EmitContext ec)
@@ -163,10 +212,10 @@ namespace Mono.CSharp {
 
                        // Inflated type instance has to be updated manually
                        if (Instance.Type is InflatedTypeSpec) {
-                               var inflator = new TypeParameterInflator (Instance.Type, TypeParameterSpec.EmptyTypes, TypeSpec.EmptyTypes);
+                               var inflator = new TypeParameterInflator (this, Instance.Type, TypeParameterSpec.EmptyTypes, TypeSpec.EmptyTypes);
                                Instance.Type.MemberCache.AddMember (f.Spec.InflateMember (inflator));
 
-                               inflator = new TypeParameterInflator (f.Parent.CurrentType, TypeParameterSpec.EmptyTypes, TypeSpec.EmptyTypes);
+                               inflator = new TypeParameterInflator (this, f.Parent.CurrentType, TypeParameterSpec.EmptyTypes, TypeSpec.EmptyTypes);
                                f.Parent.CurrentType.MemberCache.AddMember (f.Spec.InflateMember (inflator));
                        }
                }
@@ -180,7 +229,7 @@ namespace Mono.CSharp {
                                return AddCompilerGeneratedField (name, field_type);
 
                        const Modifiers mod = Modifiers.INTERNAL | Modifiers.COMPILER_GENERATED;
-                       Field f = new HoistedGenericField (this, field_type, mod, name, null, Location);
+                       Field f = new HoistedField (this, field_type, mod, name, null, Location);
                        AddField (f);
                        return f;
                }
@@ -194,7 +243,7 @@ namespace Mono.CSharp {
                }
 
                //
-               // Creates a link between block and the anonymous method storey
+               // Creates a link between hoisted variable block and the anonymous method storey
                //
                // An anonymous method can reference variables from any outer block, but they are
                // hoisted in their own ExplicitBlock. When more than one block is referenced we
@@ -223,7 +272,7 @@ namespace Mono.CSharp {
                        used_parent_storeys.Add (new StoreyFieldPair (storey, f));
                }
 
-               public void CaptureLocalVariable (ResolveContext ec, LocalInfo local_info)
+               public void CaptureLocalVariable (ResolveContext ec, LocalVariable local_info)
                {
                        ec.CurrentBlock.Explicit.HasCapturedVariable = true;
                        if (ec.CurrentBlock.Explicit != local_info.Block.Explicit)
@@ -321,13 +370,19 @@ namespace Mono.CSharp {
                                }
                        }
 
+                       //
+                       // Update parent cache as we most likely passed the point
+                       // where the cache was constructed
+                       //
+                       Parent.CurrentType.MemberCache.AddMember (this.spec);
+
                        return true;
                }
 
                //
                // Initializes all hoisted variables
                //
-               public void EmitStoreyInstantiation (EmitContext ec)
+               public void EmitStoreyInstantiation (EmitContext ec, ExplicitBlock block)
                {
                        // There can be only one instance variable for each storey type
                        if (Instance != null)
@@ -341,26 +396,25 @@ namespace Mono.CSharp {
                        var storey_type_expr = CreateStoreyTypeExpression (ec);
 
                        ResolveContext rc = new ResolveContext (ec.MemberContext);
+                       rc.CurrentBlock = block;
                        Expression e = new New (storey_type_expr, null, Location).Resolve (rc);
                        e.Emit (ec);
 
                        Instance = new LocalTemporary (storey_type_expr.Type);
                        Instance.Store (ec);
 
-                       EmitHoistedFieldsInitialization (ec);
+                       EmitHoistedFieldsInitialization (rc, ec);
 
                        SymbolWriter.DefineScopeVariable (ID, Instance.Builder);
                        SymbolWriter.CloseCompilerGeneratedBlock (ec);
                }
 
-               void EmitHoistedFieldsInitialization (EmitContext ec)
+               void EmitHoistedFieldsInitialization (ResolveContext rc, EmitContext ec)
                {
                        //
                        // Initialize all storey reference fields by using local or hoisted variables
                        //
                        if (used_parent_storeys != null) {
-                               var rc = new ResolveContext (ec.MemberContext);
-
                                foreach (StoreyFieldPair sf in used_parent_storeys) {
                                        //
                                        // Get instance expression of storey field
@@ -384,7 +438,7 @@ namespace Mono.CSharp {
                        //
                        if (OriginalSourceBlock.Explicit.HasCapturedThis && !(Parent is AnonymousMethodStorey)) {
                                AddCapturedThisField (ec);
-                               OriginalSourceBlock.AddScopeStatement (new ThisInitializer (hoisted_this));
+                               rc.CurrentBlock.AddScopeStatement (new ThisInitializer (hoisted_this));
                        }
 
                        //
@@ -433,15 +487,6 @@ namespace Mono.CSharp {
                        base.EmitType ();
                }
 
-               public AnonymousMethodStorey GetGenericStorey ()
-               {
-                       DeclSpace storey = this;
-                       while (storey != null && storey.CurrentTypeParameters == null)
-                               storey = storey.Parent;
-
-                       return storey as AnonymousMethodStorey;
-               }
-
                //
                // Returns a field which holds referenced storey instance
                //
@@ -499,7 +544,7 @@ namespace Mono.CSharp {
                        return f_ind;
                }
 
-               protected virtual string GetVariableMangledName (LocalInfo local_info)
+               protected virtual string GetVariableMangledName (LocalVariable local_info)
                {
                        //
                        // No need to mangle anonymous method hoisted variables cause they
@@ -512,15 +557,6 @@ namespace Mono.CSharp {
                        get { return hoisted_this; }
                }
 
-               public TypeParameterMutator Mutator {
-                       get {
-                               return mutator;
-                       }
-                       set {
-                               mutator = value;
-                       }
-               }
-
                public IList<ExplicitBlock> ReferencesFromChildrenBlock {
                        get { return children_references; }
                }
@@ -549,13 +585,13 @@ namespace Mono.CSharp {
 
                        public override Expression CreateExpressionTree (ResolveContext ec)
                        {
-                               throw new NotSupportedException ("ET");
+                               return hv.CreateExpressionTree ();
                        }
 
                        protected override Expression DoResolve (ResolveContext ec)
                        {
                                eclass = ExprClass.Value;
-                               type = TypeManager.expression_type_expr.Type;
+                               type = ec.Module.PredefinedTypes.Expression.Resolve ();
                                return this;
                        }
 
@@ -604,7 +640,7 @@ namespace Mono.CSharp {
                //
                // Creates field access expression for hoisted variable
                //
-               protected FieldExpr GetFieldExpression (EmitContext ec)
+               protected virtual FieldExpr GetFieldExpression (EmitContext ec)
                {
                        if (ec.CurrentAnonymousMethod == null || ec.CurrentAnonymousMethod.Storey == null) {
                                if (cached_outer_access != null)
@@ -724,8 +760,8 @@ namespace Mono.CSharp {
        {
                readonly string name;
 
-               public HoistedLocalVariable (AnonymousMethodStorey scope, LocalInfo local, string name)
-                       : base (scope, name, local.VariableType)
+               public HoistedLocalVariable (AnonymousMethodStorey scope, LocalVariable local, string name)
+                       : base (scope, name, local.Type)
                {
                        this.name = local.Name;
                }
@@ -795,7 +831,7 @@ namespace Mono.CSharp {
                }
 
                Dictionary<TypeSpec, Expression> compatibles;
-               public ToplevelBlock Block;
+               public ParametersBlock Block;
 
                public AnonymousMethodExpression (Location loc)
                {
@@ -832,12 +868,12 @@ namespace Mono.CSharp {
                        }
                }
 
-               protected TypeSpec CompatibleChecks (ResolveContext ec, TypeSpec delegate_type)
+               TypeSpec CompatibleChecks (ResolveContext ec, TypeSpec delegate_type)
                {
                        if (delegate_type.IsDelegate)
                                return delegate_type;
 
-                       if (delegate_type.IsGeneric && delegate_type.GetDefinition () == TypeManager.expression_type) {
+                       if (delegate_type.IsExpressionTreeType) {
                                delegate_type = delegate_type.TypeArguments [0];
                                if (delegate_type.IsDelegate)
                                        return delegate_type;
@@ -906,7 +942,7 @@ namespace Mono.CSharp {
                                if (TypeManager.HasElementType (type) && TypeManager.IsGenericParameter (TypeManager.GetElementType (type)))
                                        continue;
                                
-                               if (invoke_pd.Types [i] != Parameters.Types [i]) {
+                               if (!TypeSpecComparer.IsEqual (invoke_pd.Types [i], Parameters.Types [i])) {
                                        if (ignore_errors)
                                                return false;
                                        
@@ -930,7 +966,7 @@ namespace Mono.CSharp {
                                return false;
 
                        if (!delegate_type.IsDelegate) {
-                               if (delegate_type.GetDefinition () != TypeManager.expression_type)
+                               if (!delegate_type.IsExpressionTreeType)
                                        return false;
 
                                delegate_type = TypeManager.GetTypeArguments (delegate_type) [0];
@@ -938,7 +974,7 @@ namespace Mono.CSharp {
                                        return false;
                        }
                        
-                       AParametersCollection d_params = Delegate.GetParameters (ec.Compiler, delegate_type);
+                       AParametersCollection d_params = Delegate.GetParameters (delegate_type);
                        if (d_params.Count != Parameters.Count)
                                return false;
 
@@ -958,16 +994,24 @@ namespace Mono.CSharp {
 
                public TypeSpec InferReturnType (ResolveContext ec, TypeInferenceContext tic, TypeSpec delegate_type)
                {
+                       Expression expr;
                        AnonymousExpression am;
+
+                       if (compatibles.TryGetValue (delegate_type, out expr)) {
+                               am = expr as AnonymousExpression;
+                               return am == null ? null : am.ReturnType;
+                       }
+
                        using (ec.Set (ResolveContext.Options.ProbingMode | ResolveContext.Options.InferReturnType)) {
                                am = CompatibleMethodBody (ec, tic, InternalType.Arglist, delegate_type);
                                if (am != null)
                                        am = am.Compatible (ec);
                        }
-                       
+
                        if (am == null)
                                return null;
 
+//                     compatibles.Add (delegate_type, am);
                        return am.ReturnType;
                }
 
@@ -990,7 +1034,7 @@ namespace Mono.CSharp {
                        // needed for the anonymous method.  We create the method here.
                        //
 
-                       var invoke_mb = Delegate.GetInvokeMethod (ec.Compiler, delegate_type);
+                       var invoke_mb = Delegate.GetInvokeMethod (delegate_type);
                        TypeSpec return_type = invoke_mb.ReturnType;
 
                        //
@@ -1042,9 +1086,10 @@ namespace Mono.CSharp {
                        } catch (Exception e) {
                                throw new InternalErrorException (e, loc);
                        }
-                       
-                       if (!ec.IsInProbingMode)
-                               compatibles.Add (type, am == null ? EmptyExpression.Null : am);
+
+                       if (!ec.IsInProbingMode) {
+                               compatibles.Add (type, am ?? EmptyExpression.Null);
+                       }
 
                        return am;
                }
@@ -1062,7 +1107,7 @@ namespace Mono.CSharp {
 
                protected virtual ParametersCompiled ResolveParameters (ResolveContext ec, TypeInferenceContext tic, TypeSpec delegate_type)
                {
-                       var delegate_parameters = Delegate.GetParameters (ec.Compiler, delegate_type);
+                       var delegate_parameters = Delegate.GetParameters (delegate_type);
 
                        if (Parameters == ParametersCompiled.Undefined) {
                                //
@@ -1082,7 +1127,7 @@ namespace Mono.CSharp {
                                                return null;
                                        }
                                        fixedpars[i] = new Parameter (
-                                               null, null,
+                                               new TypeExpression (delegate_parameters.Types [i], loc), null,
                                                delegate_parameters.FixedParameters [i].ModFlags, null, loc);
                                }
 
@@ -1116,7 +1161,7 @@ namespace Mono.CSharp {
                        // 
                        type = InternalType.AnonymousMethod;
 
-                       if ((Parameters != null) && !Parameters.Resolve (ec))
+                       if (!DoResolveParameters (ec))
                                return null;
 
                        // FIXME: The emitted code isn't very careful about reachability
@@ -1128,6 +1173,11 @@ namespace Mono.CSharp {
                        return this;
                }
 
+               protected virtual bool DoResolveParameters (ResolveContext rc)
+               {
+                       return Parameters.Resolve (rc);
+               }
+
                public override void Emit (EmitContext ec)
                {
                        // nothing, as we only exist to not do anything.
@@ -1136,7 +1186,7 @@ namespace Mono.CSharp {
                public static void Error_AddressOfCapturedVar (ResolveContext ec, IVariableReference var, Location loc)
                {
                        ec.Report.Error (1686, loc,
-                               "Local variable or parameter `{0}' cannot have their address taken and be used inside an anonymous method or lambda expression",
+                               "Local variable or parameter `{0}' cannot have their address taken and be used inside an anonymous method, lambda expression or query expression",
                                var.Name);
                }
 
@@ -1151,13 +1201,13 @@ namespace Mono.CSharp {
                        if (p == null)
                                return null;
 
-                       ToplevelBlock b = ec.IsInProbingMode ? (ToplevelBlock) Block.PerformClone () : Block;
+                       ParametersBlock b = ec.IsInProbingMode ? (ParametersBlock) Block.PerformClone () : Block;
 
                        return CompatibleMethodFactory (return_type, delegate_type, p, b);
 
                }
 
-               protected virtual AnonymousMethodBody CompatibleMethodFactory (TypeSpec return_type, TypeSpec delegate_type, ParametersCompiled p, ToplevelBlock b)
+               protected virtual AnonymousMethodBody CompatibleMethodFactory (TypeSpec return_type, TypeSpec delegate_type, ParametersCompiled p, ParametersBlock b)
                {
                        return new AnonymousMethodBody (p, b, return_type, delegate_type, loc);
                }
@@ -1166,7 +1216,7 @@ namespace Mono.CSharp {
                {
                        AnonymousMethodExpression target = (AnonymousMethodExpression) t;
 
-                       target.Block = (ToplevelBlock) clonectx.LookupBlock (Block);
+                       target.Block = (ParametersBlock) clonectx.LookupBlock (Block);
                }
        }
 
@@ -1193,7 +1243,7 @@ namespace Mono.CSharp {
                                this.RealName = real_name;
 
                                Parent.PartialContainer.AddMethod (this);
-                               Block = am.Block;
+                               Block = new ToplevelBlock (am.block, parameters);
                        }
 
                        public override EmitContext CreateEmitContext (ILGenerator ig)
@@ -1246,13 +1296,13 @@ namespace Mono.CSharp {
                        }
                }
 
-               readonly ToplevelBlock block;
+               protected ParametersBlock block;
 
                public TypeSpec ReturnType;
 
                object return_label;
 
-               protected AnonymousExpression (ToplevelBlock block, TypeSpec return_type, Location loc)
+               protected AnonymousExpression (ParametersBlock block, TypeSpec return_type, Location loc)
                {
                        this.ReturnType = return_type;
                        this.block = block;
@@ -1270,15 +1320,19 @@ namespace Mono.CSharp {
 
                public AnonymousExpression Compatible (ResolveContext ec, AnonymousExpression ae)
                {
+                       if (block.Resolved)
+                               return this;
+
                        // TODO: Implement clone
-                       BlockContext aec = new BlockContext (ec.MemberContext, Block, ReturnType);
+                       BlockContext aec = new BlockContext (ec, block, ReturnType);
                        aec.CurrentAnonymousMethod = ae;
 
-                       IDisposable aec_dispose = null;
                        ResolveContext.Options flags = 0;
-                       if (ec.HasSet (ResolveContext.Options.InferReturnType)) {
-                               flags |= ResolveContext.Options.InferReturnType;
-                               aec.ReturnTypeInference = new TypeInferenceContext ();
+
+                       var am = this as AnonymousMethodBody;
+
+                       if (ec.HasSet (ResolveContext.Options.InferReturnType) && am != null) {
+                               am.ReturnTypeInference = new TypeInferenceContext ();
                        }
 
                        if (ec.IsInProbingMode)
@@ -1287,33 +1341,22 @@ namespace Mono.CSharp {
                        if (ec.HasSet (ResolveContext.Options.FieldInitializerScope))
                                flags |= ResolveContext.Options.FieldInitializerScope;
 
-                       if (ec.IsUnsafe)
-                               flags |= ResolveContext.Options.UnsafeScope;
-
-                       if (ec.HasSet (ResolveContext.Options.CheckedScope))
-                               flags |= ResolveContext.Options.CheckedScope;
-
                        if (ec.HasSet (ResolveContext.Options.ExpressionTreeConversion))
                                flags |= ResolveContext.Options.ExpressionTreeConversion;
 
-                       // HACK: Flag with 0 cannot be set 
-                       if (flags != 0)
-                               aec_dispose = aec.Set (flags);
+                       aec.Set (flags);
 
                        var errors = ec.Report.Errors;
 
-                       bool res = Block.Resolve (ec.CurrentBranching, aec, Block.Parameters, null);
+                       bool res = Block.Resolve (ec.CurrentBranching, aec, null);
 
                        if (aec.HasReturnLabel)
                                return_label = aec.ReturnLabel;
 
-                       if (ec.HasSet (ResolveContext.Options.InferReturnType)) {
-                               aec.ReturnTypeInference.FixAllTypes (ec);
-                               ReturnType = aec.ReturnTypeInference.InferredTypeArguments [0];
-                       }
-
-                       if (aec_dispose != null) {
-                               aec_dispose.Dispose ();
+                       if (am != null && am.ReturnTypeInference != null) {
+                               am.ReturnTypeInference.FixAllTypes (ec);
+                               ReturnType = am.ReturnTypeInference.InferredTypeArguments [0];
+                               am.ReturnTypeInference = null;
                        }
 
                        if (res && errors != ec.Report.Errors)
@@ -1324,22 +1367,20 @@ namespace Mono.CSharp {
 
                public void SetHasThisAccess ()
                {
-                       Block.HasCapturedThis = true;
-                       ExplicitBlock b = Block.Parent.Explicit;
-
-                       while (b != null) {
+                       ExplicitBlock b = block;
+                       do {
                                if (b.HasCapturedThis)
                                        return;
 
                                b.HasCapturedThis = true;
                                b = b.Parent == null ? null : b.Parent.Explicit;
-                       }
+                       } while (b != null);
                }
 
                //
                // The block that makes up the body for the anonymous method
                //
-               public ToplevelBlock Block {
+               public ParametersBlock Block {
                        get {
                                return block;
                        }
@@ -1355,11 +1396,12 @@ namespace Mono.CSharp {
                AnonymousMethodMethod method;
                Field am_cache;
                string block_name;
+               TypeInferenceContext return_inference;
 
                static int unique_id;
 
                public AnonymousMethodBody (ParametersCompiled parameters,
-                                       ToplevelBlock block, TypeSpec return_type, TypeSpec delegate_type,
+                                       ParametersBlock block, TypeSpec return_type, TypeSpec delegate_type,
                                        Location loc)
                        : base (block, return_type, loc)
                {
@@ -1367,17 +1409,30 @@ namespace Mono.CSharp {
                        this.parameters = parameters;
                }
 
+               #region Properties
+
                public override string ContainerType {
                        get { return "anonymous method"; }
                }
 
+               public override bool IsIterator {
+                       get { return false; }
+               }
+
+               public TypeInferenceContext ReturnTypeInference {
+                       get {
+                               return return_inference;
+                       }
+                       set {
+                               return_inference = value;
+                       }
+               }
+
                public override AnonymousMethodStorey Storey {
                        get { return storey; }
                }
 
-               public override bool IsIterator {
-                       get { return false; }
-               }
+               #endregion
 
                public override Expression CreateExpressionTree (ResolveContext ec)
                {
@@ -1436,7 +1491,7 @@ namespace Mono.CSharp {
                                var hoisted_tparams = ec.CurrentTypeParameters;
                                var type_params = new TypeParameter[hoisted_tparams.Length];
                                for (int i = 0; i < type_params.Length; ++i) {
-                                       type_params[i] = hoisted_tparams[i].CreateHoistedCopy (null);
+                                       type_params[i] = hoisted_tparams[i].CreateHoistedCopy (parent, null);
                                }
 
                                generic_method = new GenericMethod (parent.NamespaceEntry, parent, member_name, type_params,
@@ -1553,10 +1608,13 @@ namespace Mono.CSharp {
 
                                ec.Emit (OpCodes.Ldftn, TypeBuilder.GetMethod (t.GetMetaInfo (), (MethodInfo) delegate_method.GetMetaInfo ()));
                        } else {
+                               if (delegate_method.IsGeneric)
+                                       delegate_method = delegate_method.MakeGenericMethod (ec.MemberContext, method.TypeParameters);
+
                                ec.Emit (OpCodes.Ldftn, delegate_method);
                        }
 
-                       var constructor_method = Delegate.GetConstructor (ec.MemberContext.Compiler, ec.CurrentType, type);
+                       var constructor_method = Delegate.GetConstructor (type);
                        ec.Emit (OpCodes.Newobj, constructor_method);
 
                        if (am_cache != null) {
@@ -1599,45 +1657,54 @@ namespace Mono.CSharp {
        //
        public class AnonymousTypeClass : CompilerGeneratedClass
        {
-               sealed class AnonymousParameters : ParametersCompiled
-               {
-                       public AnonymousParameters (CompilerContext ctx, params Parameter[] parameters)
-                               : base (ctx, parameters)
-                       {
-                       }
-
-                       protected override void ErrorDuplicateName (Parameter p, Report Report)
-                       {
-                               Report.Error (833, p.Location, "`{0}': An anonymous type cannot have multiple properties with the same name",
-                                       p.Name);
-                       }
-               }
-
                static int types_counter;
                public const string ClassNamePrefix = "<>__AnonType";
                public const string SignatureForError = "anonymous type";
                
                readonly IList<AnonymousTypeParameter> parameters;
 
-               private AnonymousTypeClass (DeclSpace parent, MemberName name, IList<AnonymousTypeParameter> parameters, Location loc)
-                       : base (parent, name, (RootContext.EvalMode ? Modifiers.PUBLIC : 0) | Modifiers.SEALED)
+               private AnonymousTypeClass (TypeContainer parent, MemberName name, IList<AnonymousTypeParameter> parameters, Location loc)
+                       : base (parent, name, (parent.Module.Evaluator != null ? Modifiers.PUBLIC : 0) | Modifiers.SEALED)
                {
                        this.parameters = parameters;
                }
 
-               public static AnonymousTypeClass Create (CompilerContext ctx, TypeContainer parent, IList<AnonymousTypeParameter> parameters, Location loc)
+               public static AnonymousTypeClass Create (TypeContainer parent, IList<AnonymousTypeParameter> parameters, Location loc)
                {
                        string name = ClassNamePrefix + types_counter++;
 
-                       SimpleName [] t_args = new SimpleName [parameters.Count];
-                       TypeParameterName [] t_params = new TypeParameterName [parameters.Count];
-                       Parameter [] ctor_params = new Parameter [parameters.Count];
-                       for (int i = 0; i < parameters.Count; ++i) {
-                               AnonymousTypeParameter p = (AnonymousTypeParameter) parameters [i];
+                       ParametersCompiled all_parameters;
+                       TypeParameterName[] t_params;
+                       SimpleName[] t_args;
+
+                       if (parameters.Count == 0) {
+                               all_parameters = ParametersCompiled.EmptyReadOnlyParameters;
+                               t_params = new TypeParameterName[0];
+                               t_args = null;
+                       } else {
+                               t_args = new SimpleName[parameters.Count];
+                               t_params = new TypeParameterName[parameters.Count];
+                               Parameter[] ctor_params = new Parameter[parameters.Count];
+                               for (int i = 0; i < parameters.Count; ++i) {
+                                       AnonymousTypeParameter p = parameters[i];
+                                       for (int ii = 0; ii < i; ++ii) {
+                                               if (parameters[ii].Name == p.Name) {
+                                                       parent.Compiler.Report.Error (833, parameters[ii].Location,
+                                                               "`{0}': An anonymous type cannot have multiple properties with the same name",
+                                                                       p.Name);
+
+                                                       p = new AnonymousTypeParameter (null, "$" + i.ToString (), p.Location);
+                                                       parameters[i] = p;
+                                                       break;
+                                               }
+                                       }
+
+                                       t_args[i] = new SimpleName ("<" + p.Name + ">__T", p.Location);
+                                       t_params[i] = new TypeParameterName (t_args[i].Name, null, p.Location);
+                                       ctor_params[i] = new Parameter (t_args[i], p.Name, Parameter.Modifier.NONE, null, p.Location);
+                               }
 
-                               t_args [i] = new SimpleName ("<" + p.Name + ">__T", p.Location);
-                               t_params [i] = new TypeParameterName (t_args [i].Name, null, p.Location);
-                               ctor_params [i] = new Parameter (t_args [i], p.Name, 0, null, p.Location);
+                               all_parameters = new ParametersCompiled (ctor_params);
                        }
 
                        //
@@ -1651,15 +1718,15 @@ namespace Mono.CSharp {
                                a_type.SetParameterInfo (null);
 
                        Constructor c = new Constructor (a_type, name, Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN,
-                               null, new AnonymousParameters (ctx, ctor_params), null, loc);
-                       c.Block = new ToplevelBlock (ctx, c.ParameterInfo, loc);
+                               null, all_parameters, null, loc);
+                       c.Block = new ToplevelBlock (parent.Module.Compiler, c.ParameterInfo, loc);
 
                        // 
                        // Create fields and contructor body with field initialization
                        //
                        bool error = false;
                        for (int i = 0; i < parameters.Count; ++i) {
-                               AnonymousTypeParameter p = (AnonymousTypeParameter) parameters [i];
+                               AnonymousTypeParameter p = parameters [i];
 
                                Field f = new Field (a_type, t_args [i], Modifiers.PRIVATE | Modifiers.READONLY,
                                        new MemberName ("<" + p.Name + ">", p.Location), null);
@@ -1671,9 +1738,9 @@ namespace Mono.CSharp {
 
                                c.Block.AddStatement (new StatementExpression (
                                        new SimpleAssign (new MemberAccess (new This (p.Location), f.Name),
-                                               c.Block.GetParameterReference (p.Name, p.Location))));
+                                               c.Block.GetParameterReference (i, p.Location))));
 
-                               ToplevelBlock get_block = new ToplevelBlock (ctx, p.Location);
+                               ToplevelBlock get_block = new ToplevelBlock (parent.Module.Compiler, p.Location);
                                get_block.AddStatement (new Return (
                                        new MemberAccess (new This (p.Location), f.Name), p.Location));
 
@@ -1705,8 +1772,14 @@ namespace Mono.CSharp {
                                return true;
                        }
 
-                       Report.SymbolRelatedToPreviousError (mc);
-                       return false;
+                       // A conflict between anonymous type members will be reported
+                       if (symbol is TypeParameter) {
+                               Report.SymbolRelatedToPreviousError (symbol);
+                               return false;
+                       }
+
+                       // Ignore other conflicts
+                       return true;
                }
 
                protected override bool DoDefineMembers ()
@@ -1716,15 +1789,21 @@ namespace Mono.CSharp {
 
                        Location loc = Location;
 
-                       Method equals = new Method (this, null, new TypeExpression (TypeManager.bool_type, loc),
+                       var equals_parameters = ParametersCompiled.CreateFullyResolved (
+                               new Parameter (new TypeExpression (Compiler.BuiltinTypes.Object, loc), "obj", 0, null, loc), Compiler.BuiltinTypes.Object);
+
+                       Method equals = new Method (this, null, new TypeExpression (Compiler.BuiltinTypes.Bool, loc),
                                Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN, new MemberName ("Equals", loc),
-                               Mono.CSharp.ParametersCompiled.CreateFullyResolved (new Parameter (null, "obj", 0, null, loc), TypeManager.object_type), null);
+                               equals_parameters, null);
 
-                       Method tostring = new Method (this, null, new TypeExpression (TypeManager.string_type, loc),
+                       equals_parameters[0].Resolve (equals, 0);
+
+                       Method tostring = new Method (this, null, new TypeExpression (Compiler.BuiltinTypes.String, loc),
                                Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN, new MemberName ("ToString", loc),
                                Mono.CSharp.ParametersCompiled.EmptyReadOnlyParameters, null);
 
                        ToplevelBlock equals_block = new ToplevelBlock (Compiler, equals.ParameterInfo, loc);
+
                        TypeExpr current_type;
                        if (type_params != null) {
                                var targs = new TypeArguments ();
@@ -1736,15 +1815,16 @@ namespace Mono.CSharp {
                                current_type = new TypeExpression (Definition, loc);
                        }
 
-                       equals_block.AddVariable (current_type, "other", loc);
-                       LocalVariableReference other_variable = new LocalVariableReference (equals_block, "other", loc);
+                       var li_other = LocalVariable.CreateCompilerGenerated (CurrentType, equals_block, loc);
+                       equals_block.AddStatement (new BlockVariableDeclaration (new TypeExpression (li_other.Type, loc), li_other));
+                       var other_variable = new LocalVariableReference (li_other, loc);
 
                        MemberAccess system_collections_generic = new MemberAccess (new MemberAccess (
                                new QualifiedAliasMember ("global", "System", loc), "Collections", loc), "Generic", loc);
 
                        Expression rs_equals = null;
-                       Expression string_concat = new StringConstant ("{", loc);
-                       Expression rs_hashcode = new IntConstant (-2128831035, loc);
+                       Expression string_concat = new StringConstant (Compiler.BuiltinTypes, "{", loc);
+                       Expression rs_hashcode = new IntConstant (Compiler.BuiltinTypes, -2128831035, loc);
                        for (int i = 0; i < parameters.Count; ++i) {
                                var p = parameters [i];
                                var f = Fields [i];
@@ -1766,7 +1846,7 @@ namespace Mono.CSharp {
                                Expression field_hashcode = new Invocation (new MemberAccess (equality_comparer,
                                        "GetHashCode", loc), arguments_hashcode);
 
-                               IntConstant FNV_prime = new IntConstant (16777619, loc);                                
+                               IntConstant FNV_prime = new IntConstant (Compiler.BuiltinTypes, 16777619, loc);                         
                                rs_hashcode = new Binary (Binary.Operator.Multiply,
                                        new Binary (Binary.Operator.ExclusiveOr, rs_hashcode, field_hashcode, loc),
                                        FNV_prime, loc);
@@ -1775,14 +1855,14 @@ namespace Mono.CSharp {
                                        new MemberAccess (new This (f.Location), f.Name), new NullLiteral (loc), loc)),
                                        new Invocation (new MemberAccess (
                                                new MemberAccess (new This (f.Location), f.Name), "ToString"), null),
-                                       new StringConstant (string.Empty, loc), loc);
+                                       new StringConstant (Compiler.BuiltinTypes, string.Empty, loc), loc);
 
                                if (rs_equals == null) {
                                        rs_equals = field_equal;
                                        string_concat = new Binary (Binary.Operator.Addition,
                                                string_concat,
                                                new Binary (Binary.Operator.Addition,
-                                                       new StringConstant (" " + p.Name + " = ", loc),
+                                                       new StringConstant (Compiler.BuiltinTypes, " " + p.Name + " = ", loc),
                                                        field_to_string,
                                                        loc),
                                                loc);
@@ -1795,7 +1875,7 @@ namespace Mono.CSharp {
                                string_concat = new Binary (Binary.Operator.Addition,
                                        new Binary (Binary.Operator.Addition,
                                                string_concat,
-                                               new StringConstant (", " + p.Name + " = ", loc),
+                                               new StringConstant (Compiler.BuiltinTypes, ", " + p.Name + " = ", loc),
                                                loc),
                                        field_to_string,
                                        loc);
@@ -1805,16 +1885,16 @@ namespace Mono.CSharp {
 
                        string_concat = new Binary (Binary.Operator.Addition,
                                string_concat,
-                               new StringConstant (" }", loc),
+                               new StringConstant (Compiler.BuiltinTypes, " }", loc),
                                loc);
 
                        //
                        // Equals (object obj) override
                        //              
-                       LocalVariableReference other_variable_assign = new LocalVariableReference (equals_block, "other", loc);
+                       var other_variable_assign = new TemporaryVariableReference (li_other, loc);
                        equals_block.AddStatement (new StatementExpression (
                                new SimpleAssign (other_variable_assign,
-                                       new As (equals_block.GetParameterReference ("obj", loc),
+                                       new As (equals_block.GetParameterReference (0, loc),
                                                current_type, loc), loc)));
 
                        Expression equals_test = new Binary (Binary.Operator.Inequality, other_variable, new NullLiteral (loc), loc);
@@ -1829,7 +1909,7 @@ namespace Mono.CSharp {
                        //
                        // GetHashCode () override
                        //
-                       Method hashcode = new Method (this, null, new TypeExpression (TypeManager.int32_type, loc),
+                       Method hashcode = new Method (this, null, new TypeExpression (Compiler.BuiltinTypes.Int, loc),
                                Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN,
                                new MemberName ("GetHashCode", loc),
                                Mono.CSharp.ParametersCompiled.EmptyReadOnlyParameters, null);
@@ -1849,30 +1929,31 @@ namespace Mono.CSharp {
                        // hash += hash << 5;
 
                        ToplevelBlock hashcode_top = new ToplevelBlock (Compiler, loc);
-                       Block hashcode_block = new Block (hashcode_top);
+                       Block hashcode_block = new Block (hashcode_top, loc, loc);
                        hashcode_top.AddStatement (new Unchecked (hashcode_block, loc));
 
-                       hashcode_block.AddVariable (new TypeExpression (TypeManager.int32_type, loc), "hash", loc);
-                       LocalVariableReference hash_variable = new LocalVariableReference (hashcode_block, "hash", loc);
-                       LocalVariableReference hash_variable_assign = new LocalVariableReference (hashcode_block, "hash", loc);
+                       var li_hash = LocalVariable.CreateCompilerGenerated (Compiler.BuiltinTypes.Int, hashcode_top, loc);
+                       hashcode_block.AddStatement (new BlockVariableDeclaration (new TypeExpression (li_hash.Type, loc), li_hash));
+                       LocalVariableReference hash_variable_assign = new LocalVariableReference (li_hash, loc);
                        hashcode_block.AddStatement (new StatementExpression (
                                new SimpleAssign (hash_variable_assign, rs_hashcode)));
 
+                       var hash_variable = new LocalVariableReference (li_hash, loc);
                        hashcode_block.AddStatement (new StatementExpression (
                                new CompoundAssign (Binary.Operator.Addition, hash_variable,
-                                       new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (13, loc), loc), loc)));
+                                       new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (Compiler.BuiltinTypes, 13, loc), loc), loc)));
                        hashcode_block.AddStatement (new StatementExpression (
                                new CompoundAssign (Binary.Operator.ExclusiveOr, hash_variable,
-                                       new Binary (Binary.Operator.RightShift, hash_variable, new IntConstant (7, loc), loc), loc)));
+                                       new Binary (Binary.Operator.RightShift, hash_variable, new IntConstant (Compiler.BuiltinTypes, 7, loc), loc), loc)));
                        hashcode_block.AddStatement (new StatementExpression (
                                new CompoundAssign (Binary.Operator.Addition, hash_variable,
-                                       new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (3, loc), loc), loc)));
+                                       new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (Compiler.BuiltinTypes, 3, loc), loc), loc)));
                        hashcode_block.AddStatement (new StatementExpression (
                                new CompoundAssign (Binary.Operator.ExclusiveOr, hash_variable,
-                                       new Binary (Binary.Operator.RightShift, hash_variable, new IntConstant (17, loc), loc), loc)));
+                                       new Binary (Binary.Operator.RightShift, hash_variable, new IntConstant (Compiler.BuiltinTypes, 17, loc), loc), loc)));
                        hashcode_block.AddStatement (new StatementExpression (
                                new CompoundAssign (Binary.Operator.Addition, hash_variable,
-                                       new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (5, loc), loc), loc)));
+                                       new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (Compiler.BuiltinTypes, 5, loc), loc), loc)));
 
                        hashcode_block.AddStatement (new Return (hash_variable, loc));
                        hashcode.Block = hashcode_top;