unicode_format.h 40.7 KB
Newer Older
1
/*
Martin v. Löwis's avatar
Martin v. Löwis committed
2
    unicode_format.h -- implementation of str.format().
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
*/


/* Defines for more efficiently reallocating the string buffer */
#define INITIAL_SIZE_INCREMENT 100
#define SIZE_MULTIPLIER 2
#define MAX_SIZE_INCREMENT  3200


/************************************************************************/
/***********   Global data structures and forward declarations  *********/
/************************************************************************/

/*
   A SubString consists of the characters between two string or
   unicode pointers.
*/
typedef struct {
Martin v. Löwis's avatar
Martin v. Löwis committed
21 22
    PyObject *str; /* borrowed reference */
    Py_ssize_t start, end;
23 24 25
} SubString;


26 27 28
typedef enum {
    ANS_INIT,
    ANS_AUTO,
29
    ANS_MANUAL
30 31 32 33 34 35 36 37 38
} AutoNumberState;   /* Keep track if we're auto-numbering fields */

/* Keeps track of our auto-numbering state, and which number field we're on */
typedef struct {
    AutoNumberState an_state;
    int an_field_number;
} AutoNumber;


39 40 41
/* forward declaration for recursion */
static PyObject *
build_string(SubString *input, PyObject *args, PyObject *kwargs,
42
             int recursion_depth, AutoNumber *auto_number);
43 44 45 46 47 48 49



/************************************************************************/
/**************************  Utility  functions  ************************/
/************************************************************************/

50 51 52 53 54 55 56
static void
AutoNumber_Init(AutoNumber *auto_number)
{
    auto_number->an_state = ANS_INIT;
    auto_number->an_field_number = 0;
}

57 58
/* fill in a SubString from a pointer and length */
Py_LOCAL_INLINE(void)
59
SubString_init(SubString *str, PyObject *s, Py_ssize_t start, Py_ssize_t end)
60
{
Martin v. Löwis's avatar
Martin v. Löwis committed
61 62 63
    str->str = s;
    str->start = start;
    str->end = end;
64 65
}

Martin v. Löwis's avatar
Martin v. Löwis committed
66
/* return a new string.  if str->str is NULL, return None */
67 68 69
Py_LOCAL_INLINE(PyObject *)
SubString_new_object(SubString *str)
{
Martin v. Löwis's avatar
Martin v. Löwis committed
70
    if (str->str == NULL) {
71 72 73
        Py_INCREF(Py_None);
        return Py_None;
    }
Martin v. Löwis's avatar
Martin v. Löwis committed
74
    return PyUnicode_Substring(str->str, str->start, str->end);
75 76
}

Martin v. Löwis's avatar
Martin v. Löwis committed
77
/* return a new string.  if str->str is NULL, return None */
78 79 80
Py_LOCAL_INLINE(PyObject *)
SubString_new_object_or_empty(SubString *str)
{
Martin v. Löwis's avatar
Martin v. Löwis committed
81 82
    if (str->str == NULL) {
        return PyUnicode_FromUnicode(NULL, 0);
83
    }
Martin v. Löwis's avatar
Martin v. Löwis committed
84
    return SubString_new_object(str);
85 86
}

87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
/* Return 1 if an error has been detected switching between automatic
   field numbering and manual field specification, else return 0. Set
   ValueError on error. */
static int
autonumber_state_error(AutoNumberState state, int field_name_is_empty)
{
    if (state == ANS_MANUAL) {
        if (field_name_is_empty) {
            PyErr_SetString(PyExc_ValueError, "cannot switch from "
                            "manual field specification to "
                            "automatic field numbering");
            return 1;
        }
    }
    else {
        if (!field_name_is_empty) {
            PyErr_SetString(PyExc_ValueError, "cannot switch from "
                            "automatic field numbering to "
                            "manual field specification");
            return 1;
        }
    }
    return 0;
}


113 114 115 116 117 118 119 120 121 122 123 124 125 126
/************************************************************************/
/***********    Output string management functions       ****************/
/************************************************************************/

/*
    output_data dumps characters into our output string
    buffer.

    In some cases, it has to reallocate the string.

    It returns a status:  0 for a failed reallocation,
    1 for success.
*/
static int
127
output_data(_PyAccu *acc, PyObject *s, Py_ssize_t start, Py_ssize_t end)
128
{
129 130 131 132 133
    PyObject *substring;
    int r;

    substring = PyUnicode_Substring(s, start, end);
    if (substring == NULL)
134
        return 0;
135 136 137
    r = _PyAccu_Accumulate(acc, substring);
    Py_DECREF(substring);
    return r == 0;
138 139 140 141 142 143
}

/************************************************************************/
/***********  Format string parsing -- integers and identifiers *********/
/************************************************************************/

144 145
static Py_ssize_t
get_integer(const SubString *str)
146
{
147 148
    Py_ssize_t accumulator = 0;
    Py_ssize_t digitval;
Martin v. Löwis's avatar
Martin v. Löwis committed
149
    Py_ssize_t i;
150

151
    /* empty string is an error */
Martin v. Löwis's avatar
Martin v. Löwis committed
152
    if (str->start >= str->end)
153
        return -1;
154

Martin v. Löwis's avatar
Martin v. Löwis committed
155 156
    for (i = str->start; i < str->end; i++) {
        digitval = Py_UNICODE_TODECIMAL(PyUnicode_READ_CHAR(str->str, i));
157
        if (digitval < 0)
158
            return -1;
159
        /*
160 161 162 163
           Detect possible overflow before it happens:

              accumulator * 10 + digitval > PY_SSIZE_T_MAX if and only if
              accumulator > (PY_SSIZE_T_MAX - digitval) / 10.
164
        */
165
        if (accumulator > (PY_SSIZE_T_MAX - digitval) / 10) {
166 167 168 169
            PyErr_Format(PyExc_ValueError,
                         "Too many decimal digits in format string");
            return -1;
        }
170
        accumulator = accumulator * 10 + digitval;
171
    }
172
    return accumulator;
173 174
}

175 176 177 178 179 180 181 182 183
/************************************************************************/
/******** Functions to get field objects and specification strings ******/
/************************************************************************/

