summaryrefslogtreecommitdiff
path: root/compiler/src/main/java/android/databinding/tool/CompilerChef.java
blob: b747d8b4d012867039cd26baa6443db1ec2a52a5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
/*
 * Copyright (C) 2015 The Android Open Source Project
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *      http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package android.databinding.tool;

import android.databinding.tool.processing.Scope;
import android.databinding.tool.processing.ScopedException;
import android.databinding.tool.reflection.InjectedClass;
import android.databinding.tool.reflection.ModelAnalyzer;
import android.databinding.tool.store.GenClassInfoLog;
import android.databinding.tool.store.ResourceBundle;
import android.databinding.tool.util.L;
import android.databinding.tool.writer.BRWriter;
import android.databinding.tool.reflection.ModelClass;
import android.databinding.tool.store.FeatureInfoList;
import android.databinding.tool.store.GenClassInfoLog;
import android.databinding.tool.store.ResourceBundle;
import android.databinding.tool.util.L;
import android.databinding.tool.util.Preconditions;
import android.databinding.tool.writer.BindingMapperWriter;
import android.databinding.tool.writer.BindingMapperWriterV2;
import android.databinding.tool.writer.JavaFileWriter;
import android.databinding.tool.writer.MergedBindingMapperWriter;
import com.android.annotations.NonNull;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.TypeSpec;

import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Chef class for compiler.
 *
 * Different build systems can initiate a version of this to handle their work
 */
public class CompilerChef {
    private static final String[] VERSION_CODES = {
            "BASE",                 // 1
            "BASE_1_1",             // 2
            "CUPCAKE",              // 3
            "DONUT",                // 4
            "ECLAIR",               // 5
            "ECLAIRE_0_1",          // 6
            "ECLAIR_MR1",           // 7
            "FROYO",                // 8
            "GINGERBREAD",          // 9
            "GINGERBREAD_MR1",      // 10
            "HONEYCOMB",            // 11
            "HONEYCOMB_MR1",        // 12
            "HONEYCOMB_MR2",        // 13
            "ICE_CREAM_SANDWICH",   // 14
            "ICE_CREAM_SANDWICH_MR1",// 15
            "JELLY_BEAN",           // 16
            "JELLY_BEAN_MR1",       // 17
            "JELLY_BEAN_MR2",       // 18
            "KITKAT",               // 19
            "KITKAT_WATCH",         // 20
            "LOLLIPOP",             // 21
            "LOLLIPOP_MR1",         // 22
            "M",                    // 23
    };
    private JavaFileWriter mFileWriter;
    private ResourceBundle mResourceBundle;
    private DataBinder mDataBinder;
    private boolean mEnableV2;

    private CompilerChef() {
    }

    public static CompilerChef createChef(
            ResourceBundle bundle,
            JavaFileWriter fileWriter,
            DataBindingCompilerArgs compilerArgs) {
        CompilerChef chef = new CompilerChef();

        chef.mResourceBundle = bundle;
        chef.mFileWriter = fileWriter;
        chef.mResourceBundle.validateMultiResLayouts();
        chef.mEnableV2 = compilerArgs.isEnableV2();
        chef.pushClassesToAnalyzer();
        return chef;
    }

    @SuppressWarnings("unused")
    public ResourceBundle getResourceBundle() {
        return mResourceBundle;
    }

    public void ensureDataBinder() {
        if (mDataBinder == null) {
            mDataBinder = new DataBinder(mResourceBundle, mEnableV2);
            mDataBinder.setFileWriter(mFileWriter);
        }
    }

    public boolean hasAnythingToGenerate() {
        L.d("checking if we have anything to generate. bundle size: %s",
                mResourceBundle == null ? -1 : mResourceBundle.getLayoutBundles().size());
        return mResourceBundle != null && mResourceBundle.getLayoutBundles().size() > 0;
    }

    /**
     * Injects ViewDataBinding subclasses to the ModelAnalyzer so that they can be
     * analyzed prior to creation. This is useful for resolving variable setters and
     * View fields during compilation.
     */
    private void pushClassesToAnalyzer() {
        ModelAnalyzer analyzer = ModelAnalyzer.getInstance();
        for (String layoutName : mResourceBundle.getLayoutBundles().keySet()) {
            final HashSet<String> variables = new HashSet();
            final HashSet<String> fields = new HashSet();

            List<ResourceBundle.LayoutFileBundle> bundles =
                    mResourceBundle.getLayoutBundles().get(layoutName);
            final String className = bundles.get(0).getBindingClassPackage() + "."
                    + bundles.get(0).getBindingClassName();
            // inject base class
            InjectedClass bindingClass =
                    new InjectedClass(className, ModelAnalyzer.VIEW_DATA_BINDING);
            analyzer.injectClass(bindingClass);

            for (ResourceBundle.LayoutFileBundle layoutFileBundle : bundles) {
                final HashMap<String, String> imports = new HashMap<String, String>();
                for (ResourceBundle.NameTypeLocation imp : layoutFileBundle.getImports()) {
                    imports.put(imp.name, imp.type);
                }

                for (ResourceBundle.VariableDeclaration variable :
                        layoutFileBundle.getVariables()) {
                    if (variables.add(variable.name)) {
                        bindingClass.addVariable(variable.name, variable.type, imports);
                    }
                }

                for (ResourceBundle.BindingTargetBundle bindingTargetBundle :
                        layoutFileBundle.getBindingTargetBundles()) {
                    if (bindingTargetBundle.getId() != null) {
                        String fieldName = bindingTargetBundle.getId();
                        if (fields.add(fieldName)) {
                            String fieldType = bindingTargetBundle.getInterfaceType();
                            bindingClass.addField(fieldName, fieldType);
                        }
                    }
                }
                // inject implementation
                if (mEnableV2 || bundles.size() > 1) {
                    // Add the implementation class
                    final String implName =
                            layoutFileBundle.getBindingClassPackage() + "."
                            + layoutFileBundle.createImplClassNameWithConfig();
                    analyzer.injectClass(new InjectedClass(implName, className));
                }
            }
        }
    }

