/
parser.d
6580 lines (5823 loc) · 265 KB
/
parser.d
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
// Written in the D programming language
/++
This implements a range-based
$(LINK2 https://en.wikipedia.org/wiki/StAX, StAX _parser) for XML 1.0 (which
will work with XML 1.1 documents assuming that they don't use any
1.1-specific features). For the sake of simplicity, sanity, and efficiency,
the $(LINK2 https://en.wikipedia.org/wiki/Document_type_definition, DTD)
section is not supported beyond what is required to parse past it.
Start tags, end tags, comments, cdata sections, and processing instructions
are all supported and reported to the application. Anything in the DTD is
skipped (though it's parsed enough to parse past it correctly, and that
$(I can) result in an $(LREF XMLParsingException) if that XML isn't valid
enough to be correctly skipped), and the
$(LINK2 http://www.w3.org/TR/REC-xml/#NT-XMLDecl, XML declaration) at the
top is skipped if present (XML 1.1 requires that it be there, but XML 1.0
does not).
Regardless of what the XML declaration says (if present), any range of
$(K_CHAR) will be treated as being encoded in UTF-8, any range of $(K_WCHAR)
will be treated as being encoded in UTF-16, and any range of $(K_DCHAR) will
be treated as having been encoded in UTF-32. Strings will be treated as
ranges of their code units, not code points.
Since the DTD is skipped, entity references other than the five which are
predefined by the XML spec cannot be fully processed (since wherever they
were used in the document would be replaced by what they referred to, which
could be arbitrarily complex XML). As such, by default, if any entity
references which are not predefined are encountered outside of the DTD, an
$(LREF XMLParsingException) will be thrown (see
$(LREF Config.throwOnEntityRef) for how that can be configured). The
predefined entity references and any character references encountered will
be checked to verify that they're valid, but they will not be replaced
(since that does not work with returning slices of the original input).
However, $(REF_ALTTEXT decodeXML, decodeXML, dxml, util) or
$(REF_ALTTEXT parseStdEntityRef, parseStdEntityRef, dxml, util) from
$(MREF dxml, util) can be used to convert the predefined entity references
to what the refer to, and $(REF_ALTTEXT decodeXML, decodeXML, dxml, util) or
$(REF_ALTTEXT parseCharRef, parseCharRef, dxml, util) from
$(MREF dxml, util) can be used to convert character references to what they
refer to.
$(H3 Primary Symbols)
$(TABLE
$(TR $(TH Symbol) $(TH Description))
$(TR $(TD $(LREF parseXML))
$(TD The function used to initiate the parsing of an XML
document.))
$(TR $(TD $(LREF EntityRange))
$(TD The range returned by $(LREF parseXML).))
$(TR $(TD $(LREF EntityRange.Entity))
$(TD The element type of $(LREF EntityRange).))
)
$(H3 Parser Configuration Helpers)
$(TABLE
$(TR $(TH Symbol) $(TH Description))
$(TR $(TD $(LREF Config))
$(TD Used to configure how $(LREF EntityRange) parses the XML.))
$(TR $(TD $(LREF simpleXML))
$(TD A user-friendly configuration for when the application just
wants the element tags and the data in between them.))
$(TR $(TD $(LREF makeConfig))
$(TD A convenience function for constructing a custom
$(LREF Config).))
$(TR $(TD $(LREF SkipComments))
$(TD A $(PHOBOS_REF Flag, std, typecons) used with $(LREF Config)
to tell the parser to skip comments.))
$(TR $(TD $(LREF SkipPI))
$(TD A $(PHOBOS_REF Flag, std, typecons) used with $(LREF Config)
to tell the parser to skip processing instructions.))
$(TR $(TD $(LREF SplitEmpty))
$(TD A $(PHOBOS_REF Flag, std, typecons) used with $(LREF Config)
to configure how the parser deals with empty element tags.))
)
$(H3 Helper Types Used When Parsing)
$(TABLE
$(TR $(TH Symbol) $(TH Description))
$(TR $(TD $(LREF EntityType))
$(TD The type of an entity in the XML (e.g. a
$(LREF_ALTTEXT start tag, EntityType.elementStart) or a
$(LREF_ALTTEXT comment, EntityType.comment)).))
$(TR $(TD $(LREF TextPos))
$(TD Gives the line and column number in the XML document.))
$(TR $(TD $(LREF XMLParsingException))
$(TD Thrown by $(LREF EntityRange) when it encounters invalid
XML.))
)
$(H3 Helper Functions Used When Parsing)
$(TABLE
$(TR $(TH Symbol) $(TH Description))
$(TR $(TD $(LREF skipContents))
$(TD Iterates an $(LREF EntityRange) from a start tag to its
matching end tag.))
$(TR $(TD $(LREF skipToPath))
$(TD Used to navigate from one start tag to another as if the start
tag names formed a file path.))
$(TR $(TD $(LREF skipToEntityType))
$(TD Skips to the next entity of the given type in the range.))
$(TR $(TD $(LREF skipToParentEndTag))
$(TD Iterates an $(LREF EntityRange) until it reaches the end tag
that matches the start tag which is the parent of the
current entity.))
)
Copyright: Copyright 2017 - 2018
License: $(HTTP www.boost.org/LICENSE_1_0.txt, Boost License 1.0).
Authors: $(HTTPS jmdavisprog.com, Jonathan M Davis)
Source: $(LINK_TO_SRC dxml/_parser.d)
See_Also: $(LINK2 http://www.w3.org/TR/REC-xml/, Official Specification for XML 1.0)
+/
module dxml.parser;
///
version(dxmlTests) unittest
{
auto xml = "<!-- comment -->\n" ~
"<root>\n" ~
" <foo>some text<whatever/></foo>\n" ~
" <bar/>\n" ~
" <baz></baz>\n" ~
"</root>";
{
auto range = parseXML(xml);
assert(range.front.type == EntityType.comment);
assert(range.front.text == " comment ");
range.popFront();
assert(range.front.type == EntityType.elementStart);
assert(range.front.name == "root");
range.popFront();
assert(range.front.type == EntityType.elementStart);
assert(range.front.name == "foo");
range.popFront();
assert(range.front.type == EntityType.text);
assert(range.front.text == "some text");
range.popFront();
assert(range.front.type == EntityType.elementEmpty);
assert(range.front.name == "whatever");
range.popFront();
assert(range.front.type == EntityType.elementEnd);
assert(range.front.name == "foo");
range.popFront();
assert(range.front.type == EntityType.elementEmpty);
assert(range.front.name == "bar");
range.popFront();
assert(range.front.type == EntityType.elementStart);
assert(range.front.name == "baz");
range.popFront();
assert(range.front.type == EntityType.elementEnd);
assert(range.front.name == "baz");
range.popFront();
assert(range.front.type == EntityType.elementEnd);
assert(range.front.name == "root");
range.popFront();
assert(range.empty);
}
{
auto range = parseXML!simpleXML(xml);
// simpleXML skips comments
assert(range.front.type == EntityType.elementStart);
assert(range.front.name == "root");
range.popFront();
assert(range.front.type == EntityType.elementStart);
assert(range.front.name == "foo");
range.popFront();
assert(range.front.type == EntityType.text);
assert(range.front.text == "some text");
range.popFront();
// simpleXML splits empty element tags into a start tag and end tag
// so that the code doesn't have to care whether a start tag with no
// content is an empty tag or a start tag and end tag with nothing but
// whitespace in between.
assert(range.front.type == EntityType.elementStart);
assert(range.front.name == "whatever");
range.popFront();
assert(range.front.type == EntityType.elementEnd);
assert(range.front.name == "whatever");
range.popFront();
assert(range.front.type == EntityType.elementEnd);
assert(range.front.name == "foo");
range.popFront();
assert(range.front.type == EntityType.elementStart);
assert(range.front.name == "bar");
range.popFront();
assert(range.front.type == EntityType.elementEnd);
assert(range.front.name == "bar");
range.popFront();
assert(range.front.type == EntityType.elementStart);
assert(range.front.name == "baz");
range.popFront();
assert(range.front.type == EntityType.elementEnd);
assert(range.front.name == "baz");
range.popFront();
assert(range.front.type == EntityType.elementEnd);
assert(range.front.name == "root");
range.popFront();
assert(range.empty);
}
}
import std.range.primitives;
import std.traits;
import std.typecons : Flag;
/++
The exception type thrown when the XML parser encounters invalid XML.
+/
class XMLParsingException : Exception
{
/++
The position in the XML input where the problem is.
+/
TextPos pos;
package:
this(string msg, TextPos textPos, string file = __FILE__, size_t line = __LINE__) @safe pure
{
import std.format : format;
pos = textPos;
if(pos.line != -1)
{
if(pos.col != -1)
msg = format!"[%s:%s]: %s"(pos.line, pos.col, msg);
else
msg = format!"[Line %s]: %s"(pos.line, msg);
}
super(msg, file, line);
}
}
/++
Where in the XML document an entity is.
The line and column numbers are 1-based.
The primary use case for TextPos is $(LREF XMLParsingException), but an
application may have other uses for it. The TextPos for an
$(LREF2 Entity, EntityRange) can be obtained from
$(LREF2 Entity.pos, EntityRange).
See_Also: $(LREF XMLParsingException.pos)$(BR)
$(LREF EntityRange.Entity.pos)
+/
struct TextPos
{
/// A line number in the XML file.
int line = 1;
/++
A column number in a line of the XML file.
Each code unit is considered a column, so depending on what a program
is looking to do with the column number, it may need to examine the
actual text on that line and calculate the number that represents
what the program wants to display (e.g. the number of graphemes).
+/
int col = 1;
}
/++
Used to configure how the parser works.
See_Also:
$(LREF makeConfig)$(BR)
$(LREF parseXML)$(BR)
$(LREF simpleXML)
+/
struct Config
{
/++
Whether the comments should be skipped while parsing.
If $(D skipComments == SkipComments.yes), any entities of type
$(LREF EntityType.comment) will be omitted from the parsing results,
and they will not be validated beyond what is required to parse past
them.
Defaults to $(D SkipComments.no).
+/
auto skipComments = SkipComments.no;
/++
Whether processing instructions should be skipped.
If $(D skipPI == SkipPI.yes), any entities of type
$(LREF EntityType.pi) will be skipped, and they will not be validated
beyond what is required to parse past them.
Defaults to $(D SkipPI.no).
+/
auto skipPI = SkipPI.no;
/++
Whether the parser should report empty element tags as if they were a
start tag followed by an end tag with nothing in between.
If $(D splitEmpty == SplitEmpty.yes), then whenever an
$(LREF EntityType.elementEmpty) is encountered, the parser will claim
that that entity is an $(LREF EntityType.elementStart), and then it
will provide an $(LREF EntityType.elementEnd) as the next entity before
the entity that actually follows it.
The purpose of this is to simplify the code using the parser, since most
code does not care about the difference between an empty tag and a start
and end tag with nothing in between. But since some code may care about
the difference, the behavior is configurable.
Defaults to $(D SplitEmpty.no).
+/
auto splitEmpty = SplitEmpty.no;
///
version(dxmlTests) unittest
{
enum configSplitYes = makeConfig(SplitEmpty.yes);
{
auto range = parseXML("<root></root>");
assert(range.front.type == EntityType.elementStart);
assert(range.front.name == "root");
range.popFront();
assert(range.front.type == EntityType.elementEnd);
assert(range.front.name == "root");
range.popFront();
assert(range.empty);
}
{
// No difference if the tags are already split.
auto range = parseXML!configSplitYes("<root></root>");
assert(range.front.type == EntityType.elementStart);
assert(range.front.name == "root");
range.popFront();
assert(range.front.type == EntityType.elementEnd);
assert(range.front.name == "root");
range.popFront();
assert(range.empty);
}
{
// This treats <root></root> and <root/> as distinct.
auto range = parseXML("<root/>");
assert(range.front.type == EntityType.elementEmpty);
assert(range.front.name == "root");
range.popFront();
assert(range.empty);
}
{
// This is parsed as if it were <root></root> insead of <root/>.
auto range = parseXML!configSplitYes("<root/>");
assert(range.front.type == EntityType.elementStart);
assert(range.front.name == "root");
range.popFront();
assert(range.front.type == EntityType.elementEnd);
assert(range.front.name == "root");
range.popFront();
assert(range.empty);
}
}
/++
Whether the parser should throw when it encounters any entity references
other than the five entity references defined in the XML standard.
Any other entity references would have to be defined in the DTD in
order to be valid. And in order to know what XML they represent (which
could be arbitrarily complex, even effectively inserting entire XML
documents into the middle of the XML), the DTD would have to be parsed.
However, dxml does not support parsing the DTD beyond what is required
to correctly parse past it, and replacing entity references with what
they represent would not work with the slicing semantics that
$(LREF EntityRange) provides. As such, it is not possible for dxml to
correctly handle any entity references other than the five which are
defined in the XML standard, and even those are only parsed by using
$(REF decodeXML, dxml, util) or $(REF parseStdEntityRef, dxml, util).
$(LREF EntityRange) always validates that entity references are one
of the five, predefined entity references, but otherwise, it lets them
pass through as normal text. It does not replace them with what they
represent.
As such, the default behavior of $(LREF EntityRange) is to throw an
$(LREF XMLParsingException) when it encounters an entity reference
which is not one of the five defined by the XML standard. With that
behavior, there is no risk of processing an XML document as if it had
no entity references and ending up with what the program using the
parser would probably consider incorrect results. However, there are
cases where a program may find it acceptable to treat entity references
as normal text and ignore them. As such, if a program wishes to take
that approach, it can set throwOnEntityRef to $(D ThrowOnEntityRef.no).
If $(D throwOnEntityRef == ThrowOnEntityRef.no), then any entity
reference that it encounters will be validated to ensure that it is
syntactically valid (i.e. that the characters it contains form what
could be a valid entity reference assuming that the DTD declared it
properly), but otherwise, $(LREF EntityRange) will treat it as normal
text, just like it treats the five, predefined entity references as
normal text.
Note that any valid XML entity reference which contains start or end
tags must contain matching start or end tags, and entity references
cannot contain incomplete fragments of XML (e.g. the start or end of a
comment). So, missing entity references should only affect the data in
the XML document and not its overall structure (if that were not _true,
attempting to ignore entity references such as $(D ThrowOnEntityRef.no)
does would be a disaster in the making). However, how reasonable it is
to miss that data depends entirely on the application and what the XML
documents it's parsing contain - hence, the behavior is configurable.
See_Also: $(REF StdEntityRef, dxml, util)$(BR)
$(REF parseStdEntityRef, dxml, util)$(BR)
$(REF parseCharRef, dxml, util)$(BR)
$(REF encodeCharRef, dxml, util)$(BR)
$(REF decodeXML, dxml, util)$(BR)
$(REF asDecodedXML, dxml, util)
+/
auto throwOnEntityRef = ThrowOnEntityRef.yes;
///
version(dxmlTests) unittest
{
import std.exception : assertThrown;
import dxml.util : decodeXML;
auto xml = "<root>\n" ~
" <std>&'><"</std>\n" ~
" <other>&foobar;</other>\n" ~
" <invalid>&--;</invalid>\n" ~
"</root>";
// ThrowOnEntityRef.yes
{
auto range = parseXML(xml);
assert(range.front.type == EntityType.elementStart);
assert(range.front.name == "root");
range.popFront();
assert(range.front.type == EntityType.elementStart);
assert(range.front.name == "std");
range.popFront();
assert(range.front.type == EntityType.text);
assert(range.front.text == "&'><"");
assert(range.front.text.decodeXML() == `&'><"`);
range.popFront();
assert(range.front.type == EntityType.elementEnd);
assert(range.front.name == "std");
range.popFront();
assert(range.front.type == EntityType.elementStart);
assert(range.front.name == "other");
// Attempted to parse past "&foobar;", which is syntactically
// valid, but it's not one of the five predefined entity references.
assertThrown!XMLParsingException(range.popFront());
}
// ThrowOnEntityRef.no
{
auto range = parseXML!(makeConfig(ThrowOnEntityRef.no))(xml);
assert(range.front.type == EntityType.elementStart);
assert(range.front.name == "root");
range.popFront();
assert(range.front.type == EntityType.elementStart);
assert(range.front.name == "std");
range.popFront();
assert(range.front.type == EntityType.text);
assert(range.front.text == "&'><"");
assert(range.front.text.decodeXML() == `&'><"`);
range.popFront();
assert(range.front.type == EntityType.elementEnd);
assert(range.front.name == "std");
range.popFront();
assert(range.front.type == EntityType.elementStart);
assert(range.front.name == "other");
// Doesn't throw, because "&foobar;" is syntactically valid.
range.popFront();
assert(range.front.type == EntityType.text);
assert(range.front.text == "&foobar;");
// decodeXML has no effect on non-standard entity references.
assert(range.front.text.decodeXML() == "&foobar;");
range.popFront();
assert(range.front.type == EntityType.elementEnd);
assert(range.front.name == "other");
range.popFront();
assert(range.front.type == EntityType.elementStart);
assert(range.front.name == "invalid");
// Attempted to parse past "&--;", which is not syntactically valid,
// because -- is not a valid name for an entity reference.
assertThrown!XMLParsingException(range.popFront());
}
}
}
/// See_Also: $(LREF2 skipComments, Config)
alias SkipComments = Flag!"SkipComments";
/// See_Also: $(LREF2 skipPI, Config)
alias SkipPI = Flag!"SkipPI";
/// See_Also: $(LREF2 splitEmpty, Config)
alias SplitEmpty = Flag!"SplitEmpty";
/// See_Also: $(LREF2 throwOnEntityRef, Config)
alias ThrowOnEntityRef = Flag!"ThrowOnEntityRef";
/++
Helper function for creating a custom config. It makes it easy to set one
or more of the member variables to something other than the default without
having to worry about explicitly setting them individually or setting them
all at once via a constructor.
The order of the arguments does not matter. The types of each of the members
of Config are unique, so that information alone is sufficient to determine
which argument should be assigned to which member.
+/
Config makeConfig(Args...)(Args args)
{
import std.format : format;
import std.meta : AliasSeq, staticIndexOf, staticMap;
template isValid(T, Types...)
{
static if(Types.length == 0)
enum isValid = false;
else static if(is(T == Types[0]))
enum isValid = true;
else
enum isValid = isValid!(T, Types[1 .. $]);
}
Config config;
alias TypeOfMember(string memberName) = typeof(__traits(getMember, config, memberName));
alias MemberTypes = staticMap!(TypeOfMember, AliasSeq!(__traits(allMembers, Config)));
foreach(i, arg; args)
{
static assert(isValid!(typeof(arg), MemberTypes),
format!"Argument %s does not match the type of any members of Config"(i));
static foreach(j, Other; Args)
{
static if(i != j)
static assert(!is(typeof(arg) == Other), format!"Argument %s and %s have the same type"(i, j));
}
foreach(memberName; __traits(allMembers, Config))
{
static if(is(typeof(__traits(getMember, config, memberName)) == typeof(arg)))
mixin("config." ~ memberName ~ " = arg;");
}
}
return config;
}
///
version(dxmlTests) @safe pure nothrow @nogc unittest
{
{
auto config = makeConfig(SkipComments.yes);
assert(config.skipComments == SkipComments.yes);
assert(config.skipPI == Config.init.skipPI);
assert(config.splitEmpty == Config.init.splitEmpty);
assert(config.throwOnEntityRef == Config.init.throwOnEntityRef);
}
{
auto config = makeConfig(SkipComments.yes, SkipPI.yes);
assert(config.skipComments == SkipComments.yes);
assert(config.skipPI == SkipPI.yes);
assert(config.splitEmpty == Config.init.splitEmpty);
assert(config.throwOnEntityRef == Config.init.throwOnEntityRef);
}
{
auto config = makeConfig(SplitEmpty.yes, SkipComments.yes, ThrowOnEntityRef.no);
assert(config.skipComments == SkipComments.yes);
assert(config.skipPI == Config.init.skipPI);
assert(config.splitEmpty == SplitEmpty.yes);
assert(config.throwOnEntityRef == ThrowOnEntityRef.no);
}
}
version(dxmlTests) unittest
{
import std.typecons : Flag;
static assert(!__traits(compiles, makeConfig(42)));
static assert(!__traits(compiles, makeConfig("hello")));
static assert(!__traits(compiles, makeConfig(Flag!"SomeOtherFlag".yes)));
static assert(!__traits(compiles, makeConfig(SplitEmpty.yes, SplitEmpty.no)));
}
/++
This $(LREF Config) is intended for making it easy to parse XML by skipping
everything that isn't the actual data as well as making it simpler to deal
with empty element tags by treating them the same as a start tag and end
tag with nothing but whitespace between them.
+/
enum simpleXML = makeConfig(SkipComments.yes, SkipPI.yes, SplitEmpty.yes);
///
version(dxmlTests) @safe pure nothrow @nogc unittest
{
static assert(simpleXML.skipComments == SkipComments.yes);
static assert(simpleXML.skipPI == SkipPI.yes);
static assert(simpleXML.splitEmpty == SplitEmpty.yes);
static assert(simpleXML.throwOnEntityRef == ThrowOnEntityRef.yes);
}
/++
Represents the type of an XML entity. Used by $(LREF EntityRange.Entity).
+/
enum EntityType
{
/++
A cdata section: `<![CDATA[ ... ]]>`.
See_Also: $(LINK http://www.w3.org/TR/REC-xml/#sec-cdata-sect)
+/
cdata,
/++
An XML comment: `<!-- ... -->`.
See_Also: $(LINK http://www.w3.org/TR/REC-xml/#sec-comments)
+/
comment,
/++
The start tag for an element. e.g. `<foo name="value">`.
See_Also: $(LINK http://www.w3.org/TR/REC-xml/#sec-starttags)
+/
elementStart,
/++
The end tag for an element. e.g. `</foo>`.
See_Also: $(LINK http://www.w3.org/TR/REC-xml/#sec-starttags)
+/
elementEnd,
/++
The tag for an element with no contents or matching end tag. e.g.
`<foo name="value"/>`.
See_Also: $(LINK http://www.w3.org/TR/REC-xml/#sec-starttags)
+/
elementEmpty,
/++
A processing instruction such as `<?foo?>`. Note that the
`<?xml ... ?>` is skipped and not treated as an $(LREF EntityType._pi).
See_Also: $(LINK http://www.w3.org/TR/REC-xml/#sec-pi)
+/
pi,
/++
The content of an element tag that is simple text.
If there is an entity other than the end tag following the text, then
the text includes up to that entity.
Note however that character references (e.g.
$(D_CODE_STRING "$(AMP)#42")) and the predefined entity references (e.g.
$(D_CODE_STRING "$(AMP)apos;")) are left unprocessed in the text. In
order for them to be processed, the text should be passed to either
$(REF_ALTTEXT decodeXML, decodeXML, dxml, util) or
$(REF_ALTTEXT asDecodedXML, asDecodedXML, dxml, util). Entity references
which are not predefined are considered invalid XML, because the DTD
section is skipped, and thus they cannot be processed properly.
See_Also: $(LINK http://www.w3.org/TR/REC-xml/#sec-starttags)$(BR)
$(REF decodeXML, dxml, util)$(BR)
$(REF asDecodedXML, dxml, util)$(BR)
$(REF parseStdEntityRef, dxml, util)$(BR)
$(REF parseCharRef, dxml, util)$(BR)
$(LREF EntityRange.Entity._text)
+/
text,
}
/++
Lazily parses the given range of characters as an XML document.
EntityRange is essentially a
$(LINK2 https://en.wikipedia.org/wiki/StAX, StAX) parser, though it evolved
into that rather than being based on what Java did, and it's range-based
rather than iterator-based, so its API is likely to differ from other
implementations. The basic concept should be the same though.
One of the core design goals of this parser is to slice the original input
rather than having to allocate strings for the output or wrap it in a lazy
range that produces a mutated version of the data. So, all of the text that
the parser provides is either a slice or
$(PHOBOS_REF takeExactly, std, range) of the input. However, in some cases,
for the parser to be fully compliant with the XML spec,
$(REF decodeXML, dxml, util) must be called on the text to mutate certain
constructs (e.g. removing any $(D_CODE_STRING '\r') in the text or
converting $(D_CODE_STRING "$(AMP)lt;") to $(D_CODE_STRING '<')). But
that's left up to the application.
The parser is not $(K_NOGC), but it allocates memory very minimally. It
allocates some of its state on the heap so it can validate attributes and
end tags. However, that state is shared among all the ranges that came from
the same call to parseXML (only the range farthest along in parsing
validates attributes or end tags), so $(LREF2 save, _EntityRange) does not
allocate memory unless $(D save) on the underlying range allocates memory.
The shared state currently uses a couple of dynamic arrays to validate the
tags and attributes, and if the document has a particularly deep tag depth
or has a lot of attributes on a start tag, then some reallocations may
occur until the maximum is reached, but enough is reserved that for most
documents, no reallocations will occur. The only other times that the
parser would allocate would be if an exception were thrown or if the range
that was passed to parseXML allocates for any reason when calling any of the
range primitives.
If invalid XML is encountered at any point during the parsing process, an
$(LREF XMLParsingException) will be thrown. If an exception has been thrown,
then the parser is in an invalid state, and it is an error to call any
functions on it.
However, note that XML validation is reduced for any entities that are
skipped (e.g. for anything in the DTD, validation is reduced to what is
required to correctly parse past it, and when
$(D Config.skipPI == SkipPI.yes), processing instructions are only validated
enough to correctly skip past them).
As the module documentation says, this parser does not provide any DTD
support. It is not possible to properly support the DTD while returning
slices of the original input, and the DTD portion of the spec makes parsing
XML far, far more complicated.
A quick note about carriage returns$(COLON) per the XML spec, they are all
supposed to either be stripped out or replaced with newlines or spaces
before the XML parser even processes the text. That doesn't work when the
parser is slicing the original text and not mutating it at all. So, for the
purposes of parsing, this parser treats all carriage returns as if they
were newlines or spaces (though they won't count as newlines when counting
the lines for $(LREF TextPos)). However, they $(I will) appear in any text
fields or attribute values if they are in the document (since the text
fields and attribute values are slices of the original text).
$(REF decodeXML, dxml, util) can be used to strip them along with
converting any character references in the text. Alternatively, the
application can remove them all before calling parseXML, but it's not
necessary.
+/
struct EntityRange(Config cfg, R)
if(isForwardRange!R && isSomeChar!(ElementType!R))
{
import std.algorithm : canFind;
import std.range : only, takeExactly;
import std.typecons : Nullable;
import std.utf : byCodeUnit;
enum compileInTests = is(R == EntityRangeCompileTests);
public:
/// The Config used for when parsing the XML.
alias config = cfg;
/// The type of the range that EntityRange is parsing.
alias Input = R;
/++
The type used when any slice of the original input is used. If $(D R)
is a string or supports slicing, then SliceOfR is the same as $(D R);
otherwise, it's the result of calling
$(PHOBOS_REF takeExactly, std, range) on the input.
---
import std.algorithm : filter;
import std.range : takeExactly;
static assert(is(EntityRange!(Config.init, string).SliceOfR == string));
auto range = filter!(a => true)("some xml");
static assert(is(EntityRange!(Config.init, typeof(range)).SliceOfR ==
typeof(takeExactly(range, 42))));
---
+/
static if(isDynamicArray!R || hasSlicing!R)
alias SliceOfR = R;
else
alias SliceOfR = typeof(takeExactly(R.init, 42));
// https://issues.dlang.org/show_bug.cgi?id=11133 prevents this from being
// a ddoc-ed unit test.
static if(compileInTests) @safe unittest
{
import std.algorithm : filter;
import std.range : takeExactly;
static assert(is(EntityRange!(Config.init, string).SliceOfR == string));
auto range = filter!(a => true)("some xml");
static assert(is(EntityRange!(Config.init, typeof(range)).SliceOfR ==
typeof(takeExactly(range, 42))));
}
/++
Represents an entity in the XML document.
Note that the $(LREF2 type, EntityRange._Entity) determines which
properties can be used, and it can determine whether functions which
an Entity or $(LREF EntityRange) is passed to are allowed to be called.
Each function lists which $(LREF EntityType)s are allowed, and it is an
error to call them with any other $(LREF EntityType).
+/
struct Entity
{
public:
/++
The $(LREF EntityType) for this Entity.
+/
@property EntityType type() @safe const pure nothrow @nogc
{
return _type;
}
///
static if(compileInTests) unittest
{
auto xml = "<root>\n" ~
" <!--no comment-->\n" ~
" <![CDATA[cdata run]]>\n" ~
" <text>I am text!</text>\n" ~
" <empty/>\n" ~
" <?pi?>\n" ~
"</root>";
auto range = parseXML(xml);
assert(range.front.type == EntityType.elementStart);
assert(range.front.name == "root");
range.popFront();
assert(range.front.type == EntityType.comment);
assert(range.front.text == "no comment");
range.popFront();
assert(range.front.type == EntityType.cdata);
assert(range.front.text == "cdata run");
range.popFront();
assert(range.front.type == EntityType.elementStart);
assert(range.front.name == "text");
range.popFront();
assert(range.front.type == EntityType.text);
assert(range.front.text == "I am text!");
range.popFront();
assert(range.front.type == EntityType.elementEnd);
assert(range.front.name == "text");
range.popFront();
assert(range.front.type == EntityType.elementEmpty);
assert(range.front.name == "empty");
range.popFront();
assert(range.front.type == EntityType.pi);
assert(range.front.name == "pi");
range.popFront();
assert(range.front.type == EntityType.elementEnd);
assert(range.front.name == "root");
range.popFront();
assert(range.empty);
}
/++
The position in the the original text where the entity starts.
See_Also: $(LREF TextPos)$(BR)
$(LREF XMLParsingException._pos)
+/
@property TextPos pos() @safe const pure nothrow @nogc
{
return _pos;
}
///
static if(compileInTests) unittest
{
auto xml = "<root>\n" ~
" <foo>\n" ~
" Foo and bar. Always foo and bar...\n" ~
" </foo>\n" ~
"</root>";
auto range = parseXML(xml);
assert(range.front.type == EntityType.elementStart);
assert(range.front.name == "root");
assert(range.front.pos == TextPos(1, 1));
range.popFront();
assert(range.front.type == EntityType.elementStart);
assert(range.front.name == "foo");
assert(range.front.pos == TextPos(2, 5));
range.popFront();
assert(range.front.type == EntityType.text);
assert(range.front.text ==
"\n" ~
" Foo and bar. Always foo and bar...\n" ~
" ");
assert(range.front.pos == TextPos(2, 10));
range.popFront();
assert(range.front.type == EntityType.elementEnd);
assert(range.front.name == "foo");
assert(range.front.pos == TextPos(4, 5));
range.popFront();
assert(range.front.type == EntityType.elementEnd);
assert(range.front.name == "root");
assert(range.front.pos == TextPos(5, 1));
range.popFront();
assert(range.empty);
}
static if(compileInTests) unittest
{
import core.exception : AssertError;
import std.exception : enforce;
static void test(ER)(ref ER range, EntityType type, int row, int col, size_t line = __LINE__)
{
enforce!AssertError(!range.empty, "unittest failure 1", __FILE__, line);
enforce!AssertError(range.front.type == type, "unittest failure 2", __FILE__, line);
enforce!AssertError(range.front.pos == TextPos(row, col), "unittest failure 3", __FILE__, line);
range.popFront();
}
auto xml = "<?xml?>\n" ~
" <!--comment-->\n" ~
" <?pi?>\n" ~
" <root>\n" ~
" <!--comment--><!--comment-->\n" ~
" <?pi?>\n" ~
" <![CDATA[]]>\n" ~
" <empty/> </root>\n" ~
" <!--comment-->\n" ~
" <?pi?>\n";
{