File: FXXML.cpp

package info (click to toggle)
gogglesmm 1.2.5-6
  • links: PTS
  • area: main
  • in suites: forky, sid
  • size: 16,812 kB
  • sloc: cpp: 231,960; ansic: 893; xml: 222; makefile: 33
file content (1714 lines) | stat: -rw-r--r-- 46,359 bytes parent folder | download | duplicates (2)
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
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
/********************************************************************************
*                                                                               *
*                       X M L   R e a d e r  &  W r i t e r                     *
*                                                                               *
*********************************************************************************
* Copyright (C) 2016,2022 by Jeroen van der Zijp.   All Rights Reserved.        *
*********************************************************************************
* This library is free software; you can redistribute it and/or modify          *
* it under the terms of the GNU Lesser General Public License as published by   *
* the Free Software Foundation; either version 3 of the License, or             *
* (at your option) any later version.                                           *
*                                                                               *
* This library 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 Lesser General Public License for more details.                           *
*                                                                               *
* You should have received a copy of the GNU Lesser General Public License      *
* along with this program.  If not, see <http://www.gnu.org/licenses/>          *
********************************************************************************/
#include "xincs.h"
#include "fxver.h"
#include "fxdefs.h"
#include "fxchar.h"
#include "fxmath.h"
#include "fxascii.h"
#include "fxunicode.h"
#include "FXElement.h"
#include "FXArray.h"
#include "FXString.h"
#include "FXParseBuffer.h"
#include "FXException.h"
#include "FXStringDictionary.h"
#include "FXCallback.h"
#include "FXXML.h"

/*
  Notes:

  XML in Extended Backus-Naur form:
  =================================

  - First couple of bytes are tested to determine encoding used in the stream, which is made available
    in the 'enc' member variable.  The parser expects the subclass to use this variable to deliver UTF8
    into the parse buffer, however.  Therefore, the fill() API must fetch bytes from the file/device,
    decode them (if not already in UTF8 format), and leave the UTF8 in the parse buffer.

  - Grammar rules:

    //// Document structure syntax
    document             ::=    ( prolog element Misc* ) - ( Char* RestrictedChar Char* )

    //// XML Header syntax
    prolog               ::=    XMLDecl Misc* (doctypedecl Misc*)?
    XMLDecl              ::=    '<?xml' VersionInfo EncodingDecl? SDDecl? S? '?>'
    VersionInfo          ::=    S 'version' Eq ("'" VersionNum "'" | '"' VersionNum '"')
    VersionNum           ::=    '1.1'
    EncodingDecl         ::=    S 'encoding' Eq ('"' EncName '"' | "'" EncName "'" )
    EncName              ::=    [A-Za-z] ([A-Za-z0-9._] | '-')*
    SDDecl               ::=    S 'standalone' Eq (("'" ('yes' | 'no') "'") | ('"' ('yes' | 'no') '"'))

    //// Document type syntax
    doctypedecl          ::=    '<!DOCTYPE' S Name (S ExternalID)? S? ('[' intSubset ']' S?)? '>'

    ExternalID           ::=    'SYSTEM' S SystemLiteral | 'PUBLIC' S PubidLiteral S SystemLiteral
    SystemLiteral        ::=    ('"' [^"]* '"') | ("'" [^']* "'")
    PublicID             ::=    'PUBLIC' S PubidLiteral
    PubidLiteral         ::=    '"' PubidChar* '"' | "'" (PubidChar - "'")* "'"
    PubidChar            ::=    #x20 | #xD | #xA | [a-zA-Z0-9] | [-'()+,./:=?;!*#@$_%]

    intSubset            ::=    (markupdecl | DeclSep)*
    markupdecl           ::=    elementdecl | AttlistDecl | EntityDecl | NotationDecl | PI | Comment
    DeclSep              ::=    PEReference | S
    PEReference          ::=    '%' Name ';'

    //// Element declaration
    elementdecl          ::=    '<!ELEMENT' S Name S contentspec S? '>'
    contentspec          ::=    'EMPTY' | 'ANY' | Mixed | children
    Mixed                ::=    '(' S? '#PCDATA' (S? '|' S? Name)* S? ')*' | '(' S? '#PCDATA' S? ')'
    children             ::=    (choice | seq) ('?' | '*' | '+')?
    choice               ::=    '(' S? cp ( S? '|' S? cp)+ S? ')'
    seq                  ::=    '(' S? cp ( S? ',' S? cp )* S? ')'
    cp                   ::=    (Name | choice | seq) ('?' | '*' | '+')?

    //// Attribute declaration
    AttlistDecl          ::=    '<!ATTLIST' S Name AttDef* S? '>'
    AttDef               ::=    S Name S AttType S DefaultDecl
    AttType              ::=    StringType | TokenizedType | EnumeratedType
    StringType           ::=    'CDATA'
    TokenizedType        ::=    'ID' | 'IDREF' | 'IDREFS' | 'ENTITY' | 'ENTITIES' | 'NMTOKEN' | 'NMTOKENS'
    EnumeratedType       ::=    NotationType | Enumeration
    NotationType         ::=    'NOTATION' S '(' S? Name (S? '|' S? Name)* S? ')'
    Enumeration          ::=    '(' S? Nmtoken (S? '|' S?  Nmtoken)* S? ')'
    Nmtoken              ::=    (NameChar)+
    Nmtokens             ::=    Nmtoken (#x20 Nmtoken)*

    //// Default declaration
    DefaultDecl          ::=    '#REQUIRED' | '#IMPLIED' | (('#FIXED' S)? AttValue)

    //// Entity declarations
    EntityDecl           ::=    GEDecl | PEDecl
    GEDecl               ::=    '<!ENTITY' S Name S EntityDef S? '>'
    EntityDef            ::=    EntityValue | (ExternalID NDataDecl?)
    EntityValue          ::=    '"' ([^%&"] | PEReference | Reference)* '"' |  "'" ([^%&'] | PEReference | Reference)* "'"
    NDataDecl            ::=    S 'NDATA' S Name
    PEDecl               ::=    '<!ENTITY' S '%' S Name S PEDef S? '>'
    PEDef                ::=    EntityValue | ExternalID

    //// Notation declaration
    NotationDecl         ::=    '<!NOTATION' S Name S (ExternalID | PublicID) S? '>'


    //// Element syntax (the beaf)
    element              ::=    EmptyElemTag | STag content ETag
    EmptyElemTag         ::=    '<' Name (S Attribute)* S? '/>'
    STag                 ::=    '<' Name (S Attribute)* S? '>'
    ETag                 ::=    '</' Name S? '>'

    Attribute            ::=    Name Eq AttValue
    AttValue             ::=    '"' ([^<&"] | Reference)* '"' |  "'" ([^<&'] | Reference)* "'"

    //// Element contents
    content              ::=    CharData? ((element | Reference | CDSect | PI | Comment) CharData?)*

    //// Character reference
    Reference            ::=    EntityRef | CharRef
    EntityRef            ::=    '&' Name ';'
    CharRef              ::=    '&#' [0-9]+ ';' | '&#x' [0-9a-fA-F]+ ';'

    CDSect               ::=    CDStart CData CDEnd
    CDStart              ::=    '<![CDATA['
    CData                ::=    (Char* - (Char* ']]>' Char*))
    CDEnd                ::=    ']]>'

    //// Non-content, skipped over stuff
    Misc                 ::=    Comment | PI | S

    //// Processing instruction
    PI                   ::=    '<?' PITarget (S (Char* - (Char* '?>' Char*)))? '?>'
    PITarget             ::=    Name - (('X' | 'x') ('M' | 'm') ('L' | 'l'))

    //// Comments
    Comment              ::=    '<!--' ((Char - '-') | ('-' (Char - '-')))* '-->'


    //// Character classes
    S                    ::=    (#x20 | #x9 | #xD | #xA)+

    Eq                   ::=    S? '=' S?

    Char                 ::=    [#x1-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]

    RestrictedChar       ::=    [#x1-#x8] | [#xB-#xC] | [#xE-#x1F] | [#x7F-#x84] | [#x86-#x9F]

    CharData             ::=    [^<&]* - ([^<&]* ']]>' [^<&]*)

    //// Name identifier
    Name                 ::=    NameStartChar (NameChar)*
    Names                ::=    Name (#x20 Name)*
    NameStartChar        ::=    ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x2FF] |
                                [#x370-#x37D] | [#x37F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] |
                                [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] |
                                [#x10000-#xEFFFF]
    NameChar             ::=    NameStartChar | "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] | [#x203F-#x2040]

    //// Unreachable productions ??
    conditionalSect      ::=    includeSect | ignoreSect
    includeSect          ::=    '<![' S? 'INCLUDE' S? '[' extSubsetDecl ']]>'
    extSubsetDecl        ::=    ( markupdecl | conditionalSect | DeclSep)*
    extSubset            ::=    TextDecl? extSubsetDecl
    TextDecl             ::=    '<?xml' VersionInfo? EncodingDecl S? '?>'

    ignoreSect           ::=    '<![' S? 'IGNORE' S? '[' ignoreSectContents* ']]>'
    ignoreSectContents   ::=    Ignore ('<![' ignoreSectContents ']]>' Ignore)*
    Ignore               ::=    Char* - (Char* ('<![' | ']]>') Char*)

    extParsedEnt         ::=    ( TextDecl? content ) - ( Char* RestrictedChar Char* )

  - Output formatting:

      o Element without children is printed as:

          <tag/>

      o Element with only text is printed as:

          <tag>text</foo>

      o Element with children is printed as:

          <tag>
            ...
          </tag>

  - Report characters to application when:

      o Buffer was completely filled with last call to fill(), or wptr==endptr.
        If wptr<endptr, no more data is available so no need to make room for next
        call to fill().

      o Free space in buffer drops below a certain minimum.

      o We're not at token or (multibyte) character boundary.

  - The column may be incorrect if input string is not UTF8; column number is incremented
    for every character-start [not for UTF8 follower characters, in other words].
*/


