Coverage Report

Created: 2026-11-20 06:19

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython3/Objects/unicode_format.c
Line
Count
Source
1
/*
2
3
Unicode implementation based on original code by Fredrik Lundh,
4
modified by Marc-Andre Lemburg <mal@lemburg.com>.
5
6
Major speed upgrades to the method implementations at the Reykjavik
7
NeedForSpeed sprint, by Fredrik Lundh and Andrew Dalke.
8
9
Copyright (c) Corporation for National Research Initiatives.
10
11
--------------------------------------------------------------------
12
The original string type implementation is:
13
14
  Copyright (c) 1999 by Secret Labs AB
15
  Copyright (c) 1999 by Fredrik Lundh
16
17
By obtaining, using, and/or copying this software and/or its
18
associated documentation, you agree that you have read, understood,
19
and will comply with the following terms and conditions:
20
21
Permission to use, copy, modify, and distribute this software and its
22
associated documentation for any purpose and without fee is hereby
23
granted, provided that the above copyright notice appears in all
24
copies, and that both that copyright notice and this permission notice
25
appear in supporting documentation, and that the name of Secret Labs
26
AB or the author not be used in advertising or publicity pertaining to
27
distribution of the software without specific, written prior
28
permission.
29
30
SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO
31
THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
32
FITNESS.  IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR
33
ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
34
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
35
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
36
OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
37
--------------------------------------------------------------------
38
39
*/
40
41
// PyUnicode_Format() implementation
42
43
#include "Python.h"
44
#include "pycore_abstract.h"      // _PyIndex_Check()
45
#include "pycore_format.h"        // F_ALT
46
#include "pycore_long.h"          // _PyLong_FormatWriter()
47
#include "pycore_object.h"        // _PyObject_IsUniquelyReferenced()
48
#include "pycore_unicodeobject.h" // _Py_MAX_UNICODE
49
50
51
0
#define MAX_UNICODE _Py_MAX_UNICODE
52
1.61M
#define ensure_unicode _PyUnicode_EnsureUnicode
53
54
struct unicode_formatter_t {
55
    PyObject *args;
56
    int args_owned;
57
    Py_ssize_t arglen, argidx;
58
    PyObject *dict;
59
60
    int fmtkind;
61
    Py_ssize_t fmtcnt, fmtpos;
62
    const void *fmtdata;
63
    PyObject *fmtstr;
64
65
    _PyUnicodeWriter writer;
66
};
67
68
69
struct unicode_format_arg_t {
70
    Py_UCS4 ch;
71
    int flags;
72
    Py_ssize_t width;
73
    int prec;
74
    int sign;
75
    Py_ssize_t fmtstart;
76
    PyObject *key;
77
};
78
79
80
// Use FORMAT_ERROR("...%s", "") when there is no arguments.
81
0
#define FORMAT_ERROR(EXC, FMT, ...) do {                                    \
82
0
    if (arg->key != NULL) {                                                 \
83
0
        PyErr_Format((EXC), "format argument %R: " FMT,                     \
84
0
                     arg->key, __VA_ARGS__);                                \
85
0
    }                                                                       \
86
0
    else if (ctx->argidx >= 0) {                                            \
87
0
        PyErr_Format((EXC), "format argument %zd: " FMT,                    \
88
0
                     ctx->argidx, __VA_ARGS__);                             \
89
0
    }                                                                       \
90
0
    else {                                                                  \
91
0
        PyErr_Format((EXC), "format argument: " FMT, __VA_ARGS__);          \
92
0
    }                                                                       \
93
0
} while (0)
94
95
96
static PyObject *
97
unicode_format_getnextarg(struct unicode_formatter_t *ctx, int allowone)
98
1.63M
{
99
1.63M
    Py_ssize_t argidx = ctx->argidx;
100
101
1.63M
    if (argidx < ctx->arglen && (allowone || ctx->arglen >= 0)) {
102
1.63M
        ctx->argidx++;
103
1.63M
        if (ctx->arglen >= 0) {
104
30.5k
            return PyTuple_GetItem(ctx->args, argidx);
105
30.5k
        }
106
1.60M
        else if (allowone) {
107
1.60M
            return ctx->args;
108
1.60M
        }
109
1.63M
    }
110
0
    PyErr_Format(PyExc_TypeError,
111
0
                 "not enough arguments for format string (got %zd)",
112
0
                 ctx->arglen < 0 ? 1 : ctx->arglen);
113
0
    return NULL;
114
1.63M
}
115
116
117
/* Returns a new reference to a PyUnicode object, or NULL on failure. */
118
119
/* Format a float into the writer if the writer is not NULL, or into *p_output
120
   otherwise.
121
122
   Return 0 on success, raise an exception and return -1 on error. */
123
static int
124
formatfloat(PyObject *v,
125
            struct unicode_formatter_t *ctx,
126
            struct unicode_format_arg_t *arg,
127
            PyObject **p_output,
128
            _PyUnicodeWriter *writer)
129
0
{
130
0
    char *p;
131
0
    double x;
132
0
    Py_ssize_t len;
133
0
    int prec;
134
0
    int dtoa_flags = 0;
135
136
0
    x = PyFloat_AsDouble(v);
137
0
    if (x == -1.0 && PyErr_Occurred()) {
138
0
        if (PyErr_ExceptionMatches(PyExc_TypeError)) {
139
0
            FORMAT_ERROR(PyExc_TypeError,
140
0
                         "%%%c requires a real number, not %T",
141
0
                         arg->ch, v);
142
0
        }
143
0
        return -1;
144
0
    }
145
146
0
    prec = arg->prec;
147
0
    if (prec < 0)
148
0
        prec = 6;
149
150
0
    if (arg->flags & F_ALT)
151
0
        dtoa_flags |= Py_DTSF_ALT;
152
0
    p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL);
