Ejemplo n.º 1
0
    def check_inner(self, file_content, file_contentf):
        last_func = ''
        i = 0
        index = 0
        line_start = -1
        lines = file_content.split('\n')

        for line in lines:
            i += 1
            if line in v.function_defs:
                last_func = v.function_defs[line]

            started_newindent = 0
            if '{' in line:
                started_newindent = 1
                if index == 0:
                    line_start = i
                index += 1
                if i - 1 >= 0 and i - 1 in v.function_defs:
                    last_func = v.function_defs[i - 1]
            elif re.match(r'[ \t]*}[ \t]*', line):
                started_newindent = 0
                index -= 1
                if index <= 0:
                    index = 0
                    if line_start > 0 and i - line_start - 2 > 20:
                        BuErrors.print_error(
                            self.file_name, i + self.header_lines - 1, 2, "F4",
                            "Func '{0}' too long ({1} > 20)".format(
                                last_func, (i - line_start - 2)))
                    line_start = -1
                    last_func = ''
            else:
                started_newindent = 0
Ejemplo n.º 2
0
 def err(self, line, line_number, text):
     if not self.is_enabled():
         return 0
     if line_number != -1:
         line_number += self.header_lines
     BuErrors.print_error(self.path, self.file_name, line_number,
                          self.get_check_level(), self.get_check_id(), text)
 def check_inner(self, file_content, file_contentf):
     lines_with_comments = file_content.split('\n')
     i = 0
     index = 0
     for line in lines_with_comments:
         i += 1
         base_line = line.replace("\t", "").lstrip()
         if index > 0:
             if base_line.startswith("//") or base_line.startswith("/*"):
                 self.fill_error(last_func)
                 BuErrors.print_error(
                     self.path, self.file_name, i, self.get_check_level(),
                     self.get_check_id(),
                     self.get_config()['message'].format(last_func))
         if re.match(r'{[ \t]*', line):
             index += 1
             if i - 1 >= 0 and cache_visitor is not None and i - self.header_lines - 1 in cache_visitor.function_defs:
                 last_func = cache_visitor.function_defs[i -
                                                         self.header_lines -
                                                         1]
         elif re.match(r'[ \t]*}[ \t]*', line):
             index -= 1
             if index <= 0:
                 index = 0
                 last_func = ''
     return 0
Ejemplo n.º 4
0
    def stmt_parse(self, node, last, ilvl, last_expr):
        stmb = 0
        for st in sub_stmt:
            if isinstance(node, st):
                stmb = 1
        if not stmb:
            return 0
        stms = []
        stms_expr = []
        if hasattr(node, 'iftrue') and node.iftrue is not None:
            stms.append(node.iftrue)
            stms_expr.append('iftrue')
        if hasattr(node, 'iffalse') and node.iffalse is not None:
            stms.append(node.iffalse)
            stms_expr.append('iffalse')
        if hasattr(node, 'stmt') and node.stmt is not None:
            stms.append(node.stmt)
            stms_expr.append('stmt')
        node_cc = node.coord.line - 1
        nodel = tc[node_cc]
        node_s = len(nodel) - len(nodel.lstrip())
        #if node_s != (ilvl) * t_mul and node_cc + 1 not in flag_lines:
        #    flag_lines.append(node_cc + 1)
        #    BuErrors.print_error(self.path, self.file_name, node_cc + 1 + self.header_lines,
        #                         self.get_check_level(), self.get_check_id(),
        #                         'a' + self.message.format(str((ilvl) * t_mul), str(node_s)))
        pos = -1
        for stm1 in stms:
            pos += 1
            if self.stmt_parse(stm1, node, ilvl + 1, stms_expr[pos]):
                continue
            try:
                for stm in stm1:
                    ilvl_n = ilvl
                    if self.stmt_parse(stm, node, ilvl + 1, stms_expr[pos]):
                        continue
                    li = stm.coord.line - 1
                    l = tc[li]
                    s = len(l) - len(l.lstrip())
                    line = li + 1 + self.header_lines + (1 if self.header_lines > 0 else 0)
                    # Handle conditional branches

                    ilvl_t = ilvl
                    if isinstance(node, If) and isinstance(last, If):
                        if last.iffalse and hasattr(last.iffalse, 'iftrue') and stm1 == last.iffalse.iftrue:
                            ilvl_t -= 1
                        elif last.iffalse and hasattr(last.iffalse, 'iffalse') and stm1 == last.iffalse.iffalse:
                            ilvl_t -= 1
                    if s != ilvl_t * self.get_config()['spaces_per_level'] and line not in flag_lines:
                        flag_lines.append(line)
                        BuErrors.print_error(self.path, self.file_name, line,
                                             self.get_check_level(), self.get_check_id(),
                                             self.message.format(str(ilvl_t * self.get_config()['spaces_per_level']), str(s)))
            except:
                pass
        return 1
