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