153
0
    if (p == NULL)
154
0
        return -1;
155
0
    len = strlen(p);
156
0
    if (writer) {
157
0
        if (_PyUnicodeWriter_WriteASCIIString(writer, p, len) < 0) {
158
0
            PyMem_Free(p);
159
0
            return -1;
160
0
        }
161
0
    }
162
0
    else {
163
0
        *p_output = _PyUnicode_FromASCII(p, len);
164
0
        if (*p_output == NULL) {
165
0
            PyMem_Free(p);
166
0
            return -1;
167
0
        }
168
0
    }
169
0
    PyMem_Free(p);
170
0
    return 0;
171
0
}
172
173
174
/* formatlong() emulates the format codes d, u, o, x and X, and
175
 * the F_ALT flag, for Python's long (unbounded) ints.  It's not used for
176
 * Python's regular ints.
177
 * Return value:  a new PyUnicodeObject*, or NULL if error.
178
 *     The output string is of the form
179
 *         "-"? ("0x" | "0X")? digit+
180
 *     "0x"/"0X" are present only for x and X conversions, with F_ALT
181
 *         set in flags.  The case of hex digits will be correct,
182
 *     There will be at least prec digits, zero-filled on the left if
183
 *         necessary to get that many.
184
 * val          object to be converted
185
 * flags        bitmask of format flags; only F_ALT is looked at
186
 * prec         minimum number of digits; 0-fill on left if needed
187
 * type         a character in [duoxX]; u acts the same as d
188
 *
189
 * CAUTION:  o, x and X conversions on regular ints can never
190
 * produce a '-' sign, but can for Python's unbounded ints.
191
 */
192
PyObject *
193
_PyUnicode_FormatLong(PyObject *val, int alt, int prec, int type)
194
0
{
195
0
    PyObject *result = NULL;
196
0
    char *buf;
197
0
    Py_ssize_t i;
198
0
    int sign;           /* 1 if '-', else 0 */
199
0
    int len;            /* number of characters */
200
0
    Py_ssize_t llen;
201
0
    int numdigits;      /* len == numnondigits + numdigits */
202
0
    int numnondigits = 0;
203
204
    /* Avoid exceeding SSIZE_T_MAX */
205
0
    if (prec > INT_MAX-3) {
206
0
        PyErr_SetString(PyExc_OverflowError,
207
0
                        "precision too large");
208
0
        return NULL;
209
0
    }
210
211
0
    assert(PyLong_Check(val));
212
213
0
    switch (type) {
214
0
    default:
215
0
        Py_UNREACHABLE();
216
0
    case 'd':
217
0
    case 'i':
218
0
    case 'u':
219
        /* int and int subclasses should print numerically when a numeric */
220
        /* format code is used (see issue18780) */
221
0
        result = PyNumber_ToBase(val, 10);
222
0
        break;
223
0
    case 'o':
224
0
        numnondigits = 2;
225
0
        result = PyNumber_ToBase(val, 8);
226
0
        break;
227
0
    case 'x':
228
0
    case 'X':
229
0
        numnondigits = 2;
230
0
        result = PyNumber_ToBase(val, 16);
231
0
        break;
232
0
    }
233
0
    if (!result)
234
0
        return NULL;
235
236
0
    assert(_PyUnicode_IsModifiable(result));
237
0
    assert(PyUnicode_IS_ASCII(result));
238
239
    /* To modify the string in-place, there can only be one reference. */
240
0
    if (!_PyObject_IsUniquelyReferenced(result)) {
241
0
        Py_DECREF(result);
242
0
        PyErr_BadInternalCall();
243
0
        return NULL;
244
0
    }
245
0
    buf = PyUnicode_DATA(result);
246
0
    llen = PyUnicode_GET_LENGTH(result);
247
0
    if (llen > INT_MAX) {
248
0
        Py_DECREF(result);
249
0
        PyErr_SetString(PyExc_ValueError,
250
0
                        "string too large in _PyUnicode_FormatLong");
251
0
        return NULL;
252
0
    }
253
0
    len = (int)llen;
254
0
    sign = buf[0] == '-';
255
0
    numnondigits += sign;
256
0
    numdigits = len - numnondigits;
257
0
    assert(numdigits > 0);
258
259
    /* Get rid of base marker unless F_ALT */
260
0
    if (((alt) == 0 &&
261
0
        (type == 'o' || type == 'x' || type == 'X'))) {
262
0
        assert(buf[sign] == '0');
263
0
        assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
264
0
               buf[sign+1] == 'o');
265
0
        numnondigits -= 2;
266
0
        buf += 2;
267
0
        len -= 2;
268
0
        if (sign)
269
0
            buf[0] = '-';
270
0
        assert(len == numnondigits + numdigits);
271
0
        assert(numdigits > 0);
272
0
    }
273
274
    /* Fill with leading zeroes to meet minimum width. */
275
0
    if (prec > numdigits) {
276
0
        PyObject *r1 = PyBytes_FromStringAndSize(NULL,
277
0
                                numnondigits + prec);
278
0
        char *b1;
279
0
        if (!r1) {
280
0
            Py_DECREF(result);
281
0
            return NULL;
282
0
        }
283
0
        b1 = PyBytes_AS_STRING(r1);
284
0
        for (i = 0; i < numnondigits; ++i)
285
0
            *b1++ = *buf++;
286
0
        for (i = 0; i < prec - numdigits; i++)
287
0
            *b1++ = '0';
288
0
        for (i = 0; i < numdigits; i++)
289
0
            *b1++ = *buf++;
290
0
        *b1 = '\0';
291
0
        Py_SETREF(result, r1);
292
0
        buf = PyBytes_AS_STRING(result);
293
0
        len = numnondigits + prec;
294
0
    }
