Ejemplo n.º 1
0
def test_dump_expr():
    assert dump(src_to_ast("1+1", False)) == \
            "BinOp(left=Num(n='1'), op=Add(), right=Num(n='1'))"
    assert dump(src_to_ast("1+x", False)) == \
            "BinOp(left=Num(n='1'), op=Add(), right=Name(id='x'))"
    assert dump(src_to_ast("(x+y)**2", False)) == \
            "BinOp(left=BinOp(left=Name(id='x'), op=Add(), " \
            "right=Name(id='y')), op=Pow(), right=Num(n='2'))"
Ejemplo n.º 2
0
def test_dump_programs():
    assert dump(src_to_ast("""\
program a
integer :: b
b = 1
end program
""")) == "Program(name='a', use=[], decl=[Declaration(vars=[decl(sym='b', sym_type='integer', dims=[], attrs=[], initializer=None)])], body=[Assignment(target=Name(id='b'), value=Num(n='1'))], contains=[])"
Ejemplo n.º 3
0
def test_dump_subroutines():
    assert dump(
        src_to_ast(
            """\
subroutine f
integer :: a, b
b = (1+2+a)*3
end subroutine
""", False)
    ) == "Subroutine(name='f', args=[], use=[], decl=[Declaration(vars=[decl(sym='a', sym_type='integer', dims=[], attrs=[], initializer=None), decl(sym='b', sym_type='integer', dims=[], attrs=[], initializer=None)])], body=[Assignment(target=Name(id='b'), value=BinOp(left=BinOp(left=BinOp(left=Num(n='1'), op=Add(), right=Num(n='2')), op=Add(), right=Name(id='a')), op=Mul(), right=Num(n='3')))], contains=[])"
    assert dump(
        src_to_ast(
            """\
subroutine f(x, y)
integer, intent(out) :: x, y
x = 1
end subroutine
""", False)
    ) == "Subroutine(name='f', args=[arg(arg='x'), arg(arg='y')], use=[], decl=[Declaration(vars=[decl(sym='x', sym_type='integer', dims=[], attrs=[Attribute(name='intent', args=[attribute_arg(arg='out')])], initializer=None), decl(sym='y', sym_type='integer', dims=[], attrs=[Attribute(name='intent', args=[attribute_arg(arg='out')])], initializer=None)])], body=[Assignment(target=Name(id='x'), value=Num(n='1'))], contains=[])"
Ejemplo n.º 4
0
def test_to_tuple():
    ast_tree = src_to_ast("2+3", False)
    t = to_tuple(ast_tree)
    t_ref = ('BinOp', (1, 1), ('Num', (1, 1), '2'), ('Add', ), ('Num', (1, 1),
                                                                '3'))
    assert t == t_ref

    ast_tree = src_to_ast("2+x", False)
    t = to_tuple(ast_tree)
    t_ref = ('BinOp', (1, 1), ('Num', (1, 1), '2'), ('Add', ), ('Name', (1, 1),
                                                                'x'))
    assert t == t_ref

    ast_tree = src_to_ast("(x+y)**2", False)
    t = to_tuple(ast_tree)
    t_ref = ('BinOp', (1, 1), ('BinOp', (1, 1), ('Name', (1, 1), 'x'),
                               ('Add', ), ('Name', (1, 1), 'y')), ('Pow', ),
             ('Num', (1, 1), '2'))
    assert t == t_ref
Ejemplo n.º 5
0
def parses(test, translation_unit=False):
    """
    Returns True if and only if the string `test` parses to AST.
    """
    try:
        s = src_to_ast(test, translation_unit)
        passed = True
    except SyntaxErrorException:
        passed = False
    return passed
Ejemplo n.º 6
0
def test_unknown_type2b():
    source = """\
subroutine sub1(a)
integer, intent(in) :: a
b = 1
end subroutine
"""
    tree = src_to_ast(source, False)
    symbol_table = create_symbol_table(tree)
    with pytest.raises(UndeclaredVariableError):
        annotate_tree(tree, symbol_table)
