From 71b8575d7a2a27156221fea825f82bb9a13cff67 Mon Sep 17 00:00:00 2001 From: Sebastien Bourdeauducq Date: Sun, 7 Sep 2014 15:26:05 +0800 Subject: [PATCH] py2llvm/fractions: add numerator/denominator getattr support --- artiq/py2llvm/fractions.py | 14 ++++++++++++++ test/py2llvm.py | 14 +++++++++++++- 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/artiq/py2llvm/fractions.py b/artiq/py2llvm/fractions.py index 3544d7275..b12382ae0 100644 --- a/artiq/py2llvm/fractions.py +++ b/artiq/py2llvm/fractions.py @@ -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: diff --git a/test/py2llvm.py b/test/py2llvm.py index be81364fd..03c742777 100644 --- a/test/py2llvm.py +++ b/test/py2llvm.py @@ -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))