TernaryExpr.java revision e52882df6130221462bf07f5f2b52de5c4b0f8de
1/* 2 * Copyright (C) 2015 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.databinding.tool.expr; 18 19import android.databinding.tool.reflection.ModelAnalyzer; 20import android.databinding.tool.reflection.ModelClass; 21import android.databinding.tool.writer.KCode; 22 23import java.util.ArrayList; 24import java.util.BitSet; 25import java.util.List; 26 27public class TernaryExpr extends Expr { 28 TernaryExpr(Expr pred, Expr ifTrue, Expr ifFalse) { 29 super(pred, ifTrue, ifFalse); 30 } 31 32 public Expr getPred() { 33 return getChildren().get(0); 34 } 35 36 public Expr getIfTrue() { 37 return getChildren().get(1); 38 } 39 40 public Expr getIfFalse() { 41 return getChildren().get(2); 42 } 43 44 @Override 45 protected String computeUniqueKey() { 46 return "?:" + super.computeUniqueKey(); 47 } 48 49 @Override 50 protected ModelClass resolveType(ModelAnalyzer modelAnalyzer) { 51 return modelAnalyzer.findCommonParentOf(getIfTrue().getResolvedType(), 52 getIfFalse().getResolvedType()); 53 } 54 55 @Override 56 protected List<Dependency> constructDependencies() { 57 List<Dependency> deps = new ArrayList<>(); 58 Expr predExpr = getPred(); 59 if (predExpr.isDynamic()) { 60 final Dependency pred = new Dependency(this, predExpr); 61 pred.setMandatory(true); 62 deps.add(pred); 63 } 64 Expr ifTrueExpr = getIfTrue(); 65 if (ifTrueExpr.isDynamic()) { 66 deps.add(new Dependency(this, ifTrueExpr, predExpr, true)); 67 } 68 Expr ifFalseExpr = getIfFalse(); 69 if (ifFalseExpr.isDynamic()) { 70 deps.add(new Dependency(this, ifFalseExpr, predExpr, false)); 71 } 72 return deps; 73 } 74 75 @Override 76 protected BitSet getPredicateInvalidFlags() { 77 return getPred().getInvalidFlags(); 78 } 79 80 @Override 81 protected KCode generateCode() { 82 return new KCode() 83 .app("", getPred().toCode()) 84 .app(" ? ", getIfTrue().toCode()) 85 .app(" : ", getIfFalse().toCode()); 86 87 } 88 89 @Override 90 public boolean isConditional() { 91 return true; 92 } 93} 94