summaryrefslogtreecommitdiff
path: root/gnu/xml/validation/relaxng/FullSyntaxBuilder.java
blob: bb73c4f38a4d38d780f698e7c226e3e82c68c995 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
/* FullSyntaxBuilder.java --
   Copyright (C) 2006  Free Software Foundation, Inc.

This file is part of GNU Classpath.

GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.

GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING.  If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.

Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.

As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module.  An independent module is a module which is not derived from
or based on this library.  If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so.  If you do not wish to do so, delete this
exception statement from your version. */

package gnu.xml.validation.relaxng;

import java.io.InputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.relaxng.datatype.DatatypeException;
import org.relaxng.datatype.DatatypeLibrary;
import org.relaxng.datatype.helpers.DatatypeLibraryLoader;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

import gnu.xml.stream.XMLParser;

/**
 * Parses a RELAX NG XML DOM tree, constructing a compiled internal
 * representation.
 *
 * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a>
 */
class FullSyntaxBuilder
{

  /**
   * Complete vocabulary (elements and attributes) of the full syntax.
   */
  static final Map VOCABULARY = new HashMap();
  static final Set STRIPPED_ATTRIBUTES = new HashSet();
  static final Set PATTERN_ELEMENTS = new HashSet();
  static
  {
    Set elementAttrs = Collections.singleton("name");
    Set dataAttrs = new HashSet();
    dataAttrs.add("type");
    dataAttrs.add("datatypeLibrary");
    Set valueAttrs = new HashSet();
    valueAttrs.add("type");
    valueAttrs.add("datatypeLibrary");
    valueAttrs.add("ns");
    Set externalAttrs = Collections.singleton("href");
    Set startAttrs = Collections.singleton("combine");
    Set defineAttrs = new HashSet();
    defineAttrs.add("name");
    defineAttrs.add("combine");
    Set nsAttrs = Collections.singleton("ns");

    VOCABULARY.put("element", elementAttrs);
    VOCABULARY.put("attribute", elementAttrs);
    VOCABULARY.put("group", Collections.EMPTY_SET);
    VOCABULARY.put("interleave", Collections.EMPTY_SET);
    VOCABULARY.put("choice", Collections.EMPTY_SET);
    VOCABULARY.put("optional", Collections.EMPTY_SET);
    VOCABULARY.put("zeroOrMore", Collections.EMPTY_SET);
    VOCABULARY.put("oneOrMore", Collections.EMPTY_SET);
    VOCABULARY.put("list", Collections.EMPTY_SET);
    VOCABULARY.put("mixed", Collections.EMPTY_SET);
    VOCABULARY.put("ref", elementAttrs);
    VOCABULARY.put("parentRef", elementAttrs);
    VOCABULARY.put("empty", Collections.EMPTY_SET);
    VOCABULARY.put("text", Collections.EMPTY_SET);
    VOCABULARY.put("value", valueAttrs);
    VOCABULARY.put("data", dataAttrs);
    VOCABULARY.put("notAllowed", Collections.EMPTY_SET);
    VOCABULARY.put("externalRef", externalAttrs);
    VOCABULARY.put("grammar", Collections.EMPTY_SET);
    VOCABULARY.put("param", elementAttrs);
    VOCABULARY.put("except", Collections.EMPTY_SET);
    VOCABULARY.put("div", Collections.EMPTY_SET);
    VOCABULARY.put("include", externalAttrs);
    VOCABULARY.put("start", startAttrs);
    VOCABULARY.put("define", defineAttrs);
    VOCABULARY.put("name", nsAttrs);
    VOCABULARY.put("anyName", Collections.EMPTY_SET);
    VOCABULARY.put("nsName", nsAttrs);

    STRIPPED_ATTRIBUTES.add("name");
    STRIPPED_ATTRIBUTES.add("type");
    STRIPPED_ATTRIBUTES.add("combine");

    PATTERN_ELEMENTS.add("element");
    PATTERN_ELEMENTS.add("attribute");
    PATTERN_ELEMENTS.add("group");
    PATTERN_ELEMENTS.add("interleave");
    PATTERN_ELEMENTS.add("choice");
    PATTERN_ELEMENTS.add("optional");
    PATTERN_ELEMENTS.add("zeroOrMore");
    PATTERN_ELEMENTS.add("oneOrMore");
    PATTERN_ELEMENTS.add("list");
    PATTERN_ELEMENTS.add("mixed");
    PATTERN_ELEMENTS.add("ref");
    PATTERN_ELEMENTS.add("parentRef");
    PATTERN_ELEMENTS.add("empty");
    PATTERN_ELEMENTS.add("text");
    PATTERN_ELEMENTS.add("value");
    PATTERN_ELEMENTS.add("data");
    PATTERN_ELEMENTS.add("notAllowed");
    PATTERN_ELEMENTS.add("externalRef");
    PATTERN_ELEMENTS.add("grammar");
  }

  private Set urls; // recursion checking
  private int refCount; // creation of ref names
  private Map datatypeLibraries;

