blob: a4c20633e0ac1a200bc51f3950786815c17deff4 [file] [log] [blame]
Francois-Rene Rideau6fc5ee72015-03-12 20:55:17 +00001// Copyright 2014 Google Inc. All rights reserved.
2//
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.
14
15package com.google.devtools.build.lib.syntax;
16
17/**
18 * Syntax node for an if/else expression.
19 */
20public final class ConditionalExpression extends Expression {
21
22 // Python conditional expressions: $thenCase if $condition else $elseCase
23 // https://docs.python.org/3.5/reference/expressions.html#conditional-expressions
24 private final Expression thenCase;
25 private final Expression condition;
26 private final Expression elseCase;
27
28 public Expression getThenCase() { return thenCase; }
29 public Expression getCondition() { return condition; }
30 public Expression getElseCase() { return elseCase; }
31
32 /**
33 * Constructor for a conditional expression
34 */
35 public ConditionalExpression(
36 Expression thenCase, Expression condition, Expression elseCase) {
37 this.thenCase = thenCase;
38 this.condition = condition;
39 this.elseCase = elseCase;
40 }
41
42 /**
43 * Constructs a string representation of the if expression
44 */
45 @Override
46 public String toString() {
47 return thenCase + " if " + condition + " else " + elseCase;
48 }
49
50 @Override
Florian Weikert90a15962015-09-11 13:43:10 +000051 Object doEval(Environment env) throws EvalException, InterruptedException {
Francois-Rene Rideau6fc5ee72015-03-12 20:55:17 +000052 if (EvalUtils.toBoolean(condition.eval(env))) {
53 return thenCase.eval(env);
54 } else {
55 return elseCase.eval(env);
56 }
57 }
58
59 @Override
60 public void accept(SyntaxTreeVisitor visitor) {
61 visitor.visit(this);
62 }
63
64 @Override
Laurent Le Brun2e78d612015-04-15 09:06:46 +000065 void validate(ValidationEnvironment env) throws EvalException {
Francois-Rene Rideau6fc5ee72015-03-12 20:55:17 +000066 condition.validate(env);
Laurent Le Brun2e78d612015-04-15 09:06:46 +000067 thenCase.validate(env);
68 elseCase.validate(env);
Francois-Rene Rideau6fc5ee72015-03-12 20:55:17 +000069 }
70}