2008-08-08 Marek Safar <marek.safar@gmail.com>
[mono.git] / mcs / mcs / delegate.cs
index 6997ff98f65c6e73e1121b67c9f2dba5fa72428b..e0065e2dd7cb548de7776aa8168e08827799693a 100644 (file)
@@ -6,10 +6,10 @@
 //     Miguel de Icaza (miguel@ximian.com)
 //     Marek Safar (marek.safar@gmail.com)
 //
-// Licensed under the terms of the GNU GPL
-//
-// (C) 2001 Ximian, Inc (http://www.ximian.com)
+// Dual licensed under the terms of the MIT X11 or GNU GPL
 //
+// Copyright 2001 Ximian, Inc (http://www.ximian.com)
+// Copyright 2003-2008 Novell, Inc (http://www.ximian.com)
 //
 
 using System;
@@ -25,7 +25,7 @@ namespace Mono.CSharp {
        /// </summary>
        public class Delegate : DeclSpace, IMemberContainer
        {
-               public Expression ReturnType;
+               FullNamedExpression ReturnType;
                public Parameters      Parameters;
 
                public ConstructorBuilder ConstructorBuilder;
@@ -42,7 +42,10 @@ namespace Mono.CSharp {
                ReturnParameter return_attributes;
 
                MemberCache member_cache;
-       
+
+               const MethodAttributes mattr = MethodAttributes.Public | MethodAttributes.HideBySig |
+                       MethodAttributes.Virtual | MethodAttributes.NewSlot;
+
                const int AllowedModifiers =
                        Modifiers.NEW |
                        Modifiers.PUBLIC |
@@ -51,7 +54,7 @@ namespace Mono.CSharp {
                        Modifiers.UNSAFE |
                        Modifiers.PRIVATE;
 
-               public Delegate (NamespaceEntry ns, DeclSpace parent, Expression type,
+               public Delegate (NamespaceEntry ns, DeclSpace parent, FullNamedExpression type,
                                 int mod_flags, MemberName name, Parameters param_list,
                                 Attributes attrs)
                        : base (ns, parent, name, attrs)
@@ -82,18 +85,6 @@ namespace Mono.CSharp {
                        if (TypeBuilder != null)
                                return TypeBuilder;
 
-                       if (TypeManager.multicast_delegate_type == null && !RootContext.StdLib) {
-                               Namespace system = RootNamespace.Global.GetNamespace ("System", true);
-                               TypeExpr expr = system.Lookup (this, "MulticastDelegate", Location) as TypeExpr;
-                               TypeManager.multicast_delegate_type = expr.Type;
-                       }
-
-                       if (TypeManager.multicast_delegate_type == null)
-                               Report.Error (-100, Location, "Internal error: delegate used before " +
-                                             "System.MulticastDelegate is resolved.  This can only " +
-                                             "happen during corlib compilation, when using a delegate " +
-                                             "in any of the `core' classes.  See bug #72015 for details.");
-
                        if (IsTopLevel) {
                                if (TypeManager.NamespaceClash (Name, Location))
                                        return null;
@@ -211,11 +202,12 @@ namespace Mono.CSharp {
 
                        // Check accessibility
                        foreach (Type partype in Parameters.Types){
-                               if (!Parent.AsAccessible (partype, ModFlags)) {
+                               if (!IsAccessibleAs (partype)) {
+                                       Report.SymbolRelatedToPreviousError (partype);
                                        Report.Error (59, Location,
                                                      "Inconsistent accessibility: parameter type `" +
                                                      TypeManager.CSharpName (partype) + "' is less " +
-                                                     "accessible than delegate `" + Name + "'");
+                                                         "accessible than delegate `" + GetSignatureForError () + "'");
                                        return false;
                                }
                        }
@@ -226,14 +218,17 @@ namespace Mono.CSharp {
 
                        ret_type = ReturnType.Type;
             
-                       if (!Parent.AsAccessible (ret_type, ModFlags)) {
+                       if (!IsAccessibleAs (ret_type)) {
+                               Report.SymbolRelatedToPreviousError (ret_type);
                                Report.Error (58, Location,
                                              "Inconsistent accessibility: return type `" +
                                              TypeManager.CSharpName (ret_type) + "' is less " +
-                                             "accessible than delegate `" + Name + "'");
+                                             "accessible than delegate `" + GetSignatureForError () + "'");
                                return false;
                        }
 
+                       CheckProtectedModifier ();
+
                        if (RootContext.StdLib && (ret_type == TypeManager.arg_iterator_type || ret_type == TypeManager.typed_reference_type)) {
                                Method.Error1599 (Location, ret_type);
                                return false;
@@ -246,8 +241,6 @@ namespace Mono.CSharp {
                        
                        CallingConventions cc = Parameters.CallingConvention;
 
-                       const MethodAttributes mattr = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual | MethodAttributes.NewSlot;
-
                        InvokeBuilder = TypeBuilder.DefineMethod ("Invoke", 
                                                                  mattr,                     
                                                                  cc,
@@ -259,14 +252,22 @@ namespace Mono.CSharp {
                        TypeManager.RegisterMethod (InvokeBuilder, Parameters);
                        member_cache.AddMember (InvokeBuilder, this);
 
+                       if (TypeManager.iasyncresult_type != null && TypeManager.asynccallback_type != null) {
+                               DefineAsyncMethods (cc);
+                       }
+
+                       return true;
+               }
+
+               void DefineAsyncMethods (CallingConventions cc)
+               {
                        //
                        // BeginInvoke
                        //
-                       
-                       Parameters async_parameters = Parameters.MergeGenerated (Parameters, 
+                       Parameters async_parameters = Parameters.MergeGenerated (Parameters,
                                new Parameter (TypeManager.asynccallback_type, "callback", Parameter.Modifier.NONE, null, Location),
                                new Parameter (TypeManager.object_type, "object", Parameter.Modifier.NONE, null, Location));
-                       
+
                        BeginInvokeBuilder = TypeBuilder.DefineMethod ("BeginInvoke",
                                mattr, cc, TypeManager.iasyncresult_type, async_parameters.Types);
 
@@ -292,27 +293,26 @@ namespace Mono.CSharp {
 
                        if (out_params > 0) {
                                Type [] end_param_types = new Type [out_params];
-                               Parameter [] end_params = new Parameter [out_params ];
+                               Parameter [] end_params = new Parameter [out_params];
 
-                               int param = 0; 
+                               int param = 0;
                                for (int i = 0; i < Parameters.FixedParameters.Length; ++i) {
                                        Parameter p = Parameters.FixedParameters [i];
                                        if ((p.ModFlags & Parameter.Modifier.ISBYREF) == 0)
                                                continue;
 
-                                       end_param_types [param] = p.ExternalType();
+                                       end_param_types [param] = p.ExternalType ();
                                        end_params [param] = p;
                                        ++param;
                                }
                                end_parameters = Parameters.CreateFullyResolved (end_params, end_param_types);
-                       }
-                       else {
+                       } else {
                                end_parameters = Parameters.EmptyReadOnlyParameters;
                        }
 
                        end_parameters = Parameters.MergeGenerated (end_parameters,
                                new Parameter (TypeManager.iasyncresult_type, "result", Parameter.Modifier.NONE, null, Location));
-                       
+
                        //
                        // Create method, define parameters, register parameters with type system
                        //
@@ -322,16 +322,16 @@ namespace Mono.CSharp {
                        end_parameters.ApplyAttributes (EndInvokeBuilder);
                        TypeManager.RegisterMethod (EndInvokeBuilder, end_parameters);
                        member_cache.AddMember (EndInvokeBuilder, this);
-
-                       return true;
                }
 
                public override void Emit ()
                {
                        Parameters.ApplyAttributes (InvokeBuilder);
 
-                       Parameters p = (Parameters)TypeManager.GetParameterData (BeginInvokeBuilder);
-                       p.ApplyAttributes (BeginInvokeBuilder);
+                       if (BeginInvokeBuilder != null) {
+                               Parameters p = (Parameters) TypeManager.GetParameterData (BeginInvokeBuilder);
+                               p.ApplyAttributes (BeginInvokeBuilder);
+                       }
 
                        if (OptAttributes != null) {
                                OptAttributes.Emit ();
@@ -364,7 +364,8 @@ namespace Mono.CSharp {
                        Parameters.VerifyClsCompliance ();
 
                        if (!AttributeTester.IsClsCompliant (ReturnType.Type)) {
-                               Report.Error (3002, Location, "Return type of `{0}' is not CLS-compliant", GetSignatureForError ());
+                               Report.Warning (3002, 1, Location, "Return type of `{0}' is not CLS-compliant",
+                                       GetSignatureForError ());
                        }
                        return true;
                }
@@ -446,20 +447,23 @@ namespace Mono.CSharp {
                        return (MethodInfo) mg.Methods[0];
                }
 
+               //
+               // 15.2 Delegate compatibility
+               //
                public static bool IsTypeCovariant (Expression a, Type b)
                {
-                       Type a_type = a.Type;
-                       if (a_type == b)
+                       //
+                       // For each value parameter (a parameter with no ref or out modifier), an 
+                       // identity conversion or implicit reference conversion exists from the
+                       // parameter type in D to the corresponding parameter type in M
+                       //
+                       if (a.Type == b)
                                return true;
 
                        if (RootContext.Version == LanguageVersion.ISO_1)
                                return false;
 
-                       if (a.Type.IsValueType)
-                               return false;
-
-                       return Convert.ImplicitReferenceConversionCore (
-                               a, b);
+                       return Convert.ImplicitReferenceConversionExists (a, b);
                }
                
                /// <summary>
@@ -467,10 +471,12 @@ namespace Mono.CSharp {
                ///  Returns the method itself if okay and null if not.
                /// </summary>
                public static MethodBase VerifyMethod (Type container_type, Type delegate_type,
-                                                      MethodGroupExpr old_mg, MethodBase mb,
-                                                      Location loc)
+                                                      MethodGroupExpr old_mg, MethodBase mb)
                {
                        MethodInfo invoke_mb = GetInvokeMethod (container_type, delegate_type);
+                       if (invoke_mb == null)
+                               return null;
+
                        ParameterData invoke_pd = TypeManager.GetParameterData (invoke_mb);
 
 #if GMCS_SOURCE
@@ -510,7 +516,7 @@ namespace Mono.CSharp {
 
                        Type invoke_mb_retval = ((MethodInfo) invoke_mb).ReturnType;
                        Type mb_retval = ((MethodInfo) mb).ReturnType;
-                       if (invoke_mb_retval == mb_retval)
+                       if (TypeManager.TypeToCoreType (invoke_mb_retval) == TypeManager.TypeToCoreType (mb_retval))
                                return mb;
 
                        //if (!IsTypeCovariant (mb_retval, invoke_mb_retval))
@@ -562,7 +568,7 @@ namespace Mono.CSharp {
                        }
 
                        return me.VerifyArgumentsCompat (
-                                       ec, args, arg_count, mb, 
+                                       ec, ref args, arg_count, mb, 
                                        is_params_applicable || (!is_applicable && params_method),
                                        false, loc);
                }
@@ -652,12 +658,12 @@ namespace Mono.CSharp {
        public abstract class DelegateCreation : Expression, MethodGroupExpr.IErrorHandler
        {
                protected ConstructorInfo constructor_method;
-               protected MethodBase delegate_method;
+               protected MethodInfo delegate_method;
                // We keep this to handle IsBase only
                protected MethodGroupExpr method_group;
                protected Expression delegate_instance_expression;
 
-               ArrayList CreateDelegateMethodArguments (MethodInfo invoke_method)
+               public static ArrayList CreateDelegateMethodArguments (MethodInfo invoke_method, Location loc)
                {
                        ParameterData pd = TypeManager.GetParameterData (invoke_method);
                        ArrayList delegate_arguments = new ArrayList (pd.Count);
@@ -674,8 +680,8 @@ namespace Mono.CSharp {
                                                atype = atype.GetElementType ();
                                                break;
                                        case Parameter.Modifier.ARGLIST:
-                                               // TODO: investigate and test
-                                               throw new NotImplementedException ();
+                                               // __arglist is not valid
+                                               throw new InternalErrorException ("__arglist modifier");
                                        default:
                                                atype_modifier = Argument.AType.Expression;
                                                break;
@@ -685,6 +691,25 @@ namespace Mono.CSharp {
                        return delegate_arguments;
                }
 
+               public override Expression CreateExpressionTree (EmitContext ec)
+               {
+                       MemberAccess ma = new MemberAccess (new MemberAccess (new QualifiedAliasMember ("global", "System", loc), "Delegate", loc), "CreateDelegate", loc);
+
+                       ArrayList args = new ArrayList (3);
+                       args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
+                       args.Add (new Argument (new NullLiteral (loc)));
+                       args.Add (new Argument (new TypeOfMethodInfo (delegate_method, loc)));
+                       Expression e = new Invocation (ma, args).Resolve (ec);
+                       if (e == null)
+                               return null;
+
+                       e = Convert.ExplicitConversion (ec, e, type, loc);
+                       if (e == null)
+                               return null;
+
+                       return e.CreateExpressionTree (ec);
+               }
+
                public override Expression DoResolve (EmitContext ec)
                {
                        constructor_method = Delegate.GetConstructor (ec.ContainerType, type);
@@ -692,21 +717,28 @@ namespace Mono.CSharp {
                        MethodInfo invoke_method = Delegate.GetInvokeMethod (ec.ContainerType, type);
                        method_group.DelegateType = type;
                        method_group.CustomErrorHandler = this;
-                       method_group = method_group.OverloadResolve (ec, CreateDelegateMethodArguments (invoke_method), false, loc);
+
+                       ArrayList arguments = CreateDelegateMethodArguments (invoke_method, loc);
+                       method_group = method_group.OverloadResolve (ec, ref arguments, false, loc);
                        if (method_group == null)
                                return null;
 
                        delegate_method = (MethodInfo) method_group;
-                       if (method_group is ExtensionMethodGroupExpr) {
-                               ParameterData p = TypeManager.GetParameterData (delegate_method);
-                               if (p.ExtensionMethodType.IsValueType) {
+                       Invocation.IsSpecialMethodInvocation (delegate_method, loc);
+
+                       ExtensionMethodGroupExpr emg = method_group as ExtensionMethodGroupExpr;
+                       if (emg != null) {
+                               delegate_instance_expression = emg.ExtensionExpression;
+                               Type e_type = delegate_instance_expression.Type;
+                               if (TypeManager.IsValueType (e_type)) {
                                        Report.Error (1113, loc, "Extension method `{0}' of value type `{1}' cannot be used to create delegates",
-                                               TypeManager.CSharpSignature (delegate_method), TypeManager.CSharpName (p.ExtensionMethodType));
+                                               TypeManager.CSharpSignature (delegate_method), TypeManager.CSharpName (e_type));
                                }
                        }
 
-                       Expression ret_expr = new TypeExpression (((MethodInfo) delegate_method).ReturnType, loc);
-                       if (!Delegate.IsTypeCovariant (ret_expr, (invoke_method.ReturnType))) {
+                       Type rt = TypeManager.TypeToCoreType (delegate_method.ReturnType);
+                       Expression ret_expr = new TypeExpression (rt, loc);
+                       if (!Delegate.IsTypeCovariant (ret_expr, (TypeManager.TypeToCoreType (invoke_method.ReturnType)))) {
                                Error_ConversionFailed (ec, delegate_method, ret_expr);
                        }
 
@@ -722,20 +754,22 @@ namespace Mono.CSharp {
                        //
                        if (delegate_instance_expression != null)
                                return;
-                       
-                       if (method_group.InstanceExpression != null)
+
+                       if (method_group.InstanceExpression != null) {
                                delegate_instance_expression = method_group.InstanceExpression;
-                       else if (!ec.IsStatic)
+                               Type instance_type = delegate_instance_expression.Type;
+                               if (TypeManager.IsValueType (instance_type) || TypeManager.IsGenericParameter (instance_type)) {
+                                       delegate_instance_expression = new BoxedCast (
+                                               delegate_instance_expression, TypeManager.object_type);
+                               }
+                       } else if (!delegate_method.IsStatic && !ec.IsStatic) {
                                delegate_instance_expression = ec.GetThis (loc);
-
-                       if (delegate_instance_expression != null && delegate_instance_expression.Type.IsValueType)
-                               delegate_instance_expression = new BoxedCast (
-                                       delegate_instance_expression, TypeManager.object_type);
+                       }
                }
                
                public override void Emit (EmitContext ec)
                {
-                       if (delegate_instance_expression == null || delegate_method.IsStatic)
+                       if (delegate_instance_expression == null)
                                ec.ig.Emit (OpCodes.Ldnull);
                        else
                                delegate_instance_expression.Emit (ec);
@@ -776,14 +810,26 @@ namespace Mono.CSharp {
 
                public static MethodBase ImplicitStandardConversionExists (MethodGroupExpr mg, Type target_type)
                {
+                       if (target_type == TypeManager.delegate_type || target_type == TypeManager.multicast_delegate_type)
+                               return null;
+
                        foreach (MethodInfo mi in mg.Methods){
-                               MethodBase mb = Delegate.VerifyMethod (mg.DeclaringType, target_type, mg, mi, Location.Null);
+                               MethodBase mb = Delegate.VerifyMethod (mg.DeclaringType, target_type, mg, mi);
                                if (mb != null)
                                        return mb;
                        }
                        return null;
                }
 
+               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
+               {
+                       if (delegate_instance_expression != null)
+                               delegate_instance_expression.MutateHoistedGenericType (storey);
+
+                       delegate_method = storey.MutateGenericMethod (delegate_method);
+                       constructor_method = storey.MutateConstructor (constructor_method);
+               }
+
                #region IErrorHandler Members
 
                public bool NoExactMatch (EmitContext ec, MethodBase method)
@@ -845,12 +891,15 @@ namespace Mono.CSharp {
                        Argument a = (Argument) Arguments [0];
                        if (!a.ResolveMethodGroup (ec))
                                return null;
-                       
+
                        Expression e = a.Expr;
-                       if (e is AnonymousMethodExpression && RootContext.Version != LanguageVersion.ISO_1) {
-                               e = ((AnonymousMethodExpression) e).Compatible (ec, type);
+
+                       AnonymousMethodExpression ame = e as AnonymousMethodExpression;
+                       if (ame != null && RootContext.Version != LanguageVersion.ISO_1) {
+                               e = ame.Compatible (ec, type);
                                if (e == null)
                                        return null;
+
                                return e.Resolve (ec);
                        }
 
@@ -877,7 +926,7 @@ namespace Mono.CSharp {
                                        TypeManager.GetFullNameSignature (delegate_method));
                        }
 
-                       if (Invocation.IsMethodExcluded (delegate_method)) {
+                       if (Invocation.IsMethodExcluded (delegate_method, loc)) {
                                Report.SymbolRelatedToPreviousError (delegate_method);
                                Report.Error (1618, loc, "Cannot create delegate with `{0}' because it has a Conditional attribute",
                                        TypeManager.CSharpSignature (delegate_method));
@@ -897,7 +946,7 @@ namespace Mono.CSharp {
                readonly Expression InstanceExpr;
                readonly ArrayList  Arguments;
 
-               MethodBase method;
+               MethodInfo method;
                
                public DelegateInvocation (Expression instance_expr, ArrayList args, Location loc)
                {
@@ -905,34 +954,31 @@ namespace Mono.CSharp {
                        this.Arguments = args;
                        this.loc = loc;
                }
+               
+               public override Expression CreateExpressionTree (EmitContext ec)
+               {
+                       ArrayList args;
+                       if (Arguments == null)
+                               args = new ArrayList (1);
+                       else
+                               args = new ArrayList (Arguments.Count + 1);
+
+                       args.Add (new Argument (InstanceExpr.CreateExpressionTree (ec)));
+                       if (Arguments != null) {
+                               foreach (Argument a in Arguments)
+                                       args.Add (new Argument (a.Expr.CreateExpressionTree (ec)));
+                       }
+
+                       return CreateExpressionFactoryCall ("Invoke", args);
+               }
 
                public override Expression DoResolve (EmitContext ec)
                {
                        if (InstanceExpr is EventExpr) {
-                               
-                               EventInfo ei = ((EventExpr) InstanceExpr).EventInfo;
-                               
-                               Expression ml = MemberLookup (
-                                       ec.ContainerType, ec.ContainerType, ei.Name,
-                                       MemberTypes.Event, AllBindingFlags | BindingFlags.DeclaredOnly, loc);
-
-                               if (ml == null) {
-                                       //
-                                       // If this is the case, then the Event does not belong 
-                                       // to this Type and so, according to the spec
-                                       // cannot be accessed directly
-                                       //
-                                       // Note that target will not appear as an EventExpr
-                                       // in the case it is being referenced within the same type container;
-                                       // it will appear as a FieldExpr in that case.
-                                       //
-                                       
-                                       Assign.error70 (ei, loc);
-                                       return null;
-                               }
+                               ((EventExpr) InstanceExpr).Error_CannotAssign ();
+                               return null;
                        }
                        
-                       
                        Type del_type = InstanceExpr.Type;
                        if (del_type == null)
                                return null;
@@ -948,7 +994,7 @@ namespace Mono.CSharp {
                                return null;
 
                        method = Delegate.GetInvokeMethod (ec.ContainerType, del_type);
-                       type = ((MethodInfo) method).ReturnType;
+                       type = TypeManager.TypeToCoreType (method.ReturnType);
                        eclass = ExprClass.Value;
                        
                        return this;
@@ -969,12 +1015,22 @@ namespace Mono.CSharp {
                        // 
                        // Pop the return value if there is one
                        //
-                       if (method is MethodInfo){
-                               Type ret = ((MethodInfo)method).ReturnType;
-                               if (TypeManager.TypeToCoreType (ret) != TypeManager.void_type)
-                                       ec.ig.Emit (OpCodes.Pop);
-                       }
+                       if (type != TypeManager.void_type)
+                               ec.ig.Emit (OpCodes.Pop);
                }
 
+               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
+               {
+                       method = storey.MutateGenericMethod (method);
+                       type = storey.MutateType (type);
+
+                       if (Arguments != null) {
+                               foreach (Argument a in Arguments) {
+                                       a.Expr.MutateHoistedGenericType (storey);
+                               }
+                       }
+
+                       InstanceExpr.MutateHoistedGenericType (storey);
+               }
        }
 }