forked from yuyang0/iu-p423
-
Notifications
You must be signed in to change notification settings - Fork 0
/
compiler.rkt
45 lines (37 loc) · 1.25 KB
/
compiler.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
#lang racket
(require racket/fixnum)
(require "interp.rkt")
;; This exports r0-passes, defined below, to users of this file.
(provide r0-passes)
;; The following pass is just a silly pass that doesn't change anything important,
;; but is nevertheless an example of a pass. It flips the arguments of +. -Jeremy
(define (flipper e)
(match e
[(? fixnum?) e]
[`(read) `(read)]
[`(- ,e1) `(- ,(flipper e1))]
[`(+ ,e1 ,e2) `(+ ,(flipper e2) ,(flipper e1))]
[`(program ,e) `(program ,(flipper e))]
))
;; Next we have the partial evaluation pass described in the book.
(define (pe-neg r)
(cond [(fixnum? r) (fx- 0 r)]
[else `(- ,r)]))
(define (pe-add r1 r2)
(cond [(and (fixnum? r1) (fixnum? r2)) (fx+ r1 r2)]
[else `(+ ,r1 ,r2)]))
(define (pe-arith e)
(match e
[(? fixnum?) e]
[`(read) `(read)]
[`(- ,e1) (pe-neg (pe-arith e1))]
[`(+ ,e1 ,e2) (pe-add (pe-arith e1) (pe-arith e2))]
[`(program ,e) `(program ,(pe-arith e))]
))
;; Define the passes to be used by interp-tests and the grader
;; Note that your compiler file (or whatever file provides your passes)
;; should be named "compiler.rkt"
(define r0-passes
`( ("flipper" ,flipper ,interp-scheme)
("partial evaluator" ,pe-arith ,interp-scheme)
))