File: ProjectionPlanCompiler.cs

package info (click to toggle)
mono 4.6.2.7+dfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 778,148 kB
  • ctags: 914,052
  • sloc: cs: 5,779,509; xml: 2,773,713; ansic: 432,645; sh: 14,749; makefile: 12,361; perl: 2,488; python: 1,434; cpp: 849; asm: 531; sql: 95; sed: 16; php: 1
file content (863 lines) | stat: -rw-r--r-- 38,183 bytes parent folder | download | duplicates (2)
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
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
//Copyright 2010 Microsoft Corporation
//
//Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
//You may obtain a copy of the License at 
//
//http://www.apache.org/licenses/LICENSE-2.0 
//
//Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an 
//"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
//See the License for the specific language governing permissions and limitations under the License.



namespace System.Data.Services.Client
{
    #region Namespaces.

    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Linq;
    using System.Linq.Expressions;
    using System.Reflection;

    #endregion Namespaces.

    internal class ProjectionPlanCompiler : ExpressionVisitor
    {
        #region Private fields.

        private readonly Dictionary<Expression, ExpressionAnnotation> annotations;

        private readonly ParameterExpression materializerExpression;

        private readonly Dictionary<Expression, Expression> normalizerRewrites;

        private int identifierId;

        private ProjectionPathBuilder pathBuilder;

        private bool topLevelProjectionFound;

        #endregion Private fields.

        #region Constructors.

        private ProjectionPlanCompiler(Dictionary<Expression, Expression> normalizerRewrites)
        {
            this.annotations = new Dictionary<Expression, ExpressionAnnotation>(ReferenceEqualityComparer<Expression>.Instance);
            this.materializerExpression = Expression.Parameter(typeof(object), "mat");
            this.normalizerRewrites = normalizerRewrites;
            this.pathBuilder = new ProjectionPathBuilder();
        }

        #endregion Constructors.

        #region Internal methods.

        internal static ProjectionPlan CompilePlan(LambdaExpression projection, Dictionary<Expression, Expression> normalizerRewrites)
        {
            Debug.Assert(projection != null, "projection != null");
            Debug.Assert(projection.Parameters.Count == 1, "projection.Parameters.Count == 1");
            Debug.Assert(
                projection.Body.NodeType == ExpressionType.Constant ||
                projection.Body.NodeType == ExpressionType.MemberInit ||
                projection.Body.NodeType == ExpressionType.MemberAccess ||
                projection.Body.NodeType == ExpressionType.Convert ||
                projection.Body.NodeType == ExpressionType.ConvertChecked ||
                projection.Body.NodeType == ExpressionType.New,
                "projection.Body.NodeType == Constant, MemberInit, MemberAccess, Convert(Checked) New");

            ProjectionPlanCompiler rewriter = new ProjectionPlanCompiler(normalizerRewrites);
#if TRACE_CLIENT_PROJECTIONS
            Trace.WriteLine("Projection: " + projection);
#endif

            Expression plan = rewriter.Visit(projection);
#if TRACE_CLIENT_PROJECTIONS
            Trace.WriteLine("Becomes: " + plan);
#endif

            ProjectionPlan result = new ProjectionPlan();
            result.Plan = (Func<object, object, Type, object>)((LambdaExpression)plan).Compile();
            result.ProjectedType = projection.Body.Type;
#if DEBUG
            result.SourceProjection = projection;
            result.TargetProjection = plan;
#endif
            return result;
        }

        internal override Expression VisitBinary(BinaryExpression b)
        {
            Expression original = this.GetExpressionBeforeNormalization(b);
            if (original == b)
            {
                return base.VisitBinary(b);
            }
            else
            {
                return this.Visit(original);
            }
        }

        internal override Expression VisitConditional(ConditionalExpression conditional)
        {
            Debug.Assert(conditional != null, "conditional != null");
            Expression original = this.GetExpressionBeforeNormalization(conditional);
            if (original != conditional)
            {
                return this.Visit(original);
            }

            var nullCheck = ResourceBinder.PatternRules.MatchNullCheck(this.pathBuilder.LambdaParameterInScope, conditional);
            if (!nullCheck.Match || !ClientType.CheckElementTypeIsEntity(nullCheck.AssignExpression.Type))
            {
                return base.VisitConditional(conditional);
            }

            return this.RebindConditionalNullCheck(conditional, nullCheck);
        }