295
296
    /* Fix up case for hex conversions. */
297
0
    if (type == 'X') {
298
        /* Need to convert all lower case letters to upper case.
299
           and need to convert 0x to 0X (and -0x to -0X). */
300
0
        for (i = 0; i < len; i++)
301
0
            if (buf[i] >= 'a' && buf[i] <= 'x')
302
0
                buf[i] -= 'a'-'A';
303
0
    }
304
0
    if (!PyUnicode_Check(result)
305
0
        || buf != PyUnicode_DATA(result)) {
306
0
        PyObject *unicode;
307
0
        unicode = _PyUnicode_FromASCII(buf, len);
308
0
        Py_SETREF(result, unicode);
309
0
    }
310
0
    else if (len != PyUnicode_GET_LENGTH(result)) {
311
0
        if (PyUnicode_Resize(&result, len) < 0)
312
0
            Py_CLEAR(result);
313
0
    }
314
0
    return result;
315
0
}
316
317
318
/* Format an integer or a float as an integer.
319
 * Return 1 if the number has been formatted into the writer,
320
 *        0 if the number has been formatted into *p_output
321
 *       -1 and raise an exception on error */
322
static int
323
mainformatlong(PyObject *v,
324
               struct unicode_formatter_t *ctx,
325
               struct unicode_format_arg_t *arg,
326
               PyObject **p_output,
327
               _PyUnicodeWriter *writer)
328
1.62M
{
329
1.62M
    PyObject *iobj, *res;
330
1.62M
    char type = (char)arg->ch;
331
332
1.62M
    if (!PyNumber_Check(v))
333
0
        goto wrongtype;
334
335
    /* make sure number is a type of integer for o, x, and X */
336
1.62M
    if (!PyLong_Check(v)) {
337
0
        if (type == 'o' || type == 'x' || type == 'X') {
338
0
            iobj = _PyNumber_Index(v);
339
0
        }
340
0
        else {
341
0
            iobj = PyNumber_Long(v);
342
0
        }
343
0
        if (iobj == NULL ) {
344
0
            if (PyErr_ExceptionMatches(PyExc_TypeError))
345
0
                goto wrongtype;
346
0
            return -1;
347
0
        }
348
0
        assert(PyLong_Check(iobj));
349
0
    }
350
1.62M
    else {
351
1.62M
        iobj = Py_NewRef(v);
352
1.62M
    }
353
354
1.62M
    if (PyLong_CheckExact(v)
355
1.62M
        && arg->width == -1 && arg->prec == -1
356
1.62M
        && !(arg->flags & (F_SIGN | F_BLANK))
357
1.62M
        && type != 'X')
358
1.62M
    {
359
        /* Fast path */
360
1.62M
        int alternate = arg->flags & F_ALT;
361
1.62M
        int base;
362
363
1.62M
        switch(type)
364
1.62M
        {
365
0
            default:
366
0
                Py_UNREACHABLE();
367
1.62M
            case 'd':
368
1.62M
            case 'i':
369
1.62M
            case 'u':
370
1.62M
                base = 10;
371
1.62M
                break;
372
0
            case 'o':
373
0
                base = 8;
374
0
                break;
375
0
            case 'x':
376
0
            case 'X':
377
0
                base = 16;
378
0
                break;
379
1.62M
        }
380
381
1.62M
        if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) {
382
0
            Py_DECREF(iobj);
383
0
            return -1;
384
0
        }
385
1.62M
        Py_DECREF(iobj);
386
1.62M
        return 1;
387
1.62M
    }
388
389
0
    res = _PyUnicode_FormatLong(iobj, arg->flags & F_ALT, arg->prec, type);
390
0
    Py_DECREF(iobj);
391
0
    if (res == NULL)
392
0
        return -1;
393
0
    *p_output = res;
394
0
    return 0;
395
396
0
wrongtype:
397
0
    switch(type)
398
0
    {
399
0
        case 'o':
400
0
        case 'x':
401
0
        case 'X':
402
0
            FORMAT_ERROR(PyExc_TypeError,
403
0
                         "%%%c requires an integer, not %T",
404
0
                         arg->ch, v);
405
0
            break;
406
0
        default:
407
0
            FORMAT_ERROR(PyExc_TypeError,
408
0
                         "%%%c requires a real number, not %T",
409
0
                         arg->ch, v);
410
0
            break;
411
0
    }
412
0
    return -1;
413
0
}
414
415
416
static Py_UCS4
417
formatchar(PyObject *v,
418
           struct unicode_formatter_t *ctx,
419
           struct unicode_format_arg_t *arg)