Ejemplo n.º 7
0
def test_subroutines1():
    source = """\
subroutine sub1(a, b)
integer, intent(in) :: a
integer, intent(out) :: b
b = a + 1
end subroutine
"""
    tree = src_to_ast(source, False)
    symbol_table = create_symbol_table(tree)
    annotate_tree(tree, symbol_table)
Ejemplo n.º 8
0
def test_logical3():
    source = """\
subroutine sub1(a, b)
integer, intent(in) :: a, b
integer :: c
if (a == b) c = 1
end subroutine
"""
    tree = src_to_ast(source, False)
    symbol_table = create_symbol_table(tree)
    annotate_tree(tree, symbol_table)
Ejemplo n.º 9
0
def test_dump():
    source = """\
subroutine sub1(a, b)
integer, intent(in) :: a
integer, intent(in) :: b
a = (b + 1)*a*5
end subroutine
"""
    tree = src_to_ast(source, False)
    symbol_table = create_symbol_table(tree)
    annotate_tree(tree, symbol_table)
    assert dump(tree, include_type=True) == "Subroutine(name='sub1', args=[arg(arg='a'), arg(arg='b')], use=[], decl=[Declaration(vars=[decl(sym='a', sym_type='integer', dims=[], attrs=[Attribute(name='intent', args=[attribute_arg(arg='in')])], initializer=None)]), Declaration(vars=[decl(sym='b', sym_type='integer', dims=[], attrs=[Attribute(name='intent', args=[attribute_arg(arg='in')])], initializer=None)])], body=[Assignment(target=Name(id='a'), value=BinOp(left=BinOp(left=BinOp(left=Name(id='b', type=Integer()), op=Add(), right=Num(n='1', type=Integer()), type=Integer()), op=Mul(), right=Name(id='a', type=Integer()), type=Integer()), op=Mul(), right=Num(n='5', type=Integer()), type=Integer()), type=Integer())], contains=[])"
Ejemplo n.º 10
0
def test_logical4():
    source = """\
subroutine sub1(a, b)
integer, intent(in) :: a, b
integer :: c
if (a) c = 1
end subroutine
"""
    tree = src_to_ast(source, False)
    symbol_table = create_symbol_table(tree)
    with pytest.raises(TypeMismatch):
        annotate_tree(tree, symbol_table)
Ejemplo n.º 11
0
def test_type7():
    source = """\
subroutine sub1(a, b)
real, intent(in) :: a
real, intent(in) :: b
a = (b + a)*a
end subroutine
"""
    tree = src_to_ast(source, False)
    symbol_table = create_symbol_table(tree)
    annotate_tree(tree, symbol_table)
    assert tree.body[0]._type == Real()
Ejemplo n.º 12
0
def test_arrays1():
    source = """\
subroutine sub1()
integer :: a(3), i
a(1) = 1
i = 2
a(2) = i
a(i) = i+1
end subroutine
"""
    tree = src_to_ast(source, False)
    symbol_table = create_symbol_table(tree)
    annotate_tree(tree, symbol_table)
Ejemplo n.º 13
0
def test_logical1():
    source = """\
subroutine sub1(a, b)
integer, intent(in) :: a
integer, intent(in) :: b
logical :: r
r = (a == b)
end subroutine
"""
    tree = src_to_ast(source, False)
    symbol_table = create_symbol_table(tree)
    annotate_tree(tree, symbol_table)
    assert tree.body[0]._type == Logical()
Ejemplo n.º 14
0
def test_arrays2():
    source = """\
subroutine sub1()
integer :: a(3)
real :: r
a(1) = 1
r = 2
a(r) = 2
end subroutine
"""
    tree = src_to_ast(source, False)
    symbol_table = create_symbol_table(tree)
    with pytest.raises(TypeMismatch):
        annotate_tree(tree, symbol_table)
Ejemplo n.º 15
0
def test_logical5():
    source = """\
subroutine sub1(a, b)
integer, intent(in) :: a, b
integer :: c
if (a == b) then
    d = 1
end if
end subroutine
"""
    tree = src_to_ast(source, False)
    symbol_table = create_symbol_table(tree)
    with pytest.raises(UndeclaredVariableError):
        annotate_tree(tree, symbol_table)