Ejemplo n.º 5
0
 def check_ast(self, ast):
     # Check for structures in source file
     if not self.is_header_file():
         for dcl in ast:
             if not isinstance(dcl, Decl) or not hasattr(dcl, 'type'):
                 continue
             if not isinstance(dcl.type, Struct):
                 continue
             self.message = self.get_config()['source_struct']
             BuErrors.print_error(self.path, self.file_name, -1,
                                  self.get_check_level(),
                                  self.get_check_id(), self.message)
     return 0
Ejemplo n.º 6
0
    def stmt_parse(self, node, last, ilvl, last_expr):
        stmb = 0
        for st in sub_stmt:
            if isinstance(node, st):
                stmb = 1
        if not stmb:
            return 0
        stms = []
        stms_expr = []
        if hasattr(node, 'iftrue') and node.iftrue is not None:
            stms.append(node.iftrue)
            stms_expr.append('iftrue')
        if hasattr(node, 'iffalse') and node.iffalse is not None:
            stms.append(node.iffalse)
            stms_expr.append('iffalse')
        if hasattr(node, 'stmt') and node.stmt is not None:
            stms.append(node.stmt)
            stms_expr.append('stmt')
        pos = -1
        for stm1 in stms:
            pos += 1
            if self.stmt_parse(stm1, node, ilvl + 1, stms_expr[pos]):
                continue
            try:
                for stm in stm1:
                    if self.stmt_parse(stm, node, ilvl + 1, stms_expr[pos]):
                        continue
                    li = stm.coord.line - 1
                    l = tc[li]
                    s = len(l) - len(l.lstrip())
                    line = li + 1 + self.header_lines + (
                        1 if self.header_lines > 0 else 0)
                    # Handle conditional branches

                    ilvl_t = ilvl
                    if isinstance(node, If) and isinstance(last, If):
                        if last.iffalse and hasattr(
                                last.iffalse,
                                'iftrue') and stm1 == last.iffalse.iftrue:
                            ilvl_t -= 1
                        elif last.iffalse and hasattr(
                                last.iffalse,
                                'iffalse') and stm1 == last.iffalse.iffalse:
                            ilvl_t -= 1
                    if ilvl_t > self.get_config()['max_branches']:
                        BuErrors.print_error(self.path, self.file_name, line,
                                             self.get_check_level(),
                                             self.get_check_id(), self.message)
            except:
                pass
        return 1
Ejemplo n.º 7
0
 def curly_process(self, dt):
     if not re.search(r'for\s*\(((?!\s).+)\)', tc[dt.coord.line - 1]):
         return 0
     if re.search(r'for\s*\(((?!\s*\{).+)\)\s*{', tc[dt.coord.line - 1]):
         return 0
     if re.search(r'for\s*\(((?!\s*\{).+)\)\s*;', tc[dt.coord.line - 1]):
         return 0
     if not tc[dt.coord.line].strip().startswith('{'):
         return 0
     self.line = dt.coord.line + self.header_lines + (
         1 if self.header_lines != 0 else 0)
     BuErrors.print_error(self.path, self.file_name, self.line,
                          self.get_check_level(), self.get_check_id(),
                          self.message)