/* do the equivalent of obj.name */
static PyObject *
getattr(PyObject *obj, SubString *name)
{
    PyObject *newobj;
184
    PyObject *str = SubString_new_object(name);
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
    if (str == NULL)
        return NULL;
    newobj = PyObject_GetAttr(obj, str);
    Py_DECREF(str);
    return newobj;
}

/* do the equivalent of obj[idx], where obj is a sequence */
static PyObject *
getitem_sequence(PyObject *obj, Py_ssize_t idx)
{
    return PySequence_GetItem(obj, idx);
}

/* do the equivalent of obj[idx], where obj is not a sequence */
static PyObject *
getitem_idx(PyObject *obj, Py_ssize_t idx)
{
    PyObject *newobj;
204
    PyObject *idx_obj = PyLong_FromSsize_t(idx);
205 206 207 208 209 210 211 212
    if (idx_obj == NULL)
        return NULL;
    newobj = PyObject_GetItem(obj, idx_obj);
    Py_DECREF(idx_obj);
    return newobj;
}

/* do the equivalent of obj[name] */
213
static PyObject *
214
getitem_str(PyObject *obj, SubString *name)
215
{
216
    PyObject *newobj;
217
    PyObject *str = SubString_new_object(name);
218
    if (str == NULL)
219
        return NULL;
220 221 222 223 224 225 226 227 228 229 230
    newobj = PyObject_GetItem(obj, str);
    Py_DECREF(str);
    return newobj;
}

typedef struct {
    /* the entire string we're parsing.  we assume that someone else
       is managing its lifetime, and that it will exist for the
       lifetime of the iterator.  can be empty */
    SubString str;

Martin v. Löwis's avatar
Martin v. Löwis committed
231 232
    /* index to where we are inside field_name */
    Py_ssize_t index;
233 234 235 236
} FieldNameIterator;


static int
Martin v. Löwis's avatar
Martin v. Löwis committed
237 238
FieldNameIterator_init(FieldNameIterator *self, PyObject *s,
                       Py_ssize_t start, Py_ssize_t end)
239
{
Martin v. Löwis's avatar
Martin v. Löwis committed
240 241
    SubString_init(&self->str, s, start, end);
    self->index = start;
242 243 244 245 246 247
    return 1;
}

static int
_FieldNameIterator_attr(FieldNameIterator *self, SubString *name)
{
Martin v. Löwis's avatar
Martin v. Löwis committed
248
    Py_UCS4 c;
249

Martin v. Löwis's avatar
Martin v. Löwis committed
250 251
    name->str = self->str.str;
    name->start = self->index;
252 253

    /* return everything until '.' or '[' */
Martin v. Löwis's avatar
Martin v. Löwis committed
254 255 256
    while (self->index < self->str.end) {
        c = PyUnicode_READ_CHAR(self->str.str, self->index++);
        switch (c) {
257 258 259
        case '[':
        case '.':
            /* backup so that we this character will be seen next time */
Martin v. Löwis's avatar
Martin v. Löwis committed
260
            self->index--;
261 262 263 264 265
            break;
        default:
            continue;
        }
        break;
266
    }
267
    /* end of string is okay */
Martin v. Löwis's avatar
Martin v. Löwis committed
268
    name->end = self->index;
269
    return 1;
270 271
}

272 273 274
static int
_FieldNameIterator_item(FieldNameIterator *self, SubString *name)
{
275
    int bracket_seen = 0;
Martin v. Löwis's avatar
Martin v. Löwis committed
276
    Py_UCS4 c;
277

Martin v. Löwis's avatar
Martin v. Löwis committed
278 279
    name->str = self->str.str;
    name->start = self->index;
280

281
    /* return everything until ']' */
Martin v. Löwis's avatar
Martin v. Löwis committed
282 283 284
    while (self->index < self->str.end) {
        c = PyUnicode_READ_CHAR(self->str.str, self->index++);
        switch (c) {
285
        case ']':
286
            bracket_seen = 1;
287 288 289 290 291 292
            break;
        default:
            continue;
        }
        break;
    }
293 294 295 296 297 298
    /* make sure we ended with a ']' */
    if (!bracket_seen) {
        PyErr_SetString(PyExc_ValueError, "Missing ']' in format string");
        return 0;
    }

299 300
    /* end of string is okay */
    /* don't include the ']' */
Martin v. Löwis's avatar
Martin v. Löwis committed
301
    name->end = self->index-1;
302 303 304 305 306 307 308 309 310
    return 1;
}

/* returns 0 on error, 1 on non-error termination, and 2 if it returns a value */
static int
FieldNameIterator_next(FieldNameIterator *self, int *is_attribute,
                       Py_ssize_t *name_idx, SubString *name)
{
    /* check at end of input */
Martin v. Löwis's avatar
Martin v. Löwis committed
311
    if (self->index >= self->str.end)
312 313
        return 1;

Martin v. Löwis's avatar
Martin v. Löwis committed
314
    switch (PyUnicode_READ_CHAR(self->str.str, self->index++)) {
315 316
    case '.':
        *is_attribute = 1;
317
        if (_FieldNameIterator_attr(self, name) == 0)
318 319 320 321 322
            return 0;
        *name_idx = -1;
        break;
    case '[':
        *is_attribute = 0;
323
        if (_FieldNameIterator_item(self, name) == 0)
324 325
            return 0;
        *name_idx = get_integer(name);
326 327
        if (*name_idx == -1 && PyErr_Occurred())
            return 0;
328 329
        break;
    default:
330 331 332
        /* Invalid character follows ']' */
        PyErr_SetString(PyExc_ValueError, "Only '.' or '[' may "
                        "follow ']' in format field specifier");
333 334 335 336
        return 0;
    }

    /* empty string is an error */
Martin v. Löwis's avatar
Martin v. Löwis committed
337
    if (name->start == name->end) {
338 339 340 341 342 343 344 345 346 347 348 349 350
        PyErr_SetString(PyExc_ValueError, "Empty attribute in format string");
        return 0;
    }

    return 2;
}


