aboutsummaryrefslogtreecommitdiff
path: root/lux-js/source/program.lux
blob: fff7eba21726098d7977b1edfea6a8e85fedb177 (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
(.require
 [library
  [lux (.except)
   [program (.only program)]
   ["[0]" ffi (.only import)]
   ["[0]" debug]
   [abstract
    [monad (.only do)]]
   [control
    ["[0]" maybe (.use "[1]#[0]" monad)]
    ["[0]" try (.only Try)]
    ["[0]" exception (.only Exception)]
    ["[0]" io (.only IO io)]
    ["[0]" function]
    [concurrency
     ["[0]" async (.only Async)]]]
   [data
    ["[0]" product]
    [text
     ["%" \\format (.only format)]
     [encoding
      ["[0]" utf8]]]
    [collection
     ["[0]" array (.only Array)]]]
   [math
    [number
     ["n" nat]
     ["i" int]
     ["[0]" i64]]]
   ["[0]" world
    ["[0]" file]
    ["[1]/[0]" environment]]
   [meta
    ["@" target (.only)
     ["_" js]]
    [macro
     ["^" pattern]
     ["[0]" template]]
    [compiler
     ["[0]" phase (.only Operation Phase)]
     [reference
      [variable (.only Register)]]
     [language
      [lux
       [program (.only Program)]
       [generation (.only Host)]
       [analysis
        [macro (.only Expander)]]
       [phase
        ["[0]" extension (.only Extender Handler)
         ["[1]/[0]" bundle]
         ["[0]" analysis
          ["[1]" js]]
         ["[0]" generation
          ["[1]" js]]]
        [generation
         ["[0]" reference]
         ["[0]" js (.only)
          ["[0]" runtime]
          ["[1]/[0]" reference]]]]]]
     [default
      ["[0]" platform (.only Platform)]]
     [meta
      ["[0]" cli]
      ["[0]" context]
      [archive (.only Archive)
       ["[0]" unit]]
      ["[0]" packager
       ["[1]" script]]]]]]]
 [program
  ["/" compositor]])

(exception.def (null_has_no_lux_representation code)
  (Exception (Maybe _.Expression))
  (when code
    {.#Some code}
    (_.code code)

    {.#None}
    "???"))

(for @.jvm
     (these (import java/lang/String
              "[1]::[0]")

            (import (java/lang/Class a)
              "[1]::[0]")

            (import java/lang/Object
              "[1]::[0]"
              (toString [] java/lang/String)
              (getClass [] (java/lang/Class java/lang/Object)))

            (import java/lang/Long
              "[1]::[0]"
              (intValue [] int))

            (import java/lang/Integer
              "[1]::[0]"
              (longValue [] long))

            (import java/lang/Number
              "[1]::[0]"
              (intValue [] int)
              (longValue [] long)
              (doubleValue [] double))

            (import java/util/Arrays
              "[1]::[0]"
              ("static" [t] copyOfRange [[t] int int] [t]))

            (import javax/script/ScriptEngine
              "[1]::[0]"
              (eval [java/lang/String] "try" "?" java/lang/Object))

            (import javax/script/ScriptEngineFactory
              "[1]::[0]"
              (getScriptEngine [] javax/script/ScriptEngine))

            (import org/openjdk/nashorn/api/scripting/NashornScriptEngineFactory
              "[1]::[0]"
              (new []))

            (import org/openjdk/nashorn/api/scripting/JSObject
              "[1]::[0]"
              (isArray [] boolean)
              (isFunction [] boolean)
              (getSlot [int] "?" java/lang/Object)
              (getMember [java/lang/String] "?" java/lang/Object)
              (hasMember [java/lang/String] boolean)
              (call ["?" java/lang/Object [java/lang/Object]] "try" java/lang/Object))

            (import org/openjdk/nashorn/api/scripting/AbstractJSObject
              "[1]::[0]")

            (import org/openjdk/nashorn/api/scripting/ScriptObjectMirror
              "[1]::[0]"
              (size [] int)
              (toString [] java/lang/String)
              (getOwnKeys [boolean] [java/lang/String]))

            (import org/openjdk/nashorn/internal/runtime/Undefined
              "[1]::[0]")

            (with_template [<name>]
              [(ffi.interface <name>
                 (getValue [] java/lang/Object))

               (import <name>
                 "[1]::[0]"
                 (getValue [] java/lang/Object))]

              [IntValue]
              [StructureValue]
              )

            (exception.def (unknown_member [member object])
              (Exception [Text java/lang/Object])
              (exception.report
               (list ["Member" member]
                     ["Object" (debug.inspection object)])))

            (def jvm_int
              (-> (I64 Any) java/lang/Integer)
              (|>> .int
                   ffi.as_long
                   java/lang/Long::intValue))

            (def (js_int value)
              (-> Int org/openjdk/nashorn/api/scripting/JSObject)
              (<| (ffi.is org/openjdk/nashorn/api/scripting/JSObject)
                  (ffi.object [] org/openjdk/nashorn/api/scripting/AbstractJSObject [IntValue]
                    []
                    ... Methods
                    (IntValue
                     [] (getValue self []) java/lang/Object
                     (ffi.is java/lang/Object (ffi.as_long value)))
                    (org/openjdk/nashorn/api/scripting/AbstractJSObject
                     [] (getMember self [member java/lang/String]) java/lang/Object
                     (when (ffi.of_string member)
                       runtime.i64_high_field
                       (|> value
                           .nat
                           runtime.high
                           jvm_int
                           (ffi.is java/lang/Object))

                       runtime.i64_low_field
                       (|> value
                           .nat
                           runtime.low
                           jvm_int
                           (ffi.is java/lang/Object))

                       _
                       (panic! (exception.error ..unknown_member [(ffi.of_string member)
                                                                  (ffi.is java/lang/Object (ffi.as_long value))]))))
                    )))

            (def (::toString js_object)
              (-> Any org/openjdk/nashorn/api/scripting/JSObject)
              (<| (ffi.is org/openjdk/nashorn/api/scripting/JSObject)
                  (ffi.object [] org/openjdk/nashorn/api/scripting/AbstractJSObject []
                    []
                    (org/openjdk/nashorn/api/scripting/AbstractJSObject
                     [] (isFunction self []) boolean
                     (ffi.as_boolean true))
                    (org/openjdk/nashorn/api/scripting/AbstractJSObject
                     [] (call self [this java/lang/Object
                                    args [java/lang/Object]])
                     java/lang/Object
                     (|> js_object
                         debug.inspection
                         ffi.as_string
                         (ffi.is java/lang/Object)))
                    )))

            (def (::slice js_object value)
              (-> (-> java/lang/Object org/openjdk/nashorn/api/scripting/JSObject) (Array java/lang/Object) org/openjdk/nashorn/api/scripting/JSObject)
              (<| (ffi.is org/openjdk/nashorn/api/scripting/JSObject)
                  (ffi.object [] org/openjdk/nashorn/api/scripting/AbstractJSObject []
                    []
                    (org/openjdk/nashorn/api/scripting/AbstractJSObject
                     [] (isFunction self []) boolean
                     (ffi.as_boolean true))
                    (org/openjdk/nashorn/api/scripting/AbstractJSObject
                     [] (call self [this java/lang/Object
                                    args [java/lang/Object]])
                     java/lang/Object
                     (|> (java/util/Arrays::copyOfRange value
                                                        (|> args
                                                            (array.item 0)
                                                            maybe.trusted
                                                            (as Int)
                                                            ffi.as_int)
                                                        (ffi.as_int (.int (array.size value))))
                         (as java/lang/Object)
                         js_object
                         (ffi.is java/lang/Object)))
                    )))

            (def (js_structure value)
              (-> (Array java/lang/Object) org/openjdk/nashorn/api/scripting/JSObject)
              (let [js_object (is (-> java/lang/Object org/openjdk/nashorn/api/scripting/JSObject)
                                  (function (_ sub_value)
                                    (<| (when (ffi.as [java/lang/Object] sub_value)
                                          {.#Some sub_value}
                                          (|> sub_value
                                              (as (Array java/lang/Object))
                                              js_structure)

                                          {.#None})
                                        (when (ffi.as java/lang/Long sub_value)
                                          {.#Some sub_value}
                                          (|> sub_value
                                              ffi.of_long
                                              js_int)

                                          {.#None})
                                        ... else
                                        (as org/openjdk/nashorn/api/scripting/JSObject sub_value))))]
                (<| (ffi.is org/openjdk/nashorn/api/scripting/JSObject)
                    (ffi.object [] org/openjdk/nashorn/api/scripting/AbstractJSObject [StructureValue]
                      []
                      ... Methods
                      (StructureValue
                       [] (getValue self [])
                       java/lang/Object
                       (as java/lang/Object value))
                      (org/openjdk/nashorn/api/scripting/AbstractJSObject
                       [] (isArray self [])
                       boolean
                       (ffi.as_boolean true))
                      (org/openjdk/nashorn/api/scripting/AbstractJSObject
                       [] (getMember self [member java/lang/String])
                       java/lang/Object
                       (when (ffi.of_string member)
                         (^.or "toJSON" "toString")
                         (|> (::toString value)
                             (ffi.is java/lang/Object))
                         
                         "length"
                         (|> value
                             array.size
                             jvm_int
                             (ffi.is java/lang/Object))
                         
                         "slice"
                         (|> (::slice js_object value)
                             (ffi.is java/lang/Object))

                         runtime.variant_tag_field
                         (|> value
                             (array.item 0)
                             maybe.trusted)
                         
                         runtime.variant_flag_field
                         (when (array.item 1 value)
                           {.#Some set!}
                           set!

                           _
                           (ffi.null))
                         
                         runtime.variant_value_field
                         (|> value
                             (array.item 2)
                             maybe.trusted
                             js_object
                             (ffi.is java/lang/Object))
                         
                         _
                         (panic! (exception.error ..unknown_member [(as Text member) (as java/lang/Object value)]))))
                      (org/openjdk/nashorn/api/scripting/AbstractJSObject
                       [] (getSlot self [idx int])
                       java/lang/Object
                       (|> value
                           (array.item (|> idx java/lang/Integer::longValue (as Nat)))
                           maybe.trusted
                           js_object
                           (as java/lang/Object)))
                      ))))

            (exception.def undefined_has_no_lux_representation)

            (exception.def (unknown_kind_of_host_object object)
              (Exception java/lang/Object)
              (exception.report
               (list ["Class" (ffi.of_string (java/lang/Object::toString (java/lang/Object::getClass object)))]
                     ["Object" (ffi.of_string (java/lang/Object::toString object))]
                     ["Keys" (when (ffi.as org/openjdk/nashorn/api/scripting/ScriptObjectMirror object)
                               {.#Some object}
                               (|> object
                                   (org/openjdk/nashorn/api/scripting/ScriptObjectMirror::getOwnKeys true)
                                   (array.list {.#None})
                                   (%.list (|>> ffi.of_string %.text)))
                               
                               {.#None}
                               "???")])))

            (def (i32 half i64)
              (-> Text org/openjdk/nashorn/api/scripting/ScriptObjectMirror (Maybe Int))
              (|> i64
                  (org/openjdk/nashorn/api/scripting/JSObject::getMember [(ffi.as_string half)])
                  (maybe#each (|>> (ffi.as java/lang/Number)))
                  maybe#conjoint
                  (maybe#each (|>> java/lang/Number::longValue ffi.of_long))))

            (def (check_int js_object)
              (-> org/openjdk/nashorn/api/scripting/ScriptObjectMirror
                  (Maybe Int))
              (when [(..i32 runtime.i64_high_field js_object)
                     (..i32 runtime.i64_low_field js_object)]
                [{.#Some high} {.#Some low}]
                {.#Some (.int (n.+ (|> high .nat (i64.left_shifted 32))
                                   (if (i.< +0 (.int low))
                                     (|> low .nat (i64.left_shifted 32) (i64.right_shifted 32))
                                     (.nat low))))}

                _
                {.#None}))

            (def (check_variant lux_object js_object)
              (-> (-> java/lang/Object (Try Any))
                  org/openjdk/nashorn/api/scripting/ScriptObjectMirror
                  (Maybe Any))
              (when [(org/openjdk/nashorn/api/scripting/JSObject::getMember [(ffi.as_string runtime.variant_tag_field)] js_object)
                     (org/openjdk/nashorn/api/scripting/JSObject::getMember [(ffi.as_string runtime.variant_flag_field)] js_object)
                     (org/openjdk/nashorn/api/scripting/JSObject::getMember [(ffi.as_string runtime.variant_value_field)] js_object)]
                (^.multi [{.#Some tag} ?flag {.#Some value}]
                         [[(ffi.as java/lang/Number tag) (lux_object value)]
                          [{.#Some tag} {try.#Success value}]])
                {.#Some [(java/lang/Number::intValue (as java/lang/Number tag))
                         (maybe.else (ffi.null) ?flag)
                         value]}

                _
                {.#None}))

            (def (check_tuple lux_object js_object)
              (-> (-> java/lang/Object (Try Any))
                  org/openjdk/nashorn/api/scripting/ScriptObjectMirror
                  (Maybe (Array java/lang/Object)))
              (if (ffi.of_boolean (org/openjdk/nashorn/api/scripting/JSObject::isArray js_object))
                (let [num_keys (.nat (ffi.of_int (org/openjdk/nashorn/api/scripting/ScriptObjectMirror::size js_object)))]
                  (loop (again [idx 0
                                output (is (Array java/lang/Object)
                                           (array.empty num_keys))])
                    (if (n.< num_keys idx)
                      (when (org/openjdk/nashorn/api/scripting/JSObject::getMember (ffi.as_string (%.nat idx)) js_object)
                        {.#Some member}
                        (when (ffi.as org/openjdk/nashorn/internal/runtime/Undefined member)
                          {.#Some _}
                          (again (++ idx) output)

                          {.#None}
                          (when (lux_object member)
                            {try.#Success parsed_member}
                            (again (++ idx) (array.has! idx (as java/lang/Object parsed_member) output))

                            {try.#Failure error}
                            {.#None}))

                        {.#None}
                        (again (++ idx) output))
                      {.#Some output})))
                {.#None}))

            (def (lux_object js_object)
              (-> java/lang/Object (Try Any))
              (`` (<| (if (ffi.null? js_object)
                        (exception.except ..null_has_no_lux_representation [{.#None}]))
                      (when (ffi.as org/openjdk/nashorn/internal/runtime/Undefined js_object)
                        {.#Some _}
                        (exception.except ..undefined_has_no_lux_representation [])

                        {.#None})
                      (,, (with_template [<class>]
                            [(when (ffi.as <class> js_object)
                               {.#Some js_object}
                               {try.#Success js_object}

                               {.#None})]

                            [java/lang/Boolean] [java/lang/String]))
                      (,, (with_template [<class> <method>]
                            [(when (ffi.as <class> js_object)
                               {.#Some js_object}
                               {try.#Success (<method> js_object)}

                               {.#None})]

                            [java/lang/Number java/lang/Number::doubleValue]
                            [StructureValue StructureValue::getValue]
                            [IntValue IntValue::getValue]))
                      (when (ffi.as org/openjdk/nashorn/api/scripting/ScriptObjectMirror js_object)
                        {.#Some js_object}
                        (when (check_int js_object)
                          {.#Some value}
                          {try.#Success value}

                          {.#None}
                          (when (check_variant lux_object js_object)
                            {.#Some value}
                            {try.#Success value}

                            {.#None}
                            (when (check_tuple lux_object js_object)
                              {.#Some value}
                              {try.#Success value}

                              {.#None}
                              (if (ffi.of_boolean (org/openjdk/nashorn/api/scripting/JSObject::isFunction js_object))
                                {try.#Success js_object}
                                ... (exception.except ..unknown_kind_of_host_object [(as java/lang/Object js_object)])
                                {try.#Success js_object}
                                ))))
                        {.#None})
                      ... else
                      ... (exception.except ..unknown_kind_of_host_object [(as java/lang/Object js_object)])
                      {try.#Success js_object}
                      )))

            (def (ensure_function function)
              (-> Any (Maybe org/openjdk/nashorn/api/scripting/JSObject))
              (do maybe.monad
                [function (|> function
                              (as java/lang/Object)
                              (ffi.as org/openjdk/nashorn/api/scripting/JSObject))]
                (if (ffi.of_boolean (org/openjdk/nashorn/api/scripting/JSObject::isFunction function))
                  {.#Some function}
                  {.#None})))
            )

     @.js
     (these))

(for @.jvm
     (these (def (call_macro inputs lux macro)
              (-> (List Code) Lux org/openjdk/nashorn/api/scripting/JSObject (Try (Try [Lux (List Code)])))
              (let [to_js (is (-> Any java/lang/Object)
                              (|>> (as (Array java/lang/Object)) js_structure (as java/lang/Object)))]
                (<| (as (Try (Try [Lux (List Code)])))
                    (org/openjdk/nashorn/api/scripting/JSObject::call {.#None}
                                                                      (|> (array.empty 2)
                                                                          (is (Array java/lang/Object))
                                                                          (array.has! 0 (to_js inputs))
                                                                          (array.has! 1 (to_js lux)))
                                                                      macro))))

            (exception.def (cannot_apply_a_non_function object)
              (Exception java/lang/Object)
              (exception.report
               (list ["Object" (ffi.of_string (java/lang/Object::toString object))])))

            (def (expander macro inputs lux)
              Expander
              (when (..ensure_function macro)
                {.#Some macro}
                (when (call_macro inputs lux macro)
                  {try.#Success output}
                  (|> output
                      (as java/lang/Object)
                      lux_object
                      (as (Try (Try [Lux (List Code)]))))

                  {try.#Failure error}
                  {try.#Failure error})
                
                {.#None}
                (exception.except ..cannot_apply_a_non_function (as java/lang/Object macro))))
            )

     @.js
     (def (expander macro inputs lux)
       Expander
       {try.#Success ((as Macro' macro) inputs lux)})
     )

(for @.jvm
     (these (def (evaluate! interpreter alias input)
              (-> javax/script/ScriptEngine unit.ID _.Expression (Try Any))
              (do try.monad
                [?output (javax/script/ScriptEngine::eval (ffi.as_string (_.code input)) interpreter)]
                (when ?output
                  {.#Some output}
                  (..lux_object output)

                  {.#None}
                  (exception.except ..null_has_no_lux_representation [{.#Some input}]))))

            (def (execute! interpreter input)
              (-> javax/script/ScriptEngine _.Statement (Try Any))
              (do try.monad
                [?output (javax/script/ScriptEngine::eval (ffi.as_string (_.code input)) interpreter)]
                (in [])))

            (def (define! interpreter context custom input)
              (-> javax/script/ScriptEngine unit.ID (Maybe Text) _.Expression (Try [Text Any _.Statement]))
              (let [global (maybe.else (reference.artifact context)
                                       custom)
                    @global (_.var global)]
                (do try.monad
                  [.let [definition (_.define @global input)]
                   _ (execute! interpreter definition)
                   value (evaluate! interpreter context @global)]
                  (in [global value definition]))))

            (def host
              (IO (Host _.Expression _.Statement))
              (io (let [interpreter (javax/script/ScriptEngineFactory::getScriptEngine
                                     (org/openjdk/nashorn/api/scripting/NashornScriptEngineFactory::new))]
                    (is (Host _.Expression _.Statement)
                        (implementation
                         (def (evaluate alias [_ input]) (..evaluate! interpreter alias input))
                         (def execute (..execute! interpreter))
                         (def (define context custom [_ input]) (..define! interpreter context custom input))

                         (def (ingest context content)
                           (|> content (at utf8.codec decoded) try.trusted (as _.Statement)))

                         (def (re_learn context custom content)
                           (..execute! interpreter content))
                         
                         (def (re_load context custom content)
                           (do try.monad
                             [_ (..execute! interpreter content)]
                             (..evaluate! interpreter context (_.var (reference.artifact context))))))))))
            )

     @.js
     (these (def (eval code)
              (-> Text (Try (Maybe Any)))
              ... Note: I have to call "eval" this way
              ... in order to avoid a quirk of calling eval in Node
              ... when the code is running under "use strict";.
              (try (let [return ("js apply" (function.identity ("js constant" "eval")) [code])]
                     (if ("js object null?" return)
                       {.#None}
                       {.#Some return}))))
            
            (def (evaluate! alias input)
              (-> unit.ID _.Expression (Try Any))
              (do try.monad
                [?output (..eval (_.code input))]
                (when ?output
                  {.#Some output}
                  (in output)

                  {.#None}
                  (exception.except ..null_has_no_lux_representation [{.#Some input}]))))

            (def (execute! input)
              (-> _.Statement (Try Any))
              (do try.monad
                [?output (..eval (_.code input))]
                (in [])))

            (def (define! context custom input)
              (-> unit.ID (Maybe Text) _.Expression (Try [Text Any _.Statement]))
              (let [global (maybe.else (reference.artifact context)
                                       custom)
                    @global (_.var global)]
                (do try.monad
                  [.let [definition (_.define @global input)]
                   _ (..execute! definition)
                   value (..evaluate! context @global)]
                  (in [global value definition]))))

            (def host
              (IO (Host _.Expression _.Statement))
              (io (is (Host _.Expression _.Statement)
                      (implementation
                       (def (evaluate alias [_ input]) (..evaluate! alias input))
                       (def execute ..execute!)
                       (def (define context custom [_ input]) (..define! context custom input))

                       (def (ingest context content)
                         (|> content (at utf8.codec decoded) try.trusted (as _.Statement)))

                       (def (re_learn context custom content)
                         (..execute! content))
                       
                       (def (re_load context custom content)
                         (do try.monad
                           [_ (..execute! content)]
                           (..evaluate! context (_.var (reference.artifact context)))))))))
            ))

(def phase_wrapper
  phase.Wrapper
  (for @.jvm
       ... The implementation for @.jvm is technically incorrect.
       ... However, the JS compiler runs fast enough on Node to be fully hosted there.
       ... And running the JS compiler on the JVM (on top of Nashorn) is impractically slow.
       ... This means that in practice, only the @.js implementation matters.
       ... And since no cross-language boundary needs to be handled, it's a correct implementation.
       (|>>)

       @.js
       (|>>)))

(def platform
  (IO (Platform [Register Text] _.Expression _.Statement))
  (do io.monad
    [host ..host]
    (in [platform.#file_system (for @.jvm (file.async file.default)
                                    @.jvm (file.async file.default)
                                    ... TODO: Handle this in a safer manner.
                                    ... This would crash if the compiler was run on a browser.
                                    @.js (maybe.trusted file.default))
         platform.#host host
         platform.#phase js.generate
         platform.#runtime runtime.generate
         platform.#phase_wrapper ..phase_wrapper
         platform.#write (|>> _.code (at utf8.codec encoded))])))

(def (lux_program context program)
  (Program _.Expression _.Statement)
  (let [@process (_.var "process")
        on_node_js? (|> @process
                        _.type_of
                        (_.= (_.string "undefined"))
                        _.not
                        (_.and (_.the "argv" @process)))
        node_js_inputs (|> @process
                           (_.the "argv")
                           (_.do "slice" (list (_.int +2))))
        no_inputs (_.array (list))]
    (_.statement (_.apply_1 (_.apply_1 program (runtime.lux//program_args (_.? on_node_js?
                                                                               node_js_inputs
                                                                               no_inputs)))
                            (_.string "")))))

(for @.jvm
     (def extender
       Extender
       ... TODO: Stop relying on coercions ASAP.
       (<| (as Extender)
           (function (@self handler))
           (as Handler)
           (function (@self name phase))
           (as Phase)
           (function (@self archive parameters))
           (as Operation)
           (function (@self state))
           (as Try)
           try.trusted
           (as Try)
           (do try.monad
             [handler (try.of_maybe (..ensure_function handler))
              .let [to_js (is (-> Any java/lang/Object)
                              (|>> (as (Array java/lang/Object)) js_structure (as java/lang/Object)))]
              output (org/openjdk/nashorn/api/scripting/JSObject::call {.#None}
                                                                       (|> (array.empty 5)
                                                                           (is (Array java/lang/Object))
                                                                           (array.has! 0 name)
                                                                           (array.has! 1 (as java/lang/Object (extender phase)))
                                                                           (array.has! 2 (to_js archive))
                                                                           (array.has! 3 (to_js parameters))
                                                                           (array.has! 4 (to_js state)))
                                                                       handler)]
             (lux_object (as java/lang/Object output)))))

     @.js
     (def (extender phase_wrapper handler)
       (-> phase.Wrapper Extender)
       (as_expected handler)))

(def (declare_success! _)
  (-> Any (Async Any))
  (async.future (at world/environment.default exit +0)))

(def (scope body)
  (-> _.Statement _.Statement)
  (_.statement (_.apply (_.closure (list) body)
                        (list))))

(def (lux_compiler it)
  (-> Any platform.Custom)
  (undefined))

(def _
  (program [service cli.service]
    (let [context (context.js (cli.target service))]
      (exec
        (do async.monad
          [platform (async.future ..platform)
           _ (/.compiler ..lux_compiler
                         context
                         ..expander
                         analysis.bundle
                         (io.io platform)
                         generation.bundle
                         extension/bundle.empty
                         ..lux_program
                         (reference.constant js/reference.system)
                         ..extender
                         service
                         [(packager.package _.use_strict _.code _.then ..scope)
                          (format (cli.target service)
                                  (at (the platform.#file_system platform) separator)
                                  "program"
                                  (the context.#artifact_extension context))])]
          (..declare_success! []))
        (io.io [])))))