summaryrefslogtreecommitdiffstats
path: root/Python/ast_unparse.c
blob: af9604eb45b18366e30d6bc1630d9d53e51d5e56 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
#include <stdbool.h>
#include "Python.h"
#include "Python-ast.h"

static PyObject *_str_open_br;
static PyObject *_str_dbl_open_br;
static PyObject *_str_close_br;
static PyObject *_str_dbl_close_br;

/* Forward declarations for recursion via helper functions. */
static PyObject *
expr_as_unicode(expr_ty e, int level);
static int
append_ast_expr(_PyUnicodeWriter *writer, expr_ty e, int level);
static int
append_joinedstr(_PyUnicodeWriter *writer, expr_ty e, bool is_format_spec);
static int
append_formattedvalue(_PyUnicodeWriter *writer, expr_ty e, bool is_format_spec);
static int
append_ast_slice(_PyUnicodeWriter *writer, slice_ty slice);

static int
append_charp(_PyUnicodeWriter *writer, const char *charp)
{
    return _PyUnicodeWriter_WriteASCIIString(writer, charp, -1);
}

#define APPEND_STR_FINISH(str)  do { \
        return append_charp(writer, (str)); \
    } while (0)

#define APPEND_STR(str)  do { \
        if (-1 == append_charp(writer, (str))) { \
            return -1; \
        } \
    } while (0)

#define APPEND_STR_IF(cond, str)  do { \
        if ((cond) && -1 == append_charp(writer, (str))) { \
            return -1; \
        } \
    } while (0)

#define APPEND_STR_IF_NOT_FIRST(str)  do { \
        APPEND_STR_IF(!first, (str)); \
        first = false; \
    } while (0)

#define APPEND_EXPR(expr, pr)  do { \
        if (-1 == append_ast_expr(writer, (expr), (pr))) { \
            return -1; \
        } \
    } while (0)

#define APPEND(type, value)  do { \
        if (-1 == append_ast_ ## type(writer, (value))) { \
            return -1; \
        } \
    } while (0)

static int
append_repr(_PyUnicodeWriter *writer, PyObject *obj)
{
    int ret;
    PyObject *repr;
    repr = PyObject_Repr(obj);
    if (!repr) {
        return -1;
    }
    ret = _PyUnicodeWriter_WriteStr(writer, repr);
    Py_DECREF(repr);
    return ret;
}

/* Priority levels */

enum {
    PR_TUPLE,
    PR_TEST,            /* 'if'-'else', 'lambda' */
    PR_OR,              /* 'or' */
    PR_AND,             /* 'and' */
    PR_NOT,             /* 'not' */
    PR_CMP,             /* '<', '>', '==', '>=', '<=', '!=',
                           'in', 'not in', 'is', 'is not' */
    PR_EXPR,
    PR_BOR = PR_EXPR,   /* '|' */
    PR_BXOR,            /* '^' */
    PR_BAND,            /* '&' */
    PR_SHIFT,           /* '<<', '>>' */
    PR_ARITH,           /* '+', '-' */
    PR_TERM,            /* '*', '@', '/', '%', '//' */
    PR_FACTOR,          /* unary '+', '-', '~' */
    PR_POWER,           /* '**' */
    PR_AWAIT,           /* 'await' */
    PR_ATOM,
};

static int
append_ast_boolop(_PyUnicodeWriter *writer, expr_ty e, int level)
{
    Py_ssize_t i, value_count;
    asdl_seq *values;
    const char *op = (e->v.BoolOp.op == And) ? " and " : " or ";
    int pr = (e->v.BoolOp.op == And) ? PR_AND : PR_OR;

    APPEND_STR_IF(level > pr, "(");

    values = e->v.BoolOp.values;
    value_count = asdl_seq_LEN(values);

    for (i = 0; i < value_count; ++i) {
        APPEND_STR_IF(i > 0, op);
        APPEND_EXPR((expr_ty)asdl_seq_GET(values, i), pr + 1);
    }

    APPEND_STR_IF(level > pr, ")");
    return 0;
}

static int
append_ast_binop(_PyUnicodeWriter *writer, expr_ty e, int level)
{
    const char *op;
    int pr;
    bool rassoc = false;  /* is right-associative? */

    switch (e->v.BinOp.op) {
    case Add: op = " + "; pr = PR_ARITH; break;
    case Sub: op = " - "; pr = PR_ARITH; break;
    case Mult: op = " * "; pr = PR_TERM; break;
    case MatMult: op = " @ "; pr = PR_TERM; break;
    case Div: op = " / "; pr = PR_TERM; break;
    case Mod: op = " % "; pr = PR_TERM; break;
    case LShift: op = " << "; pr = PR_SHIFT; break;
    case RShift: op = " >> "; pr = PR_SHIFT; break;
    case BitOr: op = " | "; pr = PR_BOR; break;
    case BitXor: op = " ^ "; pr = PR_BXOR; break;
    case BitAnd: op = " & "; pr = PR_BAND; break;
    case FloorDiv: op = " // "; pr = PR_TERM; break;
    case Pow: op = " ** "; pr = PR_POWER; rassoc = true; break;
    default:
        PyErr_SetString(PyExc_SystemError,
                        "unknown binary operator");
        return -1;
    }

    APPEND_STR_IF(level > pr, "(");
    APPEND_EXPR(e->v.BinOp.left, pr + rassoc);
    APPEND_STR(op);
    APPEND_EXPR(e->v.BinOp.right, pr + !rassoc);
    APPEND_STR_IF(level > pr, ")");
    return 0;
}

static int
append_ast_unaryop(_PyUnicodeWriter *writer, expr_ty e, int level)
{
    const char *op;
    int pr;

    switch (e->v.UnaryOp.op) {
    case Invert: op = "~"; pr = PR_FACTOR; break;
    case Not: op = "not "; pr = PR_NOT; break;
    case UAdd: op = "+"; pr = PR_FACTOR; break;
    case USub: op = "-"; pr = PR_FACTOR; break;
    default:
        PyErr_SetString(PyExc_SystemError,
                        "unknown unary operator");
        return -1;
    }

    APPEND_STR_IF(level > pr, "(");
    APPEND_STR(op);
    APPEND_EXPR(e->v.UnaryOp.operand, pr);
    APPEND_STR_IF(level > pr, ")");
    return 0;
}

static int
append_ast_arg(_PyUnicodeWriter *writer, arg_ty arg)
{
    if (-1 == _PyUnicodeWriter_WriteStr(writer, arg->arg)) {
        return -1;
    }
    if (arg->annotation) {
        APPEND_STR(": ");
        APPEND_EXPR(arg->annotation, PR_TEST);
    }
    return 0;
}

static int
append_ast_args(_PyUnicodeWriter *writer, arguments_ty args)
{
    bool first;
    Py_ssize_t i, di, arg_count, posonlyarg_count, default_count;

    first = true;

    /* positional-only and positional arguments with defaults */
    posonlyarg_count = asdl_seq_LEN(args->posonlyargs);
    arg_count = asdl_seq_LEN(args->args);
    default_count = asdl_seq_LEN(args->defaults);
    for (i = 0; i < posonlyarg_count + arg_count; i++) {
        APPEND_STR_IF_NOT_FIRST(", ");
        if (i < posonlyarg_count){
            APPEND(arg, (arg_ty)asdl_seq_GET(args->posonlyargs, i));
        } else {
            APPEND(arg, (arg_ty)asdl_seq_GET(args->args, i-posonlyarg_count));
        }

        di = i - posonlyarg_count - arg_count + default_count;
        if (di >= 0) {
            APPEND_STR("=");
            APPEND_EXPR((expr_ty)asdl_seq_GET(args->defaults, di), PR_TEST);
        }
        if (posonlyarg_count && i + 1 == posonlyarg_count) {
            APPEND_STR(", /");
        }
    }

    /* vararg, or bare '*' if no varargs but keyword-only arguments present */
    if (args->vararg || asdl_seq_LEN(args->kwonlyargs)) {
        APPEND_STR_IF_NOT_FIRST(", ");
        APPEND_STR("*");
        if (args->vararg) {
            APPEND(arg, args->vararg);
        }
    }

    /* keyword-only arguments */
    arg_count = asdl_seq_LEN(args->kwonlyargs);
    default_count = asdl_seq_LEN(args->kw_defaults);
    for (i = 0; i < arg_count; i++) {
        APPEND_STR_IF_NOT_FIRST(", ");
        APPEND(arg, (arg_ty)asdl_seq_GET(args->kwonlyargs, i));

        di = i - arg_count + default_count;
        if (di >= 0) {
            expr_ty default_ = (expr_ty)asdl_seq_GET(args->kw_defaults, di);
            if (default_) {
                APPEND_STR("=");
                APPEND_EXPR(default_, PR_TEST);
            }
        }
    }

    /* **kwargs */
    if (args->kwarg) {
        APPEND_STR_IF_NOT_FIRST(", ");
        APPEND_STR("**");
        APPEND(arg, args->kwarg);
    }

    return 0;
}

static int
append_ast_lambda(_PyUnicodeWriter *writer, expr_ty e, int level)
{
    APPEND_STR_IF(level > PR_TEST, "(");
    Py_ssize_t n_positional = (asdl_seq_LEN(e->v.Lambda.args->args) +
                               asdl_seq_LEN(e->v.Lambda.args->posonlyargs));
    APPEND_STR(n_positional ? "lambda " : "lambda");
    APPEND(args, e->v.Lambda.args);
    APPEND_STR(": ");
    APPEND_EXPR(e->v.Lambda.body, PR_TEST);
    APPEND_STR_IF(level > PR_TEST, ")");
    return 0;
}

static int
append_ast_ifexp(_PyUnicodeWriter *writer, expr_ty e, int level)
{
    APPEND_STR_IF(level > PR_TEST, "(");
    APPEND_EXPR(e->v.IfExp.body, PR_TEST + 1);
    APPEND_STR(" if ");
    APPEND_EXPR(e->v.IfExp.test, PR_TEST + 1);
    APPEND_STR(" else ");
    APPEND_EXPR(e->v.IfExp.orelse, PR_TEST);
    APPEND_STR_IF(level > PR_TEST, ")");
    return 0;
}

static int
append_ast_dict(_PyUnicodeWriter *writer, expr_ty e)
{
    Py_ssize_t i, value_count;
    expr_ty key_node;

    APPEND_STR("{");
    value_count = asdl_seq_LEN(e->v.Dict.values);

    for (i = 0; i < value_count; i++) {
        APPEND_STR_IF(i > 0, ", ");
        key_node = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i);
        if (key_node != NULL) {
            APPEND_EXPR(key_node, PR_TEST);
            APPEND_STR(": ");
            APPEND_EXPR((expr_ty)asdl_seq_GET(e->v.Dict.values, i), PR_TEST);
        }
        else {
            APPEND_STR("**");
            APPEND_EXPR((expr_ty)asdl_seq_GET(e->v.Dict.values, i), PR_EXPR);
        }
    }

    APPEND_STR_FINISH("}");
}

static int
append_ast_set(_PyUnicodeWriter *writer, expr_ty e)
{
    Py_ssize_t i, elem_count;

    APPEND_STR("{");
    elem_count = asdl_seq_LEN(e->v.Set.elts);
    for (i = 0; i < elem_count; i++) {
        APPEND_STR_IF(i > 0, ", ");
        APPEND_EXPR((expr_ty)asdl_seq_GET(e->v.Set.elts, i), PR_TEST);
    }

    APPEND_STR_FINISH("}");
}