        internal override Expression VisitUnary(UnaryExpression u)
        {
            Expression original = this.GetExpressionBeforeNormalization(u);
            Expression result;
            if (original == u)
            {
                result = base.VisitUnary(u);
                UnaryExpression unaryResult = result as UnaryExpression;
                if (unaryResult != null)
                {
                    ExpressionAnnotation annotation;
                    if (this.annotations.TryGetValue(unaryResult.Operand, out annotation))
                    {
                        this.annotations[result] = annotation;
                    }
                }
            }
            else
            {
                result = this.Visit(original);
            }

            return result;
        }

        internal override Expression VisitMemberAccess(MemberExpression m)
        {
            Debug.Assert(m != null, "m != null");

            Expression result;
            Expression baseSourceExpression = m.Expression;

            if (ClientConvert.IsKnownNullableType(baseSourceExpression.Type))
            {
                result = base.VisitMemberAccess(m);
            }
            else
            {
                Expression baseTargetExpression = this.Visit(baseSourceExpression);
                ExpressionAnnotation annotation;
                if (this.annotations.TryGetValue(baseTargetExpression, out annotation))
                {
                    result = this.RebindMemberAccess(m, annotation);
                }
                else
                {
                    result = Expression.MakeMemberAccess(baseTargetExpression, m.Member);
                }
            }

            return result;
        }

        internal override Expression VisitParameter(ParameterExpression p)
        {
            Debug.Assert(p != null, "p != null");

            Expression result;
            ExpressionAnnotation annotation;
            if (this.annotations.TryGetValue(p, out annotation))
            {
                result = this.RebindParameter(p, annotation);
            }
            else
            {
                result = base.VisitParameter(p);
            }

            return result;
        }

        internal override Expression VisitMemberInit(MemberInitExpression init)
        {
            this.pathBuilder.EnterMemberInit(init);
            
            Expression result = null;
            if (this.pathBuilder.CurrentIsEntity && init.Bindings.Count > 0)
            {
                result = this.RebindEntityMemberInit(init);
            }
            else
            {
                result = base.VisitMemberInit(init);
            }

            this.pathBuilder.LeaveMemberInit();
            return result;
        }

        internal override Expression VisitMethodCall(MethodCallExpression m)
        {
            Debug.Assert(m != null, "m != null");

            Expression original = this.GetExpressionBeforeNormalization(m);
            if (original != m)
            {
                return this.Visit(original);
            }

            Expression result;
            if (this.pathBuilder.CurrentIsEntity)
            {
                Debug.Assert(
                    ProjectionAnalyzer.IsMethodCallAllowedEntitySequence(m) || ResourceBinder.PatternRules.MatchReferenceEquals(m),
                    "ProjectionAnalyzer.IsMethodCallAllowedEntitySequence(m) || ResourceBinder.PatternRules.MatchReferenceEquals(m) -- otherwise ProjectionAnalyzer should have blocked this for entities");
                if (m.Method.Name == "Select")
                {
                    result = this.RebindMethodCallForMemberSelect(m);
                }
                else if (m.Method.Name == "ToList")
                {
                    result = this.RebindMethodCallForMemberToList(m);
                }
                else
                {
                    Debug.Assert(m.Method.Name == "ReferenceEquals", "We don't know how to handle this method, ProjectionAnalyzer updated?");
                    result = base.VisitMethodCall(m);
                }
            }
            else
            {
                if (ProjectionAnalyzer.IsMethodCallAllowedEntitySequence(m))
                {
                    result = this.RebindMethodCallForNewSequence(m);
                }
                else
                {
                    result = base.VisitMethodCall(m);
                }
            }

            return result;
        }