420
0
{
421
    /* presume that the buffer is at least 3 characters long */
422
0
    if (PyUnicode_Check(v)) {
423
0
        if (PyUnicode_GET_LENGTH(v) == 1) {
424
0
            return PyUnicode_READ_CHAR(v, 0);
425
0
        }
426
0
        FORMAT_ERROR(PyExc_TypeError,
427
0
                     "%%c requires an integer or a unicode character, "
428
0
                     "not a string of length %zd",
429
0
                     PyUnicode_GET_LENGTH(v));
430
0
        return (Py_UCS4) -1;
431
0
    }
432
0
    else {
433
0
        int overflow;
434
0
        long x = PyLong_AsLongAndOverflow(v, &overflow);
435
0
        if (x == -1 && PyErr_Occurred()) {
436
0
            if (PyErr_ExceptionMatches(PyExc_TypeError)) {
437
0
                FORMAT_ERROR(PyExc_TypeError,
438
0
                             "%%c requires an integer or a unicode character, "
439
0
                             "not %T",
440
0
                             v);
441
0
            }
442
0
            return (Py_UCS4) -1;
443
0
        }
444
445
0
        if (x < 0 || x > MAX_UNICODE) {
446
            /* this includes an overflow in converting to C long */
447
0
            FORMAT_ERROR(PyExc_OverflowError,
448
0
                         "%%c argument not in range(0x110000)%s", "");
449
0
            return (Py_UCS4) -1;
450
0
        }
451
452
0
        return (Py_UCS4) x;
453
0
    }
454
0
}
455
456
457
/* Parse options of an argument: flags, width, precision.
458
   Handle also "%(name)" syntax.
459
460
   Return 0 if the argument has been formatted into arg->str.
461
   Return 1 if the argument has been written into ctx->writer,
462
   Raise an exception and return -1 on error. */
463
static int
464
unicode_format_arg_parse(struct unicode_formatter_t *ctx,
465
                         struct unicode_format_arg_t *arg)
466
1.63M
{
467
1.63M
#define FORMAT_READ(ctx) \
468
1.63M
        PyUnicode_READ((ctx)->fmtkind, (ctx)->fmtdata, (ctx)->fmtpos)
469
470
1.63M
    PyObject *v;
471
472
1.63M
    if (arg->ch == '(') {
473
        /* Get argument value from a dictionary. Example: "%(name)s". */
474
0
        Py_ssize_t keystart;
475
0
        Py_ssize_t keylen;
476
0
        int pcount = 1;
477
478
0
        if (ctx->dict == NULL) {
479
0
            PyErr_Format(PyExc_TypeError,
480
0
                         "format requires a mapping, not %T",
481
0
                         ctx->args);
482
0
            return -1;
483
0
        }
484
0
        ++ctx->fmtpos;
485
0
        --ctx->fmtcnt;
486
0
        keystart = ctx->fmtpos;
487
        /* Skip over balanced parentheses */
488
0
        while (pcount > 0 && --ctx->fmtcnt >= 0) {
489
0
            arg->ch = FORMAT_READ(ctx);
490
0
            if (arg->ch == ')')
491
0
                --pcount;
492
0
            else if (arg->ch == '(')
493
0
                ++pcount;
494
0
            ctx->fmtpos++;
495
0
        }
496
0
        keylen = ctx->fmtpos - keystart - 1;
497
0
        if (ctx->fmtcnt < 0 || pcount > 0) {
498
0
            PyErr_Format(PyExc_ValueError,
499
0
                         "stray %% or incomplete format key at position %zd",
500
0
                         arg->fmtstart);
501
0
            return -1;
502
0
        }
503
0
        arg->key = PyUnicode_Substring(ctx->fmtstr,
504
0
                                       keystart, keystart + keylen);
505
0
        if (arg->key == NULL)
506
0
            return -1;
507
0
        if (ctx->args_owned) {
508
0
            ctx->args_owned = 0;
509
0
            Py_DECREF(ctx->args);
510
0
        }
511
0
        ctx->args = PyObject_GetItem(ctx->dict, arg->key);
512
0
        if (ctx->args == NULL)
513
0
            return -1;
514
0
        ctx->args_owned = 1;
515
0
        ctx->arglen = -3;
516
0
        ctx->argidx = -4;
517
0
    }
518
1.63M
    else {
519
1.63M
        if (ctx->arglen < -1) {
520
0
            PyErr_Format(PyExc_ValueError,
521
0
                         "format requires a parenthesised mapping key "
522
0
                         "at position %zd",
523
0
                         arg->fmtstart);
524
0
            return -1;
525
0
        }
526
1.63M
    }
527
528
    /* Parse flags. Example: "%+i" => flags=F_SIGN. */
529
1.63M
    while (--ctx->fmtcnt >= 0) {
530
1.63M
        arg->ch = FORMAT_READ(ctx);
531
1.63M
        ctx->fmtpos++;
532
1.63M
        switch (arg->ch) {
533
0
        case '-': arg->flags |= F_LJUST; continue;
534
0
        case '+': arg->flags |= F_SIGN; continue;
535
0
        case ' ': arg->flags |= F_BLANK; continue;
536
0
        case '#': arg->flags |= F_ALT; continue;
537
0
        case '0': arg->flags |= F_ZERO; continue;
538
1.63M
        }
539
1.63M
        break;
540
1.63M
    }
541
542
    /* Parse width. Example: "%10s" => width=10 */
543
1.63M
    if (arg->ch == '*') {
544
0
        if (ctx->arglen < -1) {
545
0
            PyErr_Format(PyExc_ValueError,
546
0
                    "* cannot be used with a parenthesised mapping key "
547
0
                    "at position %zd",
548
0
                    arg->fmtstart);
549
0
            return -1;
550
0
        }
551
0
        v = unicode_format_getnextarg(ctx, 0);
552
0
        if (v == NULL)
553
0
            return -1;
554
0
        if (!PyLong_Check(v)) {
555
0
            FORMAT_ERROR(PyExc_TypeError, "* requires int, not %T", v);
556
0
            return -1;
557
0
        }
558
0
        arg->width = PyLong_AsSsize_t(v);
559
0
        if (arg->width == -1 && PyErr_Occurred()) {
560
0
            if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
561
0
                FORMAT_ERROR(PyExc_OverflowError,
562
0
                             "too big for width%s", "");
563
0
            }
564
0
            return -1;
565
0
        }
566
0
        if (arg->width < 0) {
567
0
            if (arg->width == PY_SSIZE_T_MIN) {
568
0
                FORMAT_ERROR(PyExc_OverflowError, "too big for width%s", "");
569
0
                return -1;
570
0
            }
571
0
            arg->flags |= F_LJUST;
572
0
            arg->width = -arg->width;
573
0
        }
574
0
        if (--ctx->fmtcnt >= 0) {
575
0
            arg->ch = FORMAT_READ(ctx);
576
0
            ctx->fmtpos++;
577
0
        }
578
0
        assert(arg->width >= 0);
579
0
    }
