Welcome to mirror list, hosted at ThFree Co, Russian Federation.

Funcletizer.cs « ELinq « Objects « Data « System « System.Data.Entity « referencesource « class « mcs - github.com/mono/mono.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 7b45f33dd05e0e031c038be3b436013849dbaf6d (plain)
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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
//---------------------------------------------------------------------
// <copyright file="Funcletizer.cs" company="Microsoft">
//      Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//
// @owner       [....]
// @backupOwner [....]
//---------------------------------------------------------------------

namespace System.Data.Objects.ELinq
{
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Data.Common.CommandTrees;
    using System.Data.Common.CommandTrees.ExpressionBuilder;
    using System.Data.Entity;
    using System.Data.Metadata.Edm;
    using System.Diagnostics;
    using System.Globalization;
    using System.Linq;
    using System.Linq.Expressions;
    using System.Reflection;

    /// <summary>
    /// Determines which leaves of a LINQ expression tree should be evaluated locally before
    /// sending a query to the store. These sub-expressions may map to query parameters (e.g. local variables),
    /// to constants (e.g. literals 'new DateTime(2008, 1, 1)') or query sub-expression
    /// (e.g. 'context.Products'). Parameter expressions are replaced with QueryParameterExpression
    /// nodes. All other elements are swapped in place with either expanded expressions (for sub-queries)
    /// or constants. Where the expression includes mutable state that may influence the translation
    /// to a query, a Func(Of Boolean) delegate is returned indicating when a recompilation is necessary.
    /// </summary>
    internal sealed class Funcletizer
    {
        // Compiled query information
        private readonly ParameterExpression _rootContextParameter;
        private readonly ObjectContext _rootContext;
        private readonly ConstantExpression _rootContextExpression;
        private readonly ReadOnlyCollection<ParameterExpression> _compiledQueryParameters;
        private readonly Mode _mode;
        private readonly HashSet<Expression> _linqExpressionStack = new HashSet<Expression>();

        // Object parameters
        private static readonly string s_parameterPrefix = "p__linq__";
        private long _parameterNumber;

        private Funcletizer(
            Mode mode,
            ObjectContext rootContext, 
            ParameterExpression rootContextParameter, 
            ReadOnlyCollection<ParameterExpression> compiledQueryParameters)
        {
            _mode = mode;
            _rootContext = rootContext;
            _rootContextParameter = rootContextParameter;
            _compiledQueryParameters = compiledQueryParameters;
            if (null != _rootContextParameter && null != _rootContext)
            {
                _rootContextExpression = Expression.Constant(_rootContext);
            }
        }

        internal static Funcletizer CreateCompiledQueryEvaluationFuncletizer(
            ObjectContext rootContext,
            ParameterExpression rootContextParameter,
            ReadOnlyCollection<ParameterExpression> compiledQueryParameters)
        {
            EntityUtil.CheckArgumentNull(rootContext, "rootContext");
            EntityUtil.CheckArgumentNull(rootContextParameter, "rootContextParameter");
            EntityUtil.CheckArgumentNull(compiledQueryParameters, "compiledQueryParameters");

            return new Funcletizer(Mode.CompiledQueryEvaluation, rootContext, rootContextParameter, compiledQueryParameters);
        }

        internal static Funcletizer CreateCompiledQueryLockdownFuncletizer()
        {
            return new Funcletizer(Mode.CompiledQueryLockdown, null, null, null);
        }

        internal static Funcletizer CreateQueryFuncletizer(ObjectContext rootContext)
        {
            EntityUtil.CheckArgumentNull(rootContext, "rootContext");

            return new Funcletizer(Mode.ConventionalQuery, rootContext, null, null);
        }

        internal ObjectContext RootContext
        {
            get { return _rootContext; }
        }

        internal ParameterExpression RootContextParameter
        {
            get { return _rootContextParameter; }
        }

        internal ConstantExpression RootContextExpression
        {
            get { return _rootContextExpression; }
        }

        internal bool IsCompiledQuery
        {
            get { return _mode == Mode.CompiledQueryEvaluation || _mode == Mode.CompiledQueryLockdown; }
        }