    public void writeDataBinderMapper(
            DataBindingCompilerArgs compilerArgs,
            Map<String, Integer> brValueLookup,
            List<String> modulePackages) {
        if (compilerArgs.isEnableV2()) {
            final boolean generateMapper;
            if (compilerArgs.isApp()) {
                // generate mapper for apps only if it is not test or enabled for tests.
                generateMapper = !compilerArgs.isTestVariant() || compilerArgs.isEnabledForTests();
            } else {
                // always generate mapper for libs or features
                generateMapper = true;
            }
            if (generateMapper) {
                writeMapperForModule(compilerArgs, brValueLookup);
            }

            // merged mapper is the one generated for the whole app that includes the mappers
            // generated for individual modules.
            final boolean generateMergedMapper;
            if (compilerArgs.isApp()) {
                generateMergedMapper = !compilerArgs.isTestVariant();
            } else if (!compilerArgs.isFeature()) {
                generateMergedMapper = compilerArgs.isTestVariant();
            } else {
                generateMergedMapper = false;
            }
            if (generateMergedMapper) {
                writeMergedMapper(compilerArgs, modulePackages);
            }
        } else {
            final String pkg = "android.databinding";
            final String mapperName = "DataBinderMapperImpl";

            ensureDataBinder();
            BindingMapperWriter dbr = new BindingMapperWriter(pkg, mapperName,
                    mDataBinder.getLayoutBinders(), compilerArgs);
            mFileWriter.writeToFile(
                    pkg + "." + dbr.getClassName(),
                    dbr.write(brValueLookup));
        }
    }

    /**
     * Writes the mapper android.databinding.DataBinderMapperImpl which is a merged mapper
     * that includes all mappers from dependencies.
     */
    private void writeMergedMapper(
            DataBindingCompilerArgs compilerArgs,
            List<String> modulePackages) {
        Set<String> featurePackageIds = loadFeaturePackageIds(compilerArgs);
        StringBuilder sb = new StringBuilder();
        MergedBindingMapperWriter mergedBindingMapperWriter =
                new MergedBindingMapperWriter(modulePackages, compilerArgs, featurePackageIds);
        TypeSpec mergedMapperSpec = mergedBindingMapperWriter.write();
        try {
            JavaFile.builder(mergedBindingMapperWriter.getPkg(), mergedMapperSpec)
                    .build().writeTo(sb);
            mFileWriter.writeToFile(mergedBindingMapperWriter.getQualifiedName(),
                    sb.toString());
        } catch (IOException e) {
            Scope.defer(new ScopedException("cannot generate merged mapper class", e));
        }
    }

    @NonNull
    private Set<String> loadFeaturePackageIds(DataBindingCompilerArgs compilerArgs) {
        if (compilerArgs.getBaseFeatureInfoFolder() == null) {
            return Collections.emptySet();
        }
        File input = new File(compilerArgs.getBaseFeatureInfoFolder(),
                DataBindingBuilder.FEATURE_PACKAGE_LIST_FILE_NAME);
        if (!input.exists()) {
            return Collections.emptySet();
        }
        return FeatureInfoList.fromFile(input).getPackages();
    }

    /**
     * Generates a mapper that knows only about the bindings in this module (excl dependencies).
     */
    private void writeMapperForModule(
            DataBindingCompilerArgs compilerArgs,
            Map<String, Integer> brValueLookup) {
        GenClassInfoLog infoLog;
        try {
            infoLog = ResourceBundle.loadClassInfoFromFolder(
                    new File(compilerArgs.getClassLogDir()));
        } catch (IOException e) {
            Scope.defer(new ScopedException("Cannot read class info log"));
            infoLog = new GenClassInfoLog();
        }
        GenClassInfoLog infoLogInThisModule = infoLog
                .createPackageInfoLog(compilerArgs.getModulePackage());
        BindingMapperWriterV2 v2 = new BindingMapperWriterV2(
                infoLogInThisModule,
                compilerArgs);
        TypeSpec spec = v2.write(brValueLookup);
        StringBuilder sb = new StringBuilder();
        try {
            JavaFile.builder(v2.getPkg(), spec).build().writeTo(sb);
            mFileWriter.writeToFile(v2.getQualifiedName(), sb.toString());
        } catch (IOException e) {
            Scope.defer(new ScopedException("cannot generate mapper class", e));
        }
    }

    /**
     * Adds variables to list of Bindables.
     */
    public void addBRVariables(BindableHolder bindables) {
        ensureDataBinder();
        for (LayoutBinder layoutBinder : mDataBinder.mLayoutBinders) {
            for (String variableName : layoutBinder.getUserDefinedVariables().keySet()) {
                bindables.addVariable(variableName, layoutBinder.getClassName());
            }
        }
    }

    public void sealModels() {
        ensureDataBinder();
        mDataBinder.sealModels();
    }

    public void writeViewBinderInterfaces(boolean isLibrary) {
        ensureDataBinder();
        mDataBinder.writerBaseClasses(isLibrary);
    }

    public void writeViewBinders(int minSdk) {
        ensureDataBinder();
        mDataBinder.writeBinders(minSdk);
    }

    public void writeComponent() {
        ensureDataBinder();
        mDataBinder.writeComponent();
    }

    public Set<String> getClassesToBeStripped() {
        ensureDataBinder();
        return mDataBinder.getClassesToBeStripped();
    }

    public interface BindableHolder {
        void addVariable(String variableName, String containingClassName);
    }
}