Пример #1
0
def test_Declaration():
    u = symbols('u', real=True)
    vu = Variable(u, type=Type.from_expr(u))
    assert Declaration(vu).variable.type == real
    vn = Variable(n, type=Type.from_expr(n))
    assert Declaration(vn).variable.type == integer

    lt = StrictLessThan(vu, vn)
    assert isinstance(lt, StrictLessThan)

    vuc = Variable(u, Type.from_expr(u), value=3.0, attrs={value_const})
    assert value_const in vuc.attrs
    assert pointer_const not in vuc.attrs
    decl = Declaration(vuc)
    assert decl.variable == vuc
    assert isinstance(decl.variable.value, Float)
    assert decl.variable.value == 3.0
    assert decl.func(*decl.args) == decl
    assert vuc.as_Declaration() == decl
    assert vuc.as_Declaration(value=None, attrs=None) == Declaration(vu)

    vy = Variable(y, type=integer, value=3)
    decl2 = Declaration(vy)
    assert decl2.variable == vy
    assert decl2.variable.value == Integer(3)

    vi = Variable(i, type=Type.from_expr(i), value=3.0)
    decl3 = Declaration(vi)
    assert decl3.variable.type == integer
    assert decl3.variable.value == 3.0

    raises(ValueError, lambda: Declaration(vi, 42))
Пример #2
0
def test_C99CodePrinter_custom_type():
    # We will look at __float128 (new in glibc 2.26)
    f128 = FloatType('_Float128', float128.nbits, float128.nmant,
                     float128.nexp)
    p128 = C99CodePrinter(
        dict(type_aliases={real: f128},
             type_literal_suffixes={f128: 'Q'},
             type_func_suffixes={f128: 'f128'},
             type_math_macro_suffixes={
                 real: 'f128',
                 f128: 'f128'
             },
             type_macros={f128: ('__STDC_WANT_IEC_60559_TYPES_EXT__', )}))
    assert p128.doprint(x) == 'x'
    assert not p128.headers
    assert not p128.libraries
    assert not p128.macros
    assert p128.doprint(2.0) == '2.0Q'
    assert not p128.headers
    assert not p128.libraries
    assert p128.macros == {'__STDC_WANT_IEC_60559_TYPES_EXT__'}

    assert p128.doprint(Rational(1, 2)) == '1.0Q/2.0Q'
    assert p128.doprint(sin(x)) == 'sinf128(x)'
    assert p128.doprint(cos(2., evaluate=False)) == 'cosf128(2.0Q)'

    var5 = Variable(x, {value_const}, f128)

    dcl5a = Declaration(var5)
    assert ccode(dcl5a) == 'const _Float128 x'
    dcl5b = Declaration(var5, pi)
    assert p128.doprint(dcl5b) == 'const _Float128 x = M_PIf128'
    dcl5c = Declaration(var5, Catalan.evalf(38))
    assert p128.doprint(dcl5c) == 'const _Float128 x = %sQ' % Catalan.evalf(
        f128.decimal_dig)
Пример #3
0
    def test_c_parse():
        src1 = """\
        int a, b = 4;
        float c, d = 2.4;
        """
        expr1.convert_to_expr(src1, 'c')
        ls = expr1.return_expr()

        assert ls[0] == Declaration(
            Variable(Symbol('a'), type=IntBaseType(String('intc'))))
        assert ls[1] == Declaration(
            Variable(Symbol('b'),
                     type=IntBaseType(String('intc')),
                     value=Integer(4)))
        assert ls[2] == Declaration(
            Variable(Symbol('c'),
                     type=FloatType(String('float32'),
                                    nbits=Integer(32),
                                    nmant=Integer(23),
                                    nexp=Integer(8))))
        assert ls[3] == Declaration(
            Variable(Symbol('d'),
                     type=FloatType(String('float32'),
                                    nbits=Integer(32),
                                    nmant=Integer(23),
                                    nexp=Integer(8)),
                     value=Float('2.3999999999999999', precision=53)))
Пример #4
0
    def test_c_parse():
        src1 = """\
        int a, b = 4;
        float c, d = 2.4;
        """
        expr1.convert_to_expr(src1, "c")
        ls = expr1.return_expr()

        assert ls[0] == Declaration(
            Variable(Symbol("a"),
                     type=IntBaseType(String("integer")),
                     value=Integer(0)))
        assert ls[1] == Declaration(
            Variable(Symbol("b"),
                     type=IntBaseType(String("integer")),
                     value=Integer(4)))
        assert ls[2] == Declaration(
            Variable(
                Symbol("c"),
                type=FloatBaseType(String("real")),
                value=Float("0.0", precision=53),
            ))
        assert ls[3] == Declaration(
            Variable(
                Symbol("d"),
                type=FloatBaseType(String("real")),
                value=Float("2.3999999999999999", precision=53),
            ))
