Source

dram / test / dram / test / parser.clj

Full commit
  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
(ns dram.test.parser
  (:require [dram.parser :as p]
            [dram.test.utils.ast :refer [e b v f i it ct bt]]
            [clojure.test :refer :all]
            [the.parsatron :as tron :refer [run defparser let->> >>]]))


; Extra Utility Parsers -------------------------------------------------------
(defparser complete [p]
  (let->> [r p _ (tron/eof)]
    (tron/always r)))

(defparser any-string []
  (let->> [r (tron/many1 (tron/any-char))]
    (tron/always (apply str r))))


; Convenience Macros ----------------------------------------------------------
(defmacro is-error [input parser]
  `(~'is (~'thrown? RuntimeException (run ~parser ~input))))

(defmacro parses-as [input parser output]
  `(~'is (~'= (run ~parser ~input) ~output)))

(defmacro testing-parser [parser desc & data]
  (let [p (gensym "parser")
        pairs (partition 2 data)]
    `(let [~p (complete ~parser)]
       (~'testing ~desc
          ~@(map (fn [[input output]]
                   `(parses-as ~input ~p ~output))
                 pairs)))))

(defmacro testing-parser-errors [parser desc & data]
  (let [p (gensym "parser")]
    `(let [~p (complete ~parser)]
       (~'testing ~desc
          ~@(map (fn [input]
                   `(is-error ~input ~p))
                 data)))))


; Tests -----------------------------------------------------------------------
(deftest optional-test
  (testing-parser
    (p/optional (p/literal-integer))
    "The optional parser makes another parser optional!"

    "42" 42
    ""  nil))

(deftest separated1-test
  (testing-parser
    (p/separated1 (tron/digit) (tron/char \,))
    "The separated1 parser parses items separated by things."

    "1"     [\1]
    "1,2"   [\1 \2]
    "1,2,3" [\1 \2 \3])

  (testing-parser
    (p/separated1 (p/literal) (tron/char \,))
    "Separated items can be complex."

    "1"                   [1]
    "\"foo\""             ["foo"]
    "42,\"hello, world\"" [42 "hello, world"]
    "19,\"foo\",1"        [19 "foo" 1])

  (testing-parser-errors
    (p/separated1 (p/literal) (tron/char \,))
    "The separated1 parser requires at least one item."

    ""
    ","
    "a")

  (testing-parser-errors
    (p/separated1 (p/literal) (tron/char \,))
    "The separated1 parser doesn't allow garbage."

    "dogs"
    "1,,2"
    "1 2"
    ",1"
    "1,2,3,")

  (testing-parser
    (tron/either
      (p/separated1 (tron/digit) (tron/char \,))
      (tron/char \!))
    "The separated1 parser does not consume input if it fails."

    "1"   [\1]
    "1,2" [\1 \2]
    "!"   \!)

  (testing-parser
    (let->> [a (p/separated1 (tron/digit) (tron/char \,))
             b (tron/char \,)]
      (tron/always [a b]))
    "A more complicated example of input consumption."

    "1,2," [[\1 \2] \,]
    "1,"   [[\1] \,]))

(deftest separated-test
  (testing-parser
    (p/separated (tron/digit) (tron/char \,))
    "The separated parser is like separated1, but allows zero-length seqs."

    "1"     [\1]
    "1,2"   [\1 \2]
    ""      [])

  (testing-parser
    (p/separated (p/literal) (tron/char \,))
    "Separated items can be complex."

    "1"                   [1]
    "\"foo\""             ["foo"]
    "42,\"hello, world\"" [42 "hello, world"]
    "19,\"foo\",1"        [19 "foo" 1])

  (testing-parser-errors
    (p/separated (p/literal) (tron/char \,))
    "The separated parser doesn't allow garbage."

    "dogs"
    "1,,2"
    "1 2"
    ",1"
    "1,2,3,")

  (testing-parser
    (>>
      (p/separated (tron/digit) (tron/char \,))
      (tron/char \!))
    "The separated parser does not consume input if it fails."

    "1!"   \!
    "1,2!" \!
    "!"    \!)

  (testing-parser
    (let->> [a (p/separated (tron/digit) (tron/char \,))
             b (tron/char \,)]
      (tron/always [a b]))
    "A more complicated example of input consumption."

    "1,2," [[\1 \2] \,]
    "1,"   [[\1] \,]
    ","    [[] \,]))

