Debian Codegraph @

net/sf/saxon/trace/ExpressionPresenter.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.trace;
9
10 import net.sf.saxon.Configuration;
11 import net.sf.saxon.event.CheckSumFilter;
12 import net.sf.saxon.event.NamespaceReducer;
13 import net.sf.saxon.event.Receiver;
14 import net.sf.saxon.expr.Component;
15 import net.sf.saxon.expr.Expression;
16 import net.sf.saxon.expr.parser.ExplicitLocation;
17 import net.sf.saxon.expr.parser.RetainedStaticContext;
18 import net.sf.saxon.lib.Logger;
19 import net.sf.saxon.lib.NamespaceConstant;
20 import net.sf.saxon.lib.SaxonOutputKeys;
21 import net.sf.saxon.om.*;
22 import net.sf.saxon.serialize.SerializationProperties;
23 import net.sf.saxon.serialize.charcode.UTF16CharacterSet;
24 import net.sf.saxon.style.StylesheetPackage;
25 import net.sf.saxon.trans.XPathException;
26 import net.sf.saxon.tree.util.FastStringBuffer;
27 import net.sf.saxon.type.BuiltInAtomicType;
28 import net.sf.saxon.type.TypeHierarchy;
29 import net.sf.saxon.type.Untyped;
30 import net.sf.saxon.value.Whitespace;
31
32 import javax.xml.transform.OutputKeys;
33 import javax.xml.transform.stream.StreamResult;
34 import java.util.Iterator;
35 import java.util.Map;
36 import java.util.Stack;
37
38 /**
39 * This class handles the display of an abstract expression tree in an XML format
40 * with some slight resemblance to XQueryX
41 */
42 public class ExpressionPresenter {
43
44 private Configuration config;
45 private Receiver receiver;
46 private int depth = 0;
47 private boolean inStartTag = false;
48 private String nextRole = null;
49 private Stack<Expression> expressionStack = new Stack<Expression>();
50 private Stack<String> nameStack = new Stack<String>();
51 private String defaultNamespace;
52 private Options options = new ExportOptions();
53 private boolean relocatable = false;
54
55 /**
56 * Make an uncommitted ExpressionPresenter. This must be followed by a call on init()
57 */
58
59 public ExpressionPresenter() {}
60
61 /**
62 * Make an ExpressionPresenter that writes indented output to the standard error output
63 * destination of the Configuration
64 *
65 * @param config the Saxon configuration
66 */
67
68 public ExpressionPresenter(/*@NotNull*/ Configuration config) {
69 this(config, config.getLogger());
70 }
71
72 /**
73 * Make an ExpressionPresenter that writes indented output to a specified output stream
74 *
75 * @param config the Saxon configuration
76 * @param out the output destination
77 */
78
79 public ExpressionPresenter(Configuration config, StreamResult out) {
80 this(config, out, false);
81 }
82
83 /**
84 * Make an ExpressionPresenter that writes indented output to a specified output stream,
85 * with checksumming
86 *
87 * @param config the Saxon configuration
88 * @param out the output destination
89 * @param checksum true if a checksum is to be written at the end of the file
90 */
91
92 public ExpressionPresenter(Configuration config, StreamResult out, boolean checksum) {
93 init(config, out, checksum);
94 }
95
96 /**
97 * Make an ExpressionPresenter that writes indented output to a specified output stream,
98 * with checksumming
99 *
100 * @param config the Saxon configuration
101 * @param out the output destination
102 * @param checksum true if a checksum is to be written at the end of the file
103 */
104
105 public void init(Configuration config, StreamResult out, boolean checksum) {
106 SerializationProperties props = makeDefaultProperties(config);
107 if (config.getXMLVersion() == Configuration.XML11) {
108 if ("JS".equals(((ExportOptions) getOptions()).target)) {
109 config.getLogger().warning("For target=JS, the SEF file will use XML 1.0, which disallows control characters");
110 } else {
111 props.setProperty(OutputKeys.VERSION, "1.1");
112 }
113 }
114 try {
115 receiver = config.getSerializerFactory().getReceiver(out, props);
116 receiver = new NamespaceReducer(receiver);
117 if (checksum) {
118 receiver = new CheckSumFilter(receiver);
119 }
120 } catch (XPathException err) {
121 err.printStackTrace();
122 throw new InternalError(err.getMessage());
123 }
124 this.config = config;
125 try {
126 receiver.open();
127 receiver.startDocument(0);
128 } catch (XPathException err) {
129 err.printStackTrace();
130 throw new InternalError(err.getMessage());
131 }
132 }
133
134 /**
135 * Make an ExpressionPresenter that writes indented output to a specified output stream,
136 * with checksumming
137 *
138 * @param config the Saxon configuration
139 * @param out the output destination
140 * @param checksum true if a checksum is to be written at the end of the file
141 */
142
143 public void init(Configuration config, Receiver out, boolean checksum) {
144
145 receiver = out;
146 receiver = new NamespaceReducer(receiver);
147 if (checksum) {
148 receiver = new CheckSumFilter(receiver);
149 }
150
151 this.config = config;
152 try {
153 receiver.open();
154 receiver.startDocument(0);
155 } catch (XPathException err) {
156 err.printStackTrace();
157 throw new InternalError(err.getMessage());
158 }
159 }
160
161
162 /**
163 * Make an ExpressionPresenter that writes indented output to a specified output stream
164 *
165 * @param config the Saxon configuration
166 * @param out the output stream
167 */
168
169 public ExpressionPresenter(Configuration config, Logger out) {
170 this(config, out.asStreamResult());
171 }
172
173 /**
174 * Make an ExpressionPresenter for a given Configuration using a user-supplied Receiver
175 * to accept the output
176 *
177 * @param config the Configuration
178 * @param receiver the user-supplied Receiver
179 */
180
181 public ExpressionPresenter(Configuration config, /*@NotNull*/ Receiver receiver) {
182 this.config = config;
183 this.receiver = receiver;
184 try {
185 receiver.open();
186 receiver.startDocument(0);
187 } catch (XPathException err) {
188 err.printStackTrace();
189 throw new InternalError(err.getMessage());
190 }
191 }
192
193 /**
194 * Set the default namespace, used for subsequent calls on startElement.
195 * Must be consistent throughout the whole document
196 *
197 * @param namespace the default namespace
198 */
199
200 public void setDefaultNamespace(String namespace) {
201 defaultNamespace = namespace;
202 }
203
204 /**
205 * Set the options
206 */
207
208 public void setOptions(Options options) {
209 this.options = options;
210 }
211
212 /**
213 * Get the options
214 *
215 * @return the options, or null if none have been set
216 */
217
218 public Options getOptions() {
219 return options;
220 }
221
222 /**
223 * Ask whether the package can be deployed to a different location, with a different base URI
224 *
225 * @return if true then static-base-uri() represents the deployed location of the package,
226 * rather than its compile time location
227 */
228
229 public boolean isRelocatable() {
230 return relocatable;
231 }
232
233 /**
234 * Say whether the package can be deployed to a different location, with a different base URI
235 *
236 * @param relocatable if true then static-base-uri() represents the deployed location of the package,
237 * rather than its compile time location
238 */
239
240 public void setRelocatable(boolean relocatable) {
241 this.relocatable = relocatable;
242 }
243
244
245 /**
246 * Make a receiver, using default output properties, with serialized output going
247 * to a specified OutputStream
248 *
249 * @param config the Configuration
250 * @param out the OutputStream
251 * @return a Receiver that directs serialized output to this output stream
252 * @throws XPathException
253 */
254
255 /*@Nullable*/
256 public static Receiver defaultDestination(/*@NotNull*/ Configuration config, Logger out) throws XPathException {
257 SerializationProperties props = makeDefaultProperties(config);
258 return config.getSerializerFactory().getReceiver(out.asStreamResult(), props);
259 }
260
261
262 /**
263 * Make a Properties object containing defaulted serialization attributes for the expression tree
264 *
265 * @return a default set of properties
266 */
267
268 /*@NotNull*/
269 public static SerializationProperties makeDefaultProperties(Configuration config) {
270 SerializationProperties props = new SerializationProperties();
271 props.setProperty(OutputKeys.METHOD, "xml");
272 props.setProperty(OutputKeys.INDENT, "yes");
273 if (config.isLicensedFeature(Configuration.LicenseFeature.PROFESSIONAL_EDITION)) {
274 props.setProperty(SaxonOutputKeys.INDENT_SPACES, "1");
275 props.setProperty(SaxonOutputKeys.LINE_LENGTH, "4096");
276 }
277 props.setProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
278 props.setProperty(OutputKeys.ENCODING, "utf-8");
279 props.setProperty(OutputKeys.VERSION, "1.0");
280 props.setProperty(SaxonOutputKeys.SINGLE_QUOTES, "yes");
281 return props;
282 }
283
284 /**
285 * Start an element representing an expression in the expression tree
286 *
287 * @param name the name of the element
288 * @param expr the expression represented
289 * @return the depth of the tree before this element: for diagnostics, this can be compared
290 * with the value returned by endElement
291 */
292
293 public int startElement(String name, Expression expr) {
294 Expression parent = expressionStack.isEmpty() ? null : expressionStack.peek();
295 expressionStack.push(expr);
296 nameStack.push("*" + name);
297 int n = _startElement(name);
298 if (parent == null || expr.getRetainedStaticContext() != parent.getRetainedStaticContext()) {
299 if (expr.getRetainedStaticContext() == null) {
300 throw new AssertionError("Export failure: no retained static context on " + expr.toShortString());
301 } else {
302 emitRetainedStaticContext(expr.getRetainedStaticContext(), parent == null ? null : parent.getRetainedStaticContext());
303 }
304 }
305 String mod = expr.getLocation().getSystemId();
306 if (mod != null && parent != null && (parent.getLocation().getSystemId() == null || !parent.getLocation().getSystemId().equals(mod))) {
307 emitAttribute("module", truncatedModuleName(mod));
308 }
309 int lineNr = expr.getLocation().getLineNumber();
310 if (parent == null || (parent.getLocation().getLineNumber() != lineNr && lineNr != -1)) {
311 emitAttribute("line", lineNr + "");
312 }
313 return n;
314 }
315
316 private String truncatedModuleName(String module) {
317 if (!relocatable) {
318 return module;
319 } else {
320 // If not exporting the base URI, cut the filename used for diagnostic location of errors down to its last component
321 String parts[] = module.split("/");
322 for (int p = parts.length - 1; p >= 0; p--) {
323 if (!parts[p].isEmpty()) {
324 return parts[p];
325 }
326 }
327 return module;
328 }
329 }
330
331 public void emitRetainedStaticContext(RetainedStaticContext sc, RetainedStaticContext parentSC) {
332 try {
333 if (!((ExportOptions) options).suppressStaticContext && !relocatable && sc.getStaticBaseUri() != null && (parentSC == null || !sc.getStaticBaseUri().equals(parentSC.getStaticBaseUri()))) {
334 emitAttribute("baseUri", sc.getStaticBaseUriString());
335 }
336 if (!sc.getDefaultCollationName().equals(NamespaceConstant.CODEPOINT_COLLATION_URI) &&
337 (parentSC == null || !sc.getDefaultCollationName().equals(parentSC.getDefaultCollationName()))) {
338 emitAttribute("defaultCollation", sc.getDefaultCollationName());
339 }
340 if (!sc.getDefaultElementNamespace().isEmpty() &&
341 (parentSC == null || !sc.getDefaultElementNamespace().equals(parentSC.getDefaultElementNamespace()))) {
342 emitAttribute("defaultElementNS", sc.getDefaultElementNamespace());
343 }
344 if (!NamespaceConstant.FN.equals(sc.getDefaultFunctionNamespace())) {
345 emitAttribute("defaultFunctionNS", sc.getDefaultFunctionNamespace());
346 }
347 if (!((ExportOptions)options).suppressStaticContext && (parentSC == null || !sc.declaresSameNamespaces(parentSC))) {
348 FastStringBuffer fsb = new FastStringBuffer(FastStringBuffer.C256);
349 for (Iterator<String> iter = sc.iteratePrefixes(); iter.hasNext(); ) {
350 String p = iter.next();
351
352 String uri = sc.getURIForPrefix(p, true);
353 fsb.append(p);
354 fsb.append("=");
355
356 if (Whitespace.containsWhitespace(uri)) {
357 throw new XPathException("Cannot export a stylesheet if namespaces contain whitespace: '" + uri + "'");
358 }
359 if (uri.equals(NamespaceConstant.getUriForConventionalPrefix(p))) {
360 uri = "~";
361 }
362 fsb.append(uri);
363 fsb.append(" ");
364
365 }
366 emitAttribute("ns", Whitespace.trim(fsb));
367 }
368 } catch (XPathException e) {
369 throw new AssertionError(e);
370 }
371 }
372
373 /**
374 * Start an element
375 *
376 * @param name the name of the element
377 * @return the depth of the tree before this element: for diagnostics, this can be compared
378 * with the value returned by endElement
379 */
380
381 public int startElement(String name) {
382 nameStack.push(name);
383 return _startElement(name);
384 }
385
386 private int _startElement(String name) {
387 //System.err.println("start " + name + " at " + new XPathException("").getStackTrace().length);
388 try {
389 if (inStartTag) {
390 receiver.startContent();
391 inStartTag = false;
392 }
393 NodeName nodeName;
394 if (defaultNamespace == null) {
395 nodeName = new NoNamespaceName(name);
396 } else {
397 nodeName = new FingerprintedQName("", defaultNamespace, name);
398 }
399 receiver.startElement(nodeName, Untyped.getInstance(), ExplicitLocation.UNKNOWN_LOCATION, 0);
400 if (nextRole != null) {
401 emitAttribute("role", nextRole);
402 nextRole = null;
403 }
404 } catch (XPathException err) {
405 err.printStackTrace();
406 throw new InternalError(err.getMessage());
407 }
408 inStartTag = true;
409 return depth++;
410 }
411
412 /**
413 * Set the role of the next element to be output
414 *
415 * @param role the value of the role output to be used
416 */
417
418 public void setChildRole(String role) {
419 nextRole = role;
420 }
421
422 /**
423 * Output an attribute node
424 *
425 * @param name the name of the attribute
426 * @param value the value of the attribute
427 */
428
429 public void emitAttribute(String name, String value) {
430 if (value != null) {
431 if (name.equals("module")) {
432 value = truncatedModuleName(value);
433 }
434 try {
435 receiver.attribute(new NoNamespaceName(name), BuiltInAtomicType.UNTYPED_ATOMIC, value, ExplicitLocation.UNKNOWN_LOCATION, 0);
436 } catch (XPathException err) {
437 err.printStackTrace();
438 throw new InternalError(err.getMessage());
439 }
440 }
441 }
442
443 /**
444 * Output a QName-valued attribute node
445 *
446 * @param name the name of the attribute
447 * @param value the value of the attribute
448 */
449
450 public void emitAttribute(String name, StructuredQName value) {
451 String attVal = value.getEQName();
452 // if (value.hasURI("") && value.getPrefix().isEmpty()) {
453 // attVal = value.getLocalPart();
454 // } else {
455 // String uri = value.getURI();
456 // String prefix = value.getPrefix();
457 // if (uri.equals(NamespaceConstant.getUriForConventionalPrefix(prefix))) {
458 // uri = "~";
459 // }
460 // attVal = prefix + "{" + uri + "}" + value.getLocalPart();
461 // }
462 try {
463 receiver.attribute(new NoNamespaceName(name), BuiltInAtomicType.UNTYPED_ATOMIC,
464 attVal, ExplicitLocation.UNKNOWN_LOCATION, 0);
465 } catch (XPathException err) {
466 err.printStackTrace();
467 throw new InternalError(err.getMessage());
468 }
469 //
470 // try {
471 // if (value.hasURI("")) {
472 // receiver.attribute(new NoNamespaceName(name), BuiltInAtomicType.UNTYPED_ATOMIC, value.getLocalPart(), ExplicitLocation.UNKNOWN_LOCATION, 0);
473 // } else if (value.getPrefix().isEmpty()) {
474 // String prefix = config.getNamePool().suggestPrefixForURI(value.getURI());
475 // if (prefix == null) {
476 // prefix = allocatePrefix(value.getURI());
477 // }
478 // receiver.namespace(new NamespaceBinding(prefix, value.getURI()), 0);
479 // receiver.attribute(new NoNamespaceName(name),
480 // BuiltInAtomicType.UNTYPED_ATOMIC, prefix + ":" + value.getLocalPart(), ExplicitLocation.UNKNOWN_LOCATION, 0);
481 // } else {
482 // receiver.namespace(new NamespaceBinding(value.getPrefix(), value.getURI()), 0);
483 // receiver.attribute(new NoNamespaceName(name),
484 // BuiltInAtomicType.UNTYPED_ATOMIC, value.getDisplayName(), ExplicitLocation.UNKNOWN_LOCATION, 0);
485 // }
486 // } catch (XPathException err) {
487 // err.printStackTrace();
488 // throw new InternalError(err.getMessage());
489 // }
490 }
491
492 private String allocatePrefix(String uri) {
493 if (uri.equals(NamespaceConstant.SCHEMA)) {
494 return "xs";
495 } else if (uri.equals(NamespaceConstant.FN)) {
496 return "fn";
497 } else if (uri.equals(NamespaceConstant.SAXON)) {
498 return "saxon";
499 } else {
500 int c = uri.lastIndexOf('/');
501 if (c == uri.length() - 1) {
502 c = uri.substring(0, uri.length() - 1).lastIndexOf('/');
503 }
504 if (c >= 0 && c + 3 < uri.length()) {
505 String prefix = uri.substring(c + 1, c + 3);
506 if (NameChecker.isValidNCName(prefix)) {
507 return prefix;
508 }
509 }
510 return "p";
511 }
512 }
513
514 /**
515 * Output a namespace declaration
516 *
517 * @param prefix the namespace prefix
518 * @param uri the namespace URI
519 */
520
521 public void namespace(String prefix, String uri) {
522 try {
523 receiver.namespace(new NamespaceBinding(prefix, uri), 0);
524 } catch (XPathException e) {
525 e.printStackTrace();
526 throw new InternalError(e.getMessage());
527 }
528 }
529
530 /**
531 * End an element in the expression tree
532 *
533 * @return the depth of the tree after ending this element. For diagnostics, this can be compared with the
534 * value returned by startElement()
535 */
536
537 public int endElement() {
538 //System.err.println("end at " + new XPathException("").getStackTrace().length);
539 try {
540 if (inStartTag) {
541 receiver.startContent();
542 inStartTag = false;
543 }
544 receiver.endElement();
545 } catch (XPathException err) {
546 err.printStackTrace();
547 throw new InternalError(err.getMessage());
548 }
549 String name = nameStack.pop();
550 if (name.startsWith("*")) {
551 expressionStack.pop();
552 }
553 return --depth;
554 }
555
556 /**
557 * Start a child element in the output
558 *
559 * @param name the name of the child element
560 */
561
562 public void startSubsidiaryElement(String name) {
563 startElement(name);
564 }
565
566 /**
567 * End a child element in the output
568 */
569
570 public void endSubsidiaryElement() {
571 endElement();
572 }
573
574 /**
575 * Close the output
576 */
577
578 public void close() {
579 try {
580 if (receiver instanceof CheckSumFilter) {
581 int c = ((CheckSumFilter) receiver).getChecksum();
582 receiver.processingInstruction(CheckSumFilter.SIGMA, Integer.toHexString(c), ExplicitLocation.UNKNOWN_LOCATION, 0);
583 }
584 receiver.endDocument();
585 receiver.close();
586 } catch (XPathException err) {
587 err.printStackTrace();
588 throw new InternalError(err.getMessage());
589 }
590 }
591
592
593 /**
594 * Get the Saxon configuration
595 *
596 * @return the Saxon configuration
597 */
598
599 public Configuration getConfiguration() {
600 return config;
601 }
602
603 /**
604 * Get the name pool
605 *
606 * @return the name pool
607 */
608
609 public NamePool getNamePool() {
610 return config.getNamePool();
611 }
612
613 /**
614 * Get the type hierarchy cache
615 *
616 * @return the type hierarchy cache
617 */
618
619 public TypeHierarchy getTypeHierarchy() {
620 return config.getTypeHierarchy();
621 }
622
623 /**
624 * Static method to escape a string using Javascript escaping conventions
625 * @param in the string to be escaped
626 */
627
628 public static String jsEscape(String in) {
629 FastStringBuffer out = new FastStringBuffer(in.length());
630 for (int i = 0; i < in.length(); i++) {
631 char c = in.charAt(i);
632 switch (c) {
633 case '\'':
634 out.append("\\\'");
635 break;
636 case '"':
637 out.append("\\\"");
638 break;
639 case '\b':
640 out.append("\\b");
641 break;
642 case '\f':
643 out.append("\\f");
644 break;
645 case '\n':
646 out.append("\\n");
647 break;
648 case '\r':
649 out.append("\\r");
650 break;
651 case '\t':
652 out.append("\\t");
653 break;
654 case '\\':
655 out.append("\\\\");
656 break;
657 default:
658 if (c < 32 || (c > 127 && c < 160) || c > UTF16CharacterSet.SURROGATE1_MIN) {
659 out.append("\\u");
660 String hex = Integer.toHexString(c).toUpperCase();
661 while (hex.length() < 4) {
662 hex = "0" + hex;
663 }
664 out.append(hex);
665 } else {
666 out.append(c);
667 }
668 }
669 }
670 return out.toString();
671 }
672
673 public interface Options {};
674
675 public static class ExportOptions implements Options {
676 public String target = "";
677 public int targetVersion = 0;
678 public StylesheetPackage rootPackage;
679 public Map<Component, Integer> componentMap;
680 public Map<StylesheetPackage, Integer> packageMap;
681 public boolean explaining;
682 public boolean suppressStaticContext;
683 public boolean addStaticType;
684 }
685 }
686