EmitContext.cs 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  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 Dictionary<object, int> indexes;
  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. EmitScope ();
  145. ig.Emit (OpCodes.Ldfld, typeof (ExecutionScope).GetField ("Globals"));
  146. int index;
  147. if (!indexes.TryGetValue (global, out index))
  148. throw new InvalidOperationException ();
  149. ig.Emit (OpCodes.Ldc_I4, index);
  150. ig.Emit (OpCodes.Ldelem, typeof (object));
  151. var type = global.GetType ().MakeStrongBoxType ();
  152. ig.Emit (OpCodes.Isinst, type);
  153. ig.Emit (OpCodes.Ldfld, type.GetField ("Value"));
  154. }
  155. }
  156. class GlobalCollector : ExpressionVisitor {
  157. List<object> globals = new List<object> ();
  158. Dictionary<object, int> indexes = new Dictionary<object,int> ();
  159. public List<object> Globals {
  160. get { return globals; }
  161. }
  162. public Dictionary<object, int> Indexes {
  163. get { return indexes; }
  164. }
  165. public GlobalCollector (Expression expression)
  166. {
  167. Visit (expression);
  168. }
  169. protected override void VisitConstant (ConstantExpression constant)
  170. {
  171. if (constant.Value == null)
  172. return;
  173. var value = constant.Value;
  174. var type = value.GetType ();
  175. if (Type.GetTypeCode (type) != TypeCode.Object)
  176. return;
  177. indexes.Add (value, globals.Count);
  178. globals.Add (CreateStrongBox (value, type));
  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. List<object> globals;
  189. static object mlock = new object ();
  190. static int method_count;
  191. public DynamicMethod Method {
  192. get { return method; }
  193. }
  194. public DynamicEmitContext (LambdaExpression lambda)
  195. : base (lambda)
  196. {
  197. // FIXME: Need to force this to be verifiable, see:
  198. // https://bugzilla.novell.com/show_bug.cgi?id=355005
  199. method = new DynamicMethod (GenerateName (), return_type, param_types, typeof (ExecutionScope), true);
  200. ig = method.GetILGenerator ();
  201. var collector = new GlobalCollector (lambda);
  202. globals = collector.Globals;
  203. indexes = collector.Indexes;
  204. owner.Emit (this);
  205. }
  206. public override Delegate CreateDelegate ()
  207. {
  208. return method.CreateDelegate (owner.Type, new ExecutionScope (globals.ToArray ()));
  209. }
  210. static string GenerateName ()
  211. {
  212. lock (mlock) {
  213. return "lambda_method-" + (method_count++);
  214. }
  215. }
  216. }
  217. #if !NET_2_1
  218. class DebugEmitContext : DynamicEmitContext {
  219. public DebugEmitContext (LambdaExpression lambda)
  220. : base (lambda)
  221. {
  222. var name = Method.Name;
  223. var file_name = name + ".dll";
  224. var assembly = AppDomain.CurrentDomain.DefineDynamicAssembly (
  225. new AssemblyName (name), AssemblyBuilderAccess.RunAndSave, Path.GetTempPath ());
  226. var type = assembly.DefineDynamicModule (file_name, file_name).DefineType ("Linq", TypeAttributes.Public);
  227. var method = type.DefineMethod (name, MethodAttributes.Public | MethodAttributes.Static, return_type, param_types);
  228. ig = method.GetILGenerator ();
  229. owner.Emit (this);
  230. type.CreateType ();
  231. assembly.Save (file_name);
  232. }
  233. }
  234. #endif
  235. }