(deftest whitespace-test
  (testing-parser
    (p/optional-whitespace) "Optional whitespace parses to nil."

    ""       nil
    " "      nil
    "     "  nil
    "\t"     nil
    "\n"     nil
    "\n \t " nil)

  (testing-parser
    (>> (p/optional-whitespace) (p/literal))
    "Optional whitespace doesn't consume input on failure."

    "  1" 1
    "1"   1)

  (testing-parser
    (p/required-whitespace) "Required whitespace parses to nil."

    " "      nil
    "     "  nil
    "\t"     nil
    "\n"     nil
    "\n \t " nil)

  (testing-parser-errors
    (p/required-whitespace) "Required whitespace is actually required."

    ""
    "foo")

  (testing-parser
    (tron/either (p/required-whitespace) (p/literal))
    "Required whitespace can't consume input on failure."

    "1" 1))

(deftest integer-test
  (testing-parser
    (p/literal-integer) "Parsing integers results in Clojure integers."

    "1"    1
    "10"   10
    "9234" 9234)

  (testing-parser
    (p/literal-integer) "Parsing negative integers results in integers too."

    "-1"    -1
    "-2945" -2945)

  (testing-parser-errors
    (p/literal-integer) "Parsing garbage with the integer parser fails."

    ""
    " 1"
    "foo"
    "-"
    "--1"
    " -1"
    "- 1"
    "-a12")

  (testing-parser
    (tron/either (p/literal-integer) (any-string))
    "Parsing integers does not consume data on failure."

    "-1"  -1
    "--1" "--1"
    "c4t" "c4t"))

(deftest string-test
  (testing-parser
    (p/literal-string)
    "Literal strings of simple characters parse to Clojure strings."

    "\"\""      ""
    "\"foo\""   "foo"
    "\" bar \"" " bar ")

  (testing-parser
    (p/literal-string)
    "Escape sequences are supported in strings."

    "\"a\\nb\""   "a\nb"
    "\"a\\\\b\""  "a\\b"
    "\"a\\\\nb\"" "a\\nb"
    "\"a\\\"b\""  "a\"b")

  (testing-parser-errors
    (p/literal-string)
    "Garbage doesn't parse as strings."

    "foo"
    "\"foo"
    "foo\""
    "fo\"o")

  (testing-parser
    (tron/either (p/literal-string) (any-string))
    "Strings don't consume input on failure."

    "aaa"   "aaa"
    "\"a"   "\"a"))

(deftest literal-test
  (testing-parser
    (p/literal) "Literals can parse integers."

    "-42" -42
    "585" 585)

  (testing-parser
    (p/literal) "Literals can parse strings."

    "\"foo\"" "foo")

  (testing-parser
    (tron/either (p/literal) (any-string))
    "Literals don't consume input on failure."

    "-cats" "-cats"
    "--1"   "--1"
    "\"foo" "\"foo"))

(deftest value-test
  (testing-parser
    (p/value)
    "A context value's base can be a path or a literal."

    "42"         (v 42)
    "\"foo\""    (v "foo")
    "user.email" (v ["user" "email"])
    "users.0"    (v ["users" "0"]))

  (testing-parser
    (p/value)
    "A context value can be filtered through one or more filters."

    "42|abs"        (v 42 [(f ["abs"])])
    "42|math.floor" (v 42 [(f ["math" "floor"])])

    "\"foo\"|reverse|upper"
    (v "foo" [(f ["reverse"])
              (f ["upper"])])

    "\"foo\"|reverse|upper|custom.dogs"
    (v "foo" [(f ["reverse"])
              (f ["upper"])
              (f ["custom" "dogs"])]))

  (testing-parser
    (p/value)
    "Filters can take arguments."

    "total|add:extra.widgets"
    (v ["total"] [(f ["add"] [["extra" "widgets"]])])

    "description|trim:10"
    (v ["description"] [(f ["trim"] [10])])

    "description|slice:0,30"
    (v ["description"] [(f ["slice"] [0 30])])

    "user.join-date|date:\"yyyy-mm\",\"est\""
    (v ["user" "join-date"] [(f ["date"] ["yyyy-mm" "est"])])

    "number_of_cats|pluralize:\"y,ies\""
    (v ["number_of_cats"] [(f ["pluralize"] ["y,ies"])])

    "foo|join:\",\"|strip:\" ,.{}\"|slice:20,30,2|length"
    (v ["foo"] [(f ["join"] [","])
                (f ["strip"] [" ,.{}"])
                (f ["slice"] [20 30 2])
                (f ["length"])])))

