xronos /Microsoft.Scripting.Core/Ast/ExpressionVisitor.cs

Language C# Lines 791
MD5 Hash c9f1eec4646560fa3c357cd3fc45844c Estimated Cost $11,219 (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
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
/* ****************************************************************************
 *
 * 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.ObjectModel;
using System.Diagnostics;
#if CODEPLEX_40
using System.Dynamic.Utils;
#else
using Microsoft.Scripting.Utils;
#endif
using System.Runtime.CompilerServices;
#if !CODEPLEX_40
using Microsoft.Runtime.CompilerServices;
#endif


#if CODEPLEX_40
namespace System.Linq.Expressions {
#else
namespace Microsoft.Linq.Expressions {
#endif

    /// <summary>
    /// Represents a visitor or rewriter for expression trees.
    /// </summary>
    /// <remarks>
    /// This class is designed to be inherited to create more specialized
    /// classes whose functionality requires traversing, examining or copying
    /// an expression tree.
    /// </remarks>
    public abstract class ExpressionVisitor {

        /// <summary>
        /// Initializes a new instance of <see cref="ExpressionVisitor"/>.
        /// </summary>
        protected ExpressionVisitor() {
        }

        /// <summary>
        /// Dispatches the expression to one of the more specialized visit methods in this class.
        /// </summary>
        /// <param name="node">The expression to visit.</param>
        /// <returns>The modified expression, if it or any subexpression was modified;
        /// otherwise, returns the original expression.</returns>
        public virtual Expression Visit(Expression node) {
            if (node != null) {
                return node.Accept(this);
            }
            return null;
        }

        /// <summary>
        /// Dispatches the list of expressions to one of the more specialized visit methods in this class.
        /// </summary>
        /// <param name="nodes">The expressions to visit.</param>
        /// <returns>The modified expression list, if any of the elements were modified;
        /// otherwise, returns the original expression list.</returns>
        protected ReadOnlyCollection<Expression> Visit(ReadOnlyCollection<Expression> nodes) {
            Expression[] newNodes = null;
            for (int i = 0, n = nodes.Count; i < n; i++) {
                Expression node = Visit(nodes[i]);

                if (newNodes != null) {
                    newNodes[i] = node;
                } else if (!object.ReferenceEquals(node, nodes[i])) {
                    newNodes = new Expression[n];
                    for (int j = 0; j < i; j++) {
                        newNodes[j] = nodes[j];
                    }
                    newNodes[i] = node;
                }
            }
            if (newNodes == null) {
                return nodes;
            }
            return new TrueReadOnlyCollection<Expression>(newNodes);
        }

        internal Expression[] VisitArguments(IArgumentProvider nodes) {
            Expression[] newNodes = null;
            for (int i = 0, n = nodes.ArgumentCount; i < n; i++) {
                Expression curNode = nodes.GetArgument(i);
                Expression node = Visit(curNode);

                if (newNodes != null) {
                    newNodes[i] = node;
                } else if (!object.ReferenceEquals(node, curNode)) {
                    newNodes = new Expression[n];
                    for (int j = 0; j < i; j++) {
                        newNodes[j] = nodes.GetArgument(j);
                    }
                    newNodes[i] = node;
                }
            }
            return newNodes;
        }

        /// <summary>
        /// Visits all nodes in the collection using a specified element visitor.
        /// </summary>
        /// <typeparam name="T">The type of the nodes.</typeparam>
        /// <param name="nodes">The nodes to visit.</param>
        /// <param name="elementVisitor">A delegate that visits a single element,
        /// optionally replacing it with a new element.</param>
        /// <returns>The modified node list, if any of the elements were modified;
        /// otherwise, returns the original node list.</returns>
        protected static ReadOnlyCollection<T> Visit<T>(ReadOnlyCollection<T> nodes, Func<T, T> elementVisitor) {
            T[] newNodes = null;
            for (int i = 0, n = nodes.Count; i < n; i++) {
                T node = elementVisitor(nodes[i]);
                if (newNodes != null) {
                    newNodes[i] = node;
                } else if (!object.ReferenceEquals(node, nodes[i])) {
                    newNodes = new T[n];
                    for (int j = 0; j < i; j++) {
                        newNodes[j] = nodes[j];
                    }
                    newNodes[i] = node;
                }
            }
            if (newNodes == null) {
                return nodes;
            }
            return new TrueReadOnlyCollection<T>(newNodes);
        }

        /// <summary>
        /// Visits an expression, casting the result back to the original expression type.
        /// </summary>
        /// <typeparam name="T">The type of the expression.</typeparam>
        /// <param name="node">The expression to visit.</param>
        /// <param name="callerName">The name of the calling method; used to report to report a better error message.</param>
        /// <returns>The modified expression, if it or any subexpression was modified;
        /// otherwise, returns the original expression.</returns>
        /// <exception cref="InvalidOperationException">The visit method for this node returned a different type.</exception>
        protected T VisitAndConvert<T>(T node, string callerName) where T : Expression {
            if (node == null) {
                return null;
            }
            node = Visit(node) as T;
            if (node == null) {
                throw Error.MustRewriteToSameNode(callerName, typeof(T), callerName);
            }
            return node;
        }

        /// <summary>
        /// Visits an expression, casting the result back to the original expression type.
        /// </summary>
        /// <typeparam name="T">The type of the expression.</typeparam>
        /// <param name="nodes">The expression to visit.</param>
        /// <param name="callerName">The name of the calling method; used to report to report a better error message.</param>
        /// <returns>The modified expression, if it or any subexpression was modified;
        /// otherwise, returns the original expression.</returns>
        /// <exception cref="InvalidOperationException">The visit method for this node returned a different type.</exception>
        protected ReadOnlyCollection<T> VisitAndConvert<T>(ReadOnlyCollection<T> nodes, string callerName) where T : Expression {
            T[] newNodes = null;
            for (int i = 0, n = nodes.Count; i < n; i++) {
                T node = Visit(nodes[i]) as T;
                if (node == null) {
                    throw Error.MustRewriteToSameNode(callerName, typeof(T), callerName);
                }

                if (newNodes != null) {
                    newNodes[i] = node;
                } else if (!object.ReferenceEquals(node, nodes[i])) {
                    newNodes = new T[n];
                    for (int j = 0; j < i; j++) {
                        newNodes[j] = nodes[j];
                    }
                    newNodes[i] = node;
                }
            }
            if (newNodes == null) {
                return nodes;
            }
            return new TrueReadOnlyCollection<T>(newNodes);
        }

        /// <summary>
        /// Visits the children of the <see cref="BinaryExpression" />.
        /// </summary>
        /// <param name="node">The expression to visit.</param>
        /// <returns>The modified expression, if it or any subexpression was modified;
        /// otherwise, returns the original expression.</returns>
        protected internal virtual Expression VisitBinary(BinaryExpression node) {
            // Walk children in evaluation order: left, conversion, right
            Expression l = Visit(node.Left);
            LambdaExpression c = VisitAndConvert(node.Conversion, "VisitBinary");
            Expression r = Visit(node.Right);
            if (l == node.Left && r == node.Right && c == node.Conversion) {
                return node;
            }
            if (node.IsReferenceComparison) {
                if (node.NodeType == ExpressionType.Equal) {
                    return Expression.ReferenceEqual(l, r);
                } else {
                    return Expression.ReferenceNotEqual(l, r);
                }
            }
            var result = Expression.MakeBinary(node.NodeType, l, r, node.IsLiftedToNull, node.Method, c);
            ValidateBinary(node, result);
            return result;
        }

        /// <summary>
        /// Visits the children of the <see cref="BlockExpression" />.
        /// </summary>
        /// <param name="node">The expression to visit.</param>
        /// <returns>The modified expression, if it or any subexpression was modified;
        /// otherwise, returns the original expression.</returns>
        protected internal virtual Expression VisitBlock(BlockExpression node) {
            int count = node.ExpressionCount;
            Expression[] nodes = null;
            for (int i = 0; i < count; i++) {
                Expression oldNode = node.GetExpression(i);
                Expression newNode = Visit(oldNode);

                if (oldNode != newNode) {
                    if (nodes == null) {
                        nodes = new Expression[count];
                    }
                    nodes[i] = newNode;
                }
            }
            var v = VisitAndConvert(node.Variables, "VisitBlock");

            if (v == node.Variables && nodes == null) {
                return node;
            } else {
                for (int i = 0; i < count; i++) {
                    if (nodes[i] == null) {
                        nodes[i] = node.GetExpression(i);
                    }
                }
            }

            return node.Rewrite(v, nodes);
        }

        /// <summary>
        /// Visits the children of the <see cref="ConditionalExpression" />.
        /// </summary>
        /// <param name="node">The expression to visit.</param>
        /// <returns>The modified expression, if it or any subexpression was modified;
        /// otherwise, returns the original expression.</returns>
        protected internal virtual Expression VisitConditional(ConditionalExpression node) {
            Expression t = Visit(node.Test);
            Expression l = Visit(node.IfTrue);
            Expression r = Visit(node.IfFalse);
            if (t == node.Test && l == node.IfTrue && r == node.IfFalse) {
                return node;
            }
            return Expression.Condition(t, l, r, node.Type);
        }

        /// <summary>
        /// Visits the <see cref="ConstantExpression" />.
        /// </summary>
        /// <param name="node">The expression to visit.</param>
        /// <returns>The modified expression, if it or any subexpression was modified;
        /// otherwise, returns the original expression.</returns>
        protected internal virtual Expression VisitConstant(ConstantExpression node) {
            return node;
        }

        /// <summary>
        /// Visits the <see cref="DebugInfoExpression" />.
        /// </summary>
        /// <param name="node">The expression to visit.</param>
        /// <returns>The modified expression, if it or any subexpression was modified;
        /// otherwise, returns the original expression.</returns>
        protected internal virtual Expression VisitDebugInfo(DebugInfoExpression node) {
            return node;
        }

        /// <summary>
        /// Visits the children of the <see cref="DynamicExpression" />.
        /// </summary>
        /// <param name="node">The expression to visit.</param>
        /// <returns>The modified expression, if it or any subexpression was modified;
        /// otherwise, returns the original expression.</returns>
        protected internal virtual Expression VisitDynamic(DynamicExpression node) {
            Expression[] a = VisitArguments((IArgumentProvider)node);
            if (a == null) {
                return node;
            }

            return node.Rewrite(a);
        }

        /// <summary>
        /// Visits the <see cref="DefaultExpression" />.
        /// </summary>
        /// <param name="node">The expression to visit.</param>
        /// <returns>The modified expression, if it or any subexpression was modified;
        /// otherwise, returns the original expression.</returns>
        protected internal virtual Expression VisitDefault(DefaultExpression node) {
            return node;
        }

        /// <summary>
        /// Visits the children of the extension expression.
        /// </summary>
        /// <param name="node">The expression to visit.</param>
        /// <returns>The modified expression, if it or any subexpression was modified;
        /// otherwise, returns the original expression.</returns>
        /// <remarks>
        /// This can be overridden to visit or rewrite specific extension nodes.
        /// If it is not overridden, this method will call <see cref="Expression.VisitChildren" />,
        /// which gives the node a chance to walk its children. By default,
        /// <see cref="Expression.VisitChildren" /> will try to reduce the node.
        /// </remarks>
        protected internal virtual Expression VisitExtension(Expression node) {
            return node.VisitChildren(this.Visit);
        }

        /// <summary>
        /// Visits the children of the <see cref="GotoExpression" />.
        /// </summary>
        /// <param name="node">The expression to visit.</param>
        /// <returns>The modified expression, if it or any subexpression was modified;
        /// otherwise, returns the original expression.</returns>
        protected internal virtual Expression VisitGoto(GotoExpression node) {
            LabelTarget t = VisitLabelTarget(node.Target);
            Expression v = Visit(node.Value);
            if (t == node.Target && v == node.Value) {
                return node;
            }
            return Expression.MakeGoto(node.Kind, t, v, node.Type);
        }

        /// <summary>
        /// Visits the children of the <see cref="InvocationExpression" />.
        /// </summary>
        /// <param name="node">The expression to visit.</param>
        /// <returns>The modified expression, if it or any subexpression was modified;
        /// otherwise, returns the original expression.</returns>
        protected internal virtual Expression VisitInvocation(InvocationExpression node) {
            Expression e = Visit(node.Expression);
            Expression[] a = VisitArguments(node);
            if (e == node.Expression && a == null) {
                return node;
            }

            return node.Rewrite(e, a);
        }

        /// <summary>
        /// Visits the <see cref="LabelTarget" />.
        /// </summary>
        /// <param name="node">The expression to visit.</param>
        /// <returns>The modified expression, if it or any subexpression was modified;
        /// otherwise, returns the original expression.</returns>
        protected virtual LabelTarget VisitLabelTarget(LabelTarget node) {
            return node;
        }

        /// <summary>
        /// Visits the children of the <see cref="LabelExpression" />.
        /// </summary>
        /// <param name="node">The expression to visit.</param>
        /// <returns>The modified expression, if it or any subexpression was modified;
        /// otherwise, returns the original expression.</returns>
        protected internal virtual Expression VisitLabel(LabelExpression node) {
            LabelTarget l = VisitLabelTarget(node.Target);
            Expression d = Visit(node.DefaultValue);
            if (l == node.Target && d == node.DefaultValue) {
                return node;
            }
            return Expression.Label(l, d);
        }

        /// <summary>
        /// Visits the children of the <see cref="Expression&lt;T&gt;" />.
        /// </summary>
        /// <typeparam name="T">The type of the delegate.</typeparam>
        /// <param name="node">The expression to visit.</param>
        /// <returns>The modified expression, if it or any subexpression was modified;
        /// otherwise, returns the original expression.</returns>
        protected internal virtual Expression VisitLambda<T>(Expression<T> node) {
            Expression b = Visit(node.Body);
            var p = VisitAndConvert(node.Parameters, "VisitLambda");
            if (b == node.Body && p == node.Parameters) {
                return node;
            }
            return Expression.Lambda<T>(b, node.Name, p);
        }

        /// <summary>
        /// Visits the children of the <see cref="LoopExpression" />.
        /// </summary>
        /// <param name="node">The expression to visit.</param>
        /// <returns>The modified expression, if it or any subexpression was modified;
        /// otherwise, returns the original expression.</returns>
        protected internal virtual Expression VisitLoop(LoopExpression node) {
            LabelTarget @break = VisitLabelTarget(node.BreakLabel);
            LabelTarget @continue = VisitLabelTarget(node.ContinueLabel);
            Expression b = Visit(node.Body);
            if (@break == node.BreakLabel &&
                @continue == node.ContinueLabel &&
                b == node.Body) {
                return node;
            }
            return Expression.Loop(b, @break, @continue);
        }

        /// <summary>
        /// Visits the children of the <see cref="MemberExpression" />.
        /// </summary>
        /// <param name="node">The expression to visit.</param>
        /// <returns>The modified expression, if it or any subexpression was modified;
        /// otherwise, returns the original expression.</returns>
        protected internal virtual Expression VisitMember(MemberExpression node) {
            Expression e = Visit(node.Expression);
            if (e == node.Expression) {
                return node;
            }
            return Expression.MakeMemberAccess(e, node.Member);
        }

        /// <summary>
        /// Visits the children of the <see cref="IndexExpression" />.
        /// </summary>
        /// <param name="node">The expression to visit.</param>
        /// <returns>The modified expression, if it or any subexpression was modified;
        /// otherwise, returns the original expression.</returns>
        protected internal virtual Expression VisitIndex(IndexExpression node) {
            Expression o = Visit(node.Object);
            Expression[] a = VisitArguments(node);
            if (o == node.Object && a == null) {
                return node;
            }

            return node.Rewrite(o, a);
        }

        /// <summary>
        /// Visits the children of the <see cref="MethodCallExpression" />.
        /// </summary>
        /// <param name="node">The expression to visit.</param>
        /// <returns>The modified expression, if it or any subexpression was modified;
        /// otherwise, returns the original expression.</returns>
        protected internal virtual Expression VisitMethodCall(MethodCallExpression node) {
            Expression o = Visit(node.Object);
            Expression[] a = VisitArguments((IArgumentProvider)node);
            if (o == node.Object && a == null) {
                return node;
            }

            return node.Rewrite(o, a);
        }

        /// <summary>
        /// Visits the children of the <see cref="NewArrayExpression" />.
        /// </summary>
        /// <param name="node">The expression to visit.</param>
        /// <returns>The modified expression, if it or any subexpression was modified;
        /// otherwise, returns the original expression.</returns>
        protected internal virtual Expression VisitNewArray(NewArrayExpression node) {
            ReadOnlyCollection<Expression> e = Visit(node.Expressions);
            if (e == node.Expressions) {
                return node;
            }
            if (node.NodeType == ExpressionType.NewArrayInit) {
                return Expression.NewArrayInit(node.Type.GetElementType(), e);
            }
            return Expression.NewArrayBounds(node.Type.GetElementType(), e);
        }

        /// <summary>
        /// Visits the children of the <see cref="NewExpression" />.
        /// </summary>
        /// <param name="node">The expression to visit.</param>
        /// <returns>The modified expression, if it or any subexpression was modified;
        /// otherwise, returns the original expression.</returns>
        protected internal virtual Expression VisitNew(NewExpression node) {
            ReadOnlyCollection<Expression> a = Visit(node.Arguments);
            if (a == node.Arguments) {
                return node;
            }
            if (node.Members != null) {
                return Expression.New(node.Constructor, a, node.Members);
            }
            return Expression.New(node.Constructor, a);
        }

        /// <summary>
        /// Visits the <see cref="ParameterExpression" />.
        /// </summary>
        /// <param name="node">The expression to visit.</param>
        /// <returns>The modified expression, if it or any subexpression was modified;
        /// otherwise, returns the original expression.</returns>
        protected internal virtual Expression VisitParameter(ParameterExpression node) {
            return node;
        }

        /// <summary>
        /// Visits the children of the <see cref="RuntimeVariablesExpression" />.
        /// </summary>
        /// <param name="node">The expression to visit.</param>
        /// <returns>The modified expression, if it or any subexpression was modified;
        /// otherwise, returns the original expression.</returns>
        protected internal virtual Expression VisitRuntimeVariables(RuntimeVariablesExpression node) {
            var v = VisitAndConvert(node.Variables, "VisitRuntimeVariables");
            if (v == node.Variables) {
                return node;
            }
            return Expression.RuntimeVariables(v);
        }

        /// <summary>
        /// Visits the children of the <see cref="SwitchCase" />.
        /// </summary>
        /// <param name="node">The expression to visit.</param>
        /// <returns>The modified expression, if it or any subexpression was modified;
        /// otherwise, returns the original expression.</returns>
        protected virtual SwitchCase VisitSwitchCase(SwitchCase node) {
            ReadOnlyCollection<Expression> t = Visit(node.TestValues);
            Expression b = Visit(node.Body);
            if (t == node.TestValues && b == node.Body) {
                return node;
            }
            return Expression.SwitchCase(b, t);
        }

        /// <summary>
        /// Visits the children of the <see cref="SwitchExpression" />.
        /// </summary>
        /// <param name="node">The expression to visit.</param>
        /// <returns>The modified expression, if it or any subexpression was modified;
        /// otherwise, returns the original expression.</returns>
        protected internal virtual Expression VisitSwitch(SwitchExpression node) {
            Expression s = Visit(node.SwitchValue);
            ReadOnlyCollection<SwitchCase> c = Visit(node.Cases, VisitSwitchCase);
            Expression d = Visit(node.DefaultBody);
            if (s == node.SwitchValue && c == node.Cases && d == node.DefaultBody) {
                return node;
            }
            var result = Expression.Switch(node.Type, s, d, node.Comparison, c);
            ValidateSwitch(node, result);
            return result;
        }

        /// <summary>
        /// Visits the children of the <see cref="CatchBlock" />.
        /// </summary>
        /// <param name="node">The expression to visit.</param>
        /// <returns>The modified expression, if it or any subexpression was modified;
        /// otherwise, returns the original expression.</returns>
        protected virtual CatchBlock VisitCatchBlock(CatchBlock node) {
            ParameterExpression v = VisitAndConvert(node.Variable, "VisitCatchBlock");
            Expression f = Visit(node.Filter);
            Expression b = Visit(node.Body);
            if (v == node.Variable && b == node.Body && f == node.Filter) {
                return node;
            }
            return Expression.MakeCatchBlock(node.Test, v, b, f);
        }

        /// <summary>
        /// Visits the children of the <see cref="TryExpression" />.
        /// </summary>
        /// <param name="node">The expression to visit.</param>
        /// <returns>The modified expression, if it or any subexpression was modified;
        /// otherwise, returns the original expression.</returns>
        protected internal virtual Expression VisitTry(TryExpression node) {
            Expression b = Visit(node.Body);
            ReadOnlyCollection<CatchBlock> h = Visit(node.Handlers, VisitCatchBlock);
            Expression y = Visit(node.Finally);
            Expression f = Visit(node.Fault);

            if (b == node.Body &&
                h == node.Handlers &&
                y == node.Finally &&
                f == node.Fault) {
                return node;
            }
            return Expression.MakeTry(node.Type, b, y, f, h);
        }

        /// <summary>
        /// Visits the children of the <see cref="TypeBinaryExpression" />.
        /// </summary>
        /// <param name="node">The expression to visit.</param>
        /// <returns>The modified expression, if it or any subexpression was modified;
        /// otherwise, returns the original expression.</returns>
        protected internal virtual Expression VisitTypeBinary(TypeBinaryExpression node) {
            Expression e = Visit(node.Expression);
            if (e == node.Expression) {
                return node;
            }
            if (node.NodeType == ExpressionType.TypeIs) {
                return Expression.TypeIs(e, node.TypeOperand);
            }
            return Expression.TypeEqual(e, node.TypeOperand);
        }

        /// <summary>
        /// Visits the children of the <see cref="UnaryExpression" />.
        /// </summary>
        /// <param name="node">The expression to visit.</param>
        /// <returns>The modified expression, if it or any subexpression was modified;
        /// otherwise, returns the original expression.</returns>
        protected internal virtual Expression VisitUnary(UnaryExpression node) {
            Expression o = Visit(node.Operand);
            if (o == node.Operand) {
                return node;
            }
            var result = Expression.MakeUnary(node.NodeType, o, node.Type, node.Method);
            ValidateUnary(node, result);
            return result;
        }

        /// <summary>
        /// Visits the children of the <see cref="MemberInitExpression" />.
        /// </summary>
        /// <param name="node">The expression to visit.</param>
        /// <returns>The modified expression, if it or any subexpression was modified;
        /// otherwise, returns the original expression.</returns>
        protected internal virtual Expression VisitMemberInit(MemberInitExpression node) {
            NewExpression n = VisitAndConvert(node.NewExpression, "VisitMemberInit");
            ReadOnlyCollection<MemberBinding> bindings = Visit(node.Bindings, VisitMemberBinding);
            if (n == node.NewExpression && bindings == node.Bindings) {
                return node;
            }
            return Expression.MemberInit(n, bindings);
        }

        /// <summary>
        /// Visits the children of the <see cref="ListInitExpression" />.
        /// </summary>
        /// <param name="node">The expression to visit.</param>
        /// <returns>The modified expression, if it or any subexpression was modified;
        /// otherwise, returns the original expression.</returns>
        protected internal virtual Expression VisitListInit(ListInitExpression node) {
            NewExpression n = VisitAndConvert(node.NewExpression, "VisitListInit");
            ReadOnlyCollection<ElementInit> initializers = Visit(node.Initializers, VisitElementInit);
            if (n == node.NewExpression && initializers == node.Initializers) {
                return node;
            }
            return Expression.ListInit(n, initializers);
        }

        /// <summary>
        /// Visits the children of the <see cref="ElementInit" />.
        /// </summary>
        /// <param name="node">The expression to visit.</param>
        /// <returns>The modified expression, if it or any subexpression was modified;
        /// otherwise, returns the original expression.</returns>
        protected virtual ElementInit VisitElementInit(ElementInit node) {
            ReadOnlyCollection<Expression> arguments = Visit(node.Arguments);
            if (arguments == node.Arguments) {
                return node;
            }
            return Expression.ElementInit(node.AddMethod, arguments);
        }

        /// <summary>
        /// Visits the children of the <see cref="MemberBinding" />.
        /// </summary>
        /// <param name="node">The expression to visit.</param>
        /// <returns>The modified expression, if it or any subexpression was modified;
        /// otherwise, returns the original expression.</returns>
        protected virtual MemberBinding VisitMemberBinding(MemberBinding node) {
            switch (node.BindingType) {
                case MemberBindingType.Assignment:
                    return VisitMemberAssignment((MemberAssignment)node);
                case MemberBindingType.MemberBinding:
                    return VisitMemberMemberBinding((MemberMemberBinding)node);
                case MemberBindingType.ListBinding:
                    return VisitMemberListBinding((MemberListBinding)node);
                default:
                    throw Error.UnhandledBindingType(node.BindingType);
            }
        }

        /// <summary>
        /// Visits the children of the <see cref="MemberAssignment" />.
        /// </summary>
        /// <param name="node">The expression to visit.</param>
        /// <returns>The modified expression, if it or any subexpression was modified;
        /// otherwise, returns the original expression.</returns>
        protected virtual MemberAssignment VisitMemberAssignment(MemberAssignment node) {
            Expression e = Visit(node.Expression);
            if (e == node.Expression) {
                return node;
            }
            return Expression.Bind(node.Member, e);
        }

        /// <summary>
        /// Visits the children of the <see cref="MemberMemberBinding" />.
        /// </summary>
        /// <param name="node">The expression to visit.</param>
        /// <returns>The modified expression, if it or any subexpression was modified;
        /// otherwise, returns the original expression.</returns>
        protected virtual MemberMemberBinding VisitMemberMemberBinding(MemberMemberBinding node) {
            ReadOnlyCollection<MemberBinding> bindings = Visit(node.Bindings, VisitMemberBinding);
            if (bindings == node.Bindings) {
                return node;
            }
            return Expression.MemberBind(node.Member, bindings);
        }

        /// <summary>
        /// Visits the children of the <see cref="MemberListBinding" />.
        /// </summary>
        /// <param name="node">The expression to visit.</param>
        /// <returns>The modified expression, if it or any subexpression was modified;
        /// otherwise, returns the original expression.</returns>
        protected virtual MemberListBinding VisitMemberListBinding(MemberListBinding node) {
            ReadOnlyCollection<ElementInit> initializers = Visit(node.Initializers, VisitElementInit);
            if (initializers == node.Initializers) {
                return node;
            }
            return Expression.ListBind(node.Member, initializers);
        }


        //
        // Prevent some common cases of invalid rewrites.
        //
        // Essentially, we don't want the rewritten node to be semantically
        // bound by the factory, which may do the wrong thing. Instead we
        // require derived classes to be explicit about what they want to do if
        // types change.
        //
        private static void ValidateUnary(UnaryExpression before, UnaryExpression after) {
            if (before.Method == null) {
                if (after.Method != null) {
                    throw Error.MustRewriteWithoutMethod(after.Method, "VisitUnary");
                }

                ValidateChildType(before.Operand.Type, after.Operand.Type, "VisitUnary");
            }
        }

        private static void ValidateBinary(BinaryExpression before, BinaryExpression after) {
            if (before.Method == null) {
                if (after.Method != null) {
                    throw Error.MustRewriteWithoutMethod(after.Method, "VisitBinary");
                }

                ValidateChildType(before.Left.Type, after.Left.Type, "VisitBinary");
                ValidateChildType(before.Right.Type, after.Right.Type, "VisitBinary");
            }
        }

        // We wouldn't need this if switch didn't infer the method.
        private static void ValidateSwitch(SwitchExpression before, SwitchExpression after) {
            // If we did not have a method, we don't want to bind to one,
            // it might not be the right thing.
            if (before.Comparison == null && after.Comparison != null) {
                throw Error.MustRewriteWithoutMethod(after.Comparison, "VisitSwitch");
            }
        }

        // Value types must stay as the same type, otherwise it's now a
        // different operation, e.g. adding two doubles vs adding two ints.
        private static void ValidateChildType(Type before, Type after, string methodName) {
            if (before.IsValueType) {
                if (before == after) {
                    // types are the same value type
                    return;
                }
            } else if (!after.IsValueType) {
                // both are reference types
                return;
            }

            // Otherwise, it's an invalid type change.
            throw Error.MustRewriteChildToSameType(before, after, methodName);
        }
    }
}
Back to Top