Ejemplo n.º 8
0
 def check_inner(self, file_content, file_contentf):
     lines = file_content.split('\n')
     i = 0
     last = -2
     for l in lines:
         i += 1
         if len(l.lstrip().strip()) == 0 or l == ' ' * len(l):
             if i == last + 1:
                 line = i
                 BuErrors.print_error(self.path, self.file_name, line,
                                      self.get_check_level(),
                                      self.get_check_id(), self.message)
             last = i
     return 0
 def check_visitor(self, visitor, lines):
     self.fill_error(visitor.function_count)
     if visitor.function_count <= self.get_config(
     )['max_functions_per_file']:
         return 0
     i = 0
     for func in visitor.function_defs:
         i += 1
         if i <= 5:
             continue
         line = func + self.header_lines + (1 if self.header_lines != 0 else
                                            0)
         BuErrors.print_error(self.path, self.file_name, line,
                              self.get_check_level(), self.get_check_id(),
                              self.message.format(visitor.function_count))
     return 0
Ejemplo n.º 10
0
 def check_function_decl(self, visitor, func):
     if func.body.block_items is None:
         return 0
     if tc is None:
         return 0
     ilvl = 1
     for b in func.body.block_items:
         li = b.coord.line - 1
         l = tc[li]
         s = len(l) - len(l.lstrip())
         line = li + 1 + self.header_lines + 1 if self.header_lines > 1 else 0
         if s != ilvl * self.get_config()['spaces_per_level'] and line not in flag_lines:
             flag_lines.append(line)
             BuErrors.print_error(self.path, self.file_name, line,
                                  self.get_check_level(), self.get_check_id(),
                                  self.message.format(str(ilvl * self.get_config()['spaces_per_level']), str(s)))
         self.stmt_parse(b, None, ilvl + 1, 'a')
     return 0
Ejemplo n.º 11
0
    def check_inner(self, file_content, file_contentf):
        global tc
        global flag_lines
        flag_lines = []
        lines = file_contentf.split('\n')
        lc = 0
        tc = lines

        for l in lines:
            lc += 1
            s = len(l) - len(l.lstrip())
            self.line = lc + self.header_lines
            self.line += 1 if self.header_lines > 0 else 0
            if s % 4 != 0:
                flag_lines.append(self.line)
                BuErrors.print_error(self.path, self.file_name, self.line, self.get_check_level(),
                                     self.get_check_id(), self.base_message)
        return 0
Ejemplo n.º 12
0
    def check_inner(self, file_content, file_contentf):
        lines = file_contentf.split('\n')
        i = 0
        index = 0
        new_ind = 0
        last_dc = 0

        for line in lines:
            i += 1
            new_ind = 0
            dc = 0

            if '{' in line:
                index += 1
                new_ind = 1
            elif re.match(r'[ \t]*}[ \t]*', line):
                index -= 1
                if index <= 0:
                    index = 0

            if index > 0 and not len(line) <= 0:
                spaces_diff = len(line) - len(line.lstrip())
                self.line = i + self.header_lines - 2
                if not new_ind:
                    for match in matches:
                        if len(re.findall(match, line)) > 0:
                            dc = 1
                if not last_dc:
                    tmp_indx = 4 * (index - new_ind)
                    if spaces_diff != tmp_indx:
                        print("spaces: {0} / {1}".format(
                            spaces_diff, tmp_indx))
                        BuErrors.print_error(self.file_name, self.line,
                                             self.get_check_level(),
                                             self.get_check_id(), self.message)
                    if index >= 4:
                        BuErrors.print_error(self.file_name, self.line, 1,
                                             "C1",
                                             "3 or more conditionnal blocks.")

            last_dc = dc
        return 0
