-
Notifications
You must be signed in to change notification settings - Fork 513
/
py_string.js
3109 lines (2885 loc) · 93.8 KB
/
py_string.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"use strict";
(function($B){
var _b_ = $B.builtins
// build tables from data in unicode_data.js
var escape2cp = $B.escape2cp = {b: '\b', f: '\f', n: '\n', r: '\r', t: '\t', v: '\v'}
$B.surrogates = function(s){
var s1 = '',
escaped = false
for(var char of s){
if(escaped){
var echar = escape2cp[char]
if(echar !== undefined){
s1 += echar
}else{
s1 += '\\' + char
}
escaped = false
}else if(char == '\\'){
escaped = true
}else{
s1 += char
}
}
var surrogates = [],
j = 0
for(var i = 0, len = s1.length; i < len; i++){
var cp = s1.codePointAt(i)
if(cp >= 0x10000){
surrogates.push(j)
i++
}
j++
}
return surrogates
}
$B.String = function(s){
var srg = $B.surrogates(s)
return srg.length == 0 ? s : $B.make_String(s, srg)
}
$B.make_String = function(s, surrogates){
var res = new String(s)
res.__class__ = str
res.surrogates = surrogates
return res
}
function pypos2jspos(s, pypos){
// convert Python position to JS position
if(s.surrogates === undefined){
return pypos
}
var nb = 0
while(s.surrogates[nb] < pypos){
nb++
}
return pypos + nb
}
function jspos2pypos(s, jspos){
// convert JS position to Python position
if(s.surrogates === undefined){
return jspos
}
var nb = 0
while(s.surrogates[nb] + nb < jspos){
nb++
}
return jspos - nb
}
function to_string(args){
if(typeof args == 'string'){
return args
}
if(Array.isArray(args)){
for(var i = 0, len = args.length; i < len; i++){
args[i] = to_string(args[i])
}
return args
}else{
if(args.__class__ && ! (args instanceof String)){
return args.$brython_value
}else{
return args
}
}
}
var str = {
__class__: _b_.type,
__dir__: _b_.object.__dir__,
__qualname__: 'str',
$is_class: true,
$native: true
}
str.$to_string = to_string
function normalize_start_end($){
var len
if(typeof $.self == "string"){
len = $.self.length
}else{
len = str.__len__($.self)
}
if($.start === null || $.start === _b_.None){
$.start = 0
}else if($.start < 0){
$.start += len
$.start = Math.max(0, $.start)
}
if($.end === null || $.end === _b_.None){
$.end = len
}else if($.end < 0){
$.end += len
$.end = Math.max(0, $.end)
}
if(! $B.$isinstance($.start, _b_.int) || ! $B.$isinstance($.end, _b_.int)){
throw _b_.TypeError.$factory("slice indices must be integers " +
"or None or have an __index__ method")
}
if($.self.surrogates){
$.js_start = pypos2jspos($.self, $.start)
$.js_end = pypos2jspos($.self, $.end)
}
}
function reverse(s){
// Reverse a string
return s.split("").reverse().join("")
}
function check_str(obj, prefix){
if(obj instanceof String || typeof obj == "string"){
return
}
if(! $B.$isinstance(obj, str)){
throw _b_.TypeError.$factory((prefix || '') +
"must be str, not " + $B.class_name(obj))
}
}
function to_chars(s){
// Transform Javascript string s into a list of Python characters
// (2 JS chars if surrogate, 1 otherwise)
s = to_string(s)
return Array.from(s)
}
str.__add__ = function(_self, other){
if(! $B.$isinstance(other, str)){
try{
return $B.$getattr(other, "__radd__")(_self)
}catch(err){
throw _b_.TypeError.$factory("Can't convert " +
$B.class_name(other) + " to str implicitly")}
}
[_self, other] = to_string([_self, other])
if(typeof _self == 'string' && typeof other == 'string'){
return _self + other
}
return $B.String(_self + other)
}
str.__contains__ = function(_self, item){
if(! $B.$isinstance(item, str)){
throw _b_.TypeError.$factory("'in <string>' requires " +
"string as left operand, not " + $B.class_name(item))
}
[_self, item] = to_string([_self, item])
return _self.includes(item)
}
str.__delitem__ = function(){
throw _b_.TypeError.$factory("'str' object doesn't support item deletion")
}
// __dir__must be assigned explicitely because attribute resolution for
// builtin classes doesn't use __mro__
str.__dir__ = _b_.object.__dir__
str.__eq__ = function(_self, other){
if($B.$isinstance(other, str)){
[_self, other] = to_string([_self, other])
return _self + '' == other + ''
}
return _b_.NotImplemented
}
function preformat(_self, fmt){
if(fmt.empty){
return _b_.str.$factory(_self)
}
if(fmt.type && fmt.type != "s"){
throw _b_.ValueError.$factory("Unknown format code '" + fmt.type +
"' for object of type 'str'")
}
return _self
}
str.__format__ = function(_self, format_spec) {
[_self, format_spec] = to_string([_self, format_spec])
var fmt = new $B.parse_format_spec(format_spec, _self)
if(fmt.sign !== undefined){
throw _b_.ValueError.$factory(
"Sign not allowed in string format specifier")
}
if(fmt.precision){
_self = _self.substr(0, fmt.precision)
}
// For strings, alignment default to left
fmt.align = fmt.align || "<"
return $B.format_width(preformat(_self, fmt), fmt)
}
str.__getitem__ = function(_self, arg){
_self = to_string(_self)
if($B.$isinstance(arg, _b_.int)){
var len = str.__len__(_self)
var pos = arg
if(arg < 0){
pos += len
}
if(pos >= 0 && pos < len){
var jspos = pypos2jspos(_self, pos)
if(_self.codePointAt(jspos) >= 0x10000){
return $B.String(_self.substr(jspos, 2))
}else{
return _self[jspos]
}
}
throw _b_.IndexError.$factory("string index out of range")
}
if($B.$isinstance(arg, _b_.slice)){
return _b_.str.$getitem_slice(_self, arg)
}
if($B.$isinstance(arg, _b_.bool)){
return _self.__getitem__(_b_.int.$factory(arg))
}
throw _b_.TypeError.$factory("string indices must be integers")
}
str.$getitem_slice = function(_self, slice){
var len = str.__len__(_self),
s = _b_.slice.$conv_for_seq(slice, len),
start = pypos2jspos(_self, s.start),
stop = pypos2jspos(_self, s.stop),
step = s.step
var res = ""
if(step > 0){
if(stop <= start){
return ""
}
for(let i = start; i < stop; i += step){
res += _self[i]
}
}else{
if(stop >= start){
return ''
}
for(let i = start; i > stop; i += step){
res += _self[i]
}
}
return $B.String(res)
}
var prefix = 2,
suffix = 3
str.$getnewargs = function(self){
return $B.fast_tuple([to_string(self)])
}
str.__getnewargs__ = function(){
return str.$getnewargs($B.single_arg('__getnewargs__', 'self', arguments))
}
str.__hash__ = function(_self){
// copied from
// https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript
var s = to_string(_self)
for(var i = 0, h = 0, len = s.length; i < len; i++){
h = Math.imul(31, h) + s.charCodeAt(i) | 0;
}
return h;
}
str.__init__ = function(){
// no-op
return _b_.None
}
var str_iterator = $B.make_class("str_iterator",
function(s){
return {
__class__: str_iterator,
it: s[Symbol.iterator]()
}
}
)
str_iterator.__iter__ = function(_self){
return _self
}
str_iterator.__next__ = function(_self){
var res = _self.it.next()
if(res.done){
throw _b_.StopIteration.$factory('')
}
return res.value
}
$B.set_func_names(str_iterator, 'builtins')
str.__iter__ = function(_self){
return str_iterator.$factory(_self)
}
str.__len__ = function(_self){
_self = to_string(_self)
if(_self.surrogates === undefined){
return _self.length
}
if(_self.len !== undefined){
return _self.len
}
var len = _self.len = _self.length - _self.surrogates.length
return len
}
// Start of section for legacy formatting (with %)
var number_check = function(s, flags){
if(! $B.$isinstance(s, [_b_.int, _b_.float])){
var type = flags.conversion_type
throw _b_.TypeError.$factory(`%${type} format: a real number ` +
`is required, not ${$B.class_name(s)}`)
}
}
var get_char_array = function(size, char){
if(size <= 0){
return ""
}
return new Array(size + 1).join(char)
}
var format_padding = function(s, flags, minus_one){
var padding = flags.padding
if(! padding){ // undefined
return s
}
s = s.toString()
padding = parseInt(padding, 10)
if(minus_one){ // numeric formatting where sign goes in front of padding
padding -= 1
}
if(! flags.left){
return get_char_array(padding - s.length, flags.pad_char) + s
}else{
// left adjusted
return s + get_char_array(padding - s.length, flags.pad_char)
}
}
const max_precision = 2 ** 31 - 4,
max_repeat = 2 ** 30 - 1
var format_int_precision = function(val, flags){
var precision = flags.precision
if(! precision){
return _b_.str.$factory(val)
}
precision = parseInt(precision, 10)
if(precision > max_precision){
throw _b_.OverflowError.$factory('precision too large')
}
var s
if(val.__class__ === $B.long_int){
s = $B.long_int.to_base(val, 10)
}else{
s = val.toString()
}
if(precision - s.length > max_repeat){
throw _b_.OverflowError.$factory('precision too large')
}
if(s[0] === "-"){
return "-" + "0".repeat(Math.max(0, precision - s.length + 1)) +
s.slice(1)
}
return "0".repeat(Math.max(0, precision - s.length)) + s
}
var format_float_precision = function(val, upper, flags, modifier){
var precision = flags.precision
if(isFinite(val)){
return modifier(val, precision, flags, upper)
}
if(val === Infinity){
val = "inf"
}else if(val === -Infinity){
val = "-inf"
}else{
val = "nan"
}
if(upper){
return val.toUpperCase()
}
return val
}
var format_sign = function(val, flags){
if(flags.sign){
if(val >= 0 || isNaN(val) || val === Number.POSITIVE_INFINITY){
return "+"
}
}else if(flags.space){
if(val >= 0 || isNaN(val)){
return " "
}
}
return ''
}
var str_format = function(val, flags) {
// string format supports left and right padding
flags.pad_char = " " // even if 0 padding is defined, don't use it
return format_padding(str.$factory(val), flags)
}
var num_format = function(val, flags) {
number_check(val, flags)
if($B.$isinstance(val, _b_.float)){
val = parseInt(val.value)
}else if(! $B.$isinstance(val, _b_.int)){
val = parseInt(val)
}else if ($B.$isinstance(val, _b_.bool)) {
val = val ? 1 : 0
}
var s = format_int_precision(val, flags)
if(flags.pad_char === "0"){
if(val < 0){
s = s.substring(1)
return "-" + format_padding(s, flags, true)
}
var sign = format_sign(val, flags)
if(sign !== ""){
return sign + format_padding(s, flags, true)
}
}
return format_padding(format_sign(val, flags) + s, flags)
}
var repr_format = function(val, flags) {
flags.pad_char = " " // even if 0 padding is defined, don't use it
return format_padding(_b_.repr(val), flags)
}
var ascii_format = function(val, flags, type) {
flags.pad_char = " " // even if 0 padding is defined, don't use it
var ascii
if(type == 'bytes'){
var repr = _b_.repr(val)
ascii = _b_.str.encode(repr, 'ascii', 'backslashreplace')
ascii = _b_.bytes.decode(ascii, 'ascii')
}else{
ascii = _b_.ascii(val)
}
return format_padding(ascii, flags)
}
// converts val to float and sets precision if missing
var _float_helper = function(val, flags){
number_check(val, flags)
if(flags.precision === undefined){
if(! flags.decimal_point){
flags.precision = 6
}else{
flags.precision = 0
}
}else{
flags.precision = parseInt(flags.precision, 10)
validate_precision(flags.precision)
}
return $B.$isinstance(val, _b_.int) ? val : val.value
}
var validate_precision = function(precision) {
// force precision to limits of javascript
if(precision > 20){precision = 20}
}
function handle_special_values(value, upper){
var special
if(isNaN(value)){
special = upper ? "NAN" : "nan"
}else if(value == Number.POSITIVE_INFINITY){
special = upper ? "INF" : "inf"
}else if(value == Number.NEGATIVE_INFINITY){
special = upper ? "-INF" : "-inf"
}
return special
}
// gG
var floating_point_format = function(val, upper, flags){
val = _float_helper(val, flags)
var special = handle_special_values(val, upper)
if(special){
return format_padding(format_sign(val, flags) + special, flags)
}
var p = flags.precision
if(p == 0){
p = 1
}
var exp_format = val.toExponential(p - 1),
e_index = exp_format.indexOf('e'),
exp = parseInt(exp_format.substr(e_index + 1)),
res
function remove_zeros(v){
if(flags.alternate){
return v
}
if(v.indexOf('.') > -1){
while(v.endsWith('0')){
v = v.substr(0, v.length - 1)
}
if(v.endsWith('.')){
v = v.substr(0, v.length - 1)
}
}
return v
}
if(-4 <= exp && exp < p){
/*
If m <= exp < p, where m is -4 for floats and -6 for Decimals, the
number is formatted with presentation type 'f' and precision p-1-exp
*/
flags.precision = Math.max(0, p - 1 - exp)
res = floating_point_decimal_format(val, upper, flags)
res = remove_zeros(res)
}else{
/*
Otherwise, the number is formatted with presentation type 'e' and
precision p-1
*/
flags.precision = Math.max(0, p - 1)
var delim = upper ? 'E' : 'e',
exp_fmt = floating_point_exponential_format(val, upper, flags),
parts = exp_fmt.split(delim)
parts[0] = remove_zeros(parts[0])
res = parts.join(delim)
}
return format_padding(format_sign(val, flags) + res, flags)
}
var roundDownToFixed = $B.roundDownToFixed = function(v, d){
if(d == 0 && v.toString().indexOf('e') > -1){
// with precision 0, never include "e"
return BigInt(v).toString()
}
const mul = Math.pow(10, d);
var is_neg = v < 0
if(is_neg){
v = -v
}
var res_floor = (Math.floor(v * mul) / mul).toFixed(d),
res_ceil = (Math.ceil(v * mul) / mul).toFixed(d),
res
if(v - res_floor == res_ceil - v){
// if two multiples are equally close, rounding is done toward
// the even choice
var last = res_floor[res_floor.length - 1]
res = last.match(/[02468]/) ? res_floor : res_ceil
}else{
res = v - res_floor < res_ceil - v ? res_floor : res_ceil
}
return is_neg ? '-' + res : res
}
// fF
var floating_point_decimal_format = function(val, upper, flags){
val = _float_helper(val, flags)
var unpadded = format_float_precision(val, upper, flags,
function(val, precision, flags) {
// can't use val.toFixed(precision) because
// (2.5).toFixed(0) returns "3", not "2"...
var res = roundDownToFixed(val, precision)
if(precision === 0 && flags.alternate){
res += '.'
}
if(Object.is(val, -0)){
res = '-' + res
}
return res
})
return format_padding(format_sign(val, flags) + unpadded,
flags)
}
var _floating_exp_helper = function(val, precision, flags, upper){
var is_neg = false,
val_pos = val.toString()
if(val < 0){
is_neg = true
val_pos = val_pos.substr(1)
}else if(Object.is(val, -0)){
is_neg = true
}
var parts = val_pos.split('.'),
exp = 0,
exp_sign = '+',
mant
if(parts[0] == '0'){
if(parts[1]){
exp_sign = '-'
exp++
var i = 0
while(parts[1][i] == '0'){
i++
}
exp += i
mant = parts[1][i]
if(parts[1][i + 1]){
mant += '.' + parts[1].substr(i + 1)
}
}else{
mant = '0'
}
}else{
exp = parts[0].length - 1
mant = parts[0][0]
if(parts[0].length > 1){
mant += '.' + parts[0].substr(1) + (parts[1] || '')
}else if(parts[1]){
mant += '.' + parts[1]
}
}
mant = parseFloat(mant)
// round mantissa to precision
mant = roundDownToFixed(parseFloat(mant), precision)
if(parseFloat(mant) == 10){
// 9.5 is rounded to 10 !
parts = mant.split('.')
parts[0] = '1'
mant = parts.join('.')
exp = parseInt(exp) + (exp_sign == '+' ? 1 : -1)
if(exp == 0){
exp_sign = '+'
}
}
if(flags.alternate && mant.indexOf('.') == -1){
mant += '.'
}
if(exp.toString().length == 1){
// exponent has at least 2 digits
exp = '0' + exp
}
return `${is_neg ? '-' : ''}${mant}${upper ? 'E' : 'e'}${exp_sign}${exp}`
}
// eE
var floating_point_exponential_format = function(val, upper, flags){
val = _float_helper(val, flags)
return format_padding(format_sign(val, flags) +
format_float_precision(val, upper, flags, _floating_exp_helper), flags)
}
$B.formatters = {
floating_point_format,
floating_point_decimal_format,
floating_point_exponential_format
}
var signed_hex_format = function(val, upper, flags){
var ret
if(! $B.$isinstance(val, _b_.int)){
throw _b_.TypeError.$factory(
`%X format: an integer is required, not ${$B.class_name(val)}`)
} else if ($B.$isinstance(val, _b_.bool)) {
val = val ? 1 : 0
}
if(val.__class__ === $B.long_int){
ret = val.value.toString(16)
}else{
ret = parseInt(val)
ret = ret.toString(16)
}
ret = format_int_precision(ret, flags)
if(upper){ret = ret.toUpperCase()}
if(flags.pad_char === "0"){
if(val < 0){
ret = ret.substring(1)
ret = "-" + format_padding(ret, flags, true)
}
var sign = format_sign(val, flags)
if(sign !== ""){
ret = sign + format_padding(ret, flags, true)
}
}
if(flags.alternate){
if(ret.charAt(0) === "-"){
if(upper){ret = "-0X" + ret.slice(1)}
else{ret = "-0x" + ret.slice(1)}
}else{
if(upper){ret = "0X" + ret}
else{ret = "0x" + ret}
}
}
return format_padding(format_sign(val, flags) + ret, flags)
}
var octal_format = function(val, flags) {
number_check(val, flags)
var ret
if(val.__class__ === $B.long_int){
ret = $B.long_int.to_base(8)
}else{
ret = parseInt(val)
ret = ret.toString(8)
}
ret = format_int_precision(ret, flags)
if(flags.pad_char === "0"){
if(val < 0){
ret = ret.substring(1)
ret = "-" + format_padding(ret, flags, true)
}
var sign = format_sign(val, flags)
if(sign !== ""){
ret = sign + format_padding(ret, flags, true)
}
}
if(flags.alternate){
if(ret.charAt(0) === "-"){ret = "-0o" + ret.slice(1)}
else{ret = "0o" + ret}
}
return format_padding(ret, flags)
}
function series_of_bytes(val, flags){
if(val.__class__ && val.__class__.$buffer_protocol){
var it = _b_.iter(val),
ints = []
while(true){
try{
ints.push(_b_.next(it))
}catch(err){
if(err.__class__ === _b_.StopIteration){
var b = _b_.bytes.$factory(ints)
return format_padding(_b_.bytes.decode(b, "ascii"), flags)
}
throw err
}
}
}else{
try{
var bytes_obj = $B.$getattr(val, "__bytes__")()
return format_padding(_b_.bytes.decode(bytes_obj), flags)
}catch(err){
if(err.__class__ === _b_.AttributeError){
throw _b_.TypeError.$factory("%b does not accept '" +
$B.class_name(val) + "'")
}
throw err
}
}
}
var single_char_format = function(val, flags, type){
if(type == 'bytes'){
if($B.$isinstance(val, _b_.int)){
if(val.__class__ === $B.long_int || val < 0 || val > 255){
throw _b_.OverflowError.$factory("%c arg not in range(256)")
}
}else if($B.$isinstance(val, [_b_.bytes, _b_.bytearray])){
if(val.source.length > 1){
throw _b_.TypeError.$factory(
"%c requires an integer in range(256) or a single byte")
}
val = val.source[0]
}
}else{
if($B.$isinstance(val, _b_.str)){
if(_b_.str.__len__(val) == 1){
return val
}
throw _b_.TypeError.$factory("%c requires int or char")
}else if(! $B.$isinstance(val, _b_.int)){
throw _b_.TypeError.$factory("%c requires int or char")
}
if((val.__class__ === $B.long_int &&
(val.value < 0 || val.value >= 0x110000)) ||
(val < 0 || val >= 0x110000)){
throw _b_.OverflowError.$factory('%c arg not in range(0x110000)')
}
}
return format_padding(_b_.chr(val), flags)
}
var num_flag = function(c, flags){
if(c === "0" && ! flags.padding && ! flags.decimal_point && ! flags.left){
flags.pad_char = "0"
return
}
if(!flags.decimal_point){
flags.padding = (flags.padding || "") + c
}else{
flags.precision = (flags.precision || "") + c
}
}
var decimal_point_flag = function(val, flags) {
if(flags.decimal_point){
// can only have one decimal point
throw new UnsupportedChar()
}
flags.decimal_point = true
}
var neg_flag = function(val, flags){
flags.pad_char = " " // overrides '0' flag
flags.left = true
}
var space_flag = function(val, flags){
flags.space = true
}
var sign_flag = function(val, flags){
flags.sign = true
}
var alternate_flag = function(val, flags){
flags.alternate = true
}
var char_mapping = {
"b": series_of_bytes,
"s": str_format,
"d": num_format,
"i": num_format,
"u": num_format,
"o": octal_format,
"r": repr_format,
"a": ascii_format,
"g": function(val, flags){
return floating_point_format(val, false, flags)
},
"G": function(val, flags){return floating_point_format(val, true, flags)},
"f": function(val, flags){
return floating_point_decimal_format(val, false, flags)
},
"F": function(val, flags){
return floating_point_decimal_format(val, true, flags)
},
"e": function(val, flags){
return floating_point_exponential_format(val, false, flags)
},
"E": function(val, flags){
return floating_point_exponential_format(val, true, flags)
},
"x": function(val, flags){return signed_hex_format(val, false, flags)},
"X": function(val, flags){return signed_hex_format(val, true, flags)},
"c": single_char_format,
"0": function(val, flags){return num_flag("0", flags)},
"1": function(val, flags){return num_flag("1", flags)},
"2": function(val, flags){return num_flag("2", flags)},
"3": function(val, flags){return num_flag("3", flags)},
"4": function(val, flags){return num_flag("4", flags)},
"5": function(val, flags){return num_flag("5", flags)},
"6": function(val, flags){return num_flag("6", flags)},
"7": function(val, flags){return num_flag("7", flags)},
"8": function(val, flags){return num_flag("8", flags)},
"9": function(val, flags){return num_flag("9", flags)},
"-": neg_flag,
" ": space_flag,
"+": sign_flag,
".": decimal_point_flag,
"#": alternate_flag
}
// exception thrown when an unsupported char is encountered in legacy format
var UnsupportedChar = function(){
this.name = "UnsupportedChar"
}
const conversion_flags = '#0- +',
length_modifiers = 'hlL',
conversion_types = 'diouxXeEfFgGcrsa'
function parse_mod_format(s, type, pos){
var flags = {pad_char: ' '},
len = s.length,
start_pos = pos,
mo
pos++
while(pos < len){
var char = s[pos]
if(char == '('){
var end = s.substr(pos).indexOf(')')
if(end == -1){
throw _b_.ValueError.$factory('incomplete format key')
}else{
flags.mapping_key = s.substr(pos + 1, end - 1)
pos += end + 1
}
}else if(conversion_flags.indexOf(char) > -1){
flags.conversion_flag = char
if(char == '#'){
flags.alternate = true
}else if(char == '-'){
flags.left = true
}else if(char == '+'){
flags.sign = '+'
}else if(char == '0'){
flags.pad_char = '0'
}else if(char == ' '){
flags.space = true
}
pos++
}else if(char == '*'){
flags.padding = '*'
pos++
}else if(mo = /^\d+/.exec(s.substr(pos))){
flags.padding = mo[0]
pos += mo[0].length
}else if(char == '.'){
pos++
if(s[pos] == '*'){
flags.precision = '*'
pos++
}else if(mo = /^\d+/.exec(s.substr(pos))){
flags.precision = mo[0]
pos += mo[0].length
}else{
flags.precision = "0"
}
}else if(length_modifiers.indexOf(char) > -1){
flags.length_modifier = char
pos++
}else if((conversion_types.indexOf(char) > -1) ||
(char == 'b' && type == 'bytes')){
if(type == 'bytes'){
if(char == 's'){
// for bytes, 's' is an alias for 'b'
char = 'b'
}else if(char == 'r'){
char = 'a'
}
}
flags.conversion_type = char
flags.end = pos
flags.string = s.substring(start_pos, pos + 1)
if(flags.left && flags.pad_char == '0'){
// conversion flag "-" overrides "0" if both are given
flags.pad_char = ' '
}
return flags
}else{
throw _b_.ValueError.$factory(`invalid character in format: ${char}`)
}
}
throw _b_.ValueError.$factory('invalid format')
}
function is_mapping(obj){
return _b_.hasattr(obj, 'keys') && _b_.hasattr(obj, '__getitem__')
}
$B.printf_format = function(s, type, args){
// printf-style bytes or string formatting
// s is a string
// type is 'str' or 'bytes', the class of the original formatted object
// args are the arguments passed to %
var argpos = null,
getitem