-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.rkt
45 lines (32 loc) · 1.13 KB
/
parser.rkt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#lang typed/racket
(require "utilities.rkt")
(provide S-Exp s-exp? trans parse untrans unparse)
;; (define-type Literal (U Boolean Real Symbol Char String))
(define-type Literal Fixnum)
(define-type S-List (Listof S-Exp))
(define-type S-Exp (U Symbol Literal S-List))
(define-predicate s-exp? S-Exp)
(define-predicate s-list? S-List)
(: trans [-> S-Exp Exp])
(define trans
(λ (code)
(match code
[(? fixnum? x) (Int x)]
[(? symbol? v) (Var v)]
['(read) (Prim 'read '())]
[`(- ,(? s-exp? e)) (Prim '- (list (trans e)))]
[`(+ ,(? s-exp? e1) ,(? s-exp? e2)) (Prim '+ (list (trans e1) (trans e2)))]
[`(let ([,(? symbol? v) ,(? s-exp? e)]) ,(? s-exp? body))
(Let v (trans e) (trans body))])))
(: parse [-> S-Exp Program])
(define parse (λ (code) (Program '() (trans code))))
(: untrans [-> Exp S-Exp])
(define untrans
(λ (exp)
(define-values (in out) (make-pipe))
(parameterize ([port-count-lines-enabled #t])
(write-ast exp out)
(close-output-port out)
(assert (read in) s-exp?))))
(: unparse [-> Program S-Exp])
(define unparse (λ (prog) (untrans (Program-body prog))))