OILS / mycpp / mops.py View on Github | oilshell.org

270 lines, 100 significant
1"""
2Math operations, e.g. for arbitrary precision integers
3
4They are currently int64_t, rather than C int, but we want to upgrade to
5heap-allocated integers.
6
7Regular int ops can use the normal operators + - * /, or maybe i_add() if we
8really want. Does that make code gen harder or worse?
9
10Float ops could be + - * / too, but it feels nicer to develop a formal
11interface?
12"""
13from __future__ import print_function
14
15from typing import Tuple
16
17
18class BigInt(object):
19
20 def __init__(self, i):
21 # type: (int) -> None
22 self.i = i
23
24 def __eq__(self, other):
25 # type: (object) -> bool
26
27 # Disabled check
28 # Prevent possible mistakes. Could do this with other operators
29 # raise AssertionError('Use mops.Equal()')
30
31 if not isinstance(other, BigInt):
32 raise AssertionError()
33
34 # Used for hashing
35 return self.i == other.i
36
37 def __gt__(self, other):
38 # type: (object) -> bool
39 raise AssertionError('Use functions in mops.py')
40
41 def __ge__(self, other):
42 # type: (object) -> bool
43 raise AssertionError('Use functions in mops.py')
44
45 def __hash__(self):
46 # type: () -> int
47 """For dict lookups."""
48 return hash(self.i)
49
50
51ZERO = BigInt(0)
52ONE = BigInt(1)
53MINUS_ONE = BigInt(-1)
54MINUS_TWO = BigInt(-2) # for printf
55
56
57def ToStr(b):
58 # type: (BigInt) -> str
59 return str(b.i)
60
61
62def ToOctal(b):
63 # type: (BigInt) -> str
64 return '%o' % b.i
65
66
67def ToHexUpper(b):
68 # type: (BigInt) -> str
69 return '%X' % b.i
70
71
72def ToHexLower(b):
73 # type: (BigInt) -> str
74 return '%x' % b.i
75
76
77# Notes on FromStr() and recognizing integers
78#
79# 3 similar but DIFFERENT cases:
80#
81# 1. trap ' 42 ' x - unsigned, including 09, but not -1
82# 2. echo $(( x )) - 0123 is octal, but no -0123 because that's separate I think
83# 3. int(), j8 - 077 is decimal
84#
85# - mops.FromStr should not use exceptions? That is consistent with mops.FromFloat
86# - under the hood it uses StringToInt64, which uses strtoll
87# - problem: we DO NOT want to rely on strtoll() to define a language, to
88# reject user-facing strings - we want to use something like
89# match.LooksLikeInteger() usually. This is part of our spec-driven
90# philosophy.
91#
92# - a problem though is if we support 00, because sometimes that is OCTAL
93# - int("00") is zero
94# - match.LooksLikeInteger returns it
95
96# uses LooksLikeInteger and then FromStr()
97# - YSH int()
98# - printf builtin
99# - YSH expression conversion
100
101# Uses only FromStr()
102# - j8 - uses its own regex though
103# - ulimit
104# - trap - NON-NEGATIVE only
105# - arg parser
106
107
108def FromStr(s, base=10):
109 # type: (str, int) -> BigInt
110 return BigInt(int(s, base))
111
112
113def BigTruncate(b):
114 # type: (BigInt) -> int
115 """Only truncates in C++"""
116 return b.i
117
118
119def IntWiden(i):
120 # type: (int) -> BigInt
121 """Only widens in C++"""
122 return BigInt(i)
123
124
125def FromC(i):
126 # type: (int) -> BigInt
127 """A no-op in C, for RLIM_INFINITY"""
128 return BigInt(i)
129
130
131def FromBool(b):
132 # type: (bool) -> BigInt
133 """Only widens in C++"""
134 return BigInt(1) if b else BigInt(0)
135
136
137def ToFloat(b):
138 # type: (BigInt) -> float
139 """Used by float(42) in Oils"""
140 return float(b.i)
141
142
143def FromFloat(f):
144 # type: (float) -> Tuple[bool, BigInt]
145 """Used by int(3.14) in Oils"""
146 try:
147 big = int(f)
148 except ValueError: # NAN
149 return False, MINUS_ONE
150 except OverflowError: # INFINITY
151 return False, MINUS_ONE
152 return True, BigInt(big)
153
154
155# Can't use operator overloading
156
157
158def Negate(b):
159 # type: (BigInt) -> BigInt
160 return BigInt(-b.i)
161
162
163def Add(a, b):
164 # type: (BigInt, BigInt) -> BigInt
165 return BigInt(a.i + b.i)
166
167
168def Sub(a, b):
169 # type: (BigInt, BigInt) -> BigInt
170 return BigInt(a.i - b.i)
171
172
173def Mul(a, b):
174 # type: (BigInt, BigInt) -> BigInt
175 return BigInt(a.i * b.i)
176
177
178def Div(a, b):
179 # type: (BigInt, BigInt) -> BigInt
180 """Integer division.
181
182 Oils rounds toward zero.
183
184 Python rounds toward negative infinity, while C++ rounds toward zero. We
185 have to work around Python a bit.
186 """
187 assert b.i != 0, b.i # divisor can't be zero -- caller checks
188
189 # Only use Python // on non-negative numbers. Apply sign afterward.
190 sign = 1
191
192 if a.i < 0:
193 pa = -a.i
194 sign = -1
195 else:
196 pa = a.i
197
198 if b.i < 0:
199 pb = -b.i
200 sign = -sign
201 else:
202 pb = b.i
203
204 return BigInt(sign * (pa // pb))
205
206
207def Rem(a, b):
208 # type: (BigInt, BigInt) -> BigInt
209 """Integer remainder."""
210 assert b.i != 0, b.i # YSH divisor must be positive, but OSH can be negative
211
212 # Only use Python % on non-negative numbers. Apply sign afterward.
213 if a.i < 0:
214 pa = -a.i
215 sign = -1
216 else:
217 pa = a.i
218 sign = 1
219
220 if b.i < 0:
221 pb = -b.i
222 else:
223 pb = b.i
224
225 return BigInt(sign * (pa % pb))
226
227
228def Equal(a, b):
229 # type: (BigInt, BigInt) -> bool
230 return a.i == b.i
231
232
233def Greater(a, b):
234 # type: (BigInt, BigInt) -> bool
235 return a.i > b.i
236
237
238# GreaterEq, Less, LessEq can all be expressed as the 2 ops above
239
240
241def LShift(a, b):
242 # type: (BigInt, BigInt) -> BigInt
243 assert b.i >= 0, b.i # Must be checked by caller
244 return BigInt(a.i << b.i)
245
246
247def RShift(a, b):
248 # type: (BigInt, BigInt) -> BigInt
249 assert b.i >= 0, b.i # Must be checked by caller
250 return BigInt(a.i >> b.i)
251
252
253def BitAnd(a, b):
254 # type: (BigInt, BigInt) -> BigInt
255 return BigInt(a.i & b.i)
256
257
258def BitOr(a, b):
259 # type: (BigInt, BigInt) -> BigInt
260 return BigInt(a.i | b.i)
261
262
263def BitXor(a, b):
264 # type: (BigInt, BigInt) -> BigInt
265 return BigInt(a.i ^ b.i)
266
267
268def BitNot(a):
269 # type: (BigInt) -> BigInt
270 return BigInt(~a.i)