        /// <summary>
        /// Performs funcletization on the given expression. Also returns a delegates that can be used
        /// to determine if the entire tree needs to be recompiled.
        /// </summary>
        internal Expression Funcletize(Expression expression, out Func<bool> recompileRequired)
        {
            EntityUtil.CheckArgumentNull(expression, "expression");

            // Find all candidates for funcletization. Some sub-expressions are reduced to constants,
            // others are reduced to variables. The rules vary based on the _mode.
            Func<Expression, bool> isClientConstant;
            Func<Expression, bool> isClientVariable;

            expression = ReplaceRootContextParameter(expression);

            if (_mode == Mode.CompiledQueryEvaluation)
            {
                // We lock down closure expressions for compiled queries, so everything is either
                // a constant or a query parameter produced from the explicit parameters to the
                // compiled query delegate.
                isClientConstant = Nominate(expression, this.IsClosureExpression);
                isClientVariable = Nominate(expression, this.IsCompiledQueryParameterVariable);
            }
            else if (_mode == Mode.CompiledQueryLockdown)
            {
                // When locking down a compiled query, we can evaluate all closure expressions.
                isClientConstant = Nominate(expression, this.IsClosureExpression);
                isClientVariable = (exp) => false;
            }
            else
            {
                Debug.Assert(_mode == Mode.ConventionalQuery, "No other options...");

                // There are no variable parameters outside of compiled queries, so everything is
                // either a constant or a closure expression.
                isClientConstant = Nominate(expression, this.IsImmutable);
                isClientVariable = Nominate(expression, this.IsClosureExpression);
            }

            // Now rewrite given nomination functions
            FuncletizingVisitor visitor = new FuncletizingVisitor(this, isClientConstant, isClientVariable);
            Expression result = visitor.Visit(expression);
            recompileRequired = visitor.GetRecompileRequiredFunction();
            
            return result;
        }

        /// <summary>
        /// Replaces context parameter (e.g. 'ctx' in CompiledQuery.Compile(ctx => ctx.Products)) with constant
        /// containing the object context.
        /// </summary>
        private Expression ReplaceRootContextParameter(Expression expression)
        {
            if (null != _rootContextExpression)
            {
                return EntityExpressionVisitor.Visit(
                    expression, (exp, baseVisit) =>
                    exp == _rootContextParameter ? _rootContextExpression : baseVisit(exp));
            }
            else
            {
                return expression;
            }
        }

        /// <summary>
        /// Returns a function indicating whether the given expression and all of its children satisfy the 
        /// 'localCriterion'.
        /// </summary>
        private static Func<Expression, bool> Nominate(Expression expression, Func<Expression, bool> localCriterion)
        {
            EntityUtil.CheckArgumentNull(localCriterion, "localCriterion");
            HashSet<Expression> candidates = new HashSet<Expression>();
            bool cannotBeNominated = false;
            Func<Expression, Func<Expression, Expression>, Expression> visit = (exp, baseVisit) =>
                {
                    if (exp != null)
                    {
                        bool saveCannotBeNominated = cannotBeNominated;
                        cannotBeNominated = false;
                        baseVisit(exp);
                        if (!cannotBeNominated)
                        {
                            // everyone below me can be nominated, so
                            // see if this one can be also
                            if (localCriterion(exp))
                            {
                                candidates.Add(exp);
                            }
                            else
                            {
                                cannotBeNominated = true;
                            }
                        }
                        cannotBeNominated |= saveCannotBeNominated;
                    }
                    return exp;
                };
            EntityExpressionVisitor.Visit(expression, visit);
            return candidates.Contains;
        }

        private enum Mode
        {
            CompiledQueryLockdown,
            CompiledQueryEvaluation,
            ConventionalQuery,
        }

        /// <summary>
        /// Determines whether the node may be evaluated locally and whether 
        /// it is a constant. Assumes that all children are also client expressions.
        /// </summary>
        private bool IsImmutable(Expression expression)
        {
            if (null == expression) { return false; }
            switch (expression.NodeType)
            {
                case ExpressionType.New:
                    {
                        // support construction of primitive types
                        PrimitiveType primitiveType;
                        if (!ClrProviderManifest.Instance.TryGetPrimitiveType(TypeSystem.GetNonNullableType(expression.Type),
                            out primitiveType))
                        {
                            return false;
                        }
                        return true;
                    }
                case ExpressionType.Constant:
                    return true;
                case ExpressionType.NewArrayInit:
                    // allow initialization of byte[] 'literals'
                    return (typeof(byte[]) == expression.Type);
                case ExpressionType.Convert:
                    return true;
                default:
                    return false;
            }
        }