(deftest variable-test
  (testing-parser
    (p/variable) "Variables can be simple literals."

    "{{ 42 }}"      (v 42)
    "{{ -2 }}"      (v -2)
    "{{ \"foo\" }}" (v "foo"))

  (testing-parser
    (p/variable)
    "Variables can be values."

    "{{ dogs }}"          (v ["dogs"])
    "{{ user|is_admin }}" (v ["user"] [(f ["is_admin"])])

    "{{ \"sjl\"|is_admin }}"
    (v "sjl" [(f ["is_admin"])])

    "{{ user.username|slice:2,4 }}"
    (v ["user" "username"] [(f ["slice"] [2 4])])

    "{{ a|horrible:\"{{thing}}\" }}"
    (v ["a"] [(f ["horrible"] ["{{thing}}"])]))

  (testing-parser
    (p/variable) "Variables can handle wonky whitespace."

    "{{42}}"         (v 42)
    "{{ 42}}"        (v 42)
    "{{42 }}"        (v 42)
    "{{42  }}"       (v 42)
    "{{\n\t\n\t42}}" (v 42))

  )

(deftest extends-test
  (testing-parser
    (p/tag-extends)
    "{% extends ... %} parses to its own custom AST element."

    "{% extends \"p\" %}"       (e "p")
    "{% extends \"foo/bar\" %}" (e "foo/bar"))

  (testing-parser
    (p/tag-extends)
    "{% extends ... %} can take weird whitespace."

    "{%extends \"foo\"%}"          (e "foo")
    "{% extends \"foo\"%}"         (e "foo")
    "{%extends \"foo\" %}"         (e "foo")
    "{%\n  \n\textends\n\"foo\"%}" (e "foo"))

  (testing-parser-errors
    (p/tag-extends)
    "{% extends ... %} requires a non-empty argument."

    "{% extends \"\" %}"
    "{% extends %}")

  (testing-parser-errors
    (p/tag-extends)
    "{% extends ... %} doesn't accept garbage."

    "{% extends\"foo\" %}"
    "{% extends foo %}"
    "{% extends \"foo\" foo %}"
    "{% extends foo \"foo\" %}"
    "{% extends foo\"foo\" %}"
    "{% extends 43 %}"
    "{% extends foo/bar %}"
    "{% extends the quick brown fox %}"))

(deftest block-test
  (testing-parser
    (p/tag-block-open)
    "{% block ... %} parses to an intermediate AST element."

    "{% block cats %}"            {:name "cats"}
    "{% block boots-and-cats %}"  {:name "boots-and-cats"}
    "{% block hello-world_585 %}" {:name "hello-world_585"}
    "{% block a %}"               {:name "a"}
    "{% block a_ %}"              {:name "a_"})

  (testing-parser-errors
    (p/tag-block-open)
    "{% block ... %} requires valid block names."

    "{% block 1 %}"
    "{% block -1 %}"
    "{% block -foo %}"
    "{% block __foo %}"
    "{% block 12dogs %}"
    "{% block c&ats %}"
    "{% block boots and cats %}"
    "{% block \"rochester-made\" %}"
    "{% block dogs* %}"
    "{% block dogs% %}"
    "{% block dogs} %}")

  (testing-parser
    (p/tag-block-open)
    "{% block ... %} allows wonky whitespace."

    "{%block foo%}"           {:name "foo"}
    "{%   block foo%}"        {:name "foo"}
    "{%block      foo     %}" {:name "foo"}
    "{%\n\nblock\tfoo\n%}"    {:name "foo"})

  (testing-parser-errors
    (p/tag-block-open)
    "{% block ... %} REQUIRES whitespace between block and the name."

    "{% blockfoo %}")

  (testing-parser
    (p/tag-block-close)
    "{% endblock %} parses to nil and allows weird whitespace."

    "{% endblock %}"   nil
    "{%\nendblock\t%}" nil
    "{%endblock %}"    nil
    "{% endblock%}"    nil)

  (testing-parser-errors
    (p/tag-block-close)
    "{% endblock %} does NOT take a block name (for now)."

    "{% endblock foo %}")

  (testing-parser
    (p/tag-block)
    "Empty blocks are totally fine."

    "{% block foo %}{% endblock %}" (b "foo"))

  (testing-parser
    (p/tag-block)
    "Blocks can contain anything except other blocks."

    "{% block foo %}hi{% endblock %}"
    (b "foo" ["hi"])

    "{% block foo %}hi {{ 1 }} five{% endblock %}"
    (b "foo" ["hi " (v 1) " five"])

    "{% block foo %}
    {{ user.name|capitalize|trim:10 }}
    {% endblock %}"
    (b "foo" ["\n    "
              (v ["user" "name"] [(f ["capitalize"])
                                  (f ["trim"] [10])])
              "\n    "])))

