blob: 769762895efca233c715cae3ff490f1e1d90a0c4 [file] [log] [blame]
Damien Martin-Guillerezf88f4d82015-09-25 13:56:55 +00001// Copyright 2014 The Bazel Authors. All rights reserved.
Francois-Rene Rideau6fc5ee72015-03-12 20:55:17 +00002//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
Francois-Rene Rideau6fc5ee72015-03-12 20:55:17 +000014package com.google.devtools.build.lib.syntax;
15
brandjone2ffd5d2017-06-27 18:14:54 +020016import java.io.IOException;
Florian Weikert1bf1c972015-11-09 16:06:49 +000017
janakr76de1ad2018-03-03 11:12:36 -080018/** Syntax node for an if/else expression. */
Francois-Rene Rideau6fc5ee72015-03-12 20:55:17 +000019public final class ConditionalExpression extends Expression {
20
21 // Python conditional expressions: $thenCase if $condition else $elseCase
22 // https://docs.python.org/3.5/reference/expressions.html#conditional-expressions
23 private final Expression thenCase;
24 private final Expression condition;
25 private final Expression elseCase;
26
27 public Expression getThenCase() { return thenCase; }
28 public Expression getCondition() { return condition; }
29 public Expression getElseCase() { return elseCase; }
30
31 /**
32 * Constructor for a conditional expression
33 */
34 public ConditionalExpression(
35 Expression thenCase, Expression condition, Expression elseCase) {
36 this.thenCase = thenCase;
37 this.condition = condition;
38 this.elseCase = elseCase;
39 }
40
41 /**
42 * Constructs a string representation of the if expression
43 */
44 @Override
brandjone2ffd5d2017-06-27 18:14:54 +020045 public void prettyPrint(Appendable buffer) throws IOException {
46 thenCase.prettyPrint(buffer);
47 buffer.append(" if ");
48 condition.prettyPrint(buffer);
49 buffer.append(" else ");
50 elseCase.prettyPrint(buffer);
Francois-Rene Rideau6fc5ee72015-03-12 20:55:17 +000051 }
52
53 @Override
Florian Weikert90a15962015-09-11 13:43:10 +000054 Object doEval(Environment env) throws EvalException, InterruptedException {
Francois-Rene Rideau6fc5ee72015-03-12 20:55:17 +000055 if (EvalUtils.toBoolean(condition.eval(env))) {
56 return thenCase.eval(env);
57 } else {
58 return elseCase.eval(env);
59 }
60 }
61
62 @Override
63 public void accept(SyntaxTreeVisitor visitor) {
64 visitor.visit(this);
65 }
laurentlbaf682d12017-08-24 20:32:02 +020066
67 @Override
68 public Kind kind() {
69 return Kind.CONDITIONAL;
70 }
Francois-Rene Rideau6fc5ee72015-03-12 20:55:17 +000071}