/* input: field_name
   output: 'first' points to the part before the first '[' or '.'
           'first_idx' is -1 if 'first' is not an integer, otherwise
                       it's the value of first converted to an integer
           'rest' is an iterator to return the rest
351
*/
352
static int
Martin v. Löwis's avatar
Martin v. Löwis committed
353
field_name_split(PyObject *str, Py_ssize_t start, Py_ssize_t end, SubString *first,
354 355
                 Py_ssize_t *first_idx, FieldNameIterator *rest,
                 AutoNumber *auto_number)
356
{
Martin v. Löwis's avatar
Martin v. Löwis committed
357 358
    Py_UCS4 c;
    Py_ssize_t i = start;
359 360
    int field_name_is_empty;
    int using_numeric_index;
361 362

    /* find the part up until the first '.' or '[' */
Martin v. Löwis's avatar
Martin v. Löwis committed
363 364
    while (i < end) {
        switch (c = PyUnicode_READ_CHAR(str, i++)) {
365 366 367 368
        case '[':
        case '.':
            /* backup so that we this character is available to the
               "rest" iterator */
Martin v. Löwis's avatar
Martin v. Löwis committed
369
            i--;
370 371 372 373 374 375 376 377
            break;
        default:
            continue;
        }
        break;
    }

    /* set up the return values */
Martin v. Löwis's avatar
Martin v. Löwis committed
378 379
    SubString_init(first, str, start, i);
    FieldNameIterator_init(rest, str, i, end);
380

381 382
    /* see if "first" is an integer, in which case it's used as an index */
    *first_idx = get_integer(first);
383 384
    if (*first_idx == -1 && PyErr_Occurred())
        return 0;
385

Martin v. Löwis's avatar
Martin v. Löwis committed
386
    field_name_is_empty = first->start >= first->end;
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417

    /* If the field name is omitted or if we have a numeric index
       specified, then we're doing numeric indexing into args. */
    using_numeric_index = field_name_is_empty || *first_idx != -1;

    /* We always get here exactly one time for each field we're
       processing. And we get here in field order (counting by left
       braces). So this is the perfect place to handle automatic field
       numbering if the field name is omitted. */

    /* Check if we need to do the auto-numbering. It's not needed if
       we're called from string.Format routines, because it's handled
       in that class by itself. */
    if (auto_number) {
        /* Initialize our auto numbering state if this is the first
           time we're either auto-numbering or manually numbering. */
        if (auto_number->an_state == ANS_INIT && using_numeric_index)
            auto_number->an_state = field_name_is_empty ?
                ANS_AUTO : ANS_MANUAL;

        /* Make sure our state is consistent with what we're doing
           this time through. Only check if we're using a numeric
           index. */
        if (using_numeric_index)
            if (autonumber_state_error(auto_number->an_state,
                                       field_name_is_empty))
                return 0;
        /* Zero length field means we want to do auto-numbering of the
           fields. */
        if (field_name_is_empty)
            *first_idx = (auto_number->an_field_number)++;
418
    }
419 420

    return 1;
421 422
}

423

424 425 426 427 428 429
/*
    get_field_object returns the object inside {}, before the
    format_spec.  It handles getindex and getattr lookups and consumes
    the entire input string.
*/
static PyObject *
430 431
get_field_object(SubString *input, PyObject *args, PyObject *kwargs,
                 AutoNumber *auto_number)
432
{
433 434 435 436 437
    PyObject *obj = NULL;
    int ok;
    int is_attribute;
    SubString name;
    SubString first;
438
    Py_ssize_t index;
439
    FieldNameIterator rest;
440

Martin v. Löwis's avatar
Martin v. Löwis committed
441
    if (!field_name_split(input->str, input->start, input->end, &first,
442
                          &index, &rest, auto_number)) {
443 444
        goto error;
    }
445

446 447
    if (index == -1) {
        /* look up in kwargs */
448
        PyObject *key = SubString_new_object(&first);
449 450
        if (key == NULL)
            goto error;
451 452 453 454 455

        /* Use PyObject_GetItem instead of PyDict_GetItem because this
           code is no longer just used with kwargs. It might be passed
           a non-dict when called through format_map. */
        if ((kwargs == NULL) || (obj = PyObject_GetItem(kwargs, key)) == NULL) {
456
            PyErr_SetObject(PyExc_KeyError, key);
457 458
            Py_DECREF(key);
            goto error;
459
        }
460
        Py_DECREF(key);
461 462
    }
    else {
463 464 465 466 467 468 469 470 471 472
        /* If args is NULL, we have a format string with a positional field
           with only kwargs to retrieve it from. This can only happen when
           used with format_map(), where positional arguments are not
           allowed. */
        if (args == NULL) {
            PyErr_SetString(PyExc_ValueError, "Format string contains "
                            "positional fields");
            goto error;
        }

473 474
        /* look up in args */
        obj = PySequence_GetItem(args, index);
475
        if (obj == NULL)
476
            goto error;
477
    }
478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502

    /* iterate over the rest of the field_name */
    while ((ok = FieldNameIterator_next(&rest, &is_attribute, &index,
                                        &name)) == 2) {
        PyObject *tmp;

        if (is_attribute)
            /* getattr lookup "." */
            tmp = getattr(obj, &name);
        else
            /* getitem lookup "[]" */
            if (index == -1)
                tmp = getitem_str(obj, &name);
            else
                if (PySequence_Check(obj))
                    tmp = getitem_sequence(obj, index);
                else
                    /* not a sequence */
                    tmp = getitem_idx(obj, index);
        if (tmp == NULL)
            goto error;

        /* assign to obj */
        Py_DECREF(obj);
        obj = tmp;
503
    }
504 505 506 507 508
    /* end of iterator, this is the non-error case */
    if (ok == 1)
        return obj;
error:
    Py_XDECREF(obj);
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
    return NULL;
}

/************************************************************************/
/*****************  Field rendering functions  **************************/
/************************************************************************/