        /// <summary>
        /// Determines whether the node may be evaluated locally and whether 
        /// it is a variable. Assumes that all children are also variable client expressions.
        /// </summary>
        private bool IsClosureExpression(Expression expression)
        {
            if (null == expression) { return false; }
            if (IsImmutable(expression)) { return true; }
            if (ExpressionType.MemberAccess == expression.NodeType)
            {
                MemberExpression member = (MemberExpression)expression;
                if (member.Member.MemberType == MemberTypes.Property)
                {
                    return ExpressionConverter.CanFuncletizePropertyInfo((PropertyInfo)member.Member);
                }
                return true;
            }
            return false;
        }

        /// <summary>
        /// Determines whether the node may be evaluated as a compiled query parameter.
        /// Assumes that all children are also eligible compiled query parameters.
        /// </summary>
        private bool IsCompiledQueryParameterVariable(Expression expression)
        {
            if (null == expression) { return false; }
            if (IsClosureExpression(expression)) { return true; }
            if (ExpressionType.Parameter == expression.NodeType)
            {
                ParameterExpression parameter = (ParameterExpression)expression;
                return _compiledQueryParameters.Contains(parameter);
            }
            return false;
        }

        /// <summary>
        /// Determine whether the given CLR type is legal for an ObjectParameter or constant
        /// DbExpression.
        /// </summary>
        private bool TryGetTypeUsageForTerminal(Type type, out TypeUsage typeUsage)
        {
            EntityUtil.CheckArgumentNull(type, "type");

            if (_rootContext.Perspective.TryGetTypeByName(TypeSystem.GetNonNullableType(type).FullName,
                false, // bIgnoreCase
                out typeUsage) &&
                (TypeSemantics.IsScalarType(typeUsage)))
            {
                return true;
            }

            typeUsage = null;
            return false;
        }

        /// <summary>
        /// Creates the next available parameter name.
        /// </summary>
        internal string GenerateParameterName()
        {
            // To avoid collisions with user parameters (the full set is not
            // known at this time) we plug together an 'unlikely' prefix and 
            // a number.
            return String.Format(CultureInfo.InvariantCulture, "{0}{1}",
                s_parameterPrefix,
                _parameterNumber++);
        }

        /// <summary>
        /// Walks the expression tree and replaces client-evaluable expressions with constants
        /// or QueryParameterExpressions.
        /// </summary>
        private sealed class FuncletizingVisitor : EntityExpressionVisitor
        {
            private readonly Funcletizer _funcletizer;
            private readonly Func<Expression, bool> _isClientConstant;
            private readonly Func<Expression, bool> _isClientVariable;
            private readonly List<Func<bool>> _recompileRequiredDelegates = new List<Func<bool>>();

            internal FuncletizingVisitor(
                Funcletizer funcletizer,
                Func<Expression, bool> isClientConstant,
                Func<Expression, bool> isClientVariable)
            {
                EntityUtil.CheckArgumentNull(funcletizer, "funcletizer");
                EntityUtil.CheckArgumentNull(isClientConstant, "isClientConstant");
                EntityUtil.CheckArgumentNull(isClientVariable, "isClientVariable");
            
                _funcletizer = funcletizer;
                _isClientConstant = isClientConstant;
                _isClientVariable = isClientVariable;
            }

            /// <summary>
            /// Returns a delegate indicating (when called) whether a change has been identified
            /// requiring a complete recompile of the query.
            /// </summary>
            internal Func<bool> GetRecompileRequiredFunction()
            {
                // assign list to local variable to avoid including the entire Funcletizer
                // class in the closure environment
                ReadOnlyCollection<Func<bool>> recompileRequiredDelegates = _recompileRequiredDelegates.AsReadOnly();
                return () => recompileRequiredDelegates.Any(d => d());
            }

