Debian Codegraph @

net/sf/saxon/event/NamespaceReducer.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.Location;
11 import net.sf.saxon.lib.NamespaceConstant;
12 import net.sf.saxon.om.NamespaceBinding;
13 import net.sf.saxon.om.NamespaceBindingSet;
14 import net.sf.saxon.om.NamespaceResolver;
15 import net.sf.saxon.om.NodeName;
16 import net.sf.saxon.trans.XPathException;
17 import net.sf.saxon.type.SchemaType;
18
19 import java.util.ArrayList;
20 import java.util.Arrays;
21 import java.util.Iterator;
22 import java.util.List;
23
24 /**
25 * <tt>NamespaceReducer</tt> is a {@link ProxyReceiver} responsible for removing duplicate namespace
26 * declarations. It also ensures that an {@code xmlns=""} undeclaration is output when
27 * necessary. Used on its own, the {@code NamespaceReducer} simply eliminates unwanted
28 * namespace declarations. It can also be subclassed, in which case the subclass
29 * can use the services of the {@code NamespaceReducer} to resolve QNames.
30 * <p>The {@code NamespaceReducer} also validates namespace-sensitive content.</p>
31 */
32
33 public class NamespaceReducer extends ProxyReceiver implements NamespaceResolver {
34 // We keep track of namespaces to avoid outputting duplicate declarations. The namespaces
35 // array holds a list of all namespaces currently declared (organised as pairs of entries,
36 // prefix followed by URI). The countStack contains an entry for each element currently open; the
37 // value on the stack is an integer giving the number of namespaces added to the main
38 // namespace stack by that element.
39
40 private NamespaceBinding[] namespaces = new NamespaceBinding[50]; // all namespace codes currently declared
41 private int namespacesSize = 0; // all namespaces currently declared
42 private int[] countStack = new int[50];
43 private int depth = 0;
44
45 // Creating an element does not automatically inherit the namespaces of the containing element.
46 // When the DISINHERIT property is set on startElement(), this indicates that the namespaces
47 // on that element are not to be automatically inherited by its children. So startElement()
48 // stacks a boolean flag indicating whether the children are to disinherit the parent's namespaces.
49
50 private boolean[] disinheritStack = new boolean[50];
51
52 // When a child element does not inherit the namespaces of its parent, it acquires undeclarations
53 // to indicate this fact. This array keeps track of the undeclarations that need to be added to the
54 // current child element.
55
56 private NamespaceBinding[] pendingUndeclarations = null;
57
58 /**
59 * Create a NamespaceReducer
60 *
61 * @param next the Receiver to which events will be passed after namespace reduction
62 */
63
64 public NamespaceReducer(Receiver next) {
65 super(next);
66 }
67
68 /**
69 * startElement. This call removes redundant namespace declarations, and
70 * possibly adds an xmlns="" undeclaration.
71 */
72
73 public void startElement(NodeName elemName, SchemaType typeCode, Location location, int properties) throws XPathException {
74
75 nextReceiver.startElement(elemName, typeCode, location, properties);
76
77
78 if ((properties & ReceiverOptions.REFUSE_NAMESPACES) != 0) {
79 // Typically XQuery: the element does not inherit namespaces from its parent
80 pendingUndeclarations = Arrays.copyOf(namespaces, namespacesSize);
81 } else if (depth > 0 && disinheritStack[depth - 1]) {
82 // If the parent element specified inherit=no, keep a list of namespaces that need to be
83 // undeclared. Note (bug 20340) that namespaces are still inherited from grandparent elements
84 List<NamespaceBinding> undeclarations = new ArrayList<>(namespacesSize);
85 int k = namespacesSize;
86 for (int d = depth-1; d>=0; d--) {
87 if (!disinheritStack[d]) {
88 break;
89 }
90 for (int i=0; i<countStack[d]; i++) {
91 undeclarations.add(namespaces[--k]);
92 }
93 }
94 pendingUndeclarations = undeclarations.toArray(NamespaceBinding.EMPTY_ARRAY);
95 } else {
96 pendingUndeclarations = null;
97 }
98
99 // Record the current height of the namespace list so it can be reset at endElement time
100
101 countStack[depth] = 0;
102 disinheritStack[depth] = (properties & ReceiverOptions.DISINHERIT_NAMESPACES) != 0;
103 if (++depth >= countStack.length) {
104 countStack = Arrays.copyOf(countStack, depth*2);
105 disinheritStack = Arrays.copyOf(disinheritStack, depth*2);
106 }
107
108 // Ensure that the element namespace is output, unless this is done
109 // automatically by the caller (which is true, for example, for a literal
110 // result element).
111
112 if ((properties & ReceiverOptions.NAMESPACE_OK) == 0) {
113 namespace(elemName.getNamespaceBinding(), 0);
114 }
115
116 }
117
118 /**
119 * Output a namespace node (binding)
120 *
121 * @param namespaceBindings the prefix/uri pair to be output
122 * @param properties the properties of the namespace binding
123 * @throws XPathException if any downstream error occurs
124 */
125
126 public void namespace(NamespaceBindingSet namespaceBindings, int properties) throws XPathException {
127
128 // Keep the namespace only if it is actually needed
129
130 for (NamespaceBinding ns : namespaceBindings) {
131 if (isNeeded(ns)) {
132 addToStack(ns);
133 countStack[depth - 1]++;
134 nextReceiver.namespace(ns, properties);
135 }
136 }
137 }
138
139 /**
140 * Determine whether a namespace declaration is needed
141 *
142 * @param nsBinding the namespace binding
143 * @return true if the namespace is needed: that is, if it not the XML namespace, is not a duplicate,
144 * and is not a redundant xmlns="".
145 */
146
147 private boolean isNeeded(NamespaceBinding nsBinding) {
148 if (nsBinding.isXmlNamespace()) {
149 // Ignore the XML namespace
150 return false;
151 }
152
153 // First cancel any pending undeclaration of this namespace prefix (there may be more than one)
154
155 String prefix = nsBinding.getPrefix();
156 if (pendingUndeclarations != null) {
157 for (int p = 0; p < pendingUndeclarations.length; p++) {
158 NamespaceBinding nb = pendingUndeclarations[p];
159 if (nb != null && prefix.equals(nb.getPrefix())) {
160 pendingUndeclarations[p] = null;
161 //break;
162 }
163 }
164 }
165
166 for (int i = namespacesSize - 1; i >= 0; i--) {
167 if (namespaces[i].equals(nsBinding)) {
168 // it's a duplicate so we don't need it
169 return false;
170 }
171 if (namespaces[i].getPrefix().equals(nsBinding.getPrefix())) {
172 // same prefix, different URI.
173 return true;
174 }
175 }
176
177 // we need it unless it's a redundant xmlns=""
178 return !nsBinding.isDefaultUndeclaration();
179 }
180
181 /**
182 * Add a namespace declaration to the stack
183 *
184 * @param nsBinding the namespace code to be added
185 */
186
187 private void addToStack(NamespaceBinding nsBinding) {
188 // expand the stack if necessary
189 if (namespacesSize + 1 >= namespaces.length) {
190 namespaces = Arrays.copyOf(namespaces, namespacesSize * 2);
191 }
192 namespaces[namespacesSize++] = nsBinding;
193 }
194
195 /**
196 * Ask whether the namespace reducer is disinheriting namespaces at the current level
197 * @return true if namespaces are being disinherited
198 */
199
200 public boolean isDisinheritingNamespaces() {
201 return depth > 0 && disinheritStack[depth-1];
202 }
203
204 /**
205 * startContent: Add any namespace undeclarations needed to stop
206 * namespaces being inherited from parent elements
207 */
208
209 public void startContent() throws XPathException {
210
211 if (pendingUndeclarations != null) {
212 for (NamespaceBinding ns : pendingUndeclarations) {
213 if (ns != null) {
214 namespace(new NamespaceBinding(ns.getPrefix(), ""), 0);
215 // relies on the namespace() method to prevent duplicate undeclarations
216 }
217 }
218 }
219 pendingUndeclarations = null;
220 nextReceiver.startContent();
221 }
222
223 /**
224 * endElement: Discard the namespaces declared on this element.
225 */
226
227
228 public void endElement() throws XPathException {
229 if (depth-- == 0) {
230 throw new IllegalStateException("Attempt to output end tag with no matching start tag");
231 }
232
233 namespacesSize -= countStack[depth];
234
235 nextReceiver.endElement();
236
237 }
238
239 /**
240 * Get the namespace URI corresponding to a given prefix. Return null
241 * if the prefix is not in scope.
242 *
243 * @param prefix the namespace prefix
244 * @param useDefault true if the default namespace is to be used when the
245 * prefix is ""
246 * @return the uri for the namespace, or null if the prefix is not in scope
247 */
248
249 /*@Nullable*/
250 public String getURIForPrefix(String prefix, boolean useDefault) {
251 if (prefix.isEmpty() && !useDefault) {
252 return NamespaceConstant.NULL;
253 } else if ("xml".equals(prefix)) {
254 return NamespaceConstant.XML;
255 } else {
256 for (int i = namespacesSize - 1; i >= 0; i--) {
257 if (namespaces[i].getPrefix().equals(prefix)) {
258 return namespaces[i].getURI();
259 }
260 }
261 }
262 return prefix.isEmpty() ? NamespaceConstant.NULL : null;
263 }
264
265 /**
266 * Get an iterator over all the prefixes declared in this namespace context. This will include
267 * the default namespace (prefix="") and the XML namespace where appropriate
268 */
269
270 public Iterator<String> iteratePrefixes() {
271 List<String> prefixes = new ArrayList<>(namespacesSize);
272 for (int i = namespacesSize - 1; i >= 0; i--) {
273 String prefix = namespaces[i].getPrefix();
274 if (!prefixes.contains(prefix)) {
275 prefixes.add(prefix);
276 }
277 }
278 prefixes.add("xml");
279 return prefixes.iterator();
280 }
281 }
282