Пример #1
0
def handle_req(ext, fmt, sem, line):
    line -= len(fmt['includes'])
    req_type = '{0}_{1}'.format(sem['request'], sem['construct'])
    node = req_checker(req_type, sem)
    coord = Coord('file', line, 0)

    # error: missing field
    if isinstance(node, dict):
        return coord, node

    if req_type == 'declare_function':
        coord.line = 3
        ext.insert(0, node)
    elif req_type == 'include_package':
        fmt['includes'].append(node)
    else:
        coord, found = find_node(ext, line, {'method': req_type, 'arg': node})
        # error: could not find node to insert at
        if found is False:
            err = {
                'output': 'ASTInsertError' + '\n' + str(sem),
                'Error': 'Could not insert into the A. S. T.',
                'id': 'ASTInsertError'
            }
            return coord, err
    if coord is None:
        coord = Coord('file', line, 0)
    if isinstance(node, tuple):
        node = node[0]
    coord.line += len(fmt['includes'])
    return coord, node
def create_new_assign(old_cond, new_cond, coord):
    global coord_aux

    coord_aux -= 1
    # coord = old_cond.coord
    new_coord = Coord(coord.file, coord.line, coord.column)
    new_coord.line = coord_aux
    new_coord.column = coord_aux
    # print type(new_cond), type(new_cond)
    assign = Assignment('=', ID(new_cond), ID(old_cond), new_coord)
    return assign
Пример #3
0
def add_else_if(stmt, pos, elseif):
    if not hasattr(stmt, 'iffalse'):
        return None, False
    old_iffalse = stmt.iffalse
    coord = Coord('file', coord_last_line(stmt) + 2, 0)
    stmt.iffalse = elseif
    stmt.iffalse.iffalse = old_iffalse
    return coord, True
def _parse_coord(coord_str):
    """ Parse coord string (file:line[:column]) into Coord object. """
    if coord_str is None:
        return None

    vals = coord_str.split(':')
    vals.extend([None] * 3)
    filename, line, column = vals[:3]
    return Coord(filename, line, column)
Пример #5
0
def add_else(stmt, pos, els):
    '''adds else block to if statement'''
    if not hasattr(stmt, 'iffalse'):
        return None, False
    if stmt.iffalse is None:
        coord = Coord('file', coord_last_line(stmt) + 2, 0)
        stmt.iffalse = els
        return coord, True
    elif isinstance(stmt.iffalse, If):
        return add_else(stmt.iffalse, pos, els)
    return None, True
Пример #6
0
    def __init__(self, annotations, struct, json_annotations, ext):
        """
        Describes the property list for a struct
        Also create a list of c_ast.Decl to append to the struct decls
        """
        self.json_annotations = json_annotations
        self.annotated_properties = None
        self.annotations = annotations
        self.ext = ext
        self.init_list = None
        self.decls = None
        self.struct = struct
        self.extra_decls = None

        def make_extra_decl(name, t):
            idtype = c_ast.IdentifierType([t])
            td = c_ast.TypeDecl(name, [], idtype)
            return c_ast.Decl(
                name,
                [],  # quals
                [],  # storage
                [],  # funcspec
                td,  # type
                None,  # init
                None,  # bitsize
            )

        fi = getframeinfo(currentframe())
        annotated_properties = [
            AnnotatedProperty(self, d) for d in struct.decls
        ]

        out_ap = []
        for ap in annotated_properties:
            inline_annotation = ap.values.get('inline', False)
            if inline_annotation:
                astruct = self.inline_struct_annotated(inline_annotation,
                                                       ap.decl)
                out_ap += astruct.annotated_properties
            else:
                out_ap.append(ap)

        self.annotated_properties = out_ap

        init_lists = [
            ap.init_list for ap in out_ap
            # 'private' and 'inline' have no init_list
            if ap.init_list is not None
        ]

        # NULL terminator
        init_lists.append(c_ast.InitList([c_ast.Constant('int', '0')]))

        self.init_list = c_ast.InitList(init_lists,
                                        Coord(fi.filename, fi.lineno))

        decls = [ap.decl for ap in out_ap]

        extra_decls = chain.from_iterable(
            (ap.extra_decls.iteritems() for ap in out_ap))
        extra_decls = [make_extra_decl(name, t) for name, t in extra_decls]

        decls += extra_decls

        self.decls = decls
