1 /* ****************************************************************************
3 * Copyright (c) Microsoft Corporation.
5 * This source code is subject to terms and conditions of the Apache License, Version 2.0. A
6 * copy of the license can be found in the License.html file at the root of this distribution. If
7 * you cannot locate the Apache License, Version 2.0, please send an email to
8 * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
9 * by the terms of the Apache License, Version 2.0.
11 * You must not remove this notice, or any other, from this software.
14 * ***************************************************************************/
17 using System.Collections.Generic;
18 using System.Collections.ObjectModel;
19 using System.Diagnostics;
20 using System.Dynamic.Utils;
21 using System.Reflection;
22 using System.Reflection.Emit;
23 using System.Threading;
24 using System.Runtime.CompilerServices;
31 namespace Microsoft.Scripting.Ast {
33 namespace System.Linq.Expressions {
38 /// Creates a <see cref="LambdaExpression"/> node.
39 /// This captures a block of code that is similar to a .NET method body.
42 /// Lambda expressions take input through parameters and are expected to be fully bound.
45 [DebuggerTypeProxy(typeof(Expression.LambdaExpressionProxy))]
47 public abstract class LambdaExpression : Expression {
48 private readonly string _name;
49 private readonly Expression _body;
50 private readonly ReadOnlyCollection<ParameterExpression> _parameters;
51 private readonly Type _delegateType;
52 private readonly bool _tailCall;
54 internal LambdaExpression(
59 ReadOnlyCollection<ParameterExpression> parameters
62 Debug.Assert(delegateType != null);
66 _parameters = parameters;
67 _delegateType = delegateType;
72 /// Gets the static type of the expression that this <see cref="Expression" /> represents. (Inherited from <see cref="Expression"/>.)
74 /// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns>
75 public sealed override Type Type {
76 get { return _delegateType; }
80 /// Returns the node type of this <see cref="Expression" />. (Inherited from <see cref="Expression" />.)
82 /// <returns>The <see cref="ExpressionType"/> that represents this expression.</returns>
83 public sealed override ExpressionType NodeType {
84 get { return ExpressionType.Lambda; }
88 /// Gets the parameters of the lambda expression.
90 public ReadOnlyCollection<ParameterExpression> Parameters {
91 get { return _parameters; }
95 /// Gets the name of the lambda expression.
97 /// <remarks>Used for debugging purposes.</remarks>
103 /// Gets the body of the lambda expression.
105 public Expression Body {
106 get { return _body; }
110 /// Gets the return type of the lambda expression.
112 public Type ReturnType {
113 get { return Type.GetMethod("Invoke").ReturnType; }
117 /// Gets the value that indicates if the lambda expression will be compiled with
118 /// tail call optimization.
120 public bool TailCall {
121 get { return _tailCall; }
125 /// Produces a delegate that represents the lambda expression.
127 /// <returns>A delegate containing the compiled version of the lambda.</returns>
128 public Delegate Compile() {
129 return LambdaCompiler.Compile(this, null);
133 /// Produces a delegate that represents the lambda expression.
135 /// <param name="debugInfoGenerator">Debugging information generator used by the compiler to mark sequence points and annotate local variables.</param>
136 /// <returns>A delegate containing the compiled version of the lambda.</returns>
137 public Delegate Compile(DebugInfoGenerator debugInfoGenerator) {
138 ContractUtils.RequiresNotNull(debugInfoGenerator, "debugInfoGenerator");
139 return LambdaCompiler.Compile(this, debugInfoGenerator);
143 public Delegate Compile(bool preferInterpretation) {
144 // TODO: add logic for preferInterpretation
150 /// Compiles the lambda into a method definition.
152 /// <param name="method">A <see cref="MethodBuilder"/> which will be used to hold the lambda's IL.</param>
153 public void CompileToMethod(MethodBuilder method) {
154 CompileToMethodInternal(method, null);
158 /// Compiles the lambda into a method definition and custom debug information.
160 /// <param name="method">A <see cref="MethodBuilder"/> which will be used to hold the lambda's IL.</param>
161 /// <param name="debugInfoGenerator">Debugging information generator used by the compiler to mark sequence points and annotate local variables.</param>
162 public void CompileToMethod(MethodBuilder method, DebugInfoGenerator debugInfoGenerator) {
163 ContractUtils.RequiresNotNull(debugInfoGenerator, "debugInfoGenerator");
164 CompileToMethodInternal(method, debugInfoGenerator);
167 private void CompileToMethodInternal(MethodBuilder method, DebugInfoGenerator debugInfoGenerator) {
168 ContractUtils.RequiresNotNull(method, "method");
169 ContractUtils.Requires(method.IsStatic, "method");
170 var type = method.DeclaringType as TypeBuilder;
171 if (type == null) throw Error.MethodBuilderDoesNotHaveTypeBuilder();
173 LambdaCompiler.Compile(this, method, debugInfoGenerator);
176 internal abstract LambdaExpression Accept(StackSpiller spiller);
180 /// Defines a <see cref="Expression{TDelegate}"/> node.
181 /// This captures a block of code that is similar to a .NET method body.
183 /// <typeparam name="TDelegate">The type of the delegate.</typeparam>
185 /// Lambda expressions take input through parameters and are expected to be fully bound.
187 public sealed class Expression<TDelegate> : LambdaExpression {
188 internal Expression(Expression body, string name, bool tailCall, ReadOnlyCollection<ParameterExpression> parameters)
189 : base(typeof(TDelegate), name, body, tailCall, parameters) {
193 /// Produces a delegate that represents the lambda expression.
195 /// <returns>A delegate containing the compiled version of the lambda.</returns>
196 public new TDelegate Compile() {
197 return (TDelegate)(object)LambdaCompiler.Compile(this, null);
201 /// Produces a delegate that represents the lambda expression.
203 /// <param name="debugInfoGenerator">Debugging information generator used by the compiler to mark sequence points and annotate local variables.</param>
204 /// <returns>A delegate containing the compiled version of the lambda.</returns>
205 public new TDelegate Compile(DebugInfoGenerator debugInfoGenerator) {
206 ContractUtils.RequiresNotNull(debugInfoGenerator, "debugInfoGenerator");
207 return (TDelegate)(object)LambdaCompiler.Compile(this, debugInfoGenerator);
211 public new TDelegate Compile(bool preferInterpretation) {
212 // TODO: add logic for preferInterpretation
218 /// Creates a new expression that is like this one, but using the
219 /// supplied children. If all of the children are the same, it will
220 /// return this expression.
222 /// <param name="body">The <see cref="LambdaExpression.Body">Body</see> property of the result.</param>
223 /// <param name="parameters">The <see cref="LambdaExpression.Parameters">Parameters</see> property of the result.</param>
224 /// <returns>This expression if no children changed, or an expression with the updated children.</returns>
225 public Expression<TDelegate> Update(Expression body, IEnumerable<ParameterExpression> parameters) {
226 if (body == Body && parameters == Parameters) {
229 return Expression.Lambda<TDelegate>(body, Name, TailCall, parameters);
233 /// Dispatches to the specific visit method for this node type.
235 protected internal override Expression Accept(ExpressionVisitor visitor) {
236 return visitor.VisitLambda(this);
239 internal override LambdaExpression Accept(StackSpiller spiller) {
240 return spiller.Rewrite(this);
243 internal static LambdaExpression Create(Expression body, string name, bool tailCall, ReadOnlyCollection<ParameterExpression> parameters) {
244 return new Expression<TDelegate>(body, name, tailCall, parameters);
249 public partial class Expression {
252 /// Creates an Expression{T} given the delegate type. Caches the
253 /// factory method to speed up repeated creations for the same T.
255 internal static LambdaExpression CreateLambda(Type delegateType, Expression body, string name, bool tailCall, ReadOnlyCollection<ParameterExpression> parameters) {
256 // Get or create a delegate to the public Expression.Lambda<T>
257 // method and call that will be used for creating instances of this
259 LambdaFactory fastPath;
260 var factories = _LambdaFactories;
261 if (factories == null) {
262 _LambdaFactories = factories = new CacheDict<Type, LambdaFactory>(50);
265 MethodInfo create = null;
266 if (!factories.TryGetValue(delegateType, out fastPath)) {
267 create = typeof(Expression<>).MakeGenericType(delegateType).GetMethod("Create", BindingFlags.Static | BindingFlags.NonPublic);
268 if (TypeUtils.CanCache(delegateType)) {
269 factories[delegateType] = fastPath = (LambdaFactory)Delegate.CreateDelegate(typeof(LambdaFactory), create);
273 if (fastPath != null) {
274 return fastPath(body, name, tailCall, parameters);
277 Debug.Assert(create != null);
278 return (LambdaExpression)create.Invoke(null, new object[] { body, name, tailCall, parameters });
282 /// Creates an <see cref="Expression{TDelegate}"/> where the delegate type is known at compile time.
284 /// <typeparam name="TDelegate">The delegate type. </typeparam>
285 /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
286 /// <param name="parameters">An array that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
287 /// <returns>An <see cref="Expression{TDelegate}"/> that has the <see cref="P:NodeType"/> property equal to <see cref="P:Lambda"/> and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
288 public static Expression<TDelegate> Lambda<TDelegate>(Expression body, params ParameterExpression[] parameters) {
289 return Lambda<TDelegate>(body, false, (IEnumerable<ParameterExpression>)parameters);
293 /// Creates an <see cref="Expression{TDelegate}"/> where the delegate type is known at compile time.
295 /// <typeparam name="TDelegate">The delegate type. </typeparam>
296 /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
297 /// <param name="tailCall">A <see cref="Boolean"/> that indicates if tail call optimization will be applied when compiling the created expression. </param>
298 /// <param name="parameters">An array that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
299 /// <returns>An <see cref="Expression{TDelegate}"/> that has the <see cref="P:NodeType"/> property equal to <see cref="P:Lambda"/> and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
300 public static Expression<TDelegate> Lambda<TDelegate>(Expression body, bool tailCall, params ParameterExpression[] parameters) {
301 return Lambda<TDelegate>(body, tailCall, (IEnumerable<ParameterExpression>)parameters);
305 /// Creates an <see cref="Expression{TDelegate}"/> where the delegate type is known at compile time.
307 /// <typeparam name="TDelegate">The delegate type. </typeparam>
308 /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
309 /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
310 /// <returns>An <see cref="Expression{TDelegate}"/> that has the <see cref="P:NodeType"/> property equal to <see cref="P:Lambda"/> and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
311 public static Expression<TDelegate> Lambda<TDelegate>(Expression body, IEnumerable<ParameterExpression> parameters) {
312 return Lambda<TDelegate>(body, null, false, parameters);
316 /// Creates an <see cref="Expression{TDelegate}"/> where the delegate type is known at compile time.
318 /// <typeparam name="TDelegate">The delegate type. </typeparam>
319 /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
320 /// <param name="tailCall">A <see cref="Boolean"/> that indicates if tail call optimization will be applied when compiling the created expression. </param>
321 /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
322 /// <returns>An <see cref="Expression{TDelegate}"/> that has the <see cref="P:NodeType"/> property equal to <see cref="P:Lambda"/> and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
323 public static Expression<TDelegate> Lambda<TDelegate>(Expression body, bool tailCall, IEnumerable<ParameterExpression> parameters) {
324 return Lambda<TDelegate>(body, null, tailCall, parameters);
328 /// Creates an <see cref="Expression{TDelegate}"/> where the delegate type is known at compile time.
330 /// <typeparam name="TDelegate">The delegate type. </typeparam>
331 /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
332 /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
333 /// <param name="name">The name of the lambda. Used for generating debugging info.</param>
334 /// <returns>An <see cref="Expression{TDelegate}"/> that has the <see cref="P:NodeType"/> property equal to <see cref="P:Lambda"/> and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
335 public static Expression<TDelegate> Lambda<TDelegate>(Expression body, String name, IEnumerable<ParameterExpression> parameters) {
336 return Lambda<TDelegate>(body, name, false, parameters);
340 /// Creates an <see cref="Expression{TDelegate}"/> where the delegate type is known at compile time.
342 /// <typeparam name="TDelegate">The delegate type. </typeparam>
343 /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
344 /// <param name="name">The name of the lambda. Used for generating debugging info.</param>
345 /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
346 /// <param name="tailCall">A <see cref="Boolean"/> that indicates if tail call optimization will be applied when compiling the created expression. </param>
347 /// <returns>An <see cref="Expression{TDelegate}"/> that has the <see cref="P:NodeType"/> property equal to <see cref="P:Lambda"/> and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
348 public static Expression<TDelegate> Lambda<TDelegate>(Expression body, String name, bool tailCall, IEnumerable<ParameterExpression> parameters) {
349 var parameterList = parameters.ToReadOnly();
350 ValidateLambdaArgs(typeof(TDelegate), ref body, parameterList);
351 return new Expression<TDelegate>(body, name, tailCall, parameterList);
356 /// Creates a LambdaExpression by first constructing a delegate type.
358 /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
359 /// <param name="parameters">An array that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
360 /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
361 public static LambdaExpression Lambda(Expression body, params ParameterExpression[] parameters) {
362 return Lambda(body, false, (IEnumerable<ParameterExpression>)parameters);
366 /// Creates a LambdaExpression by first constructing a delegate type.
368 /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
369 /// <param name="tailCall">A <see cref="Boolean"/> that indicates if tail call optimization will be applied when compiling the created expression. </param>
370 /// <param name="parameters">An array that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
371 /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
372 public static LambdaExpression Lambda(Expression body, bool tailCall, params ParameterExpression[] parameters) {
373 return Lambda(body, tailCall, (IEnumerable<ParameterExpression>)parameters);
377 /// Creates a LambdaExpression by first constructing a delegate type.
379 /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
380 /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
381 /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
382 public static LambdaExpression Lambda(Expression body, IEnumerable<ParameterExpression> parameters) {
383 return Lambda(body, null, false, parameters);
387 /// Creates a LambdaExpression by first constructing a delegate type.
389 /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
390 /// <param name="tailCall">A <see cref="Boolean"/> that indicates if tail call optimization will be applied when compiling the created expression. </param>
391 /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
392 /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
393 public static LambdaExpression Lambda(Expression body, bool tailCall, IEnumerable<ParameterExpression> parameters) {
394 return Lambda(body, null, tailCall, parameters);
398 /// Creates a LambdaExpression by first constructing a delegate type.
400 /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
401 /// <param name="parameters">An array that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
402 /// <param name="delegateType">A <see cref="Type"/> representing the delegate signature for the lambda.</param>
403 /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
404 public static LambdaExpression Lambda(Type delegateType, Expression body, params ParameterExpression[] parameters) {
405 return Lambda(delegateType, body, null, false, parameters);
409 /// Creates a LambdaExpression by first constructing a delegate type.
411 /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
412 /// <param name="tailCall">A <see cref="Boolean"/> that indicates if tail call optimization will be applied when compiling the created expression. </param>
413 /// <param name="parameters">An array that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
414 /// <param name="delegateType">A <see cref="Type"/> representing the delegate signature for the lambda.</param>
415 /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
416 public static LambdaExpression Lambda(Type delegateType, Expression body, bool tailCall, params ParameterExpression[] parameters) {
417 return Lambda(delegateType, body, null, tailCall, parameters);
421 /// Creates a LambdaExpression by first constructing a delegate type.
423 /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
424 /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
425 /// <param name="delegateType">A <see cref="Type"/> representing the delegate signature for the lambda.</param>
426 /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
427 public static LambdaExpression Lambda(Type delegateType, Expression body, IEnumerable<ParameterExpression> parameters) {
428 return Lambda(delegateType, body, null, false, parameters);
432 /// Creates a LambdaExpression by first constructing a delegate type.
434 /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
435 /// <param name="tailCall">A <see cref="Boolean"/> that indicates if tail call optimization will be applied when compiling the created expression. </param>
436 /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
437 /// <param name="delegateType">A <see cref="Type"/> representing the delegate signature for the lambda.</param>
438 /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
439 public static LambdaExpression Lambda(Type delegateType, Expression body, bool tailCall, IEnumerable<ParameterExpression> parameters) {
440 return Lambda(delegateType, body, null, tailCall, parameters);
444 /// Creates a LambdaExpression by first constructing a delegate type.
446 /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
447 /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
448 /// <param name="name">The name for the lambda. Used for emitting debug information.</param>
449 /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
450 public static LambdaExpression Lambda(Expression body, string name, IEnumerable<ParameterExpression> parameters) {
451 return Lambda(body, name, false, parameters);
455 /// Creates a LambdaExpression by first constructing a delegate type.
457 /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
458 /// <param name="name">The name for the lambda. Used for emitting debug information.</param>
459 /// <param name="tailCall">A <see cref="Boolean"/> that indicates if tail call optimization will be applied when compiling the created expression. </param>
460 /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
461 /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
462 public static LambdaExpression Lambda(Expression body, string name, bool tailCall, IEnumerable<ParameterExpression> parameters) {
463 ContractUtils.RequiresNotNull(body, "body");
465 var parameterList = parameters.ToReadOnly();
467 int paramCount = parameterList.Count;
468 Type[] typeArgs = new Type[paramCount + 1];
469 if (paramCount > 0) {
470 var set = new Set<ParameterExpression>(parameterList.Count);
471 for (int i = 0; i < paramCount; i++) {
472 var param = parameterList[i];
473 ContractUtils.RequiresNotNull(param, "parameter");
474 typeArgs[i] = param.IsByRef ? param.Type.MakeByRefType() : param.Type;
475 if (set.Contains(param)) {
476 throw Error.DuplicateVariable(param);
481 typeArgs[paramCount] = body.Type;
483 Type delegateType = DelegateHelpers.MakeDelegateType(typeArgs);
485 return CreateLambda(delegateType, body, name, tailCall, parameterList);
489 /// Creates a LambdaExpression by first constructing a delegate type.
491 /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
492 /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
493 /// <param name="name">The name for the lambda. Used for emitting debug information.</param>
494 /// <param name="delegateType">A <see cref="Type"/> representing the delegate signature for the lambda.</param>
495 /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
496 public static LambdaExpression Lambda(Type delegateType, Expression body, string name, IEnumerable<ParameterExpression> parameters) {
497 var paramList = parameters.ToReadOnly();
498 ValidateLambdaArgs(delegateType, ref body, paramList);
500 return CreateLambda(delegateType, body, name, false, paramList);
504 /// Creates a LambdaExpression by first constructing a delegate type.
506 /// <param name="delegateType">A <see cref="Type"/> representing the delegate signature for the lambda.</param>
507 /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
508 /// <param name="name">The name for the lambda. Used for emitting debug information.</param>
509 /// <param name="tailCall">A <see cref="Boolean"/> that indicates if tail call optimization will be applied when compiling the created expression. </param>
510 /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
511 /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
512 public static LambdaExpression Lambda(Type delegateType, Expression body, string name, bool tailCall, IEnumerable<ParameterExpression> parameters) {
513 var paramList = parameters.ToReadOnly();
514 ValidateLambdaArgs(delegateType, ref body, paramList);
516 return CreateLambda(delegateType, body, name, tailCall, paramList);
519 private static void ValidateLambdaArgs(Type delegateType, ref Expression body, ReadOnlyCollection<ParameterExpression> parameters) {
520 ContractUtils.RequiresNotNull(delegateType, "delegateType");
521 RequiresCanRead(body, "body");
523 if (!typeof(MulticastDelegate).IsAssignableFrom(delegateType) || delegateType == typeof(MulticastDelegate)) {
524 throw Error.LambdaTypeMustBeDerivedFromSystemDelegate();
528 var ldc = _LambdaDelegateCache;
529 if (!ldc.TryGetValue(delegateType, out mi)) {
530 mi = delegateType.GetMethod("Invoke");
531 if (TypeUtils.CanCache(delegateType)) {
532 ldc[delegateType] = mi;
536 ParameterInfo[] pis = mi.GetParametersCached();
538 if (pis.Length > 0) {
539 if (pis.Length != parameters.Count) {
540 throw Error.IncorrectNumberOfLambdaDeclarationParameters();
542 var set = new Set<ParameterExpression>(pis.Length);
543 for (int i = 0, n = pis.Length; i < n; i++) {
544 ParameterExpression pex = parameters[i];
545 ParameterInfo pi = pis[i];
546 RequiresCanRead(pex, "parameters");
547 Type pType = pi.ParameterType;
549 if (!pType.IsByRef) {
550 //We cannot pass a parameter of T& to a delegate that takes T or any non-ByRef type.
551 throw Error.ParameterExpressionNotValidAsDelegate(pex.Type.MakeByRefType(), pType);
553 pType = pType.GetElementType();
555 if (!TypeUtils.AreReferenceAssignable(pex.Type, pType)) {
556 throw Error.ParameterExpressionNotValidAsDelegate(pex.Type, pType);
558 if (set.Contains(pex)) {
559 throw Error.DuplicateVariable(pex);
563 } else if (parameters.Count > 0) {
564 throw Error.IncorrectNumberOfLambdaDeclarationParameters();
566 if (mi.ReturnType != typeof(void) && !TypeUtils.AreReferenceAssignable(mi.ReturnType, body.Type)) {
567 if (!TryQuote(mi.ReturnType, ref body)) {
568 throw Error.ExpressionTypeDoesNotMatchReturn(body.Type, mi.ReturnType);
573 private static bool ValidateTryGetFuncActionArgs(Type[] typeArgs) {
574 if (typeArgs == null) {
575 throw new ArgumentNullException("typeArgs");
577 for (int i = 0, n = typeArgs.Length; i < n; i++) {
580 throw new ArgumentNullException("typeArgs");
590 /// Creates a <see cref="Type"/> object that represents a generic System.Func delegate type that has specific type arguments.
591 /// The last type argument specifies the return type of the created delegate.
593 /// <param name="typeArgs">An array of Type objects that specify the type arguments for the System.Func delegate type.</param>
594 /// <returns>The type of a System.Func delegate that has the specified type arguments.</returns>
595 public static Type GetFuncType(params Type[] typeArgs) {
596 if (!ValidateTryGetFuncActionArgs(typeArgs)) throw Error.TypeMustNotBeByRef();
598 Type result = DelegateHelpers.GetFuncType(typeArgs);
599 if (result == null) {
600 throw Error.IncorrectNumberOfTypeArgsForFunc();
606 /// Creates a <see cref="Type"/> object that represents a generic System.Func delegate type that has specific type arguments.
607 /// The last type argument specifies the return type of the created delegate.
609 /// <param name="typeArgs">An array of Type objects that specify the type arguments for the System.Func delegate type.</param>
610 /// <param name="funcType">When this method returns, contains the generic System.Func delegate type that has specific type arguments. Contains null if there is no generic System.Func delegate that matches the <paramref name="typeArgs"/>.This parameter is passed uninitialized.</param>
611 /// <returns>true if generic System.Func delegate type was created for specific <paramref name="typeArgs"/>; false otherwise.</returns>
612 public static bool TryGetFuncType(Type[] typeArgs, out Type funcType) {
613 if (ValidateTryGetFuncActionArgs(typeArgs)) {
614 return (funcType = DelegateHelpers.GetFuncType(typeArgs)) != null;
621 /// Creates a <see cref="Type"/> object that represents a generic System.Action delegate type that has specific type arguments.
623 /// <param name="typeArgs">An array of Type objects that specify the type arguments for the System.Action delegate type.</param>
624 /// <returns>The type of a System.Action delegate that has the specified type arguments.</returns>
625 public static Type GetActionType(params Type[] typeArgs) {
626 if (!ValidateTryGetFuncActionArgs(typeArgs)) throw Error.TypeMustNotBeByRef();
628 Type result = DelegateHelpers.GetActionType(typeArgs);
629 if (result == null) {
630 throw Error.IncorrectNumberOfTypeArgsForAction();
636 /// Creates a <see cref="Type"/> object that represents a generic System.Action delegate type that has specific type arguments.
638 /// <param name="typeArgs">An array of Type objects that specify the type arguments for the System.Action delegate type.</param>
639 /// <param name="actionType">When this method returns, contains the generic System.Action delegate type that has specific type arguments. Contains null if there is no generic System.Action delegate that matches the <paramref name="typeArgs"/>.This parameter is passed uninitialized.</param>
640 /// <returns>true if generic System.Action delegate type was created for specific <paramref name="typeArgs"/>; false otherwise.</returns>
641 public static bool TryGetActionType(Type[] typeArgs, out Type actionType) {
642 if (ValidateTryGetFuncActionArgs(typeArgs)) {
643 return (actionType = DelegateHelpers.GetActionType(typeArgs)) != null;
650 /// Gets a <see cref="Type"/> object that represents a generic System.Func or System.Action delegate type that has specific type arguments.
651 /// The last type argument determines the return type of the delegate. If no Func or Action is large enough, it will generate a custom
654 /// <param name="typeArgs">The type arguments of the delegate.</param>
655 /// <returns>The delegate type.</returns>
657 /// As with Func, the last argument is the return type. It can be set
658 /// to System.Void to produce an Action.</remarks>
659 public static Type GetDelegateType(params Type[] typeArgs) {
660 ContractUtils.RequiresNotEmpty(typeArgs, "typeArgs");
661 ContractUtils.RequiresNotNullItems(typeArgs, "typeArgs");
662 return DelegateHelpers.MakeDelegateType(typeArgs);