Пример #5
0
    def test_function():
        c_src1 = "void fun1()" + "\n" + "{" + "\n" + "int a;" + "\n" + "}"
        c_src2 = ("int fun2()" + "\n" + "{" + "\n" + "int a;" + "\n" +
                  "return a;" + "\n" + "}")
        c_src3 = ("float fun3()" + "\n" + "{" + "\n" + "float b;" + "\n" +
                  "return b;" + "\n" + "}")
        c_src4 = "float fun4()" + "\n" + "{}"

        res1 = SymPyExpression(c_src1, "c").return_expr()
        res2 = SymPyExpression(c_src2, "c").return_expr()
        res3 = SymPyExpression(c_src3, "c").return_expr()
        res4 = SymPyExpression(c_src4, "c").return_expr()

        assert res1[0] == FunctionDefinition(
            NoneToken(),
            name=String("fun1"),
            parameters=(),
            body=CodeBlock(
                Declaration(
                    Variable(
                        Symbol("a"),
                        type=IntBaseType(String("integer")),
                        value=Integer(0),
                    ))),
        )

        assert res2[0] == FunctionDefinition(
            IntBaseType(String("integer")),
            name=String("fun2"),
            parameters=(),
            body=CodeBlock(
                Declaration(
                    Variable(
                        Symbol("a"),
                        type=IntBaseType(String("integer")),
                        value=Integer(0),
                    )),
                Return("a"),
            ),
        )

        assert res3[0] == FunctionDefinition(
            FloatBaseType(String("real")),
            name=String("fun3"),
            parameters=(),
            body=CodeBlock(
                Declaration(
                    Variable(
                        Symbol("b"),
                        type=FloatBaseType(String("real")),
                        value=Float("0.0", precision=53),
                    )),
                Return("b"),
            ),
        )

        assert res4[0] == FunctionPrototype(FloatBaseType(String("real")),
                                            name=String("fun4"),
                                            parameters=())
Пример #6
0
    def test_parameters():
        c_src1 = ('void fun1( int a)' + '\n' + '{' + '\n' + 'int i;' + '\n' +
                  '}')
        c_src2 = ('int fun2(float x, float y)' + '\n' + '{' + '\n' + 'int a;' +
                  '\n' + 'return a;' + '\n' + '}')
        c_src3 = ('float fun3(int p, float q, int r)' + '\n' + '{' + '\n' +
                  'float b;' + '\n' + 'return b;' + '\n' + '}')

        res1 = SymPyExpression(c_src1, 'c').return_expr()
        res2 = SymPyExpression(c_src2, 'c').return_expr()
        res3 = SymPyExpression(c_src3, 'c').return_expr()

        assert res1[0] == FunctionDefinition(
            NoneToken(),
            name=String('fun1'),
            parameters=(Variable(Symbol('a'),
                                 type=IntBaseType(String('integer')),
                                 value=Integer(0)), ),
            body=CodeBlock(
                Declaration(
                    Variable(Symbol('i'),
                             type=IntBaseType(String('integer')),
                             value=Integer(0)))))

        assert res2[0] == FunctionDefinition(
            IntBaseType(String('integer')),
            name=String('fun2'),
            parameters=(Variable(Symbol('x'),
                                 type=FloatBaseType(String('real')),
                                 value=Float('0.0', precision=53)),
                        Variable(Symbol('y'),
                                 type=FloatBaseType(String('real')),
                                 value=Float('0.0', precision=53))),
            body=CodeBlock(
                Declaration(
                    Variable(Symbol('a'),
                             type=IntBaseType(String('integer')),
                             value=Integer(0))), Return('a')))

        assert res3[0] == FunctionDefinition(
            FloatBaseType(String('real')),
            name=String('fun3'),
            parameters=(Variable(Symbol('p'),
                                 type=IntBaseType(String('integer')),
                                 value=Integer(0)),
                        Variable(Symbol('q'),
                                 type=FloatBaseType(String('real')),
                                 value=Float('0.0', precision=53)),
                        Variable(Symbol('r'),
                                 type=IntBaseType(String('integer')),
                                 value=Integer(0))),
            body=CodeBlock(
                Declaration(
                    Variable(Symbol('b'),
                             type=FloatBaseType(String('real')),
                             value=Float('0.0', precision=53))), Return('b')))
