| 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.functions; |
| 9 | |
| 10 | import net.sf.saxon.expr.*; |
| 11 | import net.sf.saxon.expr.parser.ContextItemStaticInfo; |
| 12 | import net.sf.saxon.expr.parser.ExpressionVisitor; |
| 13 | import net.sf.saxon.expr.parser.RetainedStaticContext; |
| 14 | import net.sf.saxon.functions.registry.BuiltInFunctionSet; |
| 15 | import net.sf.saxon.lib.NamespaceConstant; |
| 16 | import net.sf.saxon.om.*; |
| 17 | import net.sf.saxon.trace.ExpressionPresenter; |
| 18 | import net.sf.saxon.trans.XPathException; |
| 19 | import net.sf.saxon.type.FunctionItemType; |
| 20 | import net.sf.saxon.type.ItemType; |
| 21 | import net.sf.saxon.type.SpecificFunctionType; |
| 22 | import net.sf.saxon.value.Cardinality; |
| 23 | import net.sf.saxon.value.IntegerValue; |
| 24 | import net.sf.saxon.value.SequenceType; |
| 25 | |
| 26 | import java.util.Properties; |
| 27 | |
| 28 | |
| 29 | /** |
| 30 | * Abstract superclass for calls to functions in the standard function library |
| 31 | */ |
| 32 | |
| 33 | public abstract class SystemFunction extends AbstractFunction { |
| 34 | |
| 35 | private int arity; |
| 36 | private BuiltInFunctionSet.Entry details; |
| 37 | private RetainedStaticContext retainedStaticContext; |
| 38 | |
| 39 | /** |
| 40 | * Make a system function call (one in the standard function namespace). |
| 41 | * |
| 42 | * @param name The local name of the function. |
| 43 | * @param rsc Necessary information about the static context |
| 44 | * @param arguments the arguments to the function call |
| 45 | * @return a FunctionCall that implements this function, if it |
| 46 | * exists, or null if the function is unknown. |
| 47 | */ |
| 48 | |
| 49 | /*@Nullable*/ |
| 50 | public static Expression makeCall(String name, RetainedStaticContext rsc, Expression... arguments) { |
| 51 | SystemFunction f = makeFunction(name, rsc, arguments.length); |
| 52 | if (f == null) { |
| 53 | return null; |
| 54 | } |
| 55 | Expression expr = f.makeFunctionCall(arguments); |
| 56 | expr.setRetainedStaticContext(rsc); |
| 57 | return expr; |
| 58 | } |
| 59 | |
| 60 | /** |
| 61 | * Make a system function item (one in the standard function namespace). |
| 62 | * |
| 63 | * @param name The local name of the function. |
| 64 | * @param rsc Necessary information about the static context |
| 65 | * @param arity the arity of the function |
| 66 | * @return the function item |
| 67 | */ |
| 68 | |
| 69 | public static SystemFunction makeFunction(String name, RetainedStaticContext rsc, int arity) { |
| 70 | if (rsc == null) { |
| 71 | throw new NullPointerException(); |
| 72 | } |
| 73 | SystemFunction fn = rsc.getConfiguration().makeSystemFunction(name, arity); |
| 74 | if (fn == null) { |
| 75 | rsc.getConfiguration().makeSystemFunction(name, arity); |
| 76 | throw new IllegalStateException(name); |
| 77 | } |
| 78 | fn.setRetainedStaticContext(rsc); |
| 79 | return fn; |
| 80 | } |
| 81 | |
| 82 | /** |
| 83 | * Make an expression that either calls this function, or that is equivalent to a call |
| 84 | * on this function |
| 85 | * @param arguments the supplied arguments to the function call |
| 86 | * @return either a function call on this function, or an expression that delivers |
| 87 | * the same result |
| 88 | */ |
| 89 | |
| 90 | public Expression makeFunctionCall(Expression... arguments) { |
| 91 | Expression e = new SystemFunctionCall(this, arguments); |
| 92 | e.setRetainedStaticContext(getRetainedStaticContext()); |
| 93 | return e; |
| 94 | } |
| 95 | |
| 96 | /** |
| 97 | * Set the arity of the function |
| 98 | * @param arity the number of arguments |
| 99 | */ |
| 100 | |
| 101 | public void setArity(int arity) { |
| 102 | this.arity = arity; |
| 103 | } |
| 104 | |
| 105 | /** |
| 106 | * Get an estimate of the net cost of evaluating the function, excluding the cost of evaluating |
| 107 | * its arguments. The result is 0 for very simple functions like position() and exists(), 1 by |
| 108 | * default, and higher values for particularly expensive functions. |
| 109 | * @return the estimated cost |
| 110 | */ |
| 111 | |
| 112 | public int getNetCost() { |
| 113 | return 1; |
| 114 | } |
| 115 | |
| 116 | /** |
| 117 | * Allow the function to create an optimized call based on the values of the actual arguments |
| 118 | * @param visitor the expression visitor |
| 119 | * @param contextInfo information about the context item |
| 120 | * @param arguments the supplied arguments to the function call. Note: modifying the contents |
| 121 | * of this array should not be attempted, it is likely to have no effect. |
| 122 | * @return either a function call on this function, or an expression that delivers |
| 123 | * the same result, or null indicating that no optimization has taken place |
| 124 | * @throws XPathException if an error is detected |
| 125 | */ |
| 126 | |
| 127 | public Expression makeOptimizedFunctionCall ( |
| 128 | ExpressionVisitor visitor, ContextItemStaticInfo contextInfo, Expression... arguments) |
| 129 | throws XPathException { |
| 130 | return fixArguments(arguments); |
| 131 | } |
| 132 | |
| 133 | /** |
| 134 | * Optimize for constant argument values |
| 135 | */ |
| 136 | |
| 137 | public Expression fixArguments(Expression... arguments) throws XPathException { |
| 138 | // Check if any arguments are known to be empty, with a declared result for that case |
| 139 | for (int i = 0; i < getArity(); i++) { |
| 140 | if (Literal.isEmptySequence(arguments[i]) && resultIfEmpty(i) != null) { |
| 141 | return Literal.makeLiteral(details.resultIfEmpty[i].materialize()); |
| 142 | } |
| 143 | } |
| 144 | return null; |
| 145 | } |
| 146 | |
| 147 | /** |
| 148 | * Ask if the function always returns a known result when one of the arguments is an empty sequence |
| 149 | * @param arg the argument whose value is an empty sequence (counting from zero) |
| 150 | * @return the value to be returned when this argument is an empty sequence, or null if unknown / not applicable |
| 151 | */ |
| 152 | |
| 153 | protected Sequence<?> resultIfEmpty(int arg) { |
| 154 | return details.resultIfEmpty[arg]; |
| 155 | } |
| 156 | |
| 157 | /** |
| 158 | * Get the static context in which the function operates, for use with functions whose result |
| 159 | * depends on the static context |
| 160 | * @return the retained static context |
| 161 | */ |
| 162 | |
| 163 | public RetainedStaticContext getRetainedStaticContext() { |
| 164 | return retainedStaticContext; |
| 165 | } |
| 166 | |
| 167 | /** |
| 168 | * Set the static context in which the function operates, for use with functions whose result |
| 169 | * depends on the static context |
| 170 | * |
| 171 | * @param retainedStaticContext the retained static context |
| 172 | */ |
| 173 | |
| 174 | public void setRetainedStaticContext(RetainedStaticContext retainedStaticContext) { |
| 175 | this.retainedStaticContext = retainedStaticContext; |
| 176 | } |
| 177 | |
| 178 | /** |
| 179 | * Ask whether the result of the function depends on the context item |
| 180 | * @return true if the function depends on the context item |
| 181 | */ |
| 182 | |
| 183 | public boolean dependsOnContextItem() { |
| 184 | return (details.properties & (BuiltInFunctionSet.CITEM | BuiltInFunctionSet.CDOC)) != 0; |
| 185 | } |
| 186 | |
| 187 | /** |
| 188 | * Set the details of this type of function |
| 189 | * |
| 190 | * @param entry information giving details of the function signature and other function properties |
| 191 | */ |
| 192 | |
| 193 | public void setDetails(BuiltInFunctionSet.Entry entry) { |
| 194 | details = entry; |
| 195 | } |
| 196 | |
| 197 | /** |
| 198 | * Get the details of the function signature |
| 199 | * |
| 200 | * @return information about the function signature and other function properties |
| 201 | */ |
| 202 | |
| 203 | public BuiltInFunctionSet.Entry getDetails() { |
| 204 | return details; |
| 205 | } |
| 206 | |
| 207 | /** |
| 208 | * Get the qualified name of the function being called |
| 209 | * |
| 210 | * @return the qualified name |
| 211 | */ |
| 212 | |
| 213 | public StructuredQName getFunctionName() { |
| 214 | return details.name; |
| 215 | } |
| 216 | |
| 217 | /** |
| 218 | * Get a description of this function for use in error messages. For named functions, the description |
| 219 | * is the function name (as a lexical QName). For others, it might be, for example, "inline function", |
| 220 | * or "partially-applied ends-with function". |
| 221 | * |
| 222 | * @return a description of the function for use in error messages |
| 223 | */ |
| 224 | public String getDescription() { |
| 225 | return details.name.getDisplayName(); |
| 226 | } |
| 227 | |
| 228 | /** |
| 229 | * Get the arity of the function (the number of arguments). Note that a subclass of SystemFunction may |
| 230 | * support a family of functions with different arity, but an instance of the SystemFunction class always has |
| 231 | * a single arity. |
| 232 | * @return the arity of the function |
| 233 | */ |
| 234 | |
| 235 | public int getArity() { |
| 236 | return arity; |
| 237 | } |
| 238 | |
| 239 | /** |
| 240 | * Get the roles of the arguments, for the purposes of streaming |
| 241 | * |
| 242 | * @return an array of OperandRole objects, one for each argument |
| 243 | */ |
| 244 | public OperandRole[] getOperandRoles() { |
| 245 | OperandRole[] roles = new OperandRole[getArity()]; |
| 246 | OperandUsage[] usages = details.usage; |
| 247 | try { |
| 248 | for (int i = 0; i < getArity(); i++) { |
| 249 | roles[i] = new OperandRole(0, usages[i], getRequiredType(i)); |
| 250 | } |
| 251 | } catch (ArrayIndexOutOfBoundsException e) { |
| 252 | e.printStackTrace(); |
| 253 | } |
| 254 | return roles; |
| 255 | } |
| 256 | |
| 257 | /** |
| 258 | * For a function that returns an integer or a sequence of integers, get |
| 259 | * a lower and upper bound on the values of the integers that may be returned, from |
| 260 | * static analysis. The default implementation returns null, meaning "unknown" or |
| 261 | * "not applicable". Other implementations return an array of two IntegerValue objects, |
| 262 | * representing the lower and upper bounds respectively. The values |
| 263 | * UNBOUNDED_LOWER and UNBOUNDED_UPPER are used by convention to indicate that |
| 264 | * the value may be arbitrarily large. The values MAX_STRING_LENGTH and MAX_SEQUENCE_LENGTH |
| 265 | * are used to indicate values limited by the size of a string or the size of a sequence. |
| 266 | * |
| 267 | * @return the lower and upper bounds of integer values in the result, or null to indicate |
| 268 | * unknown or not applicable. |
| 269 | */ |
| 270 | |
| 271 | /*@Nullable*/ |
| 272 | public IntegerValue[] getIntegerBounds() { |
| 273 | return null; |
| 274 | } |
| 275 | |
| 276 | /** |
| 277 | * Method called during static type checking. This method may be implemented in subclasses so that functions |
| 278 | * can take advantage of knowledge of the types of the arguments that will be supplied. |
| 279 | * @param visitor an expression visitor, providing access to the static context and configuration |
| 280 | * @param contextItemType information about whether the context item is set, and what its type is |
| 281 | * @param arguments the expressions appearing as arguments in the function call |
| 282 | */ |
| 283 | |
| 284 | public void supplyTypeInformation ( |
| 285 | ExpressionVisitor visitor, ContextItemStaticInfo contextItemType, Expression[] arguments) throws XPathException { |
| 286 | //default: no action |
| 287 | } |
| 288 | |
| 289 | /** |
| 290 | * Determine whether two functions are equivalent |
| 291 | */ |
| 292 | @Override |
| 293 | public boolean equals(Object o) { |
| 294 | return (o instanceof SystemFunction) && super.equals(o); |
| 295 | } |
| 296 | |
| 297 | /** |
| 298 | * Return the error code to be used for type errors. This is overridden for functions |
| 299 | * such as exactly-one(), one-or-more(), ... |
| 300 | * |
| 301 | * @return the error code to be used for type errors in the function call. Normally XPTY0004, |
| 302 | * but different codes are used for functions such as exactly-one() |
| 303 | */ |
| 304 | |
| 305 | public String getErrorCodeForTypeErrors() { |
| 306 | return "XPTY0004"; |
| 307 | } |
| 308 | |
| 309 | /** |
| 310 | * Get the required type of the nth argument |
| 311 | * |
| 312 | * @param arg the number of the argument whose type is requested, zero-based |
| 313 | * @return the required type of the argument as defined in the function signature |
| 314 | */ |
| 315 | |
| 316 | public SequenceType getRequiredType(int arg) { |
| 317 | if (details == null) { |
| 318 | return SequenceType.ANY_SEQUENCE; |
| 319 | } |
| 320 | return details.argumentTypes[arg]; |
| 321 | // this is overridden for concat() |
| 322 | } |
| 323 | |
| 324 | /** |
| 325 | * Determine the item type of the value returned by the function |
| 326 | */ |
| 327 | public ItemType getResultItemType() { |
| 328 | return details.itemType; |
| 329 | // if (details == null) { |
| 330 | // // probably an unresolved function call |
| 331 | // return AnyItemType.getInstance(); |
| 332 | // } |
| 333 | // ItemType type = details.itemType; |
| 334 | // if ((details.properties & StandardFunction.AS_ARG0) != 0) { |
| 335 | // if (getArity() > 0) { |
| 336 | // return getArg(0).getItemType(); |
| 337 | // } else { |
| 338 | // return AnyItemType.getInstance(); |
| 339 | // // if there is no first argument, an error will be reported |
| 340 | // } |
| 341 | // } else if ((details.properties & StandardFunction.AS_PRIM_ARG0) != 0) { |
| 342 | // if (getArity() > 0) { |
| 343 | // ItemType t0 = getArg(0).getItemType().getPrimitiveItemType(); |
| 344 | // return UType.NUMERIC.subsumes(t0.getUType()) ? t0 : type; |
| 345 | // } else { |
| 346 | // return AnyItemType.getInstance(); |
| 347 | // // if there is no first argument, an error will be reported |
| 348 | // } |
| 349 | // } else { |
| 350 | // return type; |
| 351 | // } |
| 352 | } |
| 353 | |
| 354 | /** |
| 355 | * Get the item type of the function item |
| 356 | * |
| 357 | * @return the function item's type |
| 358 | */ |
| 359 | |
| 360 | public FunctionItemType getFunctionItemType() { |
| 361 | SequenceType resultType = SequenceType.makeSequenceType(getResultItemType(), details.cardinality); |
| 362 | return new SpecificFunctionType(details.argumentTypes, resultType); |
| 363 | } |
| 364 | |
| 365 | /** |
| 366 | * Get the return type, given knowledge of the actual arguments |
| 367 | * @param args the actual arguments supplied |
| 368 | * @return the best available item type that the function will return |
| 369 | */ |
| 370 | |
| 371 | public ItemType getResultItemType(Expression[] args) { |
| 372 | if ((details.properties & BuiltInFunctionSet.AS_ARG0) != 0) { |
| 373 | return args[0].getItemType(); |
| 374 | } else if ((details.properties & BuiltInFunctionSet.AS_PRIM_ARG0) != 0) { |
| 375 | return args[0].getItemType().getPrimitiveItemType(); |
| 376 | } else { |
| 377 | return details.itemType; |
| 378 | } |
| 379 | } |
| 380 | |
| 381 | /** |
| 382 | * Get the cardinality, given knowledge of the actual arguments |
| 383 | * @param args the actual arguments supplied |
| 384 | * @return the most precise available cardinality that the function will return |
| 385 | */ |
| 386 | |
| 387 | public int getCardinality(Expression[] args) { |
| 388 | int c = details.cardinality; |
| 389 | if (c == BuiltInFunctionSet.OPT && (details.properties & BuiltInFunctionSet.CARD0) != 0 && |
| 390 | !Cardinality.allowsZero(args[0].getCardinality())) { |
| 391 | return StaticProperty.EXACTLY_ONE; |
| 392 | } else { |
| 393 | return c; |
| 394 | } |
| 395 | } |
| 396 | |
| 397 | /** |
| 398 | * Determine the special properties of this function. The general rule |
| 399 | * is that a system function call is non-creative unless more details |
| 400 | * are defined in a subclass. |
| 401 | * @param arguments the actual arguments supplied in a call to the function |
| 402 | */ |
| 403 | |
| 404 | public int getSpecialProperties(Expression[] arguments) { |
| 405 | if ((details.properties & BuiltInFunctionSet.NEW) != 0) { |
| 406 | return StaticProperty.ALL_NODES_NEWLY_CREATED; |
| 407 | } |
| 408 | int p = StaticProperty.NO_NODES_NEWLY_CREATED; |
| 409 | if ((details.properties & BuiltInFunctionSet.SIDE) != 0) { |
| 410 | p |= StaticProperty.HAS_SIDE_EFFECTS; |
| 411 | } |
| 412 | return p; |
| 413 | } |
| 414 | |
| 415 | /** |
| 416 | * Helper method for subclasses: get the context item if it is a node, throwing appropriate errors |
| 417 | * if not |
| 418 | * |
| 419 | * @param context the XPath dynamic context |
| 420 | * @return the context item if it exists and is a node |
| 421 | * @throws XPathException if there is no context item or if the context item is not a node |
| 422 | */ |
| 423 | |
| 424 | protected NodeInfo getContextNode(XPathContext context) throws XPathException { |
| 425 | Item item = context.getContextItem(); |
| 426 | if (item == null) { |
| 427 | XPathException err = new XPathException("Context item for " + getFunctionName() + "() is absent", "XPDY0002"); |
| 428 | err.maybeSetContext(context); |
| 429 | throw err; |
| 430 | } else if (!(item instanceof NodeInfo)) { |
| 431 | XPathException err = new XPathException("Context item for " + getFunctionName() + "() is not a node", "XPTY0004"); |
| 432 | err.maybeSetContext(context); |
| 433 | throw err; |
| 434 | } else { |
| 435 | return (NodeInfo) item; |
| 436 | } |
| 437 | } |
| 438 | |
| 439 | /** |
| 440 | * Make a dynamic call to a supplied argument function (convenience method for use by implementations) |
| 441 | * |
| 442 | * @param context the XPath dynamic evaluation context |
| 443 | * @param args the actual arguments to be supplied |
| 444 | * @return the result of invoking the function |
| 445 | * @throws XPathException if a dynamic error occurs within the function |
| 446 | */ |
| 447 | |
| 448 | public static Sequence<?> dynamicCall(Function f, XPathContext context, Sequence[] args) throws XPathException { |
| 449 | context = f.makeNewContext(context, null); |
| 450 | return f.call(context, args); |
| 451 | } |
| 452 | |
| 453 | |
| 454 | /** |
| 455 | * Diagnostic print of expression structure. The abstract expression tree |
| 456 | * is written to the supplied output destination. |
| 457 | */ |
| 458 | |
| 459 | public void export(ExpressionPresenter out) throws XPathException { |
| 460 | out.startElement("fnRef"); |
| 461 | StructuredQName qName = getFunctionName(); |
| 462 | String name = qName.hasURI(NamespaceConstant.FN) ? qName.getLocalPart() : qName.getEQName(); |
| 463 | out.emitAttribute("name", name); |
| 464 | out.emitAttribute("arity", getArity() + ""); |
| 465 | if ((getDetails().properties & BuiltInFunctionSet.DEPENDS_ON_STATIC_CONTEXT) != 0) { |
| 466 | out.emitRetainedStaticContext(getRetainedStaticContext(), null); |
| 467 | } |
| 468 | out.endElement(); |
| 469 | } |
| 470 | |
| 471 | /** |
| 472 | * Typecheck a call on this function |
| 473 | */ |
| 474 | |
| 475 | public Expression typeCheckCaller(FunctionCall caller, ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) |
| 476 | throws XPathException { |
| 477 | return caller; |
| 478 | } |
| 479 | |
| 480 | public boolean isTrustedResultType() { |
| 481 | return true; |
| 482 | } |
| 483 | |
| 484 | public String getStaticBaseUriString() { |
| 485 | return getRetainedStaticContext().getStaticBaseUriString(); |
| 486 | } |
| 487 | |
| 488 | /** |
| 489 | * Export any context attributes held within the SystemFunction object. The implementation |
| 490 | * will normally make one or more calls on out.emitAttribute(name, value). |
| 491 | * @param out the export destination |
| 492 | */ |
| 493 | |
| 494 | public void exportAttributes(ExpressionPresenter out) {} |
| 495 | |
| 496 | /** |
| 497 | * Export any implicit arguments held in optimized form within the SystemFunction call |
| 498 | * @param out the export destination |
| 499 | */ |
| 500 | |
| 501 | public void exportAdditionalArguments(SystemFunctionCall call, ExpressionPresenter out) throws XPathException { |
| 502 | } |
| 503 | |
| 504 | /** |
| 505 | * Import any attributes found in the export file, that is, any attributes output using |
| 506 | * the exportAttributes method |
| 507 | * @param attributes the attributes, as a properties object |
| 508 | * @throws XPathException |
| 509 | */ |
| 510 | |
| 511 | public void importAttributes(Properties attributes) throws XPathException {} |
| 512 | |
| 513 | /** |
| 514 | * Get the (local) name of a class that can be used to generate bytecode for this |
| 515 | * system function |
| 516 | * @return the name of a bytecode generation class, or null if there is no bytecode |
| 517 | * support for this function |
| 518 | */ |
| 519 | public String getCompilerName() { |
| 520 | return null; |
| 521 | } |
| 522 | |
| 523 | /** |
| 524 | * Get a name that identifies the class that can be used to evaluate this function |
| 525 | * in streaming mode, that is, supplying one item or event at a time as it is |
| 526 | * delivered by the parser. Special streaming support is generally available in |
| 527 | * Saxon-EE for all system functions that take a sequence as their argument. |
| 528 | * @return a name that identifies a class that supports streamed evaluation of this system |
| 529 | * function, or null if no such class is available. The mapping of names to classes is |
| 530 | * defined in the Saxon-EE class {@code StreamerMap}. In non-streaming Saxon editions |
| 531 | * (HE and PE) the method always returns null. |
| 532 | */ |
| 533 | |
| 534 | public String getStreamerName() { |
| 535 | return null; |
| 536 | } |
| 537 | |
| 538 | /** |
| 539 | * Provide a short string showing the contents of the item, suitable |
| 540 | * for use in error messages |
| 541 | * |
| 542 | * @return a depiction of the item suitable for use in error messages |
| 543 | */ |
| 544 | @Override |
| 545 | public String toShortString() { |
| 546 | return getFunctionName().getDisplayName() + '#' + getArity(); |
| 547 | } |
| 548 | |
| 549 | public String toString() { |
| 550 | return getFunctionName().getDisplayName() + '#' + getArity(); |
| 551 | } |
| 552 | |
| 553 | |
| 554 | } |
| 555 |