static int
append_ast_list(_PyUnicodeWriter *writer, expr_ty e)
{
    Py_ssize_t i, elem_count;

    APPEND_STR("[");
    elem_count = asdl_seq_LEN(e->v.List.elts);
    for (i = 0; i < elem_count; i++) {
        APPEND_STR_IF(i > 0, ", ");
        APPEND_EXPR((expr_ty)asdl_seq_GET(e->v.List.elts, i), PR_TEST);
    }

    APPEND_STR_FINISH("]");
}

static int
append_ast_tuple(_PyUnicodeWriter *writer, expr_ty e, int level)
{
    Py_ssize_t i, elem_count;

    elem_count = asdl_seq_LEN(e->v.Tuple.elts);

    if (elem_count == 0) {
        APPEND_STR_FINISH("()");
    }

    APPEND_STR_IF(level > PR_TUPLE, "(");

    for (i = 0; i < elem_count; i++) {
        APPEND_STR_IF(i > 0, ", ");
        APPEND_EXPR((expr_ty)asdl_seq_GET(e->v.Tuple.elts, i), PR_TEST);
    }

    APPEND_STR_IF(elem_count == 1, ",");
    APPEND_STR_IF(level > PR_TUPLE, ")");
    return 0;
}

static int
append_ast_comprehension(_PyUnicodeWriter *writer, comprehension_ty gen)
{
    Py_ssize_t i, if_count;

    APPEND_STR(gen->is_async ? " async for " : " for ");
    APPEND_EXPR(gen->target, PR_TUPLE);
    APPEND_STR(" in ");
    APPEND_EXPR(gen->iter, PR_TEST + 1);

    if_count = asdl_seq_LEN(gen->ifs);
    for (i = 0; i < if_count; i++) {
        APPEND_STR(" if ");
        APPEND_EXPR((expr_ty)asdl_seq_GET(gen->ifs, i), PR_TEST + 1);
    }
    return 0;
}

static int
append_ast_comprehensions(_PyUnicodeWriter *writer, asdl_seq *comprehensions)
{
    Py_ssize_t i, gen_count;
    gen_count = asdl_seq_LEN(comprehensions);

    for (i = 0; i < gen_count; i++) {
        APPEND(comprehension, (comprehension_ty)asdl_seq_GET(comprehensions, i));
    }

    return 0;
}

static int
append_ast_genexp(_PyUnicodeWriter *writer, expr_ty e)
{
    APPEND_STR("(");
    APPEND_EXPR(e->v.GeneratorExp.elt, PR_TEST);
    APPEND(comprehensions, e->v.GeneratorExp.generators);
    APPEND_STR_FINISH(")");
}

static int
append_ast_listcomp(_PyUnicodeWriter *writer, expr_ty e)
{
    APPEND_STR("[");
    APPEND_EXPR(e->v.ListComp.elt, PR_TEST);
    APPEND(comprehensions, e->v.ListComp.generators);
    APPEND_STR_FINISH("]");
}

static int
append_ast_setcomp(_PyUnicodeWriter *writer, expr_ty e)
{
    APPEND_STR("{");
    APPEND_EXPR(e->v.SetComp.elt, PR_TEST);
    APPEND(comprehensions, e->v.SetComp.generators);
    APPEND_STR_FINISH("}");
}

static int
append_ast_dictcomp(_PyUnicodeWriter *writer, expr_ty e)
{
    APPEND_STR("{");
    APPEND_EXPR(e->v.DictComp.key, PR_TEST);
    APPEND_STR(": ");
    APPEND_EXPR(e->v.DictComp.value, PR_TEST);
    APPEND(comprehensions, e->v.DictComp.generators);
    APPEND_STR_FINISH("}");
}

static int
append_ast_compare(_PyUnicodeWriter *writer, expr_ty e, int level)
{
    const char *op;
    Py_ssize_t i, comparator_count;
    asdl_seq *comparators;
    asdl_int_seq *ops;

    APPEND_STR_IF(level > PR_CMP, "(");

    comparators = e->v.Compare.comparators;
    ops = e->v.Compare.ops;
    comparator_count = asdl_seq_LEN(comparators);
    assert(comparator_count > 0);
    assert(comparator_count == asdl_seq_LEN(ops));

    APPEND_EXPR(e->v.Compare.left, PR_CMP + 1);

    for (i = 0; i < comparator_count; i++) {
        switch ((cmpop_ty)asdl_seq_GET(ops, i)) {
        case Eq:
            op = " == ";
            break;
        case NotEq:
            op = " != ";
            break;
        case Lt:
            op = " < ";
            break;
        case LtE:
            op = " <= ";
            break;
        case Gt:
            op = " > ";
            break;
        case GtE:
            op = " >= ";
            break;
        case Is:
            op = " is ";
            break;
        case IsNot:
            op = " is not ";
            break;
        case In:
            op = " in ";
            break;
        case NotIn:
            op = " not in ";
            break;
        default:
            PyErr_SetString(PyExc_SystemError,
                            "unexpected comparison kind");
            return -1;
        }

        APPEND_STR(op);
        APPEND_EXPR((expr_ty)asdl_seq_GET(comparators, i), PR_CMP + 1);
    }

    APPEND_STR_IF(level > PR_CMP, ")");
    return 0;
}

static int
append_ast_keyword(_PyUnicodeWriter *writer, keyword_ty kw)
{
    if (kw->arg == NULL) {
        APPEND_STR("**");
    }
    else {
        if (-1 == _PyUnicodeWriter_WriteStr(writer, kw->arg)) {
            return -1;
        }

        APPEND_STR("=");
    }

    APPEND_EXPR(kw->value, PR_TEST);
    return 0;
}

static int
append_ast_call(_PyUnicodeWriter *writer, expr_ty e)
{
    bool first;
    Py_ssize_t i, arg_count, kw_count;
    expr_ty expr;

    APPEND_EXPR(e->v.Call.func, PR_ATOM);

    arg_count = asdl_seq_LEN(e->v.Call.args);
    kw_count = asdl_seq_LEN(e->v.Call.keywords);
    if (arg_count == 1 && kw_count == 0) {
        expr = (expr_ty)asdl_seq_GET(e->v.Call.args, 0);
        if (expr->kind == GeneratorExp_kind) {
            /* Special case: a single generator expression. */
            return append_ast_genexp(writer, expr);
        }
    }

    APPEND_STR("(");

    first = true;
    for (i = 0; i < arg_count; i++) {
        APPEND_STR_IF_NOT_FIRST(", ");
        APPEND_EXPR((expr_ty)asdl_seq_GET(e->v.Call.args, i), PR_TEST);
    }

    for (i = 0; i < kw_count; i++) {
        APPEND_STR_IF_NOT_FIRST(", ");
        APPEND(keyword, (keyword_ty)asdl_seq_GET(e->v.Call.keywords, i));
    }

    APPEND_STR_FINISH(")");
}

static PyObject *
escape_braces(PyObject *orig)
{
    PyObject *temp;
    PyObject *result;
    temp = PyUnicode_Replace(orig, _str_open_br, _str_dbl_open_br, -1);
    if (!temp) {
        return NULL;
    }
    result = PyUnicode_Replace(temp, _str_close_br, _str_dbl_close_br, -1);
    Py_DECREF(temp);
    return result;
}

static int
append_fstring_unicode(_PyUnicodeWriter *writer, PyObject *unicode)
{
    PyObject *escaped;
    int result = -1;
    escaped = escape_braces(unicode);
    if (escaped) {
        result = _PyUnicodeWriter_WriteStr(writer, escaped);
        Py_DECREF(escaped);
    }
    return result;
}

static int
append_fstring_element(_PyUnicodeWriter *writer, expr_ty e, bool is_format_spec)
{
    switch (e->kind) {
    case Constant_kind:
        return append_fstring_unicode(writer, e->v.Constant.value);
    case JoinedStr_kind:
        return append_joinedstr(writer, e, is_format_spec);
    case FormattedValue_kind:
        return append_formattedvalue(writer, e, is_format_spec);
    default:
        PyErr_SetString(PyExc_SystemError,
                        "unknown expression kind inside f-string");
        return -1;
    }
}

/* Build body separately to enable wrapping the entire stream of Strs,
   Constants and FormattedValues in one opening and one closing quote. */
static PyObject *
build_fstring_body(asdl_seq *values, bool is_format_spec)
{
    Py_ssize_t i, value_count;
    _PyUnicodeWriter body_writer;
    _PyUnicodeWriter_Init(&body_writer);
    body_writer.min_length = 256;
    body_writer.overallocate = 1;

    value_count = asdl_seq_LEN(values);
    for (i = 0; i < value_count; ++i) {
        if (-1 == append_fstring_element(&body_writer,
                                         (expr_ty)asdl_seq_GET(values, i),
                                         is_format_spec
                                         )) {
            _PyUnicodeWriter_Dealloc(&body_writer);
            return NULL;
        }
    }

    return _PyUnicodeWriter_Finish(&body_writer);
}

static int
append_joinedstr(_PyUnicodeWriter *writer, expr_ty e, bool is_format_spec)
{
    int result = -1;
    PyObject *body = build_fstring_body(e->v.JoinedStr.values, is_format_spec);
    if (!body) {
        return -1;
    }

    if (!is_format_spec) {
        if (-1 != append_charp(writer, "f") &&
            -1 != append_repr(writer, body))
        {
            result = 0;
        }
    }
    else {
        result = _PyUnicodeWriter_WriteStr(writer, body);
    }
    Py_DECREF(body);
    return result;
}

static int
append_formattedvalue(_PyUnicodeWriter *writer, expr_ty e, bool is_format_spec)
{
    const char *conversion;
    const char *outer_brace = "{";
    /* Grammar allows PR_TUPLE, but use >PR_TEST for adding parenthesis
       around a lambda with ':' */
    PyObject *temp_fv_str = expr_as_unicode(e->v.FormattedValue.value, PR_TEST + 1);
    if (!temp_fv_str) {
        return -1;
    }
    if (PyUnicode_Find(temp_fv_str, _str_open_br, 0, 1, 1) == 0) {
        /* Expression starts with a brace, split it with a space from the outer
           one. */
        outer_brace = "{ ";
    }
    if (-1 == append_charp(writer, outer_brace)) {
        Py_DECREF(temp_fv_str);
        return -1;
    }
    if (-1 == _PyUnicodeWriter_WriteStr(writer, temp_fv_str)) {
        Py_DECREF(temp_fv_str);
        return -1;
    }
    Py_DECREF(temp_fv_str);

    if (e->v.FormattedValue.conversion > 0) {
        switch (e->v.FormattedValue.conversion) {
        case 'a':
            conversion = "!a";
            break;
        case 'r':
            conversion = "!r";
            break;
        case 's':
            conversion = "!s";
            break;
        default:
            PyErr_SetString(PyExc_SystemError,
                            "unknown f-value conversion kind");
            return -1;
        }
        APPEND_STR(conversion);
    }
    if (e->v.FormattedValue.format_spec) {
        if (-1 == _PyUnicodeWriter_WriteASCIIString(writer, ":", 1) ||
            -1 == append_fstring_element(writer,
                                         e->v.FormattedValue.format_spec,
                                         true
                                        ))
        {
            return -1;
        }
    }

    APPEND_STR_FINISH("}");
}

static int
append_ast_attribute(_PyUnicodeWriter *writer, expr_ty e)
{
    const char *period;
    expr_ty v = e->v.Attribute.value;
    APPEND_EXPR(v, PR_ATOM);

    /* Special case: integers require a space for attribute access to be
       unambiguous. */
    if (v->kind == Constant_kind && PyLong_CheckExact(v->v.Constant.value)) {
        period = " .";
    }
    else {
        period = ".";
    }
    APPEND_STR(period);

    return _PyUnicodeWriter_WriteStr(writer, e->v.Attribute.attr);
}