Пример #7
0
    def __init__(self, annotated_struct, decl):
        self.init_list = None
        self.decl = decl
        self.extra_decls = {}
        self.values = {}
        init_exprs = []

        self.struct = annotated_struct

        annotations = self.struct.annotations.get(decl,
                                                  self.struct.json_annotations)
        try:
            for a in annotations:
                expr = self.expand_annotation(a, self.values)
                if expr is not None:
                    init_exprs.append(expr)
        except StopIteration:
            name = a.name
            a = next(annotations, None)
            if a is not None:
                raise ExpansionError(a, decl,
                                     'Unexpected annotation after ' + name)
            return
        init_list = []

        prop_name = type_find(decl, c_ast.TypeDecl).declname

        # name the property if it hasn't already been named
        if 'name' not in self.values:
            self.values['name'] = prop_name

        # add string initializers
        for init_name in ('name', 'schema'):
            if init_name in self.values:
                literal = str_literal(self.values[init_name])
                init_exprs.append(
                    c_ast.NamedInitializer([c_ast.ID(init_name)],
                                           c_ast.Constant('string', literal)))

        # assign types
        type_annotations = {
            name: t
            for name, t in self.values.iteritems()
            if isinstance(t, Annotation)
        }
        types, arraydecl = self.struct.annotations.get_types(
            decl, type_annotations)
        type_inits = [
            c_ast.NamedInitializer([c_ast.ID(ttype)], c_ast.ID(t))
            for ttype, t in types.iteritems()
        ]
        fi = getframeinfo(currentframe())
        init_exprs.append(
            c_ast.NamedInitializer([c_ast.ID('type')],
                                   c_ast.InitList(
                                       type_inits,
                                       Coord(fi.filename, fi.lineno))))
        struct = annotated_struct.struct
        # calculate struct offset
        init_exprs.append(
            c_ast.NamedInitializer([c_ast.ID('offset')],
                                   self.offsetof(struct.name, prop_name)))
        if 'nullable' in self.values and self.values['nullable']:
            self.extra_decls[AnnotatedProperty.NULLABLE_NAME(
                decl.name)] = 'bool'
            init_exprs.append(
                c_ast.NamedInitializer(
                    [c_ast.ID('null_offset')],
                    self.offsetof(struct.name,
                                  AnnotatedProperty.NULLABLE_NAME(prop_name))))
        if arraydecl:
            # static array
            init_exprs.append(
                c_ast.NamedInitializer([c_ast.ID('length')], arraydecl.dim))
        elif types['json'] == 'json_type_array':
            # calculate length offset
            len_prop = AnnotatedProperty.LENGTH_NAME(prop_name)
            self.extra_decls[len_prop] = 'int'
            init_exprs.append(
                c_ast.NamedInitializer([c_ast.ID('length_offset')],
                                       self.offsetof(struct.name, len_prop)))
            init_exprs.append(
                c_ast.NamedInitializer([c_ast.ID('dereference')],
                                       c_ast.Constant('int', '1')))

        if types['json'] == 'json_type_array':
            # assume PtrDecl for now
            init_exprs.append(
                c_ast.NamedInitializer([c_ast.ID('stride')],
                                       self.sizeof(decl.type.type)))

        fi = getframeinfo(currentframe())
        self.init_list = c_ast.InitList(init_exprs,
                                        Coord(fi.filename, fi.lineno))