Ejemplo n.º 16
0
def test_arrays4():
    source = """\
subroutine sub1()
integer :: a(3), b(4), i
a(1) = b(2)
a(i) = b(2)
a(1) = b(2) + 1
a(1) = 1 + b(2)
a(1) = b(i) + 1
a(1) = b(i) + b(1)
end subroutine
"""
    tree = src_to_ast(source, False)
    symbol_table = create_symbol_table(tree)
    annotate_tree(tree, symbol_table)
Ejemplo n.º 17
0
def test_arrays3():
    # Here we test assigning the wrong type to an array. Since only real and
    # integer types are implemented for now, just test that real cannot be
    # assinged to an integer. Later we can change this to, say, a character.
    source = """\
subroutine sub1()
integer :: a(3), i
real :: r
i = 1
a(i) = r
end subroutine
"""
    tree = src_to_ast(source, False)
    symbol_table = create_symbol_table(tree)
    with pytest.raises(TypeMismatch):
        annotate_tree(tree, symbol_table)
Ejemplo n.º 18
0
def test_unknown_type3():
    source = """\
module test
implicit none
contains

    subroutine sub1(a)
    integer, intent(in) :: a
    a = (1+a)**2
    end subroutine

end module
"""
    tree = src_to_ast(source)
    symbol_table = create_symbol_table(tree)
    annotate_tree(tree, symbol_table)
Ejemplo n.º 19
0
def test_doloop_transformer():
    source = """\
subroutine test()
integer :: i, j
j = 0
do i = 1, 10
    j = j + i
end do
if (j /= 55) error stop
end subroutine
"""
    tree = ast.src_to_ast(source, False)
    v = DoLoopTransformer()
    assert isinstance(tree.body[1], ast.ast.DoLoop)
    tree = v.visit(tree)
    assert isinstance(tree.body[1], ast.ast.Assignment)
    assert isinstance(tree.body[2], ast.ast.WhileLoop)
Ejemplo n.º 20
0
def test_unknown_type2():
    source = """\
module test
implicit none
contains

    subroutine sub1(a)
    integer, intent(in) :: a
    a = (1+b)**2
    end subroutine

end module
"""
    tree = src_to_ast(source)
    symbol_table = create_symbol_table(tree)
    with pytest.raises(UndeclaredVariableError):
        annotate_tree(tree, symbol_table)
Ejemplo n.º 21
0
def test_type1():
    source = """\
module test
implicit none
contains

    subroutine sub1(a, b)
    integer, intent(in) :: a, b
    a = b
    end subroutine

end module
"""
    tree = src_to_ast(source)
    symbol_table = create_symbol_table(tree)
    annotate_tree(tree, symbol_table)
    assert tree.contains[0].body[0]._type == Integer()
Ejemplo n.º 22
0
def test_type6():
    source = """\
module test
implicit none
contains

    subroutine sub1(a, b)
    integer, intent(in) :: a
    real, intent(in) :: b
    a = (b + 1)*a*5
    end subroutine

end module
"""
    tree = src_to_ast(source)
    symbol_table = create_symbol_table(tree)
    with pytest.raises(TypeMismatch):
        annotate_tree(tree, symbol_table)
Ejemplo n.º 23
0
def run_tests(tests, filename, translation_unit=False):
    results = []
    for s in tests:
        results.append(to_tuple(src_to_ast(s, translation_unit)))

    here = os.path.dirname(__file__)
    results_filename = os.path.abspath(os.path.join(here, filename))
    try:
        with open(results_filename) as f:
            d = {}
            exec(f.read(), d)
            results_ref = d["results"]
        equal = (results == results_ref)
        report = True
    except FileNotFoundError:
        equal = False
        report = False
        print("Results file does not exist.")
    if not equal:
        results_str = "results = [\n"
        for r in results:
            results_str += "    %r,\n" % (r, )
        results_str += "]\n"
        with open(results_filename + ".latest", "w") as f:
            f.write(results_str)
        print("Results file generated. If you want to use it, execute:\n" \
            "cp '{0}.latest' '{0}'".format(results_filename))
        if report:
            print()
            if (len(results) == len(results_ref)):
                print("REPORT:")
                print("Printing failed tests:")
                for i, t, s, l in zip(range(len(tests)), tests, results,
                                      results_ref):
                    if s != l:
                        print("n test")
                        print("%d: %s" % (i, t))
                        print(s)
                        print(l)
                        print()
            else:
                print("Results lists have different lengths.")
    assert equal