/*
    render_field() is the main function in this section.  It takes the
    field object and field specification string generated by
    get_field_and_spec, and renders the field into the output string.

    render_field calls fieldobj.__format__(format_spec) method, and
    appends to the output.
*/
static int
525
render_field(PyObject *fieldobj, SubString *format_spec, _PyAccu *acc)
526 527
{
    int ok = 0;
528
    PyObject *result = NULL;
529
    PyObject *format_spec_object = NULL;
Martin v. Löwis's avatar
Martin v. Löwis committed
530
    PyObject *(*formatter)(PyObject *, PyObject *, Py_ssize_t, Py_ssize_t) = NULL;
531

532 533 534
    /* If we know the type exactly, skip the lookup of __format__ and just
       call the formatter directly. */
    if (PyUnicode_CheckExact(fieldobj))
535
        formatter = _PyUnicode_FormatAdvanced;
536
    else if (PyLong_CheckExact(fieldobj))
537
        formatter =_PyLong_FormatAdvanced;
538
    else if (PyFloat_CheckExact(fieldobj))
539
        formatter = _PyFloat_FormatAdvanced;
540 541 542 543 544

    /* XXX: for 2.6, convert format_spec to the appropriate type
       (unicode, str) */

    if (formatter) {
545 546
        /* we know exactly which formatter will be called when __format__ is
           looked up, so call it directly, instead. */
Martin v. Löwis's avatar
Martin v. Löwis committed
547 548
        result = formatter(fieldobj, format_spec->str,
                           format_spec->start, format_spec->end);
549
    }
550
    else {
551 552
        /* We need to create an object out of the pointers we have, because
           __format__ takes a string/unicode object for format_spec. */
Martin v. Löwis's avatar
Martin v. Löwis committed
553 554 555 556 557 558
        if (format_spec->str)
            format_spec_object = PyUnicode_Substring(format_spec->str,
                                                     format_spec->start,
                                                     format_spec->end);
        else
            format_spec_object = PyUnicode_New(0, 0);
559 560 561 562
        if (format_spec_object == NULL)
            goto done;

        result = PyObject_Format(fieldobj, format_spec_object);
563
    }
Martin v. Löwis's avatar
Martin v. Löwis committed
564
    if (result == NULL || PyUnicode_READY(result) == -1)
565 566
        goto done;

567
    assert(PyUnicode_Check(result));
568
    ok = output_data(acc, result, 0, PyUnicode_GET_LENGTH(result));
569
done:
570
    Py_XDECREF(format_spec_object);
571 572 573 574 575 576
    Py_XDECREF(result);
    return ok;
}

static int
parse_field(SubString *str, SubString *field_name, SubString *format_spec,
Martin v. Löwis's avatar
Martin v. Löwis committed
577
            Py_UCS4 *conversion)
578
{
579 580 581 582
    /* Note this function works if the field name is zero length,
       which is good.  Zero length field names are handled later, in
       field_name_split. */

Martin v. Löwis's avatar
Martin v. Löwis committed
583
    Py_UCS4 c = 0;
584 585 586

    /* initialize these, as they may be empty */
    *conversion = '\0';
Martin v. Löwis's avatar
Martin v. Löwis committed
587
    SubString_init(format_spec, NULL, 0, 0);
588

589 590
    /* Search for the field name.  it's terminated by the end of
       the string, or a ':' or '!' */
Martin v. Löwis's avatar
Martin v. Löwis committed
591 592 593 594
    field_name->str = str->str;
    field_name->start = str->start;
    while (str->start < str->end) {
        switch ((c = PyUnicode_READ_CHAR(str->str, str->start++))) {
595 596 597 598 599 600 601 602 603 604 605 606
        case ':':
        case '!':
            break;
        default:
            continue;
        }
        break;
    }

    if (c == '!' || c == ':') {
        /* we have a format specifier and/or a conversion */
        /* don't include the last character */
Martin v. Löwis's avatar
Martin v. Löwis committed
607
        field_name->end = str->start-1;
608 609

        /* the format specifier is the rest of the string */
Martin v. Löwis's avatar
Martin v. Löwis committed
610 611
        format_spec->str = str->str;
        format_spec->start = str->start;
612 613 614 615 616
        format_spec->end = str->end;

        /* see if there's a conversion specifier */
        if (c == '!') {
            /* there must be another character present */
Martin v. Löwis's avatar
Martin v. Löwis committed
617
            if (format_spec->start >= format_spec->end) {
618 619 620 621 622
                PyErr_SetString(PyExc_ValueError,
                                "end of format while looking for conversion "
                                "specifier");
                return 0;
            }
Martin v. Löwis's avatar
Martin v. Löwis committed
623
            *conversion = PyUnicode_READ_CHAR(format_spec->str, format_spec->start++);
624 625

            /* if there is another character, it must be a colon */
Martin v. Löwis's avatar
Martin v. Löwis committed
626 627
            if (format_spec->start < format_spec->end) {
                c = PyUnicode_READ_CHAR(format_spec->str, format_spec->start++);
628 629 630 631 632 633 634
                if (c != ':') {
                    PyErr_SetString(PyExc_ValueError,
                                    "expected ':' after format specifier");
                    return 0;
                }
            }
        }
635
    }
636
    else
637
        /* end of string, there's no format_spec or conversion */
Martin v. Löwis's avatar
Martin v. Löwis committed
638
        field_name->end = str->start;
639 640

    return 1;
641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656
}

/************************************************************************/
/******* Output string allocation and escape-to-markup processing  ******/
/************************************************************************/

/* MarkupIterator breaks the string into pieces of either literal
   text, or things inside {} that need to be marked up.  it is
   designed to make it easy to wrap a Python iterator around it, for
   use with the Formatter class */

typedef struct {
    SubString str;
} MarkupIterator;

static int
657
MarkupIterator_init(MarkupIterator *self, PyObject *str,
Martin v. Löwis's avatar
Martin v. Löwis committed
658
                    Py_ssize_t start, Py_ssize_t end)
659
{
Martin v. Löwis's avatar
Martin v. Löwis committed
660
    SubString_init(&self->str, str, start, end);
661 662 663 664 665 666
    return 1;
}

/* returns 0 on error, 1 on non-error termination, and 2 if it got a
   string (or something to be expanded) */
