forked from leafgray/pysonar2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Builtins.java
2293 lines (1958 loc) · 94.4 KB
/
Builtins.java
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
package org.python.indexer;
import org.python.indexer.ast.Url;
import org.python.indexer.types.*;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import static org.python.indexer.Binding.Kind.*;
/**
* Initializes the built-in types, functions and modules.
* This approach was easy (if tedious) to implement, but longer-term
* it would be better to define these type signatures in python
* "externs files", using a standard type annotation syntax.
*/
public class Builtins {
public static final String LIBRARY_URL = "http://docs.python.org/library/";
public static final String TUTORIAL_URL = "http://docs.python.org/tutorial/";
public static final String REFERENCE_URL = "http://docs.python.org/reference/";
public static final String DATAMODEL_URL = "http://docs.python.org/reference/datamodel#";
public static Url newLibUrl(String module, String name) {
return newLibUrl(module + ".html#" + name);
}
public static Url newLibUrl(String path) {
if (!path.contains("#") && !path.endsWith(".html")) {
path += ".html";
}
return new Url(LIBRARY_URL + path);
}
public static Url newRefUrl(String path) {
return new Url(REFERENCE_URL + path);
}
public static Url newDataModelUrl(String path) {
return new Url(DATAMODEL_URL + path);
}
public static Url newTutUrl(String path) {
return new Url(TUTORIAL_URL + path);
}
// XXX: need to model "types" module and reconcile with these types
public ModuleType Builtin;
public UnknownType unknown = new UnknownType();
public ClassType Object;
public ClassType Type;
public InstanceType None;
public InstanceType Cont;
public InstanceType BaseNum; // BaseNum models int, float and long
public InstanceType BaseFloat; // BaseNum models int, float and long
public InstanceType BaseComplex;
public InstanceType BaseBool;
public InstanceType BaseStr;
public ClassType BaseList;
public ClassType BaseArray;
public ClassType BaseDict;
public ClassType BaseTuple;
public ClassType BaseModule;
public ClassType BaseFile;
public ClassType BaseException;
public ClassType BaseStruct;
public ClassType BaseFunction; // models functions, lambas and methods
public ClassType BaseClass; // models classes and instances
public ClassType Datetime_datetime;
public ClassType Datetime_date;
public ClassType Datetime_time;
public ClassType Datetime_timedelta;
public ClassType Datetime_tzinfo;
public ClassType Time_struct_time;
Scope globaltable;
Scope moduleTable;
String[] builtin_exception_types = {
"ArithmeticError", "AssertionError", "AttributeError",
"BaseException", "Exception", "DeprecationWarning", "EOFError",
"EnvironmentError", "FloatingPointError", "FutureWarning",
"GeneratorExit", "IOError", "ImportError", "ImportWarning",
"IndentationError", "IndexError", "KeyError", "KeyboardInterrupt",
"LookupError", "MemoryError", "NameError", "NotImplemented",
"NotImplementedError", "OSError", "OverflowError",
"PendingDeprecationWarning", "ReferenceError", "RuntimeError",
"RuntimeWarning", "StandardError", "StopIteration", "SyntaxError",
"SyntaxWarning", "SystemError", "SystemExit", "TabError",
"TypeError", "UnboundLocalError", "UnicodeDecodeError",
"UnicodeEncodeError", "UnicodeError", "UnicodeTranslateError",
"UnicodeWarning", "UserWarning", "ValueError", "Warning",
"ZeroDivisionError"
};
Set<org.python.indexer.types.Type> nativeTypes = new HashSet<org.python.indexer.types.Type>();
ClassType newClass(String name, Scope table) {
return newClass(name, table, null);
}
ClassType newClass(String name, Scope table,
ClassType superClass, ClassType... moreSupers) {
ClassType t = new ClassType(name, table, superClass);
for (ClassType c : moreSupers) {
t.addSuper(c);
}
nativeTypes.add(t);
return t;
}
ModuleType newModule(String name) {
ModuleType mt = new ModuleType(name, null, globaltable);
nativeTypes.add(mt);
return mt;
}
UnknownType unknown() {
UnknownType t = Indexer.idx.builtins.unknown;
nativeTypes.add(t);
return t;
}
ClassType newException(String name, Scope t) {
return newClass(name, t, BaseException);
}
FunType newFunc() {
FunType t = new FunType();
nativeTypes.add(t);
return t;
}
FunType newFunc(org.python.indexer.types.Type type) {
FunType t = new FunType(Indexer.idx.builtins.unknown, type);
nativeTypes.add(t);
return t;
}
ListType newList() {
return newList(unknown());
}
ListType newList(org.python.indexer.types.Type type) {
ListType t = new ListType(type);
nativeTypes.add(t);
return t;
}
DictType newDict(org.python.indexer.types.Type ktype, org.python.indexer.types.Type vtype) {
DictType t = new DictType(ktype, vtype);
nativeTypes.add(t);
return t;
}
TupleType newTuple(org.python.indexer.types.Type... types) {
TupleType t = new TupleType(types);
nativeTypes.add(t);
return t;
}
UnionType newUnion(org.python.indexer.types.Type... types) {
UnionType t = new UnionType(types);
nativeTypes.add(t);
return t;
}
String[] list(String... names) {
return names;
}
private abstract class NativeModule {
protected String name;
protected ModuleType module;
protected Scope table; // the module's symbol table
NativeModule(String name) {
this.name = name;
modules.put(name, this);
}
/** Lazily load the module. */
ModuleType getModule() {
if (module == null) {
createModuleType();
initBindings();
}
return module;
}
protected abstract void initBindings();
protected void createModuleType() {
if (module == null) {
module = newModule(name);
table = module.getTable();
moduleTable.put(name, liburl(), module, MODULE, 0);
}
}
protected Binding update(String name, Url url, org.python.indexer.types.Type type, Binding.Kind kind) {
return table.update(name, url, type, kind);
}
protected Binding addClass(String name, Url url, org.python.indexer.types.Type type) {
return table.update(name, url, type, CLASS);
}
protected Binding addMethod(String name, Url url, org.python.indexer.types.Type type) {
return table.update(name, url, type, METHOD);
}
protected Binding addFunction(String name, Url url, org.python.indexer.types.Type type) {
return table.update(name, url, newFunc(type), FUNCTION);
}
// don't use this unless you're sure it's OK to share the type object
protected void addFunctions_beCareful(org.python.indexer.types.Type type, String... names) {
for (String name : names) {
addFunction(name, liburl(), type);
}
}
protected void addNoneFuncs(String... names) {
addFunctions_beCareful(None, names);
}
protected void addNumFuncs(String... names) {
addFunctions_beCareful(BaseNum, names);
}
protected void addStrFuncs(String... names) {
addFunctions_beCareful(BaseStr, names);
}
protected void addUnknownFuncs(String... names) {
for (String name : names) {
addFunction(name, liburl(), unknown());
}
}
protected Binding addAttr(String name, Url url, org.python.indexer.types.Type type) {
return table.update(name, url, type, ATTRIBUTE);
}
// don't use this unless you're sure it's OK to share the type object
protected void addAttributes_beCareful(org.python.indexer.types.Type type, String... names) {
for (String name : names) {
addAttr(name, liburl(), type);
}
}
protected void addNumAttrs(String... names) {
addAttributes_beCareful(BaseNum, names);
}
protected void addStrAttrs(String... names) {
addAttributes_beCareful(BaseStr, names);
}
protected void addUnknownAttrs(String... names) {
for (String name : names) {
addAttr(name, liburl(), unknown());
}
}
protected Url liburl() {
return newLibUrl(name);
}
protected Url liburl(String anchor) {
return newLibUrl(name, anchor);
}
@Override
public String toString() {
return module == null
? "<Non-loaded builtin module '" + name + "'>"
: "<NativeModule:" + module + ">";
}
}
/**
* The set of top-level native modules.
*/
private Map<String, NativeModule> modules = new HashMap<String, NativeModule>();
public Builtins(Scope globals, Scope modules) {
globaltable = globals;
moduleTable = modules;
buildTypes();
}
private void buildTypes() {
new BuiltinsModule();
Scope bt = Builtin.getTable();
Object = newClass("object", bt);
None = new InstanceType(newClass("None", bt));
Cont = new InstanceType(newClass("None", bt)); // continuation (to express non-return)
Type = newClass("type", bt, Object);
BaseTuple = newClass("tuple", bt, Object);
BaseList = newClass("list", bt, Object);
BaseArray = newClass("array", bt);
BaseDict = newClass("dict", bt, Object);
ClassType numClass = newClass("int", bt, Object);
BaseNum = new InstanceType(numClass);
BaseFloat = new InstanceType(newClass("float", bt, Object));
BaseComplex = new InstanceType(newClass("complex", bt, Object));
BaseBool = new InstanceType(newClass("bool", bt, numClass));
BaseStr = new InstanceType(newClass("str", bt, Object));
BaseModule = newClass("module", bt);
BaseFile = newClass("file", bt, Object);
BaseFunction = newClass("function", bt, Object);
BaseClass = newClass("classobj", bt, Object);
}
void init() {
buildObjectType();
buildTupleType();
buildArrayType();
buildListType();
buildDictType();
buildNumTypes();
buildStrType();
buildModuleType();
buildFileType();
buildFunctionType();
buildClassType();
modules.get("__builtin__").initBindings(); // eagerly load these bindings
new ArrayModule();
new AudioopModule();
new BinasciiModule();
new Bz2Module();
new CPickleModule();
new CStringIOModule();
new CMathModule();
new CollectionsModule();
new CryptModule();
new CTypesModule();
new DatetimeModule();
new DbmModule();
new ErrnoModule();
new ExceptionsModule();
new FcntlModule();
new FpectlModule();
new GcModule();
new GdbmModule();
new GrpModule();
new ImpModule();
new ItertoolsModule();
new MarshalModule();
new MathModule();
new Md5Module();
new MmapModule();
new NisModule();
new OperatorModule();
new OsModule();
new ParserModule();
new PosixModule();
new PwdModule();
new PyexpatModule();
new ReadlineModule();
new ResourceModule();
new SelectModule();
new SignalModule();
new ShaModule();
new SpwdModule();
new StropModule();
new StructModule();
new SysModule();
new SyslogModule();
new TermiosModule();
new ThreadModule();
new TimeModule();
new UnicodedataModule();
new ZipimportModule();
new ZlibModule();
}
/**
* Loads (if necessary) and returns the specified built-in module.
*/
public ModuleType get(String name) {
if (name.startsWith(".")) {
return null;
}
if (name.indexOf(".") == -1) { // unqualified
return getModule(name);
}
String[] mods = name.split("\\.");
org.python.indexer.types.Type type = getModule(mods[0]);
if (type == null) {
return null;
}
for (int i = 1; i < mods.length; i++) {
type = type.getTable().lookupType(mods[i]);
if (!(type instanceof ModuleType)) {
return null;
}
}
return (ModuleType)type;
}
private ModuleType getModule(String name) {
NativeModule wrap = modules.get(name);
return wrap == null ? null : wrap.getModule();
}
public boolean isNative(org.python.indexer.types.Type type) {
return nativeTypes.contains(type);
}
void buildObjectType() {
String[] obj_methods = {
"__delattr__", "__format__", "__getattribute__", "__hash__",
"__init__", "__new__", "__reduce__", "__reduce_ex__",
"__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__"
};
for (String m : obj_methods) {
Object.getTable().update(m, newLibUrl("stdtypes"), newFunc(), METHOD);
}
Object.getTable().update("__doc__", newLibUrl("stdtypes"), BaseStr, CLASS);
Object.getTable().update("__class__", newLibUrl("stdtypes"), unknown(), CLASS);
}
void buildTupleType() {
Scope bt = BaseTuple.getTable();
String[] tuple_methods = {
"__add__", "__contains__", "__eq__", "__ge__", "__getnewargs__",
"__gt__", "__iter__", "__le__", "__len__", "__lt__", "__mul__",
"__ne__", "__new__", "__rmul__", "count", "index"
};
for (String m : tuple_methods) {
bt.update(m, newLibUrl("stdtypes"), newFunc(), METHOD);
}
Binding b = bt.update("__getslice__", newDataModelUrl("object.__getslice__"),
newFunc(), METHOD);
b.markDeprecated();
bt.update("__getitem__", newDataModelUrl("object.__getitem__"), newFunc(), METHOD);
bt.update("__iter__", newDataModelUrl("object.__iter__"), newFunc(), METHOD);
}
void buildArrayType() {
String[] array_methods_none = {
"append", "buffer_info", "byteswap", "extend", "fromfile",
"fromlist", "fromstring", "fromunicode", "index", "insert", "pop",
"read", "remove", "reverse", "tofile", "tolist", "typecode", "write"
};
for (String m : array_methods_none) {
BaseArray.getTable().update(m, newLibUrl("array"), newFunc(None), METHOD);
}
String[] array_methods_num = { "count", "itemsize", };
for (String m : array_methods_num) {
BaseArray.getTable().update(m, newLibUrl("array"), newFunc(BaseNum), METHOD);
}
String[] array_methods_str = { "tostring", "tounicode", };
for (String m : array_methods_str) {
BaseArray.getTable().update(m, newLibUrl("array"), newFunc(BaseStr), METHOD);
}
}
void buildListType() {
BaseList.getTable().update("__getslice__", newDataModelUrl("object.__getslice__"),
newFunc(BaseList), METHOD);
BaseList.getTable().update("__getitem__", newDataModelUrl("object.__getitem__"),
newFunc(BaseList), METHOD);
BaseList.getTable().update("__iter__", newDataModelUrl("object.__iter__"),
newFunc(BaseList), METHOD);
String[] list_methods_none = {
"append", "extend", "index", "insert", "pop", "remove", "reverse", "sort"
};
for (String m : list_methods_none) {
BaseList.getTable().update(m, newLibUrl("stdtypes"), newFunc(None), METHOD);
}
String[] list_methods_num = { "count" };
for (String m : list_methods_num) {
BaseList.getTable().update(m, newLibUrl("stdtypes"), newFunc(BaseNum), METHOD);
}
}
Url numUrl() {
return newLibUrl("stdtypes", "typesnumeric");
}
void buildNumTypes() {
Scope bft = BaseFloat.getTable();
String[] float_methods_num = {
"__abs__", "__add__", "__coerce__", "__div__", "__divmod__",
"__eq__", "__float__", "__floordiv__", "__format__",
"__ge__", "__getformat__", "__gt__", "__int__",
"__le__", "__long__", "__lt__", "__mod__", "__mul__", "__ne__",
"__neg__", "__new__", "__nonzero__", "__pos__", "__pow__",
"__radd__", "__rdiv__", "__rdivmod__", "__rfloordiv__", "__rmod__",
"__rmul__", "__rpow__", "__rsub__", "__rtruediv__", "__setformat__",
"__sub__", "__truediv__", "__trunc__", "as_integer_ratio",
"fromhex", "is_integer"
};
for (String m : float_methods_num) {
bft.update(m, numUrl(), newFunc(BaseFloat), METHOD);
}
Scope bnt = BaseNum.getTable();
String[] num_methods_num = {
"__abs__", "__add__", "__and__",
"__class__", "__cmp__", "__coerce__", "__delattr__", "__div__",
"__divmod__", "__doc__", "__float__", "__floordiv__",
"__getattribute__", "__getnewargs__", "__hash__", "__hex__",
"__index__", "__init__", "__int__", "__invert__", "__long__",
"__lshift__", "__mod__", "__mul__", "__neg__", "__new__",
"__nonzero__", "__oct__", "__or__", "__pos__", "__pow__",
"__radd__", "__rand__", "__rdiv__", "__rdivmod__",
"__reduce__", "__reduce_ex__", "__repr__", "__rfloordiv__",
"__rlshift__", "__rmod__", "__rmul__", "__ror__", "__rpow__",
"__rrshift__", "__rshift__", "__rsub__", "__rtruediv__",
"__rxor__", "__setattr__", "__str__", "__sub__", "__truediv__",
"__xor__"
};
for (String m : num_methods_num) {
bnt.update(m, numUrl(), newFunc(BaseNum), METHOD);
}
bnt.update("__getnewargs__", numUrl(), newFunc(newTuple(BaseNum)), METHOD);
bnt.update("hex", numUrl(), newFunc(BaseStr), METHOD);
bnt.update("conjugate", numUrl(), newFunc(BaseComplex), METHOD);
Scope bct = BaseComplex.getTable();
String[] complex_methods = {
"__abs__", "__add__", "__div__", "__divmod__",
"__float__", "__floordiv__", "__format__", "__getformat__", "__int__",
"__long__", "__mod__", "__mul__", "__neg__", "__new__",
"__pos__", "__pow__", "__radd__", "__rdiv__", "__rdivmod__",
"__rfloordiv__", "__rmod__", "__rmul__", "__rpow__", "__rsub__",
"__rtruediv__", "__sub__", "__truediv__", "conjugate"
};
for (String c : complex_methods) {
bct.update(c, numUrl(), newFunc(BaseComplex), METHOD);
}
String[] complex_methods_num = {
"__eq__", "__ge__", "__gt__", "__le__","__lt__", "__ne__",
"__nonzero__", "__coerce__"
};
for (String cn : complex_methods_num) {
bct.update(cn, numUrl(), newFunc(BaseNum), METHOD);
}
bct.update("__getnewargs__", numUrl(), newFunc(newTuple(BaseComplex)), METHOD);
bct.update("imag", numUrl(), BaseNum, ATTRIBUTE);
bct.update("real", numUrl(), BaseNum, ATTRIBUTE);
}
void buildStrType() {
BaseStr.getTable().update("__getslice__", newDataModelUrl("object.__getslice__"),
newFunc(BaseStr), METHOD);
BaseStr.getTable().update("__getitem__", newDataModelUrl("object.__getitem__"),
newFunc(BaseStr), METHOD);
BaseStr.getTable().update("__iter__", newDataModelUrl("object.__iter__"),
newFunc(BaseStr), METHOD);
String[] str_methods_str = {
"capitalize", "center", "decode", "encode", "expandtabs", "format",
"index", "join", "ljust", "lower", "lstrip", "partition", "replace",
"rfind", "rindex", "rjust", "rpartition", "rsplit", "rstrip",
"strip", "swapcase", "title", "translate", "upper", "zfill"
};
for (String m : str_methods_str) {
BaseStr.getTable().update(m, newLibUrl("stdtypes.html#str." + m),
newFunc(BaseStr), METHOD);
}
String[] str_methods_num = {
"count", "isalnum", "isalpha", "isdigit", "islower", "isspace",
"istitle", "isupper", "find", "startswith", "endswith"
};
for (String m : str_methods_num) {
BaseStr.getTable().update(m, newLibUrl("stdtypes.html#str." + m),
newFunc(BaseNum), METHOD);
}
String[] str_methods_list = { "split", "splitlines" };
for (String m : str_methods_list) {
BaseStr.getTable().update(m, newLibUrl("stdtypes.html#str." + m),
newFunc(newList(BaseStr)), METHOD);
}
BaseStr.getTable().update("partition", newLibUrl("stdtypes"),
newFunc(newTuple(BaseStr)), METHOD);
}
void buildModuleType() {
String[] attrs = { "__doc__", "__file__", "__name__", "__package__" };
for (String m : attrs) {
BaseModule.getTable().update(m, newTutUrl("modules.html"), BaseStr, ATTRIBUTE);
}
BaseModule.getTable().update("__dict__", newLibUrl("stdtypes", "modules"),
newDict(BaseStr, unknown()), ATTRIBUTE);
}
void buildDictType() {
String url = "datastructures.html#dictionaries";
Scope bt = BaseDict.getTable();
bt.update("__getitem__", newTutUrl(url), newFunc(), METHOD);
bt.update("__iter__", newTutUrl(url), newFunc(), METHOD);
bt.update("get", newTutUrl(url), newFunc(), METHOD);
bt.update("items", newTutUrl(url),
newFunc(newList(newTuple(unknown(), unknown()))), METHOD);
bt.update("keys", newTutUrl(url), newFunc(BaseList), METHOD);
bt.update("values", newTutUrl(url), newFunc(BaseList), METHOD);
String[] dict_method_unknown = {
"clear", "copy", "fromkeys", "get", "iteritems", "iterkeys",
"itervalues", "pop", "popitem", "setdefault", "update"
};
for (String m : dict_method_unknown) {
bt.update(m, newTutUrl(url), newFunc(), METHOD);
}
String[] dict_method_num = { "has_key" };
for (String m : dict_method_num) {
bt.update(m, newTutUrl(url), newFunc(BaseNum), METHOD);
}
}
void buildFileType() {
String url = "stdtypes.html#bltin-file-objects";
Scope table = BaseFile.getTable();
String[] methods_unknown = {
"__enter__", "__exit__", "__iter__", "flush", "readinto", "truncate"
};
for (String m : methods_unknown) {
table.update(m, newLibUrl(url), newFunc(), METHOD);
}
String[] methods_str = { "next", "read", "readline" };
for (String m : methods_str) {
table.update(m, newLibUrl(url), newFunc(BaseStr), METHOD);
}
String[] num = { "fileno", "isatty", "tell" };
for (String m : num) {
table.update(m, newLibUrl(url), newFunc(BaseNum), METHOD);
}
String[] methods_none = { "close", "seek", "write", "writelines" };
for (String m : methods_none) {
table.update(m, newLibUrl(url), newFunc(None), METHOD);
}
table.update("readlines", newLibUrl(url), newFunc(newList(BaseStr)), METHOD);
table.update("xreadlines", newLibUrl(url), newFunc(BaseFile), METHOD);
table.update("closed", newLibUrl(url), BaseNum, ATTRIBUTE);
table.update("encoding", newLibUrl(url), BaseStr, ATTRIBUTE);
table.update("errors", newLibUrl(url), unknown(), ATTRIBUTE);
table.update("mode", newLibUrl(url), BaseNum, ATTRIBUTE);
table.update("name", newLibUrl(url), BaseStr, ATTRIBUTE);
table.update("softspace", newLibUrl(url), BaseNum, ATTRIBUTE);
table.update("newlines", newLibUrl(url), newUnion(BaseStr, newTuple(BaseStr)), ATTRIBUTE);
}
private Binding synthetic(Scope table, String n, Url url, org.python.indexer.types.Type type, Binding.Kind k) {
Binding b = table.update(n, url, type, k);
b.markSynthetic();
return b;
}
void buildFunctionType() {
Scope t = BaseFunction.getTable();
for (String s : list("func_doc", "__doc__", "func_name", "__name__", "__module__")) {
t.update(s, new Url(DATAMODEL_URL), BaseStr, ATTRIBUTE);
}
Binding b = synthetic(t, "func_closure", new Url(DATAMODEL_URL), newTuple(), ATTRIBUTE);
b.markReadOnly();
synthetic(t, "func_code", new Url(DATAMODEL_URL), unknown(), ATTRIBUTE);
synthetic(t, "func_defaults", new Url(DATAMODEL_URL), newTuple(), ATTRIBUTE);
synthetic(t, "func_globals", new Url(DATAMODEL_URL),
new DictType(BaseStr, Indexer.idx.builtins.unknown), ATTRIBUTE);
synthetic(t, "func_dict", new Url(DATAMODEL_URL),
new DictType(BaseStr, Indexer.idx.builtins.unknown), ATTRIBUTE);
// Assume any function can become a method, for simplicity.
for (String s : list("__func__", "im_func")) {
synthetic(t, s, new Url(DATAMODEL_URL), new FunType(), METHOD);
}
}
// XXX: finish wiring this up. ClassType needs to inherit from it somehow,
// so we can remove the per-instance attributes from NClassDef.
void buildClassType() {
Scope t = BaseClass.getTable();
for (String s : list("__name__", "__doc__", "__module__")) {
synthetic(t, s, new Url(DATAMODEL_URL), BaseStr, ATTRIBUTE);
}
synthetic(t, "__dict__", new Url(DATAMODEL_URL),
new DictType(BaseStr, unknown()), ATTRIBUTE);
}
class BuiltinsModule extends NativeModule {
public BuiltinsModule() {
super("__builtin__");
Builtin = module = newModule(name);
table = module.getTable();
}
@Override
public void initBindings() {
moduleTable.put(name, liburl(), module, MODULE, 0);
table.addSuper(BaseModule.getTable());
addClass("None", newLibUrl("constants"), None);
addClass("bool", newLibUrl("functions", "bool"), BaseBool);
addClass("complex", newLibUrl("functions", "complex"), BaseComplex);
addClass("dict", newLibUrl("stdtypes", "typesmapping"), BaseDict);
addClass("file", newLibUrl("functions", "file"), BaseFile);
addClass("float", newLibUrl("functions", "float"), BaseFloat);
addClass("int", newLibUrl("functions", "int"), BaseNum);
addClass("list", newLibUrl("functions", "list"), BaseList);
addClass("long", newLibUrl("functions", "long"), BaseNum);
addClass("object", newLibUrl("functions", "object"), Object);
addClass("str", newLibUrl("functions", "str"), BaseStr);
addClass("tuple", newLibUrl("functions", "tuple"), BaseTuple);
addClass("type", newLibUrl("functions", "type"), Type);
// XXX: need to model the following as built-in class types:
// basestring, bool, buffer, frozenset, property, set, slice,
// staticmethod, super and unicode
String[] builtin_func_unknown = {
"apply", "basestring", "callable", "classmethod",
"coerce", "compile", "copyright", "credits", "delattr", "enumerate",
"eval", "execfile", "exit", "filter", "frozenset", "getattr",
"help", "input", "intern", "iter", "license", "long",
"property", "quit", "raw_input", "reduce", "reload", "reversed",
"set", "setattr", "slice", "sorted", "staticmethod", "super",
"type", "unichr", "unicode",
};
for (String f : builtin_func_unknown) {
addFunction(f, newLibUrl("functions.html#" + f), unknown());
}
String[] builtin_func_num = {
"abs", "all", "any", "cmp", "coerce", "divmod",
"hasattr", "hash", "id", "isinstance", "issubclass", "len", "max",
"min", "ord", "pow", "round", "sum"
};
for (String f : builtin_func_num) {
addFunction(f, newLibUrl("functions.html#" + f), BaseNum);
}
for (String f : list("hex", "oct", "repr", "chr")) {
addFunction(f, newLibUrl("functions.html#" + f), BaseStr);
}
addFunction("dir", newLibUrl("functions", "dir"), newList(BaseStr));
addFunction("map", newLibUrl("functions", "map"), newList(unknown()));
addFunction("range", newLibUrl("functions", "range"), newList(BaseNum));
addFunction("xrange", newLibUrl("functions", "range"), newList(BaseNum));
addFunction("buffer", newLibUrl("functions", "buffer"), newList(unknown()));
addFunction("zip", newLibUrl("functions", "zip"), newList(newTuple(unknown())));
for (String f : list("globals", "vars", "locals")) {
addFunction(f, newLibUrl("functions.html#" + f), newDict(BaseStr, unknown()));
}
for (String f : builtin_exception_types) {
addClass(f, newDataModelUrl("types"), newClass(f, globaltable, Object));
}
BaseException = (ClassType)table.lookup("BaseException").getType();
for (String f : list("True", "False", "None", "Ellipsis")) {
addAttr(f, newDataModelUrl("types"), unknown());
}
addFunction("open", newTutUrl("inputoutput.html#reading-and-writing-files"), BaseFile);
addFunction("__import__", newLibUrl("functions"), newModule("<?>"));
globaltable.put("__builtins__", liburl(), module, ATTRIBUTE, 0);
globaltable.merge(table);
}
}
class ArrayModule extends NativeModule {
public ArrayModule() {
super("array");
}
@Override
public void initBindings() {
addClass("array", newLibUrl("array", "array"), BaseArray);
addClass("ArrayType", newLibUrl("array", "ArrayType"), BaseArray);
}
}
class AudioopModule extends NativeModule {
public AudioopModule() {
super("audioop");
}
@Override
public void initBindings() {
addClass("error", liburl(), newException("error", table));
addStrFuncs("add", "adpcm2lin", "alaw2lin", "bias", "lin2alaw", "lin2lin",
"lin2ulaw", "mul", "reverse", "tomono", "ulaw2lin");
addNumFuncs("avg", "avgpp", "cross", "findfactor", "findmax",
"getsample", "max", "maxpp", "rms");
for (String s : list("adpcm2lin", "findfit", "lin2adpcm", "minmax", "ratecv")) {
addFunction(s, liburl(), newTuple());
}
}
}
class BinasciiModule extends NativeModule {
public BinasciiModule() {
super("binascii");
}
@Override
public void initBindings() {
addStrFuncs(
"a2b_uu", "b2a_uu", "a2b_base64", "b2a_base64", "a2b_qp",
"b2a_qp", "a2b_hqx", "rledecode_hqx", "rlecode_hqx", "b2a_hqx",
"b2a_hex", "hexlify", "a2b_hex", "unhexlify");
addNumFuncs("crc_hqx", "crc32");
addClass("Error", liburl(), newException("Error", table));
addClass("Incomplete", liburl(), newException("Incomplete", table));
}
}
class Bz2Module extends NativeModule {
public Bz2Module() {
super("bz2");
}
@Override
public void initBindings() {
ClassType bz2 = newClass("BZ2File", table, BaseFile); // close enough.
addClass("BZ2File", liburl(), bz2);
ClassType bz2c = newClass("BZ2Compressor", table, Object);
bz2c.getTable().update("compress", newLibUrl("bz2", "sequential-de-compression"),
newFunc(BaseStr), METHOD);
bz2c.getTable().update("flush", newLibUrl("bz2", "sequential-de-compression"),
newFunc(None), METHOD);
addClass("BZ2Compressor", newLibUrl("bz2", "sequential-de-compression"), bz2c);
ClassType bz2d = newClass("BZ2Decompressor", table, Object);
bz2d.getTable().update("decompress", newLibUrl("bz2", "sequential-de-compression"),
newFunc(BaseStr), METHOD);
addClass("BZ2Decompressor", newLibUrl("bz2", "sequential-de-compression"), bz2d);
addFunction("compress", newLibUrl("bz2", "one-shot-de-compression"), BaseStr);
addFunction("decompress", newLibUrl("bz2", "one-shot-de-compression"), BaseStr);
}
}
class CPickleModule extends NativeModule {
public CPickleModule() {
super("cPickle");
}
@Override
protected Url liburl() {
return newLibUrl("pickle", "module-cPickle");
}
@Override
public void initBindings() {
addUnknownFuncs("dump", "load", "dumps", "loads");
addClass("PickleError", liburl(), newException("PickleError", table));
ClassType picklingError = newException("PicklingError", table);
addClass("PicklingError", liburl(), picklingError);
update("UnpickleableError", liburl(),
newClass("UnpickleableError", table, picklingError), CLASS);
ClassType unpicklingError = newException("UnpicklingError", table);
addClass("UnpicklingError", liburl(), unpicklingError);
update("BadPickleGet", liburl(),
newClass("BadPickleGet", table, unpicklingError), CLASS);
ClassType pickler = newClass("Pickler", table, Object);
pickler.getTable().update("dump", liburl(), newFunc(), METHOD);
pickler.getTable().update("clear_memo", liburl(), newFunc(), METHOD);
addClass("Pickler", liburl(), pickler);
ClassType unpickler = newClass("Unpickler", table, Object);
unpickler.getTable().update("load", liburl(), newFunc(), METHOD);
unpickler.getTable().update("noload", liburl(), newFunc(), METHOD);
addClass("Unpickler", liburl(), unpickler);
}
}
class CStringIOModule extends NativeModule {
public CStringIOModule() {
super("cStringIO");
}
@Override
protected Url liburl() {
return newLibUrl("stringio");
}
@Override
protected Url liburl(String anchor) {
return newLibUrl("stringio", anchor);
}
@Override
public void initBindings() {
ClassType StringIO = newClass("StringIO", table, BaseFile);
addFunction("StringIO", liburl(), StringIO);
addAttr("InputType", liburl(), Type);
addAttr("OutputType", liburl(), Type);
addAttr("cStringIO_CAPI", liburl(), unknown());
}
}
class CMathModule extends NativeModule {
public CMathModule() {
super("cmath");
}
@Override
public void initBindings() {
addFunction("phase", liburl("conversions-to-and-from-polar-coordinates"), BaseNum);
addFunction("polar", liburl("conversions-to-and-from-polar-coordinates"),
newTuple(BaseNum, BaseNum));
addFunction("rect", liburl("conversions-to-and-from-polar-coordinates"),
BaseComplex);
for (String plf : list("exp", "log", "log10", "sqrt")) {
addFunction(plf, liburl("power-and-logarithmic-functions"), BaseNum);
}
for (String tf : list("acos", "asin", "atan", "cos", "sin", "tan")) {
addFunction(tf, liburl("trigonometric-functions"), BaseNum);
}
for (String hf : list("acosh", "asinh", "atanh", "cosh", "sinh", "tanh")) {
addFunction(hf, liburl("hyperbolic-functions"), BaseComplex);
}
for (String cf : list("isinf", "isnan")) {
addFunction(cf, liburl("classification-functions"), BaseBool);
}
for (String c : list("pi", "e")) {
addAttr(c, liburl("constants"), BaseNum);
}
}
}
class CollectionsModule extends NativeModule {
public CollectionsModule() {
super("collections");
}
private Url abcUrl() {
return liburl("abcs-abstract-base-classes");
}
private Url dequeUrl() {
return liburl("deque-objects");
}
@Override
public void initBindings() {
ClassType Callable = newClass("Callable", table, Object);
Callable.getTable().update("__call__", abcUrl(), newFunc(), METHOD);
addClass("Callable", abcUrl(), Callable);
ClassType Iterable = newClass("Iterable", table, Object);
Iterable.getTable().update("__next__", abcUrl(), newFunc(), METHOD);
Iterable.getTable().update("__iter__", abcUrl(), newFunc(), METHOD);
addClass("Iterable", abcUrl(), Iterable);
ClassType Hashable = newClass("Hashable", table, Object);
Hashable.getTable().update("__hash__", abcUrl(), newFunc(BaseNum), METHOD);
addClass("Hashable", abcUrl(), Hashable);
ClassType Sized = newClass("Sized", table, Object);
Sized.getTable().update("__len__", abcUrl(), newFunc(BaseNum), METHOD);
addClass("Sized", abcUrl(), Sized);
ClassType Container = newClass("Container", table, Object);
Container.getTable().update("__contains__", abcUrl(), newFunc(BaseNum), METHOD);
addClass("Container", abcUrl(), Container);
ClassType Iterator = newClass("Iterator", table, Iterable);
addClass("Iterator", abcUrl(), Iterator);
ClassType Sequence = newClass("Sequence", table, Sized, Iterable, Container);
Sequence.getTable().update("__getitem__", abcUrl(), newFunc(), METHOD);
Sequence.getTable().update("reversed", abcUrl(), newFunc(Sequence), METHOD);
Sequence.getTable().update("index", abcUrl(), newFunc(BaseNum), METHOD);
Sequence.getTable().update("count", abcUrl(), newFunc(BaseNum), METHOD);