static int
append_ast_simple_slice(_PyUnicodeWriter *writer, slice_ty slice)
{
    if (slice->v.Slice.lower) {
        APPEND_EXPR(slice->v.Slice.lower, PR_TEST);
    }

    APPEND_STR(":");

    if (slice->v.Slice.upper) {
        APPEND_EXPR(slice->v.Slice.upper, PR_TEST);
    }

    if (slice->v.Slice.step) {
        APPEND_STR(":");
        APPEND_EXPR(slice->v.Slice.step, PR_TEST);
    }
    return 0;
}

static int
append_ast_ext_slice(_PyUnicodeWriter *writer, slice_ty slice)
{
    Py_ssize_t i, dims_count;
    dims_count = asdl_seq_LEN(slice->v.ExtSlice.dims);
    for (i = 0; i < dims_count; i++) {
        APPEND_STR_IF(i > 0, ", ");
        APPEND(slice, (slice_ty)asdl_seq_GET(slice->v.ExtSlice.dims, i));
    }
    APPEND_STR_IF(dims_count == 1, ",");
    return 0;
}

static int
append_ast_index_slice(_PyUnicodeWriter *writer, slice_ty slice)
{
    int level = PR_TUPLE;
    expr_ty value = slice->v.Index.value;
    if (value->kind == Tuple_kind) {
        for (Py_ssize_t i = 0; i < asdl_seq_LEN(value->v.Tuple.elts); i++) {
            expr_ty element = asdl_seq_GET(value->v.Tuple.elts, i);
            if (element->kind == Starred_kind) {
                ++level;
                break;
            }
        }
    }
    APPEND_EXPR(value, level);
    return 0;
}

static int
append_ast_slice(_PyUnicodeWriter *writer, slice_ty slice)
{
    switch (slice->kind) {
    case Slice_kind:
        return append_ast_simple_slice(writer, slice);
    case ExtSlice_kind:
        return append_ast_ext_slice(writer, slice);
    case Index_kind:
        return append_ast_index_slice(writer, slice);
    default:
        PyErr_SetString(PyExc_SystemError,
                        "unexpected slice kind");
        return -1;
    }
}

static int
append_ast_subscript(_PyUnicodeWriter *writer, expr_ty e)
{
    APPEND_EXPR(e->v.Subscript.value, PR_ATOM);
    APPEND_STR("[");
    APPEND(slice, e->v.Subscript.slice);
    APPEND_STR_FINISH("]");
}

static int
append_ast_starred(_PyUnicodeWriter *writer, expr_ty e)
{
    APPEND_STR("*");
    APPEND_EXPR(e->v.Starred.value, PR_EXPR);
    return 0;
}

static int
append_ast_yield(_PyUnicodeWriter *writer, expr_ty e)
{
    if (!e->v.Yield.value) {
        APPEND_STR_FINISH("(yield)");
    }

    APPEND_STR("(yield ");
    APPEND_EXPR(e->v.Yield.value, PR_TEST);
    APPEND_STR_FINISH(")");
}

static int
append_ast_yield_from(_PyUnicodeWriter *writer, expr_ty e)
{
    APPEND_STR("(yield from ");
    APPEND_EXPR(e->v.YieldFrom.value, PR_TEST);
    APPEND_STR_FINISH(")");
}

static int
append_ast_await(_PyUnicodeWriter *writer, expr_ty e, int level)
{
    APPEND_STR_IF(level > PR_AWAIT, "(");
    APPEND_STR("await ");
    APPEND_EXPR(e->v.Await.value, PR_ATOM);
    APPEND_STR_IF(level > PR_AWAIT, ")");
    return 0;
}

static int
append_named_expr(_PyUnicodeWriter *writer, expr_ty e, int level)
{
    APPEND_STR_IF(level > PR_TUPLE, "(");
    APPEND_EXPR(e->v.NamedExpr.target, PR_ATOM);
    APPEND_STR(":=");
    APPEND_EXPR(e->v.NamedExpr.value, PR_ATOM);
    APPEND_STR_IF(level > PR_TUPLE, ")");
    return 0;
}

static int
append_ast_expr(_PyUnicodeWriter *writer, expr_ty e, int level)
{
    switch (e->kind) {
    case BoolOp_kind:
        return append_ast_boolop(writer, e, level);
    case BinOp_kind:
        return append_ast_binop(writer, e, level);
    case UnaryOp_kind:
        return append_ast_unaryop(writer, e, level);
    case Lambda_kind:
        return append_ast_lambda(writer, e, level);
    case IfExp_kind:
        return append_ast_ifexp(writer, e, level);
    case Dict_kind:
        return append_ast_dict(writer, e);
    case Set_kind:
        return append_ast_set(writer, e);
    case GeneratorExp_kind:
        return append_ast_genexp(writer, e);
    case ListComp_kind:
        return append_ast_listcomp(writer, e);
    case SetComp_kind:
        return append_ast_setcomp(writer, e);
    case DictComp_kind:
        return append_ast_dictcomp(writer, e);
    case Yield_kind:
        return append_ast_yield(writer, e);
    case YieldFrom_kind:
        return append_ast_yield_from(writer, e);
    case Await_kind:
        return append_ast_await(writer, e, level);
    case Compare_kind:
        return append_ast_compare(writer, e, level);
    case Call_kind:
        return append_ast_call(writer, e);
    case Constant_kind:
        if (e->v.Constant.value == Py_Ellipsis) {
            APPEND_STR_FINISH("...");
        }
        return append_repr(writer, e->v.Constant.value);
    case JoinedStr_kind:
        return append_joinedstr(writer, e, false);
    case FormattedValue_kind:
        return append_formattedvalue(writer, e, false);
    /* The following exprs can be assignment targets. */
    case Attribute_kind:
        return append_ast_attribute(writer, e);
    case Subscript_kind:
        return append_ast_subscript(writer, e);
    case Starred_kind:
        return append_ast_starred(writer, e);
    case Name_kind:
        return _PyUnicodeWriter_WriteStr(writer, e->v.Name.id);
    case List_kind:
        return append_ast_list(writer, e);
    case Tuple_kind:
        return append_ast_tuple(writer, e, level);
    case NamedExpr_kind:
        return append_named_expr(writer, e, level);
    default:
        PyErr_SetString(PyExc_SystemError,
                        "unknown expression kind");
        return -1;
    }
}

static int
maybe_init_static_strings(void)
{
    if (!_str_open_br &&
        !(_str_open_br = PyUnicode_InternFromString("{"))) {
        return -1;
    }
    if (!_str_dbl_open_br &&
        !(_str_dbl_open_br = PyUnicode_InternFromString("{{"))) {
        return -1;
    }
    if (!_str_close_br &&
        !(_str_close_br = PyUnicode_InternFromString("}"))) {
        return -1;
    }
    if (!_str_dbl_close_br &&
        !(_str_dbl_close_br = PyUnicode_InternFromString("}}"))) {
        return -1;
    }
    return 0;
}

static PyObject *
expr_as_unicode(expr_ty e, int level)
{
    _PyUnicodeWriter writer;
    _PyUnicodeWriter_Init(&writer);
    writer.min_length = 256;
    writer.overallocate = 1;
    if (-1 == maybe_init_static_strings() ||
        -1 == append_ast_expr(&writer, e, level))
    {
        _PyUnicodeWriter_Dealloc(&writer);
        return NULL;
    }
    return _PyUnicodeWriter_Finish(&writer);
}

