Debian Codegraph @

net/sf/saxon/expr/instruct/GlobalVariable.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.instruct;
9
10 import net.sf.saxon.Configuration;
11 import net.sf.saxon.Controller;
12 import net.sf.saxon.PreparedStylesheet;
13 import net.sf.saxon.expr.*;
14 import net.sf.saxon.expr.parser.*;
15 import net.sf.saxon.lib.NamespaceConstant;
16 import net.sf.saxon.om.GroundedValue;
17 import net.sf.saxon.om.SequenceTool;
18 import net.sf.saxon.om.StandardNames;
19 import net.sf.saxon.om.StructuredQName;
20 import net.sf.saxon.query.XQueryFunction;
21 import net.sf.saxon.query.XQueryFunctionLibrary;
22 import net.sf.saxon.trace.ExpressionPresenter;
23 import net.sf.saxon.trace.InstructionInfo;
24 import net.sf.saxon.trace.LocationKind;
25 import net.sf.saxon.trans.SymbolicName;
26 import net.sf.saxon.trans.Visibility;
27 import net.sf.saxon.trans.XPathException;
28 import net.sf.saxon.tree.iter.ManualIterator;
29 import net.sf.saxon.type.AnyItemType;
30 import net.sf.saxon.type.ItemType;
31 import net.sf.saxon.type.TypeHierarchy;
32 import net.sf.saxon.value.Cardinality;
33 import net.sf.saxon.value.IntegerValue;
34 import net.sf.saxon.value.SequenceType;
35
36 import java.util.*;
37
38 /**
39 * A compiled global variable in a stylesheet or query. <br>
40 */
41
42 public class GlobalVariable extends Actor
43 implements Binding, net.sf.saxon.query.Declaration, InstructionInfo, ContextOriginator {
44
45 protected List<BindingReference> references = new ArrayList<>(10);
46 // Note that variableReferences on this list might be dormant;
47 // that is, they might be disconnected from the live expression tree.
48 // References are maintained in XQuery but not in XSLT (where they are handled at the level of the
49 // XSLSourceBinding object)
50
51 private Expression select;
52 private StructuredQName variableQName;
53 private SequenceType requiredType;
54
55 private boolean indexed;
56 private boolean isPrivate = false;
57 private boolean isAssignable = false;
58 private GlobalVariable originalVariable;
59 private int binderySlotNumber;
60 private boolean isRequiredParam;
61 private boolean isStatic;
62
63 /**
64 * Create a global variable
65 */
66
67 public GlobalVariable() {
68 }
69
70 /**
71 * Initialize the properties of the variable
72 *
73 * @param select the expression to which the variable is bound
74 * @param qName the name of the variable
75 */
76
77 public void init(Expression select, StructuredQName qName) {
78 this.select = select;
79 variableQName = qName;
80 setBody(select);
81 }
82
83 /**
84 * Get the symbolic name of the component
85 *
86 * @return the symbolic name
87 */
88 @Override
89 public SymbolicName getSymbolicName() {
90 return new SymbolicName(StandardNames.XSL_VARIABLE, variableQName);
91 }
92
93 /**
94 * Set the expression to which this variable is bound
95 *
96 * @param select the initializing expression. May be null in the case of a global parameter with no initializer.
97 */
98
99 public void setSelectExpression(Expression select) {
100 this.select = select;
101 setBody(select);
102 }
103
104 /**
105 * Get the expression to which this variable is bound
106 *
107 * @return the initializing expression
108 */
109
110 public Expression getSelectExpression() {
111 return select;
112 }
113
114 /**
115 * Say whether this variable is declared to be static
116 * @param declaredStatic true if the variable is declared with static="yes"
117 */
118
119 public void setStatic(boolean declaredStatic) {
120 isStatic = declaredStatic;
121 }
122
123 /**
124 * Ask whether this variable is declared to be static
125 * @return true if the variable is declared with static="yes"
126 */
127
128 public boolean isStatic() {
129 return this.isStatic;
130 }
131
132 /**
133 * Set the required type of this variable
134 *
135 * @param required the required type
136 */
137
138 public void setRequiredType(SequenceType required) {
139 requiredType = required;
140 }
141
142 /**
143 * Get the required type of this variable
144 *
145 * @return the required type
146 */
147
148 public SequenceType getRequiredType() {
149 return requiredType;
150 }
151
152 /**
153 * Get the Configuration to which this Container belongs
154 *
155 * @return the Configuration
156 */
157 private Configuration getConfiguration() {
158 return getPackageData().getConfiguration();
159 }
160
161 /**
162 * Say that this (XQuery) variable is a copy of some originally declared variable. It's a
163 * separate variable when imported into another module, but it retains the link
164 * to the original.
165 *
166 * @param var the variable in the imported module from which this variable is derived
167 */
168
169 public void setOriginalVariable(GlobalVariable var) {
170 originalVariable = var;
171 }
172
173 /**
174 * Get the original declaration of this variable
175 *
176 * @return the variable in the imported module from which this variable is derived
177 */
178
179 public GlobalVariable getOriginalVariable() {
180 return originalVariable;
181 }
182
183 /**
184 * Get the original declaration of this variable, or its original declaration, transitively
185 *
186 * @return the real variable declaration in some transitively imported module from which this variable is
187 * ultimately derived
188 */
189
190 public GlobalVariable getUltimateOriginalVariable() {
191 if (originalVariable == null) {
192 return this;
193 } else {
194 return originalVariable.getUltimateOriginalVariable();
195 }
196 }
197
198 /**
199 * Say whether this variable is unused. Normally, unused variables are not
200 * compiled. However, in XSLT with debugging enabled (that is, with compileWithTracing
201 * set), dummy unused variables are created in respect of global variables that are
202 * declared but never referenced. These variables are included in the list
203 * of variables known to the Executable, but they are never evaluated, and do
204 * not have slot numbers allocated in the bindery.
205 * @param unused set to true if this global variable is to be marked as unused.
206 */
207
208 public void setUnused(boolean unused) {
209 this.binderySlotNumber = -9234;
210 }
211
212 /**
213 * Ask whether this variable is unused. Normally, unused variables are not
214 * compiled. However, in XSLT with debugging enabled (that is, with compileWithTracing
215 * set), dummy unused variables are created in respect of global variables that are
216 * declared but never referenced. These variables are included in the list
217 * of variables known to the Executable, but they are never evaluated, and do
218 * not have slot numbers allocated in the bindery.
219 * @return true if this global variable is marked as unused.
220 */
221
222 public boolean isUnused() {
223 return this.binderySlotNumber == -9234;
224 }
225
226 /**
227 * Ask whether this global variable is private
228 *
229 * @return true if this variable is private
230 */
231
232 public boolean isPrivate() {
233 return isPrivate;
234 }
235
236 /**
237 * Say whether this global variable is private
238 *
239 * @param b true if this variable is external
240 */
241 public void setPrivate(boolean b) {
242 isPrivate = b;
243 }
244
245 /**
246 * Indicate whether this variable is assignable using saxon:assign
247 *
248 * @param assignable true if this variable is assignable
249 */
250
251 public void setAssignable(boolean assignable) {
252 isAssignable = assignable;
253 }
254
255 /**
256 * Test whether it is permitted to assign to the variable using the saxon:assign
257 * extension element. This will only be true if the extra attribute saxon:assignable="yes"
258 * is present.
259 */
260
261 public final boolean isAssignable() {
262 return isAssignable;
263 }
264
265
266 /**
267 * Get the type of construct. This will either be the fingerprint of a standard XSLT instruction name
268 * (values in {@link net.sf.saxon.om.StandardNames}: all less than 1024)
269 * or it will be a constant in class {@link LocationKind}.
270 *
271 * @return an integer identifying the kind of construct
272 */
273 public int getConstructType() {
274 return StandardNames.XSL_VARIABLE;
275 }
276
277 /**
278 * Get a name identifying the object of the expression, for example a function name, template name,
279 * variable name, key name, element name, etc. This is used only where the name is known statically.
280 *
281 * @return the QName of the object declared or manipulated by this instruction or expression
282 */
283 public StructuredQName getObjectName() {
284 return getVariableQName();
285 }
286
287 /**
288 * Get the value of a particular property of the instruction. Properties
289 * of XSLT instructions are generally known by the name of the stylesheet attribute
290 * that defines them.
291 *
292 * @param name The name of the required property
293 * @return The value of the requested property, or null if the property is not available
294 */
295 public Object getProperty(String name) {
296 return null;
297 }
298
299 /**
300 * Get an iterator over all the properties available. The values returned by the iterator
301 * will be of type String, and each string can be supplied as input to the getProperty()
302 * method to retrieve the value of the property. The iterator may return properties whose
303 * value is null.
304 *
305 * @return an iterator over the properties.
306 */
307 public Iterator<String> getProperties() {
308 List<String> list = Collections.emptyList();
309 return list.iterator();
310 }
311
312 /**
313 * Get the host language (XSLT, XQuery, XPath) used to implement the code in this container
314 *
315 * @return typically {@link net.sf.saxon.Configuration#XSLT} or {@link net.sf.saxon.Configuration#XQUERY}
316 */
317
318 public int getHostLanguage() {
319 return getPackageData().getHostLanguage();
320 }
321
322 /**
323 * Mark this as an indexed variable, to allow fast searching
324 */
325
326 public void setIndexedVariable() {
327 indexed = true;
328 }
329
330 /**
331 * Ask whether this is an indexed variable
332 *
333 * @return true if this variable is indexed
334 */
335
336 public boolean isIndexedVariable() {
337 return indexed;
338 }
339
340 /**
341 * The expression that initializes a global variable may itself use local variables.
342 * In this case a stack frame needs to be allocated while evaluating the global variable
343 *
344 * @param map The stack frame map for local variables used while evaluating this global
345 * variable.
346 */
347
348 public void setContainsLocals(SlotManager map) {
349 setStackFrameMap(map);
350 }
351
352 /**
353 * Is this a global variable?
354 *
355 * @return true (yes, it is a global variable)
356 */
357
358 public boolean isGlobal() {
359 return true;
360 }
361
362 /**
363 * Register a variable reference that refers to this global variable
364 *
365 * @param ref the variable reference
366 */
367 public void registerReference(BindingReference ref) {
368 references.add(ref);
369 }
370
371 /**
372 * Iterate over the references to this variable
373 *
374 * @return an iterator over the references: returns objects of class {@link VariableReference}
375 */
376
377 public Iterator iterateReferences() {
378 return references.iterator();
379 }
380
381 /**
382 * Get the slot number allocated to this variable in the Bindery
383 *
384 * @return the slot number, that is the position allocated to the variable within the Bindery
385 */
386
387 public int getBinderySlotNumber() {
388 return binderySlotNumber;
389 }
390
391 /**
392 * Set the slot number of this variable in the Bindery
393 *
394 * @param s the slot number, that is, the position allocated to this variable within the Bindery
395 */
396
397 public void setBinderySlotNumber(int s) {
398 if (!isUnused()) {
399 binderySlotNumber = s;
400 }
401 }
402
403 /**
404 * Indicate that this variable represents a required parameter
405 *
406 * @param requiredParam true if this is a required parameter
407 */
408
409 public void setRequiredParam(boolean requiredParam) {
410 this.isRequiredParam = requiredParam;
411 }
412
413 /**
414 * Ask whether this variable represents a required parameter
415 *
416 * @return true if this variable represents a required parameter
417 */
418
419 public boolean isRequiredParam() {
420 return this.isRequiredParam;
421 }
422
423 /**
424 * Create a compiled representation of this global variable. Used in XQuery only.
425 *
426 * @param exec the executable
427 * @param slot the slot number allocated to this variable
428 * @throws XPathException if compile-time errors are found.
429 */
430
431 public void compile(Executable exec, int slot) throws XPathException {
432 TypeHierarchy th = getConfiguration().getTypeHierarchy();
433
434 setBinderySlotNumber(slot);
435 if (this instanceof GlobalParam) {
436 setRequiredParam(select == null);
437 }
438 SequenceType type = getRequiredType();
439 for (BindingReference ref : references) {
440 ref.fixup(this);
441 GroundedValue<?> constantValue = null;
442 int properties = 0;
443 Expression select = getSelectExpression();
444 if (select instanceof Literal && !(this instanceof GlobalParam)) {
445 // we can't rely on the constant value because it hasn't yet been type-checked,
446 // which could change it (eg by numeric promotion). Rather than attempt all the type-checking
447 // now, we do a quick check. See test bug64
448 int relation = th.relationship(select.getItemType(), type.getPrimaryType());
449 if (relation == TypeHierarchy.SAME_TYPE || relation == TypeHierarchy.SUBSUMED_BY) {
450 constantValue = ((Literal) select).getValue();
451 type = SequenceType.makeSequenceType(SequenceTool.getItemType(constantValue, th), SequenceTool.getCardinality(constantValue));
452 }
453 }
454 if (select != null) {
455 properties = select.getSpecialProperties();
456 }
457 properties |= StaticProperty.NO_NODES_NEWLY_CREATED;
458 // a variable reference is non-creative even if its initializer is creative
459 ref.setStaticType(type, constantValue, properties);
460 }
461 //exec.registerGlobalVariable(this);
462 if (isRequiredParam()) {
463 exec.registerGlobalParameter((GlobalParam) this);
464 }
465 }
466
467
468 /**
469 * Type check the compiled representation of this global variable
470 *
471 * @param visitor an expression visitor
472 * @throws XPathException if compile-time errors are found.
473 */
474
475 public void typeCheck(/*@NotNull*/ ExpressionVisitor visitor) throws XPathException {
476 Expression value = getSelectExpression();
477 if (value != null) {
478 value.checkForUpdatingSubexpressions();
479 if (value.isUpdatingExpression()) {
480 throw new XPathException(
481 "Initializing expression for global variable must not be an updating expression", "XUST0001");
482 }
483 RoleDiagnostic role = new RoleDiagnostic(
484 RoleDiagnostic.VARIABLE, getVariableQName().getDisplayName(), 0);
485 ContextItemStaticInfo cit = getConfiguration().makeContextItemStaticInfo(AnyItemType.getInstance(), true);
486 Expression value2 = TypeChecker.strictTypeCheck(
487 value.simplify().typeCheck(visitor, cit),
488 getRequiredType(), role, visitor.getStaticContext());
489 value2 = value2.optimize(visitor, cit);
490 setSelectExpression(value2);
491 // the value expression may declare local variables
492 SlotManager map = getConfiguration().makeSlotManager();
493 int slots = ExpressionTool.allocateSlots(value2, 0, map);
494 if (slots > 0) {
495 setContainsLocals(map);
496 }
497
498 if (getRequiredType() == SequenceType.ANY_SEQUENCE && !(this instanceof GlobalParam)) {
499 // no type was declared; try to deduce a type from the value
500 try {
501 final ItemType itemType = value.getItemType();
502 final int cardinality = value.getCardinality();
503 setRequiredType(SequenceType.makeSequenceType(itemType, cardinality));
504 GroundedValue<?> constantValue = null;
505 if (value2 instanceof Literal) {
506 constantValue = ((Literal) value2).getValue();
507 }
508 for (BindingReference reference : references) {
509 if (reference instanceof VariableReference) {
510 ((VariableReference) reference).refineVariableType(
511 itemType, cardinality, constantValue, value.getSpecialProperties());
512 }
513 }
514 } catch (Exception err) {
515 // exceptions can happen because references to variables and functions are still unbound
516 }
517 }
518
519
520 }
521 }
522
523
524 /**
525 * Check for cycles in this variable definition
526 *
527 * @param referees the calls leading up to this one; it's an error if this variable is on the
528 * stack, because that means it calls itself directly or indirectly. The stack may contain
529 * variable definitions (GlobalVariable objects) and user-defined functions (UserFunction objects).
530 * It will never contain the same object more than once.
531 * @param globalFunctionLibrary the library containing all global functions
532 * @throws net.sf.saxon.trans.XPathException
533 * if cycles are found
534 */
535
536 public void lookForCycles(Stack<Object> referees, XQueryFunctionLibrary globalFunctionLibrary) throws XPathException {
537 if (referees.contains(this)) {
538 int s = referees.indexOf(this);
539 referees.push(this);
540
541 StringBuilder messageBuilder = new StringBuilder("Circular definition of global variable: $" + getVariableQName().getDisplayName());
542 for (int i = s; i < referees.size() - 1; i++) {
543 if (i != s) {
544 messageBuilder.append(", which");
545 }
546 if (referees.get(i + 1) instanceof GlobalVariable) {
547 GlobalVariable next = (GlobalVariable) referees.get(i + 1);
548 messageBuilder.append(" uses $").append(next.getVariableQName().getDisplayName());
549 } else if (referees.get(i + 1) instanceof XQueryFunction) {
550 XQueryFunction next = (XQueryFunction) referees.get(i + 1);
551 messageBuilder.append(" calls ").append(next.getFunctionName().getDisplayName()).append("#").append(next.getNumberOfArguments()).append("()");
552 }
553 }
554 String message = messageBuilder.toString();
555 message += '.';
556 XPathException err = new XPathException(message);
557 String errorCode;
558 if (getPackageData().getHostLanguage() == Configuration.XSLT) {
559 errorCode = "XTDE0640";
560 } else if (s == 0 && referees.size() == 2) {
561 // Simple self-reference, treated specially in XQuery
562 errorCode = "XPST0008";
563 } else {
564 errorCode = "XQDY0054";
565 }
566 err.setErrorCode(errorCode);
567 err.setIsStaticError(true);
568 err.setLocation(getLocation());
569 throw err;
570 }
571 if (select != null) {
572 referees.push(this);
573 List<Binding> list = new ArrayList<>(10);
574 ExpressionTool.gatherReferencedVariables(select, list);
575 for (Binding b : list) {
576 if (b instanceof GlobalVariable) {
577 ((GlobalVariable) b).lookForCycles(referees, globalFunctionLibrary);
578 }
579 }
580 List<SymbolicName> flist = new ArrayList<>();
581 ExpressionTool.gatherCalledFunctionNames(select, flist);
582 for (SymbolicName s : flist) {
583 XQueryFunction f = globalFunctionLibrary.getDeclarationByKey(s);
584 if (!referees.contains(f)) {
585 // recursive function calls are allowed
586 lookForFunctionCycles(f, referees, globalFunctionLibrary);
587 }
588 }
589 referees.pop();
590 }
591 }
592
593 /**
594 * Look for cyclic variable references that go via one or more function calls
595 *
596 * @param f a used-defined function
597 * @param referees a list of variables and functions that refer directly or indirectly to this variable
598 * @param globalFunctionLibrary the library containing all global functions
599 * @throws XPathException if an error occurs during evaluation
600 */
601
602 private static void lookForFunctionCycles(
603 XQueryFunction f, Stack<Object> referees, XQueryFunctionLibrary globalFunctionLibrary) throws XPathException {
604 Expression body = f.getBody();
605 referees.push(f);
606 List<Binding> list = new ArrayList<>(10);
607 ExpressionTool.gatherReferencedVariables(body, list);
608 for (Binding b : list) {
609 if (b instanceof GlobalVariable) {
610 ((GlobalVariable) b).lookForCycles(referees, globalFunctionLibrary);
611 }
612 }
613 List<SymbolicName> flist = new ArrayList<>();
614 ExpressionTool.gatherCalledFunctionNames(body, flist);
615 for (SymbolicName s : flist) {
616 XQueryFunction qf = globalFunctionLibrary.getDeclarationByKey(s);
617 if (!referees.contains(qf)) {
618 // recursive function calls are allowed
619 lookForFunctionCycles(qf, referees, globalFunctionLibrary);
620 }
621 }
622 referees.pop();
623 }
624
625 /**
626 * Evaluate the variable. That is,
627 * get the value of the select expression if present or the content
628 * of the element otherwise, either as a tree or as a sequence
629 * @param context the dynamic evaluation context
630 * @param target the component representing the variable to be evaluated
631 * @return the value of the variable
632 * @throws XPathException if a dynamic error occurs during evaluation
633 */
634
635 public GroundedValue<?> getSelectValue(XPathContext context, Component target) throws XPathException {
636 if (select == null) {
637 throw new AssertionError("*** No select expression for global variable $" +
638 getVariableQName().getDisplayName() + "!!");
639 } else if (select instanceof Literal) {
640 // fast path for constant global variables
641 return ((Literal)select).getValue();
642 } else {
643 try {
644 Controller controller = context.getController();
645 Executable exec = controller.getExecutable();
646 boolean hasAccessToGlobalContext = true;
647 if (exec instanceof PreparedStylesheet) {
648 hasAccessToGlobalContext = target == null || target.getDeclaringPackage() == ((PreparedStylesheet) exec).getTopLevelPackage();
649 }
650 XPathContextMajor c2 = context.newCleanContext();
651 c2.setOrigin(this);
652 if (hasAccessToGlobalContext) {
653 ManualIterator<?> mi =
654 new ManualIterator<>(context.getController().getGlobalContextItem());
655 c2.setCurrentIterator(mi);
656 } else {
657 c2.setCurrentIterator(null);
658 }
659 if (getStackFrameMap() != null) {
660 c2.openStackFrame(getStackFrameMap());
661 }
662 c2.setCurrentComponent(target);
663 int savedOutputState = c2.getTemporaryOutputState();
664 c2.setTemporaryOutputState(StandardNames.XSL_VARIABLE);
665 c2.setCurrentOutputUri(null);
666 GroundedValue<?> result;
667 if (indexed) {
668 result = c2.getConfiguration().makeSequenceExtent(select, FilterExpression.FILTERED, c2);
669 } else {
670 result = select.iterate(c2).materialize();
671 }
672 c2.setTemporaryOutputState(savedOutputState);
673 return result;
674 } catch (XPathException e) {
675 if (!getVariableQName().hasURI(NamespaceConstant.SAXON_GENERATED_VARIABLE)) {
676 e.setIsGlobalError(true);
677 }
678 throw e;
679 }
680 }
681 }
682
683 /**
684 * Evaluate the variable
685 */
686
687 public GroundedValue<?> evaluateVariable(XPathContext context) throws XPathException {
688 final Controller controller = context.getController();
689 assert controller != null;
690 final Bindery b = controller.getBindery(getPackageData());
691
692 final GroundedValue<?> v = b.getGlobalVariable(getBinderySlotNumber());
693
694 if (v != null) {
695 return v;
696 } else {
697 return actuallyEvaluate(context, null);
698 }
699 }
700
701 /**
702 * Evaluate the variable
703 */
704
705 public GroundedValue evaluateVariable(XPathContext context, Component target) throws XPathException {
706 final Controller controller = context.getController();
707 assert controller != null;
708 Bindery b = controller.getBindery(getPackageData());
709 if (b == null) {
710 // This is to handle those paths that haven't properly adjusted to multiple binderies...
711 throw new AssertionError();
712 //b = controller.getTopLevelBindery();
713 }
714 final GroundedValue v = b.getGlobalVariable(getBinderySlotNumber());
715
716 if (v != null) {
717 if (v instanceof Bindery.FailureValue) {
718 throw ((Bindery.FailureValue)v).getObject();
719 }
720 return v;
721 } else {
722 return actuallyEvaluate(context, target);
723 }
724 }
725
726 /**
727 * Evaluate the global variable, and save its value for use in subsequent references.
728 *
729 * @param context the XPath dynamic context
730 * @param target the component representing this variable (in the context of a package where it is used)
731 * @return the value of the variable
732 * @throws XPathException if evaluation fails
733 */
734
735 protected GroundedValue<?> actuallyEvaluate(XPathContext context, Component target) throws XPathException {
736 final Controller controller = context.getController();
737 assert controller != null;
738 final Bindery b = controller.getBindery(getPackageData());
739
740 try {
741 // This is the first reference to a global variable; try to evaluate it now.
742 // But first check for circular dependencies.
743 setDependencies(this, context);
744
745 // Set a flag to indicate that the variable is being evaluated. This is designed to prevent
746 // (where possible) the same global variable being evaluated several times in different threads
747 boolean go = b.setExecuting(this);
748 if (!go) {
749 // some other thread has evaluated the variable while we were waiting
750 return b.getGlobalVariable(getBinderySlotNumber());
751 }
752
753 GroundedValue<?> value = getSelectValue(context, target);
754 if (indexed) {
755 value = controller.getConfiguration().obtainOptimizer().makeIndexedValue(value.iterate());
756 }
757 return b.saveGlobalVariableValue(this, value);
758
759 } catch (XPathException err) {
760 b.setNotExecuting(this);
761 if (err instanceof XPathException.Circularity) {
762 String errorCode;
763 if (getPackageData().getHostLanguage() == Configuration.XSLT) {
764 errorCode = "XTDE0640";
765 } else {
766 errorCode = "XQDY0054";
767 }
768 err.setErrorCode(errorCode);
769 err.setXPathContext(context);
770 err.setIsGlobalError(true);
771 // Detect it more quickly the next time (in a pattern, the error is recoverable)
772 b.setGlobalVariable(this, new Bindery.FailureValue(err));
773 err.setLocation(getLocation());
774 throw err;
775 } else {
776 throw err;
777 }
778 }
779 }
780
781 /**
782 * Get the variable that is immediately dependent on this one, and register the dependency, so
783 * that circularities can be detected across threads. This relies on the fact that when the initialiser
784 * for variable X contains a reference to variable Y, then when Y is evaluated, a stack frame will be found
785 * on the context stack representing the evaluation of X. We don't set a dependency from X to Y if the value
786 * of Y was already available in the Bindery; it's not needed, because in this case we know that evaluation
787 * of Y is unproblematic, and can't lead to any circularities.
788 * @param var the global variable or parameter being evaluated
789 * @param context the dynamic evaluation context
790 */
791
792 protected static void setDependencies(GlobalVariable var, XPathContext context) throws XPathException {
793 Controller controller = context.getController();
794 if (!(context instanceof XPathContextMajor)) {
795 context = getMajorCaller(context);
796 }
797 while (context != null) {
798 do {
799 ContextOriginator origin = ((XPathContextMajor) context).getOrigin();
800 if (origin instanceof GlobalVariable) {
801 controller.registerGlobalVariableDependency((GlobalVariable) origin, var);
802 return;
803 }
804 context = getMajorCaller(context);
805 } while (context != null);
806 }
807 }
808
809 private static XPathContextMajor getMajorCaller(XPathContext context) {
810 XPathContext caller = context.getCaller();
811 while (!(caller == null || caller instanceof XPathContextMajor)) {
812 caller = caller.getCaller();
813 }
814 return (XPathContextMajor) caller;
815 }
816
817 /**
818 * If the variable is bound to an integer, get the minimum and maximum possible values.
819 * Return null if unknown or not applicable
820 *
821 * @return a pair of integers containing the minimum and maximum values for the integer value;
822 * or null if the value is not an integer or the range is unknown
823 */
824 public IntegerValue[] getIntegerBoundsForVariable() {
825 return select==null ? null : select.getIntegerBounds();
826 }
827
828 /**
829 * If this is a local variable held on the local stack frame, return the corresponding slot number.
830 * In other cases, return -1.
831 *
832 * @return the slot number on the local stack frame
833 */
834 public int getLocalSlotNumber() {
835 return 0; //To change body of implemented methods use File | Settings | File Templates.
836 }
837
838 /**
839 * Set the name of the variable
840 *
841 * @param s the name of the variable (a QName)
842 */
843
844 public void setVariableQName(StructuredQName s) {
845 variableQName = s;
846 }
847
848 /**
849 * Get the name of the variable
850 *
851 * @return the name of the variable, as a structured QName
852 */
853 public StructuredQName getVariableQName() {
854 return variableQName;
855 }
856
857 /**
858 * Register a variable reference that refers to the variable bound in this expression
859 *
860 * @param ref the variable reference to be registered
861 * @param isLoopingReference - true if the reference occurs within a loop, such as the predicate
862 * of a filter expression
863 */
864 public void addReference(VariableReference ref, boolean isLoopingReference) {
865 // No action
866 }
867
868 /**
869 * Get the kind of component that this represents, using integer constants such as
870 * {@link net.sf.saxon.om.StandardNames#XSL_FUNCTION}
871 */
872 @Override
873 public int getComponentKind() {
874 return StandardNames.XSL_VARIABLE;
875 }
876
877 /**
878 * Diagnostic print of expression structure. The abstract expression tree
879 * is written to the supplied outputstream.
880 *
881 * @param presenter the expression presenter used to display the structure
882 */
883 @Override
884 public void export(ExpressionPresenter presenter) throws XPathException {
885 boolean asParam = this instanceof GlobalParam && !isStatic(); // bug 4035: export static params as variables
886 presenter.startElement(asParam ? "globalParam" : "globalVariable");
887 presenter.emitAttribute("name", getVariableQName());
888 presenter.emitAttribute("type", getRequiredType().toExportString());
889 ExpressionPresenter.ExportOptions options = (ExpressionPresenter.ExportOptions) presenter.getOptions();
890 if (options.target != null && options.target.equals("JS") && options.targetVersion == 2) {
891 presenter.emitAttribute("typeJ", getRequiredType().toExportString2());
892 }
893 presenter.emitAttribute("line", getLineNumber() + "");
894 presenter.emitAttribute("module", getSystemId());
895 if (getStackFrameMap() != null) {
896 presenter.emitAttribute("slots", getStackFrameMap().getNumberOfVariables() + "");
897 }
898 if (getDeclaringComponent() != null) {
899 Visibility vis = getDeclaringComponent().getVisibility();
900 if (vis != null) {
901 presenter.emitAttribute("visibility", vis.toString());
902 }
903 }
904 String flags = getFlags();
905 if (!flags.isEmpty()) {
906 presenter.emitAttribute("flags", flags);
907 }
908
909 if ("JS".equals(((ExpressionPresenter.ExportOptions) presenter.getOptions()).target)) {
910 int targetVersion = ((ExpressionPresenter.ExportOptions) presenter.getOptions()).targetVersion;
911 presenter.emitAttribute("jsAcceptor", getRequiredType().getPrimaryType().generateJavaScriptItemTypeAcceptor("XTTE0590", targetVersion));
912 presenter.emitAttribute("jsCardCheck", Cardinality.generateJavaScriptChecker(getRequiredType().getCardinality()));
913 }
914
915 if (getSelectExpression() != null) {
916 getSelectExpression().export(presenter);
917 }
918 presenter.endElement();
919 }
920
921 protected String getFlags() {
922 String flags = "";
923 if (isAssignable) {
924 flags += "a";
925 }
926 if (indexed) {
927 flags += "x";
928 }
929 if (isRequiredParam) {
930 flags += "r";
931 }
932 return flags;
933 }
934 }
935