Пример #7
0
    def test_parse():
        c_src1 = (
            'int a;' + '\n' +
            'int b;' + '\n'
        )
        c_src2 = (
            'void fun1()' + '\n' +
            '{' + '\n' +
            'int a;' + '\n' +
            '}'
        )

        f1 = open('..a.h', 'w')
        f2 = open('..b.h', 'w')

        f1.write(c_src1)
        f2. write(c_src2)

        f1.close()
        f2.close()

        res1 = SymPyExpression('..a.h', 'c').return_expr()
        res2 = SymPyExpression('..b.h', 'c').return_expr()

        os.remove('..a.h')
        os.remove('..b.h')

        assert res1[0] == Declaration(
            Variable(
                Symbol('a'),
                type=IntBaseType(String('integer')),
                value=Integer(0)
            )
        )
        assert res1[1] == Declaration(
            Variable(
                Symbol('b'),
                type=IntBaseType(String('integer')),
                value=Integer(0)
            )
        )
        assert res2[0] == FunctionDefinition(
            NoneToken(),
            name=String('fun1'),
            parameters=(),
            body=CodeBlock(
                Declaration(
                    Variable(
                        Symbol('a'),
                        type=IntBaseType(String('integer')),
                        value=Integer(0)
                    )
                )
            )
        )
Пример #8
0
def test_Declaration():
    u = symbols('u', real=True)
    vu = Variable(u, type=Type.from_expr(u))
    assert Declaration(vu).variable.type == real
    vn = Variable(n, type=Type.from_expr(n))
    assert Declaration(vn).variable.type == integer

    lt = StrictLessThan(vu, vn)
    assert isinstance(lt, StrictLessThan)

    vuc = Variable(u, Type.from_expr(u), value=3.0, attrs={value_const})
    assert value_const in vuc.attrs
    assert pointer_const not in vuc.attrs
    decl = Declaration(vuc)
    assert decl.variable == vuc
    assert isinstance(decl.variable.value, Float)
    assert decl.variable.value == 3.0
    assert decl.func(*decl.args) == decl
    assert vuc.as_Declaration() == decl
    assert vuc.as_Declaration(value=None, attrs=None) == Declaration(vu)

    vy = Variable(y, type=integer, value=3)
    decl2 = Declaration(vy)
    assert decl2.variable == vy
    assert decl2.variable.value == Integer(3)

    vi = Variable(i, type=Type.from_expr(i), value=3.0)
    decl3 = Declaration(vi)
    assert decl3.variable.type == integer
    assert decl3.variable.value == 3.0

    raises(ValueError, lambda: Declaration(vi, 42))
Пример #9
0
 def test_function():
     src1 = """\
     integer function f(a,b)
     integer :: x, y
     f = x + y
     end function
     """
     expr1.convert_to_expr(src1, "f")
     for iter in expr1.return_expr():
         assert isinstance(iter, FunctionDefinition)
         assert iter == FunctionDefinition(
             IntBaseType(String("integer")),
             name=String("f"),
             parameters=(Variable(Symbol("a")), Variable(Symbol("b"))),
             body=CodeBlock(
                 Declaration(
                     Variable(
                         Symbol("a"),
                         type=IntBaseType(String("integer")),
                         value=Integer(0),
                     )
                 ),
                 Declaration(
                     Variable(
                         Symbol("b"),
                         type=IntBaseType(String("integer")),
                         value=Integer(0),
                     )
                 ),
                 Declaration(
                     Variable(
                         Symbol("f"),
                         type=IntBaseType(String("integer")),
                         value=Integer(0),
                     )
                 ),
                 Declaration(
                     Variable(
                         Symbol("x"),
                         type=IntBaseType(String("integer")),
                         value=Integer(0),
                     )
                 ),
                 Declaration(
                     Variable(
                         Symbol("y"),
                         type=IntBaseType(String("integer")),
                         value=Integer(0),
                     )
                 ),
                 Assignment(Variable(Symbol("f")), Add(Symbol("x"), Symbol("y"))),
                 Return(Variable(Symbol("f"))),
             ),
         )
Пример #10
0
    def test_int():
        c_src1 = 'int a = 1;'
        c_src2 = ('int a = 1;' + '\n' + 'int b = 2;' + '\n')
        c_src3 = 'int a = 2.345, b = 5.67;'
        c_src4 = 'int p = 6, q = 23.45;'
        c_src5 = "int x = '0', y = 'a';"

        res1 = SymPyExpression(c_src1, 'c').return_expr()
        res2 = SymPyExpression(c_src2, 'c').return_expr()
        res3 = SymPyExpression(c_src3, 'c').return_expr()
        res4 = SymPyExpression(c_src4, 'c').return_expr()
        res5 = SymPyExpression(c_src5, 'c').return_expr()

        assert res1[0] == Declaration(
            Variable(Symbol('a'),
                     type=IntBaseType(String('integer')),
                     value=Integer(1)))

        assert res2[0] == Declaration(
            Variable(Symbol('a'),
                     type=IntBaseType(String('integer')),
                     value=Integer(1)))

        assert res2[1] == Declaration(
            Variable(Symbol('b'),
                     type=IntBaseType(String('integer')),
                     value=Integer(2)))

        assert res3[0] == Declaration(
            Variable(Symbol('a'),
                     type=IntBaseType(String('integer')),
                     value=Integer(2)))

        assert res3[1] == Declaration(
            Variable(Symbol('b'),
                     type=IntBaseType(String('integer')),
                     value=Integer(5)))

        assert res4[0] == Declaration(
            Variable(Symbol('p'),
                     type=IntBaseType(String('integer')),
                     value=Integer(6)))

        assert res4[1] == Declaration(
            Variable(Symbol('q'),
                     type=IntBaseType(String('integer')),
                     value=Integer(23)))

        assert res5[0] == Declaration(
            Variable(Symbol('x'),
                     type=IntBaseType(String('integer')),
                     value=Integer(48)))

        assert res5[1] == Declaration(
            Variable(Symbol('y'),
                     type=IntBaseType(String('integer')),
                     value=Integer(97)))
