Beispiel #1
0
class RenamePackageRefactoringListener(JavaParserLabeledListener):
    def __init__(self,
                 common_token_stream: CommonTokenStream = None,
                 package_identifier: str = None,
                 package_new_name: str = None,
                 packages_name: list = []):
        """
        :param common_token_stream:
        """
        self.token_stream = common_token_stream
        self.package_identifier = package_identifier
        self.package_new_name = package_new_name
        self.packages_name = packages_name
        self.is_in_scope = False
        # Move all the tokens in the source code in a buffer, token_stream_rewriter.
        if common_token_stream is not None:
            self.token_stream_rewriter = TokenStreamRewriter(
                common_token_stream)
        else:
            raise TypeError('common_token_stream is None')

    def enterPackageDeclaration(
            self, ctx: JavaParserLabeled.PackageDeclarationContext):
        if self.package_identifier == ctx.qualifiedName().IDENTIFIER(
        )[-1].getText():
            if self.package_new_name not in self.packages_name:
                self.token_stream_rewriter.replaceIndex(
                    index=ctx.qualifiedName().start.tokenIndex +
                    (2 * len(ctx.qualifiedName().IDENTIFIER()) - 2),
                    text=self.package_new_name)
                print("package changed")
Beispiel #2
0
class RenamePackageRefactoringListener(JavaParserLabeledListener):
    """
        The class implements Rename Package refactoring.
    """
    def __init__(self,
                 common_token_stream: CommonTokenStream = None,
                 package_identifier: str = None,
                 package_new_name: str = None,
                 packages_name: list = []):
        """
         Args:

             common_token_stream (CommonTokenStream): An instance of ANTLR4 CommonTokenStream class

             package_identifier(str): Name of the package in which the refactoring has to be done

             package_new_name(str): The new name of the refactored method

             packages_name(str): Name of the packages in which the refactoring has to be done

        Returns:

            RenamePackageRefactoringListener: An instance of RenamePackageRefactoringListener class

        """

        self.token_stream = common_token_stream
        self.package_identifier = package_identifier
        self.package_new_name = package_new_name
        self.packages_name = packages_name
        self.is_in_scope = False
        # Move all the tokens in the source code in a buffer, token_stream_rewriter.
        if common_token_stream is not None:
            self.token_stream_rewriter = TokenStreamRewriter(
                common_token_stream)
        else:
            raise TypeError('common_token_stream is None')

    def enterPackageDeclaration(
            self, ctx: JavaParserLabeled.PackageDeclarationContext):
        if self.package_identifier == ctx.qualifiedName().IDENTIFIER(
        )[-1].getText():
            if self.package_new_name not in self.packages_name:
                self.token_stream_rewriter.replaceIndex(
                    index=ctx.qualifiedName().start.tokenIndex +
                    (2 * len(ctx.qualifiedName().IDENTIFIER()) - 2),
                    text=self.package_new_name)
                print("package changed")

    def enterImportDeclaration(
            self, ctx: JavaParserLabeled.ImportDeclarationContext):
        if ctx.qualifiedName().IDENTIFIER()[-1].getText(
        ) == self.package_identifier:
            if self.package_new_name not in self.packages_name:
                self.token_stream_rewriter.replaceIndex(
                    index=ctx.qualifiedName().start.tokenIndex +
                    (2 * len(ctx.qualifiedName().IDENTIFIER()) - 2),
                    text=self.package_new_name)
                print("package name in import changed")
    def testReplaceMiddleIndex(self):
        input = InputStream('abc')
        lexer = TestLexer(input)
        stream = CommonTokenStream(lexer=lexer)
        stream.fill()
        rewriter = TokenStreamRewriter(tokens=stream)

        rewriter.replaceIndex(1, 'x')

        self.assertEquals(rewriter.getDefaultText(), 'axc')
    def testReplaceMiddleIndex(self):
        input = InputStream('abc')
        lexer = TestLexer(input)
        stream = CommonTokenStream(lexer=lexer)
        stream.fill()
        rewriter = TokenStreamRewriter(tokens=stream)

        rewriter.replaceIndex(1, 'x')

        self.assertEqual(rewriter.getDefaultText(), 'axc')
    def testReplaceSingleMiddleThenOverlappingSuperset(self):
        input = InputStream('abcba')
        lexer = TestLexer(input)
        stream = CommonTokenStream(lexer=lexer)
        stream.fill()
        rewriter = TokenStreamRewriter(tokens=stream)

        rewriter.replaceIndex(2, 'xyz')
        rewriter.replaceRange(0, 3, 'foo')

        self.assertEqual('fooa', rewriter.getDefaultText())
    def testInsertThenReplaceSameIndex(self):
        input = InputStream('abc')
        lexer = TestLexer(input)
        stream = CommonTokenStream(lexer=lexer)
        stream.fill()
        rewriter = TokenStreamRewriter(tokens=stream)

        rewriter.insertBeforeIndex(0, '0')
        rewriter.replaceIndex(0, 'x')

        self.assertEquals('0xbc', rewriter.getDefaultText())
    def testReplaceThenInsertAfterLastIndex(self):
        input = InputStream('abc')
        lexer = TestLexer(input)
        stream = CommonTokenStream(lexer=lexer)
        stream.fill()
        rewriter = TokenStreamRewriter(tokens=stream)

        rewriter.replaceIndex(2, 'x')
        rewriter.insertAfter(2, 'y')

        self.assertEquals('abxy', rewriter.getDefaultText())
    def testReplaceSingleMiddleThenOverlappingSuperset(self):
        input = InputStream('abcba')
        lexer = TestLexer(input)
        stream = CommonTokenStream(lexer=lexer)
        stream.fill()
        rewriter = TokenStreamRewriter(tokens=stream)

        rewriter.replaceIndex(2, 'xyz')
        rewriter.replaceRange(0, 3, 'foo')

        self.assertEquals('fooa', rewriter.getDefaultText())
    def testInsertThenReplaceSameIndex(self):
        input = InputStream('abc')
        lexer = TestLexer(input)
        stream = CommonTokenStream(lexer=lexer)
        stream.fill()
        rewriter = TokenStreamRewriter(tokens=stream)

        rewriter.insertBeforeIndex(0, '0')
        rewriter.replaceIndex(0, 'x')

        self.assertEqual('0xbc', rewriter.getDefaultText())
Beispiel #10
0
    def testReplaceThenInsertAfterLastIndex(self):
        input = InputStream('abc')
        lexer = TestLexer(input)
        stream = CommonTokenStream(lexer=lexer)
        stream.fill()
        rewriter = TokenStreamRewriter(tokens=stream)

        rewriter.replaceIndex(2, 'x')
        rewriter.insertAfter(2, 'y')

        self.assertEqual('abxy', rewriter.getDefaultText())
Beispiel #11
0
    def test2ReplaceMiddleIndex1InsertBefore(self):
        input = InputStream('abc')
        lexer = TestLexer(input)
        stream = CommonTokenStream(lexer=lexer)
        stream.fill()
        rewriter = TokenStreamRewriter(tokens=stream)

        rewriter.insertBeforeIndex(0, "_")
        rewriter.replaceIndex(1, 'x')
        rewriter.replaceIndex(1, 'y')

        self.assertEqual('_ayc', rewriter.getDefaultText())
    def test2ReplaceMiddleIndex1InsertBefore(self):
        input = InputStream('abc')
        lexer = TestLexer(input)
        stream = CommonTokenStream(lexer=lexer)
        stream.fill()
        rewriter = TokenStreamRewriter(tokens=stream)

        rewriter.insertBeforeIndex(0, "_")
        rewriter.replaceIndex(1, 'x')
        rewriter.replaceIndex(1, 'y')

        self.assertEquals('_ayc', rewriter.getDefaultText())