(deftest raw-text-test
  (testing-parser
    (p/raw-text) "Raw text parses to a vanilla Clojure string."

    "Hello"             "Hello"
    "hello there world" "hello there world"
    "  { foo } is okay" "  { foo } is okay"
    "so is { % foo % }" "so is { % foo % }")

  (testing-parser-errors
    (p/raw-text) "Reserved characters do not parse as raw text."

    "Hello{{ world }}"
    "Hello{% block world %}"
    "Hello{% there"
    "Hello{{world")

  (testing-parser-errors
    (p/raw-text) "Raw text is not zero-length."

    "{{ world }}"
    ""))

(deftest path-test
  (testing-parser
    (p/path) "A path parses to a seq of strings."

    "hello"             ["hello"]
    "hello.world"       ["hello" "world"]
    "users.0"           ["users" "0"]
    "users.0.full-name" ["users" "0" "full-name"]
    "0"                 ["0"]
    "user.full_name"    ["user" "full_name"])

  (testing-parser-errors
    (p/path) "A path can't parse garbage."

    "/foo"
    "foo/"
    ".a"
    "..a"
    "a..b"
    "a$b"
    "a,b"
    "a b"
    "a."
    "a.b."
    ":"
    ":::")

  (testing-parser-errors
    (p/path) "A path can't contain keyword-style args (for now)."

    ":foo"
    "foo.:bar"))


(deftest template-tag-arguments
  (testing-parser
    (p/ttag-generic-arg)
    "Template tag arguments are usually left to the tags to parse/handle."

    "foo"     "foo"
    "foo.bar" "foo.bar"
    "<="      "<="
    "1234"    "1234"
    "foo,bar" "foo,bar"
    "{dogs}"  "{dogs}"
    "'lisp"   "'lisp")

  (testing-parser
    (p/ttag-arg)
    "Template tag arguments special case strings though."

    "\"foo\""            {:string "foo"}
    "\"a \\\"b\\\" c\""  {:string "a \"b\" c"}
    "\"boots and cats\"" {:string "boots and cats"}
    "\"{% okay %}\""     {:string "{% okay %}"})

  (testing-parser-errors
    (>>
      (p/ttag-arg)
      (tron/eof))
    "Non-string tag arguments can't contain whitespace, quotes, or end chars."

    "foo\"bar"
    "foo bar"
    "f%}oo"))

(deftest template-tag-innards
  (testing-parser
    (p/ttag-innards)
    "Template tag innards are made of a required path and optional arguments."

    "foo"         (i ["foo"])
    "foo bar"     (i ["foo"] ["bar"])
    "foo cats 10" (i ["foo"] ["cats" "10"])
    "if  x <  10" (i ["if"] ["x" "<" "10"])

    "if username == \"sjl\""
    (i ["if"] ["username" "==" {:string "sjl"}])

    "this \"{{ is }}\" \"{%horrible%}\""
    (i ["this"] [{:string "{{ is }}"}
                 {:string "{%horrible%}"}])))