  /**
   * Parse the specified document into a grammar.
   */
  synchronized Grammar parse(Document doc)
    throws IOException
  {
    urls = new HashSet();
    refCount = 1;

    doc.normalizeDocument(); // Normalize XML document
    transform(doc); // Apply transformation rules to provide simple syntax

    // 4.18. grammar element
    Element p = doc.getDocumentElement();
    Element grammar =
      doc.createElementNS(XMLConstants.RELAXNG_NS_URI, "grammar");
    Element start =
      doc.createElementNS(XMLConstants.RELAXNG_NS_URI, "start");
    doc.removeChild(p);
    doc.appendChild(grammar);
    grammar.appendChild(start);
    start.appendChild(p);
    transformGrammar(grammar, p);
    Element define = getNextSiblingElement(start);
    while (define != null)
      {
        Element next = getNextSiblingElement(define);
        String name = define.getAttribute("new-name");
        if (name != null)
          {
            define.setAttribute("name", name);
            define.removeAttribute("new-name");
          }
        else
          grammar.removeChild(define); // unreferenced
        define = next;
      }

    // 4.19. define and ref elements
    Set allDefines = new HashSet(), reachableDefines = new HashSet();
    getDefines(allDefines, grammar, grammar, false);
    getDefines(reachableDefines, grammar, start, true);
    allDefines.removeAll(reachableDefines);
    for (Iterator i = allDefines.iterator(); i.hasNext(); )
      {
        // remove unreachable defines
        Element d = (Element) i.next();
        Node parent = d.getParentNode();
        parent.removeChild(d);
      }
    // replace all elements that are not children of defines by refs to new
    // defines
    Set elements = new HashSet();
    getElements(elements, grammar, grammar);
    for (Iterator i = elements.iterator(); i.hasNext(); )
      {
        Element element = (Element) i.next();
        Node parent = element.getParentNode();
        if (!reachableDefines.contains(parent))
          {
            define =
              doc.createElementNS(XMLConstants.RELAXNG_NS_URI, "define");
            Element ref =
              doc.createElementNS(XMLConstants.RELAXNG_NS_URI, "ref");
            String name = createRefName();
            define.setAttribute("name", name);
            ref.setAttribute("name", name);
            parent.insertBefore(ref, element);
            define.appendChild(element);
            grammar.appendChild(define);
            reachableDefines.add(define);
          }
      }
    // Get defines that don't have element children
    for (Iterator i = reachableDefines.iterator(); i.hasNext(); )
      {
        Element d = (Element) i.next();
        Element child = getFirstChildElement(d);
        if (child != null && "element".equals(child.getLocalName()))
          i.remove();
      }
    // Expand refs that refer to these defines
    expandRefs(reachableDefines, grammar);
    // Remove any defines that don't have element children
    for (Iterator i = reachableDefines.iterator(); i.hasNext(); )
      {
        Element d = (Element) i.next();
        Node parent = d.getParentNode();
        parent.removeChild(d);
      }

    transform2(p); // Apply second stage transformation rules

    Grammar ret = parseGrammar(grammar);
    datatypeLibraries = null; // free datatype libraries cache
    return ret;
  }

  private void getDefines(Set defines, Element grammar, Element node,
                          boolean followRefs)
  {
    String elementName = node.getLocalName();
    if ("define".equals(elementName))
      defines.add(node);
    else if ("ref".equals(elementName) && followRefs)
      {
        String rname = node.getAttribute("name");
        Element define = getFirstChildElement(grammar);
        define = getNextSiblingElement(define);
        while (define != null)
          {
            String dname = define.getAttribute("name");
            if (rname.equals(dname))
              {
                getDefines(defines, grammar, node, followRefs);
                break;
              }
            define = getNextSiblingElement(define);
          }
      }
    for (Element child = getFirstChildElement(node); child != null;
         child = getNextSiblingElement(child))
      getDefines(defines, grammar, child, followRefs);
  }

  private void getElements(Set elements, Element grammar, Element node)
  {
    String elementName = node.getLocalName();
    if ("element".equals(elementName))
      elements.add(node);
    for (Element child = getFirstChildElement(node); child != null;
         child = getNextSiblingElement(child))
      getElements(elements, grammar, child);
  }

  private void expandRefs(Set defines, Element node)
    throws GrammarException
  {
    String elementName = node.getLocalName();
    if ("ref".equals(elementName))
      {
        String rname = node.getAttribute("name");
        for (Iterator i = defines.iterator(); i.hasNext(); )
          {
            Element define = (Element) i.next();
            String dname = define.getAttribute("name");
            if (rname.equals(dname))
              {
                Element child = getFirstChildElement(define);
                forbidRefs(child, rname);
                Element refChild = (Element) child.cloneNode(true);
                Node parent = node.getParentNode();
                parent.insertBefore(refChild, node);
                parent.removeChild(node);
                node = refChild;
                break;
              }
          }
      }
    for (Element child = getFirstChildElement(node); child != null;
         child = getNextSiblingElement(child))
      expandRefs(defines, child);
  }

  private void forbidRefs(Element node, String name)
    throws GrammarException
  {
    String elementName = node.getLocalName();
    if ("ref".equals(elementName))
      {
        String rname = node.getAttribute("name");
        if (name.equals(rname))
          throw new GrammarException("cannot expand ref with name '" + name +
                                     "' due to circularity");
      }
    for (Element child = getFirstChildElement(node); child != null;
         child = getNextSiblingElement(child))
      forbidRefs(child, name);
  }