Beispiel #13
0
class RenameMethodRefactoringListener(JavaParserLabeledListener):
    def __init__(self,
                 common_token_stream: CommonTokenStream = None,
                 scope_class_name: str = None,
                 method_identifier: str = None,
                 method_new_name: str = None):
        """
        :param common_token_stream:
        """
        self.token_stream = common_token_stream
        self.scope_class_name = scope_class_name
        self.method_identifier = method_identifier
        self.method_new_name = method_new_name

        self.is_in_scope = False
        # Move all the tokens in the source code in a buffer, token_stream_rewriter.
        if common_token_stream is not None:
            self.token_stream_rewriter = TokenStreamRewriter(
                common_token_stream)
        else:
            raise TypeError('common_token_stream is None')

    def enterClassDeclaration(self,
                              ctx: JavaParserLabeled.ClassDeclarationContext):

        if ctx.IDENTIFIER().getText() == self.scope_class_name:
            self.is_in_scope = True
        print("class scope detected")

    def exitClassDeclaration(self,
                             ctx: JavaParserLabeled.ClassDeclarationContext):
        if ctx.IDENTIFIER().getText() == self.scope_class_name:
            self.is_in_scope = False
        print("class scope exited")

    def enterMethodDeclaration(
            self, ctx: JavaParserLabeled.MethodDeclarationContext):
        if self.is_in_scope:
            if ctx.IDENTIFIER().getText() == self.method_identifier:
                self.token_stream_rewriter.replaceIndex(
                    index=ctx.start.tokenIndex + 2, text=self.method_new_name)
                print("method name changed !")

    def enterMethodCall0(self, ctx: JavaParserLabeled.MethodCall0Context):
        if self.is_in_scope:
            if ctx.IDENTIFIER().getText() == self.method_identifier:
                self.token_stream_rewriter.replaceIndex(
                    index=ctx.start.tokenIndex, text=self.method_new_name)
                print("method call name changed !")
Beispiel #14
0
class InlineClassRefactoringListener(JavaParserLabeledListener):
    """

    To implement inline class refactoring based on its actors.

    Creates a new class and move fields and methods from two old class to the new one, then delete the two class

    """

    def __init__(
            self, common_token_stream: CommonTokenStream = None,
            source_class: str = None, source_class_data: dict = None,
            target_class: str = None, target_class_data: dict = None, is_complete: bool = False):
        """


        """

        if common_token_stream is None:
            raise ValueError('common_token_stream is None')
        else:
            self.token_stream_rewriter = TokenStreamRewriter(common_token_stream)

        if source_class is None:
            raise ValueError("source_class is None")
        else:
            self.source_class = source_class
        if target_class is None:
            raise ValueError("new_class is None")
        else:
            self.target_class = target_class
        if target_class:
            self.target_class = target_class
        if source_class_data:
            self.source_class_data = source_class_data
        else:
            self.source_class_data = {'fields': [], 'methods': [], 'constructors': []}
        if target_class_data:
            self.target_class_data = target_class_data
        else:
            self.target_class_data = {'fields': [], 'methods': [], 'constructors': []}

        self.field_that_has_source = []
        self.has_source_new = False

        self.is_complete = is_complete
        self.is_target_class = False
        self.is_source_class = False
        self.detected_field = None
        self.detected_method = None
        self.TAB = "\t"
        self.NEW_LINE = "\n"
        self.code = ""

    def enterClassDeclaration(self, ctx: JavaParserLabeled.ClassDeclarationContext):
        class_identifier = ctx.IDENTIFIER().getText()
        if class_identifier == self.source_class:
            self.is_source_class = True
            self.is_target_class = False
        elif class_identifier == self.target_class:
            self.is_target_class = True
            self.is_source_class = False
        else:
            self.is_target_class = False
            self.is_source_class = False

    def exitClassDeclaration(self, ctx: JavaParserLabeled.ClassDeclarationContext):
        if self.is_target_class and (self.source_class_data['fields'] or
                                     self.source_class_data['constructors'] or
                                     self.source_class_data['methods']):
            if not self.is_complete:
                final_fields = merge_fields(self.source_class_data['fields'], self.target_class_data['fields'],
                                            self.target_class)
                final_constructors = merge_constructors(self.source_class_data['constructors'],
                                                        self.target_class_data['constructors'])
                final_methods = merge_methods(self.source_class_data['methods'], self.target_class_data['methods'])
                text = '\t'
                for field in final_fields:
                    text += field.text + '\n'
                for constructor in final_constructors:
                    text += constructor.text + '\n'
                for method in final_methods:
                    text += method.text + '\n'
                self.token_stream_rewriter.insertBeforeIndex(
                    index=ctx.stop.tokenIndex,
                    text=text
                )
                self.is_complete = True
            else:
                self.is_target_class = False
        elif self.is_source_class:
            if ctx.parentCtx.classOrInterfaceModifier(0) is None:
                return
            self.is_source_class = False
            self.token_stream_rewriter.delete(
                program_name=self.token_stream_rewriter.DEFAULT_PROGRAM_NAME,
                from_idx=ctx.parentCtx.classOrInterfaceModifier(0).start.tokenIndex,
                to_idx=ctx.stop.tokenIndex
            )

    def enterClassBody(self, ctx: JavaParserLabeled.ClassBodyContext):
        if self.is_source_class:
            self.code += self.token_stream_rewriter.getText(
                program_name=self.token_stream_rewriter.DEFAULT_PROGRAM_NAME,
                start=ctx.start.tokenIndex + 1,
                stop=ctx.stop.tokenIndex - 1
            )
            self.token_stream_rewriter.delete(
                program_name=self.token_stream_rewriter.DEFAULT_PROGRAM_NAME,
                from_idx=ctx.parentCtx.start.tokenIndex,
                to_idx=ctx.parentCtx.stop.tokenIndex
            )
        else:
            return None

    def enterFieldDeclaration(self, ctx: JavaParserLabeled.FieldDeclarationContext):
        if self.is_source_class or self.is_target_class:
            field_text = ''
            for child in ctx.children:
                if child.getText() == ';':
                    field_text = field_text[:len(field_text) - 1] + ';'
                    break
                field_text += child.getText() + ' '

            name = ctx.variableDeclarators().variableDeclarator(0).variableDeclaratorId().IDENTIFIER().getText()

            if ctx.typeType().classOrInterfaceType() is not None and \
                    ctx.typeType().classOrInterfaceType().getText() == self.source_class:
                self.field_that_has_source.append(name)
                return

            modifier_text = ''
            for modifier in ctx.parentCtx.parentCtx.modifier():
                modifier_text += modifier.getText() + ' '
            field_text = modifier_text + field_text
            if self.is_source_class:
                self.source_class_data['fields'].append(Field(name=name, text=field_text))
            else:
                self.target_class_data['fields'].append(Field(name=name, text=field_text))

    def exitFieldDeclaration(self, ctx: JavaParserLabeled.FieldDeclarationContext):
        if self.is_target_class:
            if ctx.typeType().classOrInterfaceType().getText() == self.source_class:
                grand_parent_ctx = ctx.parentCtx.parentCtx
                self.token_stream_rewriter.delete(
                    program_name=self.token_stream_rewriter.DEFAULT_PROGRAM_NAME,
                    from_idx=grand_parent_ctx.start.tokenIndex,
                    to_idx=grand_parent_ctx.stop.tokenIndex)

    def enterConstructorDeclaration(self, ctx: JavaParserLabeled.ConstructorDeclarationContext):
        if self.is_source_class or self.is_target_class:
            if ctx.formalParameters().formalParameterList():
                constructor_parameters = [ctx.formalParameters().formalParameterList().children[i] for i in
                                          range(len(ctx.formalParameters().formalParameterList().children)) if
                                          i % 2 == 0]
            else:
                constructor_parameters = []
            constructor_text = ''
            for modifier in ctx.parentCtx.parentCtx.modifier():
                constructor_text += modifier.getText() + ' '

            if self.is_source_class:
                constructor_text += self.target_class
            else:
                constructor_text += ctx.IDENTIFIER().getText()
            constructor_text += ' ( '
            for parameter in constructor_parameters:
                constructor_text += parameter.typeType().getText() + ' '
                constructor_text += parameter.variableDeclaratorId().getText() + ', '
            if constructor_parameters:
                constructor_text = constructor_text[:len(constructor_text) - 2]
            constructor_text += ')\n\t{'
            constructor_text += self.token_stream_rewriter.getText(
                program_name=self.token_stream_rewriter.DEFAULT_PROGRAM_NAME,
                start=ctx.block().start.tokenIndex + 1,
                stop=ctx.block().stop.tokenIndex - 1
            )
            constructor_text += '}\n'
            if self.is_source_class:
                self.source_class_data['constructors'].append(ConstructorOrMethod(
                    name=self.target_class, parameters=[Parameter(parameter_type=p.typeType().getText(),
                                                                  name=p.variableDeclaratorId().IDENTIFIER().getText())
                                                        for p in constructor_parameters],
                    text=constructor_text, constructor_body=self.token_stream_rewriter.getText(
                        program_name=self.token_stream_rewriter.DEFAULT_PROGRAM_NAME,
                        start=ctx.block().start.tokenIndex + 1,
                        stop=ctx.block().stop.tokenIndex - 1
                    )))
            else:
                self.target_class_data['constructors'].append(ConstructorOrMethod(
                    name=self.target_class, parameters=[Parameter(parameter_type=p.typeType().getText(),
                                                                  name=p.variableDeclaratorId().IDENTIFIER().getText())
                                                        for p in constructor_parameters],
                    text=constructor_text, constructor_body=self.token_stream_rewriter.getText(
                        program_name=self.token_stream_rewriter.DEFAULT_PROGRAM_NAME,
                        start=ctx.block().start.tokenIndex + 1,
                        stop=ctx.block().stop.tokenIndex - 1
                    )))
                proper_constructor = get_proper_constructor(self.target_class_data['constructors'][-1],
                                                            self.source_class_data['constructors'])

                if proper_constructor is None:
                    return

                self.token_stream_rewriter.insertBeforeIndex(
                    index=ctx.stop.tokenIndex,
                    text=proper_constructor.constructorBody
                )

    def enterMethodDeclaration(self, ctx: JavaParserLabeled.MethodDeclarationContext):
        if self.is_source_class or self.is_target_class:
            if ctx.formalParameters().formalParameterList():
                method_parameters = [ctx.formalParameters().formalParameterList().children[i] for i in
                                     range(len(ctx.formalParameters().formalParameterList().children)) if i % 2 == 0]
            else:
                method_parameters = []
            method_text = ''
            for modifier in ctx.parentCtx.parentCtx.modifier():
                method_text += modifier.getText() + ' '

            type_text = ctx.typeTypeOrVoid().getText()

            if type_text == self.source_class:
                type_text = self.target_class

                if self.is_target_class:
                    self.token_stream_rewriter.replace(
                        program_name=self.token_stream_rewriter.DEFAULT_PROGRAM_NAME,
                        from_idx=ctx.typeTypeOrVoid().start.tokenIndex,
                        to_idx=ctx.typeTypeOrVoid().stop.tokenIndex,
                        text=type_text
                    )
            method_text += type_text + ' ' + ctx.IDENTIFIER().getText()
            method_text += ' ( '
            for parameter in method_parameters:
                method_text += parameter.typeType().getText() + ' '
                method_text += parameter.variableDeclaratorId().getText() + ', '
            if method_parameters:
                method_text = method_text[:len(method_text) - 2]
            method_text += ')\n\t{'
            method_text += self.token_stream_rewriter.getText(
                program_name=self.token_stream_rewriter.DEFAULT_PROGRAM_NAME,
                start=ctx.methodBody().start.tokenIndex + 1,
                stop=ctx.methodBody().stop.tokenIndex - 1
            )
            method_text += '}\n'
            if self.is_source_class:
                self.source_class_data['methods'].append(ConstructorOrMethod(
                    name=ctx.IDENTIFIER().getText(),
                    parameters=[Parameter(
                        parameter_type=p.typeType().getText(),
                        name=p.variableDeclaratorId().IDENTIFIER().getText())
                        for p in
                        method_parameters],
                    text=method_text))
            else:
                self.target_class_data['methods'].append(ConstructorOrMethod(
                    name=ctx.IDENTIFIER().getText(),
                    parameters=[Parameter(
                        parameter_type=p.typeType().getText(),
                        name=p.variableDeclaratorId().IDENTIFIER().getText())
                        for p in
                        method_parameters],
                    text=method_text))

    def enterExpression1(self, ctx: JavaParserLabeled.Expression1Context):
        if ctx.IDENTIFIER() is None and ctx.IDENTIFIER().getText() in self.field_that_has_source:
            field_text = ctx.expression().getText()
            self.token_stream_rewriter.replace(
                program_name=self.token_stream_rewriter.DEFAULT_PROGRAM_NAME,
                from_idx=ctx.start.tokenIndex,
                to_idx=ctx.stop.tokenIndex,
                text=field_text
            )

    def exitExpression21(self, ctx: JavaParserLabeled.Expression21Context):
        if self.has_source_new:
            self.has_source_new = False
            self.token_stream_rewriter.delete(
                program_name=self.token_stream_rewriter.DEFAULT_PROGRAM_NAME,
                from_idx=ctx.start.tokenIndex,
                to_idx=ctx.stop.tokenIndex + 1
            )

    def enterExpression4(self, ctx: JavaParserLabeled.Expression4Context):
        if ctx.children[-1].children[0].getText() == self.source_class:
            self.has_source_new = True

    def enterCreatedName0(self, ctx: JavaParserLabeled.CreatedName0Context):
        if ctx.IDENTIFIER(0).getText() == self.source_class and self.target_class:
            self.token_stream_rewriter.replaceIndex(
                index=ctx.start.tokenIndex,
                text=self.target_class
            )

    def enterCreatedName1(self, ctx: JavaParserLabeled.CreatedName1Context):
        if ctx.getText() == self.source_class and self.target_class:
            self.token_stream_rewriter.replaceIndex(
                index=ctx.start.tokenIndex,
                text=self.target_class
            )

    def enterFormalParameter(self, ctx: JavaParserLabeled.FormalParameterContext):
        class_type = ctx.typeType().classOrInterfaceType()
        if class_type:
            if class_type.IDENTIFIER(0).getText() == self.source_class and self.target_class:
                self.token_stream_rewriter.replaceIndex(
                    index=class_type.start.tokenIndex,
                    text=self.target_class
                )

    def enterQualifiedName(self, ctx: JavaParserLabeled.QualifiedNameContext):
        if ctx.IDENTIFIER(0).getText() == self.source_class and self.target_class:
            self.token_stream_rewriter.replaceIndex(
                index=ctx.start.tokenIndex,
                text=self.target_class
            )

    def exitExpression0(self, ctx: JavaParserLabeled.Expression0Context):
        if ctx.primary().getText() == self.source_class and self.target_class:
            self.token_stream_rewriter.replaceIndex(
                index=ctx.start.tokenIndex,
                text=self.target_class
            )

    def enterLocalVariableDeclaration(self, ctx: JavaParserLabeled.LocalVariableDeclarationContext):
        if ctx.typeType().classOrInterfaceType():
            if ctx.typeType().classOrInterfaceType().getText() == self.source_class and self.target_class:
                self.token_stream_rewriter.replace(
                    program_name=self.token_stream_rewriter.DEFAULT_PROGRAM_NAME,
                    from_idx=ctx.typeType().start.tokenIndex,
                    to_idx=ctx.typeType().stop.tokenIndex,
                    text=self.target_class
                )
