xronos /Microsoft.Scripting/Actions/RuleBuilder.cs

Language C# Lines 308
MD5 Hash 24ee23809d41a5595fabfed10d45dcb9 Estimated Cost $5,353 (why?)
Repository https://bitbucket.org/stefanrusek/xronos View Raw File
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
/* ****************************************************************************
 *
 * Copyright (c) Microsoft Corporation. 
 *
 * This source code is subject to terms and conditions of the Microsoft Public License. A 
 * copy of the license can be found in the License.html file at the root of this distribution. If 
 * you cannot locate the  Microsoft Public License, please send an email to 
 * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound 
 * by the terms of the Microsoft Public License.
 *
 * You must not remove this notice, or any other, from this software.
 *
 *
 * ***************************************************************************/

#if CODEPLEX_40
using System;
#else
using System; using Microsoft;
#endif
using System.Collections.Generic;
using System.Collections.ObjectModel;
#if CODEPLEX_40
using System.Linq.Expressions;
#else
using Microsoft.Linq.Expressions;
#endif
using System.Reflection;
#if CODEPLEX_40
using System.Dynamic;
#else
using Microsoft.Scripting;
#endif
using Microsoft.Contracts;
using Microsoft.Scripting.Generation;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
using AstUtils = Microsoft.Scripting.Ast.Utils;

namespace Microsoft.Scripting.Actions {
#if CODEPLEX_40
    using Ast = System.Linq.Expressions.Expression;
#else
    using Ast = Microsoft.Linq.Expressions.Expression;
#endif

    /// <summary>
    /// Rule Builder
    /// 
    /// A rule is the mechanism that LanguageBinders use to specify both what code to execute (the Target)
    /// for a particular action on a particular set of objects, but also a Test that guards the Target.
    /// Whenver the Test returns true, it is assumed that the Target will be the correct action to
    /// take on the arguments.
    /// 
    /// In the current design, a RuleBuilder is also used to provide a mini binding scope for the
    /// parameters and temporary variables that might be needed by the Test and Target.  This will
    /// probably change in the future as we unify around the notion of Lambdas.
    /// 
    /// TODO: remove once everyone is converted over to MetaObjects
    /// </summary>
    public sealed class RuleBuilder {
        internal Expression _test;                  // the test that determines if the rule is applicable for its parameters
        internal Expression _target;                // the target that executes if the rule is true
        internal readonly Expression _context;               // CodeContext, if any.
        private bool _error;                        // true if the rule represents an error
        internal List<ParameterExpression> _temps;  // temporaries allocated by the rule

        // the parameters which the rule is processing
        internal readonly IList<Expression> _parameters;
        
        // the return label of the rule
        internal readonly LabelTarget _return;

        /// <summary>
        /// Completed rule
        /// </summary>
        private Expression _binding;

        public RuleBuilder(ReadOnlyCollection<ParameterExpression> parameters, LabelTarget returnLabel) {

            if (parameters.Count > 0 && typeof(CodeContext).IsAssignableFrom(parameters[0].Type)) {
                _context = parameters[0];
                var p = ArrayUtils.RemoveAt(parameters, 0);
                _parameters = p;
            } else {
                // TODO: remove the copy when we have covariant IEnumerable<T>
                _parameters = parameters.ToArray();
            }
            _return = returnLabel;
        }

        public void Clear() {
            _test = null;
            _target = null;
            _error = false;
            _temps = null;
        }

        /// <summary>
        /// An expression that should return true if and only if Target should be executed
        /// </summary>
        public Expression Test {
            get { return _test; }
            set {
                ContractUtils.RequiresNotNull(value, "value");
                ContractUtils.Requires(TypeUtils.IsBool(value.Type), "value", Strings.TypeOfTestMustBeBool);
                _test = value;
            }
        }

        /// <summary>
        /// The code to execute if the Test is true.
        /// </summary>
        public Expression Target {
            get { return _target; }
            set { _target = value; }
        }

        public Expression Context {
            get {
                return _context;
            }
        }

        /// <summary>
        /// Gets the logical parameters to the dynamic site in the form of Expressions.
        /// </summary>
        public IList<Expression> Parameters {
            get {
                return _parameters;
            }
        }

        public LabelTarget ReturnLabel {
            get { return _return; }
        }

        /// <summary>
        /// Allocates a temporary variable for use during the rule.
        /// </summary>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")]
        public ParameterExpression GetTemporary(Type type, string name) {
            ParameterExpression t = Expression.Variable(type, name);
            AddTemporary(t);
            return t;
        }

