示例#1
0
    def value(self, filename: str):
        """
        Travers over AST tree and fins function with nested/sequential try statement
        :param filename:
        :return:
        List of tuples with LineNumber and List of methods names, e.g.
        [[10, 'func1'], [10, 'fun2']], [[23, 'run'], [23, 'start']]]
        """

        tree = AST(filename).value()
        res = defaultdict(list)
        for _, method_node in tree.filter(javalang.tree.MethodDeclaration):
            for _, try_node in method_node.filter(javalang.tree.TryStatement):
                formal_params = [(x.type.name + ' ' + x.name)
                                 for x in method_node.parameters
                                 if isinstance(x, FormalParameter)]
                func_name = '{f}({params})'.format(
                    f=method_node.name,
                    params=','.join(formal_params)).encode('utf-8')
                m = hashlib.md5()
                m.update(func_name)
                res[m.hexdigest()].append(method_node.position.line)

        return list(
            set(
                itertools.chain.from_iterable(
                    [y for x, y in res.items() if len(y) > 1])))
示例#2
0
 def value(self, filename: str):
     """
     Iterates over functions and finds super.func() calls.
     Javalang doesn't have code line for super.func() call,
     that's why we can only count the first match of a call inside some function.
     It has MULTIPLE MATCHES if we call super.func() inside a ANONYMOUS CLASS.
     :param filename:
     :return: Lines of code
     """
     results = []
     tree = AST(filename).value()
     with open(filename, encoding='utf-8') as file:
         text_lines = file.readlines()
     for _, method_decl_node in tree.filter(
             javalang.tree.MethodDeclaration):
         code_line = method_decl_node.position.line
         for _, super_method_inv in method_decl_node.filter(
                 javalang.tree.SuperMethodInvocation):
             str_to_find = 'super.{method_name}('.format(
                 method_name=super_method_inv.member).strip()
             for iter, line in enumerate(text_lines[code_line - 1:]):
                 string_strip = line.strip().replace('\n',
                                                     '').replace('\t', '')
                 if string_strip.find(str_to_find) > -1:
                     results.append(code_line + iter)
                     break
     return results
示例#3
0
    def value(self, filename: str) -> List[int]:
        lst: List[int] = []
        tree = AST(filename).value()

        invocation_tree = tree.filter(javalang.tree.Invocation)
        arg_list = [x for _, x in invocation_tree]

        for argument in arg_list:
            ternary_list = argument.filter(javalang.tree.TernaryExpression)
            for path, expr in ternary_list:
                if isinstance(expr.if_false, javalang.tree.Literal
                              ) and expr.if_false.value == 'null':
                    lst.append(argument._position.line)
                if isinstance(expr.if_true, javalang.tree.Literal
                              ) and expr.if_true.value == 'null':
                    lst.append(argument._position.line)

        for path, node in tree:
            try:
                for argument in node.arguments:
                    if isinstance(argument, javalang.tree.Literal) and argument.value == "null" and \
                            argument._position.line not in lst:
                        lst.append(argument._position.line)
            except (AttributeError, TypeError):
                pass
        lst = sorted(lst)
        return lst
示例#4
0
 def value(self, filename: str) -> List[LineNumber]:
     tree = AST(filename).value()
     classes = tree.filter(ClassDeclaration)
     return [
         node.position.line for _, node in classes
         if len([v for v in ['final', 'abstract']
                 if v in node.modifiers]) == 0
     ]
示例#5
0
    def value(self, filename: str):
        tree = AST(filename).value()

        traversed = []
        for _, class_body in tree.filter(ClassDeclaration):
            for each_object in class_body.body:
                if isinstance(each_object, MethodDeclaration):
                    traversed.append(self.diameter(each_object))

        return max(traversed) if len(traversed) != 0 else traversed
示例#6
0
    def value(self, filename: str) -> int:

        tree = AST(filename).value()
        traversed = []
        for _, class_body in tree.filter(javalang.tree.ClassDeclaration):
            for each_object in class_body.body:
                if isinstance(each_object, javalang.tree.MethodDeclaration):
                    traversed.append(self.countLeaves(each_object.body))

        return sum(traversed)
示例#7
0
 def value(self, filename: str):
     '''main function'''
     tree = AST(filename).value()
     num_str = []
     for path, node in tree.filter(javalang.tree.ConstructorDeclaration):
         number = node.position.line
         stats = node.children[-1]
         result, _, _ = self.__work_with_stats(stats, 0, 0)
         if result == 1:
             num_str.append(number)
     return sorted(list(set(num_str)))
