Debian Codegraph @

src/libmacbase.scm

raw
1 ;;;
2 ;;; libmacbase.scm - macro basic staff
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 (select-module gauche.internal)
35 (use util.match)
36 (inline-stub
37 (.include "gauche/priv/configP.h"
38 "gauche/priv/macroP.h"))
39
40 ;; This file defines lower level layer of macro system.
41 ;; Initialization of compile.scm depends on this file.
42
43 ;;;
44 ;;; Macro expansion utilities
45 ;;;
46
47 ;; macroexpand FORM [ENV/FLAG]
48 ;; macroexpand-1 FORM [ENV/FLAG]
49 ;; ENV/FLAG can be:
50 ;; #f - we expand it in the current runtime env, run unravel-syntax on output
51 ;; #t - we expand it in the current runtime env
52 ;; #<module> - use it as the toplevel env.
53
54 ;; API
55 (define-in-module gauche (macroexpand form :optional (env/flag #f))
56 (%do-macroexpand form env/flag #f))
57 ;; API
58 (define-in-module gauche (macroexpand-1 form :optional (env/flag #f))
59 (%do-macroexpand form env/flag #t))
60
61 (define (%do-macroexpand form env/flag once?)
62 (let* ([env (cond
63 [(boolean? env/flag) (vm-current-module)]
64 [(module? env/flag) env/flag]
65 [else (error "argument must be a boolean or a module, but got:"
66 env/flag)])]
67 [r (%internal-macro-expand form (make-cenv env) once?)])
68 (if (eq? env/flag #f)
69 (unravel-syntax r)
70 r)))
71
72 (select-module gauche)
73 ;; API
74 ;; This strips all syntactic information (lossy)
75 (define-cproc unwrap-syntax (form :optional (to_immutable::<boolean> #f))
76 (return (Scm_UnwrapSyntax2 form to_immutable)))
77
78 ;; API
79 ;; Unwrap only if obj is an identifier.
80 (define-cproc unwrap-syntax-1 (obj)
81 (if (SCM_IDENTIFIERP obj)
82 (return (SCM_OBJ (Scm_UnwrapIdentifier (SCM_IDENTIFIER obj))))
83 (return obj)))
84
85 ;; API
86 ;; This preserves identity of local identifiers by suffixing it.
87 ;; The identity of toplevel identifiers are still not preserved across modules.
88 (select-module gauche.internal)
89 (define-in-module gauche (unravel-syntax form)
90 (define id->sym
91 (let1 tab (make-hash-table 'eq?) ; identifier -> symbol
92 (^[id]
93 (or (hash-table-get tab id #f)
94 (let1 nam (unwrap-syntax id)
95 (if (global-identifier=? id (make-identifier nam
96 (vm-current-module)
97 '()))
98 (begin (hash-table-put! tab id nam) nam)
99 (let1 num ($ hash-table-fold tab
100 (^[i _ c]
101 (if (eq? (unwrap-syntax i) nam) (+ c 1) c))
102 0)
103 (rlet1 sym (symbol-append nam "." num)
104 (hash-table-put! tab id sym)))))))))
105 (define (rec form)
106 (cond [(wrapped-identifier? form) (id->sym form)]
107 [(pair? form) (cons (rec (car form)) (rec (cdr form)))]
108 [(vector? form) (vector-map rec form)]
109 [else form]))
110 (rec form))
111
112 (select-module gauche.internal)
113 (inline-stub
114 (declare-stub-type <macro> "ScmMacro*" "macro"
115 "SCM_MACROP" "SCM_MACRO" "SCM_OBJ")
116 )
117
118 ;; These are used in the compiler, and hidden inside gauche.internal.
119 (define-cproc macro? (obj) ::<boolean> SCM_MACROP)
120 (define-cproc syntax? (obj) ::<boolean> SCM_SYNTAXP)
121
122 ;;;
123 ;;; Macro object
124 ;;;
125
126 (select-module gauche)
127 (inline-stub
128 (define-cfn get-macro-flags (macro) :static
129 (SCM_ASSERT (SCM_MACROP macro))
130 (let* ([flags::u_long (-> (SCM_MACRO macro) flags)]
131 [h SCM_NIL] [t SCM_NIL])
132 (when (logand flags SCM_MACRO_IDENTIFIER)
133 (SCM_APPEND1 h t 'identifier-macro))
134 (when (logand flags SCM_MACRO_PARAMETERIZABLE)
135 (SCM_APPEND1 h t 'parameterizable))
136 (return h)))
137
138 (define-cclass <macro>
139 "ScmMacro*" "Scm_MacroClass"
140 (c "SCM_CLASS_DEFAULT_CPL")
141 ((name :setter #f)
142 (transformer :setter #f)
143 (info-alist :c-name "info_alist" :setter #f)
144 (flags :getter (c "get_macro_flags") :setter #f))
145 (printer (Scm_Printf port "#<macro %A>" (-> (SCM_MACRO obj) name)))))
146
147 ;;;
148 ;;; Transformer interface
149 ;;;
150
151 ;; NB: %make-macro-transformer is in libalpha.scm
152
153 (select-module gauche.internal)
154
155 (define-cproc compile-syntax-rules (name src ellipsis literals rules mod env)
156 Scm_CompileSyntaxRules)
157
158 (define-cproc macro-transformer (mac::<macro>) Scm_MacroTransformer)
159 (define-cproc macro-name (mac::<macro>) Scm_MacroName)
160 (define-cproc identifier-macro? (mac::<macro>) ::<boolean>
161 (return (logand (-> mac flags) SCM_MACRO_IDENTIFIER)))
162
163 ;; new-transformer&flags := (<transformer> (<flag> ...))
164 ;; Returns old info in the same format
165 ;; This API is subject to change.
166 (define-cproc %swap-macro-transformer! (mac::<macro> new-transformer&flags)
167 (SCM_ASSERT (SCM_PAIRP new-transformer&flags))
168 (SCM_ASSERT (SCM_PAIRP (SCM_CDR new-transformer&flags)))
169 (let* ([xformer (SCM_CAR new-transformer&flags)]
170 [flags (SCM_CADR new-transformer&flags)]
171 [iflags::u_long 0])
172 (for-each (lambda (f)
173 (if (SCM_EQ f 'identifier-macro)
174 (logior= iflags SCM_MACRO_IDENTIFIER)
175 (Scm_Error "Invalid macro flag: %S" f)))
176 flags)
177 (Scm__SwapMacroTransformer mac (& xformer) (& iflags))
178 (if (logand iflags SCM_MACRO_IDENTIFIER)
179 (set! flags '(identifier-macro))
180 (set! flags '()))
181 (return (SCM_LIST2 xformer flags))))
182
183 ;; Macro expand tracer
184 ;; *trace-macro* can be #f (default - no trace), #t (trace all macros),
185 ;; or a list of symbols/regexp (trace macros whose name that matches)
186 (define *trace-macro* #f)
187
188 (define (%macro-traced? mac)
189 (or (eq? *trace-macro* #t)
190 (and-let1 macname (unwrap-syntax (macro-name mac))
191 (find (^z (cond [(symbol? z) (eq? z macname)]
192 [(regexp? z) (z (symbol->string macname))]
193 [else #f]))
194 *trace-macro*))))
195
196 (define-inline (show-macro-trace mac input output)
197 (when (and *trace-macro* (%macro-traced? mac))
198 ;; NB: We need to apply unravel-syntax on input and output at once,
199 ;; so that we can correspond the identifiers from input and output.
200 (let1 unraveled (unravel-syntax (cons input output))
201 (display "Macro input>>>\n" (current-trace-port))
202 (pprint (car unraveled) :port (current-trace-port) :level #f :length #f)
203 (display "\nMacro output<<<\n" (current-trace-port))
204 (pprint (cdr unraveled) :port (current-trace-port) :level #f :length #f)
205 (display "\n" (current-trace-port))
206 (flush (current-trace-port)))))
207
208 ;; Internal API called from Pass1
209 ;; EXPR is an S-expr (<identifier> <e> ...), and we know that <identifier>
210 ;; is bound to a macro MAC. It calls macro expander and returns the result
211 ;; S-expr. There are some auxliary bookkeeping stuff---we attach macro's
212 ;; original form info to the first pair of the resulting form (if the result
213 ;; is a pair), and handles macro tracing if needed.
214 (define (call-macro-expander mac expr cenv)
215 (let* ([r (if (identifier-macro? mac)
216 (extended-cons ((macro-transformer mac) (car expr) cenv)
217 (cdr expr))
218 ((macro-transformer mac) expr cenv))]
219 [out (if (and (pair? r) (not (eq? expr r)))
220 (rlet1 p (if (extended-pair? r)
221 r
222 (extended-cons (car r) (cdr r)))
223 (pair-attribute-set! p 'original expr))
224 r)])
225 (show-macro-trace mac expr out)
226 out))
227
228 ;; This is called when a macro is used at non-head position. FORM
229 ;; can be either (set! <identifier> <expr>) form, or <identifier>.
230 ;; If MAC is not an id-macro, we don't expand the form and returns the
231 ;; macro object itself (semantically it is an error).
232 (define (call-id-macro-expander mac form cenv)
233 (if (identifier-macro? mac)
234 (rlet1 out ((macro-transformer mac) form cenv)
235 (show-macro-trace mac form out))
236 mac))
237
238 (define-cproc make-syntax (name::<symbol> module::<module> proc)
239 Scm_MakeSyntax)
240
241 (define-cproc call-syntax-handler (syn program cenv)
242 (SCM_ASSERT (SCM_SYNTAXP syn))
243 (return (Scm_VMApply2 (-> (SCM_SYNTAX syn) handler) program cenv)))
244
245 (define-cproc syntax-handler (syn)
246 (SCM_ASSERT (SCM_SYNTAXP syn))
247 (return (-> (SCM_SYNTAX syn) handler)))
248
249 (define-in-module gauche (trace-macro . args)
250 ;; force resolving autoload of pprint before changing *trace-macro*; otherwise,
251 ;; autoloading pprint can trigger macro tracing which needs pprint.
252 (procedure? pprint)
253 (match args
254 [() #f] ;just show current traces
255 [(#t) (set! *trace-macro* #t)] ;trace all macros
256 [(#f) (set! *trace-macro* #f)] ;untrace all macros
257 [(objs ...)
258 (unless (every (^x (or (symbol? x) (regexp? x))) objs)
259 (error "Argument(s) of trace-macro should be a \
260 boolean, or symbols or regexps, but got:" args))
261 (and-let1 ms (cond [(not *trace-macro*) '()]
262 [(list? *trace-macro*) *trace-macro*]
263 [else #f]) ;; if we're tracing all macros, no need to
264 ;; add symbols.
265 (set! *trace-macro* (delete-duplicates (append objs ms))))])
266 *trace-macro*)
267
268 (define-in-module gauche (untrace-macro . args)
269 (match args
270 [() (set! *trace-macro* #f)] ;untrace all
271 [(sym ...) (when (list? *trace-macro*)
272 (let1 ms (remove (cute member <> sym) *trace-macro*)
273 (set! *trace-macro* (if (null? ms) #f ms))))])
274 *trace-macro*)