580
1.63M
    else if (arg->ch >= '0' && arg->ch <= '9') {
581
0
        arg->width = arg->ch - '0';
582
0
        while (--ctx->fmtcnt >= 0) {
583
0
            arg->ch = FORMAT_READ(ctx);
584
0
            ctx->fmtpos++;
585
0
            if (arg->ch < '0' || arg->ch > '9')
586
0
                break;
587
            /* Since arg->ch is unsigned, the RHS would end up as unsigned,
588
               mixing signed and unsigned comparison. Since arg->ch is between
589
               '0' and '9', casting to int is safe. */
590
0
            if (arg->width > (PY_SSIZE_T_MAX - ((int)arg->ch - '0')) / 10) {
591
0
                PyErr_Format(PyExc_ValueError,
592
0
                             "width too big at position %zd",
593
0
                             arg->fmtstart);
594
0
                return -1;
595
0
            }
596
0
            arg->width = arg->width*10 + (arg->ch - '0');
597
0
        }
598
0
        assert(arg->width >= 0);
599
0
    }
600
601
    /* Parse precision. Example: "%.3f" => prec=3 */
602
1.63M
    if (arg->ch == '.') {
603
0
        arg->prec = 0;
604
0
        if (--ctx->fmtcnt >= 0) {
605
0
            arg->ch = FORMAT_READ(ctx);
606
0
            ctx->fmtpos++;
607
0
        }
608
0
        if (arg->ch == '*') {
609
0
            if (ctx->arglen < -1) {
610
0
                PyErr_Format(PyExc_ValueError,
611
0
                        "* cannot be used with a parenthesised mapping key "
612
0
                        "at position %zd",
613
0
                        arg->fmtstart);
614
0
                return -1;
615
0
            }
616
0
            v = unicode_format_getnextarg(ctx, 0);
617
0
            if (v == NULL)
618
0
                return -1;
619
0
            if (!PyLong_Check(v)) {
620
0
                FORMAT_ERROR(PyExc_TypeError, "* requires int, not %T", v);
621
0
                return -1;
622
0
            }
623
0
            arg->prec = PyLong_AsInt(v);
624
0
            if (arg->prec == -1 && PyErr_Occurred()) {
625
0
                if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
626
0
                    FORMAT_ERROR(PyExc_OverflowError,
627
0
                                 "too big for precision%s", "");
628
0
                }
629
0
                return -1;
630
0
            }
631
0
            if (arg->prec < 0)
632
0
                arg->prec = 0;
633
0
            if (--ctx->fmtcnt >= 0) {
634
0
                arg->ch = FORMAT_READ(ctx);
635
0
                ctx->fmtpos++;
636
0
            }
637
0
        }
638
0
        else if (arg->ch >= '0' && arg->ch <= '9') {
639
0
            arg->prec = arg->ch - '0';
640
0
            while (--ctx->fmtcnt >= 0) {
641
0
                arg->ch = FORMAT_READ(ctx);
642
0
                ctx->fmtpos++;
643
0
                if (arg->ch < '0' || arg->ch > '9')
644
0
                    break;
645
0
                if (arg->prec > (INT_MAX - ((int)arg->ch - '0')) / 10) {
646
0
                    PyErr_Format(PyExc_ValueError,
647
0
                                 "precision too big at position %zd",
648
0
                                 arg->fmtstart);
649
0
                    return -1;
650
0
                }
651
0
                arg->prec = arg->prec*10 + (arg->ch - '0');
652
0
            }
653
0
        }
654
0
        assert(arg->prec >= 0);
655
0
    }
656
657
    /* Ignore "h", "l" and "L" format prefix (ex: "%hi" or "%ls") */
658
1.63M
    if (ctx->fmtcnt >= 0) {
659
1.63M
        if (arg->ch == 'h' || arg->ch == 'l' || arg->ch == 'L') {
660
0
            if (--ctx->fmtcnt >= 0) {
661
0
                arg->ch = FORMAT_READ(ctx);
662
0
                ctx->fmtpos++;
663
0
            }
664
0
        }
665
1.63M
    }
666
1.63M
    if (ctx->fmtcnt < 0) {
667
0
        PyErr_Format(PyExc_ValueError,
668
0
                     "stray %% at position %zd", arg->fmtstart);
669
0
        return -1;
670
0
    }
671
1.63M
    return 0;
672
673
1.63M
#undef FORMAT_READ
674
1.63M
}
675
676
677
/* Format one argument. Supported conversion specifiers:
678
679
   - "s", "r", "a": any type
680
   - "i", "d", "u": int or float
681
   - "o", "x", "X": int
682
   - "e", "E", "f", "F", "g", "G": float
683
   - "c": int or str (1 character)
684
685
   When possible, the output is written directly into the Unicode writer
686
   (ctx->writer). A string is created when padding is required.
687
688
   Return 0 if the argument has been formatted into *p_str,
689
          1 if the argument has been written into ctx->writer,
690
         -1 on error. */
691
static int
692
unicode_format_arg_format(struct unicode_formatter_t *ctx,
693
                          struct unicode_format_arg_t *arg,
694
                          PyObject **p_str)