        internal override NewExpression VisitNew(NewExpression nex)
        {
            Debug.Assert(nex != null, "nex != null");

            if (ResourceBinder.PatternRules.MatchNewDataServiceCollectionOfT(nex))
            {
                return this.RebindNewExpressionForDataServiceCollectionOfT(nex);
            }

            return base.VisitNew(nex);
        }

        internal override Expression VisitLambda(LambdaExpression lambda)
        {
            Debug.Assert(lambda != null, "lambda != null");

            Expression result;
            if (!this.topLevelProjectionFound || lambda.Parameters.Count == 1 && ClientType.CheckElementTypeIsEntity(lambda.Parameters[0].Type))
            {
                this.topLevelProjectionFound = true;

                ParameterExpression expectedTypeParameter = Expression.Parameter(typeof(Type), "type" + this.identifierId);
                ParameterExpression entryParameter = Expression.Parameter(typeof(object), "entry" + this.identifierId);
                this.identifierId++;

                this.pathBuilder.EnterLambdaScope(lambda, entryParameter, expectedTypeParameter);
                ProjectionPath parameterPath = new ProjectionPath(lambda.Parameters[0], expectedTypeParameter, entryParameter);
                ProjectionPathSegment parameterSegment = new ProjectionPathSegment(parameterPath, null, null);
                parameterPath.Add(parameterSegment);
                this.annotations[lambda.Parameters[0]] = new ExpressionAnnotation() { Segment = parameterSegment };

                Expression body = this.Visit(lambda.Body);

                if (body.Type.IsValueType)
                {
                    body = Expression.Convert(body, typeof(object));
                }

                result = Expression.Lambda<Func<object, object, Type, object>>(
                    body,
                    this.materializerExpression,
                    entryParameter,
                    expectedTypeParameter);

                this.pathBuilder.LeaveLambdaScope();
            }
            else
            {
                result = base.VisitLambda(lambda);
            }

            return result;
        }

        #endregion Internal methods.

        #region Private methods.

        private static Expression CallMaterializer(string methodName, params Expression[] arguments)
        {
            return CallMaterializerWithType(methodName, null, arguments);
        }

        private static Expression CallMaterializerWithType(string methodName, Type[] typeArguments, params Expression[] arguments)
        {
            Debug.Assert(methodName != null, "methodName != null");
            Debug.Assert(arguments != null, "arguments != null");

            MethodInfo method = typeof(AtomMaterializerInvoker).GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
            Debug.Assert(method != null, "method != null - found " + methodName);
            if (typeArguments != null)
            {
                method = method.MakeGenericMethod(typeArguments);
            }

            return Expression.Call(method, arguments);
        }

        private Expression CallCheckValueForPathIsNull(Expression entry, Expression entryType, ProjectionPath path)
        {
            Expression result = CallMaterializer("ProjectionCheckValueForPathIsNull", entry, entryType, Expression.Constant(path, typeof(object)));
            this.annotations.Add(result, new ExpressionAnnotation() { Segment = path[path.Count - 1] });
            return result;
        }

        private Expression CallValueForPath(Expression entry, Expression entryType, ProjectionPath path)
        {
            Debug.Assert(entry != null, "entry != null");
            Debug.Assert(path != null, "path != null");

            Expression result = CallMaterializer("ProjectionValueForPath", this.materializerExpression, entry, entryType, Expression.Constant(path, typeof(object)));
            this.annotations.Add(result, new ExpressionAnnotation() { Segment = path[path.Count - 1] });
            return result;
        }

        private Expression CallValueForPathWithType(Expression entry, Expression entryType, ProjectionPath path, Type type)
        {
            Debug.Assert(entry != null, "entry != null");
            Debug.Assert(path != null, "path != null");
            
            Expression value = this.CallValueForPath(entry, entryType, path);
            Expression result = Expression.Convert(value, type);
            this.annotations.Add(result, new ExpressionAnnotation() { Segment = path[path.Count - 1] });
            return result;
        }