Ejemplo n.º 24
0
def test_function1():
    source = """\
integer function fn1(a, b) result(r)
integer, intent(in) :: a, b
r = a + b
end function
"""
    ast = src_to_ast(source, translation_unit=False)
    asrepr = ast_to_asr(ast)
    verify_asr(asrepr)

    assert 'fn1' in asrepr.global_scope.symbols
    fn1 = asrepr.global_scope.symbols['fn1']
    assert fn1.args[0].name == "a"
    assert fn1.args[1].name == "b"
    assert fn1.return_var.name == "r"
    assert fn1.body[0].target == fn1.return_var
    assert fn1.body[0].value.left == fn1.args[0]
    assert fn1.body[0].value.right == fn1.args[1]

    llmod = asr_to_llvm(asrepr)
    e = LLVMEvaluator()
    e.add_module(str(llmod))
    e.add_module("""\
declare i64 @fn1(i64* %".1", i64* %".2")

define i64 @f1()
{
    %a = alloca i64
    %b = alloca i64
    store i64 2, i64* %a
    store i64 3, i64* %b
    %r = call i64 @fn1(i64* %a, i64* %b)
    ret i64 %r
}
""")
    assert e.intfn("f1") == 5
Ejemplo n.º 25
0
def test_variables1():
    source = """\
module test
implicit none
contains

    subroutine sub1(a, b)
    integer, intent(in) :: a
    real, intent(out) :: b
    b = a + 1
    end subroutine

end module
"""
    tree = src_to_ast(source)
    global_scope = create_symbol_table(tree)
    assert not global_scope.resolve("a", False)
    sym = tree.contains[0]._scope.resolve("a")
    assert sym["type"] == Integer()
    assert sym["name"] == "a"
    sym = tree.contains[0]._scope.resolve("b")
    assert sym["type"] == Real()
    assert sym["name"] == "b"
    assert not tree.contains[0]._scope.resolve("c", False)
Ejemplo n.º 26
0
def test_list_subroutines2():
    source = """\
module subroutine1
implicit none

contains

subroutine sub1(a, b)
integer, intent(in) :: a
integer, intent(out) :: b
b = a + 1
end subroutine

subroutine sub2(c)
integer, intent(out) :: c
call sub1(8, c)
end subroutine

end module
"""
    tree = ast.src_to_ast(source)
    v = SubroutinesVisitor2()
    v.visit(tree)
    assert v.get_subroutine_list() == """\
Ejemplo n.º 27
0
def test_files():
    sources = [file1, file2, file3, file4, file5, file6, file7, file8, file9]
    assert len(sources) == 9
    print("Testing filenames:")
    for source in sources:
        src_to_ast(source)
Ejemplo n.º 28
0
def get_num(src):
    numexpr = src_to_ast(src, translation_unit=False)
    symbol_table = create_symbol_table(numexpr)
    annotate_tree(numexpr, symbol_table)
    return numexpr.o
Ejemplo n.º 29
0
def test_dump_statements():
    assert dump(src_to_ast("if (x == 1) stop\n", False)) == \
            "If(test=Compare(left=Name(id='x'), op=Eq(), right=Num(n='1')), " \
            "body=[Stop(code=None)], orelse=[])"
    assert dump(src_to_ast("x == 1\n", False)) == \
            "Compare(left=Name(id='x'), op=Eq(), right=Num(n='1'))"
Ejemplo n.º 30
0
from lfortran.ast import src_to_ast, print_tree
from lfortran.ast.ast_to_src import ast_to_src
from lfortran.semantic.ast_to_asr import ast_to_asr
from lfortran.asr.pprint import pprint_asr

src = """\
integer function f(a, b) result(r)
integer(kind=dp), intent(in) :: a, b
r = a + b
end function
"""

ast = src_to_ast(src, translation_unit=False)
asr = ast_to_asr(ast)

print_tree(ast)
pprint_asr(asr)