#define MINBUFFER  256 //1024         // Minimum buffer size
#define MAXTOKEN   128           // Maximum token size


using namespace FX;

namespace FX {

/*******************************************************************************/

// Character properties
enum {
  SPACE  =  1,
  LEGIT  =  2,
  ESCAPE =  4,
  LEAD   =  8,
  FOLLOW = 16,
  PUBID  = 32
  };


// Character properties for each possible byte value
static const FXuchar property_data[256]={
  0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x03,0x23,0x04,0x04,0x23,0x04,0x04,
  0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04,
  0x23,0x22,0x06,0x22,0x22,0x22,0x06,0x26,0x22,0x22,0x22,0x22,0x22,0x32,0x32,0x22,
  0x32,0x32,0x32,0x32,0x32,0x32,0x32,0x32,0x32,0x32,0x2a,0x26,0x06,0x22,0x06,0x22,
  0x22,0x2a,0x2a,0x2a,0x2a,0x2a,0x2a,0x2a,0x2a,0x2a,0x2a,0x2a,0x2a,0x2a,0x2a,0x2a,
  0x2a,0x2a,0x2a,0x2a,0x2a,0x2a,0x2a,0x2a,0x2a,0x2a,0x2a,0x02,0x02,0x02,0x02,0x2a,
  0x02,0x2a,0x2a,0x2a,0x2a,0x2a,0x2a,0x2a,0x2a,0x2a,0x2a,0x2a,0x2a,0x2a,0x2a,0x2a,
  0x2a,0x2a,0x2a,0x2a,0x2a,0x2a,0x2a,0x2a,0x2a,0x2a,0x2a,0x02,0x02,0x02,0x02,0x04,
  0x16,0x16,0x16,0x16,0x12,0x12,0x16,0x16,0x16,0x16,0x16,0x16,0x16,0x16,0x16,0x16,
  0x16,0x16,0x16,0x16,0x16,0x16,0x16,0x16,0x16,0x16,0x16,0x16,0x16,0x16,0x16,0x12,
  0x12,0x12,0x12,0x12,0x12,0x12,0x12,0x12,0x12,0x12,0x12,0x12,0x12,0x12,0x12,0x12,
  0x12,0x12,0x12,0x12,0x12,0x12,0x12,0x12,0x12,0x12,0x12,0x12,0x12,0x12,0x12,0x12,
  0x0a,0x0a,0x0a,0x0a,0x0a,0x0a,0x0a,0x0a,0x0a,0x0a,0x0a,0x0a,0x0a,0x0a,0x0a,0x0a,
  0x0a,0x0a,0x0a,0x0a,0x0a,0x0a,0x0a,0x0a,0x0a,0x0a,0x0a,0x0a,0x0a,0x0a,0x0a,0x0a,
  0x0a,0x0a,0x0a,0x0a,0x0a,0x0a,0x0a,0x0a,0x0a,0x0a,0x0a,0x0a,0x0a,0x0a,0x0a,0x0a,
  0x0a,0x0a,0x0a,0x0a,0x0a,0x0a,0x0a,0x0a,0x0e,0x0e,0x0e,0x0e,0x0e,0x0e,0x0e,0x0e,
  };


// Return non-zero if ch is tag start character
static inline FXuchar nameStartChar(FXuchar ch){
  return property_data[ch]&LEAD;
  }

// Return non-zero if ch is tag character
static inline FXuchar nameChar(FXuchar ch){
  return property_data[ch]&(LEAD|FOLLOW);
  }

// Return non-zero if ch is legal character
static inline FXuchar legalChar(FXuchar ch){
  return property_data[ch]&LEGIT;
  }

// Return non-zero if ch is restricted character
static inline FXuchar restrictedChar(FXuchar ch){
  return property_data[ch]&ESCAPE;
  }

// Return non-zero if ch is whitespace character
static inline FXuchar spaceChar(FXuchar ch){
  return property_data[ch]&SPACE;
  }


// Error messages
const FXchar *const FXXML::errors[]={
  "OK",
  "Empty",
  "Unable to save",
  "Unable to load",
  "Expected a space",
  "Expected a '='",
  "Expected a name",
  "Expected a string",
  "Illegal token",
  "Expected digit",
  "Expected hex digit",
  "Expected semicolon",
  "Unknown reference",
  "Unmatched tag",
  "Unexpected end of file"
  };


// Encoding names
static const FXchar *const encodingName[]={
  "UNKOWN","UTF8","UTF16LE","UTF16BE","UTF32LE","UTF32BE"
  };


/*******************************************************************************/

// Collect some element info during the parse
class FXXML::Element {
private:
  Element          **instance;          // Instance pointer
  Element           *upper;             // Upper pointer
public:
  FXString           name;              // Tag name
  FXStringDictionary attributes;        // Attribute list
  FXbool             empty;             // Element is empty
public:

  // Enter
  Element(Element** ins):instance(ins),upper(*ins),empty(false){ *instance=this; }

  // Leave
 ~Element(){ *instance=upper; }
  };

/*******************************************************************************/

// Decode escaped special characters from XML stream
FXbool FXXML::decode(FXString& dst,const FXString& src,FXuint flags){
  FXint p,q;
  FXwchar wc;

  // Measure the resulting string first
  p=q=0;
  while(q<src.length()){
    wc=src[q++];
    if(wc=='\r' && (flags&CRLF)){               // CR, CRLF -> LF
      if(src[q]=='\n'){ q++; }
      p++;
      continue;
      }
    if(wc=='\n' && (flags&CRLF)){               // LF, LFCR -> LF
      if(src[q]=='\r'){ q++; }
      p++;
      continue;
      }
    if(wc=='&' && (flags&REFS)){
      if(src[q]=='#'){
        if(src[q+1]=='x'){                      // &#xXXXX;
          q+=2;
          if(!Ascii::isHexDigit(src[q])) return false;  // Expected at least one hex digit
          wc=Ascii::digitValue(src[q++]);
          while(Ascii::isHexDigit(src[q])){
            wc=wc*16+Ascii::digitValue(src[q++]);
            }
          if(src[q++]!=';') return false;       // Expected semicolon
          }
        else{                                   // &#DDDD;
          q+=1;
          if(!Ascii::isDigit(src[q])) return false;     // Expected at least one digit
          wc=src[q++]-'0';
          while(Ascii::isDigit(src[q])){
            wc=wc*10+(src[q++]-'0');
            }
          if(src[q++]!=';') return false;       // Expected semicolon
          }
        p+=wc2utf(wc);
        continue;
        }
      if(src[q]=='q' && src[q+1]=='u' && src[q+2]=='o' && src[q+3]=='t' && src[q+4]==';'){      // &quot;
        q+=5;
        p++;
        continue;
        }
      if(src[q]=='a' && src[q+1]=='p' && src[q+2]=='o' && src[q+3]=='s' && src[q+4]==';'){      // &apos;
        q+=5;
        p++;
        continue;
        }
      if(src[q]=='a' && src[q+1]=='m' && src[q+2]=='p' && src[q+3]==';'){       // &amp;
        q+=4;
        p++;
        continue;
        }
      if(src[q]=='l' && src[q+1]=='t' && src[q+2]==';'){        // &lt;
        q+=3;
        p++;
        continue;
        }
      if(src[q]=='g' && src[q+1]=='t' && src[q+2]==';'){        // &gt;
        q+=3;
        p++;
        continue;
        }
      return false;                             // Unknown reference
      }
    p++;
    }

  // Now allocate space
  dst.length(p);

  // Now produce the result string
  p=q=0;
  while(q<src.length()){
    wc=src[q++];
    if(wc=='\r' && (flags&CRLF)){               // CR, CRLF -> LF
      if(src[q]=='\n'){ q++; }
      dst[p++]='\n';
      continue;
      }
    if(wc=='\n' && (flags&CRLF)){               // LF, LFCR -> LF
      if(src[q]=='\r'){ q++; }
      dst[p++]='\n';
      continue;
      }
    if(wc=='&' && (flags&REFS)){
      if(src[q]=='#'){
        if(src[q+1]=='x'){                      // &#xXXXX;
          q+=2;
          FXASSERT(Ascii::isHexDigit(src[q]));  // Expected at least one hex digit
          wc=Ascii::digitValue(src[q++]);
          while(Ascii::isHexDigit(src[q])){
            wc=wc*16+Ascii::digitValue(src[q++]);
            }
          FXASSERT(src[q]==';');                // Expected semicolon
          q++;
          }
        else{                                   // &#DDDD;
          q+=1;
          FXASSERT(Ascii::isDigit(src[q]));     // Expected at least one digit
          wc=src[q++]-'0';
          while(Ascii::isDigit(src[q])){
            wc=wc*10+(src[q++]-'0');
            }
          FXASSERT(src[q]==';');                // Expected semicolon
          q++;
          }
        p+=wc2utf(&dst[p],wc);
        continue;
        }
      if(src[q]=='q' && src[q+1]=='u' && src[q+2]=='o' && src[q+3]=='t' && src[q+4]==';'){      // &quot;
        q+=5;
        dst[p++]='\"';
        continue;
        }
      if(src[q]=='a' && src[q+1]=='p' && src[q+2]=='o' && src[q+3]=='s' && src[q+4]==';'){      // &apos;
        q+=5;
        dst[p++]='\'';
        continue;
        }
      if(src[q]=='a' && src[q+1]=='m' && src[q+2]=='p' && src[q+3]==';'){       // &amp;
        q+=4;
        dst[p++]='&';
        continue;
        }
      if(src[q]=='l' && src[q+1]=='t' && src[q+2]==';'){        // &lt;
        q+=3;
        dst[p++]='<';
        continue;
        }
      if(src[q]=='g' && src[q+1]=='t' && src[q+2]==';'){        // &gt;
        q+=3;
        dst[p++]='>';
        continue;
        }
      }
    dst[p++]=wc;
    }
  FXASSERT(p<=dst.length());
  return true;
  }

/*******************************************************************************/

// Encode special characters for inclusion into XML stream
FXbool FXXML::encode(FXString& dst,const FXString& src,FXuint flags){
  FXint p,q;
  FXuchar ch;

  // Measure the resulting string first
  p=q=0;
  while(q<src.length()){
    ch=src[q++];
    if(ch=='\n' && (flags&CRLF)){
#if defined(WIN32)
      p+=2;
#else
      p+=1;
#endif
      continue;
      }
    if(restrictedChar(ch) && (flags&REFS)){
      switch(ch){
      case '"':         // &quot;
        p+=6;
        continue;
      case '&':         // &amp;
        p+=5;
        continue;
      case '\'':        // &apos;
        p+=6;
        continue;
      case '<':         // &lt;
        p+=4;
        continue;
      case '>':         // &gt;
        p+=4;
        continue;
      default:          // &#XX;
        p+=6;
        continue;
        }
      }
    p++;
    }

  // Now allocate space
  dst.length(p);

  // Now produce the result string
  p=q=0;
  while(q<src.length()){
    ch=src[q++];
    if(ch=='\n' && (flags&CRLF)){
#if defined(WIN32)
      dst[p++]='\r';
      dst[p++]='\n';
#else
      dst[p++]='\n';
#endif
      continue;
      }
    if(restrictedChar(ch) && (flags&REFS)){
      switch(ch){
      case '"':         // &quot;
        dst[p+0]='&';
        dst[p+1]='q';
        dst[p+2]='u';
        dst[p+3]='o';
        dst[p+4]='t';
        dst[p+5]=';';
        p+=6;
        continue;
      case '&':         // &amp;
        dst[p+0]='&';
        dst[p+1]='a';
        dst[p+2]='m';
        dst[p+3]='p';
        dst[p+4]=';';
        p+=5;
        continue;
      case '\'':
        dst[p+0]='&';   // &apos;
        dst[p+1]='a';
        dst[p+2]='p';
        dst[p+3]='o';
        dst[p+4]='s';
        dst[p+5]=';';
        p+=6;
        continue;
      case '<':         // &lt;
        dst[p+0]='&';
        dst[p+1]='l';
        dst[p+2]='t';
        dst[p+3]=';';
        p+=4;
        continue;
      case '>':         // &gt;
        dst[p+0]='&';
        dst[p+1]='g';
        dst[p+2]='t';
        dst[p+3]=';';
        p+=4;
        continue;
      default:          // &#XX;
        dst[p+0]='&';
        dst[p+1]='#';
        dst[p+2]='x';
        dst[p+3]=Ascii::valueDigit(ch>>4);
        dst[p+4]=Ascii::valueDigit(ch&15);
        dst[p+5]=';';
        p+=6;
        continue;
        }
      }
    dst[p++]=ch;
    }
  FXASSERT(p<=dst.length());
  return true;
  }

/*******************************************************************************/

// Construct XML parser instance
FXXML::FXXML():offset(0),current(nullptr),column(0),line(1),enc(UTF8){
  FXTRACE((100,"FXXML::FXXML\n"));
  }


// Construct XML parser instance and pass it external buffer
FXXML::FXXML(FXchar* buffer,FXuval sz,Direction d):FXParseBuffer(buffer,sz,d),offset(0),current(nullptr),column(0),line(1),enc(UTF8){
  FXTRACE((100,"FXXML::FXXML(%p,%ld,%s)\n",buffer,sz,d==Load?"Load":d==Save?"Save":"Stop"));
  open(buffer,sz,d);
  }


// Open XML stream for given direction d
FXbool FXXML::open(FXchar* buffer,FXuval sz,Direction d){
  FXTRACE((101,"FXXML::open(%p,%ld,%s)\n",buffer,sz,d==Load?"Load":d==Save?"Save":"Stop"));
  if(FXParseBuffer::open(buffer,sz,d)){
    current=nullptr;
    column=0;
    offset=0;
    line=1;
    vers="1.0";
    enc=UTF8;
    return true;
    }
  return false;
  }

/*******************************************************************************/

// Boiler plate emitted prior to main document
static const FXchar boilerplate[]="<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";


// Document start
FXXML::Error FXXML::startDocument(){
  if(dir==Save){
    if(!emit(boilerplate,sizeof(boilerplate)-1)) return ErrSave;
    offset+=sizeof(boilerplate)-1;
    return ErrOK;
    }
  return ErrSave;
  }


// Element start w/no attributes
FXXML::Error FXXML::startElement(const FXString& tag){
  if(dir==Save){
    if(!emit("<",1)) return ErrSave;
    offset+=1;
    if(!emit(tag.text(),tag.length())) return ErrSave;
    offset+=tag.length();
    if(!emit(">",1)) return ErrSave;
    offset+=1;
    return ErrOK;
    }
  return ErrSave;
  }


// Element start w/attributes
FXXML::Error FXXML::startElement(const FXString& tag,const FXStringDictionary& atts){
  FXString encodedatt;
  if(dir==Save){
    if(!emit("<",1)) return ErrSave;
    offset+=1;
    if(!emit(tag.text(),tag.length())) return ErrSave;
    offset+=tag.length();
    if(!atts.empty()){
      for(FXint i=0; i<atts.no(); ++i){
        if(!atts.empty(i)){
          if(!emit(" ",1)) return ErrSave;
          offset+=1;
          if(!emit(atts.key(i).text(),atts.key(i).length())) return ErrSave;
          offset+=atts.key(i).length();
          if(!emit("=\"",2)) return ErrSave;
          offset+=2;
          FXXML::encode(encodedatt,atts.data(i),REFS|CRLF);
          if(!emit(encodedatt.text(),encodedatt.length())) return ErrSave;
          offset+=encodedatt.length();
          if(!emit("\"",1)) return ErrSave;
          offset+=1;
          }
        }
      }
    if(!emit(">",1)) return ErrSave;
    offset+=1;
    return ErrOK;
    }
  return ErrSave;
  }


// Characters
FXXML::Error FXXML::characters(const FXString& text){
  if(dir==Save){
    FXString encodedtext;
    FXXML::encode(encodedtext,text,CRLF|REFS);
    if(!emit(encodedtext.text(),encodedtext.length())) return ErrSave;
    offset+=encodedtext.length();
    return ErrOK;
    }
  return ErrSave;
  }


// Comment
FXXML::Error FXXML::comment(const FXString& text){
  if(dir==Save){
    if(!emit("<!--",4)) return ErrSave;
    offset+=4;
    if(!emit(text.text(),text.length())) return ErrSave;
    offset+=text.length();
    if(!emit("-->",3)) return ErrSave;
    offset+=3;
    return ErrOK;
    }
  return ErrSave;
  }


// Processing instruction
FXXML::Error FXXML::processing(const FXString& target,const FXString& data){
  if(dir==Save){
    if(!emit("<?",2)) return ErrSave;
    offset+=2;
    if(!emit(target.text(),target.length())) return ErrSave;
    offset+=target.length();
    if(!data.empty()){
      if(!emit(" ",1)) return ErrSave;
      offset+=1;
      if(!emit(data.text(),data.length())) return ErrSave;
      offset+=data.length();
      }
    if(!emit("?>",2)) return ErrSave;
    offset+=2;
    return ErrOK;
    }
  return ErrSave;
  }


// Element end
FXXML::Error FXXML::endElement(const FXString& tag){
  if(dir==Save){
    if(!emit("</",2)) return ErrSave;
    offset+=2;
    if(!emit(tag.text(),tag.length())) return ErrSave;
    offset+=tag.length();
    if(!emit(">",1)) return ErrSave;
    offset+=1;
    return ErrOK;
    }
  return ErrSave;
  }


// Document end
FXXML::Error FXXML::endDocument(){
  if(dir==Save){
    if(!emit("\n",1)) return ErrSave;
    offset+=1;
    return ErrOK;
    }
  return ErrSave;
  }

/*******************************************************************************/

// Guess coded based on first 4 bytes of stream
// Careful: smallest (barely legal) XML file is 4 bytes: '<a/>'
// Check for non-zero bytes only: file may start with whitespace.
FXuint FXXML::guess(){

  // Quick check for UTF8 coded byte order mark (most likely case)
  if(sptr+3<=wptr && sptr[0]=='\xef' && sptr[1]=='\xbb' && sptr[2]=='\xbf'){ offset+=3; sptr+=3; return UTF8; }

  // Look for 32-bit byte order mark
  if(sptr+4<=wptr && sptr[0]=='\xff' && sptr[1]=='\xfe' && sptr[2]==0 && sptr[3]==0){ offset+=4; sptr+=4; return UTF32LE; }
  if(sptr+4<=wptr && sptr[0]==0 && sptr[1]==0 && sptr[2]=='\xfe' && sptr[3]=='\xff'){ offset+=4; sptr+=4; return UTF32BE; }

  // Look for 16-bit byte order mark
  if(sptr+2<=wptr && sptr[0]=='\xff' && sptr[1]=='\xfe'){ offset+=2; sptr+=2; return UTF16LE; }
  if(sptr+2<=wptr && sptr[0]=='\xfe' && sptr[1]=='\xff'){ offset+=2; sptr+=2; return UTF16BE; }

  // Otherwise, look for 32-bit wide characters
  if(sptr+4<=wptr && (sptr[0]!=0 || sptr[1]!=0) && (sptr[2]==0 && sptr[3]==0)){ return UTF32LE; }
  if(sptr+4<=wptr && (sptr[0]==0 && sptr[1]==0) && (sptr[2]!=0 || sptr[3]!=0)){ return UTF32BE; }

  // Finally, look for 16-bit wide characters
  if(sptr+2<=wptr && sptr[0]==0 && sptr[1]!=0){ return UTF16BE; }
  if(sptr+2<=wptr && sptr[0]!=0 && sptr[1]==0){ return UTF16LE; }

  // Unknown encoding
  return 0;
  }


// Parse just spaces
void FXXML::spaces(){
  while(need(MAXTOKEN)){
    rptr=sptr;
    switch(sptr[0]){
    case '\t':
      column+=(8-column%8);
      offset++;
      sptr++;
      continue;
    case '\r':
      if(sptr+1<wptr && sptr[1]=='\n'){ offset++; sptr++; }
    case '\n':
      column=0;
      offset++;
      sptr++;
      line++;
      continue;
    case ' ':
      column++;
    case '\v':
    case '\f':
      offset++;
      sptr++;
      continue;
    default:                            // We have a non-whitespace character
      return;
      }
    }
  }


// Parse name
FXbool FXXML::name(){
  if(nameStartChar(sptr[0])){
    rptr=sptr;
    do{
      column+=isUTF8(*sptr);            // Increment if UTF8 leader only
      offset++;
      sptr++;
      if(sptr>=wptr) return false;
      }
    while(nameChar(sptr[0]));
    return true;
    }
  return false;
  }


// Match name with given name str of length len
FXbool FXXML::match(FXchar ch){
  if(sptr[0]==ch){
    rptr=sptr;
    column++;
    offset++;
    sptr++;
    return true;
    }
  return false;
  }


// Match name with given name str of length len
FXbool FXXML::match(const FXchar* str,FXint len){
  if(name() && rptr+len==sptr){
    return FXString::compare(rptr,str,len)==0;
    }
  return false;
  }


// Parse string
FXXML::Error FXXML::parsestring(FXString& str){
  FXchar q=sptr[0];
  str.clear();
  if(q=='"' || q=='\''){
    column++;
    offset++;
    sptr++;
    rptr=sptr;
    while(need(MAXTOKEN)){
      switch(sptr[0]){
      case '\t':
        column+=(8-column%8);
        offset++;
        sptr++;
        continue;
      case '\r':
        if(sptr+1<wptr && sptr[1]=='\n'){ offset++; sptr++; }
      case '\n':
        column=0;
        offset++;
        sptr++;
        line++;
        continue;
      case ' ':
        column++;
      case '\v':
      case '\f':
        offset++;
        sptr++;
        continue;
      case '\'':
      case '"':
        if(sptr[0]!=q) goto nxt;
        str.append(rptr,sptr-rptr);
        offset++;
        column++;
        sptr++;
        rptr=sptr;
        return ErrOK;
      default:
nxt:    if((sptr-rptr)>=(endptr-begptr-MAXTOKEN)){
          str.append(rptr,sptr-rptr);
          rptr=sptr;
          }
        column+=isUTF8(*sptr);          // Increment if UTF8 leader only
        offset++;
        sptr++;
        continue;
        }
      }
    return ErrEof;
    }
  return ErrString;
  }


// Parse version string
FXXML::Error FXXML::parseversion(){
  spaces();
  if(match('=')){
    spaces();
    return parsestring(vers);
    }
  return ErrEquals;
  }


// Parse encoding
FXXML::Error FXXML::parseencoding(){
  FXString code;
  spaces();
  if(match('=')){
    spaces();
    return parsestring(code);
    }
  return ErrEquals;
  }


// Parse standalone flag
FXXML::Error FXXML::parsestandalone(){
  FXString truth;
  spaces();
  if(match('=')){
    spaces();
    return parsestring(truth);
    }
  return ErrEquals;
  }


// XML header
FXXML::Error FXXML::parsexml(){
  FXXML::Error err;
  rptr=sptr;
  while(need(MAXTOKEN)){
    switch(sptr[0]){
    case '\t':
      column+=(8-column%8);
      offset++;
      sptr++;
      continue;
    case '\r':
      if(sptr+1<wptr && sptr[1]=='\n'){ offset++; sptr++; }
    case '\n':
      column=0;
      offset++;
      line++;
      sptr++;
      continue;
    case ' ':
      column++;
    case '\v':
    case '\f':
      offset++;
      sptr++;
      continue;
    case '?':                   // End of xml declaration
      if(sptr[1]!='>') return ErrToken;
      column+=2;
      offset+=2;
      sptr+=2;
      return ErrOK;
    case 'v':
      if(sptr[1]!='e') return ErrToken;
      if(sptr[2]!='r') return ErrToken;
      if(sptr[3]!='s') return ErrToken;
      if(sptr[4]!='i') return ErrToken;
      if(sptr[5]!='o') return ErrToken;
      if(sptr[6]!='n') return ErrToken;
      column+=7;
      offset+=7;
      sptr+=7;
      if((err=parseversion())!=ErrOK) return err;
      rptr=sptr;
      continue;
    case 'e':
      if(sptr[1]!='n') return ErrToken;
      if(sptr[2]!='c') return ErrToken;
      if(sptr[3]!='o') return ErrToken;
      if(sptr[4]!='d') return ErrToken;
      if(sptr[5]!='i') return ErrToken;
      if(sptr[6]!='n') return ErrToken;
      if(sptr[7]!='g') return ErrToken;
      column+=8;
      offset+=8;
      sptr+=8;
      if((err=parseencoding())!=ErrOK) return err;
      rptr=sptr;
      continue;
    case 's':
      if(sptr[1]!='t') return ErrToken;
      if(sptr[2]!='a') return ErrToken;
      if(sptr[3]!='n') return ErrToken;
      if(sptr[4]!='d') return ErrToken;
      if(sptr[5]!='a') return ErrToken;
      if(sptr[6]!='l') return ErrToken;
      if(sptr[7]!='o') return ErrToken;
      if(sptr[8]!='n') return ErrToken;
      if(sptr[9]!='e') return ErrToken;
      column+=10;
      offset+=10;
      sptr+=10;
      if((err=parsestandalone())!=ErrOK) return err;
      rptr=sptr;
      continue;
    default:
      return ErrToken;
      }
    }
  return ErrEof;
  }


// Element declaration
FXXML::Error FXXML::parseelementdecl(){
  FXString elmname;
  spaces();
  if(name()){
    elmname.assign(rptr,sptr-rptr);
    spaces();
    //?//
    return ErrOK;
    }
  return ErrName;
  }


// External ID
FXXML::Error FXXML::parseexternalid(){
  FXXML::Error err;
  FXString syslit;
  FXString publit;
  spaces();
  if(match("SYSTEM",6)){
    spaces();
    if((err=parsestring(syslit))!=ErrOK) return err;
    ///
    FXTRACE((101,"SYSTEM \"%s\"\n",syslit.text()));
    return ErrOK;
    }
  if(match("PUBLIC",6)){
    spaces();
    if((err=parsestring(publit))!=ErrOK) return err;
    spaces();
    if((err=parsestring(syslit))!=ErrOK) return err;
    FXTRACE((101,"PUBLIC \"%s\" \"%s\"\n",publit.text(),syslit.text()));
    ///
    return ErrOK;
    }
  return ErrOK;
  }


// Internal subsey
FXXML::Error FXXML::parseinternalsubset(){
  FXXML::Error err;
  spaces();
  if(match('[')){
    FXTRACE((101,"internalsubset\n"));
    while(need(MAXTOKEN)){
      switch(sptr[0]){
      case '\t':
        column+=(8-column%8);
        offset++;
        sptr++;
        continue;
      case '\r':
        if(sptr+1<wptr && sptr[1]=='\n'){ offset++; sptr++; }
      case '\n':
        column=0;
        offset++;
        line++;
        sptr++;
        continue;
      case ' ':
        column++;
      case '\v':
      case '\f':
        offset++;
        sptr++;
        continue;
      case ']':
        column++;
        offset++;
        sptr++;
        return ErrOK;
      case '<':
        if(sptr[1]=='?'){
          column+=2;
          offset+=2;
          sptr+=2;
          if((err=parseprocessing())!=ErrOK) return err;
          continue;
          }
        if(sptr[1]=='!' && sptr[2]=='-' && sptr[3]=='-'){
          column+=4;
          offset+=4;
          sptr+=4;
          if((err=parsecomment())!=ErrOK) return err;
          continue;
          }
#if 0 // SKIP NOT-YET-IMPLEMENTED STUFF
        if(sptr[1]=='!' && sptr[2]=='E' && sptr[3]=='L' && sptr[4]=='E' && sptr[5]=='M' && sptr[6]=='E' && sptr[7]=='N' && sptr[8]=='T'){
          column+=9;
          sptr+=9;
          FXTRACE((101,"<!ELEMENT\n"));
          rptr=sptr;
          continue;
          }
        if(sptr[1]=='!' && sptr[2]=='A' && sptr[3]=='T' && sptr[4]=='T' && sptr[5]=='L' && sptr[6]=='I' && sptr[7]=='T'){
          column+=8;
          sptr+=8;
          FXTRACE((101,"<!ATTLIST\n"));
          rptr=sptr;
          continue;
          }
        if(sptr[1]=='!' && sptr[2]=='E' && sptr[3]=='N' && sptr[4]=='T' && sptr[5]=='I' && sptr[6]=='T' && sptr[7]=='Y'){
          column+=8;
          sptr+=8;
          FXTRACE((101,"<!ENTITY\n"));
          rptr=sptr;
          continue;
          }
        if(sptr[1]=='!' && sptr[2]=='N' && sptr[3]=='O' && sptr[4]=='T' && sptr[5]=='A' && sptr[6]=='T' && sptr[7]=='I' && sptr[8]=='O' && sptr[9]=='N'){
          column+=10;
          sptr+=10;
          FXTRACE((101,"<!NOTATION\n"));
          rptr=sptr;
          continue;
          }
#endif
//        return ErrToken;
      default:
        column++;
        offset++;
        sptr++;
//        return ErrToken;
        }
      }
    return ErrEof;
    }
  return ErrOK;
  }


// Document type
FXXML::Error FXXML::parsedeclarations(){
  FXXML::Error err;
  FXString docname;
  spaces();
  if(name()){
    docname.assign(rptr,sptr-rptr);
    FXTRACE((101,"docname=%s\n",docname.text()));
    if((err=parseexternalid())!=ErrOK) return err;
    if((err=parseinternalsubset())!=ErrOK) return err;
    spaces();
    if(!match('>')) return ErrToken;
    return ErrOK;
    }
  return ErrName;
  }


// Processing instruction
FXXML::Error FXXML::parseprocessing(){
  FXString target;
  FXString data;
  if(name()){
    target.assign(rptr,sptr-rptr);
    rptr=sptr;                          // Start of processing instruction data
    while(need(MAXTOKEN)){
      switch(sptr[0]){
      case '\t':
        column+=(8-column%8);
        offset++;
        sptr++;
        continue;
      case '\r':
        if(sptr+1<wptr && sptr[1]=='\n'){ offset++; sptr++; }
      case '\n':
        column=0;
        offset++;
        line++;
        sptr++;
        continue;
      case ' ':
        column++;
      case '\v':
      case '\f':
        offset++;
        sptr++;
        continue;
      case '?':
        if(sptr[1]!='>') goto nxt;      // Just a lone '?'
        data.append(rptr,sptr-rptr);    // Add last chunk of processing instruction
        column+=2;
        offset+=2;
        sptr+=2;
        rptr=sptr;
        return processingCB(target,data);
      default:
nxt:    if((sptr-rptr)>=(endptr-begptr-MAXTOKEN)){
          data.append(rptr,sptr-rptr);  // Add another chunk
          rptr=sptr;
          }
        column+=isUTF8(*sptr);          // Increment if UTF8 leader only
        offset++;
        sptr++;
        continue;
        }
      }
    return ErrEof;
    }
  return ErrName;
  }


// Scan comment
FXXML::Error FXXML::parsecomment(){
  FXString text;
  rptr=sptr;
  while(need(MAXTOKEN)){
    switch(sptr[0]){
    case '\t':
      column+=(8-column%8);
      offset++;
      sptr++;
      continue;
    case '\r':
      if(sptr+1<wptr && sptr[1]=='\n'){ offset++; sptr++; }
    case '\n':
      column=0;
      offset++;
      line++;
      sptr++;
      continue;
    case ' ':
      column++;
    case '\v':
    case '\f':
      offset++;
      sptr++;
      continue;
    case '-':
      if(sptr[1]!='-') goto nxt;        // Just a lone '-'
      if(sptr[2]!='>') goto nxt;        // Allow a '--' inside a comment; technically, not spec
      text.append(rptr,sptr-rptr);      // Pass comment undecoded
      column+=3;
      offset+=3;
      sptr+=3;
      rptr=sptr;
      return commentCB(text);
    default:
nxt:  if((sptr-rptr)>=(endptr-begptr-MAXTOKEN)){
        text.append(rptr,sptr-rptr);    // Pass comment undecoded
        rptr=sptr;
        }
      column+=isUTF8(*sptr);            // Increment if UTF8 leader only
      offset++;
      sptr++;
      continue;
      }
    }
  return ErrEof;
  }


// Parse key=value pair
FXXML::Error FXXML::parseattribute(Element& elm){
  FXXML::Error err;
  FXString value;
  FXString key;
  if(name()){
    key.assign(rptr,sptr-rptr);
    spaces();
    if(!match('=')) return ErrEquals;
    spaces();
    if((err=parsestring(value))!=ErrOK) return err;
    spaces();
    if(!FXXML::decode(elm.attributes[key],value,REFS|CRLF)) return ErrToken;
    return ErrOK;
    }
  return ErrName;
  }


// Start tag
FXXML::Error FXXML::parsestarttag(Element& elm){
  FXXML::Error err;
  if(!name()) return ErrName;
  elm.name.assign(rptr,sptr-rptr);
  while(need(MAXTOKEN)){
    rptr=sptr;
    switch(sptr[0]){
    case '\t':
      column+=(8-column%8);
      offset++;
      sptr++;
      continue;
    case '\r':
      if(sptr+1<wptr && sptr[1]=='\n'){ offset++; sptr++; }
    case '\n':
      column=0;
      offset++;
      line++;
      sptr++;
      continue;
    case ' ':
      column++;
    case '\v':
    case '\f':
      offset++;
      sptr++;
      continue;
    case '/':
      if(sptr[1]!='>') return ErrToken; // Improper empty tag syntax
      elm.empty=true;
      column+=2;
      offset+=2;
      sptr+=2;
      return ErrOK;                     // End of empty stag element
    case '>':
      elm.empty=false;
      column++;
      offset++;
      sptr++;
      return ErrOK;                     // End of stag
    default:
      if((err=parseattribute(elm))!=ErrOK) return err;
      continue;
      }
    }
  return ErrEof;
  }


// End tag
FXXML::Error FXXML::parseendtag(Element& elm){
  if(!match(elm.name.text(),elm.name.length())) return ErrNoMatch;
  while(need(MAXTOKEN)){
    rptr=sptr;
    switch(sptr[0]){
    case '\t':
      column+=(8-column%8);
      offset++;
      sptr++;
      continue;
    case '\r':
      if(sptr+1<wptr && sptr[1]=='\n'){ offset++; sptr++; }
    case '\n':
      column=0;
      offset++;
      line++;
      sptr++;
      continue;
    case ' ':
      column++;
    case '\v':
    case '\f':
      offset++;
      sptr++;
      continue;
    case '>':
      column++;
      offset++;
      sptr++;
      return ErrOK;                     // End of etag
    default:
      return ErrToken;
      }
    }
  return ErrEof;
  }


// CData
FXXML::Error FXXML::parsecdata(Element& elm){
  FXXML::Error err;
  FXString text;
  rptr=sptr;
  while(need(MAXTOKEN)){
    switch(sptr[0]){
    case '\t':
      column+=(8-column%8);
      offset++;
      sptr++;
      continue;
    case '\r':
      if(sptr+1<wptr && sptr[1]=='\n'){ offset++; sptr++; }
    case '\n':
      column=0;
      offset++;
      line++;
      sptr++;
      continue;
    case ' ':
      column++;
    case '\v':
    case '\f':
      offset++;
      sptr++;
      continue;
    case ']':
      if(sptr[1]!=']') goto nxt;
      if(sptr[2]!='>') goto nxt;
      if(!FXXML::decode(text,FXString(rptr,sptr-rptr),CRLF)) return ErrToken;
      if((err=charactersCB(text))!=ErrOK) return err;
      column+=3;
      offset+=3;
      sptr+=3;
      rptr=sptr;
      return ErrOK;
    default:
nxt:  if((sptr-rptr)>=(endptr-begptr-MAXTOKEN)){
        if(!FXXML::decode(text,FXString(rptr,sptr-rptr),CRLF)) return ErrToken;
        if((err=charactersCB(text))!=ErrOK) return err;
        rptr=sptr;
        }
      column+=isUTF8(*sptr);            // Increment if UTF8 leader only
      offset++;
      sptr++;
      continue;
      }
    }
  return ErrEof;
  }


// Parse it
FXXML::Error FXXML::parsecontents(Element& elm){
  FXXML::Error err;
  FXString text;
  FXint brk=1;                          // Allow break
  rptr=sptr;
  while(need(MAXTOKEN)){
    switch(sptr[0]){
    case '\t':
      column+=(8-column%8);
      offset++;
      sptr++;
      brk=1;
      continue;
    case '\r':
      if(sptr+1<wptr && sptr[1]=='\n'){ offset++; sptr++; }
    case '\n':
      column=0;
      offset++;
      line++;
      sptr++;
      brk=1;
      continue;
    case ' ':
      column++;
    case '\v':
    case '\f':
      offset++;
      sptr++;
      brk=1;
      continue;
    case '&':                           // Disallow break in character reference
      column++;
      offset++;
      sptr++;
      brk=0;
      continue;
    case ';':                           // Allow break now
      column++;
      offset++;
      sptr++;
      brk=1;
      continue;
    case '<':
      brk=1;

      // Try decode, translate both CRLF and references
      if(!FXXML::decode(text,FXString(rptr,sptr-rptr),CRLF|REFS)) return ErrToken;

      // Report final batch of characters
      if((err=charactersCB(text))!=ErrOK) return err;

      // Eat text
      rptr=sptr;

      // End tag
      if(sptr[1]=='/'){
        column+=2;
        offset+=2;
        sptr+=2;
        return ErrOK;
        }

      // Processing instruction
      if(sptr[1]=='?'){
        column+=2;
        offset+=2;
        sptr+=2;
        if((err=parseprocessing())!=ErrOK) return err;
        continue;
        }

      // Comment
      if(sptr[1]=='!' && sptr[2]=='-' && sptr[3]=='-'){
        column+=4;
        offset+=4;
        sptr+=4;
        if((err=parsecomment())!=ErrOK) return err;
        continue;
        }

      // CDATA segment
      if(sptr[1]=='!' && sptr[2]=='[' && sptr[3]=='C' && sptr[4]=='D' && sptr[5]=='A' && sptr[6]=='T' && sptr[7]=='A' && sptr[8]=='['){
        column+=9;
        offset+=9;
        sptr+=9;
        if((err=parsecdata(elm))!=ErrOK) return err;
        continue;
        }

      // Just eat the '<'
      column++;
      offset++;
      sptr++;

      // Parse child element
      if((err=parseelement())!=ErrOK) return err;

      rptr=sptr;
      continue;
    default:
      if(brk && (sptr-rptr)>=(endptr-begptr-MAXTOKEN)){

        // Try decode, translate both CRLF and references
        if(!FXXML::decode(text,FXString(rptr,sptr-rptr),CRLF|REFS)) return ErrToken;

        // Report batch of characters
        if((err=charactersCB(text))!=ErrOK) return err;

        // Eat text
        rptr=sptr;
        }
      column+=isUTF8(*sptr);            // Increment if UTF8 leader only
      offset++;
      sptr++;
      continue;
      }
    }
  return ErrEof;
  }


// Parse element
FXXML::Error FXXML::parseelement(){
  FXXML::Element instance(&current);
  FXXML::Error err;

  // Parse start tag
  if((err=parsestarttag(instance))!=ErrOK) return err;

  // Report element start
  if((err=startElementCB(instance.name,instance.attributes))!=ErrOK) return err;

  // Its a non-empty element
  if(!instance.empty){

    // Parse contents
    if((err=parsecontents(instance))!=ErrOK) return err;

    // Parse end tag
    if((err=parseendtag(instance))!=ErrOK) return err;
    }

  // Report element end
  if((err=endElementCB(instance.name))!=ErrOK) return err;

  // OK
  return ErrOK;
  }


// Parse it
FXXML::Error FXXML::parse(){
  FXXML::Error err;
  current=nullptr;
  if(need(MAXTOKEN)){
    enc=guess();
    FXTRACE((101,"encoding=%s\n",encodingName[enc]));
    while(need(MAXTOKEN)){
      rptr=sptr;
      switch(sptr[0]){
      case '\t':
        column+=(8-column%8);
        offset++;
        sptr++;
        continue;
      case '\r':
        if(sptr+1<wptr && sptr[1]=='\n'){ offset++; sptr++; }
      case '\n':
        column=0;
        offset++;
        line++;
        sptr++;
        continue;
      case ' ':
        column++;
      case '\v':
      case '\f':
        offset++;
        sptr++;
        continue;
      case '<':

        // Parse comment
        if(sptr[1]=='!' && sptr[2]=='-' && sptr[3]=='-'){
          column+=4;
          offset+=4;
          sptr+=4;
          if((err=parsecomment())!=ErrOK) return err;
          continue;
          }

        // Parse document type declarations
        if(sptr[1]=='!' && sptr[2]=='D' && sptr[3]=='O' && sptr[4]=='C' && sptr[5]=='T' && sptr[6]=='Y' && sptr[7]=='P' && sptr[8]=='E' && spaceChar(sptr[9])){
          column+=9;
          offset+=9;
          sptr+=9;
          if((err=parsedeclarations())!=ErrOK) return err;
          continue;
          }

        // Parse XML declaration
        if(sptr[1]=='?' && sptr[2]=='x' && sptr[3]=='m' && sptr[4]=='l' && spaceChar(sptr[5])){
          column+=5;
          offset+=5;
          sptr+=5;
          if((err=parsexml())!=ErrOK) return err;
          continue;
          }

        // Parse processing instruction
        if(sptr[1]=='?'){
          column+=2;
          offset+=2;
          sptr+=2;
          if((err=parseprocessing())!=ErrOK) return err;
          continue;
          }

        // Just eat the '<'
        column++;
        offset++;
        sptr++;

        // Report document start
        if((err=startDocumentCB())!=ErrOK) return err;

        // Parse document body
        if((err=parseelement())!=ErrOK) return err;

        // Report document end
        if((err=endDocumentCB())!=ErrOK) return err;

        // End with success
        return ErrOK;
      default:
        return ErrToken;
        }
      }
    }
  return ErrEmpty;
  }

/*******************************************************************************/

// Close it
FXbool FXXML::close(){
  FXTRACE((101,"XML::close()\n"));
  if(FXParseBuffer::close()){
    current=nullptr;
    return true;
    }
  return false;
  }


// Clean up
FXXML::~FXXML(){
  FXTRACE((100,"FXXML::~FXXML\n"));
  close();
  }

}