        private Expression RebindConditionalNullCheck(ConditionalExpression conditional, ResourceBinder.PatternRules.MatchNullCheckResult nullCheck)
        {
            Debug.Assert(conditional != null, "conditional != null");
            Debug.Assert(nullCheck.Match, "nullCheck.Match -- otherwise no reason to call this rebind method");

            Expression testToNullForProjection = this.Visit(nullCheck.TestToNullExpression);
            Expression assignForProjection = this.Visit(nullCheck.AssignExpression);
            ExpressionAnnotation testToNullAnnotation;
            if (!this.annotations.TryGetValue(testToNullForProjection, out testToNullAnnotation))
            {
                return base.VisitConditional(conditional);
            }

            ProjectionPathSegment testToNullSegment = testToNullAnnotation.Segment;

            Expression testToNullThroughMethod = this.CallCheckValueForPathIsNull(
                testToNullSegment.StartPath.RootEntry,
                testToNullSegment.StartPath.ExpectedRootType,
                testToNullSegment.StartPath);

            Expression test = testToNullThroughMethod;
            Expression iftrue = Expression.Constant(null, assignForProjection.Type);
            Expression iffalse = assignForProjection;
            Expression result = Expression.Condition(test, iftrue, iffalse);
            return result;
        }

        private Expression RebindEntityMemberInit(MemberInitExpression init)
        {
            Debug.Assert(init != null, "init != null");
            Debug.Assert(init.Bindings.Count > 0, "init.Bindings.Count > 0 -- otherwise this is just empty construction");

            Expression[] expressions;
            if (!this.pathBuilder.HasRewrites)
            {
                MemberAssignmentAnalysis propertyAnalysis = MemberAssignmentAnalysis.Analyze(
                    this.pathBuilder.LambdaParameterInScope,
                    ((MemberAssignment)init.Bindings[0]).Expression);
                expressions = propertyAnalysis.GetExpressionsToTargetEntity();
                Debug.Assert(expressions.Length != 0, "expressions.Length != 0 -- otherwise there is no correlation to parameter in entity member init");
            }
            else
            {
                expressions = MemberAssignmentAnalysis.EmptyExpressionArray;
            }

            Expression entryParameterAtMemberInit = this.pathBuilder.ParameterEntryInScope;
            List<string> propertyNames = new List<string>();
            List<Func<object, object, Type, object>> propertyFunctions = new List<Func<object, object, Type, object>>();
            Type projectedType = init.NewExpression.Type;
            Expression projectedTypeExpression = Expression.Constant(projectedType, typeof(Type));

            Expression entryToInitValue;            Expression expectedParamValue;            ParameterExpression entryParameterForMembers;            ParameterExpression expectedParameterForMembers;            string[] expressionNames = expressions.Skip(1).Select(e => ((MemberExpression)e).Member.Name).ToArray();
            if (expressions.Length <= 1)
            {
                entryToInitValue = this.pathBuilder.ParameterEntryInScope;
                expectedParamValue = this.pathBuilder.ExpectedParamTypeInScope;
                entryParameterForMembers = (ParameterExpression)this.pathBuilder.ParameterEntryInScope;
                expectedParameterForMembers = (ParameterExpression)this.pathBuilder.ExpectedParamTypeInScope;
            }
            else
            {
                entryToInitValue = this.GetDeepestEntry(expressions);
                expectedParamValue = projectedTypeExpression;
                entryParameterForMembers = Expression.Parameter(typeof(object), "subentry" + this.identifierId++);
                expectedParameterForMembers = (ParameterExpression)this.pathBuilder.ExpectedParamTypeInScope;

                ProjectionPath entryPath = new ProjectionPath(
                    (ParameterExpression)this.pathBuilder.LambdaParameterInScope, 
                    this.pathBuilder.ExpectedParamTypeInScope, 
                    this.pathBuilder.ParameterEntryInScope,
                    expressions.Skip(1));

                this.annotations.Add(entryToInitValue, new ExpressionAnnotation() { Segment = entryPath[entryPath.Count - 1] });
                this.annotations.Add(entryParameterForMembers, new ExpressionAnnotation() { Segment = entryPath[entryPath.Count - 1] });
                this.pathBuilder.RegisterRewrite(this.pathBuilder.LambdaParameterInScope, expressionNames, entryParameterForMembers);
            }

            for (int i = 0; i < init.Bindings.Count; i++)
            {
                MemberAssignment assignment = (MemberAssignment)init.Bindings[i];
                propertyNames.Add(assignment.Member.Name);

                LambdaExpression propertyLambda;

                if ((ClientType.CheckElementTypeIsEntity(assignment.Member.ReflectedType) &&
                     assignment.Expression.NodeType == ExpressionType.MemberInit))
                {
                    Expression nestedEntry = CallMaterializer(
                        "ProjectionGetEntry",
                        entryParameterAtMemberInit,
                        Expression.Constant(assignment.Member.Name, typeof(string)));
                    ParameterExpression nestedEntryParameter = Expression.Parameter(
                        typeof(object),
                        "subentry" + this.identifierId++);

                    ProjectionPath entryPath;
                    ExpressionAnnotation entryAnnotation;
                    if (this.annotations.TryGetValue(this.pathBuilder.ParameterEntryInScope, out entryAnnotation))
                    {
                        entryPath = new ProjectionPath(
                            (ParameterExpression)this.pathBuilder.LambdaParameterInScope,
                            this.pathBuilder.ExpectedParamTypeInScope,
                            entryParameterAtMemberInit);
                        entryPath.AddRange(entryAnnotation.Segment.StartPath);
                    }
                    else
                    {
                        entryPath = new ProjectionPath(
                            (ParameterExpression)this.pathBuilder.LambdaParameterInScope,
                            this.pathBuilder.ExpectedParamTypeInScope,
                            entryParameterAtMemberInit,
                            expressions.Skip(1));
                    }

                    ProjectionPathSegment nestedSegment = new ProjectionPathSegment(
                        entryPath,
                        assignment.Member.Name,
                        assignment.Member.ReflectedType);

                    entryPath.Add(nestedSegment);

                    string[] names = (entryPath.Where(m => m.Member != null).Select(m => m.Member)).ToArray();

                    this.annotations.Add(nestedEntryParameter, new ExpressionAnnotation() { Segment = nestedSegment });
                    this.pathBuilder.RegisterRewrite(this.pathBuilder.LambdaParameterInScope, names, nestedEntryParameter);
                    Expression e = this.Visit(assignment.Expression);
                    this.pathBuilder.RevokeRewrite(this.pathBuilder.LambdaParameterInScope, names);
                    this.annotations.Remove(nestedEntryParameter);

                    e = Expression.Convert(e, typeof(object));
                    ParameterExpression[] parameters =
                        new ParameterExpression[] 
                        {
                            this.materializerExpression,
                            nestedEntryParameter,
                            expectedParameterForMembers,
                        };
                    propertyLambda = Expression.Lambda(e, parameters);

                    Expression[] nestedParams =
                        new Expression[]
                        {
                            this.materializerExpression, 
                            nestedEntry,
                            expectedParameterForMembers,
                        };
                    var invokeParameters =
                        new ParameterExpression[] 
                        {
                            this.materializerExpression,
                            (ParameterExpression)entryParameterAtMemberInit,
                            expectedParameterForMembers,
                        };
                    propertyLambda = Expression.Lambda(Expression.Invoke(propertyLambda, nestedParams), invokeParameters);
                }
                else
                {
                    Expression e = this.Visit(assignment.Expression);
                    e = Expression.Convert(e, typeof(object));
                    ParameterExpression[] parameters =
                        new ParameterExpression[] 
                        {
                            this.materializerExpression,
                            entryParameterForMembers,
                            expectedParameterForMembers,
                        };
                    propertyLambda = Expression.Lambda(e, parameters);
                }

#if TRACE_CLIENT_PROJECTIONS
                Trace.WriteLine("Compiling lambda for " + assignment.Member.Name + ": " + propertyLambda);
#endif
                propertyFunctions.Add((Func<object, object, Type, object>) propertyLambda.Compile());
            }

            for (int i = 1; i < expressions.Length; i++)
            {
                this.pathBuilder.RevokeRewrite(this.pathBuilder.LambdaParameterInScope, expressionNames);
                this.annotations.Remove(entryToInitValue);
                this.annotations.Remove(entryParameterForMembers);
            }

            Expression reboundExpression = CallMaterializer(
                "ProjectionInitializeEntity",
                this.materializerExpression,
                entryToInitValue,
                expectedParamValue,
                projectedTypeExpression,
                Expression.Constant(propertyNames.ToArray()),
                Expression.Constant(propertyFunctions.ToArray()));

            return Expression.Convert(reboundExpression, projectedType);
        }

