aboutsummaryrefslogtreecommitdiff
path: root/source/lux/host/jvm.lux
blob: bbb3968743f09a4eb9811911525c19b37ace3820 (plain)
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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
##  Copyright (c) Eduardo Julian. All rights reserved.
##  This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
##  If a copy of the MPL was not distributed with this file,
##  You can obtain one at http://mozilla.org/MPL/2.0/.

(;import lux
         (lux (control (monoid #as m)
                       (functor #as F)
                       (monad #as M #refer (#only do seq%))
                       (enum #as E))
              (data (list #refer #all #open ("" List/Functor List/Fold))
                    (number/int #refer #all #open ("i:" Int/Ord Int/Number))
                    maybe
                    tuple
                    (text #open ("text:" Text/Monoid)))
              (meta lux
                    ast
                    syntax)))

(open List/Monad "list:")

## [Types]
(defsyntax #export (Array [dimensions (?^ nat^)] type)
  (emit (@list (foldL (lambda [inner _] (` (#;DataT "#Array" (@list (~ inner)))))
                      type
                      (repeat (? 1 dimensions) [])))))

## [Utils]
## Types
(deftype StackFrame (^ java.lang.StackTraceElement))
(deftype StackTrace (Array StackFrame))

(deftype Modifier Text)
(deftype JvmType Text)

(deftype AnnotationParam
  (, Text AST))

(deftype Annotation
  (& #ann-name Text
     #ann-params (List AnnotationParam)))

(deftype MemberDecl
  (& #member-name      Text
     #member-modifiers (List Modifier)
     #member-anns      (List Annotation)))

(deftype FieldDecl
  JvmType)

(deftype MethodDecl
  (& #method-inputs (List JvmType)
     #method-output JvmType
     #method-exs    (List JvmType)))

(deftype ArgDecl
  (& #arg-name Text
     #arg-type JvmType))

(deftype MethodDef
  (& #method-vars (List ArgDecl)
     #return-type JvmType
     #return-body AST
     #throws-exs  (List JvmType)))

(deftype ExpectedInput
  (& #opt-input? Bool
     #input-type JvmType))

(deftype ExpectedOutput
  (& #ex-output? Bool
     #opt-output? Bool
     #output-type JvmType))

## Functions
(def (prepare-args args)
  (-> (List ExpectedInput) (Lux (, (List AST) (List AST) (List AST) (List Text))))
  (do Lux/Monad
    [vars (seq% Lux/Monad (repeat (size args) (gensym "")))
     #let [pairings (map (: (-> (, (, Bool Text) AST) (, AST (List AST)))
                            (lambda [[[opt? arg-class] var]]
                              (if opt?
                                [(` (Maybe (^ (~ (symbol$ ["" arg-class])))))
                                 (@list var (` (: (^ (~ (symbol$ ["" arg-class])))
                                                  (case (~ var)
                                                    (#;Some (~ var)) (~ var)
                                                    #;None           ;_jvm_null))))]
                                [(` (^ (~ (symbol$ ["" arg-class]))))
                                 (@list)])))
                         (zip2 args vars))
           var-types (map first pairings)
           var-rebinds (map second pairings)
           arg-classes (map second args)]]
    (wrap [vars var-types (list:join var-rebinds) arg-classes])))

## Parsers
(def annotation-params^
  (Parser (List AnnotationParam))
  (record^ (*^ (tuple^ (&^ local-tag^ id^)))))

(def annotation^
  (Parser Annotation)
  (form^ (&^ local-symbol^
             annotation-params^)))

(def annotations^'
  (Parser (List Annotation))
  (do Parser/Monad
    [_ (tag!^ ["" "ann"])]
    (tuple^ (*^ annotation^))))

(def annotations^
  (Parser (List Annotation))
  (do Parser/Monad
    [anns?? (?^ annotations^')]
    (wrap (? (@list) anns??))))

(def member-decl^
  (Parser MemberDecl)
  (do Parser/Monad
    [modifiers (*^ local-tag^)
     name local-symbol^
     anns annotations^]
    (wrap [name modifiers anns])))

(def throws-decl'^
  (Parser (List JvmType))
  (do Parser/Monad
    [_ (tag!^ ["" "throws"])]
    (tuple^ (*^ local-symbol^))))

(def throws-decl^
  (Parser (List JvmType))
  (do Parser/Monad
    [exs? (?^ throws-decl'^)]
    (wrap (? (@list) exs?))))

(def method-decl'^
  (Parser MethodDecl)
  (do Parser/Monad
    [inputs (tuple^ (*^ local-symbol^))
     outputs local-symbol^
     exs throws-decl^]
    (wrap [inputs outputs exs])))

(def method-decl^
  (Parser (, MemberDecl MethodDecl))
  (form^ (&^ member-decl^
             method-decl'^)))

(def field-decl^
  (Parser (, MemberDecl FieldDecl))
  (form^ (&^ member-decl^
             local-symbol^)))

(def arg-decl^
  (Parser ArgDecl)
  (form^ (&^ local-symbol^ local-symbol^)))

(def method-def'^
  (Parser MethodDef)
  (do Parser/Monad
    [inputs (tuple^ (*^ arg-decl^))
     output local-symbol^
     exs throws-decl^
     body id^]
    (wrap [inputs output body exs])))

(def method-def^
  (Parser (, MemberDecl MethodDef))
  (form^ (&^ member-decl^
             method-def'^)))

(def exp-input^
  (Parser ExpectedInput)
  (&^ (tag?^ ["" "?"])
      local-symbol^))

(def exp-output^
  (Parser ExpectedOutput)
  (do Parser/Monad
    [ex? (tag?^ ["" "!"])
     opt? (tag?^ ["" "?"])
     return local-symbol^]
    (wrap [ex? opt? return])))

## Generators
(def (gen-annotation-param [name value])
  (-> AnnotationParam (, AST AST))
  [(text$ name) value])

(def (gen-annotation [name params])
  (-> Annotation AST)
  (` ((~ (text$ name))
      (~ (record$ (map gen-annotation-param params))))))

(def (gen-method-decl [[name modifiers anns] [inputs output exs]])
  (-> (, MemberDecl MethodDecl) AST)
  (` ((~ (text$ name))
      [(~@ (map text$ modifiers))]
      [(~@ (map gen-annotation anns))]
      [(~@ (map text$ exs))]
      [(~@ (map text$ inputs))]
      (~ (text$ output)))))

(def (gen-field-decl [[name modifiers anns] class])
  (-> (, MemberDecl FieldDecl) AST)
  (` ((~ (text$ name))
      [(~@ (map text$ modifiers))]
      [(~@ (map gen-annotation anns))]
      (~ (text$ class))
      )))

(def (gen-arg-decl [name type])
  (-> ArgDecl AST)
  (form$ (@list (symbol$ ["" name]) (text$ type))))

(def (gen-method-def [[name modifiers anns] [inputs output body exs]])
  (-> (, MemberDecl MethodDef) AST)
  (` ((~ (text$ name))
      [(~@ (map text$ modifiers))]
      [(~@ (map gen-annotation anns))]
      [(~@ (map text$ exs))]
      [(~@ (map gen-arg-decl inputs))]
      (~ (text$ output))
      (~ body))))

(def (gen-expected-output [ex? opt? output] body)
  (-> ExpectedOutput AST (, AST AST))
  (let [type (` (^ (~ (symbol$ ["" output]))))
        [body type] (if opt?
                      [(` (;;??? (~ body)))
                       (` (Maybe (~ type)))]
                      [body type])
        [body type] (if ex?
                      [(` (;;try (~ body)))
                       (` (Either Text (~ type)))]
                      [body type])]
    [body type]))

## [Functions]
(def (stack-trace->text trace)
  (-> StackTrace Text)
  (let [size (_jvm_arraylength trace)
        idxs (E;range Int/Enum 0 (i:+ -1 size))]
    (|> idxs
        (map (: (-> Int Text)
                (lambda [idx]
                  (_jvm_invokevirtual "java.lang.Object" "toString" [] (_jvm_aaload "java.lang.StackTraceElement" trace idx) []))))
        (interpose "\n")
        (foldL text:++ "")
        )))

(def (get-stack-trace t)
  (-> (^ java.lang.Throwable) StackTrace)
  (_jvm_invokevirtual "java.lang.Throwable" "getStackTrace" [] t []))

(def #export (throwable->text t)
  ($ text:++
    (_jvm_invokevirtual "java.lang.Object" "toString" [] t [])
    "\n"
    (|> t get-stack-trace stack-trace->text)))

## [Syntax]
(defsyntax #export (defclass [name local-symbol^] [super local-symbol^] [interfaces (tuple^ (*^ local-symbol^))]
                     [annotations annotations^]
                     [fields (*^ field-decl^)]
                     [methods (*^ method-def^)])
  (emit (@list (` (;_jvm_class (~ (text$ name)) (~ (text$ super))
                               [(~@ (map text$ interfaces))]
                               [(~@ (map gen-annotation annotations))]
                               [(~@ (map gen-field-decl fields))]
                               [(~@ (map gen-method-def methods))])))))

(defsyntax #export (definterface [name local-symbol^] [supers (tuple^ (*^ local-symbol^))]
                     [annotations annotations^]
                     [members (*^ method-decl^)])
  (emit (@list (` (;_jvm_interface (~ (text$ name)) [(~@ (map text$ supers))]
                                   [(~@ (map gen-annotation annotations))]
                                   (~@ (map gen-method-decl members)))))))

(defsyntax #export (object [super local-symbol^] [interfaces (tuple^ (*^ local-symbol^))]
                           [methods (*^ method-def^)])
  (emit (@list (` (;_jvm_anon-class (~ (text$ super))
                                    [(~@ (map text$ interfaces))]
                                    [(~@ (map gen-method-def methods))])))))

(defsyntax #export (program [args symbol^] body)
  (emit (@list (` (;_jvm_program (~ (symbol$ args))
                                 (~ body))))))

(defsyntax #export (??? expr)
  (do Lux/Monad
    [g!temp (gensym "")]
    (wrap (@list (` (let [(~ g!temp) (~ expr)]
                      (if (;_jvm_null? (~ g!temp))
                        #;None
                        (#;Some (~ g!temp)))))))))

(defsyntax #export (try expr)
  (emit (@list (` (;_jvm_try (#;Right (~ expr))
                             (~ (' (_jvm_catch "java.lang.Exception" e
                                               (#;Left (throwable->text e))))))))))

(defsyntax #export (instance? [class local-symbol^] obj)
  (emit (@list (` (;_jvm_instanceof (~ (text$ class)) (~ obj))))))

(defsyntax #export (locking lock body)
  (do Lux/Monad
    [g!lock (gensym "")
     g!body (gensym "")
     g!_ (gensym "")]
    (emit (@list (` (let [(~ g!lock) (~ lock)
                          (~ g!_) (;_jvm_monitorenter (~ g!lock))
                          (~ g!body) (~ body)
                          (~ g!_) (;_jvm_monitorexit (~ g!lock))]
                      (~ g!body)))))
    ))

(defsyntax #export (null? obj)
  (emit (@list (` (;_jvm_null? (~ obj))))))

(defsyntax #export (new$ [class local-symbol^] [args (tuple^ (*^ exp-input^))] [ex? (tag?^ ["" "!"])])
  (do Lux/Monad
    [[vars var-types var-rebinds arg-classes] (prepare-args args)
     #let [new-expr (` (;_jvm_new (~ (text$ class)) [(~@ (map text$ arg-classes))] [(~@ vars)]))
           new-expr (if ex?
                      (` (try (~ new-expr)))
                      new-expr)]]
    (wrap (@list (` (: (-> (, (~@ var-types)) (^ (~ (symbol$ ["" class]))))
                       (lambda [[(~@ vars)]]
                         (let [(~@ var-rebinds)]
                           (~ new-expr)))))))))

(do-template [<name> <op>]
  [(defsyntax #export (<name> [class local-symbol^] [method local-symbol^] [args (tuple^ (*^ exp-input^))]
                              [expected-output exp-output^])
     (do Lux/Monad
       [[vars var-types var-rebinds arg-classes] (prepare-args args)
        g!self (gensym "self")
        #let [[body return-type] (gen-expected-output expected-output
                                                      (` (<op> (~ (text$ class)) (~ (text$ method)) [(~@ (map text$ arg-classes))] (~ g!self) [(~@ vars)])))]]
       (wrap (@list (` (: (-> (, (~@ var-types)) (^ (~ (symbol$ ["" class]))) (~ return-type))
                          (lambda [[(~@ vars)] (~ g!self)]
                            (let [(~@ var-rebinds)]
                              (~ body)))))))
       ))]

  [invoke-virtual$   ;_jvm_invokevirtual]
  [invoke-interface$ ;_jvm_invokeinterface]
  )

(defsyntax #export (invoke-static$ [class local-symbol^] [method local-symbol^] [args (tuple^ (*^ exp-input^))]
                                   [expected-output exp-output^])
  (do Lux/Monad
    [[vars var-types var-rebinds arg-classes] (prepare-args args)
     #let [[body return-type] (gen-expected-output expected-output
                                                   (` (;_jvm_invokestatic (~ (text$ class)) (~ (text$ method)) [(~@ (map text$ arg-classes))] [(~@ vars)])))]]
    (wrap (@list (` (: (-> (, (~@ var-types)) (~ return-type))
                       (lambda [[(~@ vars)]]
                         (let [(~@ var-rebinds)]
                           (~ body)))))))
    ))