compiles to bytecode, fails to load
[software/python-on-guile.git] / modules / language / python / module / python.scm
1 (define-module (language python module python)
2 #:use-module (oop goops)
3 #:use-module (ice-9 match)
4 #:use-module (ice-9 readline)
5 #:use-module ((oop pf-objects) #:select
6 (<p> <property> class-method static-method ref
7 py-super-mac type object pylist-ref define-python-class
8 object-method))
9 #:use-module (language python exceptions )
10 #:use-module ((language python module string ) #:select ())
11 #:use-module (language python def )
12 #:use-module (language python for )
13 #:use-module (language python try )
14 #:use-module (language python yield )
15 #:use-module (language python list )
16 #:use-module (language python dict )
17 #:use-module (language python set )
18 #:use-module (language python compile )
19 #:use-module (language python string )
20 #:use-module (language python bytes )
21 #:use-module (language python set )
22 #:use-module (language python number )
23 #:use-module (language python dir )
24 #:use-module (language python hash )
25 #:use-module (language python property )
26 #:use-module (language python range )
27 #:use-module (language python tuple )
28 #:use-module (language python eval )
29 #:use-module (language python bool )
30
31 #:replace (list abs min max hash round format)
32
33 #:re-export (StopIteration GeneratorExit RuntimeError
34 Exception ValueError TypeError
35 IndexError KeyError AttributeError
36 send sendException next
37 GeneratorExit sendClose RuntimeError
38 SyntaxError bool
39 len dir next dict None property range
40 tuple bytes bytearray eval locals globals
41 compile exec type object
42 )
43
44 #:export (print repr complex float int str
45 set all any bin callable reversed
46 chr classmethod staticmethod objectmethod
47 divmod enumerate filter open
48 getattr hasattr setattr hex isinstance issubclass
49 iter map sum id input oct ord pow super
50 sorted zip
51 ClassMethod StaticMethod Funcobj))
52
53 (define-syntax-rule (aif it p x y) (let ((it p)) (if it x y)))
54
55 (define (path-it path)
56 (aif it (ref path '__fspath__)
57 (it)
58 path))
59
60 (define print
61 (case-lambda
62 (() ((@ (guile) format) #t "~%"))
63 ((x) ((@ (guile) format) #t "~s~%" x))
64 (l ((@ (guile) format) #t "~s~%" l))))
65
66 (define (repr x) ((@ (guile) format) #f "~a" x))
67 (define abs py-abs)
68 (define str pystring)
69 (define complex py-complex)
70 (define float py-float)
71 (define int py-int)
72 (define round py-round)
73 (define set py-set)
74 (define all py-all)
75 (define any py-any)
76 (define bin py-bin)
77 (define divmod py-divmod)
78 (define format py-format)
79 (define hash py-hash)
80 (define hex py-hex)
81
82 (define-method (callable x ) #f)
83 (define-method (callable (x <procedure> )) #t)
84 (define-method (callable (x <procedure-class> )) #t)
85 (define-method (callable (x <applicable> )) #t)
86 (define-method (callable (x <primitive-generic>)) #t)
87 (define-method (callable (x <p>))
88 (ref x '__call__))
89
90 (define chr integer->char)
91
92 (define objectmethod object-method)
93 (define classmethod class-method)
94 (define staticmethod static-method)
95
96 (define (enumerate l)
97 ((make-generator ()
98 (lambda (yield)
99 (for ((x : l)) ((i 0))
100 (yield i x)
101 (+ i 1))))))
102
103 (define (filter f l)
104 ((make-generator ()
105 (lambda (yield)
106 (for ((x : l)) ()
107 (if (f x)
108 (yield x)))))))
109
110 (define miss ((@ (guile) list) 'miss))
111
112 (define* (getattr a b #:optional (k miss))
113 (let ((r (ref a (if (string? b) (string->symbol b) b) k)))
114 (if (eq? r miss)
115 (raise AttributeError "object/class ~a is missing attribute ~a" a b)
116 r)))
117
118 (define (setattr a k v)
119 (set a (if (string? k) (string->symbol k) k) v))
120
121 (define (hasattr a b)
122 (let ((r (ref a (symbol->string b) miss)))
123 (not (eq? r miss))))
124
125 (define-method (issubclass x y) #f)
126 (define-method (issubclass (sub <p>) (cls <p>))
127 (aif it (ref cls '__subclasscheck__)
128 (it cls sub)
129 (if (eq? sub cls)
130 #t
131 (is-a? (ref sub '__goops__) (ref cls '__goops__)))))
132
133 (define-method (isinstance x y) #f)
134 (define-method (isinstance (o <p>) (cl <p>))
135 (aif it (ref cl '__instancecheck__)
136 (it o)
137 (if (pair? cl)
138 (or
139 (isinstance o (car cl))
140 (isinstance o (cdr cl)))
141 (is-a? o (ref cl '__goops__)))))
142
143 (define iter
144 (case-lambda
145 ((o) (aif it (wrap-in o)
146 it
147 (aif get (ref o '__getitem__)
148 (make-generator iter
149 (lambda (yield)
150 (for () ((i 0))
151 (yield (get i))
152 (+ i 1))))
153 (raise TypeError "not iterable" o))))
154 ((f sent)
155 (make-generator iter
156 (lambda (yield)
157 (for () ()
158 (let ((r (f)))
159 (if (equal? r sent)
160 (break)
161 (yield r)))))))))
162
163
164
165 (define-syntax map
166 (lambda (x)
167 (syntax-case x ()
168 ((map f a ...)
169 (with-syntax (((x ...) (generate-temporaries #'(a ...))))
170 #'(for ((x : a) ...) ((l '()))
171 (cons (f x ...) l)
172 #:final (py-list (reverse l))))))))
173
174 (define* (sum i #:optional (start 0))
175 (for ((x : i)) ((s start))
176 (+ s x)
177 #:final
178 s))
179
180
181 (define (id x) (object-address x))
182
183 (define (input str)
184 (format #t str)
185 (readline))
186
187 (define (idx x) x)
188
189 (def (py-min (* l) (= key idx) (= default miss))
190 (let lp ((l l))
191 (match l
192 ((it)
193 (for ((x : it)) ((s miss) (b miss))
194 (if (eq? s miss)
195 (values (key x) x)
196 (let ((k (key x)))
197 (if (< k s)
198 (values k x)
199 (values s b))))
200 #:final
201 (if (eq? b miss)
202 (if (eq? default miss)
203 (raise ValueError
204 "min does not work for zero length list")
205 default)
206 b)))
207 (_ (lp ((@ (guile) list) l))))))
208
209 (def (py-max (* l) (= key idx) (= default miss))
210 (let lp ((l l))
211 (match l
212 ((it)
213 (for ((x : it)) ((s miss) (b miss))
214 (if (eq? s miss)
215 (values (key x) x)
216 (let ((k (key x)))
217 (if (> k s)
218 (values k x)
219 (values s b))))
220 #:final
221 (if (eq? b miss)
222 (if (eq? default miss)
223 (raise ValueError
224 "min does not work for zero length list")
225 default)
226 b)))
227 (_ (lp ((@ (guile) list) l))))))
228
229 (define (oct x) (+ "0o" (number->string (py-index x) 8)))
230 (define (ord x) (char->integer (string-ref (pylist-ref x 0) 0)))
231
232 (define pow
233 (case-lambda
234 ((x y)
235 (expt x y))
236 ((x y z)
237 (py-mod (expt x y) z))))
238
239 (define-syntax-rule (super . l) (py-super-mac . l))
240
241 (define min py-min)
242 (define max py-max)
243 (define list pylist)
244 (define reversed py-reversed)
245 (define (key-id x) x)
246 (define* (sorted it #:key (key key-id) (reverse #f))
247 (define l (to-pylist '()))
248 (for ((x : it)) () (pylist-append! l x))
249 (pylist-sort! l #:key key #:reverse reverse)
250 l)
251
252 (define (zip . l)
253 (let ((l ((@ (guile) map) wrap-in l)))
254 ((make-generator ()
255 (lambda (yield)
256 (let lp ()
257 (let lp2 ((l l) (r '()))
258 (if (pair? l)
259 (call-with-values (lambda () (next (car l)))
260 (lambda z
261 (lp2 (cdr l) (append (reverse z) r))))
262 (begin
263 (yield (reverse r))
264 (lp))))))))))
265
266 (define DEFAULT_BUFFER_SIZE 4096)
267 (def (open path
268 (= mode "r")
269 (= buffering -1 )
270 (= encoding None)
271 (= errors None)
272 (= newline None)
273 (= closefd #t)
274 (= opener None))
275
276 (define modelist (string->list mode))
277 (define path (path-it path))
278 (define (clean ch l)
279 (filter (lambda (c) (not (eq? ch c))) l))
280 (let ((port (if (number? path)
281 (begin
282 (if (member #\a modelist)
283 (seek path 0 SEEK_END))
284 (if (member #\x modelist)
285 (error "cannot use mode 'x' for fd input"))
286 (cond
287 ((member #\r modelist)
288 (fdes->inport path))
289 ((member #\w modelist)
290 (fdes->outport path))))
291 (begin
292 (if (member #\x modelist)
293 (if (file-exists? path)
294 (raise OSError "mode='x' and file exists")
295 (set mode (list->string
296 (clean #\x modelist)))))
297 ((@ (guile) open-file) (path-it path) mode)))))
298
299 (case buffering
300 ((-1)
301 (setvbuf port 'block DEFAULT_BUFFER_SIZE))
302 ((0)
303 (setvbuf port 'none))
304 ((1)
305 (setvbuf port 'line))
306 (else
307 (setvbuf port 'block buffering)))
308
309 port))
310
311
312 (define-python-class ClassMethod ())
313 (define-python-class StaticMethod ())
314 (define-python-class Funcobj ())
315
316
317
318
319