Debian Codegraph @

net/sf/saxon/event/StartTagBuffer.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.event;
9
10 import net.sf.saxon.expr.parser.ExplicitLocation;
11 import net.sf.saxon.expr.parser.Location;
12 import net.sf.saxon.lib.NamespaceConstant;
13 import net.sf.saxon.om.*;
14 import net.sf.saxon.trans.XPathException;
15 import net.sf.saxon.tree.util.AttributeCollectionImpl;
16 import net.sf.saxon.type.SchemaType;
17 import net.sf.saxon.type.SimpleType;
18 import net.sf.saxon.type.Type;
19
20 import java.util.ArrayList;
21 import java.util.Arrays;
22 import java.util.Iterator;
23 import java.util.List;
24
25 /**
26 * StartTagBuffer is a ProxyReceiver that buffers attributes and namespace events within a start tag.
27 * It maintains details of the namespace context, and a full set of attribute information, on behalf
28 * of other filters that need access to namespace information or need to process attributes in arbitrary
29 * order.
30 * <p>StartTagBuffer also implements namespace fixup (the process of creating namespace nodes|bindings on behalf
31 * of constructed element and attribute nodes). Although this would be done anyway, further down the pipeline,
32 * it has to be done early in the case of a validating pipeline, because the namespace bindings must be created
33 * before any namespace-sensitive attribute content is validated.</p>
34 * <p>The StartTagBuffer also allows error conditions to be buffered. This is because the XSIAttributeHandler
35 * validates attributes such as xsi:type and xsi:nil before attempting to match its parent element against
36 * a particle of its containing type. It is possible that the parent element will match a wildcard particle
37 * with processContents="skip", in which case an invalid xsi:type or xsi:nil attribute is not an error.</p>
38 */
39
40 public class StartTagBuffer extends ProxyReceiver implements NamespaceResolver {
41
42 public StartTagBuffer(Receiver next) {
43 super(next);
44 }
45
46 // Details of the pending element event
47
48 protected NodeName elementNameCode;
49 protected SchemaType elementTypeCode;
50 protected Location elementLocationId;
51 protected int elementProperties;
52
53 // Details of pending attribute events
54
55 protected AttributeCollectionImpl bufferedAttributes;
56 private boolean acceptAttributes;
57 private boolean inDocument;
58 private boolean inStartTag;
59
60 // We keep track of namespaces. The namespaces
61 // array holds a list of all namespaces currently declared (organised as pairs of entries,
62 // prefix followed by URI). The stack contains an entry for each element currently open; the
63 // value on the stack is an Integer giving the number of namespaces added to the main
64 // namespace stack by that element.
65
66 protected NamespaceBinding[] namespaces = new NamespaceBinding[50]; // all namespaces currently declared
67 protected int namespacesSize = 0; // all namespaces currently declared
68 private int[] countStack = new int[50];
69 private int depth = 0;
70 private int attCount = 0;
71
72 // The preceding filter in the pipeline can notify this class, immediately before calling startContent(),
73 // that the current element node has children
74
75 private boolean hasChildren = false;
76
77 /**
78 * Set the pipeline configuration
79 *
80 * @param pipe the pipeline configuration
81 */
82
83 public void setPipelineConfiguration(/*@NotNull*/ PipelineConfiguration pipe) {
84 super.setPipelineConfiguration(pipe);
85 bufferedAttributes = new AttributeCollectionImpl(pipe.getConfiguration());
86 }
87
88 /**
89 * Start of a document node.
90 */
91
92 public void startDocument(int properties) throws XPathException {
93 // a document node in the content sequence of an element is ignored. However, we need
94 // to stop attributes being created within the document node.
95 if (depth == 0) {
96 depth++;
97 super.startDocument(properties);
98 }
99 acceptAttributes = false;
100 inDocument = true; // we ought to clear this on endDocument, but it only affects diagnostics
101 inStartTag = false;
102 }
103
104
105 /**
106 * Notify the end of a document node
107 */
108
109 public void endDocument() throws XPathException {
110 if (depth == 1) {
111 depth--;
112 super.endDocument();
113 }
114 }
115
116 /**
117 * startElement
118 */
119
120 public void startElement(NodeName nameCode, SchemaType typeCode, Location location, int properties) throws XPathException {
121
122 maybeStartContent();
123
124 elementNameCode = nameCode;
125 elementTypeCode = typeCode;
126 elementLocationId = location.saveLocation();
127 elementProperties = properties;
128
129 bufferedAttributes.clear();
130 hasChildren = false;
131
132 // Record the current height of the namespace list so it can be reset at endElement time
133
134 countStack[depth] = 0;
135 if (++depth >= countStack.length) {
136 countStack = Arrays.copyOf(countStack, depth * 2);
137 }
138
139 // Ensure that the element namespace is output, unless this is done
140 // automatically by the caller (which is true, for example, for a literal
141 // result element).
142
143 acceptAttributes = true;
144 inDocument = false;
145 if ((properties & ReceiverOptions.NAMESPACE_OK) == 0) {
146 namespace(nameCode.getNamespaceBinding(), 0);
147 }
148 attCount = 0;
149 inStartTag = true;
150 }
151
152 public void namespace(NamespaceBindingSet namespaceBindings, int properties) throws XPathException {
153
154 for (NamespaceBinding ns : namespaceBindings) {
155 if (!acceptAttributes) {
156 throw NoOpenStartTagException.makeNoOpenStartTagException(
157 Type.NAMESPACE, ns.getPrefix(),
158 getPipelineConfiguration().getHostLanguage(),
159 inDocument, ExplicitLocation.UNKNOWN_LOCATION);
160 }
161
162 // avoid duplicates
163 boolean duplicate = false;
164 for (int n = 0; n < countStack[depth - 1]; n++) {
165 if (namespaces[namespacesSize - 1 - n].equals(ns)) {
166 duplicate = true;
167 break;
168 }
169 }
170 if (!duplicate) {
171 addToStack(ns);
172 countStack[depth - 1]++;
173 }
174 }
175 }
176
177 /**
178 * Notify an attribute. Attributes are notified after the startElement event, and before any
179 * children. Namespaces and attributes may be intermingled.
180 *
181 * @param attName The name of the attribute
182 * @param typeCode The type of the attribute
183 * @param locationId the location of the node in the source, or of the instruction that created it
184 * @param properties Bit significant value. The following bits are defined:
185 * <dl>
186 * <dd>DISABLE_ESCAPING</dd> <dt>Disable escaping for this attribute</dt>
187 * <dd>NO_SPECIAL_CHARACTERS</dd> <dt>Attribute value contains no special characters</dt>
188 * </dl>
189 * @throws IllegalStateException: attempt to output an attribute when there is no open element
190 * start tag
191 */
192
193 public void attribute(NodeName attName, SimpleType typeCode, CharSequence value, Location locationId, int properties)
194 throws XPathException {
195
196 if (!acceptAttributes) {
197 throw NoOpenStartTagException.makeNoOpenStartTagException(
198 Type.ATTRIBUTE, attName.getDisplayName(),
199 getPipelineConfiguration().getHostLanguage(),
200 inDocument, ExplicitLocation.UNKNOWN_LOCATION);
201 }
202
203 // Perform namespace fixup for the attribute
204
205 if (((properties & ReceiverOptions.NAMESPACE_OK) == 0) &&
206 !attName.hasURI("")) { // non-null prefix
207 attName = checkProposedPrefix(attName, attCount++);
208 }
209 bufferedAttributes.addAttribute(attName, typeCode, value.toString(), locationId, properties);
210
211 // Note: we're relying on the fact that AttributeCollection can hold two attributes of the same name
212 // and maintain their order, because the check for duplicate attributes is not done until later in the
213 // pipeline. We validate both the attributes (see Bugzilla #4600 which legitimizes this.)
214
215 }
216
217 /**
218 * Add a namespace declaration (or undeclaration) to the stack
219 *
220 * @param binding the namespace binding for the declaration
221 */
222
223 private void addToStack(NamespaceBinding binding) {
224 // expand the stack if necessary
225 if (namespacesSize + 1 >= namespaces.length) {
226 namespaces = Arrays.copyOf(namespaces, namespacesSize * 2);
227 }
228 namespaces[namespacesSize++] = binding;
229 }
230
231 public void setHasChildren(boolean hasChildren) {
232 this.hasChildren = hasChildren;
233 }
234
235 /**
236 * startContent: Add any namespace undeclarations needed to stop
237 * namespaces being inherited from parent elements
238 */
239
240 public void startContent() throws XPathException {
241 inStartTag = false;
242 int props = elementProperties | ReceiverOptions.NAMESPACE_OK;
243 if (hasChildren) {
244 props |= ReceiverOptions.HAS_CHILDREN;
245 }
246 nextReceiver.startElement(elementNameCode, elementTypeCode, elementLocationId, props);
247 declareNamespacesForStartElement();
248
249 final int length = bufferedAttributes.getLength();
250 for (int i = 0; i < length; i++) {
251 nextReceiver.attribute(bufferedAttributes.getNodeName(i),
252 bufferedAttributes.getTypeAnnotation(i),
253 bufferedAttributes.getValue(i),
254 bufferedAttributes.getLocation(i),
255 bufferedAttributes.getProperties(i) | ReceiverOptions.NAMESPACE_OK);
256 }
257 acceptAttributes = false;
258 nextReceiver.startContent();
259 }
260
261 private void maybeStartContent() throws XPathException {
262 if (inStartTag) {
263 startContent();
264 }
265 }
266
267 protected void declareNamespacesForStartElement() throws XPathException {
268 for (int i = namespacesSize - countStack[depth - 1]; i < namespacesSize; i++) {
269 nextReceiver.namespace(namespaces[i], 0);
270 }
271 }
272
273 /**
274 * Get the namespaces declared (or undeclared) at the current level
275 *
276 * @return an array of namespace bindings
277 */
278
279 public NamespaceBinding[] getLocalNamespaces() {
280 int size = countStack[depth - 1];
281 if (size == 0) {
282 return NamespaceBinding.EMPTY_ARRAY;
283 } else {
284 NamespaceBinding[] localBindings = new NamespaceBinding[countStack[depth - 1]];
285 System.arraycopy(namespaces, namespacesSize - size, localBindings, 0, size);
286 return localBindings;
287 }
288 }
289
290 /**
291 * Signal namespace events for all in-scope namespaces to the current receiver in the pipeline
292 *
293 * @throws XPathException if any downstream error occurs
294 */
295
296 protected void declareAllNamespaces() throws XPathException {
297 for (int i = 0; i < namespacesSize; i++) {
298 nextReceiver.namespace(namespaces[i], 0);
299 }
300 }
301
302 /**
303 * endElement: Discard the namespaces declared locally on this element.
304 */
305
306 public void endElement() throws XPathException {
307 maybeStartContent();
308 nextReceiver.endElement();
309 undeclareNamespacesForElement();
310 }
311
312 protected void undeclareNamespacesForElement() {
313 namespacesSize -= countStack[--depth];
314 }
315
316 /**
317 * Determine if the current element has any attributes
318 *
319 * @return true if the element has one or more attributes
320 */
321
322 public boolean hasAttributes() {
323 return bufferedAttributes.getLength() > 0;
324 }
325
326 /**
327 * Get the value of the current attribute with a given nameCode
328 *
329 * @param nameCode the name of the required attribute
330 * @return the attribute value, or null if the attribute is not present
331 */
332
333 public String getAttribute(int nameCode) {
334 return bufferedAttributes.getValueByFingerprint(nameCode & 0xfffff);
335 }
336
337 /**
338 * Get the value of the current attribute with a given name
339 *
340 * @param uri the uri of the name of the required attribute
341 * @param local the local part of the name of the required attribute
342 * @return the attribute value, or null if the attribute is not present
343 */
344
345 public String getAttribute(String uri, String local) {
346 return bufferedAttributes.getValue(uri, local);
347 }
348
349 /**
350 * Get all the attributes on the current element start tag
351 *
352 * @return an AttributeCollection containing all the attributes
353 */
354
355 public AttributeCollection getAllAttributes() {
356 return bufferedAttributes;
357 }
358
359 /**
360 * Ask whether the attribute collection contains any attributes
361 * in a specified namespace
362 *
363 * @param uri the specified namespace
364 * @return true if there are one or more attributes in this namespace
365 */
366
367 public boolean hasAttributeInNamespace(String uri) {
368 return bufferedAttributes.hasAttributeInNamespace(uri);
369 }
370
371 /**
372 * Get the namespace URI corresponding to a given prefix. Return null
373 * if the prefix is not in scope. f
374 *
375 * @param prefix the namespace prefix
376 * @param useDefault true if the default namespace is to be used when the
377 * prefix is ""
378 * @return the uri for the namespace, or null if the prefix is not in scope
379 */
380
381 /*@Nullable*/
382 public String getURIForPrefix(String prefix, boolean useDefault) {
383 if (prefix.isEmpty() && !useDefault) {
384 return NamespaceConstant.NULL;
385 } else if ("xml".equals(prefix)) {
386 return NamespaceConstant.XML;
387 } else {
388 for (int i = namespacesSize - 1; i >= 0; i--) {
389 if (namespaces[i].getPrefix().equals(prefix)) {
390 String uri = namespaces[i].getURI();
391 if (uri.isEmpty()) {
392 // // we've found a namespace undeclaration, so it's as if the prefix weren't there at all
393 } else {
394 return uri;
395 }
396 }
397 }
398 }
399 return (prefix.isEmpty() ? NamespaceConstant.NULL : null);
400 }
401
402 /**
403 * Get an iterator over all the prefixes declared in this namespace context. This will include
404 * the default namespace (prefix="") and the XML namespace where appropriate
405 */
406
407 public Iterator<String> iteratePrefixes() {
408 List<String> prefixes = new ArrayList<String>(namespacesSize);
409 for (int i = namespacesSize - 1; i >= 0; i--) {
410 String prefix = namespaces[i].getPrefix();
411 if (!prefixes.contains(prefix)) {
412 prefixes.add(prefix);
413 }
414 }
415 prefixes.add("xml");
416 return prefixes.iterator();
417 }
418
419 /**
420 * Check that the prefix for an element or attribute is acceptable, allocating a substitute
421 * prefix if not. The prefix is acceptable unless a namespace declaration has been
422 * written that assignes this prefix to a different namespace URI. This method
423 * also checks that the element or attribute namespace has been declared, and declares it
424 * if not.
425 *
426 * @param nameCode the proposed element or attribute name
427 * @param seq sequence number of attribute, used for generating distinctive prefixes
428 * @return the actual allocated name, which may be different.
429 * @throws net.sf.saxon.trans.XPathException
430 * if any error occurs writing the new namespace binding
431 */
432
433 private NodeName checkProposedPrefix(NodeName nameCode, int seq) throws XPathException {
434 NamespaceBinding binding = nameCode.getNamespaceBinding();
435 String prefix = binding.getPrefix();
436
437 String existingURI = getURIForPrefix(prefix, true);
438 if (existingURI == null) {
439 // prefix has not been declared: declare it now (namespace fixup)
440 namespace(binding, 0);
441 return nameCode;
442 } else {
443 if (binding.getURI().equals(existingURI)) {
444 // prefix is already bound to this URI
445 return nameCode; // all is well
446 } else {
447 // conflict: prefix is currently bound to a different URI
448 prefix = getSubstitutePrefix(binding, seq);
449
450 NodeName newCode = new FingerprintedQName(
451 prefix,
452 nameCode.getURI(),
453 nameCode.getLocalPart());
454 namespace(newCode.getNamespaceBinding(), 0);
455 return newCode;
456 }
457 }
458 }
459
460 /**
461 * It is possible for a single output element to use the same prefix to refer to different
462 * namespaces. In this case we have to generate an alternative prefix for uniqueness. The
463 * one we generate is based on the sequential position of the element/attribute: this is
464 * designed to ensure both uniqueness (with a high probability) and repeatability
465 *
466 * @param binding the namespace binding of the proposed element or attribute name
467 * @param seq sequence number of attribute, used for generating distinctive prefixes
468 * @return the actual allocated name, which may be different.
469 */
470
471 private String getSubstitutePrefix(NamespaceBinding binding, int seq) {
472 String prefix = binding.getPrefix();
473 return prefix + '_' + seq;
474 }
475
476 /**
477 * Character data
478 *
479 * @param chars
480 * @param locationId the location of the node in the source, or of the instruction that created it
481 * @param properties
482 */
483 @Override
484 public void characters(CharSequence chars, Location locationId, int properties) throws XPathException {
485 maybeStartContent();
486 nextReceiver.characters(chars, locationId, properties);
487 }
488
489 /**
490 * Processing Instruction
491 *
492 * @param target
493 * @param data
494 * @param locationId the location of the node in the source, or of the instruction that created it
495 * @param properties
496 */
497 @Override
498 public void processingInstruction(String target, CharSequence data, Location locationId, int properties) throws XPathException {
499 maybeStartContent();
500 nextReceiver.processingInstruction(target, data, locationId, properties);
501 }
502
503 /**
504 * Output a comment
505 *
506 * @param chars
507 * @param locationId the location of the node in the source, or of the instruction that created it
508 * @param properties
509 */
510 @Override
511 public void comment(CharSequence chars, Location locationId, int properties) throws XPathException {
512 maybeStartContent();
513 nextReceiver.comment(chars, locationId, properties);
514 }
515 }
516