static int
667
MarkupIterator_next(MarkupIterator *self, SubString *literal,
668
                    int *field_present, SubString *field_name,
Martin v. Löwis's avatar
Martin v. Löwis committed
669
                    SubString *format_spec, Py_UCS4 *conversion,
670 671 672
                    int *format_spec_needs_expanding)
{
    int at_end;
Martin v. Löwis's avatar
Martin v. Löwis committed
673 674
    Py_UCS4 c = 0;
    Py_ssize_t start;
675 676
    int count;
    Py_ssize_t len;
677
    int markup_follows = 0;
678

679
    /* initialize all of the output variables */
Martin v. Löwis's avatar
Martin v. Löwis committed
680 681 682
    SubString_init(literal, NULL, 0, 0);
    SubString_init(field_name, NULL, 0, 0);
    SubString_init(format_spec, NULL, 0, 0);
683
    *conversion = '\0';
684
    *format_spec_needs_expanding = 0;
685
    *field_present = 0;
686

687 688
    /* No more input, end of iterator.  This is the normal exit
       path. */
Martin v. Löwis's avatar
Martin v. Löwis committed
689
    if (self->str.start >= self->str.end)
690 691
        return 1;

Martin v. Löwis's avatar
Martin v. Löwis committed
692
    start = self->str.start;
693

694 695 696 697 698 699 700
    /* First read any literal text. Read until the end of string, an
       escaped '{' or '}', or an unescaped '{'.  In order to never
       allocate memory and so I can just pass pointers around, if
       there's an escaped '{' or '}' then we'll return the literal
       including the brace, but no format object.  The next time
       through, we'll return the rest of the literal, skipping past
       the second consecutive brace. */
Martin v. Löwis's avatar
Martin v. Löwis committed
701 702
    while (self->str.start < self->str.end) {
        switch (c = PyUnicode_READ_CHAR(self->str.str, self->str.start++)) {
703 704 705 706 707 708
        case '{':
        case '}':
            markup_follows = 1;
            break;
        default:
            continue;
709
        }
710 711
        break;
    }
712

Martin v. Löwis's avatar
Martin v. Löwis committed
713 714
    at_end = self->str.start >= self->str.end;
    len = self->str.start - start;
715

716 717
    if ((c == '}') && (at_end ||
                       (c != PyUnicode_READ_CHAR(self->str.str,
Martin v. Löwis's avatar
Martin v. Löwis committed
718
                                                 self->str.start)))) {
719 720 721
        PyErr_SetString(PyExc_ValueError, "Single '}' encountered "
                        "in format string");
        return 0;
722
    }
723 724 725 726 727 728
    if (at_end && c == '{') {
        PyErr_SetString(PyExc_ValueError, "Single '{' encountered "
                        "in format string");
        return 0;
    }
    if (!at_end) {
Martin v. Löwis's avatar
Martin v. Löwis committed
729
        if (c == PyUnicode_READ_CHAR(self->str.str, self->str.start)) {
730 731
            /* escaped } or {, skip it in the input.  there is no
               markup object following us, just this literal text */
Martin v. Löwis's avatar
Martin v. Löwis committed
732
            self->str.start++;
733
            markup_follows = 0;
734
        }
735 736 737
        else
            len--;
    }
738

739
    /* record the literal text */
Martin v. Löwis's avatar
Martin v. Löwis committed
740 741
    literal->str = self->str.str;
    literal->start = start;
742
    literal->end = start + len;
743

744 745 746 747 748 749
    if (!markup_follows)
        return 2;

    /* this is markup, find the end of the string by counting nested
       braces.  note that this prohibits escaped braces, so that
       format_specs cannot have braces in them. */
750
    *field_present = 1;
751 752
    count = 1;

Martin v. Löwis's avatar
Martin v. Löwis committed
753
    start = self->str.start;
754 755 756

    /* we know we can't have a zero length string, so don't worry
       about that case */
Martin v. Löwis's avatar
Martin v. Löwis committed
757 758
    while (self->str.start < self->str.end) {
        switch (c = PyUnicode_READ_CHAR(self->str.str, self->str.start++)) {
759 760 761 762 763 764 765 766 767 768 769 770
        case '{':
            /* the format spec needs to be recursively expanded.
               this is an optimization, and not strictly needed */
            *format_spec_needs_expanding = 1;
            count++;
            break;
        case '}':
            count--;
            if (count <= 0) {
                /* we're done.  parse and get out */
                SubString s;

Martin v. Löwis's avatar
Martin v. Löwis committed
771
                SubString_init(&s, self->str.str, start, self->str.start - 1);
772 773 774 775 776
                if (parse_field(&s, field_name, format_spec, conversion) == 0)
                    return 0;

                /* success */
                return 2;
777
            }
778
            break;
779 780
        }
    }
781 782 783 784

    /* end of string while searching for matching '}' */
    PyErr_SetString(PyExc_ValueError, "unmatched '{' in format");
    return 0;
785 786 787 788 789
}


/* do the !r or !s conversion on obj */
static PyObject *
Martin v. Löwis's avatar
Martin v. Löwis committed
790
do_conversion(PyObject *obj, Py_UCS4 conversion)
791 792 793 794 795 796 797
{
    /* XXX in pre-3.0, do we need to convert this to unicode, since it
       might have returned a string? */
    switch (conversion) {
    case 'r':
        return PyObject_Repr(obj);
    case 's':
Martin v. Löwis's avatar
Martin v. Löwis committed
798
        return PyObject_Str(obj);
799
    case 'a':
Martin v. Löwis's avatar
Martin v. Löwis committed
800
        return PyObject_ASCII(obj);
801
    default:
802 803 804 805 806
        if (conversion > 32 && conversion < 127) {
                /* It's the ASCII subrange; casting to char is safe
                   (assuming the execution character set is an ASCII
                   superset). */
                PyErr_Format(PyExc_ValueError,
807 808
                     "Unknown conversion specifier %c",
                     (char)conversion);
809 810 811 812
        } else
                PyErr_Format(PyExc_ValueError,
                     "Unknown conversion specifier \\x%x",
                     (unsigned int)conversion);
813 814 815 816 817 818 819 820 821 822 823
        return NULL;
    }
}