            internal override Expression Visit(Expression exp)
            {
                if (exp != null)
                {
                    if (!_funcletizer._linqExpressionStack.Add(exp))
                    {
                        // This expression is already in the stack.
                        throw EntityUtil.InvalidOperation(Strings.ELinq_CycleDetected);
                    }

                    try
                    {
                        if (_isClientConstant(exp))
                        {
                            return InlineValue(exp, false);
                        }
                        else if (_isClientVariable(exp))
                        {
                            TypeUsage queryParameterType;
                            if (_funcletizer.TryGetTypeUsageForTerminal(exp.Type, out queryParameterType))
                            {
                                DbParameterReferenceExpression parameterReference = queryParameterType.Parameter(_funcletizer.GenerateParameterName());
                                return new QueryParameterExpression(parameterReference, exp, _funcletizer._compiledQueryParameters);
                            }
                            else if (_funcletizer.IsCompiledQuery)
                            {
                                throw InvalidCompiledQueryParameterException(exp);
                            }
                            else
                            {
                                return InlineValue(exp, true);
                            }
                        }
                        return base.Visit(exp);
                    }
                    finally
                    {
                        _funcletizer._linqExpressionStack.Remove(exp);
                    }
                }
                return base.Visit(exp);
            }

            private static NotSupportedException InvalidCompiledQueryParameterException(Expression expression)
            {
                ParameterExpression parameterExp;
                if (expression.NodeType == ExpressionType.Parameter)
                {
                    parameterExp = (ParameterExpression)expression;
                }
                else
                {
                    // If this is a simple query parameter (involving a single delegate parameter) report the
                    // type of that parameter. Otherwise, report the type of the part of the parameter.
                    HashSet<ParameterExpression> parameters = new HashSet<ParameterExpression>();
                    EntityExpressionVisitor.Visit(expression, (exp, baseVisit) =>
                    {
                        if (null != exp && exp.NodeType == ExpressionType.Parameter)
                        {
                            parameters.Add((ParameterExpression)exp);
                        }
                        return baseVisit(exp);
                    });

                    if (parameters.Count != 1)
                    {
                        return EntityUtil.NotSupported(Strings.CompiledELinq_UnsupportedParameterTypes(expression.Type.FullName));
                    }
                    
                    parameterExp = parameters.Single();
                }

                if (parameterExp.Type.Equals(expression.Type))
                {
                    // If the expression type is the same as the parameter type, indicate that the parameter type is not valid.
                    return EntityUtil.NotSupported(Strings.CompiledELinq_UnsupportedNamedParameterType(parameterExp.Name, parameterExp.Type.FullName));                    
                }
                else
                {
                    // Otherwise, indicate that using the specified parameter to produce a value of the expression's type is not supported in compiled query
                    return EntityUtil.NotSupported(Strings.CompiledELinq_UnsupportedNamedParameterUseAsType(parameterExp.Name, expression.Type.FullName));
                }
            }
        
            /// <summary>
            /// Compiles a delegate returning the value of the given expression.
            /// </summary>
            private Func<object> CompileExpression(Expression expression)
            {
                Func<object> func = Expression
                    .Lambda<Func<object>>(TypeSystem.EnsureType(expression, typeof(object)))
                    .Compile();
                return func;
            }

            /// <summary>
            /// Inlines a funcletizable expression. Queries and lambda expressions are expanded
            /// inline. All other values become simple constants.
            /// </summary>
            private Expression InlineValue(Expression expression, bool recompileOnChange)
            {
                Func<object> getValue = null;
                object value = null;
                if (expression.NodeType == ExpressionType.Constant)
                {
                    value = ((ConstantExpression)expression).Value;
                }
                else
                {
                    bool fastPath = false;
                    //fastpath to process object query
                    if (expression.NodeType == ExpressionType.Convert)
                    {
                        var ue = (UnaryExpression)expression;
                        // The ObjectSet instance is wrapped inside Convert UnaryExpression in 
                        // ElinqQueryState.GetExpression(). The block below identifies such an 
                        // expression, makes sure the object query it contains is immutable and 
                        // extracts the reference to the object query.
                        if (!recompileOnChange
                            && ue.Operand.NodeType == ExpressionType.Constant
                            && typeof(IQueryable).IsAssignableFrom(ue.Operand.Type))
                        {
                            value = ((ConstantExpression)ue.Operand).Value;
                            fastPath = true;
                        }
                    }
                    if (!fastPath)
                    {
                        getValue = CompileExpression(expression);
                        value = getValue();
                    }
                }

                Expression result = null;
                ObjectQuery inlineQuery = value as ObjectQuery;
                if (inlineQuery != null)
                {
                    result = InlineObjectQuery(inlineQuery, expression.Type);
                }
                else
                {
                    LambdaExpression lambda = value as LambdaExpression;
                    if (null != lambda)
                    {
                        result = InlineExpression(Expression.Quote(lambda));
                    }
                    else
                    {
                        // everything else is just a constant...
                        result = expression.NodeType == ExpressionType.Constant
                            ? expression
                            : Expression.Constant(value, expression.Type);
                    }
                }

                if (recompileOnChange)
                {
                    AddRecompileRequiredDelegates(getValue, value);
                }

                return result;
            }