Пример #11
0
 def test_var():
     expr1.convert_to_expr(src, "f")
     ls = expr1.return_expr()
     for iter in expr1.return_expr():
         assert isinstance(iter, Declaration)
     assert ls[0] == Declaration(
         Variable(Symbol("a"), type=IntBaseType(String("integer")), value=Integer(0))
     )
     assert ls[1] == Declaration(
         Variable(Symbol("b"), type=IntBaseType(String("integer")), value=Integer(0))
     )
     assert ls[2] == Declaration(
         Variable(Symbol("c"), type=IntBaseType(String("integer")), value=Integer(0))
     )
     assert ls[3] == Declaration(
         Variable(Symbol("d"), type=IntBaseType(String("integer")), value=Integer(0))
     )
     assert ls[4] == Declaration(
         Variable(Symbol("p"), type=FloatBaseType(String("real")), value=Float(0.0))
     )
     assert ls[5] == Declaration(
         Variable(Symbol("q"), type=FloatBaseType(String("real")), value=Float(0.0))
     )
     assert ls[6] == Declaration(
         Variable(Symbol("r"), type=FloatBaseType(String("real")), value=Float(0.0))
     )
     assert ls[7] == Declaration(
         Variable(Symbol("s"), type=FloatBaseType(String("real")), value=Float(0.0))
     )
Пример #12
0
 def _print_FunctionPrototype(self, expr):
     pars = ', '.join(map(lambda arg: self._print(Declaration(arg)),
                          expr.parameters))
     return "%s %s(%s)" % (
         tuple(map(lambda arg: self._print(arg),
                   (expr.return_type, expr.name))) + (pars,)
     )
Пример #13
0
def test_ccode_codegen_ast():
    assert ccode(Comment("this is a comment")) == "// this is a comment"
    assert ccode(While(abs(x) > 1,
                       [aug_assign(x, '-', 1)])) == ('while (fabs(x) > 1) {\n'
                                                     '   x -= 1;\n'
                                                     '}')
    assert ccode(Scope([AddAugmentedAssignment(x, 1)])) == ('{\n'
                                                            '   x += 1;\n'
                                                            '}')
    inp_x = Declaration(Variable(x, type=real))
    assert ccode(FunctionPrototype(real, 'pwer',
                                   [inp_x])) == 'double pwer(double x)'
    assert ccode(
        FunctionDefinition(
            real, 'pwer', [inp_x],
            [Assignment(x, x**2)])) == ('double pwer(double x){\n'
                                        '   x = pow(x, 2);\n'
                                        '}')

    # Elements of CodeBlock are formatted as statements:
    block = CodeBlock(
        x,
        Print([x, y], "%d %d"),
        FunctionCall('pwer', [x]),
        Return(x),
    )
    assert ccode(block) == '\n'.join([
        'x;',
        'printf("%d %d", x, y);',
        'pwer(x);',
        'return x;',
    ])
Пример #14
0
    def test_function():
        c_src1 = ('void fun1()' + '\n' + '{' + '\n' + 'int a;' + '\n' + '}')
        c_src2 = ('int fun2()' + '\n' + '{' + '\n' + 'int a;' + '\n' +
                  'return a;' + '\n' + '}')
        c_src3 = ('float fun3()' + '\n' + '{' + '\n' + 'float b;' + '\n' +
                  'return b;' + '\n' + '}')
        c_src4 = ('float fun4()' + '\n' + '{}')

        res1 = SymPyExpression(c_src1, 'c').return_expr()
        res2 = SymPyExpression(c_src2, 'c').return_expr()
        res3 = SymPyExpression(c_src3, 'c').return_expr()
        res4 = SymPyExpression(c_src4, 'c').return_expr()

        assert res1[0] == FunctionDefinition(
            NoneToken(),
            name=String('fun1'),
            parameters=(),
            body=CodeBlock(
                Declaration(
                    Variable(Symbol('a'),
                             type=IntBaseType(String('integer')),
                             value=Integer(0)))))

        assert res2[0] == FunctionDefinition(
            IntBaseType(String('integer')),
            name=String('fun2'),
            parameters=(),
            body=CodeBlock(
                Declaration(
                    Variable(Symbol('a'),
                             type=IntBaseType(String('integer')),
                             value=Integer(0))), Return('a')))

        assert res3[0] == FunctionDefinition(
            FloatBaseType(String('real')),
            name=String('fun3'),
            parameters=(),
            body=CodeBlock(
                Declaration(
                    Variable(Symbol('b'),
                             type=FloatBaseType(String('real')),
                             value=Float('0.0', precision=53))), Return('b')))

        assert res4[0] == FunctionPrototype(FloatBaseType(String('real')),
                                            name=String('fun4'),
                                            parameters=())
