-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbuiltin.py
219 lines (177 loc) · 6.37 KB
/
builtin.py
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#=================================================
# copyright Amin By [http://aminby.net]
# Since 2014-4
#=================================================
import math
from operator import mul
from scope import SScope
import types
# define Built-in List
class BIList(object):
"""docstring for BIList"""
values = []
def __init__(self, values):
super(BIList, self).__init__()
self.values = values
def __str__(self):
return "(list %s)" % (" ".join([str(x) for x in self.values]))
def first(self):
return self.values[0] if self.values else None
def rest(self):
return BIList(self.values[1:]) if self.values else BIList([])
# define built-in function
class BIFunction(object):
"""docstring for BIFunction"""
body = None
parameters = []
scope = None
def __init__(self, body, parameters, scope):
super(BIFunction, self).__init__()
self.body = body
self.parameters = parameters
self.scope = scope
def __str__(self):
return "(func (%s) %s)" % (" ".join(self.parameters), str(self.body))
def computeFilledParams(self):
return [x for x in [self.scope.findInTop(name) for name in self.parameters] if x]
def isPartial(self):
return len(self.computeFilledParams()) in range(2, len(self.parameters)-1)
def evaluate(self):
filledParams = self.computeFilledParams()
if len(filledParams) < len(self.parameters):
return self
return self.body.evaluate(self.scope)
def update(self, arguments):
existedArguments = filter(None, [self.scope.findInTop(p) for p in self.parameters])
newArguments = existedArguments + arguments
newScope = self.scope.parent().spawnScopeWith(self.parameters, newArguments)
return BIFunction(self.body, self.parameters, newScope)
# define built-in class
# 'member' is his interface method for external using
class BuiltIn(object):
"""docstring for BuiltIn"""
# set
@staticmethod
def member(name, func=None):
if not hasattr(BuiltIn,'functions'):
BuiltIn.functions = {}
if func is not None:
BuiltIn.functions[name] = func
return
return BuiltIn.functions.get(name, None)
@staticmethod
def _sub(args, scope):
args = [x.evaluate(scope) for x in args]
return args[0] - math.fsum(args[1:])
@staticmethod
def _mul(args, scope):
return reduce(mul, [x.evaluate(scope) for x in args])
@staticmethod
def _div(args, scope):
args = [x.evaluate(scope) for x in args]
dividend = reduce(mul, args[1:])
if not dividend:
raise Exception("dived is zero")
return args[0] / dividend
@staticmethod
def _add(args, scope):
return math.fsum([x.evaluate(scope) for x in args])
@staticmethod
def _sub(args, scope):
if not args:
raise Exception("'-' operator need arguments.")
args = [x.evaluate(scope) for x in args]
return args[0] - math.fsum(args[1:])
@staticmethod
def _mod(args, scope):
if len(args) < 2:
raise Exception("'%' operator need 2 arguments.")
args = [x.evaluate(scope) for x in args[0:2]]
return int(args[0]) % int(args[1])
@staticmethod
def _and(args, scope):
for x in args:
if not x.evaluate(scope):
return False
else:
return True
@staticmethod
def _or(args, scope):
for x in args:
if x.evaluate(scope):
return True
else:
return False
@staticmethod
def _xor(args, scope):
return reduce(lambda x,y:x^y, [bool(x.evaluate(scope)) for x in args])
@staticmethod
def _not(args, scope):
if not args:
raise Exception("operator 'not' need 1 argument.")
return not args[0].evaluate(scope)
@staticmethod
def _compare(op, args, scope):
if len(args) < 2:
raise Exception("compare operator need at least 2 arguments.")
first = args[0].evaluate(scope)
for x in args[1:]:
if not eval("%f %s %f" % (first, op, x.evaluate(scope))):
return False
else:
return True
@staticmethod
def _if(args, scope):
len_a = len(args)
if len_a < 2:
raise Exception("if need at least arguments.")
if args[0].evaluate(scope):
return args[1].evaluate(scope)
elif len_a > 2:
return args[2].evaluate(scope)
return None
@staticmethod
def _def(args, scope):
return scope.define(args[0].value, args[1].evaluate(SScope(scope)))
@staticmethod
def _begin(args, scope):
if not args:
return None
return [x.evaluate(scope) for x in args][-1]
@staticmethod
def _func(args, scope):
if len(args) < 2:
raise Exception("'func' operator need 2 arguments.")
return BIFunction(args[1], [x.value for x in args[0].children], SScope(scope))
#===============================================
# define the built-in operators and functions
#===============================================
# keywords
BuiltIn.member("func", BuiltIn._func)
BuiltIn.member("def", BuiltIn._def)
BuiltIn.member("begin", BuiltIn._begin)
BuiltIn.member("if", BuiltIn._if)
# basic calculator
BuiltIn.member("+", BuiltIn._add)
BuiltIn.member("-", BuiltIn._sub)
BuiltIn.member("*", BuiltIn._mul)
BuiltIn.member("/", BuiltIn._div)
BuiltIn.member("%", BuiltIn._mod)
# compare
BuiltIn.member("=", lambda args, scope: BuiltIn._compare("==", args, scope))
BuiltIn.member(">", lambda args, scope: BuiltIn._compare(">", args, scope))
BuiltIn.member("<", lambda args, scope: BuiltIn._compare("<", args, scope))
BuiltIn.member("<=", lambda args, scope: BuiltIn._compare("<=", args, scope))
BuiltIn.member(">=", lambda args, scope: BuiltIn._compare(">=", args, scope))
# logic
BuiltIn.member("and", BuiltIn._and)
BuiltIn.member("or", BuiltIn._or)
BuiltIn.member("xor", BuiltIn._xor)
# list
BuiltIn.member("list", lambda args, scope: BIList([x.evaluate(scope) for x in args]))
BuiltIn.member("first", lambda args, scope: args[0].evaluate(scope).first())
BuiltIn.member("rest", lambda args, scope: args[0].evaluate(scope).rest())
#todo BuiltIn.member("append")
#todo BuiltIn.member("empty?")