ExprModel.java revision ec2f3896c21a504b464bf591cdb45b62692b6760
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 com.google.common.base.Optional;
20import com.google.common.base.Preconditions;
21import com.google.common.base.Predicate;
22import com.google.common.collect.Iterables;
23import com.google.common.collect.Lists;
24
25import android.databinding.tool.reflection.ModelAnalyzer;
26import android.databinding.tool.reflection.ModelClass;
27import android.databinding.tool.util.L;
28import android.databinding.tool.writer.FlagSet;
29
30import java.util.ArrayList;
31import java.util.Arrays;
32import java.util.BitSet;
33import java.util.HashMap;
34import java.util.List;
35import java.util.Map;
36
37public class ExprModel {
38
39    Map<String, Expr> mExprMap = new HashMap<String, Expr>();
40
41    List<Expr> mBindingExpressions = new ArrayList<Expr>();
42
43    private int mInvalidateableFieldLimit = 0;
44
45    private int mRequirementIdCount = 0;
46
47    // each arg list receives a unique id even if it is the same arguments and method.
48    private int mArgListIdCounter = 0;
49
50    private static final String TRUE_KEY_SUFFIX = "== true";
51    private static final String FALSE_KEY_SUFFIX = "== false";
52
53    /**
54     * Any expression can be invalidated by invalidating this flag.
55     */
56    private BitSet mInvalidateAnyFlags;
57
58    /**
59     * Used by code generation. Keeps the list of expressions that are waiting to be evaluated.
60     */
61    private List<Expr> mPendingExpressions;
62
63    /**
64     * Used for converting flags into identifiers while debugging.
65     */
66    private String[] mFlagMapping;
67
68    private BitSet mInvalidateableFlags;
69    private BitSet mConditionalFlags;
70
71    private int mFlagBucketCount;// how many buckets we use to identify flags
72
73    private List<Expr> mObservables;
74
75    private boolean mSealed = false;
76
77    private Map<String, String> mImports = new HashMap<String, String>();
78
79    /**
80     * Adds the expression to the list of expressions and returns it.
81     * If it already exists, returns existing one.
82     *
83     * @param expr The new parsed expression
84     * @return The expression itself or another one if the same thing was parsed before
85     */
86    public <T extends Expr> T register(T expr) {
87        Preconditions.checkState(!mSealed, "Cannot add expressions to a model after it is sealed");
88        T existing = (T) mExprMap.get(expr.getUniqueKey());
89        if (existing != null) {
90            Preconditions.checkState(expr.getParents().isEmpty(),
91                    "If an expression already exists, it should've never been added to a parent,"
92                            + "if thats the case, somewhere we are creating an expression w/o"
93                            + "calling expression model");
94            // tell the expr that it is being swapped so that if it was added to some other expr
95            // as a parent, those can swap their references
96            expr.onSwappedWith(existing);
97            return existing;
98        }
99        mExprMap.put(expr.getUniqueKey(), expr);
100        expr.setModel(this);
101        return expr;
102    }
103
104    public void unregister(Expr expr) {
105        mExprMap.remove(expr.getUniqueKey());
106    }
107
108    public Map<String, Expr> getExprMap() {
109        return mExprMap;
110    }
111
112    public int size() {
113        return mExprMap.size();
114    }
115
116    public ComparisonExpr comparison(String op, Expr left, Expr right) {
117        return register(new ComparisonExpr(op, left, right));
118    }
119
120    public InstanceOfExpr instanceOfOp(Expr expr, String type) {
121        return register(new InstanceOfExpr(expr, type));
122    }
123
124    public FieldAccessExpr field(Expr parent, String name) {
125        return register(new FieldAccessExpr(parent, name));
126    }
127
128    public FieldAccessExpr observableField(Expr parent, String name) {
129        return register(new FieldAccessExpr(parent, name, true));
130    }
131
132    public SymbolExpr symbol(String text, Class type) {
133        return register(new SymbolExpr(text, type));
134    }
135
136    public TernaryExpr ternary(Expr pred, Expr ifTrue, Expr ifFalse) {
137        return register(new TernaryExpr(pred, ifTrue, ifFalse));
138    }
139
140    public IdentifierExpr identifier(String name) {
141        return register(new IdentifierExpr(name));
142    }
143
144    public StaticIdentifierExpr staticIdentifier(String name) {
145        return register(new StaticIdentifierExpr(name));
146    }
147
148    /**
149     * Creates a static identifier for the given class or returns the existing one.
150     */
151    public StaticIdentifierExpr staticIdentifierFor(final ModelClass modelClass) {
152        final String type = modelClass.getCanonicalName();
153        Optional<Expr> existing = Iterables.tryFind(mExprMap.values(), new Predicate<Expr>() {
154            @Override
155            public boolean apply(Expr input) {
156                if (!(input instanceof StaticIdentifierExpr)) {
157                    return false;
158                }
159                StaticIdentifierExpr id = (StaticIdentifierExpr) input;
160                return id.getUserDefinedType().equals(type);
161            }
162        });
163        if (existing.isPresent()) {
164            return (StaticIdentifierExpr) existing.get();
165        }
166
167        // does not exist. Find a name for it.
168        int cnt = 0;
169        int dotIndex = type.lastIndexOf(".");
170        String baseName;
171        Preconditions.checkArgument(dotIndex < type.length() - 1, "Invalid type %s", type);
172        if (dotIndex == -1) {
173            baseName = type;
174        } else {
175            baseName = type.substring(dotIndex + 1);
176        }
177        while (true) {
178            String candidate = cnt == 0 ? baseName : baseName + cnt;
179            if (!mImports.containsKey(candidate)) {
180                return addImport(candidate, type);
181            }
182            cnt ++;
183            Preconditions.checkState(cnt < 100, "Failed to create an import for " + type);
184        }
185    }
186
187    public MethodCallExpr methodCall(Expr target, String name, List<Expr> args) {
188        return register(new MethodCallExpr(target, name, args));
189    }
190
191    public MathExpr math(Expr left, String op, Expr right) {
192        return register(new MathExpr(left, op, right));
193    }
194
195    public TernaryExpr logical(Expr left, String op, Expr right) {
196        if ("&&".equals(op)) {
197            // left && right
198            // left ? right : false
199            return register(new TernaryExpr(left, right, symbol("false", boolean.class)));
200        } else {
201            // left || right
202            // left ? true : right
203            return register(new TernaryExpr(left, symbol("true", boolean.class), right));
204        }
205    }
206
207    public BitShiftExpr bitshift(Expr left, String op, Expr right) {
208        return register(new BitShiftExpr(left, op, right));
209    }
210
211    public UnaryExpr unary(String op, Expr expr) {
212        return register(new UnaryExpr(op, expr));
213    }
214
215    public Expr group(Expr grouped) {
216        return register(new GroupExpr(grouped));
217    }
218
219    public Expr resourceExpr(String packageName, String resourceType, String resourceName,
220            List<Expr> args) {
221        return register(new ResourceExpr(packageName, resourceType, resourceName, args));
222    }
223
224    public Expr bracketExpr(Expr variableExpr, Expr argExpr) {
225        return register(new BracketExpr(variableExpr, argExpr));
226    }
227
228    public Expr castExpr(String type, Expr expr) {
229        return register(new CastExpr(type, expr));
230    }
231
232    public List<Expr> getBindingExpressions() {
233        return mBindingExpressions;
234    }
235
236    public StaticIdentifierExpr addImport(String alias, String type) {
237        Preconditions.checkState(!mImports.containsKey(alias),
238                "%s has already been defined as %s", alias, type);
239        final StaticIdentifierExpr id = staticIdentifier(alias);
240        L.d("adding import %s as %s klass: %s", type, alias, id.getClass().getSimpleName());
241        id.setUserDefinedType(type);
242        mImports.put(alias, type);
243        return id;
244    }
245
246    public Map<String, String> getImports() {
247        return mImports;
248    }
249
250    /**
251     * The actual thingy that is set on the binding target.
252     *
253     * Input must be already registered
254     */
255    public Expr bindingExpr(Expr bindingExpr) {
256        Preconditions.checkArgument(mExprMap.containsKey(bindingExpr.getUniqueKey()),
257                "Main expression should already be registered");
258        if (!mBindingExpressions.contains(bindingExpr)) {
259            mBindingExpressions.add(bindingExpr);
260        }
261        return bindingExpr;
262    }
263
264    public List<Expr> getObservables() {
265        return mObservables;
266    }
267
268    /**
269     * Give id to each expression. Will be useful if we serialize.
270     */
271    public void seal() {
272        L.d("sealing model");
273        List<Expr> notifiableExpressions = new ArrayList<Expr>();
274        //ensure class analyzer. We need to know observables at this point
275        final ModelAnalyzer modelAnalyzer = ModelAnalyzer.getInstance();
276        updateExpressions(modelAnalyzer);
277
278
279        int counter = 0;
280        final Iterable<Expr> observables = filterObservables(modelAnalyzer);
281        List<String> flagMapping = Lists.newArrayList();
282        mObservables = Lists.newArrayList();
283        for (Expr expr : observables) {
284            // observables gets initial ids
285            flagMapping.add(expr.getUniqueKey());
286            expr.setId(counter++);
287            mObservables.add(expr);
288            notifiableExpressions.add(expr);
289            L.d("observable %s", expr.getUniqueKey());
290        }
291
292        // non-observable identifiers gets next ids
293        final Iterable<Expr> nonObservableIds = filterNonObservableIds(modelAnalyzer);
294        for (Expr expr : nonObservableIds) {
295            flagMapping.add(expr.getUniqueKey());
296            expr.setId(counter++);
297            notifiableExpressions.add(expr);
298            L.d("non-observable %s", expr.getUniqueKey());
299        }
300
301        // descendants of observables gets following ids
302        for (Expr expr : observables) {
303            for (Expr parent : expr.getParents()) {
304                if (parent.hasId()) {
305                    continue;// already has some id, means observable
306                }
307                // only fields earn an id
308                if (parent instanceof FieldAccessExpr) {
309                    FieldAccessExpr fae = (FieldAccessExpr) parent;
310                    L.d("checking field access expr %s. getter: %s", fae,fae.getGetter());
311                    if (fae.isDynamic() && fae.getGetter().canBeInvalidated()) {
312                        flagMapping.add(parent.getUniqueKey());
313                        parent.setId(counter++);
314                        notifiableExpressions.add(parent);
315                        L.d("notifiable field %s : %s for %s : %s", parent.getUniqueKey(),
316                                Integer.toHexString(System.identityHashCode(parent)),
317                                expr.getUniqueKey(),
318                                Integer.toHexString(System.identityHashCode(expr)));
319                    }
320                }
321            }
322        }
323
324        // non-dynamic binding expressions receive some ids so that they can be invalidated
325        L.d("list of binding expressions");
326        for (int i = 0; i < mBindingExpressions.size(); i++) {
327            L.d("[%d] %s", i, mBindingExpressions.get(i));
328        }
329        // we don't assign ids to constant binding expressions because now invalidateAll has its own
330        // flag.
331
332        for (Expr expr : notifiableExpressions) {
333            expr.enableDirectInvalidation();
334        }
335
336        // make sure all dependencies are resolved to avoid future race conditions
337        for (Expr expr : mExprMap.values()) {
338            expr.getDependencies();
339        }
340        final int invalidateAnyFlagIndex = counter ++;
341        flagMapping.add("INVALIDATE ANY");
342        mInvalidateableFieldLimit = counter;
343        mInvalidateableFlags = new BitSet();
344        for (int i = 0; i < mInvalidateableFieldLimit; i++) {
345            mInvalidateableFlags.set(i, true);
346        }
347
348        // make sure all dependencies are resolved to avoid future race conditions
349        for (Expr expr : mExprMap.values()) {
350            if (expr.isConditional()) {
351                L.d("requirement id for %s is %d", expr, counter);
352                expr.setRequirementId(counter);
353                flagMapping.add(expr.getUniqueKey() + FALSE_KEY_SUFFIX);
354                flagMapping.add(expr.getUniqueKey() + TRUE_KEY_SUFFIX);
355                counter += 2;
356            }
357        }
358        mConditionalFlags = new BitSet();
359        for (int i = mInvalidateableFieldLimit; i < counter; i++) {
360            mConditionalFlags.set(i, true);
361        }
362        mRequirementIdCount = (counter - mInvalidateableFieldLimit) / 2;
363
364        // everybody gets an id
365        for (Map.Entry<String, Expr> entry : mExprMap.entrySet()) {
366            final Expr value = entry.getValue();
367            if (!value.hasId()) {
368                value.setId(counter++);
369            }
370        }
371
372        mFlagMapping = new String[flagMapping.size()];
373        flagMapping.toArray(mFlagMapping);
374
375        mFlagBucketCount = 1 + (getTotalFlagCount() / FlagSet.sBucketSize);
376        mInvalidateAnyFlags = new BitSet();
377        mInvalidateAnyFlags.set(invalidateAnyFlagIndex, true);
378
379        for (Expr expr : mExprMap.values()) {
380            expr.getShouldReadFlagsWithConditionals();
381        }
382
383        for (Expr expr : mExprMap.values()) {
384            // ensure all types are calculated
385            expr.getResolvedType();
386        }
387
388        mSealed = true;
389    }
390
391    /**
392     * Run updateExpr on each binding expression until no new expressions are added.
393     * <p>
394     * Some expressions (e.g. field access) may replace themselves and add/remove new dependencies
395     * so we need to make sure each expression's update is called at least once.
396     */
397    private void updateExpressions(ModelAnalyzer modelAnalyzer) {
398        int startSize = -1;
399        while (startSize != mExprMap.size()) {
400            startSize = mExprMap.size();
401            ArrayList<Expr> exprs = new ArrayList<Expr>(mBindingExpressions);
402            for (Expr expr : exprs) {
403                expr.updateExpr(modelAnalyzer);
404            }
405        }
406    }
407
408    public int getFlagBucketCount() {
409        return mFlagBucketCount;
410    }
411
412    public int getTotalFlagCount() {
413        return mRequirementIdCount * 2 + mInvalidateableFieldLimit;
414    }
415
416    public int getInvalidateableFieldLimit() {
417        return mInvalidateableFieldLimit;
418    }
419
420    public String[] getFlagMapping() {
421        return mFlagMapping;
422    }
423
424    public String getFlag(int id) {
425        return mFlagMapping[id];
426    }
427
428    private Iterable<Expr> filterNonObservableIds(final ModelAnalyzer modelAnalyzer) {
429        return Iterables.filter(mExprMap.values(), new Predicate<Expr>() {
430            @Override
431            public boolean apply(Expr input) {
432                return input instanceof IdentifierExpr
433                        && !input.hasId()
434                        && !input.isObservable()
435                        && input.isDynamic();
436            }
437        });
438    }
439
440    private Iterable<Expr> filterObservables(final ModelAnalyzer modelAnalyzer) {
441        return Iterables.filter(mExprMap.values(), new Predicate<Expr>() {
442            @Override
443            public boolean apply(Expr input) {
444                return input.isObservable();
445            }
446        });
447    }
448
449    public List<Expr> getPendingExpressions() {
450        if (mPendingExpressions == null) {
451            mPendingExpressions = Lists.newArrayList();
452            for (Expr expr : mExprMap.values()) {
453                if (!expr.isRead() && expr.isDynamic()) {
454                    mPendingExpressions.add(expr);
455                }
456            }
457        }
458        return mPendingExpressions;
459    }
460
461    public boolean markBitsRead() {
462        // each has should read flags, we set them back on them
463        List<Expr> markedSomeFlagsRead = Lists.newArrayList();
464        for (Expr expr : filterShouldRead(getPendingExpressions())) {
465            expr.markFlagsAsRead(expr.getShouldReadFlags());
466            markedSomeFlagsRead.add(expr);
467        }
468        return pruneDone(markedSomeFlagsRead);
469    }
470
471    private boolean pruneDone(List<Expr> markedSomeFlagsAsRead) {
472        boolean marked = true;
473        List<Expr> markedAsReadList = Lists.newArrayList();
474        while (marked) {
475            marked = false;
476            for (Expr expr : mExprMap.values()) {
477                if (expr.isRead()) {
478                    continue;
479                }
480                if (expr.markAsReadIfDone()) {
481                    L.d("marked %s as read ", expr.getUniqueKey());
482                    marked = true;
483                    markedAsReadList.add(expr);
484                    markedSomeFlagsAsRead.remove(expr);
485                }
486            }
487        }
488        boolean elevated = false;
489        for (Expr markedAsRead : markedAsReadList) {
490            for (Dependency dependency : markedAsRead.getDependants()) {
491                if (dependency.getDependant().considerElevatingConditionals(markedAsRead)) {
492                    elevated = true;
493                }
494            }
495        }
496        for (Expr partialRead : markedSomeFlagsAsRead) {
497            boolean allPathsAreSatisfied = partialRead.getAllCalculationPaths()
498                    .areAllPathsSatisfied(partialRead.mReadSoFar);
499            if (!allPathsAreSatisfied) {
500                continue;
501            }
502            for (Dependency dependency : partialRead.getDependants()) {
503                if (dependency.getDependant().considerElevatingConditionals(partialRead)) {
504                    elevated = true;
505                }
506            }
507        }
508        if (elevated) {
509            // some conditionals are elevated. We should re-calculate flags
510            for (Expr expr : getPendingExpressions()) {
511                if (!expr.isRead()) {
512                    expr.invalidateReadFlags();
513                }
514            }
515            mPendingExpressions = null;
516        }
517        return elevated;
518    }
519
520    public static Iterable<Expr> filterShouldRead(Iterable<Expr> exprs) {
521        return toCollection(Iterables.filter(exprs, sShouldReadPred));
522    }
523
524    public static List<Expr> toCollection(Iterable<Expr> iterable) {
525        return Arrays.asList(Iterables.toArray(iterable, Expr.class));
526    }
527
528    private static final Predicate<Expr> sShouldReadPred = new Predicate<Expr>() {
529        @Override
530        public boolean apply(final Expr expr) {
531            return !expr.getShouldReadFlags().isEmpty() && !Iterables.any(
532                    expr.getDependencies(), new Predicate<Dependency>() {
533                        @Override
534                        public boolean apply(Dependency dependency) {
535                            final boolean result = dependency.isConditional() ||
536                                    dependency.getOther().hasNestedCannotRead();
537                            return result;
538                        }
539                    });
540        }
541    };
542
543    /**
544     * May return null if flag is equal to invalidate any flag.
545     */
546    public Expr findFlagExpression(int flag) {
547        if (mInvalidateAnyFlags.get(flag)) {
548            return null;
549        }
550        final String key = mFlagMapping[flag];
551        if (mExprMap.containsKey(key)) {
552            return mExprMap.get(key);
553        }
554        int falseIndex = key.indexOf(FALSE_KEY_SUFFIX);
555        if (falseIndex > -1) {
556            final String trimmed = key.substring(0, falseIndex);
557            return mExprMap.get(trimmed);
558        }
559        int trueIndex = key.indexOf(TRUE_KEY_SUFFIX);
560        if (trueIndex > -1) {
561            final String trimmed = key.substring(0, trueIndex);
562            return mExprMap.get(trimmed);
563        }
564        // log everything we call
565        StringBuilder error = new StringBuilder();
566        error.append("cannot find flag:").append(flag).append("\n");
567        error.append("invalidate any flag:").append(mInvalidateAnyFlags).append("\n");
568        error.append("key:").append(key).append("\n");
569        error.append("flag mapping:").append(Arrays.toString(mFlagMapping));
570        Preconditions.checkArgument(false, error.toString());
571        return null;
572    }
573
574    public BitSet getInvalidateAnyBitSet() {
575        return mInvalidateAnyFlags;
576    }
577
578    public Expr argListExpr(Iterable<Expr> expressions) {
579        return register(new ArgListExpr(mArgListIdCounter ++, expressions));
580    }
581}
582