EmitContext.cs 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  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, IEnumerable<Expression> arguments, MethodInfo method)
  98. {
  99. EmitLoad (local);
  100. EmitCollection (arguments);
  101. EmitCall (method);
  102. }
  103. public void EmitCall (Expression expression, IEnumerable<Expression> arguments, MethodInfo method)
  104. {
  105. if (!method.IsStatic)
  106. EmitLoad (expression);
  107. EmitCollection (arguments);
  108. EmitCall (method);
  109. }
  110. public void EmitCall (MethodInfo method)
  111. {
  112. ig.Emit (
  113. method.IsVirtual ? OpCodes.Callvirt : OpCodes.Call,
  114. method);
  115. }
  116. public void EmitCollection<T> (IEnumerable<T> collection) where T : Expression
  117. {
  118. foreach (var expression in collection)
  119. expression.Emit (this);
  120. }
  121. public void EmitCollection (IEnumerable<ElementInit> initializers, LocalBuilder local)
  122. {
  123. foreach (var initializer in initializers)
  124. initializer.Emit (this, local);
  125. }
  126. public void EmitCollection (IEnumerable<MemberBinding> bindings, LocalBuilder local)
  127. {
  128. foreach (var binding in bindings)
  129. binding.Emit (this, local);
  130. }
  131. public void EmitIsInst (Expression expression, Type candidate)
  132. {
  133. expression.Emit (this);
  134. if (expression.Type.IsValueType)
  135. ig.Emit (OpCodes.Box, expression.Type);
  136. ig.Emit (OpCodes.Isinst, candidate);
  137. }
  138. public void EmitScope ()
  139. {
  140. ig.Emit (OpCodes.Ldarg_0);
  141. }
  142. public void EmitReadGlobal (object global)
  143. {
  144. EmitReadGlobal (global, global.GetType ());
  145. }
  146. public void EmitReadGlobal (object global, Type type)
  147. {
  148. EmitScope ();
  149. ig.Emit (OpCodes.Ldfld, typeof (ExecutionScope).GetField ("Globals"));
  150. ig.Emit (OpCodes.Ldc_I4, AddGlobal (global, type));
  151. ig.Emit (OpCodes.Ldelem, typeof (object));
  152. var strongbox = type.MakeStrongBoxType ();
  153. ig.Emit (OpCodes.Isinst, strongbox);
  154. ig.Emit (OpCodes.Ldfld, strongbox.GetField ("Value"));
  155. }
  156. int AddGlobal (object value, Type type)
  157. {
  158. globals.Add (CreateStrongBox (value, type));
  159. return globals.Count - 1;
  160. }
  161. static object CreateStrongBox (object value, Type type)
  162. {
  163. return Activator.CreateInstance (
  164. type.MakeStrongBoxType (), value);
  165. }
  166. }
  167. class DynamicEmitContext : EmitContext {
  168. DynamicMethod method;
  169. static object mlock = new object ();
  170. static int method_count;
  171. public DynamicMethod Method {
  172. get { return method; }
  173. }
  174. public DynamicEmitContext (LambdaExpression lambda)
  175. : base (lambda)
  176. {
  177. // FIXME: Need to force this to be verifiable, see:
  178. // https://bugzilla.novell.com/show_bug.cgi?id=355005
  179. method = new DynamicMethod (GenerateName (), return_type, param_types, typeof (ExecutionScope), true);
  180. ig = method.GetILGenerator ();
  181. owner.Emit (this);
  182. }
  183. public override Delegate CreateDelegate ()
  184. {
  185. return method.CreateDelegate (owner.Type, new ExecutionScope (globals.ToArray ()));
  186. }
  187. static string GenerateName ()
  188. {
  189. lock (mlock) {
  190. return "lambda_method-" + (method_count++);
  191. }
  192. }
  193. }
  194. #if !NET_2_1
  195. class DebugEmitContext : DynamicEmitContext {
  196. public DebugEmitContext (LambdaExpression lambda)
  197. : base (lambda)
  198. {
  199. var name = Method.Name;
  200. var file_name = name + ".dll";
  201. var assembly = AppDomain.CurrentDomain.DefineDynamicAssembly (
  202. new AssemblyName (name), AssemblyBuilderAccess.RunAndSave, Path.GetTempPath ());
  203. var type = assembly.DefineDynamicModule (file_name, file_name).DefineType ("Linq", TypeAttributes.Public);
  204. var method = type.DefineMethod (name, MethodAttributes.Public | MethodAttributes.Static, return_type, param_types);
  205. ig = method.GetILGenerator ();
  206. owner.Emit (this);
  207. type.CreateType ();
  208. assembly.Save (file_name);
  209. }
  210. }
  211. #endif
  212. }