This repository has been archived by the owner on Sep 18, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
helper.scm
95 lines (79 loc) · 2.41 KB
/
helper.scm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
(def var-counter 0)
(defn generate-var ()
(set! var-counter (add1 var-counter))
(string-append "%tmp"
(fixnum->string var-counter)))
(def label-count 0)
(defn unique-label (name)
(set! label-count (add1 label-count))
(format "L~A_~A"(list label-count name)))
(defn arg-str (arity)
(cond
((eq? arity 0) "")
((eq? arity 1) "i64")
(else
(~>> arity sub1 arg-str (string-append "i64, ")))))
(defn var-str (vars)
(~>> vars
(map (fn (a) (string-append "i64 " a)))
(join ", ")))
(defn escape-char (char) char
(cond
((eq? char #\+) "_plus_")
((eq? char #\>) "_greater_")
((eq? char #\<) "_less_")
((eq? char #\=) "_equal_")
((eq? char #\*) "_times_")
((eq? char #\/) "_slash_")
((eq? char #\?) "_questionmark_")
(else (char->string char))))
(defn escape (str)
(~>> str any->string string->list
(map escape-char)
(cons "prim_")
(join "")))
(defn tagged-list? (expr tag)
(and (pair? expr) (eq? (fst expr) tag)))
(defn map-with-index (f lst) (map-with-index_ f 0 lst))
(defn map-with-index_ (f start lst)
(if (null? lst)
lst
(cons
(f (fst lst) start)
(map-with-index_ f (add1 start) (rst lst)))))
(defn empty-set () '())
(defn singleton-set (expr) (list expr))
(defn set-subtract (a b)
(filter (fn (e) (not (member? e b)))
a))
(defn set-union (a b)
(cond
((null? a) b)
((null? b) a)
((member? (fst b) a)
(set-union a (rst b)))
(else
(set-union (cons (fst b) a) (rst b)))))
(defn set-union* (sets)
(cond
((null? sets) sets)
((null? (rst sets)) (fst sets))
(else (set-union*
(cons (set-union (fst sets) (frst sets))
(rrst sets))))))
(def empty-env '())
(defn extend-env (var val env)
(alist-cons var val env))
(defn extend-env* (vars vals env)
(if (null? vars)
env
(extend-env* (rst vars) (rst vals)
(extend-env (fst vars) (fst vals) env))))
(defn lookup (var env)
(let ((res (assoc var env)))
(if res
(rst res)
(error "Trying to lookup unbound variable: " var))))
(defn lookup-or (var alt env)
(let ((res (assoc var env)))
(if res (rst res) alt)))