Пример #15
0
 def _declare_number_const(self, name, value):
     type_ = self.type_aliases[real]
     var = Variable(name,
                    type=type_,
                    value=value.evalf(type_.decimal_dig),
                    attrs={value_const})
     decl = Declaration(var)
     return self._get_statement(self._print(decl))
Пример #16
0
def test_ccode_Declaration():
    i = symbols('i', integer=True)
    var1 = Variable(i, type_=Type.from_expr(i))
    dcl1 = Declaration(var1)
    assert ccode(dcl1) == 'int i'

    var2 = Variable(x, {value_const}, float32)
    dcl2a = Declaration(var2)
    assert ccode(dcl2a) == 'const float x'
    dcl2b = Declaration(var2, pi)
    assert ccode(dcl2b) == 'const float x = M_PI'

    var3 = Variable(y, type_=Type('bool'))
    dcl3 = Declaration(var3)
    printer = C89CodePrinter()
    assert 'stdbool.h' not in printer.headers
    assert printer.doprint(dcl3) == 'bool y'
    assert 'stdbool.h' in printer.headers

    u = symbols('u', real=True)
    ptr4 = Pointer.deduced(u, {pointer_const, restrict})
    dcl4 = Declaration(ptr4)
    assert ccode(dcl4) == 'double * const restrict u'

    var5 = Variable(x, {value_const}, Type('__float128'))
    dcl5a = Declaration(var5)
    assert ccode(dcl5a) == 'const __float128 x'
    dcl5b = Declaration(var5, pi)
    assert ccode(dcl5b) == 'const __float128 x = M_PI'
Пример #17
0
def test_Subroutine():
    # Code to generate the subroutine in the example from
    # http://www.fortran90.org/src/best-practices.html#arrays
    r = Symbol("r", real=True)
    i = Symbol("i", integer=True)
    v_r = Variable.deduced(r, attrs=(dimension(assumed_extent), intent_out))
    v_i = Variable.deduced(i)
    v_n = Variable("n", integer)
    do_loop = Do([Assignment(Element(r, [i]),
                             literal_dp(1) / i**2)], i, 1, v_n)
    sub = Subroutine(
        "f",
        [v_r],
        [
            Declaration(v_n),
            Declaration(v_i),
            Assignment(v_n, size(r)), do_loop
        ],
    )
    x = Symbol("x", real=True)
    v_x3 = Variable.deduced(x, attrs=[dimension(3)])
    mod = Module("mymod", definitions=[sub])
    prog = Program(
        "foo",
        [
            use(mod, only=[sub]),
            Declaration(v_x3),
            SubroutineCall(sub, [v_x3]),
            Print([sum_(v_x3), v_x3]),
        ],
    )

    if not has_fortran():
        skip("No fortran compiler found.")

    (stdout, stderr), info = compile_run_strings(
        [("a.f90", fcode(mod, standard=90)),
         ("b.f90", fcode(prog, standard=90))],
        clean=True,
    )
    ref = [1.0 / i**2 for i in range(1, 4)]
    assert str(sum(ref))[:-3] in stdout
    for _ in ref:
        assert str(_)[:-3] in stdout
    assert stderr == ""
Пример #18
0
    def test_float():
        c_src1 = "float a = 1.0;"
        c_src2 = "float a = 1.25;" + "\n" + "float b = 2.39;" + "\n"
        c_src3 = "float x = 1, y = 2;"
        c_src4 = "float p = 5, e = 7.89;"

        res1 = SymPyExpression(c_src1, "c").return_expr()
        res2 = SymPyExpression(c_src2, "c").return_expr()
        res3 = SymPyExpression(c_src3, "c").return_expr()
        res4 = SymPyExpression(c_src4, "c").return_expr()

        assert res1[0] == Declaration(
            Variable(
                Symbol("a"),
                type=FloatBaseType(String("real")),
                value=Float("1.0", precision=53),
            ))

        assert res2[0] == Declaration(
            Variable(
                Symbol("a"),
                type=FloatBaseType(String("real")),
                value=Float("1.25", precision=53),
            ))

        assert res2[1] == Declaration(
            Variable(
                Symbol("b"),
                type=FloatBaseType(String("real")),
                value=Float("2.3900000000000001", precision=53),
            ))

        assert res3[0] == Declaration(
            Variable(
                Symbol("x"),
                type=FloatBaseType(String("real")),
                value=Float("1.0", precision=53),
            ))

        assert res3[1] == Declaration(
            Variable(
                Symbol("y"),
                type=FloatBaseType(String("real")),
                value=Float("2.0", precision=53),
            ))

        assert res4[0] == Declaration(
            Variable(
                Symbol("p"),
                type=FloatBaseType(String("real")),
                value=Float("5.0", precision=53),
            ))

        assert res4[1] == Declaration(
            Variable(
                Symbol("e"),
                type=FloatBaseType(String("real")),
                value=Float("7.89", precision=53),
            ))
