public void FreeVariableFinder_Basics()
        {
            var finder = new FreeVariableFinder();

            var x  = Expression.Parameter(typeof(int));
            var y  = Expression.Parameter(typeof(int));
            var z  = Expression.Parameter(typeof(int));
            var ex = Expression.Parameter(typeof(Exception));

            var e =
                Expression.Block(
                    new[] { x },
                    Expression.Lambda(
                        Expression.TryCatch(
                            Expression.Add(x, y),
                            Expression.Catch(
                                ex,
                                z
                                )
                            ),
                        y
                        )
                    );

            finder.Visit(e);

            CollectionAssert.AreEquivalent(new[] { z }, finder.FreeVariables.ToArray());
        }
Exemple #2
0
        /// <summary>
        /// Removes the variable used for a catch block if it's not used.
        /// </summary>
        /// <param name="catchBlock">The catch block to remove unused exception variables from.</param>
        /// <returns>The result of rewriting the catch block.</returns>
        private static CatchBlock RemoveUnusedVariables(CatchBlock catchBlock)
        {
            var variable = catchBlock.Variable;

            if (variable != null)
            {
                // REVIEW: This does a lot of repeated scanning of the same child nodes.
                //         We could consider storing these results for later reuse.

                var finder = new FreeVariableFinder();

                finder.Visit(catchBlock.Filter);
                finder.Visit(catchBlock.Body);

                var freeVariables = finder.FreeVariables;

                if (!freeVariables.Contains(variable))
                {
                    return(catchBlock.Update(variable: null, catchBlock.Filter, catchBlock.Body));
                }
            }

            return(catchBlock);
        }