Beispiel #15
0
class RenameClassRefactoringListener(JavaParserLabeledListener):
    """
    To implement the encapsulate filed refactored
    Encapsulate field: Make a public field private and provide accessors
    """
    def __init__(self,
                 common_token_stream: CommonTokenStream = None,
                 class_new_name: str = None,
                 class_identifier: str = None,
                 package_identifier: str = None):
        """
        :param common_token_stream:
        """
        self.token_stream = common_token_stream
        self.class_new_name = class_new_name
        self.class_identifier = class_identifier
        self.package_identifier = package_identifier
        self.declared_objects_names = []

        self.is_package_imported = False
        self.in_selected_package = False
        self.in_selected_class = False
        self.in_some_package = False

        # Move all the tokens in the source code in a buffer, token_stream_rewriter.
        if common_token_stream is not None:
            self.token_stream_rewriter = TokenStreamRewriter(
                common_token_stream)
        else:
            raise TypeError('common_token_stream is None')

    def enterPackageDeclaration(
            self, ctx: JavaParserLabeled.PackageDeclarationContext):
        self.in_some_package = True
        if self.package_identifier is not None:
            if self.package_identifier == ctx.qualifiedName().getText():
                self.in_selected_package = True
                print("Package Found")

    def enterClassDeclaration(self,
                              ctx: JavaParserLabeled.ClassDeclarationContext):
        if self.package_identifier is None \
                and not self.in_some_package \
                or self.package_identifier is not None \
                and self.in_selected_package:
            if ctx.IDENTIFIER().getText() == self.class_identifier:
                print("Class Found")
                self.in_selected_class = True
                self.token_stream_rewriter.replaceIndex(
                    index=ctx.start.tokenIndex + 2, text=self.class_new_name)

    def enterImportDeclaration(
            self, ctx: JavaParserLabeled.ImportDeclarationContext):
        if self.package_identifier is not None:
            if ctx.getText() == "import" + self.package_identifier + "." + self.class_identifier + ";"\
                    or ctx.getText() == "import" + self.package_identifier + ".*" + ";"\
                    or ctx.getText() == "import" +  self.package_identifier + ";":
                self.is_package_imported = True
            if ctx.getText(
            ) == "import" + self.package_identifier + "." + self.class_identifier + ";":
                self.token_stream_rewriter.replaceIndex(
                    index=ctx.qualifiedName().start.tokenIndex +
                    2 * len(ctx.qualifiedName().IDENTIFIER()) - 2,
                    text=self.class_new_name)

    def enterConstructorDeclaration(
            self, ctx: JavaParserLabeled.ConstructorDeclarationContext):
        if self.in_selected_package and ctx.IDENTIFIER().getText(
        ) == self.class_identifier:
            self.token_stream_rewriter.replaceIndex(index=ctx.start.tokenIndex,
                                                    text=self.class_new_name)

    def exitFieldDeclaration(self,
                             ctx: JavaParserLabeled.FieldDeclarationContext):
        if self.package_identifier is None \
                or self.package_identifier is not None \
                and self.is_package_imported:
            if ctx.typeType().getText() == self.class_identifier:
                # change the name class; (we find right class then change the name class)
                self.token_stream_rewriter.replaceIndex(
                    index=ctx.typeType().start.tokenIndex,
                    text=self.class_new_name)
                print("class name has change to new_class_name")

    # def enterExpressionName2(self, ctx:Java9_v2Parser.ExpressionName1Context):
    #     if self.is_package_imported \
    #             or self.package_identifier is None \
    #             or self.in_selected_package:
    #         if ctx.getText() == self.class_identifier:
    #             self.token_stream_rewriter.replaceIndex(
    #                 index=ctx.start.tokenIndex,
    #                 text=self.class_identifier)
    #
    def exitPrimary4(self, ctx: JavaParserLabeled.Primary4Context):
        if self.is_package_imported \
                or self.package_identifier is None \
                or self.in_selected_package:
            if ctx.getText() == self.class_identifier:
                self.token_stream_rewriter.replaceIndex(
                    index=ctx.start.tokenIndex, text=self.class_new_name)

    def enterCreatedName0(self, ctx: JavaParserLabeled.CreatedName0Context):
        if self.is_package_imported \
                or self.package_identifier is None \
                or self.in_selected_package:
            if ctx.getText() == self.class_identifier:
                print("ClassInstanceCreationExpression_lfno_primary1")
                self.token_stream_rewriter.replaceIndex(
                    index=ctx.start.tokenIndex, text=self.class_new_name)
