diet.parser 0/685(0%) line coverage

      
10
20
30
40
50
60
70
80
90
100
110
120
130
140
150
160
170
180
190
200
210
220
230
240
250
260
270
280
290
300
310
320
330
340
350
360
370
380
390
400
410
420
430
440
450
460
470
480
490
500
510
520
530
540
550
560
570
580
590
600
610
620
630
640
650
660
670
680
690
700
710
720
730
740
750
760
770
780
790
800
810
820
830
840
850
860
870
880
890
900
910
920
930
940
950
960
970
980
990
1000
1010
1020
1030
1040
1050
1060
1070
1080
1090
1100
1110
1120
1130
1140
1150
1160
1170
1180
1190
1200
1210
1220
1230
1240
1250
1260
1270
1280
1290
1300
1310
1320
1330
1340
1350
1360
1370
1380
1390
1400
1410
1420
1430
1440
1450
1460
1470
1480
1490
1500
1510
1520
1530
1540
1550
1560
1570
1580
1590
1600
1610
1620
1630
1640
1650
1660
1670
1680
1690
1700
1710
1720
1730
1740
1750
1760
1770
1780
1790
1800
1810
1820
1830
1840
1850
1860
1870
1880
1890
1900
1910
1920
1930
1940
1950
1960
1970
1980
1990
2000
2010
2020
2030
2040
2050
2060
2070
2080
2090
2100
2110
2120
2130
2140
2150
2160
2170
2180
2190
2200
2210
2220
2230
2240
2250
2260
2270
2280
2290
2300
2310
2320
2330
2340
2350
2360
2370
2380
2390
2400
2410
2420
2430
2440
2450
2460
2470
2480
2490
2500
2510
2520
2530
2540
2550
2560
2570
2580
2590
2600
2610
2620
2630
2640
2650
2660
2670
2680
2690
2700
2710
2720
2730
2740
2750
2760
2770
2780
2790
2800
2810
2820
2830
2840
2850
2860
2870
2880
2890
2900
2910
2920
2930
2940
2950
2960
2970
2980
2990
3000
3010
3020
3030
3040
3050
3060
3070
3080
3090
3100
3110
3120
3130
3140
3150
3160
3170
3180
3190
3200
3210
3220
3230
3240
3250
3260
3270
3280
3290
3300
3310
3320
3330
3340
3350
3360
3370
3380
3390
3400
3410
3420
3430
3440
3450
3460
3470
3480
3490
3500
3510
3520
3530
3540
3550
3560
3570
3580
3590
3600
3610
3620
3630
3640
3650
3660
3670
3680
3690
3700
3710
3720
3730
3740
3750
3760
3770
3780
3790
3800
3810
3820
3830
3840
3850
3860
3870
3880
3890
3900
3910
3920
3930
3940
3950
3960
3970
3980
3990
4000
4010
4020
4030
4040
4050
4060
4070
4080
4090
4100
4110
4120
4130
4140
4150
4160
4170
4180
4190
4200
4210
4220
4230
4240
4250
4260
4270
4280
4290
4300
4310
4320
4330
4340
4350
4360
4370
4380
4390
4400
4410
4420
4430
4440
4450
4460
4470
4480
4490
4500
4510
4520
4530
4540
4550
4560
4570
4580
4590
4600
4610
4620
4630
4640
4650
4660
4670
4680
4690
4700
4710
4720
4730
4740
4750
4760
4770
4780
4790
4800
4810
4820
4830
4840
4850
4860
4870
4880
4890
4900
4910
4920
4930
4940
4950
4960
4970
4980
4990
5000
5010
5020
5030
5040
5050
5060
5070
5080
5090
5100
5110
5120
5130
5140
5150
5160
5170
5180
5190
5200
5210
5220
5230
5240
5250
5260
5270
5280
5290
5300
5310
5320
5330
5340
5350
5360
5370
5380
5390
5400
5410
5420
5430
5440
5450
5460
5470
5480
5490
5500
5510
5520
5530
5540
5550
5560
5570
5580
5590
5600
5610
5620
5630
5640
5650
5660
5670
5680
5690
5700
5710
5720
5730
5740
5750
5760
5770
5780
5790
5800
5810
5820
5830
5840
5850
5860
5870
5880
5890
5900
5910
5920
5930
5940
5950
5960
5970
5980
5990
6000
6010
6020
6030
6040
6050
6060
6070
6080
6090
6100
6110
6120
6130
6140
6150
6160
6170
6180
6190
6200
6210
6220
6230
6240
6250
6260
6270
6280
6290
6300
6310
6320
6330
6340
6350
6360
6370
6380
6390
6400
6410
6420
6430
6440
6450
6460
6470
6480
6490
6500
6510
6520
6530
6540
6550
6560
6570
6580
6590
6600
6610
6620
6630
6640
6650
6660
6670
6680
6690
6700
6710
6720
6730
6740
6750
6760
6770
6780
6790
6800
6810
6820
6830
6840
6850
6860
6870
6880
6890
6900
6910
6920
6930
6940
6950
6960
6970
6980
6990
7000
7010
7020
7030
7040
7050
7060
7070
7080
7090
7100
7110
7120
7130
7140
7150
7160
7170
7180
7190
7200
7210
7220
7230
7240
7250
7260
7270
7280
7290
7300
7310
7320
7330
7340
7350
7360
7370
7380
7390
7400
7410
7420
7430
7440
7450
7460
7470
7480
7490
7500
7510
7520
7530
7540
7550
7560
7570
7580
7590
7600
7610
7620
7630
7640
7650
7660
7670
7680
7690
7700
7710
7720
7730
7740
7750
7760
7770
7780
7790
7800
7810
7820
7830
7840
7850
7860
7870
7880
7890
7900
7910
7920
7930
7940
7950
7960
7970
7980
7990
8000
8010
8020
8030
8040
8050
8060
8070
8080
8090
8100
8110
8120
8130
8140
8150
8160
8170
8180
8190
8200
8210
8220
8230
8240
8250
8260
8270
8280
8290
8300
8310
8320
8330
8340
8350
8360
8370
8380
8390
8400
8410
8420
8430
8440
8450
8460
8470
8480
8490
8500
8510
8520
8530
8540
8550
8560
8570
8580
8590
8600
8610
8620
8630
8640
8650
8660
8670
8680
8690
8700
8710
8720
8730
8740
8750
8760
8770
8780
8790
8800
8810
8820
8830
8840
8850
8860
8870
8880
8890
8900
8910
8920
8930
8940
8950
8960
8970
8980
8990
9000
9010
9020
9030
9040
9050
9060
9070
9080
9090
9100
9110
9120
9130
9140
9150
9160
9170
9180
9190
9200
9210
9220
9230
9240
9250
9260
9270
9280
9290
9300
9310
9320
9330
9340
9350
9360
9370
9380
9390
9400
9410
9420
9430
9440
9450
9460
9470
9480
9490
9500
9510
9520
9530
9540
9550
9560
9570
9580
9590
9600
9610
9620
9630
9640
9650
9660
9670
9680
9690
9700
9710
9720
9730
9740
9750
9760
9770
9780
9790
9800
9810
9820
9830
9840
9850
9860
9870
9880
9890
9900
9910
9920
9930
9940
9950
9960
9970
9980
9990
10000
10010
10020
10030
10040
10050
10060
10070
10080
10090
10100
10110
10120
10130
10140
10150
10160
10170
10180
10190
10200
10210
10220
10230
10240
10250
10260
10270
10280
10290
10300
10310
10320
10330
10340
10350
10360
10370
10380
10390
10400
10410
10420
10430
10440
10450
10460
10470
10480
10490
10500
10510
10520
10530
10540
10550
10560
10570
10580
10590
10600
10610
10620
10630
10640
10650
10660
10670
10680
10690
10700
10710
10720
10730
10740
10750
10760
10770
10780
10790
10800
10810
10820
10830
10840
10850
10860
10870
10880
10890
10900
10910
10920
10930
10940
10950
10960
10970
10980
10990
11000
11010
11020
11030
11040
11050
11060
11070
11080
11090
11100
11110
11120
11130
11140
11150
11160
11170
11180
11190
11200
11210
11220
11230
11240
11250
11260
11270
11280
11290
11300
11310
11320
11330
11340
11350
11360
11370
11380
11390
11400
11410
11420
11430
11440
11450
11460
11470
11480
11490
11500
11510
11520
11530
11540
11550
11560
11570
11580
11590
11600
11610
11620
11630
11640
11650
11660
11670
11680
11690
11700
11710
11720
11730
11740
11750
11760
11770
11780
11790
11800
11810
11820
11830
11840
11850
11860
11870
11880
11890
11900
11910
11920
11930
11940
11950
11960
11970
11980
11990
12000
12010
12020
12030
12040
12050
12060
12070
12080
12090
12100
12110
12120
12130
12140
12150
12160
12170
12180
12190
12200
12210
12220
12230
12240
12250
12260
12270
12280
12290
12300
12310
12320
12330
12340
12350
12360
12370
12380
12390
12400
12410
12420
12430
12440
12450
12460
12470
12480
12490
12500
12510
12520
12530
12540
12550
12560
12570
12580
12590
12600
12610
12620
12630
12640
12650
12660
12670
12680
12690
12700
12710
12720
12730
12740
12750
12760
12770
12780
12790
12800
12810
12820
12830
12840
12850
12860
12870
12880
12890
12900
12910
12920
12930
12940
12950
12960
12970
12980
12990
13000
13010
13020
13030
13040
13050
13060
13070
13080
13090
13100
13110
13120
13130
13140
13150
13160
13170
13180
13190
13200
13210
13220
13230
13240
13250
13260
13270
13280
13290
13300
13310
13320
13330
13340
13350
13360
13370
13380
13390
13400
13410
13420
13430
13440
13450
13460
13470
13480
13490
13500
13510
13520
13530
13540
13550
13560
13570
13580
13590
13600
13610
13620
13630
13640
13650
13660
13670
13680
13690
13700
13710
13720
13730
13740
13750
13760
13770
13780
13790
13800
13810
13820
13830
13840
13850
13860
13870
13880
13890
13900
13910
13920
13930
13940
13950
13960
13970
13980
13990
14000
14010
14020
14030
14040
14050
14060
14070
14080
14090
14100
14110
14120
14130
14140
14150
14160
14170
14180
14190
14200
14210
14220
14230
14240
14250
14260
14270
14280
14290
14300
14310
14320
14330
14340
14350
14360
14370
14380
14390
14400
14410
14420
14430
14440
14450
14460
14470
14480
14490
14500
14510
14520
14530
14540
14550
14560
14570
14580
14590
14600
14610
14620
14630
14640
14650
14660
14670
14680
14690
14700
14710
14720
14730
14740
14750
14760
14770
14780
14790
14800
14810
14820
14830
14840
14850
14860
14870
14880
14890
14900
14910
14920
14930
14940
14950
14960
14970
14980
14990
15000
15010
15020
15030
15040
15050
15060
15070
15080
15090
15100
15110
15120
15130
15140
15150
15160
15170
15180
15190
15200
15210
15220
15230
15240
15250
15260
15270
15280
15290
15300
15310
15320
15330
15340
15350
15360
15370
15380
15390
15400
15410
15420
15430
15440
15450
15460
15470
15480
15490
15500
15510
15520
15530
/** 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); } Document parseDiet(alias TR = identity)(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) ]); // 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) ]); 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) ]); 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) ]); assert(parseDiet!tr("|&x").nodes == [ new Node(ln(0), Node.SpecialName.text, null, [NodeContent.text("(X)", ln(0))], NodeAttribs.translated) ]); 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) ]); } 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", "Includes cannot have children."); testFail("p\ninclude inc\n\tp", "Includes cannot have children."); } 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 { // 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); auto 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); } // parse base template return parseDietWithExtensions(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 ~= np; } else if (!ret.isNull) ret ~= 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); enforcep(n.contents.length == 1, "Includes cannot have children.", n.loc); auto fidx = files.countUntil!(f => matchesName(f.name, name, files[file_index].name)); enforcep(fidx >= 0, "Missing include input file: "~name, n.loc); insert(parseDietWithExtensions(files, fidx, blocks, import_stack ~ file_index)); } else { n.contents.modifyArray!((nc) { Nullable!(NodeContent[]) rn; if (nc.kind == NodeContent.Kind.node) { auto mod = processNode(nc.node); if (!mod.isNull()) rn = mod.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.modifyArray!(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 (indent.length) pnode.addText(indent, loc); if (pnode.attribs & NodeAttribs.translated) { size_t idx; Location loccopy = loc; auto ln = TR(skipLine(input, idx, loc)); input = input[idx .. $]; parseTextLine(ln, pnode, loccopy); } else parseTextLine(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; do { input = input[1 .. $]; size_t idx = 0; if (chain.length) chain ~= ' '; chain ~= skipIdent(input, idx, "-_", loc, false, true); input = input[idx .. $]; if (input.startsWith(' ')) input = input[1 .. $]; } while (input.startsWith(':')); Node chn = new Node; chn.loc = loc; chn.name = Node.SpecialName.filter; chn.attribs = NodeAttribs.textNode; chn.attributes = [Attribute(loc, "filterChain", [AttributeContent.text(chain)])]; stack[level] ~= chn; /*auto tmploc = loc; auto trailing = skipLine(input, loc); if (trailing.length) parseTextLine(input, chn, tmploc);*/ parseTextLine(input, chn, loc); } else { // normal tag line bool has_nested; stack[level] = null; do stack[level] ~= parseTagLine!TR(input, loc, has_nested); while (has_nested); } // add it to its parent contents foreach (i; 1 .. stack[level].length) stack[level][i-1].contents ~= NodeContent.tag(stack[level][i]); if (level > 0) stack[level-1][$-1].contents ~= NodeContent.tag(stack[level][0]); else ret ~= stack[0][0]; // remember the nesting level for the next line prevlevel = level; } return ret; } private Node parseTagLine(alias TR)(ref string input, ref Location loc, out bool has_nested) { size_t idx = 0; auto ret = new Node; ret.loc = loc; if (input.startsWith("!!! ")) { // legacy doctype support input = input[4 .. $]; ret.name = "doctype"; parseTextLine(input, ret, loc); return ret; } if (input.startsWith('<')) { // inline HTML/XML ret.name = Node.SpecialName.text; parseTextLine(input, ret, loc); return ret; } if (input.startsWith('|')) { // text line input = input[1 .. $]; ret.name = Node.SpecialName.text; if (idx < input.length && input[idx] == '&') { ret.attribs |= NodeAttribs.translated; idx++; } } else { // normal tag if (parseTag(input, idx, ret, has_nested, loc)) return ret; } if (idx+1 < input.length && input[idx .. idx+2] == "!=") { enforcep(!(ret.attribs & NodeAttribs.translated), "Compile-time translation is not supported for (raw) assignments.", ret.loc); idx += 2; auto l = loc; ret.contents ~= NodeContent.rawInterpolation(ctstrip(skipLine(input, idx, loc)), l); input = input[idx .. $]; } else if (idx < input.length && input[idx] == '=') { enforcep(!(ret.attribs & NodeAttribs.translated), "Compile-time translation is not supported for assignments.", ret.loc); idx++; auto l = loc; ret.contents ~= NodeContent.interpolation(ctstrip(skipLine(input, idx, loc)), l); input = input[idx .. $]; } else { auto tmploc = loc; auto remainder = skipLine(input, idx, loc); input = input[idx .. $]; if (remainder.length && remainder[0] == ' ') { // parse the rest of the line as text contents (if any non-ws) remainder = remainder[1 .. $]; if (ret.attribs & NodeAttribs.translated) remainder = TR(remainder); parseTextLine(remainder, ret, tmploc); } else if (ret.name == Node.SpecialName.text) { // allow omitting the whitespace for "|" text nodes if (ret.attribs & NodeAttribs.translated) remainder = TR(remainder); parseTextLine(remainder, ret, tmploc); } else { import std.string : strip; enforcep(remainder.strip().length == 0, "Expected node text separated by a space character or end of line, but got '"~remainder~"'.", loc); } } return ret; } private bool parseTag(ref string input, ref size_t idx, ref Node dst, ref bool has_nested, ref Location loc) { import std.ascii : isWhite; dst.name = skipIdent(input, idx, ":-_", loc, true); // a trailing ':' is not part of the tag name, but signals a nested node if (dst.name.endsWith(":")) { dst.name = dst.name[0 .. $-1]; idx--; } bool have_id = false; while (idx < input.length) { if (input[idx] == '#') { // node ID idx++; auto value = skipIdent(input, idx, "-_", loc); enforcep(value.length > 0, "Expected id.", loc); enforcep(!have_id, "Only one \"id\" definition using '#' is allowed.", loc); have_id = true; dst.attributes ~= Attribute.text("id", value, loc); } else if (input[idx] == '.') { // node classes if (idx+1 >= input.length || input[idx+1].isWhite) goto textBlock; idx++; auto value = skipIdent(input, idx, "-_", loc); enforcep(value.length > 0, "Expected class name identifier.", loc); dst.attributes ~= Attribute.text("class", value, loc); } else break; } // generic attributes if (idx < input.length && input[idx] == '(') parseAttributes(input, idx, dst, loc); // avoid whitespace inside of tag if (idx < input.length && input[idx] == '<') { idx++; dst.attribs |= NodeAttribs.fitInside; } // avoid whitespace outside of tag if (idx < input.length && input[idx] == '>') { idx++; dst.attribs |= NodeAttribs.fitOutside; } // avoid whitespace inside of tag (also allowed after >) if (!(dst.attribs & NodeAttribs.fitInside) && idx < input.length && input[idx] == '<') { idx++; dst.attribs |= NodeAttribs.fitInside; } // translate text contents if (idx < input.length && input[idx] == '&') { idx++; dst.attribs |= NodeAttribs.translated; } // treat nested lines as text if (idx < input.length && input[idx] == '.') { textBlock: dst.attribs |= NodeAttribs.textNode; idx++; skipLine(input, idx, loc); // ignore the rest of the line input = input[idx .. $]; return true; } // another nested tag on the same line if (idx < input.length && input[idx] == ':') { idx++; // skip trailing whitespace (but no line breaks) while (idx < input.length && (input[idx] == ' ' || input[idx] == '\t')) idx++; // see if we got anything left on the line if (idx < input.length) { if (input[idx] == '\n' || input[idx] == '\r') { // FIXME: should we rather error out here? skipLine(input, idx, loc); } else { // leaves the rest of the line to parse another tag has_nested = true; } } input = input[idx .. $]; return true; } return false; } /** Parses a single line of text (possibly containing interpolations and inline tags). If there a a newline at the end, it will be appended to the contents of the destination node. */ private void parseTextLine(ref string input, ref Node dst, ref Location loc) { import std.algorithm.comparison : among; size_t sidx = 0, idx = 0; void flushText() { if (idx > sidx) dst.addText(input[sidx .. idx], loc); } while (idx < input.length) { char cur = input[idx]; switch (cur) { default: idx++; break; case '\\': if (idx+1 < input.length && input[idx+1].among('#', '!')) { flushText(); sidx = idx+1; idx += 2; } else idx++; break; case '!', '#': if (idx+1 < input.length && input[idx+1] == '{') { flushText(); idx += 2; auto expr = skipUntilClosingBrace(input, idx, loc); idx++; if (cur == '#') dst.contents ~= NodeContent.interpolation(expr, loc); else dst.contents ~= NodeContent.rawInterpolation(expr, loc); sidx = idx; } else if (cur == '#' && idx+1 < input.length && input[idx+1] == '[') { flushText(); idx += 2; auto tag = skipUntilClosingBracket(input, idx, loc); idx++; bool has_nested; auto itag = parseTagLine!identity(tag, loc, has_nested); enforcep(!(itag.attribs & (NodeAttribs.textNode|NodeAttribs.rawTextNode)), "Multi-line text nodes are not permitted for inline-tags.", loc); enforcep(!(itag.attribs & NodeAttribs.translated), "Inline-tags cannot be translated individually.", loc); enforcep(!has_nested, "Nested inline-tags not allowed.", loc); dst.contents ~= NodeContent.tag(itag); sidx = idx; } else idx++; break; case '\r': flushText(); idx++; if (idx < input.length && input[idx] == '\n') idx++; input = input[idx .. $]; loc.line++; return; case '\n': flushText(); idx++; input = input[idx .. $]; loc.line++; return; } } flushText(); assert(idx == input.length); input = null; } private string skipLine(ref string input, ref size_t idx, ref Location loc) { auto sidx = idx; while (idx < input.length) { char cur = input[idx]; switch (cur) { default: idx++; break; case '\r': auto ret = input[sidx .. idx]; idx++; if (idx < input.length && input[idx] == '\n') idx++; loc.line++; return ret; case '\n': auto ret = input[sidx .. idx]; idx++; loc.line++; return ret; } } return input[sidx .. $]; } private string skipLine(ref string input, ref Location loc) { size_t idx = 0; auto ret = skipLine(input, idx, loc); input = input[idx .. $]; return ret; } private void parseAttributes(ref string input, ref size_t i, ref Node node, in ref Location loc) { assert(i < input.length && input[i] == '('); i++; skipAnyWhitespace(input, i); while (i < input.length && input[i] != ')') { string name = parseIdent(input, i, ",)=", loc); string value; skipAnyWhitespace(input, i); if( i < input.length && input[i] == '=' ){ i++; skipAnyWhitespace(input, i); enforcep(i < input.length, "'=' must be followed by attribute string.", loc); value = skipExpression(input, i, loc, true); assert(i <= input.length); if (isStringLiteral(value) && value[0] == '\'') { auto tmp = dstringUnescape(value[1 .. $-1]); value = '"' ~ dstringEscape(tmp) ~ '"'; } } else value = "true"; enforcep(i < input.length, "Unterminated attribute section.", loc); enforcep(input[i] == ')' || input[i] == ',', "Unexpected text following attribute: '"~input[0..i]~"' ('"~input[i..$]~"')", loc); if (input[i] == ',') { i++; skipAnyWhitespace(input, i); } if (name == "class" && value == `""`) continue; if (isStringLiteral(value)) { AttributeContent[] content; parseAttributeText(value[1 .. $-1], content, loc); node.attributes ~= Attribute(loc, name, content); } else { node.attributes ~= Attribute.expr(name, value, loc); } } enforcep(i < input.length, "Missing closing clamp.", loc); i++; } private void parseAttributeText(string input, ref AttributeContent[] dst, in ref Location loc) { size_t sidx = 0, idx = 0; void flushText() { if (idx > sidx) dst ~= AttributeContent.text(input[sidx .. idx]); } while (idx < input.length) { char cur = input[idx]; switch (cur) { default: idx++; break; case '\\': flushText(); dst ~= AttributeContent.text(dstringUnescape(sanitizeEscaping(input[idx .. idx+2]))); idx += 2; sidx = idx; break; case '!', '#': if (idx+1 < input.length && input[idx+1] == '{') { flushText(); idx += 2; auto expr = dstringUnescape(skipUntilClosingBrace(input, idx, loc)); idx++; if (cur == '#') dst ~= AttributeContent.interpolation(expr); else dst ~= AttributeContent.rawInterpolation(expr); sidx = idx; } else idx++; break; } } flushText(); input = input[idx .. $]; } private string skipUntilClosingBrace(in ref string s, ref size_t idx, in ref Location loc) { import std.algorithm.comparison : among; int level = 0; auto start = idx; while( idx < s.length ){ if( s[idx] == '{' ) level++; else if( s[idx] == '}' ) level--; enforcep(!s[idx].among('\n', '\r'), "Missing '}' before end of line.", loc); if( level < 0 ) return s[start .. idx]; idx++; } enforcep(false, "Missing closing brace", loc); assert(false); } private string skipUntilClosingBracket(in ref string s, ref size_t idx, in ref Location loc) { import std.algorithm.comparison : among; int level = 0; auto start = idx; while( idx < s.length ){ if( s[idx] == '[' ) level++; else if( s[idx] == ']' ) level--; enforcep(!s[idx].among('\n', '\r'), "Missing ']' before end of line.", loc); if( level < 0 ) return s[start .. idx]; idx++; } enforcep(false, "Missing closing bracket", loc); assert(false); } private string skipIdent(in ref string s, ref size_t idx, string additional_chars, in ref Location loc, bool accept_empty = false, bool require_alpha_start = false) { import std.ascii : isAlpha; size_t start = idx; while (idx < s.length) { if (isAlpha(s[idx])) idx++; else if ((!require_alpha_start || start != idx) && s[idx] >= '0' && s[idx] <= '9') idx++; else { bool found = false; foreach (ch; additional_chars) if (s[idx] == ch) { found = true; idx++; break; } if (!found) { enforcep(accept_empty || start != idx, "Expected identifier but got '"~s[idx]~"'.", loc); return s[start .. idx]; } } } enforcep(start != idx, "Expected identifier but got nothing.", loc); return s[start .. idx]; } /// Skips all trailing spaces and tab characters of the input string. private string skipIndent(ref string input) { size_t idx = 0; while (idx < input.length && isIndentChar(input[idx])) idx++; auto ret = input[0 .. idx]; input = input[idx .. $]; return ret; } private bool isIndentChar(dchar ch) { return ch == ' ' || ch == '\t'; } private string skipAnyWhitespace(in ref string s, ref size_t idx) { import std.ascii : isWhite; size_t start = idx; while (idx < s.length) { if (s[idx].isWhite) idx++; else break; } return s[start .. idx]; } private bool isStringLiteral(string str) { size_t i = 0; // skip leading white space while (i < str.length && (str[i] == ' ' || str[i] == '\t')) i++; // no string literal inside if (i >= str.length) return false; char delimiter = str[i++]; if (delimiter != '"' && delimiter != '\'') return false; while (i < str.length && str[i] != delimiter) { if (str[i] == '\\') i++; i++; } // unterminated string literal if (i >= str.length) return false; i++; // skip delimiter // skip trailing white space while (i < str.length && (str[i] == ' ' || str[i] == '\t')) i++; // check if the string has ended with the closing delimiter return i == str.length; } unittest { assert(isStringLiteral(`""`)); assert(isStringLiteral(`''`)); assert(isStringLiteral(`"hello"`)); assert(isStringLiteral(`'hello'`)); assert(isStringLiteral(` "hello" `)); assert(isStringLiteral(` 'hello' `)); assert(isStringLiteral(`"hel\"lo"`)); assert(isStringLiteral(`"hel'lo"`)); assert(isStringLiteral(`'hel\'lo'`)); assert(isStringLiteral(`'hel"lo'`)); assert(isStringLiteral(`'#{"address_"~item}'`)); assert(!isStringLiteral(`"hello\`)); assert(!isStringLiteral(`"hello\"`)); assert(!isStringLiteral(`"hello\"`)); assert(!isStringLiteral(`"hello'`)); assert(!isStringLiteral(`'hello"`)); assert(!isStringLiteral(`"hello""world"`)); assert(!isStringLiteral(`"hello" "world"`)); assert(!isStringLiteral(`"hello" world`)); assert(!isStringLiteral(`'hello''world'`)); assert(!isStringLiteral(`'hello' 'world'`)); assert(!isStringLiteral(`'hello' world`)); assert(!isStringLiteral(`"name" value="#{name}"`)); } private string skipExpression(in ref string s, ref size_t idx, in ref Location loc, bool multiline = false) { string clamp_stack; size_t start = idx; outer: while (idx < s.length) { switch (s[idx]) { default: break; case '\n', '\r': enforcep(multiline, "Unexpected end of line.", loc); break; case ',': if (clamp_stack.length == 0) break outer; break; case '"', '\'': idx++; skipAttribString(s, idx, s[idx-1], loc); break; case '(': clamp_stack ~= ')'; break; case '[': clamp_stack ~= ']'; break; case '{': clamp_stack ~= '}'; break; case ')', ']', '}': if (s[idx] == ')' && clamp_stack.length == 0) break outer; enforcep(clamp_stack.length > 0 && clamp_stack[$-1] == s[idx], "Unexpected '"~s[idx]~"'", loc); clamp_stack.length--; break; } idx++; } enforcep(clamp_stack.length == 0, "Expected '"~clamp_stack[$-1]~"' before end of attribute expression.", loc); return ctstrip(s[start .. idx]); } private string skipAttribString(in ref string s, ref size_t idx, char delimiter, in ref Location loc) { size_t start = idx; while( idx < s.length ){ if( s[idx] == '\\' ){ // pass escape character through - will be handled later by buildInterpolatedString idx++; enforcep(idx < s.length, "'\\' must be followed by something (escaped character)!", loc); } else if( s[idx] == delimiter ) break; idx++; } enforcep(idx < s.length, "Unterminated attribute string: "~s[start-1 .. $]~"||", loc); return s[start .. idx]; } private bool matchesName(string filename, string logical_name, string parent_name) { import std.path : extension; if (filename == logical_name) return true; auto ext = extension(parent_name); if (filename.endsWith(ext) && filename[0 .. $-ext.length] == logical_name) return true; return false; } private void modifyArray(alias modify, T)(ref T[] arr) { size_t i = 0; while (i < arr.length) { auto mod = modify(arr[i]); if (mod.isNull()) i++; else { arr = arr[0 .. i] ~ mod.get() ~ arr[i+1 .. $]; i += mod.length; } } }