Пример #19
0
    def _print_TemplateFunctionDefinition(self, expr):
        decl = "template<{template_args}>\n{ret_type} {name}({params}){body}".format(
                    template_args=', '.join(map(lambda arg: 'typename '+self._print(arg), expr.template_types)),
                    ret_type=self._print(expr.return_type),
                    name=expr.name,
                    params=', '.join(map(lambda arg: self._print(Declaration(arg)), expr.parameters)),
                    body=self._print_Scope(expr)

                )
        return decl
Пример #20
0
    def test_float():
        c_src1 = 'float a = 1.0;'
        c_src2 = ('float a = 1.25;' + '\n' + 'float b = 2.39;' + '\n')

        res1 = SymPyExpression(c_src1, 'c').return_expr()
        res2 = SymPyExpression(c_src2, 'c').return_expr()

        assert res1[0] == Declaration(
            Variable(Symbol('a'),
                     type=FloatBaseType(String('real')),
                     value=Float('1.0', precision=53)))

        assert res2[0] == Declaration(
            Variable(Symbol('a'),
                     type=FloatBaseType(String('real')),
                     value=Float('1.25', precision=53)))

        assert res2[1] == Declaration(
            Variable(Symbol('b'),
                     type=FloatBaseType(String('real')),
                     value=Float('2.3900000000000001', precision=53)))
Пример #21
0
    def test_int():
        c_src1 = 'int a = 1;'
        c_src2 = ('int a = 1;' + '\n' + 'int b = 2;' + '\n')

        res1 = SymPyExpression(c_src1, 'c').return_expr()
        res2 = SymPyExpression(c_src2, 'c').return_expr()

        assert res1[0] == Declaration(
            Variable(Symbol('a'),
                     type=IntBaseType(String('integer')),
                     value=Integer(1)))

        assert res2[0] == Declaration(
            Variable(Symbol('a'),
                     type=IntBaseType(String('integer')),
                     value=Integer(1)))

        assert res2[1] == Declaration(
            Variable(Symbol('b'),
                     type=IntBaseType(String('integer')),
                     value=Integer(2)))
Пример #22
0
 def kernel_arg_local_assign(self, args_var):
     member_types = {
         "int32": lambda x: Variable(x, type=int32),
         "uint32": lambda x: Variable(x, type=uint32),
         "pint8": lambda x: Pointer(x, type=int8, attrs=(restrict, )),
     }
     return [
         AssignmentEx(
             Declaration(member_types[kernel_arg[1]](kernel_arg[0])),
             StructVariable(args_var, Symbol(kernel_arg[0])))
         for kernel_arg in self.kernel_args
     ]
Пример #23
0
def test_ccode_Declaration():
    i = symbols("i", integer=True)
    var1 = Variable(i, type=Type.from_expr(i))
    dcl1 = Declaration(var1)
    assert ccode(dcl1) == "int i"

    var2 = Variable(x, type=float32, attrs={value_const})
    dcl2a = Declaration(var2)
    assert ccode(dcl2a) == "const float x"
    dcl2b = var2.as_Declaration(value=pi)
    assert ccode(dcl2b) == "const float x = M_PI"

    var3 = Variable(y, type=Type("bool"))
    dcl3 = Declaration(var3)
    printer = C89CodePrinter()
    assert "stdbool.h" not in printer.headers
    assert printer.doprint(dcl3) == "bool y"
    assert "stdbool.h" in printer.headers

    u = symbols("u", real=True)
    ptr4 = Pointer.deduced(u, attrs={pointer_const, restrict})
    dcl4 = Declaration(ptr4)
    assert ccode(dcl4) == "double * const restrict u"

    var5 = Variable(x, Type("__float128"), attrs={value_const})
    dcl5a = Declaration(var5)
    assert ccode(dcl5a) == "const __float128 x"
    var5b = Variable(var5.symbol, var5.type, pi, attrs=var5.attrs)
    dcl5b = Declaration(var5b)
    assert ccode(dcl5b) == "const __float128 x = M_PI"
