/*
 * 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.
 */
package com.facebook.presto.sql.planner;

import com.facebook.presto.sql.planner.iterative.GroupReference;
import com.facebook.presto.sql.planner.iterative.Lookup;
import com.facebook.presto.sql.planner.plan.AggregationNode;
import com.facebook.presto.sql.planner.plan.ApplyNode;
import com.facebook.presto.sql.planner.plan.FilterNode;
import com.facebook.presto.sql.planner.plan.JoinNode;
import com.facebook.presto.sql.planner.plan.PlanNode;
import com.facebook.presto.sql.planner.plan.ProjectNode;
import com.facebook.presto.sql.planner.plan.TableScanNode;
import com.facebook.presto.sql.planner.plan.ValuesNode;
import com.facebook.presto.sql.tree.Expression;
import com.google.common.collect.ImmutableList;

import java.util.List;
import java.util.Optional;

import static com.google.common.base.Preconditions.checkState;
import static java.util.Objects.requireNonNull;

public class ExpressionExtractor
{
    public static List<Expression> extractExpressions(PlanNode plan)
    {
        ImmutableList.Builder<Expression> expressionsBuilder = ImmutableList.builder();
        plan.accept(new Visitor(true), expressionsBuilder);
        return expressionsBuilder.build();
    }

    public static List<Expression> extractExpressions(PlanNode plan, Lookup lookup)
    {
        ImmutableList.Builder<Expression> expressionsBuilder = ImmutableList.builder();
        plan.accept(new Visitor(true, lookup), expressionsBuilder);
        return expressionsBuilder.build();
    }

    public static List<Expression> extractExpressionsNonRecursive(PlanNode plan)
    {
        ImmutableList.Builder<Expression> expressionsBuilder = ImmutableList.builder();
        plan.accept(new Visitor(false), expressionsBuilder);
        return expressionsBuilder.build();
    }

    private ExpressionExtractor()
    {
    }

    private static class Visitor
            extends SimplePlanVisitor<ImmutableList.Builder<Expression>>
    {
        private final boolean recursive;
        private final Optional<Lookup> lookup;

        public Visitor(boolean recursive)
        {
            this(recursive, Optional.empty());
        }

        public Visitor(boolean recursive, Lookup lookup)
        {
            this(recursive, Optional.of(lookup));
        }

        private Visitor(boolean recursive, Optional<Lookup> lookup)
        {
            this.recursive = recursive;
            this.lookup = requireNonNull(lookup, "lookup is null");
        }

        @Override
        protected Void visitPlan(PlanNode node, ImmutableList.Builder<Expression> context)
        {
            if (node instanceof GroupReference) {
                checkState(lookup.isPresent(), "Cannot extract expressions in iterative optimizer without providing a Lookup method");
                return lookup.get().resolve(node).accept(this, context);
            }

            if (recursive) {
                return super.visitPlan(node, context);
            }
            return null;
        }

        @Override
        public Void visitAggregation(AggregationNode node, ImmutableList.Builder<Expression> context)
        {
            node.getAssignments().values()
                    .forEach(aggregation -> context.add(aggregation.getCall()));
            return super.visitAggregation(node, context);
        }

        @Override
        public Void visitFilter(FilterNode node, ImmutableList.Builder<Expression> context)
        {
            context.add(node.getPredicate());
            return super.visitFilter(node, context);
        }

        @Override
        public Void visitProject(ProjectNode node, ImmutableList.Builder<Expression> context)
        {
            context.addAll(node.getAssignments().getExpressions());
            return super.visitProject(node, context);
        }

        @Override
        public Void visitTableScan(TableScanNode node, ImmutableList.Builder<Expression> context)
        {
            if (node.getOriginalConstraint() != null) {
                context.add(node.getOriginalConstraint());
            }
            return super.visitTableScan(node, context);
        }

        @Override
        public Void visitJoin(JoinNode node, ImmutableList.Builder<Expression> context)
        {
            node.getFilter().ifPresent(context::add);
            return super.visitJoin(node, context);
        }

        @Override
        public Void visitValues(ValuesNode node, ImmutableList.Builder<Expression> context)
        {
            node.getRows().forEach(context::addAll);
            return super.visitValues(node, context);
        }

        @Override
        public Void visitApply(ApplyNode node, ImmutableList.Builder<Expression> context)
        {
            context.addAll(node.getSubqueryAssignments().getExpressions());
            return super.visitApply(node, context);
        }
    }
}

@@ -1295,97 +1295,80 @@
 st;%0A
-import java.util.Optional;%0A%0Aimport static com.google.common.base.Preconditions.checkState
+%0Aimport static com.facebook.presto.sql.planner.iterative.Lookup.noLookup
 ;%0Aim
@@ -1536,188 +1536,50 @@
     
-ImmutableList.Builder%3CExpression%3E expressionsBuilder = ImmutableList.builder();%0A        plan.accept(new Visitor(true), expressionsBuilder);%0A        return expressionsBuilder.build(
+return extractExpressions(plan, noLookup()
 );%0A 
@@ -1666,32 +1666,129 @@
 p lookup)%0A    %7B%0A
+        requireNonNull(plan, %22plan is null%22);%0A        requireNonNull(lookup, %22lookup is null%22);%0A%0A
         Immutabl
@@ -2189,16 +2189,28 @@
 or(false
+, noLookup()
 ), expre
@@ -2497,32 +2497,22 @@
 e final 
-Optional%3C
 Lookup
-%3E
  lookup;
@@ -2525,297 +2525,41 @@
     
-public Visitor(boolean recursive)%0A        %7B%0A            this(recursive, Optional.empty());%0A        %7D%0A%0A        public Visitor(boolean recursive, Lookup lookup)%0A        %7B%0A            this(recursive, Optional.of(lookup));%0A        %7D%0A%0A        private Visitor(boolean recursive, Optional%3CLookup%3E
+Visitor(boolean recursive, Lookup
  loo
@@ -2831,183 +2831,90 @@
 if (
-node instanceof GroupReference) %7B%0A                checkState(lookup.isPresent(), %22C
+recursive) %7B%0A                return super.visitPl
 an
+(
 no
-t extract expressions in iterative optimizer without providing a Lookup method%22);%0A
+de, context);%0A      
       
+%7D%0A
     
@@ -2923,69 +2923,23 @@
     
+  
 return 
-lookup.get().resolve(node).accept(this, context);%0A    
+null;%0A
     
@@ -2957,73 +2957,112 @@
     
-    
-if (recursive) %7B%0A                return super.visitPlan(node,
+@Override%0A        public Void visitGroupReference(GroupReference node, ImmutableList.Builder%3CExpression%3E
  con
@@ -3058,33 +3058,32 @@
 ession%3E context)
-;
 %0A            %7D%0A 
@@ -3067,37 +3067,33 @@
 ontext)%0A        
-    %7D
+%7B
 %0A            ret
@@ -3088,36 +3088,74 @@
          return 
-null
+lookup.resolve(node).accept(this, context)
 ;%0A        %7D%0A%0A   

Use noLookup() Lookup stub in ExpressionExtractor