Beispiel #16
0
class MakeFieldStaticRefactoringListener(JavaParserLabeledListener):
    """
    To implement the encapsulate filed refactored
    Encapsulate field: Make a public field private and provide accessors
    """
    def __init__(self,
                 common_token_stream: CommonTokenStream = None,
                 field_identifier: str = None,
                 class_identifier: str = None,
                 package_identifier: str = None):
        """
        :param common_token_stream:
        """
        self.token_stream = common_token_stream
        self.field_identifier = field_identifier
        self.class_identifier = class_identifier
        self.package_identifier = package_identifier
        self.declared_objects_names = []

        self.is_package_imported = False
        self.in_selected_package = False
        self.in_selected_class = False
        self.in_some_package = False

        # Move all the tokens in the source code in a buffer, token_stream_rewriter.
        if common_token_stream is not None:
            self.token_stream_rewriter = TokenStreamRewriter(
                common_token_stream)
        else:
            raise TypeError('common_token_stream is None')

    def enterPackageDeclaration(
            self, ctx: JavaParserLabeled.PackageDeclarationContext):
        self.in_some_package = True
        if self.package_identifier is not None:
            if self.package_identifier == ctx.qualifiedName().getText():
                self.in_selected_package = True
                print("Package Found")

    def enterClassDeclaration(self,
                              ctx: JavaParserLabeled.ClassDeclarationContext):

        if self.package_identifier is None and not self.in_some_package or\
                self.package_identifier is not None and self.in_selected_package:
            if ctx.IDENTIFIER().getText() == self.class_identifier:
                print("Class Found")
                self.in_selected_class = True

    def enterImportDeclaration(
            self, ctx: JavaParserLabeled.ImportDeclarationContext):
        if self.package_identifier is not None:
            if ctx.getText() == "import" + self.package_identifier + "." + self.class_identifier + ";" \
                    or ctx.getText() == "import" + self.package_identifier + ".*" + ";" \
                    or ctx.getText() == "import" + self.package_identifier + ";":
                self.is_package_imported = True

    def exitFieldDeclaration(self,
                             ctx: JavaParserLabeled.FieldDeclarationContext):
        if self.package_identifier is None and not self.in_some_package\
                or self.package_identifier is not None and self.in_selected_package:
            if self.in_selected_class:
                if ctx.variableDeclarators().variableDeclarator(0)\
                        .variableDeclaratorId().getText() == self.field_identifier:

                    grand_parent_ctx = ctx.parentCtx.parentCtx
                    if len(grand_parent_ctx.modifier()) == 0:
                        self.token_stream_rewriter.insertBeforeIndex(
                            index=ctx.parentCtx.start.tokenIndex,
                            text=' static ')
                    else:
                        is_static = False
                        for modifier in grand_parent_ctx.modifier():
                            if modifier.getText() == "static":
                                is_static = True
                                break
                        if not is_static:
                            self.token_stream_rewriter.insertAfter(
                                index=grand_parent_ctx.start.tokenIndex +
                                len(grand_parent_ctx.modifier()),
                                text=' static ')

        if self.package_identifier is None or self.package_identifier is not None and self.is_package_imported:
            if ctx.typeType().classOrInterfaceType() is not None:
                if ctx.typeType().classOrInterfaceType().getText(
                ) == self.class_identifier:
                    self.declared_objects_names.append(
                        ctx.variableDeclarators().variableDeclarator(
                            0).variableDeclaratorId().getText())
                    print("Object " + ctx.variableDeclarators().variableDeclarator(0).variableDeclaratorId().getText()\
                          + " of type " + self.class_identifier + " found.")

    def enterExpression1(self, ctx: JavaParserLabeled.Expression1Context):
        if self.is_package_imported or self.package_identifier is None or self.in_selected_package:
            for object_name in self.declared_objects_names:
                if ctx.getText() == object_name + "." + self.field_identifier:
                    self.token_stream_rewriter.replaceIndex(
                        index=ctx.start.tokenIndex, text=self.class_identifier)
