| 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.Configuration; |
| 11 | import net.sf.saxon.event.Receiver; |
| 12 | import net.sf.saxon.event.ReceiverOptions; |
| 13 | import net.sf.saxon.expr.parser.*; |
| 14 | import net.sf.saxon.functions.KeyFn; |
| 15 | import net.sf.saxon.functions.SuperId; |
| 16 | import net.sf.saxon.functions.SystemFunction; |
| 17 | import net.sf.saxon.lib.Logger; |
| 18 | import net.sf.saxon.om.*; |
| 19 | import net.sf.saxon.pattern.NodeKindTest; |
| 20 | import net.sf.saxon.pattern.NodeSetPattern; |
| 21 | import net.sf.saxon.pattern.NodeTest; |
| 22 | import net.sf.saxon.pattern.Pattern; |
| 23 | import net.sf.saxon.trace.ExpressionPresenter; |
| 24 | import net.sf.saxon.trace.LocationKind; |
| 25 | import net.sf.saxon.trans.XPathException; |
| 26 | import net.sf.saxon.tree.iter.EmptyIterator; |
| 27 | import net.sf.saxon.tree.iter.SingletonIterator; |
| 28 | import net.sf.saxon.tree.jiter.MonoIterator; |
| 29 | import net.sf.saxon.tree.util.FastStringBuffer; |
| 30 | import net.sf.saxon.type.AtomicType; |
| 31 | import net.sf.saxon.type.ItemType; |
| 32 | import net.sf.saxon.type.SchemaType; |
| 33 | import net.sf.saxon.type.UType; |
| 34 | import net.sf.saxon.value.*; |
| 35 | import net.sf.saxon.z.IntHashSet; |
| 36 | import net.sf.saxon.z.IntIterator; |
| 37 | |
| 38 | import java.net.URI; |
| 39 | import java.util.*; |
| 40 | |
| 41 | /** |
| 42 | * Interface supported by an XPath expression. This includes both compile-time |
| 43 | * and run-time methods. |
| 44 | * |
| 45 | * <p>Two expressions are considered equal if they return the same result when evaluated in the |
| 46 | * same context.</p> |
| 47 | * |
| 48 | * <p>Expressions manage their own subexpressions but must observe certain conventions when doing |
| 49 | * so. Every expression must implement the methods operands() and getOperand(N) to access the |
| 50 | * operands of the expression; here N is an integer identifier for the subexpression which |
| 51 | * is unique among the subexpressions and whose allocation is a matter for each expression |
| 52 | * to determined. So a subexpression of an expression can change (during optimization rewrite, |
| 53 | * for example), then (a) the expression must implement the method setOperandExpression(N, expr) |
| 54 | * to effect the change, and (b) calling this method must cause a call on adoptChildExpression(N, expr) |
| 55 | * which is implemented in the expression class itself, and takes responsibility for maintaining |
| 56 | * the consistency of the tree, e.g. by invalidating cached information.</p> |
| 57 | * |
| 58 | * <p>The default implementations of methods such as operands() work for expressions that have |
| 59 | * no subexpressions.</p> |
| 60 | */ |
| 61 | |
| 62 | public abstract class Expression implements IdentityComparable, ExportAgent, Locatable { |
| 63 | |
| 64 | public static final int EVALUATE_METHOD = 1; |
| 65 | public static final int ITERATE_METHOD = 2; |
| 66 | public static final int PROCESS_METHOD = 4; |
| 67 | public static final int WATCH_METHOD = 8; |
| 68 | public static final int ITEM_FEED_METHOD = 16; |
| 69 | public static final int EFFECTIVE_BOOLEAN_VALUE = 32; |
| 70 | public static final int UPDATE_METHOD = 64; |
| 71 | |
| 72 | |
| 73 | protected int staticProperties = -1; |
| 74 | private Location location = ExplicitLocation.UNKNOWN_LOCATION; |
| 75 | private Expression parentExpression; |
| 76 | private RetainedStaticContext retainedStaticContext; |
| 77 | private int[] slotsUsed; |
| 78 | private int evaluationMethod; |
| 79 | private Map<String, Object> extraProperties; |
| 80 | private int cost = -1; |
| 81 | private int cachedHashCode = -1; |
| 82 | |
| 83 | // public int serial; // used to identify expressions for internal diagnostics |
| 84 | // private static int nextSerial = 0; |
| 85 | |
| 86 | public Expression() { |
| 87 | //serial = nextSerial++; |
| 88 | } |
| 89 | |
| 90 | |
| 91 | /** |
| 92 | * Get a name identifying the kind of expression, in terms meaningful to a user. |
| 93 | * |
| 94 | * @return a name identifying the kind of expression, in terms meaningful to a user. |
| 95 | * The name will always be in the form of a lexical XML QName, and should match the name used |
| 96 | * in export() output displaying the expression. |
| 97 | */ |
| 98 | |
| 99 | public String getExpressionName() { |
| 100 | return getClass().getSimpleName(); |
| 101 | } |
| 102 | |
| 103 | /** |
| 104 | * Get the immediate sub-expressions of this expression, with information about the relationship |
| 105 | * of each expression to its parent expression. Default implementation |
| 106 | * works off the results of iterateSubExpressions() |
| 107 | * |
| 108 | * <p>If the expression is a Callable, then it is required that the order of the operands |
| 109 | * returned by this function is the same as the order of arguments supplied to the corresponding |
| 110 | * call() method.</p> |
| 111 | * |
| 112 | * @return an iterator containing the sub-expressions of this expression |
| 113 | */ |
| 114 | |
| 115 | /*@NotNull*/ |
| 116 | public Iterable<Operand> operands() { |
| 117 | return Collections.emptyList(); |
| 118 | } |
| 119 | |
| 120 | /** |
| 121 | * Get the interpreted form of the expression. Normally this returns the expression unchanged; |
| 122 | * but on a CompiledExpression (the result of bytecode generation) it returns the original |
| 123 | * interpreted form. |
| 124 | * @return the interpreted form of this expression |
| 125 | */ |
| 126 | |
| 127 | public Expression getInterpretedExpression() { |
| 128 | return this; |
| 129 | } |
| 130 | |
| 131 | /** |
| 132 | * Get the immediate sub-expressions of this expression, verifying that the parent pointers |
| 133 | * in the child expressions are correct. |
| 134 | * @return the list of sub-expressions, in the same way as with the {@link #operands()} method, |
| 135 | * but with additional checking |
| 136 | */ |
| 137 | |
| 138 | public final Iterable<Operand> checkedOperands() { |
| 139 | Iterable<Operand> ops = operands(); |
| 140 | for (Operand o : ops) { |
| 141 | Expression child = o.getChildExpression(); |
| 142 | boolean badOperand = o.getParentExpression() != this; |
| 143 | boolean badExpression = child.getParentExpression() != this; |
| 144 | if (badOperand || badExpression) { |
| 145 | String message = "*** Bad parent pointer found in " + |
| 146 | (badOperand ? "operand " : "expression ") + |
| 147 | child.toShortString() + |
| 148 | " at " + child.getLocation().getSystemId() + "#" + child.getLocation().getLineNumber() + " ***"; |
| 149 | try { |
| 150 | Configuration config = getConfiguration(); |
| 151 | Logger logger = config == null ? null : config.getLogger(); |
| 152 | if (logger != null) { |
| 153 | logger.warning(message); |
| 154 | } else { |
| 155 | throw new IllegalStateException(message); |
| 156 | } |
| 157 | } catch (Exception err) { |
| 158 | throw new IllegalStateException(message); |
| 159 | } |
| 160 | child.setParentExpression(Expression.this); |
| 161 | } |
| 162 | if (child.getRetainedStaticContext() == null) { |
| 163 | child.setRetainedStaticContext(getRetainedStaticContext()); |
| 164 | } |
| 165 | } |
| 166 | return ops; |
| 167 | } |
| 168 | |
| 169 | /** |
| 170 | * Helper method for subclasses to build a list of operands |
| 171 | * @param a the sequence of operands (which must all be non-null) |
| 172 | * @return a list of operands |
| 173 | */ |
| 174 | |
| 175 | protected List<Operand> operandList(Operand... a) { |
| 176 | return Arrays.asList(a); |
| 177 | } |
| 178 | |
| 179 | /** |
| 180 | * Helper method for subclasses to build a list of operands |
| 181 | * @param a the sequence of operands; any null values in the list are ignored |
| 182 | * @return a list of operands |
| 183 | */ |
| 184 | |
| 185 | protected List<Operand> operandSparseList(Operand... a) { |
| 186 | List<Operand> operanda = new ArrayList<>(); |
| 187 | for (Operand o : a) { |
| 188 | if (o != null) { |
| 189 | operanda.add(o); |
| 190 | } |
| 191 | } |
| 192 | return operanda; |
| 193 | } |
| 194 | |
| 195 | /** |
| 196 | * Get the parent expression of this expression in the expression tree. |
| 197 | * @return the parent expression. Null if at the root of the tree, for example, |
| 198 | * the expression representing the body of a function or template. |
| 199 | */ |
| 200 | |
| 201 | public Expression getParentExpression() { |
| 202 | return parentExpression; |
| 203 | } |
| 204 | |
| 205 | /** |
| 206 | * Set the parent expression of this expression in the expression tree. |
| 207 | * @param parent the parent expression |
| 208 | */ |
| 209 | |
| 210 | public void setParentExpression(Expression parent) { |
| 211 | // if (parent != null && parent != parentExpression) { |
| 212 | // System.err.println("Set parent of " + this.getClass() + serial + " to " + parent.getClass() + parent.serial); |
| 213 | // } |
| 214 | parentExpression = parent; |
| 215 | } |
| 216 | |
| 217 | /** |
| 218 | * Verify that parent pointers are correct throughout the subtree rooted at this expression |
| 219 | * @throws IllegalStateException if invalid parent pointers are found |
| 220 | * @return the expression |
| 221 | */ |
| 222 | |
| 223 | public Expression verifyParentPointers() throws IllegalStateException { |
| 224 | for (Operand o : operands()) { |
| 225 | Expression parent = o.getChildExpression().getParentExpression(); |
| 226 | if (parent != this) { |
| 227 | throw new IllegalStateException("Invalid parent pointer in " + parent.toShortString() + |
| 228 | " subexpression " + o.getChildExpression().toShortString()); |
| 229 | } |
| 230 | if (o.getParentExpression() != this) { |
| 231 | throw new IllegalStateException("Invalid parent pointer in operand object " + parent.toShortString() + |
| 232 | " subexpression " + o.getChildExpression().toShortString()); |
| 233 | } |
| 234 | if (ExpressionTool.findOperand(parent, o.getChildExpression()) == null) { |
| 235 | throw new IllegalStateException("Incorrect parent pointer in " + parent.toShortString() + |
| 236 | " subexpression " + o.getChildExpression().toShortString()); |
| 237 | } |
| 238 | o.getChildExpression().verifyParentPointers(); |
| 239 | } |
| 240 | return this; |
| 241 | } |
| 242 | |
| 243 | /** |
| 244 | * Restore parent pointers for the subtree rooted at this expression |
| 245 | */ |
| 246 | |
| 247 | public void restoreParentPointers() { |
| 248 | for (Operand o : operands()) { |
| 249 | Expression child = o.getChildExpression(); |
| 250 | child.setParentExpression(Expression.this); |
| 251 | child.restoreParentPointers(); |
| 252 | } |
| 253 | } |
| 254 | |
| 255 | /** |
| 256 | * An implementation of Expression must provide at least one of the methods evaluateItem(), iterate(), or process(). |
| 257 | * This method indicates which of these methods is provided directly. The other methods will always be available |
| 258 | * indirectly, using an implementation that relies on one of the other methods. |
| 259 | * |
| 260 | * @return the implementation method, for example {@link #ITERATE_METHOD} or {@link #EVALUATE_METHOD} or |
| 261 | * {@link #PROCESS_METHOD} |
| 262 | */ |
| 263 | |
| 264 | public abstract int getImplementationMethod(); |
| 265 | |
| 266 | /** |
| 267 | * Determine whether this expression implements its own method for static type checking |
| 268 | * |
| 269 | * @return true if this expression has a non-trivial implementation of the staticTypeCheck() |
| 270 | * method |
| 271 | */ |
| 272 | |
| 273 | public boolean implementsStaticTypeCheck() { |
| 274 | return false; |
| 275 | } |
| 276 | |
| 277 | /** |
| 278 | * Ask whether this expression is, or contains, the binding of a given variable |
| 279 | * @param binding the variable binding |
| 280 | * @return true if this expression is the variable binding (for example a ForExpression |
| 281 | * or LetExpression) or if it is a FLWOR expression that binds the variable in one of its |
| 282 | * clauses. |
| 283 | */ |
| 284 | |
| 285 | public boolean hasVariableBinding(Binding binding) { |
| 286 | return false; |
| 287 | } |
| 288 | |
| 289 | /** |
| 290 | * Ask whether the expression can be lifted out of a loop, assuming it has no dependencies |
| 291 | * on the controlling variable/focus of the loop |
| 292 | * @param forStreaming true if we are optimizing for streamed evaluation |
| 293 | * @return true if the expression can be loop lifted |
| 294 | */ |
| 295 | |
| 296 | public boolean isLiftable(boolean forStreaming) { |
| 297 | int p = getSpecialProperties(); |
| 298 | int d = getDependencies(); |
| 299 | return (p & StaticProperty.NO_NODES_NEWLY_CREATED) != 0 && (p & StaticProperty.HAS_SIDE_EFFECTS) == 0 |
| 300 | && ((d & StaticProperty.DEPENDS_ON_ASSIGNABLE_GLOBALS) == 0) |
| 301 | && ((d & StaticProperty.DEPENDS_ON_POSITION) == 0) // bug 3758 |
| 302 | && ((d & StaticProperty.DEPENDS_ON_LAST) == 0); |
| 303 | } |
| 304 | |
| 305 | /** |
| 306 | * Get the innermost scoping expression of this expression, for expressions that directly |
| 307 | * depend on something in the dynamic context. For example, in the case of a local variable |
| 308 | * reference this is the expression that causes the relevant variable to be bound; for a |
| 309 | * context item expression it is the innermost focus-setting container. For expressions |
| 310 | * that have no intrinsic dependency on the dynamic context, the value returned is null; |
| 311 | * the scoping container for such an expression is the innermost scoping container of its |
| 312 | * operands. |
| 313 | * @return the innermost scoping container of this expression |
| 314 | */ |
| 315 | |
| 316 | public Expression getScopingExpression() { |
| 317 | int d = getIntrinsicDependencies() & StaticProperty.DEPENDS_ON_FOCUS; |
| 318 | if (d != 0) { |
| 319 | if (d == StaticProperty.DEPENDS_ON_CONTEXT_DOCUMENT) { |
| 320 | return ExpressionTool.getContextDocumentSettingContainer(this); |
| 321 | } else { |
| 322 | return ExpressionTool.getFocusSettingContainer(this); |
| 323 | } |
| 324 | } else { |
| 325 | return null; |
| 326 | } |
| 327 | } |
| 328 | |
| 329 | /** |
| 330 | * Ask whether the expression is multithreaded (that is, whether its operands are |
| 331 | * evaluated in parallel) |
| 332 | * @param config the Saxon configuration |
| 333 | * @return true if execution will be multithreaded |
| 334 | */ |
| 335 | |
| 336 | public boolean isMultiThreaded(Configuration config) { |
| 337 | return false; |
| 338 | } |
| 339 | |
| 340 | /** |
| 341 | * Ask whether common subexpressions found in the operands of this expression can |
| 342 | * be extracted and evaluated outside the expression itself. The result is irrelevant |
| 343 | * in the case of operands evaluated with a different focus, which will never be |
| 344 | * extracted in this way, even if they have no focus dependency. |
| 345 | * @return true by default, unless overridden in a subclass |
| 346 | */ |
| 347 | |
| 348 | public boolean allowExtractingCommonSubexpressions() { |
| 349 | return true; |
| 350 | } |
| 351 | |
| 352 | /** |
| 353 | * Simplify an expression. This performs any static optimization (by rewriting the expression |
| 354 | * as a different expression). The default implementation simplifies its operands. |
| 355 | * @return the simplified expression (or the original if unchanged, or if modified in-situ) |
| 356 | * @throws net.sf.saxon.trans.XPathException |
| 357 | * if an error is discovered during expression |
| 358 | * rewriting |
| 359 | */ |
| 360 | |
| 361 | /*@NotNull*/ |
| 362 | public Expression simplify() throws XPathException { |
| 363 | simplifyChildren(); |
| 364 | return Expression.this; |
| 365 | } |
| 366 | |
| 367 | /** |
| 368 | * Simplify this expression. This performs any static optimization (by rewriting the expression |
| 369 | * as a different expression). The default implementation simplifies its operands. |
| 370 | * @throws net.sf.saxon.trans.XPathException |
| 371 | * if an error is discovered during expression |
| 372 | * rewriting |
| 373 | */ |
| 374 | |
| 375 | /*@NotNull*/ |
| 376 | protected final void simplifyChildren() throws XPathException { |
| 377 | for (Operand o : operands()) { |
| 378 | if (o != null) { |
| 379 | Expression e = o.getChildExpression(); |
| 380 | if (e != null) { |
| 381 | Expression f = e.simplify(); |
| 382 | o.setChildExpression(f); |
| 383 | } |
| 384 | } |
| 385 | } |
| 386 | } |
| 387 | |
| 388 | |
| 389 | /** |
| 390 | * Set the retained static context |
| 391 | * @param rsc the static context to be retained |
| 392 | */ |
| 393 | |
| 394 | public void setRetainedStaticContext(RetainedStaticContext rsc) { |
| 395 | if (rsc != null) { |
| 396 | retainedStaticContext = rsc; |
| 397 | for (Operand o : operands()) { |
| 398 | if (o != null) { |
| 399 | Expression child = o.getChildExpression(); |
| 400 | if (child != null && child.retainedStaticContext == null) { |
| 401 | child.setRetainedStaticContext(rsc); |
| 402 | } |
| 403 | } |
| 404 | } |
| 405 | } |
| 406 | } |
| 407 | |
| 408 | /** |
| 409 | * Set the retained static context on this expression and on all subexpressions in the expression tree. |
| 410 | * The supplied retained static context is applied to all subexpressions, unless they have a closer |
| 411 | * ancestor with an existing retained static context, in which case that is used instead, |
| 412 | * |
| 413 | * @param rsc the static context to be retained |
| 414 | */ |
| 415 | |
| 416 | public void setRetainedStaticContextThoroughly(RetainedStaticContext rsc) { |
| 417 | if (rsc != null) { |
| 418 | retainedStaticContext = rsc; |
| 419 | for (Operand o : operands()) { |
| 420 | if (o != null) { |
| 421 | Expression child = o.getChildExpression(); |
| 422 | if (child != null) { |
| 423 | if (child.getLocalRetainedStaticContext() == null) { |
| 424 | child.setRetainedStaticContextThoroughly(rsc); |
| 425 | } else { |
| 426 | rsc = child.getLocalRetainedStaticContext(); |
| 427 | for (Operand p : child.operands()) { |
| 428 | Expression grandchild = p.getChildExpression(); |
| 429 | if (grandchild != null) { |
| 430 | grandchild.setRetainedStaticContextThoroughly(rsc); |
| 431 | } |
| 432 | } |
| 433 | } |
| 434 | } |
| 435 | } |
| 436 | } |
| 437 | } |
| 438 | } |
| 439 | |
| 440 | /** |
| 441 | * Set the parts of the static context that might be needed by the function, without |
| 442 | * passing them on to subexpressions. Used for dynamic function calls only. |
| 443 | * @param rsc the retained static context |
| 444 | */ |
| 445 | |
| 446 | public void setRetainedStaticContextLocally(RetainedStaticContext rsc) { |
| 447 | if (rsc != null) { |
| 448 | retainedStaticContext = rsc; |
| 449 | } |
| 450 | } |
| 451 | |
| 452 | /** |
| 453 | * Get the retained static context of the expression |
| 454 | * @return the retained static context |
| 455 | */ |
| 456 | |
| 457 | public final RetainedStaticContext getRetainedStaticContext() { |
| 458 | if (retainedStaticContext == null) { |
| 459 | Expression parent = getParentExpression(); |
| 460 | assert parent != null; |
| 461 | retainedStaticContext = parent.getRetainedStaticContext(); |
| 462 | assert retainedStaticContext != null; |
| 463 | } |
| 464 | return retainedStaticContext; |
| 465 | } |
| 466 | |
| 467 | public RetainedStaticContext getLocalRetainedStaticContext() { |
| 468 | return retainedStaticContext; |
| 469 | } |
| 470 | |
| 471 | /** |
| 472 | * Get the saved static base URI as a string |
| 473 | * |
| 474 | * @return the static base URI |
| 475 | */ |
| 476 | |
| 477 | public String getStaticBaseURIString() { |
| 478 | return getRetainedStaticContext().getStaticBaseUriString(); |
| 479 | } |
| 480 | |
| 481 | /** |
| 482 | * Get the saved static base URI as a URI |
| 483 | * |
| 484 | * @return the static base URI as a URI |
| 485 | * @throws XPathException if the static base URI is not a valid URI |
| 486 | */ |
| 487 | |
| 488 | public URI getStaticBaseURI() throws XPathException { |
| 489 | return getRetainedStaticContext().getStaticBaseUri(); |
| 490 | } |
| 491 | |
| 492 | /** |
| 493 | * Ask whether this expression is a call on a particular function |
| 494 | * @param function the implementation class of the function in question |
| 495 | * @return true if the expression is a call on the function |
| 496 | */ |
| 497 | |
| 498 | public boolean isCallOn(Class<? extends SystemFunction> function) { |
| 499 | return false; |
| 500 | } |
| 501 | |
| 502 | /** |
| 503 | * Perform type checking of an expression and its subexpressions. This is the second phase of |
| 504 | * static optimization. |
| 505 | * <p>This checks statically that the operands of the expression have |
| 506 | * the correct type; if necessary it generates code to do run-time type checking or type |
| 507 | * conversion. A static type error is reported only if execution cannot possibly succeed, that |
| 508 | * is, if a run-time type error is inevitable. The call may return a modified form of the expression.</p> |
| 509 | * <p>This method is called after all references to functions and variables have been resolved |
| 510 | * to the declaration of the function or variable. However, the types of such functions and |
| 511 | * variables may not be accurately known if they have not been explicitly declared.</p> |
| 512 | * |
| 513 | * |
| 514 | * @param visitor an expression visitor |
| 515 | * @param contextInfo Information available statically about the context item: whether it is (possibly) |
| 516 | * absent; its static type; its streaming posture. |
| 517 | * @return the original expression, rewritten to perform necessary run-time type checks, |
| 518 | * and to perform other type-related optimizations |
| 519 | * @throws XPathException if an error is discovered during this phase |
| 520 | * (typically a type error) |
| 521 | */ |
| 522 | |
| 523 | /*@NotNull*/ |
| 524 | public Expression typeCheck(ExpressionVisitor visitor, |
| 525 | ContextItemStaticInfo contextInfo) throws XPathException { |
| 526 | typeCheckChildren(visitor, contextInfo); |
| 527 | return Expression.this; |
| 528 | } |
| 529 | |
| 530 | /** |
| 531 | * Perform type checking of the children of this expression (and their children, recursively) |
| 532 | * This method is provided as a helper for implementations of the |
| 533 | * {@link #typeCheck(net.sf.saxon.expr.parser.ExpressionVisitor, net.sf.saxon.expr.parser.ContextItemStaticInfo)} |
| 534 | * method, since checking the children is an inevitable part of checking the expression itse.f |
| 535 | * |
| 536 | * @param visitor an expression visitor |
| 537 | * @param contextInfo Information available statically about the context item: whether it is (possibly) |
| 538 | * absent; its static type; its streaming posture. |
| 539 | * @throws XPathException if an error is discovered during this phase |
| 540 | * (typically a type error) |
| 541 | */ |
| 542 | |
| 543 | /*@NotNull*/ |
| 544 | protected final void typeCheckChildren(ExpressionVisitor visitor, |
| 545 | ContextItemStaticInfo contextInfo) throws XPathException { |
| 546 | for (Operand o : operands()) { |
| 547 | o.typeCheck(visitor, contextInfo); |
| 548 | } |
| 549 | } |
| 550 | |
| 551 | |
| 552 | /** |
| 553 | * Static type checking of some expressions is delegated to the expression itself, by calling |
| 554 | * this method. The default implementation of the method throws UnsupportedOperationException. |
| 555 | * If there is a non-default implementation, then implementsStaticTypeCheck() will return true |
| 556 | * |
| 557 | * |
| 558 | * @param req the required type |
| 559 | * @param backwardsCompatible true if backwards compatibility mode applies |
| 560 | * @param role the role of the expression in relation to the required type |
| 561 | * @param visitor an expression visitor |
| 562 | * @return the expression after type checking (perhaps augmented with dynamic type checking code) |
| 563 | * @throws XPathException if failures occur, for example if the static type of one branch of the conditional |
| 564 | * is incompatible with the required type |
| 565 | */ |
| 566 | |
| 567 | public Expression staticTypeCheck(SequenceType req, |
| 568 | boolean backwardsCompatible, |
| 569 | RoleDiagnostic role, ExpressionVisitor visitor) |
| 570 | throws XPathException { |
| 571 | throw new UnsupportedOperationException("staticTypeCheck"); |
| 572 | } |
| 573 | |
| 574 | /** |
| 575 | * Perform optimisation of an expression and its subexpressions. This is the third and final |
| 576 | * phase of static optimization. |
| 577 | * <p>This method is called after all references to functions and variables have been resolved |
| 578 | * to the declaration of the function or variable, and after all type checking has been done.</p> |
| 579 | * |
| 580 | * @param visitor an expression visitor |
| 581 | * @param contextInfo the static type of "." at the point where this expression is invoked. |
| 582 | * The parameter is set to null if it is known statically that the context item will be undefined. |
| 583 | * If the type of the context item is not known statically, the argument is set to |
| 584 | * {@link net.sf.saxon.type.Type#ITEM_TYPE} |
| 585 | * @return the original expression, rewritten if appropriate to optimize execution |
| 586 | * @throws XPathException if an error is discovered during this phase |
| 587 | * (typically a type error) |
| 588 | */ |
| 589 | |
| 590 | /*@NotNull*/ |
| 591 | public Expression optimize(ExpressionVisitor visitor, |
| 592 | /*@Nullable*/ ContextItemStaticInfo contextInfo) throws XPathException { |
| 593 | if (visitor.incrementAndTestDepth()) { // protect against infinite recursion |
| 594 | optimizeChildren(visitor, contextInfo); |
| 595 | visitor.decrementDepth(); |
| 596 | } |
| 597 | return Expression.this; |
| 598 | } |
| 599 | |
| 600 | /** |
| 601 | * Perform optimization of the children of this expression (and their children, recursively) |
| 602 | * This method is provided as a helper for implementations of the |
| 603 | * {@link #optimize(net.sf.saxon.expr.parser.ExpressionVisitor, net.sf.saxon.expr.parser.ContextItemStaticInfo)} |
| 604 | * method, since optimizing the children is an inevitable part of optimizing the expression itself |
| 605 | * |
| 606 | * @param visitor an expression visitor |
| 607 | * @param contextInfo Information available statically about the context item: whether it is (possibly) |
| 608 | * absent; its static type; its streaming posture. |
| 609 | * @throws XPathException if an error is discovered during this phase |
| 610 | * (typically a type error) |
| 611 | */ |
| 612 | |
| 613 | /*@NotNull*/ |
| 614 | protected final void optimizeChildren(ExpressionVisitor visitor, |
| 615 | ContextItemStaticInfo contextInfo) throws XPathException { |
| 616 | for (Operand o : operands()) { |
| 617 | o.optimize(visitor, contextInfo); |
| 618 | } |
| 619 | } |
| 620 | |
| 621 | public void prepareForStreaming() throws XPathException { |
| 622 | // no action by default |
| 623 | } |
| 624 | |
| 625 | /** |
| 626 | * Return the estimated cost of evaluating an expression. This is a very crude measure based |
| 627 | * on the syntactic form of the expression (we have no knowledge of data values). We take |
| 628 | * the cost of evaluating a simple scalar comparison or arithmetic expression as 1 (one), |
| 629 | * and we assume that a sequence has length 5. The resulting estimates may be used, for |
| 630 | * example, to reorder the predicates in a filter expression so cheaper predicates are |
| 631 | * evaluated first. |
| 632 | * @return an estimate of the gross cost of evaluating the expression, including the cost |
| 633 | * of evaluating its operands. |
| 634 | */ |
| 635 | |
| 636 | public int getCost() { |
| 637 | if (cost < 0) { |
| 638 | int i = getNetCost(); |
| 639 | for (Operand o : operands()) { |
| 640 | i += o.getChildExpression().getCost(); |
| 641 | } |
| 642 | cost = i; |
| 643 | } |
| 644 | return cost; |
| 645 | } |
| 646 | |
| 647 | /** |
| 648 | * Return the net cost of evaluating this expression, excluding the cost of evaluating |
| 649 | * its operands. We take the cost of evaluating a simple scalar comparison or arithmetic |
| 650 | * expression as 1 (one). |
| 651 | * @return the intrinsic cost of this operation, excluding the costs of evaluating |
| 652 | * the operands |
| 653 | */ |
| 654 | |
| 655 | public int getNetCost() { |
| 656 | return 1; |
| 657 | } |
| 658 | |
| 659 | |
| 660 | /** |
| 661 | * Replace this expression by a simpler expression that delivers the results without regard |
| 662 | * to order. |
| 663 | * |
| 664 | * @param retainAllNodes set to true if the result must contain exactly the same nodes as the |
| 665 | * original; set to false if the result can eliminate (or introduce) duplicates. |
| 666 | * @param forStreaming set to true if the result is to be optimized for streaming |
| 667 | * @return an expression that delivers the same nodes in a more convenient order |
| 668 | * @throws XPathException if the rewrite fails |
| 669 | */ |
| 670 | |
| 671 | public Expression unordered(boolean retainAllNodes, boolean forStreaming) throws XPathException { |
| 672 | return Expression.this; |
| 673 | } |
| 674 | |
| 675 | /** |
| 676 | * Get the static properties of this expression (other than its type). The result is |
| 677 | * bit-signficant. These properties are used for optimizations. In general, if |
| 678 | * property bit is set, it is true, but if it is unset, the value is unknown. |
| 679 | * |
| 680 | * @return a set of flags indicating static properties of this expression |
| 681 | */ |
| 682 | |
| 683 | public final int getSpecialProperties() { |
| 684 | if (staticProperties == -1) { |
| 685 | computeStaticProperties(); |
| 686 | } |
| 687 | return staticProperties & StaticProperty.SPECIAL_PROPERTY_MASK; |
| 688 | } |
| 689 | |
| 690 | /** |
| 691 | * Ask whether a particular "special property" is present for this expression |
| 692 | * @param property the property in question, as an integer code in the {@link StaticProperty} class |
| 693 | * @return true if the given property is present |
| 694 | */ |
| 695 | |
| 696 | public boolean hasSpecialProperty(int property) { |
| 697 | return (getSpecialProperties() & property) != 0; |
| 698 | } |
| 699 | |
| 700 | /** |
| 701 | * Determine the static cardinality of the expression. This establishes how many items |
| 702 | * there will be in the result of the expression, at compile time (i.e., without |
| 703 | * actually evaluating the result. |
| 704 | * |
| 705 | * @return one of the values Cardinality.ONE_OR_MORE, |
| 706 | * Cardinality.ZERO_OR_MORE, Cardinality.EXACTLY_ONE, |
| 707 | * Cardinality.ZERO_OR_ONE, Cardinality.EMPTY. This default |
| 708 | * implementation returns ZERO_OR_MORE (which effectively gives no |
| 709 | * information). |
| 710 | */ |
| 711 | |
| 712 | public int getCardinality() { |
| 713 | if (staticProperties == -1) { |
| 714 | computeStaticProperties(); |
| 715 | } |
| 716 | return staticProperties & StaticProperty.CARDINALITY_MASK; |
| 717 | } |
| 718 | |
| 719 | /** |
| 720 | * Determine the static item type of the expression, as precisely possible. All expression return |
| 721 | * sequences, in general; this method determines the type of the items within the |
| 722 | * sequence, assuming that (a) this is known in advance, and (b) it is the same for |
| 723 | * all items in the sequence. |
| 724 | * <p>This method should always return a result, though it may be the best approximation |
| 725 | * that is available at the time.</p> |
| 726 | * |
| 727 | * @return a value such as Type.STRING, Type.BOOLEAN, Type.NUMBER, |
| 728 | * Type.NODE, or Type.ITEM (meaning not known at compile time) |
| 729 | */ |
| 730 | |
| 731 | /*@NotNull*/ |
| 732 | public abstract ItemType getItemType(); |
| 733 | |
| 734 | /** |
| 735 | * Get the static type of the expression as a SequenceType: this is the combination of the |
| 736 | * item type and the cardinality. |
| 737 | * @return the static type of the expression |
| 738 | */ |
| 739 | |
| 740 | public SequenceType getStaticType() { |
| 741 | return SequenceType.makeSequenceType(getItemType(), getCardinality()); |
| 742 | } |
| 743 | |
| 744 | /** |
| 745 | * Get the static type of the expression as a UType, following precisely the type |
| 746 | * inference rules defined in the XSLT 3.0 specification. |
| 747 | * @return the static item type of the expression according to the XSLT 3.0 defined rules |
| 748 | * @param contextItemType the static type of the context item |
| 749 | */ |
| 750 | |
| 751 | public UType getStaticUType(UType contextItemType) { |
| 752 | return UType.ANY; |
| 753 | } |
| 754 | |
| 755 | /** |
| 756 | * Determine which aspects of the context the expression depends on. The result is |
| 757 | * a bitwise-or'ed value composed from constants such as XPathContext.VARIABLES and |
| 758 | * XPathContext.CURRENT_NODE. The default implementation combines the intrinsic |
| 759 | * dependencies of this expression with the dependencies of the subexpressions, |
| 760 | * computed recursively. This is overridden for expressions such as FilterExpression |
| 761 | * where a subexpression's dependencies are not necessarily inherited by the parent |
| 762 | * expression. |
| 763 | * |
| 764 | * @return a set of bit-significant flags identifying the dependencies of |
| 765 | * the expression |
| 766 | */ |
| 767 | |
| 768 | public int getDependencies() { |
| 769 | // Implemented as a memo function: we only compute the dependencies |
| 770 | // for each expression once |
| 771 | if (staticProperties == -1) { |
| 772 | computeStaticProperties(); |
| 773 | } |
| 774 | return staticProperties & StaticProperty.DEPENDENCY_MASK; |
| 775 | } |
| 776 | |
| 777 | /** |
| 778 | * For an expression that returns an integer or a sequence of integers, get |
| 779 | * a lower and upper bound on the values of the integers that may be returned, from |
| 780 | * static analysis. The default implementation returns null, meaning "unknown" or |
| 781 | * "not applicable". Other implementations return an array of two IntegerValue objects, |
| 782 | * representing the lower and upper bounds respectively. The values |
| 783 | * UNBOUNDED_LOWER and UNBOUNDED_UPPER are used by convention to indicate that |
| 784 | * the value may be arbitrarily large. The values MAX_STRING_LENGTH and MAX_SEQUENCE_LENGTH |
| 785 | * are used to indicate values limited by the size of a string or the size of a sequence. |
| 786 | * |
| 787 | * @return the lower and upper bounds of integer values in the result, or null to indicate |
| 788 | * unknown or not applicable. |
| 789 | */ |
| 790 | |
| 791 | /*@Nullable*/ |
| 792 | public IntegerValue[] getIntegerBounds() { |
| 793 | return null; |
| 794 | } |
| 795 | |
| 796 | public static final IntegerValue UNBOUNDED_LOWER = (IntegerValue) IntegerValue.makeIntegerValue(new DoubleValue(-1e100)); |
| 797 | public static final IntegerValue UNBOUNDED_UPPER = (IntegerValue) IntegerValue.makeIntegerValue(new DoubleValue(+1e100)); |
| 798 | public static final IntegerValue MAX_STRING_LENGTH = Int64Value.makeIntegerValue(Integer.MAX_VALUE); |
| 799 | public static final IntegerValue MAX_SEQUENCE_LENGTH = Int64Value.makeIntegerValue(Integer.MAX_VALUE); |
| 800 | |
| 801 | |
| 802 | /** |
| 803 | * Mark an expression as being "flattened". This is a collective term that includes extracting the |
| 804 | * string value or typed value, or operations such as simple value construction that concatenate text |
| 805 | * nodes before atomizing. The implication of all of these is that although the expression might |
| 806 | * return nodes, the identity of the nodes has no significance. This is called during type checking |
| 807 | * of the parent expression. |
| 808 | * |
| 809 | * @param flattened set to true if the result of the expression is atomized or otherwise turned into |
| 810 | * an atomic value |
| 811 | */ |
| 812 | |
| 813 | public void setFlattened(boolean flattened) { |
| 814 | // no action in general |
| 815 | } |
| 816 | |
| 817 | /** |
| 818 | * Mark an expression as filtered: that is, it appears as the base expression in a filter expression. |
| 819 | * This notification currently has no effect except when the expression is a variable reference. |
| 820 | * |
| 821 | * @param filtered if true, marks this expression as the base of a filter expression |
| 822 | */ |
| 823 | |
| 824 | public void setFiltered(boolean filtered) { |
| 825 | // default: do nothing |
| 826 | } |
| 827 | |
| 828 | /** |
| 829 | * Evaluate an expression as a single item. This always returns either a single Item or |
| 830 | * null (denoting the empty sequence). No conversion is done. This method should not be |
| 831 | * used unless the static type of the expression is a subtype of "item" or "item?": that is, |
| 832 | * it should not be called if the expression may return a sequence. There is no guarantee that |
| 833 | * this condition will be detected. |
| 834 | * |
| 835 | * @param context The context in which the expression is to be evaluated |
| 836 | * @return the node or atomic value that results from evaluating the |
| 837 | * expression; or null to indicate that the result is an empty |
| 838 | * sequence |
| 839 | * @throws net.sf.saxon.trans.XPathException |
| 840 | * if any dynamic error occurs evaluating the |
| 841 | * expression |
| 842 | */ |
| 843 | |
| 844 | /*@Nullable*/ |
| 845 | public Item<?> evaluateItem(XPathContext context) throws XPathException { |
| 846 | return iterate(context).next(); |
| 847 | } |
| 848 | |
| 849 | /** |
| 850 | * Return an Iterator to iterate over the values of a sequence. The value of every |
| 851 | * expression can be regarded as a sequence, so this method is supported for all |
| 852 | * expressions. This default implementation handles iteration for expressions that |
| 853 | * return singleton values: for non-singleton expressions, the subclass must |
| 854 | * provide its own implementation. |
| 855 | * |
| 856 | * @param context supplies the context for evaluation |
| 857 | * @return a SequenceIterator that can be used to iterate over the result |
| 858 | * of the expression |
| 859 | * @throws net.sf.saxon.trans.XPathException |
| 860 | * if any dynamic error occurs evaluating the |
| 861 | * expression |
| 862 | */ |
| 863 | |
| 864 | /*@NotNull*/ |
| 865 | public SequenceIterator<?> iterate(XPathContext context) throws XPathException { |
| 866 | Item<?> value = evaluateItem(context); |
| 867 | return value == null ? EmptyIterator.emptyIterator() : SingletonIterator.rawIterator(value); |
| 868 | } |
| 869 | |
| 870 | /** |
| 871 | * Get the effective boolean value of the expression. This returns false if the value |
| 872 | * is the empty sequence, a zero-length string, a number equal to zero, or the boolean |
| 873 | * false. Otherwise it returns true. |
| 874 | * |
| 875 | * @param context The context in which the expression is to be evaluated |
| 876 | * @return the effective boolean value |
| 877 | * @throws net.sf.saxon.trans.XPathException |
| 878 | * if any dynamic error occurs evaluating the |
| 879 | * expression |
| 880 | */ |
| 881 | |
| 882 | public boolean effectiveBooleanValue(XPathContext context) throws XPathException { |
| 883 | try { |
| 884 | return ExpressionTool.effectiveBooleanValue(iterate(context)); |
| 885 | } catch (XPathException e) { |
| 886 | e.maybeSetFailingExpression(this); |
| 887 | e.maybeSetContext(context); |
| 888 | throw e; |
| 889 | } |
| 890 | } |
| 891 | |
| 892 | /** |
| 893 | * Evaluate an expression as a String. This function must only be called in contexts |
| 894 | * where it is known that the expression will return a single string (or where an empty sequence |
| 895 | * is to be treated as a zero-length string). Implementations should not attempt to convert |
| 896 | * the result to a string, other than converting () to "". This method is used mainly to |
| 897 | * evaluate expressions produced by compiling an attribute value template. |
| 898 | * |
| 899 | * @param context The context in which the expression is to be evaluated |
| 900 | * @return the value of the expression, evaluated in the current context. |
| 901 | * The expression must return a string or (); if the value of the |
| 902 | * expression is (), this method returns "". |
| 903 | * @throws net.sf.saxon.trans.XPathException |
| 904 | * if any dynamic error occurs evaluating the |
| 905 | * expression |
| 906 | * @throws ClassCastException if the result type of the |
| 907 | * expression is not xs:string?, xs:untypedAtomic?, or xs:anyURI? |
| 908 | */ |
| 909 | |
| 910 | public CharSequence evaluateAsString(XPathContext context) throws XPathException { |
| 911 | Item o = evaluateItem(context); |
| 912 | StringValue value = (StringValue) o; // the ClassCastException is deliberate |
| 913 | if (value == null) { |
| 914 | return ""; |
| 915 | } |
| 916 | return value.getStringValueCS(); |
| 917 | } |
| 918 | |
| 919 | /** |
| 920 | * Process the instruction, without returning any tail calls |
| 921 | * |
| 922 | * @param context The dynamic context, giving access to the current node, |
| 923 | * the current variables, etc. |
| 924 | * @throws net.sf.saxon.trans.XPathException |
| 925 | * if a dynamic error occurs |
| 926 | */ |
| 927 | |
| 928 | public void process(XPathContext context) throws XPathException { |
| 929 | int m = getImplementationMethod(); |
| 930 | |
| 931 | if ((m & EVALUATE_METHOD) != 0) { |
| 932 | Item item = evaluateItem(context); |
| 933 | if (item != null) { |
| 934 | context.getReceiver().append(item, getLocation(), ReceiverOptions.ALL_NAMESPACES); |
| 935 | } |
| 936 | |
| 937 | } else if ((m & ITERATE_METHOD) != 0) { |
| 938 | |
| 939 | Receiver out = context.getReceiver(); |
| 940 | try { |
| 941 | iterate(context).forEachOrFail(it -> out.append(it, getLocation(), ReceiverOptions.ALL_NAMESPACES)); |
| 942 | } catch (XPathException e) { |
| 943 | e.maybeSetLocation(getLocation()); |
| 944 | e.maybeSetContext(context); |
| 945 | throw e; |
| 946 | } |
| 947 | |
| 948 | } else { |
| 949 | throw new AssertionError("process() is not implemented in the subclass " + getClass()); |
| 950 | } |
| 951 | } |
| 952 | |
| 953 | /** |
| 954 | * Evaluate an updating expression, adding the results to a Pending Update List. |
| 955 | * The default implementation of this method, which is used for non-updating expressions, |
| 956 | * throws an UnsupportedOperationException |
| 957 | * |
| 958 | * @param context the XPath dynamic evaluation context |
| 959 | * @param pul the pending update list to which the results should be written |
| 960 | * @throws net.sf.saxon.trans.XPathException |
| 961 | * if evaluation fails |
| 962 | * @throws UnsupportedOperationException if the expression is not an updating expression |
| 963 | */ |
| 964 | |
| 965 | public void evaluatePendingUpdates(XPathContext context, PendingUpdateList pul) throws XPathException { |
| 966 | if (isVacuousExpression()) { |
| 967 | iterate(context).next(); // typically, a call on fn:error |
| 968 | } else { |
| 969 | throw new UnsupportedOperationException("Expression " + getClass() + " is not an updating expression"); |
| 970 | } |
| 971 | } |
| 972 | |
| 973 | /** |
| 974 | * <p>The toString() method for an expression attempts to give a representation of the expression |
| 975 | * in an XPath-like form.</p> |
| 976 | * <p>For subclasses of Expression that represent XPath expressions, the result should always be a string that |
| 977 | * parses as an XPath 3.0 expression. The expression produced should be equivalent to the original making certain |
| 978 | * assumptions about the static context. In general the expansion will make no assumptions about namespace bindings, |
| 979 | * except that (a) the prefix "xs" is used to refer to the XML Schema namespace, and (b) the default function namespace |
| 980 | * is assumed to be the "fn" namespace.</p> |
| 981 | * <p>In the case of XSLT instructions and XQuery expressions, the toString() method gives an abstracted view of the syntax |
| 982 | * that is not designed in general to be parseable.</p> |
| 983 | * |
| 984 | * @return a representation of the expression as a string |
| 985 | */ |
| 986 | |
| 987 | public String toString() { |
| 988 | // fallback implementation |
| 989 | FastStringBuffer buff = new FastStringBuffer(FastStringBuffer.C64); |
| 990 | String className = getClass().getName(); |
| 991 | while (true) { |
| 992 | int dot = className.indexOf('.'); |
| 993 | if (dot >= 0) { |
| 994 | className = className.substring(dot + 1); |
| 995 | } else { |
| 996 | break; |
| 997 | } |
| 998 | } |
| 999 | buff.append(className); |
| 1000 | boolean first = true; |
| 1001 | for (Operand o : operands()) { |
| 1002 | buff.append(first ? "(" : ", "); |
| 1003 | buff.append(o.getChildExpression().toString()); |
| 1004 | first = false; |
| 1005 | } |
| 1006 | if (!first) { |
| 1007 | buff.append(")"); |
| 1008 | } |
| 1009 | return buff.toString(); |
| 1010 | } |
| 1011 | |
| 1012 | /** |
| 1013 | * Produce a short string identifying the expression for use in error messages |
| 1014 | * @return a short string, sufficient to identify the expression |
| 1015 | */ |
| 1016 | |
| 1017 | public String toShortString() { |
| 1018 | // fallback implementation |
| 1019 | return getExpressionName(); |
| 1020 | } |
| 1021 | |
| 1022 | /** |
| 1023 | * Diagnostic print of expression structure. The abstract expression tree |
| 1024 | * is written to the supplied output destination. |
| 1025 | * |
| 1026 | * @param out the expression presenter used to display the structure |
| 1027 | * @throws XPathException if the export fails, for example if an expression is found that won't work |
| 1028 | * in the target environment. |
| 1029 | */ |
| 1030 | |
| 1031 | public abstract void export(ExpressionPresenter out) throws XPathException; |
| 1032 | |
| 1033 | /** |
| 1034 | * Diagnostic print of expression structure. The abstract expression tree |
| 1035 | * is written to the supplied outputstream. |
| 1036 | * |
| 1037 | * @param out the expression presenter used to display the structure |
| 1038 | */ |
| 1039 | |
| 1040 | public final void explain(Logger out) { |
| 1041 | ExpressionPresenter ep = new ExpressionPresenter(getConfiguration(), out); |
| 1042 | ExpressionPresenter.ExportOptions options = new ExpressionPresenter.ExportOptions(); |
| 1043 | options.explaining = true; |
| 1044 | ep.setOptions(options); |
| 1045 | try { |
| 1046 | export(ep); |
| 1047 | } catch (XPathException e) { |
| 1048 | ep.startElement("failure"); |
| 1049 | ep.emitAttribute("message", e.getMessage()); |
| 1050 | ep.endElement(); |
| 1051 | } |
| 1052 | ep.close(); |
| 1053 | } |
| 1054 | |
| 1055 | /** |
| 1056 | * Check that any elements and attributes constructed or returned by this expression are acceptable |
| 1057 | * in the content model of a given complex type. It's always OK to say yes, since the check will be |
| 1058 | * repeated at run-time. The process of checking element and attribute constructors against the content |
| 1059 | * model of a complex type also registers the type of content expected of those constructors, so the |
| 1060 | * static validation can continue recursively. |
| 1061 | * |
| 1062 | * @param parentType the "given complex type": the method is checking that the nodes returned by this |
| 1063 | * expression are acceptable members of the content model of this type |
| 1064 | * @param whole if true, we want to check that the value of this expression satisfies the content model |
| 1065 | * as a whole; if false we want to check that the value of the expression is acceptable as one part |
| 1066 | * of the content |
| 1067 | * @throws XPathException if the value delivered by this expression cannot be part of the content model |
| 1068 | * of the given type |
| 1069 | */ |
| 1070 | |
| 1071 | public void checkPermittedContents(SchemaType parentType, boolean whole) throws XPathException { |
| 1072 | // |
| 1073 | } |
| 1074 | |
| 1075 | |
| 1076 | /** |
| 1077 | * Set up a parent-child relationship between this expression and a given child expression. |
| 1078 | * <p>Note: many calls on this method are now redundant, but are kept in place for "belt-and-braces" |
| 1079 | * reasons. The rule is that an implementation of simplify(), typeCheck(), or optimize() that returns |
| 1080 | * a value other than "this" is required to set the location information and parent pointer in the new |
| 1081 | * child expression. However, in the past this was often left to the caller, which did it by calling |
| 1082 | * this method, either unconditionally on return from one of these methods, or after testing that the |
| 1083 | * returned object was not the same as the original.</p> |
| 1084 | * |
| 1085 | * @param child the child expression |
| 1086 | */ |
| 1087 | |
| 1088 | public void adoptChildExpression(Expression child) { |
| 1089 | if (child == null) { |
| 1090 | return; |
| 1091 | } |
| 1092 | |
| 1093 | // if (child.getParentExpression() != null && child.getParentExpression() != this) { |
| 1094 | // for (Operand o : child.getParentExpression().operands()) { |
| 1095 | // if (o.getChildExpression() == child) { |
| 1096 | // o.detachChild(); |
| 1097 | // } |
| 1098 | // } |
| 1099 | // } |
| 1100 | child.setParentExpression(Expression.this); |
| 1101 | |
| 1102 | if (child.retainedStaticContext == null) { |
| 1103 | child.retainedStaticContext = retainedStaticContext; |
| 1104 | } |
| 1105 | |
| 1106 | if (getLocation() == null || getLocation() == ExplicitLocation.UNKNOWN_LOCATION) { |
| 1107 | ExpressionTool.copyLocationInfo(child, Expression.this); |
| 1108 | } else if (child.getLocation() == null || child.getLocation() == ExplicitLocation.UNKNOWN_LOCATION) { |
| 1109 | ExpressionTool.copyLocationInfo(Expression.this, child); |
| 1110 | } |
| 1111 | resetLocalStaticProperties(); |
| 1112 | } |
| 1113 | |
| 1114 | /** |
| 1115 | * Set the location on an expression. |
| 1116 | * |
| 1117 | * @param id the location |
| 1118 | */ |
| 1119 | |
| 1120 | public void setLocation(Location id) { |
| 1121 | location = id; |
| 1122 | } |
| 1123 | |
| 1124 | /** |
| 1125 | * Get the location of the expression |
| 1126 | * |
| 1127 | * @return a location identifier, which can be turned into real |
| 1128 | * location information by reference to a location provider |
| 1129 | */ |
| 1130 | |
| 1131 | public final Location getLocation() { |
| 1132 | int limit = 0; |
| 1133 | Expression exp = this; |
| 1134 | while (limit < 10) { |
| 1135 | if ((exp.location == null || exp.location == ExplicitLocation.UNKNOWN_LOCATION) |
| 1136 | && exp.getParentExpression() != null) { |
| 1137 | // avoid infinite recursion: bug 3703#1 |
| 1138 | exp = exp.getParentExpression(); |
| 1139 | limit++; |
| 1140 | } else { |
| 1141 | return exp.location; |
| 1142 | } |
| 1143 | } |
| 1144 | return exp.location; |
| 1145 | } |
| 1146 | |
| 1147 | /** |
| 1148 | * Get the configuration containing this expression |
| 1149 | * |
| 1150 | * @return the containing Configuration |
| 1151 | */ |
| 1152 | |
| 1153 | public Configuration getConfiguration() { |
| 1154 | try { |
| 1155 | return getRetainedStaticContext().getConfiguration(); |
| 1156 | } catch (NullPointerException e) { |
| 1157 | throw new NullPointerException("Internal error: expression " + toShortString() + " has no retained static context"); |
| 1158 | } |
| 1159 | } |
| 1160 | |
| 1161 | /** |
| 1162 | * Get information about the containing package |
| 1163 | * @return package data |
| 1164 | */ |
| 1165 | |
| 1166 | public PackageData getPackageData() { |
| 1167 | try { |
| 1168 | return getRetainedStaticContext().getPackageData(); |
| 1169 | } catch (NullPointerException e) { |
| 1170 | throw new NullPointerException("Internal error: expression " + toShortString() + " has no retained static context"); |
| 1171 | } |
| 1172 | } |
| 1173 | |
| 1174 | /** |
| 1175 | * Ask whether this expression is an instruction. In XSLT streamability analysis this |
| 1176 | * is used to distinguish constructs corresponding to XSLT instructions from other constructs, |
| 1177 | * typically XPath expressions (but also things like attribute constructors on a literal result element, |
| 1178 | * references to attribute sets, etc. However, an XPath expression within a text value template |
| 1179 | * in a text node of an XSLT stylesheet is treated as an instruction. |
| 1180 | * In a non-XSLT environment (such as XQuery) this property has no meaning and its setting is undefined. |
| 1181 | * @return true if this construct originates as an XSLT instruction |
| 1182 | */ |
| 1183 | |
| 1184 | public boolean isInstruction() { |
| 1185 | return false; |
| 1186 | } |
| 1187 | |
| 1188 | /** |
| 1189 | * Compute the static properties. This should only be done once for each |
| 1190 | * expression. |
| 1191 | */ |
| 1192 | |
| 1193 | public final void computeStaticProperties() { |
| 1194 | staticProperties = |
| 1195 | computeDependencies() | |
| 1196 | computeCardinality() | |
| 1197 | computeSpecialProperties(); |
| 1198 | } |
| 1199 | |
| 1200 | /** |
| 1201 | * Reset the static properties of the expression to -1, so that they have to be recomputed |
| 1202 | * next time they are used. |
| 1203 | */ |
| 1204 | |
| 1205 | public void resetLocalStaticProperties() { |
| 1206 | staticProperties = -1; |
| 1207 | cachedHashCode = -1; |
| 1208 | } |
| 1209 | |
| 1210 | /** |
| 1211 | * Ask whether the static properties of the expression have been computed |
| 1212 | * @return true if the static properties have been computed |
| 1213 | */ |
| 1214 | |
| 1215 | public boolean isStaticPropertiesKnown() { |
| 1216 | return staticProperties != -1; |
| 1217 | } |
| 1218 | |
| 1219 | /** |
| 1220 | * Compute the static cardinality of this expression |
| 1221 | * |
| 1222 | * @return the computed cardinality, as one of the values {@link StaticProperty#ALLOWS_ZERO_OR_ONE}, |
| 1223 | * {@link StaticProperty#EXACTLY_ONE}, {@link StaticProperty#ALLOWS_ONE_OR_MORE}, |
| 1224 | * {@link StaticProperty#ALLOWS_ZERO_OR_MORE}. May also return {@link StaticProperty#ALLOWS_ZERO} if |
| 1225 | * the result is known to be an empty sequence, or {@link StaticProperty#ALLOWS_MANY} if |
| 1226 | * if is known to return a sequence of length two or more. |
| 1227 | */ |
| 1228 | |
| 1229 | protected abstract int computeCardinality(); |
| 1230 | |
| 1231 | /** |
| 1232 | * Compute the special properties of this expression. These properties are denoted by a bit-significant |
| 1233 | * integer, possible values are in class {@link StaticProperty}. The "special" properties are properties |
| 1234 | * other than cardinality and dependencies, and most of them relate to properties of node sequences, for |
| 1235 | * example whether the nodes are in document order. |
| 1236 | * |
| 1237 | * @return the special properties, as a bit-significant integer |
| 1238 | */ |
| 1239 | |
| 1240 | protected int computeSpecialProperties() { |
| 1241 | return 0; |
| 1242 | } |
| 1243 | |
| 1244 | /** |
| 1245 | * Compute the dependencies of an expression, as the union of the |
| 1246 | * dependencies of its subexpressions. (This is overridden for path expressions |
| 1247 | * and filter expressions, where the dependencies of a subexpression are not all |
| 1248 | * propogated). This method should be called only once, to compute the dependencies; |
| 1249 | * after that, getDependencies should be used. |
| 1250 | * |
| 1251 | * @return the depencies, as a bit-mask |
| 1252 | */ |
| 1253 | |
| 1254 | public int computeDependencies() { |
| 1255 | int dependencies = getIntrinsicDependencies(); |
| 1256 | for (Operand o : operands()) { |
| 1257 | if (o.hasSameFocus()) { |
| 1258 | dependencies |= o.getChildExpression().getDependencies(); |
| 1259 | } else { |
| 1260 | dependencies |= o.getChildExpression().getDependencies() & ~StaticProperty.DEPENDS_ON_FOCUS; |
| 1261 | } |
| 1262 | } |
| 1263 | return dependencies; |
| 1264 | } |
| 1265 | |
| 1266 | /** |
| 1267 | * Determine the intrinsic dependencies of an expression, that is, those which are not derived |
| 1268 | * from the dependencies of its subexpressions. For example, position() has an intrinsic dependency |
| 1269 | * on the context position, while (position()+1) does not. The default implementation |
| 1270 | * of the method returns 0, indicating "no dependencies". |
| 1271 | * |
| 1272 | * @return a set of bit-significant flags identifying the "intrinsic" |
| 1273 | * dependencies. The flags are documented in class net.sf.saxon.value.StaticProperty |
| 1274 | */ |
| 1275 | |
| 1276 | public int getIntrinsicDependencies() { |
| 1277 | return 0; |
| 1278 | } |
| 1279 | |
| 1280 | /** |
| 1281 | * Set a static property on an expression. Used when inlining functions to retain properties |
| 1282 | * of the inlined function (though this is only partially successful because the properties |
| 1283 | * can be recomputed later |
| 1284 | * @param prop the property to be set |
| 1285 | */ |
| 1286 | |
| 1287 | public void setStaticProperty(int prop) { |
| 1288 | if (staticProperties == -1) { |
| 1289 | computeStaticProperties(); |
| 1290 | } |
| 1291 | staticProperties |= prop; |
| 1292 | } |
| 1293 | |
| 1294 | /** |
| 1295 | * Check to ensure that this expression does not contain any inappropriate updating subexpressions. |
| 1296 | * This check is overridden for those expressions that permit updating subexpressions. |
| 1297 | * |
| 1298 | * @throws XPathException if the expression has a non-permitted updating subexpression |
| 1299 | */ |
| 1300 | |
| 1301 | public void checkForUpdatingSubexpressions() throws XPathException { |
| 1302 | for (Operand o : operands()) { |
| 1303 | Expression sub = o.getChildExpression(); |
| 1304 | if (sub == null) { |
| 1305 | throw new NullPointerException(); |
| 1306 | } |
| 1307 | sub.checkForUpdatingSubexpressions(); |
| 1308 | if (sub.isUpdatingExpression()) { |
| 1309 | XPathException err = new XPathException( |
| 1310 | "Updating expression appears in a context where it is not permitted", "XUST0001"); |
| 1311 | err.setLocation(sub.getLocation()); |
| 1312 | throw err; |
| 1313 | } |
| 1314 | } |
| 1315 | } |
| 1316 | |
| 1317 | /** |
| 1318 | * Determine whether this is an updating expression as defined in the XQuery update specification |
| 1319 | * |
| 1320 | * @return true if this is an updating expression |
| 1321 | */ |
| 1322 | |
| 1323 | public boolean isUpdatingExpression() { |
| 1324 | for (Operand o : operands()) { |
| 1325 | if (o.getChildExpression().isUpdatingExpression()) { |
| 1326 | return true; |
| 1327 | } |
| 1328 | } |
| 1329 | return false; |
| 1330 | } |
| 1331 | |
| 1332 | /** |
| 1333 | * Determine whether this is a vacuous expression as defined in the XQuery update specification |
| 1334 | * |
| 1335 | * @return true if this expression is vacuous |
| 1336 | */ |
| 1337 | |
| 1338 | public boolean isVacuousExpression() { |
| 1339 | return false; |
| 1340 | } |
| 1341 | |
| 1342 | /** |
| 1343 | * Copy an expression. This makes a deep copy. |
| 1344 | * |
| 1345 | * @return the copy of the original expression |
| 1346 | * @param rebindings a mutable list of (old binding, new binding) pairs |
| 1347 | * that is used to update the bindings held in any |
| 1348 | * local variable references that are copied. |
| 1349 | */ |
| 1350 | |
| 1351 | /*@NotNull*/ |
| 1352 | public abstract Expression copy(RebindingMap rebindings); |
| 1353 | |
| 1354 | /** |
| 1355 | * Suppress validation on contained element constructors, on the grounds that the parent element |
| 1356 | * is already performing validation. The default implementation does nothing. |
| 1357 | * |
| 1358 | * @param parentValidationMode the kind of validation being performed on the parent expression |
| 1359 | */ |
| 1360 | |
| 1361 | public void suppressValidation(int parentValidationMode) { |
| 1362 | // do nothing |
| 1363 | } |
| 1364 | |
| 1365 | /** |
| 1366 | * Mark tail-recursive calls on stylesheet functions. For most expressions, this does nothing. |
| 1367 | * |
| 1368 | * @param qName the name of the function |
| 1369 | * @param arity the arity (number of parameters) of the function |
| 1370 | * @return {@link UserFunctionCall#NOT_TAIL_CALL} if no tail call was found; |
| 1371 | * {@link UserFunctionCall#FOREIGN_TAIL_CALL} if a tail call on a different function was found; |
| 1372 | * {@link UserFunctionCall#SELF_TAIL_CALL} if a tail recursive call was found and if this call accounts for the whole of the value. |
| 1373 | */ |
| 1374 | |
| 1375 | public int markTailFunctionCalls(StructuredQName qName, int arity) { |
| 1376 | return UserFunctionCall.NOT_TAIL_CALL; |
| 1377 | } |
| 1378 | |
| 1379 | /** |
| 1380 | * Convert this expression to an equivalent XSLT pattern |
| 1381 | * |
| 1382 | * @param config the Saxon configuration |
| 1383 | * @return the equivalent pattern |
| 1384 | * @throws XPathException if conversion is not possible |
| 1385 | */ |
| 1386 | |
| 1387 | public Pattern toPattern(Configuration config) throws XPathException { |
| 1388 | ItemType type = getItemType(); |
| 1389 | if (((getDependencies() & StaticProperty.DEPENDS_ON_NON_DOCUMENT_FOCUS) == 0) && |
| 1390 | (type instanceof NodeTest || this instanceof VariableReference)) { |
| 1391 | return new NodeSetPattern(Expression.this); |
| 1392 | } |
| 1393 | if (isCallOn(KeyFn.class) || isCallOn(SuperId.class)) { |
| 1394 | return new NodeSetPattern(Expression.this); |
| 1395 | } |
| 1396 | throw new XPathException("Cannot convert the expression {" + this + "} to a pattern"); |
| 1397 | } |
| 1398 | |
| 1399 | /** |
| 1400 | * Get the local variables (identified by their slot numbers) on which this expression depends. |
| 1401 | * Should only be called if the caller has established that there is a dependency on local variables. |
| 1402 | * |
| 1403 | * @return an array of integers giving the slot numbers of the local variables referenced in this |
| 1404 | * expression. |
| 1405 | */ |
| 1406 | |
| 1407 | public final synchronized int[] getSlotsUsed() { |
| 1408 | // synchronized because it's calculated lazily at run-time the first time it's needed |
| 1409 | if (slotsUsed != null) { |
| 1410 | return slotsUsed; |
| 1411 | } |
| 1412 | IntHashSet slots = new IntHashSet(10); |
| 1413 | gatherSlotsUsed(Expression.this, slots); |
| 1414 | slotsUsed = new int[slots.size()]; |
| 1415 | int i = 0; |
| 1416 | IntIterator iter = slots.iterator(); |
| 1417 | while (iter.hasNext()) { |
| 1418 | slotsUsed[i++] = iter.next(); |
| 1419 | } |
| 1420 | Arrays.sort(slotsUsed); |
| 1421 | return slotsUsed; |
| 1422 | } |
| 1423 | |
| 1424 | private static void gatherSlotsUsed(Expression exp, IntHashSet slots) { |
| 1425 | exp = exp.getInterpretedExpression(); |
| 1426 | if (exp instanceof LocalVariableReference) { |
| 1427 | slots.add(((LocalVariableReference)exp).getSlotNumber()); |
| 1428 | } else if (exp instanceof SuppliedParameterReference) { |
| 1429 | int slot = ((SuppliedParameterReference) exp).getSlotNumber(); |
| 1430 | slots.add(slot); |
| 1431 | } else { |
| 1432 | for (Operand o : exp.operands()) { |
| 1433 | gatherSlotsUsed(o.getChildExpression(), slots); |
| 1434 | } |
| 1435 | } |
| 1436 | } |
| 1437 | |
| 1438 | /** |
| 1439 | * Method used in subclasses to signal a dynamic error |
| 1440 | * |
| 1441 | * @param message the error message |
| 1442 | * @param code the error code |
| 1443 | * @param context the XPath dynamic context |
| 1444 | * @throws XPathException always thrown, to signal a dynamic error |
| 1445 | */ |
| 1446 | |
| 1447 | protected void dynamicError(String message, String code, XPathContext context) throws XPathException { |
| 1448 | XPathException err = new XPathException(message, code, getLocation()); |
| 1449 | err.setXPathContext(context); |
| 1450 | err.setFailingExpression(this); |
| 1451 | throw err; |
| 1452 | } |
| 1453 | |
| 1454 | /** |
| 1455 | * Method used in subclasses to signal a runtime type error |
| 1456 | * |
| 1457 | * @param message the error message |
| 1458 | * @param errorCode the error code |
| 1459 | * @param context the XPath dynamic context |
| 1460 | * @throws XPathException always thrown, to signal a dynamic error |
| 1461 | */ |
| 1462 | |
| 1463 | protected void typeError(String message, String errorCode, XPathContext context) throws XPathException { |
| 1464 | XPathException e = new XPathException(message, errorCode, getLocation()); |
| 1465 | e.setIsTypeError(true); |
| 1466 | e.setXPathContext(context); |
| 1467 | e.setFailingExpression(this); |
| 1468 | throw e; |
| 1469 | } |
| 1470 | |
| 1471 | /** |
| 1472 | * Get the type of this expression for use in tracing and diagnostics |
| 1473 | * |
| 1474 | * @return the type of expression, as enumerated in class {@link LocationKind} |
| 1475 | */ |
| 1476 | |
| 1477 | public int getConstructType() { |
| 1478 | return LocationKind.XPATH_EXPRESSION; |
| 1479 | } |
| 1480 | |
| 1481 | /*@Nullable*/ |
| 1482 | public StructuredQName getObjectName() { |
| 1483 | return null; |
| 1484 | } |
| 1485 | |
| 1486 | /*@Nullable*/ |
| 1487 | public Object getProperty(String name) { |
| 1488 | if (name.equals("expression")) { |
| 1489 | return Expression.this.getLocation(); |
| 1490 | } else { |
| 1491 | return null; |
| 1492 | } |
| 1493 | } |
| 1494 | |
| 1495 | /** |
| 1496 | * Get an iterator over all the properties available. The values returned by the iterator |
| 1497 | * will be of type String, and each string can be supplied as input to the getProperty() |
| 1498 | * method to retrieve the value of the property. The iterator may return properties whose |
| 1499 | * value is null. |
| 1500 | * |
| 1501 | * @return an iterator over the properties |
| 1502 | */ |
| 1503 | |
| 1504 | public Iterator<String> getProperties() { |
| 1505 | return new MonoIterator<>("expression"); |
| 1506 | } |
| 1507 | |
| 1508 | /** |
| 1509 | * Add a representation of this expression to a PathMap. The PathMap captures a map of the nodes visited |
| 1510 | * by an expression in a source tree. |
| 1511 | * <p>The default implementation of this method assumes that an expression does no navigation other than |
| 1512 | * the navigation done by evaluating its subexpressions, and that the subexpressions are evaluated in the |
| 1513 | * same context as the containing expression. The method must be overridden for any expression |
| 1514 | * where these assumptions do not hold. For example, implementations exist for AxisExpression, ParentExpression, |
| 1515 | * and RootExpression (because they perform navigation), and for the doc(), document(), and collection() |
| 1516 | * functions because they create a new navigation root. Implementations also exist for PathExpression and |
| 1517 | * FilterExpression because they have subexpressions that are evaluated in a different context from the |
| 1518 | * calling expression.</p> |
| 1519 | * |
| 1520 | * @param pathMap the PathMap to which the expression should be added |
| 1521 | * @param pathMapNodeSet the PathMapNodeSet to which the paths embodied in this expression should be added |
| 1522 | * @return the pathMapNodeSet representing the points in the source document that are both reachable by this |
| 1523 | * expression, and that represent possible results of this expression. For an expression that does |
| 1524 | * navigation, it represents the end of the arc in the path map that describes the navigation route. For other |
| 1525 | * expressions, it is the same as the input pathMapNode. |
| 1526 | */ |
| 1527 | |
| 1528 | /*@Nullable*/ |
| 1529 | public PathMap.PathMapNodeSet addToPathMap(PathMap pathMap, /*@Nullable*/ PathMap.PathMapNodeSet pathMapNodeSet) { |
| 1530 | boolean dependsOnFocus = ExpressionTool.dependsOnFocus(Expression.this); |
| 1531 | PathMap.PathMapNodeSet attachmentPoint; |
| 1532 | if (pathMapNodeSet == null) { |
| 1533 | if (dependsOnFocus) { |
| 1534 | ContextItemExpression cie = new ContextItemExpression(); |
| 1535 | ExpressionTool.copyLocationInfo(Expression.this, cie); |
| 1536 | pathMapNodeSet = new PathMap.PathMapNodeSet(pathMap.makeNewRoot(cie)); |
| 1537 | } |
| 1538 | attachmentPoint = pathMapNodeSet; |
| 1539 | } else { |
| 1540 | attachmentPoint = dependsOnFocus ? pathMapNodeSet : null; |
| 1541 | } |
| 1542 | PathMap.PathMapNodeSet result = new PathMap.PathMapNodeSet(); |
| 1543 | for (Operand o : operands()) { |
| 1544 | OperandUsage usage = o.getUsage(); |
| 1545 | Expression child = o.getChildExpression(); |
| 1546 | PathMap.PathMapNodeSet target = child.addToPathMap(pathMap, attachmentPoint); |
| 1547 | if (usage == OperandUsage.NAVIGATION) { |
| 1548 | // indicate that the function navigates to all elements in the document |
| 1549 | target = target.createArc(AxisInfo.ANCESTOR_OR_SELF, NodeKindTest.ELEMENT); |
| 1550 | target = target.createArc(AxisInfo.DESCENDANT, NodeKindTest.ELEMENT); |
| 1551 | } |
| 1552 | result.addNodeSet(target); |
| 1553 | } |
| 1554 | if (getItemType() instanceof AtomicType) { |
| 1555 | // if expression returns an atomic value then any nodes accessed don't contribute to the result |
| 1556 | return null; |
| 1557 | } else { |
| 1558 | return result; |
| 1559 | } |
| 1560 | } |
| 1561 | |
| 1562 | /** |
| 1563 | * Determine whether the expression can be evaluated without reference to the part of the context |
| 1564 | * document outside the subtree rooted at the context node. |
| 1565 | * |
| 1566 | * @return true if the expression has no dependencies on the context node, or if the only dependencies |
| 1567 | * on the context node are downward selections using the self, child, descendant, attribute, and namespace |
| 1568 | * axes. |
| 1569 | */ |
| 1570 | |
| 1571 | public boolean isSubtreeExpression() { |
| 1572 | if (ExpressionTool.dependsOnFocus(Expression.this)) { |
| 1573 | if ((getIntrinsicDependencies() & StaticProperty.DEPENDS_ON_FOCUS) != 0) { |
| 1574 | return false; |
| 1575 | } else { |
| 1576 | for (Operand o : operands()) { |
| 1577 | if (!o.getChildExpression().isSubtreeExpression()) { |
| 1578 | return false; |
| 1579 | } |
| 1580 | } |
| 1581 | return true; |
| 1582 | } |
| 1583 | } else { |
| 1584 | return true; |
| 1585 | } |
| 1586 | } |
| 1587 | |
| 1588 | public void setEvaluationMethod(int method) { |
| 1589 | Expression.this.evaluationMethod = method; |
| 1590 | } |
| 1591 | |
| 1592 | public int getEvaluationMethod() { |
| 1593 | return evaluationMethod; |
| 1594 | } |
| 1595 | |
| 1596 | /** |
| 1597 | * The equals() test for expressions returns true if it can be determined that two expressions (given |
| 1598 | * their static context) will return the same result in all circumstances. The value false is returned |
| 1599 | * if this is not the case or if it cannot be determined to be the case. |
| 1600 | * <p>During the various phases of compilation, expression objects are mutable. Changing an expression |
| 1601 | * may change its hashCode, and may change the result of equals() comparisons. Expressions should therefore |
| 1602 | * not be held in data structures such as maps and sets that depend on equality comparison unless they |
| 1603 | * are no longer subject to such mutation.</p> |
| 1604 | * |
| 1605 | * @param obj the other operand; the result is false if this is not an Expression |
| 1606 | * @return true if the other operand is an expression and if it can be determined that the two |
| 1607 | * expressions are equivalent, in the sense that they will always return the same result. |
| 1608 | */ |
| 1609 | |
| 1610 | @Override |
| 1611 | public boolean equals(Object obj) { |
| 1612 | return super.equals(obj); |
| 1613 | } |
| 1614 | |
| 1615 | /** |
| 1616 | * Test if this is expression is equivalent to another. This method first compares the hash codes, |
| 1617 | * allowing a quick exit if the expressions are not equal (except that computing the hash code may |
| 1618 | * itself be expensive...). |
| 1619 | * @param other the other expression |
| 1620 | * @return true if the two expressions are equal in the sense of the equals() method |
| 1621 | */ |
| 1622 | |
| 1623 | public final boolean isEqual(Expression other) { |
| 1624 | return this == other || (hashCode() == other.hashCode() && equals(other)); |
| 1625 | } |
| 1626 | |
| 1627 | /** |
| 1628 | * The hashCode() for an expression has semantics corresponding to equals(). Because computing |
| 1629 | * a hashCode may be expensive, it is computed lazily on first reference and saved with the |
| 1630 | * expression. |
| 1631 | * |
| 1632 | * @return a hashCode which is the same for two expressions that are equal(). |
| 1633 | */ |
| 1634 | |
| 1635 | public final int hashCode() { |
| 1636 | if (cachedHashCode == -1) { |
| 1637 | cachedHashCode = computeHashCode(); |
| 1638 | } |
| 1639 | return cachedHashCode; |
| 1640 | } |
| 1641 | |
| 1642 | /** |
| 1643 | * Ask whether the static context of this expression is compatible with the static context |
| 1644 | * of another expression. The static contexts are considered compatible if either (a) |
| 1645 | * neither expression depends on the static context, or (b) both expressions depend on the static |
| 1646 | * context and the two static contexts compare equal. |
| 1647 | * @param other the other expression |
| 1648 | * @return true if the two expressions have equivalent static contexts |
| 1649 | */ |
| 1650 | |
| 1651 | protected boolean hasCompatibleStaticContext(Expression other) { |
| 1652 | boolean d1 = (getIntrinsicDependencies() & StaticProperty.DEPENDS_ON_STATIC_CONTEXT) != 0; |
| 1653 | boolean d2 = (other.getIntrinsicDependencies() & StaticProperty.DEPENDS_ON_STATIC_CONTEXT) != 0; |
| 1654 | if (d1 != d2) { |
| 1655 | return false; |
| 1656 | } |
| 1657 | if (d1) { |
| 1658 | return getRetainedStaticContext().equals(other.getRetainedStaticContext()); |
| 1659 | } |
| 1660 | return true; |
| 1661 | } |
| 1662 | |
| 1663 | |
| 1664 | /** |
| 1665 | * Compute a hash code, which will then be cached for later use |
| 1666 | * @return a computed hash code |
| 1667 | */ |
| 1668 | |
| 1669 | protected int computeHashCode() { |
| 1670 | return super.hashCode(); |
| 1671 | } |
| 1672 | |
| 1673 | /** |
| 1674 | * Determine whether two IdentityComparable objects are identical. This is a stronger |
| 1675 | * test than equality (even schema-equality); for example two dateTime values are not identical unless |
| 1676 | * they are in the same timezone. In the case of expressions, we test object identity, since the normal |
| 1677 | * equality test ignores the location of the expression. |
| 1678 | * |
| 1679 | * @param other the value to be compared with |
| 1680 | * @return true if the two values are indentical, false otherwise |
| 1681 | */ |
| 1682 | public boolean isIdentical(IdentityComparable other) { |
| 1683 | return this == other; |
| 1684 | } |
| 1685 | |
| 1686 | /** |
| 1687 | * Get a hashCode that offers the guarantee that if A.isIdentical(B), then A.identityHashCode() == B.identityHashCode() |
| 1688 | * |
| 1689 | * @return a hashCode suitable for use when testing for identity. |
| 1690 | */ |
| 1691 | public int identityHashCode() { |
| 1692 | return System.identityHashCode(Expression.this.getLocation()); |
| 1693 | } |
| 1694 | |
| 1695 | /** |
| 1696 | * Set an extra property on the expression. (Used for Saxon-EE properties, e.g. properties |
| 1697 | * relating to streaming). |
| 1698 | * @param name the name of the property |
| 1699 | * @param value the value of the property, or null to remove the property |
| 1700 | */ |
| 1701 | |
| 1702 | public void setExtraProperty(String name, Object value) { |
| 1703 | if (extraProperties == null) { |
| 1704 | if (value == null) { |
| 1705 | return; |
| 1706 | } |
| 1707 | extraProperties = new HashMap<>(4); |
| 1708 | } |
| 1709 | if (value == null) { |
| 1710 | extraProperties.remove(name); |
| 1711 | } else { |
| 1712 | extraProperties.put(name, value); |
| 1713 | } |
| 1714 | } |
| 1715 | |
| 1716 | /** |
| 1717 | * Get the value of an extra property on the expression |
| 1718 | * @param name the name of the property |
| 1719 | * @return the value of the property if set, or null otherwise |
| 1720 | */ |
| 1721 | |
| 1722 | public Object getExtraProperty(String name) { |
| 1723 | if (extraProperties == null) { |
| 1724 | return null; |
| 1725 | } else { |
| 1726 | return extraProperties.get(name); |
| 1727 | } |
| 1728 | } |
| 1729 | |
| 1730 | /** |
| 1731 | * Get the (partial) name of a class that supports streaming of this kind of expression |
| 1732 | * @return the partial name of a class that can be instantiated to provide streaming support in Saxon-EE, |
| 1733 | * or null if there is no such class |
| 1734 | */ |
| 1735 | |
| 1736 | public String getStreamerName() { |
| 1737 | return null; |
| 1738 | } |
| 1739 | |
| 1740 | |
| 1741 | } |
| 1742 |