  private void transform(Node node)
    throws IOException
  {
    Node parent = node.getParentNode();
    switch (node.getNodeType())
      {
      case Node.ELEMENT_NODE:
        // 4.1 Annotations
        String elementNs = node.getNamespaceURI();
        String elementName = node.getLocalName();
        if (!XMLConstants.RELAXNG_NS_URI.equals(elementNs) ||
            !VOCABULARY.containsKey(elementName))
          parent.removeChild(node);
        else
          {
            Set allowedAttrs = (Set) VOCABULARY.get(elementName);
            NamedNodeMap attrs = node.getAttributes();
            int len = attrs.getLength();
            for (int i = len - 1; i >= 0; i--)
              {
                Node attr = attrs.item(i);
                String attrNs = attr.getNamespaceURI();
                String attrName = attr.getLocalName();
                if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(attrNs))
                  continue; // ignore namespace nodes
                if (!(XMLConstants.RELAXNG_NS_URI.equals(attrNs) ||
                      attrNs == null) ||
                    !allowedAttrs.contains(attrName))
                  attrs.removeNamedItemNS(attrNs, attrName);
                else
                  {
                    // 4.2 Whitespace
                    if (STRIPPED_ATTRIBUTES.contains(attrName))
                      attr.setNodeValue(attr.getNodeValue().trim());
                    // 4.3 datatypeLibrary attribute
                    else if ("datatypeLibrary".equals(attrName))
                      {
                        String dl = attr.getNodeValue();
                        attr.setNodeValue(escapeURL(dl));
                      }
                    // 4.5. href attribute
                    else if ("href".equals(attrName))
                      {
                        String href = attr.getNodeValue();
                        href = XMLParser.absolutize(node.getBaseURI(),
                                                    escapeURL(href));
                        attr.setNodeValue(href);
                      }
                  }
              }
            // 4.3 datatypeLibrary attribute
            if ("data".equals(elementName) || "value".equals(elementName))
              {
                Element element = (Element) node;
                String dl = element.getAttribute("datatypeLibrary");
                if (dl == null)
                  {
                    Node p = parent;
                    while (dl == null && p != null &&
                           p.getNodeType() == Node.ELEMENT_NODE)
                      {
                        dl = ((Element) p)
                          .getAttribute("datatypeLibrary");
                        p = p.getParentNode();
                      }
                    if (dl == null)
                      dl = "";
                    element.setAttribute("datatypeLibrary", dl);
                  }
                // 4.4. type attribute of value element
                if ("value".equals(elementName))
                  {
                    String type = element.getAttribute("type");
                    if (type == null)
                      {
                        element.setAttribute("type", "token");
                        element.setAttribute("datatypeLibrary", "");
                      }
                  }
                // 4.16. Constraints
                // TODO validate type
              }
            // 4.6. externalRef element
            else if ("externalRef".equals(elementName))
              {
                Element externalRef = (Element) node;
                String href = externalRef.getAttribute("href");
                // check for recursion
                if (urls.contains(href))
                  throw new GrammarException("recursive href");
                urls.add(href);
                Element element = resolve(href);
                String eNs = element.getNamespaceURI();
                String eName = element.getLocalName();
                if (!(XMLConstants.RELAXNG_NS_URI.equals(eNs) ||
                      eNs == null) ||
                    !PATTERN_ELEMENTS.contains(eName))
                  throw new GrammarException("externally referenced element " +
                                             "is not a pattern");
                transform(element);
                urls.remove(href);
                String ns = element.getAttribute("ns");
                if (ns != null)
                  element.setAttribute("ns",
                                       externalRef.getAttribute("ns"));
                element = (Element) externalRef.getOwnerDocument()
                  .importNode(element, true);
                parent.replaceChild(element, externalRef);
                return;
              }
            // 4.7 include element
            else if ("include".equals(elementName))
              {
                Element include = (Element) node;
                String href = include.getAttribute("href");
                // check for recursion
                if (urls.contains(href))
                  throw new GrammarException("recursive href");
                urls.add(href);
                Element element = resolve(href);
                String eNs = element.getNamespaceURI();
                String eName = element.getLocalName();
                if (!(XMLConstants.RELAXNG_NS_URI.equals(eNs) ||
                      eNs == null) ||
                    !"grammar".equals(eName))
                  throw new GrammarException("included element is not " +
                                             "a grammar");

                transform(element);
                urls.remove(href);
                // handle components
                List includeComponents = getComponents(include);
                List grammarComponents = getComponents(element);
                for (Iterator i = includeComponents.iterator(); i.hasNext(); )
                  {
                    Element comp = (Element) i.next();
                    String compName = comp.getLocalName();
                    if ("start".equals(compName))
                      {
                        boolean found = false;
                        for (Iterator j = grammarComponents.iterator();
                             j.hasNext(); )
                          {
                            Element c2 = (Element) j.next();
                            if ("start".equals(c2.getLocalName()))
                              {
                                c2.getParentNode().removeChild(c2);
                                found = true;
                              }
                          }
                        if (!found)
                          throw new GrammarException("no start component in " +
                                                     "included grammar");
                      }
                    else if ("define".equals(compName))
                      {
                        String name = comp.getAttribute("name");
                        boolean found = false;
                        for (Iterator j = grammarComponents.iterator();
                             j.hasNext(); )
                          {
                            Element c2 = (Element) j.next();
                            if ("define".equals(c2.getLocalName()) &&
                                name.equals(c2.getAttribute("name")))
                              {
                                c2.getParentNode().removeChild(c2);
                                found = true;
                              }
                          }
                        if (!found)
                          throw new GrammarException("no define component " +
                                                     "with name '" + name +
                                                     "' in included grammar");
                      }
                  }
                // transform to div element
                Document doc = include.getOwnerDocument();
                Element includeDiv =
                  doc.createElementNS(XMLConstants.RELAXNG_NS_URI, "div");
                Element grammarDiv =
                  doc.createElementNS(XMLConstants.RELAXNG_NS_URI, "div");
                // XXX copy include non-href attributes (none defined?)
                element = (Element) doc.importNode(element, true);
                Node ctx = element.getFirstChild();
                while (ctx != null)
                  {
                    Node next = ctx.getNextSibling();
                    grammarDiv.appendChild(ctx);
                    ctx = next;
                  }
                includeDiv.appendChild(grammarDiv);
                ctx = include.getFirstChild();
                while (ctx != null)
                  {
                    Node next = ctx.getNextSibling();
                    includeDiv.appendChild(ctx);
                    ctx = next;
                  }
                parent.replaceChild(includeDiv, include);
                transform(includeDiv);
                return;
              }
            // 4.8. name attribute of element and attribute elements
            else if ("attribute".equals(elementName) ||
                     "element".equals(elementName))
              {
                Element element = (Element) node;
                String name = element.getAttribute("name");
                if (name != null)
                  {
                    Document doc = element.getOwnerDocument();
                    Element n =
                      doc.createElementNS(XMLConstants.RELAXNG_NS_URI, "name");
                    n.appendChild(doc.createTextNode(name));
                    Node first = element.getFirstChild();
                    if (first != null)
                      element.insertBefore(n, first);
                    else
                      element.appendChild(n);
                    if ("attribute".equals(elementName))
                      {
                        String ns = element.getAttribute("ns");
                        if (ns != null)
                          {
                            n.setAttribute("ns", ns);
                            element.removeAttribute("ns");
                          }
                      }
                    element.removeAttribute("name");
                  }
                // 4.12. Number of child elements
                if ("attribute".equals(elementName))
                  {
                    if (getComponents(node).size() == 1)
                      {
                        Document doc = node.getOwnerDocument();
                        Element text =
                          doc.createElementNS(XMLConstants.RELAXNG_NS_URI,
                                              "text");
                        node.appendChild(text);
                      }
                  }
                else // element
                  {
                    if (node.getChildNodes().getLength() > 2)
                      {
                        // transform to 2 child elements
                        Document doc = node.getOwnerDocument();
                        Element child =
                          doc.createElementNS(XMLConstants.RELAXNG_NS_URI,
                                              "group");
                        Node ctx = getFirstChildElement(node);
                        ctx = getNextSiblingElement(ctx); // skip 1
                        while (ctx != null)
                          {
                            Node next = getNextSiblingElement(ctx);
                            child.appendChild(ctx);
                            ctx = next;
                          }
                        node.appendChild(child);
                      }
                  }
              }
            // 4.11. div element
            else if ("div".equals(elementName))
              {
                Node ctx = node.getFirstChild();
                while (ctx != null)
                  {
                    Node next = ctx.getNextSibling();
                    parent.insertBefore(ctx, node);
                    transform(ctx);
                    ctx = next;
                  }
                parent.removeChild(node);
                return;
              }
            else if ("mixed".equals(elementName))
              {
                // 4.12. Number of child elements
                transformToOneChildElement(node, "group");
                // 4.13. mixed element
                Document doc = node.getOwnerDocument();
                Node interleave =
                  doc.createElementNS(XMLConstants.RELAXNG_NS_URI,
                                      "interleave");
                Node ctx = node.getFirstChild();
                while (ctx != null)
                  {
                    Node next = ctx.getNextSibling();
                    interleave.appendChild(ctx);
                    ctx = next;
                  }
                Node text =
                  doc.createElementNS(XMLConstants.RELAXNG_NS_URI,
                                      "text");
                interleave.appendChild(text);
                parent.insertBefore(interleave, node);
                parent.removeChild(node);
                node = interleave;
              }
            else if ("optional".equals(elementName))
              {
                // 4.12. Number of child elements
                transformToOneChildElement(node, "group");
                // 4.14. optional element
                Document doc = node.getOwnerDocument();
                Node choice =
                  doc.createElementNS(XMLConstants.RELAXNG_NS_URI,
                                      "choice");
                Node ctx = node.getFirstChild();
                while (ctx != null)
                  {
                    Node next = ctx.getNextSibling();
                    choice.appendChild(ctx);
                    ctx = next;
                  }
                Node empty =
                  doc.createElementNS(XMLConstants.RELAXNG_NS_URI,
                                      "empty");
                choice.appendChild(empty);
                parent.insertBefore(choice, node);
                parent.removeChild(node);
                node = choice;
              }
            else if ("zeroOrMore".equals(elementName))
              {
                // 4.12. Number of child elements
                transformToOneChildElement(node, "group");
                // 4.15. zeroOrMore element
                Document doc = node.getOwnerDocument();
                Node choice =
                  doc.createElementNS(XMLConstants.RELAXNG_NS_URI,
                                      "choice");
                Node oneOrMore =
                  doc.createElementNS(XMLConstants.RELAXNG_NS_URI,
                                      "oneOrMore");
                Node ctx = node.getFirstChild();
                while (ctx != null)
                  {
                    Node next = ctx.getNextSibling();
                    oneOrMore.appendChild(ctx);
                    ctx = next;
                  }
                Node empty =
                  doc.createElementNS(XMLConstants.RELAXNG_NS_URI,
                                      "empty");
                choice.appendChild(oneOrMore);
                choice.appendChild(empty);
                parent.insertBefore(choice, node);
                parent.removeChild(node);
                node = choice;
              }
            else if ("list".equals(elementName) ||
                     "oneOrMore".equals(elementName) ||
                     "define".equals(elementName))
              {
                // 4.12. Number of child elements
                transformToOneChildElement(node, "group");
              }
            else if ("except".equals(elementName))
              {
                // 4.12. Number of child elements
                transformToOneChildElement(node, "choice");
                // 4.16. Constraints
                String parentName = parent.getLocalName();
                if ("anyName".equals(parentName))
                  forbidDescendants(node, Collections.singleton("anyName"));
                else if ("nsName".equals(parentName))
                  {
                    Set names = new HashSet();
                    names.add("nsName");
                    names.add("anyName");
                    forbidDescendants(node, names);
                  }
              }
            else if ("choice".equals(elementName) ||
                     "group".equals(elementName) ||
                     "interleave".equals(elementName))
              {
                // 4.12. Number of child elements
                Node ctx = getFirstChildElement(node);
                Node next = getNextSiblingElement(ctx);
                if (next == null)
                  {
                    // replace
                    parent.insertBefore(ctx, node);
                    parent.removeChild(node);
                    transform(ctx);
                    return;
                  }
                else
                  {
                    // transform to 2 child elements
                    Node next2 = getNextSiblingElement(next);
                    if (next2 != null)
                      {
                        Document doc = node.getOwnerDocument();
                        Node child =
                          doc.createElementNS(XMLConstants.RELAXNG_NS_URI,
                                              elementName);
                        child.appendChild(ctx);
                        child.appendChild(next);
                        node.insertBefore(next2, child);
                        transform(node); // recurse
                      }
                  }
              }
            // 4.17. combine attribute
            else if ("grammar".equals(elementName))
              {
                String combine = null;
                List nodes = new LinkedList();
                Node ctx = node.getFirstChild();
                while (ctx != null)
                  {
                    Node next = ctx.getNextSibling();
                    if ("start".equals(ctx.getLocalName()))
                      {
                        String c = ((Element) ctx).getAttribute("combine");
                        if (combine != null && !combine.equals(c))
                          throw new GrammarException("multiple start elements "+
                                                     "but no combine attribute");
                        combine = c;
                        nodes.add(ctx);
                      }
                    ctx = next;
                  }
                if (!nodes.isEmpty())
                  combineNodes(node, combine, "start", nodes);
                // defines
                Map defines = new HashMap();
                Map defineCombines = new HashMap();
                ctx = node.getFirstChild();
                while (ctx != null)
                  {
                    Node next = ctx.getNextSibling();
                    if ("define".equals(ctx.getLocalName()))
                      {
                        String name = ((Element) ctx).getAttribute("name");
                        combine = (String) defineCombines.get(name);
                        String c = ((Element) ctx).getAttribute("combine");
                        if (combine != null && !combine.equals(c))
                          throw new GrammarException("multiple define " +
                                                     "elements with name '"+
                                                     name + "' but no " +
                                                     "combine attribute");
                        defineCombines.put(name, c);
                        nodes = (List) defines.get(name);
                        if (nodes == null)
                          {
                            nodes = new LinkedList();
                            defines.put(name, nodes);
                          }
                        nodes.add(ctx);
                      }
                    ctx = next;
                  }
                for (Iterator i = defines.keySet().iterator(); i.hasNext(); )
                  {
                    String name = (String) i.next();
                    combine = (String) defineCombines.get(name);
                    nodes = (List) defines.get(name);
                    if (!nodes.isEmpty())
                      combineNodes(node, combine, "define", nodes);
                  }
              }
            // 4.9. ns attribute
            if ("name".equals(elementName) ||
                "nsName".equals(elementName) ||
                "value".equals(elementName))
              {
                Element element = (Element) node;
                String ns = element.getAttribute("ns");
                if (ns == null)
                  {
                    Node ctx = parent;
                    while (ns == null && ctx != null &&
                           ctx.getNodeType() == Node.ELEMENT_NODE)
                      {
                        ns = ((Element) ctx).getAttribute("ns");
                        ctx = ctx.getParentNode();
                      }
                    element.setAttribute("ns", (ns == null) ? "" : ns);
                  }
                if ("name".equals(elementName))
                  {
                    // 4.10. QNames
                    String name = element.getTextContent();
                    int ci = name.indexOf(':');
                    if (ci != -1)
                      {
                        String prefix = name.substring(0, ci);
                        element.setTextContent(name.substring(ci + 1));
                        ns = element.lookupNamespaceURI(prefix);
                        element.setAttribute("ns", (ns == null) ? "" : ns);
                      }
                    // 4.16. Constraints
                    if (isDescendantOfFirstChildOfAttribute(element) &&
                        "".equals(element.getAttribute("ns")) &&
                        "xmlns".equals(element.getTextContent()))
                      throw new GrammarException("name cannot be xmlns");
                  }
                else if ("nsName".equals(elementName))
                  {
                    // 4.16. Constraints
                    if (isDescendantOfFirstChildOfAttribute(element) &&
                        "http://www.w3.org/2000/xmlns"
                        .equals(element.getAttribute("ns")))
                      throw new GrammarException("nsName cannot be XMLNS URI");
                  }
              }
          }

        break;
      case Node.TEXT_NODE:
      case Node.CDATA_SECTION_NODE:
        // 4.2 Whitespace
        String parentName = parent.getLocalName();
        if ("name".equals(parentName))
          node.setNodeValue(node.getNodeValue().trim());
        if (!"param".equals(parentName) &&
            !"value".equals(parentName) &&
            isWhitespace(node.getNodeValue()))
          parent.removeChild(node);
        break;
      case Node.DOCUMENT_NODE:
        break;
      default:
        parent.removeChild(node);
      }
    // Transform children
    Node ctx = node.getFirstChild();
    while (ctx != null)
      {
        Node next = ctx.getNextSibling();
        transform(ctx);
        ctx = next;
      }
  }

  /**
   * Transforms the schema to place all defines under the top-level grammar
   * element and replace all other grammar elements by their start child.
   */
  private void transformGrammar(Node grammar, Node node)
    throws GrammarException
  {
    if (node.getNodeType() == Node.ELEMENT_NODE)
      {
        String elementName = node.getLocalName();
        if ("grammar".equals(elementName))
          {
            handleRefs(grammar, node, node);
            Node start = null;
            Node ctx = node.getFirstChild();
            while (ctx != null)
              {
                Node next = ctx.getNextSibling();
                String childName = ctx.getLocalName();
                if ("define".equals(childName))
                  grammar.appendChild(ctx);
                else if ("start".equals(childName))
                  start = ctx;
                ctx = next;
              }
            if (start == null)
              throw new GrammarException("no start element for grammar");
            Node p = getFirstChildElement(start);
            Node parent = node.getParentNode();
            parent.insertBefore(p, node);
            parent.removeChild(node);
            node = p;
          }
        Node ctx = node.getFirstChild();
        while (ctx != null)
          {
            Node next = ctx.getNextSibling();
            transformGrammar(grammar, ctx);
            ctx = next;
          }
      }
  }

  /**
   * Checks that all references in the specified grammar match a define in
   * the grammar.
   */
  private void handleRefs(Node grammar1, Node grammar2, Node node)
    throws GrammarException
  {
    if (node.getNodeType() == Node.ELEMENT_NODE)
      {
        String elementName = node.getLocalName();
        if ("ref".equals(elementName) || "parentRef".equals(elementName))
          {
            Node grammar = grammar2;
            if ("parentRef".equals(elementName))
              grammar = grammar1;

            String name = ((Element) node).getAttribute("name");
            if (name != null)
              throw new GrammarException("no name attribute on " +
                                         elementName);
            Node define = null;
            for (Node ctx = grammar.getFirstChild();
                 define == null && ctx != null;
                 ctx = ctx.getNextSibling())
              {
                if ("define".equals(ctx.getLocalName()))
                  {
                    String dname = ((Element) ctx).getAttribute("name");
                    if (name.equals(dname))
                      define = ctx;
                  }
              }
            if (define == null)
              throw new GrammarException("no define for '" + name + "'");
            name = ((Element) define).getAttribute("new-name");
            if (name == null)
              {
                name = createRefName();
                ((Element) define).setAttribute("new-name", name);
              }
            if ("parentRef".equals(elementName))
              {
                Document doc = node.getOwnerDocument();
                Node ref = doc.createElementNS(XMLConstants.RELAXNG_NS_URI,
                                               "ref");
                Node ctx = node.getFirstChild();
                while (ctx != null)
                  {
                    Node next = ctx.getNextSibling();
                    ref.appendChild(ctx);
                    ctx = next;
                  }
                Node parent = node.getParentNode();
                parent.insertBefore(ref, node);
                parent.removeChild(node);
                node = ref;
              }
            ((Element) node).setAttribute("name", name);
          }
        else if ("grammar".equals(elementName))
          {
            grammar1 = grammar2;
            grammar2 = node;
          }
        Node ctx = node.getFirstChild();
        while (ctx != null)
          {
            Node next = ctx.getNextSibling();
            handleRefs(grammar1, grammar2, ctx);
            ctx = next;
          }
      }
  }

  private String createRefName()
  {
    return "ref" + Integer.toString(refCount++);
  }

  private void transform2(Node node)
    throws GrammarException
  {
    Node parent = node.getParentNode();
    if (node.getNodeType() == Node.ELEMENT_NODE)
      {
        String elementName = node.getLocalName();
        // 4.20. notAllowed element
        if ("notAllowed".equals(elementName))
          {
            String parentName = parent.getLocalName();
            if ("attribute".equals(parentName) ||
                "list".equals(parentName) ||
                "group".equals(parentName) ||
                "interleave".equals(parentName) ||
                "oneOrMore".equals(parentName))
              {
                Node pp = parent.getParentNode();
                pp.insertBefore(node, parent);
                pp.removeChild(parent);
                transform2(node); // apply recursively
                return;
              }
            else if ("choice".equals(parentName))
              {
                Node p1 = getFirstChildElement(parent);
                Node p2 = getNextSiblingElement(p1);
                if (p1 == null || p2 == null)
                  throw new GrammarException("choice does not have two " +
                                             "children");
                String p1Name = p1.getLocalName();
                String p2Name = p2.getLocalName();
                Node pp = parent.getParentNode();
                if ("notAllowed".equals(p1Name) &&
                    "notAllowed".equals(p2Name))
                  {
                    pp.insertBefore(p1, parent);
                    pp.removeChild(parent);
                    transform2(p1); //apply recursively
                    return;
                  }
                else if ("notAllowed".equals(p1Name))
                  {
                    pp.insertBefore(p2, parent);
                    pp.removeChild(parent);
                    transform2(p2);
                    return;
                  }
                else
                  {
                    pp.insertBefore(p1, parent);
                    pp.removeChild(parent);
                    transform2(p1);
                    return;
                  }
              }
            else if ("except".equals(parentName))
              {
                Node pp = parent.getParentNode();
                pp.removeChild(parent);
                return;
              }
          }
        // 4.21. empty element
        else if ("empty".equals(elementName))
          {
            String parentName = parent.getLocalName();
            if ("group".equals(parentName) ||
                "interleave".equals(parentName))
              {
                Node p1 = getFirstChildElement(parent);
                Node p2 = getNextSiblingElement(p1);
                if (p1 == null || p2 == null)
                  throw new GrammarException(parentName + " does not have " +
                                             "two children");
                String p1Name = p1.getLocalName();
                String p2Name = p2.getLocalName();
                Node pp = parent.getParentNode();
                if ("empty".equals(p1Name) &&
                    "empty".equals(p2Name))
                  {
                    pp.insertBefore(p1, parent);
                    pp.removeChild(parent);
                    transform2(p1);
                    return;
                  }
                else if ("empty".equals(p1Name))
                  {
                    pp.insertBefore(p2, parent);
                    pp.removeChild(parent);
                    transform2(p2);
                    return;
                  }
                else
                  {
                    pp.insertBefore(p1, parent);
                    pp.removeChild(parent);
                    transform2(p1);
                    return;
                  }
              }
            else if ("choice".equals(parentName))
              {
                Node p1 = getFirstChildElement(parent);
                Node p2 = getNextSiblingElement(p1);
                if (p1 == null || p2 == null)
                  throw new GrammarException(parentName + " does not have " +
                                             "two children");
                String p1Name = p1.getLocalName();
                String p2Name = p2.getLocalName();
                Node pp = parent.getParentNode();
                if ("empty".equals(p1Name) &&
                    "empty".equals(p2Name))
                  {
                    pp.insertBefore(p1, parent);
                    pp.removeChild(parent);
                    transform2(p1);
                    return;
                  }
              }
            else if ("oneOrMore".equals(parentName))
              {
                Node pp = parent.getParentNode();
                pp.insertBefore(node, parent);
                pp.removeChild(parent);
                transform2(node);
                return;
              }
          }
        Node ctx = node.getFirstChild();
        while (ctx != null)
          {
            Node next = ctx.getNextSibling();
            transform2(ctx);
            ctx = next;
          }
      }
  }

  private static boolean isWhitespace(String text)
  {
    int len = text.length();
    for (int i = 0; i < len; i++)
      {
        char c = text.charAt(i);
        if (c != ' ' && c != '\t' && c != '\n' && c != '\r')
          return false;
      }
    return true;
  }

  private static String escapeURL(String url)
  {
    try
      {
        return URLEncoder.encode(url, "UTF-8");
      }
    catch (UnsupportedEncodingException e)
      {
        RuntimeException e2 = new RuntimeException("UTF-8 is unsupported");
        e2.initCause(e);
        throw e2;
      }
  }

  /**
   * Resolve a URL to an element, as described in section 4.5.
   */
  private static Element resolve(String url)
    throws IOException
  {
    try
      {
        URL u = new URL(url);
        InputStream in = u.openStream();
        DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
        f.setNamespaceAware(true);
        f.setCoalescing(true);
        f.setExpandEntityReferences(true);
        f.setIgnoringComments(true);
        f.setIgnoringElementContentWhitespace(true);
        DocumentBuilder b = f.newDocumentBuilder();
        Document doc = b.parse(in, url);
        in.close();
        String fragment = u.getRef();
        if (fragment != null)
          return doc.getElementById(fragment);
        return doc.getDocumentElement();
      }
    catch (SAXException e)
      {
        IOException e2 = new IOException("error parsing included element");
        e2.initCause(e);
        throw e2;
      }
    catch (ParserConfigurationException e)
      {
        IOException e2 = new IOException("error parsing included element");
        e2.initCause(e);
        throw e2;
      }
  }

  /**
   * Returns the "components" of an element, as described in section 4.7.
   */
  private List getComponents(Node node)
  {
    List ret = new LinkedList();
    for (Node ctx = node.getFirstChild(); ctx != null;
         ctx = ctx.getNextSibling())
      {
        if (ctx.getNodeType() != Node.ELEMENT_NODE)
          continue;
        String ns = ctx.getNamespaceURI();
        if (ns != null && !ns.equals(XMLConstants.RELAXNG_NS_URI))
          continue;
        String name = ctx.getLocalName();
        if ("div".equals(name))
          ret.addAll(getComponents(ctx));
        else if (VOCABULARY.containsKey(name))
          ret.add(ctx);
      }
    return ret;
  }

  private static void transformToOneChildElement(Node node, String name)
  {
    if (node.getChildNodes().getLength() < 2)
      return;
    Document doc = node.getOwnerDocument();
    Element child = doc.createElementNS(XMLConstants.RELAXNG_NS_URI, name);
    Node ctx = getFirstChildElement(node);
    while (ctx != null)
      {
        Node next = getNextSiblingElement(ctx);
        child.appendChild(ctx);
        ctx = next;
      }
    node.appendChild(child);
  }

  private static Element getFirstChildElement(Node node)
  {
    Node ctx = node.getFirstChild();
    while (ctx != null && ctx.getNodeType() != Node.ELEMENT_NODE)
      ctx = ctx.getNextSibling();
    return (Element) ctx;
  }

  private static Element getNextSiblingElement(Node node)
  {
    Node ctx = node.getNextSibling();
    while (ctx != null && ctx.getNodeType() != Node.ELEMENT_NODE)
      ctx = ctx.getNextSibling();
    return (Element) ctx;
  }

  private static void forbidDescendants(Node node, Set names)
    throws GrammarException
  {
    for (Node ctx = node.getFirstChild(); ctx != null;
         ctx = ctx.getNextSibling())
      {
        String ns = ctx.getNamespaceURI();
        if (!XMLConstants.RELAXNG_NS_URI.equals(ns))
          continue;
        String name = ctx.getLocalName();
        if (names.contains(name))
          throw new GrammarException("name not allowed: " + name);
        forbidDescendants(ctx, names);
      }
  }

  private static boolean isDescendantOfFirstChildOfAttribute(Node node)
  {
    Node child = node;
    Node parent = node.getParentNode();
    while (parent != null && !"attribute".equals(parent.getLocalName()))
      {
        child = parent;
        parent = child.getParentNode();
      }
    if (parent == null)
      return false;
    Node firstChild = getFirstChildElement(parent);
    return firstChild == child;
  }

  private static void combineNodes(Node node, String combine, String name,
                                   List nodes)
  {
    Document doc = node.getOwnerDocument();
    Node child =
      doc.createElementNS(XMLConstants.RELAXNG_NS_URI, name);
    Node combineNode =
      doc.createElementNS(XMLConstants.RELAXNG_NS_URI, combine);
    child.appendChild(combineNode);
    boolean inserted = false;
    for (Iterator i = nodes.iterator(); i.hasNext(); )
      {
        Node startNode = (Node) i.next();
        if (!inserted)
          {
            node.insertBefore(child, startNode);
            inserted = true;
          }
        Node ctx = startNode.getFirstChild();
        while (ctx != null)
          {
            Node next = ctx.getNextSibling();
            combineNode.appendChild(ctx);
            ctx = next;
          }
        node.removeChild(startNode);
      }
  }

  Grammar parseGrammar(Element node)
    throws GrammarException
  {
    checkName(node, "grammar");
    Grammar grammar = new Grammar();
    Element start = getFirstChildElement(node);
    grammar.start = parsePattern(getFirstChildElement(start));
    for (Element define = getNextSiblingElement(start); define != null;
         define = getNextSiblingElement(define))
      grammar.defines.add(parseDefine(define));
    return grammar;
  }

  Define parseDefine(Element node)
    throws GrammarException
  {
    checkName(node, "define");
    Define define = new Define();
    define.name = node.getAttribute("name");
    define.element = parseElement(getFirstChildElement(node));
    return define;
  }

  Pattern parseTop(Element node)
    throws GrammarException
  {
    String name = node.getLocalName();
    if ("notAllowed".equals(name))
      return parseNotAllowed(node);
    return parsePattern(node);
  }

  Pattern parsePattern(Element node)
    throws GrammarException
  {
    String name = node.getLocalName();
    if ("empty".equals(name))
      return parseEmpty(node);
    return parseNonEmptyPattern(node);
  }

  Pattern parseNonEmptyPattern(Element node)
    throws GrammarException
  {
    String name = node.getLocalName();
    if ("text".equals(name))
      return parseText(node);
    else if ("data".equals(name))
      return parseData(node);
    else if ("value".equals(name))
      return parseValue(node);
    else if ("list".equals(name))
      return parseList(node);
    else if ("attribute".equals(name))
      return parseAttribute(node);
    else if ("ref".equals(name))
      return parseRef(node);
    else if ("oneOrMore".equals(name))
      return parseOneOrMore(node);
    else if ("choice".equals(name))
      return parseChoice(node);
    else if ("group".equals(name))
      return parseGroup(node);
    else if ("interleave".equals(name))
      return parseInterleave(node);
    throw new GrammarException("invalid pattern: " + name);
  }

  ElementPattern parseElement(Element node)
    throws GrammarException
  {
    checkName(node, "element");
    ElementPattern element = new ElementPattern();
    Element nameClass = getFirstChildElement(node);
    element.nameClass = parseNameClass(nameClass);
    element.pattern = parseTop(getNextSiblingElement(nameClass));
    return element;
  }

  NotAllowedPattern parseNotAllowed(Element node)
    throws GrammarException
  {
    checkName(node, "notAllowed");
    return NotAllowedPattern.INSTANCE;
  }

  EmptyPattern parseEmpty(Element node)
    throws GrammarException
  {
    checkName(node, "empty");
    return EmptyPattern.INSTANCE;
  }

  TextPattern parseText(Element node)
    throws GrammarException
  {
    checkName(node, "text");
    return TextPattern.INSTANCE;
  }

  DataPattern parseData(Element node)
    throws GrammarException
  {
    checkName(node, "data");
    DataPattern data = new DataPattern();
    DatatypeLibrary dl =
      getDatatypeLibrary(node.getAttribute("datatypeLibrary"));
    String type = node.getAttribute("type");
    try
      {
        data.type = dl.createDatatype(type);
        data.datatypeLibrary = dl;
      }
    catch (DatatypeException e)
      {
        GrammarException e2 = new GrammarException(type);
        e2.initCause(e);
        throw e2;
      }
    Element ctx = getFirstChildElement(node);
    while (ctx != null)
      {
        Element next = getNextSiblingElement(ctx);
        String name = ctx.getLocalName();
        if ("param".equals(name))
          data.params.add(parseParam(ctx));
        else if ("except".equals(name) && next == null)
          data.exceptPattern = parsePattern(getFirstChildElement(ctx));
        else
          throw new GrammarException("invalid element: " + name);
        ctx = next;
      }
    return data;
  }

  Param parseParam(Element node)
    throws GrammarException
  {
    checkName(node, "param");
    Param param  = new Param();
    param.name = node.getAttribute("name");
    param.value = node.getTextContent();
    return param;
  }

  ValuePattern parseValue(Element node)
    throws GrammarException
  {
    checkName(node, "value");
    ValuePattern value = new ValuePattern();
    DatatypeLibrary dl =
      getDatatypeLibrary(node.getAttribute("datatypeLibrary"));
    String type = node.getAttribute("type");
    try
      {
        value.type = dl.createDatatype(type);
        value.datatypeLibrary = dl;
      }
    catch (DatatypeException e)
      {
        GrammarException e2 = new GrammarException(type);
        e2.initCause(e);
        throw e2;
      }
    value.ns = node.getAttribute("ns");
    value.value = node.getTextContent();
    return value;
  }

  ListPattern parseList(Element node)
    throws GrammarException
  {
    checkName(node, "list");
    ListPattern list = new ListPattern();
    list.pattern = parsePattern(getFirstChildElement(node));
    return list;
  }

  AttributePattern parseAttribute(Element node)
    throws GrammarException
  {
    checkName(node, "attribute");
    AttributePattern attribute = new AttributePattern();
    Element nameClass = getFirstChildElement(node);
    attribute.nameClass = parseNameClass(nameClass);
    attribute.pattern = parsePattern(getNextSiblingElement(nameClass));
    return attribute;
  }

  RefPattern parseRef(Element node)
    throws GrammarException
  {
    checkName(node, "ref");
    RefPattern ref = new RefPattern();
    ref.name = node.getAttribute("name");
    return ref;
  }

  OneOrMorePattern parseOneOrMore(Element node)
    throws GrammarException
  {
    checkName(node, "oneOrMore");
    OneOrMorePattern oneOrMore = new OneOrMorePattern();
    oneOrMore.pattern = parseNonEmptyPattern(getFirstChildElement(node));
    return oneOrMore;
  }

  ChoicePattern parseChoice(Element node)
    throws GrammarException
  {
    checkName(node, "choice");
    ChoicePattern choice = new ChoicePattern();
    Element p1 = getFirstChildElement(node);
    Element p2 = getNextSiblingElement(p1);
    choice.pattern1 = parsePattern(p1);
    choice.pattern2 = parseNonEmptyPattern(p2);
    return choice;
  }

  GroupPattern parseGroup(Element node)
    throws GrammarException
  {
    checkName(node, "group");
    GroupPattern group = new GroupPattern();
    Element p1 = getFirstChildElement(node);
    Element p2 = getNextSiblingElement(p1);
    group.pattern1 = parseNonEmptyPattern(p1);
    group.pattern2 = parseNonEmptyPattern(p2);
    return group;
  }

  InterleavePattern parseInterleave(Element node)
    throws GrammarException
  {
    checkName(node, "interleave");
    InterleavePattern interleave = new InterleavePattern();
    Element p1 = getFirstChildElement(node);
    Element p2 = getNextSiblingElement(p1);
    interleave.pattern1 = parseNonEmptyPattern(p1);
    interleave.pattern2 = parseNonEmptyPattern(p2);
    return interleave;
  }

  NameClass parseNameClass(Element node)
    throws GrammarException
  {
    String name = node.getLocalName();
    if ("anyName".equals(name))
      return parseAnyName(node);
    else if ("name".equals(name))
      return parseName(node);
    else if ("nsName".equals(name))
      return parseNsName(node);
    else if ("choice".equals(name))
      return parseChoiceNameClass(node);
    throw new GrammarException("invalid name class: " + name);
  }

  AnyNameNameClass parseAnyName(Element node)
    throws GrammarException
  {
    checkName(node, "anyName");
    AnyNameNameClass anyName = new AnyNameNameClass();
    Element except = getFirstChildElement(node);
    if (except != null) {
      checkName(except, "except");
      anyName.exceptNameClass = parseNameClass(getFirstChildElement(except));
    }
    return anyName;
  }

  NameNameClass parseName(Element node)
    throws GrammarException
  {
    checkName(node, "name");
    NameNameClass name = new NameNameClass();
    name.ns = node.getAttribute("ns");
    name.name = node.getTextContent();
    return name;
  }

  NSNameNameClass parseNsName(Element node)
    throws GrammarException
  {
    checkName(node, "nsName");
    NSNameNameClass nsName = new NSNameNameClass();
    nsName.ns = node.getAttribute("ns");
    Element except = getFirstChildElement(node);
    if (except != null) {
      checkName(except, "except");
      nsName.exceptNameClass = parseNameClass(getFirstChildElement(except));
    }
    return nsName;
  }

  ChoiceNameClass parseChoiceNameClass(Element node)
    throws GrammarException
  {
    checkName(node, "choice");
    ChoiceNameClass choice = new ChoiceNameClass();
    Element c1 = getFirstChildElement(node);
    Element c2 = getNextSiblingElement(c1);
    choice.name1 = parseNameClass(c1);
    choice.name2 = parseNameClass(c2);
    return choice;
  }

  void checkName(Element node, String name)
    throws GrammarException
  {
    if (!name.equals(node.getLocalName()))
      throw new GrammarException("expecting " + name);
  }

  DatatypeLibrary getDatatypeLibrary(String uri)
    throws GrammarException
  {
    if (datatypeLibraries == null)
      datatypeLibraries = new HashMap();
    DatatypeLibrary library = (DatatypeLibrary) datatypeLibraries.get(uri);
    if (library == null)
      {
        library = new DatatypeLibraryLoader().createDatatypeLibrary(uri);
        if (library == null)
          throw new GrammarException("Datatype library not supported: " + uri);
        datatypeLibraries.put(uri, library);
      }
    return library;
  }

}