2008-01-21 Miguel de Icaza <miguel@novell.com>
[mono.git] / mcs / class / System.Core / System.Linq.Expressions / LambdaExpression.cs
1 //
2 // LambdaExpression.cs
3 //
4 // Author:
5 //   Jb Evain (jbevain@novell.com)
6 //   Miguel de Icaza (miguel@novell.com)
7 //
8 // (C) 2008 Novell, Inc. (http://www.novell.com)
9 //
10 // Permission is hereby granted, free of charge, to any person obtaining
11 // a copy of this software and associated documentation files (the
12 // "Software"), to deal in the Software without restriction, including
13 // without limitation the rights to use, copy, modify, merge, publish,
14 // distribute, sublicense, and/or sell copies of the Software, and to
15 // permit persons to whom the Software is furnished to do so, subject to
16 // the following conditions:
17 //
18 // The above copyright notice and this permission notice shall be
19 // included in all copies or substantial portions of the Software.
20 //
21 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
22 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
23 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
24 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
25 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
26 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
27 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
28 //
29
30 using System;
31 using System.Collections.ObjectModel;
32 using System.Collections.Generic;
33 using System.Reflection;
34 using System.Reflection.Emit;
35 using System.Threading;
36
37 namespace System.Linq.Expressions {
38
39         internal class EmitContext {
40                 internal LambdaExpression Owner;
41                 internal Type [] ParamTypes;
42                 internal DynamicMethod Method;
43                 internal ILGenerator ig;
44
45                 // When debugging:
46                 internal AssemblyBuilder ab;
47                 internal TypeBuilder tb;
48                 internal MethodBuilder mb;
49                 
50                 static object mlock = new object ();
51                 static int method_count;
52                 static string GenName ()
53                 {
54                         lock (mlock){
55                                 return "<LINQ-" + method_count++ + ">";
56                         }
57                 }
58                 
59                 public EmitContext (LambdaExpression owner)
60                 {
61                         Owner = owner;
62
63                         ParamTypes = new Type [Owner.parameters.Count];
64                         for (int i = 0; i < Owner.parameters.Count; i++)
65                                 ParamTypes [i] = Owner.parameters [i].Type;
66
67                         //
68                         // We probably want to use the 3.5 new API calls to associate
69                         // the method with the "sandboxed" Assembly, instead am currently
70                         // dumping these types in this class
71                         //
72                         Type owner_of_code = typeof (EmitContext);
73
74
75                         //
76                         // FIXME: Need to force this to be verifiable, see:
77                         // https://bugzilla.novell.com/show_bug.cgi?id=355005
78                         //
79                         string name = GenName ();
80                         if (Environment.GetEnvironmentVariable ("LINQ_DBG") != null){
81                                 string fname = "linq" + (method_count-1) + ".dll";
82                                 ab = Thread.GetDomain ().DefineDynamicAssembly (new AssemblyName (fname),
83                                                                                 AssemblyBuilderAccess.RunAndSave, "/tmp");
84                                 ModuleBuilder b = ab.DefineDynamicModule (fname, fname);
85                                 tb = b.DefineType ("LINQ", TypeAttributes.Public);
86                                 mb = tb.DefineMethod ("A", MethodAttributes.Static, Owner.Type, ParamTypes);
87                                 ig = mb.GetILGenerator ();
88                         } else {
89                                 Method = new DynamicMethod (name, Owner.Type, ParamTypes, owner_of_code);
90                         
91                                 ig = Method.GetILGenerator ();
92                         }
93                 }
94
95                 internal Delegate CreateDelegate ()
96                 {
97                         if (ab != null){
98                                 tb.CreateType ();
99                                 ab.Save ("linq" + (method_count-1) + ".dll");
100
101                                 // This does not work, need to figure out why, for now
102                                 // makes debugging harder (only one linq file will work unless
103                                 // you do not compile them
104                                 Delegate d = Delegate.CreateDelegate (Owner.delegate_type, tb, mb, true);
105
106                                 ab = null;
107                                 tb = null;
108
109                                 //Console.WriteLine ("got: {0}", d);
110                                 return null;
111                         }
112                         return Method.CreateDelegate (Owner.delegate_type);                     
113                 }
114
115                 internal int GetParameterPosition (ParameterExpression p)
116                 {
117                         ReadOnlyCollection<ParameterExpression> pars = Owner.Parameters;
118                         
119                         for (int i = 0; i < pars.Count; i++){
120                                 if (pars [i] == p)
121                                         return i;
122                         }
123                         throw new InvalidOperationException ("Parameter not in scope");
124                 }
125         }
126         
127         public class LambdaExpression : Expression {
128
129                 //
130                 // LambdaExpression parameters
131                 //
132                 Expression body;
133                 internal ReadOnlyCollection<ParameterExpression> parameters;
134                 internal Type delegate_type;
135
136                 // This is set during compilation
137                 Delegate lambda_delegate;
138
139                 static bool CanAssign (Type target, Type source)
140                 {
141                         // This catches object and value type mixage, type compatibility is handled later
142                         if (target.IsValueType ^ source.IsValueType)
143                                 return false;
144                         
145                         return target.IsAssignableFrom (source);
146                 }
147                                 
148                 internal LambdaExpression (Type delegateType, Expression body, ReadOnlyCollection<ParameterExpression> parameters)
149                         : base (ExpressionType.Lambda, body.Type)
150                 {
151                         if (!delegateType.IsSubclassOf (typeof (System.Delegate))){
152                                 throw new ArgumentException ("delegateType");
153                         }
154                         
155                         MethodInfo [] invokes = delegateType.GetMethods (BindingFlags.Instance | BindingFlags.Public);
156                         MethodInfo invoke = null;
157                         foreach (MethodInfo m in invokes)
158                                 if (m.Name == "Invoke"){
159                                         invoke = m;
160                                         break;
161                                 }
162                         if (invoke == null)
163                                 throw new ArgumentException ("delegate must contain an Invoke method", "delegateType");
164
165                         ParameterInfo [] invoke_parameters = invoke.GetParameters ();
166                         if (invoke_parameters.Length != parameters.Count)
167                                 throw new ArgumentException ("Different number of arguments in delegate {0}", "delegateType");
168
169                         for (int i = 0; i < invoke_parameters.Length; i++){
170                                 if (!CanAssign (parameters [i].Type, invoke_parameters [i].ParameterType))
171                                         throw new ArgumentException (String.Format ("Can not assign a {0} to a {1}", invoke_parameters [i].ParameterType, parameters [i].Type));
172                         }
173
174                         if (!CanAssign (invoke.ReturnType, body.Type))
175                                 throw new ArgumentException (String.Format ("body type {0} can not be assigned to {1}", body.Type, invoke.ReturnType));
176                         
177                         this.body = body;
178                         this.parameters = parameters;
179                         delegate_type = delegateType;
180                 }
181                 
182                 public Expression Body {
183                         get { return body; }
184                 }
185
186                 public ReadOnlyCollection<ParameterExpression> Parameters {
187                         get { return parameters; }
188                 }
189
190                 internal override void Emit (EmitContext ec)
191                 {
192                         throw new NotImplementedException ();
193                 }
194                 
195                 public Delegate Compile ()
196                 {
197                         if (lambda_delegate == null){
198                                 EmitContext ec = new EmitContext (this);
199                                 
200                                 body.Emit (ec);
201
202                                 ec.ig.Emit (OpCodes.Ret);
203
204                                 lambda_delegate = ec.CreateDelegate ();
205                         }
206                         return lambda_delegate;
207                 }
208         }
209 }