Beispiel #17
0
class RenameClassRefactoringListener(JavaParserLabeledListener):
    """
    The class performs Rename Class refactoring.
    The main listener which parses the file based on the provided information, \
        using ANTLR parser generator and tokenization methods

    """
    def __init__(self,
                 java_file_path,
                 common_token_stream: CommonTokenStream = None,
                 class_new_name: str = None,
                 class_identifier: str = None,
                 package_identifier: str = None):
        """
        Initializer of rename class refactoring listener

        Args:
            java_file_path(str): Address path to the test/source file

            common_token_stream (CommonTokenStream): An instance of ANTLR4 CommonTokenStream class

            class_new_name(str): The new name of the refactored class

            class_identifier(str): Name of the class in which the refactoring has to be done

            package_identifier(str): Name of the package in which the refactoring has to be done

        Returns:

            RenameMethodListener: An instance of RenameClassRefactoringListener class

        """

        self.file_path = java_file_path
        self.token_stream = common_token_stream
        self.class_new_name = class_new_name
        self.class_identifier = class_identifier
        self.package_identifier = package_identifier
        self.in_class = False
        self.changed = False
        self.declared_objects_names = []

        self.is_package_imported = False
        self.in_selected_package = False
        self.in_selected_class = False
        self.in_some_package = False

        # Move all the tokens in the source code in a buffer, token_stream_rewriter.
        if common_token_stream is not None:
            self.token_stream_rewriter = TokenStreamRewriter(
                common_token_stream)
        else:
            raise TypeError('common_token_stream is None')

    def enterPackageDeclaration(
            self, ctx: JavaParserLabeled.PackageDeclarationContext):
        self.in_some_package = True
        if self.package_identifier is not None:
            print(ctx.qualifiedName())
            print(ctx.getText())
            if self.package_identifier == ctx.qualifiedName().getText():
                self.in_selected_package = True
                print("Package Found")

    def enterClassDeclaration(self,
                              ctx: JavaParserLabeled.ClassDeclarationContext):
        if self.package_identifier is None \
                and not self.in_some_package \
                or self.package_identifier is not None \
                and self.in_selected_package:
            if ctx.IDENTIFIER().getText() == self.class_identifier:
                print("Class Found")
                self.in_selected_class = True
                self.token_stream_rewriter.replaceIndex(
                    index=ctx.start.tokenIndex + 2, text=self.class_new_name)
                self.changed = True

    def enterImportDeclaration(
            self, ctx: JavaParserLabeled.ImportDeclarationContext):
        if self.package_identifier is not None:
            if ctx.getText() == "import" + self.package_identifier + "." + self.class_identifier + ";" \
                    or ctx.getText() == "import" + self.package_identifier + ".*" + ";" \
                    or ctx.getText() == "import" + self.package_identifier + ";":
                self.is_package_imported = True
            if ctx.getText(
            ) == "import" + self.package_identifier + "." + self.class_identifier + ";":
                self.token_stream_rewriter.replaceIndex(
                    index=ctx.qualifiedName().start.tokenIndex +
                    2 * len(ctx.qualifiedName().IDENTIFIER()) - 2,
                    text=self.class_new_name)
                self.changed = True

    def enterConstructorDeclaration(
            self, ctx: JavaParserLabeled.ConstructorDeclarationContext):
        if self.in_selected_package and ctx.IDENTIFIER().getText(
        ) == self.class_identifier:
            self.token_stream_rewriter.replaceIndex(index=ctx.start.tokenIndex,
                                                    text=self.class_new_name)
            self.changed = True

    def exitFieldDeclaration(self,
                             ctx: JavaParserLabeled.FieldDeclarationContext):
        if self.package_identifier is None \
                or self.package_identifier is not None \
                and self.is_package_imported:
            if ctx.typeType().getText() == self.class_identifier:
                # change the name class; (we find right class then change the name class)
                self.token_stream_rewriter.replaceIndex(
                    index=ctx.typeType().start.tokenIndex,
                    text=self.class_new_name)
                self.changed = True
                print("class name has change to new_class_name")

    # def enterExpressionName2(self, ctx:Java9_v2Parser.ExpressionName1Context):
    #     if self.is_package_imported \
    #             or self.package_identifier is None \
    #             or self.in_selected_package:
    #         if ctx.getText() == self.class_identifier:
    #             self.token_stream_rewriter.replaceIndex(
    #                 index=ctx.start.tokenIndex,
    #                 text=self.class_identifier)
    #
    def exitPrimary4(self, ctx: JavaParserLabeled.Primary4Context):
        if self.is_package_imported \
                or self.package_identifier is None \
                or self.in_selected_package:
            if ctx.getText() == self.class_identifier:
                self.token_stream_rewriter.replaceIndex(
                    index=ctx.start.tokenIndex, text=self.class_new_name)
                self.changed = True

    def enterCreatedName0(self, ctx: JavaParserLabeled.CreatedName0Context):
        if self.is_package_imported \
                or self.package_identifier is None \
                or self.in_selected_package:
            if ctx.getText() == self.class_identifier:
                print("ClassInstanceCreationExpression_lfno_primary1")
                self.token_stream_rewriter.replaceIndex(
                    index=ctx.start.tokenIndex, text=self.class_new_name)
                self.changed = True
Beispiel #18
0
class RenameMethodListener(JavaParserLabeledListener):
    """

    The class implements Rename Method refactoring.
    The Main listener which parses the file based on the provided information, \
        using ANTLR parser generator and tokenization methods

    """
    def __init__(self,
                 java_file_path,
                 common_token_stream,
                 scope_class_name,
                 target_method_name,
                 new_name,
                 reference=None):
        """

        Initializer of rename method refactoring listener

            Args:

                java_file_path(str): Address path to the test/source file

                common_token_stream (CommonTokenStream): An instance of ANTLR4 CommonTokenStream class

                scope_class_name(str): Name of the class in which the refactoring has to be done

                target_method_name(str): Name of the method in which the refactoring has to be done

                new_name(str): The new name of the refactored method

            Returns:

                RenameMethodListener: An instance of RenameMethodListener class

        """

        self.file_path = java_file_path
        self.token_stream = common_token_stream
        self.token_stream_rewriter = TokenStreamRewriter(common_token_stream)
        self.class_name = scope_class_name
        self.method_name = target_method_name
        self.new_method_name = new_name
        self.in_class = False
        self.changed = False
        self.reference = reference

    def enterClassDeclaration(self,
                              ctx: JavaParserLabeled.ClassDeclarationContext):
        name = ctx.IDENTIFIER().getText()
        if name == self.class_name:
            self.in_class = True

    def exitClassDeclaration(self,
                             ctx: JavaParserLabeled.ClassDeclarationContext):
        name = ctx.IDENTIFIER().getText()
        if name == self.class_name:
            self.in_class = False

    def enterMethodDeclaration(
            self, ctx: JavaParserLabeled.MethodDeclarationContext):
        if self.in_class:
            name = ctx.IDENTIFIER()
            if name.getText() == self.method_name:
                node = name.getSymbol()
                self.token_stream_rewriter.replaceIndex(
                    node.tokenIndex, self.new_method_name)
                self.changed = True

    def enterMethodCall0(self, ctx: JavaParserLabeled.MethodCall0Context):
        if self.in_class and self.reference:
            name = ctx.IDENTIFIER()
            if name.getText() == self.method_name:
                node = name.getSymbol()
                if node.line == self.reference["line"]:
                    self.token_stream_rewriter.replaceIndex(
                        node.tokenIndex, self.new_method_name)
                    self.changed = True

    def enterMethodCall1(self, ctx: JavaParserLabeled.MethodCall1Context):
        if self.in_class and self.reference:
            name = ctx.IDENTIFIER()
            if name.getText() == self.method_name:
                node = name.getSymbol()
                if node.line == self.reference["line"]:
                    self.token_stream_rewriter.replaceIndex(
                        node.tokenIndex, self.new_method_name)
                    self.changed = True
Beispiel #19
0
class RenameMethodListener(JavaParserLabeledListener):
    """
    ## Introduction

    When the name of a method does not explain what the method does (method's functionality), it needs to be changed.

    ## Pre and Post Conditions

    ### Pre Conditions:

    1. User must enter the existing method's name, The source class's name for the refactoring, and the new method name
         in order to rename.

    2. Check if the method exist, then rename it.

    ### Post Conditions:

    1. After refactoring, all the old method names in the project should be changed.

    See whether the method is defined in a superclass or subclass. If so, you must repeat all steps in these classes too.

    The next method is important for maintaining the functionality of the program during the refactoring process. Create
    a new method with a new name. Copy the code of the old method to it. Delete all the code in the old method and,
    instead of it, insert a call for the new method.

    Find all references to the old method and replace them with references to the new one.

    Delete the old method. If the old method is part of a public interface, don’t perform this step. Instead,
    mark the old method as deprecated.
    """
    def __init__(self,
                 java_file_path,
                 common_token_stream,
                 scope_class_name,
                 target_method_name,
                 new_name,
                 reference=None):
        """The Main listener which parses the file based on the provided information,
            using ANTLR parser generator and tokenization methods

            Args:
                java_file_path(str): Address path to the test/source file

                scope_class_name(str): Name of the class in which the refactoring has to be done

                target_method_name(str): Name of the method in which the refactoring has to be done

                new_name(str): The new name of the refactored method

            Returns:
                No returns
        """
        self.file_path = java_file_path
        self.token_stream = common_token_stream
        self.token_stream_rewriter = TokenStreamRewriter(common_token_stream)
        self.class_name = scope_class_name
        self.method_name = target_method_name
        self.new_method_name = new_name
        self.in_class = False
        self.changed = False
        self.reference = reference

    def enterClassDeclaration(self,
                              ctx: JavaParserLabeled.ClassDeclarationContext):
        name = ctx.IDENTIFIER().getText()
        if name == self.class_name:
            self.in_class = True

    def exitClassDeclaration(self,
                             ctx: JavaParserLabeled.ClassDeclarationContext):
        name = ctx.IDENTIFIER().getText()
        if name == self.class_name:
            self.in_class = False

    def enterMethodDeclaration(
            self, ctx: JavaParserLabeled.MethodDeclarationContext):
        if self.in_class:
            name = ctx.IDENTIFIER()
            if name.getText() == self.method_name:
                node = name.getSymbol()
                self.token_stream_rewriter.replaceIndex(
                    node.tokenIndex, self.new_method_name)
                self.changed = True

    def enterMethodCall0(self, ctx: JavaParserLabeled.MethodCall0Context):
        if self.in_class and self.reference:
            name = ctx.IDENTIFIER()
            if name.getText() == self.method_name:
                node = name.getSymbol()
                if node.line == self.reference["line"]:
                    self.token_stream_rewriter.replaceIndex(
                        node.tokenIndex, self.new_method_name)
                    self.changed = True

    def enterMethodCall1(self, ctx: JavaParserLabeled.MethodCall1Context):
        if self.in_class and self.reference:
            name = ctx.IDENTIFIER()
            if name.getText() == self.method_name:
                node = name.getSymbol()
                if node.line == self.reference["line"]:
                    self.token_stream_rewriter.replaceIndex(
                        node.tokenIndex, self.new_method_name)
                    self.changed = True
