Coverage Report

Created: 2026-03-23 06:45

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/Python/ast_unparse.c
Line
Count
Source
1
#include "Python.h"
2
#include "pycore_ast.h"           // expr_ty
3
#include "pycore_pystate.h"       // _PyInterpreterState_GET()
4
#include "pycore_runtime.h"       // _Py_ID()
5
#include <stdbool.h>
6
7
/* This limited unparser is used to convert annotations back to strings
8
 * during compilation rather than being a full AST unparser.
9
 * See ast.unparse for a full unparser (written in Python)
10
 */
11
12
_Py_DECLARE_STR(dbl_open_br, "{{");
13
_Py_DECLARE_STR(dbl_close_br, "}}");
14
15
/* Forward declarations for recursion via helper functions. */
16
static PyObject *
17
expr_as_unicode(expr_ty e, int level);
18
static int
19
append_ast_expr(PyUnicodeWriter *writer, expr_ty e, int level);
20
static int
21
append_templatestr(PyUnicodeWriter *writer, expr_ty e);
22
static int
23
append_joinedstr(PyUnicodeWriter *writer, expr_ty e, bool is_format_spec);
24
static int
25
append_interpolation(PyUnicodeWriter *writer, expr_ty e);
26
static int
27
append_formattedvalue(PyUnicodeWriter *writer, expr_ty e);
28
static int
29
append_ast_slice(PyUnicodeWriter *writer, expr_ty e);
30
31
static int
32
append_char(PyUnicodeWriter *writer, Py_UCS4 ch)
33
0
{
34
0
    return PyUnicodeWriter_WriteChar(writer, ch);
35
0
}
36
37
static int
38
append_charp(PyUnicodeWriter *writer, const char *charp)
39
0
{
40
0
    return PyUnicodeWriter_WriteUTF8(writer, charp, -1);
41
0
}
42
43
0
#define APPEND_CHAR_FINISH(ch)  do { \
44
0
        return append_char(writer, (ch)); \
45
0
    } while (0)
46
47
0
#define APPEND_STR_FINISH(str)  do { \
48
0
        return append_charp(writer, (str)); \
49
0
    } while (0)
50
51
0
#define APPEND_CHAR(ch)  do { \
52
0
        if (-1 == append_char(writer, (ch))) { \
53
0
            return -1; \
54
0
        } \
55
0
    } while (0)
56
57
0
#define APPEND_STR(str)  do { \
58
0
        if (-1 == append_charp(writer, (str))) { \
59
0
            return -1; \
60
0
        } \
61
0
    } while (0)
62
63
0
#define APPEND_STR_IF(cond, str)  do { \
64
0
        if ((cond) && -1 == append_charp(writer, (str))) { \
65
0
            return -1; \
66
0
        } \
67
0
    } while (0)
68
69
0
#define APPEND_STR_IF_NOT_FIRST(str)  do { \
70
0
        APPEND_STR_IF(!first, (str)); \
71
0
        first = false; \
72
0
    } while (0)
73
74
0
#define APPEND_EXPR(expr, pr)  do { \
75
0
        if (-1 == append_ast_expr(writer, (expr), (pr))) { \
76
0
            return -1; \
77
0
        } \
78
0
    } while (0)
79
80
0
#define APPEND(type, value)  do { \
81
0
        if (-1 == append_ast_ ## type(writer, (value))) { \
82
0
            return -1; \
83
0
        } \
84
0
    } while (0)
