py2llvm/fractions: add numerator/denominator getattr support

This commit is contained in:
Sebastien Bourdeauducq 2014-09-07 15:26:05 +08:00
parent e2d834928f
commit 71b8575d7a
2 changed files with 27 additions and 1 deletions

View File

@ -76,6 +76,20 @@ class VFraction(VGeneric):
raise TypeError
self.set_ssa_value(builder, n.get_ssa_value(builder))
def o_getattr(self, attr, builder):
if attr == "numerator":
idx = 0
elif attr == "denominator":
idx = 1
else:
raise AttributeError
r = VInt(64)
if builder is not None:
elt = builder.extract_element(
self.get_ssa_value(builder), lc.Constant.int(lc.Type.int(), idx))
r.set_ssa_value(builder, elt)
return r
def o_bool(self, builder):
r = VBool()
if builder is not None:

View File

@ -1,6 +1,7 @@
import unittest
import ast
import inspect
from fractions import Fraction
from llvm import ee as le
@ -79,8 +80,19 @@ def is_prime(x):
d += 1
return True
def simplify_encode(n, d):
f = Fraction(n, d)
return f.numerator*1000 + f.denominator
class CodeGenCase(unittest.TestCase):
def test_is_prime(self):
is_prime_c = CompiledFunction(is_prime, {"x": base_types.VInt(32)})
is_prime_c = CompiledFunction(is_prime, {"x": base_types.VInt()})
for i in range(200):
self.assertEqual(is_prime_c(i), is_prime(i))
def test_frac_simplify(self):
simplify_encode_c = CompiledFunction(
simplify_encode, {"n": base_types.VInt(), "d": base_types.VInt()})
for n in range(5, 20):
for d in range(5, 20):
self.assertEqual(simplify_encode_c(n, d), simplify_encode(n, d))