/* given:

   {field_name!conversion:format_spec}

   compute the result and write it to output.
   format_spec_needs_expanding is an optimization.  if it's false,
   just output the string directly, otherwise recursively expand the
824 825 826 827 828
   format_spec string.

   field_name is allowed to be zero length, in which case we
   are doing auto field numbering.
*/
829 830 831

static int
output_markup(SubString *field_name, SubString *format_spec,
Martin v. Löwis's avatar
Martin v. Löwis committed
832
              int format_spec_needs_expanding, Py_UCS4 conversion,
833
              _PyAccu *acc, PyObject *args, PyObject *kwargs,
834
              int recursion_depth, AutoNumber *auto_number)
835 836 837 838 839 840 841 842
{
    PyObject *tmp = NULL;
    PyObject *fieldobj = NULL;
    SubString expanded_format_spec;
    SubString *actual_format_spec;
    int result = 0;

    /* convert field_name to an object */
843
    fieldobj = get_field_object(field_name, args, kwargs, auto_number);
844 845 846 847 848
    if (fieldobj == NULL)
        goto done;

    if (conversion != '\0') {
        tmp = do_conversion(fieldobj, conversion);
Martin v. Löwis's avatar
Martin v. Löwis committed
849
        if (tmp == NULL || PyUnicode_READY(tmp) == -1)
850 851 852 853 854 855 856 857 858 859
            goto done;

        /* do the assignment, transferring ownership: fieldobj = tmp */
        Py_DECREF(fieldobj);
        fieldobj = tmp;
        tmp = NULL;
    }

    /* if needed, recurively compute the format_spec */
    if (format_spec_needs_expanding) {
860 861
        tmp = build_string(format_spec, args, kwargs, recursion_depth-1,
                           auto_number);
Martin v. Löwis's avatar
Martin v. Löwis committed
862
        if (tmp == NULL || PyUnicode_READY(tmp) == -1)
863 864 865 866 867
            goto done;

        /* note that in the case we're expanding the format string,
           tmp must be kept around until after the call to
           render_field. */
Martin v. Löwis's avatar
Martin v. Löwis committed
868
        SubString_init(&expanded_format_spec, tmp, 0, PyUnicode_GET_LENGTH(tmp));
869
        actual_format_spec = &expanded_format_spec;
870 871
    }
    else
872 873
        actual_format_spec = format_spec;

874
    if (render_field(fieldobj, actual_format_spec, acc) == 0)
875 876 877 878 879 880 881 882 883 884 885 886
        goto done;

    result = 1;

done:
    Py_XDECREF(fieldobj);
    Py_XDECREF(tmp);

    return result;
}

/*
887
    do_markup is the top-level loop for the format() method.  It
888 889 890 891 892 893
    searches through the format string for escapes to markup codes, and
    calls other functions to move non-markup text to the output,
    and to perform the markup to the output.
*/
static int
do_markup(SubString *input, PyObject *args, PyObject *kwargs,
894
          _PyAccu *acc, int recursion_depth, AutoNumber *auto_number)
895 896 897 898
{
    MarkupIterator iter;
    int format_spec_needs_expanding;
    int result;
899
    int field_present;
900
    SubString literal;
901 902
    SubString field_name;
    SubString format_spec;
Martin v. Löwis's avatar
Martin v. Löwis committed
903
    Py_UCS4 conversion;
904

Martin v. Löwis's avatar
Martin v. Löwis committed
905
    MarkupIterator_init(&iter, input->str, input->start, input->end);
906 907 908
    while ((result = MarkupIterator_next(&iter, &literal, &field_present,
                                         &field_name, &format_spec,
                                         &conversion,
909
                                         &format_spec_needs_expanding)) == 2) {
910
        if (!output_data(acc, literal.str, literal.start, literal.end))
911
            return 0;
912
        if (field_present)
913
            if (!output_markup(&field_name, &format_spec,
914
                               format_spec_needs_expanding, conversion, acc,
915
                               args, kwargs, recursion_depth, auto_number))
916 917 918 919 920 921 922 923 924 925 926 927
                return 0;
    }
    return result;
}


/*
    build_string allocates the output string and then
    calls do_markup to do the heavy lifting.
*/
static PyObject *
build_string(SubString *input, PyObject *args, PyObject *kwargs,
928
             int recursion_depth, AutoNumber *auto_number)
929
{
930
    _PyAccu acc;
931 932

    /* check the recursion level */
933
    if (recursion_depth <= 0) {
934 935
        PyErr_SetString(PyExc_ValueError,
                        "Max string recursion exceeded");
936
        return NULL;
937 938
    }

939 940
    if (_PyAccu_Init(&acc))
        return NULL;
941

942
    if (!do_markup(input, args, kwargs, &acc, recursion_depth,
943
                   auto_number)) {
944 945
        _PyAccu_Destroy(&acc);
        return NULL;
946 947
    }

948
    return _PyAccu_Finish(&acc);
949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964
}

/************************************************************************/
/*********** main routine ***********************************************/
/************************************************************************/

/* this is the main entry point */
static PyObject *
do_string_format(PyObject *self, PyObject *args, PyObject *kwargs)
{
    SubString input;

    /* PEP 3101 says only 2 levels, so that
       "{0:{1}}".format('abc', 's')            # works
       "{0:{1:{2}}}".format('abc', 's', '')    # fails
    */
965
    int recursion_depth = 2;
966

967 968
    AutoNumber auto_number;

Martin v. Löwis's avatar
Martin v. Löwis committed
969 970 971
    if (PyUnicode_READY(self) == -1)
        return NULL;

972
    AutoNumber_Init(&auto_number);
Martin v. Löwis's avatar
Martin v. Löwis committed
973
    SubString_init(&input, self, 0, PyUnicode_GET_LENGTH(self));
974
    return build_string(&input, args, kwargs, recursion_depth, &auto_number);
975
}
976

977 978 979 980 981
static PyObject *
do_string_format_map(PyObject *self, PyObject *obj)
{
    return do_string_format(self, NULL, obj);
}
982 983 984 985 986 987 988 989 990 991 992 993 994


/************************************************************************/
/*********** formatteriterator ******************************************/
/************************************************************************/

/* This is used to implement string.Formatter.vparse().  It exists so
   Formatter can share code with the built in unicode.format() method.
   It's really just a wrapper around MarkupIterator that is callable
   from Python. */

