aboutsummaryrefslogtreecommitdiff
path: root/new-luxc/source/luxc/analyser/procedure/host.jvm.lux
blob: 1592827db309904698ce17adb9befebdf4b201a0 (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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
(;module:
  [lux #- char]
  (lux (control [monad #+ do]
                ["p" parser]
                ["ex" exception #+ exception:])
       (concurrency ["A" atom])
       (data ["R" result]
             [maybe]
             [product]
             [text "text/" Eq<Text>]
             (text format
                   ["l" lexer])
             (coll [list "list/" Fold<List> Functor<List>]
                   [array #+ Array]
                   [dict #+ Dict]))
       [macro "lux/" Monad<Lux>]
       [type]
       (type ["tc" check])
       [host])
  (luxc ["&" base]
        ["&;" host]
        (lang ["la" analysis])
        (analyser ["&;" common]))
  ["@" ../common]
  )

(def: #export null-class Text "#Null")

(do-template [<name> <class>]
  [(def: #export <name> Type (#;Host <class> (list)))]

  ## Boxes
  [Boolean   "java.lang.Boolean"]
  [Byte      "java.lang.Byte"]
  [Short     "java.lang.Short"]
  [Integer   "java.lang.Integer"]
  [Long      "java.lang.Long"]
  [Float     "java.lang.Float"]
  [Double    "java.lang.Double"]
  [Character "java.lang.Character"]
  [String    "java.lang.String"]

  ## Primitives
  [boolean   "boolean"]
  [byte      "byte"]
  [short     "short"]
  [int       "int"]
  [long      "long"]
  [float     "float"]
  [double    "double"]
  [char      "char"]
  )

(def: conversion-procs
  @;Bundle
  (<| (@;prefix "convert")
      (|> (dict;new text;Hash<Text>)
          (@;install "double-to-float" (@;unary Double Float))
          (@;install "double-to-int" (@;unary Double Integer))
          (@;install "double-to-long" (@;unary Double Long))
          (@;install "float-to-double" (@;unary Float Double))
          (@;install "float-to-int" (@;unary Float Integer))
          (@;install "float-to-long" (@;unary Float Long))
          (@;install "int-to-byte" (@;unary Integer Byte))
          (@;install "int-to-char" (@;unary Integer Character))
          (@;install "int-to-double" (@;unary Integer Double))
          (@;install "int-to-float" (@;unary Integer Float))
          (@;install "int-to-long" (@;unary Integer Long))
          (@;install "int-to-short" (@;unary Integer Short))
          (@;install "long-to-double" (@;unary Long Double))
          (@;install "long-to-float" (@;unary Long Float))
          (@;install "long-to-int" (@;unary Long Integer))
          (@;install "long-to-short" (@;unary Long Short))
          (@;install "long-to-byte" (@;unary Long Byte))
          (@;install "char-to-byte" (@;unary Character Byte))
          (@;install "char-to-short" (@;unary Character Short))
          (@;install "char-to-int" (@;unary Character Integer))
          (@;install "char-to-long" (@;unary Character Long))
          (@;install "byte-to-long" (@;unary Byte Long))
          (@;install "short-to-long" (@;unary Short Long))
          )))

(do-template [<name> <prefix> <type>]
  [(def: <name>
     @;Bundle
     (<| (@;prefix <prefix>)
         (|> (dict;new text;Hash<Text>)
             (@;install "+" (@;binary <type> <type> <type>))
             (@;install "-" (@;binary <type> <type> <type>))
             (@;install "*" (@;binary <type> <type> <type>))
             (@;install "/" (@;binary <type> <type> <type>))
             (@;install "%" (@;binary <type> <type> <type>))
             (@;install "=" (@;binary <type> <type> Boolean))
             (@;install "<" (@;binary <type> <type> Boolean))
             (@;install "and" (@;binary <type> <type> <type>))
             (@;install "or" (@;binary <type> <type> <type>))
             (@;install "xor" (@;binary <type> <type> <type>))
             (@;install "shl" (@;binary <type> Integer <type>))
             (@;install "shr" (@;binary <type> Integer <type>))
             (@;install "ushr" (@;binary <type> Integer <type>))
             )))]

  [int-procs  "int"  Integer]
  [long-procs "long" Long]
  )

(do-template [<name> <prefix> <type>]
  [(def: <name>
     @;Bundle
     (<| (@;prefix <prefix>)
         (|> (dict;new text;Hash<Text>)
             (@;install "+" (@;binary <type> <type> <type>))
             (@;install "-" (@;binary <type> <type> <type>))
             (@;install "*" (@;binary <type> <type> <type>))
             (@;install "/" (@;binary <type> <type> <type>))
             (@;install "%" (@;binary <type> <type> <type>))
             (@;install "=" (@;binary <type> <type> Boolean))
             (@;install "<" (@;binary <type> <type> Boolean))
             )))]

  [float-procs  "float"  Float]
  [double-procs "double" Double]
  )

(def: char-procs
  @;Bundle
  (<| (@;prefix "char")
      (|> (dict;new text;Hash<Text>)
          (@;install "=" (@;binary Character Character Boolean))
          (@;install "<" (@;binary Character Character Boolean))
          )))

(def: #export boxes
  (Dict Text Text)
  (|> (list ["boolean" "java.lang.Boolean"]
            ["byte" "java.lang.Byte"]
            ["short" "java.lang.Short"]
            ["int" "java.lang.Integer"]
            ["long" "java.lang.Long"]
            ["float" "java.lang.Float"]
            ["double" "java.lang.Double"]
            ["char" "java.lang.Character"])
      (dict;from-list text;Hash<Text>)))

(def: (array-length proc)
  (-> Text @;Proc)
  (function [analyse args]
    (&common;with-var
      (function [[var-id varT]]
        (case args
          (^ (list arrayC))
          (do macro;Monad<Lux>
            [arrayA (&;with-expected-type (type (Array varT))
                      (analyse arrayC))
             _ (&;infer Nat)]
            (wrap (#la;Procedure proc (list arrayA))))

          _
          (&;fail (@;wrong-arity proc +1 (list;size args))))))))

(def: (invalid-array-type arrayT)
  (-> Type Text)
  (format "Invalid type for array: " (%type arrayT)))

(def: (array-new proc)
  (-> Text @;Proc)
  (function [analyse args]
    (case args
      (^ (list lengthC))
      (do macro;Monad<Lux>
        [lengthA (&;with-expected-type Nat
                   (analyse lengthC))
         expectedT macro;expected-type
         [level elem-class] (: (Lux [Nat Text])
                               (loop [analysisT expectedT
                                      level +0]
                                 (case analysisT
                                   (#;Apply inputT funcT)
                                   (case (type;apply (list inputT) funcT)
                                     (#;Some outputT)
                                     (recur outputT level)

                                     #;None
                                     (&;fail (invalid-array-type expectedT)))

                                   (^ (#;Host "#Array" (list elemT)))
                                   (recur elemT (n.inc level))

                                   (#;Host class _)
                                   (wrap [level class])
                                   
                                   _
                                   (&;fail (invalid-array-type expectedT)))))
         _ (&;assert "Must have at least 1 level of nesting in array type."
                     (n.> +0 level))]
        (wrap (#la;Procedure proc (list (#la;Nat (n.dec level)) (#la;Text elem-class) lengthA))))

      _
      (&;fail (@;wrong-arity proc +1 (list;size args))))))

(def: (not-object type)
  (-> Type Text)
  (format "Non-object type: " (%type type)))

(def: (check-jvm objectT)
  (-> Type (Lux Text))
  (case objectT
    (#;Host name _)
    (lux/wrap name)

    (#;Named name unnamed)
    (check-jvm unnamed)

    (^template [<tag>]
      (<tag> env unquantified)
      (check-jvm unquantified))
    ([#;UnivQ]
     [#;ExQ])

    (#;Apply inputT funcT)
    (case (type;apply (list inputT) funcT)
      (#;Some outputT)
      (check-jvm outputT)

      #;None
      (&;fail (not-object objectT)))

    _
    (&;fail (not-object objectT))))

(def: (check-object objectT)
  (-> Type (Lux Text))
  (do macro;Monad<Lux>
    [name (check-jvm objectT)]
    (if (dict;contains? name boxes)
      (&;fail (format "Primitives are not objects: " name))
      (:: macro;Monad<Lux> wrap name))))

(def: (box-array-element-type elemT)
  (-> Type (Lux [Type Text]))
  (do macro;Monad<Lux>
    []
    (case elemT
      (#;Host name #;Nil)
      (let [boxed-name (|> (dict;get name boxes)
                           (maybe;default name))]
        (wrap [(#;Host boxed-name #;Nil)
               boxed-name]))

      (#;Host name _)
      (if (dict;contains? name boxes)
        (&;fail (format "Primitives cannot be parameterized: " name))
        (:: macro;Monad<Lux> wrap [elemT name]))

      _
      (&;fail (format "Invalid type for array element: " (%type elemT))))))

(def: (array-read proc)
  (-> Text @;Proc)
  (function [analyse args]
    (&common;with-var
      (function [[var-id varT]]
        (case args
          (^ (list arrayC idxC))
          (do macro;Monad<Lux>
            [arrayA (&;with-expected-type (type (Array varT))
                      (analyse arrayC))
             elemT (&;with-type-env
                     (tc;read var-id))
             [elemT elem-class] (box-array-element-type elemT)
             idxA (&;with-expected-type Nat
                    (analyse idxC))
             _ (&;infer elemT)]
            (wrap (#la;Procedure proc (list (#la;Text elem-class) idxA arrayA))))

          _
          (&;fail (@;wrong-arity proc +2 (list;size args))))))))

(def: (array-write proc)
  (-> Text @;Proc)
  (function [analyse args]
    (&common;with-var
      (function [[var-id varT]]
        (case args
          (^ (list arrayC idxC valueC))
          (do macro;Monad<Lux>
            [arrayA (&;with-expected-type (type (Array varT))
                      (analyse arrayC))
             elemT (&;with-type-env
                     (tc;read var-id))
             [valueT elem-class] (box-array-element-type elemT)
             idxA (&;with-expected-type Nat
                    (analyse idxC))
             valueA (&;with-expected-type valueT
                      (analyse valueC))
             _ (&;infer (type (Array elemT)))]
            (wrap (#la;Procedure proc (list (#la;Text elem-class) idxA valueA arrayA))))

          _
          (&;fail (@;wrong-arity proc +3 (list;size args))))))))

(def: array-procs
  @;Bundle
  (<| (@;prefix "array")
      (|> (dict;new text;Hash<Text>)
          (@;install "length" array-length)
          (@;install "new" array-new)
          (@;install "read" array-read)
          (@;install "write" array-write)
          )))

(def: (object-null proc)
  (-> Text @;Proc)
  (function [analyse args]
    (case args
      (^ (list))
      (do macro;Monad<Lux>
        [expectedT macro;expected-type
         _ (check-object expectedT)]
        (wrap (#la;Procedure proc (list))))

      _
      (&;fail (@;wrong-arity proc +0 (list;size args))))))

(def: (object-null? proc)
  (-> Text @;Proc)
  (function [analyse args]
    (&common;with-var
      (function [[var-id varT]]
        (case args
          (^ (list objectC))
          (do macro;Monad<Lux>
            [objectA (&;with-expected-type varT
                       (analyse objectC))
             objectT (&;with-type-env
                       (tc;read var-id))
             _ (check-object objectT)
             _ (&;infer Bool)]
            (wrap (#la;Procedure proc (list objectA))))

          _
          (&;fail (@;wrong-arity proc +1 (list;size args))))))))

(def: (object-synchronized proc)
  (-> Text @;Proc)
  (function [analyse args]
    (&common;with-var
      (function [[var-id varT]]
        (case args
          (^ (list monitorC exprC))
          (do macro;Monad<Lux>
            [monitorA (&;with-expected-type varT
                        (analyse monitorC))
             monitorT (&;with-type-env
                        (tc;read var-id))
             _ (check-object monitorT)
             exprA (analyse exprC)]
            (wrap (#la;Procedure proc (list monitorA exprA))))

          _
          (&;fail (@;wrong-arity proc +2 (list;size args))))))))

(host;import java.lang.Object)

(host;import java.lang.ClassLoader)

(host;import #long java.lang.reflect.Type
  (getTypeName [] String))

(host;import java.lang.reflect.GenericArrayType
  (getGenericComponentType [] java.lang.reflect.Type))

(host;import java.lang.reflect.ParameterizedType
  (getRawType [] java.lang.reflect.Type)
  (getActualTypeArguments [] (Array java.lang.reflect.Type)))

(host;import (java.lang.reflect.TypeVariable d)
  (getName [] String)
  (getBounds [] (Array java.lang.reflect.Type)))

(host;import (java.lang.reflect.WildcardType d)
  (getLowerBounds [] (Array java.lang.reflect.Type))
  (getUpperBounds [] (Array java.lang.reflect.Type)))

(host;import java.lang.reflect.Modifier
  (#static isStatic [int] boolean)
  (#static isFinal [int] boolean))

(host;import java.lang.reflect.Field
  (getDeclaringClass [] (java.lang.Class Object))
  (getModifiers [] int)
  (getGenericType [] java.lang.reflect.Type))

(host;import (java.lang.Class c)
  (getName [] String)
  (#static forName [String boolean ClassLoader] #try (Class Object))
  (isAssignableFrom [(Class Object)] boolean)
  (getTypeParameters [] (Array (TypeVariable (Class c))))
  (getGenericInterfaces [] (Array java.lang.reflect.Type))
  (getGenericSuperclass [] java.lang.reflect.Type)
  (getDeclaredField [String] #try Field))

(def: (load-class name)
  (-> Text (Lux (Class Object)))
  (do macro;Monad<Lux>
    [class-loader &host;class-loader]
    (case (Class.forName [name false class-loader])
      (#R;Success [class])
      (wrap class)

      (#R;Error error)
      (&;fail (format "Unknown class: " name)))))

(def: (sub-class? super sub)
  (-> Text Text (Lux Bool))
  (do macro;Monad<Lux>
    [super (load-class super)
     sub (load-class sub)]
    (wrap (Class.isAssignableFrom [sub] super))))

(exception: #export Not-Throwable)

(def: (object-throw proc)
  (-> Text @;Proc)
  (function [analyse args]
    (&common;with-var
      (function [[var-id varT]]
        (case args
          (^ (list exceptionC))
          (do macro;Monad<Lux>
            [exceptionA (&;with-expected-type varT
                          (analyse exceptionC))
             exceptionT (&;with-type-env
                          (tc;read var-id))
             exception-class (check-object exceptionT)
             ? (sub-class? "java.lang.Throwable" exception-class)
             _ (: (Lux Unit)
                  (if ?
                    (wrap [])
                    (&;throw Not-Throwable exception-class)))
             _ (&;infer Bottom)]
            (wrap (#la;Procedure proc (list exceptionA))))

          _
          (&;fail (@;wrong-arity proc +1 (list;size args))))))))

(def: (object-class proc)
  (-> Text @;Proc)
  (function [analyse args]
    (case args
      (^ (list classC))
      (case classC
        [_ (#;Text class)]
        (do macro;Monad<Lux>
          [_ (load-class class)
           _ (&;infer (#;Host "java.lang.Class" (list (#;Host class (list)))))]
          (wrap (#la;Procedure proc (list (#la;Text class)))))

        _
        (&;fail (format "Wrong syntax for '" proc "'.")))

      _
      (&;fail (@;wrong-arity proc +1 (list;size args))))))

(exception: #export Cannot-Be-Instance)

(def: (object-instance? proc)
  (-> Text @;Proc)
  (function [analyse args]
    (&common;with-var
      (function [[var-id varT]]
        (case args
          (^ (list classC objectC))
          (case classC
            [_ (#;Text class)]
            (do macro;Monad<Lux>
              [objectA (&;with-expected-type varT
                         (analyse objectC))
               objectT (&;with-type-env
                         (tc;read var-id))
               object-class (check-object objectT)
               ? (sub-class? class object-class)]
              (if ?
                (do @
                  [_ (&;infer Bool)]
                  (wrap (#la;Procedure proc (list (#la;Text class)))))
                (&;throw Cannot-Be-Instance (format object-class " !<= "  class))))

            _
            (&;fail (format "Wrong syntax for '" proc "'.")))

          _
          (&;fail (@;wrong-arity proc +2 (list;size args))))))))

(def: object-procs
  @;Bundle
  (<| (@;prefix "object")
      (|> (dict;new text;Hash<Text>)
          (@;install "null" object-null)
          (@;install "null?" object-null?)
          (@;install "synchronized" object-synchronized)
          (@;install "throw" object-throw)
          (@;install "class" object-class)
          (@;install "instance?" object-instance?)
          )))

(exception: #export Final-Field)

(exception: #export Cannot-Convert-To-Class)
(exception: #export Cannot-Convert-To-Lux-Type)
(exception: #export Cannot-Cast-To-Primitive)
(exception: #export JVM-Type-Is-Not-Class)

(def: type-descriptor
  (-> java.lang.reflect.Type Text)
  (java.lang.reflect.Type.getTypeName []))

(def: (java-type-to-class type)
  (-> java.lang.reflect.Type (Lux Text))
  (cond (host;instance? Class type)
        (lux/wrap (Class.getName [] (:! Class type)))

        (host;instance? ParameterizedType type)
        (java-type-to-class (ParameterizedType.getRawType [] (:! ParameterizedType type)))

        ## else
        (&;throw Cannot-Convert-To-Class (type-descriptor type))))

(exception: #export Unknown-Type-Var)

(type: Mappings
  (Dict Text Type))

(def: fresh-mappings Mappings (dict;new text;Hash<Text>))

(def: (java-type-to-lux-type mappings java-type)
  (-> Mappings java.lang.reflect.Type (Lux Type))
  (cond (host;instance? TypeVariable java-type)
        (let [var-name (TypeVariable.getName [] (:! TypeVariable java-type))]
          (case (dict;get var-name mappings)
            (#;Some var-type)
            (lux/wrap var-type)
            
            #;None
            (&;throw Unknown-Type-Var var-name)))

        (host;instance? WildcardType java-type)
        (let [java-type (:! WildcardType java-type)]
          (case [(array;get +0 (WildcardType.getUpperBounds [] java-type))
                 (array;get +0 (WildcardType.getLowerBounds [] java-type))]
            (^or [(#;Some bound) _] [_ (#;Some bound)])
            (java-type-to-lux-type mappings bound)
            
            _
            (lux/wrap Top)))

        (host;instance? Class java-type)
        (let [java-type (:! (Class Object) java-type)
              class-name (Class.getName [] java-type)]
          (lux/wrap (case (array;size (Class.getTypeParameters [] java-type))
                      +0
                      (#;Host class-name (list))
                      
                      arity
                      (|> (list;n.range +0 (n.dec arity))
                          list;reverse
                          (list/map (|>. (n.* +2) n.inc #;Bound))
                          (#;Host class-name)
                          (type;univ-q arity)))))

        (host;instance? ParameterizedType java-type)
        (let [java-type (:! ParameterizedType java-type)
              raw (ParameterizedType.getRawType [] java-type)]
          (if (host;instance? Class raw)
            (do macro;Monad<Lux>
              [paramsT (|> java-type
                           (ParameterizedType.getActualTypeArguments [])
                           array;to-list
                           (monad;map @ (java-type-to-lux-type mappings)))]
              (lux/wrap (#;Host (Class.getName [] (:! (Class Object) raw))
                                paramsT)))
            (&;throw JVM-Type-Is-Not-Class (type-descriptor raw))))

        (host;instance? GenericArrayType java-type)
        (do macro;Monad<Lux>
          [innerT (|> (:! GenericArrayType java-type)
                      (GenericArrayType.getGenericComponentType [])
                      (java-type-to-lux-type mappings))]
          (wrap (#;Host "#Array" (list innerT))))

        ## else
        (&;throw Cannot-Convert-To-Lux-Type (type-descriptor java-type))))

(type: Direction
  #In
  #Out)

(def: (choose direction to from)
  (-> Direction Text Text Text)
  (case direction
    #In to
    #Out from))

(def: (cast direction to from)
  (-> Direction Type Type (Lux [Text Type]))
  (do macro;Monad<Lux>
    [to-name (check-jvm to)
     from-name (check-jvm from)]
    (cond (dict;contains? to-name boxes)
          (let [box (maybe;assume (dict;get to-name boxes))]
            (if (text/= box from-name)
              (wrap [(choose direction to-name from-name) (#;Host to-name (list))])
              (&;throw Cannot-Cast-To-Primitive (format from-name " => " to-name))))

          (dict;contains? from-name boxes)
          (let [box (maybe;assume (dict;get from-name boxes))]
            (do @
              [[_ castT] (cast direction to (#;Host box (list)))]
              (wrap [(choose direction to-name from-name) castT])))

          (text/= to-name from-name)
          (wrap [(choose direction to-name from-name) from])

          (text/= null-class from-name)
          (wrap [(choose direction to-name from-name) to])

          ## else
          (do @
            [to-class (load-class to-name)
             from-class (load-class from-name)
             _ (&;assert (format "Class '" from-name "' is not a sub-class of class '" to-name "'.")
                         (Class.isAssignableFrom [from-class] to-class))
             candiate-parents (monad;map @
                                         (function [java-type]
                                           (do @
                                             [class-name (java-type-to-class java-type)
                                              class (load-class class-name)]
                                             (wrap [java-type (Class.isAssignableFrom [from-class] to-class)])))
                                         (list& (Class.getGenericSuperclass [] from-class)
                                                (array;to-list (Class.getGenericInterfaces [] from-class))))]
            (case (|> candiate-parents
                      (list;filter product;right)
                      (list/map product;left))
              (#;Cons parent _)
              (do @
                [parentT (java-type-to-lux-type fresh-mappings parent)
                 [_ castT] (cast direction to parentT)]
                (wrap [(choose direction to-name from-name) castT]))

              #;Nil
              (&;fail (format "No valid path between " (%type from) "and " (%type to) ".")))))))

(def: (find-field class-name field-name)
  (-> Text Text (Lux [(Class Object) Field]))
  (do macro;Monad<Lux>
    [class (load-class class-name)]
    (case (Class.getDeclaredField [field-name] class)
      (#R;Success field)
      (let [owner (Field.getDeclaringClass [] field)]
        (if (is owner class)
          (wrap [class field])
          (&;fail (format "Field '" field-name "' does not belong to class '" class-name "'.\n"
                          "Belongs to '" (Class.getName [] owner) "'."))))

      (#R;Error _)
      (&;fail (format "Unknown field '" field-name "' for class '" class-name "'.")))))

(def: (static-field class-name field-name)
  (-> Text Text (Lux [Type Bool]))
  (do macro;Monad<Lux>
    [[class fieldJ] (find-field class-name field-name)
     #let [modifiers (Field.getModifiers [] fieldJ)]]
    (if (Modifier.isStatic [modifiers])
      (let [fieldJT (Field.getGenericType [] fieldJ)]
        (do @
          [fieldT (java-type-to-lux-type fresh-mappings fieldJT)]
          (wrap [fieldT (Modifier.isFinal [modifiers])])))
      (&;fail (format "Field '" field-name "' of class '" class-name "' is not static.")))))

(exception: #export Non-Object-Type)

(def: (virtual-field class-name field-name objectT)
  (-> Text Text Type (Lux [Type Bool]))
  (do macro;Monad<Lux>
    [[class fieldJ] (find-field class-name field-name)
     #let [modifiers (Field.getModifiers [] fieldJ)]]
    (if (not (Modifier.isStatic [modifiers]))
      (do @
        [#let [fieldJT (Field.getGenericType [] fieldJ)
               var-names (|> class
                             (Class.getTypeParameters [])
                             array;to-list
                             (list/map (TypeVariable.getName [])))]
         mappings (: (Lux Mappings)
                     (case objectT
                       (#;Host _class-name _class-params)
                       (do @
                         [#let [num-params (list;size _class-params)
                                num-vars (list;size var-names)]
                          _ (&;assert (format "Number of paremeters in type does not match expected amount (" (%n num-vars) "): " (%type objectT))
                                      (n.= num-params num-vars))]
                         (wrap (|> (list;zip2 var-names _class-params)
                                   (dict;from-list text;Hash<Text>))))

                       _
                       (&;throw Non-Object-Type (%type objectT))))
         fieldT (java-type-to-lux-type mappings fieldJT)]
        (wrap [fieldT (Modifier.isFinal [modifiers])]))
      (&;fail (format "Field '" field-name "' of class '" class-name "' is static.")))))

(def: (analyse-object class analyse sourceC)
  (-> Text &;Analyser Code (Lux [Type la;Analysis]))
  (<| &common;with-var (function [[var-id varT]])
      (do macro;Monad<Lux>
        [target-class (load-class class)
         targetT (java-type-to-lux-type fresh-mappings
                                        (:! java.lang.reflect.Type
                                            target-class))
         sourceA (&;with-expected-type varT
                   (analyse sourceC))
         sourceT (&;with-type-env
                   (tc;read var-id))
         [unboxed castT] (cast #Out targetT sourceT)
         _ (&;assert (format "Object cannot be a primitive: " unboxed)
                     (not (dict;contains? unboxed boxes)))]
        (wrap [castT sourceA]))))

(def: (analyse-input analyse targetT sourceC)
  (-> &;Analyser Type Code (Lux [Type Text la;Analysis]))
  (<| &common;with-var (function [[var-id varT]])
      (do macro;Monad<Lux>
        [sourceA (&;with-expected-type varT
                   (analyse sourceC))
         sourceT (&;with-type-env
                   (tc;read var-id))
         [unboxed castT] (cast #In targetT sourceT)]
        (wrap [castT unboxed sourceA]))))

(def: (static-get proc)
  (-> Text @;Proc)
  (function [analyse args]
    (case args
      (^ (list classC fieldC))
      (case [classC fieldC]
        [[_ (#;Text class)] [_ (#;Text field)]]
        (do macro;Monad<Lux>
          [[fieldT final?] (static-field class field)
           expectedT macro;expected-type
           [unboxed castT] (cast #Out expectedT fieldT)
           _ (&;with-type-env
               (tc;check expectedT castT))]
          (wrap (#la;Procedure proc (list (#la;Text class) (#la;Text field) (#la;Text unboxed)))))

        _
        (&;fail (format "Wrong syntax for '" proc "'.")))

      _
      (&;fail (@;wrong-arity proc +2 (list;size args))))))

(def: (static-put proc)
  (-> Text @;Proc)
  (function [analyse args]
    (case args
      (^ (list classC fieldC valueC))
      (case [classC fieldC]
        [[_ (#;Text class)] [_ (#;Text field)]]
        (do macro;Monad<Lux>
          [[fieldT final?] (static-field class field)
           _ (&;assert (Final-Field (format class "#" field))
                       (not final?))
           [valueT unboxed valueA] (analyse-input analyse fieldT valueC)
           _ (&;with-type-env
               (tc;check fieldT valueT))
           _ (&;infer Unit)]
          (wrap (#la;Procedure proc (list (#la;Text class) (#la;Text field) (#la;Text unboxed) valueA))))

        _
        (&;fail (format "Wrong syntax for '" proc "'.")))

      _
      (&;fail (@;wrong-arity proc +3 (list;size args))))))

(def: (virtual-get proc)
  (-> Text @;Proc)
  (function [analyse args]
    (case args
      (^ (list classC fieldC objectC))
      (case [classC fieldC]
        [[_ (#;Text class)] [_ (#;Text field)]]
        (do macro;Monad<Lux>
          [[objectT objectA] (analyse-object class analyse objectC)
           [fieldT final?] (virtual-field class field objectT)
           expectedT macro;expected-type
           [unboxed castT] (cast #Out expectedT fieldT)
           _ (&;with-type-env
               (tc;check expectedT castT))]
          (wrap (#la;Procedure proc (list (#la;Text class) (#la;Text field) (#la;Text unboxed) objectA))))

        _
        (&;fail (format "Wrong syntax for '" proc "'.")))

      _
      (&;fail (@;wrong-arity proc +3 (list;size args))))))

(def: (virtual-put proc)
  (-> Text @;Proc)
  (function [analyse args]
    (case args
      (^ (list classC fieldC valueC objectC))
      (case [classC fieldC]
        [[_ (#;Text class)] [_ (#;Text field)]]
        (do macro;Monad<Lux>
          [[objectT objectA] (analyse-object class analyse objectC)
           [fieldT final?] (virtual-field class field objectT)
           _ (&;assert (Final-Field (format class "#" field))
                       (not final?))
           [valueT unboxed valueA] (analyse-input analyse fieldT valueC)
           _ (&;with-type-env
               (tc;check fieldT valueT))
           _ (&;infer Unit)]
          (wrap (#la;Procedure proc (list (#la;Text class) (#la;Text field) (#la;Text unboxed) valueA objectA))))

        _
        (&;fail (format "Wrong syntax for '" proc "'.")))

      _
      (&;fail (@;wrong-arity proc +4 (list;size args))))))

(def: member-procs
  @;Bundle
  (<| (@;prefix "member")
      (|> (dict;new text;Hash<Text>)
          (dict;merge (<| (@;prefix "static")
                          (|> (dict;new text;Hash<Text>)
                              (@;install "get" static-get)
                              (@;install "put" static-put))))
          (dict;merge (<| (@;prefix "virtual")
                          (|> (dict;new text;Hash<Text>)
                              (@;install "get" virtual-get)
                              (@;install "put" virtual-put))))
          )))

(def: #export procedures
  @;Bundle
  (<| (@;prefix "jvm")
      (|> (dict;new text;Hash<Text>)
          (dict;merge conversion-procs)
          (dict;merge int-procs)
          (dict;merge long-procs)
          (dict;merge float-procs)
          (dict;merge double-procs)
          (dict;merge char-procs)
          (dict;merge array-procs)
          (dict;merge object-procs)
          (dict;merge member-procs)
          )))