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.List;
24
25public class InstanceOfExpr extends Expr {
26    final String mTypeStr;
27    ModelClass mType;
28
29    InstanceOfExpr(Expr left, String type) {
30        super(left);
31        mTypeStr = type;
32    }
33
34    @Override
35    protected String computeUniqueKey() {
36        return join("instanceof", super.computeUniqueKey(), mTypeStr);
37    }
38
39    @Override
40    protected KCode generateCode() {
41        return new KCode()
42                .app("", getExpr().toCode())
43                .app(" instanceof ")
44                .app(getType().toJavaCode());
45    }
46
47    @Override
48    public Expr cloneToModel(ExprModel model) {
49        return model.instanceOfOp(getExpr().cloneToModel(model), mTypeStr);
50    }
51
52    @Override
53    protected ModelClass resolveType(ModelAnalyzer modelAnalyzer) {
54        mType = modelAnalyzer.findClass(mTypeStr, getModel().getImports());
55        return modelAnalyzer.loadPrimitive("boolean");
56    }
57
58    @Override
59    protected List<Dependency> constructDependencies() {
60        return constructDynamicChildrenDependencies();
61    }
62
63    public Expr getExpr() {
64        return getChildren().get(0);
65    }
66
67    public ModelClass getType() {
68        return mType;
69    }
70
71    @Override
72    public String getInvertibleError() {
73        return "two-way binding can't target a value with the 'instanceof' operator";
74    }
75
76    @Override
77    public String toString() {
78        return getExpr().toString() + " instanceof " + mTypeStr;
79    }
80}
81