Beispiel #20
0
class RenameFieldRefactoringListener(JavaParserLabeledListener):
    """
    The class performs Rename Field Refactoring

    """
    def __init__(self,
                 common_token_stream: CommonTokenStream = None,
                 package_name: str = None,
                 scope_class_name: str = None,
                 field_identifier: str = None,
                 field_new_name: str = None):
        """
        Args:

            common_token_stream (CommonTokenStream): An instance of ANTLR4 CommonTokenStream class

            package_name(str): Name of the packages in which the refactoring has to be done

            scope_class_name(str): Name of the class in which the refactoring has to be done

            field_identifier(str): Name of the package in which the refactoring has to be done

            field_new_name(str): The new name of the refactored method

        Returns:

            RenameFieldListener: An instance of RenameFieldListener class

        """

        self.token_stream = common_token_stream
        self.class_identifier = scope_class_name
        self.field_identifier = field_identifier
        self.field_new_name = field_new_name
        self.package_identifier = package_name

        self.is_package_imported = False
        self.in_class = False
        self.in_selected_package = False
        # Move all the tokens in the source code in a buffer, token_stream_rewriter.
        if common_token_stream is not None:
            self.token_stream_rewriter = TokenStreamRewriter(
                common_token_stream)
        else:
            raise TypeError('common_token_stream is None')

    def enterPackageDeclaration(
            self, ctx: JavaParserLabeled.PackageDeclarationContext):
        if self.package_identifier == ctx.qualifiedName().getText():
            self.in_selected_package = True
            print("Package " + self.package_identifier + " Found")

    def enterImportDeclaration(
            self, ctx: JavaParserLabeled.ImportDeclarationContext):
        if ctx.getText() == "import" + self.package_identifier + "." + self.class_identifier + ";" \
                or ctx.getText() == "import" + self.package_identifier + ".*" + ";" \
                or ctx.getText() == "import" + self.package_identifier + ";":
            self.is_package_imported = True
            print("package " + self.package_identifier + " imported")

    def enterClassDeclaration(self,
                              ctx: JavaParserLabeled.ClassDeclarationContext):
        if self.is_package_imported or self.in_selected_package:
            if ctx.IDENTIFIER().getText() == self.class_identifier:
                self.in_class = True

    def exitClassDeclaration(self,
                             ctx: JavaParserLabeled.ClassDeclarationContext):
        if self.is_package_imported or self.in_selected_package:
            if ctx.IDENTIFIER().getText() == self.class_identifier:
                self.in_class = False

    def enterFieldDeclaration(self,
                              ctx: JavaParserLabeled.FieldDeclarationContext):
        if self.in_class:
            if ctx.variableDeclarators().variableDeclarator(
                    0).variableDeclaratorId().getText(
                    ) == self.field_identifier:
                self.token_stream_rewriter.replaceIndex(
                    index=ctx.variableDeclarators().variableDeclarator(
                        0).variableDeclaratorId().start.tokenIndex,
                    text=self.field_new_name)
                print("field name changed !")

    def enterExpression21(self, ctx: JavaParserLabeled.Expression21Context):
        if self.in_class:
            if ctx.expression(0).getText() == self.field_identifier:
                self.token_stream_rewriter.replaceIndex(
                    index=ctx.expression(0).start.tokenIndex,
                    text=self.field_new_name)
                print("expression21 changed! ")
            elif ctx.expression(
                    0).getText() == "this." + self.field_identifier:
                self.token_stream_rewriter.replaceIndex(
                    index=ctx.expression(0).start.tokenIndex + 2,
                    text=self.field_new_name)
                # print("expression21 ", ctx.expression(0).getText(), " changed to: ", "this.", self.field_new_name)
                print("expression21 changed! ")

            if ctx.expression(1).getText() == self.field_identifier:
                self.token_stream_rewriter.replaceIndex(
                    index=ctx.expression(1).start.tokenIndex,
                    text=self.field_new_name)
                # print("expression21 ", ctx.expression(1).getText(), " changed to: ", self.field_new_name)
                print("expression21 changed! ")

            elif ctx.expression(
                    1).getText() == "this." + self.field_identifier:
                self.token_stream_rewriter.replaceIndex(
                    index=ctx.expression(1).start.tokenIndex + 2,
                    text=self.field_new_name)
                # print("expression21 ", ctx.expression(1).getText(), " changed to: ", "this.", self.field_new_name)
                print("expression21 changed! ")

    # def enterVariableDeclarator(self, ctx: JavaParserLabeled.VariableDeclaratorContext):
    #     print("8888888888888888888888888888888888888888888888888888888888888888888888888888888888")
    #     x = JavaParserLabeled.VariableInitializer1Context(ctx.variableInitializer(),ctx.)
    #     y = JavaParserLabeled.Expression1Context(x.expression(), ctx)
    #     print(y.IDENTIFIER())
    #     # if self.is_in_scope:
    #     #     if ctx.variableInitializer().expression().IDENTIFIER().getText() == self.field_identifier:
    #     #         self.token_stream_rewriter.replaceIndex(
    #     #             index=ctx.expression().start.tokenIndex,
    #     #             text=self.field_new_name)
    #     #         print("8888888888888888888888888888888888888888888888888888888888888888888888888888888888")

    def enterVariableInitializer1(
            self, ctx: JavaParserLabeled.VariableInitializer1Context):
        if self.in_class:
            if ctx.expression().getText() == self.field_identifier:
                self.token_stream_rewriter.replaceIndex(
                    index=ctx.expression().start.tokenIndex,
                    text=self.field_new_name)
                print("variable initializer changed")
            elif ctx.expression().getText() == "this." + self.field_identifier:
                self.token_stream_rewriter.replaceIndex(
                    index=ctx.expression().start.tokenIndex + 2,
                    text=self.field_new_name)
                print("variable initializer changed")
