Debian Codegraph @

test-suite/tests/peg.test

raw
1 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2 ;;;;; PEG test suite.
3 ;; Tests the parsing capabilities of (ice-9 peg). Could use more
4 ;; tests for edge cases.
5 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
6
7 (define-module (test-suite test-peg)
8 :use-module (test-suite lib)
9 :use-module (ice-9 peg)
10 :use-module (ice-9 pretty-print)
11 :use-module (srfi srfi-1))
12
13 ;; Doubled up for pasting into REPL.
14 (use-modules (test-suite lib))
15 (use-modules (ice-9 peg))
16 (use-modules (ice-9 pretty-print))
17 (use-modules (srfi srfi-1))
18
19 ;; Evaluates an expression at the toplevel. Not the prettiest
20 ;; solution to runtime issues ever, but m3h. Runs at toplevel so that
21 ;; symbols are bound globally instead of in the scope of the pass-if
22 ;; expression.
23 (define (eeval exp)
24 (eval exp (interaction-environment)))
25 (define make-prec (@@ (ice-9 peg) make-prec))
26
27 ;; Maps the nonterminals defined in the PEG parser written as a PEG to
28 ;; the nonterminals defined in the PEG parser written with
29 ;; S-expressions.
30 (define grammar-mapping
31 '((Grammar Grammar)
32 (Definition Definition)
33 (Expression Expression)
34 (Sequence Sequence)
35 (Prefix Prefix)
36 (Suffix Suffix)
37 (Primary Primary)
38 (Identifier Identifier)
39 (Literal Literal)
40 (Class Class)
41 (NotInClass NotInClass)
42 (Range Range)
43 (Char Char)
44 (LEFTARROW LEFTARROW)
45 (AND AND)
46 (NOT NOT)
47 (QUESTION QUESTION)
48 (STAR STAR)
49 (PLUS PLUS)
50 (DOT DOT)))
51
52 ;; Transforms the nonterminals defined in the PEG parser written as a PEG to the nonterminals defined in the PEG parser written with S-expressions.
53 (define (grammar-transform x)
54 (let ((res (assoc x grammar-mapping)))
55 (if res (cadr res) x)))
56
57 ;; Maps a function onto a tree (recurses until it finds atoms, then calls the function on the atoms).
58 (define (tree-map fn lst)
59 (if (list? lst)
60 (if (null? lst)
61 lst
62 (cons (tree-map fn (car lst))
63 (tree-map fn (cdr lst))))
64 (fn lst)))
65
66 ;; Tests to make sure that we can parse a PEG defining a grammar for
67 ;; PEGs, then uses that grammar to parse the same PEG again to make
68 ;; sure we get the same result (i.e. make sure our PEG grammar
69 ;; expressed as a PEG is equivalent to our PEG grammar expressed with
70 ;; S-expressions).
71 (with-test-prefix "PEG Grammar"
72 (pass-if
73 "defining PEGs with PEG"
74 (and (eeval `(define-peg-string-patterns ,(@@ (ice-9 peg) peg-as-peg))) #t))
75 (pass-if
76 "equivalence of definitions"
77 (equal?
78 (peg:tree (match-pattern (@@ (ice-9 peg) peg-grammar) (@@ (ice-9 peg) peg-as-peg)))
79 (tree-map
80 grammar-transform
81 (peg:tree (match-pattern Grammar (@@ (ice-9 peg) peg-as-peg)))))))
82
83 ;; A grammar for pascal-style comments from Wikipedia.
84 (define comment-grammar
85 "Begin <-- '(*'
86 End <-- '*)'
87 C <- Begin N* End
88 N <- C / (!Begin !End Z)
89 Z <- .")
90
91 ;; A short /etc/passwd file.
92 (define *etc-passwd*
93 "root:x:0:0:root:/root:/bin/bash
94 daemon:x:1:1:daemon:/usr/sbin:/bin/sh
95 bin:x:2:2:bin:/bin:/bin/sh
96 sys:x:3:3:sys:/dev:/bin/sh
97 nobody:x:65534:65534:nobody:/nonexistent:/bin/sh
98 messagebus:x:103:107::/var/run/dbus:/bin/false
99 ")
100
101 ;; A grammar for parsing /etc/passwd files.
102 (define-peg-string-patterns
103 "passwd <-- entry* !.
104 entry <-- login CO pass CO uid CO gid CO nameORcomment CO homedir CO shell NL*
105 login <-- text
106 pass <-- text
107 uid <-- [0-9]*
108 gid <-- [0-9]*
109 nameORcomment <-- text
110 homedir <-- path
111 shell <-- path
112 path <-- (SLASH pathELEMENT)*
113 pathELEMENT <-- (!NL !CO !'/' .)*
114 text <- (!NL !CO .)*
115 CO < ':'
116 NL < '\n'
117 SLASH < '/'")
118
119 ;; Tests some actual parsing using PEGs.
120 (with-test-prefix "Parsing"
121 (eeval `(define-peg-string-patterns ,comment-grammar))
122 (pass-if
123 ;; Pascal-style comment parsing
124 "simple comment"
125 (equal?
126 (match-pattern C "(*blah*)")
127 (make-prec 0 8 "(*blah*)"
128 '((Begin "(*") "blah" (End "*)")))))
129 (pass-if
130 "simple comment padded"
131 (equal?
132 (match-pattern C "(*blah*)abc")
133 (make-prec 0 8 "(*blah*)abc"
134 '((Begin "(*") "blah" (End "*)")))))
135 (pass-if
136 "nested comment"
137 (equal?
138 (match-pattern C "(*1(*2*)*)")
139 (make-prec 0 10 "(*1(*2*)*)"
140 '((Begin "(*") ("1" ((Begin "(*") "2" (End "*)"))) (End "*)")))))
141 (pass-if
142 "early termination"
143 (not (match-pattern C "(*blah")))
144 (pass-if
145 "never starts"
146 (not (match-pattern C "blah")))
147 ;; /etc/passwd parsing
148 (pass-if
149 "/etc/passwd"
150 (equal?
151 (match-pattern passwd *etc-passwd*)
152 (make-prec 0 220 *etc-passwd*
153 '(passwd (entry (login "root") (pass "x") (uid "0") (gid "0") (nameORcomment "root") (homedir (path (pathELEMENT "root"))) (shell (path (pathELEMENT "bin") (pathELEMENT "bash")))) (entry (login "daemon") (pass "x") (uid "1") (gid "1") (nameORcomment "daemon") (homedir (path (pathELEMENT "usr") (pathELEMENT "sbin"))) (shell (path (pathELEMENT "bin") (pathELEMENT "sh")))) (entry (login "bin") (pass "x") (uid "2") (gid "2") (nameORcomment "bin") (homedir (path (pathELEMENT "bin"))) (shell (path (pathELEMENT "bin") (pathELEMENT "sh")))) (entry (login "sys") (pass "x") (uid "3") (gid "3") (nameORcomment "sys") (homedir (path (pathELEMENT "dev"))) (shell (path (pathELEMENT "bin") (pathELEMENT "sh")))) (entry (login "nobody") (pass "x") (uid "65534") (gid "65534") (nameORcomment "nobody") (homedir (path (pathELEMENT "nonexistent"))) (shell (path (pathELEMENT "bin") (pathELEMENT "sh")))) (entry (login "messagebus") (pass "x") (uid "103") (gid "107") nameORcomment (homedir (path (pathELEMENT "var") (pathELEMENT "run") (pathELEMENT "dbus"))) (shell (path (pathELEMENT "bin") (pathELEMENT "false")))))))))
154
155 ;; Tests the functions for pulling data out of PEG Match Records.
156 (with-test-prefix "PEG Match Records"
157 (define-peg-pattern bs all (peg "'b'+"))
158 (pass-if
159 "basic parameter extraction"
160 (equal?
161 (let ((pm (search-for-pattern bs "aabbcc")))
162 `((string ,(peg:string pm))
163 (start ,(peg:start pm))
164 (end ,(peg:end pm))
165 (substring ,(peg:substring pm))
166 (tree ,(peg:tree pm))
167 (record? ,(peg-record? pm))))
168 '((string "aabbcc")
169 (start 2)
170 (end 4)
171 (substring "bb")
172 (tree (bs "bb"))
173 (record? #t)))))
174
175 ;; PEG for parsing right-associative equations.
176 (define-peg-string-patterns
177 "expr <- sum
178 sum <-- (product ('+' / '-') sum) / product
179 product <-- (value ('*' / '/') product) / value
180 value <-- number / '(' expr ')'
181 number <-- [0-9]+")
182
183 ;; Functions to actually evaluate the equations parsed with the PEG.
184 (define (parse-sum sum left . rest)
185 (if (null? rest)
186 (apply parse-product left)
187 (list (string->symbol (car rest))
188 (apply parse-product left)
189 (apply parse-sum (cadr rest)))))
190
191 (define (parse-product product left . rest)
192 (if (null? rest)
193 (apply parse-value left)
194 (list (string->symbol (car rest))
195 (apply parse-value left)
196 (apply parse-product (cadr rest)))))
197
198 (define (parse-value value first . rest)
199 (if (null? rest)
200 (string->number (cadr first))
201 (apply parse-sum (car rest))))
202
203 (define parse-expr parse-sum)
204 (define (eq-parse str) (apply parse-expr (peg:tree (match-pattern expr str))))
205
206 (with-test-prefix "Parsing right-associative equations"
207 (pass-if
208 "1"
209 (equal? (eq-parse "1") 1))
210 (pass-if
211 "1+2"
212 (equal? (eq-parse "1+2") '(+ 1 2)))
213 (pass-if
214 "1+2+3"
215 (equal? (eq-parse "1+2+3") '(+ 1 (+ 2 3))))
216 (pass-if
217 "1+2*3+4"
218 (equal? (eq-parse "1+2*3+4") '(+ 1 (+ (* 2 3) 4))))
219 (pass-if
220 "1+2/3*(4+5)/6-7-8"
221 (equal? (eq-parse "1+2/3*(4+5)/6-7-8")
222 '(+ 1 (- (/ 2 (* 3 (/ (+ 4 5) 6))) (- 7 8)))))
223 (pass-if
224 "1+1/2*3+(1+1)/2"
225 (equal? (eq-parse "1+1/2*3+(1+1)/2")
226 '(+ 1 (+ (/ 1 (* 2 3)) (/ (+ 1 1) 2))))))
227
228 ;; PEG for parsing left-associative equations (normal ones).
229 (define-peg-string-patterns
230 "expr <- sum
231 sum <-- (product ('+' / '-'))* product
232 product <-- (value ('*' / '/'))* value
233 value <-- number / '(' expr ')'
234 number <-- [0-9]+")
235
236 ;; Functions to actually evaluate the equations parsed with the PEG.
237 (define (make-left-parser next-func)
238 (lambda (sum first . rest)
239 (if (null? rest)
240 (apply next-func first)
241 (if (string? (cadr first))
242 (list (string->symbol (cadr first))
243 (apply next-func (car first))
244 (apply next-func (car rest)))
245 (car
246 (reduce
247 (lambda (l r)
248 (list (list (cadr r) (car r) (apply next-func (car l)))
249 (string->symbol (cadr l))))
250 'ignore
251 (append
252 (list (list (apply next-func (caar first))
253 (string->symbol (cadar first))))
254 (cdr first)
255 (list (append rest '("done"))))))))))
256
257 (define (parse-value value first . rest)
258 (if (null? rest)
259 (string->number (cadr first))
260 (apply parse-sum (car rest))))
261 (define parse-product (make-left-parser parse-value))
262 (define parse-sum (make-left-parser parse-product))
263 (define parse-expr parse-sum)
264 (define (eq-parse str) (apply parse-expr (peg:tree (match-pattern expr str))))
265
266 (with-test-prefix "Parsing left-associative equations"
267 (pass-if
268 "1"
269 (equal? (eq-parse "1") 1))
270 (pass-if
271 "1+2"
272 (equal? (eq-parse "1+2") '(+ 1 2)))
273 (pass-if
274 "1+2+3"
275 (equal? (eq-parse "1+2+3") '(+ (+ 1 2) 3)))
276 (pass-if
277 "1+2*3+4"
278 (equal? (eq-parse "1+2*3+4") '(+ (+ 1 (* 2 3)) 4)))
279 (pass-if
280 "1+2/3*(4+5)/6-7-8"
281 (equal? (eq-parse "1+2/3*(4+5)/6-7-8")
282 '(- (- (+ 1 (/ (* (/ 2 3) (+ 4 5)) 6)) 7) 8)))
283 (pass-if
284 "1+1/2*3+(1+1)/2"
285 (equal? (eq-parse "1+1/2*3+(1+1)/2")
286 '(+ (+ 1 (* (/ 1 2) 3)) (/ (+ 1 1) 2)))))
287
288
289 (define html-grammar
290 "
291 # Based on code from https://github.com/Fantom-Factory/afHtmlParser
292 # 2014-2023 Steve Eynon. This code was originally released under the following
293 # terms:
294 #
295 # Permission to use, copy, modify, and/or distribute this software for any
296 # purpose with or without fee is hereby granted, provided that the above
297 # copyright notice and this permission notice appear in all copies.
298 #
299 # THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL
300 # WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
301 # OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE
302 # FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY
303 # DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
304 # IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
305 # OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
306
307 # PEG Rules for parsing well formed HTML 5 documents
308 # https://html.spec.whatwg.org/multipage/syntax.html
309
310 html <-- bom? blurb* doctype? blurb* xmlProlog? blurb* elem blurb*
311 bom <-- \"\\uFEFF\"
312 xmlProlog <-- \"<?xml\" (!\"?>\" .)+ \"?>\"
313
314 # ---- Doctype ----
315
316 doctype <-- \"<!DOCTYPE\" [ \\t\\n\\f\\r]+ [a-zA-Z0-9]+ (doctypePublicId / doctypeSystemId)* [ \\t\\n\\f\\r]* \">\"
317 doctypePublicId <-- [ \\t\\n\\f\\r]+ \"PUBLIC\" [ \\t\\n\\f\\r]+ ((\"\\\"\" [^\"]* \"\\\"\") / (\"'\" [^']* \"'\"))
318 doctypeSystemId <-- [ \\t\\n\\f\\r]+ (\"SYSTEM\" [ \\t\\n\\f\\r]+)? ((\"\\\"\" [^\"]* \"\\\"\") / (\"'\" [^']* \"'\"))
319
320 # ---- Elems ----
321
322 elem <-- voidElem / rawTextElem / escRawTextElem / selfClosingElem / normalElem
323 voidElem <-- \"<\" voidElemName attributes \">\"
324 rawTextElem <-- \"<\" rawTextElemName attributes \">\" rawTextContent endElem
325 escRawTextElem <-- \"<\" escRawTextElemName attributes \">\" escRawTextContent endElem
326 selfClosingElem <-- \"<\" elemName attributes \"/>\"
327 normalElem <-- \"<\" elemName attributes \">\" normalContent? endElem?
328 endElem <-- \"</\" elemName \">\"
329
330 elemName <-- [a-zA-Z] [^\\t\\n\\f />]*
331 voidElemName <-- \"area\" / \"base\" / \"br\" / \"col\" / \"embed\" /
332 \"hr\" / \"img\" / \"input\" / \"keygen\" / \"link\" /
333 \"meta\" / \"param\" / \"source\" / \"track\" / \"wbr\"
334 rawTextElemName <-- \"script\" / \"style\"
335 escRawTextElemName <-- \"textarea\" / \"title\"
336
337 rawTextContent <-- (!(\"</script>\" / \"</style>\") .)+
338 escRawTextContent <-- ((!(\"</textarea>\" / \"</title>\" / \"&\") .)+ / charRef)*
339 normalContent <-- !\"</\" (([^<&]+ / charRef) / comment / cdata / elem)*
340
341 # ---- Attributes ----
342
343 attributes <-- (&[^/>] ([ \\t]+ / doubleQuoteAttr / singleQuoteAttr / unquotedAttr / emptyAttr))*
344 attrName <-- [^ \\t\\n\\r\\f\"'>/=]+
345 emptyAttr <-- attrName+
346 unquotedAttr <-- attrName [ \\t]* \"=\" [ \\t]* (charRef / [^ \\t\\n\\r\\f\"'=<>`&]+)+
347 singleQuoteAttr <-- attrName [ \\t]* \"=\" [ \\t]* \"'\" (charRef / [^'&]+)* \"'\"
348 doubleQuoteAttr <-- attrName [ \\t]* \"=\" [ \\t]* \"\\\"\" (charRef / [^\"&]+)* \"\\\"\"
349
350 # ---- Character References ----
351
352 charRef <-- &\"&\" (decNumCharRef / hexNumCharRef / namedCharRef / borkedRef)
353 namedCharRef <-- \"&\" [^;>]+ \";\"
354 decNumCharRef <-- \"&#\" [0-9]+ \";\"
355 hexNumCharRef <-- \"&#x\" [a-fA-F0-9]+ \";\"
356 borkedRef <-- \"&\" &[ \\t]
357
358 # ---- Misc ----
359
360 cdata <-- \"<![CDATA[\" (!\"]]>\" .)+ \"]]>\"
361 comment <-- \"<!--\" (!\"--\" .)+ \"-->\"
362 blurb <-- [ \\t\\n\\f\\r]+ / comment")
363
364 (define html-example "
365 <!DOCTYPE html>
366 <html>
367 <head>
368 <title>Example Domain</title>
369 <meta charset=\"utf-8\" />
370 <meta http-equiv=\"Content-type\" content=\"text/html; charset=utf-8\" />
371 <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />
372 <style type=\"text/css\">
373 body {
374 background-color: #f0f0f2;
375 margin: 0;
376 padding: 0;
377 }
378 </style>
379 </head>
380
381 <body>
382 <div>
383 <h1>Example Domain</h1>
384 <p>This domain is for use in illustrative examples in documents. You may
385 use this domain in literature without prior coordination or asking for
386 permission.</p> <p><a href=\"https://www.iana.org/domains/example\">More
387 information...</a></p>
388 </div>
389 </body>
390 </html>
391 ")
392
393 (with-test-prefix "parsing with complex grammars"
394 (eeval `(define-peg-string-patterns ,html-grammar))
395 (pass-if
396 "HTML parsing"
397 (equal?
398 (peg:tree (match-pattern html html-example))
399 '(html (blurb "\n") (doctype "<!DOCTYPE html>") (blurb "\n") (elem (normalElem "<" (elemName "html") attributes ">" (normalContent "\n" (elem (normalElem "<" (elemName "head") attributes ">" (normalContent "\n " (elem (escRawTextElem "<" (escRawTextElemName "title") attributes ">" (escRawTextContent "Example Domain") (endElem "</" (elemName "title") ">"))) "\n " (elem (selfClosingElem "<" (elemName "meta") (attributes " " (doubleQuoteAttr (attrName "charset") "=\"utf-8\"") " ") "/>")) "\n " (elem (selfClosingElem "<" (elemName "meta") (attributes " " (doubleQuoteAttr (attrName "http-equiv") "=\"Content-type\"") " " (doubleQuoteAttr (attrName "content") "=\"text/html; charset=utf-8\"") " ") "/>")) "\n " (elem (selfClosingElem "<" (elemName "meta") (attributes " " (doubleQuoteAttr (attrName "name") "=\"viewport\"") " " (doubleQuoteAttr (attrName "content") "=\"width=device-width, initial-scale=1\"") " ") "/>")) "\n " (elem (rawTextElem "<" (rawTextElemName "style") (attributes " " (doubleQuoteAttr (attrName "type") "=\"text/css\"")) ">" (rawTextContent "\n body {\n background-color: #f0f0f2;\n margin: 0;\n padding: 0;\n }\n ") (endElem "</" (elemName "style") ">"))) "\n") (endElem "</" (elemName "head") ">"))) "\n\n" (elem (normalElem "<" (elemName "body") attributes ">" (normalContent "\n" (elem (normalElem "<" (elemName "div") attributes ">" (normalContent "\n " (elem (normalElem "<" (elemName "h1") attributes ">" (normalContent "Example Domain") (endElem "</" (elemName "h1") ">"))) "\n " (elem (normalElem "<" (elemName "p") attributes ">" (normalContent "This domain is for use in illustrative examples in documents. You may\n use this domain in literature without prior coordination or asking for\n permission.") (endElem "</" (elemName "p") ">"))) " " (elem (normalElem "<" (elemName "p") attributes ">" (normalContent (elem (normalElem "<" (elemName "a") (attributes " " (doubleQuoteAttr (attrName "href") "=\"https://www.iana.org/domains/example\"")) ">" (normalContent "More\n information...") (endElem "</" (elemName "a") ">")))) (endElem "</" (elemName "p") ">"))) "\n") (endElem "</" (elemName "div") ">"))) "\n") (endElem "</" (elemName "body") ">"))) "\n") (endElem "</" (elemName "html") ">"))) (blurb "\n")))))