        private Expression GetDeepestEntry(Expression[] path)
        {
            Debug.Assert(path.Length > 1, "path.Length > 1");
            
            Expression result = null;
            int pathIndex = 1;
            do
            {
                result = CallMaterializer(
                    "ProjectionGetEntry",
                    result ?? this.pathBuilder.ParameterEntryInScope,
                    Expression.Constant(((MemberExpression)path[pathIndex]).Member.Name, typeof(string)));
                pathIndex++;
            }
            while (pathIndex < path.Length);

            return result;
        }

        private Expression GetExpressionBeforeNormalization(Expression expression)
        {
            Debug.Assert(expression != null, "expression != null");
            if (this.normalizerRewrites != null)
            {
                Expression original;
                if (this.normalizerRewrites.TryGetValue(expression, out original))
                {
                    expression = original;
                }
            }

            return expression;
        }

        private Expression RebindParameter(Expression expression, ExpressionAnnotation annotation)
        {
            Debug.Assert(expression != null, "expression != null");
            Debug.Assert(annotation != null, "annotation != null");

            Expression result;
            result = this.CallValueForPathWithType(
                annotation.Segment.StartPath.RootEntry,
                annotation.Segment.StartPath.ExpectedRootType,
                annotation.Segment.StartPath,
                expression.Type);

            ProjectionPath parameterPath = new ProjectionPath(
                annotation.Segment.StartPath.Root,
                annotation.Segment.StartPath.ExpectedRootType,
                annotation.Segment.StartPath.RootEntry);
            ProjectionPathSegment parameterSegment = new ProjectionPathSegment(parameterPath, null, null);
            parameterPath.Add(parameterSegment);
            this.annotations[expression] = new ExpressionAnnotation() { Segment = parameterSegment };

            return result;
        }

