1# Licensed to the Apache Software Foundation (ASF) under one
2# or more contributor license agreements.  See the NOTICE file
3# distributed with this work for additional information
4# regarding copyright ownership.  The ASF licenses this file
5# to you under the Apache License, Version 2.0 (the
6# "License"); you may not use this file except in compliance
7# with the License.  You may obtain a copy of the License at
8#
9#   http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing,
12# software distributed under the License is distributed on an
13# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14# KIND, either express or implied.  See the License for the
15# specific language governing permissions and limitations
16# under the License.
17
18module Gandiva
19  class ExpressionBuilder
20    class If
21      def initialize(condition)
22        @condition = condition
23        @then = nil
24        @else = nil
25      end
26
27      def then(clause)
28        @then = clause
29        self
30      end
31
32      def else(clause)
33        @else = clause
34        self
35      end
36
37      def elsif(condition)
38        Elsif.new(self, condition)
39      end
40
41      def build
42        build_if_node(condition_node,
43                      then_node,
44                      else_node)
45      end
46
47      protected
48      def condition_node
49        @condition.build
50      end
51
52      def then_node
53        @then&.build
54      end
55
56      def else_node
57        @else&.build
58      end
59
60      private
61      def build_if_node(condition_node, then_node, else_node)
62        if then_node and else_node
63          # TODO: Validate then_node.return_type == else_node.return_type
64          return_type = then_node.return_type
65        else
66          return_type = (then_node || else_node).return_type
67        end
68        IfNode.new(condition_node,
69                   then_node,
70                   else_node,
71                   return_type)
72      end
73    end
74  end
75end
76