示例#8
0
    def value(self, filename: str) -> int:

        tree = AST(filename).value()
        for _, class_body in tree.filter(javalang.tree.ClassDeclaration):
            for each_object in class_body.body:
                if isinstance(each_object, MethodDeclaration):

                    # memorize the name for detecting recursion call
                    self.method_name = each_object.name
                    self._get_complexity(each_object, 0)

        final_value, self.complexity = self.complexity, 0
        return final_value
 def value(self, filename):
     tree = AST(filename).value().filter(javalang.tree.MethodDeclaration)
     ret = []
     for path, node in tree:
         if len(node.parameters) > 0:
             if any(len(parameter.type.dimensions) > 0 for parameter in node.parameters):
                 ret += [node.position.line]
     return ret
示例#10
0
 def value(self, filename: str):
     classes = ('manager', 'controller', 'router', 'dispatcher', 'printer',
                'writer', 'reader', 'parser', 'generator', 'renderer',
                'listener', 'producer', 'holder', 'interceptor')
     tree = AST(filename).value().filter(javalang.tree.ClassDeclaration)
     return [
         node._position.line for _, node in tree
         if [n for n in classes if n in node.name.lower()] != []
     ]
示例#11
0
 def value(self, filename):
     tree = AST(filename).value()
     total_code_lines = set()
     for _, method_node in tree.filter(javalang.tree.MethodDeclaration):
         for _, try_node in method_node.filter(javalang.tree.TryStatement):
             for _, throw_node in try_node.filter(
                     javalang.tree.ThrowStatement):
                 if try_node.catches:
                     catch_classes = [
                         x.parameter.name for x in try_node.catches
                     ]
                     mem_ref = throw_node.children[1]
                     if isinstance(mem_ref, javalang.tree.ClassCreator):
                         continue
                     else:
                         if hasattr(mem_ref, 'member'
                                    ) and mem_ref.member in catch_classes:
                             total_code_lines.add(mem_ref.position.line)
     return sorted(total_code_lines)
示例#12
0
class Lines:
    """
    Return the lines for some AST
    """
    def __init__(self, filename: str):
        self._filename = filename
        self._ast = AST(filename)

    def value(self) -> Tuple[Node, List[str]]:
        with open(self._filename, encoding='utf-8') as file:
            lines = file.readlines()

        return self._ast.value(), lines
示例#13
0
    def value(self, filename: str):
        """
        Travers over AST tree and finds pattern
        :param filename:
        """
        tree = AST(filename).value()
        chain_lst = defaultdict(int)
        for _, method_node in tree.filter(javalang.tree.MethodDeclaration):
            for _, return_node in method_node.filter(
                    javalang.tree.ReturnStatement):
                return_literal = return_node.children[1]
                if isinstance(return_literal, javalang.tree.Literal
                              ) and return_literal.value == 'null':
                    chain_lst[
                        method_node.
                        name] = return_literal.position.line or return_node.position.line
                elif isinstance(return_literal,
                                javalang.tree.TernaryExpression):
                    chain_lst[method_node.name] = return_node.position.line

        filtered_dict = list(filter(lambda elem: elem > 0, chain_lst.values()))
        return filtered_dict
示例#14
0
    def value(self, filename: str):
        """
        Travers over AST tree finds method chaining. It is searched in a statement
        :param filename:
        :return:
        List of tuples with LineNumber and List of methods names, e.g.
        [[10, 'func1'], [10, 'fun2']], [[23, 'run'], [23, 'start']]]
        """
        tree = AST(filename).value()
        chain_lst = defaultdict(list)
        for path, node in tree.filter(javalang.tree.StatementExpression):
            if isinstance(node.expression, javalang.tree.MethodInvocation):
                children = node.children
                if isinstance(children[1], javalang.tree.MethodInvocation):
                    uuid_first_method = str(uuid.uuid1())
                    chain_lst[uuid_first_method].append(
                        [children[1].position.line, children[1].member])
                    self.traverse_node(children[1], chain_lst,
                                       uuid_first_method)

        filtered_dict = list(
            filter(lambda elem: len(elem) > 1, chain_lst.values()))
        return [item[0][0] for item in filtered_dict]
示例#15
0
    def value(self, filename: str):
        """
        Travers over AST tree and finds function with sequential while statement
        :param filename:
        :return:
        List of LineNumber of methods which have sequential while statements
        """

        res = []
        for _, method_node in AST(filename).value().filter(
                javalang.tree.MethodDeclaration):
            if len(list(method_node.filter(javalang.tree.WhileStatement))) > 1:
                res.append(method_node.position.line)

        return res
