1/*
2 * Copyright (C) 2016 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.ext.ExtKt;
20import android.databinding.tool.reflection.ModelAnalyzer;
21import android.databinding.tool.reflection.ModelClass;
22import android.databinding.tool.util.BrNameUtil;
23import android.databinding.tool.util.L;
24
25public class ObservableFieldExpr extends FieldAccessExpr {
26
27    ObservableFieldExpr(Expr parent, String name) {
28        super(parent, name);
29    }
30
31    @Override
32    public Expr resolveListeners(ModelClass listener, Expr parent) {
33        return this;  // ObservableFields aren't listeners
34    }
35
36    @Override
37    protected String computeUniqueKey() {
38        return join(mName, "..", getTarget().getUniqueKey());
39    }
40
41    @Override
42    protected ModelClass resolveType(ModelAnalyzer modelAnalyzer) {
43        if (mGetter == null) {
44            Expr target = getTarget();
45            target.getResolvedType();
46            boolean isStatic = target instanceof StaticIdentifierExpr;
47            ModelClass resolvedType = target.getResolvedType();
48            L.d("resolving %s. Resolved class type: %s", this, resolvedType);
49
50            mGetter = resolvedType.findGetterOrField(mName, isStatic);
51
52            if (mGetter == null) {
53                L.e("Could not find accessor %s.%s", resolvedType.getCanonicalName(), mName);
54                return null;
55            }
56
57            if (mGetter.isStatic() && !isStatic) {
58                // found a static method on an instance. register a new one
59                replaceStaticIdentifier(resolvedType);
60            }
61            if (hasBindableAnnotations()) {
62                mBrName = ExtKt.br(BrNameUtil.brKey(getGetter()));
63            } else {
64                mBrName = ExtKt.br(mName);
65            }
66        }
67        return mGetter.resolvedType;
68    }
69
70    @Override
71    public Expr cloneToModel(ExprModel model) {
72        final Expr clonedTarget = getTarget().cloneToModel(model);
73        return model.observableField(clonedTarget, mName);
74    }
75
76    @Override
77    public String toString() {
78        return getTarget().toString() + '.' + mName;
79    }
80}
81