695
1.63M
{
696
1.63M
    PyObject *v;
697
1.63M
    _PyUnicodeWriter *writer = &ctx->writer;
698
699
1.63M
    if (ctx->fmtcnt == 0)
700
1.60M
        ctx->writer.overallocate = 0;
701
702
1.63M
    v = unicode_format_getnextarg(ctx, 1);
703
1.63M
    if (v == NULL)
704
0
        return -1;
705
706
707
1.63M
    switch (arg->ch) {
708
9.05k
    case 's':
709
9.19k
    case 'r':
710
9.47k
    case 'a':
711
9.47k
        if (arg->width < 0 && arg->prec < 0) {
712
9.47k
            if (arg->ch == 's') {
713
9.05k
                if (PyUnicodeWriter_WriteStr((PyUnicodeWriter*)writer, v) < 0) {
714
0
                    return -1;
715
0
                }
716
9.05k
                return 1;
717
9.05k
            }
718
413
            else if (arg->ch == 'r') {
719
139
                if (PyUnicodeWriter_WriteRepr((PyUnicodeWriter*)writer, v) < 0) {
720
0
                    return -1;
721
0
                }
722
139
                return 1;
723
139
            }
724
9.47k
        }
725
726
274
        if (arg->ch == 's')
727
0
            *p_str = PyObject_Str(v);
728
274
        else if (arg->ch == 'r')
729
0
            *p_str = PyObject_Repr(v);
730
274
        else
731
274
            *p_str = PyObject_ASCII(v);
732
274
        break;
733
734
0
    case 'i':
735
1.62M
    case 'd':
736
1.62M
    case 'u':
737
1.62M
    case 'o':
738
1.62M
    case 'x':
739
1.62M
    case 'X':
740
1.62M
    {
741
1.62M
        int ret = mainformatlong(v, ctx, arg, p_str, writer);
742
1.62M
        if (ret != 0)
743
1.62M
            return ret;
744
0
        arg->sign = 1;
745
0
        break;
746
1.62M
    }
747
748
0
    case 'e':
749
0
    case 'E':
750
0
    case 'f':
751
0
    case 'F':
752
0
    case 'g':
753
0
    case 'G':
754
0
        if (arg->width == -1 && arg->prec == -1
755
0
            && !(arg->flags & (F_SIGN | F_BLANK)))
756
0
        {
757
            /* Fast path */
758
0
            if (formatfloat(v, ctx, arg, NULL, writer) == -1)
759
0
                return -1;
760
0
            return 1;
761
0
        }
762
763
0
        arg->sign = 1;
764
0
        if (formatfloat(v, ctx, arg, p_str, NULL) == -1)
765
0
            return -1;
766
0
        break;
767
768
0
    case 'c':
769
0
    {
770
0
        Py_UCS4 ch = formatchar(v, ctx, arg);
771
0
        if (ch == (Py_UCS4) -1)
772
0
            return -1;
773
0
        if (arg->width == -1 && arg->prec == -1) {
774
            /* Fast path */
775
0
            if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
776
0
                return -1;
777
0
            return 1;
778
0
        }
779
0
        *p_str = PyUnicode_FromOrdinal(ch);
780
0
        break;
781
0
    }
782
783
0
    default:
784
0
        if (arg->ch < 128 && Py_ISALPHA(arg->ch)) {
785
0
            PyErr_Format(PyExc_ValueError,
786
0
                         "unsupported format %%%c at position %zd",
787
0
                         (int)arg->ch, arg->fmtstart);
788
0
        }
789
0
        else if (arg->ch == '\'') {
790
0
            PyErr_Format(PyExc_ValueError,
791
0
                         "stray %% at position %zd or unexpected "
792
0
                         "format character \"'\" at position %zd",
793
0
                         arg->fmtstart,
794
0
                         ctx->fmtpos - 1);
795
0
        }
796
0
        else if (arg->ch >= 32 && arg->ch < 127) {
797
0
            PyErr_Format(PyExc_ValueError,
798
0
                         "stray %% at position %zd or unexpected "
799
0
                         "format character '%c' at position %zd",
800
0
                         arg->fmtstart,
801
0
                         (int)arg->ch, ctx->fmtpos - 1);
802
0
        }
803
0
        else if (Py_UNICODE_ISPRINTABLE(arg->ch)) {
804
0
            PyErr_Format(PyExc_ValueError,
805
0
                         "stray %% at position %zd or unexpected "
806
0
                         "format character '%c' (U+%04X) at position %zd",
807
0
                         arg->fmtstart,
808
0
                         (int)arg->ch, (int)arg->ch, ctx->fmtpos - 1);
809
0
        }
810
0
        else {
811
0
            PyErr_Format(PyExc_ValueError,
812
0
                         "stray %% at position %zd or unexpected "
813
0
                         "format character U+%04X at position %zd",
814
0
                         arg->fmtstart, (int)arg->ch, ctx->fmtpos - 1);
815
0
        }
816
0
        return -1;
817
1.63M
    }
818
274
    if (*p_str == NULL)
819
0
        return -1;
820
274
    assert (PyUnicode_Check(*p_str));
821
274
    return 0;
822
274
}
823
824
825
static int
826
unicode_format_arg_output(struct unicode_formatter_t *ctx,
827
                          struct unicode_format_arg_t *arg,
828
                          PyObject *str)
