objstr.c 84 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457
  1. /*
  2. * This file is part of the MicroPython project, http://micropython.org/
  3. *
  4. * The MIT License (MIT)
  5. *
  6. * Copyright (c) 2013, 2014 Damien P. George
  7. * Copyright (c) 2014-2018 Paul Sokolovsky
  8. *
  9. * Permission is hereby granted, free of charge, to any person obtaining a copy
  10. * of this software and associated documentation files (the "Software"), to deal
  11. * in the Software without restriction, including without limitation the rights
  12. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. * copies of the Software, and to permit persons to whom the Software is
  14. * furnished to do so, subject to the following conditions:
  15. *
  16. * The above copyright notice and this permission notice shall be included in
  17. * all copies or substantial portions of the Software.
  18. *
  19. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. * THE SOFTWARE.
  26. */
  27. #include <string.h>
  28. #include <assert.h>
  29. #include "py/unicode.h"
  30. #include "py/objstr.h"
  31. #include "py/objlist.h"
  32. #include "py/runtime.h"
  33. #include "py/stackctrl.h"
  34. #if MICROPY_PY_BUILTINS_STR_OP_MODULO
  35. static mp_obj_t str_modulo_format(mp_obj_t pattern, size_t n_args, const mp_obj_t *args, mp_obj_t dict);
  36. #endif
  37. static mp_obj_t mp_obj_new_bytes_iterator(mp_obj_t str, mp_obj_iter_buf_t *iter_buf);
  38. static NORETURN void bad_implicit_conversion(mp_obj_t self_in);
  39. static mp_obj_t mp_obj_new_str_type_from_vstr(const mp_obj_type_t *type, vstr_t *vstr);
  40. static void str_check_arg_type(const mp_obj_type_t *self_type, const mp_obj_t arg) {
  41. // String operations generally need the args type to match the object they're called on,
  42. // e.g. str.find(str), byte.startswith(byte)
  43. // with the exception that bytes may be used for bytearray and vice versa.
  44. const mp_obj_type_t *arg_type = mp_obj_get_type(arg);
  45. #if MICROPY_PY_BUILTINS_BYTEARRAY
  46. if (arg_type == &mp_type_bytearray) {
  47. arg_type = &mp_type_bytes;
  48. }
  49. if (self_type == &mp_type_bytearray) {
  50. self_type = &mp_type_bytes;
  51. }
  52. #endif
  53. if (arg_type != self_type) {
  54. bad_implicit_conversion(arg);
  55. }
  56. }
  57. static void check_is_str_or_bytes(mp_obj_t self_in) {
  58. mp_check_self(mp_obj_is_str_or_bytes(self_in));
  59. }
  60. /******************************************************************************/
  61. /* str */
  62. void mp_str_print_quoted(const mp_print_t *print, const byte *str_data, size_t str_len, bool is_bytes) {
  63. // this escapes characters, but it will be very slow to print (calling print many times)
  64. bool has_single_quote = false;
  65. bool has_double_quote = false;
  66. for (const byte *s = str_data, *top = str_data + str_len; !has_double_quote && s < top; s++) {
  67. if (*s == '\'') {
  68. has_single_quote = true;
  69. } else if (*s == '"') {
  70. has_double_quote = true;
  71. }
  72. }
  73. int quote_char = '\'';
  74. if (has_single_quote && !has_double_quote) {
  75. quote_char = '"';
  76. }
  77. mp_printf(print, "%c", quote_char);
  78. for (const byte *s = str_data, *top = str_data + str_len; s < top; s++) {
  79. if (*s == quote_char) {
  80. mp_printf(print, "\\%c", quote_char);
  81. } else if (*s == '\\') {
  82. mp_print_str(print, "\\\\");
  83. } else if (*s >= 0x20 && *s != 0x7f && (!is_bytes || *s < 0x80)) {
  84. // In strings, anything which is not ascii control character
  85. // is printed as is, this includes characters in range 0x80-0xff
  86. // (which can be non-Latin letters, etc.)
  87. mp_printf(print, "%c", *s);
  88. } else if (*s == '\n') {
  89. mp_print_str(print, "\\n");
  90. } else if (*s == '\r') {
  91. mp_print_str(print, "\\r");
  92. } else if (*s == '\t') {
  93. mp_print_str(print, "\\t");
  94. } else {
  95. mp_printf(print, "\\x%02x", *s);
  96. }
  97. }
  98. mp_printf(print, "%c", quote_char);
  99. }
  100. #if MICROPY_PY_JSON
  101. void mp_str_print_json(const mp_print_t *print, const byte *str_data, size_t str_len) {
  102. // for JSON spec, see http://www.ietf.org/rfc/rfc4627.txt
  103. // if we are given a valid utf8-encoded string, we will print it in a JSON-conforming way
  104. mp_print_str(print, "\"");
  105. for (const byte *s = str_data, *top = str_data + str_len; s < top; s++) {
  106. if (*s == '"' || *s == '\\') {
  107. mp_printf(print, "\\%c", *s);
  108. } else if (*s >= 32) {
  109. // this will handle normal and utf-8 encoded chars
  110. mp_printf(print, "%c", *s);
  111. } else if (*s == '\n') {
  112. mp_print_str(print, "\\n");
  113. } else if (*s == '\r') {
  114. mp_print_str(print, "\\r");
  115. } else if (*s == '\t') {
  116. mp_print_str(print, "\\t");
  117. } else {
  118. // this will handle control chars
  119. mp_printf(print, "\\u%04x", *s);
  120. }
  121. }
  122. mp_print_str(print, "\"");
  123. }
  124. #endif
  125. static void str_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
  126. GET_STR_DATA_LEN(self_in, str_data, str_len);
  127. #if MICROPY_PY_JSON
  128. if (kind == PRINT_JSON) {
  129. mp_str_print_json(print, str_data, str_len);
  130. return;
  131. }
  132. #endif
  133. #if !MICROPY_PY_BUILTINS_STR_UNICODE
  134. bool is_bytes = mp_obj_is_type(self_in, &mp_type_bytes);
  135. #else
  136. bool is_bytes = true;
  137. #endif
  138. if (kind == PRINT_RAW || (!MICROPY_PY_BUILTINS_STR_UNICODE && kind == PRINT_STR && !is_bytes)) {
  139. print->print_strn(print->data, (const char *)str_data, str_len);
  140. } else {
  141. if (is_bytes) {
  142. print->print_strn(print->data, "b", 1);
  143. }
  144. mp_str_print_quoted(print, str_data, str_len, is_bytes);
  145. }
  146. }
  147. mp_obj_t mp_obj_str_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
  148. #if MICROPY_CPYTHON_COMPAT
  149. if (n_kw != 0) {
  150. mp_arg_error_unimpl_kw();
  151. }
  152. #endif
  153. mp_arg_check_num(n_args, n_kw, 0, 3, false);
  154. switch (n_args) {
  155. case 0:
  156. return MP_OBJ_NEW_QSTR(MP_QSTR_);
  157. case 1: {
  158. vstr_t vstr;
  159. mp_print_t print;
  160. vstr_init_print(&vstr, 16, &print);
  161. mp_obj_print_helper(&print, args[0], PRINT_STR);
  162. return mp_obj_new_str_type_from_vstr(type, &vstr);
  163. }
  164. default: // 2 or 3 args
  165. // TODO: validate 2nd/3rd args
  166. if (mp_obj_is_type(args[0], &mp_type_bytes)) {
  167. GET_STR_DATA_LEN(args[0], str_data, str_len);
  168. GET_STR_HASH(args[0], str_hash);
  169. if (str_hash == 0) {
  170. str_hash = qstr_compute_hash(str_data, str_len);
  171. }
  172. #if MICROPY_PY_BUILTINS_STR_UNICODE_CHECK
  173. if (!utf8_check(str_data, str_len)) {
  174. mp_raise_msg(&mp_type_UnicodeError, NULL);
  175. }
  176. #endif
  177. // Check if a qstr with this data already exists
  178. qstr q = qstr_find_strn((const char *)str_data, str_len);
  179. if (q != MP_QSTRnull) {
  180. return MP_OBJ_NEW_QSTR(q);
  181. }
  182. mp_obj_str_t *o = MP_OBJ_TO_PTR(mp_obj_new_str_copy(type, NULL, str_len));
  183. o->data = str_data;
  184. o->hash = str_hash;
  185. return MP_OBJ_FROM_PTR(o);
  186. } else {
  187. mp_buffer_info_t bufinfo;
  188. mp_get_buffer_raise(args[0], &bufinfo, MP_BUFFER_READ);
  189. // This will utf-8 check the input.
  190. return mp_obj_new_str(bufinfo.buf, bufinfo.len);
  191. }
  192. }
  193. }
  194. static mp_obj_t bytes_make_new(const mp_obj_type_t *type_in, size_t n_args, size_t n_kw, const mp_obj_t *args) {
  195. (void)type_in;
  196. #if MICROPY_CPYTHON_COMPAT
  197. if (n_kw != 0) {
  198. mp_arg_error_unimpl_kw();
  199. }
  200. #else
  201. (void)n_kw;
  202. #endif
  203. if (n_args == 0) {
  204. return mp_const_empty_bytes;
  205. }
  206. if (mp_obj_is_type(args[0], &mp_type_bytes)) {
  207. return args[0];
  208. }
  209. if (mp_obj_is_str(args[0])) {
  210. if (n_args < 2 || n_args > 3) {
  211. #if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
  212. goto wrong_args;
  213. #else
  214. mp_raise_TypeError(MP_ERROR_TEXT("string argument without an encoding"));
  215. #endif
  216. }
  217. GET_STR_DATA_LEN(args[0], str_data, str_len);
  218. GET_STR_HASH(args[0], str_hash);
  219. if (str_hash == 0) {
  220. str_hash = qstr_compute_hash(str_data, str_len);
  221. }
  222. mp_obj_str_t *o = MP_OBJ_TO_PTR(mp_obj_new_str_copy(&mp_type_bytes, NULL, str_len));
  223. o->data = str_data;
  224. o->hash = str_hash;
  225. return MP_OBJ_FROM_PTR(o);
  226. }
  227. if (n_args > 1) {
  228. goto wrong_args;
  229. }
  230. if (mp_obj_is_small_int(args[0])) {
  231. mp_int_t len = MP_OBJ_SMALL_INT_VALUE(args[0]);
  232. if (len < 0) {
  233. mp_raise_ValueError(NULL);
  234. }
  235. vstr_t vstr;
  236. vstr_init_len(&vstr, len);
  237. memset(vstr.buf, 0, len);
  238. return mp_obj_new_bytes_from_vstr(&vstr);
  239. }
  240. // check if argument has the buffer protocol
  241. mp_buffer_info_t bufinfo;
  242. if (mp_get_buffer(args[0], &bufinfo, MP_BUFFER_READ)) {
  243. return mp_obj_new_bytes(bufinfo.buf, bufinfo.len);
  244. }
  245. vstr_t vstr;
  246. // Try to create array of exact len if initializer len is known
  247. mp_obj_t len_in = mp_obj_len_maybe(args[0]);
  248. if (len_in == MP_OBJ_NULL) {
  249. vstr_init(&vstr, 16);
  250. } else {
  251. mp_int_t len = MP_OBJ_SMALL_INT_VALUE(len_in);
  252. vstr_init(&vstr, len);
  253. }
  254. mp_obj_iter_buf_t iter_buf;
  255. mp_obj_t iterable = mp_getiter(args[0], &iter_buf);
  256. mp_obj_t item;
  257. while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
  258. mp_int_t val = mp_obj_get_int(item);
  259. #if MICROPY_FULL_CHECKS
  260. if (val < 0 || val > 255) {
  261. mp_raise_ValueError(MP_ERROR_TEXT("bytes value out of range"));
  262. }
  263. #endif
  264. vstr_add_byte(&vstr, val);
  265. }
  266. return mp_obj_new_bytes_from_vstr(&vstr);
  267. wrong_args:
  268. mp_raise_TypeError(MP_ERROR_TEXT("wrong number of arguments"));
  269. }
  270. // like strstr but with specified length and allows \0 bytes
  271. // TODO replace with something more efficient/standard
  272. const byte *find_subbytes(const byte *haystack, size_t hlen, const byte *needle, size_t nlen, int direction) {
  273. if (hlen >= nlen) {
  274. size_t str_index, str_index_end;
  275. if (direction > 0) {
  276. str_index = 0;
  277. str_index_end = hlen - nlen;
  278. } else {
  279. str_index = hlen - nlen;
  280. str_index_end = 0;
  281. }
  282. for (;;) {
  283. if (memcmp(&haystack[str_index], needle, nlen) == 0) {
  284. // found
  285. return haystack + str_index;
  286. }
  287. if (str_index == str_index_end) {
  288. // not found
  289. break;
  290. }
  291. str_index += direction;
  292. }
  293. }
  294. return NULL;
  295. }
  296. // Note: this function is used to check if an object is a str or bytes, which
  297. // works because both those types use it as their binary_op method. Revisit
  298. // mp_obj_is_str_or_bytes if this fact changes.
  299. mp_obj_t mp_obj_str_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_in) {
  300. // check for modulo
  301. if (op == MP_BINARY_OP_MODULO) {
  302. #if MICROPY_PY_BUILTINS_STR_OP_MODULO
  303. mp_obj_t *args = &rhs_in;
  304. size_t n_args = 1;
  305. mp_obj_t dict = MP_OBJ_NULL;
  306. if (mp_obj_is_type(rhs_in, &mp_type_tuple)) {
  307. // TODO: Support tuple subclasses?
  308. mp_obj_tuple_get(rhs_in, &n_args, &args);
  309. } else if (mp_obj_is_type(rhs_in, &mp_type_dict)) {
  310. dict = rhs_in;
  311. }
  312. return str_modulo_format(lhs_in, n_args, args, dict);
  313. #else
  314. return MP_OBJ_NULL;
  315. #endif
  316. }
  317. // from now on we need lhs type and data, so extract them
  318. const mp_obj_type_t *lhs_type = mp_obj_get_type(lhs_in);
  319. GET_STR_DATA_LEN(lhs_in, lhs_data, lhs_len);
  320. // check for multiply
  321. if (op == MP_BINARY_OP_MULTIPLY) {
  322. mp_int_t n;
  323. if (!mp_obj_get_int_maybe(rhs_in, &n)) {
  324. return MP_OBJ_NULL; // op not supported
  325. }
  326. if (n <= 0) {
  327. if (lhs_type == &mp_type_str) {
  328. return MP_OBJ_NEW_QSTR(MP_QSTR_); // empty str
  329. } else {
  330. return mp_const_empty_bytes;
  331. }
  332. }
  333. vstr_t vstr;
  334. vstr_init_len(&vstr, lhs_len * n);
  335. mp_seq_multiply(lhs_data, sizeof(*lhs_data), lhs_len, n, vstr.buf);
  336. return mp_obj_new_str_type_from_vstr(lhs_type, &vstr);
  337. }
  338. // From now on all operations allow:
  339. // - str with str
  340. // - bytes with bytes
  341. // - bytes with bytearray
  342. // - bytes with array.array
  343. // To do this efficiently we use the buffer protocol to extract the raw
  344. // data for the rhs, but only if the lhs is a bytes object.
  345. //
  346. // NOTE: CPython does not allow comparison between bytes ard array.array
  347. // (even if the array is of type 'b'), even though it allows addition of
  348. // such types. We are not compatible with this (we do allow comparison
  349. // of bytes with anything that has the buffer protocol). It would be
  350. // easy to "fix" this with a bit of extra logic below, but it costs code
  351. // size and execution time so we don't.
  352. const byte *rhs_data;
  353. size_t rhs_len;
  354. if (lhs_type == mp_obj_get_type(rhs_in)) {
  355. GET_STR_DATA_LEN(rhs_in, rhs_data_, rhs_len_);
  356. rhs_data = rhs_data_;
  357. rhs_len = rhs_len_;
  358. } else if (lhs_type == &mp_type_bytes) {
  359. mp_buffer_info_t bufinfo;
  360. if (!mp_get_buffer(rhs_in, &bufinfo, MP_BUFFER_READ)) {
  361. return MP_OBJ_NULL; // op not supported
  362. }
  363. rhs_data = bufinfo.buf;
  364. rhs_len = bufinfo.len;
  365. } else {
  366. // LHS is str and RHS has an incompatible type
  367. // (except if operation is EQUAL, but that's handled by mp_obj_equal)
  368. // CONTAINS must fail with a bad-implicit-conversion exception, because
  369. // otherwise mp_binary_op() will fallback to `list(lhs).__contains__(rhs)`.
  370. if (op == MP_BINARY_OP_CONTAINS) {
  371. bad_implicit_conversion(rhs_in);
  372. }
  373. // All other operations are not supported, and may be handled by another
  374. // type, eg for reverse operations.
  375. return MP_OBJ_NULL;
  376. }
  377. switch (op) {
  378. case MP_BINARY_OP_ADD:
  379. case MP_BINARY_OP_INPLACE_ADD: {
  380. if (lhs_len == 0 && mp_obj_get_type(rhs_in) == lhs_type) {
  381. return rhs_in;
  382. }
  383. if (rhs_len == 0) {
  384. return lhs_in;
  385. }
  386. vstr_t vstr;
  387. vstr_init_len(&vstr, lhs_len + rhs_len);
  388. memcpy(vstr.buf, lhs_data, lhs_len);
  389. memcpy(vstr.buf + lhs_len, rhs_data, rhs_len);
  390. return mp_obj_new_str_type_from_vstr(lhs_type, &vstr);
  391. }
  392. case MP_BINARY_OP_CONTAINS:
  393. return mp_obj_new_bool(find_subbytes(lhs_data, lhs_len, rhs_data, rhs_len, 1) != NULL);
  394. // case MP_BINARY_OP_NOT_EQUAL: // This is never passed here
  395. case MP_BINARY_OP_EQUAL: // This will be passed only for bytes, str is dealt with in mp_obj_equal()
  396. case MP_BINARY_OP_LESS:
  397. case MP_BINARY_OP_LESS_EQUAL:
  398. case MP_BINARY_OP_MORE:
  399. case MP_BINARY_OP_MORE_EQUAL:
  400. return mp_obj_new_bool(mp_seq_cmp_bytes(op, lhs_data, lhs_len, rhs_data, rhs_len));
  401. default:
  402. return MP_OBJ_NULL; // op not supported
  403. }
  404. }
  405. #if !MICROPY_PY_BUILTINS_STR_UNICODE
  406. // objstrunicode defines own version
  407. const byte *str_index_to_ptr(const mp_obj_type_t *type, const byte *self_data, size_t self_len,
  408. mp_obj_t index, bool is_slice) {
  409. size_t index_val = mp_get_index(type, self_len, index, is_slice);
  410. return self_data + index_val;
  411. }
  412. #endif
  413. // This is used for both bytes and 8-bit strings. This is not used for unicode strings.
  414. static mp_obj_t bytes_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) {
  415. const mp_obj_type_t *type = mp_obj_get_type(self_in);
  416. GET_STR_DATA_LEN(self_in, self_data, self_len);
  417. if (value == MP_OBJ_SENTINEL) {
  418. // load
  419. #if MICROPY_PY_BUILTINS_SLICE
  420. if (mp_obj_is_type(index, &mp_type_slice)) {
  421. mp_bound_slice_t slice;
  422. if (!mp_seq_get_fast_slice_indexes(self_len, index, &slice)) {
  423. mp_raise_NotImplementedError(MP_ERROR_TEXT("only slices with step=1 (aka None) are supported"));
  424. }
  425. return mp_obj_new_str_of_type(type, self_data + slice.start, slice.stop - slice.start);
  426. }
  427. #endif
  428. size_t index_val = mp_get_index(type, self_len, index, false);
  429. // If we have unicode enabled the type will always be bytes, so take the short cut.
  430. if (MICROPY_PY_BUILTINS_STR_UNICODE || type == &mp_type_bytes) {
  431. return MP_OBJ_NEW_SMALL_INT(self_data[index_val]);
  432. } else {
  433. return mp_obj_new_str_via_qstr((char *)&self_data[index_val], 1);
  434. }
  435. } else {
  436. return MP_OBJ_NULL; // op not supported
  437. }
  438. }
  439. static mp_obj_t str_join(mp_obj_t self_in, mp_obj_t arg) {
  440. check_is_str_or_bytes(self_in);
  441. const mp_obj_type_t *self_type = mp_obj_get_type(self_in);
  442. const mp_obj_type_t *ret_type = self_type;
  443. // get separation string
  444. GET_STR_DATA_LEN(self_in, sep_str, sep_len);
  445. // process args
  446. size_t seq_len;
  447. mp_obj_t *seq_items;
  448. if (!mp_obj_is_type(arg, &mp_type_list) && !mp_obj_is_type(arg, &mp_type_tuple)) {
  449. // arg is not a list nor a tuple, try to convert it to a list
  450. // TODO: Try to optimize?
  451. arg = mp_obj_list_make_new(&mp_type_list, 1, 0, &arg);
  452. }
  453. mp_obj_get_array(arg, &seq_len, &seq_items);
  454. // count required length
  455. size_t required_len = 0;
  456. #if MICROPY_PY_BUILTINS_BYTEARRAY
  457. if (self_type == &mp_type_bytearray) {
  458. self_type = &mp_type_bytes;
  459. }
  460. #endif
  461. for (size_t i = 0; i < seq_len; i++) {
  462. const mp_obj_type_t *seq_type = mp_obj_get_type(seq_items[i]);
  463. #if MICROPY_PY_BUILTINS_BYTEARRAY
  464. if (seq_type == &mp_type_bytearray) {
  465. seq_type = &mp_type_bytes;
  466. }
  467. #endif
  468. if (seq_type != self_type) {
  469. mp_raise_TypeError(
  470. MP_ERROR_TEXT("join expects a list of str/bytes objects consistent with self object"));
  471. }
  472. if (i > 0) {
  473. required_len += sep_len;
  474. }
  475. GET_STR_LEN(seq_items[i], l);
  476. required_len += l;
  477. }
  478. // make joined string
  479. vstr_t vstr;
  480. vstr_init_len(&vstr, required_len);
  481. byte *data = (byte *)vstr.buf;
  482. for (size_t i = 0; i < seq_len; i++) {
  483. if (i > 0) {
  484. memcpy(data, sep_str, sep_len);
  485. data += sep_len;
  486. }
  487. GET_STR_DATA_LEN(seq_items[i], s, l);
  488. memcpy(data, s, l);
  489. data += l;
  490. }
  491. // return joined string
  492. return mp_obj_new_str_type_from_vstr(ret_type, &vstr);
  493. }
  494. MP_DEFINE_CONST_FUN_OBJ_2(str_join_obj, str_join);
  495. mp_obj_t mp_obj_str_split(size_t n_args, const mp_obj_t *args) {
  496. const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
  497. mp_int_t splits = -1;
  498. mp_obj_t sep = mp_const_none;
  499. if (n_args > 1) {
  500. sep = args[1];
  501. if (n_args > 2) {
  502. splits = mp_obj_get_int(args[2]);
  503. }
  504. }
  505. mp_obj_t res = mp_obj_new_list(0, NULL);
  506. GET_STR_DATA_LEN(args[0], s, len);
  507. const byte *top = s + len;
  508. if (sep == mp_const_none) {
  509. // sep not given, so separate on whitespace
  510. // Initial whitespace is not counted as split, so we pre-do it
  511. while (s < top && unichar_isspace(*s)) {
  512. s++;
  513. }
  514. while (s < top && splits != 0) {
  515. const byte *start = s;
  516. while (s < top && !unichar_isspace(*s)) {
  517. s++;
  518. }
  519. mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, s - start));
  520. if (s >= top) {
  521. break;
  522. }
  523. while (s < top && unichar_isspace(*s)) {
  524. s++;
  525. }
  526. if (splits > 0) {
  527. splits--;
  528. }
  529. }
  530. if (s < top) {
  531. mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, s, top - s));
  532. }
  533. } else {
  534. // sep given
  535. str_check_arg_type(self_type, sep);
  536. size_t sep_len;
  537. const char *sep_str = mp_obj_str_get_data(sep, &sep_len);
  538. if (sep_len == 0) {
  539. mp_raise_ValueError(MP_ERROR_TEXT("empty separator"));
  540. }
  541. for (;;) {
  542. const byte *start = s;
  543. for (;;) {
  544. if (splits == 0 || s + sep_len > top) {
  545. s = top;
  546. break;
  547. } else if (memcmp(s, sep_str, sep_len) == 0) {
  548. break;
  549. }
  550. s++;
  551. }
  552. mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, s - start));
  553. if (s >= top) {
  554. break;
  555. }
  556. s += sep_len;
  557. if (splits > 0) {
  558. splits--;
  559. }
  560. }
  561. }
  562. return res;
  563. }
  564. MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_split_obj, 1, 3, mp_obj_str_split);
  565. #if MICROPY_PY_BUILTINS_STR_SPLITLINES
  566. static mp_obj_t str_splitlines(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
  567. enum { ARG_keepends };
  568. static const mp_arg_t allowed_args[] = {
  569. { MP_QSTR_keepends, MP_ARG_BOOL, {.u_bool = false} },
  570. };
  571. // parse args
  572. mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
  573. mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
  574. const mp_obj_type_t *self_type = mp_obj_get_type(pos_args[0]);
  575. mp_obj_t res = mp_obj_new_list(0, NULL);
  576. GET_STR_DATA_LEN(pos_args[0], s, len);
  577. const byte *top = s + len;
  578. while (s < top) {
  579. const byte *start = s;
  580. size_t match = 0;
  581. while (s < top) {
  582. if (*s == '\n') {
  583. match = 1;
  584. break;
  585. } else if (*s == '\r') {
  586. if (s[1] == '\n') {
  587. match = 2;
  588. } else {
  589. match = 1;
  590. }
  591. break;
  592. }
  593. s++;
  594. }
  595. size_t sub_len = s - start;
  596. if (args[ARG_keepends].u_bool) {
  597. sub_len += match;
  598. }
  599. mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, sub_len));
  600. s += match;
  601. }
  602. return res;
  603. }
  604. MP_DEFINE_CONST_FUN_OBJ_KW(str_splitlines_obj, 1, str_splitlines);
  605. #endif
  606. static mp_obj_t str_rsplit(size_t n_args, const mp_obj_t *args) {
  607. if (n_args < 3) {
  608. // If we don't have split limit, it doesn't matter from which side
  609. // we split.
  610. return mp_obj_str_split(n_args, args);
  611. }
  612. const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
  613. mp_obj_t sep = args[1];
  614. GET_STR_DATA_LEN(args[0], s, len);
  615. mp_int_t splits = mp_obj_get_int(args[2]);
  616. if (splits < 0) {
  617. // Negative limit means no limit, so delegate to split().
  618. return mp_obj_str_split(n_args, args);
  619. }
  620. mp_int_t org_splits = splits;
  621. // Preallocate list to the max expected # of elements, as we
  622. // will fill it from the end.
  623. mp_obj_list_t *res = MP_OBJ_TO_PTR(mp_obj_new_list(splits + 1, NULL));
  624. mp_int_t idx = splits;
  625. if (sep == mp_const_none) {
  626. mp_raise_NotImplementedError(MP_ERROR_TEXT("rsplit(None,n)"));
  627. } else {
  628. size_t sep_len;
  629. const char *sep_str = mp_obj_str_get_data(sep, &sep_len);
  630. if (sep_len == 0) {
  631. mp_raise_ValueError(MP_ERROR_TEXT("empty separator"));
  632. }
  633. const byte *beg = s;
  634. const byte *last = s + len;
  635. for (;;) {
  636. s = last - sep_len;
  637. for (;;) {
  638. if (splits == 0 || s < beg) {
  639. break;
  640. } else if (memcmp(s, sep_str, sep_len) == 0) {
  641. break;
  642. }
  643. s--;
  644. }
  645. if (s < beg || splits == 0) {
  646. res->items[idx] = mp_obj_new_str_of_type(self_type, beg, last - beg);
  647. break;
  648. }
  649. res->items[idx--] = mp_obj_new_str_of_type(self_type, s + sep_len, last - s - sep_len);
  650. last = s;
  651. splits--;
  652. }
  653. if (idx != 0) {
  654. // We split less parts than split limit, now go cleanup surplus
  655. size_t used = org_splits + 1 - idx;
  656. memmove(res->items, &res->items[idx], used * sizeof(mp_obj_t));
  657. mp_seq_clear(res->items, used, res->alloc, sizeof(*res->items));
  658. res->len = used;
  659. }
  660. }
  661. return MP_OBJ_FROM_PTR(res);
  662. }
  663. MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rsplit_obj, 1, 3, str_rsplit);
  664. static mp_obj_t str_finder(size_t n_args, const mp_obj_t *args, int direction, bool is_index) {
  665. const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
  666. check_is_str_or_bytes(args[0]);
  667. // check argument type
  668. str_check_arg_type(self_type, args[1]);
  669. GET_STR_DATA_LEN(args[0], haystack, haystack_len);
  670. GET_STR_DATA_LEN(args[1], needle, needle_len);
  671. const byte *start = haystack;
  672. const byte *end = haystack + haystack_len;
  673. if (n_args >= 3 && args[2] != mp_const_none) {
  674. start = str_index_to_ptr(self_type, haystack, haystack_len, args[2], true);
  675. }
  676. if (n_args >= 4 && args[3] != mp_const_none) {
  677. end = str_index_to_ptr(self_type, haystack, haystack_len, args[3], true);
  678. }
  679. if (end < start) {
  680. goto out_error;
  681. }
  682. const byte *p = find_subbytes(start, end - start, needle, needle_len, direction);
  683. if (p == NULL) {
  684. out_error:
  685. // not found
  686. if (is_index) {
  687. mp_raise_ValueError(MP_ERROR_TEXT("substring not found"));
  688. } else {
  689. return MP_OBJ_NEW_SMALL_INT(-1);
  690. }
  691. } else {
  692. // found
  693. #if MICROPY_PY_BUILTINS_STR_UNICODE
  694. if (self_type == &mp_type_str) {
  695. return MP_OBJ_NEW_SMALL_INT(utf8_ptr_to_index(haystack, p));
  696. }
  697. #endif
  698. return MP_OBJ_NEW_SMALL_INT(p - haystack);
  699. }
  700. }
  701. static mp_obj_t str_find(size_t n_args, const mp_obj_t *args) {
  702. return str_finder(n_args, args, 1, false);
  703. }
  704. MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_find_obj, 2, 4, str_find);
  705. static mp_obj_t str_rfind(size_t n_args, const mp_obj_t *args) {
  706. return str_finder(n_args, args, -1, false);
  707. }
  708. MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rfind_obj, 2, 4, str_rfind);
  709. static mp_obj_t str_index(size_t n_args, const mp_obj_t *args) {
  710. return str_finder(n_args, args, 1, true);
  711. }
  712. MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_index_obj, 2, 4, str_index);
  713. static mp_obj_t str_rindex(size_t n_args, const mp_obj_t *args) {
  714. return str_finder(n_args, args, -1, true);
  715. }
  716. MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rindex_obj, 2, 4, str_rindex);
  717. // TODO: (Much) more variety in args
  718. static mp_obj_t str_startswith(size_t n_args, const mp_obj_t *args) {
  719. const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
  720. GET_STR_DATA_LEN(args[0], str, str_len);
  721. size_t prefix_len;
  722. const char *prefix = mp_obj_str_get_data(args[1], &prefix_len);
  723. const byte *start = str;
  724. if (n_args > 2) {
  725. start = str_index_to_ptr(self_type, str, str_len, args[2], true);
  726. }
  727. if (prefix_len + (start - str) > str_len) {
  728. return mp_const_false;
  729. }
  730. return mp_obj_new_bool(memcmp(start, prefix, prefix_len) == 0);
  731. }
  732. MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_startswith_obj, 2, 3, str_startswith);
  733. static mp_obj_t str_endswith(size_t n_args, const mp_obj_t *args) {
  734. GET_STR_DATA_LEN(args[0], str, str_len);
  735. size_t suffix_len;
  736. const char *suffix = mp_obj_str_get_data(args[1], &suffix_len);
  737. if (n_args > 2) {
  738. mp_raise_NotImplementedError(MP_ERROR_TEXT("start/end indices"));
  739. }
  740. if (suffix_len > str_len) {
  741. return mp_const_false;
  742. }
  743. return mp_obj_new_bool(memcmp(str + (str_len - suffix_len), suffix, suffix_len) == 0);
  744. }
  745. MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_endswith_obj, 2, 3, str_endswith);
  746. enum { LSTRIP, RSTRIP, STRIP };
  747. static mp_obj_t str_uni_strip(int type, size_t n_args, const mp_obj_t *args) {
  748. check_is_str_or_bytes(args[0]);
  749. const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
  750. const byte *chars_to_del;
  751. uint chars_to_del_len;
  752. static const byte whitespace[] = " \t\n\r\v\f";
  753. if (n_args == 1) {
  754. chars_to_del = whitespace;
  755. chars_to_del_len = sizeof(whitespace) - 1;
  756. } else {
  757. str_check_arg_type(self_type, args[1]);
  758. GET_STR_DATA_LEN(args[1], s, l);
  759. chars_to_del = s;
  760. chars_to_del_len = l;
  761. }
  762. GET_STR_DATA_LEN(args[0], orig_str, orig_str_len);
  763. size_t first_good_char_pos = 0;
  764. bool first_good_char_pos_set = false;
  765. size_t last_good_char_pos = 0;
  766. size_t i = 0;
  767. int delta = 1;
  768. if (type == RSTRIP) {
  769. i = orig_str_len - 1;
  770. delta = -1;
  771. }
  772. for (size_t len = orig_str_len; len > 0; len--) {
  773. if (find_subbytes(chars_to_del, chars_to_del_len, &orig_str[i], 1, 1) == NULL) {
  774. if (!first_good_char_pos_set) {
  775. first_good_char_pos_set = true;
  776. first_good_char_pos = i;
  777. if (type == LSTRIP) {
  778. last_good_char_pos = orig_str_len - 1;
  779. break;
  780. } else if (type == RSTRIP) {
  781. first_good_char_pos = 0;
  782. last_good_char_pos = i;
  783. break;
  784. }
  785. }
  786. last_good_char_pos = i;
  787. }
  788. i += delta;
  789. }
  790. if (!first_good_char_pos_set) {
  791. // string is all whitespace, return ''
  792. if (self_type == &mp_type_str) {
  793. return MP_OBJ_NEW_QSTR(MP_QSTR_);
  794. } else {
  795. return mp_const_empty_bytes;
  796. }
  797. }
  798. assert(last_good_char_pos >= first_good_char_pos);
  799. // +1 to accommodate the last character
  800. size_t stripped_len = last_good_char_pos - first_good_char_pos + 1;
  801. if (stripped_len == orig_str_len) {
  802. // If nothing was stripped, don't bother to dup original string
  803. // TODO: watch out for this case when we'll get to bytearray.strip()
  804. assert(first_good_char_pos == 0);
  805. return args[0];
  806. }
  807. return mp_obj_new_str_of_type(self_type, orig_str + first_good_char_pos, stripped_len);
  808. }
  809. static mp_obj_t str_strip(size_t n_args, const mp_obj_t *args) {
  810. return str_uni_strip(STRIP, n_args, args);
  811. }
  812. MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_strip_obj, 1, 2, str_strip);
  813. static mp_obj_t str_lstrip(size_t n_args, const mp_obj_t *args) {
  814. return str_uni_strip(LSTRIP, n_args, args);
  815. }
  816. MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_lstrip_obj, 1, 2, str_lstrip);
  817. static mp_obj_t str_rstrip(size_t n_args, const mp_obj_t *args) {
  818. return str_uni_strip(RSTRIP, n_args, args);
  819. }
  820. MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rstrip_obj, 1, 2, str_rstrip);
  821. #if MICROPY_PY_BUILTINS_STR_CENTER
  822. static mp_obj_t str_center(mp_obj_t str_in, mp_obj_t width_in) {
  823. GET_STR_DATA_LEN(str_in, str, str_len);
  824. mp_uint_t width = mp_obj_get_int(width_in);
  825. if (str_len >= width) {
  826. return str_in;
  827. }
  828. vstr_t vstr;
  829. vstr_init_len(&vstr, width);
  830. memset(vstr.buf, ' ', width);
  831. int left = (width - str_len) / 2;
  832. memcpy(vstr.buf + left, str, str_len);
  833. return mp_obj_new_str_type_from_vstr(mp_obj_get_type(str_in), &vstr);
  834. }
  835. MP_DEFINE_CONST_FUN_OBJ_2(str_center_obj, str_center);
  836. #endif
  837. // Takes an int arg, but only parses unsigned numbers, and only changes
  838. // *num if at least one digit was parsed.
  839. static const char *str_to_int(const char *str, const char *top, int *num) {
  840. if (str < top && '0' <= *str && *str <= '9') {
  841. *num = 0;
  842. do {
  843. *num = *num * 10 + (*str - '0');
  844. str++;
  845. }
  846. while (str < top && '0' <= *str && *str <= '9');
  847. }
  848. return str;
  849. }
  850. static bool isalignment(char ch) {
  851. return ch && strchr("<>=^", ch) != NULL;
  852. }
  853. static bool istype(char ch) {
  854. return ch && strchr("bcdeEfFgGnosxX%", ch) != NULL;
  855. }
  856. static bool arg_looks_integer(mp_obj_t arg) {
  857. return mp_obj_is_bool(arg) || mp_obj_is_int(arg);
  858. }
  859. static bool arg_looks_numeric(mp_obj_t arg) {
  860. return arg_looks_integer(arg)
  861. #if MICROPY_PY_BUILTINS_FLOAT
  862. || mp_obj_is_float(arg)
  863. #endif
  864. ;
  865. }
  866. #if MICROPY_PY_BUILTINS_STR_OP_MODULO
  867. static mp_obj_t arg_as_int(mp_obj_t arg) {
  868. #if MICROPY_PY_BUILTINS_FLOAT
  869. if (mp_obj_is_float(arg)) {
  870. return mp_obj_new_int_from_float(mp_obj_float_get(arg));
  871. }
  872. #endif
  873. return arg;
  874. }
  875. #endif
  876. #if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
  877. static NORETURN void terse_str_format_value_error(void) {
  878. mp_raise_ValueError(MP_ERROR_TEXT("bad format string"));
  879. }
  880. #else
  881. // define to nothing to improve coverage
  882. #define terse_str_format_value_error()
  883. #endif
  884. static vstr_t mp_obj_str_format_helper(const char *str, const char *top, int *arg_i, size_t n_args, const mp_obj_t *args, mp_map_t *kwargs) {
  885. vstr_t vstr;
  886. mp_print_t print;
  887. vstr_init_print(&vstr, 16, &print);
  888. for (; str < top; str++) {
  889. if (*str == '}') {
  890. str++;
  891. if (str < top && *str == '}') {
  892. vstr_add_byte(&vstr, '}');
  893. continue;
  894. }
  895. #if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
  896. terse_str_format_value_error();
  897. #else
  898. mp_raise_ValueError(MP_ERROR_TEXT("single '}' encountered in format string"));
  899. #endif
  900. }
  901. if (*str != '{') {
  902. vstr_add_byte(&vstr, *str);
  903. continue;
  904. }
  905. str++;
  906. if (str < top && *str == '{') {
  907. vstr_add_byte(&vstr, '{');
  908. continue;
  909. }
  910. // replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"
  911. const char *field_name = NULL;
  912. const char *field_name_top = NULL;
  913. char conversion = '\0';
  914. const char *format_spec = NULL;
  915. if (str < top && *str != '}' && *str != '!' && *str != ':') {
  916. field_name = (const char *)str;
  917. while (str < top && *str != '}' && *str != '!' && *str != ':') {
  918. ++str;
  919. }
  920. field_name_top = (const char *)str;
  921. }
  922. // conversion ::= "r" | "s"
  923. if (str < top && *str == '!') {
  924. str++;
  925. if (str < top && (*str == 'r' || *str == 's')) {
  926. conversion = *str++;
  927. } else {
  928. #if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
  929. terse_str_format_value_error();
  930. #elif MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_NORMAL
  931. mp_raise_ValueError(MP_ERROR_TEXT("bad conversion specifier"));
  932. #else
  933. if (str >= top) {
  934. mp_raise_ValueError(
  935. MP_ERROR_TEXT("end of format while looking for conversion specifier"));
  936. } else {
  937. mp_raise_msg_varg(&mp_type_ValueError,
  938. MP_ERROR_TEXT("unknown conversion specifier %c"), *str);
  939. }
  940. #endif
  941. }
  942. }
  943. if (str < top && *str == ':') {
  944. str++;
  945. // {:} is the same as {}, which is the same as {!s}
  946. // This makes a difference when passing in a True or False
  947. // '{}'.format(True) returns 'True'
  948. // '{:d}'.format(True) returns '1'
  949. // So we treat {:} as {} and this later gets treated to be {!s}
  950. if (*str != '}') {
  951. format_spec = str;
  952. for (int nest = 1; str < top;) {
  953. if (*str == '{') {
  954. ++nest;
  955. } else if (*str == '}') {
  956. if (--nest == 0) {
  957. break;
  958. }
  959. }
  960. ++str;
  961. }
  962. }
  963. }
  964. if (str >= top) {
  965. #if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
  966. terse_str_format_value_error();
  967. #else
  968. mp_raise_ValueError(MP_ERROR_TEXT("unmatched '{' in format"));
  969. #endif
  970. }
  971. if (*str != '}') {
  972. #if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
  973. terse_str_format_value_error();
  974. #else
  975. mp_raise_ValueError(MP_ERROR_TEXT("expected ':' after format specifier"));
  976. #endif
  977. }
  978. mp_obj_t arg = mp_const_none;
  979. if (field_name) {
  980. int index = 0;
  981. if (MP_LIKELY(unichar_isdigit(*field_name))) {
  982. if (*arg_i > 0) {
  983. #if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
  984. terse_str_format_value_error();
  985. #else
  986. mp_raise_ValueError(
  987. MP_ERROR_TEXT("can't switch from automatic field numbering to manual field specification"));
  988. #endif
  989. }
  990. field_name = str_to_int(field_name, field_name_top, &index);
  991. if ((uint)index >= n_args - 1) {
  992. mp_raise_msg(&mp_type_IndexError, MP_ERROR_TEXT("tuple index out of range"));
  993. }
  994. arg = args[index + 1];
  995. *arg_i = -1;
  996. } else {
  997. const char *lookup;
  998. for (lookup = field_name; lookup < field_name_top && *lookup != '.' && *lookup != '['; lookup++) {;
  999. }
  1000. mp_obj_t field_q = mp_obj_new_str_via_qstr(field_name, lookup - field_name); // should it be via qstr?
  1001. field_name = lookup;
  1002. mp_map_elem_t *key_elem = mp_map_lookup(kwargs, field_q, MP_MAP_LOOKUP);
  1003. if (key_elem == NULL) {
  1004. mp_raise_type_arg(&mp_type_KeyError, field_q);
  1005. }
  1006. arg = key_elem->value;
  1007. }
  1008. if (field_name < field_name_top) {
  1009. mp_raise_NotImplementedError(MP_ERROR_TEXT("attributes not supported"));
  1010. }
  1011. } else {
  1012. if (*arg_i < 0) {
  1013. #if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
  1014. terse_str_format_value_error();
  1015. #else
  1016. mp_raise_ValueError(
  1017. MP_ERROR_TEXT("can't switch from manual field specification to automatic field numbering"));
  1018. #endif
  1019. }
  1020. if ((uint)*arg_i >= n_args - 1) {
  1021. mp_raise_msg(&mp_type_IndexError, MP_ERROR_TEXT("tuple index out of range"));
  1022. }
  1023. arg = args[(*arg_i) + 1];
  1024. (*arg_i)++;
  1025. }
  1026. if (!format_spec && !conversion) {
  1027. conversion = 's';
  1028. }
  1029. if (conversion) {
  1030. mp_print_kind_t print_kind;
  1031. if (conversion == 's') {
  1032. print_kind = PRINT_STR;
  1033. } else {
  1034. assert(conversion == 'r');
  1035. print_kind = PRINT_REPR;
  1036. }
  1037. vstr_t arg_vstr;
  1038. mp_print_t arg_print;
  1039. vstr_init_print(&arg_vstr, 16, &arg_print);
  1040. mp_obj_print_helper(&arg_print, arg, print_kind);
  1041. arg = mp_obj_new_str_type_from_vstr(&mp_type_str, &arg_vstr);
  1042. }
  1043. char fill = '\0';
  1044. char align = '\0';
  1045. int width = -1;
  1046. int precision = -1;
  1047. char type = '\0';
  1048. int flags = 0;
  1049. if (format_spec) {
  1050. // The format specifier (from http://docs.python.org/2/library/string.html#formatspec)
  1051. //
  1052. // [[fill]align][sign][#][0][width][,][.precision][type]
  1053. // fill ::= <any character>
  1054. // align ::= "<" | ">" | "=" | "^"
  1055. // sign ::= "+" | "-" | " "
  1056. // width ::= integer
  1057. // precision ::= integer
  1058. // type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
  1059. // recursively call the formatter to format any nested specifiers
  1060. MP_STACK_CHECK();
  1061. vstr_t format_spec_vstr = mp_obj_str_format_helper(format_spec, str, arg_i, n_args, args, kwargs);
  1062. const char *s = vstr_null_terminated_str(&format_spec_vstr);
  1063. const char *stop = s + format_spec_vstr.len;
  1064. if (isalignment(*s)) {
  1065. align = *s++;
  1066. } else if (*s && isalignment(s[1])) {
  1067. fill = *s++;
  1068. align = *s++;
  1069. }
  1070. if (*s == '+' || *s == '-' || *s == ' ') {
  1071. if (*s == '+') {
  1072. flags |= PF_FLAG_SHOW_SIGN;
  1073. } else if (*s == ' ') {
  1074. flags |= PF_FLAG_SPACE_SIGN;
  1075. }
  1076. s++;
  1077. }
  1078. if (*s == '#') {
  1079. flags |= PF_FLAG_SHOW_PREFIX;
  1080. s++;
  1081. }
  1082. if (*s == '0') {
  1083. if (!align && arg_looks_numeric(arg)) {
  1084. align = '=';
  1085. }
  1086. if (!fill) {
  1087. fill = '0';
  1088. }
  1089. }
  1090. s = str_to_int(s, stop, &width);
  1091. if (*s == ',') {
  1092. flags |= PF_FLAG_SHOW_COMMA;
  1093. s++;
  1094. }
  1095. if (*s == '.') {
  1096. s++;
  1097. s = str_to_int(s, stop, &precision);
  1098. }
  1099. if (istype(*s)) {
  1100. type = *s++;
  1101. }
  1102. if (*s) {
  1103. #if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
  1104. terse_str_format_value_error();
  1105. #else
  1106. mp_raise_ValueError(MP_ERROR_TEXT("invalid format specifier"));
  1107. #endif
  1108. }
  1109. vstr_clear(&format_spec_vstr);
  1110. }
  1111. if (!align) {
  1112. if (arg_looks_numeric(arg)) {
  1113. align = '>';
  1114. } else {
  1115. align = '<';
  1116. }
  1117. }
  1118. if (!fill) {
  1119. fill = ' ';
  1120. }
  1121. if (flags & (PF_FLAG_SHOW_SIGN | PF_FLAG_SPACE_SIGN)) {
  1122. if (type == 's') {
  1123. #if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
  1124. terse_str_format_value_error();
  1125. #else
  1126. mp_raise_ValueError(MP_ERROR_TEXT("sign not allowed in string format specifier"));
  1127. #endif
  1128. }
  1129. if (type == 'c') {
  1130. #if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
  1131. terse_str_format_value_error();
  1132. #else
  1133. mp_raise_ValueError(
  1134. MP_ERROR_TEXT("sign not allowed with integer format specifier 'c'"));
  1135. #endif
  1136. }
  1137. }
  1138. switch (align) {
  1139. case '<':
  1140. flags |= PF_FLAG_LEFT_ADJUST;
  1141. break;
  1142. case '=':
  1143. flags |= PF_FLAG_PAD_AFTER_SIGN;
  1144. break;
  1145. case '^':
  1146. flags |= PF_FLAG_CENTER_ADJUST;
  1147. break;
  1148. }
  1149. if (arg_looks_integer(arg)) {
  1150. switch (type) {
  1151. case 'b':
  1152. mp_print_mp_int(&print, arg, 2, 'a', flags, fill, width, 0);
  1153. continue;
  1154. case 'c': {
  1155. char ch = mp_obj_get_int(arg);
  1156. mp_print_strn(&print, &ch, 1, flags, fill, width);
  1157. continue;
  1158. }
  1159. case '\0': // No explicit format type implies 'd'
  1160. case 'n': // I don't think we support locales in uPy so use 'd'
  1161. case 'd':
  1162. mp_print_mp_int(&print, arg, 10, 'a', flags, fill, width, 0);
  1163. continue;
  1164. case 'o':
  1165. if (flags & PF_FLAG_SHOW_PREFIX) {
  1166. flags |= PF_FLAG_SHOW_OCTAL_LETTER;
  1167. }
  1168. mp_print_mp_int(&print, arg, 8, 'a', flags, fill, width, 0);
  1169. continue;
  1170. case 'X':
  1171. case 'x':
  1172. mp_print_mp_int(&print, arg, 16, type - ('X' - 'A'), flags, fill, width, 0);
  1173. continue;
  1174. case 'e':
  1175. case 'E':
  1176. case 'f':
  1177. case 'F':
  1178. case 'g':
  1179. case 'G':
  1180. case '%':
  1181. // The floating point formatters all work with anything that
  1182. // looks like an integer
  1183. break;
  1184. default:
  1185. #if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
  1186. terse_str_format_value_error();
  1187. #else
  1188. mp_raise_msg_varg(&mp_type_ValueError,
  1189. MP_ERROR_TEXT("unknown format code '%c' for object of type '%s'"),
  1190. type, mp_obj_get_type_str(arg));
  1191. #endif
  1192. }
  1193. }
  1194. // NOTE: no else here. We need the e, f, g etc formats for integer
  1195. // arguments (from above if) to take this if.
  1196. if (arg_looks_numeric(arg)) {
  1197. if (!type) {
  1198. // Even though the docs say that an unspecified type is the same
  1199. // as 'g', there is one subtle difference, when the exponent
  1200. // is one less than the precision.
  1201. //
  1202. // '{:10.1}'.format(0.0) ==> '0e+00'
  1203. // '{:10.1g}'.format(0.0) ==> '0'
  1204. //
  1205. // TODO: Figure out how to deal with this.
  1206. //
  1207. // A proper solution would involve adding a special flag
  1208. // or something to format_float, and create a format_double
  1209. // to deal with doubles. In order to fix this when using
  1210. // sprintf, we'd need to use the e format and tweak the
  1211. // returned result to strip trailing zeros like the g format
  1212. // does.
  1213. //
  1214. // {:10.3} and {:10.2e} with 1.23e2 both produce 1.23e+02
  1215. // but with 1.e2 you get 1e+02 and 1.00e+02
  1216. //
  1217. // Stripping the trailing 0's (like g) does would make the
  1218. // e format give us the right format.
  1219. //
  1220. // CPython sources say:
  1221. // Omitted type specifier. Behaves in the same way as repr(x)
  1222. // and str(x) if no precision is given, else like 'g', but with
  1223. // at least one digit after the decimal point. */
  1224. type = 'g';
  1225. }
  1226. if (type == 'n') {
  1227. type = 'g';
  1228. }
  1229. switch (type) {
  1230. #if MICROPY_PY_BUILTINS_FLOAT
  1231. case 'e':
  1232. case 'E':
  1233. case 'f':
  1234. case 'F':
  1235. case 'g':
  1236. case 'G':
  1237. mp_print_float(&print, mp_obj_get_float(arg), type, flags, fill, width, precision);
  1238. break;
  1239. case '%':
  1240. flags |= PF_FLAG_ADD_PERCENT;
  1241. #if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT
  1242. #define F100 100.0F
  1243. #else
  1244. #define F100 100.0
  1245. #endif
  1246. mp_print_float(&print, mp_obj_get_float(arg) * F100, 'f', flags, fill, width, precision);
  1247. #undef F100
  1248. break;
  1249. #endif
  1250. default:
  1251. #if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
  1252. terse_str_format_value_error();
  1253. #else
  1254. mp_raise_msg_varg(&mp_type_ValueError,
  1255. MP_ERROR_TEXT("unknown format code '%c' for object of type '%s'"),
  1256. type, mp_obj_get_type_str(arg));
  1257. #endif
  1258. }
  1259. } else {
  1260. // arg doesn't look like a number
  1261. if (align == '=') {
  1262. #if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
  1263. terse_str_format_value_error();
  1264. #else
  1265. mp_raise_ValueError(
  1266. MP_ERROR_TEXT("'=' alignment not allowed in string format specifier"));
  1267. #endif
  1268. }
  1269. switch (type) {
  1270. case '\0': // no explicit format type implies 's'
  1271. case 's': {
  1272. size_t slen;
  1273. const char *s = mp_obj_str_get_data(arg, &slen);
  1274. if (precision < 0) {
  1275. precision = slen;
  1276. }
  1277. if (slen > (size_t)precision) {
  1278. slen = precision;
  1279. }
  1280. mp_print_strn(&print, s, slen, flags, fill, width);
  1281. break;
  1282. }
  1283. default:
  1284. #if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
  1285. terse_str_format_value_error();
  1286. #else
  1287. mp_raise_msg_varg(&mp_type_ValueError,
  1288. MP_ERROR_TEXT("unknown format code '%c' for object of type '%s'"),
  1289. type, mp_obj_get_type_str(arg));
  1290. #endif
  1291. }
  1292. }
  1293. }
  1294. return vstr;
  1295. }
  1296. mp_obj_t mp_obj_str_format(size_t n_args, const mp_obj_t *args, mp_map_t *kwargs) {
  1297. check_is_str_or_bytes(args[0]);
  1298. GET_STR_DATA_LEN(args[0], str, len);
  1299. int arg_i = 0;
  1300. vstr_t vstr = mp_obj_str_format_helper((const char *)str, (const char *)str + len, &arg_i, n_args, args, kwargs);
  1301. return mp_obj_new_str_type_from_vstr(mp_obj_get_type(args[0]), &vstr);
  1302. }
  1303. MP_DEFINE_CONST_FUN_OBJ_KW(str_format_obj, 1, mp_obj_str_format);
  1304. #if MICROPY_PY_BUILTINS_STR_OP_MODULO
  1305. static mp_obj_t str_modulo_format(mp_obj_t pattern, size_t n_args, const mp_obj_t *args, mp_obj_t dict) {
  1306. check_is_str_or_bytes(pattern);
  1307. GET_STR_DATA_LEN(pattern, str, len);
  1308. #if MICROPY_ERROR_REPORTING > MICROPY_ERROR_REPORTING_TERSE
  1309. const byte *start_str = str;
  1310. #endif
  1311. bool is_bytes = mp_obj_is_type(pattern, &mp_type_bytes);
  1312. size_t arg_i = 0;
  1313. vstr_t vstr;
  1314. mp_print_t print;
  1315. vstr_init_print(&vstr, 16, &print);
  1316. for (const byte *top = str + len; str < top; str++) {
  1317. mp_obj_t arg = MP_OBJ_NULL;
  1318. if (*str != '%') {
  1319. vstr_add_byte(&vstr, *str);
  1320. continue;
  1321. }
  1322. if (++str >= top) {
  1323. goto incomplete_format;
  1324. }
  1325. if (*str == '%') {
  1326. vstr_add_byte(&vstr, '%');
  1327. continue;
  1328. }
  1329. // Dictionary value lookup
  1330. if (*str == '(') {
  1331. if (dict == MP_OBJ_NULL) {
  1332. mp_raise_TypeError(MP_ERROR_TEXT("format needs a dict"));
  1333. }
  1334. arg_i = 1; // we used up the single dict argument
  1335. const byte *key = ++str;
  1336. while (*str != ')') {
  1337. if (str >= top) {
  1338. #if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
  1339. terse_str_format_value_error();
  1340. #else
  1341. mp_raise_ValueError(MP_ERROR_TEXT("incomplete format key"));
  1342. #endif
  1343. }
  1344. ++str;
  1345. }
  1346. mp_obj_t k_obj = mp_obj_new_str_via_qstr((const char *)key, str - key);
  1347. arg = mp_obj_dict_get(dict, k_obj);
  1348. str++;
  1349. }
  1350. int flags = 0;
  1351. char fill = ' ';
  1352. int alt = 0;
  1353. while (str < top) {
  1354. if (*str == '-') {
  1355. flags |= PF_FLAG_LEFT_ADJUST;
  1356. } else if (*str == '+') {
  1357. flags |= PF_FLAG_SHOW_SIGN;
  1358. } else if (*str == ' ') {
  1359. flags |= PF_FLAG_SPACE_SIGN;
  1360. } else if (*str == '#') {
  1361. alt = PF_FLAG_SHOW_PREFIX;
  1362. } else if (*str == '0') {
  1363. flags |= PF_FLAG_PAD_AFTER_SIGN;
  1364. fill = '0';
  1365. } else {
  1366. break;
  1367. }
  1368. str++;
  1369. }
  1370. // parse width, if it exists
  1371. int width = 0;
  1372. if (str < top) {
  1373. if (*str == '*') {
  1374. if (arg_i >= n_args) {
  1375. goto not_enough_args;
  1376. }
  1377. width = mp_obj_get_int(args[arg_i++]);
  1378. str++;
  1379. } else {
  1380. str = (const byte *)str_to_int((const char *)str, (const char *)top, &width);
  1381. }
  1382. }
  1383. int prec = -1;
  1384. if (str < top && *str == '.') {
  1385. if (++str < top) {
  1386. if (*str == '*') {
  1387. if (arg_i >= n_args) {
  1388. goto not_enough_args;
  1389. }
  1390. prec = mp_obj_get_int(args[arg_i++]);
  1391. str++;
  1392. } else {
  1393. prec = 0;
  1394. str = (const byte *)str_to_int((const char *)str, (const char *)top, &prec);
  1395. }
  1396. }
  1397. }
  1398. if (str >= top) {
  1399. incomplete_format:
  1400. #if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
  1401. terse_str_format_value_error();
  1402. #else
  1403. mp_raise_ValueError(MP_ERROR_TEXT("incomplete format"));
  1404. #endif
  1405. }
  1406. // Tuple value lookup
  1407. if (arg == MP_OBJ_NULL) {
  1408. if (arg_i >= n_args) {
  1409. not_enough_args:
  1410. mp_raise_TypeError(MP_ERROR_TEXT("format string needs more arguments"));
  1411. }
  1412. arg = args[arg_i++];
  1413. }
  1414. switch (*str) {
  1415. case 'c':
  1416. if (mp_obj_is_str(arg)) {
  1417. size_t slen;
  1418. const char *s = mp_obj_str_get_data(arg, &slen);
  1419. if (slen != 1) {
  1420. mp_raise_TypeError(MP_ERROR_TEXT("%c needs int or char"));
  1421. }
  1422. mp_print_strn(&print, s, 1, flags, ' ', width);
  1423. } else if (arg_looks_integer(arg)) {
  1424. char ch = mp_obj_get_int(arg);
  1425. mp_print_strn(&print, &ch, 1, flags, ' ', width);
  1426. } else {
  1427. mp_raise_TypeError(MP_ERROR_TEXT("integer needed"));
  1428. }
  1429. break;
  1430. case 'd':
  1431. case 'i':
  1432. case 'u':
  1433. mp_print_mp_int(&print, arg_as_int(arg), 10, 'a', flags, fill, width, prec);
  1434. break;
  1435. #if MICROPY_PY_BUILTINS_FLOAT
  1436. case 'e':
  1437. case 'E':
  1438. case 'f':
  1439. case 'F':
  1440. case 'g':
  1441. case 'G':
  1442. mp_print_float(&print, mp_obj_get_float(arg), *str, flags, fill, width, prec);
  1443. break;
  1444. #endif
  1445. case 'o':
  1446. if (alt) {
  1447. flags |= (PF_FLAG_SHOW_PREFIX | PF_FLAG_SHOW_OCTAL_LETTER);
  1448. }
  1449. mp_print_mp_int(&print, arg, 8, 'a', flags, fill, width, prec);
  1450. break;
  1451. case 'r':
  1452. case 's': {
  1453. vstr_t arg_vstr;
  1454. mp_print_t arg_print;
  1455. vstr_init_print(&arg_vstr, 16, &arg_print);
  1456. mp_print_kind_t print_kind = (*str == 'r' ? PRINT_REPR : PRINT_STR);
  1457. if (print_kind == PRINT_STR && is_bytes && mp_obj_is_type(arg, &mp_type_bytes)) {
  1458. // If we have something like b"%s" % b"1", bytes arg should be
  1459. // printed undecorated.
  1460. print_kind = PRINT_RAW;
  1461. }
  1462. mp_obj_print_helper(&arg_print, arg, print_kind);
  1463. uint vlen = arg_vstr.len;
  1464. if (prec < 0) {
  1465. prec = vlen;
  1466. }
  1467. if (vlen > (uint)prec) {
  1468. vlen = prec;
  1469. }
  1470. mp_print_strn(&print, arg_vstr.buf, vlen, flags, ' ', width);
  1471. vstr_clear(&arg_vstr);
  1472. break;
  1473. }
  1474. case 'X':
  1475. case 'x':
  1476. mp_print_mp_int(&print, arg, 16, *str - ('X' - 'A'), flags | alt, fill, width, prec);
  1477. break;
  1478. default:
  1479. #if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
  1480. terse_str_format_value_error();
  1481. #else
  1482. mp_raise_msg_varg(&mp_type_ValueError,
  1483. MP_ERROR_TEXT("unsupported format character '%c' (0x%x) at index %d"),
  1484. *str, *str, str - start_str);
  1485. #endif
  1486. }
  1487. }
  1488. if (dict == MP_OBJ_NULL && arg_i != n_args) {
  1489. // NOTE: if `dict` exists, then `n_args` is 1 and the dict is always consumed; either
  1490. // positionally, or as a map of named args, even if none were actually referenced.
  1491. mp_raise_TypeError(MP_ERROR_TEXT("format string didn't convert all arguments"));
  1492. }
  1493. return mp_obj_new_str_type_from_vstr(is_bytes ? &mp_type_bytes : &mp_type_str, &vstr);
  1494. }
  1495. #endif
  1496. // The implementation is optimized, returning the original string if there's
  1497. // nothing to replace.
  1498. static mp_obj_t str_replace(size_t n_args, const mp_obj_t *args) {
  1499. check_is_str_or_bytes(args[0]);
  1500. mp_int_t max_rep = -1;
  1501. if (n_args == 4) {
  1502. max_rep = mp_obj_get_int(args[3]);
  1503. if (max_rep == 0) {
  1504. return args[0];
  1505. } else if (max_rep < 0) {
  1506. max_rep = -1;
  1507. }
  1508. }
  1509. // if max_rep is still -1 by this point we will need to do all possible replacements
  1510. // check argument types
  1511. const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
  1512. str_check_arg_type(self_type, args[1]);
  1513. str_check_arg_type(self_type, args[2]);
  1514. // extract string data
  1515. GET_STR_DATA_LEN(args[0], str, str_len);
  1516. GET_STR_DATA_LEN(args[1], old, old_len);
  1517. GET_STR_DATA_LEN(args[2], new, new_len);
  1518. // old won't exist in str if it's longer, so nothing to replace
  1519. if (old_len > str_len) {
  1520. return args[0];
  1521. }
  1522. // data for the replaced string
  1523. byte *data = NULL;
  1524. vstr_t vstr;
  1525. // do 2 passes over the string:
  1526. // first pass computes the required length of the replaced string
  1527. // second pass does the replacements
  1528. for (;;) {
  1529. size_t replaced_str_index = 0;
  1530. size_t num_replacements_done = 0;
  1531. const byte *old_occurrence;
  1532. const byte *offset_ptr = str;
  1533. size_t str_len_remain = str_len;
  1534. if (old_len == 0) {
  1535. // if old_str is empty, copy new_str to start of replaced string
  1536. // copy the replacement string
  1537. if (data != NULL) {
  1538. memcpy(data, new, new_len);
  1539. }
  1540. replaced_str_index += new_len;
  1541. num_replacements_done++;
  1542. }
  1543. while (num_replacements_done != (size_t)max_rep && str_len_remain > 0 && (old_occurrence = find_subbytes(offset_ptr, str_len_remain, old, old_len, 1)) != NULL) {
  1544. if (old_len == 0) {
  1545. old_occurrence += 1;
  1546. }
  1547. // copy from just after end of last occurrence of to-be-replaced string to right before start of next occurrence
  1548. if (data != NULL) {
  1549. memcpy(data + replaced_str_index, offset_ptr, old_occurrence - offset_ptr);
  1550. }
  1551. replaced_str_index += old_occurrence - offset_ptr;
  1552. // copy the replacement string
  1553. if (data != NULL) {
  1554. memcpy(data + replaced_str_index, new, new_len);
  1555. }
  1556. replaced_str_index += new_len;
  1557. offset_ptr = old_occurrence + old_len;
  1558. str_len_remain = str + str_len - offset_ptr;
  1559. num_replacements_done++;
  1560. }
  1561. // copy from just after end of last occurrence of to-be-replaced string to end of old string
  1562. if (data != NULL) {
  1563. memcpy(data + replaced_str_index, offset_ptr, str_len_remain);
  1564. }
  1565. replaced_str_index += str_len_remain;
  1566. if (data == NULL) {
  1567. // first pass
  1568. if (num_replacements_done == 0) {
  1569. // no substr found, return original string
  1570. return args[0];
  1571. } else {
  1572. // substr found, allocate new string
  1573. vstr_init_len(&vstr, replaced_str_index);
  1574. data = (byte *)vstr.buf;
  1575. assert(data != NULL);
  1576. }
  1577. } else {
  1578. // second pass, we are done
  1579. break;
  1580. }
  1581. }
  1582. return mp_obj_new_str_type_from_vstr(self_type, &vstr);
  1583. }
  1584. MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_replace_obj, 3, 4, str_replace);
  1585. #if MICROPY_PY_BUILTINS_STR_COUNT
  1586. static mp_obj_t str_count(size_t n_args, const mp_obj_t *args) {
  1587. const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
  1588. check_is_str_or_bytes(args[0]);
  1589. // check argument type
  1590. str_check_arg_type(self_type, args[1]);
  1591. GET_STR_DATA_LEN(args[0], haystack, haystack_len);
  1592. GET_STR_DATA_LEN(args[1], needle, needle_len);
  1593. const byte *start = haystack;
  1594. const byte *end = haystack + haystack_len;
  1595. if (n_args >= 3 && args[2] != mp_const_none) {
  1596. start = str_index_to_ptr(self_type, haystack, haystack_len, args[2], true);
  1597. }
  1598. if (n_args >= 4 && args[3] != mp_const_none) {
  1599. end = str_index_to_ptr(self_type, haystack, haystack_len, args[3], true);
  1600. }
  1601. // if needle_len is zero then we count each gap between characters as an occurrence
  1602. if (needle_len == 0) {
  1603. return MP_OBJ_NEW_SMALL_INT(utf8_charlen(start, end - start) + 1);
  1604. }
  1605. bool is_str = self_type == &mp_type_str;
  1606. // count the occurrences
  1607. mp_int_t num_occurrences = 0;
  1608. for (const byte *haystack_ptr = start; haystack_ptr + needle_len <= end;) {
  1609. if (memcmp(haystack_ptr, needle, needle_len) == 0) {
  1610. num_occurrences++;
  1611. haystack_ptr += needle_len;
  1612. } else {
  1613. haystack_ptr = is_str ? utf8_next_char(haystack_ptr) : haystack_ptr + 1;
  1614. }
  1615. }
  1616. return MP_OBJ_NEW_SMALL_INT(num_occurrences);
  1617. }
  1618. MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_count_obj, 2, 4, str_count);
  1619. #endif
  1620. #if MICROPY_PY_BUILTINS_STR_PARTITION
  1621. static mp_obj_t str_partitioner(mp_obj_t self_in, mp_obj_t arg, int direction) {
  1622. check_is_str_or_bytes(self_in);
  1623. const mp_obj_type_t *self_type = mp_obj_get_type(self_in);
  1624. str_check_arg_type(self_type, arg);
  1625. GET_STR_DATA_LEN(self_in, str, str_len);
  1626. GET_STR_DATA_LEN(arg, sep, sep_len);
  1627. if (sep_len == 0) {
  1628. mp_raise_ValueError(MP_ERROR_TEXT("empty separator"));
  1629. }
  1630. mp_obj_t result[3];
  1631. if (self_type == &mp_type_str) {
  1632. result[0] = MP_OBJ_NEW_QSTR(MP_QSTR_);
  1633. result[1] = MP_OBJ_NEW_QSTR(MP_QSTR_);
  1634. result[2] = MP_OBJ_NEW_QSTR(MP_QSTR_);
  1635. } else {
  1636. result[0] = mp_const_empty_bytes;
  1637. result[1] = mp_const_empty_bytes;
  1638. result[2] = mp_const_empty_bytes;
  1639. }
  1640. if (direction > 0) {
  1641. result[0] = self_in;
  1642. } else {
  1643. result[2] = self_in;
  1644. }
  1645. #if MICROPY_PY_BUILTINS_BYTEARRAY
  1646. if (mp_obj_get_type(arg) != self_type) {
  1647. arg = mp_obj_new_str_of_type(self_type, sep, sep_len);
  1648. }
  1649. #endif
  1650. const byte *position_ptr = find_subbytes(str, str_len, sep, sep_len, direction);
  1651. if (position_ptr != NULL) {
  1652. size_t position = position_ptr - str;
  1653. result[0] = mp_obj_new_str_of_type(self_type, str, position);
  1654. result[1] = arg;
  1655. result[2] = mp_obj_new_str_of_type(self_type, str + position + sep_len, str_len - position - sep_len);
  1656. }
  1657. return mp_obj_new_tuple(3, result);
  1658. }
  1659. static mp_obj_t str_partition(mp_obj_t self_in, mp_obj_t arg) {
  1660. return str_partitioner(self_in, arg, 1);
  1661. }
  1662. MP_DEFINE_CONST_FUN_OBJ_2(str_partition_obj, str_partition);
  1663. static mp_obj_t str_rpartition(mp_obj_t self_in, mp_obj_t arg) {
  1664. return str_partitioner(self_in, arg, -1);
  1665. }
  1666. MP_DEFINE_CONST_FUN_OBJ_2(str_rpartition_obj, str_rpartition);
  1667. #endif
  1668. // Supposedly not too critical operations, so optimize for code size
  1669. static mp_obj_t str_caseconv(unichar (*op)(unichar), mp_obj_t self_in) {
  1670. GET_STR_DATA_LEN(self_in, self_data, self_len);
  1671. vstr_t vstr;
  1672. vstr_init_len(&vstr, self_len);
  1673. byte *data = (byte *)vstr.buf;
  1674. for (size_t i = 0; i < self_len; i++) {
  1675. *data++ = op(*self_data++);
  1676. }
  1677. return mp_obj_new_str_type_from_vstr(mp_obj_get_type(self_in), &vstr);
  1678. }
  1679. static mp_obj_t str_lower(mp_obj_t self_in) {
  1680. return str_caseconv(unichar_tolower, self_in);
  1681. }
  1682. MP_DEFINE_CONST_FUN_OBJ_1(str_lower_obj, str_lower);
  1683. static mp_obj_t str_upper(mp_obj_t self_in) {
  1684. return str_caseconv(unichar_toupper, self_in);
  1685. }
  1686. MP_DEFINE_CONST_FUN_OBJ_1(str_upper_obj, str_upper);
  1687. static mp_obj_t str_uni_istype(bool (*f)(unichar), mp_obj_t self_in) {
  1688. GET_STR_DATA_LEN(self_in, self_data, self_len);
  1689. if (self_len == 0) {
  1690. return mp_const_false; // default to False for empty str
  1691. }
  1692. if (f != unichar_isupper && f != unichar_islower) {
  1693. for (size_t i = 0; i < self_len; i++) {
  1694. if (!f(*self_data++)) {
  1695. return mp_const_false;
  1696. }
  1697. }
  1698. } else {
  1699. bool contains_alpha = false;
  1700. for (size_t i = 0; i < self_len; i++) { // only check alphanumeric characters
  1701. if (unichar_isalpha(*self_data++)) {
  1702. contains_alpha = true;
  1703. if (!f(*(self_data - 1))) { // -1 because we already incremented above
  1704. return mp_const_false;
  1705. }
  1706. }
  1707. }
  1708. if (!contains_alpha) {
  1709. return mp_const_false;
  1710. }
  1711. }
  1712. return mp_const_true;
  1713. }
  1714. static mp_obj_t str_isspace(mp_obj_t self_in) {
  1715. return str_uni_istype(unichar_isspace, self_in);
  1716. }
  1717. MP_DEFINE_CONST_FUN_OBJ_1(str_isspace_obj, str_isspace);
  1718. static mp_obj_t str_isalpha(mp_obj_t self_in) {
  1719. return str_uni_istype(unichar_isalpha, self_in);
  1720. }
  1721. MP_DEFINE_CONST_FUN_OBJ_1(str_isalpha_obj, str_isalpha);
  1722. static mp_obj_t str_isdigit(mp_obj_t self_in) {
  1723. return str_uni_istype(unichar_isdigit, self_in);
  1724. }
  1725. MP_DEFINE_CONST_FUN_OBJ_1(str_isdigit_obj, str_isdigit);
  1726. static mp_obj_t str_isupper(mp_obj_t self_in) {
  1727. return str_uni_istype(unichar_isupper, self_in);
  1728. }
  1729. MP_DEFINE_CONST_FUN_OBJ_1(str_isupper_obj, str_isupper);
  1730. static mp_obj_t str_islower(mp_obj_t self_in) {
  1731. return str_uni_istype(unichar_islower, self_in);
  1732. }
  1733. MP_DEFINE_CONST_FUN_OBJ_1(str_islower_obj, str_islower);
  1734. #if MICROPY_CPYTHON_COMPAT
  1735. // These methods are superfluous in the presence of str() and bytes()
  1736. // constructors.
  1737. // TODO: should accept kwargs too
  1738. static mp_obj_t bytes_decode(size_t n_args, const mp_obj_t *args) {
  1739. mp_obj_t new_args[2];
  1740. if (n_args == 1) {
  1741. new_args[0] = args[0];
  1742. new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
  1743. args = new_args;
  1744. n_args++;
  1745. }
  1746. return mp_obj_str_make_new(&mp_type_str, n_args, 0, args);
  1747. }
  1748. MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(bytes_decode_obj, 1, 3, bytes_decode);
  1749. // TODO: should accept kwargs too
  1750. static mp_obj_t str_encode(size_t n_args, const mp_obj_t *args) {
  1751. mp_obj_t new_args[2];
  1752. if (n_args == 1) {
  1753. new_args[0] = args[0];
  1754. new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
  1755. args = new_args;
  1756. n_args++;
  1757. }
  1758. return bytes_make_new(NULL, n_args, 0, args);
  1759. }
  1760. MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_encode_obj, 1, 3, str_encode);
  1761. #endif
  1762. #if MICROPY_PY_BUILTINS_BYTES_HEX
  1763. mp_obj_t mp_obj_bytes_hex(size_t n_args, const mp_obj_t *args, const mp_obj_type_t *type) {
  1764. // First argument is the data to convert.
  1765. // Second argument is an optional separator to be used between values.
  1766. const char *sep = NULL;
  1767. mp_buffer_info_t bufinfo;
  1768. mp_get_buffer_raise(args[0], &bufinfo, MP_BUFFER_READ);
  1769. // Code below assumes non-zero buffer length when computing size with
  1770. // separator, so handle the zero-length case here.
  1771. if (bufinfo.len == 0) {
  1772. return mp_const_empty_bytes;
  1773. }
  1774. vstr_t vstr;
  1775. size_t out_len = bufinfo.len * 2;
  1776. if (n_args > 1) {
  1777. // 1-char separator between hex numbers
  1778. out_len += bufinfo.len - 1;
  1779. sep = mp_obj_str_get_str(args[1]);
  1780. }
  1781. vstr_init_len(&vstr, out_len);
  1782. byte *in = bufinfo.buf, *out = (byte *)vstr.buf;
  1783. for (mp_uint_t i = bufinfo.len; i--;) {
  1784. byte d = (*in >> 4);
  1785. if (d > 9) {
  1786. d += 'a' - '9' - 1;
  1787. }
  1788. *out++ = d + '0';
  1789. d = (*in++ & 0xf);
  1790. if (d > 9) {
  1791. d += 'a' - '9' - 1;
  1792. }
  1793. *out++ = d + '0';
  1794. if (sep != NULL && i != 0) {
  1795. *out++ = *sep;
  1796. }
  1797. }
  1798. return mp_obj_new_str_type_from_vstr(type, &vstr);
  1799. }
  1800. mp_obj_t mp_obj_bytes_fromhex(mp_obj_t type_in, mp_obj_t data) {
  1801. mp_buffer_info_t bufinfo;
  1802. mp_get_buffer_raise(data, &bufinfo, MP_BUFFER_READ);
  1803. if ((bufinfo.len & 1) != 0) {
  1804. mp_raise_ValueError(MP_ERROR_TEXT("odd-length string"));
  1805. }
  1806. vstr_t vstr;
  1807. vstr_init_len(&vstr, bufinfo.len / 2);
  1808. byte *in = bufinfo.buf, *out = (byte *)vstr.buf;
  1809. byte hex_byte = 0;
  1810. for (mp_uint_t i = bufinfo.len; i--;) {
  1811. byte hex_ch = *in++;
  1812. if (unichar_isxdigit(hex_ch)) {
  1813. hex_byte += unichar_xdigit_value(hex_ch);
  1814. } else {
  1815. mp_raise_ValueError(MP_ERROR_TEXT("non-hex digit found"));
  1816. }
  1817. if (i & 1) {
  1818. hex_byte <<= 4;
  1819. } else {
  1820. *out++ = hex_byte;
  1821. hex_byte = 0;
  1822. }
  1823. }
  1824. return mp_obj_new_str_type_from_vstr(MP_OBJ_TO_PTR(type_in), &vstr);
  1825. }
  1826. static mp_obj_t bytes_hex_as_str(size_t n_args, const mp_obj_t *args) {
  1827. return mp_obj_bytes_hex(n_args, args, &mp_type_str);
  1828. }
  1829. static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(bytes_hex_as_str_obj, 1, 2, bytes_hex_as_str);
  1830. static MP_DEFINE_CONST_FUN_OBJ_2(bytes_fromhex_obj, mp_obj_bytes_fromhex);
  1831. static MP_DEFINE_CONST_CLASSMETHOD_OBJ(bytes_fromhex_classmethod_obj, MP_ROM_PTR(&bytes_fromhex_obj));
  1832. #endif // MICROPY_PY_BUILTINS_BYTES_HEX
  1833. mp_int_t mp_obj_str_get_buffer(mp_obj_t self_in, mp_buffer_info_t *bufinfo, mp_uint_t flags) {
  1834. if (flags == MP_BUFFER_READ) {
  1835. GET_STR_DATA_LEN(self_in, str_data, str_len);
  1836. bufinfo->buf = (void *)str_data;
  1837. bufinfo->len = str_len;
  1838. bufinfo->typecode = 'B'; // bytes should be unsigned, so should unicode byte-access
  1839. return 0;
  1840. } else {
  1841. // can't write to a string
  1842. return 1;
  1843. }
  1844. }
  1845. void mp_obj_str_set_data(mp_obj_str_t *str, const byte *data, size_t len) {
  1846. str->data = data;
  1847. str->len = len;
  1848. str->hash = qstr_compute_hash(data, len);
  1849. }
  1850. // This locals table is used for the following types: str, bytes, bytearray, array.array.
  1851. // Each type takes a different section (start to end offset) of this table.
  1852. static const mp_rom_map_elem_t array_bytearray_str_bytes_locals_table[] = {
  1853. #if MICROPY_PY_ARRAY || MICROPY_PY_BUILTINS_BYTEARRAY
  1854. { MP_ROM_QSTR(MP_QSTR_append), MP_ROM_PTR(&mp_obj_array_append_obj) },
  1855. { MP_ROM_QSTR(MP_QSTR_extend), MP_ROM_PTR(&mp_obj_array_extend_obj) },
  1856. #endif
  1857. #if MICROPY_PY_BUILTINS_BYTES_HEX
  1858. { MP_ROM_QSTR(MP_QSTR_hex), MP_ROM_PTR(&bytes_hex_as_str_obj) },
  1859. { MP_ROM_QSTR(MP_QSTR_fromhex), MP_ROM_PTR(&bytes_fromhex_classmethod_obj) },
  1860. #endif
  1861. #if MICROPY_CPYTHON_COMPAT
  1862. { MP_ROM_QSTR(MP_QSTR_decode), MP_ROM_PTR(&bytes_decode_obj) },
  1863. #endif
  1864. { MP_ROM_QSTR(MP_QSTR_find), MP_ROM_PTR(&str_find_obj) },
  1865. { MP_ROM_QSTR(MP_QSTR_rfind), MP_ROM_PTR(&str_rfind_obj) },
  1866. { MP_ROM_QSTR(MP_QSTR_index), MP_ROM_PTR(&str_index_obj) },
  1867. { MP_ROM_QSTR(MP_QSTR_rindex), MP_ROM_PTR(&str_rindex_obj) },
  1868. { MP_ROM_QSTR(MP_QSTR_join), MP_ROM_PTR(&str_join_obj) },
  1869. { MP_ROM_QSTR(MP_QSTR_split), MP_ROM_PTR(&str_split_obj) },
  1870. #if MICROPY_PY_BUILTINS_STR_SPLITLINES
  1871. { MP_ROM_QSTR(MP_QSTR_splitlines), MP_ROM_PTR(&str_splitlines_obj) },
  1872. #endif
  1873. { MP_ROM_QSTR(MP_QSTR_rsplit), MP_ROM_PTR(&str_rsplit_obj) },
  1874. { MP_ROM_QSTR(MP_QSTR_startswith), MP_ROM_PTR(&str_startswith_obj) },
  1875. { MP_ROM_QSTR(MP_QSTR_endswith), MP_ROM_PTR(&str_endswith_obj) },
  1876. { MP_ROM_QSTR(MP_QSTR_strip), MP_ROM_PTR(&str_strip_obj) },
  1877. { MP_ROM_QSTR(MP_QSTR_lstrip), MP_ROM_PTR(&str_lstrip_obj) },
  1878. { MP_ROM_QSTR(MP_QSTR_rstrip), MP_ROM_PTR(&str_rstrip_obj) },
  1879. { MP_ROM_QSTR(MP_QSTR_format), MP_ROM_PTR(&str_format_obj) },
  1880. { MP_ROM_QSTR(MP_QSTR_replace), MP_ROM_PTR(&str_replace_obj) },
  1881. #if MICROPY_PY_BUILTINS_STR_COUNT
  1882. { MP_ROM_QSTR(MP_QSTR_count), MP_ROM_PTR(&str_count_obj) },
  1883. #endif
  1884. #if MICROPY_PY_BUILTINS_STR_PARTITION
  1885. { MP_ROM_QSTR(MP_QSTR_partition), MP_ROM_PTR(&str_partition_obj) },
  1886. { MP_ROM_QSTR(MP_QSTR_rpartition), MP_ROM_PTR(&str_rpartition_obj) },
  1887. #endif
  1888. #if MICROPY_PY_BUILTINS_STR_CENTER
  1889. { MP_ROM_QSTR(MP_QSTR_center), MP_ROM_PTR(&str_center_obj) },
  1890. #endif
  1891. { MP_ROM_QSTR(MP_QSTR_lower), MP_ROM_PTR(&str_lower_obj) },
  1892. { MP_ROM_QSTR(MP_QSTR_upper), MP_ROM_PTR(&str_upper_obj) },
  1893. { MP_ROM_QSTR(MP_QSTR_isspace), MP_ROM_PTR(&str_isspace_obj) },
  1894. { MP_ROM_QSTR(MP_QSTR_isalpha), MP_ROM_PTR(&str_isalpha_obj) },
  1895. { MP_ROM_QSTR(MP_QSTR_isdigit), MP_ROM_PTR(&str_isdigit_obj) },
  1896. { MP_ROM_QSTR(MP_QSTR_isupper), MP_ROM_PTR(&str_isupper_obj) },
  1897. { MP_ROM_QSTR(MP_QSTR_islower), MP_ROM_PTR(&str_islower_obj) },
  1898. #if MICROPY_CPYTHON_COMPAT
  1899. { MP_ROM_QSTR(MP_QSTR_encode), MP_ROM_PTR(&str_encode_obj) },
  1900. #endif
  1901. };
  1902. #if MICROPY_CPYTHON_COMPAT
  1903. #define TABLE_ENTRIES_COMPAT 1
  1904. #else
  1905. #define TABLE_ENTRIES_COMPAT 0
  1906. #endif
  1907. #if MICROPY_PY_BUILTINS_BYTES_HEX
  1908. #define TABLE_ENTRIES_HEX 2
  1909. #else
  1910. #define TABLE_ENTRIES_HEX 0
  1911. #endif
  1912. #if MICROPY_PY_ARRAY || MICROPY_PY_BUILTINS_BYTEARRAY
  1913. #define TABLE_ENTRIES_ARRAY 2
  1914. #else
  1915. #define TABLE_ENTRIES_ARRAY 0
  1916. #endif
  1917. MP_DEFINE_CONST_DICT_WITH_SIZE(mp_obj_str_locals_dict,
  1918. array_bytearray_str_bytes_locals_table + TABLE_ENTRIES_ARRAY + TABLE_ENTRIES_HEX + TABLE_ENTRIES_COMPAT,
  1919. MP_ARRAY_SIZE(array_bytearray_str_bytes_locals_table) - (TABLE_ENTRIES_ARRAY + TABLE_ENTRIES_HEX + TABLE_ENTRIES_COMPAT));
  1920. #if TABLE_ENTRIES_COMPAT == 0
  1921. #define mp_obj_bytes_locals_dict mp_obj_str_locals_dict
  1922. #else
  1923. MP_DEFINE_CONST_DICT_WITH_SIZE(mp_obj_bytes_locals_dict,
  1924. array_bytearray_str_bytes_locals_table + TABLE_ENTRIES_ARRAY,
  1925. MP_ARRAY_SIZE(array_bytearray_str_bytes_locals_table) - (TABLE_ENTRIES_ARRAY + TABLE_ENTRIES_COMPAT));
  1926. #endif
  1927. #if MICROPY_PY_BUILTINS_BYTEARRAY
  1928. MP_DEFINE_CONST_DICT_WITH_SIZE(mp_obj_bytearray_locals_dict,
  1929. array_bytearray_str_bytes_locals_table,
  1930. MP_ARRAY_SIZE(array_bytearray_str_bytes_locals_table) - TABLE_ENTRIES_COMPAT);
  1931. #endif
  1932. #if MICROPY_PY_ARRAY
  1933. MP_DEFINE_CONST_DICT_WITH_SIZE(mp_obj_array_locals_dict,
  1934. array_bytearray_str_bytes_locals_table,
  1935. TABLE_ENTRIES_ARRAY);
  1936. #endif
  1937. #if MICROPY_PY_BUILTINS_MEMORYVIEW && MICROPY_PY_BUILTINS_BYTES_HEX
  1938. MP_DEFINE_CONST_DICT_WITH_SIZE(mp_obj_memoryview_locals_dict,
  1939. array_bytearray_str_bytes_locals_table + TABLE_ENTRIES_ARRAY,
  1940. 1); // Just the "hex" entry.
  1941. #endif
  1942. #if !MICROPY_PY_BUILTINS_STR_UNICODE
  1943. static mp_obj_t mp_obj_new_str_iterator(mp_obj_t str, mp_obj_iter_buf_t *iter_buf);
  1944. MP_DEFINE_CONST_OBJ_TYPE(
  1945. mp_type_str,
  1946. MP_QSTR_str,
  1947. MP_TYPE_FLAG_NONE,
  1948. make_new, mp_obj_str_make_new,
  1949. print, str_print,
  1950. binary_op, mp_obj_str_binary_op,
  1951. subscr, bytes_subscr,
  1952. iter, mp_obj_new_str_iterator,
  1953. buffer, mp_obj_str_get_buffer,
  1954. locals_dict, &mp_obj_str_locals_dict
  1955. );
  1956. #endif // !MICROPY_PY_BUILTINS_STR_UNICODE
  1957. // Reuses most methods from str
  1958. MP_DEFINE_CONST_OBJ_TYPE(
  1959. mp_type_bytes,
  1960. MP_QSTR_bytes,
  1961. MP_TYPE_FLAG_NONE,
  1962. make_new, bytes_make_new,
  1963. print, str_print,
  1964. binary_op, mp_obj_str_binary_op,
  1965. subscr, bytes_subscr,
  1966. iter, mp_obj_new_bytes_iterator,
  1967. buffer, mp_obj_str_get_buffer,
  1968. locals_dict, &mp_obj_bytes_locals_dict
  1969. );
  1970. // The zero-length bytes object, with data that includes a null-terminating byte
  1971. const mp_obj_str_t mp_const_empty_bytes_obj = {{&mp_type_bytes}, 0, 0, (const byte *)""};
  1972. // Create a str/bytes object using the given data. New memory is allocated and
  1973. // the data is copied across. This function should only be used if the type is bytes,
  1974. // or if the type is str and the string data is known to be not interned.
  1975. mp_obj_t mp_obj_new_str_copy(const mp_obj_type_t *type, const byte *data, size_t len) {
  1976. mp_obj_str_t *o = mp_obj_malloc(mp_obj_str_t, type);
  1977. o->len = len;
  1978. if (data) {
  1979. o->hash = qstr_compute_hash(data, len);
  1980. byte *p = m_new(byte, len + 1);
  1981. o->data = p;
  1982. memcpy(p, data, len * sizeof(byte));
  1983. p[len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
  1984. }
  1985. return MP_OBJ_FROM_PTR(o);
  1986. }
  1987. // Create a str/bytes object using the given data. If the type is str and the string
  1988. // data is already interned, then a qstr object is returned. Otherwise new memory is
  1989. // allocated for the object and the data is copied across.
  1990. mp_obj_t mp_obj_new_str_of_type(const mp_obj_type_t *type, const byte *data, size_t len) {
  1991. if (type == &mp_type_str) {
  1992. return mp_obj_new_str((const char *)data, len);
  1993. #if MICROPY_PY_BUILTINS_BYTEARRAY
  1994. } else if (type == &mp_type_bytearray) {
  1995. return mp_obj_new_bytearray(len, data);
  1996. #endif
  1997. } else {
  1998. return mp_obj_new_bytes(data, len);
  1999. }
  2000. }
  2001. // Create a str using a qstr to store the data; may use existing or new qstr.
  2002. mp_obj_t mp_obj_new_str_via_qstr(const char *data, size_t len) {
  2003. return MP_OBJ_NEW_QSTR(qstr_from_strn(data, len));
  2004. }
  2005. // Create a str/bytes object from the given vstr. The vstr buffer is resized to
  2006. // the exact length required and then reused for the str/bytes object. The vstr
  2007. // is cleared and can safely be passed to vstr_free if it was heap allocated.
  2008. static mp_obj_t mp_obj_new_str_type_from_vstr(const mp_obj_type_t *type, vstr_t *vstr) {
  2009. // if not a bytes object, look if a qstr with this data already exists
  2010. if (type == &mp_type_str) {
  2011. qstr q = qstr_find_strn(vstr->buf, vstr->len);
  2012. if (q != MP_QSTRnull) {
  2013. vstr_clear(vstr);
  2014. vstr->alloc = 0;
  2015. return MP_OBJ_NEW_QSTR(q);
  2016. }
  2017. }
  2018. byte *data;
  2019. if (vstr->len + 1 == vstr->alloc) {
  2020. data = (byte *)vstr->buf;
  2021. } else {
  2022. data = (byte *)m_renew(char, vstr->buf, vstr->alloc, vstr->len + 1);
  2023. }
  2024. data[vstr->len] = '\0'; // add null byte
  2025. vstr->buf = NULL;
  2026. vstr->alloc = 0;
  2027. #if MICROPY_PY_BUILTINS_BYTEARRAY
  2028. if (type == &mp_type_bytearray) {
  2029. return mp_obj_new_bytearray_by_ref(vstr->len, data);
  2030. }
  2031. #endif
  2032. mp_obj_str_t *o = mp_obj_malloc(mp_obj_str_t, type);
  2033. o->len = vstr->len;
  2034. o->hash = qstr_compute_hash(data, vstr->len);
  2035. o->data = data;
  2036. return MP_OBJ_FROM_PTR(o);
  2037. }
  2038. mp_obj_t mp_obj_new_str_from_vstr(vstr_t *vstr) {
  2039. #if MICROPY_PY_BUILTINS_STR_UNICODE && MICROPY_PY_BUILTINS_STR_UNICODE_CHECK
  2040. if (!utf8_check((byte *)vstr->buf, vstr->len)) {
  2041. mp_raise_msg(&mp_type_UnicodeError, NULL);
  2042. }
  2043. #endif // MICROPY_PY_BUILTINS_STR_UNICODE && MICROPY_PY_BUILTINS_STR_UNICODE_CHECK
  2044. return mp_obj_new_str_type_from_vstr(&mp_type_str, vstr);
  2045. }
  2046. #if MICROPY_PY_BUILTINS_STR_UNICODE && MICROPY_PY_BUILTINS_STR_UNICODE_CHECK
  2047. mp_obj_t mp_obj_new_str_from_utf8_vstr(vstr_t *vstr) {
  2048. // bypasses utf8_check.
  2049. return mp_obj_new_str_type_from_vstr(&mp_type_str, vstr);
  2050. }
  2051. #endif // MICROPY_PY_BUILTINS_STR_UNICODE && MICROPY_PY_BUILTINS_STR_UNICODE_CHECK
  2052. mp_obj_t mp_obj_new_bytes_from_vstr(vstr_t *vstr) {
  2053. return mp_obj_new_str_type_from_vstr(&mp_type_bytes, vstr);
  2054. }
  2055. mp_obj_t mp_obj_new_str(const char *data, size_t len) {
  2056. #if MICROPY_PY_BUILTINS_STR_UNICODE && MICROPY_PY_BUILTINS_STR_UNICODE_CHECK
  2057. if (!utf8_check((byte *)data, len)) {
  2058. mp_raise_msg(&mp_type_UnicodeError, NULL);
  2059. }
  2060. #endif
  2061. qstr q = qstr_find_strn(data, len);
  2062. if (q != MP_QSTRnull) {
  2063. // qstr with this data already exists
  2064. return MP_OBJ_NEW_QSTR(q);
  2065. } else {
  2066. // no existing qstr, don't make one
  2067. return mp_obj_new_str_copy(&mp_type_str, (const byte *)data, len);
  2068. }
  2069. }
  2070. mp_obj_t mp_obj_str_intern(mp_obj_t str) {
  2071. GET_STR_DATA_LEN(str, data, len);
  2072. return mp_obj_new_str_via_qstr((const char *)data, len);
  2073. }
  2074. mp_obj_t mp_obj_str_intern_checked(mp_obj_t obj) {
  2075. size_t len;
  2076. const char *data = mp_obj_str_get_data(obj, &len);
  2077. return mp_obj_new_str_via_qstr((const char *)data, len);
  2078. }
  2079. mp_obj_t mp_obj_new_bytes(const byte *data, size_t len) {
  2080. return mp_obj_new_str_copy(&mp_type_bytes, data, len);
  2081. }
  2082. bool mp_obj_str_equal(mp_obj_t s1, mp_obj_t s2) {
  2083. if (mp_obj_is_qstr(s1) && mp_obj_is_qstr(s2)) {
  2084. return s1 == s2;
  2085. } else {
  2086. GET_STR_HASH(s1, h1);
  2087. GET_STR_HASH(s2, h2);
  2088. // If any of hashes is 0, it means it's not valid
  2089. if (h1 != 0 && h2 != 0 && h1 != h2) {
  2090. return false;
  2091. }
  2092. GET_STR_DATA_LEN(s1, d1, l1);
  2093. GET_STR_DATA_LEN(s2, d2, l2);
  2094. if (l1 != l2) {
  2095. return false;
  2096. }
  2097. return memcmp(d1, d2, l1) == 0;
  2098. }
  2099. }
  2100. static NORETURN void bad_implicit_conversion(mp_obj_t self_in) {
  2101. #if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
  2102. mp_raise_TypeError(MP_ERROR_TEXT("can't convert to str implicitly"));
  2103. #else
  2104. const qstr src_name = mp_obj_get_type(self_in)->name;
  2105. mp_raise_msg_varg(&mp_type_TypeError,
  2106. MP_ERROR_TEXT("can't convert '%q' object to %q implicitly"),
  2107. src_name, src_name == MP_QSTR_str ? MP_QSTR_bytes : MP_QSTR_str);
  2108. #endif
  2109. }
  2110. // use this if you will anyway convert the string to a qstr
  2111. // will be more efficient for the case where it's already a qstr
  2112. qstr mp_obj_str_get_qstr(mp_obj_t self_in) {
  2113. if (mp_obj_is_qstr(self_in)) {
  2114. return MP_OBJ_QSTR_VALUE(self_in);
  2115. } else if (mp_obj_is_exact_type(self_in, &mp_type_str)) {
  2116. mp_obj_str_t *self = MP_OBJ_TO_PTR(self_in);
  2117. return qstr_from_strn((char *)self->data, self->len);
  2118. } else {
  2119. bad_implicit_conversion(self_in);
  2120. }
  2121. }
  2122. // only use this function if you need the str data to be zero terminated
  2123. // at the moment all strings are zero terminated to help with C ASCIIZ compatibility
  2124. const char *mp_obj_str_get_str(mp_obj_t self_in) {
  2125. if (mp_obj_is_str_or_bytes(self_in)) {
  2126. GET_STR_DATA_LEN(self_in, s, l);
  2127. (void)l; // len unused
  2128. return (const char *)s;
  2129. } else {
  2130. bad_implicit_conversion(self_in);
  2131. }
  2132. }
  2133. const char *mp_obj_str_get_data(mp_obj_t self_in, size_t *len) {
  2134. if (mp_obj_is_str_or_bytes(self_in)) {
  2135. GET_STR_DATA_LEN(self_in, s, l);
  2136. *len = l;
  2137. return (const char *)s;
  2138. } else {
  2139. bad_implicit_conversion(self_in);
  2140. }
  2141. }
  2142. #if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_C || MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_D
  2143. const byte *mp_obj_str_get_data_no_check(mp_obj_t self_in, size_t *len) {
  2144. if (mp_obj_is_qstr(self_in)) {
  2145. return qstr_data(MP_OBJ_QSTR_VALUE(self_in), len);
  2146. } else {
  2147. MP_STATIC_ASSERT_STR_ARRAY_COMPATIBLE;
  2148. *len = ((mp_obj_str_t *)MP_OBJ_TO_PTR(self_in))->len;
  2149. return ((mp_obj_str_t *)MP_OBJ_TO_PTR(self_in))->data;
  2150. }
  2151. }
  2152. #endif
  2153. /******************************************************************************/
  2154. /* str iterator */
  2155. typedef struct _mp_obj_str8_it_t {
  2156. mp_obj_base_t base;
  2157. mp_fun_1_t iternext;
  2158. mp_obj_t str;
  2159. size_t cur;
  2160. } mp_obj_str8_it_t;
  2161. #if !MICROPY_PY_BUILTINS_STR_UNICODE
  2162. static mp_obj_t str_it_iternext(mp_obj_t self_in) {
  2163. mp_obj_str8_it_t *self = MP_OBJ_TO_PTR(self_in);
  2164. GET_STR_DATA_LEN(self->str, str, len);
  2165. if (self->cur < len) {
  2166. mp_obj_t o_out = mp_obj_new_str_via_qstr((const char *)str + self->cur, 1);
  2167. self->cur += 1;
  2168. return o_out;
  2169. } else {
  2170. return MP_OBJ_STOP_ITERATION;
  2171. }
  2172. }
  2173. static mp_obj_t mp_obj_new_str_iterator(mp_obj_t str, mp_obj_iter_buf_t *iter_buf) {
  2174. assert(sizeof(mp_obj_str8_it_t) <= sizeof(mp_obj_iter_buf_t));
  2175. mp_obj_str8_it_t *o = (mp_obj_str8_it_t *)iter_buf;
  2176. o->base.type = &mp_type_polymorph_iter;
  2177. o->iternext = str_it_iternext;
  2178. o->str = str;
  2179. o->cur = 0;
  2180. return MP_OBJ_FROM_PTR(o);
  2181. }
  2182. #endif
  2183. static mp_obj_t bytes_it_iternext(mp_obj_t self_in) {
  2184. mp_obj_str8_it_t *self = MP_OBJ_TO_PTR(self_in);
  2185. GET_STR_DATA_LEN(self->str, str, len);
  2186. if (self->cur < len) {
  2187. mp_obj_t o_out = MP_OBJ_NEW_SMALL_INT(str[self->cur]);
  2188. self->cur += 1;
  2189. return o_out;
  2190. } else {
  2191. return MP_OBJ_STOP_ITERATION;
  2192. }
  2193. }
  2194. mp_obj_t mp_obj_new_bytes_iterator(mp_obj_t str, mp_obj_iter_buf_t *iter_buf) {
  2195. assert(sizeof(mp_obj_str8_it_t) <= sizeof(mp_obj_iter_buf_t));
  2196. mp_obj_str8_it_t *o = (mp_obj_str8_it_t *)iter_buf;
  2197. o->base.type = &mp_type_polymorph_iter;
  2198. o->iternext = bytes_it_iternext;
  2199. o->str = str;
  2200. o->cur = 0;
  2201. return MP_OBJ_FROM_PTR(o);
  2202. }