            private void AddRecompileRequiredDelegates(Func<object> getValue, object value)
            {
                // Build a delegate that returns true when the inline value has changed.
                // Outside of ObjectQuery, this amounts to a reference comparison.
                ObjectQuery originalQuery = value as ObjectQuery;
                if (null != originalQuery)
                {
                    // For inline queries, we need to check merge options as well (it's mutable)
                    MergeOption? originalMergeOption = originalQuery.QueryState.UserSpecifiedMergeOption;
                    if (null == getValue)
                    {
                        _recompileRequiredDelegates.Add(() => originalQuery.QueryState.UserSpecifiedMergeOption != originalMergeOption);
                    }
                    else
                    {
                        _recompileRequiredDelegates.Add(() =>
                        {
                            ObjectQuery currentQuery = getValue() as ObjectQuery;
                            return !object.ReferenceEquals(originalQuery, currentQuery) ||
                                currentQuery.QueryState.UserSpecifiedMergeOption != originalMergeOption;
                        });

                    }
                }
                else if (null != getValue)
                {
                    _recompileRequiredDelegates.Add(() => !object.ReferenceEquals(value, getValue()));
                }
            }

            /// <summary>
            /// Gets the appropriate LINQ expression for an inline ObjectQuery instance.
            /// </summary>
            private Expression InlineObjectQuery(ObjectQuery inlineQuery, Type expressionType)
            {
                EntityUtil.CheckArgumentNull(inlineQuery, "inlineQuery");

                Expression queryExpression;
                if (_funcletizer._mode == Mode.CompiledQueryLockdown)
                {
                    // In the lockdown phase, we don't chase down inline object queries because
                    // we don't yet know what the object context is supposed to be.
                    queryExpression = Expression.Constant(inlineQuery, expressionType);
                }
                else
                {
                    if (!object.ReferenceEquals(_funcletizer._rootContext, inlineQuery.QueryState.ObjectContext))
                    {
                        throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_UnsupportedDifferentContexts);
                    }

                    queryExpression = inlineQuery.GetExpression();

                    // If it's not an entity-sql (terminal) query, recursively process
                    if (!(inlineQuery.QueryState is EntitySqlQueryState))
                    {
                        queryExpression = InlineExpression(queryExpression);
                    }

                    queryExpression = TypeSystem.EnsureType(queryExpression, expressionType);
                }

                return queryExpression;
            }

