Debian Codegraph @

rhino/xmlimplsrc/org/mozilla/javascript/xmlimpl/XML.java

raw symbols SCIP
1 /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2 *
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 package org.mozilla.javascript.xmlimpl;
8
9 import org.mozilla.javascript.*;
10 import org.mozilla.javascript.xml.XMLObject;
11
12 class XML extends XMLObjectImpl {
13 static final long serialVersionUID = -630969919086449092L;
14
15 private XmlNode node;
16
17 XML(XMLLibImpl lib, Scriptable scope, XMLObject prototype, XmlNode node) {
18 super(lib, scope, prototype);
19 initialize(node);
20 }
21
22 void initialize(XmlNode node) {
23 this.node = node;
24 this.node.setXml(this);
25 }
26
27 @Override
28 final XML getXML() {
29 return this;
30 }
31
32 void replaceWith(XML value) {
33 // We use the underlying document structure if the node is not
34 // "standalone," but we need to just replace the XmlNode instance
35 // otherwise
36 if (this.node.parent() != null) {
37 this.node.replaceWith(value.node);
38 } else {
39 this.initialize(value.node);
40 }
41 }
42
43 /* TODO: needs encapsulation. */
44 XML makeXmlFromString(XMLName name, String value) {
45 try {
46 return newTextElementXML(this.node, name.toQname(), value);
47 } catch(Exception e) {
48 throw ScriptRuntime.typeError(e.getMessage());
49 }
50 }
51
52 /* TODO: Rename this, at the very least. But it's not clear it's even necessary */
53 XmlNode getAnnotation() {
54 return node;
55 }
56
57 //
58 // Methods from ScriptableObject
59 //
60
61 // TODO Either cross-reference this next comment with the specification or delete it and change the behavior
62 // The comment: XML[0] should return this, all other indexes are Undefined
63 @Override
64 public Object get(int index, Scriptable start) {
65 if (index == 0) {
66 return this;
67 } else {
68 return Scriptable.NOT_FOUND;
69 }
70 }
71
72 @Override
73 public boolean has(int index, Scriptable start) {
74 return (index == 0);
75 }
76
77 @Override
78 public void put(int index, Scriptable start, Object value) {
79 // TODO Clarify the following comment and add a reference to the spec
80 // The comment: Spec says assignment to indexed XML object should return type error
81 throw ScriptRuntime.typeError("Assignment to indexed XML is not allowed");
82 }
83
84 @Override
85 public Object[] getIds() {
86 if (isPrototype()) {
87 return new Object[0];
88 } else {
89 return new Object[] { Integer.valueOf(0) };
90 }
91 }
92
93 // TODO This is how I found it but I am not sure it makes sense
94 @Override
95 public void delete(int index) {
96 if (index == 0) {
97 this.remove();
98 }
99 }
100
101 //
102 // Methods from XMLObjectImpl
103 //
104
105 @Override
106 boolean hasXMLProperty(XMLName xmlName) {
107 return (getPropertyList(xmlName).length() > 0);
108 }
109
110 @Override
111 Object getXMLProperty(XMLName xmlName) {
112 return getPropertyList(xmlName);
113 }
114
115 //
116 //
117 // Methods that merit further review
118 //
119 //
120
121 XmlNode.QName getNodeQname() {
122 return this.node.getQname();
123 }
124
125 XML[] getChildren() {
126 if (!isElement()) return null;
127 XmlNode[] children = this.node.getMatchingChildren(XmlNode.Filter.TRUE);
128 XML[] rv = new XML[children.length];
129 for (int i=0; i<rv.length; i++) {
130 rv[i] = toXML(children[i]);
131 }
132 return rv;
133 }
134
135 XML[] getAttributes() {
136 XmlNode[] attributes = this.node.getAttributes();
137 XML[] rv = new XML[attributes.length];
138 for (int i=0; i<rv.length; i++) {
139 rv[i] = toXML(attributes[i]);
140 }
141 return rv;
142 }
143
144 // Used only by XML, XMLList
145 XMLList getPropertyList(XMLName name) {
146 return name.getMyValueOn(this);
147 }
148
149 @Override
150 void deleteXMLProperty(XMLName name) {
151 XMLList list = getPropertyList(name);
152 for (int i=0; i<list.length(); i++) {
153 list.item(i).node.deleteMe();
154 }
155 }
156
157 @Override
158 void putXMLProperty(XMLName xmlName, Object value) {
159 if (isPrototype()) {
160 // TODO Is this really a no-op? Check the spec to be sure
161 } else {
162 xmlName.setMyValueOn(this, value);
163 }
164 }
165
166 @Override
167 boolean hasOwnProperty(XMLName xmlName) {
168 boolean hasProperty = false;
169
170 if (isPrototype()) {
171 String property = xmlName.localName();
172 hasProperty = (0 != findPrototypeId(property));
173 } else {
174 hasProperty = (getPropertyList(xmlName).length() > 0);
175 }
176
177 return hasProperty;
178 }
179
180 @Override
181 protected Object jsConstructor(Context cx, boolean inNewExpr, Object[] args) {
182 if (args.length == 0 || args[0] == null || args[0] == Undefined.instance) {
183 args = new Object[] { "" };
184 }
185 // ECMA 13.4.2 does not appear to specify what to do if multiple arguments are sent.
186 XML toXml = ecmaToXml(args[0]);
187 if (inNewExpr) {
188 return toXml.copy();
189 } else {
190 return toXml;
191 }
192 }
193
194 // See ECMA 357, 11_2_2_1, Semantics, 3_f.
195 @Override
196 public Scriptable getExtraMethodSource(Context cx) {
197 if (hasSimpleContent()) {
198 String src = toString();
199 return ScriptRuntime.toObjectOrNull(cx, src);
200 }
201 return null;
202 }
203
204 //
205 // TODO Miscellaneous methods not yet grouped
206 //
207
208 void removeChild(int index) {
209 this.node.removeChild(index);
210 }
211
212 @Override
213 void normalize() {
214 this.node.normalize();
215 }
216
217 private XML toXML(XmlNode node) {
218 if (node.getXml() == null) {
219 node.setXml(newXML(node));
220 }
221 return node.getXml();
222 }
223
224 void setAttribute(XMLName xmlName, Object value) {
225 if (!isElement()) throw new IllegalStateException("Can only set attributes on elements.");
226 // TODO Is this legal, but just not "supported"? If so, support it.
227 if (xmlName.uri() == null && xmlName.localName().equals("*")) {
228 throw ScriptRuntime.typeError("@* assignment not supported.");
229 }
230 this.node.setAttribute(xmlName.toQname(), ScriptRuntime.toString(value));
231 }
232
233 void remove() {
234 this.node.deleteMe();
235 }
236
237 @Override
238 void addMatches(XMLList rv, XMLName name) {
239 name.addMatches(rv, this);
240 }
241
242 @Override
243 XMLList elements(XMLName name) {
244 XMLList rv = newXMLList();
245 rv.setTargets(this, name.toQname());
246 // TODO Should have an XMLNode.Filter implementation based on XMLName
247 XmlNode[] elements = this.node.getMatchingChildren(XmlNode.Filter.ELEMENT);
248 for (int i=0; i<elements.length; i++) {
249 if (name.matches( toXML(elements[i]) )) {
250 rv.addToList( toXML(elements[i]) );
251 }
252 }
253 return rv;
254 }
255
256 @Override
257 XMLList child(XMLName xmlName) {
258 // TODO Right now I think this method would allow child( "@xxx" ) to return the xxx attribute, which is wrong
259
260 XMLList rv = newXMLList();
261
262 // TODO Should this also match processing instructions? If so, we have to change the filter and also the XMLName
263 // class to add an acceptsProcessingInstruction() method
264
265 XmlNode[] elements = this.node.getMatchingChildren(XmlNode.Filter.ELEMENT);
266 for (int i=0; i<elements.length; i++) {
267 if (xmlName.matchesElement(elements[i].getQname())) {
268 rv.addToList( toXML(elements[i]) );
269 }
270 }
271 rv.setTargets(this, xmlName.toQname());
272 return rv;
273 }
274
275 XML replace(XMLName xmlName, Object xml) {
276 putXMLProperty(xmlName, xml);
277 return this;
278 }
279
280 @Override
281 XMLList children() {
282 XMLList rv = newXMLList();
283 XMLName all = XMLName.formStar();
284 rv.setTargets(this, all.toQname());
285 XmlNode[] children = this.node.getMatchingChildren(XmlNode.Filter.TRUE);
286 for (int i=0; i<children.length; i++) {
287 rv.addToList( toXML(children[i]) );
288 }
289 return rv;
290 }
291
292 @Override
293 XMLList child(int index) {
294 // ECMA357 13.4.4.6 (numeric case)
295 XMLList result = newXMLList();
296 result.setTargets(this, null);
297 if (index >= 0 && index < this.node.getChildCount()) {
298 result.addToList(getXmlChild(index));
299 }
300 return result;
301 }
302
303 XML getXmlChild(int index) {
304 XmlNode child = this.node.getChild(index);
305 if (child.getXml() == null) {
306 child.setXml(newXML(child));
307 }
308 return child.getXml();
309 }
310
311 /* Return the last added element */
312 XML getLastXmlChild() {
313 int pos = this.node.getChildCount() - 1;
314 if (pos < 0) return null;
315 return getXmlChild(pos);
316 }
317
318 int childIndex() {
319 return this.node.getChildIndex();
320 }
321
322 @Override
323 boolean contains(Object xml) {
324 if (xml instanceof XML) {
325 return equivalentXml(xml);
326 } else {
327 return false;
328 }
329 }
330
331 // Method overriding XMLObjectImpl
332 @Override
333 boolean equivalentXml(Object target) {
334 boolean result = false;
335
336 if (target instanceof XML) {
337 // TODO This is a horrifyingly inefficient way to do this so we should make it better. It may also not work.
338 return this.node.toXmlString(getProcessor()).equals( ((XML)target).node.toXmlString(getProcessor()) );
339 } else if (target instanceof XMLList) {
340 // TODO Is this right? Check the spec ...
341 XMLList otherList = (XMLList) target;
342
343 if (otherList.length() == 1) {
344 result = equivalentXml(otherList.getXML());
345 }
346 } else if (hasSimpleContent()) {
347 String otherStr = ScriptRuntime.toString(target);
348
349 result = toString().equals(otherStr);
350 }
351
352 return result;
353 }
354
355 @Override
356 XMLObjectImpl copy() {
357 return newXML( this.node.copy() );
358 }
359
360 @Override
361 boolean hasSimpleContent() {
362 if (isComment() || isProcessingInstruction()) return false;
363 if (isText() || this.node.isAttributeType()) return true;
364 return !this.node.hasChildElement();
365 }
366
367 @Override
368 boolean hasComplexContent() {
369 return !hasSimpleContent();
370 }
371
372 // TODO Cross-reference comment below with spec
373 // Comment is: Length of an XML object is always 1, it's a list of XML objects of size 1.
374 @Override
375 int length() {
376 return 1;
377 }
378
379 // TODO it is not clear what this method was for ...
380 boolean is(XML other) {
381 return this.node.isSameNode(other.node);
382 }
383
384 Object nodeKind() {
385 return ecmaClass();
386 }
387
388 @Override
389 Object parent() {
390 XmlNode parent = this.node.parent();
391 if (parent == null) return null;
392 return newXML(this.node.parent());
393 }
394
395 @Override
396 boolean propertyIsEnumerable(Object name)
397 {
398 boolean result;
399 if (name instanceof Integer) {
400 result = (((Integer)name).intValue() == 0);
401 } else if (name instanceof Number) {
402 double x = ((Number)name).doubleValue();
403 // Check that number is positive 0
404 result = (x == 0.0 && 1.0 / x > 0);
405 } else {
406 result = ScriptRuntime.toString(name).equals("0");
407 }
408 return result;
409 }
410
411 @Override
412 Object valueOf() {
413 return this;
414 }
415
416 //
417 // Selection of children
418 //
419
420 @Override
421 XMLList comments() {
422 XMLList rv = newXMLList();
423 this.node.addMatchingChildren(rv, XmlNode.Filter.COMMENT);
424 return rv;
425 }
426
427 @Override
428 XMLList text() {
429 XMLList rv = newXMLList();
430 this.node.addMatchingChildren(rv, XmlNode.Filter.TEXT);
431 return rv;
432 }
433
434 @Override
435 XMLList processingInstructions(XMLName xmlName) {
436 XMLList rv = newXMLList();
437 this.node.addMatchingChildren(rv, XmlNode.Filter.PROCESSING_INSTRUCTION(xmlName));
438 return rv;
439 }
440
441 //
442 // Methods relating to modification of child nodes
443 //
444
445 // We create all the nodes we are inserting before doing the insert to
446 // avoid nasty cycles caused by mutability of these objects. For example,
447 // what if the toString() method of value modifies the XML object we were
448 // going to insert into? insertAfter might get confused about where to
449 // insert. This actually came up with SpiderMonkey, leading to a (very)
450 // long discussion. See bug #354145.
451 private XmlNode[] getNodesForInsert(Object value) {
452 if (value instanceof XML) {
453 return new XmlNode[] { ((XML)value).node };
454 } else if (value instanceof XMLList) {
455 XMLList list = (XMLList)value;
456 XmlNode[] rv = new XmlNode[list.length()];
457 for (int i=0; i<list.length(); i++) {
458 rv[i] = list.item(i).node;
459 }
460 return rv;
461 } else {
462 return new XmlNode[] {
463 XmlNode.createText(getProcessor(), ScriptRuntime.toString(value))
464 };
465 }
466 }
467
468 XML replace(int index, Object xml) {
469 XMLList xlChildToReplace = child(index);
470 if (xlChildToReplace.length() > 0) {
471 // One exists an that index
472 XML childToReplace = xlChildToReplace.item(0);
473 insertChildAfter(childToReplace, xml);
474 removeChild(index);
475 }
476 return this;
477 }
478
479 XML prependChild(Object xml) {
480 if (this.node.isParentType()) {
481 this.node.insertChildrenAt(0, getNodesForInsert(xml));
482 }
483 return this;
484 }
485
486 XML appendChild(Object xml) {
487 if (this.node.isParentType()) {
488 XmlNode[] nodes = getNodesForInsert(xml);
489 this.node.insertChildrenAt(this.node.getChildCount(), nodes);
490 }
491 return this;
492 }
493
494 private int getChildIndexOf(XML child) {
495 for (int i=0; i<this.node.getChildCount(); i++) {
496 if (this.node.getChild(i).isSameNode(child.node)) {
497 return i;
498 }
499 }
500 return -1;
501 }
502
503 XML insertChildBefore(XML child, Object xml) {
504 if (child == null) {
505 // Spec says inserting before nothing is the same as appending
506 appendChild(xml);
507 } else {
508 XmlNode[] toInsert = getNodesForInsert(xml);
509 int index = getChildIndexOf(child);
510 if (index != -1) {
511 this.node.insertChildrenAt(index, toInsert);
512 }
513 }
514
515 return this;
516 }
517
518 XML insertChildAfter(XML child, Object xml) {
519 if (child == null) {
520 // Spec says inserting after nothing is the same as prepending
521 prependChild(xml);
522 } else {
523 XmlNode[] toInsert = getNodesForInsert(xml);
524 int index = getChildIndexOf(child);
525 if (index != -1) {
526 this.node.insertChildrenAt(index+1, toInsert);
527 }
528 }
529
530 return this;
531 }
532
533 XML setChildren(Object xml) {
534 // TODO Have not carefully considered the spec but it seems to call for this
535 if (!isElement()) return this;
536
537 while(this.node.getChildCount() > 0) {
538 this.node.removeChild(0);
539 }
540 XmlNode[] toInsert = getNodesForInsert(xml);
541 // append new children
542 this.node.insertChildrenAt(0, toInsert);
543
544 return this;
545 }
546
547 //
548 // Name and namespace-related methods
549 //
550
551 private void addInScopeNamespace(Namespace ns) {
552 if (!isElement()) {
553 return;
554 }
555 // See ECMA357 9.1.1.13
556 // in this implementation null prefix means ECMA undefined
557 if (ns.prefix() != null) {
558 if (ns.prefix().length() == 0 && ns.uri().length() == 0) {
559 return;
560 }
561 if (node.getQname().getNamespace().getPrefix().equals(ns.prefix())) {
562 node.invalidateNamespacePrefix();
563 }
564 node.declareNamespace(ns.prefix(), ns.uri());
565 } else {
566 return;
567 }
568 }
569
570 Namespace[] inScopeNamespaces() {
571 XmlNode.Namespace[] inScope = this.node.getInScopeNamespaces();
572 return createNamespaces(inScope);
573 }
574
575 private XmlNode.Namespace adapt(Namespace ns) {
576 if (ns.prefix() == null) {
577 return XmlNode.Namespace.create(ns.uri());
578 } else {
579 return XmlNode.Namespace.create(ns.prefix(), ns.uri());
580 }
581 }
582
583 XML removeNamespace(Namespace ns) {
584 if (!isElement()) return this;
585 this.node.removeNamespace(adapt(ns));
586 return this;
587 }
588
589 XML addNamespace(Namespace ns) {
590 addInScopeNamespace(ns);
591 return this;
592 }
593
594 QName name() {
595 if (isText() || isComment()) return null;
596 if (isProcessingInstruction()) return newQName("", this.node.getQname().getLocalName(), null);
597 return newQName(node.getQname());
598 }
599
600 Namespace[] namespaceDeclarations() {
601 XmlNode.Namespace[] declarations = node.getNamespaceDeclarations();
602 return createNamespaces(declarations);
603 }
604
605 Namespace namespace(String prefix) {
606 if (prefix == null) {
607 return createNamespace( this.node.getNamespaceDeclaration() );
608 } else {
609 return createNamespace( this.node.getNamespaceDeclaration(prefix) );
610 }
611 }
612
613 String localName() {
614 if (name() == null) return null;
615 return name().localName();
616 }
617
618 void setLocalName(String localName) {
619 // ECMA357 13.4.4.34
620 if (isText() || isComment()) return;
621 this.node.setLocalName(localName);
622 }
623
624 void setName(QName name) {
625 // See ECMA357 13.4.4.35
626 if (isText() || isComment()) return;
627 if (isProcessingInstruction()) {
628 // Spec says set the name URI to empty string and then set the [[Name]] property, but I understand this to do the same
629 // thing, unless we allow colons in processing instruction targets, which I think we do not.
630 this.node.setLocalName(name.localName());
631 return;
632 }
633 node.renameNode(name.getDelegate());
634 }
635
636 void setNamespace(Namespace ns) {
637 // See ECMA357 13.4.4.36
638 if (isText() || isComment() || isProcessingInstruction()) return;
639 setName(newQName(ns.uri(), localName(), ns.prefix()));
640 }
641
642 final String ecmaClass() {
643 // See ECMA357 9.1
644
645 // TODO See ECMA357 9.1.1 last paragraph for what defaults should be
646
647 if (node.isTextType()) {
648 return "text";
649 } else if (node.isAttributeType()) {
650 return "attribute";
651 } else if (node.isCommentType()) {
652 return "comment";
653 } else if (node.isProcessingInstructionType()) {
654 return "processing-instruction";
655 } else if (node.isElementType()) {
656 return "element";
657 } else {
658 throw new RuntimeException("Unrecognized type: " + node);
659 }
660 }
661
662 @Override
663 public String getClassName() {
664 // TODO: This appears to confuse the interpreter if we use the "real" class property from ECMA. Otherwise this code
665 // would be:
666 // return ecmaClass();
667 return "XML";
668 }
669
670 private String ecmaValue() {
671 return node.ecmaValue();
672 }
673
674 private String ecmaToString() {
675 // See ECMA357 10.1.1
676 if (isAttribute() || isText()) {
677 return ecmaValue();
678 }
679 if (this.hasSimpleContent()) {
680 StringBuilder rv = new StringBuilder();
681 for (int i=0; i < this.node.getChildCount(); i++) {
682 XmlNode child = this.node.getChild(i);
683 if (!child.isProcessingInstructionType() &&
684 !child.isCommentType())
685 {
686 // TODO: Probably inefficient; taking clean non-optimized
687 // solution for now
688 XML x = new XML(getLib(), getParentScope(),
689 (XMLObject)getPrototype(), child);
690 rv.append(x.toString());
691 }
692 }
693 return rv.toString();
694 }
695 return toXMLString();
696 }
697
698 @Override
699 public String toString() {
700 return ecmaToString();
701 }
702
703 @Override
704 String toSource(int indent) {
705 return toXMLString();
706 }
707
708 @Override
709 String toXMLString() {
710 return this.node.ecmaToXMLString(getProcessor());
711 }
712
713 final boolean isAttribute() {
714 return node.isAttributeType();
715 }
716
717 final boolean isComment() {
718 return node.isCommentType();
719 }
720
721 final boolean isText() {
722 return node.isTextType();
723 }
724
725 final boolean isElement() {
726 return node.isElementType();
727 }
728
729 final boolean isProcessingInstruction() {
730 return node.isProcessingInstructionType();
731 }
732
733 // Support experimental Java interface
734 org.w3c.dom.Node toDomNode() {
735 return node.toDomNode();
736 }
737 }