Пример #8
0
def whiles_to_if(extern_while_body, conditii=None):
    """
    modifies the main while loop
    all recv loops are translated to ifs

    :param extern_while_body:
    :return: modified main while
    """
    global coord_aux
    coord_aux -= 1
    i = 0
    # print "aaaaaaaaaaa", extern_while_body.coord

    # print extern_while_body.coord, "merge"
    size = len(extern_while_body.block_items)
    # print "aici e ok"
    list = []
    delete = []

    while i < size:
        aux = extern_while_body
        element = aux.block_items[i]

        if isinstance(element, While) and to_modify(element):

            coord = element.stmt.coord

            new_if = modify_while(element)
            if isinstance(new_if, If):
                list = aux.block_items[i + 1:]  # next code is part of iftrue
                extern_while_body.block_items[i + 1:] = [
                ]  # don't copy the next code
                aux.block_items.remove(aux.block_items[i])
                new_if.iftrue = Compound(list, coord)

                new_coord = Coord(coord.file, coord.line, coord.column)
                new_coord.line = coord_aux
                new_coord.column = coord_aux

                coord_aux -= 1
                new_break_coord = Coord(coord.file, coord.line, coord.column)
                new_break_coord.line = coord_aux
                new_break_coord.column = coord_aux

                coord_aux -= 1
                id_coord = Coord(coord.file, coord.line, coord.column)
                id_coord.line = coord_aux
                id_coord.column = coord_aux

                coord_aux -= 1
                assign_coord = Coord(coord.file, coord.line, coord.column)
                assign_coord.line = coord_aux
                assign_coord.column = coord_aux

                new_if.iffalse = Compound([
                    Assignment('=', ID("round"), ID("ERR_ROUND"), assign_coord)
                ], new_coord)

                # FuncCall(ID("wait_for_messages", id_coord), None, new_break_coord)

                aux.block_items.insert(i, new_if)
                if new_if.iftrue:
                    whiles_to_if(new_if.iftrue, conditii)

                break
            else:
                delete.append(aux.block_items[i]
                              )  # daca are timeout, sterg bucla cu totull
                conditii.append((new_if, coord))
                # aux.block_items[i] = None
        # elif isinstance(element, While) and (not to_modify(element)):
        #         whiles_to_if(element.stmt, conditii)

        if isinstance(element, If):
            # if there is any if statement which contains
            # a recv loop in iftrue or iffalse it will be modified

            if isinstance(element.iftrue, Compound):
                to_delete = []
                for index, item in enumerate(element.iftrue.block_items):

                    if not isinstance(item, While):
                        list.append(item)
                        if isinstance(item, If):
                            if item.iftrue:
                                whiles_to_if(
                                    item.iftrue, conditii
                                )  # nu stiu inca de ce trb sa pun asta aici
                            if item.iffalse:
                                whiles_to_if(item.iffalse, conditii)
                    elif to_modify(item):
                        # print item.coord, 'aaaa'
                        coord = item.stmt.coord

                        new_if = modify_while(item)
                        if isinstance(
                                new_if, If
                        ):  # daca intoarce if,adica daca nu are timeout
                            lista = element.iftrue.block_items[index + 1:]
                            element.iftrue.block_items[index + 1:] = []
                            element.iftrue.block_items.remove(
                                element.iftrue.block_items[index])
                            new_if.iftrue = Compound(lista, coord)

                            new_coord = Coord(coord.file, coord.line,
                                              coord.column)
                            new_coord.line = coord_aux
                            new_coord.column = coord_aux

                            coord_aux -= 1
                            new_break_coord = Coord(coord.file, coord.line,
                                                    coord.column)
                            new_break_coord.line = coord_aux
                            new_break_coord.column = coord_aux

                            coord_aux -= 1
                            id_coord = Coord(coord.file, coord.line,
                                             coord.column)
                            id_coord.line = coord_aux
                            id_coord.column = coord_aux

                            coord_aux -= 1
                            assign_coord = Coord(coord.file, coord.line,
                                                 coord.column)
                            assign_coord.line = coord_aux
                            assign_coord.column = coord_aux

                            new_if.iffalse = Compound([
                                Assignment('=', ID("round"), ID("ERR_ROUND"),
                                           assign_coord)
                            ], new_coord)

                            element.iftrue.block_items.insert(index, new_if)
                            if new_if.iftrue:
                                whiles_to_if(new_if.iftrue, conditii)

                            break
                        else:
                            to_delete.append(element.iftrue.block_items[index])
                            conditii.append((new_if, coord))
                            # element.iftrue.block_items[index] = None
                for x in to_delete:
                    element.iftrue.block_items.remove(x)
            if element.iffalse is not None:
                if isinstance(element.iffalse, Compound):
                    to_delete = []
                    for index, item in enumerate(element.iffalse.block_items):

                        # print item.coord
                        if not isinstance(item, While):
                            list.append(item)
                            # print item
                            if isinstance(item, If):
                                whiles_to_if(item.iftrue, conditii)
                                if item.iffalse:
                                    whiles_to_if(item.iffalse, conditii)
                        elif to_modify(item):
                            # print item.coord,"bbb"
                            coord = item.stmt.coord
                            new_if = modify_while(item)
                            if isinstance(new_if, If):
                                lista = element.iffalse.block_items[index + 1:]
                                element.iffalse.block_items[index + 1:] = []
                                element.iffalse.block_items.remove(
                                    element.iffalse.block_items[index])
                                new_if.iffalse = Compound(lista, coord)
                                # new_if.iffalse = Compound([Break()], coord_aux)
                                element.iffalse.block_items.insert(
                                    index, new_if)
                                if new_if.iffalse:
                                    whiles_to_if(new_if.iffalse, conditii)

                                break
                            else:
                                to_delete.append(
                                    element.iffalse.block_items[index])
                                # element.iffalse.block_items[index] = None
                    for x in to_delete:
                        element.iffalse.block_items.remove(x)

        i += 1
    for x in delete:
        extern_while_body.block_items.remove(x)