Beispiel #21
0
class RenameClassRefactoringListener(JavaParserLabeledListener):
    """
    To implement the encapsulate filed refactored
    Encapsulate field: Make a public field private and provide accessors
    """
    def __init__(self,
                 common_token_stream: CommonTokenStream = None,
                 class_new_name: str = None,
                 class_identifier: str = None):
        """
        :param common_token_stream:
        """
        self.token_stream = common_token_stream
        self.class_new_name = class_new_name
        self.class_identifier = class_identifier

        # Move all the tokens in the source code in a buffer, token_stream_rewriter.
        if common_token_stream is not None:
            self.token_stream_rewriter = TokenStreamRewriter(
                common_token_stream)
        else:
            raise TypeError('common_token_stream is None')

    # def enterPackageDeclaration(self, ctx: JavaParserLabeled.PackageDeclarationContext):
    #     self.in_some_package = True
    #     if self.package_identifier is not None:
    #         if self.package_identifier == ctx.qualifiedName().getText():
    #             self.in_selected_package = True
    #             print("Package Found")

    def enterClassDeclaration(self,
                              ctx: JavaParserLabeled.ClassDeclarationContext):

        if ctx.IDENTIFIER().getText() == self.class_identifier:
            print("Class Found")
            self.token_stream_rewriter.replaceIndex(
                index=ctx.start.tokenIndex + 2, text=self.class_new_name)
            print("class name changed !")

    def enterCreatedName0(self, ctx: JavaParserLabeled.CreatedName0Context):
        if ctx.IDENTIFIER(0).getText() == self.class_identifier:
            self.token_stream_rewriter.replaceIndex(index=ctx.start.tokenIndex,
                                                    text=self.class_new_name)
            print("creator changed")

    def enterLocalVariableDeclaration(
            self, ctx: JavaParserLabeled.LocalVariableDeclarationContext):
        if self.class_identifier == ctx.typeType().classOrInterfaceType(
        ).IDENTIFIER(0).getText():
            self.token_stream_rewriter.replaceIndex(
                index=ctx.typeType().classOrInterfaceType().start.tokenIndex,
                text=self.class_new_name)
            print("creator changed")

    # def enterImportDeclaration(self, ctx:JavaParserLabeled.ImportDeclarationContext):
    #     if self.package_identifier is not None:
    #         if ctx.getText() == "import" + self.package_identifier + "." + self.class_identifier + ";"\
    #                 or ctx.getText() == "import" + self.package_identifier + ".*" + ";"\
    #                 or ctx.getText() == "import" +  self.package_identifier + ";":
    #             self.is_package_imported = True
    #         if ctx.getText() == "import" + self.package_identifier + "." + self.class_identifier + ";":
    #             self.token_stream_rewriter.replaceIndex(
    #                 index=ctx.qualifiedName().start.tokenIndex + 2*len(ctx.qualifiedName().IDENTIFIER()) - 2,
    #                 text=self.class_new_name)

    def enterConstructorDeclaration(
            self, ctx: JavaParserLabeled.ConstructorDeclarationContext):
        if ctx.IDENTIFIER().getText() == self.class_identifier:
            self.token_stream_rewriter.replaceIndex(index=ctx.start.tokenIndex,
                                                    text=self.class_new_name)
        print("constructor name changed !")
Beispiel #22
0
class RenameClassRefactoringListener(JavaParserLabeledListener):
    """

    The class implements rename class refactoring

    """

    def __init__(self,
                 common_token_stream: CommonTokenStream = None,
                 package_name: str = None,
                 class_identifier: str = None,
                 class_new_name: str = None):

        """
        Args:

            common_token_stream (CommonTokenStream): An instance of ANTLR4 CommonTokenStream class

            package_name(str): Name of the package in which the refactoring has to be done

            class_identifier(str): Name of the class in which the refactoring has to be done

            class_new_name(str): The new name of the refactored class


        Returns:

            RenameMethodListener: An instance of RenameClassRefactoringListener class

        """

        self.token_stream = common_token_stream
        self.class_new_name = class_new_name
        self.class_identifier = class_identifier
        self.package_identifier = package_name

        self.is_package_imported = False
        self.in_selected_package = False
        self.in_selected_class = False
        self.in_some_package = False

        # Move all the tokens in the source code in a buffer, token_stream_rewriter.
        if common_token_stream is not None:
            self.token_stream_rewriter = TokenStreamRewriter(common_token_stream)
        else:
            raise TypeError('common_token_stream is None')

    def enterPackageDeclaration(self, ctx: JavaParserLabeled.PackageDeclarationContext):
        self.in_some_package = True
        if self.package_identifier == ctx.qualifiedName().getText():
            self.in_selected_package = True
            print("Package " + self.package_identifier + " Found")

    def enterImportDeclaration(self, ctx: JavaParserLabeled.ImportDeclarationContext):
        if ctx.getText() == "import" + self.package_identifier + "." + self.class_identifier + ";" \
                or ctx.getText() == "import" + self.package_identifier + ".*" + ";" \
                or ctx.getText() == "import" + self.package_identifier + ";":
            self.is_package_imported = True
            print("package " + self.package_identifier + " imported")
        if ctx.getText() == "import" + self.package_identifier + "." + self.class_identifier + ";":
            self.token_stream_rewriter.replaceIndex(
                index=ctx.qualifiedName().start.tokenIndex + 2 * len(ctx.qualifiedName().IDENTIFIER()) - 2,
                text=self.class_new_name)
            print("class name in package changed")

    def enterClassDeclaration(self, ctx: JavaParserLabeled.ClassDeclarationContext):
        if self.is_package_imported or self.in_selected_package:
            if ctx.IDENTIFIER().getText() == self.class_identifier:
                self.token_stream_rewriter.replaceIndex(
                    index=ctx.start.tokenIndex + 2,
                    text=self.class_new_name)
                change_file_name(self.class_identifier, self.class_new_name)
                print("class name : " + self.class_identifier + " in class declaration changed ")

    def enterCreatedName0(self, ctx: JavaParserLabeled.CreatedName0Context):
        if self.is_package_imported or self.in_selected_package:
            if ctx.IDENTIFIER(0).getText() == self.class_identifier:
                self.token_stream_rewriter.replaceIndex(
                    index=ctx.start.tokenIndex,
                    text=self.class_new_name)
                print("class name in creator changed")

    def enterClassOrInterfaceType(self, ctx:JavaParserLabeled.ClassOrInterfaceTypeContext):
        if self.is_package_imported or self.in_selected_package:
            if ctx.IDENTIFIER(0).getText() == self.class_identifier:
                self.token_stream_rewriter.replaceIndex(
                    index=ctx.start.tokenIndex,
                    text=self.class_new_name)
                print("class type changed")

    def enterConstructorDeclaration(self, ctx: JavaParserLabeled.ConstructorDeclarationContext):
        if self.is_package_imported or self.in_selected_package:
            if ctx.IDENTIFIER().getText() == self.class_identifier:
                self.token_stream_rewriter.replaceIndex(
                    index=ctx.start.tokenIndex,
                    text=self.class_new_name)
                print("constructor name changed !")
Beispiel #23
0
class RenameFieldRefactoringListener(JavaParserLabeledListener):
    def __init__(self,
                 common_token_stream: CommonTokenStream = None,
                 scope_class_name: str = None,
                 field_identifier: str = None,
                 field_new_name: str = None):

        self.token_stream = common_token_stream
        self.scope_class_name = scope_class_name
        self.field_identifier = field_identifier
        self.field_new_name = field_new_name

        self.is_in_scope = False
        # Move all the tokens in the source code in a buffer, token_stream_rewriter.
        if common_token_stream is not None:
            self.token_stream_rewriter = TokenStreamRewriter(
                common_token_stream)
        else:
            raise TypeError('common_token_stream is None')

    def enterFieldDeclaration(self,
                              ctx: JavaParserLabeled.FieldDeclarationContext):
        if self.is_in_scope:
            if ctx.variableDeclarators().variableDeclarator(
                    0).variableDeclaratorId().getText(
                    ) == self.field_identifier:
                self.token_stream_rewriter.replaceIndex(
                    index=ctx.variableDeclarators().variableDeclarator(
                        0).variableDeclaratorId().start.tokenIndex,
                    text=self.field_new_name)
                print("field name changed !")

    def enterClassDeclaration(self,
                              ctx: JavaParserLabeled.ClassDeclarationContext):

        if ctx.IDENTIFIER().getText() == self.scope_class_name:
            self.is_in_scope = True
            print("enter class : ", self.scope_class_name)

    def exitClassDeclaration(self,
                             ctx: JavaParserLabeled.ClassDeclarationContext):
        if ctx.IDENTIFIER().getText() == self.scope_class_name:
            self.is_in_scope = False
            print("exit class : ", self.scope_class_name)

    def enterExpression21(self, ctx: JavaParserLabeled.Expression21Context):
        if self.is_in_scope:
            if ctx.expression(0).getText() == self.field_identifier:
                self.token_stream_rewriter.replaceIndex(
                    index=ctx.expression(0).start.tokenIndex,
                    text=self.field_new_name)
                print("expression21 ",
                      ctx.expression(0).getText(), " changed to: ",
                      self.field_new_name)
            elif ctx.expression(
                    0).getText() == "this." + self.field_identifier:
                self.token_stream_rewriter.replaceIndex(
                    index=ctx.expression(0).start.tokenIndex + 2,
                    text=self.field_new_name)
                print("expression21 ",
                      ctx.expression(0).getText(), " changed to: ", "this.",
                      self.field_new_name)

            if ctx.expression(1).getText() == self.field_identifier:
                self.token_stream_rewriter.replaceIndex(
                    index=ctx.expression(1).start.tokenIndex,
                    text=self.field_new_name)
                print("expression21 ",
                      ctx.expression(1).getText(), " changed to: ",
                      self.field_new_name)
            elif ctx.expression(
                    1).getText() == "this." + self.field_identifier:
                self.token_stream_rewriter.replaceIndex(
                    index=ctx.expression(1).start.tokenIndex + 2,
                    text=self.field_new_name)
                print("expression21 ",
                      ctx.expression(1).getText(), " changed to: ", "this.",
                      self.field_new_name)

    # def enterVariableDeclarator(self, ctx: JavaParserLabeled.VariableDeclaratorContext):
    #     print("8888888888888888888888888888888888888888888888888888888888888888888888888888888888")
    #     x = JavaParserLabeled.VariableInitializer1Context(ctx.variableInitializer(),ctx.)
    #     y = JavaParserLabeled.Expression1Context(x.expression(), ctx)
    #     print(y.IDENTIFIER())
    #     # if self.is_in_scope:
    #     #     if ctx.variableInitializer().expression().IDENTIFIER().getText() == self.field_identifier:
    #     #         self.token_stream_rewriter.replaceIndex(
    #     #             index=ctx.expression().start.tokenIndex,
    #     #             text=self.field_new_name)
    #     #         print("8888888888888888888888888888888888888888888888888888888888888888888888888888888888")

    def enterVariableInitializer1(
            self, ctx: JavaParserLabeled.VariableInitializer1Context):
        if self.is_in_scope:
            if ctx.expression().getText() == self.field_identifier:
                self.token_stream_rewriter.replaceIndex(
                    index=ctx.expression().start.tokenIndex,
                    text=self.field_new_name)
                print("variable initializer changed")
            elif ctx.expression().getText() == "this." + self.field_identifier:
                self.token_stream_rewriter.replaceIndex(
                    index=ctx.expression().start.tokenIndex + 2,
                    text=self.field_new_name)
                print("variable initializer changed")

    def enterMethodCall0(self, ctx: JavaParserLabeled.MethodCall0Context):
        print(ctx.expressionList())
