| 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.Location; |
| 11 | import net.sf.saxon.om.Item; |
| 12 | import net.sf.saxon.om.NamespaceBindingSet; |
| 13 | import net.sf.saxon.om.NodeName; |
| 14 | import net.sf.saxon.trans.XPathException; |
| 15 | import net.sf.saxon.type.SchemaType; |
| 16 | import net.sf.saxon.type.SimpleType; |
| 17 | |
| 18 | import java.util.HashMap; |
| 19 | import java.util.Map; |
| 20 | import java.util.Stack; |
| 21 | |
| 22 | /** |
| 23 | * A <tt>RegularSequenceChecker</tt> is a filter that can be inserted into a Receiver pipeline |
| 24 | * to check that the sequence of events passed in is a <b>regular event sequence</b>. Many |
| 25 | * (though not all) implementations of {@link Receiver} require the sequence of events to |
| 26 | * be regular according to this definition. |
| 27 | * <p>A sequence of {@code Receiver} events is <b>regular</b> if the following conditions |
| 28 | * are satisfied:</p> |
| 29 | * <ol> |
| 30 | * <li>Calls to {@link #startElement(NodeName, SchemaType, Location, int)}, {@link #endElement()}, |
| 31 | * {@link #startDocument(int)}, and {@link #endDocument()} are properly paired and nested.</li> |
| 32 | * <li>Events must only occur in a state where they are permitted; the states and transitions |
| 33 | * between states are defined by the table below. The initial state is <b>initial</b>, |
| 34 | * and the final state must be <b>final</b>.</li> |
| 35 | * </ol> |
| 36 | * <table> |
| 37 | * <thead> |
| 38 | * <tr><th>State</th><th>Events</th><th>Next State</th></tr> |
| 39 | * </thead> |
| 40 | * <tbody> |
| 41 | * <tr><td>initial</td><td>{@link #open()}</td><td>open</td></tr> |
| 42 | * <tr><td>open</td><td>{@link #open()}</td><td>open</td></tr> |
| 43 | * <tr><td>open</td><td>{@link #append(Item, Location, int)}, {@link #append(Item)}, |
| 44 | * {@link #attribute(NodeName, SimpleType, CharSequence, Location, int)}, {@link #namespace(NamespaceBindingSet, int)}, |
| 45 | * {@link #characters(CharSequence, Location, int)}, {@link #comment(CharSequence, Location, int)}, |
| 46 | * {@link #processingInstruction(String, CharSequence, Location, int)}</td><td>open</td></tr> |
| 47 | * <tr><td>open</td><td>{@link #startDocument(int)}</td><td>content</td></tr> |
| 48 | * <tr><td>open</td><td>{@link #startElement(NodeName, SchemaType, Location, int)}</td><td>startTag</td></tr> |
| 49 | * <tr><td>startTag</td><td>{@link #attribute(NodeName, SimpleType, CharSequence, Location, int)}, {@link #namespace(NamespaceBindingSet, int)}</td><td>startTag</td></tr> |
| 50 | * <tr><td>startTag</td><td>{@link #startContent()}</td><td>content</td></tr> |
| 51 | * <tr><td>content</td><td>{@link #characters(CharSequence, Location, int)}, {@link #comment(CharSequence, Location, int)}, |
| 52 | * {@link #processingInstruction(String, CharSequence, Location, int)}</td><td>content</td></tr> |
| 53 | * <tr><td>content</td><td>{@link #startElement(NodeName, SchemaType, Location, int)}</td><td>startTag</td></tr> |
| 54 | * <tr><td>content</td><td>{@link #endDocument()}, {@link #endElement()}</td><td>if the stack is empty, then content, otherwise open</td></tr> |
| 55 | * <tr><td>(any)</td><td>close</td><td>final</td></tr> |
| 56 | * <tr><td>final</td><td>close</td><td>final</td></tr> |
| 57 | * </tbody> |
| 58 | * </table> |
| 59 | * <p>This class is not normally used in production within Saxon, but is available for diagnostics when needed.</p> |
| 60 | * <p>Some implementations of {@code Receiver} accept sequences of events that are not regular; indeed, some |
| 61 | * implementations are explicitly designed to produce a regular sequence from an irregular sequence. |
| 62 | * Examples of such irregularities are <b>append</b> or <b>startDocument</b> events appearing within |
| 63 | * element content, or <b>attribute</b> events being followed by <b>text</b> events with no intervening |
| 64 | * <b>startContent</b>.</p> |
| 65 | * <p>The rules for a <b>regular sequence</b> imply that the top level events (any events not surrounded |
| 66 | * by startElement-endElement or startDocument-endDocument) can represent any sequence of items, including |
| 67 | * for example multiple document nodes, free-standing attribute and namespace nodes, maps, arrays, and functions; |
| 68 | * but within a startElement-endElement or startDocument-endDocument pair, the events represent content |
| 69 | * that has been normalized and validated according to the XSLT rules for constructing complex content, or |
| 70 | * the XQuery equivalent: for example, attributes and namespaces must appear before child nodes, a |
| 71 | * {@link #startContent()} event must occur after the attributes and namespaces, adjacent text nodes should |
| 72 | * have been merged, zero-length text nodes should have been eliminated, all namespaces should be explicitly |
| 73 | * declared, document nodes should be replaced by their children.</p> |
| 74 | * <p>Element nodes in "composed form" (that is, existing as a tree in memory) may be passed through |
| 75 | * the {@link #append(Item)} method at the top level, but within a startElement-endElement or |
| 76 | * startDocument-endDocument pair, elements must be represented in "decomposed form" as a sequence |
| 77 | * of events.</p> |
| 78 | * <p>A call to {@link #close} is permitted in any state, but it should only be called in <code>Open</code> |
| 79 | * state except on an error path; on error paths calling {@link #close} is recommended to ensure that |
| 80 | * resources are released.</p> |
| 81 | */ |
| 82 | public class RegularSequenceChecker extends ProxyReceiver { |
| 83 | |
| 84 | private Stack<Integer> stack = new Stack<>(); |
| 85 | public enum State {Initial, Open, StartTag, Content, Final} |
| 86 | private State state = State.Initial; |
| 87 | private static Map<State, Map<String, State>> machine = new HashMap<>(); |
| 88 | |
| 89 | static void edge(State from, String event, State to) { |
| 90 | Map<String, State> edges = machine.computeIfAbsent(from, s -> new HashMap<>()); |
| 91 | edges.put(event, to); |
| 92 | } |
| 93 | |
| 94 | static { |
| 95 | edge(State.Initial, "open", State.Open); |
| 96 | edge(State.Open, "append", State.Open); |
| 97 | edge(State.Open, "text", State.Open); |
| 98 | edge(State.Open, "comment", State.Open); |
| 99 | edge(State.Open, "pi", State.Open); |
| 100 | edge(State.Open, "attribute", State.Open); |
| 101 | edge(State.Open, "namespace", State.Open); |
| 102 | edge(State.Open, "startDocument", State.Content); |
| 103 | edge(State.Open, "startElement", State.StartTag); |
| 104 | edge(State.StartTag, "attribute", State.StartTag); |
| 105 | edge(State.StartTag, "namespace", State.StartTag); |
| 106 | edge(State.StartTag, "startContent", State.Content); |
| 107 | edge(State.Content, "text", State.Content); |
| 108 | edge(State.Content, "comment", State.Content); |
| 109 | edge(State.Content, "pi", State.Content); |
| 110 | edge(State.Content, "startElement", State.StartTag); |
| 111 | edge(State.Content, "endElement", State.Content); // or Open if the stack is empty |
| 112 | edge(State.Content, "endDocument", State.Open); |
| 113 | edge(State.Open, "close", State.Final); |
| 114 | //edge(State.Final, "close", State.Final); // This was a concession to poor practice, but apparently no longer needed |
| 115 | } |
| 116 | |
| 117 | private void transition(String event) { |
| 118 | State newState = machine.get(state).get(event); |
| 119 | if (newState == null) { |
| 120 | //assert false; |
| 121 | throw new IllegalStateException("Event " + event + " is not permitted in state " + state); |
| 122 | } else { |
| 123 | state = newState; |
| 124 | } |
| 125 | } |
| 126 | |
| 127 | |
| 128 | /** |
| 129 | * Create a RegularSequenceChecker and allocate a unique Id. |
| 130 | * |
| 131 | * @param nextReceiver the underlying receiver to which the events will be sent (without change) |
| 132 | */ |
| 133 | |
| 134 | public RegularSequenceChecker(Receiver nextReceiver) { |
| 135 | super(nextReceiver); |
| 136 | state = State.Initial; |
| 137 | } |
| 138 | |
| 139 | /** |
| 140 | * Append an arbitrary item (node or atomic value) to the output. In a regular sequence, append |
| 141 | * events occur only at the top level, that is, when the document / element stack is empty. |
| 142 | * |
| 143 | * @param item the item to be appended |
| 144 | * @param locationId the location of the calling instruction, for diagnostics |
| 145 | * @param copyNamespaces if the item is an element node, this indicates whether its namespaces |
| 146 | * need to be copied. Values are {@link ReceiverOptions#ALL_NAMESPACES}, |
| 147 | * {@link ReceiverOptions#LOCAL_NAMESPACES}; the default (0) means |
| 148 | * no namespaces |
| 149 | */ |
| 150 | |
| 151 | public void append(Item item, Location locationId, int copyNamespaces) throws XPathException { |
| 152 | transition("append"); |
| 153 | nextReceiver.append(item, locationId, copyNamespaces); |
| 154 | } |
| 155 | |
| 156 | /** |
| 157 | * Notify an attribute. An attribute is either free-standing attribute, or a parented attribute. A free-standing |
| 158 | * attribute is one that occurs when the startElement / startDocument stack is empty; a parented attribute |
| 159 | * occurs between a startElement event and a startContent event. |
| 160 | * <p> |
| 161 | * All attributes must satisfy the following constraints: |
| 162 | * <ol> |
| 163 | * <li>The namespace prefix and URI must either both be present (non-zero-length) or both absent</li> |
| 164 | * <li>The prefix "xml" and the URI "http://www.w3.org/XML/1998/namespace" |
| 165 | * are allowed only in combination.</li> |
| 166 | * <li>The namespace URI "http://www.w3.org/2000/xmlns/" is not allowed.</li> |
| 167 | * <li>The namespace prefix "xmlns" is not allowed.</li> |
| 168 | * <li>The local name "xmlns" is not allowed in the absence of a namespace prefix and URI.</li> |
| 169 | * </ol> |
| 170 | * <p> |
| 171 | * For a parented attribute, the following additional constraints apply to the set of attributes between |
| 172 | * a startElement event and the next startContent event: |
| 173 | * <ol> |
| 174 | * <li>No two attributes may have the same (local-name, namespace URI) combination.</li> |
| 175 | * <li>No namespace prefix may be used in conjunction with more than one namespace URI.</li> |
| 176 | * <li>Every (namespace prefix, namespace URI) combination must correspond to an in-scope namespace: |
| 177 | * that is, unless the (prefix, URI) pair is ("", "") or ("xml", "http://www.w3.org/XML/1998/namespace"), |
| 178 | * it must be the subject of a {@link #namespace(NamespaceBindingSet, int)} event applicable to this |
| 179 | * element or to some parent element, that has not been cancelled by a namespace undeclaration on |
| 180 | * an inner element. If the namespace event appears on the same element as the attribute event then they |
| 181 | * may arrive in either order.</li> |
| 182 | * </ol> |
| 183 | * <p> |
| 184 | * These constraints are not currently enforced by this class. |
| 185 | * </p> |
| 186 | * |
| 187 | * |
| 188 | * @param nameCode The name of the attribute |
| 189 | * @param typeCode The type of the attribute |
| 190 | * @param locationId The location of the attribute |
| 191 | * @param properties Bit significant value. The following bits are defined: |
| 192 | * <dl> |
| 193 | * <dd>DISABLE_ESCAPING</dd> <dt>Disable escaping for this attribute</dt> |
| 194 | * <dd>NO_SPECIAL_CHARACTERS</dd> <dt>Attribute value contains no special characters</dt> |
| 195 | * </dl> |
| 196 | * @throws IllegalStateException: attempt to output an attribute when there is no open element |
| 197 | * start tag |
| 198 | */ |
| 199 | |
| 200 | public void attribute(NodeName nameCode, SimpleType typeCode, CharSequence value, Location locationId, int properties) throws XPathException { |
| 201 | transition("attribute"); |
| 202 | nextReceiver.attribute(nameCode, typeCode, value, locationId, properties); |
| 203 | } |
| 204 | |
| 205 | /** |
| 206 | * Character data (corresponding to a text node). For character data within content (that is, events occurring |
| 207 | * when the startDocument / startElement stack is non-empty), character data events will never be consecutive |
| 208 | * and will never be zero-length. |
| 209 | */ |
| 210 | |
| 211 | public void characters(CharSequence chars, Location locationId, int properties) throws XPathException { |
| 212 | transition("text"); |
| 213 | if (chars.length() == 0 && !stack.isEmpty()) { |
| 214 | throw new IllegalStateException("Zero-length text nodes not allowed within document/element content"); |
| 215 | } |
| 216 | nextReceiver.characters(chars, locationId, properties); |
| 217 | } |
| 218 | |
| 219 | /** |
| 220 | * End of sequence |
| 221 | */ |
| 222 | |
| 223 | public void close() throws XPathException { |
| 224 | if (state != State.Final) { |
| 225 | nextReceiver.close(); |
| 226 | state = State.Final; |
| 227 | } |
| 228 | } |
| 229 | |
| 230 | /** |
| 231 | * Output a comment |
| 232 | */ |
| 233 | |
| 234 | public void comment(CharSequence chars, Location locationId, int properties) throws XPathException { |
| 235 | transition("comment"); |
| 236 | nextReceiver.comment(chars, locationId, properties); |
| 237 | } |
| 238 | |
| 239 | /** |
| 240 | * Notify the end of a document node |
| 241 | */ |
| 242 | |
| 243 | public void endDocument() throws XPathException { |
| 244 | transition("endDocument"); |
| 245 | if (stack.isEmpty() || stack.pop() != 0) { |
| 246 | throw new IllegalStateException("Unmatched endDocument() call"); |
| 247 | } |
| 248 | nextReceiver.endDocument(); |
| 249 | } |
| 250 | |
| 251 | /** |
| 252 | * End of element |
| 253 | */ |
| 254 | |
| 255 | public void endElement() throws XPathException { |
| 256 | transition("endElement"); |
| 257 | if (stack.isEmpty() || stack.pop() != 1) { |
| 258 | throw new IllegalStateException("Unmatched endElement() call"); |
| 259 | } |
| 260 | if (stack.isEmpty()) { |
| 261 | state = State.Open; |
| 262 | } |
| 263 | nextReceiver.endElement(); |
| 264 | } |
| 265 | |
| 266 | /** |
| 267 | * Notify a namespace. Namespaces are notified <b>after</b> the startElement event, and before |
| 268 | * any children for the element. The namespaces that are reported are only required |
| 269 | * to include those that are different from the parent element; however, duplicates may be reported. |
| 270 | * A namespace must not conflict with any namespaces already used for element or attribute names. |
| 271 | * |
| 272 | * @param namespaceBindings the namespace (prefix, uri) pair to be notified |
| 273 | * @throws IllegalStateException: attempt to output a namespace when there is no open element |
| 274 | * start tag |
| 275 | */ |
| 276 | |
| 277 | public void namespace(NamespaceBindingSet namespaceBindings, int properties) throws XPathException { |
| 278 | transition("namespace"); |
| 279 | nextReceiver.namespace(namespaceBindings, properties); |
| 280 | } |
| 281 | |
| 282 | /** |
| 283 | * Start of event stream |
| 284 | */ |
| 285 | |
| 286 | public void open() throws XPathException { |
| 287 | transition("open"); |
| 288 | nextReceiver.open(); |
| 289 | } |
| 290 | |
| 291 | /** |
| 292 | * Processing Instruction |
| 293 | */ |
| 294 | |
| 295 | public void processingInstruction(String target, CharSequence data, Location locationId, int properties) throws XPathException { |
| 296 | transition("pi"); |
| 297 | nextReceiver.processingInstruction(target, data, locationId, properties); |
| 298 | } |
| 299 | |
| 300 | /** |
| 301 | * Notify the start of the content, that is, the completion of all attributes and namespaces. |
| 302 | * Note that the initial receiver of output from XSLT instructions will not receive this event, |
| 303 | * it has to detect it itself. Note that this event is reported for every element even if it has |
| 304 | * no attributes, no namespaces, and no content. |
| 305 | */ |
| 306 | |
| 307 | |
| 308 | public void startContent() throws XPathException { |
| 309 | transition("startContent"); |
| 310 | nextReceiver.startContent(); |
| 311 | } |
| 312 | |
| 313 | /** |
| 314 | * Start of a document node. |
| 315 | */ |
| 316 | |
| 317 | public void startDocument(int properties) throws XPathException { |
| 318 | transition("startDocument"); |
| 319 | stack.push(0); |
| 320 | nextReceiver.startDocument(properties); |
| 321 | } |
| 322 | |
| 323 | /** |
| 324 | * Notify the start of an element |
| 325 | * @param nameCode integer code identifying the name of the element within the name pool. |
| 326 | * @param typeCode integer code identifying the element's type within the name pool. |
| 327 | * @param location provides information such as line number and system ID. |
| 328 | * @param properties properties of the element node |
| 329 | */ |
| 330 | |
| 331 | public void startElement(NodeName nameCode, SchemaType typeCode, Location location, int properties) throws XPathException { |
| 332 | transition("startElement"); |
| 333 | stack.push(1); |
| 334 | nextReceiver.startElement(nameCode, typeCode, location, properties); |
| 335 | } |
| 336 | } |
| 337 |