forked from rescript-lang/rescript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcaml_format.ml
699 lines (635 loc) · 19.5 KB
/
caml_format.ml
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
(*
* Js_of_ocaml runtime support
* http://www.ocsigen.org/js_of_ocaml/
* Copyright (C) 2010 Jérôme Vouillon
* Laboratoire PPS - CNRS Université Paris Diderot
* Copyright (C) 2015-2016 Bloomberg Finance L.P.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published * by
* the Free Software Foundation, with linking exception;
* either version 2.1 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*)
(** *)
let repeat = Caml_utils.repeat
let caml_failwith s = raise (Failure s)
let caml_invalid_argument s= raise (Invalid_argument s )
let (>>>) = Caml_nativeint_extern.shift_right_logical
let to_nat x = Caml_nativeint_extern.of_int x
let of_nat x = Caml_nativeint_extern.to_int x
let (+~) = Caml_nativeint_extern.add
let ( *~ ) = Caml_nativeint_extern.mul
let parse_digit c =
match c with
| '0' .. '9'
-> Caml_char.code c - Caml_char.code '0'
| 'A' .. 'Z'
-> Caml_char.code c - (Caml_char.code 'A' - 10)
| 'a' .. 'z'
-> Caml_char.code c - (Caml_char.code 'a' - 10 )
| _ -> -1
type of_string_base =
| Oct
| Hex
| Dec
| Bin
let int_of_string_base = function
| Oct -> 8
| Hex -> 16
| Dec -> 10
| Bin -> 2
let parse_sign_and_base (s : string) =
let module String = Caml_string_extern in
let sign = ref 1n in
let base = ref Dec in
let i = ref 0 in
(match s.[!i] with
| '-' ->
sign := -1n;
incr i
| '+' ->
incr i
| _ -> ());
if s.[!i] = '0' then
(match s.[!i + 1] with
| ('x' | 'X')
-> base := Hex; i:=!i + 2
| ( 'o' | 'O')
-> base := Oct; i := !i + 2
| ('b' | 'B' )
-> base := Bin; i := !i + 2
| ('u' | 'U')
-> i := !i + 2
| _ -> ());
(!i, !sign, !base)
let caml_int_of_string s =
let module String = Caml_string_extern in
let i, sign, hbase = parse_sign_and_base s in
let base = Caml_nativeint_extern.of_int (int_of_string_base hbase) in
let threshold = (-1n >>> 0) in
let len =Caml_string_extern.length s in
let c = if i < len then s.[i] else '\000' in
let d = to_nat (parse_digit c) in
let () =
if d < 0n || d >= base then
caml_failwith "int_of_string" in
(* let () = [%bs.debugger] in *)
let rec aux acc k =
if k = len then acc
else
let a = s.[k] in
if a = '_' then aux acc ( k + 1)
else
let v = to_nat (parse_digit a) in
if v < 0n || v >= base then
caml_failwith "int_of_string"
else
let acc = base *~ acc +~ v in
if acc > threshold then
caml_failwith "int_of_string"
else aux acc ( k + 1)
in
let res = sign *~ aux d (i + 1) in
let or_res = Caml_nativeint_extern.logor res 0n in
(if base = 10n && res <> or_res then
caml_failwith "int_of_string");
or_res
let caml_int64_of_string s =
let module String = Caml_string_extern in
let i, sign, hbase = parse_sign_and_base s in
let base = Caml_int64_extern.of_int (int_of_string_base hbase) in
let sign = Caml_int64_extern.of_nativeint sign in
let threshold =
match hbase with
| Hex -> (* 2 ^ 64 - 1 / 16*)
1152921504606846975L
| Dec ->
1844674407370955161L
| Oct ->
2305843009213693951L
| Bin ->
9223372036854775807L
in
let len =Caml_string_extern.length s in
let c = if i < len then s.[i] else '\000' in
let d = Caml_int64_extern.of_int (parse_digit c) in
let () =
if d < 0L || d >= base then
caml_failwith "int64_of_string" in
let (+~) = Caml_int64_extern.add in
let ( *~ ) = Caml_int64_extern.mul in
let rec aux acc k =
if k = len then acc
else
let a = s.[k] in
if a = '_' then aux acc ( k + 1)
else
let v = Caml_int64_extern.of_int (parse_digit a) in
if v < 0L || v >= base || acc > threshold then
caml_failwith "int64_of_string"
else
let acc = base *~ acc +~ v in
aux acc ( k + 1)
in
let res = sign *~ aux d (i + 1) in
let or_res = Caml_int64_extern.logor res 0L in
(if base = 10L && res <> or_res then
caml_failwith "int64_of_string");
or_res
type base =
| Oct | Hex | Dec
let int_of_base = function
| Oct -> 8
| Hex -> 16
| Dec -> 10
type fmt = {
mutable justify : string;
mutable signstyle : string;
mutable filter : string ;
mutable alternate : bool;
mutable base : base;
mutable signedconv : bool;
mutable width :int;
mutable uppercase : bool;
mutable sign : int;
mutable prec : int;
mutable conv : string
}
let lowercase c =
if (c >= 'A' && c <= 'Z')
|| (c >= '\192' && c <= '\214')
|| (c >= '\216' && c <= '\222')
then Caml_char.unsafe_chr(Caml_char.code c + 32)
else c
let parse_format fmt =
let module String = Caml_string_extern in
let len =Caml_string_extern.length fmt in
if len > 31 then
raise (Invalid_argument "format_int: format too long") ;
let rec aux (f : fmt) i : fmt =
if i >= len then f
else
let c = fmt.[i] in
match c with
| '-' ->
f.justify <- "-";
aux f (i + 1)
| '+'|' '
->
f.signstyle <- Caml_string_extern.of_char c ;
aux f (i + 1)
| '#' ->
f.alternate <- true;
aux f (i + 1)
| '0' ->
f.filter <- "0";
aux f (i + 1)
| '1' .. '9'
->
begin
f.width <- 0;
let j = ref i in
while (let w = Caml_char.code fmt.[!j] - Caml_char.code '0' in w >=0 && w <= 9 ) do
f.width <- f.width * 10 + Caml_char.code fmt.[!j] - Caml_char.code '0';
incr j
done;
aux f !j
end
| '.'
->
f.prec <- 0;
let j = ref (i + 1 ) in
while (let w = Caml_char.code fmt.[!j] - Caml_char.code '0' in w >=0 && w <= 9 ) do
f.prec <- f.prec * 10 + Caml_char.code fmt.[!j] - Caml_char.code '0';
incr j;
done;
aux f !j
| 'd'
| 'i' ->
f.signedconv <- true;
f.base <- Dec;
aux f (i + 1)
| 'u' ->
f.base <- Dec;
aux f (i + 1)
| 'x' ->
f.base <- Hex;
aux f (i + 1)
| 'X' ->
f.base <- Hex;
f.uppercase <- true;
aux f (i + 1)
| 'o' ->
f.base <- Oct;
aux f (i + 1)
(* | 'O' -> base := 8; uppercase := true no uppercase for oct *)
| 'e' | 'f' | 'g'
->
f.signedconv <- true;
f.conv <- Caml_string_extern.of_char c ;
aux f (i + 1)
| 'E' | 'F' | 'G'
->
f.signedconv <- true;
f.uppercase <- true;
f.conv <- Caml_string_extern.of_char (lowercase c);
aux f (i + 1)
| _ ->
aux f (i + 1)
in
aux { justify = "+" ;
signstyle = "-";
filter = " " ;
alternate = false ;
base= Dec ;
signedconv= false ;
width = 0 ;
uppercase= false ;
sign = 1 ;
prec = (-1);
conv = "f"} 0
let finish_formatting (config : fmt) rawbuffer =
let {
justify;
signstyle;
filter ;
alternate;
base;
signedconv;
width;
uppercase;
sign;
prec;
conv
} = config in
let len = ref (Caml_string_extern.length rawbuffer) in
if signedconv && (sign < 0 || signstyle <> "-") then
incr len;
if alternate then
begin
if base = Oct then
incr len
else
if base = Hex then
len := !len + 2
else ()
end ;
let buffer = ref "" in
(* let (+=) buffer s = buffer := !buffer ^ s in
FIXME: should get inlined
*)
(* let (+:) s = buffer := !buffer ^ s in *)
if justify = "+" && filter = " " then
for i = !len to width - 1 do
buffer := !buffer ^ filter
done;
if signedconv then
if sign < 0 then
buffer := !buffer ^ "-"
else if signstyle <> "-" then
buffer := !buffer ^ signstyle
else () ;
if alternate && base = Oct then
buffer := !buffer ^ "0";
if alternate && base == Hex then
buffer := !buffer ^ "0x";
if justify = "+" && filter = "0" then
for i = !len to width - 1 do
buffer := !buffer ^ filter;
done;
begin
if uppercase then
buffer := !buffer ^ Caml_string_extern.toUpperCase rawbuffer
else
buffer := !buffer ^ rawbuffer
end;
if justify = "-" then
for i = !len to width - 1 do
buffer := !buffer ^ " ";
done;
!buffer
let aux f (i : nativeint) =
let i =
if i < 0n then
if f.signedconv then
begin
f.sign <- -1;
Caml_nativeint_extern.neg i
end
else
Caml_nativeint_extern.shift_right_logical i 0
else i in
let s = ref (Caml_string_extern.of_nativeint i ~base:(int_of_base f.base)) in
if f.prec >= 0 then
begin
f.filter <- " ";
let n = f.prec -Caml_string_extern.length !s in
if n > 0 then
s := repeat n "0" ^ !s
end ;
finish_formatting f !s
let caml_format_int fmt i =
if fmt = "%d" then Caml_nativeint_extern.to_string i
else
let f = parse_format fmt in
aux f i
(* FIXME: improve codegen for such cases
let div_mod (x : int64) (y : int64) : int64 * int64 =
let a, b = Caml_int64.(div_mod (unsafe_of_int64 x) (unsafe_of_int64 y)) in
Caml_int64.unsafe_to_int64 a , Caml_int64.unsafe_to_int64 b
*)
let caml_int64_format fmt x =
let module String = Caml_string_extern in
let f = parse_format fmt in
let x =
if f.signedconv && x < 0L then
begin
f.sign <- -1;
Caml_int64_extern.neg x
end
else x in
let s = ref "" in
begin match f.base with
| Hex ->
s := Caml_int64.to_hex x ^ !s
| Oct ->
let wbase = 8L in
let cvtbl = "01234567" in
if x < 0L then
begin
let y = Caml_int64.discard_sign x in
(* 2 ^ 63 + y `div_mod` 8 *)
let quotient_l = 1152921504606846976L (**)
(* {lo = 0n; hi = 268435456n } *) (* 2 ^ 31 / 8 *)
in
(* let c, d = Caml_int64.div_mod (Caml_int64.add y modulus_l) wbase in
we can not do the code above, it can overflow when y is really large
*)
let c, d = Caml_int64.div_mod y wbase in
let quotient =
ref (Caml_int64_extern.add quotient_l c ) in
let modulus = ref d in
s :=
Caml_string_extern.of_char
cvtbl.[ Caml_int64_extern.to_int !modulus] ^ !s ;
while !quotient <> 0L do
let a, b = Caml_int64.div_mod (!quotient) wbase in
quotient := a;
modulus := b;
s := Caml_string_extern.of_char cvtbl.[Caml_int64_extern.to_int !modulus] ^ !s ;
done;
end
else
let a, b = Caml_int64.div_mod x wbase in
let quotient = ref a in
let modulus = ref b in
s :=
Caml_string_extern.of_char
cvtbl.[ Caml_int64_extern.to_int !modulus] ^ !s ;
while !quotient <> 0L do
let a, b = Caml_int64.div_mod (!quotient) wbase in
quotient := a;
modulus := b;
s := Caml_string_extern.of_char cvtbl.[Caml_int64_extern.to_int !modulus] ^ !s ;
done
| Dec ->
let wbase = 10L in
let cvtbl = "0123456789" in
if x < 0L then
let y = Caml_int64.discard_sign x in
(* 2 ^ 63 + y `div_mod` 10 *)
let quotient_l = 922337203685477580L (* 2 ^ 63 / 10 *)
(* {lo = -858993460n; hi = 214748364n} *)
(* TODO: int64 constant folding so that we can do idiomatic code
2 ^ 63 / 10 *)in
let modulus_l = 8L in
(* let c, d = Caml_int64.div_mod (Caml_int64.add y modulus_l) wbase in
we can not do the code above, it can overflow when y is really large
*)
let c, d = Caml_int64.div_mod y wbase in
let e ,f = Caml_int64.div_mod (Caml_int64_extern.add modulus_l d) wbase in
let quotient =
ref (Caml_int64_extern.add (Caml_int64_extern.add quotient_l c )
e) in
let modulus = ref f in
s :=
Caml_string_extern.of_char
cvtbl.[Caml_int64_extern.to_int !modulus] ^ !s ;
while !quotient <> 0L do
let a, b = Caml_int64.div_mod (!quotient) wbase in
quotient := a;
modulus := b;
s := Caml_string_extern.of_char cvtbl.[Caml_int64_extern.to_int !modulus] ^ !s ;
done;
else
let a, b = Caml_int64.div_mod x wbase in
let quotient = ref a in
let modulus = ref b in
s :=
Caml_string_extern.of_char
cvtbl.[ Caml_int64_extern.to_int !modulus] ^ !s ;
while !quotient <> 0L do
let a, b = Caml_int64.div_mod (!quotient) wbase in
quotient := a;
modulus := b;
s := Caml_string_extern.of_char cvtbl.[Caml_int64_extern.to_int !modulus] ^ !s ;
done;
end;
if f.prec >= 0 then
begin
f.filter <- " ";
let n = f.prec -Caml_string_extern.length !s in
if n > 0 then
s := repeat n "0" ^ !s
end;
finish_formatting f !s
let caml_format_float fmt x =
let module String = Caml_string_extern in
let f = parse_format fmt in
let prec = if f.prec < 0 then 6 else f.prec in
let x = if x < 0. then (f.sign <- (-1); -. x) else x in
let s = ref "" in
if Caml_float_extern.isNaN x then
begin
s := "nan";
f.filter <- " "
end
else if not (Caml_float_extern.isFinite x) then
begin
s := "inf";
f.filter <- " "
end
else
begin
match f.conv with
| "e"
->
s := Caml_float_extern.toExponentialWithPrecision x ~digits:prec;
(* exponent should be at least two digits
{[
(3.3).toExponential()
"3.3e+0"
3.3e+00
]}
*)
let i =Caml_string_extern.length !s in
if !s.[i-3] = 'e' then
begin
s := Caml_string_extern.slice !s 0 (i - 1) ^ "0" ^ Caml_string_extern.slice_rest !s (i - 1)
end
| "f"
->
(* this will not work large numbers *)
(* ("%3.10f", 3e+56, "300000000000000005792779041490073052596128503513888063488.0000000000") *)
s := Caml_float_extern.toFixedWithPrecision x ~digits:prec
| "g" ->
let prec = if prec <> 0 then prec else 1 in
s := Caml_float_extern.toExponentialWithPrecision x ~digits:(prec - 1);
let j = Caml_string_extern.index_of !s "e" in
let exp = Caml_float.int_of_float (Caml_float_extern.fromString (Caml_string_extern.slice_rest !s (j + 1))) in
if exp < -4 || x >= 1e21 ||Caml_string_extern.length (Caml_float_extern.toFixed x) > prec then
let i = ref (j - 1) in
while !s.[!i] = '0' do
decr i
done;
if !s.[!i] = '.' then
decr i ;
s := Caml_string_extern.slice !s 0 (!i+1) ^ Caml_string_extern.slice_rest !s j ;
let i =Caml_string_extern.length !s in
if !s.[i - 3] = 'e' then
s := Caml_string_extern.slice !s 0 (i - 1) ^ "0" ^ Caml_string_extern.slice_rest !s (i - 1)
else ()
else
let p = ref prec in
if exp < 0 then
begin
p := !p - (exp + 1);
s := Caml_float_extern.toFixedWithPrecision x ~digits:!p
end
else
while (s := Caml_float_extern.toFixedWithPrecision x ~digits:!p;Caml_string_extern.length !s > prec + 1) do
decr p
done ;
if !p <> 0 then
let k = ref (Caml_string_extern.length !s - 1) in
while !s.[!k] = '0' do
decr k
done ;
if !s.[!k] = '.' then
decr k ;
s := Caml_string_extern.slice !s 0 (!k + 1)
| _ -> ()
end;
finish_formatting f !s
let caml_hexstring_of_float : float -> int -> char -> string =
fun%raw x prec style -> {|
if (!isFinite(x)) {
if (isNaN(x)) return "nan";
return x > 0 ? "infinity":"-infinity";
}
var sign = (x==0 && 1/x == -Infinity)?1:(x>=0)?0:1;
if(sign) x = -x;
var exp = 0;
if (x == 0) { }
else if (x < 1) {
while (x < 1 && exp > -1022) { x *= 2; exp-- }
} else {
while (x >= 2) { x /= 2; exp++ }
}
var exp_sign = exp < 0 ? '' : '+';
var sign_str = '';
if (sign) sign_str = '-'
else {
switch(style){
case 43 /* '+' */: sign_str = '+'; break;
case 32 /* ' ' */: sign_str = ' '; break;
default: break;
}
}
if (prec >= 0 && prec < 13) {
/* If a precision is given, and is small, round mantissa accordingly */
var cst = Math.pow(2,prec * 4);
x = Math.round(x * cst) / cst;
}
var x_str = x.toString(16);
if(prec >= 0){
var idx = x_str.indexOf('.');
if(idx<0) {
x_str += '.' + '0'.repeat(prec);
}
else {
var size = idx+1+prec;
if(x_str.length < size)
x_str += '0'.repeat(size - x_str.length);
else
x_str = x_str.substr(0,size);
}
}
return (sign_str + '0x' + x_str + 'p' + exp_sign + exp.toString(10));
|}
let float_of_string : string -> exn -> float =
#if OCAML_VERSION =~ ">4.3.0" then
fun%raw s exn -> {|
var res = +s;
if ((s.length > 0) && (res === res))
return res;
s = s.replace(/_/g, "");
res = +s;
if (((s.length > 0) && (res === res)) || /^[+-]?nan$/i.test(s)) {
return res;
};
var m = /^ *([+-]?)0x([0-9a-f]+)\.?([0-9a-f]*)p([+-]?[0-9]+)/i.exec(s);
// 1 2 3 4
if(m){
var m3 = m[3].replace(/0+$/,'');
var mantissa = parseInt(m[1] + m[2] + m3, 16);
var exponent = (m[4]|0) - 4*m3.length;
res = mantissa * Math.pow(2, exponent);
return res;
}
if (/^\+?inf(inity)?$/i.test(s))
return Infinity;
if (/^-inf(inity)?$/i.test(s))
return -Infinity;
throw exn;
|}
#else
fun%raw s exn -> {|
var res = +s;
if ((s.length > 0) && (res === res))
return res;
s = s.replace(/_/g, "");
res = +s;
if (((s.length > 0) && (res === res)) || /^[+-]?nan$/i.test(s)) {
return res;
};
if (/^\+?inf(inity)?$/i.test(s))
return Infinity;
if (/^-inf(inity)?$/i.test(s))
return -Infinity;
throw exn;
|}
#end
(**
Pervasives.float_of_string : string -> float = "caml_float_of_string"
Semantics is slightly different from javascript :
console.assert(caml_float_of_string('infinity')===Infinity)
console.assert(caml_float_of_string('Infinity')===Infinity
parseFloat('Infinity') === Infinity
parseFloat('infinity') === Nan
*)
let caml_float_of_string (s : string) : float =
float_of_string s (Failure "float_of_string")
let caml_nativeint_format = caml_format_int
let caml_int32_format = caml_format_int
let caml_int32_of_string = caml_int_of_string
let caml_nativeint_of_string = caml_int32_of_string