        private Expression RebindMemberAccess(MemberExpression m, ExpressionAnnotation baseAnnotation)
        {
            Debug.Assert(m != null, "m != null");
            Debug.Assert(baseAnnotation != null, "baseAnnotation != null");

            ProjectionPathSegment memberSegment;

            Expression baseSourceExpression = m.Expression;
            Expression result = this.pathBuilder.GetRewrite(baseSourceExpression);
            if (result != null)
            {
                Expression baseTypeExpression = Expression.Constant(baseSourceExpression.Type, typeof(Type));
                ProjectionPath nestedPath = new ProjectionPath(result as ParameterExpression, baseTypeExpression, result);
                ProjectionPathSegment nestedSegment = new ProjectionPathSegment(nestedPath, m.Member.Name, m.Type);
                nestedPath.Add(nestedSegment);
                result = this.CallValueForPathWithType(result, baseTypeExpression, nestedPath, m.Type);
            }
            else
            {
                memberSegment = new ProjectionPathSegment(baseAnnotation.Segment.StartPath, m.Member.Name, m.Type);
                baseAnnotation.Segment.StartPath.Add(memberSegment);
                result = this.CallValueForPathWithType(
                    baseAnnotation.Segment.StartPath.RootEntry,
                    baseAnnotation.Segment.StartPath.ExpectedRootType,
                    baseAnnotation.Segment.StartPath,
                    m.Type);
            }

            return result;
        }

