| 1 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// |
| 2 | // Copyright (c) 2018 Saxonica Limited. |
| 3 | // This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. |
| 4 | // If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. |
| 5 | // This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0. |
| 6 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// |
| 7 | |
| 8 | package net.sf.saxon.expr; |
| 9 | |
| 10 | import net.sf.saxon.expr.parser.ExpressionTool; |
| 11 | import net.sf.saxon.expr.parser.PathMap; |
| 12 | import net.sf.saxon.om.*; |
| 13 | import net.sf.saxon.trans.XPathException; |
| 14 | import net.sf.saxon.type.ItemType; |
| 15 | import net.sf.saxon.value.IntegerValue; |
| 16 | import net.sf.saxon.value.SequenceType; |
| 17 | |
| 18 | import java.util.ArrayList; |
| 19 | import java.util.List; |
| 20 | |
| 21 | /** |
| 22 | * Assignation is an abstract superclass for the kinds of expression |
| 23 | * that declare range variables: for, some, and every. |
| 24 | */ |
| 25 | |
| 26 | public abstract class Assignation extends Expression implements LocalBinding { |
| 27 | |
| 28 | private Operand sequenceOp; |
| 29 | private Operand actionOp; |
| 30 | protected int slotNumber = -999; // slot number for range variable |
| 31 | // (initialized to ensure a crash if no real slot is allocated) |
| 32 | protected StructuredQName variableName; |
| 33 | protected SequenceType requiredType; |
| 34 | protected boolean isIndexedVariable = false; |
| 35 | protected boolean hasLoopingReference = false; |
| 36 | protected List<VariableReference> references = null; |
| 37 | |
| 38 | private final static OperandRole REPEATED_ACTION_ROLE = new OperandRole(OperandRole.HIGHER_ORDER, OperandUsage.TRANSMISSION); |
| 39 | |
| 40 | public Assignation() { |
| 41 | sequenceOp = new Operand(this, null, OperandRole.NAVIGATE); |
| 42 | actionOp = new Operand(this, null, this instanceof LetExpression ? OperandRole.SAME_FOCUS_ACTION : REPEATED_ACTION_ROLE); |
| 43 | } |
| 44 | |
| 45 | public Operand getSequenceOp() { |
| 46 | return sequenceOp; |
| 47 | } |
| 48 | |
| 49 | public Operand getActionOp() { |
| 50 | return actionOp; |
| 51 | } |
| 52 | |
| 53 | @Override |
| 54 | public Iterable<Operand> operands() { |
| 55 | return operandList(sequenceOp, actionOp); |
| 56 | } |
| 57 | |
| 58 | |
| 59 | /** |
| 60 | * Set the required type (declared type) of the variable |
| 61 | * |
| 62 | * @param requiredType the required type |
| 63 | */ |
| 64 | public void setRequiredType(SequenceType requiredType) { |
| 65 | this.requiredType = requiredType; |
| 66 | } |
| 67 | |
| 68 | /** |
| 69 | * Set the name of the variable |
| 70 | * |
| 71 | * @param variableName the name of the variable |
| 72 | */ |
| 73 | |
| 74 | public void setVariableQName(StructuredQName variableName) { |
| 75 | this.variableName = variableName; |
| 76 | } |
| 77 | |
| 78 | |
| 79 | /** |
| 80 | * Get the name of the variable |
| 81 | * |
| 82 | * @return the variable name, as a QName |
| 83 | */ |
| 84 | |
| 85 | public StructuredQName getVariableQName() { |
| 86 | return variableName; |
| 87 | } |
| 88 | |
| 89 | public StructuredQName getObjectName() { |
| 90 | return variableName; |
| 91 | } |
| 92 | |
| 93 | |
| 94 | /** |
| 95 | * Get the declared type of the variable |
| 96 | * |
| 97 | * @return the declared type |
| 98 | */ |
| 99 | |
| 100 | public SequenceType getRequiredType() { |
| 101 | return requiredType; |
| 102 | } |
| 103 | |
| 104 | /** |
| 105 | * If the variable is bound to an integer, get the minimum and maximum possible values. |
| 106 | * Return null if unknown or not applicable |
| 107 | */ |
| 108 | public IntegerValue[] getIntegerBoundsForVariable() { |
| 109 | return getSequence().getIntegerBounds(); |
| 110 | } |
| 111 | |
| 112 | /** |
| 113 | * If this is a local variable held on the local stack frame, return the corresponding slot number. |
| 114 | * In other cases, return -1. |
| 115 | */ |
| 116 | |
| 117 | public int getLocalSlotNumber() { |
| 118 | return slotNumber; |
| 119 | } |
| 120 | |
| 121 | /** |
| 122 | * Compute the dependencies of an expression, as the union of the |
| 123 | * dependencies of its sub-expressions. (This is overridden for path expressions |
| 124 | * and filter expressions, where the dependencies of a sub-expression are not all |
| 125 | * propagated). This method should be called only once, to compute the dependencies; |
| 126 | * after that, getDependencies should be used. |
| 127 | * |
| 128 | * @return the dependencies, as a bit-mask |
| 129 | */ |
| 130 | @Override |
| 131 | public int computeDependencies() { |
| 132 | int d = super.computeDependencies(); |
| 133 | // Unset the DEPENDS_ON_LOCAL_VARIABLES bit if the only dependencies are to |
| 134 | // variables declared within the expression itself (typically, the variable |
| 135 | // bound by this Assignation) |
| 136 | if (!ExpressionTool.containsLocalVariableReference(this)) { |
| 137 | d &= ~StaticProperty.DEPENDS_ON_LOCAL_VARIABLES; |
| 138 | } |
| 139 | return d; |
| 140 | } |
| 141 | |
| 142 | /** |
| 143 | * Get the value of the range variable |
| 144 | */ |
| 145 | |
| 146 | public Sequence<?> evaluateVariable(XPathContext context) throws XPathException { |
| 147 | Sequence<?> actual = context.evaluateLocalVariable(slotNumber); |
| 148 | if (!(actual instanceof GroundedValue || actual instanceof NodeInfo)) { |
| 149 | actual = actual.materialize(); |
| 150 | context.setLocalVariable(slotNumber, actual); |
| 151 | } |
| 152 | return actual; |
| 153 | } |
| 154 | |
| 155 | /** |
| 156 | * Add the "return" or "satisfies" expression, and fix up all references to the |
| 157 | * range variable that occur within that expression |
| 158 | * |
| 159 | * @param action the expression that occurs after the "return" keyword of a "for" |
| 160 | * expression, the "satisfies" keyword of "some/every", or the ":=" operator of |
| 161 | * a "let" expression. |
| 162 | */ |
| 163 | |
| 164 | public void setAction(Expression action) { |
| 165 | actionOp.setChildExpression(action); |
| 166 | } |
| 167 | |
| 168 | /** |
| 169 | * Indicate whether the binding is local or global. A global binding is one that has a fixed |
| 170 | * value for the life of a query or transformation; any other binding is local. |
| 171 | */ |
| 172 | |
| 173 | public final boolean isGlobal() { |
| 174 | return false; |
| 175 | } |
| 176 | |
| 177 | /** |
| 178 | * Test whether it is permitted to assign to the variable using the saxon:assign |
| 179 | * extension element. This will only be for an XSLT global variable where the extra |
| 180 | * attribute saxon:assignable="yes" is present. |
| 181 | */ |
| 182 | |
| 183 | public final boolean isAssignable() { |
| 184 | return false; |
| 185 | } |
| 186 | |
| 187 | /** |
| 188 | * Check to ensure that this expression does not contain any inappropriate updating subexpressions. |
| 189 | * This check is overridden for those expressions that permit updating subexpressions. |
| 190 | * |
| 191 | * @throws net.sf.saxon.trans.XPathException |
| 192 | * if the expression has a non-permitted updateing subexpression |
| 193 | */ |
| 194 | |
| 195 | public void checkForUpdatingSubexpressions() throws XPathException { |
| 196 | getSequence().checkForUpdatingSubexpressions(); |
| 197 | if (getSequence().isUpdatingExpression()) { |
| 198 | XPathException err = new XPathException( |
| 199 | "An updating expression cannot be used to initialize a variable", "XUST0001"); |
| 200 | err.setLocator(getSequence().getLocation()); |
| 201 | throw err; |
| 202 | } |
| 203 | getAction().checkForUpdatingSubexpressions(); |
| 204 | } |
| 205 | |
| 206 | /** |
| 207 | * Determine whether this is an updating expression as defined in the XQuery update specification |
| 208 | * |
| 209 | * @return true if this is an updating expression |
| 210 | */ |
| 211 | |
| 212 | public boolean isUpdatingExpression() { |
| 213 | return getAction().isUpdatingExpression(); |
| 214 | } |
| 215 | |
| 216 | /** |
| 217 | * Get the action expression |
| 218 | * |
| 219 | * @return the action expression (introduced by "return" or "satisfies") |
| 220 | */ |
| 221 | |
| 222 | public Expression getAction() { |
| 223 | return actionOp.getChildExpression(); |
| 224 | } |
| 225 | |
| 226 | /** |
| 227 | * Set the "sequence" expression - the one to which the variable is bound |
| 228 | * |
| 229 | * @param sequence the expression to which the variable is bound |
| 230 | */ |
| 231 | |
| 232 | public void setSequence(Expression sequence) { |
| 233 | sequenceOp.setChildExpression(sequence); |
| 234 | } |
| 235 | |
| 236 | /** |
| 237 | * Get the "sequence" expression - the one to which the variable is bound |
| 238 | * |
| 239 | * @return the expression to which the variable is bound |
| 240 | */ |
| 241 | |
| 242 | public Expression getSequence() { |
| 243 | return sequenceOp.getChildExpression(); |
| 244 | } |
| 245 | |
| 246 | /** |
| 247 | * Set the slot number for the range variable |
| 248 | * |
| 249 | * @param nr the slot number to be used |
| 250 | */ |
| 251 | |
| 252 | public void setSlotNumber(int nr) { |
| 253 | slotNumber = nr; |
| 254 | } |
| 255 | |
| 256 | /** |
| 257 | * Get the number of slots required. Normally 1, except for a FOR expression with an AT clause, where it is 2. |
| 258 | * |
| 259 | * @return the number of slots required |
| 260 | */ |
| 261 | |
| 262 | public int getRequiredSlots() { |
| 263 | return 1; |
| 264 | } |
| 265 | |
| 266 | public boolean hasVariableBinding(Binding binding) { |
| 267 | return this == binding; |
| 268 | } |
| 269 | |
| 270 | /** |
| 271 | * Replace this expression by a simpler expression that delivers the results without regard |
| 272 | * to order. |
| 273 | * |
| 274 | * @param retainAllNodes set to true if the result must contain exactly the same nodes as the |
| 275 | * original; set to false if the result can eliminate (or introduce) duplicates. |
| 276 | * @param forStreaming set to true if optimizing for streaming |
| 277 | */ |
| 278 | @Override |
| 279 | public Expression unordered(boolean retainAllNodes, boolean forStreaming) throws XPathException { |
| 280 | setAction(getAction().unordered(retainAllNodes, forStreaming)); |
| 281 | return this; |
| 282 | } |
| 283 | |
| 284 | /** |
| 285 | * Return the estimated cost of evaluating an expression. This is a very crude measure based |
| 286 | * on the syntactic form of the expression (we have no knowledge of data values). We take |
| 287 | * the cost of evaluating a simple scalar comparison or arithmetic expression as 1 (one), |
| 288 | * and we assume that a sequence has length 5. The resulting estimates may be used, for |
| 289 | * example, to reorder the predicates in a filter expression so cheaper predicates are |
| 290 | * evaluated first. |
| 291 | */ |
| 292 | @Override |
| 293 | public int getCost() { |
| 294 | return getSequence().getCost() + 5 * getAction().getCost(); |
| 295 | } |
| 296 | |
| 297 | /** |
| 298 | * Suppress validation on contained element constructors, on the grounds that the parent element |
| 299 | * is already performing validation. The default implementation does nothing. |
| 300 | */ |
| 301 | |
| 302 | public void suppressValidation(int validationMode) { |
| 303 | getAction().suppressValidation(validationMode); |
| 304 | } |
| 305 | |
| 306 | /** |
| 307 | * Add a representation of this expression to a PathMap. The PathMap captures a map of the nodes visited |
| 308 | * by an expression in a source tree. |
| 309 | * <p>The default implementation of this method assumes that an expression does no navigation other than |
| 310 | * the navigation done by evaluating its subexpressions, and that the subexpressions are evaluated in the |
| 311 | * same context as the containing expression. The method must be overridden for any expression |
| 312 | * where these assumptions do not hold. For example, implementations exist for AxisExpression, ParentExpression, |
| 313 | * and RootExpression (because they perform navigation), and for the doc(), document(), and collection() |
| 314 | * functions because they create a new navigation root. Implementations also exist for PathExpression and |
| 315 | * FilterExpression because they have subexpressions that are evaluated in a different context from the |
| 316 | * calling expression.</p> |
| 317 | * |
| 318 | * @param pathMap the PathMap to which the expression should be added |
| 319 | * @param pathMapNodeSet the PathMapNodeSet to which the paths embodied in this expression should be added |
| 320 | * @return the pathMapNodeSet representing the points in the source document that are both reachable by this |
| 321 | * expression, and that represent possible results of this expression. For an expression that does |
| 322 | * navigation, it represents the end of the arc in the path map that describes the navigation route. For other |
| 323 | * expressions, it is the same as the input pathMapNode. |
| 324 | */ |
| 325 | |
| 326 | public PathMap.PathMapNodeSet addToPathMap(PathMap pathMap, PathMap.PathMapNodeSet pathMapNodeSet) { |
| 327 | PathMap.PathMapNodeSet varPath = getSequence().addToPathMap(pathMap, pathMapNodeSet); |
| 328 | pathMap.registerPathForVariable(this, varPath); |
| 329 | return getAction().addToPathMap(pathMap, pathMapNodeSet); |
| 330 | } |
| 331 | |
| 332 | /** |
| 333 | * Get the display name of the range variable, for diagnostics only |
| 334 | * |
| 335 | * @return the lexical QName of the range variable. For system allocated |
| 336 | * variables, the conventional namespace prefix "zz" is used. |
| 337 | */ |
| 338 | |
| 339 | public String getVariableName() { |
| 340 | if (variableName == null) { |
| 341 | return "zz:var" + computeHashCode(); |
| 342 | } else { |
| 343 | return variableName.getDisplayName(); |
| 344 | } |
| 345 | } |
| 346 | |
| 347 | /** |
| 348 | * Get the name of the range variable as a Name or EQName. |
| 349 | * |
| 350 | * @return the name of the range variable. For system allocated |
| 351 | * variables, the namespace "http://ns.saxonica.com/anonymous-var" |
| 352 | * is used. For names in no namespace, the local name alone is used |
| 353 | */ |
| 354 | |
| 355 | public String getVariableEQName() { |
| 356 | if (variableName == null) { |
| 357 | return "Q{http://ns.saxonica.com/anonymous-var}var" + computeHashCode(); |
| 358 | } else if (variableName.hasURI("")) { |
| 359 | return variableName.getLocalPart(); |
| 360 | } else { |
| 361 | return variableName.getEQName(); |
| 362 | } |
| 363 | } |
| 364 | |
| 365 | /** |
| 366 | * Refine the type information associated with this variable declaration. This is useful when the |
| 367 | * type of the variable has not been explicitly declared (which is common); the variable then takes |
| 368 | * a static type based on the type of the expression to which it is bound. The effect of this call |
| 369 | * is to update the static expression type for all references to this variable. |
| 370 | * @param type the inferred item type of the expression to which the variable is bound |
| 371 | * @param cardinality the inferred cardinality of the expression to which the variable is bound |
| 372 | * @param constantValue the constant value to which the variable is bound (null if there is no constant value) |
| 373 | * @param properties other static properties of the expression to which the variable is bound |
| 374 | * @param currentExpression the expression that binds the variable |
| 375 | */ |
| 376 | |
| 377 | public void refineTypeInformation(final ItemType type, |
| 378 | final int cardinality, |
| 379 | final GroundedValue<?> constantValue, |
| 380 | final int properties, |
| 381 | final Assignation currentExpression) throws XPathException { |
| 382 | ExpressionTool.processExpressionTree(currentExpression.getAction(), null, (exp, result) -> { |
| 383 | if (exp instanceof VariableReference && ((VariableReference)exp).getBinding() == currentExpression) { |
| 384 | ((VariableReference) exp).refineVariableType(type, cardinality, constantValue, properties); |
| 385 | } |
| 386 | return false; |
| 387 | }); |
| 388 | } |
| 389 | |
| 390 | /** |
| 391 | * Register a variable reference that refers to the variable bound in this expression |
| 392 | * |
| 393 | * @param ref the variable reference |
| 394 | * @param isLoopingReference - true if the reference occurs within a loop, such as the predicate |
| 395 | * of a filter expression |
| 396 | */ |
| 397 | |
| 398 | public void addReference(VariableReference ref, boolean isLoopingReference) { |
| 399 | hasLoopingReference |= isLoopingReference; |
| 400 | if (references == null) { |
| 401 | references = new ArrayList<VariableReference>(); |
| 402 | } |
| 403 | for (VariableReference vr : references) { |
| 404 | if (vr == ref) { |
| 405 | return; |
| 406 | } |
| 407 | } |
| 408 | references.add(ref); |
| 409 | } |
| 410 | |
| 411 | /** |
| 412 | * Get the (nominal) count of the number of references to this variable |
| 413 | * |
| 414 | * @return zero if there are no references, one if there is a single reference that is not in |
| 415 | * a loop, some higher number if there are multiple references (or a single reference in a loop), |
| 416 | * or the special value @link RangeVariable#FILTERED} if there are any references |
| 417 | * in filter expressions that require searching. |
| 418 | */ |
| 419 | |
| 420 | public int getNominalReferenceCount() { |
| 421 | if (isIndexedVariable) { |
| 422 | return FilterExpression.FILTERED; |
| 423 | } else if (references == null || hasLoopingReference) { |
| 424 | return 10; |
| 425 | } else { |
| 426 | return references.size(); |
| 427 | } |
| 428 | } |
| 429 | |
| 430 | /** |
| 431 | * Remove dead references from the reference list of the variable; at the same time, check whether |
| 432 | * any of the variable references is in a loop, and return true if so. References are considered dead |
| 433 | * if they do not have this Binding as an ancestor in the expression tree; this typically occurs because |
| 434 | * they are in a part of the tree that has been rewritten or removed. |
| 435 | * @return true if any of the references in the reference list occurs within a looping construct. |
| 436 | */ |
| 437 | |
| 438 | protected boolean removeDeadReferences() { |
| 439 | boolean inLoop = false; |
| 440 | if (references != null) { |
| 441 | for (int i = references.size() - 1; i >= 0; i--) { |
| 442 | // Check whether the reference still has this Assignation as an ancestor in the expression tree |
| 443 | boolean found = false; |
| 444 | inLoop |= references.get(i).isInLoop(); |
| 445 | Expression parent = references.get(i).getParentExpression(); |
| 446 | while (parent != null) { |
| 447 | if (parent == this) { |
| 448 | found = true; |
| 449 | break; |
| 450 | } else { |
| 451 | parent = parent.getParentExpression(); |
| 452 | } |
| 453 | } |
| 454 | if (!found) { |
| 455 | references.remove(i); |
| 456 | } |
| 457 | } |
| 458 | } |
| 459 | return inLoop; |
| 460 | } |
| 461 | |
| 462 | /** |
| 463 | * This method recomputes the reference list by scanning the subtree rooted at this variable binding. |
| 464 | * If the scan proves expensive, or if more than two references are found, or if a looping reference is found, |
| 465 | * then the scan is abandoned. On completion the reference list for the variable is either accurate, or |
| 466 | * is null. |
| 467 | */ |
| 468 | |
| 469 | protected void verifyReferences() { |
| 470 | rebuildReferenceList(false); |
| 471 | } |
| 472 | |
| 473 | /** |
| 474 | * Rebuild the reference list to guide subsequent optimization. |
| 475 | * @param force if true, the search is exhaustive. If false, the search (and therefore the attempt to |
| 476 | * inline variables) is abandoned after a while to avoid excessive cost. This happens when |
| 477 | * a stylesheet contains very large templates or functions. |
| 478 | */ |
| 479 | |
| 480 | public void rebuildReferenceList(boolean force) { |
| 481 | int[] results = new int[]{0, force ? Integer.MAX_VALUE : 500}; |
| 482 | List<VariableReference> references = new ArrayList<>(); |
| 483 | countReferences(this, getAction(), references, results); |
| 484 | this.references = results[1] <= 0 ? null : references; |
| 485 | } |
| 486 | |
| 487 | private static void countReferences(Binding binding, Expression exp, List<VariableReference> references, int[] results) { |
| 488 | // results[0] = nominal reference count |
| 489 | // results[1] = quota nodes visited |
| 490 | if (exp instanceof LocalVariableReference) { |
| 491 | LocalVariableReference ref = (LocalVariableReference) exp; |
| 492 | if (ref.getBinding() == binding) { |
| 493 | ref.recomputeInLoop(); |
| 494 | results[0] += ref.isInLoop() ? 10 : 1; |
| 495 | references.add((LocalVariableReference) exp); |
| 496 | } |
| 497 | } else if ((exp.getDependencies() & StaticProperty.DEPENDS_ON_LOCAL_VARIABLES) != 0) { |
| 498 | if (--results[1] <= 0) { |
| 499 | // abandon the search |
| 500 | results[0] = 100; |
| 501 | results[1] = 0; |
| 502 | } else { |
| 503 | for (Operand o : exp.operands()) { |
| 504 | countReferences(binding, o.getChildExpression(), references, results); |
| 505 | } |
| 506 | } |
| 507 | } |
| 508 | } |
| 509 | |
| 510 | /** |
| 511 | * Test whether the variable bound by this let expression should be indexable |
| 512 | * |
| 513 | * @return true if the variable should be indexable |
| 514 | */ |
| 515 | |
| 516 | public boolean isIndexedVariable() { |
| 517 | return isIndexedVariable; |
| 518 | } |
| 519 | |
| 520 | /** |
| 521 | * Replace all references to the variable bound by this let expression, |
| 522 | * that occur within the action expression, with the given expression |
| 523 | * |
| 524 | * |
| 525 | * @param seq the expression |
| 526 | * @return true if the variable was successfully inlined. (Returns false, for example, |
| 527 | * if a variable reference occurs inside a try/catch, which inhibits inlining). |
| 528 | */ |
| 529 | |
| 530 | public boolean replaceVariable(Expression seq) { |
| 531 | boolean done = ExpressionTool.inlineVariableReferences(getAction(), this, seq); |
| 532 | if (done && isIndexedVariable() && seq instanceof VariableReference) { |
| 533 | Binding newBinding = ((VariableReference) seq).getBinding(); |
| 534 | if (newBinding instanceof Assignation) { |
| 535 | ((Assignation) newBinding).setIndexedVariable(); |
| 536 | } |
| 537 | } |
| 538 | return done; |
| 539 | } |
| 540 | |
| 541 | /** |
| 542 | * Indicate that the variable bound by this let expression should be indexable |
| 543 | * (because it is used in an appropriate filter expression) |
| 544 | */ |
| 545 | |
| 546 | public void setIndexedVariable() { |
| 547 | isIndexedVariable = true; |
| 548 | } |
| 549 | } |
| 550 |