PyObject *
_PyAST_ExprAsUnicode(expr_ty e)
{
    return expr_as_unicode(e, PR_TEST);
}
t">} if (!eventArgs) { goto exit; } /* Call global hooks */ _Py_AuditHookEntry *e = is->runtime->audit_hook_head; for (; e; e = e->next) { if (e->hookCFunction(event, eventArgs, e->userData) < 0) { goto exit; } } /* Dtrace USDT point */ if (dtrace) { PyDTrace_AUDIT(event, (void *)eventArgs); } /* Call interpreter hooks */ if (is->audit_hooks) { eventName = PyUnicode_FromString(event); if (!eventName) { goto exit; } hooks = PyObject_GetIter(is->audit_hooks); if (!hooks) { goto exit; } /* Disallow tracing in hooks unless explicitly enabled */ PyThreadState_EnterTracing(ts); while ((hook = PyIter_Next(hooks)) != NULL) { PyObject *o; int canTrace = _PyObject_LookupAttr(hook, &_Py_ID(__cantrace__), &o); if (o) { canTrace = PyObject_IsTrue(o); Py_DECREF(o); } if (canTrace < 0) { break; } if (canTrace) { PyThreadState_LeaveTracing(ts); } PyObject* args[2] = {eventName, eventArgs}; o = _PyObject_FastCallTstate(ts, hook, args, 2); if (canTrace) { PyThreadState_EnterTracing(ts); } if (!o) { break; } Py_DECREF(o); Py_CLEAR(hook); } PyThreadState_LeaveTracing(ts); if (_PyErr_Occurred(ts)) { goto exit; } } res = 0; exit: Py_XDECREF(hook); Py_XDECREF(hooks); Py_XDECREF(eventName); Py_XDECREF(eventArgs); if (!res) { _PyErr_Restore(ts, exc_type, exc_value, exc_tb); } else { assert(_PyErr_Occurred(ts)); Py_XDECREF(exc_type); Py_XDECREF(exc_value); Py_XDECREF(exc_tb); } return res; } int _PySys_Audit(PyThreadState *tstate, const char *event, const char *argFormat, ...) { va_list vargs; #ifdef HAVE_STDARG_PROTOTYPES va_start(vargs, argFormat); #else va_start(vargs); #endif int res = sys_audit_tstate(tstate, event, argFormat, vargs); va_end(vargs); return res; } int PySys_Audit(const char *event, const char *argFormat, ...) { PyThreadState *tstate = _PyThreadState_GET(); va_list vargs; #ifdef HAVE_STDARG_PROTOTYPES va_start(vargs, argFormat); #else va_start(vargs); #endif int res = sys_audit_tstate(tstate, event, argFormat, vargs); va_end(vargs); return res; } /* We expose this function primarily for our own cleanup during * finalization. In general, it should not need to be called, * and as such the function is not exported. * * Must be finalizing to clear hooks */ void _PySys_ClearAuditHooks(PyThreadState *ts) { assert(ts != NULL); if (!ts) { return; } _PyRuntimeState *runtime = ts->interp->runtime; PyThreadState *finalizing = _PyRuntimeState_GetFinalizing(runtime); assert(finalizing == ts); if (finalizing != ts) { return; } const PyConfig *config = _PyInterpreterState_GetConfig(ts->interp); if (config->verbose) { PySys_WriteStderr("# clear sys.audit hooks\n"); } /* Hooks can abort later hooks for this event, but cannot abort the clear operation itself. */ _PySys_Audit(ts, "cpython._PySys_ClearAuditHooks", NULL); _PyErr_Clear(ts); _Py_AuditHookEntry *e = runtime->audit_hook_head, *n; runtime->audit_hook_head = NULL; while (e) { n = e->next; PyMem_RawFree(e); e = n; } } int PySys_AddAuditHook(Py_AuditHookFunction hook, void *userData) { /* tstate can be NULL, so access directly _PyRuntime: PySys_AddAuditHook() can be called before Python is initialized. */ _PyRuntimeState *runtime = &_PyRuntime; PyThreadState *tstate; if (runtime->initialized) { tstate = _PyRuntimeState_GetThreadState(runtime); } else { tstate = NULL; } /* Invoke existing audit hooks to allow them an opportunity to abort. */ /* Cannot invoke hooks until we are initialized */ if (tstate != NULL) { if (_PySys_Audit(tstate, "sys.addaudithook", NULL) < 0) { if (_PyErr_ExceptionMatches(tstate, PyExc_RuntimeError)) { /* We do not report errors derived from RuntimeError */ _PyErr_Clear(tstate); return 0; } return -1; } } _Py_AuditHookEntry *e = runtime->audit_hook_head; if (!e) { e = (_Py_AuditHookEntry*)PyMem_RawMalloc(sizeof(_Py_AuditHookEntry)); runtime->audit_hook_head = e; } else { while (e->next) { e = e->next; } e = e->next = (_Py_AuditHookEntry*)PyMem_RawMalloc( sizeof(_Py_AuditHookEntry)); } if (!e) { if (tstate != NULL) { _PyErr_NoMemory(tstate); } return -1; } e->next = NULL; e->hookCFunction = (Py_AuditHookFunction)hook; e->userData = userData; return 0; } /*[clinic input] sys.addaudithook hook: object Adds a new audit hook callback. [clinic start generated code]*/ static PyObject * sys_addaudithook_impl(PyObject *module, PyObject *hook) /*[clinic end generated code: output=4f9c17aaeb02f44e input=0f3e191217a45e34]*/ { PyThreadState *tstate = _PyThreadState_GET(); /* Invoke existing audit hooks to allow them an opportunity to abort. */ if (_PySys_Audit(tstate, "sys.addaudithook", NULL) < 0) { if (_PyErr_ExceptionMatches(tstate, PyExc_Exception)) { /* We do not report errors derived from Exception */ _PyErr_Clear(tstate); Py_RETURN_NONE; } return NULL; } PyInterpreterState *interp = tstate->interp; if (interp->audit_hooks == NULL) { interp->audit_hooks = PyList_New(0); if (interp->audit_hooks == NULL) { return NULL; } } if (PyList_Append(interp->audit_hooks, hook) < 0) { return NULL; } Py_RETURN_NONE; } PyDoc_STRVAR(audit_doc, "audit(event, *args)\n\ \n\ Passes the event to any audit hooks that are attached."); static PyObject * sys_audit(PyObject *self, PyObject *const *args, Py_ssize_t argc) { PyThreadState *tstate = _PyThreadState_GET(); _Py_EnsureTstateNotNULL(tstate); if (argc == 0) { _PyErr_SetString(tstate, PyExc_TypeError, "audit() missing 1 required positional argument: " "'event'"); return NULL; } if (!should_audit(tstate->interp)) { Py_RETURN_NONE; } PyObject *auditEvent = args[0]; if (!auditEvent) { _PyErr_SetString(tstate, PyExc_TypeError, "expected str for argument 'event'"); return NULL; } if (!PyUnicode_Check(auditEvent)) { _PyErr_Format(tstate, PyExc_TypeError, "expected str for argument 'event', not %.200s", Py_TYPE(auditEvent)->tp_name); return NULL; } const char *event = PyUnicode_AsUTF8(auditEvent); if (!event) { return NULL; } PyObject *auditArgs = _PyTuple_FromArray(args + 1, argc - 1); if (!auditArgs) { return NULL; } int res = _PySys_Audit(tstate, event, "O", auditArgs); Py_DECREF(auditArgs); if (res < 0) { return NULL; } Py_RETURN_NONE; } static PyObject * sys_breakpointhook(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *keywords) { PyThreadState *tstate = _PyThreadState_GET(); assert(!_PyErr_Occurred(tstate)); char *envar = Py_GETENV("PYTHONBREAKPOINT"); if (envar == NULL || strlen(envar) == 0) { envar = "pdb.set_trace"; } else if (!strcmp(envar, "0")) { /* The breakpoint is explicitly no-op'd. */ Py_RETURN_NONE; } /* According to POSIX the string returned by getenv() might be invalidated * or the string content might be overwritten by a subsequent call to * getenv(). Since importing a module can performs the getenv() calls, * we need to save a copy of envar. */ envar = _PyMem_RawStrdup(envar); if (envar == NULL) { _PyErr_NoMemory(tstate); return NULL; } const char *last_dot = strrchr(envar, '.'); const char *attrname = NULL; PyObject *modulepath = NULL; if (last_dot == NULL) { /* The breakpoint is a built-in, e.g. PYTHONBREAKPOINT=int */ modulepath = PyUnicode_FromString("builtins"); attrname = envar; } else if (last_dot != envar) { /* Split on the last dot; */ modulepath = PyUnicode_FromStringAndSize(envar, last_dot - envar); attrname = last_dot + 1; } else { goto warn; } if (modulepath == NULL) { PyMem_RawFree(envar); return NULL; } PyObject *module = PyImport_Import(modulepath); Py_DECREF(modulepath); if (module == NULL) { if (_PyErr_ExceptionMatches(tstate, PyExc_ImportError)) { goto warn; } PyMem_RawFree(envar); return NULL; } PyObject *hook = PyObject_GetAttrString(module, attrname); Py_DECREF(module); if (hook == NULL) { if (_PyErr_ExceptionMatches(tstate, PyExc_AttributeError)) { goto warn; } PyMem_RawFree(envar); return NULL; } PyMem_RawFree(envar); PyObject *retval = PyObject_Vectorcall(hook, args, nargs, keywords); Py_DECREF(hook); return retval; warn: /* If any of the imports went wrong, then warn and ignore. */ _PyErr_Clear(tstate); int status = PyErr_WarnFormat( PyExc_RuntimeWarning, 0, "Ignoring unimportable $PYTHONBREAKPOINT: \"%s\"", envar); PyMem_RawFree(envar); if (status < 0) { /* Printing the warning raised an exception. */ return NULL; } /* The warning was (probably) issued. */ Py_RETURN_NONE; } PyDoc_STRVAR(breakpointhook_doc, "breakpointhook(*args, **kws)\n" "\n" "This hook function is called by built-in breakpoint().\n" ); /* Write repr(o) to sys.stdout using sys.stdout.encoding and 'backslashreplace' error handler. If sys.stdout has a buffer attribute, use sys.stdout.buffer.write(encoded), otherwise redecode the string and use sys.stdout.write(redecoded). Helper function for sys_displayhook(). */ static int sys_displayhook_unencodable(PyObject *outf, PyObject *o) { PyObject *stdout_encoding = NULL; PyObject *encoded, *escaped_str, *repr_str, *buffer, *result; const char *stdout_encoding_str; int ret; stdout_encoding = PyObject_GetAttr(outf, &_Py_ID(encoding)); if (stdout_encoding == NULL) goto error; stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding); if (stdout_encoding_str == NULL) goto error; repr_str = PyObject_Repr(o); if (repr_str == NULL) goto error; encoded = PyUnicode_AsEncodedString(repr_str, stdout_encoding_str, "backslashreplace"); Py_DECREF(repr_str); if (encoded == NULL) goto error; if (_PyObject_LookupAttr(outf, &_Py_ID(buffer), &buffer) < 0) { Py_DECREF(encoded); goto error; } if (buffer) { result = PyObject_CallMethodOneArg(buffer, &_Py_ID(write), encoded); Py_DECREF(buffer); Py_DECREF(encoded); if (result == NULL) goto error; Py_DECREF(result); } else { escaped_str = PyUnicode_FromEncodedObject(encoded, stdout_encoding_str, "strict"); Py_DECREF(encoded); if (PyFile_WriteObject(escaped_str, outf, Py_PRINT_RAW) != 0) { Py_DECREF(escaped_str); goto error; } Py_DECREF(escaped_str); } ret = 0; goto finally; error: ret = -1; finally: Py_XDECREF(stdout_encoding); return ret; } /*[clinic input] sys.displayhook object as o: object / Print an object to sys.stdout and also save it in builtins._ [clinic start generated code]*/ static PyObject * sys_displayhook(PyObject *module, PyObject *o) /*[clinic end generated code: output=347477d006df92ed input=08ba730166d7ef72]*/ { PyObject *outf; PyObject *builtins; PyThreadState *tstate = _PyThreadState_GET(); builtins = PyImport_GetModule(&_Py_ID(builtins)); if (builtins == NULL) { if (!_PyErr_Occurred(tstate)) { _PyErr_SetString(tstate, PyExc_RuntimeError, "lost builtins module"); } return NULL; } Py_DECREF(builtins); /* Print value except if None */ /* After printing, also assign to '_' */ /* Before, set '_' to None to avoid recursion */ if (o == Py_None) { Py_RETURN_NONE; } if (PyObject_SetAttr(builtins, &_Py_ID(_), Py_None) != 0) return NULL; outf = _PySys_GetAttr(tstate, &_Py_ID(stdout)); if (outf == NULL || outf == Py_None) { _PyErr_SetString(tstate, PyExc_RuntimeError, "lost sys.stdout"); return NULL; } if (PyFile_WriteObject(o, outf, 0) != 0) { if (_PyErr_ExceptionMatches(tstate, PyExc_UnicodeEncodeError)) { int err; /* repr(o) is not encodable to sys.stdout.encoding with * sys.stdout.errors error handler (which is probably 'strict') */ _PyErr_Clear(tstate); err = sys_displayhook_unencodable(outf, o); if (err) { return NULL; } } else { return NULL; } } _Py_DECLARE_STR(newline, "\n"); if (PyFile_WriteObject(&_Py_STR(newline), outf, Py_PRINT_RAW) != 0) return NULL; if (PyObject_SetAttr(builtins, &_Py_ID(_), o) != 0) return NULL; Py_RETURN_NONE; } /*[clinic input] sys.excepthook exctype: object value: object traceback: object / Handle an exception by displaying it with a traceback on sys.stderr. [clinic start generated code]*/ static PyObject * sys_excepthook_impl(PyObject *module, PyObject *exctype, PyObject *value, PyObject *traceback) /*[clinic end generated code: output=18d99fdda21b6b5e input=ecf606fa826f19d9]*/ { PyErr_Display(exctype, value, traceback); Py_RETURN_NONE; } /*[clinic input] sys.exception Return the current exception. Return the most recent exception caught by an except clause in the current stack frame or in an older stack frame, or None if no such exception exists. [clinic start generated code]*/ static PyObject * sys_exception_impl(PyObject *module) /*[clinic end generated code: output=2381ee2f25953e40 input=c88fbb94b6287431]*/ { _PyErr_StackItem *err_info = _PyErr_GetTopmostException(_PyThreadState_GET()); if (err_info->exc_value != NULL) { return Py_NewRef(err_info->exc_value); } Py_RETURN_NONE; } /*[clinic input] sys.exc_info Return current exception information: (type, value, traceback). Return information about the most recent exception caught by an except clause in the current stack frame or in an older stack frame. [clinic start generated code]*/ static PyObject * sys_exc_info_impl(PyObject *module) /*[clinic end generated code: output=3afd0940cf3a4d30 input=b5c5bf077788a3e5]*/ { _PyErr_StackItem *err_info = _PyErr_GetTopmostException(_PyThreadState_GET()); return _PyErr_StackItemToExcInfoTuple(err_info); } /*[clinic input] sys.unraisablehook unraisable: object / Handle an unraisable exception. The unraisable argument has the following attributes: * exc_type: Exception type. * exc_value: Exception value, can be None. * exc_traceback: Exception traceback, can be None. * err_msg: Error message, can be None. * object: Object causing the exception, can be None. [clinic start generated code]*/ static PyObject * sys_unraisablehook(PyObject *module, PyObject *unraisable) /*[clinic end generated code: output=bb92838b32abaa14 input=ec3af148294af8d3]*/ { return _PyErr_WriteUnraisableDefaultHook(unraisable); } /*[clinic input] sys.exit status: object = None / Exit the interpreter by raising SystemExit(status). If the status is omitted or None, it defaults to zero (i.e., success). If the status is an integer, it will be used as the system exit status. If it is another kind of object, it will be printed and the system exit status will be one (i.e., failure). [clinic start generated code]*/ static PyObject * sys_exit_impl(PyObject *module, PyObject *status) /*[clinic end generated code: output=13870986c1ab2ec0 input=b86ca9497baa94f2]*/ { /* Raise SystemExit so callers may catch it or clean up. */ PyErr_SetObject(PyExc_SystemExit, status); return NULL; } /*[clinic input] sys.getdefaultencoding Return the current default encoding used by the Unicode implementation. [clinic start generated code]*/ static PyObject * sys_getdefaultencoding_impl(PyObject *module) /*[clinic end generated code: output=256d19dfcc0711e6 input=d416856ddbef6909]*/ { _Py_DECLARE_STR(utf_8, "utf-8"); PyObject *ret = &_Py_STR(utf_8); Py_INCREF(ret); return ret; } /*[clinic input] sys.getfilesystemencoding Return the encoding used to convert Unicode filenames to OS filenames. [clinic start generated code]*/ static PyObject * sys_getfilesystemencoding_impl(PyObject *module) /*[clinic end generated code: output=1dc4bdbe9be44aa7 input=8475f8649b8c7d8c]*/ { PyInterpreterState *interp = _PyInterpreterState_GET(); const PyConfig *config = _PyInterpreterState_GetConfig(interp); return PyUnicode_FromWideChar(config->filesystem_encoding, -1); } /*[clinic input] sys.getfilesystemencodeerrors Return the error mode used Unicode to OS filename conversion. [clinic start generated code]*/ static PyObject * sys_getfilesystemencodeerrors_impl(PyObject *module) /*[clinic end generated code: output=ba77b36bbf7c96f5 input=22a1e8365566f1e5]*/ { PyInterpreterState *interp = _PyInterpreterState_GET(); const PyConfig *config = _PyInterpreterState_GetConfig(interp); return PyUnicode_FromWideChar(config->filesystem_errors, -1); } /*[clinic input] sys.intern string as s: unicode / ``Intern'' the given string. This enters the string in the (global) table of interned strings whose purpose is to speed up dictionary lookups. Return the string itself or the previously interned string object with the same value. [clinic start generated code]*/ static PyObject * sys_intern_impl(PyObject *module, PyObject *s) /*[clinic end generated code: output=be680c24f5c9e5d6 input=849483c006924e2f]*/ { if (PyUnicode_CheckExact(s)) { Py_INCREF(s); PyUnicode_InternInPlace(&s); return s; } else { PyErr_Format(PyExc_TypeError, "can't intern %.400s", Py_TYPE(s)->tp_name); return NULL; } } /* * Cached interned string objects used for calling the profile and * trace functions. */ static PyObject *whatstrings[8] = { &_Py_ID(call), &_Py_ID(exception), &_Py_ID(line), &_Py_ID(return), &_Py_ID(c_call), &_Py_ID(c_exception), &_Py_ID(c_return), &_Py_ID(opcode), }; static PyObject * call_trampoline(PyThreadState *tstate, PyObject* callback, PyFrameObject *frame, int what, PyObject *arg) { PyObject *stack[3]; stack[0] = (PyObject *)frame; stack[1] = whatstrings[what]; stack[2] = (arg != NULL) ? arg : Py_None; /* Discard any previous modifications the frame's fast locals */ if (frame->f_fast_as_locals) { if (PyFrame_FastToLocalsWithError(frame) < 0) { return NULL; } } /* call the Python-level function */ PyObject *result = _PyObject_FastCallTstate(tstate, callback, stack, 3); PyFrame_LocalsToFast(frame, 1); if (result == NULL) { PyTraceBack_Here(frame); } return result; } static int profile_trampoline(PyObject *self, PyFrameObject *frame, int what, PyObject *arg) { if (arg == NULL) { arg = Py_None; } PyThreadState *tstate = _PyThreadState_GET(); PyObject *result = call_trampoline(tstate, self, frame, what, arg); if (result == NULL) { _PyEval_SetProfile(tstate, NULL, NULL); return -1; } Py_DECREF(result); return 0; } static int trace_trampoline(PyObject *self, PyFrameObject *frame, int what, PyObject *arg) { PyObject *callback; if (what == PyTrace_CALL) { callback = self; } else { callback = frame->f_trace; } if (callback == NULL) { return 0; } PyThreadState *tstate = _PyThreadState_GET(); PyObject *result = call_trampoline(tstate, callback, frame, what, arg); if (result == NULL) { _PyEval_SetTrace(tstate, NULL, NULL); Py_CLEAR(frame->f_trace); return -1; } if (result != Py_None) { Py_XSETREF(frame->f_trace, result); } else { Py_DECREF(result); } return 0; } static PyObject * sys_settrace(PyObject *self, PyObject *args) { PyThreadState *tstate = _PyThreadState_GET(); if (args == Py_None) { if (_PyEval_SetTrace(tstate, NULL, NULL) < 0) { return NULL; } } else { if (_PyEval_SetTrace(tstate, trace_trampoline, args) < 0) { return NULL; } } Py_RETURN_NONE; } PyDoc_STRVAR(settrace_doc, "settrace(function)\n\ \n\ Set the global debug tracing function. It will be called on each\n\ function call. See the debugger chapter in the library manual." ); /*[clinic input] sys.gettrace Return the global debug tracing function set with sys.settrace. See the debugger chapter in the library manual. [clinic start generated code]*/ static PyObject * sys_gettrace_impl(PyObject *module) /*[clinic end generated code: output=e97e3a4d8c971b6e input=373b51bb2147f4d8]*/ { PyThreadState *tstate = _PyThreadState_GET(); PyObject *temp = tstate->c_traceobj; if (temp == NULL) temp = Py_None; Py_INCREF(temp); return temp; } static PyObject * sys_setprofile(PyObject *self, PyObject *args) { PyThreadState *tstate = _PyThreadState_GET(); if (args == Py_None) { if (_PyEval_SetProfile(tstate, NULL, NULL) < 0) { return NULL; } } else { if (_PyEval_SetProfile(tstate, profile_trampoline, args) < 0) { return NULL; } } Py_RETURN_NONE; } PyDoc_STRVAR(setprofile_doc, "setprofile(function)\n\ \n\ Set the profiling function. It will be called on each function call\n\ and return. See the profiler chapter in the library manual." ); /*[clinic input] sys.getprofile Return the profiling function set with sys.setprofile. See the profiler chapter in the library manual. [clinic start generated code]*/ static PyObject * sys_getprofile_impl(PyObject *module) /*[clinic end generated code: output=579b96b373448188 input=1b3209d89a32965d]*/ { PyThreadState *tstate = _PyThreadState_GET(); PyObject *temp = tstate->c_profileobj; if (temp == NULL) temp = Py_None; Py_INCREF(temp); return temp; } /*[clinic input] sys.setswitchinterval interval: double / Set the ideal thread switching delay inside the Python interpreter. The actual frequency of switching threads can be lower if the interpreter executes long sequences of uninterruptible code (this is implementation-specific and workload-dependent). The parameter must represent the desired switching delay in seconds A typical value is 0.005 (5 milliseconds). [clinic start generated code]*/ static PyObject * sys_setswitchinterval_impl(PyObject *module, double interval) /*[clinic end generated code: output=65a19629e5153983 input=561b477134df91d9]*/ { if (interval <= 0.0) { PyErr_SetString(PyExc_ValueError, "switch interval must be strictly positive"); return NULL; } _PyEval_SetSwitchInterval((unsigned long) (1e6 * interval)); Py_RETURN_NONE; } /*[clinic input] sys.getswitchinterval -> double Return the current thread switch interval; see sys.setswitchinterval(). [clinic start generated code]*/ static double sys_getswitchinterval_impl(PyObject *module) /*[clinic end generated code: output=a38c277c85b5096d input=bdf9d39c0ebbbb6f]*/ { return 1e-6 * _PyEval_GetSwitchInterval(); } /*[clinic input] sys.setrecursionlimit limit as new_limit: int / Set the maximum depth of the Python interpreter stack to n. This limit prevents infinite recursion from causing an overflow of the C stack and crashing Python. The highest possible limit is platform- dependent. [clinic start generated code]*/ static PyObject * sys_setrecursionlimit_impl(PyObject *module, int new_limit) /*[clinic end generated code: output=35e1c64754800ace input=b0f7a23393924af3]*/ { PyThreadState *tstate = _PyThreadState_GET(); if (new_limit < 1) { _PyErr_SetString(tstate, PyExc_ValueError, "recursion limit must be greater or equal than 1"); return NULL; } /* Reject too low new limit if the current recursion depth is higher than the new low-water mark. */ int depth = tstate->recursion_limit - tstate->recursion_remaining; if (depth >= new_limit) { _PyErr_Format(tstate, PyExc_RecursionError, "cannot set the recursion limit to %i at " "the recursion depth %i: the limit is too low", new_limit, depth); return NULL; } Py_SetRecursionLimit(new_limit); Py_RETURN_NONE; } /*[clinic input] sys.set_coroutine_origin_tracking_depth depth: int Enable or disable origin tracking for coroutine objects in this thread. Coroutine objects will track 'depth' frames of traceback information about where they came from, available in their cr_origin attribute. Set a depth of 0 to disable. [clinic start generated code]*/ static PyObject * sys_set_coroutine_origin_tracking_depth_impl(PyObject *module, int depth) /*[clinic end generated code: output=0a2123c1cc6759c5 input=a1d0a05f89d2c426]*/ { if (_PyEval_SetCoroutineOriginTrackingDepth(depth) < 0) { return NULL; } Py_RETURN_NONE; } /*[clinic input] sys.get_coroutine_origin_tracking_depth -> int Check status of origin tracking for coroutine objects in this thread. [clinic start generated code]*/ static int sys_get_coroutine_origin_tracking_depth_impl(PyObject *module) /*[clinic end generated code: output=3699f7be95a3afb8 input=335266a71205b61a]*/ { return _PyEval_GetCoroutineOriginTrackingDepth(); } static PyTypeObject AsyncGenHooksType; PyDoc_STRVAR(asyncgen_hooks_doc, "asyncgen_hooks\n\ \n\ A named tuple providing information about asynchronous\n\ generators hooks. The attributes are read only."); static PyStructSequence_Field asyncgen_hooks_fields[] = { {"firstiter", "Hook to intercept first iteration"}, {"finalizer", "Hook to intercept finalization"}, {0} }; static PyStructSequence_Desc asyncgen_hooks_desc = { "asyncgen_hooks", /* name */ asyncgen_hooks_doc, /* doc */ asyncgen_hooks_fields , /* fields */ 2 }; static PyObject * sys_set_asyncgen_hooks(PyObject *self, PyObject *args, PyObject *kw) { static char *keywords[] = {"firstiter", "finalizer", NULL}; PyObject *firstiter = NULL; PyObject *finalizer = NULL; if (!PyArg_ParseTupleAndKeywords( args, kw, "|OO", keywords, &firstiter, &finalizer)) { return NULL; } if (finalizer && finalizer != Py_None) { if (!PyCallable_Check(finalizer)) { PyErr_Format(PyExc_TypeError, "callable finalizer expected, got %.50s", Py_TYPE(finalizer)->tp_name); return NULL; } if (_PyEval_SetAsyncGenFinalizer(finalizer) < 0) { return NULL; } } else if (finalizer == Py_None && _PyEval_SetAsyncGenFinalizer(NULL) < 0) { return NULL; } if (firstiter && firstiter != Py_None) { if (!PyCallable_Check(firstiter)) { PyErr_Format(PyExc_TypeError, "callable firstiter expected, got %.50s", Py_TYPE(firstiter)->tp_name); return NULL; } if (_PyEval_SetAsyncGenFirstiter(firstiter) < 0) { return NULL; } } else if (firstiter == Py_None && _PyEval_SetAsyncGenFirstiter(NULL) < 0) { return NULL; } Py_RETURN_NONE; } PyDoc_STRVAR(set_asyncgen_hooks_doc, "set_asyncgen_hooks(* [, firstiter] [, finalizer])\n\ \n\ Set a finalizer for async generators objects." ); /*[clinic input] sys.get_asyncgen_hooks Return the installed asynchronous generators hooks. This returns a namedtuple of the form (firstiter, finalizer). [clinic start generated code]*/ static PyObject * sys_get_asyncgen_hooks_impl(PyObject *module) /*[clinic end generated code: output=53a253707146f6cf input=3676b9ea62b14625]*/ { PyObject *res; PyObject *firstiter = _PyEval_GetAsyncGenFirstiter(); PyObject *finalizer = _PyEval_GetAsyncGenFinalizer(); res = PyStructSequence_New(&AsyncGenHooksType); if (res == NULL) { return NULL; } if (firstiter == NULL) { firstiter = Py_None; } if (finalizer == NULL) { finalizer = Py_None; } Py_INCREF(firstiter); PyStructSequence_SET_ITEM(res, 0, firstiter); Py_INCREF(finalizer); PyStructSequence_SET_ITEM(res, 1, finalizer); return res; } static PyTypeObject Hash_InfoType; PyDoc_STRVAR(hash_info_doc, "hash_info\n\ \n\ A named tuple providing parameters used for computing\n\ hashes. The attributes are read only."); static PyStructSequence_Field hash_info_fields[] = { {"width", "width of the type used for hashing, in bits"}, {"modulus", "prime number giving the modulus on which the hash " "function is based"}, {"inf", "value to be used for hash of a positive infinity"}, {"nan", "value to be used for hash of a nan"}, {"imag", "multiplier used for the imaginary part of a complex number"}, {"algorithm", "name of the algorithm for hashing of str, bytes and " "memoryviews"}, {"hash_bits", "internal output size of hash algorithm"}, {"seed_bits", "seed size of hash algorithm"}, {"cutoff", "small string optimization cutoff"}, {NULL, NULL} }; static PyStructSequence_Desc hash_info_desc = { "sys.hash_info", hash_info_doc, hash_info_fields, 9, }; static PyObject * get_hash_info(PyThreadState *tstate) { PyObject *hash_info; int field = 0; PyHash_FuncDef *hashfunc; hash_info = PyStructSequence_New(&Hash_InfoType); if (hash_info == NULL) return NULL; hashfunc = PyHash_GetFuncDef(); PyStructSequence_SET_ITEM(hash_info, field++, PyLong_FromLong(8*sizeof(Py_hash_t))); PyStructSequence_SET_ITEM(hash_info, field++, PyLong_FromSsize_t(_PyHASH_MODULUS)); PyStructSequence_SET_ITEM(hash_info, field++, PyLong_FromLong(_PyHASH_INF)); PyStructSequence_SET_ITEM(hash_info, field++, PyLong_FromLong(0)); // This is no longer used PyStructSequence_SET_ITEM(hash_info, field++, PyLong_FromLong(_PyHASH_IMAG)); PyStructSequence_SET_ITEM(hash_info, field++, PyUnicode_FromString(hashfunc->name)); PyStructSequence_SET_ITEM(hash_info, field++, PyLong_FromLong(hashfunc->hash_bits)); PyStructSequence_SET_ITEM(hash_info, field++, PyLong_FromLong(hashfunc->seed_bits)); PyStructSequence_SET_ITEM(hash_info, field++, PyLong_FromLong(Py_HASH_CUTOFF)); if (_PyErr_Occurred(tstate)) { Py_CLEAR(hash_info); return NULL; } return hash_info; } /*[clinic input] sys.getrecursionlimit Return the current value of the recursion limit. The recursion limit is the maximum depth of the Python interpreter stack. This limit prevents infinite recursion from causing an overflow of the C stack and crashing Python. [clinic start generated code]*/ static PyObject * sys_getrecursionlimit_impl(PyObject *module) /*[clinic end generated code: output=d571fb6b4549ef2e input=1c6129fd2efaeea8]*/ { return PyLong_FromLong(Py_GetRecursionLimit()); } #ifdef MS_WINDOWS static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0}; static PyStructSequence_Field windows_version_fields[] = { {"major", "Major version number"}, {"minor", "Minor version number"}, {"build", "Build number"}, {"platform", "Operating system platform"}, {"service_pack", "Latest Service Pack installed on the system"}, {"service_pack_major", "Service Pack major version number"}, {"service_pack_minor", "Service Pack minor version number"}, {"suite_mask", "Bit mask identifying available product suites"}, {"product_type", "System product type"}, {"platform_version", "Diagnostic version number"}, {0} }; static PyStructSequence_Desc windows_version_desc = { "sys.getwindowsversion", /* name */ sys_getwindowsversion__doc__, /* doc */ windows_version_fields, /* fields */ 5 /* For backward compatibility, only the first 5 items are accessible via indexing, the rest are name only */ }; /* Disable deprecation warnings about GetVersionEx as the result is being passed straight through to the caller, who is responsible for using it correctly. */ #pragma warning(push) #pragma warning(disable:4996) /*[clinic input] sys.getwindowsversion Return info about the running version of Windows as a named tuple. The members are named: major, minor, build, platform, service_pack, service_pack_major, service_pack_minor, suite_mask, product_type and platform_version. For backward compatibility, only the first 5 items are available by indexing. All elements are numbers, except service_pack and platform_type which are strings, and platform_version which is a 3-tuple. Platform is always 2. Product_type may be 1 for a workstation, 2 for a domain controller, 3 for a server. Platform_version is a 3-tuple containing a version number that is intended for identifying the OS rather than feature detection. [clinic start generated code]*/ static PyObject * sys_getwindowsversion_impl(PyObject *module) /*[clinic end generated code: output=1ec063280b932857 input=73a228a328fee63a]*/ { PyObject *version; int pos = 0; OSVERSIONINFOEXW ver; DWORD realMajor, realMinor, realBuild; HANDLE hKernel32; wchar_t kernel32_path[MAX_PATH]; LPVOID verblock; DWORD verblock_size; ver.dwOSVersionInfoSize = sizeof(ver); if (!GetVersionExW((OSVERSIONINFOW*) &ver)) return PyErr_SetFromWindowsErr(0); version = PyStructSequence_New(&WindowsVersionType); if (version == NULL) return NULL; PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMajorVersion)); PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMinorVersion)); PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwBuildNumber)); PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwPlatformId)); PyStructSequence_SET_ITEM(version, pos++, PyUnicode_FromWideChar(ver.szCSDVersion, -1)); PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMajor)); PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMinor)); PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask)); PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType)); realMajor = ver.dwMajorVersion; realMinor = ver.dwMinorVersion; realBuild = ver.dwBuildNumber; // GetVersion will lie if we are running in a compatibility mode. // We need to read the version info from a system file resource // to accurately identify the OS version. If we fail for any reason, // just return whatever GetVersion said. Py_BEGIN_ALLOW_THREADS hKernel32 = GetModuleHandleW(L"kernel32.dll"); Py_END_ALLOW_THREADS if (hKernel32 && GetModuleFileNameW(hKernel32, kernel32_path, MAX_PATH) && (verblock_size = GetFileVersionInfoSizeW(kernel32_path, NULL)) && (verblock = PyMem_RawMalloc(verblock_size))) { VS_FIXEDFILEINFO *ffi; UINT ffi_len; if (GetFileVersionInfoW(kernel32_path, 0, verblock_size, verblock) && VerQueryValueW(verblock, L"", (LPVOID)&ffi, &ffi_len)) { realMajor = HIWORD(ffi->dwProductVersionMS); realMinor = LOWORD(ffi->dwProductVersionMS); realBuild = HIWORD(ffi->dwProductVersionLS); } PyMem_RawFree(verblock); } PyStructSequence_SET_ITEM(version, pos++, Py_BuildValue("(kkk)", realMajor, realMinor, realBuild )); if (PyErr_Occurred()) { Py_DECREF(version); return NULL; } return version; } #pragma warning(pop) /*[clinic input] sys._enablelegacywindowsfsencoding Changes the default filesystem encoding to mbcs:replace. This is done for consistency with earlier versions of Python. See PEP 529 for more information. This is equivalent to defining the PYTHONLEGACYWINDOWSFSENCODING environment variable before launching Python. [clinic start generated code]*/ static PyObject * sys__enablelegacywindowsfsencoding_impl(PyObject *module) /*[clinic end generated code: output=f5c3855b45e24fe9 input=2bfa931a20704492]*/ { if (_PyUnicode_EnableLegacyWindowsFSEncoding() < 0) { return NULL; } Py_RETURN_NONE; } #endif /* MS_WINDOWS */ #ifdef HAVE_DLOPEN /*[clinic input] sys.setdlopenflags flags as new_val: int / Set the flags used by the interpreter for dlopen calls. This is used, for example, when the interpreter loads extension modules. Among other things, this will enable a lazy resolving of symbols when importing a module, if called as sys.setdlopenflags(0). To share symbols across extension modules, call as sys.setdlopenflags(os.RTLD_GLOBAL). Symbolic names for the flag modules can be found in the os module (RTLD_xxx constants, e.g. os.RTLD_LAZY). [clinic start generated code]*/ static PyObject * sys_setdlopenflags_impl(PyObject *module, int new_val) /*[clinic end generated code: output=ec918b7fe0a37281 input=4c838211e857a77f]*/ { PyInterpreterState *interp = _PyInterpreterState_GET(); interp->dlopenflags = new_val; Py_RETURN_NONE; } /*[clinic input] sys.getdlopenflags Return the current value of the flags that are used for dlopen calls. The flag constants are defined in the os module. [clinic start generated code]*/ static PyObject * sys_getdlopenflags_impl(PyObject *module) /*[clinic end generated code: output=e92cd1bc5005da6e input=dc4ea0899c53b4b6]*/ { PyInterpreterState *interp = _PyInterpreterState_GET(); return PyLong_FromLong(interp->dlopenflags); } #endif /* HAVE_DLOPEN */ #ifdef USE_MALLOPT /* Link with -lmalloc (or -lmpc) on an SGI */ #include <malloc.h> /*[clinic input] sys.mdebug flag: int / [clinic start generated code]*/ static PyObject * sys_mdebug_impl(PyObject *module, int flag) /*[clinic end generated code: output=5431d545847c3637 input=151d150ae1636f8a]*/ { int flag; mallopt(M_DEBUG, flag); Py_RETURN_NONE; } #endif /* USE_MALLOPT */ size_t _PySys_GetSizeOf(PyObject *o) { PyObject *res = NULL; PyObject *method; Py_ssize_t size; PyThreadState *tstate = _PyThreadState_GET(); /* Make sure the type is initialized. float gets initialized late */ if (PyType_Ready(Py_TYPE(o)) < 0) { return (size_t)-1; } method = _PyObject_LookupSpecial(o, &_Py_ID(__sizeof__)); if (method == NULL) { if (!_PyErr_Occurred(tstate)) { _PyErr_Format(tstate, PyExc_TypeError, "Type %.100s doesn't define __sizeof__", Py_TYPE(o)->tp_name); } } else { res = _PyObject_CallNoArgs(method); Py_DECREF(method); } if (res == NULL) return (size_t)-1; size = PyLong_AsSsize_t(res); Py_DECREF(res); if (size == -1 && _PyErr_Occurred(tstate)) return (size_t)-1; if (size < 0) { _PyErr_SetString(tstate, PyExc_ValueError, "__sizeof__() should return >= 0"); return (size_t)-1; } return (size_t)size + _PyType_PreHeaderSize(Py_TYPE(o)); } static PyObject * sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds) { static char *kwlist[] = {"object", "default", 0}; size_t size; PyObject *o, *dflt = NULL; PyThreadState *tstate = _PyThreadState_GET(); if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof", kwlist, &o, &dflt)) { return NULL; } size = _PySys_GetSizeOf(o); if (size == (size_t)-1 && _PyErr_Occurred(tstate)) { /* Has a default value been given */ if (dflt != NULL && _PyErr_ExceptionMatches(tstate, PyExc_TypeError)) { _PyErr_Clear(tstate); Py_INCREF(dflt); return dflt; } else return NULL; } return PyLong_FromSize_t(size); } PyDoc_STRVAR(getsizeof_doc, "getsizeof(object [, default]) -> int\n\ \n\ Return the size of object in bytes."); /*[clinic input] sys.getrefcount -> Py_ssize_t object: object / Return the reference count of object. The count returned is generally one higher than you might expect, because it includes the (temporary) reference as an argument to getrefcount(). [clinic start generated code]*/ static Py_ssize_t sys_getrefcount_impl(PyObject *module, PyObject *object) /*[clinic end generated code: output=5fd477f2264b85b2 input=bf474efd50a21535]*/ { return Py_REFCNT(object); } #ifdef Py_REF_DEBUG /*[clinic input] sys.gettotalrefcount -> Py_ssize_t [clinic start generated code]*/ static Py_ssize_t sys_gettotalrefcount_impl(PyObject *module) /*[clinic end generated code: output=4103886cf17c25bc input=53b744faa5d2e4f6]*/ { return _Py_GetRefTotal(); } #endif /* Py_REF_DEBUG */ /*[clinic input] sys._getquickenedcount -> Py_ssize_t [clinic start generated code]*/ static Py_ssize_t sys__getquickenedcount_impl(PyObject *module) /*[clinic end generated code: output=1ab259e7f91248a2 input=249d448159eca912]*/ { return _Py_QuickenedCount; } /*[clinic input] sys.getallocatedblocks -> Py_ssize_t Return the number of memory blocks currently allocated. [clinic start generated code]*/ static Py_ssize_t sys_getallocatedblocks_impl(PyObject *module) /*[clinic end generated code: output=f0c4e873f0b6dcf7 input=dab13ee346a0673e]*/ { return _Py_GetAllocatedBlocks(); } /*[clinic input] sys._getframe depth: int = 0 / Return a frame object from the call stack. If optional integer depth is given, return the frame object that many calls below the top of the stack. If that is deeper than the call stack, ValueError is raised. The default for depth is zero, returning the frame at the top of the call stack. This function should be used for internal and specialized purposes only. [clinic start generated code]*/ static PyObject * sys__getframe_impl(PyObject *module, int depth) /*[clinic end generated code: output=d438776c04d59804 input=c1be8a6464b11ee5]*/ { PyThreadState *tstate = _PyThreadState_GET(); _PyInterpreterFrame *frame = tstate->cframe->current_frame; if (_PySys_Audit(tstate, "sys._getframe", NULL) < 0) { return NULL; } while (depth > 0 && frame != NULL) { frame = frame->previous; --depth; } if (frame == NULL) { _PyErr_SetString(tstate, PyExc_ValueError, "call stack is not deep enough"); return NULL; } return _Py_XNewRef((PyObject *)_PyFrame_GetFrameObject(frame)); } /*[clinic input] sys._current_frames Return a dict mapping each thread's thread id to its current stack frame. This function should be used for specialized purposes only. [clinic start generated code]*/ static PyObject * sys__current_frames_impl(PyObject *module) /*[clinic end generated code: output=d2a41ac0a0a3809a input=2a9049c5f5033691]*/ { return _PyThread_CurrentFrames(); } /*[clinic input] sys._current_exceptions Return a dict mapping each thread's identifier to its current raised exception. This function should be used for specialized purposes only. [clinic start generated code]*/ static PyObject * sys__current_exceptions_impl(PyObject *module) /*[clinic end generated code: output=2ccfd838c746f0ba input=0e91818fbf2edc1f]*/ { return _PyThread_CurrentExceptions(); } /*[clinic input] sys.call_tracing func: object args as funcargs: object(subclass_of='&PyTuple_Type') / Call func(*args), while tracing is enabled. The tracing state is saved, and restored afterwards. This is intended to be called from a debugger from a checkpoint, to recursively debug some other code. [clinic start generated code]*/ static PyObject * sys_call_tracing_impl(PyObject *module, PyObject *func, PyObject *funcargs) /*[clinic end generated code: output=7e4999853cd4e5a6 input=5102e8b11049f92f]*/ { return _PyEval_CallTracing(func, funcargs); } #ifdef __cplusplus extern "C" { #endif /*[clinic input] sys._debugmallocstats Print summary info to stderr about the state of pymalloc's structures. In Py_DEBUG mode, also perform some expensive internal consistency checks. [clinic start generated code]*/ static PyObject * sys__debugmallocstats_impl(PyObject *module) /*[clinic end generated code: output=ec3565f8c7cee46a input=33c0c9c416f98424]*/ { #ifdef WITH_PYMALLOC if (_PyObject_DebugMallocStats(stderr)) { fputc('\n', stderr); } #endif _PyObject_DebugTypeStats(stderr); Py_RETURN_NONE; } #ifdef Py_TRACE_REFS /* Defined in objects.c because it uses static globals in that file */ extern PyObject *_Py_GetObjects(PyObject *, PyObject *); #endif #ifdef Py_STATS /* Defined in ceval.c because it uses static globals in that file */ extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *); #endif #ifdef __cplusplus } #endif /*[clinic input] sys._clear_type_cache Clear the internal type lookup cache. [clinic start generated code]*/ static PyObject * sys__clear_type_cache_impl(PyObject *module) /*[clinic end generated code: output=20e48ca54a6f6971 input=127f3e04a8d9b555]*/ { PyType_ClearCache(); Py_RETURN_NONE; } /*[clinic input] sys.is_finalizing Return True if Python is exiting. [clinic start generated code]*/ static PyObject * sys_is_finalizing_impl(PyObject *module) /*[clinic end generated code: output=735b5ff7962ab281 input=f0df747a039948a5]*/ { return PyBool_FromLong(_Py_IsFinalizing()); } #ifdef ANDROID_API_LEVEL /*[clinic input] sys.getandroidapilevel Return the build time API version of Android as an integer. [clinic start generated code]*/ static PyObject * sys_getandroidapilevel_impl(PyObject *module) /*[clinic end generated code: output=214abf183a1c70c1 input=3e6d6c9fcdd24ac6]*/ { return PyLong_FromLong(ANDROID_API_LEVEL); } #endif /* ANDROID_API_LEVEL */ static PyMethodDef sys_methods[] = { /* Might as well keep this in alphabetic order */ SYS_ADDAUDITHOOK_METHODDEF {"audit", _PyCFunction_CAST(sys_audit), METH_FASTCALL, audit_doc }, {"breakpointhook", _PyCFunction_CAST(sys_breakpointhook), METH_FASTCALL | METH_KEYWORDS, breakpointhook_doc}, SYS__CLEAR_TYPE_CACHE_METHODDEF SYS__CURRENT_FRAMES_METHODDEF SYS__CURRENT_EXCEPTIONS_METHODDEF SYS_DISPLAYHOOK_METHODDEF SYS_EXCEPTION_METHODDEF SYS_EXC_INFO_METHODDEF SYS_EXCEPTHOOK_METHODDEF SYS_EXIT_METHODDEF SYS_GETDEFAULTENCODING_METHODDEF SYS_GETDLOPENFLAGS_METHODDEF SYS_GETALLOCATEDBLOCKS_METHODDEF #ifdef Py_STATS {"getdxp", _Py_GetDXProfile, METH_VARARGS}, #endif SYS_GETFILESYSTEMENCODING_METHODDEF SYS_GETFILESYSTEMENCODEERRORS_METHODDEF SYS__GETQUICKENEDCOUNT_METHODDEF #ifdef Py_TRACE_REFS {"getobjects", _Py_GetObjects, METH_VARARGS}, #endif SYS_GETTOTALREFCOUNT_METHODDEF SYS_GETREFCOUNT_METHODDEF SYS_GETRECURSIONLIMIT_METHODDEF {"getsizeof", _PyCFunction_CAST(sys_getsizeof), METH_VARARGS | METH_KEYWORDS, getsizeof_doc}, SYS__GETFRAME_METHODDEF SYS_GETWINDOWSVERSION_METHODDEF SYS__ENABLELEGACYWINDOWSFSENCODING_METHODDEF SYS_INTERN_METHODDEF SYS_IS_FINALIZING_METHODDEF SYS_MDEBUG_METHODDEF SYS_SETSWITCHINTERVAL_METHODDEF SYS_GETSWITCHINTERVAL_METHODDEF SYS_SETDLOPENFLAGS_METHODDEF {"setprofile", sys_setprofile, METH_O, setprofile_doc}, SYS_GETPROFILE_METHODDEF SYS_SETRECURSIONLIMIT_METHODDEF {"settrace", sys_settrace, METH_O, settrace_doc}, SYS_GETTRACE_METHODDEF SYS_CALL_TRACING_METHODDEF SYS__DEBUGMALLOCSTATS_METHODDEF SYS_SET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF SYS_GET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF {"set_asyncgen_hooks", _PyCFunction_CAST(sys_set_asyncgen_hooks), METH_VARARGS | METH_KEYWORDS, set_asyncgen_hooks_doc}, SYS_GET_ASYNCGEN_HOOKS_METHODDEF SYS_GETANDROIDAPILEVEL_METHODDEF SYS_UNRAISABLEHOOK_METHODDEF {NULL, NULL} // sentinel }; static PyObject * list_builtin_module_names(void) { PyObject *list = PyList_New(0); if (list == NULL) { return NULL; } for (Py_ssize_t i = 0; PyImport_Inittab[i].name != NULL; i++) { PyObject *name = PyUnicode_FromString(PyImport_Inittab[i].name); if (name == NULL) { goto error; } if (PyList_Append(list, name) < 0) { Py_DECREF(name); goto error; } Py_DECREF(name); } if (PyList_Sort(list) != 0) { goto error; } PyObject *tuple = PyList_AsTuple(list); Py_DECREF(list); return tuple; error: Py_DECREF(list); return NULL; } static PyObject * list_stdlib_module_names(void) { Py_ssize_t len = Py_ARRAY_LENGTH(_Py_stdlib_module_names); PyObject *names = PyTuple_New(len); if (names == NULL) { return NULL; } for (Py_ssize_t i = 0; i < len; i++) { PyObject *name = PyUnicode_FromString(_Py_stdlib_module_names[i]); if (name == NULL) { Py_DECREF(names); return NULL; } PyTuple_SET_ITEM(names, i, name); } PyObject *set = PyObject_CallFunction((PyObject *)&PyFrozenSet_Type, "(O)", names); Py_DECREF(names); return set; } /* Pre-initialization support for sys.warnoptions and sys._xoptions * * Modern internal code paths: * These APIs get called after _Py_InitializeCore and get to use the * regular CPython list, dict, and unicode APIs. * * Legacy embedding code paths: * The multi-phase initialization API isn't public yet, so embedding * apps still need to be able configure sys.warnoptions and sys._xoptions * before they call Py_Initialize. To support this, we stash copies of * the supplied wchar * sequences in linked lists, and then migrate the * contents of those lists to the sys module in _PyInitializeCore. * */ struct _preinit_entry { wchar_t *value; struct _preinit_entry *next; }; typedef struct _preinit_entry *_Py_PreInitEntry; static _Py_PreInitEntry _preinit_warnoptions = NULL; static _Py_PreInitEntry _preinit_xoptions = NULL; static _Py_PreInitEntry _alloc_preinit_entry(const wchar_t *value) { /* To get this to work, we have to initialize the runtime implicitly */ _PyRuntime_Initialize(); /* Force default allocator, so we can ensure that it also gets used to * destroy the linked list in _clear_preinit_entries. */ PyMemAllocatorEx old_alloc; _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc); _Py_PreInitEntry node = PyMem_RawCalloc(1, sizeof(*node)); if (node != NULL) { node->value = _PyMem_RawWcsdup(value); if (node->value == NULL) { PyMem_RawFree(node); node = NULL; }; }; PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc); return node; } static int _append_preinit_entry(_Py_PreInitEntry *optionlist, const wchar_t *value) { _Py_PreInitEntry new_entry = _alloc_preinit_entry(value); if (new_entry == NULL) { return -1; } /* We maintain the linked list in this order so it's easy to play back * the add commands in the same order later on in _Py_InitializeCore */ _Py_PreInitEntry last_entry = *optionlist; if (last_entry == NULL) { *optionlist = new_entry; } else { while (last_entry->next != NULL) { last_entry = last_entry->next; } last_entry->next = new_entry; } return 0; } static void _clear_preinit_entries(_Py_PreInitEntry *optionlist) { _Py_PreInitEntry current = *optionlist; *optionlist = NULL; /* Deallocate the nodes and their contents using the default allocator */ PyMemAllocatorEx old_alloc; _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc); while (current != NULL) { _Py_PreInitEntry next = current->next; PyMem_RawFree(current->value); PyMem_RawFree(current); current = next; } PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc); } PyStatus _PySys_ReadPreinitWarnOptions(PyWideStringList *options) { PyStatus status; _Py_PreInitEntry entry; for (entry = _preinit_warnoptions; entry != NULL; entry = entry->next) { status = PyWideStringList_Append(options, entry->value); if (_PyStatus_EXCEPTION(status)) { return status; } } _clear_preinit_entries(&_preinit_warnoptions); return _PyStatus_OK(); } PyStatus _PySys_ReadPreinitXOptions(PyConfig *config) { PyStatus status; _Py_PreInitEntry entry; for (entry = _preinit_xoptions; entry != NULL; entry = entry->next) { status = PyWideStringList_Append(&config->xoptions, entry->value); if (_PyStatus_EXCEPTION(status)) { return status; } } _clear_preinit_entries(&_preinit_xoptions); return _PyStatus_OK(); } static PyObject * get_warnoptions(PyThreadState *tstate) { PyObject *warnoptions = _PySys_GetAttr(tstate, &_Py_ID(warnoptions)); if (warnoptions == NULL || !PyList_Check(warnoptions)) { /* PEP432 TODO: we can reach this if warnoptions is NULL in the main * interpreter config. When that happens, we need to properly set * the `warnoptions` reference in the main interpreter config as well. * * For Python 3.7, we shouldn't be able to get here due to the * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig * call optional for embedding applications, thus making this * reachable again. */ warnoptions = PyList_New(0); if (warnoptions == NULL) { return NULL; } if (sys_set_object(tstate->interp, &_Py_ID(warnoptions), warnoptions)) { Py_DECREF(warnoptions); return NULL; } Py_DECREF(warnoptions); } return warnoptions; } void PySys_ResetWarnOptions(void) { PyThreadState *tstate = _PyThreadState_GET(); if (tstate == NULL) { _clear_preinit_entries(&_preinit_warnoptions); return; } PyObject *warnoptions = _PySys_GetAttr(tstate, &_Py_ID(warnoptions)); if (warnoptions == NULL || !PyList_Check(warnoptions)) return; PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL); } static int _PySys_AddWarnOptionWithError(PyThreadState *tstate, PyObject *option) { PyObject *warnoptions = get_warnoptions(tstate); if (warnoptions == NULL) { return -1; } if (PyList_Append(warnoptions, option)) { return -1; } return 0; } void PySys_AddWarnOptionUnicode(PyObject *option) { PyThreadState *tstate = _PyThreadState_GET(); if (_PySys_AddWarnOptionWithError(tstate, option) < 0) { /* No return value, therefore clear error state if possible */ if (tstate) { _PyErr_Clear(tstate); } } } void PySys_AddWarnOption(const wchar_t *s) { PyThreadState *tstate = _PyThreadState_GET(); if (tstate == NULL) { _append_preinit_entry(&_preinit_warnoptions, s); return; } PyObject *unicode; unicode = PyUnicode_FromWideChar(s, -1); if (unicode == NULL) return; _Py_COMP_DIAG_PUSH _Py_COMP_DIAG_IGNORE_DEPR_DECLS PySys_AddWarnOptionUnicode(unicode); _Py_COMP_DIAG_POP Py_DECREF(unicode); } int PySys_HasWarnOptions(void) { PyThreadState *tstate = _PyThreadState_GET(); PyObject *warnoptions = _PySys_GetAttr(tstate, &_Py_ID(warnoptions)); return (warnoptions != NULL && PyList_Check(warnoptions) && PyList_GET_SIZE(warnoptions) > 0); } static PyObject * get_xoptions(PyThreadState *tstate) { PyObject *xoptions = _PySys_GetAttr(tstate, &_Py_ID(_xoptions)); if (xoptions == NULL || !PyDict_Check(xoptions)) { /* PEP432 TODO: we can reach this if xoptions is NULL in the main * interpreter config. When that happens, we need to properly set * the `xoptions` reference in the main interpreter config as well. * * For Python 3.7, we shouldn't be able to get here due to the * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig * call optional for embedding applications, thus making this * reachable again. */ xoptions = PyDict_New(); if (xoptions == NULL) { return NULL; } if (sys_set_object(tstate->interp, &_Py_ID(_xoptions), xoptions)) { Py_DECREF(xoptions); return NULL; } Py_DECREF(xoptions); } return xoptions; } static int _PySys_AddXOptionWithError(const wchar_t *s) { PyObject *name = NULL, *value = NULL; PyThreadState *tstate = _PyThreadState_GET(); PyObject *opts = get_xoptions(tstate); if (opts == NULL) { goto error; } const wchar_t *name_end = wcschr(s, L'='); if (!name_end) { name = PyUnicode_FromWideChar(s, -1); value = Py_True; Py_INCREF(value); } else { name = PyUnicode_FromWideChar(s, name_end - s); value = PyUnicode_FromWideChar(name_end + 1, -1); } if (name == NULL || value == NULL) { goto error; } if (PyDict_SetItem(opts, name, value) < 0) { goto error; } Py_DECREF(name); Py_DECREF(value); return 0; error: Py_XDECREF(name); Py_XDECREF(value); return -1; } void PySys_AddXOption(const wchar_t *s) { PyThreadState *tstate = _PyThreadState_GET(); if (tstate == NULL) { _append_preinit_entry(&_preinit_xoptions, s); return; } if (_PySys_AddXOptionWithError(s) < 0) { /* No return value, therefore clear error state if possible */ _PyErr_Clear(tstate); } } PyObject * PySys_GetXOptions(void) { PyThreadState *tstate = _PyThreadState_GET(); return get_xoptions(tstate); } /* XXX This doc string is too long to be a single string literal in VC++ 5.0. Two literals concatenated works just fine. If you have a K&R compiler or other abomination that however *does* understand longer strings, get rid of the !!! comment in the middle and the quotes that surround it. */ PyDoc_VAR(sys_doc) = PyDoc_STR( "This module provides access to some objects used or maintained by the\n\ interpreter and to functions that interact strongly with the interpreter.\n\ \n\ Dynamic objects:\n\ \n\ argv -- command line arguments; argv[0] is the script pathname if known\n\ path -- module search path; path[0] is the script directory, else ''\n\ modules -- dictionary of loaded modules\n\ \n\ displayhook -- called to show results in an interactive session\n\ excepthook -- called to handle any uncaught exception other than SystemExit\n\ To customize printing in an interactive session or to install a custom\n\ top-level exception handler, assign other functions to replace these.\n\ \n\ stdin -- standard input file object; used by input()\n\ stdout -- standard output file object; used by print()\n\ stderr -- standard error object; used for error messages\n\ By assigning other file objects (or objects that behave like files)\n\ to these, it is possible to redirect all of the interpreter's I/O.\n\ \n\ last_type -- type of last uncaught exception\n\ last_value -- value of last uncaught exception\n\ last_traceback -- traceback of last uncaught exception\n\ These three are only available in an interactive session after a\n\ traceback has been printed.\n\ " ) /* concatenating string here */ PyDoc_STR( "\n\ Static objects:\n\ \n\ builtin_module_names -- tuple of module names built into this interpreter\n\ copyright -- copyright notice pertaining to this interpreter\n\ exec_prefix -- prefix used to find the machine-specific Python library\n\ executable -- absolute path of the executable binary of the Python interpreter\n\ float_info -- a named tuple with information about the float implementation.\n\ float_repr_style -- string indicating the style of repr() output for floats\n\ hash_info -- a named tuple with information about the hash algorithm.\n\ hexversion -- version information encoded as a single integer\n\ implementation -- Python implementation information.\n\ int_info -- a named tuple with information about the int implementation.\n\ maxsize -- the largest supported length of containers.\n\ maxunicode -- the value of the largest Unicode code point\n\ platform -- platform identifier\n\ prefix -- prefix used to find the Python library\n\ thread_info -- a named tuple with information about the thread implementation.\n\ version -- the version of this interpreter as a string\n\ version_info -- version information as a named tuple\n\ " ) #ifdef MS_COREDLL /* concatenating string here */ PyDoc_STR( "dllhandle -- [Windows only] integer handle of the Python DLL\n\ winver -- [Windows only] version number of the Python DLL\n\ " ) #endif /* MS_COREDLL */ #ifdef MS_WINDOWS /* concatenating string here */ PyDoc_STR( "_enablelegacywindowsfsencoding -- [Windows only]\n\ " ) #endif PyDoc_STR( "__stdin__ -- the original stdin; don't touch!\n\ __stdout__ -- the original stdout; don't touch!\n\ __stderr__ -- the original stderr; don't touch!\n\ __displayhook__ -- the original displayhook; don't touch!\n\ __excepthook__ -- the original excepthook; don't touch!\n\ \n\ Functions:\n\ \n\ displayhook() -- print an object to the screen, and save it in builtins._\n\ excepthook() -- print an exception and its traceback to sys.stderr\n\ exception() -- return the current thread's active exception\n\ exc_info() -- return information about the current thread's active exception\n\ exit() -- exit the interpreter by raising SystemExit\n\ getdlopenflags() -- returns flags to be used for dlopen() calls\n\ getprofile() -- get the global profiling function\n\ getrefcount() -- return the reference count for an object (plus one :-)\n\ getrecursionlimit() -- return the max recursion depth for the interpreter\n\ getsizeof() -- return the size of an object in bytes\n\ gettrace() -- get the global debug tracing function\n\ setdlopenflags() -- set the flags to be used for dlopen() calls\n\ setprofile() -- set the global profiling function\n\