829
274
{
830
274
    Py_ssize_t len;
831
274
    int kind;
832
274
    const void *pbuf;
833
274
    Py_ssize_t pindex;
834
274
    Py_UCS4 signchar;
835
274
    Py_ssize_t buflen;
836
274
    Py_UCS4 maxchar;
837
274
    Py_ssize_t sublen;
838
274
    _PyUnicodeWriter *writer = &ctx->writer;
839
274
    Py_UCS4 fill;
840
841
274
    fill = ' ';
842
274
    if (arg->sign && arg->flags & F_ZERO)
843
0
        fill = '0';
844
845
274
    len = PyUnicode_GET_LENGTH(str);
846
274
    if ((arg->width == -1 || arg->width <= len)
847
274
        && (arg->prec == -1 || arg->prec >= len)
848
274
        && !(arg->flags & (F_SIGN | F_BLANK)))
849
274
    {
850
        /* Fast path */
851
274
        if (_PyUnicodeWriter_WriteStr(writer, str) == -1)
852
0
            return -1;
853
274
        return 0;
854
274
    }
855
856
    /* Truncate the string for "s", "r" and "a" formats
857
       if the precision is set */
858
0
    if (arg->ch == 's' || arg->ch == 'r' || arg->ch == 'a') {
859
0
        if (arg->prec >= 0 && len > arg->prec)
860
0
            len = arg->prec;
861
0
    }
862
863
    /* Adjust sign and width */
864
0
    kind = PyUnicode_KIND(str);
865
0
    pbuf = PyUnicode_DATA(str);
866
0
    pindex = 0;
867
0
    signchar = '\0';
868
0
    if (arg->sign) {
869
0
        Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
870
0
        if (ch == '-' || ch == '+') {
871
0
            signchar = ch;
872
0
            len--;
873
0
            pindex++;
874
0
        }
875
0
        else if (arg->flags & F_SIGN)
876
0
            signchar = '+';
877
0
        else if (arg->flags & F_BLANK)
878
0
            signchar = ' ';
879
0
        else
880
0
            arg->sign = 0;
881
0
    }
882
0
    if (arg->width < len)
883
0
        arg->width = len;
884
885
    /* Prepare the writer */
886
0
    maxchar = writer->maxchar;
887
0
    if (!(arg->flags & F_LJUST)) {
888
0
        if (arg->sign) {
889
0
            if ((arg->width-1) > len)
890
0
                maxchar = Py_MAX(maxchar, fill);
891
0
        }
892
0
        else {
893
0
            if (arg->width > len)
894
0
                maxchar = Py_MAX(maxchar, fill);
895
0
        }
896
0
    }
897
0
    if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) {
898
0
        Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
899
0
        maxchar = Py_MAX(maxchar, strmaxchar);
900
0
    }
901
902
0
    buflen = arg->width;
903
0
    if (arg->sign && len == arg->width)
904
0
        buflen++;
905
0
    if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1)
906
0
        return -1;
907
908
    /* Write the sign if needed */
909
0
    if (arg->sign) {
910
0
        if (fill != ' ') {
911
0
            PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
912
0
            writer->pos += 1;
913
0
        }
914
0
        if (arg->width > len)
915
0
            arg->width--;
916
0
    }
917
918
    /* Write the numeric prefix for "x", "X" and "o" formats
919
       if the alternate form is used.
920
       For example, write "0x" for the "%#x" format. */
921
0
    if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
922
0
        assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
923
0
        assert(PyUnicode_READ(kind, pbuf, pindex + 1) == arg->ch);
924
0
        if (fill != ' ') {
925
0
            PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
926
0
            PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
927
0
            writer->pos += 2;
928
0
            pindex += 2;
929
0
        }
930
0
        arg->width -= 2;
931
0
        if (arg->width < 0)
932
0
            arg->width = 0;
933
0
        len -= 2;
934
0
    }
935
936
    /* Pad left with the fill character if needed */
937
0
    if (arg->width > len && !(arg->flags & F_LJUST)) {
938
0
        sublen = arg->width - len;
939
0
        _PyUnicode_Fill(writer->kind, writer->data, fill, writer->pos, sublen);
940
0
        writer->pos += sublen;
941
0
        arg->width = len;
942
0
    }
943
944
    /* If padding with spaces: write sign if needed and/or numeric prefix if
945
       the alternate form is used */
946
0
    if (fill == ' ') {
947
0
        if (arg->sign) {
948
0
            PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
949
0
            writer->pos += 1;
950
0
        }
951
0
        if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
952
0
            assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
953
0
            assert(PyUnicode_READ(kind, pbuf, pindex+1) == arg->ch);
954
0
            PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
955
0
            PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
956
0
            writer->pos += 2;
957
0
            pindex += 2;
958
0
        }
959
0
    }
960
961
    /* Write characters */
962
0
    if (len) {
963
0
        _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
964
0
                                      str, pindex, len);
965
0
        writer->pos += len;
966
0
    }
967
968
    /* Pad right with the fill character if needed */
969
0
    if (arg->width > len) {
970
0
        sublen = arg->width - len;
971
0
        _PyUnicode_Fill(writer->kind, writer->data, ' ', writer->pos, sublen);
972
0
        writer->pos += sublen;
973
0
    }
974
0
    return 0;
975
0
}
976
977
978
/* Helper of PyUnicode_Format(): format one arg.
979
   Return 0 on success, raise an exception and return -1 on error. */