85
86
static int
87
append_repr(PyUnicodeWriter *writer, PyObject *obj)
88
0
{
89
0
    PyObject *repr = PyObject_Repr(obj);
90
0
    if (!repr) {
91
0
        return -1;
92
0
    }
93
94
0
    if ((PyFloat_CheckExact(obj) && isinf(PyFloat_AS_DOUBLE(obj))) ||
95
0
        PyComplex_CheckExact(obj))
96
0
    {
97
0
        _Py_DECLARE_STR(str_replace_inf, "1e309");  // evaluates to inf
98
0
        PyObject *new_repr = PyUnicode_Replace(
99
0
            repr,
100
0
            &_Py_ID(inf),
101
0
            &_Py_STR(str_replace_inf),
102
0
            -1
103
0
        );
104
0
        Py_DECREF(repr);
105
0
        if (!new_repr) {
106
0
            return -1;
107
0
        }
108
0
        repr = new_repr;
109
0
    }
110
111
0
    int ret = PyUnicodeWriter_WriteStr(writer, repr);
112
0
    Py_DECREF(repr);
113
0
    return ret;
114
0
}
115
116
/* Priority levels */
117
118
enum {
119
    PR_TUPLE,
120
    PR_TEST,            /* 'if'-'else', 'lambda' */
121
    PR_OR,              /* 'or' */
122
    PR_AND,             /* 'and' */
123
    PR_NOT,             /* 'not' */
124
    PR_CMP,             /* '<', '>', '==', '>=', '<=', '!=',
125
                           'in', 'not in', 'is', 'is not' */
126
    PR_EXPR,
127
    PR_BOR = PR_EXPR,   /* '|' */
128
    PR_BXOR,            /* '^' */
129
    PR_BAND,            /* '&' */
130
    PR_SHIFT,           /* '<<', '>>' */
131
    PR_ARITH,           /* '+', '-' */
132
    PR_TERM,            /* '*', '@', '/', '%', '//' */
133
    PR_FACTOR,          /* unary '+', '-', '~' */
134
    PR_POWER,           /* '**' */
135
    PR_AWAIT,           /* 'await' */
136
    PR_ATOM,
137
};
138
139
static int
140
append_ast_boolop(PyUnicodeWriter *writer, expr_ty e, int level)
141
0
{
142
0
    Py_ssize_t i, value_count;
143
0
    asdl_expr_seq *values;
144
0
    const char *op = (e->v.BoolOp.op == And) ? " and " : " or ";
145
0
    int pr = (e->v.BoolOp.op == And) ? PR_AND : PR_OR;
146
147
0
    APPEND_STR_IF(level > pr, "(");
148
149
0
    values = e->v.BoolOp.values;
150
0
    value_count = asdl_seq_LEN(values);
151
152
0
    for (i = 0; i < value_count; ++i) {
153
0
        APPEND_STR_IF(i > 0, op);
154
0
        APPEND_EXPR((expr_ty)asdl_seq_GET(values, i), pr + 1);
155
0
    }
156
157
0
    APPEND_STR_IF(level > pr, ")");
158
0
    return 0;
159
0
}
160
161
static int
162
append_ast_binop(PyUnicodeWriter *writer, expr_ty e, int level)
163
0
{
164
0
    const char *op;
165
0
    int pr;
166
0
    bool rassoc = false;  /* is right-associative? */
167
168
0
    switch (e->v.BinOp.op) {
169
0
    case Add: op = " + "; pr = PR_ARITH; break;
170
0
    case Sub: op = " - "; pr = PR_ARITH; break;
171
0
    case Mult: op = " * "; pr = PR_TERM; break;
172
0
    case MatMult: op = " @ "; pr = PR_TERM; break;
173
0
    case Div: op = " / "; pr = PR_TERM; break;
174
0
    case Mod: op = " % "; pr = PR_TERM; break;
175
0
    case LShift: op = " << "; pr = PR_SHIFT; break;
176
0
    case RShift: op = " >> "; pr = PR_SHIFT; break;
177
0
    case BitOr: op = " | "; pr = PR_BOR; break;
178
0
    case BitXor: op = " ^ "; pr = PR_BXOR; break;
179
0
    case BitAnd: op = " & "; pr = PR_BAND; break;
180
0
    case FloorDiv: op = " // "; pr = PR_TERM; break;
181
0
    case Pow: op = " ** "; pr = PR_POWER; rassoc = true; break;
182
0
    default:
183
0
        PyErr_SetString(PyExc_SystemError,
184
0
                        "unknown binary operator");
185
0
        return -1;
186
0
    }
187
188
0
    APPEND_STR_IF(level > pr, "(");
189
0
    APPEND_EXPR(e->v.BinOp.left, pr + rassoc);
190
0
    APPEND_STR(op);
191
0
    APPEND_EXPR(e->v.BinOp.right, pr + !rassoc);
192
0
    APPEND_STR_IF(level > pr, ")");
193
0
    return 0;
194
0
}
195
196
static int
197
append_ast_unaryop(PyUnicodeWriter *writer, expr_ty e, int level)
198
0
{
199
0
    const char *op;
200
0
    int pr;
201
202
0
    switch (e->v.UnaryOp.op) {
203
0
    case Invert: op = "~"; pr = PR_FACTOR; break;
204
0
    case Not: op = "not "; pr = PR_NOT; break;
205
0
    case UAdd: op = "+"; pr = PR_FACTOR; break;
206
0
    case USub: op = "-"; pr = PR_FACTOR; break;
207
0
    default:
208
0
        PyErr_SetString(PyExc_SystemError,
209
0
                        "unknown unary operator");
210
0
        return -1;
211
0
    }
212
213
0
    APPEND_STR_IF(level > pr, "(");
214
0
    APPEND_STR(op);
215
0
    APPEND_EXPR(e->v.UnaryOp.operand, pr);
216
0
    APPEND_STR_IF(level > pr, ")");
217
0
    return 0;
218
0
}
219
220
static int
221
append_ast_arg(PyUnicodeWriter *writer, arg_ty arg)
222
0
{
223
0
    if (PyUnicodeWriter_WriteStr(writer, arg->arg) < 0) {
224
0
        return -1;
225
0
    }
226
0
    if (arg->annotation) {
227
0
        APPEND_STR(": ");
228
0
        APPEND_EXPR(arg->annotation, PR_TEST);
229
0
    }
230
0
    return 0;
231
0
}
232
233
static int
234
append_ast_args(PyUnicodeWriter *writer, arguments_ty args)
235
0
{
236
0
    bool first;
237
0
    Py_ssize_t i, di, arg_count, posonlyarg_count, default_count;
238
239
0
    first = true;
240
241
    /* positional-only and positional arguments with defaults */
242
0
    posonlyarg_count = asdl_seq_LEN(args->posonlyargs);
243
0
    arg_count = asdl_seq_LEN(args->args);
244
0
    default_count = asdl_seq_LEN(args->defaults);
245
0
    for (i = 0; i < posonlyarg_count + arg_count; i++) {
246
0
        APPEND_STR_IF_NOT_FIRST(", ");
247
0
        if (i < posonlyarg_count){
248
0
            APPEND(arg, (arg_ty)asdl_seq_GET(args->posonlyargs, i));
249
0
        } else {
250
0
            APPEND(arg, (arg_ty)asdl_seq_GET(args->args, i-posonlyarg_count));
251
0
        }
252
253
0
        di = i - posonlyarg_count - arg_count + default_count;
254
0
        if (di >= 0) {
255
0
            APPEND_CHAR('=');
256
0
            APPEND_EXPR((expr_ty)asdl_seq_GET(args->defaults, di), PR_TEST);
257
0
        }
258
0
        if (posonlyarg_count && i + 1 == posonlyarg_count) {
259
0
            APPEND_STR(", /");
260
0
        }
261
0
    }
262
263
    /* vararg, or bare '*' if no varargs but keyword-only arguments present */
264
0
    if (args->vararg || asdl_seq_LEN(args->kwonlyargs)) {
265
0
        APPEND_STR_IF_NOT_FIRST(", ");
266
0
        APPEND_STR("*");
267
0
        if (args->vararg) {
268
0
            APPEND(arg, args->vararg);
269
0
        }
270
0
    }
271
272
    /* keyword-only arguments */
273
0
    arg_count = asdl_seq_LEN(args->kwonlyargs);
274
0
    default_count = asdl_seq_LEN(args->kw_defaults);
275
0
    for (i = 0; i < arg_count; i++) {
276
0
        APPEND_STR_IF_NOT_FIRST(", ");
277
0
        APPEND(arg, (arg_ty)asdl_seq_GET(args->kwonlyargs, i));
278
279
0
        di = i - arg_count + default_count;
280
0
        if (di >= 0) {
281
0
            expr_ty default_ = (expr_ty)asdl_seq_GET(args->kw_defaults, di);
282
0
            if (default_) {
283
0
                APPEND_CHAR('=');
284
0
                APPEND_EXPR(default_, PR_TEST);
285
0
            }
286
0
        }
287
0
    }
288
289
    /* **kwargs */
290
0
    if (args->kwarg) {
291
0
        APPEND_STR_IF_NOT_FIRST(", ");
292
0
        APPEND_STR("**");
293
0
        APPEND(arg, args->kwarg);
294
0
    }
295
296
0
    return 0;
297
0
}
298
299
static int
300
append_ast_lambda(PyUnicodeWriter *writer, expr_ty e, int level)
301
0
{
302
0
    APPEND_STR_IF(level > PR_TEST, "(");
303
0
    Py_ssize_t n_positional = (asdl_seq_LEN(e->v.Lambda.args->args) +
304
0
                               asdl_seq_LEN(e->v.Lambda.args->posonlyargs));
305
0
    APPEND_STR(n_positional ? "lambda " : "lambda");
306
0
    APPEND(args, e->v.Lambda.args);
307
0
    APPEND_STR(": ");
308
0
    APPEND_EXPR(e->v.Lambda.body, PR_TEST);
309
0
    APPEND_STR_IF(level > PR_TEST, ")");
310
0
    return 0;
311
0
}
312
313
static int
314
append_ast_ifexp(PyUnicodeWriter *writer, expr_ty e, int level)
315
0
{
316
0
    APPEND_STR_IF(level > PR_TEST, "(");
317
0
    APPEND_EXPR(e->v.IfExp.body, PR_TEST + 1);
318
0
    APPEND_STR(" if ");
319
0
    APPEND_EXPR(e->v.IfExp.test, PR_TEST + 1);
320
0
    APPEND_STR(" else ");
321
0
    APPEND_EXPR(e->v.IfExp.orelse, PR_TEST);
322
0
    APPEND_STR_IF(level > PR_TEST, ")");
323
0
    return 0;
324
0
}
325
326
static int
327
append_ast_dict(PyUnicodeWriter *writer, expr_ty e)
328
0
{
329
0
    Py_ssize_t i, value_count;
330
0
    expr_ty key_node;
331
332
0
    APPEND_CHAR('{');
333
0
    value_count = asdl_seq_LEN(e->v.Dict.values);
334
335
0
    for (i = 0; i < value_count; i++) {
336
0
        APPEND_STR_IF(i > 0, ", ");
337
0
        key_node = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i);
338
0
        if (key_node != NULL) {
339
0
            APPEND_EXPR(key_node, PR_TEST);
340
0
            APPEND_STR(": ");
341
0
            APPEND_EXPR((expr_ty)asdl_seq_GET(e->v.Dict.values, i), PR_TEST);
342
0
        }
343
0
        else {
344
0
            APPEND_STR("**");
345
0
            APPEND_EXPR((expr_ty)asdl_seq_GET(e->v.Dict.values, i), PR_EXPR);
346
0
        }
347
0
    }