Ejemplo n.º 13
0
 def check_ast(self, ast):
     for p in ast:
         if not isinstance(p, Decl) or not hasattr(p, 'quals'):
             continue
         if not hasattr(p, 'type') or 'const' in p.quals:
             continue
         btype = False
         for altype in allw:
             if isinstance(p.type, altype):
                 btype = True
         if not btype:
             continue
         if not hasattr(p, 'coord'):
             continue
         line = p.coord.line + self.header_lines
         line += 1 if self.header_lines > 0 else 0
         BuErrors.print_error(self.path, self.file_name, line,
                              self.get_check_level(), self.get_check_id(),
                              self.message)
     return 0
    def check_inner(self, file_content, file_contentf):
        global v
        last_func = ''
        i = 0
        index = 0
        line_start = -1
        lines = file_contentf.split('\n')

        for line in lines:
            i += 1
            if v is not None and i in v.function_defs:
                last_func = v.function_defs[i]

            started_newindent = 0
            if '{' in line:
                started_newindent = 1
                if index == 0:
                    line_start = i
                index += 1
                if i - 1 >= 0 and v is not None and i - 1 in v.function_defs:
                    last_func = v.function_defs[i - 1]
            elif re.match(r'[ \t]*}[ \t]*', line):
                started_newindent = 0
                index -= 1
                if index <= 0:
                    index = 0
                    if line_start > 0 and i - line_start - 2 > self.get_config(
                    )['max_lines_per_function']:
                        BuErrors.print_error(
                            self.path, self.file_name,
                            line_start + self.header_lines,
                            self.get_check_level(), self.get_check_id(),
                            self.get_config()['message'].format(
                                last_func, (i - line_start - 2)))
                    line_start = -1
                    last_func = ''
            else:
                started_newindent = 0
Ejemplo n.º 15
0
    def check_inner(self, file_content, file_contentf):
        lines_with_comments = file_content.split('\n')
        i = 0
        index = 0
        for line in lines_with_comments:
            i += 1
            base_line = line.replace("\t", "").lstrip()
            if index > 0:
                if base_line.startswith("//") or base_line.startswith("/*"):
                    self.fill_error(last_func)
                    BuErrors.print_error(
                        self.file_name, i, 1, "F6",
                        "Comments inside a func ('{0}')".format(last_func))
            if re.match(r'{[ \t]*', line):
                index += 1
                if i - 1 >= 0 and i - 1 in cache_visitor.function_defs:
                    last_func = cache_visitor.function_defs[i - 1]
            elif re.match(r'[ \t]*}[ \t]*', line):
                index -= 1
                if index <= 0:
                    index = 0
                    last_func = ''

        return 0
Ejemplo n.º 16
0
 def err(self, line, line_number, text):
     line_number += self.header_lines if line_number != -1 else 0
     BuErrors.print_error(self.file_name, line_number,
                          self.get_check_level(), self.get_check_id(), text)
