Debian Codegraph @

net/sf/saxon/expr/Literal.java

raw symbols SCIP
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
11 import com.saxonica.functions.hof.FunctionLiteral;
12 import net.sf.saxon.Configuration;
13 import net.sf.saxon.event.Receiver;
14 import net.sf.saxon.event.ReceiverOptions;
15 import net.sf.saxon.expr.parser.*;
16 import net.sf.saxon.ma.arrays.ArrayItem;
17 import net.sf.saxon.ma.map.KeyValuePair;
18 import net.sf.saxon.ma.map.MapItem;
19 import net.sf.saxon.om.*;
20 import net.sf.saxon.pattern.NodeTestPattern;
21 import net.sf.saxon.pattern.Pattern;
22 import net.sf.saxon.query.QueryResult;
23 import net.sf.saxon.trace.ExpressionPresenter;
24 import net.sf.saxon.trans.XPathException;
25 import net.sf.saxon.type.*;
26 import net.sf.saxon.value.*;
27
28 import javax.xml.transform.stream.StreamResult;
29 import java.io.StringWriter;
30 import java.util.ArrayList;
31 import java.util.List;
32 import java.util.Properties;
33
34
35 /**
36 * A Literal is an expression whose value is constant: it is a class that implements the {@link Expression}
37 * interface as a wrapper around a {@link GroundedValue}. This may derive from an actual literal in an XPath expression
38 * or query, or it may be the result of evaluating a constant subexpression such as true() or xs:date('2007-01-16')
39 */
40
41 public class Literal extends Expression {
42
43 private GroundedValue<?> value;
44
45 /**
46 * Create a literal as a wrapper around a Value
47 *
48 * @param value the value of this literal
49 */
50
51 protected Literal(GroundedValue<?> value) {
52 this.value = value.reduce();
53 }
54
55 /**
56 * Create a Literal containing a sequence of strings
57 *
58 * @param strings the strings to be wrapped
59 * @return a Literal of the string sequence
60 */
61 public static Literal makeStringsLiteral(List<String> strings) {
62 List<StringValue> values = new ArrayList<>();
63 for (String s : strings) {
64 values.add(new StringValue(s));
65 }
66 GroundedValue<StringValue> gv = SequenceExtent.makeSequenceExtent(values);
67 return makeLiteral(gv);
68 }
69
70 /**
71 * Get the value represented by this Literal
72 *
73 * @return the constant value
74 */
75
76 public GroundedValue<?> getValue() {
77 return value;
78 }
79
80 /**
81 * TypeCheck an expression
82 *
83 * @return for a Value, this always returns the value unchanged
84 */
85
86 /*@NotNull*/
87 public Expression typeCheck(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
88 return this;
89 }
90
91 /**
92 * Optimize an expression
93 *
94 * @return for a Value, this always returns the value unchanged
95 */
96
97 /*@NotNull*/
98 public Expression optimize(ExpressionVisitor visitor, ContextItemStaticInfo contextItemType) throws XPathException {
99 return this;
100 }
101
102 /**
103 * Return the estimated cost of evaluating an expression. This is a very crude measure based
104 * on the syntactic form of the expression (we have no knowledge of data values). We take
105 * the cost of evaluating a simple scalar comparison or arithmetic expression as 1 (one),
106 * and we assume that a sequence has length 5. The resulting estimates may be used, for
107 * example, to reorder the predicates in a filter expression so cheaper predicates are
108 * evaluated first.
109 */
110
111 @Override
112 public int getNetCost() {
113 return 0;
114 }
115
116 /**
117 * Determine the data type of the items in the expression, if possible
118 *
119 * @return for the default implementation: AnyItemType (not known)
120 */
121
122 /*@NotNull*/
123 public ItemType getItemType() {
124 // Avoid getting the configuration if we can: it's a common source of NPE's
125 if (value instanceof AtomicValue) {
126 return ((AtomicValue) value).getItemType();
127 } else if (value.getLength() == 0) {
128 return ErrorType.getInstance();
129 } else {
130 TypeHierarchy th = getConfiguration().getTypeHierarchy();
131 return SequenceTool.getItemType(value, th);
132 }
133 }
134
135
136 /**
137 * Get the static type of the expression as a UType, following precisely the type
138 * inference rules defined in the XSLT 3.0 specification.
139 *
140 * @param contextItemType the static context item type
141 * @return the static item type of the expression according to the XSLT 3.0 defined rules
142 */
143 @Override
144 public UType getStaticUType(UType contextItemType) {
145 if (value.getLength() == 0) {
146 return UType.VOID;
147 } else if (value instanceof AtomicValue) {
148 return ((AtomicValue) value).getUType();
149 } else if (value instanceof Function) {
150 return UType.FUNCTION;
151 } else {
152 return super.getStaticUType(contextItemType);
153 }
154 }
155
156
157 /**
158 * Determine the cardinality
159 */
160
161 public int computeCardinality() {
162 if (value.getLength() == 0) {
163 return StaticProperty.EMPTY;
164 } else if (value instanceof AtomicValue) {
165 return StaticProperty.EXACTLY_ONE;
166 }
167 try {
168 SequenceIterator iter = value.iterate();
169 Item next = iter.next();
170 if (next == null) {
171 return StaticProperty.EMPTY;
172 } else {
173 if (iter.next() != null) {
174 return StaticProperty.ALLOWS_MANY;
175 } else {
176 return StaticProperty.EXACTLY_ONE;
177 }
178 }
179 } catch (XPathException err) {
180 // can't actually happen
181 return StaticProperty.ALLOWS_ZERO_OR_MORE;
182 }
183 }
184
185 /**
186 * Compute the static properties of this expression (other than its type). For a
187 * Value, the only special property is {@link StaticProperty#NO_NODES_NEWLY_CREATED}.
188 *
189 * @return the value {@link StaticProperty#NO_NODES_NEWLY_CREATED}
190 */
191
192
193 public int computeSpecialProperties() {
194 if (value.getLength() == 0) {
195 // An empty sequence has all special properties except "has side effects".
196 return StaticProperty.SPECIAL_PROPERTY_MASK & ~StaticProperty.HAS_SIDE_EFFECTS;
197 }
198 return StaticProperty.NO_NODES_NEWLY_CREATED;
199 }
200
201 /**
202 * For an expression that returns an integer or a sequence of integers, get
203 * a lower and upper bound on the values of the integers that may be returned, from
204 * static analysis. The default implementation returns null, meaning "unknown" or
205 * "not applicable". Other implementations return an array of two IntegerValue objects,
206 * representing the lower and upper bounds respectively. The values
207 * UNBOUNDED_LOWER and UNBOUNDED_UPPER are used by convention to indicate that
208 * the value may be arbitrarily large. The values MAX_STRING_LENGTH and MAX_SEQUENCE_LENGTH
209 * are used to indicate values limited by the size of a string or the size of a sequence.
210 *
211 * @return the lower and upper bounds of integer values in the result, or null to indicate
212 * unknown or not applicable.
213 */
214 /*@Nullable*/
215 @Override
216 public IntegerValue[] getIntegerBounds() {
217 if (value instanceof IntegerValue) {
218 return new IntegerValue[]{(IntegerValue) value, (IntegerValue) value};
219 } else if (value instanceof IntegerRange) {
220 return new IntegerValue[]{
221 Int64Value.makeIntegerValue(((IntegerRange) value).getStart()),
222 Int64Value.makeIntegerValue(((IntegerRange) value).getEnd())};
223 } else {
224 return null;
225 }
226 }
227
228 /**
229 * Determine whether this is a vacuous expression as defined in the XQuery update specification
230 *
231 * @return true if this expression is vacuous
232 */
233
234 public boolean isVacuousExpression() {
235 return value.getLength() == 0;
236 }
237
238 /**
239 * Copy an expression. This makes a deep copy.
240 *
241 * @param rebindings variables that need to be re-bound
242 * @return a copy of the original literal. Note that the
243 * underlying value is not copied; the code relies on the caller
244 * treating the underlying value as immutable.
245 */
246
247 /*@NotNull*/
248 public Expression copy(RebindingMap rebindings) {
249 Literal l2 = new Literal(value);
250 ExpressionTool.copyLocationInfo(this, l2);
251 return l2;
252 }
253
254 /**
255 * Convert this expression to an equivalent XSLT pattern
256 *
257 * @param config the Saxon configuration
258 * @return the equivalent pattern
259 * @throws net.sf.saxon.trans.XPathException if conversion is not possible
260 */
261 @Override
262 public Pattern toPattern(Configuration config) throws XPathException {
263 if (isEmptySequence(this)) {
264 return new NodeTestPattern(ErrorType.getInstance());
265 } else {
266 return super.toPattern(config);
267 }
268 }
269
270 /**
271 * Add a representation of this expression to a PathMap. The PathMap captures a map of the nodes visited
272 * by an expression in a source tree.
273 *
274 * @param pathMap the PathMap to which the expression should be added
275 * @param pathMapNodeSet the set of nodes within the path map
276 * @return the pathMapNode representing the focus established by this expression, in the case where this
277 * expression is the first operand of a path expression or filter expression
278 */
279
280 public PathMap.PathMapNodeSet addToPathMap(PathMap pathMap, PathMap.PathMapNodeSet pathMapNodeSet) {
281 return pathMapNodeSet;
282 }
283
284 /**
285 * Determine which aspects of the context the expression depends on. The result is
286 * a bitwise-or'ed value composed from constants such as StaticProperty.VARIABLES and
287 * StaticProperty.CURRENT_NODE
288 *
289 * @return for a Value, this always returns zero.
290 */
291
292 public final int getDependencies() {
293 return 0;
294 }
295
296
297 /**
298 * Return an Iterator to iterate over the values of a sequence. The value of every
299 * expression can be regarded as a sequence, so this method is supported for all
300 * expressions. This default implementation handles iteration for expressions that
301 * return singleton values: for non-singleton expressions, the subclass must
302 * provide its own implementation.
303 *
304 * @param context supplies the context for evaluation
305 * @return a SequenceIterator that can be used to iterate over the result
306 * of the expression
307 * @throws net.sf.saxon.trans.XPathException if any dynamic error occurs evaluating the
308 * expression
309 */
310
311 /*@NotNull*/
312 public SequenceIterator<?> iterate(XPathContext context) throws XPathException {
313 return value.iterate();
314 }
315
316 /**
317 * Return an Iterator to iterate over the values of a sequence. The value of every
318 * expression can be regarded as a sequence, so this method is supported for all
319 * expressions. This default implementation handles iteration for expressions that
320 * return singleton values: for non-singleton expressions, the subclass must
321 * provide its own implementation.
322 *
323 * @return a SequenceIterator that can be used to iterate over the result
324 * of the expression
325 * @throws net.sf.saxon.trans.XPathException if any dynamic error occurs evaluating the
326 * expression
327 */
328
329 /*@NotNull*/
330 public SequenceIterator iterate() throws XPathException {
331 return value.iterate();
332 }
333
334 /**
335 * Evaluate as a singleton item (or empty sequence). Note: this implementation returns
336 * the first item in the sequence. The method should not be used unless appropriate type-checking
337 * has been done to ensure that the value will be a singleton.
338 */
339
340 public Item evaluateItem(XPathContext context) throws XPathException {
341 return value.head();
342 }
343
344
345 /**
346 * Process the value as an instruction, without returning any tail calls
347 *
348 * @param context The dynamic context, giving access to the current node,
349 * the current variables, etc.
350 */
351
352 public void process(XPathContext context) throws XPathException {
353 Receiver out = context.getReceiver();
354 if (value instanceof Item) {
355 out.append((Item) value, getLocation(), ReceiverOptions.ALL_NAMESPACES);
356 } else {
357 value.iterate().forEachOrFail(it -> out.append(it, getLocation(), ReceiverOptions.ALL_NAMESPACES));
358 }
359 }
360
361 @Override
362 public int getImplementationMethod() {
363 return ITERATE_METHOD | PROCESS_METHOD | EVALUATE_METHOD;
364 }
365
366 /*
367 * Evaluate an expression as a String. This function must only be called in contexts
368 * where it is known that the expression will return a single string (or where an empty sequence
369 * is to be treated as a zero-length string). Implementations should not attempt to convert
370 * the result to a string, other than converting () to "". This method is used mainly to
371 * evaluate expressions produced by compiling an attribute value template.
372 *
373 * @exception net.sf.saxon.trans.XPathException if any dynamic error occurs evaluating the
374 * expression
375 * @exception ClassCastException if the result type of the
376 * expression is not xs:string?
377 * @param context The context in which the expression is to be evaluated
378 * @return the value of the expression, evaluated in the current context.
379 * The expression must return a string or (); if the value of the
380 * expression is (), this method returns "".
381 */
382
383 public CharSequence evaluateAsString(XPathContext context) throws XPathException {
384 AtomicValue value = (AtomicValue) evaluateItem(context);
385 if (value == null) {
386 return "";
387 }
388 return value.getStringValueCS();
389 }
390
391
392 /**
393 * Get the effective boolean value of the expression. This returns false if the value
394 * is the empty sequence, a zero-length string, a number equal to zero, or the boolean
395 * false. Otherwise it returns true.
396 *
397 * @param context The context in which the expression is to be evaluated
398 * @return the effective boolean value
399 * @throws net.sf.saxon.trans.XPathException if any dynamic error occurs evaluating the
400 * expression
401 */
402
403 public boolean effectiveBooleanValue(XPathContext context) throws XPathException {
404 return value.effectiveBooleanValue();
405 }
406
407
408 /**
409 * Evaluate an updating expression, adding the results to a Pending Update List.
410 * The default implementation of this method, which is used for non-updating expressions,
411 * throws an UnsupportedOperationException. The implementation for a literal representing
412 * an empty sequence, however, is a no-op.
413 *
414 * @param context the XPath dynamic evaluation context
415 * @param pul the pending update list to which the results should be written
416 */
417
418 public void evaluatePendingUpdates(XPathContext context, PendingUpdateList pul) throws XPathException {
419 if (value.getLength() == 0) {
420 // do nothing
421 } else {
422 super.evaluatePendingUpdates(context, pul);
423 }
424 }
425
426 /**
427 * Determine whether two literals are equal, when considered as expressions.
428 *
429 * @param obj the other expression
430 * @return true if the two literals are equal. The test here requires (a) identity in the
431 * sense defined by XML Schema (same value in the same value space), and (b) identical type
432 * annotations. For example the literal xs:int(3) is not equal (as an expression) to xs:short(3),
433 * because the two expressions are not interchangeable.
434 */
435
436 public boolean equals(Object obj) {
437 if (!(obj instanceof Literal)) {
438 return false;
439 }
440 GroundedValue<?> v0 = value;
441 GroundedValue<?> v1 = ((Literal) obj).value;
442 try {
443 SequenceIterator<?> i0 = v0.iterate();
444 SequenceIterator<?> i1 = v1.iterate();
445 while (true) {
446 Item m0 = i0.next();
447 Item m1 = i1.next();
448 if (m0 == null && m1 == null) {
449 return true;
450 }
451 if (m0 == null || m1 == null) {
452 return false;
453 }
454 if (m0 == m1) {
455 continue;
456 }
457 boolean n0 = m0 instanceof NodeInfo;
458 boolean n1 = m1 instanceof NodeInfo;
459 if (n0 != n1) {
460 return false;
461 }
462 if (n0) {
463 if (m0.equals(m1)) {
464 continue;
465 } else {
466 return false;
467 }
468 }
469 boolean a0 = m0 instanceof AtomicValue;
470 boolean a1 = m1 instanceof AtomicValue;
471 if (a0 != a1) {
472 return false;
473 }
474 if (a0) {
475 if (((AtomicValue) m0).isIdentical((AtomicValue) m1) &&
476 ((AtomicValue) m0).getItemType() == ((AtomicValue) m1).getItemType()) {
477 continue;
478 } else {
479 return false;
480 }
481 }
482 // don't attempt to compare functions, maps, and arrays
483 return false;
484 }
485 } catch (XPathException err) {
486 return false;
487 }
488 }
489
490 /**
491 * Return a hash code to support the equals() function
492 */
493
494 public int computeHashCode() {
495 if (value instanceof AtomicSequence) {
496 return ((AtomicSequence) value).getSchemaComparable().hashCode();
497 } else {
498 return super.computeHashCode();
499 }
500 }
501
502 /**
503 * The toString() method for an expression attempts to give a representation of the expression
504 * in an XPath-like form, but there is no guarantee that the syntax will actually be true XPath.
505 * In the case of XSLT instructions, the toString() method gives an abstracted view of the syntax
506 */
507
508 public String toString() {
509 return value.toString();
510 }
511
512 /**
513 * Diagnostic print of expression structure. The abstract expression tree
514 * is written to the supplied output destination.
515 */
516
517 public void export(ExpressionPresenter out) throws XPathException {
518 exportValue(value, out);
519 }
520
521 public static void exportValue(Sequence<?> value, ExpressionPresenter out) throws XPathException {
522 if (value.head() == null) {
523 out.startElement("empty");
524 out.endElement();
525 } else if (value instanceof AtomicValue) {
526 exportAtomicValue((AtomicValue) value, out);
527 } else if (value instanceof IntegerRange) {
528 out.startElement("range");
529 out.emitAttribute("from", "" + ((IntegerRange) value).getStart());
530 out.emitAttribute("to", "" + ((IntegerRange) value).getEnd());
531 out.endElement();
532 } else if (value instanceof NodeInfo) {
533 out.startElement("node");
534 final int nodeKind = ((NodeInfo) value).getNodeKind();
535 out.emitAttribute("kind", nodeKind + "");
536 if (((ExpressionPresenter.ExportOptions) out.getOptions()).explaining) {
537 String name = ((NodeInfo)value).getDisplayName();
538 if (!name.isEmpty()) {
539 out.emitAttribute("name", name);
540 }
541 } else {
542 switch (nodeKind) {
543 case Type.DOCUMENT:
544 case Type.ELEMENT:
545 StringWriter sw = new StringWriter();
546 Properties props = new Properties();
547 props.setProperty("method", "xml");
548 props.setProperty("indent", "no");
549 props.setProperty("omit-xml-declaration", "yes");
550 QueryResult.serialize(((NodeInfo)value), new StreamResult(sw), props);
551 out.emitAttribute("content", sw.toString());
552 out.emitAttribute("baseUri", ((NodeInfo) value).getBaseURI());
553 break;
554 case Type.TEXT:
555 case Type.COMMENT:
556 out.emitAttribute("content", ((NodeInfo)value).getStringValue());
557 break;
558 case Type.ATTRIBUTE:
559 case Type.NAMESPACE:
560 case Type.PROCESSING_INSTRUCTION:
561 final StructuredQName name = NameOfNode.makeName(((NodeInfo) value)).getStructuredQName();
562 if (!name.getLocalPart().isEmpty()) {
563 out.emitAttribute("localName", name.getLocalPart());
564 }
565 if (!name.getPrefix().isEmpty()) {
566 out.emitAttribute("prefix", name.getPrefix());
567 }
568 if (!name.getURI().isEmpty()) {
569 out.emitAttribute("ns", name.getURI());
570 }
571 out.emitAttribute("content", ((NodeInfo) value).getStringValue());
572 break;
573 default:
574 assert false;
575
576 }
577 }
578 out.endElement();
579 } else if (value instanceof MapItem) {
580 out.startElement("map");
581 out.emitAttribute("size", "" + ((MapItem) value).size());
582 for (KeyValuePair kvp : ((MapItem) value).keyValuePairs()) {
583 exportAtomicValue(kvp.key, out);
584 exportValue(kvp.value, out);
585 }
586 out.endElement();
587 } else if (value instanceof Function) {
588 ((Function) value).export(out);
589 } else if (value instanceof ExternalObject) {
590 if (((ExpressionPresenter.ExportOptions)out.getOptions()).explaining) {
591 out.startElement("externalObject");
592 out.emitAttribute("class", ((ExternalObject)value).getObject().getClass().getName());
593 out.endElement();
594 } else {
595 throw new XPathException("Cannot export a stylesheet containing literal values bound to external Java objects");
596 }
597 } else {
598 out.startElement("literal");
599 if (value instanceof GroundedValue) {
600 out.emitAttribute("count", ((GroundedValue) value).getLength() + "");
601 }
602 value.iterate().forEachOrFail(it -> exportValue(it, out));
603 out.endElement();
604
605 }
606 }
607
608 /**
609 * Get a name identifying the kind of expression, in terms meaningful to a user.
610 *
611 * @return a name identifying the kind of expression, in terms meaningful to a user.
612 * The name will always be in the form of a lexical XML QName, and should match the name used
613 * in export() output displaying the expression.
614 */
615 @Override
616 public String getExpressionName() {
617 return "literal";
618 }
619
620 public static void exportAtomicValue(AtomicValue value, ExpressionPresenter out) throws XPathException {
621 if ("JS".equals(((ExpressionPresenter.ExportOptions) out.getOptions()).target)) {
622 value.checkValidInJavascript();
623 }
624 AtomicType type = value.getItemType();
625 String val = value.getStringValue();
626 if (type.equals(BuiltInAtomicType.STRING)) {
627 out.startElement("str");
628 out.emitAttribute("val", val);
629 out.endElement();
630 } else if (type.equals(BuiltInAtomicType.INTEGER)) {
631 out.startElement("int");
632 out.emitAttribute("val", val);
633 out.endElement();
634 } else if (type.equals(BuiltInAtomicType.DECIMAL)) {
635 out.startElement("dec");
636 out.emitAttribute("val", val);
637 out.endElement();
638 } else if (type.equals(BuiltInAtomicType.DOUBLE)) {
639 out.startElement("dbl");
640 out.emitAttribute("val", val);
641 out.endElement();
642 } else if (type.equals(BuiltInAtomicType.BOOLEAN)) {
643 out.startElement(((BooleanValue) value).effectiveBooleanValue() ? "true" : "false");
644 out.endElement();
645 } else if (value instanceof QualifiedNameValue) {
646 out.startElement("qName");
647 out.emitAttribute("pre", ((QualifiedNameValue) value).getPrefix());
648 out.emitAttribute("uri", ((QualifiedNameValue) value).getNamespaceURI());
649 out.emitAttribute("loc", ((QualifiedNameValue) value).getLocalName());
650 if (!type.equals(BuiltInAtomicType.QNAME)) {
651 out.emitAttribute("type", type.getTypeName());
652 }
653 out.endElement();
654 } else {
655 out.startElement("atomic");
656 out.emitAttribute("val", val);
657 out.emitAttribute("type", type.toExportString());
658 out.endElement();
659 }
660 }
661
662 /**
663 * Produce a short string identifying the expression for use in error messages
664 *
665 * @return a short string, sufficient to identify the expression
666 */
667 @Override
668 public String toShortString() {
669 if (value.getLength() == 0) {
670 return "()";
671 } else if (value instanceof AtomicValue) {
672 return value.toString();
673 } else {
674 return "(" + value.head() + ",...)";
675 }
676 }
677
678 /**
679 * Test whether the literal wraps an atomic value. (Note, if this method returns false,
680 * this still leaves the possibility that the literal wraps a sequence that happens to contain
681 * a single atomic value).
682 *
683 * @param exp an expression
684 * @return true if the expression is a literal and the literal wraps an AtomicValue
685 */
686
687 public static boolean isAtomic(Expression exp) {
688 return exp instanceof Literal && ((Literal) exp).getValue() instanceof AtomicValue;
689 }
690
691 /**
692 * Test whether the literal explicitly wraps an empty sequence. (Note, if this method returns false,
693 * this still leaves the possibility that the literal wraps a sequence that happens to be empty).
694 *
695 * @param exp an expression
696 * @return true if the expression is a literal and the value of the literal is an empty sequence
697 */
698
699 public static boolean isEmptySequence(Expression exp) {
700 return exp instanceof Literal && ((Literal) exp).getValue().getLength() == 0;
701 }
702
703 /**
704 * Test if a literal represents the boolean value true
705 *
706 * @param exp an expression
707 * @param value true or false
708 * @return true if the expression is a literal and the literal represents the boolean value given in the
709 * second argument
710 */
711
712 public static boolean isConstantBoolean(Expression exp, boolean value) {
713 if (exp instanceof Literal) {
714 GroundedValue b = ((Literal) exp).getValue();
715 return b instanceof BooleanValue && ((BooleanValue) b).getBooleanValue() == value;
716 }
717 return false;
718 }
719
720 /**
721 * Test if a literal has the effective boolean value true (or false)
722 *
723 * @param exp an expression
724 * @param value true or false
725 * @return true if the expression is a literal and the literal represents the boolean value given in the
726 * second argument
727 */
728
729 public static boolean hasEffectiveBooleanValue(Expression exp, boolean value) {
730 if (exp instanceof Literal) {
731 try {
732 return value == ((Literal) exp).getValue().effectiveBooleanValue();
733 } catch (XPathException err) {
734 return false;
735 }
736 }
737 return false;
738 }
739
740 /**
741 * Test if a literal represents the integer value 1
742 *
743 * @param exp an expression
744 * @return true if the expression is a literal and the literal represents the integer value 1
745 */
746
747 public static boolean isConstantOne(Expression exp) {
748 if (exp instanceof Literal) {
749 GroundedValue v = ((Literal) exp).getValue();
750 return v instanceof Int64Value && ((Int64Value) v).longValue() == 1;
751 }
752 return false;
753 }
754
755 /**
756 * Determine whether the expression can be evaluated without reference to the part of the context
757 * document outside the subtree rooted at the context node.
758 *
759 * @return true if the expression has no dependencies on the context node, or if the only dependencies
760 * on the context node are downward selections using the self, child, descendant, attribute, and namespace
761 * axes.
762 */
763
764 public boolean isSubtreeExpression() {
765 return true;
766 }
767
768 /**
769 * Factory method to make an empty-sequence literal
770 *
771 * @return a literal whose value is the empty sequence
772 */
773
774 public static Literal makeEmptySequence() {
775 return new Literal(EmptySequence.getInstance());
776 }
777
778
779 /**
780 * Factory method to create a literal as a wrapper around a Value (factory method)
781 *
782 * @param value the value of this literal
783 * @return the Literal
784 */
785
786 public static <T extends Item<?>> Literal makeLiteral(GroundedValue<T> value) {
787 value = value.reduce();
788 if (value instanceof StringValue) {
789 return new StringLiteral((StringValue) value);
790 //#ifdefined HOF
791 } else if (value instanceof Function && !(value instanceof MapItem || value instanceof ArrayItem)) {
792 return new FunctionLiteral((Function) value);
793 //#endif
794 } else {
795 return new Literal(value);
796 }
797 }
798
799
800 /**
801 * Make a literal, taking the retained static context and location information from another
802 * expression which is being simplified/optimized
803 *
804 * @param value the literal value
805 * @param origin the expression whose context and location information is to be retained
806 * @return the Literal
807 */
808
809 public static Literal makeLiteral(GroundedValue<?> value, Expression origin) {
810 Literal lit = makeLiteral(value);
811 //lit.setRetainedStaticContextLocally(origin.getLocalRetainedStaticContext());
812 ExpressionTool.copyLocationInfo(origin, lit);
813 return lit;
814 }
815
816 /**
817 * Get the (partial) name of a class that supports streaming of this kind of expression
818 *
819 * @return the partial name of a class that can be instantiated to provide streaming support in Saxon-EE,
820 * or null if there is no such class
821 */
822 @Override
823 public String getStreamerName() {
824 return "Literal";
825 }
826 }