aboutsummaryrefslogtreecommitdiff
path: root/lux-ruby/source/program.lux
blob: 64a34c003fde32a9419ee113a89f587ef0f79974 (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
(.module:
  [lux #*
   [program (#+ program:)]
   ["." debug]
   ["." host (#+ import:)]
   ["." meta]
   [abstract
    ["." monad (#+ do)]]
   [control
    [pipe (#+ new>)]
    ["." try (#+ Try)]
    ["." exception (#+ exception:)]
    ["." io (#+ IO io)]
    [concurrency
     ["." promise (#+ Promise)]]
    ["<>" parser
     ["<.>" code]]]
   [data
    ["." maybe]
    ["." text ("#\." hash)
     ["%" format (#+ format)]
     ["." encoding]]
    [collection
     ["." array (#+ Array)]]]
   ["." macro
    [syntax (#+ syntax:)]
    ["." template]
    ["." code]]
   [math
    [number
     ["n" nat]
     ["i" int]
     ["." i64]]]
   ["." world #_
    ["." file]
    ["#/." program]]
   ["@" target
    ["_" ruby]]
   [tool
    [compiler
     [phase (#+ Operation Phase)]
     [reference
      [variable (#+ Register)]]
     [language
      [lux
       [program (#+ Program)]
       [generation (#+ Context Host)]
       ["." synthesis]
       [analysis
        [macro (#+ Expander)]]
       [phase
        ["." extension (#+ Bundle Extender Handler)
         ["#/." bundle]
         ["." analysis #_
          ["#" ruby]]
         ["." generation #_
          ["#" ruby]]]
        [generation
         ["." reference]
         ["." ruby
          ["." runtime]]]]]]
     [default
      ["." platform (#+ Platform)]]
     [meta
      ["." packager #_
       ["#" script]]]]]]
  [program
   ["/" compositor
    ["/." cli]
    ["/." static]]])

(import: java/lang/String)

(import: (java/lang/Class a))

(import: java/lang/Object
  ["#::."
   (toString [] java/lang/String)
   (getClass [] (java/lang/Class java/lang/Object))])

(import: java/lang/Integer
  ["#::."
   (longValue [] java/lang/Long)])

(import: java/lang/Long
  ["#::."
   (intValue [] java/lang/Integer)])

(import: org/jruby/RubyString
  ["#::."
   (#static newInternalFromJavaExternal [org/jruby/Ruby java/lang/String] org/jruby/RubyString)
   (asJavaString [] java/lang/String)])

(import: org/jruby/RubySymbol
  ["#::."
   (asJavaString [] java/lang/String)])

(import: org/jruby/runtime/builtin/IRubyObject)

(import: org/jruby/Ruby
  ["#::."
   (getCurrentContext [] org/jruby/runtime/ThreadContext)
   (getNil [] org/jruby/runtime/builtin/IRubyObject)])

(import: org/jruby/RubyClass)

(import: org/jruby/RubyArray
  ["#::."
   (getLength [] int)
   (get [int] #? Object)])

(import: org/jruby/RubyHash
  ["#::."
   (get [java/lang/Object] #? java/lang/Object)])

(import: org/jruby/runtime/ThreadContext)

(import: org/jruby/RubyRange
  ["#::."
   (first [org/jruby/runtime/ThreadContext] org/jruby/runtime/builtin/IRubyObject)
   (size [org/jruby/runtime/ThreadContext] org/jruby/runtime/builtin/IRubyObject)])

(template [<name>]
  [(host.interface: <name>
     (getValue [] java/lang/Object))

   (`` (import: (~~ (template.identifier ["program/" <name>]))
         ["#::."
          (getValue [] java/lang/Object)]))]

  [StructureValue]
  )

(syntax: (method_inputs {input_classes (<code>.tuple (<>.some <code>.any))})
  (monad.map meta.monad
             (function (_ class)
               (do meta.monad
                 [var (macro.gensym "input")]
                 (wrap (code.record (list [var class])))))
             input_classes))

(import: org/jruby/runtime/JavaSites$CheckedSites)
(import: org/jruby/runtime/builtin/Variable)
(import: org/jruby/runtime/builtin/InstanceVariables)
(import: org/jruby/runtime/builtin/InternalVariables)

(import: org/jruby/embed/internal/LocalContextProvider
  ["#::."
   (getRuntime [] org/jruby/Ruby)])

(import: org/jruby/embed/ScriptingContainer
  ["#::."
   (new [])
   (runScriptlet [java/lang/String] #try #? java/lang/Object)
   (getProvider [] org/jruby/embed/internal/LocalContextProvider)])

## TODO; Figure out a way to not need "interpreter" to be a global variable.
(def: interpreter
  (org/jruby/embed/ScriptingContainer::new))

(template: (!ruby_runtime)
  (|> ..interpreter
      org/jruby/embed/ScriptingContainer::getProvider
      org/jruby/embed/internal/LocalContextProvider::getRuntime))

(template: (!ruby_thread_context)
  (|> (!ruby_runtime)
      org/jruby/Ruby::getCurrentContext))

(def: initial_ruby_runtime
  (!ruby_runtime))

(import: org/jruby/java/proxies/JavaProxy
  ["#::."
   (new [org/jruby/Ruby org/jruby/RubyClass java/lang/Object])])

(import: org/jruby/internal/runtime/methods/DynamicMethod)

(import: org/jruby/runtime/callsite/CacheEntry
  ["#::."
   (new [org/jruby/internal/runtime/methods/DynamicMethod int])])

(import: org/jruby/RubyFixnum
  ["#::."
   (new [org/jruby/Ruby long])
   (getLongValue [] long)])

(import: org/jruby/RubyFloat
  ["#::."
   (new [org/jruby/Ruby double])])

(import: org/jruby/RubyBoolean
  ["#::."
   (#static newBoolean [org/jruby/Ruby boolean] org/jruby/RubyBoolean)])

(import: org/jruby/RubyNil
  ["#::."
   (new [org/jruby/Ruby])])

(import: org/jruby/RubyProc
  ["#::."
   (call [org/jruby/runtime/ThreadContext [org/jruby/runtime/builtin/IRubyObject]]
         #try org/jruby/runtime/builtin/IRubyObject)])

(type: Translator
  (-> java/lang/Object (Try Any)))

(def: (read_tuple read host_object)
  (-> Translator org/jruby/RubyArray (Try Any))
  (let [size (:coerce Nat (org/jruby/RubyArray::getLength host_object))]
    (loop [idx 0
           output (:coerce (Array Any) (array.new size))]
      (if (n.< size idx)
        (case (org/jruby/RubyArray::get (.int idx) host_object)
          #.None
          (recur (inc idx) output)
          
          (#.Some value)
          (case (read value)
            (#try.Failure error)
            (#try.Failure error)

            (#try.Success lux_value)
            (recur (inc idx) (array.write! idx lux_value output))))
        (#try.Success output)))))

(exception: (unknown_kind_of_object {object java/lang/Object})
  (exception.report
   ["Class" (java/lang/Object::toString (java/lang/Object::getClass object))]
   ["Object" (java/lang/Object::toString object)]))

(def: (read_variant read host_object)
  (-> Translator org/jruby/RubyHash (Try Any))
  (case [(org/jruby/RubyHash::get runtime.variant_tag_field host_object)
         (org/jruby/RubyHash::get runtime.variant_flag_field host_object)
         (org/jruby/RubyHash::get runtime.variant_value_field host_object)]
    (^multi [(#.Some tag) ?flag (#.Some value)]
            [(read value)
             (#.Some value)])
    (#try.Success [(java/lang/Long::intValue (:coerce java/lang/Long tag))
                   (: Any (case ?flag
                            (#.Some _)
                            ""

                            #.None
                            (host.null)))
                   value])

    _
    (exception.throw ..unknown_kind_of_object host_object)))

(exception: #export nil_has_no_lux_representation)

(def: (read host_object)
  Translator
  (`` (<| (if (host.null? host_object)
            (exception.throw ..nil_has_no_lux_representation []))
          (~~ (template [<class> <post_processing>]
                [(case (host.check <class> host_object)
                   (#.Some typed_object)
                   (|> typed_object <post_processing>)

                   _)]

                [java/lang/Boolean #try.Success]
                [java/lang/Long #try.Success]
                [java/lang/Double #try.Success]
                [java/lang/String #try.Success]
                [[java/lang/Object] #try.Success]
                [org/jruby/RubyArray (read_tuple read)]
                [org/jruby/RubyHash (read_variant read)]
                [org/jruby/RubySymbol #try.Success]
                [org/jruby/RubyProc #try.Success]
                ))
          (exception.throw ..unknown_kind_of_object host_object)
          )))

(def: ruby_nil
  org/jruby/runtime/builtin/IRubyObject
  (org/jruby/Ruby::getNil ..initial_ruby_runtime))

(def: lux_unit
  org/jruby/RubyString
  (org/jruby/RubyString::newInternalFromJavaExternal ..initial_ruby_runtime ""))

(def: (wrapped_lux_value lux_structure value)
  (-> (-> (Array java/lang/Object) org/jruby/runtime/builtin/IRubyObject)
      (-> java/lang/Object org/jruby/runtime/builtin/IRubyObject))
  (<| (case (host.check [java/lang/Object] value)
        (#.Some value)
        (|> value (:coerce (Array java/lang/Object)) lux_structure)

        #.None)
      (case (host.check java/lang/Boolean value)
        (#.Some value)
        (org/jruby/RubyBoolean::newBoolean ..initial_ruby_runtime value)
        
        #.None)
      (case (host.check java/lang/Long value)
        (#.Some value)
        (org/jruby/RubyFixnum::new ..initial_ruby_runtime value)
        
        #.None)
      (case (host.check java/lang/Double value)
        (#.Some value)
        (org/jruby/RubyFloat::new ..initial_ruby_runtime value)
        
        #.None)
      (case (host.check java/lang/String value)
        (#.Some value)
        (org/jruby/RubyString::newInternalFromJavaExternal ..initial_ruby_runtime value)
        
        #.None)
      (:coerce org/jruby/runtime/builtin/IRubyObject value)))

(exception: (invalid_variant_access {field Text})
  (exception.report
   ["Field" (%.text field)]))

(exception: (invalid_tuple_access {index Nat})
  (exception.report
   ["Index" (%.nat index)]))

(exception: (invalid_index {index java/lang/Object})
  (exception.report
   ["Class" (|> index
                java/lang/Object::getClass
                java/lang/Object::toString)]
   ["Index" (|> index
                java/lang/Object::toString)]))

(import: java/util/Arrays
  ["#::."
   (#static [t] copyOfRange [[t] int int] [t])])

(def: (lux_wrapper_access lux_structure value)
  (-> (-> (Array java/lang/Object) org/jruby/runtime/builtin/IRubyObject)
      (-> (Array java/lang/Object) org/jruby/internal/runtime/methods/DynamicMethod))
  (host.object [] org/jruby/internal/runtime/methods/DynamicMethod []
    [{java/lang/String "[]"}]

    (org/jruby/internal/runtime/methods/DynamicMethod
     [] (call self
              {thread_context org/jruby/runtime/ThreadContext}
              {self org/jruby/runtime/builtin/IRubyObject}
              {module org/jruby/RubyModule}
              {method java/lang/String}
              {args [org/jruby/runtime/builtin/IRubyObject]}
              {block org/jruby/runtime/Block})
     org/jruby/runtime/builtin/IRubyObject
     (let [member (host.array_read 0 args)]
       (<| (case (host.check org/jruby/RubyFixnum member)
             (#.Some member)
             (case (array.read (org/jruby/RubyFixnum::getLongValue member) value)
               (#.Some value)
               (wrapped_lux_value lux_structure value)

               #.None
               (error! (exception.construct ..invalid_tuple_access [(org/jruby/RubyFixnum::getLongValue member)])))

             #.None)
           (case (host.check org/jruby/RubyString member)
             (#.Some member)
             (case (:coerce Text (org/jruby/RubyString::asJavaString member))
               (^ (static runtime.variant_tag_field))
               (|> value
                   (array.read 0)
                   maybe.assume
                   (:coerce java/lang/Integer)
                   java/lang/Integer::longValue
                   (org/jruby/RubyFixnum::new ..initial_ruby_runtime))

               (^ (static runtime.variant_flag_field))
               (case (array.read 1 value)
                 #.None
                 ..ruby_nil
                 
                 (#.Some flag)
                 ..lux_unit)
               
               (^ (static runtime.variant_value_field))
               (case (array.read 2 value)
                 (#.Some value)
                 (wrapped_lux_value lux_structure value)

                 #.None
                 (error! (exception.construct ..nil_has_no_lux_representation [])))

               field
               (error! (exception.construct ..invalid_variant_access [field])))
             
             #.None)
           (case (host.check org/jruby/RubyRange member)
             (#.Some member)
             (case [(|> member (org/jruby/RubyRange::first thread_context) (host.check org/jruby/RubyFixnum))
                    (|> member (org/jruby/RubyRange::size thread_context) (host.check org/jruby/RubyFixnum))]
               [(#.Some first) (#.Some size)]
               (let [first (org/jruby/RubyFixnum::getLongValue first)
                     size (org/jruby/RubyFixnum::getLongValue size)]
                 (lux_structure (java/util/Arrays::copyOfRange value first (i.+ first size))))

               _
               (error! (exception.construct ..invalid_index (:coerce java/lang/Object member))))

             #.None)
           (error! (exception.construct ..invalid_index (:coerce java/lang/Object member))))))))

(def: (lux_wrapper_equality value)
  (-> (Array java/lang/Object) org/jruby/internal/runtime/methods/DynamicMethod)
  (host.object [] org/jruby/internal/runtime/methods/DynamicMethod []
    [{java/lang/String "=="}]

    (org/jruby/internal/runtime/methods/DynamicMethod
     [] (call self
              {thread_context org/jruby/runtime/ThreadContext}
              {self org/jruby/runtime/builtin/IRubyObject}
              {module org/jruby/RubyModule}
              {method java/lang/String}
              {args [org/jruby/runtime/builtin/IRubyObject]}
              {block org/jruby/runtime/Block})
     org/jruby/runtime/builtin/IRubyObject
     (let [reference (host.array_read 0 args)]
       (case (..read (:coerce java/lang/Object reference))
         (#try.Success reference)
         (org/jruby/RubyBoolean::newBoolean ..initial_ruby_runtime (is? (: Any reference) (: Any value)))
         
         (#try.Failure error)
         (org/jruby/RubyBoolean::newBoolean ..initial_ruby_runtime false))))))

(def: (lux_wrapper_length value)
  (-> (Array java/lang/Object) org/jruby/internal/runtime/methods/DynamicMethod)
  (host.object [] org/jruby/internal/runtime/methods/DynamicMethod []
    [{java/lang/String "length"}]

    (org/jruby/internal/runtime/methods/DynamicMethod
     [] (call self
              {thread_context org/jruby/runtime/ThreadContext}
              {self org/jruby/runtime/builtin/IRubyObject}
              {module org/jruby/RubyModule}
              {method java/lang/String}
              {args [org/jruby/runtime/builtin/IRubyObject]}
              {block org/jruby/runtime/Block})
     org/jruby/runtime/builtin/IRubyObject
     (|> value
         array.size
         (org/jruby/RubyFixnum::new ..initial_ruby_runtime)))))

(def: (lux_wrapper_to_s value)
  (-> (Array java/lang/Object) org/jruby/internal/runtime/methods/DynamicMethod)
  (host.object [] org/jruby/internal/runtime/methods/DynamicMethod []
    [{java/lang/String "to_s"}]

    (org/jruby/internal/runtime/methods/DynamicMethod
     [] (call self
              {thread_context org/jruby/runtime/ThreadContext}
              {self org/jruby/runtime/builtin/IRubyObject}
              {module org/jruby/RubyModule}
              {method java/lang/String}
              {args [org/jruby/runtime/builtin/IRubyObject]}
              {block org/jruby/runtime/Block})
     org/jruby/runtime/builtin/IRubyObject
     (|> value
         debug.inspect
         (org/jruby/RubyString::newInternalFromJavaExternal ..initial_ruby_runtime)))))

(exception: (invalid_operation {method Text})
  (exception.report
   ["Method" (%.text method)]))

(def: (lux_wrapper_respond_to? value)
  (-> (Array java/lang/Object) org/jruby/internal/runtime/methods/DynamicMethod)
  (host.object [] org/jruby/internal/runtime/methods/DynamicMethod []
    [{java/lang/String "respond_to?"}]

    (org/jruby/internal/runtime/methods/DynamicMethod
     [] (call self
              {thread_context org/jruby/runtime/ThreadContext}
              {self org/jruby/runtime/builtin/IRubyObject}
              {module org/jruby/RubyModule}
              {method java/lang/String}
              {args [org/jruby/runtime/builtin/IRubyObject]}
              {block org/jruby/runtime/Block})
     org/jruby/runtime/builtin/IRubyObject
     (case (|> args
               (host.array_read 0)
               (host.check org/jruby/RubySymbol))
       (#.Some method)
       (|> (case (|> method
                     org/jruby/RubySymbol::asJavaString
                     (:coerce Text))
             (^or "==" "equal?"
                  "to_s" "inspect"
                  "[]" "length" "respond_to?"
                  ## "to_hash"
                  )
             true
             
             _
             false)
           (org/jruby/RubyBoolean::newBoolean ..initial_ruby_runtime))

       #.None
       (error! (exception.construct ..invalid_operation ["respond_to?"]))))))

(exception: (unknown_method {method Text})
  (exception.report
   ["Method" (%.text method)]))

(def: (lux_structure value)
  (-> (Array java/lang/Object) org/jruby/runtime/builtin/IRubyObject)
  (let [meta_class (host.object [] org/jruby/RubyClass []
                     [{org/jruby/Ruby
                       ..initial_ruby_runtime}]

                     (org/jruby/RubyClass
                      [] (searchWithCache self
                                          {method java/lang/String})
                      org/jruby/runtime/callsite/CacheEntry
                      (case (:coerce Text method)
                        "[]"
                        (org/jruby/runtime/callsite/CacheEntry::new (..lux_wrapper_access lux_structure value) 0)

                        (^or "==" "equal?")
                        (org/jruby/runtime/callsite/CacheEntry::new (..lux_wrapper_equality value) 1)

                        "length"
                        (org/jruby/runtime/callsite/CacheEntry::new (..lux_wrapper_length value) 2)

                        (^or "to_s" "inspect")
                        (org/jruby/runtime/callsite/CacheEntry::new (..lux_wrapper_to_s value) 3)

                        "respond_to?"
                        (org/jruby/runtime/callsite/CacheEntry::new (..lux_wrapper_respond_to? value) 4)

                        _
                        (error! (exception.construct ..unknown_method [(:coerce Text method)])))))]
    (org/jruby/java/proxies/JavaProxy::new ..initial_ruby_runtime meta_class (:coerce java/lang/Object value))))

(exception: (cannot_apply_a_non_function {object java/lang/Object})
  (exception.report
   ["Non-function" (java/lang/Object::toString object)]))

(def: ensure_macro
  (-> Macro (Maybe org/jruby/RubyProc))
  (|>> (:coerce java/lang/Object) (host.check org/jruby/RubyProc)))

(def: to_host
  (-> Any org/jruby/runtime/builtin/IRubyObject)
  (|>> (:coerce (Array java/lang/Object))
       ..lux_structure))

(def: (call_macro inputs lux macro)
  (-> (List Code) Lux org/jruby/RubyProc (Try (Try [Lux (List Code)])))
  (:assume
   (do try.monad
     [expansion (org/jruby/RubyProc::call (!ruby_thread_context)
                                          (|> (host.array org/jruby/runtime/builtin/IRubyObject 2)
                                              (host.array_write 0 (..to_host inputs))
                                              (host.array_write 1 (..to_host lux)))
                                          macro)]
     (..read (:coerce java/lang/Object expansion)))))

(def: (expander macro inputs lux)
  Expander
  (case (ensure_macro macro)
    (#.Some macro)
    (case (call_macro inputs lux macro)
      (#try.Success output)
      (|> output
          (:coerce java/lang/Object)
          ..read
          (:coerce (Try (Try [Lux (List Code)]))))

      (#try.Failure error)
      (#try.Failure error))

    #.None
    (exception.throw ..cannot_apply_a_non_function (:coerce java/lang/Object macro))))

(def: separator "___")

(def: host
  (IO (Host _.Expression _.Statement))
  (io (let [run! (: (-> (_.Code Any) (Try Any))
                    (function (_ code)
                      (do try.monad
                        [output (org/jruby/embed/ScriptingContainer::runScriptlet (_.code code) ..interpreter)]
                        (..read (maybe.default (:coerce java/lang/Object [])
                                               output)))))]
        (: (Host _.Expression _.Statement)
           (structure
            (def: (evaluate! context code)
              (run! code))

            (def: execute! run!)

            (def: (define! context input)
              (let [global (reference.artifact context)
                    @global (_.global global)]
                (do try.monad
                  [#let [definition (_.set (list @global) input)]
                   value (run! definition)]
                  (wrap [global value definition]))))

            (def: (ingest context content)
              (|> content
                  (\ encoding.utf8 decode)
                  try.assume
                  (:coerce _.Statement)))

            (def: (re_learn context content)
              (run! content))
            
            (def: (re_load context content)
              (do try.monad
                [_ (run! content)]
                (run! (_.global (reference.artifact context))))))))))

(def: platform
  (IO (Platform Register _.Expression _.Statement))
  (do io.monad
    [host ..host]
    (wrap {#platform.&file_system (file.async file.default)
           #platform.host host
           #platform.phase ruby.generate
           #platform.runtime runtime.generate
           #platform.write (|>> _.code (\ encoding.utf8 encode))})))

(def: (program context program)
  (Program _.Expression _.Statement)
  (_.statement (_.apply_lambda/* (list (runtime.lux//program_args _.command_line_arguments)
                                       _.nil)
                                 program)))

(def: extender
  Extender
  ## TODO: Stop relying on coercions ASAP.
  (<| (:coerce Extender)
      (function (@self handler))
      (:coerce Handler)
      (function (@self name phase))
      (:coerce Phase)
      (function (@self archive parameters))
      (:coerce Operation)
      (function (@self state))
      (:coerce Try)
      try.assume
      (:coerce Try)
      (do try.monad
        [handler (try.from_maybe (..ensure_macro handler))
         output (org/jruby/RubyProc::call (!ruby_thread_context)
                                          (|> (host.array org/jruby/runtime/builtin/IRubyObject 5)
                                              (host.array_write 0 (org/jruby/RubyString::newInternalFromJavaExternal (!ruby_runtime) name))
                                              (host.array_write 1 (..to_host phase))
                                              (host.array_write 2 (..to_host archive))
                                              (host.array_write 3 (..to_host parameters))
                                              (host.array_write 4 (..to_host state)))
                                          handler)]
        (..read (:coerce java/lang/Object output)))))

(def: (declare_success! _)
  (-> Any (Promise Any))
  (promise.future (\ world/program.default exit +0)))

(program: [{service /cli.service}]
  (let [extension ".rb"]
    (exec (do promise.monad
            [_ (/.compiler {#/static.host @.ruby
                            #/static.host_module_extension extension
                            #/static.target (/cli.target service)
                            #/static.artifact_extension extension}
                           ..expander
                           analysis.bundle
                           ..platform
                           generation.bundle
                           extension/bundle.empty
                           ..program
                           [Register _.Expression _.Statement]
                           ..extender
                           service
                           [(packager.package (: _.Statement (_.manual ""))
                                              _.code
                                              _.then
                                              (|>>))
                            (format (/cli.target service)
                                    (\ file.default separator)
                                    "program"
                                    extension)])]
            (..declare_success! []))
      (io.io []))))