CastExpr.java revision d3f2b9229472c9dae9bf4ae8b3e2d653b5653b01
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 CastExpr extends Expr {
26
27    final String mType;
28
29    CastExpr(String type, Expr expr) {
30        super(expr);
31        mType = type;
32    }
33
34    @Override
35    protected ModelClass resolveType(ModelAnalyzer modelAnalyzer) {
36        return modelAnalyzer.findClass(mType, getModel().getImports());
37    }
38
39    @Override
40    protected List<Dependency> constructDependencies() {
41        final List<Dependency> dependencies = constructDynamicChildrenDependencies();
42        for (Dependency dependency : dependencies) {
43            dependency.setMandatory(true);
44        }
45        return dependencies;
46    }
47
48    protected String computeUniqueKey() {
49        return addTwoWay(join(mType, getCastExpr().computeUniqueKey()));
50    }
51
52    public Expr getCastExpr() {
53        return getChildren().get(0);
54    }
55
56    public String getCastType() {
57        return getResolvedType().toJavaCode();
58    }
59
60    @Override
61    protected KCode generateCode(boolean expand) {
62        return new KCode()
63                .app("(")
64                .app(getCastType())
65                .app(") ", getCastExpr().toCode(expand));
66    }
67
68    @Override
69    public String getInvertibleError() {
70        return getCastExpr().getInvertibleError();
71    }
72
73    @Override
74    public KCode toInverseCode(KCode value) {
75        // assume no need to cast in reverse
76        return getCastExpr().toInverseCode(value);
77    }
78}
79