348
349
0
    APPEND_CHAR_FINISH('}');
350
0
}
351
352
static int
353
append_ast_set(PyUnicodeWriter *writer, expr_ty e)
354
0
{
355
0
    Py_ssize_t i, elem_count;
356
357
0
    APPEND_CHAR('{');
358
0
    elem_count = asdl_seq_LEN(e->v.Set.elts);
359
0
    for (i = 0; i < elem_count; i++) {
360
0
        APPEND_STR_IF(i > 0, ", ");
361
0
        APPEND_EXPR((expr_ty)asdl_seq_GET(e->v.Set.elts, i), PR_TEST);
362
0
    }
363
364
0
    APPEND_CHAR_FINISH('}');
365
0
}
366
367
static int
368
append_ast_list(PyUnicodeWriter *writer, expr_ty e)
369
0
{
370
0
    Py_ssize_t i, elem_count;
371
372
0
    APPEND_CHAR('[');
373
0
    elem_count = asdl_seq_LEN(e->v.List.elts);
374
0
    for (i = 0; i < elem_count; i++) {
375
0
        APPEND_STR_IF(i > 0, ", ");
376
0
        APPEND_EXPR((expr_ty)asdl_seq_GET(e->v.List.elts, i), PR_TEST);
377
0
    }
378
379
0
    APPEND_CHAR_FINISH(']');
380
0
}
381
382
static int
383
append_ast_tuple(PyUnicodeWriter *writer, expr_ty e, int level)
384
0
{
385
0
    Py_ssize_t i, elem_count;
386
387
0
    elem_count = asdl_seq_LEN(e->v.Tuple.elts);
388
389
0
    if (elem_count == 0) {
390
0
        APPEND_STR_FINISH("()");
391
0
    }
392
393
0
    APPEND_STR_IF(level > PR_TUPLE, "(");
394
395
0
    for (i = 0; i < elem_count; i++) {
396
0
        APPEND_STR_IF(i > 0, ", ");
397
0
        APPEND_EXPR((expr_ty)asdl_seq_GET(e->v.Tuple.elts, i), PR_TEST);
398
0
    }
399
400
0
    APPEND_STR_IF(elem_count == 1, ",");
401
0
    APPEND_STR_IF(level > PR_TUPLE, ")");
402
0
    return 0;
403
0
}
404
405
static int
406
append_ast_comprehension(PyUnicodeWriter *writer, comprehension_ty gen)
407
0
{
408
0
    Py_ssize_t i, if_count;
409
410
0
    APPEND_STR(gen->is_async ? " async for " : " for ");
411
0
    APPEND_EXPR(gen->target, PR_TUPLE);
412
0
    APPEND_STR(" in ");
413
0
    APPEND_EXPR(gen->iter, PR_TEST + 1);
414
415
0
    if_count = asdl_seq_LEN(gen->ifs);
416
0
    for (i = 0; i < if_count; i++) {
417
0
        APPEND_STR(" if ");
418
0
        APPEND_EXPR((expr_ty)asdl_seq_GET(gen->ifs, i), PR_TEST + 1);
419
0
    }
420
0
    return 0;
421
0
}
422
423
static int
424
append_ast_comprehensions(PyUnicodeWriter *writer, asdl_comprehension_seq *comprehensions)
425
0
{
426
0
    Py_ssize_t i, gen_count;
427
0
    gen_count = asdl_seq_LEN(comprehensions);
428
429
0
    for (i = 0; i < gen_count; i++) {
430
0
        APPEND(comprehension, (comprehension_ty)asdl_seq_GET(comprehensions, i));
431
0
    }
432
433
0
    return 0;
434
0
}
435
436
static int
437
append_ast_genexp(PyUnicodeWriter *writer, expr_ty e)
438
0
{
439
0
    APPEND_CHAR('(');
440
0
    APPEND_EXPR(e->v.GeneratorExp.elt, PR_TEST);
441
0
    APPEND(comprehensions, e->v.GeneratorExp.generators);
442
0
    APPEND_CHAR_FINISH(')');
443
0
}
444
445
static int
446
append_ast_listcomp(PyUnicodeWriter *writer, expr_ty e)
447
0
{
448
0
    APPEND_CHAR('[');
449
0
    APPEND_EXPR(e->v.ListComp.elt, PR_TEST);
450
0
    APPEND(comprehensions, e->v.ListComp.generators);
451
0
    APPEND_CHAR_FINISH(']');
452
0
}
453
454
static int
455
append_ast_setcomp(PyUnicodeWriter *writer, expr_ty e)
456
0
{
457
0
    APPEND_CHAR('{');
458
0
    APPEND_EXPR(e->v.SetComp.elt, PR_TEST);
459
0
    APPEND(comprehensions, e->v.SetComp.generators);
460
0
    APPEND_CHAR_FINISH('}');
461
0
}
462
463
static int
464
append_ast_dictcomp(PyUnicodeWriter *writer, expr_ty e)
465
0
{
466
0
    APPEND_CHAR('{');
467
0
    if (e->v.DictComp.value) {
468
0
        APPEND_EXPR(e->v.DictComp.key, PR_TEST);
469
0
        APPEND_STR(": ");
470
0
        APPEND_EXPR(e->v.DictComp.value, PR_TEST);
471
0
    }
472
0
    else {
473
0
        APPEND_STR("**");
474
0
        APPEND_EXPR(e->v.DictComp.key, PR_TEST);
475
0
    }
476
0
    APPEND(comprehensions, e->v.DictComp.generators);
477
0
    APPEND_CHAR_FINISH('}');
478
0
}
479
480
static int
481
append_ast_compare(PyUnicodeWriter *writer, expr_ty e, int level)
482
0
{
483
0
    const char *op;
484
0
    Py_ssize_t i, comparator_count;
485
0
    asdl_expr_seq *comparators;
486
0
    asdl_int_seq *ops;
487
488
0
    APPEND_STR_IF(level > PR_CMP, "(");
489
490
0
    comparators = e->v.Compare.comparators;
491
0
    ops = e->v.Compare.ops;
492
0
    comparator_count = asdl_seq_LEN(comparators);
493
0
    assert(comparator_count > 0);
494
0
    assert(comparator_count == asdl_seq_LEN(ops));
495
496
0
    APPEND_EXPR(e->v.Compare.left, PR_CMP + 1);
497
498
0
    for (i = 0; i < comparator_count; i++) {
499
0
        switch ((cmpop_ty)asdl_seq_GET(ops, i)) {
500
0
        case Eq:
501
0
            op = " == ";
502
0
            break;
503
0
        case NotEq:
504
0
            op = " != ";
505
0
            break;
506
0
        case Lt:
507
0
            op = " < ";
508
0
            break;
509
0
        case LtE:
510
0
            op = " <= ";
511
0
            break;
512
0
        case Gt:
513
0
            op = " > ";
514
0
            break;
515
0
        case GtE:
516
0
            op = " >= ";
517
0
            break;
518
0
        case Is:
519
0
            op = " is ";
520
0
            break;
521
0
        case IsNot:
522
0
            op = " is not ";
523
0
            break;
524
0
        case In:
525
0
            op = " in ";
526
0
            break;
527
0
        case NotIn:
528
0
            op = " not in ";
529
0
            break;
530
0
        default:
531
0
            PyErr_SetString(PyExc_SystemError,
532
0
                            "unexpected comparison kind");
533
0
            return -1;
534
0
        }
535
536
0
        APPEND_STR(op);
537
0
        APPEND_EXPR((expr_ty)asdl_seq_GET(comparators, i), PR_CMP + 1);
538
0
    }
539
540
0
    APPEND_STR_IF(level > PR_CMP, ")");
541
0
    return 0;
542
0
}
543
544
static int
545
append_ast_keyword(PyUnicodeWriter *writer, keyword_ty kw)
546
0
{
547
0
    if (kw->arg == NULL) {
548
0
        APPEND_STR("**");
549
0
    }
550
0
    else {
551
0
        if (-1 == PyUnicodeWriter_WriteStr(writer, kw->arg)) {
552
0
            return -1;
553
0
        }
554
555
0
        APPEND_CHAR('=');
556
0
    }
557
558
0
    APPEND_EXPR(kw->value, PR_TEST);
559
0
    return 0;
560
0
}
561
562
static int
563
append_ast_call(PyUnicodeWriter *writer, expr_ty e)
564
0
{
565
0
    bool first;
566
0
    Py_ssize_t i, arg_count, kw_count;
567
0
    expr_ty expr;
568
569
0
    APPEND_EXPR(e->v.Call.func, PR_ATOM);
570
571
0
    arg_count = asdl_seq_LEN(e->v.Call.args);
572
0
    kw_count = asdl_seq_LEN(e->v.Call.keywords);
573
0
    if (arg_count == 1 && kw_count == 0) {
574
0
        expr = (expr_ty)asdl_seq_GET(e->v.Call.args, 0);
575
0
        if (expr->kind == GeneratorExp_kind) {
576
            /* Special case: a single generator expression. */
577
0
            return append_ast_genexp(writer, expr);
578
0
        }
579
0
    }
580
581
0
    APPEND_CHAR('(');
582
583
0
    first = true;
584
0
    for (i = 0; i < arg_count; i++) {
585
0
        APPEND_STR_IF_NOT_FIRST(", ");
586
0
        APPEND_EXPR((expr_ty)asdl_seq_GET(e->v.Call.args, i), PR_TEST);
587
0
    }
588
589
0
    for (i = 0; i < kw_count; i++) {
590
0
        APPEND_STR_IF_NOT_FIRST(", ");
591
0
        APPEND(keyword, (keyword_ty)asdl_seq_GET(e->v.Call.keywords, i));
592
0
    }
593
594
0
    APPEND_CHAR_FINISH(')');
595
0
}
596
597
static PyObject *
598
escape_braces(PyObject *orig)
599
0
{
600
0
    PyObject *temp;
601
0
    PyObject *result;
602
0
    temp = PyUnicode_Replace(orig, _Py_LATIN1_CHR('{'),
603
0
                             &_Py_STR(dbl_open_br), -1);
604
0
    if (!temp) {
605
0
        return NULL;
606
0
    }
607
0
    result = PyUnicode_Replace(temp, _Py_LATIN1_CHR('}'),
608
0
                               &_Py_STR(dbl_close_br), -1);
609
0
    Py_DECREF(temp);
610
0
    return result;
611
0
}
612
613
static int
614
append_fstring_unicode(PyUnicodeWriter *writer, PyObject *unicode)
615
0
{
616
0
    PyObject *escaped;
617
0
    int result = -1;
618
0
    escaped = escape_braces(unicode);
619
0
    if (escaped) {
620
0
        result = PyUnicodeWriter_WriteStr(writer, escaped);
621
0
        Py_DECREF(escaped);
622
0
    }
623
0
    return result;
624
0
}
625
626
static int
627
append_fstring_element(PyUnicodeWriter *writer, expr_ty e, bool is_format_spec)
628
0
{
629
0
    switch (e->kind) {
630
0
    case Constant_kind:
631
0
        return append_fstring_unicode(writer, e->v.Constant.value);
632
0
    case JoinedStr_kind:
633
0
        return append_joinedstr(writer, e, is_format_spec);
634
0
    case TemplateStr_kind:
635
0
        return append_templatestr(writer, e);
636
0
    case FormattedValue_kind:
637
0
        return append_formattedvalue(writer, e);
638
0
    case Interpolation_kind:
639
0
        return append_interpolation(writer, e);
640
0
    default:
641
0
        PyErr_SetString(PyExc_SystemError,
642
0
                        "unknown expression kind inside f-string or t-string");
643
0
        return -1;
644
0
    }
645
0
}
646
647
/* Build body separately to enable wrapping the entire stream of Strs,
648
   Constants and FormattedValues in one opening and one closing quote. */
