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.Linq.Expressions;
19 using Microsoft.Scripting.Ast;
23 using Microsoft.Scripting.Runtime;
24 using Microsoft.Scripting.Utils;
25 using System.Reflection;
27 namespace Microsoft.Scripting.Ast {
28 public static partial class Utils {
30 /// Converts an expression to a void type.
32 /// <param name="expression">An <see cref="Expression"/> to convert to void. </param>
33 /// <returns>An <see cref="Expression" /> that has the <see cref="P:System.Linq.Expressions.Expression.NodeType" /> property equal to <see cref="F:System.Linq.Expressions.ExpressionType.ConvertChecked" /> and the <see cref="P:System.Linq.Expressions.UnaryExpression.Operand" /> and <see cref="P:System.Linq.Expressions.Expression.Type" /> property set to void.</returns>
34 public static Expression Void(Expression expression) {
35 ContractUtils.RequiresNotNull(expression, "expression");
36 if (expression.Type == typeof(void)) {
39 return Expression.Block(expression, Utils.Empty());
42 public static Expression Convert(Expression expression, Type type) {
43 ContractUtils.RequiresNotNull(expression, "expression");
45 if (expression.Type == type) {
49 if (expression.Type == typeof(void)) {
50 return Expression.Block(expression, Utils.Default(type));
53 if (type == typeof(void)) {
54 return Void(expression);
57 // TODO: this is not the right level for this to be at. It should
58 // be pushed into languages if they really want this behavior.
59 if (type == typeof(object)) {
60 return Box(expression);
63 return Expression.Convert(expression, type);
67 /// Returns an expression that boxes a given value. Uses boxed objects cache for Int32 and Boolean types.
69 public static Expression Box(Expression expression) {
71 if (expression.Type == typeof(int)) {
72 m = ScriptingRuntimeHelpers.Int32ToObjectMethod;
73 } else if (expression.Type == typeof(bool)) {
74 m = ScriptingRuntimeHelpers.BooleanToObjectMethod;
79 return Expression.Convert(expression, typeof(object), m);