-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpython_ifa.cc
2663 lines (2509 loc) · 89.8 KB
/
python_ifa.cc
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
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2008-2011 John Plevyak, All Rights Reserved
*/
#include "defs.h"
#include "dirent.h"
#include <unordered_map>
/* TODO
move static variables into an object
"__bases__" "__class__" "lambda"
decorators (functions applied to functions)
division and floor division correctly
Eq and Is correctly
exceptions
__radd__ etc. see __pyc__.py
*/
#define TEST_SCOPE if (debug_level && (!test_scoping || !ctx.is_builtin()))
#define EXPR_CONTEXT_SYM ((expr_context_ty)100)
typedef MapElem<cchar *, PycSymbol *> MapCharPycSymbolElem;
static int scope_id = 0;
struct PycScope : public gc {
int id;
Sym *in;
Sym *cls, *fun;
Label *lbreak, *lcontinue, *lreturn, *lyield;
Map<cchar *, PycSymbol *> map;
PycScope() : in(0), cls(0), fun(0), lbreak(0), lcontinue(0), lreturn(0), lyield(0) { id = scope_id++; }
};
struct PycContext : public gc {
cchar *filename;
int lineno;
void *node;
PyArena *arena;
PycModule *mod, *package;
Vec<PycModule *> *modules;
Vec<cchar *> *search_path;
Vec<PycScope *> scope_stack;
Vec<cchar *> c_code;
Map<void *, PycScope *> saved_scopes;
Map<int, Sym *> tuple_types;
Vec<PycScope *> imports;
bool is_builtin() { return mod->is_builtin; }
Sym *fun() { return scope_stack.last()->fun; }
Sym *cls() { return scope_stack.last()->cls; }
Label *&lbreak() { return scope_stack.last()->lbreak; }
Label *&lcontinue() { return scope_stack.last()->lcontinue; }
Label *&lreturn() { return scope_stack.last()->lreturn; }
Label *&lyield() { return scope_stack.last()->lyield; }
bool in_class() { return (cls() && scope_stack.last()->in == cls()); }
void init();
PycContext() { init(); }
PycContext(PycContext &c);
};
static Map<stmt_ty, PycAST *> stmtmap;
static Map<expr_ty, PycAST *> exprmap;
static Sym *sym_long = 0, *sym_ellipsis = 0, *sym_ellipsis_type = 0, *sym_unicode = 0, *sym_buffer = 0, *sym_xrange = 0,
*sym_declare = 0;
#define S(_x) Sym *sym_##_x = 0;
#include "pyc_symbols.h"
static cchar *cannonical_self = 0;
static int finalized_aspect = 0;
static Vec<Sym *> builtin_functions;
static void install_new_fun(Sym *f);
PycSymbol::PycSymbol() : symbol(0), filename(0), previous(0) {}
void PycContext::init() {
lineno = -1;
node = 0;
mod = package = 0;
}
PycContext::PycContext(PycContext &c) {
init();
arena = c.arena;
modules = c.modules;
search_path = c.search_path;
}
cchar *cannonicalize_string(cchar *s) { return if1_cannonicalize_string(if1, s); }
Sym *PycSymbol::clone() { return copy()->sym; }
cchar *PycSymbol::pathname() {
if (filename) return filename;
if (sym->ast) return sym->ast->pathname();
return 0;
}
int PycSymbol::column() {
PycAST *a = (PycAST *)sym->ast;
if (!a) return 0;
if (a->xstmt) return a->xstmt->lineno;
if (a->xexpr) return a->xexpr->lineno;
return 0;
}
int PycSymbol::line() {
PycAST *a = (PycAST *)sym->ast;
if (!a) return 0;
if (a->xstmt) return a->xstmt->lineno;
if (a->xexpr) return a->xexpr->lineno;
return 0;
}
int PycSymbol::source_line() {
if (sym->ast /* && !((PycAST*)sym->ast)->is_builtin */) // print them all for now
return line();
else
return 0;
}
int PycSymbol::ast_id() { return 0; }
PycAST::PycAST()
: xstmt(0),
xexpr(0),
filename(0),
parent(0),
code(0),
sym(0),
rval(0),
is_builtin(0),
is_member(0),
is_object_index(0) {
label[0] = label[1] = 0;
}
cchar *PycAST::pathname() { return filename; }
int PycAST::column() { return xstmt ? xstmt->col_offset : xexpr->col_offset; }
int PycAST::line() { return xstmt ? xstmt->lineno : xexpr->lineno; }
int PycAST::source_line() {
if (is_builtin)
return 0;
else
return line();
}
Sym *PycAST::symbol() {
if (rval) return rval;
return sym;
}
IFAAST *PycAST::copy_node(ASTCopyContext *context) {
PycAST *a = new PycAST(*this);
if (context)
for (int i = 0; i < a->pnodes.n; i++) a->pnodes[i] = context->nmap->get(a->pnodes.v[i]);
return a;
}
IFAAST *PycAST::copy_tree(ASTCopyContext *context) {
PycAST *a = (PycAST *)copy_node(context);
for (int i = 0; i < a->children.n; i++) a->children[i] = (PycAST *)a->children.v[i]->copy_tree(context);
return a;
}
Vec<Fun *> *PycAST::visible_functions(Sym *arg0) {
Vec<Fun *> *v = 0;
if (arg0->fun) {
Fun *f = arg0->fun;
v = new Vec<Fun *>;
v->add(f);
return v;
}
return NULL;
}
static cchar *stmt_string(enum _stmt_kind k) {
switch (k) {
default:
assert(!"bad case");
case FunctionDef_kind:
return "FunctionDef";
case ClassDef_kind:
return "ClassDef";
case Return_kind:
return "Return";
case Delete_kind:
return "Delete";
case Assign_kind:
return "Assign";
case AugAssign_kind:
return "AugAssign";
case Print_kind:
return "Print";
case For_kind:
return "For";
case While_kind:
return "While";
case If_kind:
return "If";
case With_kind:
return "With";
case Raise_kind:
return "Raise";
case TryExcept_kind:
return "TryExcept";
case TryFinally_kind:
return "TryFinally";
case Assert_kind:
return "Assert";
case Import_kind:
return "Import";
case ImportFrom_kind:
return "ImportFrom";
case Exec_kind:
return "Exec";
case Global_kind:
return "Global";
#if PY_MAJOR_VERSION == 3
case NonLocal_kind:
return "Global";
#endif
case Expr_kind:
return "Expr";
case Pass_kind:
return "Pass";
case Break_kind:
return "Break";
case Continue_kind:
return "Continue";
}
};
static cchar *expr_string(enum _expr_kind k) {
switch (k) {
default:
assert(!"bad case");
case BoolOp_kind:
return "BoolOp";
case BinOp_kind:
return "BinOp";
case UnaryOp_kind:
return "UnaryOp";
case Lambda_kind:
return "Lambda";
case IfExp_kind:
return "IfExp";
case Dict_kind:
return "Dict";
case ListComp_kind:
return "ListComp";
#if PY_MAJOR_VERSION == 3
case SetComp_kind:
return "SetComp";
#endif
case GeneratorExp_kind:
return "GeneratorExp";
case Yield_kind:
return "Yield";
case Compare_kind:
return "Compare";
case Call_kind:
return "Call";
case Repr_kind:
return "Repr";
case Num_kind:
return "Num";
case Str_kind:
return "Str";
case Attribute_kind:
return "Attribute";
case Subscript_kind:
return "Subscript";
#if PY_MAJOR_VERSION == 3
case Starred_kind:
return "Starred";
#endif
case Name_kind:
return "Name";
case List_kind:
return "List";
case Tuple_kind:
return "Tuple";
}
}
static void ast_html(PycAST *a, FILE *fp, Fun *f, int indent) {
Sym *s = a->sym && a->sym->name ? a->sym : a->rval;
if (a->xstmt) {
fprintf(fp, "<li>%s %s\n", stmt_string(a->xstmt->kind), s && s->name ? s->name : "");
} else if (a->xexpr) {
fprintf(fp, "<li>%s %s %s\n", expr_string(a->xexpr->kind), s && s->name ? s->name : "",
s->is_constant && s->constant ? s->constant : "");
if ((!s->is_constant || !s->constant) && a->rval) {
Vec<Sym *> consts;
if (constant_info(a, consts, a->rval)) {
fprintf(fp, ":constants {");
forv_Sym(s, consts) {
fprintf(fp, " ");
fprint_imm(fp, s->imm);
}
fprintf(fp, " }\n");
}
}
}
if (a->pre_scope_children.n + a->children.n > 0) fprintf(fp, "<ul>\n");
for (int i = 0; i < a->pre_scope_children.n; i++) ast_html(a->pre_scope_children[i], fp, f, indent + 1);
for (int i = 0; i < a->children.n; i++) ast_html(a->children[i], fp, f, indent + 1);
if (a->pre_scope_children.n + a->children.n > 0) fprintf(fp, "</ul>\n");
fprintf(fp, "</li>\n");
}
void PycAST::html(FILE *fp, Fun *f) { ast_html(this, fp, f, 0); }
static PycSymbol *new_PycSymbol(cchar *name) {
PycSymbol *s = new PycSymbol;
s->sym = new Sym;
s->sym->asymbol = s;
if1_register_sym(if1, s->sym, name);
return s;
}
static PycSymbol *new_PycSymbol(cchar *name, PycContext &ctx) {
PycSymbol *s = new_PycSymbol(name);
s->filename = ctx.filename;
return s;
}
PycSymbol *PycSymbol::copy() {
PycSymbol *s = new PycSymbol;
s->sym = sym->copy();
s->sym->asymbol = s;
if (s->sym->type_kind != Type_NONE) s->sym->type = s->sym;
return s;
}
Sym *PycCallbacks::new_Sym(cchar *name) { return new_PycSymbol(name)->sym; }
static Sym *new_sym(cchar *name = 0, int global = 0) {
Sym *s = new_PycSymbol(name)->sym;
if (!global) s->nesting_depth = LOCALLY_NESTED;
return s;
}
static Sym *new_sym(PycAST *ast, int global = 0) {
Sym *s = new_PycSymbol(0)->sym;
s->ast = ast;
s->is_local = !global;
if (s->is_local) s->nesting_depth = LOCALLY_NESTED;
return s;
}
static Sym *new_sym(PycAST *ast, cchar *name, int global = 0) {
Sym *s = new_PycSymbol(name)->sym;
s->ast = ast;
s->is_local = !global;
if (s->is_local) s->nesting_depth = LOCALLY_NESTED;
return s;
}
static Sym *new_global(PycAST *ast, cchar *name = 0) {
Sym *sym = new_PycSymbol(name)->sym;
sym->ast = ast;
sym->nesting_depth = 0;
return sym;
}
static Sym *new_base_instance(Sym *c, PycAST *ast) {
if (c->type_kind == Type_PRIMITIVE) {
if (c->num_kind) return if1_const(if1, c, "0");
if (c == sym_string) return if1_const(if1, c, "");
}
if (c == sym_nil_type) return sym_nil;
if (c == sym_list) return sym_empty_list;
if (c == sym_tuple) return sym_empty_tuple;
if (c == sym_any) return NULL;
fail("no instance for type '%s' found", c->name);
return 0;
}
static void build_builtin_symbols() {
#define S(_x) sym_##_x = if1_make_symbol(if1, #_x);
#include "pyc_symbols.h"
cannonical_self = cannonicalize_string("self");
init_default_builtin_types();
new_builtin_global_variable(sym___main__, "__main__");
new_builtin_global_variable(sym_declare, "pyc__declare__");
// override default sizes
sym_int->alias = sym_int64;
sym_float->alias = sym_float64;
sym_complex->alias = sym_complex64;
sym_size->alias = sym_int64;
sym_char->alias = sym_string;
// override default names
sym_string->name = cannonicalize_string("str");
sym_nil->name = cannonicalize_string("None");
sym_nil_type->name = cannonicalize_string("__pyc_None_type__");
sym_unknown->name = cannonicalize_string("NotImplemented");
sym_true->name = cannonicalize_string("True");
sym_false->name = cannonicalize_string("False");
sym_any->name = cannonicalize_string("__pyc_any_type__");
// new types and objects
new_builtin_primitive_type(sym_unicode, "unicode");
new_builtin_primitive_type(sym_list, "list");
new_builtin_primitive_type(sym_tuple, "tuple");
new_builtin_primitive_type(sym_buffer, "buffer");
new_builtin_primitive_type(sym_xrange, "xrange");
new_builtin_primitive_type(sym_ellipsis_type, "Ellipsis_type");
new_builtin_alias_type(sym_long, "long", sym_int64); // standin for GNU gmp
new_builtin_unique_object(sym_ellipsis, "Ellipsis", sym_ellipsis_type);
sym_ellipsis_type->is_unique_type = 1;
#define B(_x) builtin_functions.set_add(sym_##_x);
#include "pyc_symbols.h"
sym_list->element = new_sym();
sym_vector->element = new_sym();
}
static inline PycAST *getAST(stmt_ty s, PycContext &ctx) {
PycAST *ast = stmtmap.get(s);
if (ast) return ast;
ast = new PycAST;
ast->filename = ctx.filename;
ast->is_builtin = ctx.is_builtin();
ast->xstmt = s;
stmtmap.put(s, ast);
return ast;
}
static inline PycAST *getAST(expr_ty e, PycContext &ctx) {
PycAST *ast = exprmap.get(e);
if (ast) return ast;
ast = new PycAST;
ast->filename = ctx.filename;
ast->is_builtin = ctx.is_builtin();
ast->xexpr = e;
exprmap.put(e, ast);
return ast;
}
static inline Sym *gen_or_default(expr_ty e, Sym *def, PycAST *ast, PycContext &ctx) {
if (e) {
PycAST *east = getAST(e, ctx);
if1_gen(if1, &ast->code, east->code);
return east->rval;
} else
return def;
}
#if 0
static inline PycAST *getAST(stmt_ty s, PycAST *a) {
PycAST *ast = stmtmap.get(s);
if (ast) return ast;
ast = new PycAST;
ast->filename = a->filename;
ast->is_builtin = a->is_builtin;
ast->xstmt = s;
stmtmap.put(s, ast);
return ast;
}
#endif
static inline PycAST *getAST(expr_ty e, PycAST *a) {
PycAST *ast = exprmap.get(e);
if (ast) return ast;
ast = new PycAST;
ast->filename = a->filename;
ast->is_builtin = a->is_builtin;
ast->xexpr = e;
exprmap.put(e, ast);
return ast;
}
static void finalize_function(Fun *f) {
Sym *fn = f->sym;
if (!f->ast) return; // __main__
PycAST *a = (PycAST *)f->ast;
arguments_ty args = 0;
if (a->xstmt) {
stmt_ty s = a->xstmt;
if (s->kind != FunctionDef_kind) {
if (!fn->init || ((PycAST *)fn->init->ast)->xstmt->kind != FunctionDef_kind) return;
s = ((PycAST *)fn->init->ast)->xstmt;
}
args = s->v.FunctionDef.args;
} else if (a->xexpr && a->xexpr->kind == Lambda_kind)
args = a->xexpr->v.Lambda.args;
if (args) {
int defaults_len = args ? asdl_seq_LEN(args->defaults) : 0;
if (defaults_len) {
int skip = fn->has.n - defaults_len;
assert(skip >= 0);
MPosition p;
p.push(skip + 1);
for (int i = 0; i < fn->has.n - skip; i++) {
fn->fun->default_args.put(cannonicalize_mposition(p), getAST((expr_ty)asdl_seq_GET(args->defaults, i), a));
p.inc();
}
}
}
}
void PycCallbacks::finalize_functions() { forv_Fun(fun, pdb->funs) finalize_function(fun); }
static Sym *new_fun(PycAST *ast, Sym *fun = 0) {
if (!fun)
fun = new_sym(ast, 1);
else
fun->ast = ast;
if (!fun->name && ast->rval && ast->rval->name) fun->name = ast->rval->name;
fun->is_fun = 1;
fun->cont = new_sym(ast);
fun->ret = new_sym(ast);
return fun;
}
Fun *PycCallbacks::default_wrapper(Fun *f, Vec<MPosition *> &default_args) {
PycAST *ast = (PycAST *)f->ast;
Sym *fn = new_fun(ast);
fn->nesting_depth = f->sym->nesting_depth;
Vec<Sym *> as;
int n = f->sym->has.n - default_args.n;
MPosition pos;
pos.push(1);
Code *body = 0;
Sym *ret = new_sym(ast);
Code *send = if1_send(if1, &body, 0, 1, ret);
send->ast = ast;
for (int i = 0; i < n; i++) {
Sym *a = new_sym(ast);
as.add(a);
if1_add_send_arg(if1, send, a);
pos.inc();
}
for (int i = 0; i < default_args.n; i++) {
if1_add_send_arg(if1, send, ((PycAST *)f->default_args.get(cannonicalize_mposition(pos)))->sym);
pos.inc();
}
if1_move(if1, &body, ret, fn->ret, ast);
if1_send(if1, &body, 4, 0, sym_primitive, sym_reply, fn->cont, fn->ret)->ast = ast;
if1_closure(if1, fn, body, as.n, as.v);
install_new_fun(fn);
fn->fun->wraps = f;
return fn->fun;
}
bool PycCallbacks::reanalyze(Vec<ATypeViolation *> &type_violations) {
if (!type_violations.n) return false;
bool again = false;
forv_Vec(ATypeViolation, v, type_violations) if (v) {
if (v->kind == ATypeViolation_NOTYPE) {
if (!v->av->var->def || v->av->var->def->rvals.n < 2) continue;
AVar *av = make_AVar(v->av->var->def->rvals[1], (EntrySet *)v->av->contour);
forv_CreationSet(cs, av->out->sorted) {
forv_Vec(cchar *, i, cs->unknown_vars) {
if (cs->var_map.get(i)) continue;
again = true;
Sym *s = new_PycSymbol(i)->sym;
s->var = new Var(s);
cs->sym->has.add(s);
AVar *iv = unique_AVar(s->var, cs);
add_var_constraint(iv);
cs->vars.add(iv);
cs->var_map.put(i, iv);
}
}
}
}
return again;
}
bool PycCallbacks::c_codegen_pre_file(FILE *fp) {
for (int i = 0; i < ctx->c_code.n; i++) {
fputs(ctx->c_code[i], fp);
fputs("\n", fp);
}
return true;
}
template <class C>
static void add(asdl_seq *seq, Vec<PycAST *> &asts, PycContext &ctx) {
for (int i = 0; i < asdl_seq_LEN(seq); i++) asts.add(getAST((C)asdl_seq_GET(seq, i), ctx));
}
static void add(expr_ty e, Vec<PycAST *> &asts, PycContext &ctx) {
if (e) asts.add(getAST(e, ctx));
}
// static void add(stmt_ty s, Vec<PycAST*> &asts, PycContext &ctx) { if (s) stmts.add(getAST(s)); } unused
static void add_comprehension(asdl_seq *comp, Vec<PycAST *> &asts, PycContext &ctx) {
int l = asdl_seq_LEN(comp);
for (int i = 0; i < l; i++) {
comprehension_ty c = (comprehension_ty)asdl_seq_GET(comp, i);
add(c->target, asts, ctx);
if (i != 0) add(c->iter, asts, ctx);
add<expr_ty>(c->ifs, asts, ctx);
}
}
static void get_pre_scope_next(stmt_ty s, Vec<PycAST *> &asts, PycContext &ctx) {
switch (s->kind) {
default:
break;
case FunctionDef_kind:
add<expr_ty>(s->v.FunctionDef.args->defaults, asts, ctx);
add<expr_ty>(s->v.FunctionDef.decorator_list, asts, ctx);
break;
case ClassDef_kind:
add<expr_ty>(s->v.ClassDef.bases, asts, ctx);
break;
}
}
static void get_next(stmt_ty s, Vec<PycAST *> &asts, PycContext &ctx) {
switch (s->kind) {
default:
assert(!"case");
case FunctionDef_kind:
add<expr_ty>(s->v.FunctionDef.args->args, asts, ctx);
add<stmt_ty>(s->v.FunctionDef.body, asts, ctx);
break;
case ClassDef_kind:
add<stmt_ty>(s->v.ClassDef.body, asts, ctx);
break;
case Return_kind:
add(s->v.Return.value, asts, ctx);
break;
case Delete_kind:
add<expr_ty>(s->v.Delete.targets, asts, ctx);
break;
case Assign_kind:
add<expr_ty>(s->v.Assign.targets, asts, ctx);
add(s->v.Assign.value, asts, ctx);
break;
case AugAssign_kind:
add(s->v.AugAssign.target, asts, ctx);
add(s->v.AugAssign.value, asts, ctx);
break;
case Print_kind:
add(s->v.Print.dest, asts, ctx);
add<expr_ty>(s->v.Print.values, asts, ctx);
break;
case For_kind:
add(s->v.For.target, asts, ctx);
add(s->v.For.iter, asts, ctx);
add<stmt_ty>(s->v.For.body, asts, ctx);
add<stmt_ty>(s->v.For.orelse, asts, ctx);
break;
case While_kind:
add(s->v.While.test, asts, ctx);
add<stmt_ty>(s->v.While.body, asts, ctx);
add<stmt_ty>(s->v.While.orelse, asts, ctx);
break;
case If_kind:
add(s->v.If.test, asts, ctx);
add<stmt_ty>(s->v.If.body, asts, ctx);
add<stmt_ty>(s->v.If.orelse, asts, ctx);
break;
case With_kind:
add(s->v.With.context_expr, asts, ctx);
add(s->v.With.optional_vars, asts, ctx);
add<stmt_ty>(s->v.With.body, asts, ctx);
break;
case Raise_kind:
add(s->v.Raise.type, asts, ctx);
add(s->v.Raise.inst, asts, ctx);
add(s->v.Raise.tback, asts, ctx);
break;
case TryExcept_kind: {
add<stmt_ty>(s->v.TryExcept.body, asts, ctx);
for (int i = 0; i < asdl_seq_LEN(s->v.TryExcept.handlers); i++) {
excepthandler_ty h = (excepthandler_ty)asdl_seq_GET(s->v.TryExcept.handlers, i);
add(h->v.ExceptHandler.type, asts, ctx);
add(h->v.ExceptHandler.name, asts, ctx);
add<stmt_ty>(h->v.ExceptHandler.body, asts, ctx);
}
add<stmt_ty>(s->v.TryExcept.orelse, asts, ctx);
break;
}
case TryFinally_kind:
add<stmt_ty>(s->v.TryFinally.body, asts, ctx);
add<stmt_ty>(s->v.TryFinally.finalbody, asts, ctx);
break;
case Assert_kind:
add(s->v.Assert.test, asts, ctx);
add(s->v.Assert.msg, asts, ctx);
break;
case Import_kind:
break;
case ImportFrom_kind:
break;
case Exec_kind:
add(s->v.Exec.body, asts, ctx);
add(s->v.Exec.globals, asts, ctx);
add(s->v.Exec.locals, asts, ctx);
break;
case Global_kind:
break;
#if PY_MAJOR_VERSION == 3
case Nonlocal_kind:
break;
#endif
case Expr_kind:
add(s->v.Expr.value, asts, ctx);
break;
case Pass_kind:
case Break_kind:
case Continue_kind:
break;
}
}
static void get_next(slice_ty s, Vec<PycAST *> &asts, PycContext &ctx) {
switch (s->kind) {
default:
assert(!"case");
case Ellipsis_kind:
break;
case Slice_kind: // (expr? lower, expr? upper, expr? step)
add(s->v.Slice.lower, asts, ctx);
add(s->v.Slice.upper, asts, ctx);
add(s->v.Slice.step, asts, ctx);
break;
case ExtSlice_kind: // (slice* dims)
for (int i = 0; i < asdl_seq_LEN(s->v.ExtSlice.dims); i++)
get_next((slice_ty)asdl_seq_GET(s->v.ExtSlice.dims, i), asts, ctx);
break;
case Index_kind: // (expr value)
add(s->v.Index.value, asts, ctx);
break;
}
}
static void get_pre_scope_next(expr_ty e, Vec<PycAST *> &asts, PycContext &ctx) {
switch (e->kind) {
default:
break;
case Lambda_kind:
add<expr_ty>(e->v.Lambda.args->defaults, asts, ctx);
break;
case Dict_kind: // expr* keys, expr* values
#if PY_MAJOR_VERSION == 3
add(((comprehension_ty)asdl_seq_GET(e->v.Dict.generators, 0))->iter, asts, ctx);
#endif
break;
case ListComp_kind: // expr elt, comprehension* generators
add(((comprehension_ty)asdl_seq_GET(e->v.ListComp.generators, 0))->iter, asts, ctx);
break;
#if PY_MAJOR_VERSION == 3
case SetComp_kind:
add(((comprehension_ty)asdl_seq_GET(e->v.SetComp.generators, 0))->iter, asts, ctx);
break;
#endif
case GeneratorExp_kind: // expr elt, comprehension* generators
add(((comprehension_ty)asdl_seq_GET(e->v.GeneratorExp.generators, 0))->iter, asts, ctx);
break;
}
}
static void get_next(expr_ty e, Vec<PycAST *> &asts, PycContext &ctx) {
switch (e->kind) {
default:
assert(!"case");
case BoolOp_kind: // boolop op, expr* values
add<expr_ty>(e->v.BoolOp.values, asts, ctx);
break;
case BinOp_kind: // expr left, operator op, expr right
add(e->v.BinOp.left, asts, ctx);
add(e->v.BinOp.right, asts, ctx);
break;
case UnaryOp_kind: // unaryop op, expr operand
add(e->v.UnaryOp.operand, asts, ctx);
break;
case Lambda_kind: // arguments args, expr body
add<expr_ty>(e->v.Lambda.args->args, asts, ctx);
add(e->v.Lambda.body, asts, ctx);
break;
case IfExp_kind: // expr test, expr body, expr orelse
add(e->v.IfExp.test, asts, ctx);
add(e->v.IfExp.body, asts, ctx);
add(e->v.IfExp.orelse, asts, ctx);
break;
case Dict_kind: // expr* keys, expr* values
#if PY_MAJOR_VERSION == 3
add_comprehension(e->v.Dict.generators, asts, ctx);
add(e->v.Dict.value, asts, ctx);
add(e->v.Dict.key, asts, ctx);
#else
add<expr_ty>(e->v.Dict.keys, asts, ctx);
add<expr_ty>(e->v.Dict.values, asts, ctx);
#endif
break;
case ListComp_kind: // expr elt, comprehension* generators
add_comprehension(e->v.ListComp.generators, asts, ctx);
add(e->v.ListComp.elt, asts, ctx);
break;
#if PY_MAJOR_VERSION == 3
case SetComp_kind:
add_comprehension(e->v.SetComp.generators, asts, ctx);
add(e->v.ListComp.elt, asts, ctx);
break;
#endif
case GeneratorExp_kind: // expr elt, comprehension* generators
add_comprehension(e->v.GeneratorExp.generators, asts, ctx);
add(e->v.GeneratorExp.elt, asts, ctx);
break;
case Yield_kind: // expr? value
add(e->v.Yield.value, asts, ctx);
break;
case Compare_kind: // expr left, cmpop* ops, expr* comparators
add(e->v.Compare.left, asts, ctx);
add<expr_ty>(e->v.Compare.comparators, asts, ctx);
break;
case Call_kind: // expr func, expr* args, keyword* keywords, expr? starargs, expr? kwargs
add(e->v.Call.func, asts, ctx);
add<expr_ty>(e->v.Call.args, asts, ctx);
add(e->v.Call.starargs, asts, ctx);
add(e->v.Call.kwargs, asts, ctx);
break;
case Repr_kind: // expr value
add(e->v.Repr.value, asts, ctx);
break;
case Num_kind: // object n) -- a number as a PyObject
case Str_kind: // string s) -- need to specify raw, unicode, etc
break;
case Attribute_kind: // expr value, identifier attr, expr_context ctx
add(e->v.Attribute.value, asts, ctx);
break;
case Subscript_kind: // expr value, slice slice, expr_context ctx
add(e->v.Subscript.value, asts, ctx);
get_next(e->v.Subscript.slice, asts, ctx);
break;
case Name_kind: // identifier id, expr_context ctx
break;
case List_kind: // expr* elts, expr_context ctx
add<expr_ty>(e->v.List.elts, asts, ctx);
break;
case Tuple_kind: // expr *elts, expr_context ctx
add<expr_ty>(e->v.Tuple.elts, asts, ctx);
break;
}
}
static void enter_scope(PycContext &ctx, Sym *in = 0) {
PycScope *c = ctx.saved_scopes.get(ctx.node);
if (!c) {
c = new PycScope;
c->in = in;
if (ctx.scope_stack.n) {
c->fun = ctx.scope_stack.last()->fun;
c->cls = ctx.scope_stack.last()->cls;
}
if (in) {
if (in->is_fun || (in->alias && in->alias->is_fun))
c->fun = in;
else
c->cls = in;
}
ctx.saved_scopes.put(ctx.node, c);
}
ctx.scope_stack.add(c);
TEST_SCOPE printf("enter scope level %d\n", ctx.scope_stack.n);
}
static void enter_scope(PycContext &ctx, mod_ty mod) {
ctx.node = mod;
enter_scope(ctx);
}
static void enter_scope(stmt_ty x, PycAST *ast, PycContext &ctx) {
ctx.node = x;
if (x->kind == FunctionDef_kind)
enter_scope(ctx, ast->rval);
else if (x->kind == ClassDef_kind)
enter_scope(ctx, ast->sym);
}
static int needs_scope(expr_ty x) {
return (x->kind == Lambda_kind || x->kind == GeneratorExp_kind || x->kind == Dict_kind ||
x->kind ==
ListComp_kind
#if PY_MAJOR_VERSION == 3
x->kind == SetComp_kind
#endif
);
}
static void enter_scope(expr_ty x, PycAST *ast, PycContext &ctx) {
ctx.node = x;
if (needs_scope(x)) enter_scope(ctx, ast->rval);
}
static void exit_scope(PycContext &ctx) {
TEST_SCOPE printf("exit scope level %d\n", ctx.scope_stack.n);
ctx.scope_stack.pop();
}
static void exit_scope(stmt_ty x, PycContext &ctx) {
ctx.node = x;
if (x->kind == FunctionDef_kind || x->kind == ClassDef_kind) exit_scope(ctx);
}
static void exit_scope(expr_ty x, PycContext &ctx) {
ctx.node = x;
if (needs_scope(x)) exit_scope(ctx);
}
#define EXPLICITLY_MARKED 1
#define IMPLICITLY_MARKED 2
enum PYC_SCOPINGS { PYC_USE, PYC_LOCAL, PYC_GLOBAL, PYC_NONLOCAL };
static cchar *pyc_scoping_names[] = {"use", "local", "global", "nonlocal"};
#define GLOBAL_USE ((PycSymbol *)(intptr_t)1)
#define NONLOCAL_USE ((PycSymbol *)(intptr_t)2)
#define GLOBAL_DEF ((PycSymbol *)(intptr_t)3)
#define NONLOCAL_DEF ((PycSymbol *)(intptr_t)4)
#define MARKED(_x) (((uintptr_t)(_x)) < 5)
static PycSymbol *find_PycSymbol(PycContext &ctx, cchar *name, int *level = 0, int *type = 0) {
PycSymbol *l = 0;
int i = ctx.scope_stack.n - 1, xtype = 0;
int end = -ctx.imports.n;
for (; i >= end; i--) {
bool top = i == ctx.scope_stack.n - 1;
PycScope *s = i >= 0 ? ctx.scope_stack[i] : ctx.imports.v[-i - 1];
if ((l = s->map.get(name))) {
if (l == NONLOCAL_USE || l == NONLOCAL_DEF) {
if (top) xtype = (l == NONLOCAL_DEF) ? EXPLICITLY_MARKED : IMPLICITLY_MARKED;
continue;
}
if (l == GLOBAL_USE || l == GLOBAL_DEF) {
assert(i > end);
if (top) xtype = (l == GLOBAL_DEF) ? EXPLICITLY_MARKED : IMPLICITLY_MARKED;
i = i > 1 ? 1 : i;
continue;
}
break;
}
}
if (level) *level = i;
if (type) *type = xtype;
return l;
}
// static PycSymbol *find_PycSymbol(PycContext &ctx, PyObject *o, int *level = 0, int *type = 0) {
// return find_PycSymbol(ctx, cannonicalize_string(PyString_AS_STRING(o)), level, type);
//}
static PycSymbol *make_PycSymbol(PycContext &ctx, cchar *n, PYC_SCOPINGS scoping) {
cchar *name = cannonicalize_string(n);
TEST_SCOPE printf("make_PycSymbol %s '%s'\n", pyc_scoping_names[(int)scoping], name);
int level = 0, type = 0;
PycSymbol *l = find_PycSymbol(ctx, name, &level, &type), *previous = l;
bool local = l && (ctx.scope_stack.n - 1 == level); // implies !explicitly && !implicitly
bool global = l && !level;
bool nonlocal = l && !global && !local;
bool explicitly = type == EXPLICITLY_MARKED;
bool implicitly = type == IMPLICITLY_MARKED;
bool isfun = l && (l->sym->is_fun || (l->sym->alias && l->sym->alias->is_fun));
switch (scoping) {
case PYC_USE: {
if (!l) goto Lglobal; // not found
if (!local && !explicitly) {
if (global)
ctx.scope_stack.last()->map.put(name, GLOBAL_USE);
else
ctx.scope_stack.last()->map.put(name, NONLOCAL_USE);
}
break;
}
case PYC_LOCAL:
if ((local || explicitly) && !isfun) break;
if (implicitly && !isfun) fail("error line %d, '%s' redefined as local", ctx.lineno, name);
ctx.scope_stack.last()->map.put(name, (l = new_PycSymbol(name, ctx)));
if (local && previous) l->previous = previous;
break;
case PYC_GLOBAL:
Lglobal:;
if (l && !global && (local || explicitly || implicitly))
fail("error line %d, '%s' redefined as global", ctx.lineno, name);
if (!global) {
PycSymbol *g = ctx.scope_stack[0]->map.get(name);
if (!g) ctx.scope_stack[0]->map.put(name, (l = new_PycSymbol(name, ctx)));
}
if (!explicitly && !(ctx.scope_stack.n == 1)) ctx.scope_stack.last()->map.put(name, GLOBAL_DEF);
break;
case PYC_NONLOCAL:
if (!l || (!nonlocal && (local || explicitly || implicitly)))
fail("error line %d, '%s' nonlocal redefined or not found", ctx.lineno, name);
ctx.scope_stack.last()->map.put(name, NONLOCAL_DEF);
break;