xronos /Microsoft.Scripting.Core/Actions/BindingRestrictions.cs

Language C# Lines 318
MD5 Hash 6433af9aad2448356f3a6783ff7f9f81 Estimated Cost $5,064 (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
308
309
310
311
312
313
314
315
316
317
/* ****************************************************************************
 *
 * 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.
 *
 *
 * ***************************************************************************/
using System; using Microsoft;


using System.Collections.Generic;
#if CODEPLEX_40
using System.Dynamic.Utils;
using System.Linq.Expressions;
#else
using Microsoft.Scripting.Utils;
using Microsoft.Linq.Expressions;
#endif

#if CODEPLEX_40
namespace System.Dynamic {
#else
namespace Microsoft.Scripting {
#endif
    /// <summary>
    /// Represents a set of binding restrictions on the <see cref="DynamicMetaObject"/>under which the dynamic binding is valid.
    /// </summary>
    public sealed class BindingRestrictions {
        private class Restriction {
            internal enum RestrictionKind {
                Type,
                Instance,
                Custom
            };

            private readonly RestrictionKind _kind;

            // Simplification ... for now just one kind of restriction rather than hierarchy.
            private readonly Expression _expression;
            private readonly Type _type;

            // We hold onto the instance here, but that's okay, because
            // we're binding. Once we generate the instance test however, we 
            // should store the instance as a WeakReference
            private readonly object _instance;

            internal RestrictionKind Kind {
                get { return _kind; }
            }

            internal Expression Expression {
                get { return _expression; }
            }

            internal Type Type {
                get { return _type; }
            }

            internal object Instance {
                get { return _instance; }
            }

            internal Restriction(Expression parameter, Type type) {
                _kind = RestrictionKind.Type;
                _expression = parameter;
                _type = type;
            }

            internal Restriction(Expression parameter, object instance) {
                _kind = RestrictionKind.Instance;
                _expression = parameter;
                _instance = instance;
            }

            internal Restriction(Expression expression) {
                _kind = RestrictionKind.Custom;
                _expression = expression;
            }

            public override bool Equals(object obj) {
                Restriction other = obj as Restriction;
                if (other == null) {
                    return false;
                }

                if (other.Kind != Kind ||
                    other.Expression != Expression) {
                    return false;
                }

                switch (other.Kind) {
                    case RestrictionKind.Instance:
                        return other.Instance == Instance;
                    case RestrictionKind.Type:
                        return other.Type == Type;
                    default:
                        return false;
                }
            }

            public override int GetHashCode() {
                // lots of collisions but we don't hash Restrictions ever
                return (int)Kind ^ Expression.GetHashCode();
            }
        }

        private readonly Restriction[] _restrictions;

        private BindingRestrictions(params Restriction[] restrictions) {
            _restrictions = restrictions;
        }

        private bool IsEmpty {
            get {
                return _restrictions.Length == 0;
            }
        }

        /// <summary>
        /// Merges the set of binding restrictions with the current binding restrictions.
        /// </summary>
        /// <param name="restrictions">The set of restrictions with which to merge the current binding restrictions.</param>
        /// <returns>The new set of binding restrictions.</returns>
        public BindingRestrictions Merge(BindingRestrictions restrictions) {
            if (restrictions.IsEmpty) {
                return this;
            } else if (IsEmpty) {
                return restrictions;
            } else {
                List<Restriction> res = new List<Restriction>(_restrictions.Length + restrictions._restrictions.Length);
                AddRestrictions(_restrictions, res);
                AddRestrictions(restrictions._restrictions, res);

                return new BindingRestrictions(res.ToArray());
            }
        }

        /// <summary>
        /// Adds unique restrictions and doesn't add restrictions which are alerady present
        /// </summary>
        private static void AddRestrictions(Restriction[] list, List<Restriction> res) {
            foreach (Restriction r in list) {
                bool found = false;
                for (int j = 0; j < res.Count; j++) {
                    if (res[j].Equals(r)) {
                        found = true;
                    }
                }

                if (!found) {
                    res.Add(r);
                }
            }
        }

        /// <summary>
        /// Represents an empty set of binding restrictions. This field is read only.
        /// </summary>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
        public static readonly BindingRestrictions Empty = new BindingRestrictions();

        /// <summary>
        /// Creates the binding restriction that check the expression for runtime type identity.
        /// </summary>
        /// <param name="expression">The expression to test.</param>
        /// <param name="type">The exact type to test.</param>
        /// <returns>The new binding restrictions.</returns>
        public static BindingRestrictions GetTypeRestriction(Expression expression, Type type) {
            ContractUtils.RequiresNotNull(expression, "expression");
            ContractUtils.RequiresNotNull(type, "type");

            return new BindingRestrictions(new Restriction(expression, type));
        }

        /// <summary>
        /// The method takes a DynamicMetaObject, and returns an instance restriction for testing null if the object
        /// holds a null value, otherwise returns a type restriction.
        /// </summary>
        internal static BindingRestrictions GetTypeRestriction(DynamicMetaObject obj) {
            if (obj.Value == null && obj.HasValue) {
                return BindingRestrictions.GetInstanceRestriction(obj.Expression, null);
            } else {
                return BindingRestrictions.GetTypeRestriction(obj.Expression, obj.LimitType);
            }
        }

        /// <summary>
        /// Creates the binding restriction that checks the expression for object instance identity.
        /// </summary>
        /// <param name="expression">The expression to test.</param>
        /// <param name="instance">The exact object instance to test.</param>
        /// <returns>The new binding restrictions.</returns>
        public static BindingRestrictions GetInstanceRestriction(Expression expression, object instance) {
            ContractUtils.RequiresNotNull(expression, "expression");

            return new BindingRestrictions(new Restriction(expression, instance));
        }

        /// <summary>
        /// Creates the binding restriction that checks the expression for arbitrary immutable properties.
        /// </summary>
        /// <param name="expression">The expression expression the restrictions.</param>
        /// <returns>The new binding restrictions.</returns>
        /// <remarks>
        /// By convention, the general restrictions created by this method must only test
        /// immutable object properties.
        /// </remarks>
        public static BindingRestrictions GetExpressionRestriction(Expression expression) {
            ContractUtils.RequiresNotNull(expression, "expression");
            ContractUtils.Requires(expression.Type == typeof(bool), "expression");
            return new BindingRestrictions(new Restriction(expression));
        }

        /// <summary>
        /// Combines binding restrictions from the list of <see cref="DynamicMetaObject"/> instances into one set of restrictions.
        /// </summary>
        /// <param name="contributingObjects">The list of <see cref="DynamicMetaObject"/> instances from which to combine restrictions.</param>
        /// <returns>The new set of binding restrictions.</returns>
        public static BindingRestrictions Combine(IList<DynamicMetaObject> contributingObjects) {
            BindingRestrictions res = BindingRestrictions.Empty;
            if (contributingObjects != null) {
                foreach (DynamicMetaObject mo in contributingObjects) {
                    if (mo != null) {
                        res = res.Merge(mo.Restrictions);
                    }
                }
            }
            return res;
        }

        /// <summary>
        /// Creates the <see cref="Expression"/> representing the binding restrictions.
        /// </summary>
        /// <returns>The expression tree representing the restrictions.</returns>
        public Expression ToExpression() {
            // We could optimize this better, e.g. common subexpression elimination
            // But for now, it's good enough.
            Expression test = null;
            foreach (Restriction r in _restrictions) {
                Expression one;
                switch (r.Kind) {
                    case Restriction.RestrictionKind.Type:
                        one = CreateTypeRestriction(r.Expression, r.Type);
                        break;
                    case Restriction.RestrictionKind.Instance:
                        one = CreateInstanceRestriction(r.Expression, r.Instance);
                        break;
                    case Restriction.RestrictionKind.Custom:
                        one = r.Expression;
                        break;
                    default:
                        throw new InvalidOperationException();
                }

                if (one != null) {
                    if (test == null) {
                        test = one;
                    } else {
                        test = Expression.AndAlso(test, one);
                    }
                }
            }

            return test ?? Expression.Constant(true);
        }

        /// <summary>
        /// Creates one type identity test 
        /// </summary>
        private static Expression CreateTypeRestriction(Expression expression, Type rt) {
            return Expression.TypeEqual(expression, rt);
        }

        private static Expression CreateInstanceRestriction(Expression expression, object value) {
            if (value == null) {
                return Expression.Equal(
                    Expression.Convert(expression, typeof(object)),
                    Expression.Constant(null)
                );
            }

            // TODO: need to add special cases for valuetypes and nullables
            ParameterExpression temp = Expression.Parameter(typeof(object), null);

            Expression init = Expression.Assign(
                temp,
                Expression.Property(
                    Expression.Constant(new WeakReference(value)),
                    typeof(WeakReference).GetProperty("Target")
                )
            );

            return Expression.Block(
                new ParameterExpression[] { temp },
                init,
                Expression.AndAlso(
                //check that WeekReference was not collected.
                    Expression.NotEqual(
                        temp,
                        Expression.Constant(null)
                    ),
                    Expression.Equal(
                        temp,
                        Expression.Convert(expression, typeof(object))
                    )
                )
            );
        }
    }
}
Back to Top