aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/lux/tool/compiler/phase/generation/js/runtime.lux
blob: 9102dd30dbe55dd3cfd05d4fb3a485c7c5a5b526 (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
(.module:
  [lux #*
   [abstract
    [monad (#+ do)]]
   [control
    ["." function]
    ["p" parser]]
   [data
    [number (#+ hex)
     ["." i64]]
    ["." text
     format]
    [collection
     ["." list ("#;." functor)]]]
   ["." macro
    ["." code]
    ["s" syntax (#+ syntax:)]]
   [host
    ["_" js (#+ Expression Var Computation Statement)]]]
  ["." ///
   ["//." //
    [//
     ["/////." name]
     ["." synthesis]]]]
  )

(template [<name> <base>]
  [(type: #export <name>
     (<base> Var Expression Statement))]

  [Operation ///.Operation]
  [Phase ///.Phase]
  [Handler ///.Handler]
  [Bundle ///.Bundle]
  )

(type: #export (Generator i)
  (-> i Phase (Operation Expression)))

(def: prefix Text "LuxRuntime")

(def: #export high
  (-> (I64 Any) (I64 Any))
  (i64.logic-right-shift 32))

(def: #export low
  (-> (I64 Any) (I64 Any))
  (let [mask (dec (i64.left-shift 32 1))]
    (|>> (i64.and mask))))

(def: #export variant-tag-field "_lux_tag")
(def: #export variant-flag-field "_lux_flag")
(def: #export variant-value-field "_lux_value")

(def: #export unit Computation (_.string synthesis.unit))

(def: #export (flag value)
  (-> Bit Computation)
  (if value
    (_.string "")
    _.null))

(def: #export (variant tag last? value)
  (-> Expression Expression Expression Computation)
  (_.object (list [..variant-tag-field tag]
                  [..variant-flag-field last?]
                  [..variant-value-field value])))

(def: none
  Computation
  (..variant (_.i32 +0) (flag #0) unit))

(def: some
  (-> Expression Computation)
  (..variant (_.i32 +1) (flag #1)))

(def: left
  (-> Expression Computation)
  (..variant (_.i32 +0) (flag #0)))

(def: right
  (-> Expression Computation)
  (..variant (_.i32 +1) (flag #1)))

(def: variable
  (-> Text Var)
  (|>> /////name.normalize
       _.var))

(def: runtime-name
  (-> Text Var)
  (|>> /////name.normalize
       (format ..prefix "$")
       _.var))

(def: (feature name definition)
  (-> Var (-> Var Expression) Statement)
  (_.define name (definition name)))

(syntax: #export (with-vars {vars (s.tuple (p.some s.local-identifier))}
                   body)
  (wrap (list (` (let [(~+ (|> vars
                               (list;map (function (_ var)
                                           (list (code.local-identifier var)
                                                 (` (_.var (~ (code.text (/////name.normalize var))))))))
                               list.concat))]
                   (~ body))))))

(syntax: (runtime: {declaration (p.or s.local-identifier
                                      (s.form (p.and s.local-identifier
                                                     (p.some s.local-identifier))))}
           code)
  (case declaration
    (#.Left name)
    (macro.with-gensyms [g!_]
      (let [nameC (code.local-identifier name)
            code-nameC (code.local-identifier (format "@" name))
            runtime-nameC (` (runtime-name (~ (code.text name))))]
        (wrap (list (` (def: #export (~ nameC) Var (~ runtime-nameC)))
                    (` (def: (~ code-nameC)
                         Statement
                         (..feature (~ runtime-nameC)
                                    (function ((~ g!_) (~ nameC))
                                      (~ code)))))))))
    
    (#.Right [name inputs])
    (macro.with-gensyms [g!_]
      (let [nameC (code.local-identifier name)
            code-nameC (code.local-identifier (format "@" name))
            runtime-nameC (` (runtime-name (~ (code.text name))))
            inputsC (list;map code.local-identifier inputs)
            inputs-typesC (list;map (function.constant (` _.Expression)) inputs)]
        (wrap (list (` (def: #export ((~ nameC) (~+ inputsC))
                         (-> (~+ inputs-typesC) Computation)
                         (_.apply/* (~ runtime-nameC) (list (~+ inputsC)))))
                    (` (def: (~ code-nameC)
                         Statement
                         (..feature (~ runtime-nameC)
                                    (function ((~ g!_) (~ g!_))
                                      (..with-vars [(~+ inputsC)]
                                        (_.function (~ g!_) (list (~+ inputsC))
                                          (~ code)))))))))))))

(runtime: (lux//try op)
  (with-vars [ex]
    (_.try (_.return (_.apply/1 op ..unit))
           [ex (_.return (|> ex (_.do "toString" (list))))])))

(def: length
  (-> Expression Computation)
  (_.the "length"))

(def: last-index
  (-> Expression Computation)
  (|>> ..length (_.- (_.i32 +1))))

(def: (last-element tuple)
  (_.at (..last-index tuple)
        tuple))

(runtime: (lux//program-args inputs)
  (with-vars [output idx]
    ($_ _.then
        (_.define output ..none)
        (_.for idx
               (..last-index inputs)
               (_.>= (_.i32 +0) idx)
               (_.-- idx)
               (_.set output (..some (_.array (list (_.at idx inputs)
                                                    output)))))
        (_.return output))))

(def: runtime//lux
  Statement
  ($_ _.then
      @lux//try
      @lux//program-args
      ))

(runtime: (tuple//left lefts tuple)
  (with-vars [last-index-right]
    ($_ _.then
        (_.define last-index-right (..last-index tuple))
        (_.if (_.> lefts last-index-right)
          ## No need for recursion
          (_.return (_.at lefts tuple))
          ## Needs recursion
          (_.return (tuple//left (_.- last-index-right lefts)
                                 (_.at last-index-right tuple)))))))

(runtime: (tuple//right lefts tuple)
  (with-vars [last-index-right right-index]
    ($_ _.then
        (_.define last-index-right (..last-index tuple))
        (_.define right-index (_.+ (_.i32 +1) lefts))
        (_.cond (list [(_.= right-index last-index-right)
                       (_.return (_.at right-index tuple))]
                      [(_.> right-index last-index-right)
                       ## Needs recursion.
                       (_.return (tuple//right (_.- last-index-right lefts)
                                               (_.at last-index-right tuple)))])
                (_.return (_.do "slice" (list right-index) tuple)))
        )))

(runtime: (sum//get sum wants-last wanted-tag)
  (let [no-match! (_.return _.null)
        sum-tag (|> sum (_.the ..variant-tag-field))
        sum-flag (|> sum (_.the ..variant-flag-field))
        sum-value (|> sum (_.the ..variant-value-field))
        is-last? (_.= ..unit sum-flag)
        extact-match! (_.return sum-value)
        test-recursion! (_.if is-last?
                          ## Must recurse.
                          (_.return (sum//get sum-value (_.- sum-tag wanted-tag) wants-last))
                          no-match!)
        extrac-sub-variant! (_.return (..variant (_.- wanted-tag sum-tag) sum-flag sum-value))]
    (_.cond (list [(_.= wanted-tag sum-tag)
                   (_.if (_.= wants-last sum-flag)
                     extact-match!
                     test-recursion!)]
                  [(_.< wanted-tag sum-tag)
                   test-recursion!]
                  [(_.and (_.> wanted-tag sum-tag)
                          (_.= ..unit wants-last))
                   extrac-sub-variant!])
            no-match!)))

(def: runtime//structure
  Statement
  ($_ _.then
      @tuple//left
      @tuple//right
      @sum//get
      ))

(def: #export i64-high-field Text "_lux_high")
(def: #export i64-low-field Text "_lux_low")

(runtime: (i64//new high low)
  (_.return (_.object (list [..i64-high-field high]
                            [..i64-low-field low]))))

(runtime: i64//2^16
  (_.left-shift (_.i32 +16) (_.i32 +1)))

(runtime: i64//2^32
  (_.* i64//2^16 i64//2^16))

(runtime: i64//2^64
  (_.* i64//2^32 i64//2^32))

(runtime: i64//2^63
  (|> i64//2^64 (_./ (_.i32 +2))))

(runtime: (i64//unsigned-low i64)
  (_.return (_.? (|> i64 (_.the ..i64-low-field) (_.>= (_.i32 +0)))
                 (|> i64 (_.the ..i64-low-field))
                 (|> i64 (_.the ..i64-low-field) (_.+ i64//2^32)))))

(runtime: (i64//to-number i64)
  (_.return (|> i64 (_.the ..i64-high-field) (_.* i64//2^32)
                (_.+ (i64//unsigned-low i64)))))

(runtime: i64//zero
  (i64//new (_.i32 +0) (_.i32 +0)))

(runtime: i64//min
  (i64//new (_.i32 (hex "+80000000")) (_.i32 +0)))

(runtime: i64//max
  (i64//new (_.i32 (hex "+7FFFFFFF")) (_.i32 (hex "+FFFFFFFF"))))

(runtime: i64//one
  (i64//new (_.i32 +0) (_.i32 +1)))

(runtime: (i64//= reference sample)
  (_.return (_.and (_.= (_.the ..i64-high-field reference)
                        (_.the ..i64-high-field sample))
                   (_.= (_.the ..i64-low-field reference)
                        (_.the ..i64-low-field sample)))))

(runtime: (i64//+ parameter subject)
  (let [up-16 (_.left-shift (_.i32 +16))
        high-16 (_.logic-right-shift (_.i32 +16))
        low-16 (_.bit-and (_.i32 (hex "+FFFF")))
        hh (|>> (_.the ..i64-high-field) high-16)
        hl (|>> (_.the ..i64-high-field) low-16)
        lh (|>> (_.the ..i64-low-field) high-16)
        ll (|>> (_.the ..i64-low-field) low-16)]
    (with-vars [l48 l32 l16 l00
                r48 r32 r16 r00
                x48 x32 x16 x00]
      ($_ _.then
          (_.define l48 (hh subject))
          (_.define l32 (hl subject))
          (_.define l16 (lh subject))
          (_.define l00 (ll subject))

          (_.define r48 (hh parameter))
          (_.define r32 (hl parameter))
          (_.define r16 (lh parameter))
          (_.define r00 (ll parameter))

          (_.define x00 (_.+ l00 r00))
          (_.define x16 (high-16 x00))
          (_.set x00 (low-16 x00))
          (_.set x16 (|> x16 (_.+ l16) (_.+ r16)))
          (_.define x32 (high-16 x16))
          (_.set x16 (low-16 x16))
          (_.set x32 (|> x32 (_.+ l32) (_.+ r32)))
          (_.define x48 (|> (high-16 x32) (_.+ l48) (_.+ r48) low-16))
          (_.set x32 (low-16 x32))

          (_.return (i64//new (_.bit-or (up-16 x48) x32)
                              (_.bit-or (up-16 x16) x00)))
          ))))

(template [<name> <op>]
  [(runtime: (<name> subject parameter)
     (_.return (i64//new (<op> (_.the ..i64-high-field subject)
                               (_.the ..i64-high-field parameter))
                         (<op> (_.the ..i64-low-field subject)
                               (_.the ..i64-low-field parameter)))))]

  [i64//xor _.bit-xor]
  [i64//or  _.bit-or]
  [i64//and _.bit-and]
  )

(runtime: (i64//not value)
  (_.return (i64//new (_.bit-not (_.the ..i64-high-field value))
                      (_.bit-not (_.the ..i64-low-field value)))))

(runtime: (i64//negate value)
  (_.if (i64//= i64//min value)
    (_.return i64//min)
    (_.return (i64//+ i64//one (i64//not value)))))

(runtime: i64//-one
  (i64//negate i64//one))

(runtime: (i64//from-number value)
  (_.cond (list [(_.not-a-number? value)
                 (_.return i64//zero)]
                [(_.<= (_.negate i64//2^63) value)
                 (_.return i64//min)]
                [(|> value (_.+ (_.i32 +1)) (_.>= i64//2^63))
                 (_.return i64//max)]
                [(|> value (_.< (_.i32 +0)))
                 (_.return (|> value _.negate i64//from-number i64//negate))])
          (_.return (i64//new (|> value (_./ i64//2^32) _.to-i32)
                              (|> value (_.% i64//2^32) _.to-i32)))))

(def: (cap-shift! shift)
  (-> Var Statement)
  (_.set shift (|> shift (_.bit-and (_.i32 +63)))))

(def: (no-shift! shift input)
  (-> Var Var [Expression Statement])
  [(|> shift (_.= (_.i32 +0)))
   (_.return input)])

(def: small-shift?
  (-> Var Expression)
  (|>> (_.< (_.i32 +32))))

(runtime: (i64//left-shift input shift)
  ($_ _.then
      (..cap-shift! shift)
      (_.cond (list (..no-shift! shift input)
                    [(..small-shift? shift)
                     (let [high (_.bit-or (|> input (_.the ..i64-high-field) (_.left-shift shift))
                                          (|> input (_.the ..i64-low-field) (_.logic-right-shift (_.- shift (_.i32 +32)))))
                           low (|> input (_.the ..i64-low-field) (_.left-shift shift))]
                       (_.return (i64//new high low)))])
              (let [high (|> input (_.the ..i64-low-field) (_.left-shift (_.- (_.i32 +32) shift)))]
                (_.return (i64//new high (_.i32 +0)))))))

(runtime: (i64//arithmetic-right-shift input shift)
  ($_ _.then
      (..cap-shift! shift)
      (_.cond (list (..no-shift! shift input)
                    [(..small-shift? shift)
                     (let [high (|> input (_.the ..i64-high-field) (_.arithmetic-right-shift shift))
                           low (|> input (_.the ..i64-low-field) (_.logic-right-shift shift)
                                   (_.bit-or (|> input (_.the ..i64-high-field) (_.left-shift (_.- shift (_.i32 +32))))))]
                       (_.return (i64//new high low)))])
              (let [high (_.? (|> input (_.the ..i64-high-field) (_.>= (_.i32 +0)))
                              (_.i32 +0)
                              (_.i32 -1))
                    low (|> input (_.the ..i64-high-field) (_.arithmetic-right-shift (_.- (_.i32 +32) shift)))]
                (_.return (i64//new high low))))))

(runtime: (i64//logic-right-shift input shift)
  ($_ _.then
      (..cap-shift! shift)
      (_.cond (list (..no-shift! shift input)
                    [(..small-shift? shift)
                     (let [high (|> input (_.the ..i64-high-field) (_.logic-right-shift shift))
                           low (|> input (_.the ..i64-low-field) (_.logic-right-shift shift)
                                   (_.bit-or (|> input (_.the ..i64-high-field) (_.left-shift (_.- shift (_.i32 +32))))))]
                       (_.return (i64//new high low)))]
                    [(|> shift (_.= (_.i32 +32)))
                     (_.return (i64//new (_.i32 +0) (|> input (_.the ..i64-high-field))))])
              (_.return (i64//new (_.i32 +0)
                                  (|> input (_.the ..i64-high-field) (_.logic-right-shift (_.- (_.i32 +32) shift))))))))

(def: runtime//bit
  Statement
  ($_ _.then
      @i64//and
      @i64//or
      @i64//xor
      @i64//not
      @i64//left-shift
      @i64//arithmetic-right-shift
      @i64//logic-right-shift
      ))

(runtime: (i64//- parameter subject)
  (_.return (i64//+ (i64//negate parameter) subject)))

(runtime: (i64//* parameter subject)
  (let [negative? (|>> (_.the ..i64-high-field) (_.< (_.i32 +0)))]
    (_.cond (list [(negative? subject)
                   (_.if (negative? parameter)
                     ## Both are negative
                     (_.return (i64//* (i64//negate parameter) (i64//negate subject)))
                     ## Subject is negative
                     (_.return (i64//negate (i64//* parameter (i64//negate subject)))))]
                  [(negative? parameter)
                   ## Parameter is negative
                   (_.return (i64//negate (i64//* (i64//negate parameter) subject)))])
            ## Both are positive
            (let [up-16 (_.left-shift (_.i32 +16))
                  high-16 (_.logic-right-shift (_.i32 +16))
                  low-16 (_.bit-and (_.i32 (hex "+FFFF")))
                  hh (|>> (_.the ..i64-high-field) high-16)
                  hl (|>> (_.the ..i64-high-field) low-16)
                  lh (|>> (_.the ..i64-low-field) high-16)
                  ll (|>> (_.the ..i64-low-field) low-16)]
              (with-vars [l48 l32 l16 l00
                          r48 r32 r16 r00
                          x48 x32 x16 x00]
                ($_ _.then
                    (_.define l48 (hh subject))
                    (_.define l32 (hl subject))
                    (_.define l16 (lh subject))
                    (_.define l00 (ll subject))

                    (_.define r48 (hh parameter))
                    (_.define r32 (hl parameter))
                    (_.define r16 (lh parameter))
                    (_.define r00 (ll parameter))

                    (_.define x00 (_.* l00 r00))
                    (_.define x16 (high-16 x00))
                    (_.set x00 (low-16 x00))
                    
                    (_.set x16 (|> x16 (_.+ (_.* l16 r00))))
                    (_.define x32 (high-16 x16)) (_.set x16 (low-16 x16))
                    (_.set x16 (|> x16 (_.+ (_.* l00 r16))))
                    (_.set x32 (|> x32 (_.+ (high-16 x16)))) (_.set x16 (low-16 x16))

                    (_.set x32 (|> x32 (_.+ (_.* l32 r00))))
                    (_.define x48 (high-16 x32)) (_.set x32 (low-16 x32))
                    (_.set x32 (|> x32 (_.+ (_.* l16 r16))))
                    (_.set x48 (|> x48 (_.+ (high-16 x32)))) (_.set x32 (low-16 x32))
                    (_.set x32 (|> x32 (_.+ (_.* l00 r32))))
                    (_.set x48 (|> x48 (_.+ (high-16 x32)))) (_.set x32 (low-16 x32))
                    
                    (_.set x48 (|> x48
                                   (_.+ (_.* l48 r00))
                                   (_.+ (_.* l32 r16))
                                   (_.+ (_.* l16 r32))
                                   (_.+ (_.* l00 r48))
                                   low-16))

                    (_.return (i64//new (_.bit-or (up-16 x48) x32)
                                        (_.bit-or (up-16 x16) x00)))
                    ))))))

(runtime: (i64//< parameter subject)
  (let [negative? (|>> (_.the ..i64-high-field) (_.< (_.i32 +0)))]
    (with-vars [-subject? -parameter?]
      ($_ _.then
          (_.define -subject? (negative? subject))
          (_.define -parameter? (negative? parameter))
          (_.cond (list [(_.and -subject? (_.not -parameter?))
                         (_.return _.true)]
                        [(_.and (_.not -subject?) -parameter?)
                         (_.return _.false)])
                  (_.return (negative? (i64//- parameter subject))))))))

(def: (i64//<= param subject)
  (-> Expression Expression Expression)
  (_.or (i64//< param subject)
        (i64//= param subject)))

(runtime: (i64/// parameter subject)
  (let [negative? (function (_ value)
                    (i64//< i64//zero value))
        valid-division-check [(i64//= i64//zero parameter)
                              (_.throw (_.string "Cannot divide by zero!"))]
        short-circuit-check [(i64//= i64//zero subject)
                             (_.return i64//zero)]]
    (_.cond (list valid-division-check
                  short-circuit-check

                  [(i64//= i64//min subject)
                   (_.cond (list [(_.or (i64//= i64//one parameter)
                                        (i64//= i64//-one parameter))
                                  (_.return i64//min)]
                                 [(i64//= i64//min parameter)
                                  (_.return i64//one)])
                           (with-vars [approximation]
                             (let [subject/2 (i64//arithmetic-right-shift subject (_.i32 +1))]
                               ($_ _.then
                                   (_.define approximation (i64//left-shift (i64/// parameter
                                                                                    subject/2)
                                                                            (_.i32 +1)))
                                   (_.if (i64//= i64//zero approximation)
                                     (_.return (_.? (negative? parameter)
                                                    i64//one
                                                    i64//-one))
                                     (let [remainder (i64//- (i64//* approximation
                                                                     parameter)
                                                             subject)]
                                       (_.return (i64//+ (i64/// parameter
                                                                 remainder)
                                                         approximation))))))))]
                  [(i64//= i64//min parameter)
                   (_.return i64//zero)]

                  [(negative? subject)
                   (_.return (_.? (negative? parameter)
                                  (i64/// (i64//negate parameter)
                                          (i64//negate subject))
                                  (i64//negate (i64/// parameter
                                                       (i64//negate subject)))))]

                  [(negative? parameter)
                   (_.return (i64//negate (i64/// (i64//negate parameter) subject)))])
            (with-vars [result remainder]
              ($_ _.then
                  (_.define result i64//zero)
                  (_.define remainder subject)
                  (_.while (i64//<= remainder parameter)
                           (with-vars [approximate approximate-result approximate-remainder log2 delta]
                             (let [approximate-result' (i64//from-number approximate)
                                   approx-remainder (i64//* parameter approximate-result)]
                               ($_ _.then
                                   (_.define approximate (|> (i64//to-number remainder)
                                                             (_./ (i64//to-number parameter))
                                                             (_.apply/1 (_.var "Math.floor"))
                                                             (_.apply/2 (_.var "Math.max") (_.i32 +1))))
                                   (_.define log2 (|> approximate
                                                      (_.apply/1 (_.var "Math.log"))
                                                      (_./ (_.var "Math.LN2"))
                                                      (_.apply/1 (_.var "Math.ceil"))))
                                   (_.define delta (_.? (_.<= (_.i32 +48) log2)
                                                        (_.i32 +1)
                                                        (_.apply/2 (_.var "Math.pow")
                                                                   (_.i32 +2)
                                                                   (_.- (_.i32 +48)
                                                                        log2))))
                                   (_.define approximate-result approximate-result')
                                   (_.define approximate-remainder approx-remainder)
                                   (_.while (_.or (negative? approximate-remainder)
                                                  (i64//< approximate-remainder
                                                          remainder))
                                            ($_ _.then
                                                (_.set approximate (_.- delta approximate))
                                                (_.set approximate-result approximate-result')
                                                (_.set approximate-remainder approx-remainder)))
                                   (_.set result (i64//+ (_.? (i64//= i64//zero approximate-result)
                                                              i64//one
                                                              approximate-result)
                                                         result))
                                   (_.set remainder (i64//- approximate-remainder remainder))))))
                  (_.return result)))
            )))

(runtime: (i64//% parameter subject)
  (let [flat (|> subject
                 (i64/// parameter)
                 (i64//* parameter))]
    (_.return (i64//- flat subject))))

(def: runtime//i64
  Statement
  ($_ _.then
      @i64//2^16
      @i64//2^32
      @i64//2^64
      @i64//2^63
      @i64//unsigned-low
      @i64//new
      @i64//zero
      @i64//min
      @i64//max
      @i64//one
      @i64//=
      @i64//+
      @i64//negate
      @i64//to-number
      @i64//from-number
      @i64//-
      @i64//*
      @i64//<
      @i64///
      @i64//%
      runtime//bit
      ))

(runtime: (text//index start part text)
  (with-vars [idx]
    ($_ _.then
        (_.define idx (|> text (_.do "indexOf" (list part (i64//to-number start)))))
        (_.if (_.= (_.i32 -1) idx)
          (_.return ..none)
          (_.return (..some (i64//from-number idx)))))))

(runtime: (text//clip start end text)
  (_.return (|> text (_.do "substring" (list (_.the ..i64-low-field start)
                                             (_.the ..i64-low-field end))))))

(runtime: (text//char idx text)
  (with-vars [result]
    ($_ _.then
        (_.define result (|> text (_.do "charCodeAt" (list (_.the ..i64-low-field idx)))))
        (_.if (_.not-a-number? result)
          (_.return ..none)
          (_.return (..some (i64//from-number result)))))))

(def: runtime//text
  Statement
  ($_ _.then
      @text//index
      @text//clip
      @text//char
      ))

(runtime: (io//log message)
  (let [console (_.var "console")
        print (_.var "print")
        end! (_.return ..unit)]
    (_.cond (list [(|> console _.type-of (_.= (_.string "undefined")) _.not
                       (_.and (_.the "log" console)))
                   ($_ _.then
                       (_.statement (|> console (_.do "log" (list message))))
                       end!)]
                  [(|> print _.type-of (_.= (_.string "undefined")) _.not)
                   ($_ _.then
                       (_.statement (_.apply/1 print (_.apply/1 (_.var "JSON.stringify") message)))
                       end!)])
            end!)))

(runtime: (io//error message)
  (_.throw message))

(def: runtime//io
  Statement
  ($_ _.then
      @io//log
      @io//error
      ))

(runtime: (js//get object field)
  (with-vars [temp]
    ($_ _.then
        (_.define temp (_.at field object))
        (_.if (_.= _.undefined temp)
          (_.return ..none)
          (_.return (..some temp))))))

(runtime: (js//set object field input)
  ($_ _.then
      (_.set (_.at field object) input)
      (_.return object)))

(runtime: (js//delete object field)
  ($_ _.then
      (_.delete (_.at field object))
      (_.return object)))

(def: runtime//js
  Statement
  ($_ _.then
      @js//get
      @js//set
      @js//delete
      ))

(runtime: (array//read idx array)
  (let [fail! (_.return ..none)]
    (_.if (_.< (..length array) idx)
      (with-vars [temp]
        ($_ _.then
            (_.define temp (_.at idx array))
            (_.if (_.= _.undefined temp)
              fail!
              (_.return (..some temp)))))
      fail!)))

(runtime: (array//write idx value array)
  (_.if (_.< (..length array) idx)
    ($_ _.then
        (_.set (_.at idx array) value)
        (_.return (..some array)))
    (_.return ..none)))

(runtime: (array//delete idx array)
  (_.if (_.< (..length array) idx)
    ($_ _.then
        (_.delete (_.at idx array))
        (_.return (..some array)))
    (_.return ..none)))

(def: runtime//array
  Statement
  ($_ _.then
      @array//read
      @array//write
      @array//delete))

(def: runtime
  Statement
  ($_ _.then
      runtime//lux
      runtime//structure
      runtime//i64
      runtime//text
      runtime//io
      runtime//js
      runtime//array
      ))

(def: #export artifact Text prefix)

(def: #export generate
  (Operation Any)
  (///.with-buffer
    (do ////.monad
      [_ (///.save! ["" ..prefix] ($_ _.then
                                      _.use-strict
                                      ..runtime))]
      (///.save-buffer! ..artifact))))