649
static PyObject *
650
build_ftstring_body(asdl_expr_seq *values, bool is_format_spec)
651
0
{
652
0
    PyUnicodeWriter *body_writer = PyUnicodeWriter_Create(256);
653
0
    if (body_writer == NULL) {
654
0
        return NULL;
655
0
    }
656
657
0
    Py_ssize_t value_count = asdl_seq_LEN(values);
658
0
    for (Py_ssize_t i = 0; i < value_count; ++i) {
659
0
        if (-1 == append_fstring_element(body_writer,
660
0
                                         (expr_ty)asdl_seq_GET(values, i),
661
0
                                         is_format_spec
662
0
                                         )) {
663
0
            PyUnicodeWriter_Discard(body_writer);
664
0
            return NULL;
665
0
        }
666
0
    }
667
668
0
    return PyUnicodeWriter_Finish(body_writer);
669
0
}
670
671
static int
672
append_templatestr(PyUnicodeWriter *writer, expr_ty e)
673
0
{
674
0
    int result = -1;
675
0
    PyObject *body = build_ftstring_body(e->v.TemplateStr.values, false);
676
0
    if (!body) {
677
0
        return -1;
678
0
    }
679
680
0
    if (-1 != append_charp(writer, "t") &&
681
0
        -1 != append_repr(writer, body))
682
0
    {
683
0
        result = 0;
684
0
    }
685
0
    Py_DECREF(body);
686
0
    return result;
687
0
}
688
689
static int
690
append_joinedstr(PyUnicodeWriter *writer, expr_ty e, bool is_format_spec)
691
0
{
692
0
    int result = -1;
693
0
    PyObject *body = build_ftstring_body(e->v.JoinedStr.values, is_format_spec);
694
0
    if (!body) {
695
0
        return -1;
696
0
    }
697
698
0
    if (!is_format_spec) {
699
0
        if (-1 != append_charp(writer, "f") &&
700
0
            -1 != append_repr(writer, body))
701
0
        {
702
0
            result = 0;
703
0
        }
704
0
    }
705
0
    else {
706
0
        result = PyUnicodeWriter_WriteStr(writer, body);
707
0
    }
708
0
    Py_DECREF(body);
709
0
    return result;
710
0
}
711
712
static int
713
append_interpolation_str(PyUnicodeWriter *writer, PyObject *str)
714
0
{
715
0
    const char *outer_brace = "{";
716
0
    if (PyUnicode_Find(str, _Py_LATIN1_CHR('{'), 0, 1, 1) == 0) {
717
        /* Expression starts with a brace, split it with a space from the outer
718
           one. */
719
0
        outer_brace = "{ ";
720
0
    }
721
0
    if (-1 == append_charp(writer, outer_brace)) {
722
0
        return -1;
723
0
    }
724
0
    if (-1 == PyUnicodeWriter_WriteStr(writer, str)) {
725
0
        return -1;
726
0
    }
727
0
    return 0;
728
0
}
729
730
static int
731
append_interpolation_value(PyUnicodeWriter *writer, expr_ty e)
732
0
{
733
    /* Grammar allows PR_TUPLE, but use >PR_TEST for adding parenthesis
734
       around a lambda with ':' */
735
0
    PyObject *temp_fv_str = expr_as_unicode(e, PR_TEST + 1);
736
0
    if (!temp_fv_str) {
737
0
        return -1;
738
0
    }
739
0
    int result = append_interpolation_str(writer, temp_fv_str);
740
0
    Py_DECREF(temp_fv_str);
741
0
    return result;
742
0
}
743
744
static int
745
append_interpolation_conversion(PyUnicodeWriter *writer, int conversion)
746
0
{
747
0
    if (conversion < 0) {
748
0
        return 0;
749
0
    }
750
751
0
    const char *conversion_str;
752
0
    switch (conversion) {
753
0
    case 'a':
754
0
        conversion_str = "!a";
755
0
        break;
756
0
    case 'r':
757
0
        conversion_str = "!r";
758
0
        break;
759
0
    case 's':
760
0
        conversion_str = "!s";
761
0
        break;
762
0
    default:
763
0
        PyErr_SetString(PyExc_SystemError,
764
0
                        "unknown f-value conversion kind");
765
0
        return -1;
766
0
    }
767
0
    APPEND_STR(conversion_str);
768
0
    return 0;
769
0
}
770
771
static int
772
append_interpolation_format_spec(PyUnicodeWriter *writer, expr_ty e)
773
0
{
774
0
    if (e) {
775
0
        if (-1 == PyUnicodeWriter_WriteChar(writer, ':') ||
776
0
            -1 == append_fstring_element(writer, e, true))
777
0
        {
778
0
            return -1;
779
0
        }
780
0
    }
781
0
    return 0;
782
0
}
783
784
static int
785
append_interpolation(PyUnicodeWriter *writer, expr_ty e)
786
0
{
787
0
    if (-1 == append_interpolation_str(writer, e->v.Interpolation.str)) {
788
0
        return -1;
789
0
    }
790
791
0
    if (-1 == append_interpolation_conversion(writer, e->v.Interpolation.conversion)) {
792
0
        return -1;
793
0
    }
794
795
0
    if (-1 == append_interpolation_format_spec(writer, e->v.Interpolation.format_spec)) {
796
0
        return -1;
797
0
    }
798
799
0
    APPEND_STR_FINISH("}");
800
0
}
801
802
static int
803
append_formattedvalue(PyUnicodeWriter *writer, expr_ty e)
804
0
{
805
0
    if (-1 == append_interpolation_value(writer, e->v.FormattedValue.value)) {
806
0
        return -1;
807
0
    }
808
809
0
    if (-1 == append_interpolation_conversion(writer, e->v.FormattedValue.conversion)) {
810
0
        return -1;
811
0
    }
812
813
0
    if (-1 == append_interpolation_format_spec(writer, e->v.FormattedValue.format_spec)) {
814
0
        return -1;
815
0
    }
816
817
0
    APPEND_CHAR_FINISH('}');
818
0
}
819
820
static int
821
append_ast_constant(PyUnicodeWriter *writer, PyObject *constant)
822
0
{
823
0
    if (PyTuple_CheckExact(constant)) {
824
0
        Py_ssize_t i, elem_count;
825
826
0
        elem_count = PyTuple_GET_SIZE(constant);
827
0
        APPEND_CHAR('(');
828
0
        for (i = 0; i < elem_count; i++) {
829
0
            APPEND_STR_IF(i > 0, ", ");
830
0
            if (append_ast_constant(writer, PyTuple_GET_ITEM(constant, i)) < 0) {
831
0
                return -1;
832
0
            }
833
0
        }
834
835
0
        APPEND_STR_IF(elem_count == 1, ",");
836
0
        APPEND_CHAR_FINISH(')');
837
0
    }
838
0
    return append_repr(writer, constant);
839
0
}
840
841
static int
842
append_ast_attribute(PyUnicodeWriter *writer, expr_ty e)
843
0
{
844
0
    const char *period;
845
0
    expr_ty v = e->v.Attribute.value;
846
0
    APPEND_EXPR(v, PR_ATOM);
847
848
    /* Special case: integers require a space for attribute access to be
849
       unambiguous. */
850
0
    if (v->kind == Constant_kind && PyLong_CheckExact(v->v.Constant.value)) {
851
0
        period = " .";
852
0
    }
853
0
    else {
854
0
        period = ".";
855
0
    }
856
0
    APPEND_STR(period);
857
858
0
    return PyUnicodeWriter_WriteStr(writer, e->v.Attribute.attr);
859
0
}
860
861
static int
862
append_ast_slice(PyUnicodeWriter *writer, expr_ty e)
863
0
{
864
0
    if (e->v.Slice.lower) {
865
0
        APPEND_EXPR(e->v.Slice.lower, PR_TEST);
866
0
    }
867
868
0
    APPEND_CHAR(':');
869
870
0
    if (e->v.Slice.upper) {
871
0
        APPEND_EXPR(e->v.Slice.upper, PR_TEST);
872
0
    }
873
874
0
    if (e->v.Slice.step) {
875
0
        APPEND_CHAR(':');
876
0
        APPEND_EXPR(e->v.Slice.step, PR_TEST);
877
0
    }
878
0
    return 0;
879
0
}
880
881
static int
882
append_ast_subscript(PyUnicodeWriter *writer, expr_ty e)
883
0
{
884
0
    APPEND_EXPR(e->v.Subscript.value, PR_ATOM);
885
0
    APPEND_CHAR('[');
886
0
    APPEND_EXPR(e->v.Subscript.slice, PR_TUPLE);
887
0
    APPEND_CHAR_FINISH(']');
888
0
}
889
890
static int
891
append_ast_starred(PyUnicodeWriter *writer, expr_ty e)
892
0
{
893
0
    APPEND_CHAR('*');
894
0
    APPEND_EXPR(e->v.Starred.value, PR_EXPR);
895
0
    return 0;
896
0
}
897
898
static int
899
append_ast_yield(PyUnicodeWriter *writer, expr_ty e)
900
0
{
901
0
    if (!e->v.Yield.value) {
902
0
        APPEND_STR_FINISH("(yield)");
903
0
    }
904
905
0
    APPEND_STR("(yield ");
906
0
    APPEND_EXPR(e->v.Yield.value, PR_TEST);
907
0
    APPEND_CHAR_FINISH(')');
908
0
}
909
910
static int
911
append_ast_yield_from(PyUnicodeWriter *writer, expr_ty e)
912
0
{
913
0
    APPEND_STR("(yield from ");
914
0
    APPEND_EXPR(e->v.YieldFrom.value, PR_TEST);
915
0
    APPEND_CHAR_FINISH(')');
916
0
}
917
918
static int
919
append_ast_await(PyUnicodeWriter *writer, expr_ty e, int level)
920
0
{
921
0
    APPEND_STR_IF(level > PR_AWAIT, "(");
922
0
    APPEND_STR("await ");
923
0
    APPEND_EXPR(e->v.Await.value, PR_ATOM);
924
0
    APPEND_STR_IF(level > PR_AWAIT, ")");
925
0
    return 0;
926
0
}
927
928
static int
929
append_named_expr(PyUnicodeWriter *writer, expr_ty e, int level)
930
0
{
931
0
    APPEND_STR_IF(level > PR_TUPLE, "(");
932
0
    APPEND_EXPR(e->v.NamedExpr.target, PR_ATOM);
933
0
    APPEND_STR(" := ");
934
0
    APPEND_EXPR(e->v.NamedExpr.value, PR_ATOM);
935
0
    APPEND_STR_IF(level > PR_TUPLE, ")");
936
0
    return 0;
937
0
}
938
939
static int
940
append_ast_expr(PyUnicodeWriter *writer, expr_ty e, int level)
941
0
{
942
0
    switch (e->kind) {
943
0
    case BoolOp_kind:
944
0
        return append_ast_boolop(writer, e, level);
945
0
    case BinOp_kind:
946
0
        return append_ast_binop(writer, e, level);
947
0
    case UnaryOp_kind:
948
0
        return append_ast_unaryop(writer, e, level);
949
0
    case Lambda_kind:
950
0
        return append_ast_lambda(writer, e, level);
951
0
    case IfExp_kind:
952
0
        return append_ast_ifexp(writer, e, level);
953
0
    case Dict_kind:
954
0
        return append_ast_dict(writer, e);
955
0
    case Set_kind:
956
0
        return append_ast_set(writer, e);
957
0
    case GeneratorExp_kind:
958
0
        return append_ast_genexp(writer, e);
959
0
    case ListComp_kind:
960
0
        return append_ast_listcomp(writer, e);
961
0
    case SetComp_kind:
962
0
        return append_ast_setcomp(writer, e);
963
0
    case DictComp_kind:
964
0
        return append_ast_dictcomp(writer, e);
965
0
    case Yield_kind:
966
0
        return append_ast_yield(writer, e);
967
0
    case YieldFrom_kind:
968
0
        return append_ast_yield_from(writer, e);
969
0
    case Await_kind:
970
0
        return append_ast_await(writer, e, level);
971
0
    case Compare_kind:
972
0
        return append_ast_compare(writer, e, level);
973
0
    case Call_kind:
974
0
        return append_ast_call(writer, e);
975
0
    case Constant_kind:
976
0
        if (e->v.Constant.value == Py_Ellipsis) {
977
0
            APPEND_STR_FINISH("...");
978
0
        }
979
0
        if (e->v.Constant.kind != NULL
980
0
            && -1 == PyUnicodeWriter_WriteStr(writer, e->v.Constant.kind)) {
981
0
            return -1;
982
0
        }
983
0
        return append_ast_constant(writer, e->v.Constant.value);
984
0
    case JoinedStr_kind:
985
0
        return append_joinedstr(writer, e, false);
986
0
    case TemplateStr_kind:
987
0
        return append_templatestr(writer, e);
988
0
    case FormattedValue_kind:
989
0
        return append_formattedvalue(writer, e);
990
0
    case Interpolation_kind:
991
0
        return append_interpolation(writer, e);
992
    /* The following exprs can be assignment targets. */
993
0
    case Attribute_kind:
994
0
        return append_ast_attribute(writer, e);
995
0
    case Subscript_kind:
996
0
        return append_ast_subscript(writer, e);
997
0
    case Starred_kind:
998
0
        return append_ast_starred(writer, e);
999
0
    case Slice_kind:
1000
0
        return append_ast_slice(writer, e);
1001
0
    case Name_kind:
1002
0
        return PyUnicodeWriter_WriteStr(writer, e->v.Name.id);
1003
0
    case List_kind:
1004
0
        return append_ast_list(writer, e);
1005
0
    case Tuple_kind:
1006
0
        return append_ast_tuple(writer, e, level);
1007
0
    case NamedExpr_kind:
1008
0
        return append_named_expr(writer, e, level);
1009
    // No default so compiler emits a warning for unhandled cases
1010
0
    }
1011
0
    PyErr_SetString(PyExc_SystemError,
1012
0
                    "unknown expression kind");
1013
0
    return -1;
1014
0
}
1015
1016
static PyObject *
1017
expr_as_unicode(expr_ty e, int level)
1018
0
{
1019
0
    PyUnicodeWriter *writer = PyUnicodeWriter_Create(256);
1020
0
    if (writer == NULL) {
1021
0
        return NULL;
1022
0
    }
1023
1024
0
    if (-1 == append_ast_expr(writer, e, level)) {
1025
0
        PyUnicodeWriter_Discard(writer);
1026
0
        return NULL;
1027
0
    }
1028
0
    return PyUnicodeWriter_Finish(writer);
1029
0
}
1030
1031
PyObject *
1032
_PyAST_ExprAsUnicode(expr_ty e)
1033
0
{
1034
0
    return expr_as_unicode(e, PR_TEST);
1035
0
}