Beispiel #24
0
class RenameMethodRefactoringListener(JavaParserLabeledListener):
    """

    The class implements Rename Method refactoring.
    The Main listener which parses the file based on the provided information, \
        using ANTLR parser generator and tokenization methods

    """
    def __init__(self,
                 common_token_stream: CommonTokenStream = None,
                 package_name: str = None,
                 scope_class_name: str = None,
                 method_identifier: str = None,
                 method_new_name: str = None):
        """

        Initializer of rename method refactoring listener

            Args:

                common_token_stream (CommonTokenStream): An instance of ANTLR4 CommonTokenStream class

                package_name(str): Name of the package in which the refactoring has to be done

                scope_class_name(str): Name of the class in which the refactoring has to be done

                method_identifier(str): Name of the method in which the refactoring has to be done

                method_new_name(str): The new name of the refactored method

            Returns:

                RenameMethodListener: An instance of RenameMethodListener class
        """

        self.token_stream = common_token_stream
        self.class_identifier = scope_class_name
        self.method_identifier = method_identifier
        self.method_new_name = method_new_name
        self.package_identifier = package_name

        self.is_package_imported = False
        self.in_class = False
        self.in_selected_package = False
        # Move all the tokens in the source code in a buffer, token_stream_rewriter.
        if common_token_stream is not None:
            self.token_stream_rewriter = TokenStreamRewriter(common_token_stream)
        else:
            raise TypeError('common_token_stream is None')

    def enterPackageDeclaration(self, ctx: JavaParserLabeled.PackageDeclarationContext):
        if self.package_identifier == ctx.qualifiedName().getText():
            self.in_selected_package = True
            print("Package " + self.package_identifier + " Found")

    def enterImportDeclaration(self, ctx: JavaParserLabeled.ImportDeclarationContext):
        if ctx.getText() == "import" + self.package_identifier + "." + self.class_identifier + ";" \
                or ctx.getText() == "import" + self.package_identifier + ".*" + ";" \
                or ctx.getText() == "import" + self.package_identifier + ";":
            self.is_package_imported = True
            print("package " + self.package_identifier + " imported")

    def enterClassDeclaration(self, ctx: JavaParserLabeled.ClassDeclarationContext):
        if self.is_package_imported or self.in_selected_package:
            if ctx.IDENTIFIER().getText() == self.class_identifier:
                self.in_class = True

    def exitClassDeclaration(self, ctx: JavaParserLabeled.ClassDeclarationContext):
        if self.is_package_imported or self.in_selected_package:
            if ctx.IDENTIFIER().getText() == self.class_identifier:
                self.in_class = False

    def enterMethodDeclaration(self, ctx: JavaParserLabeled.MethodDeclarationContext):
        if self.is_package_imported or self.in_selected_package:
            if self.in_class:
                if ctx.IDENTIFIER().getText() == self.method_identifier:
                    self.token_stream_rewriter.replaceIndex(
                        index=ctx.start.tokenIndex + 2,
                        text=self.method_new_name)
                    print("method name changed !")

    def enterMethodCall0(self, ctx: JavaParserLabeled.MethodCall0Context):
        if self.is_package_imported or self.in_selected_package:
            if self.in_class:
                if ctx.IDENTIFIER().getText() == self.method_identifier:
                    self.token_stream_rewriter.replaceIndex(
                        index=ctx.start.tokenIndex,
                        text=self.method_new_name)
                    print("method call name changed !")
Beispiel #25
0
class RenameMethodRefactoringListener(JavaParserLabeledListener):
    def __init__(self,
                 common_token_stream: CommonTokenStream = None,
                 package_name: str = None,
                 scope_class_name: str = None,
                 method_identifier: str = None,
                 method_new_name: str = None):
        """
        :param common_token_stream:
        """
        self.token_stream = common_token_stream
        self.class_identifier = scope_class_name
        self.method_identifier = method_identifier
        self.method_new_name = method_new_name
        self.package_identifier = package_name

        self.is_package_imported = False
        self.in_class = False
        self.in_selected_package = False
        # Move all the tokens in the source code in a buffer, token_stream_rewriter.
        if common_token_stream is not None:
            self.token_stream_rewriter = TokenStreamRewriter(
                common_token_stream)
        else:
            raise TypeError('common_token_stream is None')

    def enterPackageDeclaration(
            self, ctx: JavaParserLabeled.PackageDeclarationContext):
        if self.package_identifier == ctx.qualifiedName().getText():
            self.in_selected_package = True
            print("Package " + self.package_identifier + " Found")

    def enterImportDeclaration(
            self, ctx: JavaParserLabeled.ImportDeclarationContext):
        if ctx.getText() == "import" + self.package_identifier + "." + self.class_identifier + ";" \
                or ctx.getText() == "import" + self.package_identifier + ".*" + ";" \
                or ctx.getText() == "import" + self.package_identifier + ";":
            self.is_package_imported = True
            print("package " + self.package_identifier + " imported")

    def enterClassDeclaration(self,
                              ctx: JavaParserLabeled.ClassDeclarationContext):
        if self.is_package_imported or self.in_selected_package:
            if ctx.IDENTIFIER().getText() == self.class_identifier:
                self.in_class = True

    def exitClassDeclaration(self,
                             ctx: JavaParserLabeled.ClassDeclarationContext):
        if self.is_package_imported or self.in_selected_package:
            if ctx.IDENTIFIER().getText() == self.class_identifier:
                self.in_class = False

    def enterMethodDeclaration(
            self, ctx: JavaParserLabeled.MethodDeclarationContext):
        if self.is_package_imported or self.in_selected_package:
            if self.in_class:
                if ctx.IDENTIFIER().getText() == self.method_identifier:
                    self.token_stream_rewriter.replaceIndex(
                        index=ctx.start.tokenIndex + 2,
                        text=self.method_new_name)
                    print("method name changed !")

    def enterMethodCall0(self, ctx: JavaParserLabeled.MethodCall0Context):
        if self.is_package_imported or self.in_selected_package:
            if self.in_class:
                if ctx.IDENTIFIER().getText() == self.method_identifier:
                    self.token_stream_rewriter.replaceIndex(
                        index=ctx.start.tokenIndex, text=self.method_new_name)
                    print("method call name changed !")