2007-06-06 Amit Biswas <amit@amitbiswas.com>
[mono.git] / mcs / mcs / lambda.cs
1 //
2 // lambda.cs: support for lambda expressions
3 //
4 // Authors: Miguel de Icaza (miguel@gnu.org)
5 //
6 // Licensed under the terms of the GNU GPL
7 //
8 // (C) 2007 Novell, Inc
9 //
10
11 using System;
12 using System.Collections;
13 using System.Reflection;
14 using System.Reflection.Emit;
15
16 namespace Mono.CSharp {
17         public class LambdaExpression : AnonymousMethodExpression {
18                 bool explicit_parameters;
19
20                 //
21                 // The parameter list can either be:
22                 //    null: no parameters
23                 //    arraylist of Parameter (explicitly typed parameters)
24                 //    arraylist of strings (implicitly typed parameters)
25                 //
26                 public LambdaExpression (AnonymousMethodExpression parent,
27                                          GenericMethod generic, TypeContainer host,
28                                          Parameters parameters, Block container,
29                                          Location loc)
30                         : base (parent, generic, host, parameters, container, loc)
31                 {
32                         explicit_parameters = (parameters != null && parameters.Count > 0 && parameters [0].TypeName != null);
33                         if (parameters == null)
34                                 Parameters = Parameters.EmptyReadOnlyParameters;
35                 }
36
37                 public bool HasImplicitParameters {
38                         get {
39                                 return !explicit_parameters;
40                         }
41                 }
42
43                 public bool HasExplicitParameters {
44                         get {
45                                 return explicit_parameters;
46                         }
47                 }
48                 
49                 public override Expression DoResolve (EmitContext ec)
50                 {
51                         eclass = ExprClass.Value;
52                         type = TypeManager.anonymous_method_type;
53
54                         if (explicit_parameters){
55                                 if (!Parameters.Resolve (ec))
56                                         return null;
57                         }
58                         
59                         // We will resolve parameters later, we do not
60                         // have information at this point.
61                         
62                         return this;
63                 }
64
65                 public override void Emit (EmitContext ec)
66                 {
67                         base.Emit (ec);
68                 }
69
70                 public override bool ImplicitStandardConversionExists (Type delegate_type)
71                 {
72                         EmitContext ec = EmitContext.TempEc;
73
74                         bool result;
75
76                         try {
77                                 Report.DisableErrors ();
78                                 result = DoCompatibleTest (ec, delegate_type, true) != null;
79                         } finally {
80                                 Report.EnableErrors ();
81                         }
82                         
83                         // Ignore the result
84                         anonymous = null;
85
86                         return result;
87                 }
88                 
89                 //
90                 // Returns true if this anonymous method can be implicitly
91                 // converted to the delegate type `delegate_type'
92                 //
93                 public override Expression Compatible (EmitContext ec, Type delegate_type)
94                 {
95                         return DoCompatibleTest (ec, delegate_type, false);
96                 }
97
98                 Expression DoCompatibleTest (EmitContext ec, Type delegate_type, bool clone)
99                 {
100                         if (anonymous != null)
101                                 return anonymous.AnonymousDelegate;
102
103                         if (CompatibleChecks (ec, delegate_type) == null)
104                                 return null;
105
106                         MethodGroupExpr invoke_mg = Delegate.GetInvokeMethod (
107                                 ec.ContainerType, delegate_type, loc);
108                         MethodInfo invoke_mb = (MethodInfo) invoke_mg.Methods [0];
109                         ParameterData invoke_pd = TypeManager.GetParameterData (invoke_mb);
110
111                         //
112                         // The lambda expression is compatible with the delegate type,
113                         // provided that:
114                         //
115
116                         //
117                         // D and L have the same number of arguments.
118                         if (Parameters.Count != invoke_pd.Count)
119                                 return null;
120
121                         if (explicit_parameters){
122                                 //
123                                 // If L has an explicitly typed parameter list, each parameter
124                                 // in D has the same type and modifiers as the corresponding
125                                 // parameter in L.
126                                 //
127                                 if (!VerifyExplicitParameterCompatibility (delegate_type, invoke_pd))
128                                         return null;
129                         } else {
130                                 //
131                                 // If L has an implicitly typed parameter list, D has no ref or
132                                 // out parameters
133                                 //
134                                 // Note: We currently do nothing, because the preview does not
135                                 // follow the above rule.
136
137                                 //
138                                 // each parameter of L is given the type of the corresponding parameter in D
139                                 //
140
141                                 for (int i = 0; i < invoke_pd.Count; i++)
142                                         Parameters [i].TypeName = new TypeExpression (
143                                                 invoke_pd.ParameterType (i),
144                                                 Parameters [i].Location);
145                         }
146
147                         return CoreCompatibilityTest (ec, clone, invoke_mb.ReturnType, delegate_type);
148                 }
149
150                 Expression CoreCompatibilityTest (EmitContext ec, bool clone, Type return_type, Type delegate_type)
151                 {
152                         //
153                         // The return type of the delegate must be compatible with 
154                         // the anonymous type.   Instead of doing a pass to examine the block
155                         // we satisfy the rule by setting the return type on the EmitContext
156                         // to be the delegate type return type.
157                         //
158
159                         ToplevelBlock b = clone ? (ToplevelBlock) Block.PerformClone () : Block;
160                         
161                         anonymous = new AnonymousMethod (
162                                 Parent != null ? Parent.AnonymousMethod : null, RootScope, Host,
163                                 GenericMethod, Parameters, Container, b, return_type,
164                                 delegate_type, loc);
165
166                         bool r;
167                         if (clone)
168                                 r = anonymous.ResolveNoDefine (ec);
169                         else
170                                 r = anonymous.Resolve (ec);
171
172                         // Resolution failed.
173                         if (!r)
174                                 return null;
175
176                         return anonymous.AnonymousDelegate;
177                 }
178                 
179                 //
180                 // TryBuild: tries to compile this LambdaExpression with the given
181                 // types as the lambda expression parameter types.   
182                 //
183                 // If the lambda expression successfully builds with those types, the
184                 // return value will be the inferred type for the lambda expression,
185                 // otherwise the result will be null.
186                 //
187                 public Type TryBuild (EmitContext ec, Type [] types)
188                 {
189                         for (int i = 0; i < types.Length; i++)
190                                 Parameters [i].TypeName = new TypeExpression (types [i], Parameters [i].Location);
191
192                         Expression e;
193                         try {
194                                 Report.DisableErrors ();
195                                 e = CoreCompatibilityTest (ec, true, null, null);
196                         } finally {
197                                 Report.EnableErrors ();
198                         }
199                         
200                         if (e == null)
201                                 return null;
202                         
203                         return e.Type;
204                 }
205         }
206
207         //
208         // This is a return statement that is prepended lambda expression bodies that happen
209         // to be expressions.  Depending on the return type of the delegate this will behave
210         // as either { expr (); return (); } or { return expr (); }
211         //
212         public class ContextualReturn : Statement {
213                 public Expression Expr;
214                 
215                 public ContextualReturn (Expression e)
216                 {
217                         Expr = e;
218                         loc = Expr.Location;
219                 }
220
221                 bool unwind_protect;
222
223                 public override bool Resolve (EmitContext ec)
224                 {
225                         AnonymousContainer am = ec.CurrentAnonymousMethod;
226                         if ((am != null) && am.IsIterator && ec.InIterator) {
227                                 Report.Error (1622, loc, "Cannot return a value from iterators. Use the yield return " +
228                                               "statement to return a value, or yield break to end the iteration");
229                                 return false;
230                         }
231
232                         Expr = Expr.Resolve (ec);
233                         if (Expr == null)
234                                 return false;
235
236                         if (ec.ReturnType == null){
237                                 ec.ReturnType = Expr.Type;
238                         } else {
239                                 if (Expr.Type != ec.ReturnType) {
240                                         Expression nExpr = Convert.ImplicitConversionRequired (
241                                                 ec, Expr, ec.ReturnType, loc);
242                                         if (nExpr == null){
243                                                 Report.Error (1662, loc, "Could not implicitly convert from {0} to {1}",
244                                                               TypeManager.CSharpName (Expr.Type),
245                                                               TypeManager.CSharpName (ec.ReturnType));
246                                                 return false;
247                                         }
248                                         Expr = nExpr;
249                                 }
250                         }
251
252                         int errors = Report.Errors;
253                         unwind_protect = ec.CurrentBranching.AddReturnOrigin (ec.CurrentBranching.CurrentUsageVector, loc);
254                         if (unwind_protect)
255                                 ec.NeedReturnLabel ();
256                         ec.CurrentBranching.CurrentUsageVector.Goto ();
257                         return errors == Report.Errors;
258                 }
259                 
260                 protected override void DoEmit (EmitContext ec)
261                 {
262                         Expr.Emit (ec);
263
264                         if (unwind_protect){
265                                 ec.ig.Emit (OpCodes.Stloc, ec.TemporaryReturn ());
266                                 ec.ig.Emit (OpCodes.Leave, ec.ReturnLabel);
267                         } 
268                         ec.ig.Emit (OpCodes.Ret);
269                 }
270
271                 protected override void CloneTo (CloneContext clonectx, Statement t)
272                 {
273                         ContextualReturn cr = (ContextualReturn) t;
274
275                         cr.Expr = Expr.Clone (clonectx);
276                 }
277         }
278 }