        private NewExpression RebindNewExpressionForDataServiceCollectionOfT(NewExpression nex)
        {
            Debug.Assert(nex != null, "nex != null");
            Debug.Assert(
                ResourceBinder.PatternRules.MatchNewDataServiceCollectionOfT(nex),
                "Called should have checked that the 'new' was for our collection type");

            NewExpression result = base.VisitNew(nex);

            ExpressionAnnotation annotation = null;

            if (result != null)
            {
                ConstructorInfo constructorInfo = 
                    nex.Type.GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance).First(
                        c => c.GetParameters().Length == 7 && c.GetParameters()[0].ParameterType == typeof(object));

                Type enumerable = typeof(IEnumerable<>).MakeGenericType(nex.Type.GetGenericArguments()[0]);

                if (result.Arguments.Count == 1 && result.Constructor == nex.Type.GetConstructor(new[] { enumerable }) &&
                    this.annotations.TryGetValue(result.Arguments[0], out annotation))
                {
                    result = Expression.New(
                        constructorInfo,
                        this.materializerExpression,
                        Expression.Constant(null, typeof(DataServiceContext)),
                        result.Arguments[0],
                        Expression.Constant(TrackingMode.AutoChangeTracking, typeof(TrackingMode)),
                        Expression.Constant(null, typeof(string)),
                        Expression.Constant(null, typeof(Func<EntityChangedParams, bool>)),
                        Expression.Constant(null, typeof(Func<EntityCollectionChangedParams, bool>)));
                }
                else if (result.Arguments.Count == 2 &&
                         this.annotations.TryGetValue(result.Arguments[0], out annotation))
                {
                    result = Expression.New(
                        constructorInfo, 
                        this.materializerExpression,
                        Expression.Constant(null, typeof(DataServiceContext)),
                        result.Arguments[0],                        result.Arguments[1],                        Expression.Constant(null, typeof(string)),
                        Expression.Constant(null, typeof(Func<EntityChangedParams, bool>)),
                        Expression.Constant(null, typeof(Func<EntityCollectionChangedParams, bool>)));
                }
                else if (result.Arguments.Count == 5 &&
                         this.annotations.TryGetValue(result.Arguments[0], out annotation))
                {
                    result = Expression.New(
                        constructorInfo, 
                        this.materializerExpression,
                        Expression.Constant(null, typeof(DataServiceContext)),
                        result.Arguments[0],                        result.Arguments[1],                        result.Arguments[2],                        result.Arguments[3],                        result.Arguments[4]);                }
                else if (result.Arguments.Count == 6 &&
                         typeof(DataServiceContext).IsAssignableFrom(result.Arguments[0].Type) &&
                         this.annotations.TryGetValue(result.Arguments[1], out annotation))
                {
                    result = Expression.New(
                        constructorInfo,
                        this.materializerExpression,
                        result.Arguments[0],                        result.Arguments[1],                        result.Arguments[2],                        result.Arguments[3],                        result.Arguments[4],                        result.Arguments[5]);                }
            }

            if (annotation != null)
            {
                this.annotations.Add(result, annotation);
            }

            return result;
        }

        private Expression RebindMethodCallForMemberSelect(MethodCallExpression call)
        {
            Debug.Assert(call != null, "call != null");
            Debug.Assert(call.Method.Name == "Select", "call.Method.Name == 'Select'");
            Debug.Assert(call.Object == null, "call.Object == null -- otherwise this isn't a call to a static Select method");
            Debug.Assert(call.Arguments.Count == 2, "call.Arguments.Count == 2 -- otherwise this isn't the expected Select() call on IQueryable");

            Expression result = null;
            Expression parameterSource = this.Visit(call.Arguments[0]);
            ExpressionAnnotation annotation;
            this.annotations.TryGetValue(parameterSource, out annotation);

            if (annotation != null)
            {
                Expression selectorExpression = this.Visit(call.Arguments[1]);
                Type returnElementType = call.Method.ReturnType.GetGenericArguments()[0];
                result = CallMaterializer(
                    "ProjectionSelect",
                    this.materializerExpression,
                    this.pathBuilder.ParameterEntryInScope,
                    this.pathBuilder.ExpectedParamTypeInScope,
                    Expression.Constant(returnElementType, typeof(Type)),
                    Expression.Constant(annotation.Segment.StartPath, typeof(object)),
                    selectorExpression);
                this.annotations.Add(result, annotation);
                result = CallMaterializerWithType(
                    "EnumerateAsElementType",
                    new Type[] { returnElementType },
                    result);
                this.annotations.Add(result, annotation);
            }

            if (result == null)
            {
                result = base.VisitMethodCall(call);
            }

            return result;
        }