            private Expression InlineExpression(Expression exp)
            {
                Func<bool> inlineExpressionRequiresRecompile;
                exp = _funcletizer.Funcletize(exp, out inlineExpressionRequiresRecompile);
                if (!_funcletizer.IsCompiledQuery)
                {
                    _recompileRequiredDelegates.Add(inlineExpressionRequiresRecompile);
                }
                return exp;
            }
        }
    }

    /// <summary>
    /// A LINQ expression corresponding to a query parameter.
    /// </summary>
    internal sealed class QueryParameterExpression : Expression
    {
        private readonly DbParameterReferenceExpression _parameterReference;
        private readonly Type _type;
        private readonly Expression _funcletizedExpression;
        private readonly IEnumerable<ParameterExpression> _compiledQueryParameters;
        private Delegate _cachedDelegate;

        internal QueryParameterExpression(
            DbParameterReferenceExpression parameterReference,
            Expression funcletizedExpression,
            IEnumerable<ParameterExpression> compiledQueryParameters)
        {
            EntityUtil.CheckArgumentNull(parameterReference, "parameterReference");
            EntityUtil.CheckArgumentNull(funcletizedExpression, "funcletizedExpression");
            _compiledQueryParameters = compiledQueryParameters ?? Enumerable.Empty<ParameterExpression>();
            _parameterReference = parameterReference;
            _type = funcletizedExpression.Type;
            _funcletizedExpression = funcletizedExpression;
            _cachedDelegate = null;
        }

        /// <summary>
        /// Gets the current value of the parameter given (optional) compiled query arguments.
        /// </summary>
        internal object EvaluateParameter(object[] arguments)
        {
            if (_cachedDelegate == null)
            {
                if (_funcletizedExpression.NodeType == ExpressionType.Constant)
                {
                    return ((ConstantExpression)_funcletizedExpression).Value;
                }
                ConstantExpression ce;
                if (TryEvaluatePath(_funcletizedExpression, out ce))
                {
                    return ce.Value;
                }
            }

            try
            {
                if (_cachedDelegate == null)
                {
                    // Get the Func<> type for the property evaluator
                    Type delegateType = TypeSystem.GetDelegateType(_compiledQueryParameters.Select(p => p.Type), _type);

                    // Now compile delegate for the funcletized expression
                    _cachedDelegate = Expression.Lambda(delegateType, _funcletizedExpression, _compiledQueryParameters).Compile();
                }
                return _cachedDelegate.DynamicInvoke(arguments);
            }
            catch (TargetInvocationException e)
            {
                throw e.InnerException;
            }
        }

        /// <summary>
        /// Create QueryParameterExpression based on this one, but with the funcletized expression
        /// wrapped by the given method
        /// </summary>
        /// <param name="method"></param>
        /// <returns></returns>
        internal QueryParameterExpression EscapeParameterForLike(Func<string, string> method)
        {
            Expression wrappedExpression = Expression.Invoke(Expression.Constant(method), this._funcletizedExpression);
            return new QueryParameterExpression(this._parameterReference, wrappedExpression, this._compiledQueryParameters);
        }

        /// <summary>
        /// Gets the parameter reference for the parameter.
        /// </summary>
        internal DbParameterReferenceExpression ParameterReference
        {
            get { return _parameterReference; }
        }

        public override Type Type
        {
            get { return _type; }
        }

        public override ExpressionType NodeType
        {
            get { return EntityExpressionVisitor.CustomExpression; }
        }

        private bool TryEvaluatePath(Expression expression, out ConstantExpression constantExpression)
        {
            MemberExpression me = expression as MemberExpression;
            constantExpression = null;
            if (me != null)
            {
                Stack<MemberExpression> stack = new Stack<MemberExpression>();
                stack.Push(me);
                while ((me = me.Expression as MemberExpression) != null)
                {
                    stack.Push(me);
                }
                me = stack.Pop();
                ConstantExpression ce = me.Expression as ConstantExpression;
                if (ce != null)
                {
                    object memberVal;
                    if (!TryGetFieldOrPropertyValue(me, ((ConstantExpression)me.Expression).Value, out memberVal))
                    {
                        return false;
                    }
                    if (stack.Count > 0)
                    {
                        foreach (var rec in stack)
                        {
                            if (!TryGetFieldOrPropertyValue(rec, memberVal, out memberVal))
                            {
                                return false;
                            }
                        }
                    }
                    constantExpression = Expression.Constant(memberVal, expression.Type);
                    return true;
                }
            }
            return false;
        }

        private bool TryGetFieldOrPropertyValue(MemberExpression me, object instance, out object memberValue)
        {
            bool result = false;
            memberValue = null;

            try
            {
                if (me.Member.MemberType == MemberTypes.Field)
                {
                    memberValue = ((FieldInfo)me.Member).GetValue(instance);
                    result = true;
                }
                else if (me.Member.MemberType == MemberTypes.Property)
                {
                    memberValue = ((PropertyInfo)me.Member).GetValue(instance, null);
                    result = true;
                }
                return result;
            }
            catch (TargetInvocationException ex)
            {
                throw ex.InnerException;
            }
        }
    }
}