Debian Codegraph @

src/libalpha.scm

raw
1 ;;;
2 ;;; libalpha.scm - Procedures needed by other lib*.scm
3 ;;;
4 ;;; Copyright (c) 2000-2024 Shiro Kawai <[email protected]>
5 ;;;
6 ;;; Redistribution and use in source and binary forms, with or without
7 ;;; modification, are permitted provided that the following conditions
8 ;;; are met:
9 ;;;
10 ;;; 1. Redistributions of source code must retain the above copyright
11 ;;; notice, this list of conditions and the following disclaimer.
12 ;;;
13 ;;; 2. Redistributions in binary form must reproduce the above copyright
14 ;;; notice, this list of conditions and the following disclaimer in the
15 ;;; documentation and/or other materials provided with the distribution.
16 ;;;
17 ;;; 3. Neither the name of the authors nor the names of its contributors
18 ;;; may be used to endorse or promote products derived from this
19 ;;; software without specific prior written permission.
20 ;;;
21 ;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 ;;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 ;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24 ;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25 ;;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26 ;;; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
27 ;;; TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
28 ;;; PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
29 ;;; LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
30 ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
31 ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 ;;;
33
34 ;; This file is initialized first among lib-*.scm. Define procedures
35 ;; here that are required to run initialization of other lib-*.scm files.
36
37 (select-module gauche.internal)
38
39 (inline-stub
40 (.include "gauche/priv/configP.h"
41 "gauche/vminsn.h"
42 "gauche/vm.h"
43 "gauche/priv/glocP.h"
44 "gauche/priv/macroP.h"
45 "gauche/priv/procP.h"
46 "gauche/priv/vmP.h"))
47
48 ;; This is referred from the compiled code of toplevel definitions, so
49 ;; we need it before anything else.
50 (select-module gauche.internal)
51 (define-cproc %expression-name-mark-key ()
52 (return (Scm__GetDenvKey SCM_DENV_KEY_EXPRESSION_NAME)))
53 (define-cproc %exception-handler-mark-key ()
54 (return (Scm__GetDenvKey SCM_DENV_KEY_EXCEPTION_HANDLER)))
55
56 ;;;
57 ;;; errors
58 ;;;
59
60 (select-module gauche.internal)
61 (define (%error-scan-keys args)
62 (let loop ([args args] [keys '()])
63 (if (and (not (null? args))
64 (keyword? (car args))
65 (not (null? (cdr args))))
66 (loop (cddr args) (list* (cadr args) (car args) keys))
67 (values (reverse! keys) args))))
68
69 (define (%make-error-message msg args) ; SRFI-23 style message
70 (let1 p (open-output-string)
71 (display msg p)
72 (dolist [obj args] (display " " p) (write/ss obj p))
73 (get-output-string p)))
74
75 ;; Handy when you want to create <error> object without immediately raising it.
76 (define-in-module gauche (make-error msg . args)
77 (make <error> :message (%make-error-message msg args)
78 :message-prefix msg :message-args args))
79
80 ;; error and errorf. A bit messy to allow optional condition class argument
81 ;; as the first arg.
82 (define-in-module gauche (error msg . args)
83 (raise
84 (cond
85 [(is-a? msg <condition-meta>)
86 (receive (keys msgs) (%error-scan-keys args)
87 (if (null? msgs)
88 (apply make msg keys)
89 (apply make msg
90 :message (%make-error-message (car msgs) (cdr msgs))
91 :message-prefix (car msgs)
92 :message-args (cdr msgs)
93 keys)))]
94 [else (apply make-error msg args)])))
95
96 (define-in-module gauche (errorf fmt . args)
97 (raise
98 (cond
99 [(is-a? fmt <condition-meta>)
100 (receive (keys msgs) (%error-scan-keys args)
101 (if (null? msgs)
102 (apply make fmt keys)
103 (apply make fmt :message (apply format/ss #f msgs) keys)))]
104 [else (make <error> :message (apply format/ss #f fmt args))])))
105
106 ;;;
107 ;;; make-vector
108 ;;;
109
110 ;; make-vector needs to be defined here, for it is called
111 ;; in other initalization routines.
112 (select-module scheme)
113 (define-cproc make-vector (k::<fixnum> :optional fill) Scm_MakeVector)
114
115 ;;;
116 ;;; SRFI-17 support
117 ;;;
118
119 ;; some libraries needs to set the setter procedures during initialization,
120 ;; so we should have it before them.
121
122 (select-module gauche)
123 (define-cproc getter-with-setter (proc::<procedure> set::<procedure>) ;SRFI-17
124 (case (SCM_PROCEDURE_TYPE proc)
125 [(SCM_PROC_SUBR SCM_PROC_CLOSURE)] ;ok
126 [(SCM_PROC_GENERIC SCM_PROC_METHOD)
127 (Scm_Error "You can't attach a setter to a generic function or a method \
128 using getter-with-setter. Instead, you can define a setter \
129 method using the name (setter %S)."
130 (SCM_PROCEDURE_INFO proc))]
131 [else (Scm_Error "You can't attach a setter to %S." (SCM_OBJ proc))])
132 (let* ([p (Scm__CopyProcedure proc SCM_FALSE)])
133 ;; NB: We override p->locked, for p is a copy.
134 (set! (SCM_PROCEDURE_SETTER_LOCKED p) FALSE)
135 (return (Scm_SetterSet (SCM_PROCEDURE p) set TRUE))))
136
137 (define-cproc setter (proc) ;SRFI-17
138 (inliner SETTER)
139 (setter (proc::<procedure> setter::<procedure>) ::<void>
140 (Scm_SetterSet proc setter FALSE))
141 Scm_Setter)
142
143 ;;;
144 ;;; case-lambda support
145 ;;;
146
147 (select-module gauche.internal)
148 (inline-stub
149 ;; Support procedure for case-lambda
150 ;; Dispatch-vector maps # of required arguments to the procedure body.
151 ;; The last entry of dispatch vector is to cover more arguments; it should
152 ;; be #f if no cases take arbitrary number of arguments.
153 ;; Examples:
154 ;; (case-lambda [() a] [(x) (b)] [(x y) c] [(x y . z) d])
155 ;; =>
156 ;; #( (lambda () a) min-reqargs == 0
157 ;; (lambda (x) b)
158 ;; (lambda (x y) c)
159 ;; (lambda (x y . z) d) )
160 ;;
161 ;; (case-lambda [() a] [(x) (b)] [(x y) c])
162 ;; =>
163 ;; #( (lambda () a) min-reqargs == 0
164 ;; (lambda (x) b)
165 ;; (lambda (x y) c)
166 ;; #f )
167 ;;
168 ;; (case-lambda [(x y) a] [(x y z) b] [(x y z . w) c]
169 ;; =>
170 ;; #( (lambda (x y) a) min-reqargs == 2
171 ;; (lambda (x y z) b)
172 ;; (lambda (x y z . w) c))
173 ;;
174 ;; (case-lambda [(x y) a] [(x . y) b]
175 ;; =>
176 ;; #( (lambda (x . y) b) min-reqargs == 1
177 ;; (lambda (x y) a)
178 ;; (lambda (x . y) b))
179 ;;
180 ;; In the last example, 2 argument case matches the first procedure,
181 ;; for it has precedence.
182
183 (define-ctype case_lambda_packet
184 :: (.struct case_lambda_packet_rec
185 (dispatch_vector::ScmVector*
186 max_optargs::int
187 min_reqargs::int)))
188
189 (define-cfn case-lambda-dispatch (args::ScmObj* nargs::int data::void*):static
190 (let* ([d::case_lambda_packet* (cast case_lambda_packet* data)]
191 [rarg (aref args (- nargs 1))]
192 [_ (SCM_ASSERT (> nargs (-> d min_reqargs)))]
193 [_ (SCM_ASSERT (<= nargs (+ (-> d min_reqargs) (-> d max_optargs) 1)))]
194 ;; NB: Since this is variable-arg subr, rarg is always a list.
195 ;; If nargs <= d->max_optargs + d->min_reqargs, rargs should always
196 ;; be '(). See vmcall.c for how the arguments are folded.
197 [p (SCM_VECTOR_ELEMENT (-> d dispatch_vector)
198 (- nargs (-> d min_reqargs) 1))])
199 (when (SCM_FALSEP p)
200 (Scm_Error "wrong number of arguments to case lambda: %S"
201 (Scm_ArrayToListWithTail args (- nargs 1)
202 (aref args (- nargs 1)))))
203 (if (SCM_NULLP rarg)
204 (case (- nargs 1)
205 [(0) (return (Scm_VMApply0 p))]
206 [(1) (return (Scm_VMApply1 p (aref args 0)))]
207 [(2) (return (Scm_VMApply2 p (aref args 0) (aref args 1)))]
208 [(3) (return (Scm_VMApply3 p (aref args 0) (aref args 1)
209 (aref args 2)))]
210 [(4) (return (Scm_VMApply4 p (aref args 0) (aref args 1)
211 (aref args 2) (aref args 3)))]
212 [else (return (Scm_VMApply p (Scm_ArrayToList args (- nargs 1))))])
213 (return
214 (Scm_VMApply p (Scm_ArrayToListWithTail args (- nargs 1) rarg))))
215 ))
216
217 ;; A case-lambda procedure has special inliner procedure in its 'inliner' slot,
218 ;; which is made by pass1/make-case-labmda-inliner. There's a catch,
219 ;; though. Case-lambda procedures are made and called during booting,
220 ;; but pass1/make-case-labmda-inliner won't be available until the late
221 ;; stage of booting when the compiler is initialized. So, if we don't
222 ;; have pass1/make-case-labmda-inliner yet, we assign
223 ;; delayed-case-lambda-inliner to delay actual calling.
224 (define-cfn delayed-case-lambda-inliner (args::ScmObj* nargs::int data::void*)
225 :static
226 (let* ([clambda-proc (SCM_OBJ data)]
227 [make-inliner
228 (Scm_GlobalVariableRef (Scm_GaucheInternalModule)
229 (SCM_SYMBOL 'pass1/make-case-lambda-inliner)
230 0)])
231 (when (SCM_UNBOUNDP make-inliner)
232 (return SCM_UNDEFINED)) ;not fully booted
233 (SCM_ASSERT (== nargs 2))
234 (let* ([src (aref args 0)]
235 [arg-iforms (aref args 1)]
236 [inliner (Scm_ApplyRec1 make-inliner clambda-proc)])
237 (SCM_ASSERT (SCM_PROCEDUREP inliner))
238 (set! (SCM_PROCEDURE_INLINER clambda-proc) inliner)
239 (return (Scm_VMApply2 inliner src arg-iforms)))))
240
241 ;; The compiler expands case-lambda to a call of make-case-lambda.
242 ;; It may be called during initialization, so we need it here.
243 ;; TRANSIENT: The third argument used to be a list of formals of the closures.
244 ;; We no longer need it, for we extract info from closures. It is left for
245 ;; the backward compatibility until we switch ABI.
246 (define-cproc make-case-lambda (minarg::<int>
247 maxarg::<int>
248 _
249 closures
250 :optional (name #f))
251 (let* ([max-optargs::int (+ (- maxarg minarg) 2)]
252 [v-closures (Scm_MakeVector max-optargs SCM_FALSE)]
253 [num-closures::int 0]
254 [v-formals]
255 [packet::case_lambda_packet* (SCM_NEW case_lambda_packet)])
256 (for-each
257 (lambda (c)
258 (let* ([req::int (SCM_PROCEDURE_REQUIRED c)]
259 [opt::int (SCM_PROCEDURE_OPTIONAL c)]
260 [n::int minarg])
261 (for (() (<= n (+ maxarg 1)) (post++ n))
262 (when (and (or (== n req)
263 (and (> n req) (> opt 0)))
264 (SCM_FALSEP (SCM_VECTOR_ELEMENT v-closures (- n minarg))))
265 (set! (SCM_VECTOR_ELEMENT v-closures (- n minarg)) c)
266 (pre++ num-closures)))))
267 closures)
268 ;; v-formals is #(<formals> ...)). it is kept in the procedure-info
269 ;; slot. It is only for information, the program should not count on
270 ;; its content.
271 ;; NB: We need a standard way to extract formals from a closure. Here
272 ;; I take cdr of each closure's procedure-info, but it's not guaranteed
273 ;; that they always have the formals.
274 (set! v-formals (Scm_MakeVector num-closures SCM_FALSE))
275 (let* ([i::int 0])
276 (dotimes [n max-optargs]
277 (let* ([c (SCM_VECTOR_ELEMENT v-closures n)])
278 (when (and (SCM_PROCEDUREP c)
279 (SCM_PAIRP (SCM_PROCEDURE_INFO c)))
280 (set! (SCM_VECTOR_ELEMENT v-formals i)
281 (SCM_CDR (SCM_PROCEDURE_INFO c)))
282 (post++ i)))))
283 (set! (-> packet min_reqargs) minarg
284 (-> packet max_optargs) max-optargs
285 (-> packet dispatch_vector) (SCM_VECTOR v-closures))
286 (let* ([r (Scm_MakeSubr case_lambda_dispatch packet
287 minarg max_optargs
288 (SCM_LIST2 (?: (SCM_FALSEP name)
289 'case-lambda-dispatcher
290 name)
291 v-formals))]
292 [make-inliner
293 (Scm_GlobalVariableRef (Scm_GaucheInternalModule)
294 (SCM_SYMBOL 'pass1/make-case-lambda-inliner)
295 0)])
296 (if (SCM_UNBOUNDP make-inliner)
297 (set! (SCM_PROCEDURE_INLINER r)
298 (Scm_MakeSubr delayed-case-lambda-inliner
299 (cast void* r) 2 0
300 'delayed-case-lambda-inliner))
301 (set! (SCM_PROCEDURE_INLINER r)
302 (Scm_ApplyRec1 make-inliner r)))
303 (return r))))
304
305 ;; Returns a plist of case-lambda info if OBJ is a case lambda closure,
306 ;; otherwise #f.
307 (define-cproc %case-lambda-info (obj)
308 (if (and (SCM_SUBRP obj)
309 (== (SCM_SUBR_FUNC obj) case_lambda_dispatch))
310 (let* ([packet::case_lambda_packet* (cast case_lambda_packet*
311 (SCM_SUBR_DATA obj))])
312 (return (list ':min-reqargs
313 (SCM_MAKE_INT (-> packet min_reqargs))
314 ':max-optargs
315 (SCM_MAKE_INT (-> packet max_optargs))
316 ':dispatch-vector
317 (SCM_OBJ (-> packet dispatch_vector)))))
318 (return SCM_FALSE)))
319 )
320
321 ;; Returns ((<required args> <optional arg> <procedure>) ...)
322 ;; for easier introspection.
323 (define-in-module gauche (case-lambda-decompose proc)
324 (and-let1 info (%case-lambda-info proc)
325 (let ([min-args (get-keyword :min-reqargs info)]
326 [len (get-keyword :max-optargs info)]
327 [dispatch-vec (get-keyword :dispatch-vector info)])
328 (let loop ([r '()] [i 0])
329 (if (= i (- len 1))
330 (if-let1 optproc (vector-ref dispatch-vec i)
331 (reverse r `((,(+ min-args i -1) #t ,optproc)))
332 (reverse r))
333 (if-let1 proc (vector-ref dispatch-vec i)
334 (loop (cons `(,(+ min-args i) #f ,proc) r) (+ i 1))
335 (loop r (+ i 1))))))))
336
337 ;;;
338 ;;; Transfer binding to other module
339 ;;;
340
341 ;; Some components (e.g. libobj.scm) has its own module, and transfer
342 ;; external API to 'gauche' module.
343 ;; NB: For more general (internal) API, we have %insert-binding in libmod.
344 ;; %transfer-bindings is purely for initialization, and it is overwritten
345 ;; in libomega.
346
347 (with-module gauche.internal)
348
349 ;; Take binding of each symbol in SYMBOLS in the module FROM and inject
350 ;; it in the module TO. Binding flags (const, inlinable) are carried over,
351 ;; unless a list given to FLAGS argument. FLAGS list may include
352 ;; 'const and 'inlinable.
353 (define-cproc %transfer-bindings (from::<module> to::<module> symbols
354 :optional (flags #f))
355 ::<void>
356 (for-each (lambda (sym)
357 (SCM_ASSERT (SCM_SYMBOLP sym))
358 (let* ([g::ScmGloc* (Scm_FindBinding from (SCM_SYMBOL sym) 0)]
359 [lflags::u_long 0])
360 (SCM_ASSERT (!= g NULL))
361 (cond [(SCM_PAIRP flags)
362 (for-each (lambda (fl)
363 (cond [(SCM_EQ fl 'const)
364 (logior= lflags SCM_BINDING_CONST)]
365 [(SCM_EQ fl 'inlinable)
366 (logior= lflags SCM_BINDING_INLINABLE)]
367 [else
368 (Scm_Error "unknown flag: %S" fl)]))
369 flags)]
370 [else
371 (when (Scm_GlocInlinableP g)
372 (logior= lflags SCM_BINDING_INLINABLE))
373 (when (Scm_GlocConstP g)
374 (logior= lflags SCM_BINDING_CONST))])
375 (Scm_MakeBinding to (SCM_SYMBOL sym) (SCM_GLOC_GET g) lflags)))
376 symbols))
377
378 ;;;
379 ;;; This is needed before we use define-macro.
380 ;;;
381
382 (with-module gauche.internal)
383
384 ;; transformer :: Sexpr, Cenv -> Sexpr
385 ;; flags is a list of flag symbols (we avoid using numeric values,
386 ;; to avoid inter-version build.
387 (define-cproc %make-macro-transformer (name transformer
388 :optional (info ())
389 (flags ()))
390 (let* ([flag-bits::u_long 0])
391 (for-each (lambda (flag)
392 (cond
393 [(SCM_EQ flag 'identifier-macro)
394 (logior= flag-bits SCM_MACRO_IDENTIFIER)]
395 [(SCM_EQ flag 'parameterizable)
396 (logior= flag-bits SCM_MACRO_PARAMETERIZABLE)]
397 [else
398 (Scm_Error "Unknown flag symbol: %S" flag)]))
399 flags)
400 (return (Scm_MakeMacro name transformer info flag-bits))))