forked from bldl/magnolisp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
backend-cxx-print.rkt
340 lines (304 loc) · 10.6 KB
/
backend-cxx-print.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
#lang racket/base
#|
|#
(require (for-syntax racket/base)
racket/format
racket/list
racket/match
racket/port
racket/string
(rename-in "pp-yield.rkt" [pp pp-y])
"app-util.rkt"
"ir-ast.rkt"
"backend-cxx-ast.rkt"
"util.rkt" "util/debug.rkt")
(define (pp . ds)
(call-with-output-string
(lambda (out)
(define (yield s)
(display s out))
(pp-y #:yield yield ds))))
(define (ew-error sym msg v)
(error sym (string-append msg ": ~s") v))
(define-match-expander produces
(syntax-rules ()
((_ f pat)
(app f (and (? values) pat)))))
(define* (format-c decl*)
(apply string-append
(add-between
(for/list ((ast decl*))
(pp (format-decl ast)))
"\n\n")))
(define (format-defun-sig name modifs type args)
`(,(add-between (append modifs (list (format-type type))) " ")
" " ,(symbol->string name)
"(" (in (gr sp ,(format-params args))) " )"))
(define (format-decl decl)
(match decl
((struct* Include ([kind kind] [s header]))
(define-values (lq rq)
(if (eq? kind 'user)
(values "\"" "\"")
(values "<" ">")))
(string-append "#include " lq header rq))
((TlVerbatim _ s)
s)
((CxxDefun _ name modifs type args stmt)
`(,(format-defun-sig name modifs type args)
,(format-fun-stats (SeqStat-ss stmt))))
((Proto _ name modifs type args)
`(,(format-defun-sig name modifs type args) ";"))
(else
(ew-error 'format-decl "could not format" else))))
(define (format-fun-stats ss)
(if (null? ss)
'(" {" br "}")
`(" {" (in ,(for/list ((s ss))
`(br ,(format-stat s)))) br "}")))
(define (format-sub-stats ss)
(if (null? ss)
'(in br "{}")
`(" {" (in ,(for/list ((s ss))
`(br ,(format-stat s)))) br "}")))
(define (format-stat stmt)
(match stmt
((SeqStat _ stmt*)
(if (null? stmt*)
"{}"
`("{"
(in ,(for/list ((s stmt*))
`(br ,(format-stat s))))
br "}")))
((DefVar _ [format-ident . produces . ident]
[format-type . produces . type]
[format-expr . produces . expr])
(list type " " ident " = " expr ";"))
((DeclVar _ [format-ident . produces . ident]
[format-type . produces . type])
(list type " " ident ";"))
((IfStat _ [format-expr . produces . test]
(SeqStat _ ts) (SeqStat _ es))
`("if (" ,test ")"
,(format-sub-stats ts)
,(and (not (null? es))
`(,(if (null? ts) 'br " ")
"else"
,(format-sub-stats es)))))
((ReturnStat _ e)
(if (VoidExpr? e)
(list "return;")
(let ([e
(format-outer-expr e)]
[comma?
(matches? e
(SeqExpr _ (? (lambda (x) (> (length x) 1)))))])
(if comma?
`("return" (in br ,e) ";")
`("return " (in ,e) ";")))))
((Goto _ name)
(string-append "goto " (format-ident name) ";"))
((LabelDef _ name)
(string-append (format-ident name) ":"))
((ExprStat _ [format-outer-expr . produces . expr])
(list expr ";"))
(else (ew-error 'format-stat "could not format" else))))
(define (format-custom-literal anno-e typename dat)
(match-define (list-rest 'literal pp-lst)
(syntax->datum anno-e))
(for/list ([pp pp-lst])
(match pp
[(? string? s)
s]
[(list fmt obj)
(define f
(match fmt
['display ~a]
['write ~s]
['print ~v]
['cxx-str (compose string->narrow-cxx-string-literal ~a)]
[_ (raise-language-error
#f "illegal literal formatting style directive"
anno-e fmt)]))
(define v
(match obj
['datum dat]
['type-id typename]
[(? string?) obj]
[_ (raise-language-error
#f "illegal literal formatting object specifier"
anno-e obj)]))
(f v)]
[_ (raise-language-error
#f "illegal literal formatting item"
anno-e pp)])))
(define (format-outer-expr expr)
(match expr
[(SeqExpr a es)
(let ((es (map format-expr-in-outer-expr es)))
(add-between es '("," br)))]
[(AssignExpr _ [format-expr . produces . x]
[format-expr . produces . v])
`(,x " = " (in ,v))]
[_
(format-expr expr)]))
(define (format-expr-in-outer-expr expr)
(match expr
[(Parens _ e)
(format-expr e)]
[_
(format-expr expr)]))
(define (format-expr expr)
(match expr
((Parens _ e)
`("(" ,(format-expr e) ")"))
((VoidCast _ e)
`("(void)" ,(format-expr e)))
((SeqExpr a es)
(let ((es (map format-expr es)))
`(gr ,(add-between es '("," sp)))))
((IfExpr _ [format-expr . produces . test]
[format-expr . produces . conseq]
[format-expr . produces . alt])
`(,test (in (gr " ?" sp ,conseq " :" sp ,alt))))
((Var _ var)
(symbol->string var))
((Literal (app (lambda (h) (hash-ref h 'literal #f)) anno-e) dat)
#:when anno-e
(match-define (ForeignNameT _ tn-stx) (ast-anno-must expr 'cxx-type))
(format-custom-literal anno-e (syntax-e tn-stx) dat))
((Literal _ (? number? n))
(number->string n))
((Literal _ (? boolean? b))
(if (not b) "false" "true"))
((Literal _ (? string? s))
(string->narrow-cxx-string-literal s))
((Literal _ (? symbol? sym))
`("mgl_SYMBOL(" ,(string->narrow-cxx-string-literal
(symbol->string sym)) ")"))
((ApplyExpr a f [format-args . produces . args])
(define ts (hash-ref a 'type<> #f))
(list (format-expr f)
(and ts `("<" (in (gr ,(add-between
(map format-type ts)
'("," sp))))
">"))
"(" `(in (gr ,args)) ")"))
((AssignExpr _ [format-expr . produces . x] [format-expr . produces . v])
(list x " = " v))
((VoidExpr _)
"(void)0")
(else (ew-error 'format-expr "could not format" else))))
(define (mangle-ident x)
(let ((y ""))
(define (push c)
(set! y (string-append y c)))
(for ((c (in-string x)))
(case c
((#\-) (push "$"))
((#\$) (push "$$"))
((#\.) (push "$_"))
((#\$) (push "$$$"))
((#\>) (push "$v"))
((#\!) (push "$b"))
(else (push (string c)))))
y))
(define (format-ident ident)
(unless (symbol? ident)
(ew-error 'format-ident "could not format" ident))
(let ((reserved-words '(complex)))
(if (memq ident reserved-words)
(string-append "$$" (symbol->string ident))
(mangle-ident (symbol->string ident)))))
(define (format-type t)
(match t
((NameT _ (? symbol? s))
(symbol->string s))
((ForeignNameT _ (? identifier? s))
(symbol->string (syntax-e s)))
((ConstT _ t)
(list (format-type t) " const"))
((RefT _ t)
(list (format-type t) "&"))
((ParamT _ t ps)
`(,(format-type t) "<"
,(add-between (map format-type ps) '("," sp))
">"))
(else (ew-error 'format-type "could not format" else))))
(define (format-params args)
(add-between (map format-param args) '("," sp)))
(define (format-args args)
(add-between (map format-expr args) '("," sp)))
(define (format-param arg)
(match arg
((Param _ n [format-type . produces . t])
(list t " " (symbol->string n)))
(arg
(ew-error 'format-param "could not format" arg))))
(define (string-pad s up-to-len pad-ch)
(define len (string-length s))
(if (>= len up-to-len)
s
(let ((n (- up-to-len len)))
(string-append (make-string n pad-ch) s))))
(define (char->octal-escape c)
(define s (format "~o" (char->integer c)))
(list "\\" (string-pad s 3 #\0)))
(define (string->narrow-cxx-string-literal s)
(list
"\""
(for/list ([c (in-string s)])
(cond
[(char=? c #\newline) "\\n"]
[(char=? c #\return) "\\r"]
[(char=? c #\tab) "\\t"]
[(char=? c #\\) "\\\\"]
[(char=? c #\") "\\\""]
[(char-iso-control? c) (char->octal-escape c)]
[else
(define n (char->integer c))
(when (> n 127)
(raise-argument-error
'string->narrow-cxx-string-literal
"ASCII string" s))
c]))
"\""))
#|
The contents of this file are derived from the print-c.scm file of
Elegant Weapons. Any changes to this file are copyright University of
Bergen and the authors, and the following license applies to this
file.
Copyright (c) 2013-2014 Tero Hasu and University of Bergen
Copyright (c) 2011-2013 The Trustees of Indiana University and Indiana
University Research and Technology
Corporation. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer listed
in this license in the documentation and/or other materials
provided with the distribution.
- Neither the name of the copyright holders nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
The copyright holders provide no reassurances that the source code
provided does not infringe any patent, copyright, or any other
intellectual property rights of third parties. The copyright holders
disclaim any liability to any recipient for claims brought against
recipient by any third party for infringement of that parties
intellectual property rights.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|#