Ejemplo n.º 17
0
    def run(self):
        self.delete_temp()
        tmp = self.full_path + '.tmp'

        for clazz in check_utils.get_filenames():
            try:
                clazz = clazz(file_name=self.file_name,
                              path=self.full_path,
                              header_lines=0)
                clazz.process_filename()
            except Exception as e:
                if error_handling.args.verbose:
                    traceback.print_exc()
                    print(e)
                print(run_err.format(self.full_path, clazz.__class__.__name__))

        if not self.is_validsource():
            return

        if not self.read_content():
            return

        header_lines = self.get_headerlines()
        lines_with_comments = self.file_content.split('\n')
        lines = ()
        parser = c_parser.CParser()

        file_contentf = string_utils.removeComments(self.file_content)
        lines = file_contentf.split('\n')
        header_lines = len(lines_with_comments) - len(lines)
        if header_lines < 0:
            header_lines = 0

        parsed = False
        try:
            f = open(tmp, "a")
            f.write(file_contentf.replace("bool ", "_Bool "))
            f.close()
            ast = parse_file(tmp, use_cpp=True, cpp_args=c_utils.includes)
            self.delete_temp()
            parsed = True
        except c_parser.ParseError as e:
            line = str(e).split(':')
            if not error_handling.args.ignore_compilation:
                BuErrors.print_error(self.full_path, self.file_name,
                                     int(line[1]) + header_lines, 2, "0?",
                                     "Unable to compile the file")
            self.delete_temp()
            if error_handling.args.verbose:
                print(e)

        self.delete_temp()
        if parsed:
            v = FunctionPrinter()
            v.reset_visit()
            v.visit(ast)

            for clazz in check_utils.get_ast():
                try:
                    clazz = clazz(file_name=self.file_name,
                                  path=self.full_path,
                                  header_lines=header_lines)
                    clazz.process_ast(ast)
                except Exception as e:
                    if error_handling.args.verbose:
                        traceback.print_exc()
                        print(e)
                    print(
                        run_err.format(self.full_path,
                                       clazz.__class__.__name__))

            for clazz in check_utils.get_pre_visitor():
                try:
                    clazz = clazz(file_name=self.file_name,
                                  path=self.full_path,
                                  header_lines=header_lines)
                    clazz.process_visitor_check(v, lines)
                except Exception as e:
                    if error_handling.args.verbose:
                        traceback.print_exc()
                        print(e)
                    print(
                        run_err.format(self.full_path,
                                       clazz.__class__.__name__))

        line_index = 0
        for line in lines:
            line_index += 1
            for clazz in check_utils.get_line():
                try:
                    clazz = clazz(file_name=self.file_name,
                                  path=self.full_path,
                                  header_lines=header_lines)
                    clazz.process_line(line, line_index)
                except Exception as e:
                    if error_handling.args.verbose:
                        traceback.print_exc()
                        print(e)
                    print(
                        run_err.format(self.full_path,
                                       clazz.__class__.__name__))

        for clazz in check_utils.get_inner():
            try:
                clazz = clazz(file_name=self.file_name,
                              path=self.full_path,
                              header_lines=header_lines)
                clazz.process_inner(self.file_content, file_contentf)
            except Exception as e:
                if error_handling.args.verbose:
                    traceback.print_exc()
                    print(e)
                print(run_err.format(self.full_path, clazz.__class__.__name__))

        v = None
        if parsed:
            v = FunctionPrinter()
            v.reset_visit()
            v.visit(ast)

            for clazz in check_utils.get_visitor():
                try:
                    clazz = clazz(file_name=self.file_name,
                                  path=self.full_path,
                                  header_lines=header_lines)
                    clazz.process_visitor_check(v, lines)
                except Exception as e:
                    if error_handling.args.verbose:
                        traceback.print_exc()
                        print(e)
                    print(
                        run_err.format(self.full_path,
                                       clazz.__class__.__name__))

            for func in v.func:
                for clazz in check_utils.get_func_decl():
                    try:
                        clazz = clazz(file_name=self.file_name,
                                      path=self.full_path,
                                      header_lines=header_lines)
                        clazz.process_function_decl(v, func)
                    except Exception as e:
                        if error_handling.args.verbose:
                            traceback.print_exc()
                            print(e)
                        print(
                            run_err.format(self.full_path,
                                           clazz.__class__.__name__))
                if func.body.block_items is not None:
                    for var in func.body.block_items:
                        for clazz in check_utils.get_func_call():
                            try:
                                clazz = clazz(file_name=self.file_name,
                                              path=self.full_path,
                                              header_lines=header_lines)
                                clazz.process_function_call(var)
                            except Exception as e:
                                if error_handling.args.verbose:
                                    traceback.print_exc()
                                    print(e)
                                print(
                                    run_err.format(self.full_path,
                                                   clazz.__class__.__name__))
                        for clazz in check_utils.get_var_decl():
                            try:
                                clazz = clazz(file_name=self.file_name,
                                              path=self.full_path,
                                              header_lines=header_lines)
                                clazz.process_variable_decl(var)
                            except Exception as e:
                                if error_handling.args.verbose:
                                    traceback.print_exc()
                                    print(e)
                                print(
                                    run_err.format(self.full_path,
                                                   clazz.__class__.__name__))