        private Expression RebindMethodCallForMemberToList(MethodCallExpression call)
        {
            Debug.Assert(call != null, "call != null");
            Debug.Assert(call.Object == null, "call.Object == null -- otherwise this isn't a call to a static ToList method");
            Debug.Assert(call.Method.Name == "ToList", "call.Method.Name == 'ToList'");

            Debug.Assert(call.Arguments.Count == 1, "call.Arguments.Count == 1 -- otherwise this isn't the expected ToList() call on IEnumerable");

            Expression result = this.Visit(call.Arguments[0]);
            ExpressionAnnotation annotation;
            if (this.annotations.TryGetValue(result, out annotation))
            {
                result = this.TypedEnumerableToList(result, call.Type);
                this.annotations.Add(result, annotation);
            }

            return result;
        }

        private Expression RebindMethodCallForNewSequence(MethodCallExpression call)
        {
            Debug.Assert(call != null, "call != null");
            Debug.Assert(ProjectionAnalyzer.IsMethodCallAllowedEntitySequence(call), "ProjectionAnalyzer.IsMethodCallAllowedEntitySequence(call)");
            Debug.Assert(call.Object == null, "call.Object == null -- otherwise this isn't the supported Select or ToList methods");

            Expression result = null;

            if (call.Method.Name == "Select")
            {
                Debug.Assert(call.Arguments.Count == 2, "call.Arguments.Count == 2 -- otherwise this isn't the argument we expected");

                Expression parameterSource = this.Visit(call.Arguments[0]);
                ExpressionAnnotation annotation;
                this.annotations.TryGetValue(parameterSource, out annotation);

                if (annotation != null)
                {
                    Expression selectorExpression = this.Visit(call.Arguments[1]);
                    Type returnElementType = call.Method.ReturnType.GetGenericArguments()[0];
                    result = CallMaterializer(
                        "ProjectionSelect",
                        this.materializerExpression,
                        this.pathBuilder.ParameterEntryInScope,
                        this.pathBuilder.ExpectedParamTypeInScope,
                        Expression.Constant(returnElementType, typeof(Type)),
                        Expression.Constant(annotation.Segment.StartPath, typeof(object)),
                        selectorExpression);
                    this.annotations.Add(result, annotation);
                    result = CallMaterializerWithType(
                        "EnumerateAsElementType",
                        new Type[] { returnElementType },
                        result);
                    this.annotations.Add(result, annotation);
                }
            }
            else
            {
                Debug.Assert(call.Method.Name == "ToList", "call.Method.Name == 'ToList'");

                Expression source = this.Visit(call.Arguments[0]);
                ExpressionAnnotation annotation;
                if (this.annotations.TryGetValue(source, out annotation))
                {
                    result = this.TypedEnumerableToList(source, call.Type);
                    this.annotations.Add(result, annotation);
                }
            }

            if (result == null)
            {
                result = base.VisitMethodCall(call);
            }

            return result;
        }

        private Expression TypedEnumerableToList(Expression source, Type targetType)
        {
            Debug.Assert(source != null, "source != null");
            Debug.Assert(targetType != null, "targetType != null");

            Type enumeratedType = source.Type.GetGenericArguments()[0];
            Type listElementType = targetType.GetGenericArguments()[0];

            Expression result = CallMaterializerWithType(
                "ListAsElementType",
                new Type[] { enumeratedType, listElementType },
                this.materializerExpression,
                source);

            return result;
        }

        #endregion Private methods.

        #region Inner types.

        internal class ExpressionAnnotation
        {
            internal ProjectionPathSegment Segment 
            { 
                get; 
                set; 
            }
        }

        #endregion Inner types.
    }
}