-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathparser.d
1618 lines (1421 loc) · 46.7 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
/**
Generic Diet format parser.
Performs generic parsing of a Diet template file. The resulting AST is
agnostic to the output format context in which it is used. Format
specific constructs, such as inline code or special tags, are parsed
as-is without any preprocessing.
The supported features of the are:
$(UL
$(LI string interpolations)
$(LI assignment expressions)
$(LI blocks/extensions)
$(LI includes)
$(LI text paragraphs)
$(LI translation annotations)
$(LI class and ID attribute shortcuts)
)
*/
module diet.parser;
import diet.dom;
import diet.defs;
import diet.input;
import diet.internal.string;
import std.algorithm.searching : endsWith, startsWith;
import std.range.primitives : empty, front, popFront, popFrontN;
/** Parses a Diet template document and outputs the resulting DOM tree.
The overload that takes a list of files will automatically resolve
includes and extensions.
Params:
TR = An optional translation function that takes and returns a string.
This function will be invoked whenever node text contents need
to be translated at compile tile (for the `&` node suffix).
text = For the single-file overload, specifies the contents of the Diet
template.
filename = For the single-file overload, specifies the file name that
is displayed in error messages and stored in the DOM `Location`s.
files = A full set of Diet template files. All files referenced in
includes or extension directives must be present.
Returns:
The list of parsed root nodes is returned.
*/
Document parseDiet(alias TR = identity)(string text, string filename = "string")
if (is(typeof(TR(string.init)) == string))
{
InputFile[1] f;
f[0].name = filename;
f[0].contents = text;
return parseDiet!TR(f);
}
/// Ditto
Document parseDiet(alias TR = identity)(const(InputFile)[] files)
if (is(typeof(TR(string.init)) == string))
{
import diet.traits;
import std.algorithm.iteration : map;
import std.array : array;
FileInfo[] parsed_files = files.map!(f => FileInfo(f.name, parseDietRaw!TR(f))).array;
BlockInfo[] blocks;
return new Document(parseDietWithExtensions(parsed_files, 0, blocks, null));
}
unittest { // test basic functionality
Location ln(int l) { return Location("string", l); }
// simple node
assert(parseDiet("test").nodes == [
new Node(ln(0), "test")
]);
// nested nodes
assert(parseDiet("foo\n bar").nodes == [
new Node(ln(0), "foo", null, [
NodeContent.tag(new Node(ln(1), "bar"))
])
]);
// node with id and classes
assert(parseDiet("test#id.cls1.cls2").nodes == [
new Node(ln(0), "test", [
Attribute(ln(0), "id", [AttributeContent.text("id")]),
Attribute(ln(0), "class", [AttributeContent.text("cls1")]),
Attribute(ln(0), "class", [AttributeContent.text("cls2")])
])
]);
assert(parseDiet("test.cls1#id.cls2").nodes == [ // issue #9
new Node(ln(0), "test", [
Attribute(ln(0), "class", [AttributeContent.text("cls1")]),
Attribute(ln(0), "id", [AttributeContent.text("id")]),
Attribute(ln(0), "class", [AttributeContent.text("cls2")])
])
]);
// empty tag name (only class)
assert(parseDiet(".foo").nodes == [
new Node(ln(0), "", [
Attribute(ln(0), "class", [AttributeContent.text("foo")])
])
]);
assert(parseDiet("a.download-button\n\t.bs-hbtn.right.black").nodes == [
new Node(ln(0), "a", [
Attribute(ln(0), "class", [AttributeContent.text("download-button")]),
], [
NodeContent.tag(new Node(ln(1), "", [
Attribute(ln(1), "class", [AttributeContent.text("bs-hbtn")]),
Attribute(ln(1), "class", [AttributeContent.text("right")]),
Attribute(ln(1), "class", [AttributeContent.text("black")])
]))
])
]);
// empty tag name (only id)
assert(parseDiet("#foo").nodes == [
new Node(ln(0), "", [
Attribute(ln(0), "id", [AttributeContent.text("foo")])
])
]);
// node with attributes
assert(parseDiet("test(foo1=\"bar\", foo2=2+3)").nodes == [
new Node(ln(0), "test", [
Attribute(ln(0), "foo1", [AttributeContent.text("bar")]),
Attribute(ln(0), "foo2", [AttributeContent.interpolation("2+3")])
])
]);
// node with pure text contents
assert(parseDiet("foo.\n\thello\n\t world").nodes == [
new Node(ln(0), "foo", null, [
NodeContent.text("hello", ln(1)),
NodeContent.text("\n world", ln(2))
], NodeAttribs.textNode)
]);
assert(parseDiet("foo.\n\thello\n\n\t world").nodes == [
new Node(ln(0), "foo", null, [
NodeContent.text("hello", ln(1)),
NodeContent.text("\n", ln(2)),
NodeContent.text("\n world", ln(3))
], NodeAttribs.textNode)
]);
// translated text
assert(parseDiet("foo& test").nodes == [
new Node(ln(0), "foo", null, [
NodeContent.text("test", ln(0))
], NodeAttribs.translated, "test")
]);
// interpolated text
assert(parseDiet("foo hello #{\"world\"} #bar \\#{baz}").nodes == [
new Node(ln(0), "foo", null, [
NodeContent.text("hello ", ln(0)),
NodeContent.interpolation(`"world"`, ln(0)),
NodeContent.text(" #bar #{baz}", ln(0))
])
]);
// expression
assert(parseDiet("foo= 1+2").nodes == [
new Node(ln(0), "foo", null, [
NodeContent.interpolation(`1+2`, ln(0)),
])
]);
// expression with empty tag name
assert(parseDiet("= 1+2").nodes == [
new Node(ln(0), "", null, [
NodeContent.interpolation(`1+2`, ln(0)),
])
]);
// raw expression
assert(parseDiet("foo!= 1+2").nodes == [
new Node(ln(0), "foo", null, [
NodeContent.rawInterpolation(`1+2`, ln(0)),
])
]);
// interpolated attribute text
assert(parseDiet("foo(att='hello #{\"world\"} #bar')").nodes == [
new Node(ln(0), "foo", [
Attribute(ln(0), "att", [
AttributeContent.text("hello "),
AttributeContent.interpolation(`"world"`),
AttributeContent.text(" #bar")
])
])
]);
// attribute expression
assert(parseDiet("foo(att=1+2)").nodes == [
new Node(ln(0), "foo", [
Attribute(ln(0), "att", [
AttributeContent.interpolation(`1+2`),
])
])
]);
// multiline attribute expression
assert(parseDiet("foo(\n\tatt=1+2,\n\tfoo=bar\n)").nodes == [
new Node(ln(0), "foo", [
Attribute(ln(0), "att", [
AttributeContent.interpolation(`1+2`),
]),
Attribute(ln(0), "foo", [
AttributeContent.interpolation(`bar`),
])
])
]);
// special nodes
assert(parseDiet("//comment").nodes == [
new Node(ln(0), Node.SpecialName.comment, null, [NodeContent.text("comment", ln(0))], NodeAttribs.rawTextNode)
]);
assert(parseDiet("//-hide").nodes == [
new Node(ln(0), Node.SpecialName.hidden, null, [NodeContent.text("hide", ln(0))], NodeAttribs.rawTextNode)
]);
assert(parseDiet("!!! 5").nodes == [
new Node(ln(0), "doctype", null, [NodeContent.text("5", ln(0))])
]);
assert(parseDiet("<inline>").nodes == [
new Node(ln(0), Node.SpecialName.text, null, [NodeContent.text("<inline>", ln(0))])
]);
assert(parseDiet("|text").nodes == [
new Node(ln(0), Node.SpecialName.text, null, [NodeContent.text("text", ln(0))])
]);
assert(parseDiet("|text\n").nodes == [
new Node(ln(0), Node.SpecialName.text, null, [NodeContent.text("text", ln(0))])
]);
assert(parseDiet("| text\n").nodes == [
new Node(ln(0), Node.SpecialName.text, null, [NodeContent.text("text", ln(0))])
]);
assert(parseDiet("|.").nodes == [
new Node(ln(0), Node.SpecialName.text, null, [NodeContent.text(".", ln(0))])
]);
assert(parseDiet("|:").nodes == [
new Node(ln(0), Node.SpecialName.text, null, [NodeContent.text(":", ln(0))])
]);
assert(parseDiet("|&x").nodes == [
new Node(ln(0), Node.SpecialName.text, null, [NodeContent.text("x", ln(0))], NodeAttribs.translated, "x")
]);
assert(parseDiet("-if(x)").nodes == [
new Node(ln(0), Node.SpecialName.code, null, [NodeContent.text("if(x)", ln(0))])
]);
assert(parseDiet("-if(x)\n\t|bar").nodes == [
new Node(ln(0), Node.SpecialName.code, null, [
NodeContent.text("if(x)", ln(0)),
NodeContent.tag(new Node(ln(1), Node.SpecialName.text, null, [
NodeContent.text("bar", ln(1))
]))
])
]);
assert(parseDiet(":foo\n\tbar").nodes == [
new Node(ln(0), ":", [Attribute(ln(0), "filterChain", [AttributeContent.text("foo")])], [
NodeContent.text("bar", ln(1))
], NodeAttribs.textNode)
]);
assert(parseDiet(":foo :bar baz").nodes == [
new Node(ln(0), ":", [Attribute(ln(0), "filterChain", [AttributeContent.text("foo bar")])], [
NodeContent.text("baz", ln(0))
], NodeAttribs.textNode)
]);
assert(parseDiet(":foo\n\t:bar baz").nodes == [
new Node(ln(0), ":", [Attribute(ln(0), "filterChain", [AttributeContent.text("foo")])], [
NodeContent.text(":bar baz", ln(1))
], NodeAttribs.textNode)
]);
assert(parseDiet(":foo\n\tbar\n\t\t:baz").nodes == [
new Node(ln(0), ":", [Attribute(ln(0), "filterChain", [AttributeContent.text("foo")])], [
NodeContent.text("bar", ln(1)),
NodeContent.text("\n\t:baz", ln(2))
], NodeAttribs.textNode)
]);
// nested nodes
assert(parseDiet("a: b").nodes == [
new Node(ln(0), "a", null, [
NodeContent.tag(new Node(ln(0), "b"))
])
]);
assert(parseDiet("a: b\n\tc\nd").nodes == [
new Node(ln(0), "a", null, [
NodeContent.tag(new Node(ln(0), "b", null, [
NodeContent.tag(new Node(ln(1), "c"))
]))
]),
new Node(ln(2), "d")
]);
// inline nodes
assert(parseDiet("a #[b]").nodes == [
new Node(ln(0), "a", null, [
NodeContent.tag(new Node(ln(0), "b"))
])
]);
assert(parseDiet("a #[b #[c d]]").nodes == [
new Node(ln(0), "a", null, [
NodeContent.tag(new Node(ln(0), "b", null, [
NodeContent.tag(new Node(ln(0), "c", null, [
NodeContent.text("d", ln(0))
]))
]))
])
]);
// whitespace fitting
assert(parseDiet("a<>").nodes == [
new Node(ln(0), "a", null, [], NodeAttribs.fitInside|NodeAttribs.fitOutside)
]);
assert(parseDiet("a><").nodes == [
new Node(ln(0), "a", null, [], NodeAttribs.fitInside|NodeAttribs.fitOutside)
]);
assert(parseDiet("a<").nodes == [
new Node(ln(0), "a", null, [], NodeAttribs.fitInside)
]);
assert(parseDiet("a>").nodes == [
new Node(ln(0), "a", null, [], NodeAttribs.fitOutside)
]);
}
unittest {
Location ln(int l) { return Location("string", l); }
// angular2 html attributes tests
assert(parseDiet("div([value]=\"firstName\")").nodes == [
new Node(ln(0), "div", [
Attribute(ln(0), "[value]", [
AttributeContent.text("firstName"),
])
])
]);
assert(parseDiet("div([attr.role]=\"myRole\")").nodes == [
new Node(ln(0), "div", [
Attribute(ln(0), "[attr.role]", [
AttributeContent.text("myRole"),
])
])
]);
assert(parseDiet("div([attr.role]=\"{foo:myRole}\")").nodes == [
new Node(ln(0), "div", [
Attribute(ln(0), "[attr.role]", [
AttributeContent.text("{foo:myRole}"),
])
])
]);
assert(parseDiet("div([attr.role]=\"{foo:myRole, bar:MyRole}\")").nodes == [
new Node(ln(0), "div", [
Attribute(ln(0), "[attr.role]", [
AttributeContent.text("{foo:myRole, bar:MyRole}")
])
])
]);
assert(parseDiet("div((attr.role)=\"{foo:myRole, bar:MyRole}\")").nodes == [
new Node(ln(0), "div", [
Attribute(ln(0), "(attr.role)", [
AttributeContent.text("{foo:myRole, bar:MyRole}")
])
])
]);
assert(parseDiet("div([class.extra-sparkle]=\"isDelightful\")").nodes == [
new Node(ln(0), "div", [
Attribute(ln(0), "[class.extra-sparkle]", [
AttributeContent.text("isDelightful")
])
])
]);
auto t = parseDiet("div((click)=\"readRainbow($event)\")");
assert(t.nodes == [
new Node(ln(0), "div", [
Attribute(ln(0), "(click)", [
AttributeContent.text("readRainbow($event)")
])
])
]);
assert(parseDiet("div([(title)]=\"name\")").nodes == [
new Node(ln(0), "div", [
Attribute(ln(0), "[(title)]", [
AttributeContent.text("name")
])
])
]);
assert(parseDiet("div(*myUnless=\"myExpression\")").nodes == [
new Node(ln(0), "div", [
Attribute(ln(0), "*myUnless", [
AttributeContent.text("myExpression")
])
])
]);
assert(parseDiet("div([ngClass]=\"{active: isActive, disabled: isDisabled}\")").nodes == [
new Node(ln(0), "div", [
Attribute(ln(0), "[ngClass]", [
AttributeContent.text("{active: isActive, disabled: isDisabled}")
])
])
]);
t = parseDiet("div(*ngFor=\"\\#item of list\")");
assert(t.nodes == [
new Node(ln(0), "div", [
Attribute(ln(0), "*ngFor", [
AttributeContent.text("#"),
AttributeContent.text("item of list")
])
])
]);
t = parseDiet("div(({*ngFor})=\"{args:\\#item of list}\")");
assert(t.nodes == [
new Node(ln(0), "div", [
Attribute(ln(0), "({*ngFor})", [
AttributeContent.text("{args:"),
AttributeContent.text("#"),
AttributeContent.text("item of list}")
])
])
]);
}
unittest { // translation
import std.string : toUpper;
static Location ln(int l) { return Location("string", l); }
static string tr(string str) { return "("~toUpper(str)~")"; }
assert(parseDiet!tr("foo& test").nodes == [
new Node(ln(0), "foo", null, [
NodeContent.text("(TEST)", ln(0))
], NodeAttribs.translated, "test")
]);
assert(parseDiet!tr("foo& test #{x} it").nodes == [
new Node(ln(0), "foo", null, [
NodeContent.text("(TEST ", ln(0)),
NodeContent.interpolation("X", ln(0)),
NodeContent.text(" IT)", ln(0)),
], NodeAttribs.translated, "test #{x} it")
]);
assert(parseDiet!tr("|&x").nodes == [
new Node(ln(0), Node.SpecialName.text, null, [NodeContent.text("(X)", ln(0))], NodeAttribs.translated, "x")
]);
assert(parseDiet!tr("foo&.\n\tbar\n\tbaz").nodes == [
new Node(ln(0), "foo", null, [
NodeContent.text("(BAR)", ln(1)),
NodeContent.text("\n(BAZ)", ln(2))
], NodeAttribs.translated|NodeAttribs.textNode, "bar\nbaz")
]);
}
unittest { // test expected errors
void testFail(string diet, string msg)
{
try {
parseDiet(diet);
assert(false, "Expected exception was not thrown.");
} catch (DietParserException ex) assert(ex.msg == msg, "Unexpected error message: "~ex.msg);
}
testFail("+test", "Expected node text separated by a space character or end of line, but got '+test'.");
testFail(" test", "First node must not be indented.");
testFail("test\n test\n\ttest", "Mismatched indentation style.");
testFail("test\n\ttest\n\t\t\ttest", "Line is indented too deeply.");
testFail("test#", "Expected identifier but got nothing.");
testFail("test.()", "Expected identifier but got '('.");
testFail("a #[b.]", "Multi-line text nodes are not permitted for inline-tags.");
testFail("a #[b: c]", "Nested inline-tags not allowed.");
testFail("a#foo#bar", "Only one \"id\" definition using '#' is allowed.");
}
unittest { // includes
Node[] parse(string diet) {
auto files = [
InputFile("main.dt", diet),
InputFile("inc.dt", "p")
];
return parseDiet(files).nodes;
}
void testFail(string diet, string msg)
{
try {
parse(diet);
assert(false, "Expected exception was not thrown");
} catch (DietParserException ex) {
assert(ex.msg == msg, "Unexpected error message: "~ex.msg);
}
}
assert(parse("include inc") == [
new Node(Location("inc.dt", 0), "p", null, null)
]);
testFail("include main", "Dependency cycle detected for this module.");
testFail("include inc2", "Missing include input file: inc2");
testFail("include #{p}", "Dynamic includes are not supported.");
testFail("include inc\n\tp", "Only 'block' allowed as children of includes.");
testFail("p\ninclude inc\n\tp", "Only 'block' allowed as children of includes.");
}
unittest { // extensions
Node[] parse(string diet) {
auto files = [
InputFile("main.dt", diet),
InputFile("root.dt", "html\n\tblock a\n\tblock b"),
InputFile("intermediate.dt", "extends root\nblock a\n\tp"),
InputFile("direct.dt", "block a")
];
return parseDiet(files).nodes;
}
void testFail(string diet, string msg)
{
try {
parse(diet);
assert(false, "Expected exception was not thrown");
} catch (DietParserException ex) {
assert(ex.msg == msg, "Unexpected error message: "~ex.msg);
}
}
assert(parse("extends root") == [
new Node(Location("root.dt", 0), "html", null, null)
]);
assert(parse("extends root\nblock a\n\tdiv\nblock b\n\tpre") == [
new Node(Location("root.dt", 0), "html", null, [
NodeContent.tag(new Node(Location("main.dt", 2), "div", null, null)),
NodeContent.tag(new Node(Location("main.dt", 4), "pre", null, null))
])
]);
assert(parse("extends intermediate\nblock b\n\tpre") == [
new Node(Location("root.dt", 0), "html", null, [
NodeContent.tag(new Node(Location("intermediate.dt", 2), "p", null, null)),
NodeContent.tag(new Node(Location("main.dt", 2), "pre", null, null))
])
]);
assert(parse("extends intermediate\nblock a\n\tpre") == [
new Node(Location("root.dt", 0), "html", null, [
NodeContent.tag(new Node(Location("main.dt", 2), "pre", null, null))
])
]);
assert(parse("extends intermediate\nappend a\n\tpre") == [
new Node(Location("root.dt", 0), "html", null, [
NodeContent.tag(new Node(Location("intermediate.dt", 2), "p", null, null)),
NodeContent.tag(new Node(Location("main.dt", 2), "pre", null, null))
])
]);
assert(parse("extends intermediate\nprepend a\n\tpre") == [
new Node(Location("root.dt", 0), "html", null, [
NodeContent.tag(new Node(Location("main.dt", 2), "pre", null, null)),
NodeContent.tag(new Node(Location("intermediate.dt", 2), "p", null, null))
])
]);
assert(parse("extends intermediate\nprepend a\n\tfoo\nappend a\n\tbar") == [ // issue #13
new Node(Location("root.dt", 0), "html", null, [
NodeContent.tag(new Node(Location("main.dt", 2), "foo", null, null)),
NodeContent.tag(new Node(Location("intermediate.dt", 2), "p", null, null)),
NodeContent.tag(new Node(Location("main.dt", 4), "bar", null, null))
])
]);
assert(parse("extends intermediate\nprepend a\n\tfoo\nprepend a\n\tbar\nappend a\n\tbaz\nappend a\n\tbam") == [
new Node(Location("root.dt", 0), "html", null, [
NodeContent.tag(new Node(Location("main.dt", 2), "foo", null, null)),
NodeContent.tag(new Node(Location("main.dt", 4), "bar", null, null)),
NodeContent.tag(new Node(Location("intermediate.dt", 2), "p", null, null)),
NodeContent.tag(new Node(Location("main.dt", 6), "baz", null, null)),
NodeContent.tag(new Node(Location("main.dt", 8), "bam", null, null))
])
]);
assert(parse("extends direct") == []);
assert(parse("extends direct\nblock a\n\tp") == [
new Node(Location("main.dt", 2), "p", null, null)
]);
}
unittest { // include extensions
Node[] parse(string diet) {
auto files = [
InputFile("main.dt", diet),
InputFile("root.dt", "p\n\tblock a"),
];
return parseDiet(files).nodes;
}
assert(parse("body\n\tinclude root\n\t\tblock a\n\t\t\tem") == [
new Node(Location("main.dt", 0), "body", null, [
NodeContent.tag(new Node(Location("root.dt", 0), "p", null, [
NodeContent.tag(new Node(Location("main.dt", 3), "em", null, null))
]))
])
]);
assert(parse("body\n\tinclude root\n\t\tblock a\n\t\t\tem\n\tinclude root\n\t\tblock a\n\t\t\tstrong") == [
new Node(Location("main.dt", 0), "body", null, [
NodeContent.tag(new Node(Location("root.dt", 0), "p", null, [
NodeContent.tag(new Node(Location("main.dt", 3), "em", null, null))
])),
NodeContent.tag(new Node(Location("root.dt", 0), "p", null, [
NodeContent.tag(new Node(Location("main.dt", 6), "strong", null, null))
]))
])
]);
}
unittest { // test CTFE-ability
static const result = parseDiet("foo#id.cls(att=\"val\", att2=1+3, att3='test#{4}it')\n\tbar");
static assert(result.nodes.length == 1);
}
unittest { // regression tests
Location ln(int l) { return Location("string", l); }
// last line contains only whitespace
assert(parseDiet("test\n\t").nodes == [
new Node(ln(0), "test")
]);
}
unittest { // issue #14 - blocks in includes
auto files = [
InputFile("main.dt", "extends layout\nblock nav\n\tbaz"),
InputFile("layout.dt", "foo\ninclude inc"),
InputFile("inc.dt", "bar\nblock nav"),
];
assert(parseDiet(files).nodes == [
new Node(Location("layout.dt", 0), "foo", null, null),
new Node(Location("inc.dt", 0), "bar", null, null),
new Node(Location("main.dt", 2), "baz", null, null)
]);
}
unittest { // issue #32 - numeric id/class
Location ln(int l) { return Location("string", l); }
assert(parseDiet("foo.01#02").nodes == [
new Node(ln(0), "foo", [
Attribute(ln(0), "class", [AttributeContent.text("01")]),
Attribute(ln(0), "id", [AttributeContent.text("02")])
])
]);
}
/** Dummy translation function that returns the input unmodified.
*/
string identity(string str) nothrow @safe @nogc { return str; }
private string parseIdent(in ref string str, ref size_t start,
string breakChars, in ref Location loc)
{
import std.array : back;
/* The stack is used to keep track of opening and
closing character pairs, so that when we hit a break char of
breakChars we know if we can actually break parseIdent.
*/
char[] stack;
size_t i = start;
outer: while(i < str.length) {
if(stack.length == 0) {
foreach(char it; breakChars) {
if(str[i] == it) {
break outer;
}
}
}
if(stack.length && stack.back == str[i]) {
stack = stack[0 .. $ - 1];
} else if(str[i] == '"') {
stack ~= '"';
} else if(str[i] == '(') {
stack ~= ')';
} else if(str[i] == '[') {
stack ~= ']';
} else if(str[i] == '{') {
stack ~= '}';
}
++i;
}
/* We could have consumed the complete string and still have elements
on the stack or have ended non breakChars character.
*/
if(stack.length == 0) {
foreach(char it; breakChars) {
if(str[i] == it) {
size_t startC = start;
start = i;
return str[startC .. i];
}
}
}
enforcep(false, "Identifier was not ended by any of these characters: "
~ breakChars, loc);
assert(false);
}
private Node[] parseDietWithExtensions(FileInfo[] files, size_t file_index, ref BlockInfo[] blocks, size_t[] import_stack)
{
import std.algorithm : all, any, canFind, countUntil, filter, find, map;
import std.array : array;
import std.path : stripExtension;
import std.typecons : Nullable;
auto floc = Location(files[file_index].name, 0);
enforcep(!import_stack.canFind(file_index), "Dependency cycle detected for this module.", floc);
Node[] nodes = files[file_index].nodes;
if (!nodes.length) return null;
if (nodes[0].name == "extends") {
// extract base template name/index
enforcep(nodes[0].isTextNode, "'extends' cannot contain children or interpolations.", nodes[0].loc);
enforcep(nodes[0].attributes.length == 0, "'extends' cannot have attributes.", nodes[0].loc);
string base_template = nodes[0].contents[0].value.ctstrip;
auto base_idx = files.countUntil!(f => matchesName(f.name, base_template, files[file_index].name));
assert(base_idx >= 0, "Missing base template: "~base_template);
// collect all blocks
foreach (n; nodes[1 .. $]) {
BlockInfo.Mode mode;
switch (n.name) {
default:
enforcep(false, "Extension templates may only contain blocks definitions at the root level.", n.loc);
break;
case Node.SpecialName.comment, Node.SpecialName.hidden: continue; // also allow comments at the root level
case "block": mode = BlockInfo.Mode.replace; break;
case "prepend": mode = BlockInfo.Mode.prepend; break;
case "append": mode = BlockInfo.Mode.append; break;
}
enforcep(n.contents.length > 0 && n.contents[0].kind == NodeContent.Kind.text,
"'block' must have a name.", n.loc);
auto name = n.contents[0].value.ctstrip;
auto contents = n.contents[1 .. $].filter!(n => n.kind == NodeContent.Kind.node).map!(n => n.node).array;
blocks ~= BlockInfo(name, mode, contents);
}
// save the original file contents for a possible later parsing as part of an
// extension include directive (blocks are replaced in-place as part of the parsing
// process)
auto new_files = files.dup;
new_files[base_idx].nodes = clone(new_files[base_idx].nodes);
// parse base template
return parseDietWithExtensions(new_files, base_idx, blocks, import_stack ~ file_index);
}
static string extractFilename(Node n)
{
enforcep(n.contents.length >= 1 && n.contents[0].kind != NodeContent.Kind.node,
"Missing block name.", n.loc);
enforcep(n.contents[0].kind == NodeContent.Kind.text,
"Dynamic includes are not supported.", n.loc);
enforcep(n.contents.length == 1 || n.contents[1 .. $].all!(nc => nc.kind == NodeContent.Kind.node),
"'"~n.name~"' must only contain a block name and child nodes.", n.loc);
enforcep(n.attributes.length == 0, "'"~n.name~"' cannot have attributes.", n.loc);
return n.contents[0].value.ctstrip;
}
Nullable!(Node[]) processNode(Node n) {
Nullable!(Node[]) ret;
void insert(Node[] nodes) {
foreach (i, n; nodes) {
auto np = processNode(n);
if (!np.isNull()) {
if (ret.isNull) ret = nodes[0 .. i];
ret.get ~= np;
} else if (!ret.isNull) ret.get ~= n;
}
if (ret.isNull && nodes.length) ret = nodes;
}
if (n.name == "block") {
auto name = extractFilename(n);
auto blockdefs = blocks.filter!(b => b.name == name);
foreach (b; blockdefs.save.filter!(b => b.mode == BlockInfo.Mode.prepend))
insert(b.contents);
auto replblocks = blockdefs.save.find!(b => b.mode == BlockInfo.Mode.replace);
if (!replblocks.empty) {
insert(replblocks.front.contents);
} else {
insert(n.contents[1 .. $].map!((nc) {
assert(nc.kind == NodeContent.Kind.node, "Block contains non-node child!?");
return nc.node;
}).array);
}
foreach (b; blockdefs.save.filter!(b => b.mode == BlockInfo.Mode.append))
insert(b.contents);
if (ret.isNull) ret = [];
} else if (n.name == "include") {
auto name = extractFilename(n);
auto fidx = files.countUntil!(f => matchesName(f.name, name, files[file_index].name));
enforcep(fidx >= 0, "Missing include input file: "~name, n.loc);
if (n.contents.length > 1) {
auto dummy = new Node(n.loc, "extends");
dummy.addText(name, n.contents[0].loc);
Node[] children = [dummy];
foreach (nc; n.contents[1 .. $]) {
enforcep(nc.node !is null && nc.node.name == "block",
"Only 'block' allowed as children of includes.", nc.loc);
children ~= nc.node;
}
import std.path : extension;
auto dummyfil = FileInfo("include"~extension(files[file_index].name), children);
BlockInfo[] sub_blocks;
insert(parseDietWithExtensions(files ~ dummyfil, files.length, sub_blocks, import_stack));
} else {
insert(parseDietWithExtensions(files, fidx, blocks, import_stack ~ file_index));
}
} else {
n.contents = n.contents.mapJoin!((nc) {
Nullable!(NodeContent[]) rn;
if (nc.kind == NodeContent.Kind.node) {
auto mod = processNode(nc.node);
if (!mod.isNull()) rn = mod.get.map!(n => NodeContent.tag(n)).array;
}
assert(rn.isNull || rn.get.all!(n => n.node.name != "block"));
return rn;
});
}
assert(ret.isNull || ret.get.all!(n => n.name != "block"));
return ret;
}
nodes = nodes.mapJoin!(processNode);
assert(nodes.all!(n => n.name != "block"));
return nodes;
}
private struct BlockInfo {
enum Mode {
prepend,
replace,
append
}
string name;
Mode mode = Mode.replace;
Node[] contents;
}
private struct FileInfo {
string name;
Node[] nodes;
}
/** Parses a single Diet template file, without resolving includes and extensions.
See_Also: `parseDiet`
*/
Node[] parseDietRaw(alias TR)(InputFile file)
{
import std.algorithm.iteration : map;
import std.algorithm.comparison : among;
import std.array : array;
string indent_style;
auto loc = Location(file.name, 0);
int prevlevel = -1;
string input = file.contents;
Node[] ret;
// nested stack of nodes
// the first dimension is corresponds to indentation based nesting
// the second dimension is for in-line nested nodes
Node[][] stack;
stack.length = 8;
string previndent; // inherited by blank lines
next_line:
while (input.length) {
Node pnode;
if (prevlevel >= 0 && stack[prevlevel].length) pnode = stack[prevlevel][$-1];
// skip whitespace at the beginning of the line
string indent = input.skipIndent();
// treat empty lines as if they had the indendation level of the last non-empty line
if (input.empty || input[0].among('\n', '\r'))
indent = previndent;
else previndent = indent;
enforcep(prevlevel >= 0 || indent.length == 0, "First node must not be indented.", loc);
// determine the indentation style (tabs/spaces) from the first indented
// line of the file
if (indent.length && !indent_style.length) indent_style = indent;
// determine nesting level
bool is_text_line = pnode && (pnode.attribs & (NodeAttribs.textNode|NodeAttribs.rawTextNode)) != 0;
int level = 0;
if (indent_style.length) {
while (indent.startsWith(indent_style)) {
if (level > prevlevel) {
enforcep(is_text_line, "Line is indented too deeply.", loc);
break;
}
level++;
indent = indent[indent_style.length .. $];
}
}
enforcep(is_text_line || indent.length == 0, "Mismatched indentation style.", loc);
// read the whole line as text if the parent node is a pure text node
// ("." suffix) or pure raw text node (e.g. comments)
if (level > prevlevel && prevlevel >= 0) {
if (pnode.attribs & NodeAttribs.textNode) {
if (!pnode.contents.empty) {
pnode.addText("\n", loc);
if (pnode.attribs & NodeAttribs.translated)
pnode.translationKey ~= "\n";
}
if (indent.length) pnode.addText(indent, loc);
parseTextLine!TR(input, pnode, loc);
continue;
} else if (pnode.attribs & NodeAttribs.rawTextNode) {
if (!pnode.contents.empty)
pnode.addText("\n", loc);
if (indent.length) pnode.addText(indent, loc);
auto tmploc = loc;
pnode.addText(skipLine(input, loc), tmploc);
continue;
}
}
// skip empty lines
if (input.empty) break;
else if (input[0] == '\n') { loc.line++; input.popFront(); continue; }
else if (input[0] == '\r') {
loc.line++;
input.popFront();
if (!input.empty && input[0] == '\n')
input.popFront();
continue;
}
// parse the line and write it to the stack:
if (stack.length < level+1) stack.length = level+1;
if (input.startsWith("//")) {
// comments
auto n = new Node;
n.loc = loc;
if (input[2 .. $].startsWith("-")) { n.name = Node.SpecialName.hidden; input = input[3 .. $]; }
else { n.name = Node.SpecialName.comment; input = input[2 .. $]; }
n.attribs |= NodeAttribs.rawTextNode;
auto tmploc = loc;
n.addText(skipLine(input, loc), tmploc);
stack[level] = [n];
} else if (input.startsWith('-')) {
// D statements
input = input[1 .. $];
auto n = new Node;
n.loc = loc;
n.name = Node.SpecialName.code;
auto tmploc = loc;
n.addText(skipLine(input, loc), tmploc);
stack[level] = [n];
} else if (input.startsWith(':')) {
// filters
stack[level] = [];
string chain;