Exemple #1
0
 def test_03_basicstmt(self):
     """Test cnorm statement nodes"""
     c = nodes.Binary(nodes.Raw('<'), [nodes.Id('a'), nodes.Literal('12')])
     thencond = nodes.ExprStmt(
         nodes.Binary(nodes.Raw('='),
                      [nodes.Id('b'), nodes.Literal('1')]))
     elsecond = nodes.ExprStmt(
         nodes.Binary(nodes.Raw('='),
                      [nodes.Id('c'), nodes.Literal('2')]))
     s = nodes.If(c, thencond, elsecond)
     self.assertEqual(
         str(s.to_c()),
         "if (a < 12)\n{tab}b = 1;\nelse\n{tab}c = 2;\n".format(tab=" " *
                                                                4),
         "Failed to convert to C")
     s = nodes.RootBlockStmt(
         [thencond,
          nodes.BlockStmt([thencond, elsecond]), elsecond])
     self.assertEqual(
         str(s.to_c()),
         "b = 1;\n{{\n{tab}b = 1;\n{tab}c = 2;\n}}\nc = 2;\n".format(
             tab=" " * 4), "Failed to convert to C")
     s = nodes.While(c, thencond)
     self.assertEqual(str(s.to_c()),
                      "while (a < 12)\n{tab}b = 1;\n".format(tab=" " * 4),
                      "Failed to convert to C")
     s = nodes.Do(c, thencond)
     self.assertEqual(
         str(s.to_c()),
         "do\n{tab}b = 1;\nwhile (a < 12);\n".format(tab=" " * 4),
         "Failed to convert to C")
     s = nodes.Return(c)
     self.assertEqual(str(s.to_c()), "return a < 12;\n",
                      "Failed to convert to C")
     s = nodes.Goto(c)
     self.assertEqual(str(s.to_c()), "goto a < 12;\n",
                      "Failed to convert to C")
     s = nodes.Case(c)
     self.assertEqual(str(s.to_c()), "case a < 12:\n",
                      "Failed to convert to C")
     s = nodes.Label("Cool")
     self.assertEqual(str(s.to_c()), "Cool:\n", "Failed to convert to C")
     s = nodes.Switch(c, thencond)
     self.assertEqual(str(s.to_c()),
                      "switch (a < 12)\n{tab}b = 1;\n".format(tab=" " * 4),
                      "Failed to convert to C")
     init = nodes.ExprStmt(
         nodes.Binary(nodes.Raw('='),
                      [nodes.Id('b'), nodes.Literal('0')]))
     cond = nodes.ExprStmt(c)
     inc = nodes.Binary(nodes.Raw('+='),
                        [nodes.Id('b'), nodes.Literal('1')])
     s = nodes.For(init, cond, inc, thencond)
     self.assertEqual(
         str(s.to_c()),
         "for (b = 0; a < 12; b += 1)\n{tab}b = 1;\n".format(tab=" " * 4),
         "Failed to convert to C")
Exemple #2
0
def to_c(self):
    ctx = self.context()  # self.context is a weakref

    if isinstance(ctx, knodes.KcModule):
        # fetch all params types
        params_types = []
        for p in self.params:
            params_types.append(nodes.Decl('', get_types(p)))
            pass

        # mangle
        func_ctype = nodes.FuncType(self.expr_type._identifier, params_types)
        mangled_name = mangler.mangle_module(self.function,
                                             func_ctype,
                                             typeName=ctx.name)

        # create fake function call
        fake_func_call = nodes.Func(nodes.Id(mangled_name), self.params)
        return fake_func_call.to_c()

    # later: handle class instance
    # - assert context is class instance : any pointer(KType)
    # - get klass of KType
    # - find method
    # - method is virtual ? use vtable
    # - method is not virtual ? use direct function call

    raise Exception('Unknown context type: {}'.format(ctx))
Exemple #3
0
def create_var_symbol(self, ast, module_name, typo, var_name, block):
    # print("I'm a f*****g variable")
    module_name = self.value(module_name)
    typo = self.value(typo)
    var_name = self.value(var_name)
    if typo != "":
        typo = sm.type_m(typo)
    mangled_name = KoocFile.mangled_name_of_symbol(module_name, var_name, "",
                                                   typo)
    ast.set(nodes.Id(mangled_name))
    return True
Exemple #4
0
def to_c(self):
    ctx = self.context()  # self.context is a weakref

    if isinstance(ctx, knodes.KcModule):
        # mangle
        mangled_name = mangler.mangle_module(self.member,
                                             self.expr_type,
                                             typeName=ctx.name)
        return nodes.Id(mangled_name).to_c()

    # later: handle class instance, check class via expr_type of context
    # thoughts: the context will be a (local ?) variable, his type could
    #           be retrieved from the block ?
    #           => The type will be OK, resolved from typing visitor

    raise Exception('Unknown context type: {}'.format(ctx))
Exemple #5
0
def create_func_symbol(self, ast, module_name, typo, func_name, params, block):
    # print("I'm a f*****g function")
    # print("Module : ", self.value(module_name))
    # print("Type retour : ", self.value(typo))
    # print("Nom fonction :", self.value(func_name))
    # print("Types params : ", params.types)
    # print("Params : ", params.params)
    # print("")
    module_name = self.value(module_name)
    typo = self.value(typo)
    func_name = self.value(func_name)

    moncul = 0

    params_types = ""
    if params.types == []:
        params_types = "v"