typedef struct {
    PyObject_HEAD
995
    PyObject *str;
996 997 998 999 1000 1001 1002 1003 1004 1005 1006
    MarkupIterator it_markup;
} formatteriterobject;

static void
formatteriter_dealloc(formatteriterobject *it)
{
    Py_XDECREF(it->str);
    PyObject_FREE(it);
}

/* returns a tuple:
1007 1008 1009 1010 1011 1012
   (literal, field_name, format_spec, conversion)

   literal is any literal text to output.  might be zero length
   field_name is the string before the ':'.  might be None
   format_spec is the string after the ':'.  mibht be None
   conversion is either None, or the string after the '!'
1013 1014 1015 1016 1017 1018 1019
*/
static PyObject *
formatteriter_next(formatteriterobject *it)
{
    SubString literal;
    SubString field_name;
    SubString format_spec;
Martin v. Löwis's avatar
Martin v. Löwis committed
1020
    Py_UCS4 conversion;
1021
    int format_spec_needs_expanding;
1022 1023 1024
    int field_present;
    int result = MarkupIterator_next(&it->it_markup, &literal, &field_present,
                                     &field_name, &format_spec, &conversion,
1025 1026 1027 1028 1029
                                     &format_spec_needs_expanding);

    /* all of the SubString objects point into it->str, so no
       memory management needs to be done on them */
    assert(0 <= result && result <= 2);
1030
    if (result == 0 || result == 1)
1031 1032
        /* if 0, error has already been set, if 1, iterator is empty */
        return NULL;
1033
    else {
1034 1035 1036 1037 1038 1039
        PyObject *literal_str = NULL;
        PyObject *field_name_str = NULL;
        PyObject *format_spec_str = NULL;
        PyObject *conversion_str = NULL;
        PyObject *tuple = NULL;

1040 1041 1042 1043 1044 1045 1046 1047 1048 1049
        literal_str = SubString_new_object(&literal);
        if (literal_str == NULL)
            goto done;

        field_name_str = SubString_new_object(&field_name);
        if (field_name_str == NULL)
            goto done;

        /* if field_name is non-zero length, return a string for
           format_spec (even if zero length), else return None */
1050
        format_spec_str = (field_present ?
1051 1052 1053 1054
                           SubString_new_object_or_empty :
                           SubString_new_object)(&format_spec);
        if (format_spec_str == NULL)
            goto done;
1055

1056 1057 1058 1059 1060
        /* if the conversion is not specified, return a None,
           otherwise create a one length string with the conversion
           character */
        if (conversion == '\0') {
            conversion_str = Py_None;
1061 1062
            Py_INCREF(conversion_str);
        }
1063
        else
Martin v. Löwis's avatar
Martin v. Löwis committed
1064 1065
            conversion_str = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND,
                                                       &conversion, 1);
1066 1067 1068
        if (conversion_str == NULL)
            goto done;

1069
        tuple = PyTuple_Pack(4, literal_str, field_name_str, format_spec_str,
1070
                             conversion_str);
1071
    done:
1072 1073 1074 1075 1076 1077 1078 1079 1080
        Py_XDECREF(literal_str);
        Py_XDECREF(field_name_str);
        Py_XDECREF(format_spec_str);
        Py_XDECREF(conversion_str);
        return tuple;
    }
}

static PyMethodDef formatteriter_methods[] = {
1081
    {NULL,              NULL}           /* sentinel */
1082 1083
};

1084
static PyTypeObject PyFormatterIter_Type = {
1085
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
1086 1087 1088
    "formatteriterator",                /* tp_name */
    sizeof(formatteriterobject),        /* tp_basicsize */
    0,                                  /* tp_itemsize */
1089
    /* methods */
1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113
    (destructor)formatteriter_dealloc,  /* tp_dealloc */
    0,                                  /* tp_print */
    0,                                  /* tp_getattr */
    0,                                  /* tp_setattr */
    0,                                  /* tp_reserved */
    0,                                  /* tp_repr */
    0,                                  /* tp_as_number */
    0,                                  /* tp_as_sequence */
    0,                                  /* tp_as_mapping */
    0,                                  /* tp_hash */
    0,                                  /* tp_call */
    0,                                  /* tp_str */
    PyObject_GenericGetAttr,            /* tp_getattro */
    0,                                  /* tp_setattro */
    0,                                  /* tp_as_buffer */
    Py_TPFLAGS_DEFAULT,                 /* tp_flags */
    0,                                  /* tp_doc */
    0,                                  /* tp_traverse */
    0,                                  /* tp_clear */
    0,                                  /* tp_richcompare */
    0,                                  /* tp_weaklistoffset */
    PyObject_SelfIter,                  /* tp_iter */
    (iternextfunc)formatteriter_next,   /* tp_iternext */
    formatteriter_methods,              /* tp_methods */
1114 1115 1116 1117 1118 1119 1120 1121
    0,
};

/* unicode_formatter_parser is used to implement
   string.Formatter.vformat.  it parses a string and returns tuples
   describing the parsed elements.  It's a wrapper around
   stringlib/string_format.h's MarkupIterator */
static PyObject *
1122
formatter_parser(PyObject *ignored, PyObject *self)
1123 1124 1125
{
    formatteriterobject *it;

1126 1127 1128 1129 1130
    if (!PyUnicode_Check(self)) {
        PyErr_Format(PyExc_TypeError, "expected str, got %s", Py_TYPE(self)->tp_name);
        return NULL;
    }

Martin v. Löwis's avatar
Martin v. Löwis committed
1131 1132 1133
    if (PyUnicode_READY(self) == -1)
        return NULL;

1134 1135 1136 1137 1138 1139 1140 1141 1142
    it = PyObject_New(formatteriterobject, &PyFormatterIter_Type);
    if (it == NULL)
        return NULL;

    /* take ownership, give the object to the iterator */
    Py_INCREF(self);
    it->str = self;

    /* initialize the contained MarkupIterator */
Martin v. Löwis's avatar
Martin v. Löwis committed
1143
    MarkupIterator_init(&it->it_markup, (PyObject*)self, 0, PyUnicode_GET_LENGTH(self));
1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158
    return (PyObject *)it;
}


