-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathbuiltin_typed_api.py
More file actions
355 lines (311 loc) · 11.1 KB
/
builtin_typed_api.py
File metadata and controls
355 lines (311 loc) · 11.1 KB
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
# int Int
# float Float
# boolean Boolean
# str String
# [2] List<Int>
# {2: 2.0} Dict<Int, Float>
# [] List
# {} Dict
from pseudo_python.errors import PseudoPythonTypeCheckError
from pseudo_python.helpers import serialize_type
V = '_' # we don't really typecheck or care for a lot of the arg types, so just use this
_ = ()
# we use lists instead of tuples, because it's easier this way
# for different methods in the same type env to reference and update the same signature
# that helps us with inherited methods: each one updates the type signature for the whole hierarchy
def builtin_type_check(namespace, function, receiver, args):
fs = TYPED_API[namespace]
if fs == 'library':
fs = TYPED_API['_%s' % namespace]
# print(namespace, function, receiver, args, TYPED_API[namespace])
# input(0)
if function not in fs:
raise PseudoPythonTypeCheckError('wrong usage of %s' % str(function))
x = fs[function]
a = namespace + '#' + function if receiver else namespace + ':' + function
if namespace == 'List' or namespace == 'Set' or namespace == 'Array':
generics = {'@t': receiver['pseudo_type'][1]}
elif namespace == 'Dictionary':
generics = {'@k': receiver['pseudo_type'][1], '@v': receiver['pseudo_type'][2]}
else:
generics = {}
s = []
if x[0][0] == '*':
e = x[0][1:]
for arg in args:
s.append(simplify(e, generics))
arg_check(s[-1], arg, a)
else:
if len(x) - 1 != len(args):
raise PseudoPythonTypeCheckError("%s expects %d args not %d" % (a, len(x) - 1, args))
for e, arg in zip(x[:-1], args):
s.append(simplify(e, generics))
arg_check(s[-1], arg, a)
s.append(simplify(x[-1], generics))
return s
def arg_check(expected_type, args, a):
if expected_type != args['pseudo_type'] and expected_type != 'Any' and not(expected_type == 'Number' and (args['pseudo_type'] == 'Int' or args['pseudo_type'] == 'Float')):
raise PseudoPythonTypeCheckError('%s expected %s not %s' % (a, serialize_type(expected_type), serialize_type(args['pseudo_type'])))
def simplify(kind, generics):
if not generics:
return kind
elif isinstance(kind, str):
if kind[0] == '@' and kind in generics:
return generics[kind]
else:
return kind
else:
return [simplify(child, generics) for child in kind]
# refactoring here in future
def add(l, r):
if l == 'Float' and r in ['Float', 'Int'] or r == 'Float' and l in ['Float', 'Int']:
return [l, r, 'Float']
elif l == 'Int' and r == 'Int':
return [l, r, 'Int']
elif l == 'String' and r == 'String':
return [l, r, 'String']
elif isinstance(l, list) and l[0] == 'List' and l == r:
return [l, r, l]
else:
raise PseudoPythonTypeCheckError("wrong types for +: %s and %s" % (serialize_type(l), serialize_type(r)))
def sub(l, r):
if l == 'Float' and r in ['Float', 'Int'] or r == 'Float' and l in ['Float', 'Int']:
return [l, r, 'Float']
elif l == 'Int' and r == 'Int':
return [l, r, 'Int']
else:
raise PseudoPythonTypeCheckError("wrong types for -: %s and %s" % (serialize_type(l), serialize_type(r)))
def mul(l, r):
if l == 'Float' and r in ['Float', 'Int'] or r == 'Float' and l in ['Float', 'Int']:
return [l, r, 'Float']
elif l == 'Int' and r == 'Int':
return [l, r, 'Int']
elif l == 'Int' and (isinstance(r, list) and r[0] == 'List' or r == 'String'):
return [l, r, r]
elif r == 'Int' and (isinstance(l, list) and l[0] == 'List' or l == 'String'):
return [l, r, l]
else:
raise PseudoPythonTypeCheckError("wrong types for *: %s and %s" % (serialize_type(l), serialize_type(r)))
def div(l, r):
if l == 'Float' and r in ['Float', 'Int'] or r == 'Float' and l in ['Float', 'Int']:
return [l, r, 'Float']
elif l == 'Int' and r == 'Int':
return [l, r, 'Int']
else:
raise PseudoPythonTypeCheckError("wrong types for /: %s and %s" % (serialize_type(l), serialize_type(r)))
def pow_(l, r):
if l == 'Float' and r in ['Float', 'Int'] or r == 'Float' and l in ['Float', 'Int']:
return [l, r, 'Float']
elif l == 'Int' and r == 'Int':
return [l, r, 'Int']
else:
raise PseudoPythonTypeCheckError("wrong types for **: %s and %s" % (serialize_type(l), serialize_type(r)))
def mod(l, r):
if l == 'Int' and r == 'Int':
return [l, r, 'Int']
elif l == 'String' and (r == 'String' or r == ['Array', 'String']):
return [l, ['Array', 'String'], 'String']
else:
raise PseudoPythonTypeCheckError("wrong types for %: %s and %s" % (serialize_type(l), serialize_type(r)))
def and_(l, r):
if l == 'Boolean' and r == 'Boolean':
return 'Boolean'
else:
raise PseudoPythonTypeCheckError("wrong types for and: %s and %s" % (serialize_type(l), serialize_type(r)))
def or_(l, r):
if l == 'Boolean' and r == 'Boolean':
return 'Boolean'
else:
raise PseudoPythonTypeCheckError("wrong types for or: %s and %s" % (serialize_type(l), serialize_type(r)))
def binary_and(l, r):
if l == r == 'Int' or l == r == 'Set':
return l
else:
raise PseudoPythonTypeCheckError("wrong types for &: %s and %s" % (serialize_type(l), serialize_type(r)))
def binary_or(l, r):
if l == r == 'Int' or l == r == 'Set':
return l
else:
raise PseudoPythonTypeCheckError("wrong types for |: %s and %s" % (serialize_type(l), serialize_type(r)))
def xor_(l, r):
if l == r == 'Int' or l == r == 'Set':
return l
else:
raise PseudoPythonTypeCheckError("wrong types for ^: %s and %s" % (serialize_type(l), serialize_type(r)))
# for template types as list, dict @t is the type of list arg and @k, @v of dict args
TYPED_API = {
# methods
'global': {
'exit': ['Int', 'Void'],
'to_string': ['Any', 'String']
},
'io': {
'display': ['*Any', 'Void'],
'read': ['String'],
'read_file': ['String', 'String'],
'write_file': ['String', 'String', 'Void']
},
'system': {
'args': [['List', 'String']]
},
'regexp': {
'compile': ['String', 'Regexp'],
'escape': ['String', 'String']
},
'math': {
'tan': ['Number', 'Float'],
'sin': ['Number', 'Float'],
'cos': ['Number', 'Float'],
'ln': ['Number', 'Float'],
'log': ['Number', 'Number', 'Float']
},
'operators': {
'+': add,
'-': sub,
'*': mul,
'/': div,
'**': pow_,
'%': mod,
'&': binary_and,
'|': binary_or,
'^': xor_
},
'List': {
'push': ['@t', 'Void'],
'pop': ['@t'],
'insert': ['@t', 'Void'],
'insert_at': ['@t', 'Int', 'Void'],
'concat': [['List', '@t'], ['List', '@t']],
'repeat': ['Int', ['List', '@t']],
'push_many': [['List', '@t'], 'Void'],
'remove': ['@t', 'Void'],
'length': ['Int'],
'join': [['List', 'String'], 'String'],
'map': [['Function', '@t', '@y'], ['List', '@y']],
'filter': [['Function', '@t', 'Boolean'], ['List', '@t']]
},
'Dictionary': {
'keys': ['List', '@k'],
'values': ['List', '@v'],
'length': ['Int']
},
'String': {
'find': ['String', 'Int'],
'to_int': ['Int'],
'split': ['String', ['List', 'String']],
'c_format': [['Array', 'String'], 'String'],
'upper': ['String'],
'lower': ['String'],
'title': ['String'],
'center': ['Int', 'String', 'String'],
'find_from': ['String', 'Int', 'Int'],
'length': ['Int'],
},
'Set': {
'|': [['Set', '@t'], ['Set', '@t']],
'add': ['@t', 'Void'],
'remove': ['@t', 'Void'],
'&': [['Set', '@t'], ['Set', '@t']],
'^': [['Set', '@t'], ['Set', '@t']],
'-': [['Set', '@t'], ['Set', '@t']]
},
'Int': {'to_int': ['Int'], 'to_float': ['Float']},
'Float': {'to_int': ['Int'], 'to_float': ['Float']},
'Array': {
'length': ['Int'],
'index': ['@t', 'Int'],
'count': ['@t', 'Int']
},
'Tuple': {
'length': ['Int']
},
'Regexp': {
'match': ['String', 'RegexpMatch'],
'groups': ['String', ['String']]
},
'RegexpMatch': {
'group': ['Int', 'String']
},
'_generic_List': ['List', '@t'],
'_generic_Set': ['Set', '@t'],
'_generic_Array': ['Array', '@t'],
'_generic_Tuple': ['Tuple', '@t'],
'_generic_Dictionary': ['Dictionary', '@k', '@v'],
# 'List#pop': [_, '@t'],
# 'List#insert': [_, 'Null'],
# 'List#remove': [_, 'Null'],
# 'List#remove_at': [_, 'Null'],
# 'List#length': [_, 'Int'],
# 'List#concat_one': [_, 'List<@t>'],
# 'List#concat': [_, 'List<@t>'],
# 'List#[]': [_, '@t'],
# 'List#[]=': [_, 'Null'],
# 'List#slice': [_, 'List<@t>'],
# 'Dict#keys': [_, 'List<@k>'],
# 'Dict#values': [_, 'List<@v>'],
}
# useful for error messages
ORIGINAL_METHODS = {
'List': {
'push': 'append(element)',
'pop': 'pop',
'insert': 'insert(element)',
'insert_at': 'insert(element, index)',
'concat': '+',
'repeat': '*',
'push_many': 'extend(other)',
'remove': 'remove',
'length': 'len',
'map': 'list comprehension / map',
'filter': 'list comprehension / filter'
},
'Dictionary': {
'keys': 'keys',
'values': 'values',
'length': 'len'
},
'Int': {
'to_int': 'int',
'to_float': 'float'
},
'Float': {
'to_int': 'int',
'to_float': 'float'
},
'String': {
'find': 'index(substring)',
'join': 'join(elements)',
'split': 'split(delimiter)',
'c_format': '%',
'format': 'format(*elements)',
'upper': 'upper',
'lower': 'lower',
'title': 'title',
'center': 'center',
'find_from': 'index(substring, index)',
'to_int': 'int'
},
'Set': {
'|': '|',
'add': 'add(element)',
'remove': 'remove(element)',
'&': '&',
'^': '^',
'-': '-'
},
'Array': {
'length': 'len',
'find': 'find(element)',
'count': 'count(element)'
},
'Tuple': {
'length': 'len'
},
'Regexp': {
'match': 'match(value)',
'groups': 'find_all(value)'
},
'RegexpMatch': {
'group': 'group(z)'
}
}