2
0

EmitContext.cs 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. //
  2. // EmitContext.cs
  3. //
  4. // Author:
  5. // Miguel de Icaza ([email protected])
  6. // Jb Evain ([email protected])
  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. using System;
  30. using System.Collections.ObjectModel;
  31. using System.Collections.Generic;
  32. using System.IO;
  33. using System.Linq;
  34. using System.Reflection;
  35. using System.Reflection.Emit;
  36. using System.Runtime.CompilerServices;
  37. namespace System.Linq.Expressions {
  38. abstract class EmitContext {
  39. protected LambdaExpression owner;
  40. protected Type [] param_types;
  41. protected Type return_type;
  42. protected List<object> globals = new List<object> ();
  43. public ILGenerator ig;
  44. protected EmitContext (LambdaExpression lambda)
  45. {
  46. this.owner = lambda;
  47. param_types = CreateParameterTypes (owner.Parameters);
  48. return_type = owner.GetReturnType ();
  49. }
  50. static Type [] CreateParameterTypes (ReadOnlyCollection<ParameterExpression> parameters)
  51. {
  52. var types = new Type [parameters.Count + 1];
  53. types [0] = typeof (ExecutionScope);
  54. for (int i = 0; i < parameters.Count; i++)
  55. types [i + 1] = parameters [i].Type;
  56. return types;
  57. }
  58. public static EmitContext Create (LambdaExpression lambda)
  59. {
  60. #if !NET_2_1
  61. if (Environment.GetEnvironmentVariable ("LINQ_DBG") != null)
  62. return new DebugEmitContext (lambda);
  63. #endif
  64. return new DynamicEmitContext (lambda);
  65. }
  66. public int GetParameterPosition (ParameterExpression p)
  67. {
  68. int position = owner.Parameters.IndexOf (p);
  69. if (position == -1)
  70. throw new InvalidOperationException ("Parameter not in scope");
  71. return position + 1; // + 1 because 0 is the ExecutionScope
  72. }
  73. public abstract Delegate CreateDelegate ();
  74. public void Emit (Expression expression)
  75. {
  76. expression.Emit (this);
  77. }
  78. public LocalBuilder EmitStored (Expression expression)
  79. {
  80. var local = ig.DeclareLocal (expression.Type);
  81. expression.Emit (this);
  82. ig.Emit (OpCodes.Stloc, local);
  83. return local;
  84. }
  85. public void EmitLoad (Expression expression)
  86. {
  87. if (expression.Type.IsValueType) {
  88. var local = EmitStored (expression);
  89. ig.Emit (OpCodes.Ldloca, local);
  90. } else
  91. expression.Emit (this);
  92. }
  93. public void EmitLoad (LocalBuilder local)
  94. {
  95. ig.Emit (OpCodes.Ldloc, local);
  96. }
  97. public void EmitCall (LocalBuilder local, ReadOnlyCollection<Expression> arguments, MethodInfo method)
  98. {
  99. EmitLoad (local);
  100. EmitArguments (method, arguments);
  101. EmitCall (method);
  102. }
  103. public void EmitCall (Expression expression, MethodInfo method)
  104. {
  105. if (!method.IsStatic)
  106. EmitLoad (expression);
  107. EmitCall (method);
  108. }
  109. public void EmitCall (Expression expression, ReadOnlyCollection<Expression> arguments, MethodInfo method)
  110. {
  111. if (!method.IsStatic)
  112. EmitLoad (expression);
  113. EmitArguments (method, arguments);
  114. EmitCall (method);
  115. }
  116. void EmitArguments (MethodInfo method, ReadOnlyCollection<Expression> arguments)
  117. {
  118. var parameters = method.GetParameters ();
  119. for (int i = 0; i < parameters.Length; i++) {
  120. var parameter = parameters [i];
  121. var argument = arguments [i];
  122. if (parameter.ParameterType.IsByRef) {
  123. ig.Emit (OpCodes.Ldloca, EmitStored (argument));
  124. return;
  125. }
  126. Emit (arguments [i]);
  127. }
  128. }
  129. public void EmitCall (MethodInfo method)
  130. {
  131. ig.Emit (
  132. method.IsVirtual ? OpCodes.Callvirt : OpCodes.Call,
  133. method);
  134. }
  135. public void EmitCollection<T> (IEnumerable<T> collection) where T : Expression
  136. {
  137. foreach (var expression in collection)
  138. expression.Emit (this);
  139. }
  140. public void EmitCollection (IEnumerable<ElementInit> initializers, LocalBuilder local)
  141. {
  142. foreach (var initializer in initializers)
  143. initializer.Emit (this, local);
  144. }
  145. public void EmitCollection (IEnumerable<MemberBinding> bindings, LocalBuilder local)
  146. {
  147. foreach (var binding in bindings)
  148. binding.Emit (this, local);
  149. }
  150. public void EmitIsInst (Expression expression, Type candidate)
  151. {
  152. expression.Emit (this);
  153. if (expression.Type.IsValueType)
  154. ig.Emit (OpCodes.Box, expression.Type);
  155. ig.Emit (OpCodes.Isinst, candidate);
  156. }
  157. public void EmitScope ()
  158. {
  159. ig.Emit (OpCodes.Ldarg_0);
  160. }
  161. public void EmitReadGlobal (object global)
  162. {
  163. EmitReadGlobal (global, global.GetType ());
  164. }
  165. public void EmitReadGlobal (object global, Type type)
  166. {
  167. EmitScope ();
  168. ig.Emit (OpCodes.Ldfld, typeof (ExecutionScope).GetField ("Globals"));
  169. ig.Emit (OpCodes.Ldc_I4, AddGlobal (global, type));
  170. ig.Emit (OpCodes.Ldelem, typeof (object));
  171. var strongbox = type.MakeStrongBoxType ();
  172. ig.Emit (OpCodes.Isinst, strongbox);
  173. ig.Emit (OpCodes.Ldfld, strongbox.GetField ("Value"));
  174. }
  175. int AddGlobal (object value, Type type)
  176. {
  177. globals.Add (CreateStrongBox (value, type));
  178. return globals.Count - 1;
  179. }
  180. static object CreateStrongBox (object value, Type type)
  181. {
  182. return Activator.CreateInstance (
  183. type.MakeStrongBoxType (), value);
  184. }
  185. }
  186. class DynamicEmitContext : EmitContext {
  187. DynamicMethod method;
  188. public DynamicMethod Method {
  189. get { return method; }
  190. }
  191. public DynamicEmitContext (LambdaExpression lambda)
  192. : base (lambda)
  193. {
  194. // FIXME: Need to force this to be verifiable, see:
  195. // https://bugzilla.novell.com/show_bug.cgi?id=355005
  196. method = new DynamicMethod (GenerateName (), return_type, param_types, typeof (ExecutionScope), true);
  197. ig = method.GetILGenerator ();
  198. owner.EmitBody (this);
  199. }
  200. public override Delegate CreateDelegate ()
  201. {
  202. return method.CreateDelegate (owner.Type, new ExecutionScope (globals.ToArray ()));
  203. }
  204. protected virtual string GenerateName ()
  205. {
  206. return "lambda_method";
  207. }
  208. }
  209. #if !NET_2_1
  210. class DebugEmitContext : DynamicEmitContext {
  211. static object mlock = new object ();
  212. static int method_count;
  213. public DebugEmitContext (LambdaExpression lambda)
  214. : base (lambda)
  215. {
  216. var name = Method.Name;
  217. var file_name = name + ".dll";
  218. var assembly = AppDomain.CurrentDomain.DefineDynamicAssembly (
  219. new AssemblyName (name), AssemblyBuilderAccess.RunAndSave, Path.GetTempPath ());
  220. var type = assembly.DefineDynamicModule (file_name, file_name).DefineType ("Linq", TypeAttributes.Public);
  221. var method = type.DefineMethod (name, MethodAttributes.Public | MethodAttributes.Static, return_type, param_types);
  222. ig = method.GetILGenerator ();
  223. owner.EmitBody (this);
  224. type.CreateType ();
  225. assembly.Save (file_name);
  226. }
  227. protected override string GenerateName ()
  228. {
  229. lock (mlock) {
  230. return "lambda_method-" + (method_count++);
  231. }
  232. }
  233. }
  234. #endif
  235. }