/************************************************************************/
/*********** fieldnameiterator ******************************************/
/************************************************************************/


/* This is used to implement string.Formatter.vparse().  It parses the
   field name into attribute and item values.  It's a Python-callable
   wrapper around FieldNameIterator */

typedef struct {
    PyObject_HEAD
1159
    PyObject *str;
1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185
    FieldNameIterator it_field;
} fieldnameiterobject;

static void
fieldnameiter_dealloc(fieldnameiterobject *it)
{
    Py_XDECREF(it->str);
    PyObject_FREE(it);
}

/* returns a tuple:
   (is_attr, value)
   is_attr is true if we used attribute syntax (e.g., '.foo')
              false if we used index syntax (e.g., '[foo]')
   value is an integer or string
*/
static PyObject *
fieldnameiter_next(fieldnameiterobject *it)
{
    int result;
    int is_attr;
    Py_ssize_t idx;
    SubString name;

    result = FieldNameIterator_next(&it->it_field, &is_attr,
                                    &idx, &name);
1186
    if (result == 0 || result == 1)
1187 1188
        /* if 0, error has already been set, if 1, iterator is empty */
        return NULL;
1189
    else {
1190 1191 1192 1193 1194 1195
        PyObject* result = NULL;
        PyObject* is_attr_obj = NULL;
        PyObject* obj = NULL;

        is_attr_obj = PyBool_FromLong(is_attr);
        if (is_attr_obj == NULL)
1196
            goto done;
1197 1198 1199

        /* either an integer or a string */
        if (idx != -1)
1200
            obj = PyLong_FromSsize_t(idx);
1201 1202 1203
        else
            obj = SubString_new_object(&name);
        if (obj == NULL)
1204
            goto done;
1205 1206 1207 1208

        /* return a tuple of values */
        result = PyTuple_Pack(2, is_attr_obj, obj);

1209
    done:
1210 1211
        Py_XDECREF(is_attr_obj);
        Py_XDECREF(obj);
1212
        return result;
1213 1214 1215 1216
    }
}

static PyMethodDef fieldnameiter_methods[] = {
1217
    {NULL,              NULL}           /* sentinel */
1218 1219 1220 1221
};

static PyTypeObject PyFieldNameIter_Type = {
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
1222 1223 1224
    "fieldnameiterator",                /* tp_name */
    sizeof(fieldnameiterobject),        /* tp_basicsize */
    0,                                  /* tp_itemsize */
1225
    /* methods */
1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249
    (destructor)fieldnameiter_dealloc,  /* tp_dealloc */
    0,                                  /* tp_print */
    0,                                  /* tp_getattr */
    0,                                  /* tp_setattr */
    0,                                  /* tp_reserved */
    0,                                  /* tp_repr */
    0,                                  /* tp_as_number */
    0,                                  /* tp_as_sequence */
    0,                                  /* tp_as_mapping */
    0,                                  /* tp_hash */
    0,                                  /* tp_call */
    0,                                  /* tp_str */
    PyObject_GenericGetAttr,            /* tp_getattro */
    0,                                  /* tp_setattro */
    0,                                  /* tp_as_buffer */
    Py_TPFLAGS_DEFAULT,                 /* tp_flags */
    0,                                  /* tp_doc */
    0,                                  /* tp_traverse */
    0,                                  /* tp_clear */
    0,                                  /* tp_richcompare */
    0,                                  /* tp_weaklistoffset */
    PyObject_SelfIter,                  /* tp_iter */
    (iternextfunc)fieldnameiter_next,   /* tp_iternext */
    fieldnameiter_methods,              /* tp_methods */
1250 1251 1252 1253 1254 1255 1256 1257 1258 1259
    0};

/* unicode_formatter_field_name_split is used to implement
   string.Formatter.vformat.  it takes an PEP 3101 "field name", and
   returns a tuple of (first, rest): "first", the part before the
   first '.' or '['; and "rest", an iterator for the rest of the field
   name.  it's a wrapper around stringlib/string_format.h's
   field_name_split.  The iterator it returns is a
   FieldNameIterator */
static PyObject *
1260
formatter_field_name_split(PyObject *ignored, PyObject *self)
1261 1262 1263 1264 1265 1266 1267 1268
{
    SubString first;
    Py_ssize_t first_idx;
    fieldnameiterobject *it;

    PyObject *first_obj = NULL;
    PyObject *result = NULL;

1269 1270 1271 1272 1273
    if (!PyUnicode_Check(self)) {
        PyErr_Format(PyExc_TypeError, "expected str, got %s", Py_TYPE(self)->tp_name);
        return NULL;
    }

Martin v. Löwis's avatar
Martin v. Löwis committed
1274 1275 1276
    if (PyUnicode_READY(self) == -1)
        return NULL;

1277 1278 1279 1280 1281 1282 1283 1284 1285
    it = PyObject_New(fieldnameiterobject, &PyFieldNameIter_Type);
    if (it == NULL)
        return NULL;

    /* take ownership, give the object to the iterator.  this is
       just to keep the field_name alive */
    Py_INCREF(self);
    it->str = self;

1286 1287
    /* Pass in auto_number = NULL. We'll return an empty string for
       first_obj in that case. */
Martin v. Löwis's avatar
Martin v. Löwis committed
1288
    if (!field_name_split((PyObject*)self, 0, PyUnicode_GET_LENGTH(self),
1289
                          &first, &first_idx, &it->it_field, NULL))
1290
        goto done;
1291

1292
    /* first becomes an integer, if possible; else a string */
1293
    if (first_idx != -1)
1294
        first_obj = PyLong_FromSsize_t(first_idx);
1295 1296 1297 1298
    else
        /* convert "first" into a string object */
        first_obj = SubString_new_object(&first);
    if (first_obj == NULL)
1299
        goto done;
1300 1301 1302 1303

    /* return a tuple of values */
    result = PyTuple_Pack(2, first_obj, it);

1304
done:
1305 1306 1307 1308
    Py_XDECREF(it);
    Py_XDECREF(first_obj);
    return result;
}