示例#16
0
文件: lcom4.py 项目: dz-s/aibolit
    def value(self, filename: str) -> int:
        tree: Node = AST(filename).value()
        graph: Dict[str, Set[str]] = defaultdict(set)

        fields: List[str] = [
            node.declarators[0].name
            for _, node in tree.filter(FieldDeclaration)
        ]
        methods: List[str] = [
            node.name for _, node in tree.filter(MethodDeclaration)
        ]
        interfaces: List[InterfaceDeclaration] = [
            node for _, node in tree.filter(InterfaceDeclaration)
        ]
        current_class: ClassDeclaration = list(
            tree.filter(ClassDeclaration))[0][1]
        interfaces_methods: Set[str] = set()
        nested_methods: Set[str] = set()

        class_decl: List[ClassDeclaration] = \
            [node for _, node in current_class.filter(ClassDeclaration) if node.name != current_class.name]

        for i in interfaces:
            interfaces_methods.update(
                [node.name for _, node in i.filter(MethodDeclaration)])
        for k in class_decl:
            nested_methods.update(
                [node.name for _, node in k.filter(MethodDeclaration)])

        for _, node in tree.filter(MethodDeclaration):
            for _, mem_ref in node.filter(MemberReference):
                if mem_ref.member in fields:
                    graph[node.name].add(mem_ref.member)

            for _, this_m in node.filter(This):
                graph[node.name].add(this_m.selectors[0].member)

            for _, mi in node.filter(MethodInvocation):
                if mi.member in methods:
                    graph[node.name].add(mi.member)

        return self.get_connected_components(methods, fields, graph)
示例#17
0
    def value(self, filename: str) -> List[int]:
        '''Return line numbers in the file where patterns are found'''
        tree = AST(filename).value()
        for_links: List[Node] = []
        self.__for_node_depth(tree,
                              max_depth=self.max_depth,
                              for_links=for_links)

        def find_line_position(node: Node) -> Optional[int]:
            if hasattr(node, '_position'):
                return node._position.line
            else:
                return None

        n_lines: List[List[int]] = [
            self.__fold_traverse_tree(for_node, find_line_position)
            for for_node in for_links
        ]
        n_lines = [v for v in n_lines if len(v) > 0]

        return list(map(min, n_lines))  # type: ignore
示例#18
0
 def value(self, filename: str) -> List[LineNumber]:
     lst: List[LineNumber] = []
     tree = AST(filename).value().filter(javalang.tree.MethodDeclaration)
     for path, node in tree:
         if (node.return_type is None) and ('set' in node.name[:3]):
             if (isinstance(node.body, list)) and len(node.body) < 2:
                 for statement in node.body:
                     if isinstance(statement, javalang.tree.StatementExpression):
                         if isinstance(statement.expression, javalang.tree.Assignment):
                             expression = statement.expression.expressionl
                             if isinstance(expression, javalang.tree.This):
                                 if statement.expression.type == '=':
                                     if expression.selectors[0].member.lower() == node.name.lower()[3:]:
                                         lst.append(node._position.line)
                                 else:
                                     break
                             else:
                                 break
                         else:
                             break
     return lst
示例#19
0
 def test_wrong_file(self):
     self.assertRaises(TypeError,
                       AST(Path(self.dir_path, 'test_ast.py')).value)
示例#20
0
 def value(self, filename: str):
     tree = AST(filename).value().filter(javalang.tree.ClassDeclaration)
     return [node._position.line for _, node in tree if node.implements and (len(node.implements) > 1)]
示例#21
0
    def value(self, filename: str):
        tree = AST(filename).value()

        return self.__traverse_node(tree)
 def value(self, filename: str):
     tree = AST(filename).value().filter(javalang.tree.MethodDeclaration)
     return [
         node.position.line for path, node in tree
         if all(elem in node.modifiers for elem in ['public', 'static'])
     ]
示例#23
0
    def value(filename: str) -> int:
        tree = AST(filename).value()
        metric = MDAMetric.get_depth(tree)

        return metric
 def value(self, filename: str):
     return [
         node.position.line for _, node in AST(filename).value().filter(
             javalang.tree.MethodDeclaration)
         if all(elem in node.modifiers for elem in ['private', 'static'])
     ]
示例#25
0
 def __init__(self, filename: str):
     self._filename = filename
     self._ast = AST(filename)
示例#26
0
    def value(self, filename: str) -> List[LineNumber]:
        tree: CompilationUnit = AST(filename).value()

        return self.__traverse_node(tree)
示例#27
0
    def value(self, filename: str):

        tree = AST(filename).value()
        G = self.coh.value(tree)
        return nx.number_connected_components(G)