ExprModel.java revision 716ba89e7f459f49ea85070d4710c1d79d715298
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(ResolveListenersCallback resolveListeners) {
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        if (resolveListeners != null) {
279            resolveListeners.resolveListeners();
280        }
281
282        int counter = 0;
283        final Iterable<Expr> observables = filterObservables(modelAnalyzer);
284        List<String> flagMapping = Lists.newArrayList();
285        mObservables = Lists.newArrayList();
286        for (Expr expr : observables) {
287            // observables gets initial ids
288            flagMapping.add(expr.getUniqueKey());
289            expr.setId(counter++);
290            mObservables.add(expr);
291            notifiableExpressions.add(expr);
292            L.d("observable %s", expr.getUniqueKey());
293        }
294
295        // non-observable identifiers gets next ids
296        final Iterable<Expr> nonObservableIds = filterNonObservableIds(modelAnalyzer);
297        for (Expr expr : nonObservableIds) {
298            flagMapping.add(expr.getUniqueKey());
299            expr.setId(counter++);
300            notifiableExpressions.add(expr);
301            L.d("non-observable %s", expr.getUniqueKey());
302        }
303
304        // descendants of observables gets following ids
305        for (Expr expr : observables) {
306            for (Expr parent : expr.getParents()) {
307                if (parent.hasId()) {
308                    continue;// already has some id, means observable
309                }
310                // only fields earn an id
311                if (parent instanceof FieldAccessExpr) {
312                    FieldAccessExpr fae = (FieldAccessExpr) parent;
313                    L.d("checking field access expr %s. getter: %s", fae,fae.getGetter());
314                    if (fae.isDynamic() && fae.getGetter().canBeInvalidated()) {
315                        flagMapping.add(parent.getUniqueKey());
316                        parent.setId(counter++);
317                        notifiableExpressions.add(parent);
318                        L.d("notifiable field %s : %s for %s : %s", parent.getUniqueKey(),
319                                Integer.toHexString(System.identityHashCode(parent)),
320                                expr.getUniqueKey(),
321                                Integer.toHexString(System.identityHashCode(expr)));
322                    }
323                }
324            }
325        }
326
327        // non-dynamic binding expressions receive some ids so that they can be invalidated
328        L.d("list of binding expressions");
329        for (int i = 0; i < mBindingExpressions.size(); i++) {
330            L.d("[%d] %s", i, mBindingExpressions.get(i));
331        }
332        // we don't assign ids to constant binding expressions because now invalidateAll has its own
333        // flag.
334
335        for (Expr expr : notifiableExpressions) {
336            expr.enableDirectInvalidation();
337        }
338
339        // make sure all dependencies are resolved to avoid future race conditions
340        for (Expr expr : mExprMap.values()) {
341            expr.getDependencies();
342        }
343        final int invalidateAnyFlagIndex = counter ++;
344        flagMapping.add("INVALIDATE ANY");
345        mInvalidateableFieldLimit = counter;
346        mInvalidateableFlags = new BitSet();
347        for (int i = 0; i < mInvalidateableFieldLimit; i++) {
348            mInvalidateableFlags.set(i, true);
349        }
350
351        // make sure all dependencies are resolved to avoid future race conditions
352        for (Expr expr : mExprMap.values()) {
353            if (expr.isConditional()) {
354                L.d("requirement id for %s is %d", expr, counter);
355                expr.setRequirementId(counter);
356                flagMapping.add(expr.getUniqueKey() + FALSE_KEY_SUFFIX);
357                flagMapping.add(expr.getUniqueKey() + TRUE_KEY_SUFFIX);
358                counter += 2;
359            }
360        }
361        mConditionalFlags = new BitSet();
362        for (int i = mInvalidateableFieldLimit; i < counter; i++) {
363            mConditionalFlags.set(i, true);
364        }
365        mRequirementIdCount = (counter - mInvalidateableFieldLimit) / 2;
366
367        // everybody gets an id
368        for (Map.Entry<String, Expr> entry : mExprMap.entrySet()) {
369            final Expr value = entry.getValue();
370            if (!value.hasId()) {
371                value.setId(counter++);
372            }
373        }
374
375        mFlagMapping = new String[flagMapping.size()];
376        flagMapping.toArray(mFlagMapping);
377
378        mFlagBucketCount = 1 + (getTotalFlagCount() / FlagSet.sBucketSize);
379        mInvalidateAnyFlags = new BitSet();
380        mInvalidateAnyFlags.set(invalidateAnyFlagIndex, true);
381
382        for (Expr expr : mExprMap.values()) {
383            expr.getShouldReadFlagsWithConditionals();
384        }
385
386        for (Expr expr : mExprMap.values()) {
387            // ensure all types are calculated
388            expr.getResolvedType();
389        }
390
391        mSealed = true;
392    }
393
394    /**
395     * Run updateExpr on each binding expression until no new expressions are added.
396     * <p>
397     * Some expressions (e.g. field access) may replace themselves and add/remove new dependencies
398     * so we need to make sure each expression's update is called at least once.
399     */
400    private void updateExpressions(ModelAnalyzer modelAnalyzer) {
401        int startSize = -1;
402        while (startSize != mExprMap.size()) {
403            startSize = mExprMap.size();
404            ArrayList<Expr> exprs = new ArrayList<Expr>(mBindingExpressions);
405            for (Expr expr : exprs) {
406                expr.updateExpr(modelAnalyzer);
407            }
408        }
409    }
410
411    public int getFlagBucketCount() {
412        return mFlagBucketCount;
413    }
414
415    public int getTotalFlagCount() {
416        return mRequirementIdCount * 2 + mInvalidateableFieldLimit;
417    }
418
419    public int getInvalidateableFieldLimit() {
420        return mInvalidateableFieldLimit;
421    }
422
423    public String[] getFlagMapping() {
424        return mFlagMapping;
425    }
426
427    public String getFlag(int id) {
428        return mFlagMapping[id];
429    }
430
431    private Iterable<Expr> filterNonObservableIds(final ModelAnalyzer modelAnalyzer) {
432        return Iterables.filter(mExprMap.values(), new Predicate<Expr>() {
433            @Override
434            public boolean apply(Expr input) {
435                return input instanceof IdentifierExpr
436                        && !input.hasId()
437                        && !input.isObservable()
438                        && input.isDynamic();
439            }
440        });
441    }
442
443    private Iterable<Expr> filterObservables(final ModelAnalyzer modelAnalyzer) {
444        return Iterables.filter(mExprMap.values(), new Predicate<Expr>() {
445            @Override
446            public boolean apply(Expr input) {
447                return input.isObservable();
448            }
449        });
450    }
451
452    public List<Expr> getPendingExpressions() {
453        if (mPendingExpressions == null) {
454            mPendingExpressions = Lists.newArrayList();
455            for (Expr expr : mExprMap.values()) {
456                if (!expr.isRead() && expr.isDynamic()) {
457                    mPendingExpressions.add(expr);
458                }
459            }
460        }
461        return mPendingExpressions;
462    }
463
464    public boolean markBitsRead() {
465        // each has should read flags, we set them back on them
466        List<Expr> markedSomeFlagsRead = Lists.newArrayList();
467        for (Expr expr : filterShouldRead(getPendingExpressions())) {
468            expr.markFlagsAsRead(expr.getShouldReadFlags());
469            markedSomeFlagsRead.add(expr);
470        }
471        return pruneDone(markedSomeFlagsRead);
472    }
473
474    private boolean pruneDone(List<Expr> markedSomeFlagsAsRead) {
475        boolean marked = true;
476        List<Expr> markedAsReadList = Lists.newArrayList();
477        while (marked) {
478            marked = false;
479            for (Expr expr : mExprMap.values()) {
480                if (expr.isRead()) {
481                    continue;
482                }
483                if (expr.markAsReadIfDone()) {
484                    L.d("marked %s as read ", expr.getUniqueKey());
485                    marked = true;
486                    markedAsReadList.add(expr);
487                    markedSomeFlagsAsRead.remove(expr);
488                }
489            }
490        }
491        boolean elevated = false;
492        for (Expr markedAsRead : markedAsReadList) {
493            for (Dependency dependency : markedAsRead.getDependants()) {
494                if (dependency.getDependant().considerElevatingConditionals(markedAsRead)) {
495                    elevated = true;
496                }
497            }
498        }
499        for (Expr partialRead : markedSomeFlagsAsRead) {
500            boolean allPathsAreSatisfied = partialRead.getAllCalculationPaths()
501                    .areAllPathsSatisfied(partialRead.mReadSoFar);
502            if (!allPathsAreSatisfied) {
503                continue;
504            }
505            for (Dependency dependency : partialRead.getDependants()) {
506                if (dependency.getDependant().considerElevatingConditionals(partialRead)) {
507                    elevated = true;
508                }
509            }
510        }
511        if (elevated) {
512            // some conditionals are elevated. We should re-calculate flags
513            for (Expr expr : getPendingExpressions()) {
514                if (!expr.isRead()) {
515                    expr.invalidateReadFlags();
516                }
517            }
518            mPendingExpressions = null;
519        }
520        return elevated;
521    }
522
523    public static Iterable<Expr> filterShouldRead(Iterable<Expr> exprs) {
524        return toCollection(Iterables.filter(exprs, sShouldReadPred));
525    }
526
527    public static List<Expr> toCollection(Iterable<Expr> iterable) {
528        return Arrays.asList(Iterables.toArray(iterable, Expr.class));
529    }
530
531    private static final Predicate<Expr> sShouldReadPred = new Predicate<Expr>() {
532        @Override
533        public boolean apply(final Expr expr) {
534            return !expr.getShouldReadFlags().isEmpty() && !Iterables.any(
535                    expr.getDependencies(), new Predicate<Dependency>() {
536                        @Override
537                        public boolean apply(Dependency dependency) {
538                            final boolean result = dependency.isConditional() ||
539                                    dependency.getOther().hasNestedCannotRead();
540                            return result;
541                        }
542                    });
543        }
544    };
545
546    /**
547     * May return null if flag is equal to invalidate any flag.
548     */
549    public Expr findFlagExpression(int flag) {
550        if (mInvalidateAnyFlags.get(flag)) {
551            return null;
552        }
553        final String key = mFlagMapping[flag];
554        if (mExprMap.containsKey(key)) {
555            return mExprMap.get(key);
556        }
557        int falseIndex = key.indexOf(FALSE_KEY_SUFFIX);
558        if (falseIndex > -1) {
559            final String trimmed = key.substring(0, falseIndex);
560            return mExprMap.get(trimmed);
561        }
562        int trueIndex = key.indexOf(TRUE_KEY_SUFFIX);
563        if (trueIndex > -1) {
564            final String trimmed = key.substring(0, trueIndex);
565            return mExprMap.get(trimmed);
566        }
567        // log everything we call
568        StringBuilder error = new StringBuilder();
569        error.append("cannot find flag:").append(flag).append("\n");
570        error.append("invalidate any flag:").append(mInvalidateAnyFlags).append("\n");
571        error.append("key:").append(key).append("\n");
572        error.append("flag mapping:").append(Arrays.toString(mFlagMapping));
573        Preconditions.checkArgument(false, error.toString());
574        return null;
575    }
576
577    public BitSet getInvalidateAnyBitSet() {
578        return mInvalidateAnyFlags;
579    }
580
581    public Expr argListExpr(Iterable<Expr> expressions) {
582        return register(new ArgListExpr(mArgListIdCounter ++, expressions));
583    }
584
585    public interface ResolveListenersCallback {
586        void resolveListeners();
587    }
588}
589