#        params_types = None
    else:
        for item in params.types:
            if item == "UNDEFINED":
                if moncul == 0:
                    params_types = None
                    moncul = 1
                elif params_types != None:
                    print("va te faire farçir l'oignon")
                # params_types = item
                # print("INFERENCE DES PARAMETRES?")
            else:
                if params_types == None:
                    print("va te faire cuire un oeuf")
                param_type_node = KoocFile.kooc_a_string(item + " a;")
                params_types += param_type_node.body[0]._ctype.mangle()
    # print("params_types :", params_types)
    if typo != "":
        symbol_type_node = KoocFile.kooc_a_string(typo + " a;")
        typo = symbol_type_node.body[0]._ctype.mangle()
        # print("TYPE : ", symbol_type)
    # print("TRY TO GET: ", module_name, func_name, symbol_type, params_types)
    mangled_name = KoocFile.mangled_name_of_symbol(module_name, func_name,
                                                   params_types, typo)
    ast.set(nodes.Func(nodes.Id(mangled_name), params.params))
    # ast.set(nodes.Func(nodes.Id(module_name + "_" + typo + "_" + func_name), params.params))
    return True
Exemple #6
0
def mangle_func(self, call, spe, mod, var, params):
    from kooc import mlist, clist, glist, vlist
    from drecovery import scope
    from listToStr import listToListStr
    global mlist, clist, glist, scope, vlist
    scope_list = []
    type_object = ""
    ptr = ""
    nnname = ""
    if mod.value in mlist:
        scope_list = mlist
        type_object = "M"
    elif mod.value in clist:
        scope_list = clist
        type_object = "C"
    else:
        tmp = None
        for item in glist[scope]:
            if item["name"] == mod.value and len(item["type"]) > 3 and item["type"][:3] == "2Sp":
                if item["type"][3:] in clist:
                    tmp = item
                    break
        if tmp == None:
            print_error("error no module called : " + mod.value)
            return False
        scope_list = vlist
        ptr = "(((struct vtable_" + tmp["type"][3:] + " *)" + mod.value + ")-1)->"
        nnname = mod.value
        mod.value = tmp["type"][3:]
        type_object = "CM"
    cparse = Declaration()
    list_params = []
    all_params = [""]
    found = False
    if hasattr(params, "node"):
        for item in params.node:
            if "<class 'cnorm.nodes.Func'>" != str(type(item)):
                tmp = resolve(item, [mlist, clist])
            else:
                tmp = resolve(item.call_expr, [mlist, clist])
            if tmp == []:
                print_error("Error ambiguious statement")
                return False
            list_params.append(tmp)
        all_params = listToListStr(list_params)
    for item in all_params:
        if spe.value == "":
            m = mangle_func_from(mod.value, type_object, var.value, None, item)
            res = func_algo(call, mod, var, m, scope_list, ptr)
        else:
            ast = cparse.parse(spe.value + " " + var.value + "()" ";")
            m = mangle_func_from(mod.value, type_object, var.value, ast.body[0], item)
            res = func_algo_spe(call, mod, var, m, scope_list, ptr)
        if res == True and found == True:
            print_error("ambiguious function : " + mod.value + " " + var.value)
            return False
        if res == True:
            found = True
    if found == False:
        print_error("Don't found function : " + mod.value + " " + var.value)
        return False
    if not hasattr(params, "node"):
        params.node = []
    if nnname != "":
        params.node.append(nodes.Id(nnname))
    return True
Exemple #7
0
def new_id(self, ast, identifier):
    ast.set(nodes.Id(self.value(identifier)))
    return True
Exemple #8
0
 def test_02_basicexpr(self):
     """Test cnorm expression nodes"""
     e = nodes.Id('cool')
     self.assertEqual(str(e.to_c()), "cool", "Failed to convert to C")
     e = nodes.Literal('42')
     self.assertEqual(str(e.to_c()), "42", "Failed to convert to C")
     e = nodes.Binary(nodes.Raw('+'), [nodes.Id('a'), nodes.Literal('12')])
     p = e
     self.assertEqual(str(e.to_c()), "a + 12", "Failed to convert to C")
     e = nodes.Func(nodes.Id('f'), [nodes.Id('a'), nodes.Literal('12')])
     self.assertEqual(str(e.to_c()), "f(a, 12)", "Failed to convert to C")
     e = nodes.Ternary(
         '', [nodes.Id('a'),
              nodes.Literal('1'),
              nodes.Literal('2')])
     self.assertEqual(str(e.to_c()), "a ? 1 : 2", "Failed to convert to C")
     e = nodes.Unary(nodes.Raw('++'), [nodes.Id('a')])
     self.assertEqual(str(e.to_c()), "++a", "Failed to convert to C")
     e = nodes.Paren('', [p])
     self.assertEqual(str(e.to_c()), "(a + 12)", "Failed to convert to C")
     e = nodes.Post(nodes.Raw('++'), [nodes.Id('a')])
     self.assertEqual(str(e.to_c()), "a++", "Failed to convert to C")
     e = nodes.Array(nodes.Id('tab'), [p])
     self.assertEqual(str(e.to_c()), "tab[a + 12]",
                      "Failed to convert to C")
     e = nodes.Dot(nodes.Id('s'), [nodes.Id('a')])
     self.assertEqual(str(e.to_c()), "s.a", "Failed to convert to C")
     e = nodes.Arrow(nodes.Id('s'), [nodes.Id('a')])
     self.assertEqual(str(e.to_c()), "s->a", "Failed to convert to C")