Permalink
Mar 6, 2021
Aug 7, 2021
Mar 19, 2018
Mar 19, 2018
Apr 5, 2021
Mar 6, 2021
Mar 19, 2018
Apr 25, 2020
Mar 6, 2021
Mar 19, 2018
Mar 19, 2018
Mar 19, 2018
Mar 6, 2021
Mar 19, 2018
Mar 6, 2021
Mar 6, 2021
Mar 30, 2021
Aug 7, 2021
Jan 14, 2015
Mar 19, 2018
Mar 19, 2018
Mar 19, 2018
Jan 14, 2015
Mar 19, 2018
Jan 14, 2015
Jan 14, 2015
Jan 14, 2015
Mar 19, 2018
Jan 14, 2015
Mar 19, 2018
Mar 19, 2018
Mar 19, 2018
Mar 19, 2018
Mar 19, 2018
Mar 19, 2018
Mar 19, 2018
Mar 19, 2018
Mar 19, 2018
Jan 14, 2015
Mar 19, 2018
Jan 14, 2015
Mar 19, 2018
Mar 19, 2018
Mar 19, 2018
Mar 19, 2018
Dec 18, 2019
Dec 18, 2019
Mar 19, 2018
Jan 14, 2015
Jan 14, 2015
Mar 19, 2018
Mar 19, 2018
Jan 14, 2015
Mar 19, 2018
Mar 19, 2018
Mar 19, 2018
Mar 19, 2018
Mar 19, 2018
Mar 19, 2018
Mar 6, 2021
Mar 19, 2018
Mar 16, 2021
Mar 16, 2021
Mar 19, 2018
Mar 27, 2019
Mar 6, 2021
Mar 19, 2018
Mar 6, 2021
Mar 19, 2018
Mar 19, 2018
Mar 19, 2018
Mar 6, 2021
Mar 6, 2021
Mar 6, 2021
Mar 19, 2018
Apr 2, 2019
Apr 2, 2019
Mar 19, 2018
Aug 31, 2017
Mar 19, 2018
Mar 6, 2021
Mar 19, 2018
Mar 6, 2021
Aug 31, 2017
Apr 16, 2019
Mar 19, 2018
Apr 16, 2019
Mar 6, 2021
Mar 19, 2018
Mar 6, 2021
Mar 19, 2018
Mar 19, 2018
Mar 19, 2018
Nov 12, 2018
Nov 22, 2020
Nov 12, 2018
Mar 19, 2018
Nov 22, 2020
Mar 6, 2021
Mar 6, 2021
Mar 6, 2021
Mar 6, 2021
Mar 6, 2021
Mar 6, 2021
Mar 6, 2021
Sep 27, 2020
Sep 27, 2020
Mar 6, 2021
Mar 6, 2021
Mar 6, 2021
Mar 19, 2018
Mar 6, 2021
Mar 19, 2018
Mar 6, 2021
Mar 19, 2018
Aug 31, 2017
Mar 19, 2018
Mar 19, 2018
Mar 19, 2018
Jan 6, 2016
Mar 19, 2018
Mar 19, 2018
Mar 19, 2018
Mar 6, 2021
Jun 11, 2020
Mar 19, 2018
Mar 19, 2018
Apr 5, 2021
Mar 6, 2021
Mar 6, 2021
Mar 19, 2018
Mar 19, 2018
Aug 31, 2017
May 24, 2019
Mar 19, 2018
Mar 6, 2021
Mar 6, 2021
Mar 19, 2018
Mar 19, 2018
Mar 19, 2018
Mar 19, 2018
Mar 19, 2018
Mar 6, 2021
Mar 19, 2018
Mar 6, 2021
Mar 6, 2021
Mar 6, 2021
Mar 19, 2018
Feb 27, 2020
Feb 27, 2020
Feb 27, 2020
Aug 31, 2017
Mar 19, 2018
Mar 6, 2021
Mar 19, 2018
Mar 6, 2021
Mar 6, 2021
Mar 6, 2021
Mar 6, 2021
Mar 6, 2021
Mar 6, 2021
Jan 26, 2020
Mar 6, 2021
Nov 15, 2019
Jul 28, 2018
Oct 27, 2019
Nov 2, 2018
Oct 27, 2019
Nov 2, 2018
Mar 19, 2018
Mar 19, 2018
Mar 19, 2018
Mar 19, 2018
Mar 19, 2018
Mar 6, 2021
Nov 12, 2018
Mar 6, 2021
Mar 19, 2018
Mar 19, 2018
Mar 19, 2018
Mar 19, 2018
Mar 19, 2018
Mar 19, 2018
Mar 19, 2018
Dec 12, 2020
Jun 29, 2017
Oct 13, 2019
Jun 29, 2017
Dec 12, 2020
Jul 10, 2017
Jul 10, 2017
Mar 19, 2018
Mar 19, 2018
Jun 20, 2020
Oct 13, 2019
Oct 13, 2019
Jul 31, 2021
Jan 18, 2021
Jan 18, 2021
Newer
100644
2866 lines (2651 sloc)
86.7 KB
8
9
$B.has_surrogate = function(s){
10
// Check if there are "surrogate pairs" characters in string s
11
for(var i = 0; i < s.length; i++){
12
code = s.charCodeAt(i)
13
if(code >= 0xD800 && code <= 0xDBFF){
14
return true
15
}
16
}
17
return false
18
}
19
20
$B.String = function(s){
21
var codepoints = [],
22
index_map = {},
23
has_surrogate = false
24
for(var i = 0, len = s.length; i < len; i++){
25
index_map[codepoints.length] = i
26
var cp = s.codePointAt(i)
27
codepoints.push(cp)
28
if(cp >= 0x10000){
29
i++
30
has_surrogate = true
31
}
32
}
33
if(has_surrogate){
34
var res = new String(s)
35
res.__class__ = str
36
res.index_map = index_map
37
res.codepoints = codepoints
38
res.string = s
39
return res
40
}
41
return s
42
}
43
56
if($.start === null || $.start === _b_.None){$.start = 0}
57
else if($.start < 0){
58
$.start += $.self.length
59
$.start = Math.max(0, $.start)
60
}
61
if($.end === null || $.end === _b_.None){$.end = $.self.length}
62
else if($.end < 0){
63
$.end += $.self.length
64
$.end = Math.max(0, $.end)
65
}
68
throw _b_.TypeError.$factory("slice indices must be integers " +
69
"or None or have an __index__ method")
70
}
80
throw _b_.TypeError.$factory((prefix || '') +
81
"must be str, not " + $B.class_name(obj))
85
function to_chars(s){
86
// Transform Javascript string s into a list of Python characters
87
// (2 JS chars if surrogate, 1 otherwise)
88
var chars = []
89
for(var i = 0, len = s.length; i < len; i++){
90
var code = s.charCodeAt(i)
91
if(code >= 0xD800 && code <= 0xDBFF){
92
chars.push(s.substr(i, 2))
93
i++
94
}else{
95
chars.push(s.charAt(i))
96
}
97
}
98
return chars
99
}
100
101
function to_codepoints(s){
102
// Transform Javascript string s into a list of codepoints
106
var cps = []
107
for(var i = 0, len = s.length; i < len; i++){
108
var code = s.charCodeAt(i)
109
if(code >= 0xD800 && code <= 0xDBFF){
110
var v = 0x10000
111
v += (code & 0x03FF) << 10
112
v += (s.charCodeAt(i + 1) & 0x03FF)
113
cps.push(v)
114
i++
115
}else{
116
cps.push(code)
117
}
118
}
119
return cps
120
}
121
134
throw _b_.TypeError.$factory("'in <string>' requires " +
135
"string as left operand, not " + item.__class__)
136
}
137
if(typeof item == "string"){
138
var nbcar = item.length
139
}else{
140
var nbcar = _b_.len(item)
141
}
142
if(nbcar == 0){
143
// a string contains the empty string
144
return true
145
}
146
if(self.length == 0){
147
return nbcar == 0
148
}
161
// __dir__must be assigned explicitely because attribute resolution for
162
// builtin classes doesn't use __mro__
174
if(fmt.type && fmt.type != "s"){
175
throw _b_.ValueError.$factory("Unknown format code '" + fmt.type +
183
if(fmt.sign !== undefined){
184
throw _b_.ValueError.$factory(
185
"Sign not allowed in string format specifier")
199
if(arg < 0){
200
pos += self.length
201
}
202
if(pos >= 0 && pos < chars.length){
203
return chars[pos]
204
}
208
var s = _b_.slice.$conv_for_seq(arg, self.length),
209
start = s.start,
210
stop = s.stop,
211
step = s.step
212
var res = "",
215
if(stop <= start){
216
return ""
217
}
218
for(var i = start; i < stop; i += step){
219
res += chars[i]
220
}
222
if(stop >= start){
223
return ''
224
}
225
for(var i = start; i > stop; i += step){
226
res += chars[i]
227
}
288
// found at
289
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length
290
if(self instanceof String){
291
return self.codepoints.length
292
}
293
return self.valueOf().length
330
// left adjusted
331
return s + get_char_array(padding - s.length, flags.pad_char)
332
}
333
}
334
342
if(val.__class__ === $B.long_int){
343
s = $B.long_int.to_base(val, 10)
344
}else{
345
s = val.toString()
347
if(s[0] === "-"){
348
return "-" + get_char_array(precision - s.length + 1, "0") + s.slice(1)
359
if(val === Infinity){
360
val = "inf"
361
}else if(val === -Infinity){
362
val = "-inf"
363
}else{
364
val = "nan"
386
var str_format = function(val, flags) {
387
// string format supports left and right padding
388
flags.pad_char = " " // even if 0 padding is defined, don't use it
394
if(val.__class__ === $B.long_int){
395
val = $B.long_int.to_base(val, 10)
396
}else{
397
val = parseInt(val)
415
var repr_format = function(val, flags) {
416
flags.pad_char = " " // even if 0 padding is defined, don't use it
420
var ascii_format = function(val, flags) {
421
flags.pad_char = " " // even if 0 padding is defined, don't use it
435
flags.precision = parseInt(flags.precision, 10)
436
validate_precision(flags.precision)
437
}
438
return parseFloat(val)
439
}
442
var trailing_zeros = /(.*?)(0+)([eE].*)/,
443
leading_zeros = /\.(0*)/,
444
trailing_dot = /\.$/
446
var validate_precision = function(precision) {
447
// force precision to limits of javascript
452
var floating_point_format = function(val, upper, flags){
453
val = _float_helper(val, flags),
454
v = val.toString(),
455
v_len = v.length,
456
dot_idx = v.indexOf('.')
457
if(dot_idx < 0){dot_idx = v_len}
458
if(val < 1 && val > -1){
459
var zeros = leading_zeros.exec(v),
460
numzeros
461
if(zeros){
466
if(numzeros >= 4){
467
val = format_sign(val, flags) + format_float_precision(val, upper,
468
flags, _floating_g_exp_helper)
469
if(!flags.alternate){
482
return format_padding(format_sign(val, flags) +
483
format_float_precision(val, upper, flags,
484
function(val, precision) {
486
numzeros)
487
}),
488
flags
489
)
490
}
491
492
if(dot_idx > flags.precision){
493
val = format_sign(val, flags) + format_float_precision(val, upper,
494
flags, _floating_g_exp_helper)
495
if(! flags.alternate){
507
return format_padding(format_sign(val, flags) +
508
format_float_precision(val, upper, flags,
509
function(val, precision) {
510
if(!flags.decimal_point){
512
}else if (precision > v_len){
513
if(! flags.alternate){
514
precision = v_len
515
}
517
if(precision < dot_idx){
518
precision = dot_idx
519
}
520
return val.toFixed(precision - dot_idx)
521
}),
522
flags
523
)
526
var _floating_g_exp_helper = function(val, precision, flags, upper){
527
if(precision){--precision}
530
var e_idx = val.lastIndexOf("e")
531
if(e_idx > val.length - 4){
532
val = val.substring(0, e_idx + 2) + "0" + val.substring(e_idx + 2)
535
return val
536
}
537
538
// fF
539
var floating_point_decimal_format = function(val, upper, flags) {
540
val = _float_helper(val, flags)
541
return format_padding(format_sign(val, flags) +
542
format_float_precision(val, upper, flags,
543
function(val, precision, flags) {
544
val = val.toFixed(precision)
545
if(precision === 0 && flags.alternate){
546
val += '.'
547
}
548
return val
549
}),
550
flags
551
)
552
}
553
554
var _floating_exp_helper = function(val, precision, flags, upper) {
555
val = val.toExponential(precision)
556
// pad exponent to two digits
569
return format_padding(format_sign(val, flags) +
570
format_float_precision(val, upper, flags, _floating_exp_helper), flags)
596
if(flags.alternate){
597
if(ret.charAt(0) === "-"){
598
if(upper){ret = "-0X" + ret.slice(1)}
599
else{ret = "-0x" + ret.slice(1)}
600
}else{
601
if(upper){ret = "0X" + ret}
602
else{ret = "0x" + ret}
612
if(val.__class__ === $B.long_int){
613
ret = $B.long_int.to_base(8)
614
}else{
615
ret = parseInt(val)
616
ret = ret.toString(8)
632
if(flags.alternate){
633
if(ret.charAt(0) === "-"){ret = "-0o" + ret.slice(1)}
634
else{ret = "0o" + ret}
639
function series_of_bytes(val, flags){
640
if(val.__class__ && val.__class__.$buffer_protocol){
641
var it = _b_.iter(val),
642
ints = []
643
while(true){
644
try{
645
ints.push(_b_.next(it))
646
}catch(err){
647
if(err.__class__ === _b_.StopIteration){
648
var b = _b_.bytes.$factory(ints)
649
return format_padding(_b_.bytes.decode(b, "ascii"), flags)
650
}
651
throw err
652
}
653
}
654
}else{
655
try{
656
bytes_obj = $B.$getattr(val, "__bytes__")
657
return format_padding(_b_.bytes.decode(bytes_obj), flags)
658
}catch(err){
659
if(err.__class__ === _b_.AttributeError){
660
throw _b_.TypeError.$factory("%b does not accept '" +
661
$B.class_name(val) + "'")
662
}
663
throw err
664
}
665
}
666
}
667
672
val = val.source[0]
673
}else{
674
try{
675
val = _b_.int.$factory(val) // yes, floats are valid (they are cast to int)
676
}catch (err){
677
throw _b_.TypeError.$factory("%c requires int or char")
678
}
683
var num_flag = function(c, flags){
684
if(c === "0" && ! flags.padding && ! flags.decimal_point && ! flags.left){
685
flags.pad_char = "0"
691
flags.precision = (flags.precision || "") + c
692
}
693
}
694
695
var decimal_point_flag = function(val, flags) {
697
// can only have one decimal point
698
throw new UnsupportedChar()
699
}
700
flags.decimal_point = true
701
}
702
703
var neg_flag = function(val, flags){
704
flags.pad_char = " " // overrides '0' flag
722
"s": str_format,
723
"d": num_format,
724
"i": num_format,
725
"u": num_format,
726
"o": octal_format,
727
"r": repr_format,
728
"a": ascii_format,
729
"g": function(val, flags){
730
return floating_point_format(val, false, flags)
731
},
732
"G": function(val, flags){return floating_point_format(val, true, flags)},
733
"f": function(val, flags){
734
return floating_point_decimal_format(val, false, flags)
735
},
736
"F": function(val, flags){
737
return floating_point_decimal_format(val, true, flags)
738
},
739
"e": function(val, flags){
740
return floating_point_exponential_format(val, false, flags)
741
},
742
"E": function(val, flags){
743
return floating_point_exponential_format(val, true, flags)
744
},
745
"x": function(val, flags){return signed_hex_format(val, false, flags)},
746
"X": function(val, flags){return signed_hex_format(val, true, flags)},
747
"c": single_char_format,
748
"0": function(val, flags){return num_flag("0", flags)},
749
"1": function(val, flags){return num_flag("1", flags)},
750
"2": function(val, flags){return num_flag("2", flags)},
751
"3": function(val, flags){return num_flag("3", flags)},
752
"4": function(val, flags){return num_flag("4", flags)},
753
"5": function(val, flags){return num_flag("5", flags)},
754
"6": function(val, flags){return num_flag("6", flags)},
755
"7": function(val, flags){return num_flag("7", flags)},
756
"8": function(val, flags){return num_flag("8", flags)},
757
"9": function(val, flags){return num_flag("9", flags)},
758
"-": neg_flag,
759
" ": space_flag,
760
"+": sign_flag,
761
".": decimal_point_flag,
762
"#": alternate_flag
763
}
764
765
// exception thrown when an unsupported char is encountered in legacy format
811
if(self === undefined){
812
throw _b_.TypeError.$factory(
813
"not enough arguments for format string")
840
throw _b_.ValueError.$factory(
841
"unsupported format character '" + invalid_char +
842
"' (0x" + invalid_char.charCodeAt(0).toString(16) +
843
") at index " + newpos)
844
}else if(err.name === "NotANumber"){
845
var try_char = s[newpos],
846
cls = self.__class__
847
if(!cls){
848
if(typeof(self) === "string"){
849
cls = "str"
850
}else{
856
throw _b_.TypeError.$factory("%" + try_char +
857
" format: a number is required, not " + cls)
858
}else{
890
}while(pos < length)
891
892
if(argpos !== null){
893
if(args.length > argpos){
894
throw _b_.TypeError.$factory(
895
"not enough arguments for format string")
896
}else if(args.length < argpos){
897
throw _b_.TypeError.$factory(
898
"not all arguments converted during string formatting")
900
}else if(nbph == 0){
901
throw _b_.TypeError.$factory(
902
"not all arguments converted during string formatting")
910
var $ = $B.args("__mul__", 2, {self: null, other: null},
911
["self", "other"], arguments, {}, null, null)
922
function __newobj__(){
923
// __newobj__ is called with a generator as only argument
924
var $ = $B.args('__newobj__', 0, {}, [], arguments, {}, 'args', null),
925
args = $.args
926
var res = args[1]
927
res.__class__ = args[0]
928
return res
929
}
930
931
str.__reduce_ex__ = function(self){
932
return $B.fast_tuple([
933
__newobj__,
934
$B.fast_tuple([self.__class__ || _b_.str, self]),
935
_b_.None,
936
_b_.None])
937
}
938
941
var t = {
942
8: "\\x08",
943
9: "\\t",
944
10: "\\n",
945
11: "\\x0b",
946
12: "\\x0c",
947
13: "\\r",
948
92: "\\\\"
949
}
950
var repl = '',
951
chars = to_chars(self)
952
for(var i = 0; i < chars.length; i++){
953
var cp = _b_.ord(chars[i])
954
if(t[cp] !== undefined){
955
repl += t[cp]
956
}else if($B.is_unicode_cn(cp)){
975
if(res.search('"') == -1 && res.search("'") == -1){
976
return "'" + res + "'"
977
}else if(self.search('"') == -1){
978
return '"' + res + '"'
979
}
980
var qesc = new RegExp("'", "g") // to escape single quote
981
res = "'" + res.replace(qesc, "\\'") + "'"
985
str.__rmul__ = function(self, other){
986
if(_b_.isinstance(other, _b_.int)){
987
other = _b_.int.numerator(other)
988
var res = ''
989
while(other > 0){
990
res += self
991
other--
992
}
993
return res
994
}
995
return _b_.NotImplemented
996
}
997
998
str.__setattr__ = function(self, attr, value){
999
if(typeof self === "string"){
1000
if(str.hasOwnProperty(attr)){
1002
attr + "' is read-only")
1003
}else{
1004
throw _b_.AttributeError.$factory(
1005
"'str' object has no attribute '" + attr + "'")
1006
}
1007
}
1008
// str subclass : use __dict__
1009
_b_.dict.$setitem(self.__dict__, attr, value)
1010
return $N
1011
}
1012
1013
str.__setitem__ = function(self, attr, value){
1014
throw _b_.TypeError.$factory(
1015
"'str' object does not support item assignment")
1018
var combining = []
1019
for(var cp = 0x300; cp <= 0x36F; cp++){
1020
combining.push(String.fromCharCode(cp))
1021
}
1025
var repl = '',
1026
chars = to_chars(self)
1027
if(chars.length == self.length){
1028
return self.replace(combining_re, "\u200B$1")
1029
}
1030
for(var i = 0; i < chars.length; i++){
1031
var cp = _b_.ord(chars[i])
1032
if(cp >= 0x300 && cp <= 0x36F){
1033
repl += "\u200B" + chars[i]
1034
}else{
1035
repl += chars[i]
1036
}
1037
}
1038
return repl
1048
$comp_func += "" // source code
1049
var $comps = {">": "gt", ">=": "ge", "<": "lt", "<=": "le"}
1060
str.capitalize = function(self){
1061
var $ = $B.args("capitalize", 1, {self}, ["self"],
1062
arguments, {}, null, null)
1066
return self.charAt(0).toUpperCase() + self.substr(1)
1067
}
1068
1069
str.casefold = function(self){
1070
var $ = $B.args("casefold", 1, {self}, ["self"],
1071
arguments, {}, null, null),
1072
res = "",
1073
char,
1074
cf,
1075
chars = to_chars($.self)
1076
1077
for(var i = 0, len = chars.length; i < len; i++){
1078
char = chars[i]
1079
cf = $B.unicode_casefold[char]
1080
if(cf){
1081
cf.forEach(function(cp){
1082
res += String.fromCharCode(cp)
1083
})
1084
}else{
1091
str.center = function(){
1092
var $ = $B.args("center", 3, {self: null, width: null, fillchar: null},
1093
["self", "width", "fillchar"],
1094
arguments, {fillchar:" "}, null, null),
1095
self = $.self
1099
var pad = parseInt(($.width - self.length) / 2),
1100
res = $.fillchar.repeat(pad)
1109
var $ = $B.args("count", 4, {self:null, sub:null, start:null, stop:null},
1110
["self", "sub", "start", "stop"], arguments, {start:null, stop:null},
1113
throw _b_.TypeError.$factory("Can't convert '" + $B.class_name($.sub) +
1114
"' object to str implicitly")
1115
}
1119
if($.stop !== null){
1120
_slice = _b_.slice.$factory($.start, $.stop)
1121
}else{
1122
_slice = _b_.slice.$factory($.start, $.self.length)
1123
}
1131
if($.start == $.self.length){
1132
return 1
1133
}else if(substr.length == 0){
1134
return 0
1135
}
1138
var n = 0,
1139
pos = 0
1140
while(pos < substr.length){
1141
pos = substr.indexOf($.sub, pos)
1152
str.encode = function(){
1153
var $ = $B.args("encode", 3, {self: null, encoding: null, errors: null},
1154
["self", "encoding", "errors"], arguments,
1155
{encoding: "utf-8", errors: "strict"}, null, null)
1156
if($.encoding == "rot13" || $.encoding == "rot_13"){
1159
for(var i = 0, len = $.self.length; i < len ; i++){
1160
var char = $.self.charAt(i)
1161
if(("a" <= char && char <= "m") || ("A" <= char && char <= "M")){
1162
res += String.fromCharCode(String.charCodeAt(char) + 13)
1163
}else if(("m" < char && char <= "z") ||
1164
("M" < char && char <= "Z")){
1165
res += String.fromCharCode(String.charCodeAt(char) - 13)
1174
// Return True if the string ends with the specified suffix, otherwise
1175
// return False. suffix can also be a tuple of suffixes to look for.
1176
// With optional start, test beginning at that position. With optional
1180
["self", "suffix", "start", "end"],
1181
arguments, {start: 0, end: null}, null, null)
1194
if(! _b_.isinstance(suffix, str)){
1195
throw _b_.TypeError.$factory(
1196
"endswith first arg must be str or a tuple of str, not int")
1197
}
1207
var $ = $B.args("expandtabs", 2, {self: null, tabsize: null},
1208
["self", "tabsize"], arguments, {tabsize: 8}, null, null)
1209
var s = $B.$GetInt($.tabsize),
1210
col = 0,
1211
pos = 0,
1212
res = "",
1213
chars = to_chars(self)
1214
if(s == 1){
1215
return self.replace(/\t/g," ")
1216
}
1217
while(pos < chars.length){
1218
var car = chars[pos]
1228
res += car
1229
col = 0
1230
break
1231
default:
1232
res += car
1233
col++
1234
break
1235
}
1236
pos++
1237
}
1238
return res
1242
// Return the lowest index in the string where substring sub is found,
1243
// such that sub is contained in the slice s[start:end]. Optional
1244
// arguments start and end are interpreted as in slice notation.
1247
{self: null, sub: null, start: null, end: null},
1248
["self", "sub", "start", "end"],
1249
arguments, {start: 0, end: null}, null, null)
1255
throw _b_.TypeError.$factory("slice indices must be " +
1256
"integers or None or have an __index__ method")}
1257
// Can't use string.substring(start, end) because if end < start,
1258
// Javascript transforms it into substring(end, start)...
1259
var s = ""
1260
for(var i = $.start; i < $.end; i++){
1261
s += $.self.charAt(i)
1262
}
1264
var len = str.__len__($.self)
1265
1266
if($.sub.length == 0 && $.start == len){
1267
return len
1268
}
1269
if(s.length + $.sub.length == 0){
1270
return -1
1271
}
1273
var last_search = s.length - $.sub.length
1274
for(var i = 0; i <= last_search; i++){
1275
if(s.substr(i, $.sub.length) == $.sub){
1276
return $.start + str.__len__(s.substr(0, i))
1277
}
1288
// a.x[z]!r:...
1289
// the object has attributes :
1290
// - name : "a"
1291
// - name_ext : [".x", "[z]"]
1292
// - conv : r
1293
// - spec : rest of string after :
1301
// No : in the string : it only contains a name
1302
name = fmt_string
1303
}else{
1304
// name is before the first ":"
1305
// spec (the format specification) is after
1306
name = elts[0]
1310
var elts = name.split("!")
1311
if(elts.length > 1){
1312
name = elts[0]
1313
conv = elts[1] // conversion flag
1317
// "name' may be a subscription or attribute
1318
// Put these "extensions" in the list "name_ext"
1319
function name_repl(match){
1320
name_ext.push(match)
1322
}
1323
var name_ext_re = /\.[_a-zA-Z][_a-zA-Z0-9]*|\[[_a-zA-Z][_a-zA-Z0-9]*\]|\[[0-9]+\]/g
1324
name = name.replace(name_ext_re, name_repl)
1325
}
1332
// Parse self to detect formatting instructions
1333
// Create a list "parts" made of sections of the string :
1334
// - elements of even rank are literal text
1335
// - elements of odd rank are "format objects", built from the
1336
// format strings in self (of the form {...})
1347
text += "{"
1348
pos += 2
1349
}else if(car == "}" && self.charAt(pos + 1) == "}"){
1356
// Store current literal text
1357
parts.push(text)
1358
1359
// Search the end of the format string, ie the } closing the
1360
// opening {. Since the string can contain other pairs {} for
1361
// nested formatting, an integer nb is incremented for each { and
1362
// decremented for each } ; the end of the format string is
1363
// reached when nb == 0
1364
var end = pos + 1,
1365
nb = 1
1366
while(end < _len){
1367
if(self.charAt(end) == "{"){nb++; end++}
1368
else if(self.charAt(end) == "}"){
1369
nb--; end++
1370
if(nb == 0){
1375
var fmt_obj = $B.parse_format(fmt_string)
1376
fmt_obj.raw_name = fmt_obj.name
1377
fmt_obj.raw_spec = fmt_obj.spec
1411
}else{
1412
text += car
1413
pos++
1414
}
1415
}
1416
if(text){
1417
parts.push(text)
1423
// Special management of keyword arguments if str.format is called by
1424
// str.format_map(mapping) : the argument "mapping" might not be a
1425
// dictionary
1426
var last_arg = $B.last(arguments)
1427
if(last_arg.$nat == "mapping"){
1428
var mapping = last_arg.mapping,
1429
getitem = $B.$getattr(mapping, "__getitem__")
1430
// Get the rest of the arguments
1431
var args = []
1432
for(var i = 0, len = arguments.length - 1; i < len; i++){
1433
args.push(arguments[i])
1434
}
1435
var $ = $B.args("format", 1, {self: null}, ["self"],
1436
args, {}, "$args", null)
1437
}else{
1438
var $ = $B.args("format", 1, {self: null}, ["self"],
1439
arguments, {}, "$args", "$kw"),
1440
mapping = $.$kw, // dictionary
1441
getitem = function(key){
1442
return _b_.dict.$getitem(mapping, key)
1443
}
1444
}
1457
1458
if(fmt.spec !== undefined){
1459
// "spec" may contain "nested replacement fields"
1460
// In this case, evaluate them using the positional
1461
// or keyword arguments passed to format()
1462
function replace_nested(name, key){
1463
if(/\d+/.exec(key)){
1464
// If key is numeric, search in positional
1465
// arguments
1466
return _b_.tuple.__getitem__($.$args,
1467
parseInt(key))
1468
}else{
1469
// Else try in keyword arguments
1470
return _b_.dict.__getitem__($.$kw, key)
1471
}
1472
}
1473
fmt.spec = fmt.spec.replace(/\{(.*?)\}/g,
1474
replace_nested)
1475
}
1477
// Numerical reference : use positional arguments
1478
var pos = parseInt(fmt.name),
1499
// If the conversion flag is set, first call a function to convert
1500
// the value
1501
if(fmt.conv == "a"){value = _b_.ascii(value)}
1502
else if(fmt.conv == "r"){value = _b_.repr(value)}
1503
else if(fmt.conv == "s"){value = _b_.str.$factory(value)}
1516
str.format_map = function(self, mapping){
1517
var $ = $B.args("format_map", 2, {self: null, mapping: null},
1518
['self', 'mapping'], arguments, {}, null, null)
1519
return str.format(self, {$nat: 'mapping', mapping})
1532
/* Return true if the string is empty or all characters in the string are
1533
ASCII, false otherwise. ASCII characters have code points in the range
1534
U+0000-U+007F. */
1543
str.isalnum = function(self){
1544
/* Return true if all characters in the string are alphanumeric and there
1545
is at least one character, false otherwise. A character c is alphanumeric
1546
if one of the following returns True: c.isalpha(), c.isdecimal(),
1547
c.isdigit(), or c.isnumeric(). */
1548
var $ = $B.args("isalnum", 1, {self: null}, ["self"],
1549
arguments, {}, null, null),
1550
cp
1551
for(var char of to_chars(self)){
1552
cp = _b_.ord(char)
1553
if(unicode_tables.Ll[cp] ||
1554
unicode_tables.Lu[cp] ||
1555
unicode_tables.Lm[cp] ||
1556
unicode_tables.Lt[cp] ||
1557
unicode_tables.Lo[cp] ||
1558
unicode_tables.Nd[cp] ||
1559
unicode_tables.digits[cp] ||
1560
unicode_tables.numeric[cp]){
1561
continue
1562
}
1563
return false
1564
}
1565
return true
1566
}
1567
1568
str.isalpha = function(self){
1569
/* Return true if all characters in the string are alphabetic and there is
1570
at least one character, false otherwise. Alphabetic characters are those
1571
characters defined in the Unicode character database as "Letter", i.e.,
1572
those with general category property being one of "Lm", "Lt", "Lu", "Ll",
1573
or "Lo". */
1574
var $ = $B.args("isalpha", 1, {self: null}, ["self"],
1575
arguments, {}, null, null),
1576
cp
1577
for(var char of to_chars(self)){
1578
cp = _b_.ord(char)
1579
if(unicode_tables.Ll[cp] ||
1580
unicode_tables.Lu[cp] ||
1581
unicode_tables.Lm[cp] ||
1582
unicode_tables.Lt[cp] ||
1583
unicode_tables.Lo[cp]){
1584
continue
1585
}
1586
return false
1587
}
1588
return true
1589
}
1590
1591
str.isdecimal = function(self){
1592
/* Return true if all characters in the string are decimal characters and
1593
there is at least one character, false otherwise. Decimal characters are
1594
those that can be used to form numbers in base 10, e.g. U+0660,
1595
ARABIC-INDIC DIGIT ZERO. Formally a decimal character is a character in
1596
the Unicode General Category "Nd". */
1597
var $ = $B.args("isdecimal", 1, {self: null}, ["self"],
1598
arguments, {}, null, null),
1599
cp
1600
for(var char of to_chars(self)){
1601
cp = _b_.ord(char)
1602
if(! unicode_tables.Nd[cp]){
1603
return false
1604
}
1605
}
1606
return self.length > 0
1607
}
1608
1609
str.isdigit = function(self){
1610
/* Return true if all characters in the string are digits and there is at
1611
least one character, false otherwise. */
1612
var $ = $B.args("isdigit", 1, {self: null}, ["self"],
1613
arguments, {}, null, null),
1614
cp
1615
for(var char of to_chars(self)){
1616
cp = _b_.ord(char)
1617
if(! unicode_tables.digits[cp]){
1618
return false
1619
}
1620
}
1621
return self.length > 0
1622
}
1623
1624
str.isidentifier = function(self){
1625
/* Return true if the string is a valid identifier according to the
1626
language definition. */
1627
var $ = $B.args("isidentifier", 1, {self: null}, ["self"],
1631
}
1632
var chars = to_chars(self)
1633
if(unicode_tables.XID_Start[_b_.ord(chars[0])] === undefined){
1636
for(var char of chars){
1637
var cp = _b_.ord(char)
1638
if(unicode_tables.XID_Continue[cp] === undefined){
1639
return false
1640
}
1641
}
1642
}
1643
return true
1644
}
1645
1646
str.islower = function(self){
1647
/* Return true if all cased characters 4 in the string are lowercase and
1648
there is at least one cased character, false otherwise. */
1649
var $ = $B.args("islower", 1, {self: null}, ["self"],
1650
arguments, {}, null, null),
1651
has_cased = false,
1654
for(var char of to_chars(self)){
1655
cp = _b_.ord(char)
1656
if(unicode_tables.Ll[cp]){
1657
has_cased = true
1658
continue
1659
}else if(unicode_tables.Lu[cp] || unicode_tables.Lt[cp]){
1660
return false
1661
}
1662
}
1663
return has_cased
1664
}
1665
1666
str.isnumeric = function(self){
1667
/* Return true if all characters in the string are numeric characters, and
1668
there is at least one character, false otherwise. Numeric characters
1669
include digit characters, and all characters that have the Unicode numeric
1670
value property, e.g. U+2155, VULGAR FRACTION ONE FIFTH. Formally, numeric
1671
characters are those with the property value Numeric_Type=Digit,
1672
Numeric_Type=Decimal or Numeric_Type=Numeric.*/
1673
var $ = $B.args("isnumeric", 1, {self: null}, ["self"],
1674
arguments, {}, null, null)
1683
var unprintable = {},
1684
unprintable_gc = ['Cc', 'Cf', 'Co', 'Cs','Zl', 'Zp', 'Zs']
1685
1686
str.isprintable = function(self){
1687
/* Return true if all characters in the string are printable or the string
1688
is empty, false otherwise. Nonprintable characters are those characters
1689
defined in the Unicode character database as "Other" or "Separator",
1690
excepting the ASCII space (0x20) which is considered printable. */
1691
1692
// Set unprintable if not set yet
1693
if(Object.keys(unprintable).length == 0){
1694
for(var i = 0; i < unprintable_gc.length; i++){
1695
var table = unicode_tables[unprintable_gc[i]]
1706
return false
1707
}
1708
}
1709
return true
1710
}
1711
1712
str.isspace = function(self){
1713
/* Return true if there are only whitespace characters in the string and
1714
there is at least one character, false otherwise.
1715
1716
A character is whitespace if in the Unicode character database, either its
1717
general category is Zs ("Separator, space"), or its bidirectional class is
1718
one of WS, B, or S.*/
1719
var $ = $B.args("isspace", 1, {self: null}, ["self"],
1720
arguments, {}, null, null),
1721
cp
1722
for(var char of to_chars(self)){
1723
cp = _b_.ord(char)
1724
if(! unicode_tables.Zs[cp] &&
1725
$B.unicode_bidi_whitespace.indexOf(cp) == -1){
1726
return false
1727
}
1728
}
1729
return self.length > 0
1730
}
1731
1732
str.istitle = function(self){
1733
/* Return true if the string is a titlecased string and there is at least
1734
one character, for example uppercase characters may only follow uncased
1735
characters and lowercase characters only cased ones. Return false
1736
otherwise. */
1737
var $ = $B.args("istitle", 1, {self: null}, ["self"],
1738
arguments, {}, null, null)
1739
return self.length > 0 && str.title(self) == self
1740
}
1741
1742
str.isupper = function(self){
1743
/* Return true if all cased characters 4 in the string are lowercase and
1744
there is at least one cased character, false otherwise. */
1745
var $ = $B.args("islower", 1, {self: null}, ["self"],
1746
arguments, {}, null, null),
1750
for(var char of to_chars(self)){
1751
cp = _b_.ord(char)
1752
if(unicode_tables.Lu[cp]){
1753
is_upper = true
1754
continue
1755
}else if(unicode_tables.Ll[cp] || unicode_tables.Lt[cp]){
1774
throw _b_.TypeError.$factory("sequence item " + count +
1775
": expected str instance, " + $B.class_name(obj2) +
1776
" found")
1777
}
1790
var $ = $B.args("ljust", 3, {self: null, width: null, fillchar:null},
1791
["self", "width", "fillchar"],
1795
if($.width <= len){
1796
return self
1797
}
1798
return self + $.fillchar.repeat($.width - len)
1801
str.lower = function(self){
1802
var $ = $B.args("lower", 1, {self: null}, ["self"],
1803
arguments, {}, null, null)
1804
return self.toLowerCase()
1805
}
1806
1808
var $ = $B.args("lstrip", 2, {self: null, chars: null}, ["self", "chars"],
1809
arguments, {chars:_b_.None}, null, null)
1810
if($.chars === _b_.None){
1811
return $.self.trimLeft()
1812
}
1813
var chars = to_chars(self)
1814
for(var i = 0, len = chars.length; i < len; i++){
1815
if($.chars.indexOf(chars[i]) === -1){
1816
return chars.slice(i).join('')
1824
var $ = $B.args("maketrans", 3, {x: null, y: null, z: null},
1825
["x", "y", "z"], arguments, {y: null, z: null}, null, null)
1830
// If there is only one argument, it must be a dictionary mapping
1831
// Unicode ordinals (integers) or characters (strings of length 1) to
1832
// Unicode ordinals, strings (of arbitrary lengths) or None. Character
1834
if(! _b_.isinstance($.x, _b_.dict)){
1835
throw _b_.TypeError.$factory(
1836
"maketrans only argument must be a dict")
1839
for(var i = 0, len = items.length; i < len; i++){
1840
var k = items[i][0],
1841
v = items[i][1]
1842
if(! _b_.isinstance(k, _b_.int)){
1843
if(_b_.isinstance(k, _b_.str) && k.length == 1){
1844
k = _b_.ord(k)
1845
}else{throw _b_.TypeError.$factory("dictionary key " + k +
1848
if(v !== _b_.None && ! _b_.isinstance(v, [_b_.int, _b_.str])){
1849
throw _b_.TypeError.$factory("dictionary value " + v +
1857
// and in the resulting dictionary, each character in x will be mapped
1858
// to the character at the same position in y
1861
}else if($.x.length !== $.y.length){
1862
throw _b_.TypeError.$factory(
1863
"maketrans arguments must be strings or same length")
1869
if(! _b_.isinstance($.z, _b_.str)){
1870
throw _b_.TypeError.$factory(
1871
"maketrans third argument must be a string")
1893
var $ = $B.args("partition", 2, {self: null, sep: null}, ["self", "sep"],
1894
arguments, {}, null, null)
1901
if(i == -1){
1902
return _b_.tuple.$factory([$.self, "", ""])
1903
}
1904
return _b_.tuple.$factory([chars.slice(0, i).join(''), $.sep,
1905
chars.slice(i + $.sep.length).join('')])
1908
str.removeprefix = function(){
1909
var $ = $B.args("removeprefix", 2, {self: null, prefix: null},
1910
["self", "prefix"], arguments, {}, null, null)
1911
if(!_b_.isinstance($.prefix, str)){
1912
throw _b_.ValueError.$factory("prefix should be str, not " +
1913
`'${$B.class_name($.prefix)}'`)
1914
}
1915
if(str.startswith($.self, $.prefix)){
1916
return $.self.substr($.prefix.length)
1917
}
1918
return $.self.substr(0)
1919
}
1920
1921
str.removesuffix = function(){
1922
var $ = $B.args("removesuffix", 2, {self: null, prefix: null},
1923
["self", "suffix"], arguments, {}, null, null)
1924
if(!_b_.isinstance($.suffix, str)){
1925
throw _b_.ValueError.$factory("suffix should be str, not " +
1926
`'${$B.class_name($.prefix)}'`)
1927
}
1928
if($.suffix.length > 0 && str.endswith($.self, $.suffix)){
1929
return $.self.substr(0, $.self.length - $.suffix.length)
1930
}
1931
return $.self.substr(0)
1932
}
1933
1934
function $re_escape(str){
1935
var specials = "[.*+?|()$^"
1936
for(var i = 0, len = specials.length; i < len; i++){
1937
var re = new RegExp("\\"+specials.charAt(i), "g")
1938
str = str.replace(re, "\\"+specials.charAt(i))
1939
}
1940
return str
1947
var $ = $B.args("replace", 4,
1948
{self: null, old: null, $$new: null, count: null},
1949
["self", "old", "$$new", "count"],
1950
arguments, {count: -1}, null, null),
1951
count = $.count,
1952
self = $.self,
1953
old = $.old,
1954
_new = $.$$new
1956
check_str(old, "replace() argument 1 ")
1957
check_str(_new, "replace() argument 2 ")
1965
if(count == 0){
1966
return self
1967
}
1968
if(count.__class__ == $B.long_int){
1969
count = parseInt(count.value)
1970
}
1972
if(_new == ""){
1973
return self
1974
}
1975
if(self == ""){
1976
return _new
1977
}
1978
var elts = self.split("")
1979
if(count > -1 && elts.length >= count){
1980
var rest = elts.slice(count).join("")
1981
return _new + elts.slice(0, count).join(_new) + rest
2007
res = res.substr(0, pos) + _new + res.substr(pos + old.length)
2008
pos = pos + _new.length
2009
count--
2015
// Return the highest index in the string where substring sub is found,
2016
// such that sub is contained within s[start:end]. Optional arguments
2018
if(arguments.length == 2 && typeof substr == "string"){
2019
return self.lastIndexOf(substr)
2020
}
2022
{self: null, sub: null, start: null, end: null},
2023
["self", "sub", "start", "end"],
2024
arguments, {start: 0, end: null}, null, null)
2031
if($.start > $.self.length){
2032
return -1
2033
}else{
2034
return str.__len__($.self)
2035
}
2041
if($.self.substr(i, sublen) == $.sub){
2042
return str.__len__($.self.substr(0, i))
2043
}
2058
var $ = $B.args("rjust",3,
2059
{self: null, width: null, fillchar: null},
2060
["self", "width", "fillchar"],
2061
arguments, {fillchar: " "}, null, null)
2071
var $ = $B.args("rpartition", 2, {self: null, sep: null}, ["self", "sep"],
2072
arguments, {}, null, null)
2076
var items = str.partition(self, sep).reverse()
2077
for(var i = 0; i < items.length; i++){
2078
items[i] = items[i].split("").reverse().join("")
2084
var $ = $B.args("rsplit", 3, {self: null, sep: null, maxsplit: null},
2085
["self", "sep", "maxsplit"], arguments,
2086
{sep: _b_.None, maxsplit: -1}, null, null),
2087
sep = $.sep
2090
var rev_str = reverse($.self),
2091
rev_sep = sep === _b_.None ? sep : reverse($.sep),
2102
str.rstrip = function(self, x){
2103
var $ = $B.args("rstrip", 2, {self: null, chars: null}, ["self", "chars"],
2105
if($.chars === _b_.None){
2106
return $.self.trimRight()
2107
}
2108
var chars = to_chars(self)
2109
for(var j = chars.length - 1; j >= 0; j--){
2110
if($.chars.indexOf(chars[j]) == -1){
2111
return chars.slice(0, j + 1).join('')
2118
var $ = $B.args("split", 3, {self: null, sep: null, maxsplit: null},
2119
["self", "sep", "maxsplit"], arguments,
2120
{sep: _b_.None, maxsplit: -1}, null, null),
2121
sep = $.sep,
2122
maxsplit = $.maxsplit,
2123
self = $.self,
2124
pos = 0
2125
if(maxsplit.__class__ === $B.long_int){
2126
maxsplit = parseInt(maxsplit.value)
2127
}
2128
if(sep == ""){
2129
throw _b_.ValueError.$factory("empty separator")
2130
}
2133
while(pos < self.length && self.charAt(pos).search(/\s/) > -1){
2134
pos++
2135
}
2136
if(pos === self.length - 1){
2137
return [self]
2138
}
2142
if(name == ""){
2143
name = self.charAt(pos)
2144
}else{
2145
name += self.charAt(pos)
2146
}
2168
var res = [],
2169
s = "",
2170
seplen = sep.length
2171
if(maxsplit == 0){return [self]}
2172
while(pos < self.length){
2173
if(self.substr(pos, seplen) == sep){
2191
str.splitlines = function(self) {
2192
var $ = $B.args('splitlines', 2, {self: null, keepends: null},
2193
['self','keepends'], arguments, {keepends: false},
2194
null, null)
2195
if(!_b_.isinstance($.keepends,[_b_.bool, _b_.int])){
2196
throw _b_.TypeError('integer argument expected, got '+
2199
var keepends = _b_.int.$factory($.keepends),
2200
res = [],
2201
self = $.self,
2202
start = 0,
2203
pos = 0
2204
if(!self.length){
2208
if(self.substr(pos, 2) == '\r\n'){
2209
res.push(self.slice(start, keepends ? pos + 2 : pos))
2210
start = pos = pos+2
2211
}else if(self[pos] == '\r' || self[pos] == '\n'){
2212
res.push(self.slice(start, keepends ? pos+1 : pos))
2213
start = pos = pos+1
2214
}else{
2215
pos++
2216
}
2217
}
2218
if(start < self.length){
2219
res.push(self.slice(start))
2220
}
2221
return res
2225
// Return True if string starts with the prefix, otherwise return False.
2226
// prefix can also be a tuple of prefixes to look for. With optional
2227
// start, test string beginning at that position. With optional end,
2229
var $ = $B.args("startswith", 4,
2230
{self: null, prefix: null, start: null, end: null},
2231
["self", "prefix", "start", "end"],
2232
arguments, {start: 0, end: null}, null, null)
2244
if(! _b_.isinstance(prefix, str)){
2245
throw _b_.TypeError.$factory("endswith first arg must be str " +
2246
"or a tuple of str, not int")
2247
}
2248
if(s.substr(0, prefix.length) == prefix){
2249
return true
2250
}
2256
var $ = $B.args("strip", 2, {self: null, chars: null}, ["self", "chars"],
2257
arguments, {chars: _b_.None}, null, null)
2258
if($.chars === _b_.None){
2259
return $.self.trim()
2260
}
2261
var chars = to_chars($.self)
2262
for(var i = 0; i < chars.length; i++){
2263
if($.chars.indexOf(chars[i]) == -1){
2267
for(var j = chars.length - 1; j >= i; j--){
2268
if($.chars.indexOf(chars[j]) == -1){
2275
str.swapcase = function(self){
2276
var $ = $B.args("swapcase", 1, {self}, ["self"],
2277
arguments, {}, null, null),
2278
res = "",
2279
cp
2280
2281
for(var char of to_chars(self)){
2282
cp = _b_.ord(char)
2283
if(unicode_tables.Ll[cp]){
2284
res += char.toUpperCase()
2285
}else if(unicode_tables.Lu[cp]){
2286
res += char.toLowerCase()
2289
}
2290
}
2291
return res
2292
}
2293
2294
str.title = function(self){
2295
var $ = $B.args("title", 1, {self}, ["self"],
2296
arguments, {}, null, null),
2297
state,
2300
for(var char of to_chars(self)){
2301
cp = _b_.ord(char)
2302
if(unicode_tables.Ll[cp]){
2309
}else if(unicode_tables.Lu[cp] || unicode_tables.Lt[cp]){
2310
res += state ? char.toLowerCase() : char
2322
getitem = $B.$getattr(table, "__getitem__"),
2323
cp
2324
for(var char of to_chars(self)){
2325
cp = _b_.ord(char)
2329
if(typeof repl == "string"){
2330
res.push(repl)
2331
}else if(typeof repl == "number"){
2332
res.push(String.fromCharCode(repl))
2333
}
2342
str.upper = function(self){
2343
var $ = $B.args("upper", 1, {self: null}, ["self"],
2344
arguments, {}, null, null)
2345
return self.toUpperCase()
2346
}
2347
2350
["self", "width"], arguments, {}, null, null),
2351
len = str.__len__(self)
2352
if($.width <= len){
2353
return self
2354
}
2374
if(encoding !== undefined){
2375
// Arguments may be passed as keywords (cf. issue #1060)
2376
var $ = $B.args("str", 3, {arg: null, encoding: null, errors: null},
2377
["arg", "encoding", "errors"], arguments,
2378
{encoding: "utf-8", errors: "strict"}, null, null),
2379
encoding = $.encoding,
2380
errors = $.errors
2381
}
2392
// class or its subclasses, but the attribute __str__ of the
2393
// class metaclass (usually "type") or its subclasses (usually
2394
// "object")
2395
// The metaclass is the attribute __class__ of the class dictionary
2400
if(arg.__class__ && arg.__class__ === _b_.bytes &&
2401
encoding !== undefined){
2402
// str(bytes, encoding, errors) is equal to
2403
// bytes.decode(encoding, errors)
2406
// Implicit invocation of __str__ uses method __str__ on the class,
2407
// even if arg has an attribute __str__
2408
var klass = arg.__class__ || $B.get_class(arg)
2414
// if not better than object.__str__, try __repr__
2415
(arg.__class__ && arg.__class__ !== _b_.object &&
2416
method.$infos && method.$infos.__func__ === _b_.object.__str__)){
2417
var method = $B.$getattr(klass, "__repr__")
2423
if($B.debug > 1){console.log(err)}
2424
console.log("Warning - no method __str__ or __repr__, " +
2425
"default to toString", arg)
2432
if(cls === undefined){
2433
throw _b_.TypeError.$factory("str.__new__(): not enough arguments")
2457
var args = [],
2458
pos = 0
2459
if(arguments.length > 0){
2460
var args = [arguments[0].valueOf()],
2461
pos = 1
2462
for(var i = 1, len = arguments.length; i < len; i++){
2463
args[pos++] = arguments[i]
2480
// Function to parse the 2nd argument of format()
2481
$B.parse_format_spec = function(spec){
2485
var pos = 0,
2486
aligns = "<>=^",
2487
digits = "0123456789",
2488
types = "bcdeEfFgGnosxX%",
2490
if(align_pos != -1){
2491
if(spec.charAt(1) && aligns.indexOf(spec.charAt(1)) != -1){
2492
// If the second char is also an alignment specifier, the
2493
// first char is the fill value
2494
this.fill = spec.charAt(0)
2495
this.align = spec.charAt(1)
2496
pos = 2
2497
}else{
2498
// The first character defines alignment : fill defaults to ' '
2513
if(car == "+" || car == "-" || car == " "){
2514
this.sign = car
2515
pos++
2516
car = spec.charAt(pos)
2531
if(this.width === undefined){
2532
this.width = car
2533
}else{
2534
this.width += car
2535
}
2542
if(this.width === undefined && car == "{"){
2543
// Width is determined by a parameter
2544
var end_param_pos = spec.substr(pos).search("}")
2545
this.width = spec.substring(pos, end_param_pos)
2546
console.log("width", "[" + this.width + "]")
2547
pos += end_param_pos + 1
2548
}
2549
if(car == ","){
2550
this.comma = true
2551
pos++
2552
car = spec.charAt(pos)
2553
}
2554
if(car == "."){
2555
if(digits.indexOf(spec.charAt(pos + 1)) == -1){
2556
throw _b_.ValueError.$factory(
2557
"Missing precision in format spec")
2559
this.precision = spec.charAt(pos + 1)
2560
pos += 2
2561
car = spec.charAt(pos)
2562
while(car && digits.indexOf(car) > -1){
2569
if(car && types.indexOf(car) > -1){
2570
this.type = car
2571
pos++
2572
car = spec.charAt(pos)
2573
}
2574
if(pos !== spec.length){
2580
return (this.fill === undefined ? "" : _b_.str.$factory(this.fill)) +
2581
(this.align || "") +
2582
(this.sign || "") +
2583
(this.alternate ? "#" : "") +
2584
(this.sign_aware ? "0" : "") +
2585
(this.width || "") +
2586
(this.comma ? "," : "") +
2587
(this.precision ? "." + this.precision : "") +
2588
(this.type || "")
2593
if(fmt.width && s.length < fmt.width){
2594
var fill = fmt.fill || " ",
2595
align = fmt.align || "<",
2596
missing = fmt.width - s.length
2598
case "<":
2599
return s + fill.repeat(missing)
2600
case ">":
2601
return fill.repeat(missing) + s
2602
case "=":
2603
if("+-".indexOf(s.charAt(0)) > -1){
2604
return s.charAt(0) + fill.repeat(missing) + s.substr(1)
2608
case "^":
2609
var left = parseInt(missing / 2)
2610
return fill.repeat(left) + s + fill.repeat(missing - left)
2623
function fstring_error(msg, pos){
2624
error = Error(msg)
2625
error.position = pos
2626
throw error
2627
}
2628
2629
$B.parse_fstring = function(string){
2630
// Parse a f-string
2631
var elts = [],
2632
pos = 0,
2697
}else if(ctype == "debug"){
2698
// after the equal sign, whitespace are ignored and the only
2699
// valid characters are } and :
2700
while(string.charAt(i) == " "){i++}
2701
if(string.charAt(i) == "}"){
2702
// end of debug expression
2709
}else{
2710
// End of expression is the } matching the opening {
2711
// There may be nested braces
2712
var i = pos,
2713
nb_braces = 1,
2729
if(current.expression == ""){
2730
fstring_error("f-string: empty expression not allowed",
2731
pos)
2732
}
2742
// backslash is not allowed in expressions
2743
throw Error("f-string expression part cannot include a" +
2744
" backslash")
2751
throw Error("f-string: invalid conversion character:" +
2752
" expected 's', 'r', or 'a'")
2753
}else{
2767
if(string.substr(i, 3) == '"""'){
2768
var end = string.indexOf('"""', i + 3)
2769
if(end == -1){
2771
}else{
2772
var trs = string.substring(i, end + 3)
2773
trs = trs.replace("\n", "\\n\\")
2793
var ce = current.expression,
2794
last_char = ce.charAt(ce.length - 1),
2795
last_char_re = ('()'.indexOf(last_char) > -1 ? "\\" : "") + last_char
2804
}else{
2805
// add debug string
2806
tail = car
2807
while(string.charAt(i + 1).match(/\s/)){
2808
tail += string.charAt(i + 1)
2809
i++
2810
}
2812
elts.push(current.expression + tail)
2813
// remove trailing whitespace from expression
2814
while(ce.match(/\s$/)){
2815
ce = ce.substr(0, ce.length - 1)
2816
}
2817
current.expression = ce
2818
ctype = "debug"
2819
i++
2820
}
2834
for(var elt of elts){
2835
if(typeof elt == "object"){
2836
if(elt.fmt_pos !== undefined &&
2837
elt.expression.charAt(elt.fmt_pos) != ':'){
2838
console.log('mauvais format', string, elts)
2839
throw Error()
2840
}
2841
}
2842
}
2847
if(i >= 0x10000 && i <= 0x10FFFF){
2848
var code = (i - 0x10000)
2849
return String.fromCodePoint(0xD800 | (code >> 10)) +
2850
String.fromCodePoint(0xDC00 | (code & 0x3FF))
2851
}else{
2852
return String.fromCodePoint(i)
2853
}
2854
}
2857
if(c.length == 1){
2858
return c.charCodeAt(0)
2859
}
2860
var code = 0x10000
2861
code += (c.charCodeAt(0) & 0x03FF) << 10
2862
code += (c.charCodeAt(1) & 0x03FF)
2863
return code
2864
}
2865