Coverage Report

Created: 2025-10-12 06:40

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