]> git.proxmox.com Git - mirror_edk2.git/blame - AppPkg/Applications/Python/Python-2.7.2/Objects/stringlib/string_format.h
EmbeddedPkg: Extend NvVarStoreFormattedLib LIBRARY_CLASS
[mirror_edk2.git] / AppPkg / Applications / Python / Python-2.7.2 / Objects / stringlib / string_format.h
CommitLineData
4710c53d 1/*\r
2 string_format.h -- implementation of string.format().\r
3\r
4 It uses the Objects/stringlib conventions, so that it can be\r
5 compiled for both unicode and string objects.\r
6*/\r
7\r
8\r
9/* Defines for Python 2.6 compatibility */\r
10#if PY_VERSION_HEX < 0x03000000\r
11#define PyLong_FromSsize_t _PyLong_FromSsize_t\r
12#endif\r
13\r
14/* Defines for more efficiently reallocating the string buffer */\r
15#define INITIAL_SIZE_INCREMENT 100\r
16#define SIZE_MULTIPLIER 2\r
17#define MAX_SIZE_INCREMENT 3200\r
18\r
19\r
20/************************************************************************/\r
21/*********** Global data structures and forward declarations *********/\r
22/************************************************************************/\r
23\r
24/*\r
25 A SubString consists of the characters between two string or\r
26 unicode pointers.\r
27*/\r
28typedef struct {\r
29 STRINGLIB_CHAR *ptr;\r
30 STRINGLIB_CHAR *end;\r
31} SubString;\r
32\r
33\r
34typedef enum {\r
35 ANS_INIT,\r
36 ANS_AUTO,\r
37 ANS_MANUAL\r
38} AutoNumberState; /* Keep track if we're auto-numbering fields */\r
39\r
40/* Keeps track of our auto-numbering state, and which number field we're on */\r
41typedef struct {\r
42 AutoNumberState an_state;\r
43 int an_field_number;\r
44} AutoNumber;\r
45\r
46\r
47/* forward declaration for recursion */\r
48static PyObject *\r
49build_string(SubString *input, PyObject *args, PyObject *kwargs,\r
50 int recursion_depth, AutoNumber *auto_number);\r
51\r
52\r
53\r
54/************************************************************************/\r
55/************************** Utility functions ************************/\r
56/************************************************************************/\r
57\r
58static void\r
59AutoNumber_Init(AutoNumber *auto_number)\r
60{\r
61 auto_number->an_state = ANS_INIT;\r
62 auto_number->an_field_number = 0;\r
63}\r
64\r
65/* fill in a SubString from a pointer and length */\r
66Py_LOCAL_INLINE(void)\r
67SubString_init(SubString *str, STRINGLIB_CHAR *p, Py_ssize_t len)\r
68{\r
69 str->ptr = p;\r
70 if (p == NULL)\r
71 str->end = NULL;\r
72 else\r
73 str->end = str->ptr + len;\r
74}\r
75\r
76/* return a new string. if str->ptr is NULL, return None */\r
77Py_LOCAL_INLINE(PyObject *)\r
78SubString_new_object(SubString *str)\r
79{\r
80 if (str->ptr == NULL) {\r
81 Py_INCREF(Py_None);\r
82 return Py_None;\r
83 }\r
84 return STRINGLIB_NEW(str->ptr, str->end - str->ptr);\r
85}\r
86\r
87/* return a new string. if str->ptr is NULL, return None */\r
88Py_LOCAL_INLINE(PyObject *)\r
89SubString_new_object_or_empty(SubString *str)\r
90{\r
91 if (str->ptr == NULL) {\r
92 return STRINGLIB_NEW(NULL, 0);\r
93 }\r
94 return STRINGLIB_NEW(str->ptr, str->end - str->ptr);\r
95}\r
96\r
97/* Return 1 if an error has been detected switching between automatic\r
98 field numbering and manual field specification, else return 0. Set\r
99 ValueError on error. */\r
100static int\r
101autonumber_state_error(AutoNumberState state, int field_name_is_empty)\r
102{\r
103 if (state == ANS_MANUAL) {\r
104 if (field_name_is_empty) {\r
105 PyErr_SetString(PyExc_ValueError, "cannot switch from "\r
106 "manual field specification to "\r
107 "automatic field numbering");\r
108 return 1;\r
109 }\r
110 }\r
111 else {\r
112 if (!field_name_is_empty) {\r
113 PyErr_SetString(PyExc_ValueError, "cannot switch from "\r
114 "automatic field numbering to "\r
115 "manual field specification");\r
116 return 1;\r
117 }\r
118 }\r
119 return 0;\r
120}\r
121\r
122\r
123/************************************************************************/\r
124/*********** Output string management functions ****************/\r
125/************************************************************************/\r
126\r
127typedef struct {\r
128 STRINGLIB_CHAR *ptr;\r
129 STRINGLIB_CHAR *end;\r
130 PyObject *obj;\r
131 Py_ssize_t size_increment;\r
132} OutputString;\r
133\r
134/* initialize an OutputString object, reserving size characters */\r
135static int\r
136output_initialize(OutputString *output, Py_ssize_t size)\r
137{\r
138 output->obj = STRINGLIB_NEW(NULL, size);\r
139 if (output->obj == NULL)\r
140 return 0;\r
141\r
142 output->ptr = STRINGLIB_STR(output->obj);\r
143 output->end = STRINGLIB_LEN(output->obj) + output->ptr;\r
144 output->size_increment = INITIAL_SIZE_INCREMENT;\r
145\r
146 return 1;\r
147}\r
148\r
149/*\r
150 output_extend reallocates the output string buffer.\r
151 It returns a status: 0 for a failed reallocation,\r
152 1 for success.\r
153*/\r
154\r
155static int\r
156output_extend(OutputString *output, Py_ssize_t count)\r
157{\r
158 STRINGLIB_CHAR *startptr = STRINGLIB_STR(output->obj);\r
159 Py_ssize_t curlen = output->ptr - startptr;\r
160 Py_ssize_t maxlen = curlen + count + output->size_increment;\r
161\r
162 if (STRINGLIB_RESIZE(&output->obj, maxlen) < 0)\r
163 return 0;\r
164 startptr = STRINGLIB_STR(output->obj);\r
165 output->ptr = startptr + curlen;\r
166 output->end = startptr + maxlen;\r
167 if (output->size_increment < MAX_SIZE_INCREMENT)\r
168 output->size_increment *= SIZE_MULTIPLIER;\r
169 return 1;\r
170}\r
171\r
172/*\r
173 output_data dumps characters into our output string\r
174 buffer.\r
175\r
176 In some cases, it has to reallocate the string.\r
177\r
178 It returns a status: 0 for a failed reallocation,\r
179 1 for success.\r
180*/\r
181static int\r
182output_data(OutputString *output, const STRINGLIB_CHAR *s, Py_ssize_t count)\r
183{\r
184 if ((count > output->end - output->ptr) && !output_extend(output, count))\r
185 return 0;\r
186 memcpy(output->ptr, s, count * sizeof(STRINGLIB_CHAR));\r
187 output->ptr += count;\r
188 return 1;\r
189}\r
190\r
191/************************************************************************/\r
192/*********** Format string parsing -- integers and identifiers *********/\r
193/************************************************************************/\r
194\r
195static Py_ssize_t\r
196get_integer(const SubString *str)\r
197{\r
198 Py_ssize_t accumulator = 0;\r
199 Py_ssize_t digitval;\r
200 Py_ssize_t oldaccumulator;\r
201 STRINGLIB_CHAR *p;\r
202\r
203 /* empty string is an error */\r
204 if (str->ptr >= str->end)\r
205 return -1;\r
206\r
207 for (p = str->ptr; p < str->end; p++) {\r
208 digitval = STRINGLIB_TODECIMAL(*p);\r
209 if (digitval < 0)\r
210 return -1;\r
211 /*\r
212 This trick was copied from old Unicode format code. It's cute,\r
213 but would really suck on an old machine with a slow divide\r
214 implementation. Fortunately, in the normal case we do not\r
215 expect too many digits.\r
216 */\r
217 oldaccumulator = accumulator;\r
218 accumulator *= 10;\r
219 if ((accumulator+10)/10 != oldaccumulator+1) {\r
220 PyErr_Format(PyExc_ValueError,\r
221 "Too many decimal digits in format string");\r
222 return -1;\r
223 }\r
224 accumulator += digitval;\r
225 }\r
226 return accumulator;\r
227}\r
228\r
229/************************************************************************/\r
230/******** Functions to get field objects and specification strings ******/\r
231/************************************************************************/\r
232\r
233/* do the equivalent of obj.name */\r
234static PyObject *\r
235getattr(PyObject *obj, SubString *name)\r
236{\r
237 PyObject *newobj;\r
238 PyObject *str = SubString_new_object(name);\r
239 if (str == NULL)\r
240 return NULL;\r
241 newobj = PyObject_GetAttr(obj, str);\r
242 Py_DECREF(str);\r
243 return newobj;\r
244}\r
245\r
246/* do the equivalent of obj[idx], where obj is a sequence */\r
247static PyObject *\r
248getitem_sequence(PyObject *obj, Py_ssize_t idx)\r
249{\r
250 return PySequence_GetItem(obj, idx);\r
251}\r
252\r
253/* do the equivalent of obj[idx], where obj is not a sequence */\r
254static PyObject *\r
255getitem_idx(PyObject *obj, Py_ssize_t idx)\r
256{\r
257 PyObject *newobj;\r
258 PyObject *idx_obj = PyLong_FromSsize_t(idx);\r
259 if (idx_obj == NULL)\r
260 return NULL;\r
261 newobj = PyObject_GetItem(obj, idx_obj);\r
262 Py_DECREF(idx_obj);\r
263 return newobj;\r
264}\r
265\r
266/* do the equivalent of obj[name] */\r
267static PyObject *\r
268getitem_str(PyObject *obj, SubString *name)\r
269{\r
270 PyObject *newobj;\r
271 PyObject *str = SubString_new_object(name);\r
272 if (str == NULL)\r
273 return NULL;\r
274 newobj = PyObject_GetItem(obj, str);\r
275 Py_DECREF(str);\r
276 return newobj;\r
277}\r
278\r
279typedef struct {\r
280 /* the entire string we're parsing. we assume that someone else\r
281 is managing its lifetime, and that it will exist for the\r
282 lifetime of the iterator. can be empty */\r
283 SubString str;\r
284\r
285 /* pointer to where we are inside field_name */\r
286 STRINGLIB_CHAR *ptr;\r
287} FieldNameIterator;\r
288\r
289\r
290static int\r
291FieldNameIterator_init(FieldNameIterator *self, STRINGLIB_CHAR *ptr,\r
292 Py_ssize_t len)\r
293{\r
294 SubString_init(&self->str, ptr, len);\r
295 self->ptr = self->str.ptr;\r
296 return 1;\r
297}\r
298\r
299static int\r
300_FieldNameIterator_attr(FieldNameIterator *self, SubString *name)\r
301{\r
302 STRINGLIB_CHAR c;\r
303\r
304 name->ptr = self->ptr;\r
305\r
306 /* return everything until '.' or '[' */\r
307 while (self->ptr < self->str.end) {\r
308 switch (c = *self->ptr++) {\r
309 case '[':\r
310 case '.':\r
311 /* backup so that we this character will be seen next time */\r
312 self->ptr--;\r
313 break;\r
314 default:\r
315 continue;\r
316 }\r
317 break;\r
318 }\r
319 /* end of string is okay */\r
320 name->end = self->ptr;\r
321 return 1;\r
322}\r
323\r
324static int\r
325_FieldNameIterator_item(FieldNameIterator *self, SubString *name)\r
326{\r
327 int bracket_seen = 0;\r
328 STRINGLIB_CHAR c;\r
329\r
330 name->ptr = self->ptr;\r
331\r
332 /* return everything until ']' */\r
333 while (self->ptr < self->str.end) {\r
334 switch (c = *self->ptr++) {\r
335 case ']':\r
336 bracket_seen = 1;\r
337 break;\r
338 default:\r
339 continue;\r
340 }\r
341 break;\r
342 }\r
343 /* make sure we ended with a ']' */\r
344 if (!bracket_seen) {\r
345 PyErr_SetString(PyExc_ValueError, "Missing ']' in format string");\r
346 return 0;\r
347 }\r
348\r
349 /* end of string is okay */\r
350 /* don't include the ']' */\r
351 name->end = self->ptr-1;\r
352 return 1;\r
353}\r
354\r
355/* returns 0 on error, 1 on non-error termination, and 2 if it returns a value */\r
356static int\r
357FieldNameIterator_next(FieldNameIterator *self, int *is_attribute,\r
358 Py_ssize_t *name_idx, SubString *name)\r
359{\r
360 /* check at end of input */\r
361 if (self->ptr >= self->str.end)\r
362 return 1;\r
363\r
364 switch (*self->ptr++) {\r
365 case '.':\r
366 *is_attribute = 1;\r
367 if (_FieldNameIterator_attr(self, name) == 0)\r
368 return 0;\r
369 *name_idx = -1;\r
370 break;\r
371 case '[':\r
372 *is_attribute = 0;\r
373 if (_FieldNameIterator_item(self, name) == 0)\r
374 return 0;\r
375 *name_idx = get_integer(name);\r
376 if (*name_idx == -1 && PyErr_Occurred())\r
377 return 0;\r
378 break;\r
379 default:\r
380 /* Invalid character follows ']' */\r
381 PyErr_SetString(PyExc_ValueError, "Only '.' or '[' may "\r
382 "follow ']' in format field specifier");\r
383 return 0;\r
384 }\r
385\r
386 /* empty string is an error */\r
387 if (name->ptr == name->end) {\r
388 PyErr_SetString(PyExc_ValueError, "Empty attribute in format string");\r
389 return 0;\r
390 }\r
391\r
392 return 2;\r
393}\r
394\r
395\r
396/* input: field_name\r
397 output: 'first' points to the part before the first '[' or '.'\r
398 'first_idx' is -1 if 'first' is not an integer, otherwise\r
399 it's the value of first converted to an integer\r
400 'rest' is an iterator to return the rest\r
401*/\r
402static int\r
403field_name_split(STRINGLIB_CHAR *ptr, Py_ssize_t len, SubString *first,\r
404 Py_ssize_t *first_idx, FieldNameIterator *rest,\r
405 AutoNumber *auto_number)\r
406{\r
407 STRINGLIB_CHAR c;\r
408 STRINGLIB_CHAR *p = ptr;\r
409 STRINGLIB_CHAR *end = ptr + len;\r
410 int field_name_is_empty;\r
411 int using_numeric_index;\r
412\r
413 /* find the part up until the first '.' or '[' */\r
414 while (p < end) {\r
415 switch (c = *p++) {\r
416 case '[':\r
417 case '.':\r
418 /* backup so that we this character is available to the\r
419 "rest" iterator */\r
420 p--;\r
421 break;\r
422 default:\r
423 continue;\r
424 }\r
425 break;\r
426 }\r
427\r
428 /* set up the return values */\r
429 SubString_init(first, ptr, p - ptr);\r
430 FieldNameIterator_init(rest, p, end - p);\r
431\r
432 /* see if "first" is an integer, in which case it's used as an index */\r
433 *first_idx = get_integer(first);\r
434 if (*first_idx == -1 && PyErr_Occurred())\r
435 return 0;\r
436\r
437 field_name_is_empty = first->ptr >= first->end;\r
438\r
439 /* If the field name is omitted or if we have a numeric index\r
440 specified, then we're doing numeric indexing into args. */\r
441 using_numeric_index = field_name_is_empty || *first_idx != -1;\r
442\r
443 /* We always get here exactly one time for each field we're\r
444 processing. And we get here in field order (counting by left\r
445 braces). So this is the perfect place to handle automatic field\r
446 numbering if the field name is omitted. */\r
447\r
448 /* Check if we need to do the auto-numbering. It's not needed if\r
449 we're called from string.Format routines, because it's handled\r
450 in that class by itself. */\r
451 if (auto_number) {\r
452 /* Initialize our auto numbering state if this is the first\r
453 time we're either auto-numbering or manually numbering. */\r
454 if (auto_number->an_state == ANS_INIT && using_numeric_index)\r
455 auto_number->an_state = field_name_is_empty ?\r
456 ANS_AUTO : ANS_MANUAL;\r
457\r
458 /* Make sure our state is consistent with what we're doing\r
459 this time through. Only check if we're using a numeric\r
460 index. */\r
461 if (using_numeric_index)\r
462 if (autonumber_state_error(auto_number->an_state,\r
463 field_name_is_empty))\r
464 return 0;\r
465 /* Zero length field means we want to do auto-numbering of the\r
466 fields. */\r
467 if (field_name_is_empty)\r
468 *first_idx = (auto_number->an_field_number)++;\r
469 }\r
470\r
471 return 1;\r
472}\r
473\r
474\r
475/*\r
476 get_field_object returns the object inside {}, before the\r
477 format_spec. It handles getindex and getattr lookups and consumes\r
478 the entire input string.\r
479*/\r
480static PyObject *\r
481get_field_object(SubString *input, PyObject *args, PyObject *kwargs,\r
482 AutoNumber *auto_number)\r
483{\r
484 PyObject *obj = NULL;\r
485 int ok;\r
486 int is_attribute;\r
487 SubString name;\r
488 SubString first;\r
489 Py_ssize_t index;\r
490 FieldNameIterator rest;\r
491\r
492 if (!field_name_split(input->ptr, input->end - input->ptr, &first,\r
493 &index, &rest, auto_number)) {\r
494 goto error;\r
495 }\r
496\r
497 if (index == -1) {\r
498 /* look up in kwargs */\r
499 PyObject *key = SubString_new_object(&first);\r
500 if (key == NULL)\r
501 goto error;\r
502 if ((kwargs == NULL) || (obj = PyDict_GetItem(kwargs, key)) == NULL) {\r
503 PyErr_SetObject(PyExc_KeyError, key);\r
504 Py_DECREF(key);\r
505 goto error;\r
506 }\r
507 Py_DECREF(key);\r
508 Py_INCREF(obj);\r
509 }\r
510 else {\r
511 /* look up in args */\r
512 obj = PySequence_GetItem(args, index);\r
513 if (obj == NULL)\r
514 goto error;\r
515 }\r
516\r
517 /* iterate over the rest of the field_name */\r
518 while ((ok = FieldNameIterator_next(&rest, &is_attribute, &index,\r
519 &name)) == 2) {\r
520 PyObject *tmp;\r
521\r
522 if (is_attribute)\r
523 /* getattr lookup "." */\r
524 tmp = getattr(obj, &name);\r
525 else\r
526 /* getitem lookup "[]" */\r
527 if (index == -1)\r
528 tmp = getitem_str(obj, &name);\r
529 else\r
530 if (PySequence_Check(obj))\r
531 tmp = getitem_sequence(obj, index);\r
532 else\r
533 /* not a sequence */\r
534 tmp = getitem_idx(obj, index);\r
535 if (tmp == NULL)\r
536 goto error;\r
537\r
538 /* assign to obj */\r
539 Py_DECREF(obj);\r
540 obj = tmp;\r
541 }\r
542 /* end of iterator, this is the non-error case */\r
543 if (ok == 1)\r
544 return obj;\r
545error:\r
546 Py_XDECREF(obj);\r
547 return NULL;\r
548}\r
549\r
550/************************************************************************/\r
551/***************** Field rendering functions **************************/\r
552/************************************************************************/\r
553\r
554/*\r
555 render_field() is the main function in this section. It takes the\r
556 field object and field specification string generated by\r
557 get_field_and_spec, and renders the field into the output string.\r
558\r
559 render_field calls fieldobj.__format__(format_spec) method, and\r
560 appends to the output.\r
561*/\r
562static int\r
563render_field(PyObject *fieldobj, SubString *format_spec, OutputString *output)\r
564{\r
565 int ok = 0;\r
566 PyObject *result = NULL;\r
567 PyObject *format_spec_object = NULL;\r
568 PyObject *(*formatter)(PyObject *, STRINGLIB_CHAR *, Py_ssize_t) = NULL;\r
569 STRINGLIB_CHAR* format_spec_start = format_spec->ptr ?\r
570 format_spec->ptr : NULL;\r
571 Py_ssize_t format_spec_len = format_spec->ptr ?\r
572 format_spec->end - format_spec->ptr : 0;\r
573\r
574 /* If we know the type exactly, skip the lookup of __format__ and just\r
575 call the formatter directly. */\r
576#if STRINGLIB_IS_UNICODE\r
577 if (PyUnicode_CheckExact(fieldobj))\r
578 formatter = _PyUnicode_FormatAdvanced;\r
579 /* Unfortunately, there's a problem with checking for int, long,\r
580 and float here. If we're being included as unicode, their\r
581 formatters expect string format_spec args. For now, just skip\r
582 this optimization for unicode. This could be fixed, but it's a\r
583 hassle. */\r
584#else\r
585 if (PyString_CheckExact(fieldobj))\r
586 formatter = _PyBytes_FormatAdvanced;\r
587 else if (PyInt_CheckExact(fieldobj))\r
588 formatter =_PyInt_FormatAdvanced;\r
589 else if (PyLong_CheckExact(fieldobj))\r
590 formatter =_PyLong_FormatAdvanced;\r
591 else if (PyFloat_CheckExact(fieldobj))\r
592 formatter = _PyFloat_FormatAdvanced;\r
593#endif\r
594\r
595 if (formatter) {\r
596 /* we know exactly which formatter will be called when __format__ is\r
597 looked up, so call it directly, instead. */\r
598 result = formatter(fieldobj, format_spec_start, format_spec_len);\r
599 }\r
600 else {\r
601 /* We need to create an object out of the pointers we have, because\r
602 __format__ takes a string/unicode object for format_spec. */\r
603 format_spec_object = STRINGLIB_NEW(format_spec_start,\r
604 format_spec_len);\r
605 if (format_spec_object == NULL)\r
606 goto done;\r
607\r
608 result = PyObject_Format(fieldobj, format_spec_object);\r
609 }\r
610 if (result == NULL)\r
611 goto done;\r
612\r
613#if PY_VERSION_HEX >= 0x03000000\r
614 assert(PyUnicode_Check(result));\r
615#else\r
616 assert(PyString_Check(result) || PyUnicode_Check(result));\r
617\r
618 /* Convert result to our type. We could be str, and result could\r
619 be unicode */\r
620 {\r
621 PyObject *tmp = STRINGLIB_TOSTR(result);\r
622 if (tmp == NULL)\r
623 goto done;\r
624 Py_DECREF(result);\r
625 result = tmp;\r
626 }\r
627#endif\r
628\r
629 ok = output_data(output,\r
630 STRINGLIB_STR(result), STRINGLIB_LEN(result));\r
631done:\r
632 Py_XDECREF(format_spec_object);\r
633 Py_XDECREF(result);\r
634 return ok;\r
635}\r
636\r
637static int\r
638parse_field(SubString *str, SubString *field_name, SubString *format_spec,\r
639 STRINGLIB_CHAR *conversion)\r
640{\r
641 /* Note this function works if the field name is zero length,\r
642 which is good. Zero length field names are handled later, in\r
643 field_name_split. */\r
644\r
645 STRINGLIB_CHAR c = 0;\r
646\r
647 /* initialize these, as they may be empty */\r
648 *conversion = '\0';\r
649 SubString_init(format_spec, NULL, 0);\r
650\r
651 /* Search for the field name. it's terminated by the end of\r
652 the string, or a ':' or '!' */\r
653 field_name->ptr = str->ptr;\r
654 while (str->ptr < str->end) {\r
655 switch (c = *(str->ptr++)) {\r
656 case ':':\r
657 case '!':\r
658 break;\r
659 default:\r
660 continue;\r
661 }\r
662 break;\r
663 }\r
664\r
665 if (c == '!' || c == ':') {\r
666 /* we have a format specifier and/or a conversion */\r
667 /* don't include the last character */\r
668 field_name->end = str->ptr-1;\r
669\r
670 /* the format specifier is the rest of the string */\r
671 format_spec->ptr = str->ptr;\r
672 format_spec->end = str->end;\r
673\r
674 /* see if there's a conversion specifier */\r
675 if (c == '!') {\r
676 /* there must be another character present */\r
677 if (format_spec->ptr >= format_spec->end) {\r
678 PyErr_SetString(PyExc_ValueError,\r
679 "end of format while looking for conversion "\r
680 "specifier");\r
681 return 0;\r
682 }\r
683 *conversion = *(format_spec->ptr++);\r
684\r
685 /* if there is another character, it must be a colon */\r
686 if (format_spec->ptr < format_spec->end) {\r
687 c = *(format_spec->ptr++);\r
688 if (c != ':') {\r
689 PyErr_SetString(PyExc_ValueError,\r
690 "expected ':' after format specifier");\r
691 return 0;\r
692 }\r
693 }\r
694 }\r
695 }\r
696 else\r
697 /* end of string, there's no format_spec or conversion */\r
698 field_name->end = str->ptr;\r
699\r
700 return 1;\r
701}\r
702\r
703/************************************************************************/\r
704/******* Output string allocation and escape-to-markup processing ******/\r
705/************************************************************************/\r
706\r
707/* MarkupIterator breaks the string into pieces of either literal\r
708 text, or things inside {} that need to be marked up. it is\r
709 designed to make it easy to wrap a Python iterator around it, for\r
710 use with the Formatter class */\r
711\r
712typedef struct {\r
713 SubString str;\r
714} MarkupIterator;\r
715\r
716static int\r
717MarkupIterator_init(MarkupIterator *self, STRINGLIB_CHAR *ptr, Py_ssize_t len)\r
718{\r
719 SubString_init(&self->str, ptr, len);\r
720 return 1;\r
721}\r
722\r
723/* returns 0 on error, 1 on non-error termination, and 2 if it got a\r
724 string (or something to be expanded) */\r
725static int\r
726MarkupIterator_next(MarkupIterator *self, SubString *literal,\r
727 int *field_present, SubString *field_name,\r
728 SubString *format_spec, STRINGLIB_CHAR *conversion,\r
729 int *format_spec_needs_expanding)\r
730{\r
731 int at_end;\r
732 STRINGLIB_CHAR c = 0;\r
733 STRINGLIB_CHAR *start;\r
734 int count;\r
735 Py_ssize_t len;\r
736 int markup_follows = 0;\r
737\r
738 /* initialize all of the output variables */\r
739 SubString_init(literal, NULL, 0);\r
740 SubString_init(field_name, NULL, 0);\r
741 SubString_init(format_spec, NULL, 0);\r
742 *conversion = '\0';\r
743 *format_spec_needs_expanding = 0;\r
744 *field_present = 0;\r
745\r
746 /* No more input, end of iterator. This is the normal exit\r
747 path. */\r
748 if (self->str.ptr >= self->str.end)\r
749 return 1;\r
750\r
751 start = self->str.ptr;\r
752\r
753 /* First read any literal text. Read until the end of string, an\r
754 escaped '{' or '}', or an unescaped '{'. In order to never\r
755 allocate memory and so I can just pass pointers around, if\r
756 there's an escaped '{' or '}' then we'll return the literal\r
757 including the brace, but no format object. The next time\r
758 through, we'll return the rest of the literal, skipping past\r
759 the second consecutive brace. */\r
760 while (self->str.ptr < self->str.end) {\r
761 switch (c = *(self->str.ptr++)) {\r
762 case '{':\r
763 case '}':\r
764 markup_follows = 1;\r
765 break;\r
766 default:\r
767 continue;\r
768 }\r
769 break;\r
770 }\r
771\r
772 at_end = self->str.ptr >= self->str.end;\r
773 len = self->str.ptr - start;\r
774\r
775 if ((c == '}') && (at_end || (c != *self->str.ptr))) {\r
776 PyErr_SetString(PyExc_ValueError, "Single '}' encountered "\r
777 "in format string");\r
778 return 0;\r
779 }\r
780 if (at_end && c == '{') {\r
781 PyErr_SetString(PyExc_ValueError, "Single '{' encountered "\r
782 "in format string");\r
783 return 0;\r
784 }\r
785 if (!at_end) {\r
786 if (c == *self->str.ptr) {\r
787 /* escaped } or {, skip it in the input. there is no\r
788 markup object following us, just this literal text */\r
789 self->str.ptr++;\r
790 markup_follows = 0;\r
791 }\r
792 else\r
793 len--;\r
794 }\r
795\r
796 /* record the literal text */\r
797 literal->ptr = start;\r
798 literal->end = start + len;\r
799\r
800 if (!markup_follows)\r
801 return 2;\r
802\r
803 /* this is markup, find the end of the string by counting nested\r
804 braces. note that this prohibits escaped braces, so that\r
805 format_specs cannot have braces in them. */\r
806 *field_present = 1;\r
807 count = 1;\r
808\r
809 start = self->str.ptr;\r
810\r
811 /* we know we can't have a zero length string, so don't worry\r
812 about that case */\r
813 while (self->str.ptr < self->str.end) {\r
814 switch (c = *(self->str.ptr++)) {\r
815 case '{':\r
816 /* the format spec needs to be recursively expanded.\r
817 this is an optimization, and not strictly needed */\r
818 *format_spec_needs_expanding = 1;\r
819 count++;\r
820 break;\r
821 case '}':\r
822 count--;\r
823 if (count <= 0) {\r
824 /* we're done. parse and get out */\r
825 SubString s;\r
826\r
827 SubString_init(&s, start, self->str.ptr - 1 - start);\r
828 if (parse_field(&s, field_name, format_spec, conversion) == 0)\r
829 return 0;\r
830\r
831 /* success */\r
832 return 2;\r
833 }\r
834 break;\r
835 }\r
836 }\r
837\r
838 /* end of string while searching for matching '}' */\r
839 PyErr_SetString(PyExc_ValueError, "unmatched '{' in format");\r
840 return 0;\r
841}\r
842\r
843\r
844/* do the !r or !s conversion on obj */\r
845static PyObject *\r
846do_conversion(PyObject *obj, STRINGLIB_CHAR conversion)\r
847{\r
848 /* XXX in pre-3.0, do we need to convert this to unicode, since it\r
849 might have returned a string? */\r
850 switch (conversion) {\r
851 case 'r':\r
852 return PyObject_Repr(obj);\r
853 case 's':\r
854 return STRINGLIB_TOSTR(obj);\r
855 default:\r
856 if (conversion > 32 && conversion < 127) {\r
857 /* It's the ASCII subrange; casting to char is safe\r
858 (assuming the execution character set is an ASCII\r
859 superset). */\r
860 PyErr_Format(PyExc_ValueError,\r
861 "Unknown conversion specifier %c",\r
862 (char)conversion);\r
863 } else\r
864 PyErr_Format(PyExc_ValueError,\r
865 "Unknown conversion specifier \\x%x",\r
866 (unsigned int)conversion);\r
867 return NULL;\r
868 }\r
869}\r
870\r
871/* given:\r
872\r
873 {field_name!conversion:format_spec}\r
874\r
875 compute the result and write it to output.\r
876 format_spec_needs_expanding is an optimization. if it's false,\r
877 just output the string directly, otherwise recursively expand the\r
878 format_spec string.\r
879\r
880 field_name is allowed to be zero length, in which case we\r
881 are doing auto field numbering.\r
882*/\r
883\r
884static int\r
885output_markup(SubString *field_name, SubString *format_spec,\r
886 int format_spec_needs_expanding, STRINGLIB_CHAR conversion,\r
887 OutputString *output, PyObject *args, PyObject *kwargs,\r
888 int recursion_depth, AutoNumber *auto_number)\r
889{\r
890 PyObject *tmp = NULL;\r
891 PyObject *fieldobj = NULL;\r
892 SubString expanded_format_spec;\r
893 SubString *actual_format_spec;\r
894 int result = 0;\r
895\r
896 /* convert field_name to an object */\r
897 fieldobj = get_field_object(field_name, args, kwargs, auto_number);\r
898 if (fieldobj == NULL)\r
899 goto done;\r
900\r
901 if (conversion != '\0') {\r
902 tmp = do_conversion(fieldobj, conversion);\r
903 if (tmp == NULL)\r
904 goto done;\r
905\r
906 /* do the assignment, transferring ownership: fieldobj = tmp */\r
907 Py_DECREF(fieldobj);\r
908 fieldobj = tmp;\r
909 tmp = NULL;\r
910 }\r
911\r
912 /* if needed, recurively compute the format_spec */\r
913 if (format_spec_needs_expanding) {\r
914 tmp = build_string(format_spec, args, kwargs, recursion_depth-1,\r
915 auto_number);\r
916 if (tmp == NULL)\r
917 goto done;\r
918\r
919 /* note that in the case we're expanding the format string,\r
920 tmp must be kept around until after the call to\r
921 render_field. */\r
922 SubString_init(&expanded_format_spec,\r
923 STRINGLIB_STR(tmp), STRINGLIB_LEN(tmp));\r
924 actual_format_spec = &expanded_format_spec;\r
925 }\r
926 else\r
927 actual_format_spec = format_spec;\r
928\r
929 if (render_field(fieldobj, actual_format_spec, output) == 0)\r
930 goto done;\r
931\r
932 result = 1;\r
933\r
934done:\r
935 Py_XDECREF(fieldobj);\r
936 Py_XDECREF(tmp);\r
937\r
938 return result;\r
939}\r
940\r
941/*\r
942 do_markup is the top-level loop for the format() method. It\r
943 searches through the format string for escapes to markup codes, and\r
944 calls other functions to move non-markup text to the output,\r
945 and to perform the markup to the output.\r
946*/\r
947static int\r
948do_markup(SubString *input, PyObject *args, PyObject *kwargs,\r
949 OutputString *output, int recursion_depth, AutoNumber *auto_number)\r
950{\r
951 MarkupIterator iter;\r
952 int format_spec_needs_expanding;\r
953 int result;\r
954 int field_present;\r
955 SubString literal;\r
956 SubString field_name;\r
957 SubString format_spec;\r
958 STRINGLIB_CHAR conversion;\r
959\r
960 MarkupIterator_init(&iter, input->ptr, input->end - input->ptr);\r
961 while ((result = MarkupIterator_next(&iter, &literal, &field_present,\r
962 &field_name, &format_spec,\r
963 &conversion,\r
964 &format_spec_needs_expanding)) == 2) {\r
965 if (!output_data(output, literal.ptr, literal.end - literal.ptr))\r
966 return 0;\r
967 if (field_present)\r
968 if (!output_markup(&field_name, &format_spec,\r
969 format_spec_needs_expanding, conversion, output,\r
970 args, kwargs, recursion_depth, auto_number))\r
971 return 0;\r
972 }\r
973 return result;\r
974}\r
975\r
976\r
977/*\r
978 build_string allocates the output string and then\r
979 calls do_markup to do the heavy lifting.\r
980*/\r
981static PyObject *\r
982build_string(SubString *input, PyObject *args, PyObject *kwargs,\r
983 int recursion_depth, AutoNumber *auto_number)\r
984{\r
985 OutputString output;\r
986 PyObject *result = NULL;\r
987 Py_ssize_t count;\r
988\r
989 output.obj = NULL; /* needed so cleanup code always works */\r
990\r
991 /* check the recursion level */\r
992 if (recursion_depth <= 0) {\r
993 PyErr_SetString(PyExc_ValueError,\r
994 "Max string recursion exceeded");\r
995 goto done;\r
996 }\r
997\r
998 /* initial size is the length of the format string, plus the size\r
999 increment. seems like a reasonable default */\r
1000 if (!output_initialize(&output,\r
1001 input->end - input->ptr +\r
1002 INITIAL_SIZE_INCREMENT))\r
1003 goto done;\r
1004\r
1005 if (!do_markup(input, args, kwargs, &output, recursion_depth,\r
1006 auto_number)) {\r
1007 goto done;\r
1008 }\r
1009\r
1010 count = output.ptr - STRINGLIB_STR(output.obj);\r
1011 if (STRINGLIB_RESIZE(&output.obj, count) < 0) {\r
1012 goto done;\r
1013 }\r
1014\r
1015 /* transfer ownership to result */\r
1016 result = output.obj;\r
1017 output.obj = NULL;\r
1018\r
1019done:\r
1020 Py_XDECREF(output.obj);\r
1021 return result;\r
1022}\r
1023\r
1024/************************************************************************/\r
1025/*********** main routine ***********************************************/\r
1026/************************************************************************/\r
1027\r
1028/* this is the main entry point */\r
1029static PyObject *\r
1030do_string_format(PyObject *self, PyObject *args, PyObject *kwargs)\r
1031{\r
1032 SubString input;\r
1033\r
1034 /* PEP 3101 says only 2 levels, so that\r
1035 "{0:{1}}".format('abc', 's') # works\r
1036 "{0:{1:{2}}}".format('abc', 's', '') # fails\r
1037 */\r
1038 int recursion_depth = 2;\r
1039\r
1040 AutoNumber auto_number;\r
1041\r
1042 AutoNumber_Init(&auto_number);\r
1043 SubString_init(&input, STRINGLIB_STR(self), STRINGLIB_LEN(self));\r
1044 return build_string(&input, args, kwargs, recursion_depth, &auto_number);\r
1045}\r
1046\r
1047\r
1048\r
1049/************************************************************************/\r
1050/*********** formatteriterator ******************************************/\r
1051/************************************************************************/\r
1052\r
1053/* This is used to implement string.Formatter.vparse(). It exists so\r
1054 Formatter can share code with the built in unicode.format() method.\r
1055 It's really just a wrapper around MarkupIterator that is callable\r
1056 from Python. */\r
1057\r
1058typedef struct {\r
1059 PyObject_HEAD\r
1060\r
1061 STRINGLIB_OBJECT *str;\r
1062\r
1063 MarkupIterator it_markup;\r
1064} formatteriterobject;\r
1065\r
1066static void\r
1067formatteriter_dealloc(formatteriterobject *it)\r
1068{\r
1069 Py_XDECREF(it->str);\r
1070 PyObject_FREE(it);\r
1071}\r
1072\r
1073/* returns a tuple:\r
1074 (literal, field_name, format_spec, conversion)\r
1075\r
1076 literal is any literal text to output. might be zero length\r
1077 field_name is the string before the ':'. might be None\r
1078 format_spec is the string after the ':'. mibht be None\r
1079 conversion is either None, or the string after the '!'\r
1080*/\r
1081static PyObject *\r
1082formatteriter_next(formatteriterobject *it)\r
1083{\r
1084 SubString literal;\r
1085 SubString field_name;\r
1086 SubString format_spec;\r
1087 STRINGLIB_CHAR conversion;\r
1088 int format_spec_needs_expanding;\r
1089 int field_present;\r
1090 int result = MarkupIterator_next(&it->it_markup, &literal, &field_present,\r
1091 &field_name, &format_spec, &conversion,\r
1092 &format_spec_needs_expanding);\r
1093\r
1094 /* all of the SubString objects point into it->str, so no\r
1095 memory management needs to be done on them */\r
1096 assert(0 <= result && result <= 2);\r
1097 if (result == 0 || result == 1)\r
1098 /* if 0, error has already been set, if 1, iterator is empty */\r
1099 return NULL;\r
1100 else {\r
1101 PyObject *literal_str = NULL;\r
1102 PyObject *field_name_str = NULL;\r
1103 PyObject *format_spec_str = NULL;\r
1104 PyObject *conversion_str = NULL;\r
1105 PyObject *tuple = NULL;\r
1106\r
1107 literal_str = SubString_new_object(&literal);\r
1108 if (literal_str == NULL)\r
1109 goto done;\r
1110\r
1111 field_name_str = SubString_new_object(&field_name);\r
1112 if (field_name_str == NULL)\r
1113 goto done;\r
1114\r
1115 /* if field_name is non-zero length, return a string for\r
1116 format_spec (even if zero length), else return None */\r
1117 format_spec_str = (field_present ?\r
1118 SubString_new_object_or_empty :\r
1119 SubString_new_object)(&format_spec);\r
1120 if (format_spec_str == NULL)\r
1121 goto done;\r
1122\r
1123 /* if the conversion is not specified, return a None,\r
1124 otherwise create a one length string with the conversion\r
1125 character */\r
1126 if (conversion == '\0') {\r
1127 conversion_str = Py_None;\r
1128 Py_INCREF(conversion_str);\r
1129 }\r
1130 else\r
1131 conversion_str = STRINGLIB_NEW(&conversion, 1);\r
1132 if (conversion_str == NULL)\r
1133 goto done;\r
1134\r
1135 tuple = PyTuple_Pack(4, literal_str, field_name_str, format_spec_str,\r
1136 conversion_str);\r
1137 done:\r
1138 Py_XDECREF(literal_str);\r
1139 Py_XDECREF(field_name_str);\r
1140 Py_XDECREF(format_spec_str);\r
1141 Py_XDECREF(conversion_str);\r
1142 return tuple;\r
1143 }\r
1144}\r
1145\r
1146static PyMethodDef formatteriter_methods[] = {\r
1147 {NULL, NULL} /* sentinel */\r
1148};\r
1149\r
1150static PyTypeObject PyFormatterIter_Type = {\r
1151 PyVarObject_HEAD_INIT(&PyType_Type, 0)\r
1152 "formatteriterator", /* tp_name */\r
1153 sizeof(formatteriterobject), /* tp_basicsize */\r
1154 0, /* tp_itemsize */\r
1155 /* methods */\r
1156 (destructor)formatteriter_dealloc, /* tp_dealloc */\r
1157 0, /* tp_print */\r
1158 0, /* tp_getattr */\r
1159 0, /* tp_setattr */\r
1160 0, /* tp_compare */\r
1161 0, /* tp_repr */\r
1162 0, /* tp_as_number */\r
1163 0, /* tp_as_sequence */\r
1164 0, /* tp_as_mapping */\r
1165 0, /* tp_hash */\r
1166 0, /* tp_call */\r
1167 0, /* tp_str */\r
1168 PyObject_GenericGetAttr, /* tp_getattro */\r
1169 0, /* tp_setattro */\r
1170 0, /* tp_as_buffer */\r
1171 Py_TPFLAGS_DEFAULT, /* tp_flags */\r
1172 0, /* tp_doc */\r
1173 0, /* tp_traverse */\r
1174 0, /* tp_clear */\r
1175 0, /* tp_richcompare */\r
1176 0, /* tp_weaklistoffset */\r
1177 PyObject_SelfIter, /* tp_iter */\r
1178 (iternextfunc)formatteriter_next, /* tp_iternext */\r
1179 formatteriter_methods, /* tp_methods */\r
1180 0,\r
1181};\r
1182\r
1183/* unicode_formatter_parser is used to implement\r
1184 string.Formatter.vformat. it parses a string and returns tuples\r
1185 describing the parsed elements. It's a wrapper around\r
1186 stringlib/string_format.h's MarkupIterator */\r
1187static PyObject *\r
1188formatter_parser(STRINGLIB_OBJECT *self)\r
1189{\r
1190 formatteriterobject *it;\r
1191\r
1192 it = PyObject_New(formatteriterobject, &PyFormatterIter_Type);\r
1193 if (it == NULL)\r
1194 return NULL;\r
1195\r
1196 /* take ownership, give the object to the iterator */\r
1197 Py_INCREF(self);\r
1198 it->str = self;\r
1199\r
1200 /* initialize the contained MarkupIterator */\r
1201 MarkupIterator_init(&it->it_markup,\r
1202 STRINGLIB_STR(self),\r
1203 STRINGLIB_LEN(self));\r
1204\r
1205 return (PyObject *)it;\r
1206}\r
1207\r
1208\r
1209/************************************************************************/\r
1210/*********** fieldnameiterator ******************************************/\r
1211/************************************************************************/\r
1212\r
1213\r
1214/* This is used to implement string.Formatter.vparse(). It parses the\r
1215 field name into attribute and item values. It's a Python-callable\r
1216 wrapper around FieldNameIterator */\r
1217\r
1218typedef struct {\r
1219 PyObject_HEAD\r
1220\r
1221 STRINGLIB_OBJECT *str;\r
1222\r
1223 FieldNameIterator it_field;\r
1224} fieldnameiterobject;\r
1225\r
1226static void\r
1227fieldnameiter_dealloc(fieldnameiterobject *it)\r
1228{\r
1229 Py_XDECREF(it->str);\r
1230 PyObject_FREE(it);\r
1231}\r
1232\r
1233/* returns a tuple:\r
1234 (is_attr, value)\r
1235 is_attr is true if we used attribute syntax (e.g., '.foo')\r
1236 false if we used index syntax (e.g., '[foo]')\r
1237 value is an integer or string\r
1238*/\r
1239static PyObject *\r
1240fieldnameiter_next(fieldnameiterobject *it)\r
1241{\r
1242 int result;\r
1243 int is_attr;\r
1244 Py_ssize_t idx;\r
1245 SubString name;\r
1246\r
1247 result = FieldNameIterator_next(&it->it_field, &is_attr,\r
1248 &idx, &name);\r
1249 if (result == 0 || result == 1)\r
1250 /* if 0, error has already been set, if 1, iterator is empty */\r
1251 return NULL;\r
1252 else {\r
1253 PyObject* result = NULL;\r
1254 PyObject* is_attr_obj = NULL;\r
1255 PyObject* obj = NULL;\r
1256\r
1257 is_attr_obj = PyBool_FromLong(is_attr);\r
1258 if (is_attr_obj == NULL)\r
1259 goto done;\r
1260\r
1261 /* either an integer or a string */\r
1262 if (idx != -1)\r
1263 obj = PyLong_FromSsize_t(idx);\r
1264 else\r
1265 obj = SubString_new_object(&name);\r
1266 if (obj == NULL)\r
1267 goto done;\r
1268\r
1269 /* return a tuple of values */\r
1270 result = PyTuple_Pack(2, is_attr_obj, obj);\r
1271\r
1272 done:\r
1273 Py_XDECREF(is_attr_obj);\r
1274 Py_XDECREF(obj);\r
1275 return result;\r
1276 }\r
1277}\r
1278\r
1279static PyMethodDef fieldnameiter_methods[] = {\r
1280 {NULL, NULL} /* sentinel */\r
1281};\r
1282\r
1283static PyTypeObject PyFieldNameIter_Type = {\r
1284 PyVarObject_HEAD_INIT(&PyType_Type, 0)\r
1285 "fieldnameiterator", /* tp_name */\r
1286 sizeof(fieldnameiterobject), /* tp_basicsize */\r
1287 0, /* tp_itemsize */\r
1288 /* methods */\r
1289 (destructor)fieldnameiter_dealloc, /* tp_dealloc */\r
1290 0, /* tp_print */\r
1291 0, /* tp_getattr */\r
1292 0, /* tp_setattr */\r
1293 0, /* tp_compare */\r
1294 0, /* tp_repr */\r
1295 0, /* tp_as_number */\r
1296 0, /* tp_as_sequence */\r
1297 0, /* tp_as_mapping */\r
1298 0, /* tp_hash */\r
1299 0, /* tp_call */\r
1300 0, /* tp_str */\r
1301 PyObject_GenericGetAttr, /* tp_getattro */\r
1302 0, /* tp_setattro */\r
1303 0, /* tp_as_buffer */\r
1304 Py_TPFLAGS_DEFAULT, /* tp_flags */\r
1305 0, /* tp_doc */\r
1306 0, /* tp_traverse */\r
1307 0, /* tp_clear */\r
1308 0, /* tp_richcompare */\r
1309 0, /* tp_weaklistoffset */\r
1310 PyObject_SelfIter, /* tp_iter */\r
1311 (iternextfunc)fieldnameiter_next, /* tp_iternext */\r
1312 fieldnameiter_methods, /* tp_methods */\r
1313 0};\r
1314\r
1315/* unicode_formatter_field_name_split is used to implement\r
1316 string.Formatter.vformat. it takes an PEP 3101 "field name", and\r
1317 returns a tuple of (first, rest): "first", the part before the\r
1318 first '.' or '['; and "rest", an iterator for the rest of the field\r
1319 name. it's a wrapper around stringlib/string_format.h's\r
1320 field_name_split. The iterator it returns is a\r
1321 FieldNameIterator */\r
1322static PyObject *\r
1323formatter_field_name_split(STRINGLIB_OBJECT *self)\r
1324{\r
1325 SubString first;\r
1326 Py_ssize_t first_idx;\r
1327 fieldnameiterobject *it;\r
1328\r
1329 PyObject *first_obj = NULL;\r
1330 PyObject *result = NULL;\r
1331\r
1332 it = PyObject_New(fieldnameiterobject, &PyFieldNameIter_Type);\r
1333 if (it == NULL)\r
1334 return NULL;\r
1335\r
1336 /* take ownership, give the object to the iterator. this is\r
1337 just to keep the field_name alive */\r
1338 Py_INCREF(self);\r
1339 it->str = self;\r
1340\r
1341 /* Pass in auto_number = NULL. We'll return an empty string for\r
1342 first_obj in that case. */\r
1343 if (!field_name_split(STRINGLIB_STR(self),\r
1344 STRINGLIB_LEN(self),\r
1345 &first, &first_idx, &it->it_field, NULL))\r
1346 goto done;\r
1347\r
1348 /* first becomes an integer, if possible; else a string */\r
1349 if (first_idx != -1)\r
1350 first_obj = PyLong_FromSsize_t(first_idx);\r
1351 else\r
1352 /* convert "first" into a string object */\r
1353 first_obj = SubString_new_object(&first);\r
1354 if (first_obj == NULL)\r
1355 goto done;\r
1356\r
1357 /* return a tuple of values */\r
1358 result = PyTuple_Pack(2, first_obj, it);\r
1359\r
1360done:\r
1361 Py_XDECREF(it);\r
1362 Py_XDECREF(first_obj);\r
1363 return result;\r
1364}\r