(deftest template-tag-inline
  (testing-parser
    (p/ttag-inline)
    "Inline template tags stand alone, require a path, and have optional args."

    "{% test %}"             (it ["test"])
    "{%test%}"               (it ["test"])
    "{% forms.csrf_token %}" (it ["forms" "csrf_token"])
    "{% messages user %}"    (it ["messages"] ["user"])

    "{% if x < 20
    and user.username == \"sjl\"
    and request.user|is_admin %}"
    (it ["if"] ["x" "<" "20"
                "and" "user.username" "==" {:string "sjl"}
                "and" "request.user|is_admin"])

    "{% very.fun \"{% tag %}\" %}"
    (it ["very" "fun"] [{:string "{% tag %}"}]))

  (testing-parser
    (p/ttag-inline)
    "Inline template tags can contain not-quite-reserved words."

    "{% blocked %}"      (it ["blocked"])
    "{% block.test %}"   (it ["block" "test"])
    "{% extends-with %}" (it ["extends-with"]))

  (testing-parser-errors
    (p/ttag-inline)
    "Inline template tags must start with a valid tag name."

    "{%"
    "%}"
    "{%%}"
    "{% %}"
    "{% >> %}"
    "{% ] %}"
    "{% { %}"
    "{% ,dogs %}"
    "{% .dogs %}"
    "{% \"if\" %}"
    "{% 'lisp %}"
    "{% :keywords-are-not-valid-path-names-for-now %}"
    "{% extends %}"
    "{% extends 1 %}"
    "{% block %}"
    "{% block. %}"
    "{% endblock %}"
    "{% end.block %}"
    "{% endif %}"
    "{% end %}"
    "{% load %}"
    "{% load \"foo\" %}"))


(deftest template-chunk-test
  (testing-parser
    (p/template-chunk) "A template chunk can be raw text."

    "Hello"     "Hello"
    "  { foo }" "  { foo }"
    "..\"q\".." "..\"q\"..")

  (testing-parser
    (p/template-chunk) "A template chunk can be a variable."

    "{{ 1 }}"                 (v 1)
    "{{ \"sjl\"|uppercase }}" (v "sjl" [(f ["uppercase"])])
    "{{ cats.avy }}"          (v ["cats" "avy"])
    "{{ cats|names:10 }}"     (v ["cats"] [(f ["names"] [10])]))

  (testing-parser
    (p/template-chunk) "A template chunk can be an inline tag."

    "{% a %}"       (it ["a"])
    "{% a.b %}"     (it ["a" "b"])
    "{% a.b foo %}" (it ["a" "b"] ["foo"])

    "{% show-form-unless x < 10 or username == \"sjl\" %}"
    (it ["show-form-unless"] ["x" "<" "10" "or" "username" "=="
                              {:string "sjl"}]))

  (testing-parser-errors
    (p/template-chunk) "A template chunk cannot be zero-length."

    ""))

(deftest template-base-test
  (testing-parser
    (p/template-base)
    "A base template can be made up of a series of chunks."

    ""                        (bt [])
    "Hello"                   (bt ["Hello"])
    "Hello {{ \"Steve\" }}"   (bt ["Hello " (v "Steve")])
    "Age: {{ 27 }} years old" (bt ["Age: " (v 27) " years old"])

    "Hello {% get-name %}!"
    (bt ["Hello " (it ["get-name"]) "!"])

    "{% greeting %}{{ user.name }}!"
    (bt [(it ["greeting"]) (v ["user" "name"]) "!"]))

  (testing-parser
    (p/template-base)
    "A base template can contain blocks."

    "{% block foo %}{% endblock %}"
    (bt [(b "foo")])

    "hello {% block username %}{% endblock %}"
    (bt ["hello "
         (b "username")])

    "hello {% block username %}{% endblock %}! {% block rest %}{% endblock %}"
    (bt ["hello "
         (b "username")
         "! "
         (b "rest")])

    "foo {% block a %}{% endblock %} bar {{ 42 }}"
    (bt ["foo "
         (b "a")
         " bar "
         (v 42)])))

(deftest template-child-test
  (testing-parser
    (p/template-child)
    "A child template requires an extends tag."

    "{% extends \"a\" %}"     (ct "a")
    "  {% extends \"a\" %}"   (ct "a")
    "{% extends \"a\" %}\n\n" (ct "a"))

  (testing-parser
    (p/template-child)
    "A child template may contain blocks to override."

    "
    {% extends \"a\" %}
    {% block foo %}{% endblock %}
    "
    (ct "a" {"foo" []})

    "
    {% extends \"a\" %}
    {% block foo %}hello world{% endblock %}
    {% block bar %}{{ 10 }}{% endblock %}
    "
    (ct "a" {"foo" ["hello world"]
             "bar" [(v 10)]})))