unicode_format.h 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288
  1. /*
  2. unicode_format.h -- implementation of str.format().
  3. */
  4. #include "pycore_floatobject.h" // _PyFloat_FormatAdvancedWriter()
  5. /************************************************************************/
  6. /*********** Global data structures and forward declarations *********/
  7. /************************************************************************/
  8. /*
  9. A SubString consists of the characters between two string or
  10. unicode pointers.
  11. */
  12. typedef struct {
  13. PyObject *str; /* borrowed reference */
  14. Py_ssize_t start, end;
  15. } SubString;
  16. typedef enum {
  17. ANS_INIT,
  18. ANS_AUTO,
  19. ANS_MANUAL
  20. } AutoNumberState; /* Keep track if we're auto-numbering fields */
  21. /* Keeps track of our auto-numbering state, and which number field we're on */
  22. typedef struct {
  23. AutoNumberState an_state;
  24. int an_field_number;
  25. } AutoNumber;
  26. /* forward declaration for recursion */
  27. static PyObject *
  28. build_string(SubString *input, PyObject *args, PyObject *kwargs,
  29. int recursion_depth, AutoNumber *auto_number);
  30. /************************************************************************/
  31. /************************** Utility functions ************************/
  32. /************************************************************************/
  33. static void
  34. AutoNumber_Init(AutoNumber *auto_number)
  35. {
  36. auto_number->an_state = ANS_INIT;
  37. auto_number->an_field_number = 0;
  38. }
  39. /* fill in a SubString from a pointer and length */
  40. Py_LOCAL_INLINE(void)
  41. SubString_init(SubString *str, PyObject *s, Py_ssize_t start, Py_ssize_t end)
  42. {
  43. str->str = s;
  44. str->start = start;
  45. str->end = end;
  46. }
  47. /* return a new string. if str->str is NULL, return None */
  48. Py_LOCAL_INLINE(PyObject *)
  49. SubString_new_object(SubString *str)
  50. {
  51. if (str->str == NULL)
  52. Py_RETURN_NONE;
  53. return PyUnicode_Substring(str->str, str->start, str->end);
  54. }
  55. /* return a new string. if str->str is NULL, return a new empty string */
  56. Py_LOCAL_INLINE(PyObject *)
  57. SubString_new_object_or_empty(SubString *str)
  58. {
  59. if (str->str == NULL) {
  60. return PyUnicode_New(0, 0);
  61. }
  62. return SubString_new_object(str);
  63. }
  64. /* Return 1 if an error has been detected switching between automatic
  65. field numbering and manual field specification, else return 0. Set
  66. ValueError on error. */
  67. static int
  68. autonumber_state_error(AutoNumberState state, int field_name_is_empty)
  69. {
  70. if (state == ANS_MANUAL) {
  71. if (field_name_is_empty) {
  72. PyErr_SetString(PyExc_ValueError, "cannot switch from "
  73. "manual field specification to "
  74. "automatic field numbering");
  75. return 1;
  76. }
  77. }
  78. else {
  79. if (!field_name_is_empty) {
  80. PyErr_SetString(PyExc_ValueError, "cannot switch from "
  81. "automatic field numbering to "
  82. "manual field specification");
  83. return 1;
  84. }
  85. }
  86. return 0;
  87. }
  88. /************************************************************************/
  89. /*********** Format string parsing -- integers and identifiers *********/
  90. /************************************************************************/
  91. static Py_ssize_t
  92. get_integer(const SubString *str)
  93. {
  94. Py_ssize_t accumulator = 0;
  95. Py_ssize_t digitval;
  96. Py_ssize_t i;
  97. /* empty string is an error */
  98. if (str->start >= str->end)
  99. return -1;
  100. for (i = str->start; i < str->end; i++) {
  101. digitval = Py_UNICODE_TODECIMAL(PyUnicode_READ_CHAR(str->str, i));
  102. if (digitval < 0)
  103. return -1;
  104. /*
  105. Detect possible overflow before it happens:
  106. accumulator * 10 + digitval > PY_SSIZE_T_MAX if and only if
  107. accumulator > (PY_SSIZE_T_MAX - digitval) / 10.
  108. */
  109. if (accumulator > (PY_SSIZE_T_MAX - digitval) / 10) {
  110. PyErr_Format(PyExc_ValueError,
  111. "Too many decimal digits in format string");
  112. return -1;
  113. }
  114. accumulator = accumulator * 10 + digitval;
  115. }
  116. return accumulator;
  117. }
  118. /************************************************************************/
  119. /******** Functions to get field objects and specification strings ******/
  120. /************************************************************************/
  121. /* do the equivalent of obj.name */
  122. static PyObject *
  123. getattr(PyObject *obj, SubString *name)
  124. {
  125. PyObject *newobj;
  126. PyObject *str = SubString_new_object(name);
  127. if (str == NULL)
  128. return NULL;
  129. newobj = PyObject_GetAttr(obj, str);
  130. Py_DECREF(str);
  131. return newobj;
  132. }
  133. /* do the equivalent of obj[idx], where obj is a sequence */
  134. static PyObject *
  135. getitem_sequence(PyObject *obj, Py_ssize_t idx)
  136. {
  137. return PySequence_GetItem(obj, idx);
  138. }
  139. /* do the equivalent of obj[idx], where obj is not a sequence */
  140. static PyObject *
  141. getitem_idx(PyObject *obj, Py_ssize_t idx)
  142. {
  143. PyObject *newobj;
  144. PyObject *idx_obj = PyLong_FromSsize_t(idx);
  145. if (idx_obj == NULL)
  146. return NULL;
  147. newobj = PyObject_GetItem(obj, idx_obj);
  148. Py_DECREF(idx_obj);
  149. return newobj;
  150. }
  151. /* do the equivalent of obj[name] */
  152. static PyObject *
  153. getitem_str(PyObject *obj, SubString *name)
  154. {
  155. PyObject *newobj;
  156. PyObject *str = SubString_new_object(name);
  157. if (str == NULL)
  158. return NULL;
  159. newobj = PyObject_GetItem(obj, str);
  160. Py_DECREF(str);
  161. return newobj;
  162. }
  163. typedef struct {
  164. /* the entire string we're parsing. we assume that someone else
  165. is managing its lifetime, and that it will exist for the
  166. lifetime of the iterator. can be empty */
  167. SubString str;
  168. /* index to where we are inside field_name */
  169. Py_ssize_t index;
  170. } FieldNameIterator;
  171. static int
  172. FieldNameIterator_init(FieldNameIterator *self, PyObject *s,
  173. Py_ssize_t start, Py_ssize_t end)
  174. {
  175. SubString_init(&self->str, s, start, end);
  176. self->index = start;
  177. return 1;
  178. }
  179. static int
  180. _FieldNameIterator_attr(FieldNameIterator *self, SubString *name)
  181. {
  182. Py_UCS4 c;
  183. name->str = self->str.str;
  184. name->start = self->index;
  185. /* return everything until '.' or '[' */
  186. while (self->index < self->str.end) {
  187. c = PyUnicode_READ_CHAR(self->str.str, self->index++);
  188. switch (c) {
  189. case '[':
  190. case '.':
  191. /* backup so that we this character will be seen next time */
  192. self->index--;
  193. break;
  194. default:
  195. continue;
  196. }
  197. break;
  198. }
  199. /* end of string is okay */
  200. name->end = self->index;
  201. return 1;
  202. }
  203. static int
  204. _FieldNameIterator_item(FieldNameIterator *self, SubString *name)
  205. {
  206. int bracket_seen = 0;
  207. Py_UCS4 c;
  208. name->str = self->str.str;
  209. name->start = self->index;
  210. /* return everything until ']' */
  211. while (self->index < self->str.end) {
  212. c = PyUnicode_READ_CHAR(self->str.str, self->index++);
  213. switch (c) {
  214. case ']':
  215. bracket_seen = 1;
  216. break;
  217. default:
  218. continue;
  219. }
  220. break;
  221. }
  222. /* make sure we ended with a ']' */
  223. if (!bracket_seen) {
  224. PyErr_SetString(PyExc_ValueError, "Missing ']' in format string");
  225. return 0;
  226. }
  227. /* end of string is okay */
  228. /* don't include the ']' */
  229. name->end = self->index-1;
  230. return 1;
  231. }
  232. /* returns 0 on error, 1 on non-error termination, and 2 if it returns a value */
  233. static int
  234. FieldNameIterator_next(FieldNameIterator *self, int *is_attribute,
  235. Py_ssize_t *name_idx, SubString *name)
  236. {
  237. /* check at end of input */
  238. if (self->index >= self->str.end)
  239. return 1;
  240. switch (PyUnicode_READ_CHAR(self->str.str, self->index++)) {
  241. case '.':
  242. *is_attribute = 1;
  243. if (_FieldNameIterator_attr(self, name) == 0)
  244. return 0;
  245. *name_idx = -1;
  246. break;
  247. case '[':
  248. *is_attribute = 0;
  249. if (_FieldNameIterator_item(self, name) == 0)
  250. return 0;
  251. *name_idx = get_integer(name);
  252. if (*name_idx == -1 && PyErr_Occurred())
  253. return 0;
  254. break;
  255. default:
  256. /* Invalid character follows ']' */
  257. PyErr_SetString(PyExc_ValueError, "Only '.' or '[' may "
  258. "follow ']' in format field specifier");
  259. return 0;
  260. }
  261. /* empty string is an error */
  262. if (name->start == name->end) {
  263. PyErr_SetString(PyExc_ValueError, "Empty attribute in format string");
  264. return 0;
  265. }
  266. return 2;
  267. }
  268. /* input: field_name
  269. output: 'first' points to the part before the first '[' or '.'
  270. 'first_idx' is -1 if 'first' is not an integer, otherwise
  271. it's the value of first converted to an integer
  272. 'rest' is an iterator to return the rest
  273. */
  274. static int
  275. field_name_split(PyObject *str, Py_ssize_t start, Py_ssize_t end, SubString *first,
  276. Py_ssize_t *first_idx, FieldNameIterator *rest,
  277. AutoNumber *auto_number)
  278. {
  279. Py_UCS4 c;
  280. Py_ssize_t i = start;
  281. int field_name_is_empty;
  282. int using_numeric_index;
  283. /* find the part up until the first '.' or '[' */
  284. while (i < end) {
  285. switch (c = PyUnicode_READ_CHAR(str, i++)) {
  286. case '[':
  287. case '.':
  288. /* backup so that we this character is available to the
  289. "rest" iterator */
  290. i--;
  291. break;
  292. default:
  293. continue;
  294. }
  295. break;
  296. }
  297. /* set up the return values */
  298. SubString_init(first, str, start, i);
  299. FieldNameIterator_init(rest, str, i, end);
  300. /* see if "first" is an integer, in which case it's used as an index */
  301. *first_idx = get_integer(first);
  302. if (*first_idx == -1 && PyErr_Occurred())
  303. return 0;
  304. field_name_is_empty = first->start >= first->end;
  305. /* If the field name is omitted or if we have a numeric index
  306. specified, then we're doing numeric indexing into args. */
  307. using_numeric_index = field_name_is_empty || *first_idx != -1;
  308. /* We always get here exactly one time for each field we're
  309. processing. And we get here in field order (counting by left
  310. braces). So this is the perfect place to handle automatic field
  311. numbering if the field name is omitted. */
  312. /* Check if we need to do the auto-numbering. It's not needed if
  313. we're called from string.Format routines, because it's handled
  314. in that class by itself. */
  315. if (auto_number) {
  316. /* Initialize our auto numbering state if this is the first
  317. time we're either auto-numbering or manually numbering. */
  318. if (auto_number->an_state == ANS_INIT && using_numeric_index)
  319. auto_number->an_state = field_name_is_empty ?
  320. ANS_AUTO : ANS_MANUAL;
  321. /* Make sure our state is consistent with what we're doing
  322. this time through. Only check if we're using a numeric
  323. index. */
  324. if (using_numeric_index)
  325. if (autonumber_state_error(auto_number->an_state,
  326. field_name_is_empty))
  327. return 0;
  328. /* Zero length field means we want to do auto-numbering of the
  329. fields. */
  330. if (field_name_is_empty)
  331. *first_idx = (auto_number->an_field_number)++;
  332. }
  333. return 1;
  334. }
  335. /*
  336. get_field_object returns the object inside {}, before the
  337. format_spec. It handles getindex and getattr lookups and consumes
  338. the entire input string.
  339. */
  340. static PyObject *
  341. get_field_object(SubString *input, PyObject *args, PyObject *kwargs,
  342. AutoNumber *auto_number)
  343. {
  344. PyObject *obj = NULL;
  345. int ok;
  346. int is_attribute;
  347. SubString name;
  348. SubString first;
  349. Py_ssize_t index;
  350. FieldNameIterator rest;
  351. if (!field_name_split(input->str, input->start, input->end, &first,
  352. &index, &rest, auto_number)) {
  353. goto error;
  354. }
  355. if (index == -1) {
  356. /* look up in kwargs */
  357. PyObject *key = SubString_new_object(&first);
  358. if (key == NULL) {
  359. goto error;
  360. }
  361. if (kwargs == NULL) {
  362. PyErr_SetObject(PyExc_KeyError, key);
  363. Py_DECREF(key);
  364. goto error;
  365. }
  366. /* Use PyObject_GetItem instead of PyDict_GetItem because this
  367. code is no longer just used with kwargs. It might be passed
  368. a non-dict when called through format_map. */
  369. obj = PyObject_GetItem(kwargs, key);
  370. Py_DECREF(key);
  371. if (obj == NULL) {
  372. goto error;
  373. }
  374. }
  375. else {
  376. /* If args is NULL, we have a format string with a positional field
  377. with only kwargs to retrieve it from. This can only happen when
  378. used with format_map(), where positional arguments are not
  379. allowed. */
  380. if (args == NULL) {
  381. PyErr_SetString(PyExc_ValueError, "Format string contains "
  382. "positional fields");
  383. goto error;
  384. }
  385. /* look up in args */
  386. obj = PySequence_GetItem(args, index);
  387. if (obj == NULL) {
  388. PyErr_Format(PyExc_IndexError,
  389. "Replacement index %zd out of range for positional "
  390. "args tuple",
  391. index);
  392. goto error;
  393. }
  394. }
  395. /* iterate over the rest of the field_name */
  396. while ((ok = FieldNameIterator_next(&rest, &is_attribute, &index,
  397. &name)) == 2) {
  398. PyObject *tmp;
  399. if (is_attribute)
  400. /* getattr lookup "." */
  401. tmp = getattr(obj, &name);
  402. else
  403. /* getitem lookup "[]" */
  404. if (index == -1)
  405. tmp = getitem_str(obj, &name);
  406. else
  407. if (PySequence_Check(obj))
  408. tmp = getitem_sequence(obj, index);
  409. else
  410. /* not a sequence */
  411. tmp = getitem_idx(obj, index);
  412. if (tmp == NULL)
  413. goto error;
  414. /* assign to obj */
  415. Py_SETREF(obj, tmp);
  416. }
  417. /* end of iterator, this is the non-error case */
  418. if (ok == 1)
  419. return obj;
  420. error:
  421. Py_XDECREF(obj);
  422. return NULL;
  423. }
  424. /************************************************************************/
  425. /***************** Field rendering functions **************************/
  426. /************************************************************************/
  427. /*
  428. render_field() is the main function in this section. It takes the
  429. field object and field specification string generated by
  430. get_field_and_spec, and renders the field into the output string.
  431. render_field calls fieldobj.__format__(format_spec) method, and
  432. appends to the output.
  433. */
  434. static int
  435. render_field(PyObject *fieldobj, SubString *format_spec, _PyUnicodeWriter *writer)
  436. {
  437. int ok = 0;
  438. PyObject *result = NULL;
  439. PyObject *format_spec_object = NULL;
  440. int (*formatter) (_PyUnicodeWriter*, PyObject *, PyObject *, Py_ssize_t, Py_ssize_t) = NULL;
  441. int err;
  442. /* If we know the type exactly, skip the lookup of __format__ and just
  443. call the formatter directly. */
  444. if (PyUnicode_CheckExact(fieldobj))
  445. formatter = _PyUnicode_FormatAdvancedWriter;
  446. else if (PyLong_CheckExact(fieldobj))
  447. formatter = _PyLong_FormatAdvancedWriter;
  448. else if (PyFloat_CheckExact(fieldobj))
  449. formatter = _PyFloat_FormatAdvancedWriter;
  450. else if (PyComplex_CheckExact(fieldobj))
  451. formatter = _PyComplex_FormatAdvancedWriter;
  452. if (formatter) {
  453. /* we know exactly which formatter will be called when __format__ is
  454. looked up, so call it directly, instead. */
  455. err = formatter(writer, fieldobj, format_spec->str,
  456. format_spec->start, format_spec->end);
  457. return (err == 0);
  458. }
  459. else {
  460. /* We need to create an object out of the pointers we have, because
  461. __format__ takes a string/unicode object for format_spec. */
  462. if (format_spec->str)
  463. format_spec_object = PyUnicode_Substring(format_spec->str,
  464. format_spec->start,
  465. format_spec->end);
  466. else
  467. format_spec_object = PyUnicode_New(0, 0);
  468. if (format_spec_object == NULL)
  469. goto done;
  470. result = PyObject_Format(fieldobj, format_spec_object);
  471. }
  472. if (result == NULL)
  473. goto done;
  474. if (_PyUnicodeWriter_WriteStr(writer, result) == -1)
  475. goto done;
  476. ok = 1;
  477. done:
  478. Py_XDECREF(format_spec_object);
  479. Py_XDECREF(result);
  480. return ok;
  481. }
  482. static int
  483. parse_field(SubString *str, SubString *field_name, SubString *format_spec,
  484. int *format_spec_needs_expanding, Py_UCS4 *conversion)
  485. {
  486. /* Note this function works if the field name is zero length,
  487. which is good. Zero length field names are handled later, in
  488. field_name_split. */
  489. Py_UCS4 c = 0;
  490. /* initialize these, as they may be empty */
  491. *conversion = '\0';
  492. SubString_init(format_spec, NULL, 0, 0);
  493. /* Search for the field name. it's terminated by the end of
  494. the string, or a ':' or '!' */
  495. field_name->str = str->str;
  496. field_name->start = str->start;
  497. while (str->start < str->end) {
  498. switch ((c = PyUnicode_READ_CHAR(str->str, str->start++))) {
  499. case '{':
  500. PyErr_SetString(PyExc_ValueError, "unexpected '{' in field name");
  501. return 0;
  502. case '[':
  503. for (; str->start < str->end; str->start++)
  504. if (PyUnicode_READ_CHAR(str->str, str->start) == ']')
  505. break;
  506. continue;
  507. case '}':
  508. case ':':
  509. case '!':
  510. break;
  511. default:
  512. continue;
  513. }
  514. break;
  515. }
  516. field_name->end = str->start - 1;
  517. if (c == '!' || c == ':') {
  518. Py_ssize_t count;
  519. /* we have a format specifier and/or a conversion */
  520. /* don't include the last character */
  521. /* see if there's a conversion specifier */
  522. if (c == '!') {
  523. /* there must be another character present */
  524. if (str->start >= str->end) {
  525. PyErr_SetString(PyExc_ValueError,
  526. "end of string while looking for conversion "
  527. "specifier");
  528. return 0;
  529. }
  530. *conversion = PyUnicode_READ_CHAR(str->str, str->start++);
  531. if (str->start < str->end) {
  532. c = PyUnicode_READ_CHAR(str->str, str->start++);
  533. if (c == '}')
  534. return 1;
  535. if (c != ':') {
  536. PyErr_SetString(PyExc_ValueError,
  537. "expected ':' after conversion specifier");
  538. return 0;
  539. }
  540. }
  541. }
  542. format_spec->str = str->str;
  543. format_spec->start = str->start;
  544. count = 1;
  545. while (str->start < str->end) {
  546. switch ((c = PyUnicode_READ_CHAR(str->str, str->start++))) {
  547. case '{':
  548. *format_spec_needs_expanding = 1;
  549. count++;
  550. break;
  551. case '}':
  552. count--;
  553. if (count == 0) {
  554. format_spec->end = str->start - 1;
  555. return 1;
  556. }
  557. break;
  558. default:
  559. break;
  560. }
  561. }
  562. PyErr_SetString(PyExc_ValueError, "unmatched '{' in format spec");
  563. return 0;
  564. }
  565. else if (c != '}') {
  566. PyErr_SetString(PyExc_ValueError, "expected '}' before end of string");
  567. return 0;
  568. }
  569. return 1;
  570. }
  571. /************************************************************************/
  572. /******* Output string allocation and escape-to-markup processing ******/
  573. /************************************************************************/
  574. /* MarkupIterator breaks the string into pieces of either literal
  575. text, or things inside {} that need to be marked up. it is
  576. designed to make it easy to wrap a Python iterator around it, for
  577. use with the Formatter class */
  578. typedef struct {
  579. SubString str;
  580. } MarkupIterator;
  581. static int
  582. MarkupIterator_init(MarkupIterator *self, PyObject *str,
  583. Py_ssize_t start, Py_ssize_t end)
  584. {
  585. SubString_init(&self->str, str, start, end);
  586. return 1;
  587. }
  588. /* returns 0 on error, 1 on non-error termination, and 2 if it got a
  589. string (or something to be expanded) */
  590. static int
  591. MarkupIterator_next(MarkupIterator *self, SubString *literal,
  592. int *field_present, SubString *field_name,
  593. SubString *format_spec, Py_UCS4 *conversion,
  594. int *format_spec_needs_expanding)
  595. {
  596. int at_end;
  597. Py_UCS4 c = 0;
  598. Py_ssize_t start;
  599. Py_ssize_t len;
  600. int markup_follows = 0;
  601. /* initialize all of the output variables */
  602. SubString_init(literal, NULL, 0, 0);
  603. SubString_init(field_name, NULL, 0, 0);
  604. SubString_init(format_spec, NULL, 0, 0);
  605. *conversion = '\0';
  606. *format_spec_needs_expanding = 0;
  607. *field_present = 0;
  608. /* No more input, end of iterator. This is the normal exit
  609. path. */
  610. if (self->str.start >= self->str.end)
  611. return 1;
  612. start = self->str.start;
  613. /* First read any literal text. Read until the end of string, an
  614. escaped '{' or '}', or an unescaped '{'. In order to never
  615. allocate memory and so I can just pass pointers around, if
  616. there's an escaped '{' or '}' then we'll return the literal
  617. including the brace, but no format object. The next time
  618. through, we'll return the rest of the literal, skipping past
  619. the second consecutive brace. */
  620. while (self->str.start < self->str.end) {
  621. switch (c = PyUnicode_READ_CHAR(self->str.str, self->str.start++)) {
  622. case '{':
  623. case '}':
  624. markup_follows = 1;
  625. break;
  626. default:
  627. continue;
  628. }
  629. break;
  630. }
  631. at_end = self->str.start >= self->str.end;
  632. len = self->str.start - start;
  633. if ((c == '}') && (at_end ||
  634. (c != PyUnicode_READ_CHAR(self->str.str,
  635. self->str.start)))) {
  636. PyErr_SetString(PyExc_ValueError, "Single '}' encountered "
  637. "in format string");
  638. return 0;
  639. }
  640. if (at_end && c == '{') {
  641. PyErr_SetString(PyExc_ValueError, "Single '{' encountered "
  642. "in format string");
  643. return 0;
  644. }
  645. if (!at_end) {
  646. if (c == PyUnicode_READ_CHAR(self->str.str, self->str.start)) {
  647. /* escaped } or {, skip it in the input. there is no
  648. markup object following us, just this literal text */
  649. self->str.start++;
  650. markup_follows = 0;
  651. }
  652. else
  653. len--;
  654. }
  655. /* record the literal text */
  656. literal->str = self->str.str;
  657. literal->start = start;
  658. literal->end = start + len;
  659. if (!markup_follows)
  660. return 2;
  661. /* this is markup; parse the field */
  662. *field_present = 1;
  663. if (!parse_field(&self->str, field_name, format_spec,
  664. format_spec_needs_expanding, conversion))
  665. return 0;
  666. return 2;
  667. }
  668. /* do the !r or !s conversion on obj */
  669. static PyObject *
  670. do_conversion(PyObject *obj, Py_UCS4 conversion)
  671. {
  672. /* XXX in pre-3.0, do we need to convert this to unicode, since it
  673. might have returned a string? */
  674. switch (conversion) {
  675. case 'r':
  676. return PyObject_Repr(obj);
  677. case 's':
  678. return PyObject_Str(obj);
  679. case 'a':
  680. return PyObject_ASCII(obj);
  681. default:
  682. if (conversion > 32 && conversion < 127) {
  683. /* It's the ASCII subrange; casting to char is safe
  684. (assuming the execution character set is an ASCII
  685. superset). */
  686. PyErr_Format(PyExc_ValueError,
  687. "Unknown conversion specifier %c",
  688. (char)conversion);
  689. } else
  690. PyErr_Format(PyExc_ValueError,
  691. "Unknown conversion specifier \\x%x",
  692. (unsigned int)conversion);
  693. return NULL;
  694. }
  695. }
  696. /* given:
  697. {field_name!conversion:format_spec}
  698. compute the result and write it to output.
  699. format_spec_needs_expanding is an optimization. if it's false,
  700. just output the string directly, otherwise recursively expand the
  701. format_spec string.
  702. field_name is allowed to be zero length, in which case we
  703. are doing auto field numbering.
  704. */
  705. static int
  706. output_markup(SubString *field_name, SubString *format_spec,
  707. int format_spec_needs_expanding, Py_UCS4 conversion,
  708. _PyUnicodeWriter *writer, PyObject *args, PyObject *kwargs,
  709. int recursion_depth, AutoNumber *auto_number)
  710. {
  711. PyObject *tmp = NULL;
  712. PyObject *fieldobj = NULL;
  713. SubString expanded_format_spec;
  714. SubString *actual_format_spec;
  715. int result = 0;
  716. /* convert field_name to an object */
  717. fieldobj = get_field_object(field_name, args, kwargs, auto_number);
  718. if (fieldobj == NULL)
  719. goto done;
  720. if (conversion != '\0') {
  721. tmp = do_conversion(fieldobj, conversion);
  722. if (tmp == NULL || PyUnicode_READY(tmp) == -1)
  723. goto done;
  724. /* do the assignment, transferring ownership: fieldobj = tmp */
  725. Py_SETREF(fieldobj, tmp);
  726. tmp = NULL;
  727. }
  728. /* if needed, recursively compute the format_spec */
  729. if (format_spec_needs_expanding) {
  730. tmp = build_string(format_spec, args, kwargs, recursion_depth-1,
  731. auto_number);
  732. if (tmp == NULL || PyUnicode_READY(tmp) == -1)
  733. goto done;
  734. /* note that in the case we're expanding the format string,
  735. tmp must be kept around until after the call to
  736. render_field. */
  737. SubString_init(&expanded_format_spec, tmp, 0, PyUnicode_GET_LENGTH(tmp));
  738. actual_format_spec = &expanded_format_spec;
  739. }
  740. else
  741. actual_format_spec = format_spec;
  742. if (render_field(fieldobj, actual_format_spec, writer) == 0)
  743. goto done;
  744. result = 1;
  745. done:
  746. Py_XDECREF(fieldobj);
  747. Py_XDECREF(tmp);
  748. return result;
  749. }
  750. /*
  751. do_markup is the top-level loop for the format() method. It
  752. searches through the format string for escapes to markup codes, and
  753. calls other functions to move non-markup text to the output,
  754. and to perform the markup to the output.
  755. */
  756. static int
  757. do_markup(SubString *input, PyObject *args, PyObject *kwargs,
  758. _PyUnicodeWriter *writer, int recursion_depth, AutoNumber *auto_number)
  759. {
  760. MarkupIterator iter;
  761. int format_spec_needs_expanding;
  762. int result;
  763. int field_present;
  764. SubString literal;
  765. SubString field_name;
  766. SubString format_spec;
  767. Py_UCS4 conversion;
  768. MarkupIterator_init(&iter, input->str, input->start, input->end);
  769. while ((result = MarkupIterator_next(&iter, &literal, &field_present,
  770. &field_name, &format_spec,
  771. &conversion,
  772. &format_spec_needs_expanding)) == 2) {
  773. if (literal.end != literal.start) {
  774. if (!field_present && iter.str.start == iter.str.end)
  775. writer->overallocate = 0;
  776. if (_PyUnicodeWriter_WriteSubstring(writer, literal.str,
  777. literal.start, literal.end) < 0)
  778. return 0;
  779. }
  780. if (field_present) {
  781. if (iter.str.start == iter.str.end)
  782. writer->overallocate = 0;
  783. if (!output_markup(&field_name, &format_spec,
  784. format_spec_needs_expanding, conversion, writer,
  785. args, kwargs, recursion_depth, auto_number))
  786. return 0;
  787. }
  788. }
  789. return result;
  790. }
  791. /*
  792. build_string allocates the output string and then
  793. calls do_markup to do the heavy lifting.
  794. */
  795. static PyObject *
  796. build_string(SubString *input, PyObject *args, PyObject *kwargs,
  797. int recursion_depth, AutoNumber *auto_number)
  798. {
  799. _PyUnicodeWriter writer;
  800. /* check the recursion level */
  801. if (recursion_depth <= 0) {
  802. PyErr_SetString(PyExc_ValueError,
  803. "Max string recursion exceeded");
  804. return NULL;
  805. }
  806. _PyUnicodeWriter_Init(&writer);
  807. writer.overallocate = 1;
  808. writer.min_length = PyUnicode_GET_LENGTH(input->str) + 100;
  809. if (!do_markup(input, args, kwargs, &writer, recursion_depth,
  810. auto_number)) {
  811. _PyUnicodeWriter_Dealloc(&writer);
  812. return NULL;
  813. }
  814. return _PyUnicodeWriter_Finish(&writer);
  815. }
  816. /************************************************************************/
  817. /*********** main routine ***********************************************/
  818. /************************************************************************/
  819. /* this is the main entry point */
  820. static PyObject *
  821. do_string_format(PyObject *self, PyObject *args, PyObject *kwargs)
  822. {
  823. SubString input;
  824. /* PEP 3101 says only 2 levels, so that
  825. "{0:{1}}".format('abc', 's') # works
  826. "{0:{1:{2}}}".format('abc', 's', '') # fails
  827. */
  828. int recursion_depth = 2;
  829. AutoNumber auto_number;
  830. if (PyUnicode_READY(self) == -1)
  831. return NULL;
  832. AutoNumber_Init(&auto_number);
  833. SubString_init(&input, self, 0, PyUnicode_GET_LENGTH(self));
  834. return build_string(&input, args, kwargs, recursion_depth, &auto_number);
  835. }
  836. static PyObject *
  837. do_string_format_map(PyObject *self, PyObject *obj)
  838. {
  839. return do_string_format(self, NULL, obj);
  840. }
  841. /************************************************************************/
  842. /*********** formatteriterator ******************************************/
  843. /************************************************************************/
  844. /* This is used to implement string.Formatter.vparse(). It exists so
  845. Formatter can share code with the built in unicode.format() method.
  846. It's really just a wrapper around MarkupIterator that is callable
  847. from Python. */
  848. typedef struct {
  849. PyObject_HEAD
  850. PyObject *str;
  851. MarkupIterator it_markup;
  852. } formatteriterobject;
  853. static void
  854. formatteriter_dealloc(formatteriterobject *it)
  855. {
  856. Py_XDECREF(it->str);
  857. PyObject_Free(it);
  858. }
  859. /* returns a tuple:
  860. (literal, field_name, format_spec, conversion)
  861. literal is any literal text to output. might be zero length
  862. field_name is the string before the ':'. might be None
  863. format_spec is the string after the ':'. mibht be None
  864. conversion is either None, or the string after the '!'
  865. */
  866. static PyObject *
  867. formatteriter_next(formatteriterobject *it)
  868. {
  869. SubString literal;
  870. SubString field_name;
  871. SubString format_spec;
  872. Py_UCS4 conversion;
  873. int format_spec_needs_expanding;
  874. int field_present;
  875. int result = MarkupIterator_next(&it->it_markup, &literal, &field_present,
  876. &field_name, &format_spec, &conversion,
  877. &format_spec_needs_expanding);
  878. /* all of the SubString objects point into it->str, so no
  879. memory management needs to be done on them */
  880. assert(0 <= result && result <= 2);
  881. if (result == 0 || result == 1)
  882. /* if 0, error has already been set, if 1, iterator is empty */
  883. return NULL;
  884. else {
  885. PyObject *literal_str = NULL;
  886. PyObject *field_name_str = NULL;
  887. PyObject *format_spec_str = NULL;
  888. PyObject *conversion_str = NULL;
  889. PyObject *tuple = NULL;
  890. literal_str = SubString_new_object(&literal);
  891. if (literal_str == NULL)
  892. goto done;
  893. field_name_str = SubString_new_object(&field_name);
  894. if (field_name_str == NULL)
  895. goto done;
  896. /* if field_name is non-zero length, return a string for
  897. format_spec (even if zero length), else return None */
  898. format_spec_str = (field_present ?
  899. SubString_new_object_or_empty :
  900. SubString_new_object)(&format_spec);
  901. if (format_spec_str == NULL)
  902. goto done;
  903. /* if the conversion is not specified, return a None,
  904. otherwise create a one length string with the conversion
  905. character */
  906. if (conversion == '\0') {
  907. conversion_str = Py_NewRef(Py_None);
  908. }
  909. else
  910. conversion_str = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND,
  911. &conversion, 1);
  912. if (conversion_str == NULL)
  913. goto done;
  914. tuple = PyTuple_Pack(4, literal_str, field_name_str, format_spec_str,
  915. conversion_str);
  916. done:
  917. Py_XDECREF(literal_str);
  918. Py_XDECREF(field_name_str);
  919. Py_XDECREF(format_spec_str);
  920. Py_XDECREF(conversion_str);
  921. return tuple;
  922. }
  923. }
  924. static PyMethodDef formatteriter_methods[] = {
  925. {NULL, NULL} /* sentinel */
  926. };
  927. static PyTypeObject PyFormatterIter_Type = {
  928. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  929. "formatteriterator", /* tp_name */
  930. sizeof(formatteriterobject), /* tp_basicsize */
  931. 0, /* tp_itemsize */
  932. /* methods */
  933. (destructor)formatteriter_dealloc, /* tp_dealloc */
  934. 0, /* tp_vectorcall_offset */
  935. 0, /* tp_getattr */
  936. 0, /* tp_setattr */
  937. 0, /* tp_as_async */
  938. 0, /* tp_repr */
  939. 0, /* tp_as_number */
  940. 0, /* tp_as_sequence */
  941. 0, /* tp_as_mapping */
  942. 0, /* tp_hash */
  943. 0, /* tp_call */
  944. 0, /* tp_str */
  945. PyObject_GenericGetAttr, /* tp_getattro */
  946. 0, /* tp_setattro */
  947. 0, /* tp_as_buffer */
  948. Py_TPFLAGS_DEFAULT, /* tp_flags */
  949. 0, /* tp_doc */
  950. 0, /* tp_traverse */
  951. 0, /* tp_clear */
  952. 0, /* tp_richcompare */
  953. 0, /* tp_weaklistoffset */
  954. PyObject_SelfIter, /* tp_iter */
  955. (iternextfunc)formatteriter_next, /* tp_iternext */
  956. formatteriter_methods, /* tp_methods */
  957. 0,
  958. };
  959. /* unicode_formatter_parser is used to implement
  960. string.Formatter.vformat. it parses a string and returns tuples
  961. describing the parsed elements. It's a wrapper around
  962. stringlib/string_format.h's MarkupIterator */
  963. static PyObject *
  964. formatter_parser(PyObject *ignored, PyObject *self)
  965. {
  966. formatteriterobject *it;
  967. if (!PyUnicode_Check(self)) {
  968. PyErr_Format(PyExc_TypeError, "expected str, got %s", Py_TYPE(self)->tp_name);
  969. return NULL;
  970. }
  971. if (PyUnicode_READY(self) == -1)
  972. return NULL;
  973. it = PyObject_New(formatteriterobject, &PyFormatterIter_Type);
  974. if (it == NULL)
  975. return NULL;
  976. /* take ownership, give the object to the iterator */
  977. it->str = Py_NewRef(self);
  978. /* initialize the contained MarkupIterator */
  979. MarkupIterator_init(&it->it_markup, (PyObject*)self, 0, PyUnicode_GET_LENGTH(self));
  980. return (PyObject *)it;
  981. }
  982. /************************************************************************/
  983. /*********** fieldnameiterator ******************************************/
  984. /************************************************************************/
  985. /* This is used to implement string.Formatter.vparse(). It parses the
  986. field name into attribute and item values. It's a Python-callable
  987. wrapper around FieldNameIterator */
  988. typedef struct {
  989. PyObject_HEAD
  990. PyObject *str;
  991. FieldNameIterator it_field;
  992. } fieldnameiterobject;
  993. static void
  994. fieldnameiter_dealloc(fieldnameiterobject *it)
  995. {
  996. Py_XDECREF(it->str);
  997. PyObject_Free(it);
  998. }
  999. /* returns a tuple:
  1000. (is_attr, value)
  1001. is_attr is true if we used attribute syntax (e.g., '.foo')
  1002. false if we used index syntax (e.g., '[foo]')
  1003. value is an integer or string
  1004. */
  1005. static PyObject *
  1006. fieldnameiter_next(fieldnameiterobject *it)
  1007. {
  1008. int result;
  1009. int is_attr;
  1010. Py_ssize_t idx;
  1011. SubString name;
  1012. result = FieldNameIterator_next(&it->it_field, &is_attr,
  1013. &idx, &name);
  1014. if (result == 0 || result == 1)
  1015. /* if 0, error has already been set, if 1, iterator is empty */
  1016. return NULL;
  1017. else {
  1018. PyObject* result = NULL;
  1019. PyObject* is_attr_obj = NULL;
  1020. PyObject* obj = NULL;
  1021. is_attr_obj = PyBool_FromLong(is_attr);
  1022. if (is_attr_obj == NULL)
  1023. goto done;
  1024. /* either an integer or a string */
  1025. if (idx != -1)
  1026. obj = PyLong_FromSsize_t(idx);
  1027. else
  1028. obj = SubString_new_object(&name);
  1029. if (obj == NULL)
  1030. goto done;
  1031. /* return a tuple of values */
  1032. result = PyTuple_Pack(2, is_attr_obj, obj);
  1033. done:
  1034. Py_XDECREF(is_attr_obj);
  1035. Py_XDECREF(obj);
  1036. return result;
  1037. }
  1038. }
  1039. static PyMethodDef fieldnameiter_methods[] = {
  1040. {NULL, NULL} /* sentinel */
  1041. };
  1042. static PyTypeObject PyFieldNameIter_Type = {
  1043. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  1044. "fieldnameiterator", /* tp_name */
  1045. sizeof(fieldnameiterobject), /* tp_basicsize */
  1046. 0, /* tp_itemsize */
  1047. /* methods */
  1048. (destructor)fieldnameiter_dealloc, /* tp_dealloc */
  1049. 0, /* tp_vectorcall_offset */
  1050. 0, /* tp_getattr */
  1051. 0, /* tp_setattr */
  1052. 0, /* tp_as_async */
  1053. 0, /* tp_repr */
  1054. 0, /* tp_as_number */
  1055. 0, /* tp_as_sequence */
  1056. 0, /* tp_as_mapping */
  1057. 0, /* tp_hash */
  1058. 0, /* tp_call */
  1059. 0, /* tp_str */
  1060. PyObject_GenericGetAttr, /* tp_getattro */
  1061. 0, /* tp_setattro */
  1062. 0, /* tp_as_buffer */
  1063. Py_TPFLAGS_DEFAULT, /* tp_flags */
  1064. 0, /* tp_doc */
  1065. 0, /* tp_traverse */
  1066. 0, /* tp_clear */
  1067. 0, /* tp_richcompare */
  1068. 0, /* tp_weaklistoffset */
  1069. PyObject_SelfIter, /* tp_iter */
  1070. (iternextfunc)fieldnameiter_next, /* tp_iternext */
  1071. fieldnameiter_methods, /* tp_methods */
  1072. 0};
  1073. /* unicode_formatter_field_name_split is used to implement
  1074. string.Formatter.vformat. it takes a PEP 3101 "field name", and
  1075. returns a tuple of (first, rest): "first", the part before the
  1076. first '.' or '['; and "rest", an iterator for the rest of the field
  1077. name. it's a wrapper around stringlib/string_format.h's
  1078. field_name_split. The iterator it returns is a
  1079. FieldNameIterator */
  1080. static PyObject *
  1081. formatter_field_name_split(PyObject *ignored, PyObject *self)
  1082. {
  1083. SubString first;
  1084. Py_ssize_t first_idx;
  1085. fieldnameiterobject *it;
  1086. PyObject *first_obj = NULL;
  1087. PyObject *result = NULL;
  1088. if (!PyUnicode_Check(self)) {
  1089. PyErr_Format(PyExc_TypeError, "expected str, got %s", Py_TYPE(self)->tp_name);
  1090. return NULL;
  1091. }
  1092. if (PyUnicode_READY(self) == -1)
  1093. return NULL;
  1094. it = PyObject_New(fieldnameiterobject, &PyFieldNameIter_Type);
  1095. if (it == NULL)
  1096. return NULL;
  1097. /* take ownership, give the object to the iterator. this is
  1098. just to keep the field_name alive */
  1099. it->str = Py_NewRef(self);
  1100. /* Pass in auto_number = NULL. We'll return an empty string for
  1101. first_obj in that case. */
  1102. if (!field_name_split((PyObject*)self, 0, PyUnicode_GET_LENGTH(self),
  1103. &first, &first_idx, &it->it_field, NULL))
  1104. goto done;
  1105. /* first becomes an integer, if possible; else a string */
  1106. if (first_idx != -1)
  1107. first_obj = PyLong_FromSsize_t(first_idx);
  1108. else
  1109. /* convert "first" into a string object */
  1110. first_obj = SubString_new_object(&first);
  1111. if (first_obj == NULL)
  1112. goto done;
  1113. /* return a tuple of values */
  1114. result = PyTuple_Pack(2, first_obj, it);
  1115. done:
  1116. Py_XDECREF(it);
  1117. Py_XDECREF(first_obj);
  1118. return result;
  1119. }