Пример #24
0
    def test_parse():
        c_src1 = "int a;" + "\n" + "int b;" + "\n"
        c_src2 = "void fun1()" + "\n" + "{" + "\n" + "int a;" + "\n" + "}"

        f1 = open("..a.h", "w")
        f2 = open("..b.h", "w")

        f1.write(c_src1)
        f2.write(c_src2)

        f1.close()
        f2.close()

        res1 = SymPyExpression("..a.h", "c").return_expr()
        res2 = SymPyExpression("..b.h", "c").return_expr()

        os.remove("..a.h")
        os.remove("..b.h")

        assert res1[0] == Declaration(
            Variable(Symbol("a"),
                     type=IntBaseType(String("integer")),
                     value=Integer(0)))
        assert res1[1] == Declaration(
            Variable(Symbol("b"),
                     type=IntBaseType(String("integer")),
                     value=Integer(0)))
        assert res2[0] == FunctionDefinition(
            NoneToken(),
            name=String("fun1"),
            parameters=(),
            body=CodeBlock(
                Declaration(
                    Variable(
                        Symbol("a"),
                        type=IntBaseType(String("integer")),
                        value=Integer(0),
                    ))),
        )
Пример #25
0
def test_fcode_Declaration():
    def check(expr, ref, **kwargs):
        assert fcode(expr, standard=95, source_format='free', **kwargs) == ref

    i = symbols('i', integer=True)
    var1 = Variable.deduced(i)
    dcl1 = Declaration(var1)
    check(dcl1, "integer*4 :: i")

    x, y = symbols('x y')
    var2 = Variable(x, float32, value=42, attrs={value_const})
    dcl2b = Declaration(var2)
    check(dcl2b, 'real*4, parameter :: x = 42')

    var3 = Variable(y, type=bool_)
    dcl3 = Declaration(var3)
    check(dcl3, 'logical :: y')

    check(float32, "real*4")
    check(float64, "real*8")
    check(real, "real*4", type_aliases={real: float32})
    check(real, "real*8", type_aliases={real: float64})
Пример #26
0
    def setup_codegen(self):
        args_var = Pointer("Args")
        block = self.kernel_arg_local_assign(args_var)
        if self._kernel_dims == 1:
            last_first = Variable("Sz", type=uint32)
            block.append(
                AssignmentEx(Declaration(last_first),
                             Symbol("W") * Symbol("H")))
        elif self._kernel_dims == 2:
            last_first = Variable("H", type=uint32)
        elif self._kernel_dims == 3:
            last_first = Variable("InFeatures", type=uint32)
        else:
            raise ValueError("expression has too many dimensions")

        var_chunk = Variable("Chunk", type=uint32)
        var_first = Variable("First", type=uint32)
        var_last = Variable("Last", type=uint32)
        var_coreid = Variable("CoreId", type=uint32)
        # unsigned int CoreId = gap_coreid();
        block.append(
            AssignmentEx(Declaration(var_coreid),
                         FunctionCall("gap_coreid", [])))
        # unsigned int Chunk = ChunkSize(OutFeatures);
        block.append(
            AssignmentEx(Declaration(var_chunk),
                         FunctionCall("ChunkSize", [last_first])))
        # unsigned int First = Chunk*CoreId;
        block.append(
            AssignmentEx(Declaration(var_first),
                         Symbol("Chunk") * Symbol("CoreId")))
        # unsigned int Last = Min(First+Chunk, OutFeatures);
        block.append(
            AssignmentEx(
                Declaration(var_last),
                FunctionCall("gap_min",
                             [Symbol("First") + Symbol("Chunk"), last_first])))
        return block
Пример #27
0
def test_Program():
    x = Symbol('x', real=True)
    vx = Variable.deduced(x, 42)
    decl = Declaration(vx)
    prnt = Print([x, x+1])
    prog = Program('foo', [decl, prnt])
    if not has_fortran():
        skip("No fortran compiler found.")

    (stdout, stderr), info = compile_run_strings([('main.f90', fcode(prog, standard=90))], clean=True)
    assert '42' in stdout
    assert '43' in stdout
    assert stderr == ''
    assert info['exit_status'] == os.EX_OK