980
static int
981
unicode_format_arg(struct unicode_formatter_t *ctx)
982
1.63M
{
983
1.63M
    struct unicode_format_arg_t arg;
984
1.63M
    PyObject *str;
985
1.63M
    int ret;
986
987
1.63M
    arg.ch = PyUnicode_READ(ctx->fmtkind, ctx->fmtdata, ctx->fmtpos);
988
1.63M
    if (arg.ch == '%') {
989
0
        ctx->fmtpos++;
990
0
        ctx->fmtcnt--;
991
0
        if (_PyUnicodeWriter_WriteCharInline(&ctx->writer, '%') < 0)
992
0
            return -1;
993
0
        return 0;
994
0
    }
995
1.63M
    arg.flags = 0;
996
1.63M
    arg.width = -1;
997
1.63M
    arg.prec = -1;
998
1.63M
    arg.sign = 0;
999
1.63M
    arg.fmtstart = ctx->fmtpos - 1;
1000
1.63M
    arg.key = NULL;
1001
1.63M
    str = NULL;
1002
1003
1.63M
    ret = unicode_format_arg_parse(ctx, &arg);
1004
1.63M
    if (ret == -1) {
1005
0
        goto onError;
1006
0
    }
1007
1008
1.63M
    ret = unicode_format_arg_format(ctx, &arg, &str);
1009
1.63M
    if (ret == -1) {
1010
0
        goto onError;
1011
0
    }
1012
1013
1.63M
    if (ret != 1) {
1014
274
        ret = unicode_format_arg_output(ctx, &arg, str);
1015
274
        Py_DECREF(str);
1016
274
        if (ret == -1) {
1017
0
            goto onError;
1018
0
        }
1019
274
    }
1020
1021
1.63M
    if (ctx->dict && (ctx->argidx < ctx->arglen)) {
1022
        // XXX: Never happens?
1023
0
        PyErr_SetString(PyExc_TypeError,
1024
0
                        "not all arguments converted during string formatting");
1025
0
        goto onError;
1026
0
    }
1027
1.63M
    Py_XDECREF(arg.key);
1028
1.63M
    return 0;
1029
1030
0
  onError:
1031
0
    Py_XDECREF(arg.key);
1032
0
    return -1;
1033
1.63M
}
1034
1035
1036
PyObject *
1037
PyUnicode_Format(PyObject *format, PyObject *args)
1038
1.61M
{
1039
1.61M
    struct unicode_formatter_t ctx;
1040
1041
1.61M
    if (format == NULL || args == NULL) {
1042
0
        PyErr_BadInternalCall();
1043
0
        return NULL;
1044
0
    }
1045
1046
1.61M
    if (ensure_unicode(format) < 0)
1047
0
        return NULL;
1048
1049
1.61M
    ctx.fmtstr = format;
1050
1.61M
    ctx.fmtdata = PyUnicode_DATA(ctx.fmtstr);
1051
1.61M
    ctx.fmtkind = PyUnicode_KIND(ctx.fmtstr);
1052
1.61M
    ctx.fmtcnt = PyUnicode_GET_LENGTH(ctx.fmtstr);
1053
1.61M
    ctx.fmtpos = 0;
1054
1055
1.61M
    _PyUnicodeWriter_Init(&ctx.writer);
1056
1.61M
    ctx.writer.min_length = ctx.fmtcnt + 100;
1057
1.61M
    ctx.writer.overallocate = 1;
1058
1059
1.61M
    if (PyTuple_Check(args)) {
1060
8.86k
        ctx.arglen = PyTuple_Size(args);
1061
8.86k
        ctx.argidx = 0;
1062
8.86k
    }
1063
1.60M
    else {
1064
1.60M
        ctx.arglen = -1;
1065
1.60M
        ctx.argidx = -2;
1066
1.60M
    }
1067
1.61M
    ctx.args_owned = 0;
1068
1.61M
    if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
1069
0
        ctx.dict = args;
1070
1.61M
    else
1071
1.61M
        ctx.dict = NULL;
1072
1.61M
    ctx.args = args;
1073
1074
4.87M
    while (--ctx.fmtcnt >= 0) {
1075
3.26M
        if (PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
1076
1.62M
            Py_ssize_t nonfmtpos;
1077
1078
1.62M
            nonfmtpos = ctx.fmtpos++;
1079
69.9M
            while (ctx.fmtcnt >= 0 &&
1080
69.9M
                   PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
1081
68.2M
                ctx.fmtpos++;
1082
68.2M
                ctx.fmtcnt--;
1083
68.2M
            }
1084
1.62M
            if (ctx.fmtcnt < 0) {
1085
6.73k
                ctx.fmtpos--;
1086
6.73k
                ctx.writer.overallocate = 0;
1087
6.73k
            }
1088
1089
1.62M
            if (_PyUnicodeWriter_WriteSubstring(&ctx.writer, ctx.fmtstr,
1090
1.62M
                                                nonfmtpos, ctx.fmtpos) < 0)
1091
0
                goto onError;
1092
1.62M
        }
1093
1.63M
        else {
1094
1.63M
            ctx.fmtpos++;
1095
1.63M
            if (unicode_format_arg(&ctx) == -1)
1096
0
                goto onError;
1097
1.63M
        }
1098
3.26M
    }
1099
1100
1.61M
    if (ctx.argidx < ctx.arglen && !ctx.dict) {
1101
0
        PyErr_Format(PyExc_TypeError,
1102
0
                     "not all arguments converted during string formatting "
1103
0
                     "(required %zd, got %zd)",
1104
0
                     ctx.arglen < 0 ? 0 : ctx.argidx,
1105
0
                     ctx.arglen < 0 ? 1 : ctx.arglen);
1106
0
        goto onError;
1107
0
    }
1108
1109
1.61M
    if (ctx.args_owned) {
1110
0
        Py_DECREF(ctx.args);
1111
0
    }
1112
1.61M
    return _PyUnicodeWriter_Finish(&ctx.writer);
1113
1114
0
  onError:
1115
0
    _PyUnicodeWriter_Dealloc(&ctx.writer);
1116
0
    if (ctx.args_owned) {
1117
0
        Py_DECREF(ctx.args);
1118
0
    }
1119
    return NULL;
1120
1.61M
}