├── tests ├── peg-syntax │ ├── peg-example-n.rkt │ ├── peg-example-empty.rkt │ ├── peg-example-false-action.rkt │ ├── peg-example-float.rkt │ ├── peg-example-bake.rkt │ ├── peg-example-comma-separated-number.rkt │ ├── peg-example-import.rkt │ ├── peg-example-named-pattern.rkt │ ├── peg-example-expr.rkt │ ├── peg-example-positive-lookahead.rkt │ ├── peg-example-bracket-expand.rkt │ ├── peg-example-canopy.rkt │ ├── peg-example-guile-passwd.rkt │ ├── peg-example-guile-cfunc.rkt │ ├── peg-example-newick.rkt │ ├── peg-example-peg-in-peg-comments.rkt │ ├── peg-example-antlr-query-language.rkt │ ├── peg-example-peg-as-peg.rkt │ ├── peg-example-imp.rkt │ ├── peg-example-quests.rkt │ └── peg-example-shell.rkt ├── peg-syntax-harness │ ├── peg-test-false-action.rkt │ ├── test-named-pattern.rkt │ ├── test-bake.rkt │ ├── test-comma-separated-number.rkt │ ├── test-import.rkt │ ├── peg-test-positive-lookahead.rkt │ ├── peg-test-antlr-query-language.rkt │ ├── peg-test-canopy.rkt │ ├── peg-test-guile-cfunc.rkt │ ├── test-newick.rkt │ ├── peg-test-expr.rkt │ ├── peg-test-peg-in-peg-comments.rkt │ ├── test-imp.rkt │ ├── peg-test-guile-passwd.rkt │ └── peg-test-peg-as-peg.rkt ├── test-bracket-expand.rkt ├── s-exp │ ├── test-numbers.rkt │ ├── test-chars.rkt │ ├── test-dotted-pair.rkt │ └── tests.rkt ├── test-shell.rkt ├── test-unicode.rkt ├── docs-example-1.rkt ├── test-quests.rkt ├── test-palindrome.rkt ├── docs-example-2.rkt ├── list-monad.rkt ├── test-regex-range.rkt ├── docs-example-3.rkt ├── test-blg.rkt ├── test-verbose.rkt ├── test-multibrack.rkt ├── test-cfunc.rkt ├── test-tiny.rkt ├── test-etc-passwd.rkt └── test-json.rkt ├── .gitignore ├── info.rkt ├── push-pop-boxes.rkt ├── make ├── main.rkt ├── peg-src ├── peg-in-peg.peg └── s-exp.peg ├── README.md ├── peg-in-peg.rkt ├── s-exp.rkt ├── IMPLEMENTATION.md ├── peg-result.rkt ├── peg-to-scheme.rkt ├── scribblings └── peg.scrbl ├── peg.rkt └── LICENSE /tests/peg-syntax/peg-example-n.rkt: -------------------------------------------------------------------------------- 1 | #lang peg 2 | 3 | foo <- 'foo' [n] ; 4 | -------------------------------------------------------------------------------- /tests/peg-syntax/peg-example-empty.rkt: -------------------------------------------------------------------------------- 1 | #lang peg 2 | 3 | foo <- '' 'foo' ; 4 | -------------------------------------------------------------------------------- /tests/peg-syntax/peg-example-false-action.rkt: -------------------------------------------------------------------------------- 1 | #lang peg 2 | 3 | a <- 'a' -> #f ; 4 | -------------------------------------------------------------------------------- /tests/peg-syntax/peg-example-float.rkt: -------------------------------------------------------------------------------- 1 | #lang peg 2 | 3 | float <-- '-'? [0-9]+ ('.' [0-9]+)? ; 4 | -------------------------------------------------------------------------------- /tests/peg-syntax/peg-example-bake.rkt: -------------------------------------------------------------------------------- 1 | #lang peg 2 | 3 | number <--- [0-9]+; 4 | sum <--- number '+' number; 5 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *~ 2 | compiled/* 3 | */compiled/* 4 | doc/* 5 | *.zo 6 | *.dep 7 | *.html 8 | *.js 9 | *.css 10 | -------------------------------------------------------------------------------- /tests/peg-syntax/peg-example-comma-separated-number.rkt: -------------------------------------------------------------------------------- 1 | #lang peg 2 | 3 | number <-- [0-9]+ ; 4 | file <-- number (~',' number)* ; 5 | -------------------------------------------------------------------------------- /tests/peg-syntax/peg-example-import.rkt: -------------------------------------------------------------------------------- 1 | #lang peg 2 | 3 | (require "peg-example-expr.rkt") ; 4 | 5 | presentation <-- 'this is a well formed expr ' expr ; 6 | -------------------------------------------------------------------------------- /tests/peg-syntax/peg-example-named-pattern.rkt: -------------------------------------------------------------------------------- 1 | #lang peg 2 | 3 | number <- value:[0-9]+ -> (string->number value); 4 | sum <- v1:number ~'+' v2:number -> `(+ ,v1 ,v2); 5 | -------------------------------------------------------------------------------- /tests/peg-syntax-harness/peg-test-false-action.rkt: -------------------------------------------------------------------------------- 1 | 2 | #lang racket 3 | 4 | (require rackunit) 5 | (require peg) 6 | 7 | (require "../peg-syntax/peg-example-false-action.rkt") 8 | 9 | (check-equal? (peg a "a") #f) 10 | 11 | -------------------------------------------------------------------------------- /tests/peg-syntax/peg-example-expr.rkt: -------------------------------------------------------------------------------- 1 | #lang peg 2 | expr <- sum ; 3 | sum <-- (product ('+' / '-') sum) / product ; 4 | product <-- (value ('*' / '/') product) / value ; 5 | value <-- number / '(' expr ')' ; 6 | number <-- [0-9]+ ; 7 | -------------------------------------------------------------------------------- /tests/peg-syntax-harness/test-named-pattern.rkt: -------------------------------------------------------------------------------- 1 | #lang racket 2 | 3 | (require peg) 4 | (require rackunit) 5 | 6 | (require "../peg-syntax/peg-example-named-pattern.rkt") 7 | 8 | (check-equal? 9 | (peg sum "123+12") 10 | '(+ 123 12)) 11 | -------------------------------------------------------------------------------- /tests/test-bracket-expand.rkt: -------------------------------------------------------------------------------- 1 | #lang racket 2 | 3 | (require rackunit) 4 | (require peg) 5 | (require "peg-syntax/peg-example-bracket-expand.rkt") 6 | 7 | (check-equal? (peg items "a{x{0,1},w}b") 8 | '("ax0b" "ax1b" "awb")) 9 | 10 | 11 | -------------------------------------------------------------------------------- /tests/peg-syntax/peg-example-positive-lookahead.rkt: -------------------------------------------------------------------------------- 1 | #lang peg 2 | 3 | bncn <-- ('b' 'c') / ('b' bncn 'c') ; 4 | anbn <-- ('a' 'b') / ('a' anbn 'b') ; 5 | 6 | equal-b-c <-- 'a'+ bncn ; 7 | equal-a-b <-- anbn 'c'+ ; 8 | 9 | anbncn <-- (& equal-b-c) equal-a-b ; 10 | -------------------------------------------------------------------------------- /tests/peg-syntax-harness/test-bake.rkt: -------------------------------------------------------------------------------- 1 | #lang racket 2 | 3 | (require rackunit) 4 | (require peg) 5 | (require "../peg-syntax/peg-example-bake.rkt") 6 | 7 | (check-equal? 8 | (peg number "123") 9 | "123") 10 | 11 | (check-equal? 12 | (peg sum "12+45") 13 | '("12" "+" "45")) 14 | -------------------------------------------------------------------------------- /tests/peg-syntax/peg-example-bracket-expand.rkt: -------------------------------------------------------------------------------- 1 | #lang peg 2 | 3 | (require "../list-monad.rkt"); 4 | 5 | text <- str:[^{},]+ -> (list str); 6 | items <- xs:(text / choice)+ -> (map string-concatenate (sequence xs)); 7 | choice <- '{' x:items xs:(~',' items)* '}' -> (concatenate (cons x xs)); 8 | -------------------------------------------------------------------------------- /info.rkt: -------------------------------------------------------------------------------- 1 | #lang info 2 | (define version "0.3") 3 | (define collection "peg") 4 | (define deps '("base" "rackunit-lib")) 5 | (define build-deps '("scribble-lib" "racket-doc")) 6 | (define scribblings '(("scribblings/peg.scrbl" ()))) 7 | (define compile-omit-paths '("peg-src")) 8 | (define pkg-desc "A PEG parser generator") 9 | -------------------------------------------------------------------------------- /tests/peg-syntax-harness/test-comma-separated-number.rkt: -------------------------------------------------------------------------------- 1 | #lang racket 2 | 3 | (require peg) 4 | (require rackunit) 5 | (require "../peg-syntax/peg-example-comma-separated-number.rkt") 6 | 7 | (check-equal? (peg file "123,12,10,21") 8 | '(file (number . "123") (number . "12") (number . "10") (number . "21"))) 9 | -------------------------------------------------------------------------------- /push-pop-boxes.rkt: -------------------------------------------------------------------------------- 1 | #lang racket 2 | 3 | (provide push! pop!) 4 | 5 | ;;;; 6 | ;; push and pop for boxes 7 | 8 | (define-syntax-rule (push! place thing) 9 | (set-box! place (cons thing (unbox place)))) 10 | 11 | (define-syntax-rule (pop! place) 12 | (let ((top (car (unbox place)))) 13 | (set-box! place (cdr (unbox place))) 14 | top)) 15 | -------------------------------------------------------------------------------- /tests/s-exp/test-numbers.rkt: -------------------------------------------------------------------------------- 1 | #lang racket 2 | 3 | (require rackunit) 4 | (require peg) 5 | (require peg/s-exp) 6 | 7 | (check-equal? 8 | (peg s-exp "10e4") 9 | 10e4) 10 | 11 | (check-equal? 12 | (peg s-exp "(1 2 10.5e2)") 13 | '(1 2 10.5e2)) 14 | 15 | (check-equal? 16 | (peg s-exp "(1 2 -10.4e2 0 #\\z)") 17 | '(1 2 -10.4e2 0 #\z)) 18 | -------------------------------------------------------------------------------- /tests/test-shell.rkt: -------------------------------------------------------------------------------- 1 | #lang racket 2 | 3 | (require rackunit) 4 | (require peg) 5 | (require "peg-syntax/peg-example-shell.rkt") 6 | 7 | (check-equal? (peg top-shell "ls -l hello | less") (list (pipe-struct (ls-struct "-l" (dir-or-file "hello")) (less-struct '())))) 8 | 9 | (check-equal? (peg top-shell "echo hello world") (list (echo-struct "hello world"))) 10 | -------------------------------------------------------------------------------- /tests/peg-syntax-harness/test-import.rkt: -------------------------------------------------------------------------------- 1 | #lang racket 2 | 3 | (require rackunit) 4 | (require peg) 5 | (require "../peg-syntax/peg-example-import.rkt") 6 | 7 | (check-equal? 8 | (peg presentation "this is a well formed expr 4324+431") 9 | '(presentation "this is a well formed expr " (sum (product value number . "4324") "+" (sum product value number . "431")))) 10 | -------------------------------------------------------------------------------- /tests/peg-syntax/peg-example-canopy.rkt: -------------------------------------------------------------------------------- 1 | #lang peg 2 | 3 | url <-- scheme '://' host pathname search hash? ; 4 | scheme <-- 'http' 's'? ; 5 | host <-- hostname port? ; 6 | hostname <-- segment ('.' segment)* ; 7 | segment <-- [a-z0-9\-]+ ; 8 | port <-- ':' [0-9]+ ; 9 | pathname <-- '/' [^ ?]* ; 10 | search <-- ('?' [^ #]*)? ; 11 | hash <-- '#' [^ ]* ; 12 | -------------------------------------------------------------------------------- /tests/test-unicode.rkt: -------------------------------------------------------------------------------- 1 | #lang racket 2 | 3 | (require rackunit) 4 | 5 | (require peg) 6 | 7 | (define-peg u-chr (char #\λ)) 8 | (check-equal? (peg u-chr "λ") 9 | "λ") 10 | (check-equal? (peg (any-char) "λ") 11 | "λ") 12 | 13 | (check-equal? (peg (* (range #\ぁ #\ゖ)) "こんにちはhello") 14 | "こんにちは") 15 | 16 | (check-equal? (peg (string "こんにちは") "こんにちはhello") 17 | "こんにちは") 18 | -------------------------------------------------------------------------------- /tests/peg-syntax-harness/peg-test-positive-lookahead.rkt: -------------------------------------------------------------------------------- 1 | #lang racket 2 | 3 | (require peg) 4 | (require rackunit) 5 | 6 | (require "../peg-syntax/peg-example-positive-lookahead.rkt") 7 | 8 | (check-equal? (peg anbncn "aaabbbccc") 9 | '(anbncn (equal-a-b (anbn "a" (anbn "a" (anbn . "ab") "b") "b") "ccc"))) 10 | 11 | (check-equal? (peg anbncn "abc") 12 | '(anbncn (equal-a-b (anbn . "ab") "c"))) 13 | 14 | -------------------------------------------------------------------------------- /tests/peg-syntax-harness/peg-test-antlr-query-language.rkt: -------------------------------------------------------------------------------- 1 | #lang racket 2 | 3 | (require rackunit) 4 | (require peg) 5 | 6 | (require "../peg-syntax/peg-example-antlr-query-language.rkt") 7 | 8 | (check-equal? (peg expression "location within 10 km from (-37.814, 144.963) and status.stateOfCharge < 10%") 9 | '(predicate "location within " (amount (float . "10") " km ") "from " (location (float . "-37.814") (float . "144.963")))) 10 | -------------------------------------------------------------------------------- /tests/docs-example-1.rkt: -------------------------------------------------------------------------------- 1 | #lang racket 2 | 3 | (require peg) 4 | (require rackunit) 5 | 6 | (define *sentence* "the quick brown fox jumps over the lazy dog") 7 | 8 | (define-peg non-space 9 | (and (! #\space) (any-char))) 10 | 11 | (define-peg/bake word 12 | (and (+ non-space) 13 | (drop (? #\space)))) 14 | 15 | (check-equal? (peg (+ word) *sentence*) 16 | '("the" "quick" "brown" "fox" "jumps" "over" "the" "lazy" "dog")) 17 | 18 | -------------------------------------------------------------------------------- /tests/test-quests.rkt: -------------------------------------------------------------------------------- 1 | #lang racket 2 | 3 | (require rackunit) 4 | (require peg) 5 | (require "peg-syntax/peg-example-quests.rkt") 6 | 7 | (check-equal? (peg quest "quest firstLevel 8 | exec ls -l ; 9 | echo You type the correct command ; 10 | tseuq") 11 | (quest 12 | (identifier-quest "firstLevel") 13 | (seqComand 14 | (exec 15 | (ls-struct "-l" '())) 16 | (echo-struct "You type the correct command ")) 17 | '())) 18 | -------------------------------------------------------------------------------- /tests/peg-syntax/peg-example-guile-passwd.rkt: -------------------------------------------------------------------------------- 1 | #lang peg 2 | passwd <-- entry* !. ; 3 | entry <-- login C pass C uid C gid C nameORcomment C homedir C shell NL* ; 4 | login <-- text ; 5 | pass <-- text ; 6 | uid <-- [0-9]* ; 7 | gid <-- [0-9]* ; 8 | nameORcomment <-- text ; 9 | homedir <-- path ; 10 | shell <-- path ; 11 | path <-- (SLASH pathELEMENT)* ; 12 | pathELEMENT <-- (!NL !C !'/' .)* ; 13 | text <- (!NL !C .)* ; 14 | C < ':' ; 15 | NL < [\n] ; 16 | SLASH < '/' ; 17 | -------------------------------------------------------------------------------- /tests/peg-syntax/peg-example-guile-cfunc.rkt: -------------------------------------------------------------------------------- 1 | #lang peg 2 | cfunc <-- cSP ctype cSP cname cSP cargs cLB cSP cbody cRB ; 3 | ctype <-- cidentifier ; 4 | cname <-- cidentifier ; 5 | cargs <-- cLP (! (cSP cRP) carg cSP (cCOMMA / cRP) cSP)* cSP ; 6 | carg <-- cSP ctype cSP cname ; 7 | cbody <-- cstatement * ; 8 | cidentifier <- [a-zA-z][a-zA-Z0-9_]* ; 9 | cstatement <-- (!';'.)*cSC cSP ; 10 | cSC < ';' ; 11 | cCOMMA < ',' ; 12 | cLP < '(' ; 13 | cRP < ')' ; 14 | cLB < '{' ; 15 | cRB < '}' ; 16 | cSP < [ \t\n]* ; 17 | -------------------------------------------------------------------------------- /tests/test-palindrome.rkt: -------------------------------------------------------------------------------- 1 | #lang racket 2 | 3 | (require rackunit) 4 | (require peg) 5 | 6 | (define-peg marked-palindrome 7 | (or "m" 8 | (and "1" marked-palindrome "1") 9 | (and "0" marked-palindrome "0"))) 10 | 11 | (check-equal? (peg marked-palindrome "100m001") "100m001") 12 | (check-equal? (peg marked-palindrome "101m101") "101m101") 13 | (check-equal? (peg marked-palindrome "000001m100000") "000001m100000") 14 | (check-exn exn:fail? (lambda () (peg marked-palindrome "010101m010101"))) 15 | -------------------------------------------------------------------------------- /tests/peg-syntax/peg-example-newick.rkt: -------------------------------------------------------------------------------- 1 | #lang peg 2 | 3 | top <- v:Tree ! . -> v; 4 | Tree <-- (Branch / SubTree) ~';' ; //will work with ";" as input (peg top ";") will work because that 5 | SubTree <-- Internal / Leaf ; //always work 6 | Leaf <-- Name ; //always work 7 | Name <-- String / '' ; //always work 8 | String <-- [a-zA-Z]+ ; 9 | Internal <-- ~'(' BranchSet ~')' Name ; 10 | BranchSet <-- Branch (~',' Branch)* ; 11 | Branch <-- SubTree Length ; 12 | Length <-- ~':' Number ; 13 | Number <- [0-9]+('.' Number)? ; 14 | -------------------------------------------------------------------------------- /tests/s-exp/test-chars.rkt: -------------------------------------------------------------------------------- 1 | #lang racket 2 | 3 | (require rackunit) 4 | (require peg) 5 | (require peg/s-exp) 6 | 7 | (check-equal? (peg s-exp 8 | "((null #\\null) 9 | (backspace #\\backspace) 10 | (tab #\\tab) 11 | (newline #\\newline) 12 | (vtab #\\vtab) 13 | (page #\\page) 14 | (return #\\return) 15 | (space #\\space) 16 | (rubout #\\rubout))") 17 | (quote ((null #\nul) (backspace #\backspace) (tab #\tab) (newline #\newline) (vtab #\vtab) (page #\page) (return #\return) (space #\space) (rubout #\rubout)))) 18 | -------------------------------------------------------------------------------- /tests/docs-example-2.rkt: -------------------------------------------------------------------------------- 1 | #lang racket 2 | 3 | (require rackunit) 4 | (require peg) 5 | 6 | (define-peg number (name res (+ (range #\0 #\9))) 7 | (string->number res)) 8 | (define-peg sum 9 | (and (name v1 prod) (? (and #\+ (name v2 sum)))) 10 | (if v2 (+ v1 v2) v1)) 11 | (define-peg prod 12 | (and (name v1 number) (? (and #\* (name v2 prod)))) 13 | (if v2 (* v1 v2) v1)) 14 | 15 | (check-equal? (peg sum "7*2+3*4") 16 | 26) 17 | (check-equal? (peg sum "2+3*4") 18 | 14) 19 | (check-equal? (peg sum "2*3+4") 20 | 10) -------------------------------------------------------------------------------- /tests/list-monad.rkt: -------------------------------------------------------------------------------- 1 | #lang racket 2 | 3 | ;; list-monad.rkt 4 | 5 | (provide liftm2 sequence 6 | concatenate string-concatenate) 7 | 8 | (define (concatenate lists) 9 | (apply append lists)) 10 | 11 | (define (string-concatenate strings) 12 | (apply string-append strings)) 13 | 14 | (define (>>= m f) 15 | (apply append (map f m))) 16 | 17 | (define (liftm2 f a b) 18 | (>>= a (lambda (x) (>>= b (lambda (y) (list (f x y))))))) 19 | 20 | (define (sequence lsts) 21 | (if (null? lsts) 22 | (list '()) 23 | (liftm2 cons (car lsts) (sequence (cdr lsts))))) 24 | -------------------------------------------------------------------------------- /tests/s-exp/test-dotted-pair.rkt: -------------------------------------------------------------------------------- 1 | #lang racket 2 | 3 | (require rackunit) 4 | (require peg) 5 | (require peg/s-exp) 6 | 7 | (check-equal? 8 | (peg s-exp "()") 9 | '()) 10 | 11 | (check-equal? 12 | (peg s-exp "(a . b)") 13 | '(a . b)) 14 | 15 | (check-equal? 16 | (peg s-exp "(a)") 17 | '(a)) 18 | 19 | (check-equal? 20 | (peg s-exp "(a b)") 21 | '(a b)) 22 | 23 | (check-equal? 24 | (peg s-exp "(a b . c)") 25 | '(a b . c)) 26 | 27 | (check-equal? 28 | (peg s-exp "(a b c . d)") 29 | '(a b c . d)) 30 | 31 | (check-equal? 32 | (peg s-exp "(a b c d . e)") 33 | '(a b c d . e)) 34 | -------------------------------------------------------------------------------- /tests/peg-syntax/peg-example-peg-in-peg-comments.rkt: -------------------------------------------------------------------------------- 1 | #lang peg 2 | 3 | //we can use comments in the start of rules 4 | 5 | //we use '<' to mean that the matching string of input is discarted on parser 6 | _ < (' ' / [\t] / [\n])* ; 7 | 8 | digit <- [0-9] ; 9 | number <-- digit+ ; // we can comment on the end of a rule. We can use this to explain that a number is just 10 | // a bunch of digits concatenated(minimun of 1 digit) 11 | 12 | ident <-- [a-zA-Z] [a-zA-Z0-9_\-]* ; // yeah, charclass can be used to indicated ranges of char. 13 | 14 | //another use, final comments 15 | -------------------------------------------------------------------------------- /tests/peg-syntax-harness/peg-test-canopy.rkt: -------------------------------------------------------------------------------- 1 | #lang racket 2 | 3 | (require rackunit) 4 | (require peg) 5 | 6 | (require "../peg-syntax/peg-example-canopy.rkt") 7 | 8 | ;; example taken from 9 | ;; http://canopy.jcoglan.com/langs/javascript.html 10 | 11 | (check-equal? (peg url "http://example.com/search?q=hello#page=1") 12 | '(url 13 | (scheme . "http") 14 | "://" 15 | (host (hostname (segment . "example") "." (segment . "com"))) 16 | (pathname . "/search") 17 | (search . "?q=hello") 18 | (hash . "#page=1"))) 19 | -------------------------------------------------------------------------------- /tests/peg-syntax/peg-example-antlr-query-language.rkt: -------------------------------------------------------------------------------- 1 | #lang peg 2 | 3 | (require "peg-example-float.rkt") ; 4 | 5 | // based on https://notes.kartashov.com/2016/01/30/writing-a-simple-query-language-with-antlr/ 6 | 7 | _ <- [ ]* ; 8 | 9 | OP < '(' _ ; 10 | CL < ')' _ ; 11 | CM < ',' _ ; 12 | 13 | location <-- OP float CM float CL ; 14 | amount <-- float _ unit ; 15 | unit <- 'km' _ / '%' _ ; 16 | 17 | expression <- predicate 'and' _ expression 18 | / predicate 'or' _ expression 19 | / predicate ; 20 | predicate <-- 'location' _ 'within' _ amount 'from' _ location 21 | / 'status.stateOfCharge' '<' _ amount ; 22 | -------------------------------------------------------------------------------- /tests/peg-syntax/peg-example-peg-as-peg.rkt: -------------------------------------------------------------------------------- 1 | #lang peg 2 | peg-in-peg <-- sp grammar+ ; 3 | grammar <-- (nonterminal ('<--' / '<-' / '<') sp pattern)+ ';' sp ; 4 | pattern <-- alternative (SLASH sp alternative)* ; 5 | alternative <-- ([!&]? sp suffix)+ ; 6 | suffix <-- primary ([*+?] sp)? ; 7 | primary <-- '(' sp pattern ')' sp / '.' sp / literal / charclass / nonterminal !'<' ; 8 | literal <-- ['] (!['] .)* ['] sp ; 9 | charclass <-- LB (!']' (CCrange / CCsingle))* RB sp ; 10 | CCrange <-- . '-' . ; 11 | CCsingle <-- !']' . ; 12 | ntchar <- [a-zA-Z0-9\-] ; 13 | nonterminal <-- ntchar+ !ntchar sp ; 14 | sp < [ \t\n]* ; 15 | SLASH < '/' ; 16 | LB < '[' ; 17 | RB < ']' ; 18 | 19 | -------------------------------------------------------------------------------- /tests/test-regex-range.rkt: -------------------------------------------------------------------------------- 1 | #lang racket 2 | 3 | (require rackunit) 4 | (require peg) 5 | 6 | (define-peg regex-range 7 | (and #\[ (? (name neg #\^)) (name res (* (or regex-range-range regex-range-single))) #\]) 8 | (if neg `(negate . ,res) res)) 9 | (define-peg regex-range-range 10 | (and (name c1 (any-char)) #\- (name c2 (any-char))) 11 | `(range ,c1 ,c2)) 12 | (define-peg regex-range-single 13 | (name c1 (and (! #\]) (any-char))) 14 | `(single ,c1)) 15 | 16 | (check-equal? (peg regex-range "[a-zA-Z0-9_]") 17 | '((range "a" "z") (range "A" "Z") (range "0" "9") (single "_"))) 18 | (check-equal? (peg regex-range "[^0-9]") '(negate (range "0" "9"))) 19 | -------------------------------------------------------------------------------- /tests/peg-syntax-harness/peg-test-guile-cfunc.rkt: -------------------------------------------------------------------------------- 1 | #lang racket 2 | 3 | (require rackunit) 4 | (require peg) 5 | 6 | (require "../peg-syntax/peg-example-guile-cfunc.rkt") 7 | 8 | (check-equal? (peg cfunc "int square(int a) { return a*a;}") 9 | '(cfunc (ctype . "int") (cname . "square") (cargs (carg (ctype . "int") (cname . "a"))) 10 | (cbody (cstatement . "return a*a")))) 11 | (check-equal? (peg cfunc "int mod(int a, int b) { int c = a/b;return a-b*c; }") 12 | '(cfunc (ctype . "int") (cname . "mod") (cargs (carg (ctype . "int") (cname . "a")) (carg (ctype . "int") (cname . "b"))) 13 | (cbody (cstatement . "int c = a/b") 14 | (cstatement . "return a-b*c")))) 15 | -------------------------------------------------------------------------------- /tests/peg-syntax-harness/test-newick.rkt: -------------------------------------------------------------------------------- 1 | #lang racket 2 | 3 | (require peg) 4 | (require rackunit) 5 | 6 | (require "../peg-syntax/peg-example-newick.rkt") 7 | 8 | (check-equal? 9 | (peg top "((B:0.2,(C:0.3,D:0.4)E:0.5)A:0.1)F;") 10 | '(Tree 11 | (SubTree 12 | Internal 13 | (BranchSet 14 | (Branch 15 | (SubTree 16 | Internal 17 | (BranchSet 18 | (Branch (SubTree Leaf Name String . "B") (Length . "0.2")) 19 | (Branch 20 | (SubTree Internal (BranchSet (Branch (SubTree Leaf Name String . "C") (Length . "0.3")) (Branch (SubTree Leaf Name String . "D") (Length . "0.4"))) (Name String . "E")) 21 | (Length . "0.5"))) 22 | (Name String . "A")) 23 | (Length . "0.1"))) 24 | (Name String . "F")))) 25 | -------------------------------------------------------------------------------- /make: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | set -x 4 | 5 | if [ $# -eq 0 ]; 6 | then 7 | echo targets are 8 | echo \* install 9 | echo \* update 10 | echo \* bootstrap 11 | echo \* test 12 | echo \* docs 13 | else 14 | case "$1" in 15 | 16 | install) 17 | echo 'rm -rf ~/.racket/' 18 | raco pkg install -t dir --link `pwd` 19 | ;; 20 | 21 | update) 22 | raco pkg update --link `pwd` 23 | ;; 24 | 25 | bootstrap) 26 | raco read -n 256 peg-src/peg-in-peg.peg > peg-in-peg.rkt.tmp 27 | raco read -n 256 peg-src/s-exp.peg > s-exp.rkt.tmp 28 | mv peg-in-peg.rkt.tmp peg-in-peg.rkt 29 | mv s-exp.rkt.tmp s-exp.rkt 30 | echo make sure to run bootstrap again! 31 | ;; 32 | 33 | test) 34 | raco test tests/ 35 | ;; 36 | 37 | docs) 38 | scribble --dest scribblings/ scribblings/peg.scrbl 39 | ;; 40 | esac 41 | fi 42 | 43 | -------------------------------------------------------------------------------- /tests/docs-example-3.rkt: -------------------------------------------------------------------------------- 1 | #lang racket 2 | 3 | (require rackunit) 4 | (require peg) 5 | 6 | (define-peg _ (* (or #\space #\newline))) 7 | 8 | (define-peg symbol 9 | (and (name res (+ (and (! #\( #\) #\space #\newline) (any-char)))) _) 10 | (string->symbol res)) 11 | 12 | (define-peg/bake sexp 13 | (or symbol 14 | (and (drop #\() (* sexp) (drop #\) _)))) 15 | 16 | (check-equal? (peg sexp "()") '()) 17 | (check-equal? (peg sexp "(a)") '(a)) 18 | (check-equal? (peg sexp "(a b)") '(a b)) 19 | (check-equal? (peg sexp "(a b c)") '(a b c)) 20 | (check-equal? (peg sexp "(foob (ar baz)quux)") '(foob (ar baz) quux)) 21 | (check-equal? (peg sexp "((())(()(())))") '((())(()(())))) 22 | (check-equal? (peg sexp "(((o))(u(u)((e)x))o)") '(((o))(u(u)((e)x))o)) 23 | (check-equal? (peg sexp "(lambda (x) (list x (list (quote quote) x)))") '(lambda (x) (list x (list (quote quote) x)))) 24 | -------------------------------------------------------------------------------- /main.rkt: -------------------------------------------------------------------------------- 1 | #lang racket 2 | (require "peg.rkt") 3 | (provide (all-from-out "peg.rkt")) 4 | (module reader racket 5 | 6 | (require syntax/strip-context) 7 | 8 | (require "peg.rkt") 9 | (require "peg-result.rkt") 10 | (require "peg-in-peg.rkt") 11 | (require "peg-to-scheme.rkt") 12 | 13 | (provide (rename-out [literal-read read] 14 | [literal-read-syntax read-syntax])) 15 | 16 | (define (peg-port->scheme in) 17 | (peg->scheme (car 18 | (peg-result->object (peg (and peg (! (any-char))) in))))) 19 | 20 | (define (literal-read in) 21 | (syntax->datum 22 | (literal-read-syntax #f in))) 23 | 24 | (define (literal-read-syntax src in) 25 | (with-syntax ([body (peg-port->scheme in)]) 26 | (strip-context 27 | #'(module anything racket 28 | (provide (all-defined-out)) 29 | (require peg/peg) 30 | body)))) 31 | 32 | ) 33 | -------------------------------------------------------------------------------- /peg-src/peg-in-peg.peg: -------------------------------------------------------------------------------- 1 | #lang peg 2 | 3 | (require "s-exp.rkt"); 4 | 5 | _ < ([ \t\n] / '//' [^\n]*)*; 6 | SLASH < '/' _; 7 | 8 | name <-- [a-zA-Z_] [a-zA-Z0-9\-_.]* _; 9 | 10 | rule <-- name ('<---' / '<--' / '<-' / '<') _ pattern ('->' _ s-exp _)? ';' _; 11 | pattern <-- alternative (SLASH alternative)*; 12 | alternative <-- expression+; 13 | expression <-- (name ~':' _)? ([!&~] _)? primary ([*+?] _)?; 14 | primary <-- '(' _ pattern ')' _ / '.' _ / literal / charclass / name; 15 | 16 | literal <-- ~['] (~[\\] ['\\] / !['\\] .)* ~['] _; 17 | 18 | charclass <-- ~'[' '^'? (cc-range / cc-escape / cc-single)+ ~']' _; 19 | cc-range <-- cc-char ~'-' cc-char; 20 | cc-escape <-- ~[\\] .; 21 | cc-single <-- cc-char; 22 | cc-char <- !cc-escape-char . / 'n' / 't'; 23 | cc-escape-char <- '[' / ']' / '-' / '^' / '\\' / 'n' / 't'; 24 | 25 | peg <-- _ import* rule+; 26 | import <-- s-exp _ ';' _; 27 | -------------------------------------------------------------------------------- /tests/test-blg.rkt: -------------------------------------------------------------------------------- 1 | #lang racket 2 | 3 | (require rackunit) 4 | 5 | (require peg) 6 | (require peg/peg-result) 7 | 8 | ;; boolean logic grammar 9 | 10 | (define-peg blg (and _ blg-exp-or)) 11 | (define-peg/drop _ (* (or #\space #\newline #\tab))) 12 | 13 | (define-peg blg-op-or (and "or" _)) 14 | (define-peg blg-op-and (and "and" _)) 15 | (define-peg blg-bool-true (and "true" _)) 16 | (define-peg blg-bool-false (and "false" _)) 17 | (define-peg/bake blg-bool (or blg-bool-true blg-bool-false)) 18 | (define-peg/tag blg-exp-or (and blg-exp-and (* (and blg-op-or blg-exp-and)))) 19 | (define-peg/tag blg-exp-and (and blg-bool (* (and blg-op-and blg-bool)))) 20 | 21 | (check-equal? (peg blg "true or true and false") 22 | '((blg-exp-or (blg-exp-and "true") "or" (blg-exp-and "true" "and" "false")))) 23 | (check-equal? (peg blg "true and false") 24 | '((blg-exp-or (blg-exp-and "true" "and" "false")))) 25 | 26 | -------------------------------------------------------------------------------- /tests/peg-syntax-harness/peg-test-expr.rkt: -------------------------------------------------------------------------------- 1 | #lang racket 2 | 3 | (require rackunit) 4 | (require peg) 5 | 6 | (require "../peg-syntax/peg-example-expr.rkt") 7 | 8 | (check-equal? (peg expr "4324+431") 9 | '(sum (product value number . "4324") "+" (sum product value number . "431"))) 10 | (check-equal? (peg expr "72*4324+431") 11 | '(sum (product (value number . "72") "*" (product value number . "4324")) 12 | "+" (sum product value number . "431"))) 13 | (check-equal? (peg expr "4324+72*431") 14 | '(sum (product value number . "4324") "+" 15 | (sum product (value number . "72") "*" (product value number . "431")))) 16 | (check-equal? (peg expr "4324+72*431*27") 17 | '(sum (product value number . "4324") "+" 18 | (sum product (value number . "72") "*" 19 | (product (value number . "431") "*" (product value number . "27"))))) 20 | 21 | -------------------------------------------------------------------------------- /tests/test-verbose.rkt: -------------------------------------------------------------------------------- 1 | #lang racket 2 | 3 | (require rackunit) 4 | (require peg) 5 | 6 | (define-peg number (name v (+ (range #\0 #\9))) (string->number v)) 7 | (define-peg sum (and (name v1 number) "+" (name v2 number)) (+ v1 v2)) 8 | 9 | 10 | ;because in non-debug mode, nothing is printed, just returned 11 | (check-equal? "" (with-output-to-string (lambda () (peg sum "12+123")))) 12 | 13 | 14 | ;the result is 135, showed in the last line. ALL before is debug 15 | ;(check-equal? ">(peg-rule:local-debug #object>)\n>(peg-rule:sum-debug #)\n>(peg-rule:number-debug #)\n>(peg-rule:number-debug #)\n<135\n" (with-output-to-string (lambda () (peg sum "12+123" #t)))) 16 | 17 | ;> (peg (and sum (and "," sum)) "12+123,55+33" #t) 18 | ;peg-rule:local 19 | ; peg-rule:sum 20 | ; peg-rule:number 21 | ; peg-rule:number 22 | ; peg-rule:sum 23 | ; peg-rule:number 24 | ; peg-rule:number 25 | ;'(135 "," 88) 26 | -------------------------------------------------------------------------------- /tests/test-multibrack.rkt: -------------------------------------------------------------------------------- 1 | #lang racket 2 | 3 | (require rackunit) 4 | 5 | (require peg) 6 | (require peg/peg-result) 7 | 8 | (define-peg multibrack 9 | (* (or multibrack-paren 10 | multibrack-square 11 | multibrack-brace 12 | multibrack-angle))) 13 | (define-peg/tag multibrack-paren (and (drop #\() multibrack (drop #\)))) 14 | (define-peg/tag multibrack-square (and (drop #\[) multibrack (drop #\]))) 15 | (define-peg/tag multibrack-brace (and (drop #\{) multibrack (drop #\}))) 16 | (define-peg/tag multibrack-angle (and (drop #\<) multibrack (drop #\>))) 17 | 18 | (check-equal? (peg-result->object (peg multibrack "([][{{}}{}]{}[])")) 19 | '((multibrack-paren (multibrack-square) 20 | (multibrack-square (multibrack-brace (multibrack-brace)) 21 | (multibrack-brace)) 22 | (multibrack-brace) 23 | (multibrack-square)))) 24 | -------------------------------------------------------------------------------- /tests/peg-syntax-harness/peg-test-peg-in-peg-comments.rkt: -------------------------------------------------------------------------------- 1 | #lang racket 2 | 3 | (require peg) 4 | (require rackunit) 5 | 6 | (require "../peg-syntax/peg-example-peg-in-peg-comments.rkt") 7 | 8 | (check-equal? (peg number "123") 9 | '(number . "123")) ; 123 in decimal 10 | 11 | (check-equal? (peg number "1024") 12 | '(number . "1024")) ; 1024 in decimal 13 | 14 | (check-equal? (peg number "0123") 15 | '(number . "0123")) ; 0123 is a octal, 83 decimal. In the way that I put, don't matter. 16 | 17 | (check-not-equal? (peg number "0x1024") 18 | '(number . "1024")) 19 | 20 | (check-equal? (peg number "0x1024") 21 | '(number . "0")) 22 | ; what the hell? Simple : the parser match 0, but x is not a digit, so stop. 23 | ; this is important : the parser will try to parse so long as he get, but don't 24 | ; will find our desires. 25 | 26 | #| 27 | the comments in the parser don't show up in the parsed structure. 28 | they are just ignored by the peg 29 | 30 | |# 31 | -------------------------------------------------------------------------------- /tests/peg-syntax-harness/test-imp.rkt: -------------------------------------------------------------------------------- 1 | #lang racket 2 | 3 | (require peg) 4 | (require rackunit) 5 | 6 | (require "../peg-syntax/peg-example-imp.rkt") 7 | 8 | (check-equal? 9 | (peg program " 10 | 11 | 12 | module test 13 | 14 | var x,y,z ; 15 | const w,h,j ; 16 | init x=0,y=1,z=4,w=10,h=15,j=100; 17 | 18 | proc main 19 | { 20 | print 15 ; 21 | } 22 | 23 | 24 | end") 25 | '(program 26 | "module" 27 | (identifier . "test") 28 | (clauses 29 | (vars "var" (identifier . "x") "," (identifier . "y") "," (identifier . "z") ";") 30 | (const "const" (identifier . "w") "," (identifier . "h") "," (identifier . "j") ";") 31 | (init "init" 32 | (initialization (identifier . "x") "=" (sum product value number . "0")) 33 | "," 34 | (initialization (identifier . "y") "=" (sum product value number . "1")) 35 | "," 36 | (initialization (identifier . "z") "=" (sum product value number . "4")) 37 | "," 38 | (initialization (identifier . "w") "=" (sum product value number . "10")) 39 | "," 40 | (initialization (identifier . "h") "=" (sum product value number . "15")) 41 | "," 42 | (initialization (identifier . "j") "=" (sum product value number . "100")) 43 | ";")) 44 | (procs (proc "proc" (identifier . "main") (block "{" (clauses) (command unitary-command print "print" (sum product value number . "15") ";") "}"))) 45 | "end")) 46 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # racket-peg 2 | 3 | This library implements a PEG parser generator. 4 | 5 | ## Getting Started 6 | 7 | * run `chmod +x ./make` to turn ./make executable 8 | 9 | * Run `./make install` to install the peg library. You should be able to `(require peg)` in your own racket programs after that. Or use `#lang peg`! 10 | 11 | * Run `./make update` to apply changes, if you're hacking on it. 12 | 13 | * Run `./make docs` to build the documentation. 14 | 15 | * Run `./make test` to check that it is working after installation. 16 | 17 | ## Source Code Map 18 | 19 | The PEG parser system is built in two stages. There is a lispy s-expression version. Then there is a self-hosted PEG syntax version. 20 | 21 | The lispy version is implemented in: 22 | 23 | * `peg.rkt` - The PEG parsing VM and parser macro. 24 | * `peg-result.rkt` - The fundamental data structure used for parse results. It's a kind of automatically joinable sequence. 25 | 26 | The PEG aspect is implemented in these files: 27 | 28 | * `peg-src/peg-in-peg.rkt` - The syntax of our peg language. In peg. 29 | * `peg-src/sexp-parser.rkt` - A basic s-expression parser. In peg. 30 | 31 | Both of the above files are "bootstrapped" using the racket macro expander to produce the following: 32 | 33 | * `peg-in-peg.rkt` - expanded version of `peg-src/peg-in-peg.peg`. 34 | * `s-exp.rkt` - expanded version of `peg-src/s-exp.peg`. 35 | * `peg-to-scheme.rkt` - support for peg-in-peg. 36 | * `main.rkt` - This adds the `#lang peg` glue to racket. 37 | 38 | ## Authors 39 | 40 | * Raymond Nicholson 41 | * João Pedro Abreu de Souza 42 | -------------------------------------------------------------------------------- /peg-in-peg.rkt: -------------------------------------------------------------------------------- 1 | (module anything racket 2 | (provide (all-defined-out)) 3 | (require peg/peg) 4 | (begin 5 | (require "s-exp.rkt") 6 | (define-peg/drop _ (* (or (or #\space #\tab #\newline) (and "//" (* (and (! #\newline) (any-char))))))) 7 | (define-peg/drop SLASH (and "/" _)) 8 | (define-peg/tag name (and (or (range #\a #\z) (range #\A #\Z) #\_) (* (or (range #\a #\z) (range #\A #\Z) (range #\0 #\9) #\- #\_ #\.)) _)) 9 | (define-peg/tag rule (and name (or "<---" "<--" "<-" "<") _ pattern (? (and "->" _ s-exp _)) ";" _)) 10 | (define-peg/tag pattern (and alternative (* (and SLASH alternative)))) 11 | (define-peg/tag alternative (+ expression)) 12 | (define-peg/tag expression (and (? (and name (drop ":") _)) (? (and (or #\! #\& #\~) _)) primary (? (and (or #\* #\+ #\?) _)))) 13 | (define-peg/tag primary (or (and "(" _ pattern ")" _) (and "." _) literal charclass name)) 14 | (define-peg/tag literal (and (drop #\') (* (or (and (drop #\\) (or #\' #\\)) (and (! (or #\' #\\)) (any-char)))) (drop #\') _)) 15 | (define-peg/tag charclass (and (drop "[") (? "^") (+ (or cc-range cc-escape cc-single)) (drop "]") _)) 16 | (define-peg/tag cc-range (and cc-char (drop "-") cc-char)) 17 | (define-peg/tag cc-escape (and (drop #\\) (any-char))) 18 | (define-peg/tag cc-single cc-char) 19 | (define-peg cc-char (or (and (! cc-escape-char) (any-char)) "n" "t")) 20 | (define-peg cc-escape-char (or "[" "]" "-" "^" "\\" "n" "t")) 21 | (define-peg/tag peg (and _ (* import) (+ rule))) 22 | (define-peg/tag import (and s-exp _ ";" _)))) 23 | -------------------------------------------------------------------------------- /tests/test-cfunc.rkt: -------------------------------------------------------------------------------- 1 | #lang racket 2 | 3 | (require rackunit) 4 | (require peg) 5 | 6 | ;; https://www.gnu.org/software/guile/manual/html_node/PEG-Tutorial.html#PEG-Tutorial 7 | 8 | (define-peg/tag cfunc (and cSP ctype cSP cname cSP cargs cLB cSP cbody cRB)) 9 | (define-peg/tag ctype cidentifier) 10 | (define-peg/tag cname cidentifier) 11 | (define-peg cargs (and cLP (* (and (! (and cSP cRP)) carg cSP (or cCOMMA cRP) cSP)) cSP)) ;; ! 12 | (define-peg carg (and cSP ctype cSP cname)) 13 | (define-peg/tag cbody (* cstatement)) 14 | (define-peg cidentifier (and (or (range #\a #\z) 15 | (range #\A #\Z)) 16 | (* (or (range #\a #\z) 17 | (range #\A #\Z) 18 | (range #\0 #\9) 19 | #\-)))) 20 | (define-peg cstatement (name res (and (* (and (! #\;) (any-char))) cSC cSP)) 21 | res) 22 | (define-peg/drop cSC #\;) 23 | (define-peg/drop cCOMMA #\,) 24 | (define-peg/drop cLP #\() 25 | (define-peg/drop cRP #\)) 26 | (define-peg/drop cLB #\{) 27 | (define-peg/drop cRB #\}) 28 | (define-peg/drop cSP (* (or #\space #\newline))) 29 | 30 | (check-equal? (peg cfunc "int square(int a) { return a*a;}") 31 | '(cfunc (ctype . "int") (cname . "square") (ctype . "int") (cname . "a") (cbody "return a*a"))) 32 | (check-equal? (peg cfunc "int mod(int a, int b) { int c = a/b;return a-b*c; }") 33 | '(cfunc (ctype . "int") (cname . "mod") (ctype . "int") (cname . "a") (ctype . "int") (cname . "b") (cbody "int c = a/b" "return a-b*c"))) 34 | 35 | -------------------------------------------------------------------------------- /tests/peg-syntax/peg-example-imp.rkt: -------------------------------------------------------------------------------- 1 | #lang peg 2 | 3 | (require "peg-example-expr.rkt") ; 4 | 5 | 6 | //based on grammar 7 | //https://github.com/ChristianoBraga/BPLC/blob/python-ibm-cloud/examples/imp/doc/imp.pdf 8 | 9 | //to see a old 'broken' implementation, see 10 | //https://github.com/Grupo-de-compiladores/apresenta-o-de-racket 11 | 12 | //is in brazilian portuguese, the name is "racket's presentation" 13 | 14 | 15 | 16 | program <-- _ 'module' _ identifier _ clauses _ procs _ 'end' _ EOI ; 17 | _ < [ \t\n]* ; 18 | identifier <-- [a-zA-Z]+ ; 19 | clauses <-- vars? _ const? _ init? ; 20 | vars <-- 'var' _ identifier _ (',' _ identifier _)* ';' ; 21 | const <-- 'const' _ identifier _ (',' _ identifier _)* ';' ; 22 | init <-- 'init' _ initialization _ (',' _ initialization _)* ';' ; 23 | initialization <-- identifier _ '=' _ expr ; 24 | procs <-- proc (_ proc)* ; 25 | proc <-- 'proc' _ identifier _ block ; //yes proc can have arguments, KISS guy, KISS. 26 | block <-- '{' _ clauses? _ command (_ command)* _ '}' ; //this is wrong, because in IMP, 27 | //declarations inside block is different, 28 | //but to simplify the grammar, 29 | //I will use the same clauses. 30 | 31 | command <-- (unitary-command _ command) / unitary-command ; 32 | unitary-command <-- atribution / print / exit ; //yes, ';' is operator to seq commands, but to 33 | //simplify all command end with this 34 | atribution <-- identifier _ ':=' _ expr _ ';' ; 35 | print <-- 'print' _ expr _ ';' ; 36 | exit <-- 'exit' _ expr _ ';' ; 37 | 38 | 39 | 40 | EOI < ! . ; 41 | -------------------------------------------------------------------------------- /tests/test-tiny.rkt: -------------------------------------------------------------------------------- 1 | #lang racket 2 | 3 | (require rackunit) 4 | 5 | (require peg) 6 | (require peg/peg-result) 7 | 8 | ;;; Tiny 9 | 10 | (define-peg/drop _ (* (or #\space #\tab #\newline))) 11 | (define-peg number (name res (+ (range #\0 #\9))) 12 | (string->number res)) 13 | (define-peg symbol 14 | (and (name res (+ (and (! #\( #\) #\space #\newline #\;) (any-char)))) _) 15 | (string->symbol res)) 16 | 17 | (define-peg/bake tiny (and cmd-seq (! (any-char)))) 18 | (define-peg cmd-seq (+ (and cmd semicolon))) 19 | (define-peg cmd (or if-cmd 20 | repeat-cmd 21 | read-cmd 22 | write-cmd 23 | assign-cmd)) 24 | (define-peg/tag if-cmd (and "IF" _ number "THEN" _ cmd-seq (? (and "ELSE" _ cmd-seq)) "END" _)) 25 | (define-peg/tag repeat-cmd (and "REPEAT" _ cmd-seq "UNTIL" _ number)) 26 | (define-peg/tag read-cmd (and "READ" _ symbol)) 27 | (define-peg/tag write-cmd (and "WRITE" _ symbol)) 28 | (define-peg/tag assign-cmd (and symbol _ ":=" _ number)) 29 | (define-peg/drop semicolon (and #\; _)) 30 | 31 | (define *tiny-example* 32 | "n := 5; 33 | f := 1; 34 | REPEAT 35 | f := 35; 36 | n := 2; 37 | UNTIL 1; 38 | WRITE f;") 39 | 40 | (check-equal? (peg tiny "n := 5;") 41 | '((assign-cmd n ":=" 5))) 42 | (check-equal? (peg tiny "f := 35;") 43 | '((assign-cmd f ":=" 35))) 44 | (check-equal? (peg tiny "f := 35; WRITE f;") 45 | '((assign-cmd f ":=" 35) 46 | (write-cmd "WRITE" f))) 47 | (check-equal? (peg tiny *tiny-example*) 48 | '((assign-cmd n ":=" 5) 49 | (assign-cmd f ":=" 1) 50 | (repeat-cmd "REPEAT" (assign-cmd f ":=" 35) (assign-cmd n ":=" 2) "UNTIL" 1) 51 | (write-cmd "WRITE" f))) 52 | -------------------------------------------------------------------------------- /tests/peg-syntax/peg-example-quests.rkt: -------------------------------------------------------------------------------- 1 | #lang peg 2 | 3 | (require "peg-example-shell.rkt"); 4 | 5 | 6 | (provide (all-from-out "peg-example-shell.rkt")); 7 | 8 | (define (parser-quest port) 9 | (peg top-quest port)); 10 | 11 | (struct quest (name command preRequisites) #:transparent); 12 | 13 | (struct seqComand (a b) #:transparent); 14 | 15 | (struct identifier-quest (a) #:transparent); 16 | (struct exec (c) #:transparent); 17 | (struct file (file assertion) #:transparent); 18 | 19 | (define (red l f) 20 | (if (null? (cdr l)) 21 | (car l) 22 | (f (car l) (red (cdr l) f)))); 23 | 24 | 25 | 26 | 27 | _ < [ \t\n]* ; 28 | sep < [ \t]* ; 29 | EOI < ! . ; 30 | 31 | top-quest <- _ v:quest _ EOI -> v; 32 | quest <- quest-with-pre-requisites / quest-without-pre-requisites; 33 | 34 | quest-with-pre-requisites <- _ 'quest' _ v:identifier _ p:preRequisites _ c:comand _ 'tseuq' _ -> (quest v c p); 35 | quest-without-pre-requisites <- _ 'quest' _ v:identifier _ c:comand _ 'tseuq' _ -> (quest v c (list)); 36 | identifier <- v:[a-zA-Z]+ -> (identifier-quest v); 37 | preRequisites <- '<' _ l:(identifier _ (~',' _ identifier _)*) -> l; 38 | comand <- v:(comandUnit (_ comandUnit)*) -> (red v seqComand); //this create a sequence of commands associative from right 39 | comandUnit <- v:(exec / echo-quest / file) ';' -> v; 40 | exec <- 'exec' sep c:shell -> (exec c); 41 | echo-quest <- echo ; 42 | file <- 'file' sep v:identifier sep k:assertionOnFile -> (file v k); 43 | assertionOnFile <- exists / is-directory ; 44 | exists <- 'exists' -> 'exists; 45 | is-directory <- 'is directory' -> 'is-directory; 46 | 47 | 48 | 49 | //quest ls > cd,mkdir 50 | 51 | //exec ls; 52 | 53 | //echo Very good, this is your directory; 54 | 55 | //file ola exists; 56 | 57 | //exec cd p; 58 | 59 | //tseuq 60 | 61 | 62 | 63 | -------------------------------------------------------------------------------- /tests/peg-syntax/peg-example-shell.rkt: -------------------------------------------------------------------------------- 1 | #lang peg 2 | 3 | 4 | (struct or-struct (a b) #:transparent); 5 | (struct and-struct (a b) #:transparent); 6 | (struct pipe-struct (a b) #:transparent); 7 | (struct out-redirect (cmd file) #:transparent); 8 | (struct in-redirect (cmd file) #:transparent); 9 | (struct dir-or-file (name) #:transparent); 10 | 11 | (struct ls-struct (options directory) #:transparent); 12 | (struct cd-struct (directory) #:transparent); 13 | (struct mkdir-struct (directory) #:transparent); 14 | (struct cat-struct (l) #:transparent); 15 | (struct man-struct (name) #:transparent); 16 | (struct less-struct (name) #:transparent); 17 | (struct more-struct (name) #:transparent); 18 | (struct echo-struct (a) #:transparent); 19 | 20 | (define (parser str) 21 | (peg top-shell str)); 22 | 23 | (define (red v l) 24 | (if (null? l) v 25 | (red ((car l) v (cadr l)) (cddr l)))); 26 | 27 | (define (flat l) 28 | (match l 29 | [(list (list a ...)) (flat a)] 30 | [a a])); 31 | 32 | EOI < ! . ; 33 | _ < [ \t]* ; 34 | top-shell <- _ shell _ EOI ; 35 | shell <- _ v:logic _ -> v; 36 | logic <- v1:redirect _ v2:((logicOperator _ redirect _)*) -> (red v1 v2); 37 | logicOperator <- v:('&&' / '||' ) -> (if (equal? v "&&") and-struct or-struct); 38 | 39 | redirect <- v1:(pipeline?) _ v2:(input-redirect?) _ v3:(output-redirect?) -> (if (not (null? v3)) 40 | (out-redirect (if (not (null? v2)) (in-redirect v1 v2) v1) v3) 41 | (if (not (null? v2)) (in-redirect v1 v2) v1)); 42 | input-redirect <- '<' _ v:name _ -> v; 43 | output-redirect <- '>' _ v:name _ -> v; 44 | pipeline <- v1:simpleCommand _ v2:((pipe _ simpleCommand _ )*) -> (red v1 v2); 45 | pipe <- '|' -> pipe-struct; 46 | simpleCommand <- ls / cd / mkdir / cat / less / more / man / l / echo; 47 | 48 | ls <- 'ls' _ v1:options-ls _ v2:name? -> (ls-struct v1 v2); 49 | options-ls <- '-l'?; 50 | 51 | 52 | cd <- 'cd' _ v:name -> (cd-struct v); 53 | name <- v:([a-zA-Z.]+) -> (dir-or-file v); 54 | 55 | mkdir <- 'mkdir' _ v:name -> (mkdir-struct v); 56 | 57 | cat <- 'cat' _ v1:name? v2:((_ name)*) -> (cat-struct (flat (cons v1 v2))); 58 | 59 | less <- 'less' _ v1:name? -> (less-struct v1); 60 | 61 | more <- 'more' _ v1:name? -> (more-struct v1); 62 | 63 | man <- 'man' _ v1:name -> (man-struct v1); 64 | 65 | l <- 'l' _ v1:name? -> (ls-struct "-l" v1); 66 | 67 | echo <- 'echo' _ v:([a-zA-Z ]*) -> (echo-struct v); 68 | -------------------------------------------------------------------------------- /peg-src/s-exp.peg: -------------------------------------------------------------------------------- 1 | #lang peg 2 | 3 | (require "peg-result.rkt"); 4 | 5 | (define char-table 6 | '(("null" . #\null) 7 | ("nul" . #\null) 8 | ("backspace" . #\backspace) 9 | ("tab" . #\tab) 10 | ("newline" . #\newline) 11 | ("vtab" . #\vtab) 12 | ("page" . #\page) 13 | ("return" . #\return) 14 | ("space" . #\space) 15 | ("rubout" . #\rubout))); 16 | 17 | (define (symbol->keyword sym) 18 | (string->keyword (symbol->string sym))); 19 | 20 | _ < [ \t\n]*; 21 | 22 | s-exp <- 23 | list / box-list / 24 | quote / quasiquote / unquote / 25 | syntax-quote / syntax-quasiquote / syntax-unquote / 26 | boolean / number / identifier / dotdotdot / keyword / character / string; 27 | 28 | list <- '(' _ lst:(s-exp _)* 29 | (dotted-pair:'.' _ back:s-exp)? 30 | ')' 31 | -> (if dotted-pair 32 | (append lst back) 33 | lst); 34 | 35 | box-list <- 36 | '[' _ lst:(s-exp _)* 37 | (dotted-pair:'.' _ back:s-exp)? 38 | ']' 39 | -> (if dotted-pair 40 | (append lst back) 41 | lst); 42 | 43 | quote <- '\'' _ s:s-exp -> (list 'quote s); 44 | quasiquote <- '`' _ s:s-exp -> (list 'quasiquote s); 45 | unquote <- ',' _ s:s-exp -> (list 'unquote s); 46 | syntax-quote <- '#\'' _ s:s-exp -> (list 'syntax s); 47 | syntax-quasiquote <- '#`' _ s:s-exp -> (list 'quasisyntax s); 48 | syntax-unquote <- '#,' _ s:s-exp -> (list 'unsyntax s); 49 | 50 | boolean <- x:'#t' / x:'#f' -> (equal? "#t" x); 51 | identifier <- s:[^. \t\n()\[\]{}",'`;#|\\]+ -> (string->symbol s); 52 | dotdotdot <- '...' -> '...; 53 | keyword <- '#:' s:identifier -> (symbol->keyword s); 54 | number <- floating-point; 55 | string <- ["] s:([^"\\] / escaped-char)* ["] -> s; 56 | 57 | escaped-char <- escaped-newline / escaped-tab / ~[\\] .; 58 | escaped-newline <- [\\] 'n' -> (peg-result "\n"); 59 | escaped-tab <- [\\] 't' -> (peg-result "\t"); 60 | 61 | character <- ~'#\\' v:code -> v; 62 | alphabetic <- v:[a-zA-Z] -> (string-ref v 0); 63 | code <- named-char / alphabetic-code / digit; 64 | named-char <- nm:('null' / 'nul' / 'backspace' / 'tab' / 'newline' / 'tab' / 'vtab' / 'page' / 'return' / 'space' / 'rubout') !alphabetic 65 | -> (cdr (assoc nm char-table)); 66 | alphabetic-code <- v:alphabetic ! alphabetic -> v; 67 | digit <- v:[0-9] -> (string-ref v 0); 68 | 69 | 70 | signal <- '-' / '+'; 71 | integer-part <- [0-9]+; 72 | fractional-part <- [0-9]+; 73 | scientific-notation <- ('e' / 'E') integer-part; 74 | floating-point <- value:(signal? integer-part ('.' fractional-part)? (scientific-notation)?) -> (string->number value); 75 | -------------------------------------------------------------------------------- /tests/peg-syntax-harness/peg-test-guile-passwd.rkt: -------------------------------------------------------------------------------- 1 | #lang racket 2 | 3 | (require rackunit) 4 | (require peg) 5 | 6 | (require "../peg-syntax/peg-example-guile-passwd.rkt") 7 | 8 | (define *etc-passwd* 9 | "root:x:0:0:root:/root:/bin/bash 10 | daemon:x:1:1:daemon:/usr/sbin:/bin/sh 11 | bin:x:2:2:bin:/bin:/bin/sh 12 | sys:x:3:3:sys:/dev:/bin/sh 13 | nobody:x:65534:65534:nobody:/nonexistent:/bin/sh 14 | messagebus:x:103:107::/var/run/dbus:/bin/false 15 | ") 16 | 17 | (check-equal? (peg passwd *etc-passwd*) 18 | '(passwd 19 | (entry 20 | (login . "root") 21 | (pass . "x") 22 | (uid . "0") 23 | (gid . "0") 24 | (nameORcomment . "root") 25 | (homedir path (pathELEMENT . "root")) 26 | (shell path (pathELEMENT . "bin") (pathELEMENT . "bash"))) 27 | (entry 28 | (login . "daemon") 29 | (pass . "x") 30 | (uid . "1") 31 | (gid . "1") 32 | (nameORcomment . "daemon") 33 | (homedir path (pathELEMENT . "usr") (pathELEMENT . "sbin")) 34 | (shell path (pathELEMENT . "bin") (pathELEMENT . "sh"))) 35 | (entry 36 | (login . "bin") 37 | (pass . "x") 38 | (uid . "2") 39 | (gid . "2") 40 | (nameORcomment . "bin") 41 | (homedir path (pathELEMENT . "bin")) 42 | (shell path (pathELEMENT . "bin") (pathELEMENT . "sh"))) 43 | (entry 44 | (login . "sys") 45 | (pass . "x") 46 | (uid . "3") 47 | (gid . "3") 48 | (nameORcomment . "sys") 49 | (homedir path (pathELEMENT . "dev")) 50 | (shell path (pathELEMENT . "bin") (pathELEMENT . "sh"))) 51 | (entry 52 | (login . "nobody") 53 | (pass . "x") 54 | (uid . "65534") 55 | (gid . "65534") 56 | (nameORcomment . "nobody") 57 | (homedir path (pathELEMENT . "nonexistent")) 58 | (shell path (pathELEMENT . "bin") (pathELEMENT . "sh"))) 59 | (entry 60 | (login . "messagebus") 61 | (pass . "x") 62 | (uid . "103") 63 | (gid . "107") 64 | (nameORcomment) 65 | (homedir path (pathELEMENT . "var") (pathELEMENT . "run") (pathELEMENT . "dbus")) 66 | (shell path (pathELEMENT . "bin") (pathELEMENT . "false"))))) 67 | -------------------------------------------------------------------------------- /tests/test-etc-passwd.rkt: -------------------------------------------------------------------------------- 1 | #lang racket 2 | 3 | (require rackunit) 4 | (require peg) 5 | 6 | ;; https://www.gnu.org/software/guile/manual/html_node/PEG-Tutorial.html#PEG-Tutorial 7 | 8 | (define *etc-passwd* 9 | "root:x:0:0:root:/root:/bin/bash 10 | daemon:x:1:1:daemon:/usr/sbin:/bin/sh 11 | bin:x:2:2:bin:/bin:/bin/sh 12 | sys:x:3:3:sys:/dev:/bin/sh 13 | nobody:x:65534:65534:nobody:/nonexistent:/bin/sh 14 | messagebus:x:103:107::/var/run/dbus:/bin/false 15 | ") 16 | 17 | (define-peg digit (range #\0 #\9)) 18 | 19 | (define-peg passwd (name res (* entry)) 20 | res) 21 | (define-peg/tag entry (and login c pass c uid c gid c name-or-comment c homedir c shell newline+)) 22 | 23 | (define-peg text (* (and (! #\newline) (! c) (any-char)))) 24 | (define-peg/drop c #\:) 25 | (define-peg/drop newline+ (+ #\newline)) 26 | 27 | (define-peg/tag login text) 28 | (define-peg/tag pass text) 29 | (define-peg/tag uid (* digit)) 30 | (define-peg/tag gid (* digit)) 31 | (define-peg/tag name-or-comment text) 32 | (define-peg/tag homedir path) 33 | (define-peg/tag shell path) 34 | (define-peg path (* (and (drop #\/) path-element))) 35 | (define-peg path-element (name res (+ (and (! #\/) (! #\newline) (! c) (any-char)))) 36 | res) 37 | 38 | (check-equal? (peg passwd *etc-passwd*) 39 | '((entry 40 | (login . "root") 41 | (pass . "x") 42 | (uid . "0") 43 | (gid . "0") 44 | (name-or-comment . "root") 45 | (homedir "root") 46 | (shell "bin" "bash")) 47 | (entry 48 | (login . "daemon") 49 | (pass . "x") 50 | (uid . "1") 51 | (gid . "1") 52 | (name-or-comment . "daemon") 53 | (homedir "usr" "sbin") 54 | (shell "bin" "sh")) 55 | (entry 56 | (login . "bin") 57 | (pass . "x") 58 | (uid . "2") 59 | (gid . "2") 60 | (name-or-comment . "bin") 61 | (homedir "bin") 62 | (shell "bin" "sh")) 63 | (entry 64 | (login . "sys") 65 | (pass . "x") 66 | (uid . "3") 67 | (gid . "3") 68 | (name-or-comment . "sys") 69 | (homedir "dev") 70 | (shell "bin" "sh")) 71 | (entry 72 | (login . "nobody") 73 | (pass . "x") 74 | (uid . "65534") 75 | (gid . "65534") 76 | (name-or-comment . "nobody") 77 | (homedir "nonexistent") 78 | (shell "bin" "sh")) 79 | (entry 80 | (login . "messagebus") 81 | (pass . "x") 82 | (uid . "103") 83 | (gid . "107") 84 | (name-or-comment) 85 | (homedir "var" "run" "dbus") 86 | (shell "bin" "false")))) 87 | -------------------------------------------------------------------------------- /tests/peg-syntax-harness/peg-test-peg-as-peg.rkt: -------------------------------------------------------------------------------- 1 | #lang racket 2 | 3 | (require rackunit) 4 | (require peg) 5 | 6 | (require "../peg-syntax/peg-example-peg-as-peg.rkt") 7 | 8 | (define *expr-peg* #<keyword sym) (string->keyword (symbol->string sym))) 8 | (define-peg/drop _ (* (or #\space #\tab #\newline))) 9 | (define-peg s-exp (or list box-list quote quasiquote unquote syntax-quote syntax-quasiquote syntax-unquote boolean number identifier dotdotdot keyword character string)) 10 | (define-peg list (and "(" _ (name lst (* (and s-exp _))) (? (and (name dotted-pair ".") _ (name back s-exp))) ")") (if dotted-pair (append lst back) lst)) 11 | (define-peg box-list (and "[" _ (name lst (* (and s-exp _))) (? (and (name dotted-pair ".") _ (name back s-exp))) "]") (if dotted-pair (append lst back) lst)) 12 | (define-peg quote (and "'" _ (name s s-exp)) (list 'quote s)) 13 | (define-peg quasiquote (and "`" _ (name s s-exp)) (list 'quasiquote s)) 14 | (define-peg unquote (and "," _ (name s s-exp)) (list 'unquote s)) 15 | (define-peg syntax-quote (and "#'" _ (name s s-exp)) (list 'syntax s)) 16 | (define-peg syntax-quasiquote (and "#`" _ (name s s-exp)) (list 'quasisyntax s)) 17 | (define-peg syntax-unquote (and "#," _ (name s s-exp)) (list 'unsyntax s)) 18 | (define-peg boolean (or (name x "#t") (name x "#f")) (equal? "#t" x)) 19 | (define-peg identifier (name s (+ (and (! (or #\. #\space #\tab #\newline #\( #\) #\[ #\] #\{ #\} #\" #\, #\' #\` #\; #\# #\| #\\)) (any-char)))) (string->symbol s)) 20 | (define-peg dotdotdot "..." '...) 21 | (define-peg keyword (and "#:" (name s identifier)) (symbol->keyword s)) 22 | (define-peg number floating-point) 23 | (define-peg string (and #\" (name s (* (or (and (! (or #\" #\\)) (any-char)) escaped-char))) #\") (if (null? s) "" s)) 24 | (define-peg escaped-char (or escaped-newline escaped-tab (and (drop #\\) (any-char)))) 25 | (define-peg escaped-newline (and #\\ "n") (peg-result "\n")) 26 | (define-peg escaped-tab (and #\\ "t") (peg-result "\t")) 27 | (define-peg character (and (drop "#\\") (name v code)) v) 28 | (define-peg alphabetic (name v (or (range #\a #\z) (range #\A #\Z))) (string-ref v 0)) 29 | (define-peg code (or named-char alphabetic-code digit)) 30 | (define-peg named-char (and (name nm (or "null" "nul" "backspace" "tab" "newline" "tab" "vtab" "page" "return" "space" "rubout")) (! alphabetic)) (cdr (assoc nm char-table))) 31 | (define-peg alphabetic-code (and (name v alphabetic) (! alphabetic)) v) 32 | (define-peg digit (name v (range #\0 #\9)) (string-ref v 0)) 33 | (define-peg signal (or "-" "+")) 34 | (define-peg integer-part (+ (range #\0 #\9))) 35 | (define-peg fractional-part (+ (range #\0 #\9))) 36 | (define-peg scientific-notation (and (or "e" "E") integer-part)) 37 | (define-peg floating-point (name value (and (? signal) integer-part (? (and "." fractional-part)) (? scientific-notation))) (string->number value)))) 38 | -------------------------------------------------------------------------------- /tests/s-exp/tests.rkt: -------------------------------------------------------------------------------- 1 | #lang racket 2 | 3 | (require rackunit) 4 | (require peg) 5 | (require peg/s-exp) 6 | 7 | (define (s-exp->scheme x) x) 8 | 9 | (check-equal? 10 | (s-exp->scheme (peg s-exp "(\"foo bar\" baz (#t 244))")) 11 | '("foo bar" baz (#t 244))) 12 | 13 | ;; spacing test 14 | (check-equal? 15 | (s-exp->scheme (peg s-exp "(a b c)")) 16 | '(a b c)) 17 | (check-equal? 18 | (s-exp->scheme (peg s-exp "( a b c)")) 19 | '(a b c)) 20 | (check-equal? 21 | (s-exp->scheme (peg s-exp "(a b c )")) 22 | '(a b c)) 23 | 24 | 25 | ;; quote, unquote and quasiquote test 26 | (check-equal? 27 | (s-exp->scheme (peg s-exp "'(a b c)")) 28 | '(quote (a b c))) 29 | (check-equal? 30 | (s-exp->scheme (peg s-exp "`(a b ,(c d e))")) 31 | '(quasiquote (a b (unquote (c d e))))) 32 | (check-equal? 33 | (s-exp->scheme (peg s-exp "'''x")) 34 | ''''x) 35 | (check-equal? 36 | (s-exp->scheme (peg s-exp "'``'x")) 37 | ''``'x) 38 | (check-equal? 39 | (s-exp->scheme (peg s-exp "'``'`'x")) 40 | ''``'`'x) 41 | 42 | ;; syntax quotes 43 | (check-equal? 44 | (peg s-exp "#`(#,foo #,(list #'bar bar))") 45 | '#`(#,foo #,(list #'bar bar))) 46 | 47 | ;; + and numbers 48 | (check-equal? 49 | (s-exp->scheme (peg s-exp "(+ 1 2)")) 50 | '(+ 1 2)) 51 | 52 | ;; lambda expressions 53 | (check-equal? 54 | (s-exp->scheme (peg s-exp "((lambda (x) (+ x 1)) 13)")) 55 | '((lambda (x) (+ x 1)) 13)) 56 | 57 | ;; empty string 58 | (check-equal? 59 | (s-exp->scheme (peg s-exp "\"\"")) 60 | '"") 61 | 62 | ;; escaping inside strings 63 | (check-equal? 64 | (s-exp->scheme (peg s-exp "(\"ABC\" \"A\\\\B\\\\C\" \"A\\\"B\\\"C\")")) 65 | '("ABC" "A\\B\\C" "A\"B\"C")) 66 | 67 | (check-equal? 68 | (s-exp->scheme (peg s-exp "(string->number bar)")) 69 | '(string->number bar)) 70 | 71 | ;; box lists 72 | (check-equal? 73 | (s-exp->scheme (peg s-exp 74 | "(define (f l) 75 | (match 76 | [(list a b) a] 77 | [(list a) (list a 1)]))")) 78 | '(define (f l) 79 | (match 80 | [(list a b) a] 81 | [(list a) (list a 1)]))) 82 | 83 | (check-equal? 84 | (s-exp->scheme (peg s-exp 85 | "(struct add (a b) #:transparent)")) 86 | '(struct add (a b) #:transparent)) 87 | 88 | (check-equal? 89 | (s-exp->scheme (peg s-exp 90 | "(define (my-sort lst #:comparator [cmp <]) 91 | (sort lst cmp))")) 92 | '(define (my-sort lst #:comparator [cmp <]) 93 | (sort lst cmp))) 94 | 95 | ;; newline and tab escapes 96 | (check-equal? 97 | (peg s-exp "\"abc\\ndef\"") 98 | "abc\ndef") 99 | (check-equal? 100 | (peg s-exp "\"abc\\tdef\"") 101 | "abc\tdef") 102 | 103 | ;; a test for the special ... symbol 104 | 105 | (check-equal? 106 | (peg s-exp 107 | "(define (eval-rpn l [aux '()]) 108 | (match l 109 | ['() (car aux)] 110 | [(list (? number? a) b ...) (eval-rpn (cdr l) (cons (car l) aux))] 111 | [(list a b ...) (eval-rpn (cdr l) (cons (a (car aux) (cadr aux)) (cddr aux)))]))") 112 | '(define (eval-rpn l [aux '()]) 113 | (match l 114 | ['() (car aux)] 115 | [(list (? number? a) b ...) (eval-rpn (cdr l) (cons (car l) aux))] 116 | [(list a b ...) (eval-rpn (cdr l) (cons (a (car aux) (cadr aux)) (cddr aux)))]))) 117 | -------------------------------------------------------------------------------- /IMPLEMENTATION.md: -------------------------------------------------------------------------------- 1 | # This document describes the internal workings of the PEG parser. 2 | 3 | ## Writing PEGs 4 | 5 | There are 2 ways to make use of the PEG parser: 6 | 7 | * (A) by writing your PEG parsing code in s-expressions with the `peg` scheme macro. 8 | * (B) by writing your PEG parser code in peg syntax using `#lang peg`. 9 | 10 | (B) is implemented by transforming the peg code into version (A) s-expressions, and this is done using a PEG parser. 11 | 12 | ## PEG VM execution 13 | 14 | The execution of a PEG parser on an input string is done using a virtual machine. The state or the registers of the virtual machine as well as all the helper functions which operate directly on them are in `peg.rkt` prefixed with `pegvm-`. 15 | 16 | They store things the input text, the current position in the input text, the alternatives available for backtracking, whether we are inside a negation (which stops peg variables being bound), as well as some extra stuff that is noted down for producing better error messages. 17 | 18 | ## PEG compilation 19 | 20 | The core of the system is the `peg-compile` macro, this transforms a s-expression based PEG parser description into CPS code (continuation passing style), it takes a success continuation as a parameter. So any valid parse will put into result into `sk`, allowing `sk` to return it or to continue parsing and combining that result piece with others. 21 | 22 | Let's look at some specific parts of the implementation with commentary. Hopefully this will help make the system of continuations we used to implement the parser understandable by example. 23 | 24 | ### (epsilon) 25 | 26 | ``` 27 | [(epsilon) 28 | #'(sk empty-sequence)] 29 | ``` 30 | 31 | In this `(epsilon)` rule, parsing always succeeds so we simply call the success continuation straight away. 32 | 33 | ### (and e1 e2) 34 | 35 | ``` 36 | [(and e1 e2) 37 | (with-syntax ([p1 (peg-compile #'e1 #'mk)] 38 | [p2 (peg-compile #'e2 #'sk^)]) 39 | #'(let ((stack-reset (unbox (pegvm-control-stack)))) 40 | (let ((mk (lambda (r1) 41 | (let ((sk^ (lambda (r2) 42 | (sk (peg-result-join r1 r2))))) 43 | (set-box! (pegvm-control-stack) stack-reset) 44 | p2)))) 45 | p1)))] 46 | ``` 47 | 48 | In `(and e1 e2)` we produce code that first tries to parse `e1`. On success it puts the result of that parse into the `mk` continuation named as `r1`. If it failed then a parse error would returned straight away and `mk` would never be called. 49 | 50 | After `e1` parsed successfully we reset the control stack so that any extra alternatives that showed up during the parsing of `e1` are discarded, basically we do a commit to this first successful parse of `e1`. This was introduced to improve efficiency, but users do need to be aware of it. 51 | 52 | Then we attempt to parse the second part of the `and` expression `e2`, putting the result value into `sk^` as `r2`. If that worked we simply invoke `sk` - the ultimate success continuation with the two result objects joined together. 53 | 54 | ### (or e1 e2) 55 | 56 | ``` 57 | [($or e1 e2) 58 | (with-syntax ([p1 (peg-compile #'e1 #'sk)] 59 | [p2 (peg-compile #'e2 #'sk)]) 60 | #'(begin (pegvm-push-alternative! (lambda () p2)) 61 | p1))] 62 | [(or e1 e2) 63 | (with-syntax ([p (peg-compile #'($or e1 e2) #'sk)]) 64 | #'(parameterize ([pegvm-current-choice '(or e1 e2)]) 65 | p))] 66 | ``` 67 | 68 | In its simplest form the `or` just leaves the parsing of `e2` as an alternative option in case `e1` fails. The PEG VM will attempt to execute alternatives in the event of a failure. 69 | 70 | The implementation of `or` was split into two parts at some point though, so that we could take a note of the fact a branch was taken in order to produce improved error messages. 71 | 72 | ### (! e) 73 | 74 | Negation is a rather interesting one to watch, as it basically flips around the success and failure continuations. 75 | 76 | -------------------------------------------------------------------------------- /peg-result.rkt: -------------------------------------------------------------------------------- 1 | #lang racket 2 | 3 | (provide seq-elt seq-elt-object 4 | seq-cat seq-cat-subseqs 5 | seq? 6 | empty-sequence empty-sequence? 7 | seq->dlist seq->list 8 | 9 | peg-result peg-result-str 10 | 11 | peg-result-join 12 | peg-result->object) 13 | 14 | ;;;; 15 | ;; sequences 16 | 17 | (struct seq-elt (object) #:transparent) 18 | (struct seq-cat (subseqs) #:transparent) 19 | (define (seq? x) (or (seq-elt? x) (seq-cat? x))) 20 | 21 | (define empty-sequence (seq-cat '())) 22 | (define (empty-sequence? x) 23 | ;; *** you could cat multiple empty sequences together but that is not 24 | ;; what this function cares about 25 | (and (seq-cat? x) (null? (seq-cat-subseqs x)))) 26 | 27 | (define (seq->dlist seq tail) 28 | (cond ((seq-elt? seq) (cons (seq-elt-object seq) tail)) 29 | ((seq-cat? seq) (foldr seq->dlist tail (seq-cat-subseqs seq))) 30 | (else (error "seq->dlist failed" seq)))) 31 | (define (seq->list seq) (seq->dlist seq '())) 32 | 33 | ;;;; 34 | ;; peg results 35 | 36 | 37 | #| 38 | 39 | ;; Just basic PEG rules 40 | 41 | By default the result of a PEG rule will be the string it matched. 42 | To implement this we make a sequence of peg-result objects, so for example: 43 | 44 | the result of matching the rule 45 | (seq #\f "oo") 46 | on the input "foo" would give 47 | (seq-cat (list (seq-elt "f") (seq-elt "oo"))) 48 | which represents 49 | "foo" 50 | 51 | The function `peg-result->object` turns the representation back into the string, 52 | it does this by transforming the sequence into a list then appending all the 53 | peg-result string objects that are next to each other in the list. 54 | 55 | 56 | ;; Mixing in semantic actions 57 | 58 | The PEG results produced by operators like `and` and `*` build final results out of 59 | partial results using `peg-result-join`. At the end of the parse this can be converted 60 | into a regular scheme object using `peg-result->object`. 61 | 62 | The implementation is complicated by the fact that PEG parsers can also produce scheme 63 | values using semantic actions. For example you might make a `number` rule that matches 64 | strings like `"35"` but producing as its result the number `35`, not just the string. 65 | In that case we need `(* number)` on `"35 66 72"` to produce a list of numbers. 66 | 67 | To achieve this our `peg-result-join` operation has to 68 | * join sequences together 69 | * cons/snoc regular scheme objects onto existing sequences 70 | 71 | Secondly, `peg-result->object` can no longer just join all the peg-result strings in the 72 | result sequence together. It has to leave scheme objects alone! 73 | 74 | It also has a new singletonization rule: A length 1 sequence containing a peg-result string 75 | represents a string, not a length 1 list with a string in it. 76 | 77 | |# 78 | 79 | (struct peg-result (str) #:transparent) 80 | 81 | (define (peg-result-append x y) 82 | (peg-result (string-append (peg-result-str x) (peg-result-str y)))) 83 | 84 | (define (peg-result-join x y) 85 | (cond ((and (seq? x) (seq? y)) 86 | (seq-cat (list x y))) 87 | ((seq? y) 88 | (seq-cat (list (seq-elt x) y))) 89 | ((seq? x) 90 | (seq-cat (list x (seq-elt y)))) 91 | (else 92 | (seq-cat (list (seq-elt x) (seq-elt y)))))) 93 | 94 | (define (peg-result->object x) 95 | (cond ((peg-result? x) (peg-result-str x)) 96 | ((seq? x) (concat-peg-result-strings #t (seq->list x))) 97 | (else x))) 98 | 99 | (define (concat-peg-result-strings singletonize? lst) 100 | (cond ((null? lst) 101 | '()) 102 | ((and (null? (cdr lst)) 103 | singletonize? 104 | (peg-result? (car lst))) 105 | (peg-result-str (car lst))) 106 | ((and (not (null? (cdr lst))) 107 | (peg-result? (car lst)) 108 | (peg-result? (cadr lst))) 109 | (concat-peg-result-strings singletonize? (cons (peg-result-append (car lst) (cadr lst)) (cddr lst)))) 110 | (else 111 | (cons (peg-result->object (car lst)) 112 | (concat-peg-result-strings #f (cdr lst)))))) 113 | 114 | -------------------------------------------------------------------------------- /peg-to-scheme.rkt: -------------------------------------------------------------------------------- 1 | #lang racket 2 | 3 | (require rackunit) 4 | (require racket/trace) 5 | 6 | (require "peg.rkt") 7 | (require "peg-result.rkt") 8 | (require "peg-in-peg.rkt") 9 | 10 | (provide peg->scheme) 11 | 12 | (define (make-and lst) 13 | (cond ((null? lst) (error 'make-and "null")) 14 | ((null? (cdr lst)) (car lst)) 15 | (else `(and . ,lst)))) 16 | 17 | (define (make-or lst) 18 | (cond ((null? lst) (error 'make-or "null")) 19 | ((null? (cdr lst)) (car lst)) 20 | (else `(or . ,lst)))) 21 | 22 | (define (string->char str) 23 | (unless (and (string? str) (= 1 (string-length str))) 24 | (error 'string->char "~a" str)) 25 | (string-ref str 0)) 26 | 27 | (define (peg->scheme p) 28 | (match p 29 | (`(peg . ,grammars) 30 | `(begin . ,(map peg->scheme:grammar grammars))) 31 | (else (error 'peg->scheme "~s" p)))) 32 | 33 | (define (peg->scheme:grammar p) 34 | (define (op? op) 35 | (case op 36 | (("<") 'define-peg/drop) 37 | (("<-") 'define-peg) 38 | (("<--") 'define-peg/tag) 39 | (("<---") 'define-peg/bake) 40 | (else (error 'peg->scheme:grammar "~s" op)))) 41 | (match p 42 | (`(import ,s-exp ";") 43 | `,s-exp) 44 | (`(rule (name . ,nt) ,op ,pat ";") 45 | (let ((op^ (op? op))) 46 | `(,op^ ,(string->symbol nt) ,(peg->scheme:pattern pat)))) 47 | (`(rule (name . ,nt) "<-" ,pat "->" ,sem ";") 48 | `(define-peg ,(string->symbol nt) ,(peg->scheme:pattern pat) ,sem)) 49 | (else (error 'peg->scheme:grammar "~s" p)))) 50 | 51 | (define (peg->scheme:pattern p) 52 | (match p 53 | (`(pattern . ,alternatives) 54 | (make-or (map peg->scheme:alternative alternatives))) 55 | (else (error 'peg->scheme:pattern "~s" p)))) 56 | 57 | (define (peg->scheme:alternative p) 58 | (match p 59 | (`(alternative . ,exps) 60 | (make-and (map peg->scheme:expression exps))) 61 | (else (error 'peg->scheme:alternative "~s" p)))) 62 | 63 | (define (peg->scheme:expression p) 64 | (define (prefix-op? extra) 65 | (case extra 66 | (("!") '!) 67 | (("&") '&) 68 | (("~") 'drop) 69 | (else (error 'peg->scheme:expression "invalid prefix op" extra)))) 70 | (define (op? extra) 71 | (case extra 72 | (("*") '*) 73 | (("+") '+) 74 | (("?") '?) 75 | (else (error 'peg->scheme:expression "invalid op" extra)))) 76 | (define (go negate? prim extra?) 77 | ((lambda (x) (if negate? `(,negate? ,x) x)) 78 | ((lambda (x) (if extra? `(,extra? ,x) x)) 79 | prim))) 80 | (match p 81 | (`(expression (name . ,n) . ,rest) 82 | `(name ,(string->symbol n) ,(peg->scheme:expression `(expression . ,rest)))) 83 | (`(expression ,prim) 84 | (go #f (peg->scheme:primary prim) #f)) 85 | (`(expression ,p-op ,prim) #:when (string? p-op) 86 | (go (prefix-op? p-op) (peg->scheme:primary prim) #f)) 87 | (`(expression ,prim ,extra) 88 | (go #f (peg->scheme:primary prim) (op? extra))) 89 | (`(expression ,p-op ,prim ,extra) #:when (string? p-op) 90 | (go (prefix-op? p-op) (peg->scheme:primary prim) (op? extra))) 91 | (else (error 'peg->scheme:expression "~s" p)))) 92 | 93 | (define (peg->scheme:primary p) 94 | (match p 95 | (`(primary "(" ,pat ")") 96 | (peg->scheme:pattern pat)) 97 | (`(primary . ".") 98 | `(any-char)) 99 | (`(primary literal) 100 | "") 101 | (`(primary literal . ,lit) 102 | lit) 103 | (`(primary charclass "^" . ,cc) 104 | `(and (! ,(make-or (map peg->scheme:cc cc))) (any-char))) 105 | (`(primary charclass . ,cc) 106 | (make-or (map peg->scheme:cc cc))) 107 | (`(primary name . ,nt) 108 | (string->symbol nt)) 109 | (else (error 'peg->scheme:primary "~s" p)))) 110 | 111 | (define (peg->scheme:cc p) 112 | (define (unescape? ch) 113 | (case ch 114 | ((#\[) #\[) 115 | ((#\]) #\]) 116 | ((#\-) #\-) 117 | ((#\^) #\^) 118 | ((#\\) #\\) 119 | ((#\n) #\newline) 120 | ((#\t) #\tab) 121 | (else (error 'peg->scheme:ccrange "escaping a character that need not be escaped: ~s" ch)))) 122 | (define (length-2? str) (and (string? str) (= 2 (string-length str)))) 123 | (match p 124 | (`(cc-single . ,ch) 125 | (string->char ch)) 126 | (`(cc-escape . ,ch) 127 | (unescape? (string->char ch))) 128 | (`(cc-range . ,c1c2) 129 | (unless (length-2? c1c2) 130 | (error 'peg->scheme:cc "invalid char class range ~s" c1c2)) 131 | `(range ,(string-ref c1c2 0) ,(string-ref c1c2 1))) 132 | (else (error 'peg->scheme:cc "~s" p)))) 133 | 134 | ;(trace peg->scheme) 135 | ;(trace peg->scheme:grammar) 136 | ;(trace peg->scheme:pattern) 137 | ;(trace peg->scheme:alternative) 138 | ;(trace peg->scheme:expression) 139 | ;(trace peg->scheme:primary) 140 | -------------------------------------------------------------------------------- /tests/test-json.rkt: -------------------------------------------------------------------------------- 1 | #lang racket 2 | 3 | (require rackunit) 4 | 5 | (require peg) 6 | (require peg/peg-result) 7 | 8 | 9 | (define-peg/drop _ (* (or #\space #\tab #\newline))) 10 | 11 | (define-peg digit (or (char #\0) (call nonzero))) 12 | (define-peg nonzero (range #\1 #\9)) 13 | (define-peg number (or (char #\0) 14 | (name n (and (call nonzero) (* (call digit))))) 15 | (if n (string->number n) 0)) 16 | (define-peg pm-number (and (? (name neg (char #\-))) (name n (call number))) 17 | (if neg (- n) n)) 18 | 19 | 20 | 21 | ;JSON ← S? ( Object / Array / String / True / False / Null / Number ) S? 22 | (define-peg json (and s? (or json-object json-array json-string json-true json-false json-null json-number ) s?)) 23 | 24 | ;Object ← "{" 25 | ; ( String ":" JSON ( "," String ":" JSON )* 26 | ; / S? ) 27 | ;"}" 28 | (define-peg/tag json-object (and (drop "{") 29 | (or (and json-string (drop ":") json (* (and (drop ",") json-string (drop ":") json))) 30 | s?) 31 | (drop "}"))) 32 | 33 | 34 | ;Array ← "[" 35 | ; ( JSON ( "," JSON )* 36 | ; / S? ) 37 | ;"]" 38 | (define-peg/tag json-array (and (drop "[") 39 | (or (and json (* (and (drop ",") json))) 40 | s?) 41 | (drop "]"))) 42 | 43 | ;String ← S? ["] ( [^ " \ U+0000-U+001F ] / Escape )* ["] S? 44 | ;Escape ← [\] ( [ " / \ b f n r t ] / UnicodeEscape ) 45 | (define-peg/tag json-string (and s? 46 | (drop "\"") 47 | (* (and (! "\"") (any-char))) 48 | (drop "\""))) 49 | 50 | (define-peg json-true "true" #t) 51 | (define-peg json-false "false" #f) 52 | (define-peg json-null "null" 'null) 53 | 54 | ;Number ← Minus? IntegralPart FractionalPart? ExponentPart? 55 | ;Minus ← "-" 56 | ;IntegralPart ← "0" / [1-9] [0-9]* 57 | ;FractionalPart ← "." [0-9]+ 58 | ;ExponentPart ← ( "e" / "E" ) ( "+" / "-" )? [0-9]+ 59 | 60 | (define-peg/tag json-number pm-number) 61 | 62 | (define-peg/drop s? _) 63 | 64 | (check-equal? (peg json-object "{ \"name\": \"John\", \"age\": 30,\"car\": null }") 65 | '(json-object (json-string . "name") (json-string . "John") (json-string . "age") (json-number . 30) (json-string . "car") null)) 66 | 67 | ;; couple of tests from http://json.org/example.html 68 | 69 | (check-equal? (peg-result->object (peg json 70 | #<object (peg json 129 | #< 28 | (code:line (epsilon) (code:comment "always succeeds")) 29 | (code:line (char c) (code:comment "matches the character c")) 30 | (code:line (any-char) (code:comment "matches any character")) 31 | (code:line (range c1 c2) (code:comment "match any char between c1 and c2")) 32 | (code:line (string str) (code:comment "matches string str")) 33 | (code:line (and ...) (code:comment "sequence")) 34 | (code:line (or ...) (code:comment "prioritized choice")) 35 | (code:line (* ...) (code:comment "zero or more")) 36 | (code:line (+ ...) (code:comment "one or more")) 37 | (code:line (? ...) (code:comment "zero or one")) 38 | (code:line (call name)) 39 | (code:line (name nm )) 40 | (code:line (! ...) (code:comment "negative lookahead")) 41 | (code:line (& ) (code:comment "positive lookahead")) 42 | (code:line (drop ...) (code:comment "discard the semantic result on matching")) 43 | ])]{ 44 | Defines a new scheme function named @racket[peg-rule:name] by compiling the peg rule into scheme code that interacts with the PEG VM. 45 | 46 | If @racket[action] is supplied, it defines a semantic action to produce the result of the rule. Semantic actions are regular scheme expressions, they can refer to variables named by a @racket[capture]. 47 | } 48 | 49 | We also provide shorthands for some common semantic actions: 50 | 51 | @defform[(define-peg/drop name rule)]{ 52 | @code{= (define-peg rule-name (drop rule))} 53 | 54 | makes the parser produce no result. 55 | } 56 | 57 | @defform[(define-peg/bake name rule)]{ 58 | @code{= (define-peg rule-name (name res rule) res)} 59 | 60 | transforms the peg-result into a scheme object. 61 | } 62 | 63 | @defform[(define-peg/tag name rule)]{ 64 | @code{= (define-peg rule-name (name res exp) `(rule-name . ,res))} 65 | 66 | tags the result with the peg rule name. Useful for parsers that create an AST. 67 | } 68 | 69 | @subsection{peg} 70 | 71 | @defform[(peg rule input) 72 | #:contracts ([input (or/c string? input-port?)])]{ 73 | Runs a PEG parser and attempts to parse @racket[input] using the given @racket[rule]. This sets up the PEG VM registers into an initial state and then calls into the parser for @racket[rule]. 74 | 75 | If @racket[input] is a port, and @racket[(port-counts-lines? input)] returns @racket[#t], then parse errors will be reported at the actual position in the file. Otherwise, reported locations are relative to the point at which parsing started. 76 | } 77 | 78 | @section{Examples} 79 | 80 | @subsection{Example 1} 81 | 82 | For a simple example, lets try splitting a sentence into words. We can describe a word as one or more of non-space characters, optionally followed by a space: 83 | 84 | @codeblock{ 85 | > (require peg) 86 | > (define sentence "the quick brown fox jumps over the lazy dog") 87 | > (define-peg non-space 88 | (and (! #\space) (any-char))) 89 | > (define-peg/bake word 90 | (and (+ non-space) 91 | (drop (? #\space)))) 92 | > (peg word sentence) 93 | "the" 94 | > (peg (+ word) sentence) 95 | '("the" "quick" "brown" "fox" "jumps" "over" "the" "lazy" "dog") 96 | } 97 | 98 | Using the peg lang, the example above is equal to 99 | @verbatim{ 100 | #lang peg 101 | 102 | (define sentence "the quick brown fox jumps over the lazy dog"); //yes, we can use 103 | //one-line comments and any sequence of s-exps BEFORE the grammar definition 104 | 105 | non-space <- (! ' ') . ; //the dot is "any-char" in peg 106 | word <- c:(non-space+ ~(' ' ?)) -> c ; //the ~ is drop 107 | //we can use ident:peg to act as (name ident peg). 108 | //and rule <- exp -> action is equal to (define-peg rule exp action) 109 | //with this in a file, we can use the repl of drracket to do exactly the 110 | //uses of peg above. 111 | } 112 | 113 | 114 | @subsection{Example 2} 115 | 116 | Here is a simple calculator example that demonstrates semantic actions and recursive rules. 117 | 118 | @codeblock{ 119 | (define-peg number (name res (+ (range #\0 #\9))) 120 | (string->number res)) 121 | (define-peg sum 122 | (and (name v1 prod) (? (and #\+ (name v2 sum)))) 123 | (if v2 (+ v1 v2) v1)) 124 | (define-peg prod 125 | (and (name v1 number) (? (and #\* (name v2 prod)))) 126 | (if v2 (* v1 v2) v1)) 127 | } 128 | 129 | this grammar in peg lang is equivalent to: 130 | 131 | @codeblock{ 132 | #lang peg 133 | number <- res:[0-9]+ -> (string->number res); 134 | sum <- v1:prod ('+' v2:sum)? -> (if v2 (+ v1 v2) v1); 135 | prod <- v1:number ('*' v2:prod)? -> (if v2 (* v1 v2) v1); 136 | } 137 | 138 | Usage: 139 | 140 | @codeblock{ 141 | > (peg sum "2+3*4") 142 | 14 143 | > (peg sum "2*3+4") 144 | 10 145 | > (peg sum "7*2+3*4") 146 | 26 147 | } 148 | 149 | @subsection{Example 3} 150 | 151 | Here is an example of parsing balanced parenthesis. It demonstrates a common technique of using @racket[_] for skipping whitespace, and using @racket[define-peg/bake] to produce a list rather than a sequence from a @racket[*]. 152 | 153 | @codeblock{ 154 | #lang racket 155 | (require peg) 156 | 157 | (define-peg/drop _ (* (or #\space #\newline))) 158 | 159 | (define-peg symbol 160 | (and (name res (+ (and (! #\( #\) #\space #\newline) (any-char)))) _) 161 | (string->symbol res)) 162 | 163 | (define-peg/bake sexp 164 | (or symbol 165 | (and (drop #\() (* sexp) (drop #\) _)))) 166 | } 167 | 168 | or in PEG syntax: 169 | 170 | @codeblock{ 171 | #lang peg 172 | _ < [ \n]*; 173 | symbol <- res:(![() \n] .)+ _ -> (string->symbol res); 174 | sexp <- s:symbol / ~'(' s:sexp* ~')' _ -> s; 175 | // had to use s: -> s because there is no way to express bake from the PEG language 176 | } 177 | 178 | Usage: 179 | 180 | @codeblock{ 181 | > (peg sexp "(foob (ar baz)quux)") 182 | '(foob (ar baz) quux) 183 | > (peg sexp "((())(()(())))") 184 | '((()) (() (()))) 185 | > (peg sexp "(lambda (x) (list x (list (quote quote) x)))") 186 | '(lambda (x) (list x (list 'quote x))) 187 | } 188 | 189 | @section{PEG Syntax} 190 | 191 | This package also provides a @racketmodfont{#lang peg} alternative, to allow you to make parsers in a more standard PEG syntax. 192 | 193 | @subsection{PEG Syntax Reference} 194 | 195 | The best way to understand the PEG syntax would be by reference to examples, there are many simple examples in the racket peg repo and the follow is the actual grammar used by racket-peg to implemet the peg lang: 196 | 197 | Note: When you match the empty string in peg lang, the result object is the empty sequence, not the empty string, be careful. 198 | 199 | @verbatim{ 200 | #lang peg 201 | 202 | (require "s-exp.rkt"); 203 | 204 | _ < ([ \t\n] / '//' [^\n]*)*; 205 | SLASH < '/' _; 206 | 207 | name <-- [a-zA-Z_] [a-zA-Z0-9\-_.]* _; 208 | 209 | rule <-- name ('<--' / '<-' / '<') _ pattern ('->' _ s-exp _)? ';' _; 210 | pattern <-- alternative (SLASH alternative)*; 211 | alternative <-- expression+; 212 | expression <-- (name ~':' _)? ([!&~] _)? primary ([*+?] _)?; 213 | primary <-- '(' _ pattern ')' _ / '.' _ / literal / charclass / name; 214 | 215 | literal <-- ~['] (~[\\] ['\\] / !['\\] .)* ~['] _; 216 | 217 | charclass <-- ~'[' '^'? (cc-range / cc-escape / cc-single)+ ~']' _; 218 | cc-range <-- cc-char ~'-' cc-char; 219 | cc-escape <-- ~[\\] .; 220 | cc-single <-- cc-char; 221 | cc-char <- !cc-escape-char . / 'n' / 't'; 222 | cc-escape-char <- '[' / ']' / '-' / '^' / '\\' / 'n' / 't'; 223 | 224 | peg <-- _ import* rule+; 225 | import <-- s-exp _ ';' _; 226 | } 227 | -------------------------------------------------------------------------------- /peg.rkt: -------------------------------------------------------------------------------- 1 | #lang racket 2 | 3 | (provide define-peg 4 | define-peg/bake define-peg/drop define-peg/tag 5 | peg) 6 | 7 | (require (for-syntax racket/syntax syntax/parse)) 8 | (require racket/trace) 9 | (require "push-pop-boxes.rkt") 10 | (require "peg-result.rkt") 11 | 12 | ;;;; 13 | ;; generic utility functions 14 | 15 | (define (char-between? x c1 c2) 16 | (and (<= (char->integer c1) (char->integer x)) 17 | (<= (char->integer x) (char->integer c2)))) 18 | 19 | ;;;; 20 | ;; peg s-exp syntax 21 | 22 | ;; ::= (epsilon) 23 | ;; | (char c) | c 24 | ;; | (any-char) 25 | ;; | (range c1 c2) 26 | ;; | (string str) | str 27 | ;; | (and ...) 28 | ;; | (or ...) 29 | ;; | (* ) 30 | ;; | (+ ) 31 | ;; | (? ) 32 | ;; | (call nm) | nm 33 | ;; | (name nm ) 34 | ;; | (! ) 35 | ;; | (& ) 36 | ;; | (drop ) 37 | 38 | 39 | ;;;; 40 | ;; pegvm registers and dynamic control 41 | 42 | 43 | (define pegvm-input-port (make-parameter #f)) ;; The input port being parsed 44 | (define pegvm-input-position (make-parameter #f)) ;; The offset in bytes from the starting position 45 | (define pegvm-control-stack (make-parameter #f)) ;; For or control flow 46 | (define pegvm-stashed-stacks (make-parameter #f)) ;; For negation control flow 47 | (define pegvm-negation? (make-parameter #f)) ;; How many negations have we entered 48 | 49 | (define pegvm-best-failure (make-parameter #f)) ;; For error messages 50 | (define pegvm-current-rule (make-parameter #f)) 51 | (define pegvm-current-choice (make-parameter #f)) 52 | 53 | (struct control-frame (position label) #:transparent) 54 | 55 | (define (pegvm-advance! n) (set-box! (pegvm-input-position) (+ (unbox (pegvm-input-position)) n))) 56 | (define (pegvm-push-alternative! alt) (push! (pegvm-control-stack) (control-frame (unbox (pegvm-input-position)) alt))) 57 | (define (pegvm-fail) 58 | (pegvm-update-best-error!) 59 | (let ((cf (pop! (pegvm-control-stack)))) 60 | (when (control-frame-position cf) 61 | (set-box! (pegvm-input-position) (control-frame-position cf))) 62 | ((control-frame-label cf)))) 63 | (define (pegvm-enter-negation!) 64 | (set-box! (pegvm-negation?) (+ (unbox (pegvm-negation?)) 1)) 65 | (push! (pegvm-stashed-stacks) (unbox (pegvm-control-stack))) 66 | (set-box! (pegvm-control-stack) '())) 67 | (define (pegvm-exit-negation!) 68 | (set-box! (pegvm-negation?) (- (unbox (pegvm-negation?)) 1)) 69 | (set-box! (pegvm-control-stack) (pop! (pegvm-stashed-stacks)))) 70 | 71 | (define (pegvm-update-best-error!) 72 | (when (or (not (unbox (pegvm-best-failure))) 73 | (> (unbox (pegvm-input-position)) (car (unbox (pegvm-best-failure))))) 74 | (let ((pos (unbox (pegvm-input-position)))) 75 | (set-box! (pegvm-best-failure) (list pos (pegvm-current-rule) (pegvm-current-choice)))))) 76 | 77 | (define (calculate-line-and-column in pos) 78 | (define-values (start-line start-col start-pos) 79 | (port-next-location in)) 80 | (define str 81 | (bytes->string/utf-8 82 | (peek-bytes pos 0 in))) 83 | (let ((line (or start-line 1)) 84 | (col (or start-col 0))) 85 | (for ((chr (in-string str 0 pos))) 86 | (if (equal? chr #\newline) 87 | (begin (set! line (+ line 1)) 88 | (set! col 0)) 89 | (begin (set! col (+ 1 col))))) 90 | `(line ,line column ,col))) 91 | 92 | ;;;; 93 | ;; peg compiler 94 | 95 | (define-for-syntax (peg-names exp) 96 | (syntax-parse exp 97 | #:datum-literals (epsilon char any-char range string and or * + ? call name ! drop) 98 | [(and e1) (peg-names #'e1)] 99 | [(and e1 e2) (append (peg-names #'e1) (peg-names #'e2))] 100 | [(and e1 e2 . e3) (append (peg-names #'e1) (peg-names #'(and e2 . e3)))] 101 | [(or e1 ...) (peg-names #'(and e1 ...))] 102 | [(* e1 ...) (peg-names #'(and e1 ...))] 103 | [(+ e1 ...) (peg-names #'(and e1 ...))] 104 | [(? e1 ...) (peg-names #'(and e1 ...))] 105 | [(name nm subexp) (cons #'nm (peg-names #'subexp))] 106 | [(drop e1 ...) (peg-names #'(and e1 ...))] 107 | [else '()])) 108 | 109 | (define-for-syntax (peg-compile exp sk) 110 | (define (single-char-pred sk x cond) 111 | (with-syntax ([sk sk] [x x] [cond cond]) 112 | #'(let ((x (peek-char (pegvm-input-port) (unbox (pegvm-input-position))))) 113 | (if (or (eof-object? x) (not cond)) 114 | (pegvm-fail) 115 | (begin (pegvm-advance! (char-utf-8-length x)) 116 | (sk (peg-result (string x)))))))) 117 | (with-syntax ([sk sk]) 118 | (syntax-parse exp 119 | #:datum-literals (epsilon char any-char range string and or * + ? call name ! drop $or) 120 | [(epsilon) 121 | #'(sk empty-sequence)] 122 | [(char c) 123 | (single-char-pred #'sk #'x #'(char=? c x))] 124 | [(any-char) 125 | (single-char-pred #'sk #'x #t)] 126 | [(range c1 c2) 127 | (single-char-pred #'sk #'x #'(char-between? x c1 c2))] 128 | [(string str) 129 | (with-syntax ([str-len (string-length (syntax->datum #'str))]) 130 | #'(let ((x (peek-string str-len (unbox (pegvm-input-position)) (pegvm-input-port)))) 131 | (if (or (eof-object? x) (not (string=? str x))) 132 | (pegvm-fail) 133 | (begin (pegvm-advance! (string-utf-8-length str)) 134 | (sk (peg-result str))))))] 135 | [(and e1) 136 | (peg-compile #'e1 #'sk)] 137 | [(and e1 e2) 138 | (with-syntax ([p1 (peg-compile #'e1 #'mk)] 139 | [p2 (peg-compile #'e2 #'sk^)]) 140 | #'(let ((stack-reset (unbox (pegvm-control-stack)))) 141 | (let ((mk (lambda (r1) 142 | (let ((sk^ (lambda (r2) 143 | (sk (peg-result-join r1 r2))))) 144 | (set-box! (pegvm-control-stack) stack-reset) 145 | p2)))) 146 | p1)))] 147 | [(and e1 e2 e3 ...) 148 | (peg-compile #'(and e1 (and e2 e3 ...)) #'sk)] 149 | ; [(and e1 e2 e3 ...) 150 | ; (peg-compile #'(and (and e1 e2) e3 ...) #'sk)] 151 | [($or e1 e2) 152 | (with-syntax ([p1 (peg-compile #'e1 #'sk)] 153 | [p2 (peg-compile #'e2 #'sk)]) 154 | #'(begin (pegvm-push-alternative! (lambda () p2)) 155 | p1))] 156 | [(or e1) 157 | (peg-compile #'e1 #'sk)] 158 | [(or e1 e2) 159 | (with-syntax ([p (peg-compile #'($or e1 e2) #'sk)]) 160 | #'(parameterize ([pegvm-current-choice '(or e1 e2)]) 161 | p))] 162 | [(or e1 e2 e3 ...) 163 | (with-syntax ([p (peg-compile #'($or e1 (or e2 e3 ...)) #'sk)]) 164 | #'(parameterize ([pegvm-current-choice '(or e1 e2 e3 ...)]) 165 | p))] 166 | [(* e) 167 | (with-syntax ([p (peg-compile #'e #'s+)]) 168 | #'(letrec ((s* (lambda (res-acc) 169 | (pegvm-push-alternative! (lambda () (sk res-acc))) 170 | (let ((s+ (lambda (res) 171 | (s* (peg-result-join res-acc res))))) 172 | p)))) 173 | (s* empty-sequence)))] 174 | [(* e1 e2 ...) 175 | (peg-compile #'(* (and e1 e2 ...)) #'sk)] 176 | [(+ e) 177 | (peg-compile #'(and e (* e)) #'sk)] 178 | [(+ e1 e2 ...) 179 | (peg-compile #'(+ (and e1 e2 ...)) #'sk)] 180 | [(? e) 181 | (with-syntax ([p (peg-compile #'e #'sk)]) 182 | #'(begin (pegvm-push-alternative! (lambda () (sk empty-sequence))) 183 | p))] 184 | [(? e1 e2 ...) 185 | (peg-compile #'(? (and e1 e2 ...)) #'sk)] 186 | [(call rule-name) 187 | (with-syntax ([rule (format-id #'rule-name "peg-rule:~a" #'rule-name)]) 188 | #'(rule sk))] 189 | [(name nm e) 190 | (with-syntax ([p (peg-compile #'e #'sk^)]) 191 | #'(let ((sk^ (lambda (r) 192 | (when (= 0 (unbox (pegvm-negation?))) 193 | (set! nm (peg-result->object r))) 194 | (sk r)))) 195 | p))] 196 | ; [(transform e code) 197 | ; (with-syntax ([p (peg-compile #'e #'sk^)]) 198 | ; #'(let ((sk^ (lambda (r) 199 | ; (sk code)))) 200 | ; p))] 201 | [(! e) 202 | (with-syntax ([p (peg-compile #'e #'sk^)]) 203 | #'(let ((sk^ (lambda (_) 204 | (pegvm-exit-negation!) 205 | (pegvm-fail))) 206 | (fk (lambda () 207 | (pegvm-exit-negation!) 208 | (sk empty-sequence)))) 209 | (pegvm-enter-negation!) 210 | (pegvm-push-alternative! fk) 211 | p))] 212 | [(! e1 e2 ...) 213 | (peg-compile #'(and (! e1) (! e2) ...) #'sk)] 214 | [(drop e) 215 | (with-syntax ([p (peg-compile #'e #'sk^)]) 216 | #'(let ((sk^ (lambda (_) (sk empty-sequence)))) 217 | p))] 218 | [(drop e1 e2 ...) 219 | (peg-compile #'(drop (and e1 e2 ...)) #'sk)] 220 | [(& e) (peg-compile #'(! (! e)) #'sk)] 221 | [_ (let ((shorthand (syntax-e exp))) 222 | (cond ((char? shorthand) (peg-compile #`(char #,exp) #'sk)) 223 | ((string? shorthand) (peg-compile #`(string #,exp) #'sk)) 224 | ((symbol? shorthand) (peg-compile #`(call #,exp) #'sk)) 225 | (else (raise-syntax-error "invalid peg" (syntax->datum exp)))))]))) 226 | 227 | (define-syntax (define-peg stx) 228 | (define (make-binding nm) 229 | (with-syntax ([nm nm]) #'(nm #f))) 230 | (syntax-case stx () 231 | [(_ rule-name exp) 232 | #'(define-peg rule-name exp #f #f)] 233 | [(_ rule-name exp action) 234 | #'(define-peg rule-name exp action #t)] 235 | [(_ rule-name exp action has-action?) 236 | (with-syntax ([name (format-id #'rule-name "peg-rule:~a" (syntax-e #'rule-name))] 237 | [bindings (map make-binding (peg-names #'exp))] 238 | [body (peg-compile #'exp #'sk^)] 239 | [action (if (syntax-e #'has-action?) #'action #'res)]) 240 | #'(define (name sk) 241 | (parameterize ([pegvm-current-rule 'name]) 242 | (let* bindings 243 | (let ((sk^ (lambda (res) (sk action)))) 244 | body)))))])) 245 | 246 | (define-syntax (define-peg/drop stx) 247 | (syntax-case stx () [(_ rule-name exp) #'(define-peg rule-name (drop exp))])) 248 | 249 | (define-syntax (define-peg/bake stx) 250 | (syntax-case stx () [(_ rule-name exp) #'(define-peg rule-name (name res exp) res)])) 251 | 252 | (define-syntax (define-peg/tag stx) 253 | (syntax-case stx () [(_ rule-name exp) #'(define-peg rule-name (name res exp) (cons 'rule-name res))])) 254 | 255 | (define (copy-and-pad-substring/port in pos left right) 256 | (define before 257 | (bytes->string/utf-8 258 | (peek-bytes pos 0 in))) 259 | (define after 260 | (let ((str (peek-string right pos in))) 261 | (if (eof-object? str) "" str))) 262 | (let ((pos^ (string-length before)) 263 | (str (string-append before after))) 264 | (copy-and-pad-substring str (- pos^ left) (+ pos^ right)))) 265 | 266 | (define (copy-and-pad-substring str a b) 267 | ;; pad with spaces 268 | (let ((res (make-string (- b a) #\space)) 269 | (len (string-length str))) 270 | (let ((left-padding (max 0 (- a)))) ;; are we going off the left end of the string (is a negative) 271 | (string-copy! res left-padding str (max 0 a) (min len b)) 272 | res))) 273 | 274 | ;(check-equal? (copy-and-pad-substring "abcdefghijklmnopqrstuvwxyz" -2 3) 275 | ; " abc") 276 | ;(check-equal? (copy-and-pad-substring "abcdefghijklmnopqrstuvwxyz" -1 3) 277 | ; " abc") 278 | ;(check-equal? (copy-and-pad-substring "abcdefghijklmnopqrstuvwxyz" 0 3) 279 | ; "abc") 280 | ;(check-equal? (copy-and-pad-substring "abcdefghijklmnopqrstuvwxyz" 1 3) 281 | ; "bc") 282 | ;(check-equal? (copy-and-pad-substring "abcdefghijklmnopqrstuvwxyz" 2 3) 283 | ; "c") 284 | ;(check-equal? (copy-and-pad-substring "abcdefghijklmnopqrstuvwxyz" 26 30) 285 | ; " ") 286 | ;(check-equal? (copy-and-pad-substring "abcdefghijklmnopqrstuvwxyz" 25 30) 287 | ; "z ") 288 | ;(check-equal? (copy-and-pad-substring "abcdefghijklmnopqrstuvwxyz" 24 30) 289 | ; "yz ") 290 | 291 | (define-syntax (peg stx) 292 | (syntax-case stx () 293 | [(_ exp src) #'(peg exp src #f)] 294 | [(_ exp src v) 295 | #'(let ((fail-cont (lambda () 296 | (let ((loc (car (unbox (pegvm-best-failure))))) 297 | (display (string-replace (string-replace (copy-and-pad-substring/port (pegvm-input-port) loc 10 10) 298 | "\n" "N") "\t" "T")) 299 | (newline) 300 | (display " ^ here") 301 | (newline)) 302 | (error 'peg "parse failed in rule ~a at location ~a with options ~v" 303 | (cadr (unbox (pegvm-best-failure))) 304 | (calculate-line-and-column (pegvm-input-port) (car (unbox (pegvm-best-failure)))) 305 | (caddr (unbox (pegvm-best-failure))) 306 | ))) 307 | (success-cont peg-result->object)) 308 | (define-peg local exp) 309 | (define in 310 | (let ((src-v src)) 311 | (cond 312 | [(string? src-v) (open-input-string src-v)] 313 | [(port? src-v) src-v]))) 314 | (parameterize ([pegvm-input-port in] 315 | [pegvm-input-position (box 0)] 316 | [pegvm-control-stack (box (list (control-frame #f fail-cont)))] 317 | [pegvm-stashed-stacks (box '())] 318 | [pegvm-negation? (box 0)] 319 | [pegvm-best-failure (box #f)]) 320 | (begin0 (peg-rule:local success-cont) 321 | (port-commit-peeked (unbox (pegvm-input-position)) 322 | (port-progress-evt in) 323 | always-evt 324 | in))))])) 325 | 326 | 327 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------