-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpython-lib.rkt
83 lines (63 loc) · 2.52 KB
/
python-lib.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
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
#lang plai-typed
(require "python-core-syntax.rkt")
#|
Here is a suggestion for how to implement shared runtime functionality -
write it as core expression forms and use python-lib to wrap your
desugared expressions in an environment that will contain useful
bindings. For example, this sample library binds `print` to a function
that calls the primitive `print`.
|#
(define-type-alias Lib (CExp -> CExp))
(define print-lambda
(CFunc (list 'to-print)
(CPrim1 'print (list (CId 'to-print)))))
(define assert-true-lambda
(CFunc (list 'check-true)
(CIf (CId 'check-true) (CTrue) (CPrim1 'print (list (CError (CStr "Assert failed")))))))
(define assert-equal-lambda
(CFunc (list 'check-equal1 'check-equal2)
(CIf (CPrimP (CId 'check-equal1) '== (CId 'check-equal2))
(CTrue)
(CPrim1 'print (list (CError (CStr "Assert failed")))))))
;(define assert-raises-lambda
; (CFunc (list 'check-raises 'error-func)
; (CPrimP (
(define true-val
(CFunc (list 'check-truthy)
(CPrim1 'True (list (CId 'check-truthy)))))
(define type-lambda
(CFunc (list 'check-type)
(CPrim1 'type (list (CId 'check-type)))))
(define get-length
(CFunc (list 'check-length)
(CIf (CPrimP (CPrim1 'type (list (CId 'check-length))) '== (CStr "list"))
(CPrim1 'len (list (CId 'check-length)))
(CPrim1 'print
(list (CError (CPrimP (CStr "object of type ") '+ (CPrimP (CPrim1 'type (list (CId 'check-length))) '+ (CStr " has no len()")))))))))
(define pop-lambda
(CFunc (list 'lst 'index)
(CPrim1 'pop (list (CId 'lst) (CId 'index)))))
(define raise-exception
(CFunc (list 'err-msg)
(CError (CId 'err-msg))))
(define-type LibBinding
[bind (left : symbol) (right : CExp)])
(define lib-functions
(list (bind 'print print-lambda)
(bind 'True true-val)
(bind '___assertTrue assert-true-lambda)
(bind '___assertEqual assert-equal-lambda)
;(bind '___assertRaises assert-raises-lambda)
(bind 'type type-lambda)
(bind 'len get-length)
(bind 'pop pop-lambda)
(bind 'Exception raise-exception)
))
(define python-lib
(local [(define (python-lib/recur libs bindings)
(cond [(empty? libs) bindings]
[(cons? libs)
(type-case LibBinding (first libs)
(bind (name value)
(python-lib/recur (rest libs) (hash-set bindings name value))))]))]
(python-lib/recur lib-functions (hash empty))))