Пример #28
0
def test_C99CodePrinter_custom_type():
    # We will look at __float128 (new in glibc 2.26)
    f128 = FloatType("_Float128", float128.nbits, float128.nmant, float128.nexp)
    p128 = C99CodePrinter(
        dict(
            type_aliases={real: f128},
            type_literal_suffixes={f128: "Q"},
            type_func_suffixes={f128: "f128"},
            type_math_macro_suffixes={real: "f128", f128: "f128"},
            type_macros={f128: ("__STDC_WANT_IEC_60559_TYPES_EXT__",)},
        )
    )
    assert p128.doprint(x) == "x"
    assert not p128.headers
    assert not p128.libraries
    assert not p128.macros
    assert p128.doprint(2.0) == "2.0Q"
    assert not p128.headers
    assert not p128.libraries
    assert p128.macros == {"__STDC_WANT_IEC_60559_TYPES_EXT__"}

    assert p128.doprint(Rational(1, 2)) == "1.0Q/2.0Q"
    assert p128.doprint(sin(x)) == "sinf128(x)"
    assert p128.doprint(cos(2.0, evaluate=False)) == "cosf128(2.0Q)"

    var5 = Variable(x, f128, attrs={value_const})

    dcl5a = Declaration(var5)
    assert ccode(dcl5a) == "const _Float128 x"
    var5b = Variable(x, f128, pi, attrs={value_const})
    dcl5b = Declaration(var5b)
    assert p128.doprint(dcl5b) == "const _Float128 x = M_PIf128"
    var5b = Variable(x, f128, value=Catalan.evalf(38), attrs={value_const})
    dcl5c = Declaration(var5b)
    assert p128.doprint(dcl5c) == "const _Float128 x = %sQ" % Catalan.evalf(
        f128.decimal_dig
    )
Пример #29
0
def test_Program():
    x = Symbol("x", real=True)
    vx = Variable.deduced(x, 42)
    decl = Declaration(vx)
    prnt = Print([x, x + 1])
    prog = Program("foo", [decl, prnt])
    if not has_fortran():
        skip("No fortran compiler found.")

    (stdout, stderr), info = compile_run_strings(
        [("main.f90", fcode(prog, standard=90))], clean=True)
    assert "42" in stdout
    assert "43" in stdout
    assert stderr == ""
    assert info["exit_status"] == os.EX_OK
Пример #30
0
def test_sym_expr():
    src1 = (src + """\
        d = a + b -c
        """)
    expr3 = SymPyExpression(src, 'f')
    expr4 = SymPyExpression(src1, 'f')
    ls1 = expr3.return_expr()
    ls2 = expr4.return_expr()
    for i in range(0, 7):
        assert isinstance(ls1[i], Declaration)
        assert isinstance(ls2[i], Declaration)
    assert isinstance(ls2[8], Assignment)
    assert ls1[0] == Declaration(
        Variable(Symbol('a'),
                 type=IntBaseType(String('integer')),
                 value=Integer(0)))
    assert ls1[1] == Declaration(
        Variable(Symbol('b'),
                 type=IntBaseType(String('integer')),
                 value=Integer(0)))
    assert ls1[2] == Declaration(
        Variable(Symbol('c'),
                 type=IntBaseType(String('integer')),
                 value=Integer(0)))
    assert ls1[3] == Declaration(
        Variable(Symbol('d'),
                 type=IntBaseType(String('integer')),
                 value=Integer(0)))
    assert ls1[4] == Declaration(
        Variable(Symbol('p'),
                 type=FloatBaseType(String('real')),
                 value=Float(0.0)))
    assert ls1[5] == Declaration(
        Variable(Symbol('q'),
                 type=FloatBaseType(String('real')),
                 value=Float(0.0)))
    assert ls1[6] == Declaration(
        Variable(Symbol('r'),
                 type=FloatBaseType(String('real')),
                 value=Float(0.0)))
    assert ls1[7] == Declaration(
        Variable(Symbol('s'),
                 type=FloatBaseType(String('real')),
                 value=Float(0.0)))
    assert ls2[8] == Assignment(Variable(Symbol('d')),
                                Symbol('a') + Symbol('b') - Symbol('c'))
Пример #31
0
    def test_fortran_parse():
        expr = SymPyExpression(src, "f")
        ls = expr.return_expr()

        assert ls[0] == Declaration(
            Variable(Symbol("a"),
                     type=IntBaseType(String("integer")),
                     value=Integer(0)))
        assert ls[1] == Declaration(
            Variable(Symbol("b"),
                     type=IntBaseType(String("integer")),
                     value=Integer(0)))
        assert ls[2] == Declaration(
            Variable(Symbol("c"),
                     type=IntBaseType(String("integer")),
                     value=Integer(0)))
        assert ls[3] == Declaration(
            Variable(Symbol("d"),
                     type=IntBaseType(String("integer")),
                     value=Integer(0)))
        assert ls[4] == Declaration(
            Variable(
                Symbol("p"),
                type=FloatBaseType(String("real")),
                value=Float("0.0", precision=53),
            ))
        assert ls[5] == Declaration(
            Variable(
                Symbol("q"),
                type=FloatBaseType(String("real")),
                value=Float("0.0", precision=53),
            ))
        assert ls[6] == Declaration(
            Variable(
                Symbol("r"),
                type=FloatBaseType(String("real")),
                value=Float("0.0", precision=53),
            ))
        assert ls[7] == Declaration(
            Variable(
                Symbol("s"),
                type=FloatBaseType(String("real")),
                value=Float("0.0", precision=53),
            ))