        public void AddTemporary(ParameterExpression variable) {
            ContractUtils.RequiresNotNull(variable, "variable");
            if (_temps == null) {
                _temps = new List<ParameterExpression>();
            }
            _temps.Add(variable);
        }

        public Expression MakeReturn(ActionBinder binder, Expression expr) {
            // we create a temporary here so that ConvertExpression doesn't need to (because it has no way to declare locals).
            if (expr.Type != typeof(void)) {
                ParameterExpression variable = GetTemporary(expr.Type, "$retVal");
                Expression conv = binder.ConvertExpression(variable, ReturnType, ConversionResultKind.ExplicitCast, Context);
                if (conv == variable) return MakeReturn(expr);

                return MakeReturn(Ast.Block(Ast.Assign(variable, expr), conv));
            }
            return MakeReturn(binder.ConvertExpression(expr, ReturnType, ConversionResultKind.ExplicitCast, Context));
        }

        private Expression MakeReturn(Expression expression) {
            return Ast.Return(_return, AstUtils.Convert(expression, _return.Type));
        }

        public Expression MakeError(Expression expr) {
            if (expr != null) {
                // TODO: Change to ConvertHelper
                if (!TypeUtils.CanAssign(typeof(Exception), expr.Type)) {
                    expr = Ast.Convert(expr, typeof(Exception));
                }
            }

            _error = true;
            return Ast.Throw(expr);
        }

        public bool IsError {
            get {
                return _error;
            }
            set {
                _error = value;
            }
        }

        public void AddTest(Expression expression) {
            ContractUtils.RequiresNotNull(expression, "expression");
            ContractUtils.Requires(TypeUtils.IsBool(expression.Type), "expression", Strings.TypeOfExpressionMustBeBool);

            if (_test == null) {
                _test = expression;
            } else {
                _test = Ast.AndAlso(_test, expression);
            }
        }

        public void MakeTest(params Type[] types) {
            _test = MakeTestForTypes(types, 0);
        }

        public static Expression MakeTypeTestExpression(Type t, Expression expr) {
            // we must always check for non-sealed types explicitly - otherwise we end up
            // doing fast-path behavior on a subtype which overrides behavior that wasn't
            // present for the base type.
            //TODO there's a question about nulls here
            if (CompilerHelpers.IsSealed(t) && t == expr.Type) {
                if (t.IsValueType) {
                    return AstUtils.Constant(true);
                }
                return Ast.NotEqual(expr, AstUtils.Constant(null));
            }

            return Ast.AndAlso(
                Ast.NotEqual(
                    expr,
                    AstUtils.Constant(null)),
                Ast.Equal(
                    Ast.Call(
                        AstUtils.Convert(expr, typeof(object)),
                        typeof(object).GetMethod("GetType")
                    ),
                    AstUtils.Constant(t)
                )
            );
        }

        public Expression MakeTestForTypes(Type[] types, int index) {
            Expression test = MakeTypeTest(types[index], index);
            if (index < types.Length - 1) {
                Expression nextTests = MakeTestForTypes(types, index + 1);
                if (ConstantCheck.Check(test, true)) {
                    return nextTests;
                } else if (ConstantCheck.Check(nextTests, true)) {
                    return test;
                } else {
                    return Ast.AndAlso(test, nextTests);
                }
            } else {
                return test;
            }
        }

        public Expression MakeTypeTest(Type type, int index) {
            return MakeTypeTest(type, Parameters[index]);
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")]
        public Expression MakeTypeTest(Type type, Expression tested) {
            if (type == null || type == typeof(DynamicNull)) {
                return Ast.Equal(tested, AstUtils.Constant(null));
            }

            return MakeTypeTestExpression(type, tested);
        }

        /// <summary>
        /// Gets the number of logical parameters the dynamic site is provided with.
        /// </summary>
        public int ParameterCount {
            get {
                return _parameters.Count;
            }
        }

        public Expression MakeTypeTestExpression(Type t, int param) {
            return MakeTypeTestExpression(t, Parameters[param]);
        }

        [Confined]
        public override string ToString() {
            return string.Format("RuleBuilder({0})", _target);
        }

        public Type ReturnType {
            get { return _return.Type; }
        }

        public Expression CreateRule() {
            if (_binding == null) {
                if (_test == null) {
                    throw Error.MissingTest();
                }
                if (_target == null) {
                    throw Error.MissingTarget();
                }

                _binding = Expression.Block(
                    _temps != null ? _temps.ToArray() : new ParameterExpression[0],
                    Expression.Condition(
                        _test,
                        AstUtils.Convert(_target, typeof(void)),
                        AstUtils.Empty()
                    )
                );
            }

            return _binding;
        }
    }
}
Back to Top