From 3d5c51aa3dcda69625f5dd57b7efefdc7cab8e54 Mon Sep 17 00:00:00 2001 From: m-zakeri Date: Fri, 27 May 2022 00:01:29 +0430 Subject: [PATCH] Major restructuring in the main branch --- codart/codart_cli.py | 7 +- {sbse => codart}/config.py | 24 +- {gen => codart/gen}/__init__.py | 0 {gen => codart/gen}/java/JavaLexer.interp | 0 {gen => codart/gen}/java/JavaLexer.py | 0 {gen => codart/gen}/java/JavaLexer.tokens | 0 {gen => codart/gen}/java/JavaParser.interp | 0 {gen => codart/gen}/java/JavaParser.py | 0 {gen => codart/gen}/java/JavaParser.tokens | 0 .../gen}/java/JavaParserListener.py | 0 {gen => codart/gen}/java/__init__.py | 0 {gen => codart/gen}/java9/Java9_v2.interp | 0 {gen => codart/gen}/java9/Java9_v2.tokens | 0 .../gen}/java9/Java9_v2Lexer.interp | 0 {gen => codart/gen}/java9/Java9_v2Lexer.py | 0 .../gen}/java9/Java9_v2Lexer.tokens | 0 {gen => codart/gen}/java9/Java9_v2Listener.py | 0 {gen => codart/gen}/java9/Java9_v2Parser.py | 0 {gen => codart/gen}/java9/Java9_v2Visitor.py | 0 {gen => codart/gen}/java9/__init__.py | 0 .../gen}/javaLabeled/JavaLexer.interp | 0 {gen => codart/gen}/javaLabeled/JavaLexer.py | 0 .../gen}/javaLabeled/JavaLexer.tokens | 0 .../gen}/javaLabeled/JavaParserLabeled.interp | 0 .../gen}/javaLabeled/JavaParserLabeled.py | 0 .../gen}/javaLabeled/JavaParserLabeled.tokens | 0 .../javaLabeled/JavaParserLabeledListener.py | 0 {gen => codart/gen}/javaLabeled/__init__.py | 0 {metrics => codart/metrics}/__init__.py | 0 .../metrics}/data_model/DS07012.csv | 0 .../metrics}/data_model/DS07310.csv | 0 .../metrics}/data_model/DS07410.csv | 0 .../metrics}/data_model/DS07510.csv | 0 .../metrics}/data_model/DS07610.csv | 0 .../metrics}/data_model/DS07710.csv | 0 .../metrics}/data_preparation_evo_suite_4.py | 27 +- .../metrics}/metrics_coverability.py | 4 +- .../metrics}/metrics_jcode_odor.py | 2 +- {metrics => codart/metrics}/metrics_names.py | 0 {metrics => codart/metrics}/modularity.py | 3 +- {metrics => codart/metrics}/qmood.py | 2 +- .../metrics}/source_code_metrics.py | 0 .../metrics}/testability_learning.py | 0 .../metrics}/testability_prediction.py | 42 +- .../metrics}/testability_prediction2.py | 31 +- .../metrics}/testability_prediction3.py | 4 +- .../refactoring_design_patterns}/__init__.py | 0 .../refactoring_design_patterns}/factory1.py | 103 ++- .../singleton1.py | 51 +- .../refactoring_design_patterns}/strategy1.py | 61 +- .../refactoring_design_patterns}/visitor1.py | 88 +- .../refactorings}/__init__.py | 0 .../refactorings}/collapse_hierarchy.py | 8 +- .../refactorings}/dead_codes/__init__.py | 0 .../dead_codes/main_forbig_project.py | 20 +- .../refactorings}/dead_codes/main_omidvar.py | 10 +- .../dead_codes/refactoring_action_module.py | 59 +- ...factoring_action_module_for_big_project.py | 58 +- .../refactorings}/dead_codes/test.py | 12 +- .../decrease_field_visibility.py | 6 +- .../decrease_method_visibility.py | 6 +- .../refactorings}/encapsulate_field.py | 10 +- .../refactorings}/extract_class.py | 9 +- .../refactorings}/extract_interface.py | 7 +- .../refactorings}/extract_interface2.py | 8 +- .../refactorings}/extract_method.py | 6 +- .../refactorings}/extract_subclass.py | 6 +- .../increase_field_visibility.py | 6 +- .../increase_method_visibility.py | 6 +- .../refactorings}/inline_class.py | 4 +- .../refactorings}/make_class_abstract.py | 6 +- .../refactorings}/make_class_concrete.py | 6 +- .../refactorings}/make_class_final.py | 6 +- .../refactorings}/make_class_non_final.py | 6 +- .../refactorings}/make_field_final.py | 8 +- .../refactorings}/make_field_non_final.py | 8 +- .../refactorings}/make_field_non_static.py | 6 +- .../refactorings}/make_field_static.py | 6 +- .../refactorings}/make_method_final.py | 6 +- .../refactorings}/make_method_non_final.py | 6 +- .../refactorings}/make_method_non_static.py | 6 +- .../refactorings}/make_method_non_static2.py | 6 +- .../refactorings}/make_method_static.py | 6 +- .../refactorings}/make_method_static2.py | 7 +- .../refactorings}/move_class.py | 6 +- .../refactorings}/move_field.py | 6 +- .../refactorings}/move_method.py | 8 +- .../refactorings}/pullup_constructor.py | 6 +- .../refactorings}/pullup_field.py | 2 +- .../refactorings}/pullup_method.py | 8 +- .../refactorings}/pushdown_field.py | 2 +- .../refactorings}/pushdown_field2.py | 10 +- .../refactorings}/pushdown_method.py | 8 +- .../refactorings}/pushdown_method2.py | 6 +- .../refactorings}/remove_class.py | 6 +- .../refactorings}/remove_dead_code.py | 870 +++++++++--------- .../refactorings}/remove_field.py | 6 +- .../refactorings}/remove_flag_argument.py | 6 +- .../refactorings}/remove_interface.py | 6 +- .../refactorings}/remove_method.py | 6 +- .../refactorings}/rename_class.py | 6 +- .../refactorings}/rename_class2.py | 10 +- .../refactorings}/rename_field.py | 10 +- .../refactorings}/rename_method.py | 6 +- .../refactorings}/rename_method2.py | 10 +- .../refactorings}/rename_package.py | 10 +- .../replace_conditional_with_polymorphism.py | 12 +- ...place_constructor_with_factory_function.py | 8 +- .../replace_exception_with_test.py | 4 - .../replace_parameter_with_query.py | 6 +- .../replace_parameter_with_query2 .py | 8 +- {sbse => codart/sbse}/__init__.py | 0 {sbse => codart/sbse}/initialize.py | 11 +- {sbse => codart/sbse}/random_search.py | 4 +- .../sbse}/search_based_refactoring.py | 12 +- .../sbse}/search_based_refactoring2.py | 12 +- {sbse => codart/sbse}/sequence_application.py | 18 +- {sbse => codart/sbse}/simple_genetics.py | 67 +- codart/symbol_table.py | 253 +++-- codart/utility/cpu_ram_usage.py | 4 +- codart/utility/directory_utils.py | 7 +- codart/utility/setup_understand.py | 7 +- codart/utility/understand_install_test.py | 16 +- docs/index.md | 2 +- docs/metrics/testability.md | 2 +- docs/optimization/initialize.md | 2 +- docs/optimization/search-based_refactoring.md | 2 +- .../refactorings/decrease_field_visibility.md | 2 +- .../decrease_method_visibility.md | 2 +- docs/refactorings/encapsulate_field.md | 2 +- docs/refactorings/extract_class.md | 2 +- docs/refactorings/extract_interface.md | 2 +- docs/refactorings/extract_interface2.md | 2 +- docs/refactorings/extract_method.md | 2 +- docs/refactorings/extract_subclass.md | 2 +- .../refactorings/increase_field_visibility.md | 2 +- .../increase_method_visibility.md | 2 +- docs/refactorings/inline_class.md | 2 +- docs/refactorings/make_field_final.md | 2 +- docs/refactorings/make_field_non_final.md | 2 +- docs/refactorings/make_field_non_static.md | 2 +- docs/refactorings/make_field_static.md | 2 +- docs/refactorings/make_method_final.md | 2 +- docs/refactorings/make_method_non_final.md | 2 +- docs/refactorings/make_method_non_static.md | 4 +- docs/refactorings/make_method_static.md | 4 +- docs/refactorings/move_class.md | 2 +- docs/refactorings/move_field.md | 2 +- docs/refactorings/move_method.md | 2 +- docs/refactorings/pull_up_constructor.md | 2 +- docs/refactorings/pull_up_field.md | 2 +- docs/refactorings/pull_up_method.md | 2 +- docs/refactorings/push_down_field.md | 4 +- docs/refactorings/push_down_method.md | 4 +- docs/refactorings/rename_class.md | 4 +- docs/refactorings/rename_field.md | 2 +- docs/refactorings/rename_method.md | 4 +- docs/refactorings/rename_package.md | 2 +- docs/utilities/project_utils.md | 2 +- mkdocs.yml | 4 +- sbse/utils/__init__.py | 0 sbse/utils/input.txt | 48 - setup.py | 45 +- .../benchmark_projects_test/JSON/test_0.py | 2 +- .../benchmark_projects_test/JSON/test_1.py | 2 +- .../benchmark_projects_test/JSON/test_2.py | 2 +- .../benchmark_projects_test/JSON/test_3.py | 2 +- .../benchmark_projects_test/JSON/test_5.py | 2 +- .../benchmark_projects_test/xerces2-j/test.py | 2 +- .../java_file_equality_checker.py | 8 +- tests/extract_method/test_1.py | 12 +- tests/extract_method/test_2.py | 18 +- tests/extract_method/test_3.py | 3 +- tests/extract_method/test_4.py | 5 +- tests/extract_method/test_5.py | 5 +- tests/extract_method/test_6.py | 5 +- tests/extract_method/test_7.py | 5 +- 177 files changed, 1236 insertions(+), 1260 deletions(-) rename {sbse => codart}/config.py (94%) rename {gen => codart/gen}/__init__.py (100%) rename {gen => codart/gen}/java/JavaLexer.interp (100%) rename {gen => codart/gen}/java/JavaLexer.py (100%) rename {gen => codart/gen}/java/JavaLexer.tokens (100%) rename {gen => codart/gen}/java/JavaParser.interp (100%) rename {gen => codart/gen}/java/JavaParser.py (100%) rename {gen => codart/gen}/java/JavaParser.tokens (100%) rename {gen => codart/gen}/java/JavaParserListener.py (100%) rename {gen => codart/gen}/java/__init__.py (100%) rename {gen => codart/gen}/java9/Java9_v2.interp (100%) rename {gen => codart/gen}/java9/Java9_v2.tokens (100%) rename {gen => codart/gen}/java9/Java9_v2Lexer.interp (100%) rename {gen => codart/gen}/java9/Java9_v2Lexer.py (100%) rename {gen => codart/gen}/java9/Java9_v2Lexer.tokens (100%) rename {gen => codart/gen}/java9/Java9_v2Listener.py (100%) rename {gen => codart/gen}/java9/Java9_v2Parser.py (100%) rename {gen => codart/gen}/java9/Java9_v2Visitor.py (100%) rename {gen => codart/gen}/java9/__init__.py (100%) rename {gen => codart/gen}/javaLabeled/JavaLexer.interp (100%) rename {gen => codart/gen}/javaLabeled/JavaLexer.py (100%) rename {gen => codart/gen}/javaLabeled/JavaLexer.tokens (100%) rename {gen => codart/gen}/javaLabeled/JavaParserLabeled.interp (100%) rename {gen => codart/gen}/javaLabeled/JavaParserLabeled.py (100%) rename {gen => codart/gen}/javaLabeled/JavaParserLabeled.tokens (100%) rename {gen => codart/gen}/javaLabeled/JavaParserLabeledListener.py (100%) rename {gen => codart/gen}/javaLabeled/__init__.py (100%) rename {metrics => codart/metrics}/__init__.py (100%) rename {metrics => codart/metrics}/data_model/DS07012.csv (100%) rename {metrics => codart/metrics}/data_model/DS07310.csv (100%) rename {metrics => codart/metrics}/data_model/DS07410.csv (100%) rename {metrics => codart/metrics}/data_model/DS07510.csv (100%) rename {metrics => codart/metrics}/data_model/DS07610.csv (100%) rename {metrics => codart/metrics}/data_model/DS07710.csv (100%) rename {metrics => codart/metrics}/data_preparation_evo_suite_4.py (99%) rename {metrics => codart/metrics}/metrics_coverability.py (99%) rename {metrics => codart/metrics}/metrics_jcode_odor.py (99%) rename {metrics => codart/metrics}/metrics_names.py (100%) rename {metrics => codart/metrics}/modularity.py (99%) rename {metrics => codart/metrics}/qmood.py (99%) rename {metrics => codart/metrics}/source_code_metrics.py (100%) rename {metrics => codart/metrics}/testability_learning.py (100%) rename {metrics => codart/metrics}/testability_prediction.py (97%) rename {metrics => codart/metrics}/testability_prediction2.py (95%) rename {metrics => codart/metrics}/testability_prediction3.py (98%) rename {refactoring_design_patterns => codart/refactoring_design_patterns}/__init__.py (100%) rename {refactoring_design_patterns => codart/refactoring_design_patterns}/factory1.py (68%) rename {refactoring_design_patterns => codart/refactoring_design_patterns}/singleton1.py (79%) rename {refactoring_design_patterns => codart/refactoring_design_patterns}/strategy1.py (79%) rename {refactoring_design_patterns => codart/refactoring_design_patterns}/visitor1.py (67%) rename {refactorings => codart/refactorings}/__init__.py (100%) rename {refactorings => codart/refactorings}/collapse_hierarchy.py (98%) rename {refactorings => codart/refactorings}/dead_codes/__init__.py (100%) rename {refactorings => codart/refactorings}/dead_codes/main_forbig_project.py (94%) rename {refactorings => codart/refactorings}/dead_codes/main_omidvar.py (93%) rename {refactorings => codart/refactorings}/dead_codes/refactoring_action_module.py (97%) rename {refactorings => codart/refactorings}/dead_codes/refactoring_action_module_for_big_project.py (97%) rename {refactorings => codart/refactorings}/dead_codes/test.py (90%) rename {refactorings => codart/refactorings}/decrease_field_visibility.py (96%) rename {refactorings => codart/refactorings}/decrease_method_visibility.py (96%) rename {refactorings => codart/refactorings}/encapsulate_field.py (97%) rename {refactorings => codart/refactorings}/extract_class.py (98%) rename {refactorings => codart/refactorings}/extract_interface.py (98%) rename {refactorings => codart/refactorings}/extract_interface2.py (97%) rename {refactorings => codart/refactorings}/extract_method.py (98%) rename {refactorings => codart/refactorings}/extract_subclass.py (99%) rename {refactorings => codart/refactorings}/increase_field_visibility.py (96%) rename {refactorings => codart/refactorings}/increase_method_visibility.py (96%) rename {refactorings => codart/refactorings}/inline_class.py (99%) rename {refactorings => codart/refactorings}/make_class_abstract.py (97%) rename {refactorings => codart/refactorings}/make_class_concrete.py (97%) rename {refactorings => codart/refactorings}/make_class_final.py (93%) rename {refactorings => codart/refactorings}/make_class_non_final.py (95%) rename {refactorings => codart/refactorings}/make_field_final.py (94%) rename {refactorings => codart/refactorings}/make_field_non_final.py (94%) rename {refactorings => codart/refactorings}/make_field_non_static.py (95%) rename {refactorings => codart/refactorings}/make_field_static.py (95%) rename {refactorings => codart/refactorings}/make_method_final.py (94%) rename {refactorings => codart/refactorings}/make_method_non_final.py (94%) rename {refactorings => codart/refactorings}/make_method_non_static.py (97%) rename {refactorings => codart/refactorings}/make_method_non_static2.py (95%) rename {refactorings => codart/refactorings}/make_method_static.py (96%) rename {refactorings => codart/refactorings}/make_method_static2.py (95%) rename {refactorings => codart/refactorings}/move_class.py (98%) rename {refactorings => codart/refactorings}/move_field.py (97%) rename {refactorings => codart/refactorings}/move_method.py (98%) rename {refactorings => codart/refactorings}/pullup_constructor.py (98%) rename {refactorings => codart/refactorings}/pullup_field.py (99%) rename {refactorings => codart/refactorings}/pullup_method.py (98%) rename {refactorings => codart/refactorings}/pushdown_field.py (99%) rename {refactorings => codart/refactorings}/pushdown_field2.py (96%) rename {refactorings => codart/refactorings}/pushdown_method.py (98%) rename {refactorings => codart/refactorings}/pushdown_method2.py (97%) rename {refactorings => codart/refactorings}/remove_class.py (94%) rename {refactorings => codart/refactorings}/remove_dead_code.py (96%) rename {refactorings => codart/refactorings}/remove_field.py (94%) rename {refactorings => codart/refactorings}/remove_flag_argument.py (97%) rename {refactorings => codart/refactorings}/remove_interface.py (93%) rename {refactorings => codart/refactorings}/remove_method.py (94%) rename {refactorings => codart/refactorings}/rename_class.py (97%) rename {refactorings => codart/refactorings}/rename_class2.py (95%) rename {refactorings => codart/refactorings}/rename_field.py (96%) rename {refactorings => codart/refactorings}/rename_method.py (97%) rename {refactorings => codart/refactorings}/rename_method2.py (95%) rename {refactorings => codart/refactorings}/rename_package.py (95%) rename {refactorings => codart/refactorings}/replace_conditional_with_polymorphism.py (93%) rename {refactorings => codart/refactorings}/replace_constructor_with_factory_function.py (95%) rename {refactorings => codart/refactorings}/replace_exception_with_test.py (99%) rename {refactorings => codart/refactorings}/replace_parameter_with_query.py (97%) rename {refactorings => codart/refactorings}/replace_parameter_with_query2 .py (97%) rename {sbse => codart/sbse}/__init__.py (100%) rename {sbse => codart/sbse}/initialize.py (99%) rename {sbse => codart/sbse}/random_search.py (95%) rename {sbse => codart/sbse}/search_based_refactoring.py (98%) rename {sbse => codart/sbse}/search_based_refactoring2.py (99%) rename {sbse => codart/sbse}/sequence_application.py (95%) rename {sbse => codart/sbse}/simple_genetics.py (77%) delete mode 100644 sbse/utils/__init__.py delete mode 100644 sbse/utils/input.txt diff --git a/codart/codart_cli.py b/codart/codart_cli.py index bec08bad..a92fe5de 100644 --- a/codart/codart_cli.py +++ b/codart/codart_cli.py @@ -25,12 +25,11 @@ # from gen.java9.Java9_v2Parser import Java9_v2Parser # Old slow grammar parser # from java9speedy.parser import sa_java9_v2 # Old slow grammar enhanced by CPP backend -from gen.javaLabeled.JavaLexer import JavaLexer # Java8 grammar efficient lexer -from gen.javaLabeled.JavaParserLabeled import JavaParserLabeled # Java8 grammar efficient parser labeled +from codart.gen.javaLabeled.JavaLexer import JavaLexer # Java8 grammar efficient lexer +from codart.gen.javaLabeled.JavaParserLabeled import JavaParserLabeled # Java8 grammar efficient parser labeled # Import refactorings listeners -from refactorings.encapsulate_field import EncapsulateFiledRefactoringListener # CodART first refactoring :) -from refactorings.extract_class import ExtractClassRefactoringListener +from codart.refactorings.encapsulate_field import EncapsulateFiledRefactoringListener # CodART first refactoring :) def main(args): diff --git a/sbse/config.py b/codart/config.py similarity index 94% rename from sbse/config.py rename to codart/config.py index dea05549..323b2dfa 100644 --- a/sbse/config.py +++ b/codart/config.py @@ -52,6 +52,7 @@ 'jvlt-1.3.2', # 10 'tabula-java', # 11 'JHotDraw-7.0.6', # 12 + 'jhotdraw-6.0b1', # 13 ], # Understand DB Path @@ -82,6 +83,8 @@ 'tabula-java.und', # 'JHotDraw-7.0.6.udb', # 12 'JHotDraw-7.0.6.und', # 12 + # 'jhotdraw-6.0b1.udb', # 13 + 'jhotdraw-6.0b1.und', # 13 ], # CSV files path containing code smells identified by JDeodorant @@ -99,6 +102,7 @@ 'jVLT-1.3.2/Long-Method2_jvlt-1.3.2.csv', 'tabula-java/fake.csv', 'JHotDraw-7.0.6/Long-Method2_JHotDraw-7.0.6.csv', + 'jhotdraw-6.0b1/Long-Method2_jhotdraw-6.0b1.csv', ], 'FEATURE_ENVY': [ @@ -115,6 +119,7 @@ 'jVLT-1.3.2/Feature-Envy_jvlt-1.3.2.csv', 'tabula-java/Feature-Envy-Tabula-v1.0.6.csv', 'JHotDraw-7.0.6/Featuer-Envy2_JHotDraw-7.0.6.csv', + 'jhotdraw-6.0b1/Featuer-Envy2_jhotdraw-6.0b1.csv', ], 'GOD_CLASS': [ @@ -130,7 +135,8 @@ 'JSON20201115/God-Class_JASON-20201115.csv', 'jVLT-1.3.2/God-Class_jvlt-1.3.2.csv', 'tabula-java/God-Class-Tabula-v1.0.6.csv', - 'JHotDraw-7.0.6/God-Class_JHotDraw-7.0.6.csv' + 'JHotDraw-7.0.6/God-Class_JHotDraw-7.0.6.csv', + 'jhotdraw-6.0b1/God-Class_jhotdraw-6.0b1.csv', ], } @@ -353,6 +359,22 @@ 'TEST': 1., # Obtained by testability_prediction2 'TEST3': 1. # Obtained by testability_prediction3 }, + "jhotdraw-6.0b1": { # 13 + 'ANA': 1., + 'CAMC': 1., + 'CIS': 1., + 'DAM': 1., + 'DCC': 1., + 'DSC': 1., + 'MFA': 1., + 'MOA': 1., + 'NOH': 1., + 'NOM': 1., + 'NOP': 1., + 'MODULE': 1., + 'TEST': 1., # Obtained by testability_prediction2 + 'TEST3': 1. # Obtained by testability_prediction3 + }, } CURRENT_METRICS = INITIAL_METRICS.get(PROJECT_NAME) diff --git a/gen/__init__.py b/codart/gen/__init__.py similarity index 100% rename from gen/__init__.py rename to codart/gen/__init__.py diff --git a/gen/java/JavaLexer.interp b/codart/gen/java/JavaLexer.interp similarity index 100% rename from gen/java/JavaLexer.interp rename to codart/gen/java/JavaLexer.interp diff --git a/gen/java/JavaLexer.py b/codart/gen/java/JavaLexer.py similarity index 100% rename from gen/java/JavaLexer.py rename to codart/gen/java/JavaLexer.py diff --git a/gen/java/JavaLexer.tokens b/codart/gen/java/JavaLexer.tokens similarity index 100% rename from gen/java/JavaLexer.tokens rename to codart/gen/java/JavaLexer.tokens diff --git a/gen/java/JavaParser.interp b/codart/gen/java/JavaParser.interp similarity index 100% rename from gen/java/JavaParser.interp rename to codart/gen/java/JavaParser.interp diff --git a/gen/java/JavaParser.py b/codart/gen/java/JavaParser.py similarity index 100% rename from gen/java/JavaParser.py rename to codart/gen/java/JavaParser.py diff --git a/gen/java/JavaParser.tokens b/codart/gen/java/JavaParser.tokens similarity index 100% rename from gen/java/JavaParser.tokens rename to codart/gen/java/JavaParser.tokens diff --git a/gen/java/JavaParserListener.py b/codart/gen/java/JavaParserListener.py similarity index 100% rename from gen/java/JavaParserListener.py rename to codart/gen/java/JavaParserListener.py diff --git a/gen/java/__init__.py b/codart/gen/java/__init__.py similarity index 100% rename from gen/java/__init__.py rename to codart/gen/java/__init__.py diff --git a/gen/java9/Java9_v2.interp b/codart/gen/java9/Java9_v2.interp similarity index 100% rename from gen/java9/Java9_v2.interp rename to codart/gen/java9/Java9_v2.interp diff --git a/gen/java9/Java9_v2.tokens b/codart/gen/java9/Java9_v2.tokens similarity index 100% rename from gen/java9/Java9_v2.tokens rename to codart/gen/java9/Java9_v2.tokens diff --git a/gen/java9/Java9_v2Lexer.interp b/codart/gen/java9/Java9_v2Lexer.interp similarity index 100% rename from gen/java9/Java9_v2Lexer.interp rename to codart/gen/java9/Java9_v2Lexer.interp diff --git a/gen/java9/Java9_v2Lexer.py b/codart/gen/java9/Java9_v2Lexer.py similarity index 100% rename from gen/java9/Java9_v2Lexer.py rename to codart/gen/java9/Java9_v2Lexer.py diff --git a/gen/java9/Java9_v2Lexer.tokens b/codart/gen/java9/Java9_v2Lexer.tokens similarity index 100% rename from gen/java9/Java9_v2Lexer.tokens rename to codart/gen/java9/Java9_v2Lexer.tokens diff --git a/gen/java9/Java9_v2Listener.py b/codart/gen/java9/Java9_v2Listener.py similarity index 100% rename from gen/java9/Java9_v2Listener.py rename to codart/gen/java9/Java9_v2Listener.py diff --git a/gen/java9/Java9_v2Parser.py b/codart/gen/java9/Java9_v2Parser.py similarity index 100% rename from gen/java9/Java9_v2Parser.py rename to codart/gen/java9/Java9_v2Parser.py diff --git a/gen/java9/Java9_v2Visitor.py b/codart/gen/java9/Java9_v2Visitor.py similarity index 100% rename from gen/java9/Java9_v2Visitor.py rename to codart/gen/java9/Java9_v2Visitor.py diff --git a/gen/java9/__init__.py b/codart/gen/java9/__init__.py similarity index 100% rename from gen/java9/__init__.py rename to codart/gen/java9/__init__.py diff --git a/gen/javaLabeled/JavaLexer.interp b/codart/gen/javaLabeled/JavaLexer.interp similarity index 100% rename from gen/javaLabeled/JavaLexer.interp rename to codart/gen/javaLabeled/JavaLexer.interp diff --git a/gen/javaLabeled/JavaLexer.py b/codart/gen/javaLabeled/JavaLexer.py similarity index 100% rename from gen/javaLabeled/JavaLexer.py rename to codart/gen/javaLabeled/JavaLexer.py diff --git a/gen/javaLabeled/JavaLexer.tokens b/codart/gen/javaLabeled/JavaLexer.tokens similarity index 100% rename from gen/javaLabeled/JavaLexer.tokens rename to codart/gen/javaLabeled/JavaLexer.tokens diff --git a/gen/javaLabeled/JavaParserLabeled.interp b/codart/gen/javaLabeled/JavaParserLabeled.interp similarity index 100% rename from gen/javaLabeled/JavaParserLabeled.interp rename to codart/gen/javaLabeled/JavaParserLabeled.interp diff --git a/gen/javaLabeled/JavaParserLabeled.py b/codart/gen/javaLabeled/JavaParserLabeled.py similarity index 100% rename from gen/javaLabeled/JavaParserLabeled.py rename to codart/gen/javaLabeled/JavaParserLabeled.py diff --git a/gen/javaLabeled/JavaParserLabeled.tokens b/codart/gen/javaLabeled/JavaParserLabeled.tokens similarity index 100% rename from gen/javaLabeled/JavaParserLabeled.tokens rename to codart/gen/javaLabeled/JavaParserLabeled.tokens diff --git a/gen/javaLabeled/JavaParserLabeledListener.py b/codart/gen/javaLabeled/JavaParserLabeledListener.py similarity index 100% rename from gen/javaLabeled/JavaParserLabeledListener.py rename to codart/gen/javaLabeled/JavaParserLabeledListener.py diff --git a/gen/javaLabeled/__init__.py b/codart/gen/javaLabeled/__init__.py similarity index 100% rename from gen/javaLabeled/__init__.py rename to codart/gen/javaLabeled/__init__.py diff --git a/metrics/__init__.py b/codart/metrics/__init__.py similarity index 100% rename from metrics/__init__.py rename to codart/metrics/__init__.py diff --git a/metrics/data_model/DS07012.csv b/codart/metrics/data_model/DS07012.csv similarity index 100% rename from metrics/data_model/DS07012.csv rename to codart/metrics/data_model/DS07012.csv diff --git a/metrics/data_model/DS07310.csv b/codart/metrics/data_model/DS07310.csv similarity index 100% rename from metrics/data_model/DS07310.csv rename to codart/metrics/data_model/DS07310.csv diff --git a/metrics/data_model/DS07410.csv b/codart/metrics/data_model/DS07410.csv similarity index 100% rename from metrics/data_model/DS07410.csv rename to codart/metrics/data_model/DS07410.csv diff --git a/metrics/data_model/DS07510.csv b/codart/metrics/data_model/DS07510.csv similarity index 100% rename from metrics/data_model/DS07510.csv rename to codart/metrics/data_model/DS07510.csv diff --git a/metrics/data_model/DS07610.csv b/codart/metrics/data_model/DS07610.csv similarity index 100% rename from metrics/data_model/DS07610.csv rename to codart/metrics/data_model/DS07610.csv diff --git a/metrics/data_model/DS07710.csv b/codart/metrics/data_model/DS07710.csv similarity index 100% rename from metrics/data_model/DS07710.csv rename to codart/metrics/data_model/DS07710.csv diff --git a/metrics/data_preparation_evo_suite_4.py b/codart/metrics/data_preparation_evo_suite_4.py similarity index 99% rename from metrics/data_preparation_evo_suite_4.py rename to codart/metrics/data_preparation_evo_suite_4.py index ce3fa4f6..ffadba58 100644 --- a/metrics/data_preparation_evo_suite_4.py +++ b/codart/metrics/data_preparation_evo_suite_4.py @@ -7,38 +7,33 @@ To be used in CodART project """ -import multiprocessing + +__version__ = '0.4.0' +__author__ = 'Morteza' + import sys import os -import subprocess -import threading from collections import Counter -from functools import wraps import warnings -from deprecated import deprecated -import re import math -import matplotlib.pyplot as plt import pandas as pd import numpy as np from scipy import stats from sklearn import preprocessing from sklearn.feature_selection import SelectKBest -from sklearn.feature_selection import chi2, f_classif +from sklearn.feature_selection import f_classif from sklearn.decomposition import PCA -from sklearn.model_selection import StratifiedShuffleSplit, train_test_split +from sklearn.model_selection import train_test_split from sklearn.neighbors import LocalOutlierFactor -from sklearn.ensemble import IsolationForest from imblearn.combine import SMOTEENN, SMOTETomek -from imblearn.over_sampling import SMOTE, ADASYN # https://scitools.com/support/python-api/ # Python 3.8 and newer require the user add a call to os.add_dll_directory(“SciTools/bin/“ # os.add_dll_directory('C:/Program Files/SciTools/bin/pc-win64') -sys.path.insert(0, 'D:/program files/scitools/bin/pc-win64/python') +# sys.path.insert(0, 'D:/program files/scitools/bin/pc-win64/python') try: import understand except ModuleNotFoundError: @@ -47,13 +42,7 @@ from . import metrics_names from metrics_coverability import UnderstandUtility -from metrics.metrics_jcode_odor import JCodeOdorMetric -from metrics.source_code_metrics import * -import metrics.metrics_names - - -__version__ = '0.4.0' -__author__ = 'Morteza' +from codart.metrics.metrics_jcode_odor import JCodeOdorMetric def check_compute_metrics_by_class_list(project_name: str = None, database=None, class_list=None, diff --git a/metrics/metrics_coverability.py b/codart/metrics/metrics_coverability.py similarity index 99% rename from metrics/metrics_coverability.py rename to codart/metrics/metrics_coverability.py index 3b313192..9c2eebd6 100644 --- a/metrics/metrics_coverability.py +++ b/codart/metrics/metrics_coverability.py @@ -40,9 +40,9 @@ def NMO(cls, class_name): @classmethod def NIM(cls, class_name): declared_methods = 0 if class_name.metric(['CountDeclMethod'])['CountDeclMethod'] is None else \ - class_name.metric(['CountDeclMethod'])['CountDeclMethod'] + class_name.metric(['CountDeclMethod'])['CountDeclMethod'] all_methods = 0 if class_name.metric(['CountDeclMethodAll'])['CountDeclMethodAll'] is None else \ - class_name.metric(['CountDeclMethodAll'])['CountDeclMethodAll'] + class_name.metric(['CountDeclMethodAll'])['CountDeclMethodAll'] return all_methods - declared_methods @classmethod diff --git a/metrics/metrics_jcode_odor.py b/codart/metrics/metrics_jcode_odor.py similarity index 99% rename from metrics/metrics_jcode_odor.py rename to codart/metrics/metrics_jcode_odor.py index 60191a9b..c49d818e 100644 --- a/metrics/metrics_jcode_odor.py +++ b/codart/metrics/metrics_jcode_odor.py @@ -12,7 +12,7 @@ except ImportError as e: print(e) -from metrics.metrics_coverability import UnderstandUtility +from codart.metrics.metrics_coverability import UnderstandUtility class JCodeOdorMetric: diff --git a/metrics/metrics_names.py b/codart/metrics/metrics_names.py similarity index 100% rename from metrics/metrics_names.py rename to codart/metrics/metrics_names.py diff --git a/metrics/modularity.py b/codart/metrics/modularity.py similarity index 99% rename from metrics/modularity.py rename to codart/metrics/modularity.py index 7f8c25af..64d51cbb 100644 --- a/metrics/modularity.py +++ b/codart/metrics/modularity.py @@ -22,7 +22,6 @@ import os import re -import time from collections import defaultdict import pandas @@ -31,7 +30,7 @@ import understand -from sbse import config +from codart import config from codart.utility.directory_utils import export_understand_dependencies_csv diff --git a/metrics/qmood.py b/codart/metrics/qmood.py similarity index 99% rename from metrics/qmood.py rename to codart/metrics/qmood.py index 536ecd3b..394d872d 100644 --- a/metrics/qmood.py +++ b/codart/metrics/qmood.py @@ -13,7 +13,7 @@ import understand as und -from sbse import config +from codart import config def divide_by_initial_value(func): diff --git a/metrics/source_code_metrics.py b/codart/metrics/source_code_metrics.py similarity index 100% rename from metrics/source_code_metrics.py rename to codart/metrics/source_code_metrics.py diff --git a/metrics/testability_learning.py b/codart/metrics/testability_learning.py similarity index 100% rename from metrics/testability_learning.py rename to codart/metrics/testability_learning.py diff --git a/metrics/testability_prediction.py b/codart/metrics/testability_prediction.py similarity index 97% rename from metrics/testability_prediction.py rename to codart/metrics/testability_prediction.py index 20f2361a..88057557 100644 --- a/metrics/testability_prediction.py +++ b/codart/metrics/testability_prediction.py @@ -10,7 +10,7 @@ """ -__version__ = '0.1.1' +__version__ = '0.1.2' __author__ = 'Morteza Zakeri' import math @@ -18,9 +18,10 @@ import warnings import joblib +from joblib import Parallel, delayed import numpy as np import pandas as pd -from joblib import Parallel, delayed, wrap_non_picklable_objects + try: import understand as und @@ -31,11 +32,9 @@ from sklearn.model_selection import train_test_split from sklearn.preprocessing import QuantileTransformer -import metrics -from metrics import metrics_names -from metrics.metrics_jcode_odor import JCodeOdorMetric -from metrics.metrics_coverability import UnderstandUtility - +from codart.metrics.metrics_jcode_odor import JCodeOdorMetric +from codart.metrics.metrics_coverability import UnderstandUtility +from codart.metrics import metrics_names # patch_sklearn() @@ -52,19 +51,19 @@ class TestabilityMetrics: @classmethod def get_class_ordinary_metrics_names(cls) -> list: - return metrics.metrics_names.class_ordinary_metrics_names + return metrics_names.class_ordinary_metrics_names @classmethod def get_class_lexicon_metrics_names(cls) -> list: - return metrics.metrics_names.class_lexicon_metrics_names + return metrics_names.class_lexicon_metrics_names @classmethod def get_package_metrics_names(cls) -> list: - return metrics.metrics_names.package_metrics_names + return metrics_names.package_metrics_names @classmethod def get_project_metrics_names(cls) -> list: - return metrics.metrics_names.project_metrics_names + return metrics_names.project_metrics_names @classmethod def get_all_metrics_names(cls) -> list: @@ -92,13 +91,13 @@ def get_all_metrics_names(cls) -> list: @classmethod def get_all_primary_metrics_names(cls) -> list: primary_metrics_names = list() - for metric_name in metrics.metrics_names.project_metrics_names_primary: + for metric_name in metrics_names.project_metrics_names_primary: primary_metrics_names.append('PJ_' + metric_name) - for metric_name in metrics.metrics_names.package_metrics_names_primary: + for metric_name in metrics_names.package_metrics_names_primary: primary_metrics_names.append('PK_' + metric_name) - for metric_name in metrics.metrics_names.class_ordinary_metrics_names_primary: + for metric_name in metrics_names.class_ordinary_metrics_names_primary: primary_metrics_names.append('CSORD_' + metric_name) - for metric_name in metrics.metrics_names.class_lexicon_metrics_names: + for metric_name in metrics_names.class_lexicon_metrics_names: primary_metrics_names.append('CSLEX_' + metric_name) return primary_metrics_names @@ -497,7 +496,7 @@ def compute_java_class_metrics2(cls, db=None, entity=None): class_metrics.update({'FANIN': j_code_odor_metric.FANIN(db=db, class_entity=entity)}) class_metrics.update({'FANOUT': j_code_odor_metric.FANOUT(db=db, class_entity=entity)}) - class_metrics.update({'ATFD': UnderstandUtility.ATFD(db=db, class_entity=entity)}) ### not implement + class_metrics.update({'ATFD': UnderstandUtility.ATFD(db=db, class_entity=entity)}) # Not implemented class_metrics.update({'CFNAMM': j_code_odor_metric.CFNAMM_Class(class_name=entity)}) class_metrics.update({'DAC': UnderstandUtility.get_data_abstraction_coupling(db=db, class_entity=entity)}) @@ -735,8 +734,9 @@ def compute_java_package_metrics(cls, db=None, class_name: str = None): package_metrics.update({'SDLineCodeDecl': np.std(pk_loc_decl_list)}) package_metrics.update({'SDLineCodeExe': np.std(pk_loc_exe_list)}) except: - raise TypeError('Error happen when compute packege metric for class "{0}" and list "{1}"'.format(class_name, - pk_loc_decl_list)) + raise TypeError( + f'Error happen when compute packege metric for class "{class_name}" and list "{pk_loc_decl_list}"' + ) # 2.2 PKNOS (15) pk_stmt_list = list() @@ -1161,7 +1161,7 @@ def compute_metrics_for_single_class(cls, class_name, und_path, result_csv): all_class_metrics_value.append(one_class_metrics_value) columns = ['Class'] columns.extend(TestabilityMetrics.get_all_metrics_names()) - columns2 = [metrics.metrics_names.metric_map[c_] for c_ in columns[:-1]] + columns2 = [metrics_names.metric_map[c_] for c_ in columns[:-1]] columns2.append('NOCLINFILE') df = pd.DataFrame(data=all_class_metrics_value, columns=columns2) df.drop(columns=['NOCLINFILE'], inplace=True) @@ -1237,8 +1237,8 @@ def main(project_path, initial_value=1.0): # classes_longnames_list = p.extract_project_classes(db=db) df = p.compute_metrics_by_class_list(project_path, n_jobs=7) # n_job must be set to number of CPU cores # db.close() - model = TestabilityModel(df_path=r'../metrics/data_model/DS07012.csv') - testability_ = model.inference(model_path='../metrics/data_model/VR1_DS1.joblib', df_predict_data=df) + model = TestabilityModel(df_path=r'data_model/DS07012.csv') + testability_ = model.inference(model_path='/data_model/VR1_DS1.joblib', df_predict_data=df) # print('testability=', testability_) return testability_ / initial_value diff --git a/metrics/testability_prediction2.py b/codart/metrics/testability_prediction2.py similarity index 95% rename from metrics/testability_prediction2.py rename to codart/metrics/testability_prediction2.py index ec3fc001..46d99e28 100644 --- a/metrics/testability_prediction2.py +++ b/codart/metrics/testability_prediction2.py @@ -29,13 +29,14 @@ import understand as und -from sbse import config -from metrics import metrics_names -from metrics.metrics_coverability import UnderstandUtility - +from codart import config +from codart.metrics import metrics_names +from codart.metrics.metrics_coverability import UnderstandUtility scaler1 = joblib.load(os.path.join(os.path.dirname(__file__), 'data_model/DS07510.joblib')) model5 = joblib.load(os.path.join(os.path.dirname(__file__), 'sklearn_models7/VR1_DS5.joblib')) +model_branch = joblib.load(os.path.join(os.path.dirname(__file__), 'sklearn_models6/VR6_DS5_branch.joblib')) +model_line = joblib.load(os.path.join(os.path.dirname(__file__), 'sklearn_models6/VR6_DS5_line.joblib')) class TestabilityMetrics: @@ -143,6 +144,7 @@ def compute_java_class_metrics_lexicon(cls, entity=None): entity (understand.Ent): Returns: + dict: class-level metrics """ @@ -172,7 +174,7 @@ def compute_java_class_metrics_lexicon(cls, entity=None): super_count_kw_list = ['super'] dots_count = 0 - + # print(entity.longname()) lexeme = entity.lexer(show_inactive=False).first() while lexeme is not None: tokens_list.append(lexeme.text()) @@ -277,7 +279,7 @@ def compute_java_class_metrics2(cls, db=None, entity=None): class_metrics.update({'FANIN': UnderstandUtility.FANIN(db=db, class_entity=entity)}) class_metrics.update({'FANOUT': UnderstandUtility.FANOUT(db=db, class_entity=entity)}) - class_metrics.update({'ATFD': UnderstandUtility.ATFD(db=db, class_entity=entity)}) ### not implement + class_metrics.update({'ATFD': UnderstandUtility.ATFD(db=db, class_entity=entity)}) # Not implement class_metrics.update({'CFNAMM': UnderstandUtility.CFNAMM_Class(class_name=entity)}) class_metrics.update({'DAC': UnderstandUtility.get_data_abstraction_coupling(db=db, class_entity=entity)}) @@ -394,18 +396,28 @@ class TestabilityModel: Testability prediction model """ + def __init__(self, ): self.scaler = scaler1 self.model = model5 + self.model_branch = model_branch + self.model_line = model_line def inference(self, df_predict_data=None, verbose=False, log_path=None): df_predict_data = df_predict_data.fillna(0) X_test1 = df_predict_data.iloc[:, 1:] X_test = self.scaler.transform(X_test1) y_pred = self.model.predict(X_test) + + y_pred_branch = self.model_branch.predict(X_test) + y_pred_line = self.model_line.predict(X_test) + df_new = pd.DataFrame(df_predict_data.iloc[:, 0], columns=['Class']) df_new['PredictedTestability'] = list(y_pred) + df_new['BranchCoverage'] = list(y_pred_branch) + df_new['LineCoverage'] = list(y_pred_line) + if verbose: self.export_class_testability_values(df=df_new, log_path=log_path) @@ -423,7 +435,7 @@ def export_class_testability_values(cls, df=None, log_path=None): config.logger.info(f'maximum testability2\t {df["PredictedTestability"].max()}') config.logger.info(f'variance testability2\t {df["PredictedTestability"].var()}') config.logger.info(f'sum classes testability2\t, {df["PredictedTestability"].sum()}') - config.logger.info('-'*50) + config.logger.info('-' * 50) df.to_csv(log_path, index=False) @@ -436,7 +448,10 @@ def main(project_db_path, initial_value=1.0, verbose=False, log_path=None): """ - df = PreProcess().compute_metrics_by_class_list(project_db_path, n_jobs=0) # n_job must be set to number of CPU cores + df = PreProcess().compute_metrics_by_class_list( + project_db_path, + n_jobs=0 # n_job must be set to number of CPU cores, use zero for non-parallel computing of metrics + ) testability_ = TestabilityModel().inference(df_predict_data=df, verbose=verbose, log_path=log_path) # print('testability=', testability_) return round(testability_ / initial_value, 5) diff --git a/metrics/testability_prediction3.py b/codart/metrics/testability_prediction3.py similarity index 98% rename from metrics/testability_prediction3.py rename to codart/metrics/testability_prediction3.py index c88cd303..29b415c7 100644 --- a/metrics/testability_prediction3.py +++ b/codart/metrics/testability_prediction3.py @@ -15,7 +15,7 @@ import understand as und -from sbse import config +from codart import config scaler1 = joblib.load(os.path.join(os.path.dirname(__file__), 'data_model/DS07710.joblib')) model5 = joblib.load(os.path.join(os.path.dirname(__file__), 'sklearn_models7/VR1_DS7.joblib')) @@ -95,7 +95,7 @@ def inference(self, verbose=False, log_path=None): df_new['PredictedTestability'] = list(y_pred) if verbose: - self.export_class_testability_values(df=df_new,log_path=log_path) + self.export_class_testability_values(df=df_new, log_path=log_path) return df_new['PredictedTestability'].sum() # Return sum instead mean @classmethod diff --git a/refactoring_design_patterns/__init__.py b/codart/refactoring_design_patterns/__init__.py similarity index 100% rename from refactoring_design_patterns/__init__.py rename to codart/refactoring_design_patterns/__init__.py diff --git a/refactoring_design_patterns/factory1.py b/codart/refactoring_design_patterns/factory1.py similarity index 68% rename from refactoring_design_patterns/factory1.py rename to codart/refactoring_design_patterns/factory1.py index 319a36f1..77619a90 100644 --- a/refactoring_design_patterns/factory1.py +++ b/codart/refactoring_design_patterns/factory1.py @@ -6,16 +6,14 @@ __version__ = '1.0.0' __author__ = 'Morteza Zakeri' -import os -import time import argparse from antlr4 import * from antlr4.TokenStreamRewriter import TokenStreamRewriter -from gen.javaLabeled.JavaLexer import JavaLexer -from gen.javaLabeled.JavaParserLabeled import JavaParserLabeled -from gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener +from codart.gen.javaLabeled.JavaLexer import JavaLexer +from codart.gen.javaLabeled.JavaParserLabeled import JavaParserLabeled +from codart.gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener class FactoryMethodRefactoringListener(JavaParserLabeledListener): @@ -48,7 +46,6 @@ def enterClassDeclaration(self, ctx: JavaParserLabeled.ClassDeclarationContext): self.CretorStartIndex = ctx.classBody().start.tokenIndex self.currentClass = ctx.IDENTIFIER().symbol.text - elif ctx.IDENTIFIER().getText() in self.products_identifier: self.inProducts = True self.productsClassIndex.append(ctx.IDENTIFIER().symbol.tokenIndex) @@ -59,71 +56,75 @@ def exitClassDeclaration(self, ctx: JavaParserLabeled.ClassDeclarationContext): self.inProducts = False def enterMethodDeclaration(self, ctx: JavaParserLabeled.MethodDeclarationContext): - if self.inProducts == True: - methodModifire = ctx.parentCtx.parentCtx.start.text - if methodModifire == 'public': - MethodText = self.token_stream_rewriter.getText( + if self.inProducts: + method_modifier = ctx.parentCtx.parentCtx.start.text + if method_modifier == 'public': + method_text = self.token_stream_rewriter.getText( program_name=self.token_stream_rewriter.DEFAULT_PROGRAM_NAME, start=ctx.parentCtx.parentCtx.start.tokenIndex, stop=ctx.formalParameters().RPAREN().symbol.tokenIndex) + ";" - if MethodText not in self.productsMethod: - self.productsMethod[MethodText] = [self.currentClass] + if method_text not in self.productsMethod: + self.productsMethod[method_text] = [self.currentClass] else: - self.productsMethod[MethodText].append(self.currentClass) + self.productsMethod[method_text].append(self.currentClass) def enterLocalVariableDeclaration(self, ctx: JavaParserLabeled.LocalVariableDeclarationContext): - if self.inCreator == True: - variableType = ctx.typeType().classOrInterfaceType().IDENTIFIER(0) - if variableType.symbol.text in self.products_identifier: - self.productVarTypeIndex.append(variableType.symbol.tokenIndex) - self.productVarValueIndex.append([variableType.symbol.text, + if self.inCreator: + variable_type = ctx.typeType().classOrInterfaceType().IDENTIFIER(0) + if variable_type.symbol.text in self.products_identifier: + self.productVarTypeIndex.append(variable_type.symbol.tokenIndex) + self.productVarValueIndex.append([variable_type.symbol.text, ctx.variableDeclarators().variableDeclarator( 0).ASSIGN().symbol.tokenIndex, ctx.stop.tokenIndex]) def enterFieldDeclaration(self, ctx: JavaParserLabeled.FieldDeclarationContext): - if self.inCreator == True: - variableType = ctx.typeType().classOrInterfaceType().IDENTIFIER(0) - if variableType.symbol.text in self.products_identifier: - self.productVarTypeIndex.append(variableType.symbol.tokenIndex) - self.productVarValueIndex.append([variableType.symbol.text, + if self.inCreator: + variable_type = ctx.typeType().classOrInterfaceType().IDENTIFIER(0) + if variable_type.symbol.text in self.products_identifier: + self.productVarTypeIndex.append(variable_type.symbol.tokenIndex) + self.productVarValueIndex.append([variable_type.symbol.text, ctx.variableDeclarators().variableDeclarator( 0).ASSIGN().symbol.tokenIndex, ctx.stop.tokenIndex]) def enterConstructorDeclaration(self, ctx: JavaParserLabeled.ConstructorDeclarationContext): - if self.inProducts == True: - Parameter = "" + if self.inProducts: + parameters = "" if ctx.formalParameters().children.__len__() > 0: - ParamChild = ctx.formalParameters().children[1] - for i in range(0, ParamChild.children.__len__(), 2): - Parameter += ParamChild.children[i].stop.text + "," - Parameter = Parameter[:-1] + param_child = ctx.formalParameters().children[1] + for i in range(0, param_child.children.__len__(), 2): + parameters += param_child.children[i].stop.text + "," + parameters = parameters[:-1] - self.productConstructorParam[self.currentClass] = Parameter + self.productConstructorParam[self.currentClass] = parameters - ParamList = self.token_stream_rewriter.getText(program_name=self.token_stream_rewriter.DEFAULT_PROGRAM_NAME, - start=ctx.formalParameters().LPAREN().symbol.tokenIndex, - stop=ctx.formalParameters().RPAREN().symbol.tokenIndex) + param_list = self.token_stream_rewriter.getText( + program_name=self.token_stream_rewriter.DEFAULT_PROGRAM_NAME, + start=ctx.formalParameters().LPAREN().symbol.tokenIndex, + stop=ctx.formalParameters().RPAREN().symbol.tokenIndex + ) - Method = "\t" + self.interfaceName + " create" + \ - self.currentClass + ParamList + \ - "{\n\t\t" + "return new " + self.currentClass + "(" + Parameter + ");\n\t}\n" + method_body = ( + "\t" + self.interfaceName + " create" + + self.currentClass + param_list + + "{\n\t\t" + "return new " + self.currentClass + "(" + parameters + ");\n\t}\n" + ) - self.productConstructorMethod.append(Method) + self.productConstructorMethod.append(method_body) def exitCompilationUnit(self, ctx: JavaParserLabeled.CompilationUnitContext): # InterfaceChecked - interfaceMethodList = [] + interface_method_list = [] for key, value in self.productsMethod.items(): if sorted(value) == sorted(self.products_identifier): - interfaceMethodList.append(key) - if interfaceMethodList.__len__() > 0: - intefaceText = "public interface " + self.interfaceName + "{" - for item in interfaceMethodList: - intefaceText += "\n\t" + item - intefaceText += "\n}\n\n" + interface_method_list.append(key) + if interface_method_list.__len__() > 0: + inteface_text = "public interface " + self.interfaceName + "{" + for item in interface_method_list: + inteface_text += "\n\t" + item + inteface_text += "\n}\n\n" self.token_stream_rewriter.insertBefore(program_name=self.token_stream_rewriter.DEFAULT_PROGRAM_NAME, index=1, - text=intefaceText) + text=inteface_text) for item in self.productsClassIndex: self.token_stream_rewriter.insertAfter(program_name=self.token_stream_rewriter.DEFAULT_PROGRAM_NAME, @@ -142,12 +143,12 @@ def exitCompilationUnit(self, ctx: JavaParserLabeled.CompilationUnitContext): text="create" + item[0] + " (" + self.productConstructorParam[item[0]] + ")") - newProductMethod = "\n" + new_product_method = "\n" for item in self.productConstructorMethod: - newProductMethod += item + new_product_method += item self.token_stream_rewriter.insertAfter(program_name=self.token_stream_rewriter.DEFAULT_PROGRAM_NAME, index=self.CretorStartIndex, - text=newProductMethod) + text=new_product_method) def main(args): @@ -171,7 +172,7 @@ def main(args): walker = ParseTreeWalker() walker.walk(t=parse_tree, listener=my_listener) - with open('../tests/factory1/FactoryExample.refactored.java', mode='w', newline='') as f: + with open('../../tests/factory1/FactoryExample.refactored.java', mode='w', newline='') as f: f.write(my_listener.token_stream_rewriter.getDefaultText()) @@ -181,5 +182,5 @@ def main(args): argparser.add_argument( '-n', '--file', help='Input source', default=r'FactoryExample.java') - args = argparser.parse_args() - main(args) + args_ = argparser.parse_args() + main(args_) diff --git a/refactoring_design_patterns/singleton1.py b/codart/refactoring_design_patterns/singleton1.py similarity index 79% rename from refactoring_design_patterns/singleton1.py rename to codart/refactoring_design_patterns/singleton1.py index 9c813ef8..6f7576f6 100644 --- a/refactoring_design_patterns/singleton1.py +++ b/codart/refactoring_design_patterns/singleton1.py @@ -4,21 +4,19 @@ """ __version__ = '1.0.0' -__author__ = 'Morteza Zakeri' +__author__ = 'Morteza Zakeri, Morteza Zakeri' import os import time import argparse from shutil import copy2 - from antlr4 import * from antlr4.TokenStreamRewriter import TokenStreamRewriter -from gen.javaLabeled.JavaLexer import JavaLexer -from gen.javaLabeled.JavaParserLabeled import JavaParserLabeled -from gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener - +from codart.gen.javaLabeled.JavaLexer import JavaLexer +from codart.gen.javaLabeled.JavaParserLabeled import JavaParserLabeled +from codart.gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener class SingletonRefactoringListener(JavaParserLabeledListener): @@ -45,33 +43,35 @@ def enterClassDeclaration(self, ctx: JavaParserLabeled.ClassDeclarationContext): self.addInstance = True def exitClassDeclaration(self, ctx: JavaParserLabeled.ClassDeclarationContext): - if self.enter_class == True: + if self.enter_class: self.enter_class = False - new_code = "\n\tpublic static " + self.class_identifier + " getInstance()\n\t{\n\t\tif (Instance == null)" \ - "\n\t\t\tInstance = new " + self.class_identifier + "();" \ - "\n\t\treturn Instance;\n\t}\n" + new_code = ( + "\n\tpublic static " + + self.class_identifier + + " getInstance()\n\t{\n\t\tif (Instance == null)" + + "\n\t\t\tInstance = new " + self.class_identifier + "();" + + "\n\t\treturn Instance;\n\t}\n" + ) self.token_stream_rewriter.insertAfter(ctx.stop.tokenIndex - 1, new_code) def enterConstructorDeclaration(self, ctx: JavaParserLabeled.ConstructorDeclarationContext): - if self.enter_class == True: - constructorModifier = ctx.parentCtx.parentCtx - if constructorModifier.start.text == 'public': + if self.enter_class: + constructor_modifier = ctx.parentCtx.parentCtx + if constructor_modifier.start.text == 'public': self.token_stream_rewriter.replaceRange( - from_idx=constructorModifier.start.tokenIndex, - to_idx=constructorModifier.start.tokenIndex, + from_idx=constructor_modifier.start.tokenIndex, + to_idx=constructor_modifier.start.tokenIndex, text='private') def enterFieldDeclaration(self, ctx: JavaParserLabeled.FieldDeclarationContext): - if self.enter_class == False: - A = ctx.parentCtx.parentCtx - B = ctx.variableDeclarators() + if not self.enter_class: if ctx.start.text == self.class_identifier: start = ctx.variableDeclarators().variableDeclarator(0).ASSIGN().symbol.tokenIndex + 1 end = ctx.stop.tokenIndex self.ObjectIndex.append([start, end]) def enterLocalVariableDeclaration(self, ctx: JavaParserLabeled.LocalVariableDeclarationContext): - if self.enter_class == False: + if not self.enter_class: if ctx.start.text == self.class_identifier: start = ctx.variableDeclarators().variableDeclarator(0).ASSIGN().symbol.tokenIndex + 1 end = ctx.stop.tokenIndex @@ -84,9 +84,7 @@ def exitCompilationUnit(self, ctx: JavaParserLabeled.CompilationUnitContext): text=" " + self.class_identifier + ".getInstance()") - - -def main(args, i): +def main(args): # Step 1: Load input source into stream stream = FileStream(args.file, encoding='utf8', errors='ignore') # Step 2: Create an instance of AssignmentStLexer @@ -118,9 +116,8 @@ def main(args, i): if __name__ == '__main__': start_time = time.time() ProgramPath = r"." - i = 0 - for root, d, f in os.walk(ProgramPath): - for file in f: + for root, d, files in os.walk(ProgramPath): + for file in files: if file.endswith(".java"): try: FilePath = os.path.join(root, file) @@ -128,8 +125,8 @@ def main(args, i): argparser = argparse.ArgumentParser() argparser.add_argument( '-n', '--file', default=FilePath) - args = argparser.parse_args() - main(args, i) + args_ = argparser.parse_args() + main(args_) except: print("Error: ", os.path.join(root, file)) else: diff --git a/refactoring_design_patterns/strategy1.py b/codart/refactoring_design_patterns/strategy1.py similarity index 79% rename from refactoring_design_patterns/strategy1.py rename to codart/refactoring_design_patterns/strategy1.py index 8ffc4ed6..74de1543 100644 --- a/refactoring_design_patterns/strategy1.py +++ b/codart/refactoring_design_patterns/strategy1.py @@ -3,21 +3,18 @@ """ __version__ = '1.4.2' -__author__ = 'Nader Mesbah' +__author__ = 'Nader Mesbah, Morteza Zakeri' __date__ = '20210108' -import os import argparse -import datetime from time import time - from antlr4 import * from antlr4.TokenStreamRewriter import TokenStreamRewriter -from gen.javaLabeled.JavaLexer import JavaLexer -from gen.javaLabeled.JavaParserLabeled import JavaParserLabeled -from gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener +from codart.gen.javaLabeled.JavaLexer import JavaLexer +from codart.gen.javaLabeled.JavaParserLabeled import JavaParserLabeled +from codart.gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener class StrategyPatternRefactoringListener(JavaParserLabeledListener): @@ -70,24 +67,28 @@ def enterMethodDeclaration(self, ctx: JavaParserLabeled.MethodDeclarationContext self.old_method_Declaration = self.old_method_Declaration.replace(self.method_identifier, "doOperation") def enterStatement2(self, ctx: JavaParserLabeled.Statement2Context): - if self.method_selected == True: + if self.method_selected: self.ifelse = True self.para = ctx.parExpression().expression().getText().split('==') # Define new concrete strategy as subclass of strategy - newSubClass = "\nclass SubNewClass" + str(self.currentClass) + " implements MyStrategy{\n\t" + \ - "@Override\n\t" + self.old_method_Declaration + "\n\t" + new_sub_class = ("\nclass SubNewClass" + + str(self.currentClass) + + " implements MyStrategy{\n\t" + + "@Override\n\t" + self.old_method_Declaration + + "\n\t" + ) body = self.token_stream_rewriter.getText("", ctx.statement(0).block().start.tokenIndex, ctx.statement(0).block().stop.tokenIndex) # Make body for new subclass if body[0] != "{": body = "{" + body + "}" - self.newClasses += newSubClass + body + "\n}" + self.newClasses += new_sub_class + body + "\n}" self.currentClass += 1 def exitClassDeclaration(self, ctx: JavaParserLabeled.ClassDeclarationContext): - if self.enter_method == True: - if self.ifelse == True and self.inputPara == True: + if self.enter_method: + if self.ifelse and self.inputPara: # Create new class(Create an interface of strategy class named MyStrategy) self.interface = "\ninterface MyStrategy {\n\t" + self.new_method_Declaration + ";\n}" self.newClasses = self.newClasses.replace(self.old_method_Declaration, self.new_method_Declaration) @@ -97,15 +98,15 @@ def exitClassDeclaration(self, ctx: JavaParserLabeled.ClassDeclarationContext): self.enter_class = False def enterFormalParameter(self, ctx: JavaParserLabeled.FormalParameterContext): - if self.method_selected == True: + if self.method_selected: self.inputPara = True self.oldPara.append(ctx.typeType().getText() + " " + ctx.variableDeclaratorId().getText()) self.typePara.append(ctx.typeType().getText()) def exitMethodDeclaration(self, ctx: JavaParserLabeled.MethodDeclarationContext): - if self.method_selected == True: + if self.method_selected: # Make new method declaration - if self.ifelse == True and self.inputPara == True: + if self.ifelse and self.inputPara: self.newPara = [] for item in self.oldPara: if not item.endswith(str(self.para[0])): @@ -113,21 +114,25 @@ def exitMethodDeclaration(self, ctx: JavaParserLabeled.MethodDeclarationContext) self.newPara = ', '.join(self.newPara) LPRANindex = self.old_method_Declaration.index('(') self.new_method_Declaration = self.old_method_Declaration[:LPRANindex] + "(" + self.newPara + ")" - newName = self.old_method_Declaration.replace("doOperation", self.method_identifier + "Strategy") + new_name = self.old_method_Declaration.replace("doOperation", self.method_identifier + "Strategy") temp1 = ', '.join(self.oldPara) temp1 = "(" + temp1 + ")" temp2 = "(" + self.newPara + ")" - newName = newName.replace(temp1, temp2) + new_name = new_name.replace(temp1, temp2) for item in self.typePara: self.newPara = self.newPara.replace(item, "") # Modify original class - newbody = " private MyStrategy strategy;\n" \ - "\tpublic " + self.class_identifier + "(MyStrategy strategy){\n" \ - "\t\tthis.strategy = strategy;\n" \ - "\t}\n" \ - "\t" + newName + "{\n" \ - "\t\treturn strategy.doOperation(" + self.newPara + ");\n" \ - "\t}" + newbody = ( + " private MyStrategy strategy;\n" + + "\tpublic " + + self.class_identifier + + "(MyStrategy strategy){\n" + + "\t\tthis.strategy = strategy;\n" + + "\t}\n" + "\t" + new_name + "{\n" + + "\t\treturn strategy.doOperation(" + + self.newPara + ");\n" + + "\t}" + ) self.token_stream_rewriter.replaceRange( ctx.parentCtx.parentCtx.start.tokenIndex, @@ -165,7 +170,7 @@ def main(args): print('Compiler result:') print(my_listener.token_stream_rewriter.getDefaultText()) - with open('../tests/strategy1/StrategyExample0.refactored.java', mode='w', newline='') as f: + with open('../../tests/strategy1/StrategyExample0.refactored.java', mode='w', newline='') as f: # with open('StrategyExample1.refactored.java', mode='w', newline='') as f: # with open('StrategyExample2.refactored.java', mode='w', newline='') as f: f.write(my_listener.token_stream_rewriter.getDefaultText()) @@ -182,5 +187,5 @@ def main(args): help='Input source', default=r'StrategyExample0.java') # help = 'Input source', default = r'StrategyExample1.java') # help = 'Input source', default = r'StrategyExample2.java') - args = argparser.parse_args() - main(args) + args_ = argparser.parse_args() + main(args_) diff --git a/refactoring_design_patterns/visitor1.py b/codart/refactoring_design_patterns/visitor1.py similarity index 67% rename from refactoring_design_patterns/visitor1.py rename to codart/refactoring_design_patterns/visitor1.py index 0a98e092..58625250 100644 --- a/refactoring_design_patterns/visitor1.py +++ b/codart/refactoring_design_patterns/visitor1.py @@ -2,7 +2,7 @@ The script implements automated refactoring to visitor design pattern """ __version__ = '1.4.2' -__author__ = 'Nader Mesbah' +__author__ = 'Nader Mesbah, Morteza Zakeri' __date__ = '20210108' import argparse @@ -11,9 +11,9 @@ from antlr4 import * from antlr4.TokenStreamRewriter import TokenStreamRewriter -from gen.javaLabeled.JavaLexer import JavaLexer -from gen.javaLabeled.JavaParserLabeled import JavaParserLabeled -from gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener +from codart.gen.javaLabeled.JavaLexer import JavaLexer +from codart.gen.javaLabeled.JavaParserLabeled import JavaParserLabeled +from codart.gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener class VisitorPatternRefactoringListener(JavaParserLabeledListener): @@ -56,31 +56,41 @@ def enterClassDeclaration(self, ctx: JavaParserLabeled.ClassDeclarationContext): self.token_stream_rewriter.deleteIndex(ctx.start.tokenIndex + 4) def exitClassDeclaration(self, ctx: JavaParserLabeled.ClassDeclarationContext): - if self.InSuperClass == True: + if self.InSuperClass: # SuperClass Interface Make - InterfaceText = "interface " + self.SuperClass_identifier + "\n{\n\tpublic void accept (Visitor" \ - + self.SuperClass_identifier + " visitor);\n}" - self.token_stream_rewriter.insertAfter(ctx.start.tokenIndex - 1, "\n" + InterfaceText + "\n") + interface_text = ( + "interface " + + self.SuperClass_identifier + + "\n{\n\tpublic void accept (Visitor" + + self.SuperClass_identifier + + " visitor);\n}" + ) + self.token_stream_rewriter.insertAfter(ctx.start.tokenIndex - 1, "\n" + interface_text + "\n") # SuperClass Visitor interface Make - InterfaceTextVistor = "interface Visitor" + self.SuperClass_identifier + "\n{" + interface_text_vistor = "interface Visitor" + self.SuperClass_identifier + "\n{" index = 0 for item in self.Visitors: - InterfaceTextVistor += "\n\t" + "public void " + "visit(" + self.SubClass_identifier[ + interface_text_vistor += "\n\t" + "public void " + "visit(" + self.SubClass_identifier[ index] + " " + item + ");" index += 1 - InterfaceTextVistor += "\n}" - self.token_stream_rewriter.insertAfter(ctx.start.tokenIndex - 1, "\n" + InterfaceTextVistor + "\n") + interface_text_vistor += "\n}" + self.token_stream_rewriter.insertAfter(ctx.start.tokenIndex - 1, "\n" + interface_text_vistor + "\n") # SuperClass DoVisitor Make - newSC = "\nclass DoVisitor" + self.SuperClass_identifier + " implements Visitor" + self.SuperClass_identifier + "\n{" - methodbody = "" + newSC = ( + "\nclass DoVisitor" + + self.SuperClass_identifier + + " implements Visitor" + + self.SuperClass_identifier + "\n{" + ) + method_body = "" index = 0 # SuperClassDoVisitor Mathods Make for item in self.Visitors: - methodbody = str_list(self.Visitors[item]) - methodbody = "{\n\t" + methodbody[2:-2] + "\n\t}" + method_body = str_list(self.Visitors[item]) + method_body = "{\n\t" + method_body[2:-2] + "\n\t}" newSC += "\n\t" + "@Override\n\tpublic void visit(" + self.SubClass_identifier[ - index] + " " + item + ")\n\t" + methodbody + index] + " " + item + ")\n\t" + method_body index += 1 newSC += "\n}" self.token_stream_rewriter.replaceRange(ctx.start.tokenIndex, ctx.stop.tokenIndex, newSC) @@ -90,20 +100,23 @@ def exitClassDeclaration(self, ctx: JavaParserLabeled.ClassDeclarationContext): def enterMethodDeclaration(self, ctx: JavaParserLabeled.MethodDeclarationContext): # Extract Methods Name & Methods body of SuperClass - if self.InSuperClass == True: - newClassName = ctx.IDENTIFIER().getText() - newMethodBody = ctx.methodBody().getText() - self.Visitors[newClassName] = [newMethodBody] + if self.InSuperClass: + new_class_name = ctx.IDENTIFIER().getText() + new_method_body = ctx.methodBody().getText() + self.Visitors[new_class_name] = [new_method_body] def exitClassBody(self, ctx: JavaParserLabeled.ClassBodyContext): - if self.InSubClass == True: + if self.InSubClass: # Implement Mathod of SuperClass InterFace - OverrideText = "@Override\n\tpublic void accept(Visitor" + self.SuperClass_identifier + \ - " visitor)\n\t{\n\t\tvisitor.visit(this);\n\t}" - self.token_stream_rewriter.insertAfter(ctx.start.tokenIndex, "\n\t" + OverrideText) + override_text = ( + "@Override\n\tpublic void accept(Visitor" + + self.SuperClass_identifier + + " visitor)\n\t{\n\t\tvisitor.visit(this);\n\t}" + ) + self.token_stream_rewriter.insertAfter(ctx.start.tokenIndex, "\n\t" + override_text) def enterMethodCall0(self, ctx: JavaParserLabeled.MethodCall0Context): - if self.InMainClass == True: + if self.InMainClass: # Modify Main Method if ctx.IDENTIFIER().getText() in self.Visitors: self.token_stream_rewriter.replaceRange( @@ -130,21 +143,22 @@ def main(args): # Step 5: Create parse tree parse_tree = parser.compilationUnit() # Step 6: Create an instance of the refactoringListener, and send as a parameter the list of tokens to the class - my_listener = VisitorPatternRefactoringListener(common_token_stream=token_stream, - SuperClass_identifier='SC', - SubClass_identifier=['CC1', 'CC2', 'CC3']) - # SuperClass_identifier='ComputerPart', - # SubClass_identifier=['Keyboard', 'Monitor', 'Mouse', 'Computer']) - # SuperClass_identifier='Shape', - # SubClass_identifier=['Polygon', 'Rectangle','Arrow']) - + my_listener = VisitorPatternRefactoringListener( + common_token_stream=token_stream, + SuperClass_identifier='SC', + SubClass_identifier=['CC1', 'CC2', 'CC3'] + ) + # SuperClass_identifier='ComputerPart', + # SubClass_identifier=['Keyboard', 'Monitor', 'Mouse', 'Computer']) + # SuperClass_identifier='Shape', + # SubClass_identifier=['Polygon', 'Rectangle','Arrow']) walker = ParseTreeWalker() walker.walk(t=parse_tree, listener=my_listener) print('Compiler result:') print(my_listener.token_stream_rewriter.getDefaultText()) - with open('../tests/visitor1/VisitorExample0.refactored.java', mode='w', newline='') as f: + with open('../../tests/visitor1/VisitorExample0.refactored.java', mode='w', newline='') as f: # with open('VisitorExample1.refactored.java', mode='w', newline='') as f: # with open('VisitorExample2.refactored.java', mode='w', newline='') as f: f.write(my_listener.token_stream_rewriter.getDefaultText()) @@ -161,5 +175,5 @@ def main(args): help='Input source', default=r'VisitorExample0.java') # help='Input source', default=r'VisitorExample1.java') # help='Input source', default=r'VisitorExample2.java') - args = argparser.parse_args() - main(args) + args_ = argparser.parse_args() + main(args_) diff --git a/refactorings/__init__.py b/codart/refactorings/__init__.py similarity index 100% rename from refactorings/__init__.py rename to codart/refactorings/__init__.py diff --git a/refactorings/collapse_hierarchy.py b/codart/refactorings/collapse_hierarchy.py similarity index 98% rename from refactorings/collapse_hierarchy.py rename to codart/refactorings/collapse_hierarchy.py index 15a55b2c..1adffc6a 100644 --- a/refactorings/collapse_hierarchy.py +++ b/codart/refactorings/collapse_hierarchy.py @@ -9,10 +9,10 @@ from antlr4 import * from antlr4.TokenStreamRewriter import TokenStreamRewriter -from gen.javaLabeled.JavaLexer import JavaLexer -from gen.javaLabeled.JavaParserLabeled import JavaParserLabeled -from gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener -from refactorings.remove_class import RemoveClassRefactoringListener +from codart.gen.javaLabeled.JavaLexer import JavaLexer +from codart.gen.javaLabeled.JavaParserLabeled import JavaParserLabeled +from codart.gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener +from codart.refactorings.remove_class import RemoveClassRefactoringListener # from utility.setup_understand import * diff --git a/refactorings/dead_codes/__init__.py b/codart/refactorings/dead_codes/__init__.py similarity index 100% rename from refactorings/dead_codes/__init__.py rename to codart/refactorings/dead_codes/__init__.py diff --git a/refactorings/dead_codes/main_forbig_project.py b/codart/refactorings/dead_codes/main_forbig_project.py similarity index 94% rename from refactorings/dead_codes/main_forbig_project.py rename to codart/refactorings/dead_codes/main_forbig_project.py index f98cc4c4..4ce945ba 100644 --- a/refactorings/dead_codes/main_forbig_project.py +++ b/codart/refactorings/dead_codes/main_forbig_project.py @@ -21,28 +21,16 @@ print(und.version()) -from antlr4 import * - # from refactorings.extract_class import ExtractClassRefactoringListener -from gen.java9.Java9_v2Parser import Java9_v2Parser # from refactorings.Main_refactorings_action_module import Main_Refactors_Action # from refactorings.Main_refactorings_action_module import Main_Refactors_Action # from refactorings.Refactoring_action_module_for_big_project import Main_Refactors_Action_for_big_project -from refactorings.dead_codes.refactoring_action_module_for_big_project import Main_Refactors_Action_for_big_project -from refactorings.extract_class_migrated import myExtractClassRefactoringListener -from refactorings.field_refactorings.MoveFieldUp_Main import main_movefiledUp -from refactorings.method_refactorings.main_MoveMethodDown import main_MoveMethodDown -from refactorings.method_refactorings.main_MoveMoethodUp import main_MoveMethodUp -# from refactorings.Refactoring_action_module import Main_Refactors_Action +from codart.refactorings.dead_codes.refactoring_action_module_for_big_project import Main_Refactors_Action_for_big_project -from speedy.src.java9speedy.parser import sa_java9_v2 -# -import argparse -from antlr4 import * +# from refactorings.Refactoring_action_module import Main_Refactors_Action -from gen.java.JavaLexer import JavaLexer -from refactorings.extract_class_migrated import myExtractClassRefactoringListener +# # @@ -274,7 +262,7 @@ def get_information(Root_path_project, source_class, move_field): if __name__ == '__main__': # print(timestamp()) - with open("../../filename_status_database.txt", mode='w', encoding="utf-8", newline='', errors='ignore') as f: + with open("../../../filename_status_database.txt", mode='w', encoding="utf-8", newline='', errors='ignore') as f: f.write( "This file contains the list of Java files that were refracted, and if the Java file name was in this file, you must read it from the(files_refactord) folder.\n") refactor_action = Main_Refactors_Action_for_big_project() diff --git a/refactorings/dead_codes/main_omidvar.py b/codart/refactorings/dead_codes/main_omidvar.py similarity index 93% rename from refactorings/dead_codes/main_omidvar.py rename to codart/refactorings/dead_codes/main_omidvar.py index 5eecc603..13a96faa 100644 --- a/refactorings/dead_codes/main_omidvar.py +++ b/codart/refactorings/dead_codes/main_omidvar.py @@ -19,11 +19,11 @@ from antlr4 import * -from gen.javaLabeled.JavaLexer import JavaLexer -from gen.javaLabeled.JavaParserLabeled import JavaParserLabeled -from refactorings.make_field_non_static import MakeFieldNonStaticRefactoringListener -from refactorings.make_field_static import MakeFieldStaticRefactoringListener -from refactorings.rename_class import RenameClassRefactoringListener +from codart.gen.javaLabeled.JavaLexer import JavaLexer +from codart.gen.javaLabeled.JavaParserLabeled import JavaParserLabeled +from codart.refactorings.make_field_non_static import MakeFieldNonStaticRefactoringListener +from codart.refactorings.make_field_static import MakeFieldStaticRefactoringListener +from codart.refactorings.rename_class import RenameClassRefactoringListener def main(args): diff --git a/refactorings/dead_codes/refactoring_action_module.py b/codart/refactorings/dead_codes/refactoring_action_module.py similarity index 97% rename from refactorings/dead_codes/refactoring_action_module.py rename to codart/refactorings/dead_codes/refactoring_action_module.py index b00519fd..d3a1db65 100644 --- a/refactorings/dead_codes/refactoring_action_module.py +++ b/codart/refactorings/dead_codes/refactoring_action_module.py @@ -4,44 +4,43 @@ import understand as und from antlr4 import * -from gen.java.JavaParser import JavaParser -from gen.java.JavaLexer import JavaLexer +from codart.gen.java.JavaParser import JavaParser +from codart.gen.java.JavaLexer import JavaLexer # from refactorings.field_refactorings.IncreaseFieldVisibility import DecreaseFieldVisibilityRefactoringListener, \ # IncreaseFieldVisibilityRefactoringListener -from refactorings.collapse_hierarchy import Refactoring_GetFieldText_Listener, \ - CollapsHierarchyRefactoring_GetMethodText_Listener, CollapssHierarchyRefactoringListener, \ +from codart.refactorings.collapse_hierarchy import CollapsHierarchyRefactoring_GetMethodText_Listener, CollapssHierarchyRefactoringListener, \ PropagationCollapssHierarchyListener -from refactorings.make_class_abstract import MakeAbstractClassRefactoringListener -from refactorings.class_refactorings.MakeClassFinal import MakeFinalClassRefactoringListener -from refactorings.class_refactorings.MakeClassNonFinal import MakeNonFinalClassRefactoringListener -from refactorings.class_refactorings.MakeConcreteClass import MakeConcreteClassRefactoringListener -from refactorings.class_refactorings.RemoveClass import RemoveClassRefactoringListener -from refactorings.class_refactorings.RemoveInterface import RemoveInterfaceRefactoringListener -from refactorings.class_refactorings.extract_Subclass import myExtractSubClassRefactoringListener -from refactorings.extract_class_migrated import myExtractClassRefactoringListener -from refactorings.field_refactorings.DecreaseFieldVisibility import DecreaseFieldVisibilityRefactoringListener -from refactorings.field_refactorings.IncreaseFieldVisibility import IncreaseFieldVisibilityRefactoringListener -from refactorings.field_refactorings.MakeFieldFinal import MakeFieldFinalRefactoringListener -from refactorings.field_refactorings.MakeFieldNonFinal import MakeFieldNonFinalRefactoringListener -from refactorings.field_refactorings.MakeFieldNonStatic import MakeFieldNonStaticRefactoringListener -from refactorings.field_refactorings.MakeFieldStatic import MakeFieldStaticRefactoringListener -from refactorings.field_refactorings.RemoveField import RemoveFieldRefactoringListener -from refactorings.field_refactorings.movefielddown import PropagationMovefieldDownRefactoringListener, \ +from codart.refactorings.make_class_abstract import MakeAbstractClassRefactoringListener +from codart.refactorings import MakeFinalClassRefactoringListener +from codart.refactorings import MakeNonFinalClassRefactoringListener +from codart.refactorings import MakeConcreteClassRefactoringListener +from codart.refactorings import RemoveClassRefactoringListener +from codart.refactorings import RemoveInterfaceRefactoringListener +from codart.refactorings import myExtractSubClassRefactoringListener +from codart.refactorings import myExtractClassRefactoringListener +from codart.refactorings import DecreaseFieldVisibilityRefactoringListener +from codart.refactorings import IncreaseFieldVisibilityRefactoringListener +from codart.refactorings import MakeFieldFinalRefactoringListener +from codart.refactorings import MakeFieldNonFinalRefactoringListener +from codart.refactorings import MakeFieldNonStaticRefactoringListener +from codart.refactorings import MakeFieldStaticRefactoringListener +from codart.refactorings import RemoveFieldRefactoringListener +from codart.refactorings import PropagationMovefieldDownRefactoringListener, \ movefielddownRefactoringListener, movefield_down_gettextfield_Listener -from refactorings.field_refactorings.movefieldup import PropagationMovefieldUpRefactoringListener, \ +from codart.refactorings import PropagationMovefieldUpRefactoringListener, \ movefieldupRefactoringListener, movefieldup_gettextfield_Listener # from refactorings.method_refactorings.IncreaseMethodVisibility import DecreaseMethodVisibilityRefactoringListener -from refactorings.method_refactorings.DecreaseMethodVisibility import DecreaseMethodVisibilityRefactoringListener -from refactorings.method_refactorings.IncreaseMethodVisibility import IncreaseMethodVisibilityRefactoringListener -from refactorings.method_refactorings.MakeMethodFinal import MakeMethodFinalRefactoringListener -from refactorings.method_refactorings.MakeMethodNonFinal import MakeMethodNonFinalRefactoringListener -from refactorings.method_refactorings.MakeMethodNonStatic import MakeMethodNonStaticRefactoringListener -from refactorings.method_refactorings.MakeMethodStatic import MakeMethodStaticRefactoringListener -from refactorings.method_refactorings.MoveMethodDown import PropagationMoveMethodDownRefactoringListener, \ +from codart.refactorings import DecreaseMethodVisibilityRefactoringListener +from codart.refactorings import IncreaseMethodVisibilityRefactoringListener +from codart.refactorings import MakeMethodFinalRefactoringListener +from codart.refactorings import MakeMethodNonFinalRefactoringListener +from codart.refactorings import MakeMethodNonStaticRefactoringListener +from codart.refactorings import MakeMethodStaticRefactoringListener +from codart.refactorings import PropagationMoveMethodDownRefactoringListener, \ MoveMethodDownRefactoringListener, MoveMethodDownRefactoring_GetMethodText_Listener -from refactorings.method_refactorings.MoveMethodUp import PropagationMoveMethodUpRefactoringListener, \ +from codart.refactorings import PropagationMoveMethodUpRefactoringListener, \ MoveMethodUpRefactoringListener, GetMethodTextMoveMethodUpRefactoringListener -from refactorings.method_refactorings.RemoveMethod import RemoveMethodRefactoringListener +from codart.refactorings import RemoveMethodRefactoringListener class Main_Refactors_Action(): diff --git a/refactorings/dead_codes/refactoring_action_module_for_big_project.py b/codart/refactorings/dead_codes/refactoring_action_module_for_big_project.py similarity index 97% rename from refactorings/dead_codes/refactoring_action_module_for_big_project.py rename to codart/refactorings/dead_codes/refactoring_action_module_for_big_project.py index 6c018a14..17bf6375 100644 --- a/refactorings/dead_codes/refactoring_action_module_for_big_project.py +++ b/codart/refactorings/dead_codes/refactoring_action_module_for_big_project.py @@ -4,49 +4,49 @@ import understand as und from antlr4 import * -from gen.java.JavaParser import JavaParser -from gen.java.JavaLexer import JavaLexer +from codart.gen.java.JavaParser import JavaParser +from codart.gen.java.JavaLexer import JavaLexer # from refactorings.field_refactorings.IncreaseFieldVisibility import DecreaseFieldVisibilityRefactoringListener, \ # IncreaseFieldVisibilityRefactoringListener -from refactorings.class_refactorings.CollapseHierarchy import CollapsHierarchyRefactoring_GetFieldText_Listener, \ +from codart.refactorings import CollapsHierarchyRefactoring_GetFieldText_Listener, \ CollapsHierarchyRefactoring_GetMethodText_Listener, CollapssHierarchyRefactoringListener, \ PropagationCollapssHierarchyListener -from refactorings.class_refactorings.MakeAbstractClass import MakeAbstractClassRefactoringListener -from refactorings.class_refactorings.MakeClassFinal import MakeFinalClassRefactoringListener -from refactorings.class_refactorings.MakeClassNonFinal import MakeNonFinalClassRefactoringListener -from refactorings.class_refactorings.MakeConcreteClass import MakeConcreteClassRefactoringListener -from refactorings.class_refactorings.RemoveClass import RemoveClassRefactoringListener -from refactorings.class_refactorings.RemoveInterface import RemoveInterfaceRefactoringListener -from refactorings.class_refactorings.extract_Subclass import myExtractSubClassRefactoringListener -from refactorings.extract_class_migrated import myExtractClassRefactoringListener -from refactorings.field_refactorings.DecreaseFieldVisibility import DecreaseFieldVisibilityRefactoringListener +from codart.refactorings import MakeAbstractClassRefactoringListener +from codart.refactorings import MakeFinalClassRefactoringListener +from codart.refactorings import MakeNonFinalClassRefactoringListener +from codart.refactorings import MakeConcreteClassRefactoringListener +from codart.refactorings import RemoveClassRefactoringListener +from codart.refactorings import RemoveInterfaceRefactoringListener +from codart.refactorings import myExtractSubClassRefactoringListener +from codart.refactorings import myExtractClassRefactoringListener +from codart.refactorings import DecreaseFieldVisibilityRefactoringListener # from refactorings.field_refactorings.IncreaseFieldVisibility import IncreaseFieldVisibilityRefactoringListener, \ # PropagationIncreaseFieldVisibility, \ # PropagationIncreaseFieldVisibilityRefactoringListener -from refactorings.field_refactorings.IncreaseFieldVisibility import IncreaseFieldVisibilityRefactoringListener, \ +from codart.refactorings import IncreaseFieldVisibilityRefactoringListener, \ PropagationIncreaseFieldVisibility_GetObjects_RefactoringListener, \ PropagationIncreaseFieldVisibilityRefactoringListener -from refactorings.field_refactorings.MakeFieldFinal import MakeFieldFinalRefactoringListener -from refactorings.field_refactorings.MakeFieldNonFinal import MakeFieldNonFinalRefactoringListener -from refactorings.field_refactorings.MakeFieldNonStatic import MakeFieldNonStaticRefactoringListener -from refactorings.field_refactorings.MakeFieldStatic import MakeFieldStaticRefactoringListener -from refactorings.field_refactorings.RemoveField import RemoveFieldRefactoringListener -from refactorings.field_refactorings.movefielddown import PropagationMovefieldDownRefactoringListener, \ +from codart.refactorings import MakeFieldFinalRefactoringListener +from codart.refactorings import MakeFieldNonFinalRefactoringListener +from codart.refactorings import MakeFieldNonStaticRefactoringListener +from codart.refactorings import MakeFieldStaticRefactoringListener +from codart.refactorings import RemoveFieldRefactoringListener +from codart.refactorings import PropagationMovefieldDownRefactoringListener, \ movefielddownRefactoringListener, movefield_down_gettextfield_Listener -from refactorings.field_refactorings.movefieldup import PropagationMovefieldUpRefactoringListener, \ +from codart.refactorings import PropagationMovefieldUpRefactoringListener, \ movefieldupRefactoringListener, movefieldup_gettextfield_Listener # from refactorings.method_refactorings.IncreaseMethodVisibility import DecreaseMethodVisibilityRefactoringListener -from refactorings.method_refactorings.DecreaseMethodVisibility import DecreaseMethodVisibilityRefactoringListener -from refactorings.method_refactorings.IncreaseMethodVisibility import IncreaseMethodVisibilityRefactoringListener -from refactorings.method_refactorings.MakeMethodFinal import MakeMethodFinalRefactoringListener -from refactorings.method_refactorings.MakeMethodNonFinal import MakeMethodNonFinalRefactoringListener -from refactorings.method_refactorings.MakeMethodNonStatic import MakeMethodNonStaticRefactoringListener -from refactorings.method_refactorings.MakeMethodStatic import MakeMethodStaticRefactoringListener -from refactorings.method_refactorings.MoveMethodDown import PropagationMoveMethodDownRefactoringListener, \ +from codart.refactorings import DecreaseMethodVisibilityRefactoringListener +from codart.refactorings import IncreaseMethodVisibilityRefactoringListener +from codart.refactorings import MakeMethodFinalRefactoringListener +from codart.refactorings import MakeMethodNonFinalRefactoringListener +from codart.refactorings import MakeMethodNonStaticRefactoringListener +from codart.refactorings import MakeMethodStaticRefactoringListener +from codart.refactorings import PropagationMoveMethodDownRefactoringListener, \ MoveMethodDownRefactoringListener, MoveMethodDownRefactoring_GetMethodText_Listener -from refactorings.method_refactorings.MoveMethodUp import PropagationMoveMethodUpRefactoringListener, \ +from codart.refactorings import PropagationMoveMethodUpRefactoringListener, \ MoveMethodUpRefactoringListener, GetMethodTextMoveMethodUpRefactoringListener -from refactorings.method_refactorings.RemoveMethod import RemoveMethodRefactoringListener +from codart.refactorings import RemoveMethodRefactoringListener class Main_Refactors_Action_for_big_project(): diff --git a/refactorings/dead_codes/test.py b/codart/refactorings/dead_codes/test.py similarity index 90% rename from refactorings/dead_codes/test.py rename to codart/refactorings/dead_codes/test.py index 90e4660f..b11d8f90 100644 --- a/refactorings/dead_codes/test.py +++ b/codart/refactorings/dead_codes/test.py @@ -16,12 +16,12 @@ from antlr4 import * -from refactorings.collapse_hierarchy import CollapseHierarchyRefactoringListener -from refactorings.inline_class import InlineClassRefactoringListener -from refactorings.make_method_static import MakeMethodStaticRefactoringListener -from refactorings.make_method_non_static import MakeMethodNonStaticRefactoringListener -from gen.javaLabeled.JavaLexer import JavaLexer -from gen.javaLabeled.JavaParserLabeled import JavaParserLabeled +from codart.refactorings.collapse_hierarchy import CollapseHierarchyRefactoringListener +from codart.refactorings.inline_class import InlineClassRefactoringListener +from codart.refactorings.make_method_static import MakeMethodStaticRefactoringListener +from codart.refactorings.make_method_non_static import MakeMethodNonStaticRefactoringListener +from codart.gen.javaLabeled.JavaLexer import JavaLexer +from codart.gen.javaLabeled.JavaParserLabeled import JavaParserLabeled def main(args): diff --git a/refactorings/decrease_field_visibility.py b/codart/refactorings/decrease_field_visibility.py similarity index 96% rename from refactorings/decrease_field_visibility.py rename to codart/refactorings/decrease_field_visibility.py index cc2627e0..ee6c5551 100644 --- a/refactorings/decrease_field_visibility.py +++ b/codart/refactorings/decrease_field_visibility.py @@ -31,10 +31,10 @@ from antlr4.TokenStreamRewriter import TokenStreamRewriter -from gen.javaLabeled.JavaParserLabeled import JavaParserLabeled -from gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener +from codart.gen.javaLabeled.JavaParserLabeled import JavaParserLabeled +from codart.gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener from codart.symbol_table import parse_and_walk -from sbse.config import logger, UDB_PATH +from codart.config import logger, UDB_PATH class DecreaseFieldVisibilityListener(JavaParserLabeledListener): diff --git a/refactorings/decrease_method_visibility.py b/codart/refactorings/decrease_method_visibility.py similarity index 96% rename from refactorings/decrease_method_visibility.py rename to codart/refactorings/decrease_method_visibility.py index 48373fbc..23677ccf 100644 --- a/refactorings/decrease_method_visibility.py +++ b/codart/refactorings/decrease_method_visibility.py @@ -18,10 +18,10 @@ from antlr4.TokenStreamRewriter import TokenStreamRewriter -from gen.javaLabeled.JavaParserLabeled import JavaParserLabeled -from gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener +from codart.gen.javaLabeled.JavaParserLabeled import JavaParserLabeled +from codart.gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener from codart.symbol_table import parse_and_walk -from sbse.config import logger +from codart.config import logger class DecreaseMethodVisibilityListener(JavaParserLabeledListener): diff --git a/refactorings/encapsulate_field.py b/codart/refactorings/encapsulate_field.py similarity index 97% rename from refactorings/encapsulate_field.py rename to codart/refactorings/encapsulate_field.py index efc13351..dae55064 100644 --- a/refactorings/encapsulate_field.py +++ b/codart/refactorings/encapsulate_field.py @@ -20,10 +20,10 @@ from antlr4 import * from antlr4.TokenStreamRewriter import TokenStreamRewriter -from gen.javaLabeled.JavaParserLabeled import JavaParserLabeled -from gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener -from gen.javaLabeled.JavaLexer import JavaLexer -from sbse.config import logger +from codart.gen.javaLabeled.JavaParserLabeled import JavaParserLabeled +from codart.gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener +from codart.gen.javaLabeled.JavaLexer import JavaLexer +from codart.config import logger class EncapsulateFiledRefactoringListener(JavaParserLabeledListener): @@ -311,7 +311,7 @@ def main(directory_path, package_name, source_class, field_name): # Tests if __name__ == "__main__": - directory_path = "../tests/encapsulate_field_tests/NewTests" + directory_path = "../../tests/encapsulate_field_tests/NewTests" package_name_ = 'learnjava' source_class_ = 'First' field_name_ = 'score' diff --git a/refactorings/extract_class.py b/codart/refactorings/extract_class.py similarity index 98% rename from refactorings/extract_class.py rename to codart/refactorings/extract_class.py index 00161b76..5f6feca1 100644 --- a/refactorings/extract_class.py +++ b/codart/refactorings/extract_class.py @@ -26,7 +26,6 @@ __author__ = 'Morteza Zakeri' import os -import random from pathlib import Path import networkx as nx @@ -38,11 +37,11 @@ from antlr4 import * from antlr4.TokenStreamRewriter import TokenStreamRewriter -from gen.javaLabeled.JavaLexer import JavaLexer -from gen.javaLabeled.JavaParserLabeled import JavaParserLabeled -from gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener +from codart.gen.javaLabeled.JavaLexer import JavaLexer +from codart.gen.javaLabeled.JavaParserLabeled import JavaParserLabeled +from codart.gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener -from sbse.config import logger +from codart.config import logger class DependencyPreConditionListener(JavaParserLabeledListener): diff --git a/refactorings/extract_interface.py b/codart/refactorings/extract_interface.py similarity index 98% rename from refactorings/extract_interface.py rename to codart/refactorings/extract_interface.py index 05293d13..37400513 100644 --- a/refactorings/extract_interface.py +++ b/codart/refactorings/extract_interface.py @@ -25,8 +25,7 @@ __author__ = 'Morteza Zakeri' import os -from codart import symbol_table -from sbse import config +from codart import symbol_table, config class ExtractInterfaceRefactoring: @@ -281,13 +280,13 @@ def test1(): "../benchmark_projects/tests/extract_interface/U.java", ] if ExtractInterfaceRefactoring(filenames, "test", ["A", "B"], ["a(int,float)", "b()"], "Iab", - "../tests/extract_interface/Iab.re.java").do_refactor(): + "../../tests/extract_interface/Iab.re.java").do_refactor(): print("A, B: Success!") else: print("A, B: Cannot refactor.") for third_class in ["C", "D", "E"]: if ExtractInterfaceRefactoring(filenames, "test", ["A", "B", third_class], ["a(int,float)", "b()"], "Iab", - "../tests/extract_interface/Iab.re.java").do_refactor(): + "../../tests/extract_interface/Iab.re.java").do_refactor(): print("A, B, " + third_class + ": Success!") else: print("A, B, " + third_class + ": Cannot refactor.") diff --git a/refactorings/extract_interface2.py b/codart/refactorings/extract_interface2.py similarity index 97% rename from refactorings/extract_interface2.py rename to codart/refactorings/extract_interface2.py index 4d2bef9a..c06c1d99 100644 --- a/refactorings/extract_interface2.py +++ b/codart/refactorings/extract_interface2.py @@ -30,10 +30,10 @@ from antlr4 import * from antlr4.TokenStreamRewriter import TokenStreamRewriter -from gen.javaLabeled.JavaLexer import JavaLexer -from gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener -from gen.javaLabeled.JavaParserLabeled import JavaParserLabeled -from sbse import config +from codart.gen.javaLabeled.JavaLexer import JavaLexer +from codart.gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener +from codart.gen.javaLabeled.JavaParserLabeled import JavaParserLabeled +from codart import config class InterfaceInfoListener(JavaParserLabeledListener): diff --git a/refactorings/extract_method.py b/codart/refactorings/extract_method.py similarity index 98% rename from refactorings/extract_method.py rename to codart/refactorings/extract_method.py index ba211ea9..ca31a87e 100644 --- a/refactorings/extract_method.py +++ b/codart/refactorings/extract_method.py @@ -44,9 +44,9 @@ import numpy as np from antlr4 import * -from gen.javaLabeled.JavaLexer import JavaLexer -from gen.javaLabeled.JavaParserLabeled import JavaParserLabeled -from gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener +from codart.gen.javaLabeled.JavaLexer import JavaLexer +from codart.gen.javaLabeled.JavaParserLabeled import JavaParserLabeled +from codart.gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener # Config logging logger = logging.getLogger() diff --git a/refactorings/extract_subclass.py b/codart/refactorings/extract_subclass.py similarity index 99% rename from refactorings/extract_subclass.py rename to codart/refactorings/extract_subclass.py index 6bcec173..5d703922 100644 --- a/refactorings/extract_subclass.py +++ b/codart/refactorings/extract_subclass.py @@ -14,9 +14,9 @@ from antlr4.tree import Tree from antlr4.TokenStreamRewriter import TokenStreamRewriter -from gen.javaLabeled.JavaLexer import JavaLexer -from gen.javaLabeled.JavaParserLabeled import JavaParserLabeled -from gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener +from codart.gen.javaLabeled.JavaLexer import JavaLexer +from codart.gen.javaLabeled.JavaParserLabeled import JavaParserLabeled +from codart.gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener files_to_refactor = [] diff --git a/refactorings/increase_field_visibility.py b/codart/refactorings/increase_field_visibility.py similarity index 96% rename from refactorings/increase_field_visibility.py rename to codart/refactorings/increase_field_visibility.py index 0c0d612d..d6ee6540 100644 --- a/refactorings/increase_field_visibility.py +++ b/codart/refactorings/increase_field_visibility.py @@ -30,10 +30,10 @@ from antlr4.TokenStreamRewriter import TokenStreamRewriter -from gen.javaLabeled.JavaParserLabeled import JavaParserLabeled -from gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener +from codart.gen.javaLabeled.JavaParserLabeled import JavaParserLabeled +from codart.gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener from codart.symbol_table import parse_and_walk -from sbse.config import logger +from codart.config import logger class IncreaseFieldVisibilityListener(JavaParserLabeledListener): diff --git a/refactorings/increase_method_visibility.py b/codart/refactorings/increase_method_visibility.py similarity index 96% rename from refactorings/increase_method_visibility.py rename to codart/refactorings/increase_method_visibility.py index d79c8c55..dba40ec5 100644 --- a/refactorings/increase_method_visibility.py +++ b/codart/refactorings/increase_method_visibility.py @@ -30,10 +30,10 @@ from antlr4.TokenStreamRewriter import TokenStreamRewriter -from gen.javaLabeled.JavaParserLabeled import JavaParserLabeled -from gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener +from codart.gen.javaLabeled.JavaParserLabeled import JavaParserLabeled +from codart.gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener from codart.symbol_table import parse_and_walk -from sbse.config import logger +from codart.config import logger class IncreaseMethodVisibilityListener(JavaParserLabeledListener): diff --git a/refactorings/inline_class.py b/codart/refactorings/inline_class.py similarity index 99% rename from refactorings/inline_class.py rename to codart/refactorings/inline_class.py index 4cbd4b4c..3477d1c0 100644 --- a/refactorings/inline_class.py +++ b/codart/refactorings/inline_class.py @@ -13,8 +13,8 @@ from antlr4 import * from antlr4.TokenStreamRewriter import TokenStreamRewriter -from gen.javaLabeled.JavaParserLabeled import JavaParserLabeled -from gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener +from codart.gen.javaLabeled.JavaParserLabeled import JavaParserLabeled +from codart.gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener class InlineClassRefactoringListener(JavaParserLabeledListener): diff --git a/refactorings/make_class_abstract.py b/codart/refactorings/make_class_abstract.py similarity index 97% rename from refactorings/make_class_abstract.py rename to codart/refactorings/make_class_abstract.py index f9a002cc..283e0937 100644 --- a/refactorings/make_class_abstract.py +++ b/codart/refactorings/make_class_abstract.py @@ -16,9 +16,9 @@ from antlr4 import * from antlr4.TokenStreamRewriter import TokenStreamRewriter -from gen.javaLabeled.JavaLexer import JavaLexer -from gen.javaLabeled.JavaParserLabeled import JavaParserLabeled -from gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener +from codart.gen.javaLabeled.JavaLexer import JavaLexer +from codart.gen.javaLabeled.JavaParserLabeled import JavaParserLabeled +from codart.gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener class MakeAbstractClassRefactoringListener(JavaParserLabeledListener): diff --git a/refactorings/make_class_concrete.py b/codart/refactorings/make_class_concrete.py similarity index 97% rename from refactorings/make_class_concrete.py rename to codart/refactorings/make_class_concrete.py index e726a97d..bdf7d7b0 100644 --- a/refactorings/make_class_concrete.py +++ b/codart/refactorings/make_class_concrete.py @@ -16,9 +16,9 @@ from antlr4 import * from antlr4.TokenStreamRewriter import TokenStreamRewriter -from gen.javaLabeled.JavaLexer import JavaLexer -from gen.javaLabeled.JavaParserLabeled import JavaParserLabeled -from gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener +from codart.gen.javaLabeled.JavaLexer import JavaLexer +from codart.gen.javaLabeled.JavaParserLabeled import JavaParserLabeled +from codart.gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener class MakeConcreteClassRefactoringListener(JavaParserLabeledListener): diff --git a/refactorings/make_class_final.py b/codart/refactorings/make_class_final.py similarity index 93% rename from refactorings/make_class_final.py rename to codart/refactorings/make_class_final.py index c1055566..d194b16c 100644 --- a/refactorings/make_class_final.py +++ b/codart/refactorings/make_class_final.py @@ -17,9 +17,9 @@ from antlr4 import * from antlr4.TokenStreamRewriter import TokenStreamRewriter -from gen.javaLabeled.JavaLexer import JavaLexer -from gen.javaLabeled.JavaParserLabeled import JavaParserLabeled -from gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener +from codart.gen.javaLabeled.JavaLexer import JavaLexer +from codart.gen.javaLabeled.JavaParserLabeled import JavaParserLabeled +from codart.gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener class MakeFinalClassRefactoringListener(JavaParserLabeledListener): diff --git a/refactorings/make_class_non_final.py b/codart/refactorings/make_class_non_final.py similarity index 95% rename from refactorings/make_class_non_final.py rename to codart/refactorings/make_class_non_final.py index 1877c39b..12b65200 100644 --- a/refactorings/make_class_non_final.py +++ b/codart/refactorings/make_class_non_final.py @@ -17,9 +17,9 @@ from antlr4 import * from antlr4.TokenStreamRewriter import TokenStreamRewriter -from gen.javaLabeled.JavaLexer import JavaLexer -from gen.javaLabeled.JavaParserLabeled import JavaParserLabeled -from gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener +from codart.gen.javaLabeled.JavaLexer import JavaLexer +from codart.gen.javaLabeled.JavaParserLabeled import JavaParserLabeled +from codart.gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener class MakeNonFinalClassRefactoringListener(JavaParserLabeledListener): diff --git a/refactorings/make_field_final.py b/codart/refactorings/make_field_final.py similarity index 94% rename from refactorings/make_field_final.py rename to codart/refactorings/make_field_final.py index 84c4ee9b..b9a32982 100644 --- a/refactorings/make_field_final.py +++ b/codart/refactorings/make_field_final.py @@ -33,10 +33,10 @@ from antlr4 import * from antlr4.TokenStreamRewriter import TokenStreamRewriter -from gen.java.JavaParser import JavaParser -from gen.javaLabeled.JavaLexer import JavaLexer -from gen.javaLabeled.JavaParserLabeled import JavaParserLabeled -from gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener +from codart.gen.java.JavaParser import JavaParser +from codart.gen.javaLabeled.JavaLexer import JavaLexer +from codart.gen.javaLabeled.JavaParserLabeled import JavaParserLabeled +from codart.gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener class MakeFieldFinalRefactoringListener(JavaParserLabeledListener): diff --git a/refactorings/make_field_non_final.py b/codart/refactorings/make_field_non_final.py similarity index 94% rename from refactorings/make_field_non_final.py rename to codart/refactorings/make_field_non_final.py index aa019642..72345a58 100644 --- a/refactorings/make_field_non_final.py +++ b/codart/refactorings/make_field_non_final.py @@ -29,10 +29,10 @@ from antlr4 import * from antlr4.TokenStreamRewriter import TokenStreamRewriter -from gen.java.JavaParser import JavaParser -from gen.javaLabeled.JavaLexer import JavaLexer -from gen.javaLabeled.JavaParserLabeled import JavaParserLabeled -from gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener +from codart.gen.java.JavaParser import JavaParser +from codart.gen.javaLabeled.JavaLexer import JavaLexer +from codart.gen.javaLabeled.JavaParserLabeled import JavaParserLabeled +from codart.gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener class MakeFieldNonFinalRefactoringListener(JavaParserLabeledListener): diff --git a/refactorings/make_field_non_static.py b/codart/refactorings/make_field_non_static.py similarity index 95% rename from refactorings/make_field_non_static.py rename to codart/refactorings/make_field_non_static.py index 9261fec9..98e7d7d0 100644 --- a/refactorings/make_field_non_static.py +++ b/codart/refactorings/make_field_non_static.py @@ -31,9 +31,9 @@ from antlr4 import * from antlr4.TokenStreamRewriter import TokenStreamRewriter -from gen.javaLabeled.JavaLexer import JavaLexer -from gen.javaLabeled.JavaParserLabeled import JavaParserLabeled -from gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener +from codart.gen.javaLabeled.JavaLexer import JavaLexer +from codart.gen.javaLabeled.JavaParserLabeled import JavaParserLabeled +from codart.gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener class MakeFieldNonStaticRefactoringListener(JavaParserLabeledListener): diff --git a/refactorings/make_field_static.py b/codart/refactorings/make_field_static.py similarity index 95% rename from refactorings/make_field_static.py rename to codart/refactorings/make_field_static.py index b53aa97f..da93b69e 100644 --- a/refactorings/make_field_static.py +++ b/codart/refactorings/make_field_static.py @@ -30,9 +30,9 @@ from antlr4 import * from antlr4.TokenStreamRewriter import TokenStreamRewriter -from gen.javaLabeled.JavaLexer import JavaLexer -from gen.javaLabeled.JavaParserLabeled import JavaParserLabeled -from gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener +from codart.gen.javaLabeled.JavaLexer import JavaLexer +from codart.gen.javaLabeled.JavaParserLabeled import JavaParserLabeled +from codart.gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener class MakeFieldStaticRefactoringListener(JavaParserLabeledListener): diff --git a/refactorings/make_method_final.py b/codart/refactorings/make_method_final.py similarity index 94% rename from refactorings/make_method_final.py rename to codart/refactorings/make_method_final.py index 3256cfc2..f3094854 100644 --- a/refactorings/make_method_final.py +++ b/codart/refactorings/make_method_final.py @@ -27,9 +27,9 @@ from antlr4 import * from antlr4.TokenStreamRewriter import TokenStreamRewriter -from gen.javaLabeled.JavaLexer import JavaLexer -from gen.javaLabeled.JavaParserLabeled import JavaParserLabeled -from gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener +from codart.gen.javaLabeled.JavaLexer import JavaLexer +from codart.gen.javaLabeled.JavaParserLabeled import JavaParserLabeled +from codart.gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener class MakeMethodFinalRefactoringListener(JavaParserLabeledListener): diff --git a/refactorings/make_method_non_final.py b/codart/refactorings/make_method_non_final.py similarity index 94% rename from refactorings/make_method_non_final.py rename to codart/refactorings/make_method_non_final.py index 59280205..10f587ba 100644 --- a/refactorings/make_method_non_final.py +++ b/codart/refactorings/make_method_non_final.py @@ -28,9 +28,9 @@ from antlr4 import * from antlr4.TokenStreamRewriter import TokenStreamRewriter -from gen.javaLabeled.JavaLexer import JavaLexer -from gen.javaLabeled.JavaParserLabeled import JavaParserLabeled -from gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener +from codart.gen.javaLabeled.JavaLexer import JavaLexer +from codart.gen.javaLabeled.JavaParserLabeled import JavaParserLabeled +from codart.gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener class MakeMethodNonFinalRefactoringListener(JavaParserLabeledListener): diff --git a/refactorings/make_method_non_static.py b/codart/refactorings/make_method_non_static.py similarity index 97% rename from refactorings/make_method_non_static.py rename to codart/refactorings/make_method_non_static.py index 22ba0b01..ddcd03f5 100644 --- a/refactorings/make_method_non_static.py +++ b/codart/refactorings/make_method_non_static.py @@ -28,9 +28,9 @@ from antlr4 import * from antlr4.TokenStreamRewriter import TokenStreamRewriter -from gen.javaLabeled.JavaLexer import JavaLexer -from gen.javaLabeled.JavaParserLabeled import JavaParserLabeled -from gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener +from codart.gen.javaLabeled.JavaLexer import JavaLexer +from codart.gen.javaLabeled.JavaParserLabeled import JavaParserLabeled +from codart.gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener class Parameter: diff --git a/refactorings/make_method_non_static2.py b/codart/refactorings/make_method_non_static2.py similarity index 95% rename from refactorings/make_method_non_static2.py rename to codart/refactorings/make_method_non_static2.py index 0bd1aa0f..73b0ecf5 100644 --- a/refactorings/make_method_non_static2.py +++ b/codart/refactorings/make_method_non_static2.py @@ -29,9 +29,9 @@ except ImportError as e: print(e) -from gen.javaLabeled.JavaLexer import JavaLexer -from gen.javaLabeled.JavaParserLabeled import JavaParserLabeled -from gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener +from codart.gen.javaLabeled.JavaLexer import JavaLexer +from codart.gen.javaLabeled.JavaParserLabeled import JavaParserLabeled +from codart.gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener class MakeMethodNonStaticRefactoringListener(JavaParserLabeledListener): diff --git a/refactorings/make_method_static.py b/codart/refactorings/make_method_static.py similarity index 96% rename from refactorings/make_method_static.py rename to codart/refactorings/make_method_static.py index 5c5fb109..368031e7 100644 --- a/refactorings/make_method_static.py +++ b/codart/refactorings/make_method_static.py @@ -29,9 +29,9 @@ from antlr4 import * from antlr4.TokenStreamRewriter import TokenStreamRewriter -from gen.javaLabeled.JavaLexer import JavaLexer -from gen.javaLabeled.JavaParserLabeled import JavaParserLabeled -from gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener +from codart.gen.javaLabeled.JavaLexer import JavaLexer +from codart.gen.javaLabeled.JavaParserLabeled import JavaParserLabeled +from codart.gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener class MakeMethodStaticRefactoringListener(JavaParserLabeledListener): diff --git a/refactorings/make_method_static2.py b/codart/refactorings/make_method_static2.py similarity index 95% rename from refactorings/make_method_static2.py rename to codart/refactorings/make_method_static2.py index b89f880f..a2b0342f 100644 --- a/refactorings/make_method_static2.py +++ b/codart/refactorings/make_method_static2.py @@ -29,10 +29,9 @@ from antlr4 import * from antlr4.TokenStreamRewriter import TokenStreamRewriter -from gen.javaLabeled.JavaLexer import JavaLexer -from gen.javaLabeled.JavaParserLabeled import JavaParserLabeled -from gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener -from sbse import config +from codart.gen.javaLabeled.JavaLexer import JavaLexer +from codart.gen.javaLabeled.JavaParserLabeled import JavaParserLabeled +from codart.gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener class MakeMethodStaticRefactoringListener(JavaParserLabeledListener): diff --git a/refactorings/move_class.py b/codart/refactorings/move_class.py similarity index 98% rename from refactorings/move_class.py rename to codart/refactorings/move_class.py index 9a71b92d..4fe8e748 100644 --- a/refactorings/move_class.py +++ b/codart/refactorings/move_class.py @@ -27,10 +27,10 @@ from antlr4.TokenStreamRewriter import TokenStreamRewriter -from gen.javaLabeled.JavaParserLabeled import JavaParserLabeled -from gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener +from codart.gen.javaLabeled.JavaParserLabeled import JavaParserLabeled +from codart.gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener from codart.symbol_table import parse_and_walk -from sbse import config +from codart import config ROOT_PACKAGE = "(Unnamed_Package)" diff --git a/refactorings/move_field.py b/codart/refactorings/move_field.py similarity index 97% rename from refactorings/move_field.py rename to codart/refactorings/move_field.py index a4847483..70ee5523 100644 --- a/refactorings/move_field.py +++ b/codart/refactorings/move_field.py @@ -22,8 +22,8 @@ from antlr4.TokenStreamRewriter import TokenStreamRewriter -from gen.javaLabeled.JavaParserLabeled import JavaParserLabeled -from gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener +from codart.gen.javaLabeled.JavaParserLabeled import JavaParserLabeled +from codart.gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener from codart.symbol_table import parse_and_walk try: @@ -31,7 +31,7 @@ except ImportError as e: print(e) -from sbse.config import logger +from codart.config import logger # logging.basicConfig(level=logging.DEBUG) # logger = logging.getLogger(__file__) diff --git a/refactorings/move_method.py b/codart/refactorings/move_method.py similarity index 98% rename from refactorings/move_method.py rename to codart/refactorings/move_method.py index 1dff4290..e62c51a3 100644 --- a/refactorings/move_method.py +++ b/codart/refactorings/move_method.py @@ -30,11 +30,11 @@ except ImportError as e: print(e) -from gen.javaLabeled.JavaParserLabeled import JavaParserLabeled -from gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener -from refactorings.move_field import CheckCycleListener +from codart.gen.javaLabeled.JavaParserLabeled import JavaParserLabeled +from codart.gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener +from codart.refactorings.move_field import CheckCycleListener from codart.symbol_table import parse_and_walk -from sbse.config import logger +from codart.config import logger # logging.basicConfig(level=logging.DEBUG) # logger = logging.getLogger(__file__) diff --git a/refactorings/pullup_constructor.py b/codart/refactorings/pullup_constructor.py similarity index 98% rename from refactorings/pullup_constructor.py rename to codart/refactorings/pullup_constructor.py index 1c5f3bd9..aea91ea7 100644 --- a/refactorings/pullup_constructor.py +++ b/codart/refactorings/pullup_constructor.py @@ -36,13 +36,13 @@ from antlr4.TokenStreamRewriter import TokenStreamRewriter -from gen.javaLabeled.JavaParserLabeled import JavaParserLabeled -from gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener +from codart.gen.javaLabeled.JavaParserLabeled import JavaParserLabeled +from codart.gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener from codart.symbol_table import parse_and_walk, Program # Config logging -from sbse.config import logger +from codart.config import logger # logging.basicConfig(filename='codart_result.log', level=logging.DEBUG) diff --git a/refactorings/pullup_field.py b/codart/refactorings/pullup_field.py similarity index 99% rename from refactorings/pullup_field.py rename to codart/refactorings/pullup_field.py index f5e360cb..2d0166ce 100644 --- a/refactorings/pullup_field.py +++ b/codart/refactorings/pullup_field.py @@ -27,7 +27,7 @@ __author__ = 'Morteza Zakeri' from codart import symbol_table -from sbse.config import logger, PROJECT_PATH +from codart.config import logger, PROJECT_PATH class PullUpFieldRefactoring: diff --git a/refactorings/pullup_method.py b/codart/refactorings/pullup_method.py similarity index 98% rename from refactorings/pullup_method.py rename to codart/refactorings/pullup_method.py index 78416efd..d10a30ea 100644 --- a/refactorings/pullup_method.py +++ b/codart/refactorings/pullup_method.py @@ -30,10 +30,10 @@ from antlr4 import * from antlr4.TokenStreamRewriter import TokenStreamRewriter -from gen.javaLabeled.JavaLexer import JavaLexer -from gen.javaLabeled.JavaParserLabeled import JavaParserLabeled -from gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener -from sbse.config import logger +from codart.gen.javaLabeled.JavaLexer import JavaLexer +from codart.gen.javaLabeled.JavaParserLabeled import JavaParserLabeled +from codart.gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener +from codart.config import logger class CheckOverrideListener(JavaParserLabeledListener): diff --git a/refactorings/pushdown_field.py b/codart/refactorings/pushdown_field.py similarity index 99% rename from refactorings/pushdown_field.py rename to codart/refactorings/pushdown_field.py index fdb57f25..df4dbce4 100644 --- a/refactorings/pushdown_field.py +++ b/codart/refactorings/pushdown_field.py @@ -24,7 +24,7 @@ __author__ = 'Morteza Zakeri' from codart import symbol_table -from sbse.config import logger +from codart.config import logger class PushDownField: diff --git a/refactorings/pushdown_field2.py b/codart/refactorings/pushdown_field2.py similarity index 96% rename from refactorings/pushdown_field2.py rename to codart/refactorings/pushdown_field2.py index 76afe2e8..580f6ca7 100644 --- a/refactorings/pushdown_field2.py +++ b/codart/refactorings/pushdown_field2.py @@ -25,12 +25,12 @@ from antlr4.TokenStreamRewriter import TokenStreamRewriter -from gen.javaLabeled.JavaParserLabeled import JavaParserLabeled -from gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener +from codart.gen.javaLabeled.JavaParserLabeled import JavaParserLabeled +from codart.gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener from codart.symbol_table import parse_and_walk -import sbse.config -from sbse.config import logger +import codart.config +from codart.config import logger class CutFieldListener(JavaParserLabeledListener): @@ -167,7 +167,7 @@ def main(udb_path=None, source_package=None, source_class=None, field_name=None, """ if udb_path is None: - db = und.open(sbse.config.UDB_PATH) + db = und.open(codart.config.UDB_PATH) else: db = und.open(udb_path) diff --git a/refactorings/pushdown_method.py b/codart/refactorings/pushdown_method.py similarity index 98% rename from refactorings/pushdown_method.py rename to codart/refactorings/pushdown_method.py index 4634f52c..978ef3e0 100644 --- a/refactorings/pushdown_method.py +++ b/codart/refactorings/pushdown_method.py @@ -25,11 +25,11 @@ from antlr4 import * from antlr4.TokenStreamRewriter import TokenStreamRewriter -from gen.javaLabeled.JavaLexer import JavaLexer -from gen.javaLabeled.JavaParserLabeled import JavaParserLabeled -from gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener +from codart.gen.javaLabeled.JavaLexer import JavaLexer +from codart.gen.javaLabeled.JavaParserLabeled import JavaParserLabeled +from codart.gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener -from sbse.config import logger +from codart.config import logger class PushDownMethodRefactoringListener(JavaParserLabeledListener): diff --git a/refactorings/pushdown_method2.py b/codart/refactorings/pushdown_method2.py similarity index 97% rename from refactorings/pushdown_method2.py rename to codart/refactorings/pushdown_method2.py index 7ef58806..877d7bbf 100644 --- a/refactorings/pushdown_method2.py +++ b/codart/refactorings/pushdown_method2.py @@ -25,11 +25,11 @@ from antlr4.TokenStreamRewriter import TokenStreamRewriter -from gen.javaLabeled.JavaParserLabeled import JavaParserLabeled -from gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener +from codart.gen.javaLabeled.JavaParserLabeled import JavaParserLabeled +from codart.gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener from codart.symbol_table import parse_and_walk -from sbse import config +from codart import config class CutMethodListener(JavaParserLabeledListener): diff --git a/refactorings/remove_class.py b/codart/refactorings/remove_class.py similarity index 94% rename from refactorings/remove_class.py rename to codart/refactorings/remove_class.py index 5f0d6c64..72f15500 100644 --- a/refactorings/remove_class.py +++ b/codart/refactorings/remove_class.py @@ -13,9 +13,9 @@ from antlr4 import * from antlr4.TokenStreamRewriter import TokenStreamRewriter -from gen.javaLabeled.JavaLexer import JavaLexer -from gen.javaLabeled.JavaParserLabeled import JavaParserLabeled -from gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener +from codart.gen.javaLabeled.JavaLexer import JavaLexer +from codart.gen.javaLabeled.JavaParserLabeled import JavaParserLabeled +from codart.gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener class RemoveClassRefactoringListener(JavaParserLabeledListener): diff --git a/refactorings/remove_dead_code.py b/codart/refactorings/remove_dead_code.py similarity index 96% rename from refactorings/remove_dead_code.py rename to codart/refactorings/remove_dead_code.py index 755543f0..6f45bafe 100644 --- a/refactorings/remove_dead_code.py +++ b/codart/refactorings/remove_dead_code.py @@ -1,435 +1,435 @@ -""" - -""" -__version__ = '0.1.1' -__author__ = 'Morteza Zakeri' - -import os - -from antlr4 import * -from antlr4.TokenStreamRewriter import TokenStreamRewriter - -from gen.javaLabeled.JavaParserLabeled import JavaParserLabeled -from gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener -from gen.javaLabeled.JavaLexer import JavaLexer - - -# This is the class for detecting all of the types. -class DetectCodeClass(JavaParserLabeledListener): - def __init__(self): - self.Variables = [] - self.Fields = [] - self.MethodParameters = [] - self.Methods = [] - self.Classes = [] - - def enterVariableDeclarator(self, ctx: JavaParserLabeled.VariableDeclaratorContext): - self.Variables.append(str(ctx.variableDeclaratorId().IDENTIFIER())) - - def exitVariableDeclarator(self, ctx: JavaParserLabeled.VariableDeclaratorContext): - pass - - def enterMethodDeclaration(self, ctx: JavaParserLabeled.MethodDeclarationContext): - self.Methods.append(str(ctx.IDENTIFIER())) - self.MethodParameters.append(str(ctx.formalParameters())) - - def exitMethodDeclaration(self, ctx: JavaParserLabeled.MethodDeclarationContext): - pass - - def enterClassDeclaration(self, ctx: JavaParserLabeled.ClassDeclarationContext): - self.Classes.append(str(ctx.IDENTIFIER())) - - def exitClassDeclaration(self, ctx: JavaParserLabeled.ClassDeclarationContext): - pass - - -# This is the class for detecting dead codes. -class DetectDeadCodeClass(JavaParserLabeledListener): - def __init__(self): - self.DeadVariables = [] - self.DeadMethodParameters = [] - self.Fields = [] - self.DeadMethods = [] - self.DeadClasses = [] - - pass - - -# This is the class to remove dead codes. -class RemoveDeadCodeClass(JavaParserLabeledListener): - def __init__(self, Tokens: CommonTokenStream = None, Identifier: {} = None): - self.Class = False - self.Method = False - self.Field = False - self.Variable = False - self.Parameter = False - - self.Classes = Identifier["Classes"] - self.ClassIndex = 0 - - self.Methods = Identifier["Methods"] - self.MethodIndex = 0 - self.IsSourceClassForMethods = [None] * len(self.Methods) - - self.Fields = Identifier["Fields"] - self.FieldIndex = 0 - self.IsSourceClassForFields = [None] * len(self.Fields) - - self.Variables = Identifier["Variables"] - self.VariableIndex = 0 - self.IsSourceClassForVariables = [None] * len(self.Variables) - self.IsSourceMethodForVariables = [None] * len(self.Variables) - - self.Parameters = Identifier["Parameters"] - self.ParameterIndex = 0 - self.IsSourceClassForParameters = [None] * len(self.Parameters) - self.IsSourceMethodForParameters = [None] * len(self.Parameters) - - self.ParameterIndexCall = 0 - self.IsSourceClassForParametersCall = [None] * len(self.Parameters) - - if len(Identifier["Classes"]) != 0: - self.Class = True - - if len(Identifier["Methods"]) != 0: - self.Method = True - - if len(Identifier["Fields"]) != 0: - self.Field = True - if len(Identifier["Variables"]) != 0: - self.Variable = True - - if len(Identifier["Parameters"]) != 0: - self.Parameter = True - - if Tokens is not None: - self.CodeRewrite = TokenStreamRewriter(Tokens) - else: - raise TypeError('Tokens is None') - - def enterClassDeclaration(self, ctx: JavaParserLabeled.ClassDeclarationContext): - classIdentifier = ctx.IDENTIFIER().getText() - ctxParent = ctx.parentCtx - if self.Method: - for i in range(len(self.Methods)): - if self.Methods[i].split('/')[0] == classIdentifier: - self.IsSourceClassForMethods[i] = True - - if self.Field: - for i in range(len(self.Fields)): - if self.Fields[i].split('/')[0] == classIdentifier: - self.IsSourceClassForFields[i] = True - - if self.Variable: - for i in range(len(self.Variables)): - if self.Variables[i].split('/')[0] == classIdentifier: - self.IsSourceClassForVariables[i] = True - - if self.Parameter: - for i in range(len(self.Parameters)): - if self.Parameters[i].split('/')[0] == classIdentifier: - self.IsSourceClassForParameters[i] = True - - if self.Class and self.ClassIndex < len(self.Classes) and self.Classes[self.ClassIndex] == classIdentifier: - startIndex = ctxParent.start.tokenIndex - stopIndex = ctxParent.stop.tokenIndex - - self.CodeRewrite.delete( - self.CodeRewrite.DEFAULT_PROGRAM_NAME, - startIndex, - stopIndex - ) - self.ClassIndex += 1 - - def exitClassDeclaration(self, ctx: JavaParserLabeled.ClassDeclarationContext): - pass - - def enterMethodDeclaration(self, ctx: JavaParserLabeled.MethodDeclarationContext): - methodIdentifier = ctx.IDENTIFIER().getText() - if self.Variable: - for i in range(len(self.Variables)): - if self.IsSourceClassForVariables[i] and self.Variables[i].split('/')[1] == methodIdentifier: - self.IsSourceMethodForVariables[i] = True - - if self.Parameter: - for i in range(len(self.Parameters)): - if self.IsSourceClassForParameters[i] and self.Parameters[i].split('/')[1] == methodIdentifier: - self.IsSourceMethodForParameters[i] = True - pass - - def exitMethodDeclaration(self, ctx: JavaParserLabeled.MethodDeclarationContext): - grandParentCtx = ctx.parentCtx.parentCtx - methodIdentifier = ctx.IDENTIFIER().getText() - if self.Method and self.MethodIndex < len(self.Methods) and self.Methods[self.MethodIndex].split('/')[ - 1] == methodIdentifier: - if self.IsSourceClassForMethods[self.MethodIndex]: - self.CodeRewrite.delete( - self.CodeRewrite.DEFAULT_PROGRAM_NAME, - grandParentCtx.start.tokenIndex, - grandParentCtx.stop.tokenIndex - ) - self.MethodIndex += 1 - - def enterFieldDeclaration(self, ctx: JavaParserLabeled.FieldDeclarationContext): - pass - - def exitFieldDeclaration(self, ctx: JavaParserLabeled.FieldDeclarationContext): - fieldIdentifier = ctx.variableDeclarators().variableDeclarator(0).variableDeclaratorId().IDENTIFIER().getText() - grandParentCtx = ctx.parentCtx.parentCtx - - if self.Field and self.FieldIndex < len(self.Fields) and self.Fields[self.FieldIndex].split('/')[ - 1] == fieldIdentifier: - if self.IsSourceClassForFields[self.FieldIndex]: - self.CodeRewrite.delete( - self.CodeRewrite.DEFAULT_PROGRAM_NAME, - grandParentCtx.start.tokenIndex, - grandParentCtx.stop.tokenIndex - ) - self.FieldIndex += 1 - - def enterVariableDeclarator(self, ctx: JavaParserLabeled.VariableDeclaratorContext): - pass - - def exitVariableDeclarator(self, ctx: JavaParserLabeled.VariableDeclaratorContext): - variableIdentifier = ctx.variableDeclaratorId().IDENTIFIER().getText() - grandParentCtx = ctx.parentCtx.parentCtx.parentCtx - if self.Variable and self.VariableIndex < len(self.Variables) and self.Variables[self.VariableIndex].split('/')[2] == variableIdentifier: - if self.IsSourceClassForVariables[self.VariableIndex] and self.IsSourceMethodForVariables[ - self.VariableIndex]: - self.CodeRewrite.delete( - self.CodeRewrite.DEFAULT_PROGRAM_NAME, - grandParentCtx.start.tokenIndex, - grandParentCtx.stop.tokenIndex - ) - self.VariableIndex += 1 - - def enterFormalParameter(self, ctx: JavaParserLabeled.FormalParameterContext): - pass - - def exitFormalParameter(self, ctx: JavaParserLabeled.FormalParameterContext): - parameterIdentifier = ctx.variableDeclaratorId().IDENTIFIER().getText() - grandParentCtx = ctx - Parent = ctx.parentCtx.children - # for i in range(len(Parent)): - # print(Parent[i].variableDeclaratorId().IDENTIFIER().getText()) - - start = grandParentCtx.start.tokenIndex - stop = grandParentCtx.stop.tokenIndex - if self.Parameter and self.ParameterIndex < len(self.Parameters) and self.Parameters[self.ParameterIndex].split('/')[2] == parameterIdentifier: - if self.IsSourceClassForParameters[self.ParameterIndex] and self.IsSourceMethodForParameters[ - self.ParameterIndex]: - if self.Parameters[self.ParameterIndex].split('/')[3] != 0: - self.CodeRewrite.delete( - self.CodeRewrite.DEFAULT_PROGRAM_NAME, - start - 2, - stop - ) - - else: - self.CodeRewrite.delete( - self.CodeRewrite.DEFAULT_PROGRAM_NAME, - start, - stop + 1 - ) - self.ParameterIndex += 1 - - def exitMethodCall0(self, ctx:JavaParserLabeled.MethodCall0Context): - pass - # if self.Parameter and self.ParameterIndexCall < len(self.Parameters): - # if ctx.IDENTIFIER() in self.Parameters: - # Ind = self.Parameters[self.ParameterIndexCall].split('/')[3] - # parametersList = ctx.expressionList().expression(Ind).STRING_LITERAL() - # print(parametersList) - # start = parametersList.start.tokenIndex - # stop = parametersList.stop.tokenIndex - # self.CodeRewrite.delete( - # self.CodeRewrite.DEFAULT_PROGRAM_NAME, - # start, - # stop - # ) - # self.ParameterIndexCall += 1 - - -def main(): - # Path = "../tests/remove_dead_code" - Path = "../tests/remove_dead_code/json" - FolderPath = os.listdir(Path) - - Identifier = [ - {"Classes": [], - "Methods": [], - "Variables": [], - "Parameters": [], - "Fields": ["CDL/Field"]}, - {"Classes": ["Cookie"], - "Methods": [], - "Variables": [], - "Parameters": [], - "Fields": []}, - # This useless variable is just written to test this code on real project - {"Classes": [], - "Methods": ["CookieList/toJSONObject"], - "Variables": ["CookieList/toString/c"], - "Parameters": [], - "Fields": []}, - {"Classes": [], - "Methods": [], - "Variables": [], - "Parameters": ["HTTP/toJSONObject/Par/2"], - "Fields": []}, - {"Classes": [], - "Methods": [], - "Variables": [], - "Parameters": [], - "Fields": []}, - {"Classes": [], - "Methods": [], - "Variables": [], - "Parameters": [], - "Fields": []}, - {"Classes": [], - "Methods": [], - "Variables": [], - "Parameters": [], - "Fields": []}, - {"Classes": [], - "Methods": [], - "Variables": [], - "Parameters": [], - "Fields": []}, - {"Classes": [], - "Methods": [], - "Variables": [], - "Parameters": [], - "Fields": []}, - {"Classes": [], - "Methods": [], - "Variables": [], - "Parameters": [], - "Fields": []}, - {"Classes": [], - "Methods": [], - "Variables": [], - "Parameters": [], - "Fields": []}, - {"Classes": [], - "Methods": [], - "Variables": [], - "Parameters": [], - "Fields": []}, - {"Classes": [], - "Methods": [], - "Variables": [], - "Parameters": [], - "Fields": []}, - {"Classes": [], - "Methods": [], - "Variables": [], - "Parameters": [], - "Fields": []}, - {"Classes": [], - "Methods": [], - "Variables": [], - "Parameters": [], - "Fields": []}, - {"Classes": [], - "Methods": [], - "Variables": [], - "Parameters": [], - "Fields": []}, - {"Classes": [], - "Methods": [], - "Variables": [], - "Parameters": [], - "Fields": []}, - {"Classes": [], - "Methods": [], - "Variables": [], - "Parameters": [], - "Fields": []}, - {"Classes": [], - "Methods": [], - "Variables": [], - "Parameters": [], - "Fields": []}, - {"Classes": [], - "Methods": [], - "Variables": [], - "Parameters": [], - "Fields": []}, - {"Classes": [], - "Methods": [], - "Variables": [], - "Parameters": [], - "Fields": []}, - {"Classes": [], - "Methods": [], - "Variables": [], - "Parameters": [], - "Fields": []} - # {"Classes": ["Airplane"], - # "Methods": ["Car/Fly", "Engine/main2"], - # "Fields": ["Car/noway", "Engine/model"], - # "Variables": [], - # "Parameters": []}, - # - # {"Classes": [], - # "Methods": [], - # "Fields": [], - # "Variables": ["Car/main/dead", "Car/Run/number", "Engine/SetName/what", - # "Engine/main2/variable", "Engine/main2/dead"], - # "Parameters": ["Car/Drive/wheels/2", "Engine/main/k/2", "Engine/SetName/last/2"]}, - # - # {"Classes": ["Airplane"], - # "Methods": ["Car/Fly", "Engine/main2"], - # "Fields": ["Car/noway", "Engine/model"], - # "Variables": ["Car/main/dead", "Car/Run/number", "Engine/SetName/what", - # "Engine/main2/variable", "Engine/main2/dead"], - # "Parameters": ["Car/Drive/wheels/2", "Engine/main/k/2", "Engine/SetName/last/2"]} - ] - - i = 0 - for File in FolderPath: - # We have all of the java files in this folder now - if File.endswith('.java'): - EachFilePath = Path + "\\" + File - # Step 1: Load input source into stream - EachFile = FileStream(str(EachFilePath)) - - # Step 2: Create an instance of AssignmentStLexer - Lexer = JavaLexer(EachFile) - - # Step 3: Convert the input source into a list of tokens - TokenStream = CommonTokenStream(Lexer) - - # Step 4: Create an instance of the AssignmentStParser - Parser = JavaParserLabeled(TokenStream) - - # Step 5: Create parse tree - Tree = Parser.compilationUnit() - - # ListenerForDetection = DetectCodeClass() - # ListenerForDeadCodeDetection = DetectDeadCodeClass() - - if i < len(Identifier): - # This is a new Java file which is the result - Refactored = open(os.path.join(Path, File + "_Refactored.java"), mode='w', newline='') - - # Step 6: Create an instance of AssignmentStListener - ListenerForRemovingDeadCode = RemoveDeadCodeClass(TokenStream, Identifier[i]) - - Walker = ParseTreeWalker() - - # Walk - # Walker.walk(Listener, Tree) - # Walker.walk(ListenerOnMainCode, Tree) - - Walker.walk(ListenerForRemovingDeadCode, Tree) - - NewCode = str(ListenerForRemovingDeadCode.CodeRewrite.getDefaultText()) - Refactored.write(NewCode) - i += 1 - - -if __name__ == "__main__": - main() +""" + +""" +__version__ = '0.1.1' +__author__ = 'Morteza Zakeri' + +import os + +from antlr4 import * +from antlr4.TokenStreamRewriter import TokenStreamRewriter + +from codart.gen.javaLabeled.JavaParserLabeled import JavaParserLabeled +from codart.gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener +from codart.gen.javaLabeled.JavaLexer import JavaLexer + + +# This is the class for detecting all of the types. +class DetectCodeClass(JavaParserLabeledListener): + def __init__(self): + self.Variables = [] + self.Fields = [] + self.MethodParameters = [] + self.Methods = [] + self.Classes = [] + + def enterVariableDeclarator(self, ctx: JavaParserLabeled.VariableDeclaratorContext): + self.Variables.append(str(ctx.variableDeclaratorId().IDENTIFIER())) + + def exitVariableDeclarator(self, ctx: JavaParserLabeled.VariableDeclaratorContext): + pass + + def enterMethodDeclaration(self, ctx: JavaParserLabeled.MethodDeclarationContext): + self.Methods.append(str(ctx.IDENTIFIER())) + self.MethodParameters.append(str(ctx.formalParameters())) + + def exitMethodDeclaration(self, ctx: JavaParserLabeled.MethodDeclarationContext): + pass + + def enterClassDeclaration(self, ctx: JavaParserLabeled.ClassDeclarationContext): + self.Classes.append(str(ctx.IDENTIFIER())) + + def exitClassDeclaration(self, ctx: JavaParserLabeled.ClassDeclarationContext): + pass + + +# This is the class for detecting dead codes. +class DetectDeadCodeClass(JavaParserLabeledListener): + def __init__(self): + self.DeadVariables = [] + self.DeadMethodParameters = [] + self.Fields = [] + self.DeadMethods = [] + self.DeadClasses = [] + + pass + + +# This is the class to remove dead codes. +class RemoveDeadCodeClass(JavaParserLabeledListener): + def __init__(self, Tokens: CommonTokenStream = None, Identifier: {} = None): + self.Class = False + self.Method = False + self.Field = False + self.Variable = False + self.Parameter = False + + self.Classes = Identifier["Classes"] + self.ClassIndex = 0 + + self.Methods = Identifier["Methods"] + self.MethodIndex = 0 + self.IsSourceClassForMethods = [None] * len(self.Methods) + + self.Fields = Identifier["Fields"] + self.FieldIndex = 0 + self.IsSourceClassForFields = [None] * len(self.Fields) + + self.Variables = Identifier["Variables"] + self.VariableIndex = 0 + self.IsSourceClassForVariables = [None] * len(self.Variables) + self.IsSourceMethodForVariables = [None] * len(self.Variables) + + self.Parameters = Identifier["Parameters"] + self.ParameterIndex = 0 + self.IsSourceClassForParameters = [None] * len(self.Parameters) + self.IsSourceMethodForParameters = [None] * len(self.Parameters) + + self.ParameterIndexCall = 0 + self.IsSourceClassForParametersCall = [None] * len(self.Parameters) + + if len(Identifier["Classes"]) != 0: + self.Class = True + + if len(Identifier["Methods"]) != 0: + self.Method = True + + if len(Identifier["Fields"]) != 0: + self.Field = True + if len(Identifier["Variables"]) != 0: + self.Variable = True + + if len(Identifier["Parameters"]) != 0: + self.Parameter = True + + if Tokens is not None: + self.CodeRewrite = TokenStreamRewriter(Tokens) + else: + raise TypeError('Tokens is None') + + def enterClassDeclaration(self, ctx: JavaParserLabeled.ClassDeclarationContext): + classIdentifier = ctx.IDENTIFIER().getText() + ctxParent = ctx.parentCtx + if self.Method: + for i in range(len(self.Methods)): + if self.Methods[i].split('/')[0] == classIdentifier: + self.IsSourceClassForMethods[i] = True + + if self.Field: + for i in range(len(self.Fields)): + if self.Fields[i].split('/')[0] == classIdentifier: + self.IsSourceClassForFields[i] = True + + if self.Variable: + for i in range(len(self.Variables)): + if self.Variables[i].split('/')[0] == classIdentifier: + self.IsSourceClassForVariables[i] = True + + if self.Parameter: + for i in range(len(self.Parameters)): + if self.Parameters[i].split('/')[0] == classIdentifier: + self.IsSourceClassForParameters[i] = True + + if self.Class and self.ClassIndex < len(self.Classes) and self.Classes[self.ClassIndex] == classIdentifier: + startIndex = ctxParent.start.tokenIndex + stopIndex = ctxParent.stop.tokenIndex + + self.CodeRewrite.delete( + self.CodeRewrite.DEFAULT_PROGRAM_NAME, + startIndex, + stopIndex + ) + self.ClassIndex += 1 + + def exitClassDeclaration(self, ctx: JavaParserLabeled.ClassDeclarationContext): + pass + + def enterMethodDeclaration(self, ctx: JavaParserLabeled.MethodDeclarationContext): + methodIdentifier = ctx.IDENTIFIER().getText() + if self.Variable: + for i in range(len(self.Variables)): + if self.IsSourceClassForVariables[i] and self.Variables[i].split('/')[1] == methodIdentifier: + self.IsSourceMethodForVariables[i] = True + + if self.Parameter: + for i in range(len(self.Parameters)): + if self.IsSourceClassForParameters[i] and self.Parameters[i].split('/')[1] == methodIdentifier: + self.IsSourceMethodForParameters[i] = True + pass + + def exitMethodDeclaration(self, ctx: JavaParserLabeled.MethodDeclarationContext): + grandParentCtx = ctx.parentCtx.parentCtx + methodIdentifier = ctx.IDENTIFIER().getText() + if self.Method and self.MethodIndex < len(self.Methods) and self.Methods[self.MethodIndex].split('/')[ + 1] == methodIdentifier: + if self.IsSourceClassForMethods[self.MethodIndex]: + self.CodeRewrite.delete( + self.CodeRewrite.DEFAULT_PROGRAM_NAME, + grandParentCtx.start.tokenIndex, + grandParentCtx.stop.tokenIndex + ) + self.MethodIndex += 1 + + def enterFieldDeclaration(self, ctx: JavaParserLabeled.FieldDeclarationContext): + pass + + def exitFieldDeclaration(self, ctx: JavaParserLabeled.FieldDeclarationContext): + fieldIdentifier = ctx.variableDeclarators().variableDeclarator(0).variableDeclaratorId().IDENTIFIER().getText() + grandParentCtx = ctx.parentCtx.parentCtx + + if self.Field and self.FieldIndex < len(self.Fields) and self.Fields[self.FieldIndex].split('/')[ + 1] == fieldIdentifier: + if self.IsSourceClassForFields[self.FieldIndex]: + self.CodeRewrite.delete( + self.CodeRewrite.DEFAULT_PROGRAM_NAME, + grandParentCtx.start.tokenIndex, + grandParentCtx.stop.tokenIndex + ) + self.FieldIndex += 1 + + def enterVariableDeclarator(self, ctx: JavaParserLabeled.VariableDeclaratorContext): + pass + + def exitVariableDeclarator(self, ctx: JavaParserLabeled.VariableDeclaratorContext): + variableIdentifier = ctx.variableDeclaratorId().IDENTIFIER().getText() + grandParentCtx = ctx.parentCtx.parentCtx.parentCtx + if self.Variable and self.VariableIndex < len(self.Variables) and self.Variables[self.VariableIndex].split('/')[2] == variableIdentifier: + if self.IsSourceClassForVariables[self.VariableIndex] and self.IsSourceMethodForVariables[ + self.VariableIndex]: + self.CodeRewrite.delete( + self.CodeRewrite.DEFAULT_PROGRAM_NAME, + grandParentCtx.start.tokenIndex, + grandParentCtx.stop.tokenIndex + ) + self.VariableIndex += 1 + + def enterFormalParameter(self, ctx: JavaParserLabeled.FormalParameterContext): + pass + + def exitFormalParameter(self, ctx: JavaParserLabeled.FormalParameterContext): + parameterIdentifier = ctx.variableDeclaratorId().IDENTIFIER().getText() + grandParentCtx = ctx + Parent = ctx.parentCtx.children + # for i in range(len(Parent)): + # print(Parent[i].variableDeclaratorId().IDENTIFIER().getText()) + + start = grandParentCtx.start.tokenIndex + stop = grandParentCtx.stop.tokenIndex + if self.Parameter and self.ParameterIndex < len(self.Parameters) and self.Parameters[self.ParameterIndex].split('/')[2] == parameterIdentifier: + if self.IsSourceClassForParameters[self.ParameterIndex] and self.IsSourceMethodForParameters[ + self.ParameterIndex]: + if self.Parameters[self.ParameterIndex].split('/')[3] != 0: + self.CodeRewrite.delete( + self.CodeRewrite.DEFAULT_PROGRAM_NAME, + start - 2, + stop + ) + + else: + self.CodeRewrite.delete( + self.CodeRewrite.DEFAULT_PROGRAM_NAME, + start, + stop + 1 + ) + self.ParameterIndex += 1 + + def exitMethodCall0(self, ctx:JavaParserLabeled.MethodCall0Context): + pass + # if self.Parameter and self.ParameterIndexCall < len(self.Parameters): + # if ctx.IDENTIFIER() in self.Parameters: + # Ind = self.Parameters[self.ParameterIndexCall].split('/')[3] + # parametersList = ctx.expressionList().expression(Ind).STRING_LITERAL() + # print(parametersList) + # start = parametersList.start.tokenIndex + # stop = parametersList.stop.tokenIndex + # self.CodeRewrite.delete( + # self.CodeRewrite.DEFAULT_PROGRAM_NAME, + # start, + # stop + # ) + # self.ParameterIndexCall += 1 + + +def main(): + # Path = "../tests/remove_dead_code" + Path = "../tests/remove_dead_code/json" + FolderPath = os.listdir(Path) + + Identifier = [ + {"Classes": [], + "Methods": [], + "Variables": [], + "Parameters": [], + "Fields": ["CDL/Field"]}, + {"Classes": ["Cookie"], + "Methods": [], + "Variables": [], + "Parameters": [], + "Fields": []}, + # This useless variable is just written to test this code on real project + {"Classes": [], + "Methods": ["CookieList/toJSONObject"], + "Variables": ["CookieList/toString/c"], + "Parameters": [], + "Fields": []}, + {"Classes": [], + "Methods": [], + "Variables": [], + "Parameters": ["HTTP/toJSONObject/Par/2"], + "Fields": []}, + {"Classes": [], + "Methods": [], + "Variables": [], + "Parameters": [], + "Fields": []}, + {"Classes": [], + "Methods": [], + "Variables": [], + "Parameters": [], + "Fields": []}, + {"Classes": [], + "Methods": [], + "Variables": [], + "Parameters": [], + "Fields": []}, + {"Classes": [], + "Methods": [], + "Variables": [], + "Parameters": [], + "Fields": []}, + {"Classes": [], + "Methods": [], + "Variables": [], + "Parameters": [], + "Fields": []}, + {"Classes": [], + "Methods": [], + "Variables": [], + "Parameters": [], + "Fields": []}, + {"Classes": [], + "Methods": [], + "Variables": [], + "Parameters": [], + "Fields": []}, + {"Classes": [], + "Methods": [], + "Variables": [], + "Parameters": [], + "Fields": []}, + {"Classes": [], + "Methods": [], + "Variables": [], + "Parameters": [], + "Fields": []}, + {"Classes": [], + "Methods": [], + "Variables": [], + "Parameters": [], + "Fields": []}, + {"Classes": [], + "Methods": [], + "Variables": [], + "Parameters": [], + "Fields": []}, + {"Classes": [], + "Methods": [], + "Variables": [], + "Parameters": [], + "Fields": []}, + {"Classes": [], + "Methods": [], + "Variables": [], + "Parameters": [], + "Fields": []}, + {"Classes": [], + "Methods": [], + "Variables": [], + "Parameters": [], + "Fields": []}, + {"Classes": [], + "Methods": [], + "Variables": [], + "Parameters": [], + "Fields": []}, + {"Classes": [], + "Methods": [], + "Variables": [], + "Parameters": [], + "Fields": []}, + {"Classes": [], + "Methods": [], + "Variables": [], + "Parameters": [], + "Fields": []}, + {"Classes": [], + "Methods": [], + "Variables": [], + "Parameters": [], + "Fields": []} + # {"Classes": ["Airplane"], + # "Methods": ["Car/Fly", "Engine/main2"], + # "Fields": ["Car/noway", "Engine/model"], + # "Variables": [], + # "Parameters": []}, + # + # {"Classes": [], + # "Methods": [], + # "Fields": [], + # "Variables": ["Car/main/dead", "Car/Run/number", "Engine/SetName/what", + # "Engine/main2/variable", "Engine/main2/dead"], + # "Parameters": ["Car/Drive/wheels/2", "Engine/main/k/2", "Engine/SetName/last/2"]}, + # + # {"Classes": ["Airplane"], + # "Methods": ["Car/Fly", "Engine/main2"], + # "Fields": ["Car/noway", "Engine/model"], + # "Variables": ["Car/main/dead", "Car/Run/number", "Engine/SetName/what", + # "Engine/main2/variable", "Engine/main2/dead"], + # "Parameters": ["Car/Drive/wheels/2", "Engine/main/k/2", "Engine/SetName/last/2"]} + ] + + i = 0 + for File in FolderPath: + # We have all of the java files in this folder now + if File.endswith('.java'): + EachFilePath = Path + "\\" + File + # Step 1: Load input source into stream + EachFile = FileStream(str(EachFilePath)) + + # Step 2: Create an instance of AssignmentStLexer + Lexer = JavaLexer(EachFile) + + # Step 3: Convert the input source into a list of tokens + TokenStream = CommonTokenStream(Lexer) + + # Step 4: Create an instance of the AssignmentStParser + Parser = JavaParserLabeled(TokenStream) + + # Step 5: Create parse tree + Tree = Parser.compilationUnit() + + # ListenerForDetection = DetectCodeClass() + # ListenerForDeadCodeDetection = DetectDeadCodeClass() + + if i < len(Identifier): + # This is a new Java file which is the result + Refactored = open(os.path.join(Path, File + "_Refactored.java"), mode='w', newline='') + + # Step 6: Create an instance of AssignmentStListener + ListenerForRemovingDeadCode = RemoveDeadCodeClass(TokenStream, Identifier[i]) + + Walker = ParseTreeWalker() + + # Walk + # Walker.walk(Listener, Tree) + # Walker.walk(ListenerOnMainCode, Tree) + + Walker.walk(ListenerForRemovingDeadCode, Tree) + + NewCode = str(ListenerForRemovingDeadCode.CodeRewrite.getDefaultText()) + Refactored.write(NewCode) + i += 1 + + +if __name__ == "__main__": + main() diff --git a/refactorings/remove_field.py b/codart/refactorings/remove_field.py similarity index 94% rename from refactorings/remove_field.py rename to codart/refactorings/remove_field.py index 110ded39..2a17af7e 100644 --- a/refactorings/remove_field.py +++ b/codart/refactorings/remove_field.py @@ -13,9 +13,9 @@ from antlr4 import * from antlr4.TokenStreamRewriter import TokenStreamRewriter -from gen.javaLabeled.JavaLexer import JavaLexer -from gen.javaLabeled.JavaParserLabeled import JavaParserLabeled -from gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener +from codart.gen.javaLabeled.JavaLexer import JavaLexer +from codart.gen.javaLabeled.JavaParserLabeled import JavaParserLabeled +from codart.gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener class RemoveFieldRefactoringListener(JavaParserLabeledListener): diff --git a/refactorings/remove_flag_argument.py b/codart/refactorings/remove_flag_argument.py similarity index 97% rename from refactorings/remove_flag_argument.py rename to codart/refactorings/remove_flag_argument.py index 8836295b..a5c4badf 100644 --- a/refactorings/remove_flag_argument.py +++ b/codart/refactorings/remove_flag_argument.py @@ -10,9 +10,9 @@ from antlr4 import * from antlr4.TokenStreamRewriter import TokenStreamRewriter -from gen.javaLabeled.JavaLexer import JavaLexer -from gen.javaLabeled.JavaParserLabeled import JavaParserLabeled -from gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener +from codart.gen.javaLabeled.JavaLexer import JavaLexer +from codart.gen.javaLabeled.JavaParserLabeled import JavaParserLabeled +from codart.gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener class RemoveFlagArgumentListener(JavaParserLabeledListener): diff --git a/refactorings/remove_interface.py b/codart/refactorings/remove_interface.py similarity index 93% rename from refactorings/remove_interface.py rename to codart/refactorings/remove_interface.py index 0f55019e..81879f9e 100644 --- a/refactorings/remove_interface.py +++ b/codart/refactorings/remove_interface.py @@ -10,9 +10,9 @@ from antlr4 import * from antlr4.TokenStreamRewriter import TokenStreamRewriter -from gen.javaLabeled.JavaLexer import JavaLexer -from gen.javaLabeled.JavaParserLabeled import JavaParserLabeled -from gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener +from codart.gen.javaLabeled.JavaLexer import JavaLexer +from codart.gen.javaLabeled.JavaParserLabeled import JavaParserLabeled +from codart.gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener class RemoveInterfaceRefactoringListener(JavaParserLabeledListener): diff --git a/refactorings/remove_method.py b/codart/refactorings/remove_method.py similarity index 94% rename from refactorings/remove_method.py rename to codart/refactorings/remove_method.py index 879d72a5..f0980ca5 100644 --- a/refactorings/remove_method.py +++ b/codart/refactorings/remove_method.py @@ -9,9 +9,9 @@ from antlr4 import * from antlr4.TokenStreamRewriter import TokenStreamRewriter -from gen.javaLabeled.JavaLexer import JavaLexer -from gen.javaLabeled.JavaParserLabeled import JavaParserLabeled -from gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener +from codart.gen.javaLabeled.JavaLexer import JavaLexer +from codart.gen.javaLabeled.JavaParserLabeled import JavaParserLabeled +from codart.gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener class RemoveMethodRefactoringListener(JavaParserLabeledListener): diff --git a/refactorings/rename_class.py b/codart/refactorings/rename_class.py similarity index 97% rename from refactorings/rename_class.py rename to codart/refactorings/rename_class.py index 6c0d1d56..d8f90bdb 100644 --- a/refactorings/rename_class.py +++ b/codart/refactorings/rename_class.py @@ -21,9 +21,9 @@ from antlr4 import * from antlr4.TokenStreamRewriter import TokenStreamRewriter -from gen.javaLabeled.JavaLexer import JavaLexer -from gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener -from gen.javaLabeled.JavaParserLabeled import JavaParserLabeled +from codart.gen.javaLabeled.JavaLexer import JavaLexer +from codart.gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener +from codart.gen.javaLabeled.JavaParserLabeled import JavaParserLabeled class RenameClassRefactoringListener(JavaParserLabeledListener): diff --git a/refactorings/rename_class2.py b/codart/refactorings/rename_class2.py similarity index 95% rename from refactorings/rename_class2.py rename to codart/refactorings/rename_class2.py index 84fbd3ea..65740d1b 100644 --- a/refactorings/rename_class2.py +++ b/codart/refactorings/rename_class2.py @@ -24,11 +24,11 @@ from antlr4 import * from antlr4.TokenStreamRewriter import TokenStreamRewriter -from gen.javaLabeled.JavaParserLabeled import JavaParserLabeled -from gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener -from gen.javaLabeled.JavaLexer import JavaLexer +from codart.gen.javaLabeled.JavaParserLabeled import JavaParserLabeled +from codart.gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener +from codart.gen.javaLabeled.JavaLexer import JavaLexer -sys.path.append('../') +sys.path.append('../../') class RenameClassRefactoringListener(JavaParserLabeledListener): @@ -140,7 +140,7 @@ def change_file_name(old, new): def main(): - Path = "../tests/rename_tests/benchmark" + Path = "../../tests/rename_tests/benchmark" Package_name = "org.json" class_identifier = "CDL" new_class_name = "test" diff --git a/refactorings/rename_field.py b/codart/refactorings/rename_field.py similarity index 96% rename from refactorings/rename_field.py rename to codart/refactorings/rename_field.py index 51e6c927..639e4fe3 100644 --- a/refactorings/rename_field.py +++ b/codart/refactorings/rename_field.py @@ -23,11 +23,11 @@ from antlr4 import * from antlr4.TokenStreamRewriter import TokenStreamRewriter -from gen.javaLabeled.JavaParserLabeled import JavaParserLabeled -from gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener -from gen.javaLabeled.JavaLexer import JavaLexer +from codart.gen.javaLabeled.JavaParserLabeled import JavaParserLabeled +from codart.gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener +from codart.gen.javaLabeled.JavaLexer import JavaLexer -sys.path.append('../') +sys.path.append('../../') class RenameFieldRefactoringListener(JavaParserLabeledListener): @@ -166,7 +166,7 @@ def enterVariableInitializer1(self, ctx: JavaParserLabeled.VariableInitializer1C def main(): - path_ = "../tests/rename_tests/benchmark" + path_ = "../../tests/rename_tests/benchmark" package_name_ = "org.json" class_identifier_ = "HTTP" field_identifier_ = "CRLF" diff --git a/refactorings/rename_method.py b/codart/refactorings/rename_method.py similarity index 97% rename from refactorings/rename_method.py rename to codart/refactorings/rename_method.py index 5081dcc1..be604936 100644 --- a/refactorings/rename_method.py +++ b/codart/refactorings/rename_method.py @@ -44,9 +44,9 @@ from antlr4 import * from antlr4.TokenStreamRewriter import TokenStreamRewriter -from gen.javaLabeled.JavaLexer import JavaLexer -from gen.javaLabeled.JavaParserLabeled import JavaParserLabeled -from gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener +from codart.gen.javaLabeled.JavaLexer import JavaLexer +from codart.gen.javaLabeled.JavaParserLabeled import JavaParserLabeled +from codart.gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener class RenameMethodListener(JavaParserLabeledListener): diff --git a/refactorings/rename_method2.py b/codart/refactorings/rename_method2.py similarity index 95% rename from refactorings/rename_method2.py rename to codart/refactorings/rename_method2.py index 58c031fb..c5d1e420 100644 --- a/refactorings/rename_method2.py +++ b/codart/refactorings/rename_method2.py @@ -26,11 +26,11 @@ from antlr4 import * from antlr4.TokenStreamRewriter import TokenStreamRewriter -from gen.javaLabeled.JavaParserLabeled import JavaParserLabeled -from gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener -from gen.javaLabeled.JavaLexer import JavaLexer +from codart.gen.javaLabeled.JavaParserLabeled import JavaParserLabeled +from codart.gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener +from codart.gen.javaLabeled.JavaLexer import JavaLexer -sys.path.append('../') +sys.path.append('../../') class RenameMethodRefactoringListener(JavaParserLabeledListener): @@ -125,7 +125,7 @@ def enterMethodCall0(self, ctx: JavaParserLabeled.MethodCall0Context): def main(): - Path = "../tests/rename_tests/benchmark" + Path = "../../tests/rename_tests/benchmark" Package_name = "org.json" class_identifier = "CDL" method_identifier = "getValue" diff --git a/refactorings/rename_package.py b/codart/refactorings/rename_package.py similarity index 95% rename from refactorings/rename_package.py rename to codart/refactorings/rename_package.py index 030c9950..f91245b5 100644 --- a/refactorings/rename_package.py +++ b/codart/refactorings/rename_package.py @@ -22,12 +22,12 @@ from antlr4 import * from antlr4.TokenStreamRewriter import TokenStreamRewriter -from gen.javaLabeled.JavaParserLabeled import JavaParserLabeled -from gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener -from gen.javaLabeled.JavaLexer import JavaLexer +from codart.gen.javaLabeled.JavaParserLabeled import JavaParserLabeled +from codart.gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener +from codart.gen.javaLabeled.JavaLexer import JavaLexer -sys.path.append('../') +sys.path.append('../../') class FindPackages(JavaParserLabeledListener): @@ -114,7 +114,7 @@ def enterImportDeclaration(self, ctx: JavaParserLabeled.ImportDeclarationContext def main(): - Path = "../tests/rename_tests/benchmark" + Path = "../../tests/rename_tests/benchmark" package_identifier = "json" new_package_name = "test" diff --git a/refactorings/replace_conditional_with_polymorphism.py b/codart/refactorings/replace_conditional_with_polymorphism.py similarity index 93% rename from refactorings/replace_conditional_with_polymorphism.py rename to codart/refactorings/replace_conditional_with_polymorphism.py index b02a4e21..4c9a51cc 100644 --- a/refactorings/replace_conditional_with_polymorphism.py +++ b/codart/refactorings/replace_conditional_with_polymorphism.py @@ -4,13 +4,11 @@ """ from antlr4 import * -from gen.javaLabeled.JavaLexer import JavaLexer +from codart.gen.javaLabeled.JavaLexer import JavaLexer -from gen.javaLabeled.JavaParserLabeled import JavaParserLabeled +from codart.gen.javaLabeled.JavaParserLabeled import JavaParserLabeled -from gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener - -import ntpath +from codart.gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener switches = [] switch_type = "" @@ -30,7 +28,7 @@ def __init__(self, file_path: str, class_name: str, method_name: str): self.found_class = False self.found_func = False if file_path is None: - self.file = "../tests/replace_conditional_with_polymorphism/sample.java" + self.file = "../../tests/replace_conditional_with_polymorphism/sample.java" else: self.file = file_path if class_name is None: @@ -63,7 +61,7 @@ def exitClassDeclaration(self, ctx: JavaParserLabeled.ClassDeclarationContext): if __name__ == '__main__': - listener = ReplaceConditionalWithPolymorphism("../tests/replace_conditional_with_polymorphism/sample.java", + listener = ReplaceConditionalWithPolymorphism("../../tests/replace_conditional_with_polymorphism/sample.java", "SwitchDemo", "myMethod") try: stream = FileStream(listener.file) diff --git a/refactorings/replace_constructor_with_factory_function.py b/codart/refactorings/replace_constructor_with_factory_function.py similarity index 95% rename from refactorings/replace_constructor_with_factory_function.py rename to codart/refactorings/replace_constructor_with_factory_function.py index 02de07e2..ed89e2f0 100644 --- a/refactorings/replace_constructor_with_factory_function.py +++ b/codart/refactorings/replace_constructor_with_factory_function.py @@ -6,9 +6,9 @@ import os from antlr4 import * from antlr4.TokenStreamRewriter import TokenStreamRewriter -from gen.javaLabeled.JavaParserLabeled import JavaParserLabeled -from gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener -from gen.javaLabeled.JavaLexer import JavaLexer +from codart.gen.javaLabeled.JavaParserLabeled import JavaParserLabeled +from codart.gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener +from codart.gen.javaLabeled.JavaLexer import JavaLexer class ReplaceConstructorWithFactoryFunctionRefactoringListener(JavaParserLabeledListener): @@ -121,7 +121,7 @@ def enterExpression4(self, ctx: JavaParserLabeled.Expression4Context): def main(): # folder_path = "..\\benchmark_projects\\JSON\\src\\main\\java\\org\\json" - folder_path = "..\\tests\\replace_constructor_with_factory_function_tests" + folder_path = "../../tests/replace_constructor_with_factory_function_tests" path = os.listdir(folder_path) # target_class = "CDL" target_class = "Employee" diff --git a/refactorings/replace_exception_with_test.py b/codart/refactorings/replace_exception_with_test.py similarity index 99% rename from refactorings/replace_exception_with_test.py rename to codart/refactorings/replace_exception_with_test.py index 9c850db9..48fcb616 100644 --- a/refactorings/replace_exception_with_test.py +++ b/codart/refactorings/replace_exception_with_test.py @@ -8,10 +8,6 @@ from antlr4.TokenStreamRewriter import TokenStreamRewriter as TSR -from gen.javaLabeled.JavaLexer import * -from gen.javaLabeled.JavaParserLabeled import * -from gen.javaLabeled.JavaParserLabeledListener import * - class ReplaceExceptionWithTestClassRefactoringListener(JavaParserLabeledListener): def __init__(self, common_token_stream: CommonTokenStream = None, diff --git a/refactorings/replace_parameter_with_query.py b/codart/refactorings/replace_parameter_with_query.py similarity index 97% rename from refactorings/replace_parameter_with_query.py rename to codart/refactorings/replace_parameter_with_query.py index 3cc9d316..9d2c8940 100644 --- a/refactorings/replace_parameter_with_query.py +++ b/codart/refactorings/replace_parameter_with_query.py @@ -11,9 +11,9 @@ from antlr4 import * from antlr4.TokenStreamRewriter import TokenStreamRewriter -from gen.java.JavaLexer import JavaLexer -from gen.javaLabeled.JavaParserLabeled import JavaParserLabeled -from gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener +from codart.gen.java.JavaLexer import JavaLexer +from codart.gen.javaLabeled.JavaParserLabeled import JavaParserLabeled +from codart.gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener class ReplaceParameterWithQueryRefactoringListener(JavaParserLabeledListener): diff --git a/refactorings/replace_parameter_with_query2 .py b/codart/refactorings/replace_parameter_with_query2 .py similarity index 97% rename from refactorings/replace_parameter_with_query2 .py rename to codart/refactorings/replace_parameter_with_query2 .py index 0de9b86b..79e3047e 100644 --- a/refactorings/replace_parameter_with_query2 .py +++ b/codart/refactorings/replace_parameter_with_query2 .py @@ -14,9 +14,9 @@ from antlr4 import * from antlr4.TokenStreamRewriter import TokenStreamRewriter -from gen.java.JavaLexer import JavaLexer -from gen.javaLabeled.JavaParserLabeled import JavaParserLabeled -from gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener +from codart.gen.java.JavaLexer import JavaLexer +from codart.gen.javaLabeled.JavaParserLabeled import JavaParserLabeled +from codart.gen.javaLabeled.JavaParserLabeledListener import JavaParserLabeledListener class ReplaceParameterWithQueryListener(JavaParserLabeledListener): @@ -244,7 +244,7 @@ def do_refactor(self): if __name__ == '__main__': ReplaceParameterWithQueryAPI( - file_path="../tests/replace_parameter_with_quey_test/test4.java", + file_path="../../tests/replace_parameter_with_quey_test/test4.java", target_class='phase', target_method="bubbleSort", target_parameters=[1], diff --git a/sbse/__init__.py b/codart/sbse/__init__.py similarity index 100% rename from sbse/__init__.py rename to codart/sbse/__init__.py diff --git a/sbse/initialize.py b/codart/sbse/initialize.py similarity index 99% rename from sbse/initialize.py rename to codart/sbse/initialize.py index add60b05..5cd47a80 100644 --- a/sbse/initialize.py +++ b/codart/sbse/initialize.py @@ -31,17 +31,18 @@ import understand as und -from codart.utility.directory_utils import reset_project, update_understand_database +from codart.utility.directory_utils import reset_project -from refactorings import ( +from codart.refactorings import ( make_field_static, make_field_non_static, make_method_static2, make_method_non_static2, - move_field, move_method, move_class, + move_method, move_class, extract_method, extract_class, extract_interface2, pullup_field, pushdown_field2, pullup_method, pushdown_method, pullup_constructor, - increase_field_visibility, decrease_field_visibility, increase_method_visibility, decrease_method_visibility + decrease_field_visibility, increase_method_visibility, decrease_method_visibility ) +from codart.refactorings import move_field, increase_field_visibility -from sbse import config +from codart import config logger = config.logger diff --git a/sbse/random_search.py b/codart/sbse/random_search.py similarity index 95% rename from sbse/random_search.py rename to codart/sbse/random_search.py index 938ebf0f..5d2251bd 100644 --- a/sbse/random_search.py +++ b/codart/sbse/random_search.py @@ -10,9 +10,9 @@ import random from initialize import RandomInitialization -from metrics.qmood import DesignQualityAttributes +from codart.metrics.qmood import DesignQualityAttributes from codart.utility.directory_utils import update_understand_database, git_restore -from config import * +from codart.config import * # udb_path = "D:\Dev\ganttproject\ganttproject.udb" # project_dir = "D:\Dev\ganttproject" diff --git a/sbse/search_based_refactoring.py b/codart/sbse/search_based_refactoring.py similarity index 98% rename from sbse/search_based_refactoring.py rename to codart/sbse/search_based_refactoring.py index 29c06a95..afc51492 100644 --- a/sbse/search_based_refactoring.py +++ b/codart/sbse/search_based_refactoring.py @@ -30,12 +30,12 @@ from pymoo.core.sampling import Sampling from pymoo.optimize import minimize -from sbse import config -from sbse.config import logger -from sbse.initialize import RandomInitialization -from metrics.qmood import DesignQualityAttributes -from metrics.testability_prediction import main as testability_main -from metrics.modularity import main as modularity_main +from codart import config +from codart.config import logger +from codart.sbse.initialize import RandomInitialization +from codart.metrics.qmood import DesignQualityAttributes +from codart.metrics.testability_prediction import main as testability_main +from codart.metrics.modularity import main as modularity_main from codart.utility.directory_utils import update_understand_database, git_restore diff --git a/sbse/search_based_refactoring2.py b/codart/sbse/search_based_refactoring2.py similarity index 99% rename from sbse/search_based_refactoring2.py rename to codart/sbse/search_based_refactoring2.py index 6787c3e9..de252788 100644 --- a/sbse/search_based_refactoring2.py +++ b/codart/sbse/search_based_refactoring2.py @@ -81,14 +81,14 @@ from pymoo.optimize import minimize from pymoo.util.termination.default import MultiObjectiveDefaultTermination -from metrics.qmood import DesignQualityAttributes -from metrics.modularity import main as modularity_main -from metrics.testability_prediction2 import main as testability_main +from codart.metrics.qmood import DesignQualityAttributes +from codart.metrics.modularity import main as modularity_main +from codart.metrics.testability_prediction2 import main as testability_main from codart.utility.directory_utils import update_understand_database, git_restore, reset_project -from sbse.initialize import RandomInitialization, SmellInitialization, Initialization -from sbse import config -from sbse.config import logger +from codart.sbse.initialize import RandomInitialization, SmellInitialization, Initialization +from codart import config +from codart.config import logger POPULATION = [] diff --git a/sbse/sequence_application.py b/codart/sbse/sequence_application.py similarity index 95% rename from sbse/sequence_application.py rename to codart/sbse/sequence_application.py index 172575b5..d4168442 100644 --- a/sbse/sequence_application.py +++ b/codart/sbse/sequence_application.py @@ -15,14 +15,10 @@ import pandas as pd -import sbse.config as config -from codart.utility.directory_utils import create_understand_database, reset_project, update_understand_database -from sbse.initialize import REFACTORING_MAIN_MAP -from sbse.search_based_refactoring2 import log_project_info - -from metrics import qmood -from metrics.modularity import main as modularity_main -from metrics.testability_prediction2 import main as testability_main +import codart.config as config +from codart.utility.directory_utils import reset_project, update_understand_database +from codart.sbse.initialize import REFACTORING_MAIN_MAP +from codart.sbse.search_based_refactoring2 import log_project_info class RefactoringSequenceEvaluation: @@ -95,7 +91,7 @@ def execute_from_json_log(self, input_file_path=None, reset=True): if input_file_path is None: input_file_path = glob.glob(os.path.join(self.log_directory, 'best_refactoring_sequences*.json'))[0] - log_project_info(reset_=True, ) + # log_project_info(reset_=True, ) population = [] with open(input_file_path, 'r', encoding='utf-8') as fp: @@ -150,6 +146,8 @@ def execute_from_json_log(self, input_file_path=None, reset=True): applicability_map['Applied refactorings'].append(true_refactorings_count) applicability_map['Rejected refactorings'].append(false_refactorings_count) + continue + # Dump refactored project dump_path = os.path.join( config.PROJECT_ROOT_DIR, @@ -257,6 +255,6 @@ def measure_ad_hoc_project_quality(): # execute_refactoring_sequence() eval_ = RefactoringSequenceEvaluation(log_directory=config.PROJECT_LOG_DIR) eval_.execute_from_json_log(reset=False) - eval_.evaluate_sequences() + # eval_.evaluate_sequences() # eval_.analysis_refactoring_sequences() \ No newline at end of file diff --git a/sbse/simple_genetics.py b/codart/sbse/simple_genetics.py similarity index 77% rename from sbse/simple_genetics.py rename to codart/sbse/simple_genetics.py index 430be543..2b4a3f65 100644 --- a/sbse/simple_genetics.py +++ b/codart/sbse/simple_genetics.py @@ -1,35 +1,32 @@ -""" -Search-based refactoring with genetic algorithm - -""" - -__version__ = '0.1.' -__author__ = 'Morteza Zakeri' - -from pymoo.algorithms.soo.nonconvex.ga import GA -from pymoo.factory import get_problem -from pymoo.optimize import minimize -from initialize import make_field_non_static -from initialize import make_field_static -from initialize import make_method_static2 -from initialize import make_method_non_static2 - -problem = get_problem(make_method_non_static2, make_field_non_static, make_field_static, make_method_static2) - - -def genetic_algorithm(): - algorithm = GA( - population_size=100, - individual_size=2, - eliminate_duplicates=True) - - res = minimize(problem, - algorithm, - seed=1, - verbose=False) - - print("Best solution found: \nX = %s\nF = %s" % (res.X, res.F)) - - -if __name__ == '__main__': - genetic_algorithm() +""" +Search-based refactoring with genetic algorithm + +""" + +__version__ = '0.1.' +__author__ = 'Morteza Zakeri' + +from pymoo.algorithms.soo.nonconvex.ga import GA +from pymoo.factory import get_problem +from pymoo.optimize import minimize +from codart.refactorings import make_field_static, make_method_static2, make_method_non_static2, make_field_non_static + +problem = get_problem(make_method_non_static2, make_field_non_static, make_field_static, make_method_static2) + + +def genetic_algorithm(): + algorithm = GA( + population_size=100, + individual_size=2, + eliminate_duplicates=True) + + res = minimize(problem, + algorithm, + seed=1, + verbose=False) + + print("Best solution found: \nX = %s\nF = %s" % (res.X, res.F)) + + +if __name__ == '__main__': + genetic_algorithm() diff --git a/codart/symbol_table.py b/codart/symbol_table.py index eb9fe3e4..7eebcdcb 100644 --- a/codart/symbol_table.py +++ b/codart/symbol_table.py @@ -6,11 +6,9 @@ """ - __version__ = '0.2.0' __author__ = 'Morteza Zakeri' - import os import re # regular expressions from typing import Dict, Any @@ -23,10 +21,10 @@ from antlr4.TokenStreamRewriter import TokenStreamRewriter from codart.utility.directory_utils import create_project_parse_tree -from gen.java.JavaLexer import JavaLexer -from gen.java.JavaParser import JavaParser -from gen.java.JavaParserListener import JavaParserListener -from gen.javaLabeled.JavaLexer import JavaLexer +from codart.gen.java.JavaLexer import JavaLexer +from codart.gen.java.JavaParser import JavaParser +from codart.gen.java.JavaParserListener import JavaParserListener +from codart.gen.javaLabeled.JavaLexer import JavaLexer class Program: @@ -78,7 +76,8 @@ def has_imported_class(self, package_name: str, class_name: str) -> bool: return ( any(lambda x: x.package_name == package_name for package_import in self.package_imports) or any(lambda x: x.package_name == package_name and x.class_name == class_name for class_import in - self.class_imports)) + self.class_imports) + ) def has_imported_package(self, package_name: str): if self.package_name == package_name: @@ -126,9 +125,9 @@ def get_text_from_file(self, filename=None) -> str: filename = self.filename if filename is None: return None - file_ = open(filename, 'r') - text = file_.read() - file_.close() + f = open(filename, 'r') + text = f.read() + f.close() return text[self.get_first_symbol().start:self.get_last_symbol().stop + 1] @@ -267,6 +266,7 @@ class UtilsListener(JavaParserListener): """ """ + def __init__(self, filename): self.package = Package() @@ -558,11 +558,13 @@ def exitFieldDeclaration(self, ctx: JavaParser.FieldDeclarationContext): dims = self.current_field_dims[i] field_init = self.current_field_inits[i] var_ctx = self.current_field_var_ctxs[i] - field = Field(package_name=self.package.name, - class_name=self.current_class_identifier, - parser_context=self.current_field_decl[2], - filename=self.filename, - file_info=self.file_info) + field = Field( + package_name=self.package.name, + class_name=self.current_class_identifier, + parser_context=self.current_field_decl[2], + filename=self.filename, + file_info=self.file_info + ) field.modifiers = self.current_field_decl[0] field.modifiers_parser_contexts = self.current_field_decl[3] field.datatype = self.current_field_decl[1] + dims @@ -684,8 +686,10 @@ def enterClassDeclaration(self, ctx: JavaParser.ClassDeclarationContext): else: return - self.has_imported_source = self.file_info.has_imported_package(self.package.name) or \ - self.file_info.has_imported_class(self.package.name, self.source_class) + self.has_imported_source = ( + self.file_info.has_imported_package(self.package.name) + or self.file_info.has_imported_class(self.package.name, self.source_class) + ) # import target if we're not in Target and have not imported before if self.current_class_name != self.target_class: @@ -705,10 +709,10 @@ def enterClassBody(self, ctx: JavaParser.ClassBodyContext): # add getter and setter name = self.field_tobe_moved.name method_name = self.field_tobe_moved.name.upper() + self.field_tobe_moved.name[1:-1] - type = self.field_tobe_moved.datatype + type_ = self.field_tobe_moved.datatype - getter = f"\tpublic {type} get{method_name}() {{ return this.{name}; }}\n" - setter = f"\tpublic void set{method_name}({type} {name}) {{ this.{name} = {name}; }}\n" + getter = f"\tpublic {type_} get{method_name}() {{ return this.{name}; }}\n" + setter = f"\tpublic void set{method_name}({type_} {name}) {{ this.{name} = {name}; }}\n" self.rewriter.insertBeforeIndex(ctx.stop.tokenIndex, getter) self.rewriter.insertBeforeIndex(ctx.stop.tokenIndex, setter) @@ -792,10 +796,9 @@ def handleMethodUsage(self, ctx, is_constructor: bool): try: local_ctx = var_or_exprs.parser_context.parentCtx.parentCtx.parentCtx.parentCtx.parentCtx.parentCtx creator = local_ctx.expression()[0].getText() - if creator.__contains__( - f"new{self.source_class}") and local_ctx.IDENTIFIER().getText() == self.field_name: + if creator.__contains__(f"new{self.source_class}") \ + and local_ctx.IDENTIFIER().getText() == self.field_name: self.propagate_field(local_ctx, target_param_name) - except: pass @@ -884,9 +887,8 @@ def save(rewriter: TokenStreamRewriter, file_name: str, filename_mapping=lambda path = new_filename[:new_filename.rfind('/')] if not os.path.exists(path): os.makedirs(path) - with open(new_filename, mode='w', newline='') as file: - print("write?", new_filename) - file.write(rewriter.getDefaultText()) + with open(new_filename, mode='w', newline='') as f: + f.write(rewriter.getDefaultText()) class MethodUsageListener(UtilsListener): @@ -905,7 +907,8 @@ def enterClassCreatorRest(self, ctx: JavaParser.ClassCreatorRestContext): if type(ctx.parentCtx) is JavaParser.CreatorContext: if ctx.parentCtx.createdName().IDENTIFIER()[0].getText() not in self.method_names: return - text = f"new {self.target_class}()" if ctx.arguments().expressionList() is None else f", new {self.target_class}()" + text = f"new {self.target_class}()" \ + if ctx.arguments().expressionList() is None else f", new {self.target_class}()" index = ctx.arguments().RPAREN().symbol.tokenIndex self.rewriter.insertBeforeIndex(index, text) @@ -929,7 +932,6 @@ def get_filenames_in_dir(directory_name: str, filter_=lambda x: x.endswith(".jav return result - def clean_up_dir(files: list) -> list: """ :param files: List of files in the project directory @@ -968,50 +970,47 @@ def exitMethodBody(self, ctx: JavaParser.MethodBodyContext): self.can_convert = False - - - def get_program(source_files: list, print_status=False) -> Program: program = Program() for filename in source_files: if print_status: print("Parsing " + filename) - stream_ = FileStream(filename, encoding='utf8', errors='ignore') - lexer_ = JavaLexer(stream_) - token_stream_ = CommonTokenStream(lexer_) - parser_ = JavaParser(token_stream_) - tree_ = parser_.compilationUnit() - listener_ = UtilsListener(filename) - walker_ = ParseTreeWalker() - walker_.walk(listener_, tree_) + stream = FileStream(filename, encoding='utf8', errors='ignore') + lexer = JavaLexer(stream) + token_stream = CommonTokenStream(lexer) + parser = JavaParser(token_stream) + tree = parser.compilationUnit() + listener = UtilsListener(filename) + walker = ParseTreeWalker() + walker.walk(listener, tree) - listener_package_name = listener_.package.name or "" + listener_package_name = listener.package.name or "" if not (listener_package_name in program.packages): - program.packages[listener_package_name] = listener_.package + program.packages[listener_package_name] = listener.package else: - for classes_name in listener_.package.classes: - program.packages[listener_package_name].classes[classes_name] = listener_.package.classes[classes_name] + for classes_name in listener.package.classes: + program.packages[listener_package_name].classes[classes_name] = listener.package.classes[classes_name] return program def get_objects(source_files: str) -> Dict[Any, Any]: objects = {} for filename in source_files: - stream_ = FileStream(filename, encoding='utf8', errors='ignore') - lexer_ = JavaLexer(stream_) - token_stream_ = CommonTokenStream(lexer_) - parser_ = JavaParser(token_stream_) - tree_ = parser_.compilationUnit() - listener_ = UtilsListener(filename) - walker_ = ParseTreeWalker() - walker_.walk(listener_, tree_) + stream = FileStream(filename, encoding='utf8', errors='ignore') + lexer = JavaLexer(stream) + token_stream = CommonTokenStream(lexer) + parser = JavaParser(token_stream) + tree = parser.compilationUnit() + listener = UtilsListener(filename) + walker = ParseTreeWalker() + walker.walk(listener, tree) - if not (listener_.package.name in objects): - objects[listener_.package.name] = listener_.objects_declaration + if not (listener.package.name in objects): + objects[listener.package.name] = listener.objects_declaration else: - for class_name in listener_.objects_declaration: - objects[listener_.package.name][class_name] = listener_.objects_declaration[class_name] + for class_name in listener.objects_declaration: + objects[listener.package.name][class_name] = listener.objects_declaration[class_name] return objects @@ -1026,11 +1025,11 @@ def __init__(self, program: Program, filename_mapping=lambda x: x + ".rewritten. package = program.packages[package_name] for class_name in package.classes: _class: Class = package.classes[class_name] - token_stream_ = _class.get_token_stream() - if token_stream_ not in self.token_streams: - self.token_streams[token_stream_] = ( + token_stream = _class.get_token_stream() + if token_stream not in self.token_streams: + self.token_streams[token_stream] = ( _class.filename, - TokenStreamRewriter(token_stream_), + TokenStreamRewriter(token_stream), filename_mapping(_class.filename) ) @@ -1068,106 +1067,106 @@ def get_program_with_field_usage(source_files: list, field_name: str, source_cla for filename in source_files: if print_status: print("Parsing " + filename) - stream_ = FileStream(filename, encoding='utf8', errors='ignore') - lexer_ = JavaLexer(stream_) - token_stream_ = CommonTokenStream(lexer_) - parser_ = JavaParser(token_stream_) - tree_ = parser_.compilationUnit() - listener_ = StaticFieldUsageListener(filename, field_name, source_class) - walker_ = ParseTreeWalker() - walker_.walk(listener_, tree_) + stream = FileStream(filename, encoding='utf8', errors='ignore') + lexer = JavaLexer(stream) + token_stream = CommonTokenStream(lexer) + parser = JavaParser(token_stream) + tree = parser.compilationUnit() + listener = StaticFieldUsageListener(filename, field_name, source_class) + walker = ParseTreeWalker() + walker.walk(listener, tree) - if not (listener_.package.name in program.packages): - program.packages[listener_.package.name] = listener_.package + if not (listener.package.name in program.packages): + program.packages[listener.package.name] = listener.package else: - for classes_name in listener_.package.classes: - program.packages[listener_.package.name].classes[classes_name] = listener_.package.classes[classes_name] + for classes_name in listener.package.classes: + program.packages[listener.package.name].classes[classes_name] = listener.package.classes[classes_name] return program def parse_and_walk(file_path: str, listener_class, has_write=False, debug=False, **kwargs): - tree_, rewriter = create_project_parse_tree(file_path) + tree, rewriter = create_project_parse_tree(file_path) if has_write: if rewriter is None: raise Exception("Failed to create rewriter.") kwargs.update({'rewriter': rewriter}) - listener_ = listener_class(**kwargs) + listener = listener_class(**kwargs) ParseTreeWalker().walk( - listener_, - tree_ + listener, + tree ) if has_write: if not debug: - with open(file_path, mode='w', encoding='utf-8', errors='ignore', newline='') as f_: - f_.write(listener_.rewriter.getDefaultText()) + with open(file_path, mode='w', encoding='utf-8', errors='ignore', newline='') as f: + f.write(listener.rewriter.getDefaultText()) else: - print(listener_.rewriter.getDefaultText()) + print(listener.rewriter.getDefaultText()) - return listener_ + return listener # Tests if __name__ == '__main__': - source_class = "JSONArray" - source_package = "org.json" - target_class = "JSONObject" - target_package = "org.json" - field_name = "myArrayList" - path = "" - files = get_filenames_in_dir( - '/home/loop/Desktop/Ass/Compiler/CodART/benchmark_projects/JSON/src/main/java/org/json/') - field = None + source_class_ = "JSONArray" + source_package_ = "org.json" + target_class_ = "JSONObject" + target_package_ = "org.json" + field_name_ = "myArrayList" + # path = "" + files1 = get_filenames_in_dir('benchmark_projects/JSON/src/main/java/org/json/') + field_ = None methods_tobe_update = [] - for file in files: - stream = FileStream(file, encoding='utf8', errors='ignore') - lexer = JavaLexer(stream) - token_stream = CommonTokenStream(lexer) - parser = JavaParser(token_stream) - tree = parser.compilationUnit() - utilsListener = PreConditionListener(file) - walker = ParseTreeWalker() - walker.walk(utilsListener, tree) + for file_ in files1: + stream_ = FileStream(file_, encoding='utf8', errors='ignore') + lexer_ = JavaLexer(stream_) + token_stream_ = CommonTokenStream(lexer_) + parser_ = JavaParser(token_stream_) + tree_ = parser_.compilationUnit() + listener_ = PreConditionListener(file_) + walker_ = ParseTreeWalker() + walker_.walk(listener_, tree_) - if not utilsListener.can_convert: + if not listener_.can_convert: continue - if len(utilsListener.package.classes) > 1: + if len(listener_.package.classes) > 1: exit(1) # find fields with the type Source first and store it field_candidate = set() - for klass in utilsListener.package.classes.values(): - for f in klass.fields.values(): - if f.datatype == source_class: - field_candidate.add(f.name) - - listener = FieldUsageListener(file, - source_class, - source_package, - target_class, - target_package, - field_name, - field_candidate, - field) - walker.walk(listener, tree) + for class_ in listener_.package.classes.values(): + for field_ in class_.fields.values(): + if field_.datatype == source_class_: + field_candidate.add(field_.name) + + listener_ = FieldUsageListener( + file_, + source_class_, + source_package_, + target_class_, + target_package_, + field_name_, + field_candidate, + field_ + ) + walker_.walk(listener_, tree_) - methods_tobe_update = listener.methods_tobe_updated + methods_tobe_update + methods_tobe_update = listener_.methods_tobe_updated + methods_tobe_update - if file.__contains__(source_class): - field = listener.field_tobe_moved + if file_.__contains__(source_class_): + field_ = listener_.field_tobe_moved # for method in methods_tobe_update: # print(method.name) - files2 = [f'{file.split(".")[0]}.rewritten.java' for file in files] - for i, file in enumerate(files): - stream = FileStream(files2[i], encoding='utf8', errors='ignore') - lexer = JavaLexer(stream) - token_stream = CommonTokenStream(lexer) - parser = JavaParser(token_stream) - tree = parser.compilationUnit() - listener = MethodUsageListener(file, methods_tobe_update, target_class) - walker = ParseTreeWalker() - walker.walk(listener, tree) - + files2 = [f'{file.split(".")[0]}.rewritten.java' for file in files1] + for i_, file_ in enumerate(files1): + stream_ = FileStream(files2[i_], encoding='utf8', errors='ignore') + lexer_ = JavaLexer(stream_) + token_stream_ = CommonTokenStream(lexer_) + parser_ = JavaParser(token_stream_) + tree_ = parser_.compilationUnit() + listener_ = MethodUsageListener(file_, methods_tobe_update, target_class_) + walker_ = ParseTreeWalker() + walker_.walk(listener_, tree_) diff --git a/codart/utility/cpu_ram_usage.py b/codart/utility/cpu_ram_usage.py index b92e3fa4..f981a2f6 100644 --- a/codart/utility/cpu_ram_usage.py +++ b/codart/utility/cpu_ram_usage.py @@ -4,8 +4,8 @@ from antlr4 import FileStream, CommonTokenStream -from gen.java.JavaLexer import JavaLexer -from gen.java.JavaParser import JavaParser +from codart.gen.java.JavaLexer import JavaLexer +from codart.gen.java.JavaParser import JavaParser class ProjectParseUsage: diff --git a/codart/utility/directory_utils.py b/codart/utility/directory_utils.py index 37ba61bf..85dd13d4 100644 --- a/codart/utility/directory_utils.py +++ b/codart/utility/directory_utils.py @@ -10,18 +10,15 @@ import subprocess from multiprocessing.dummy import Pool, Process, Manager -from antlr4 import FileStream, CommonTokenStream +from antlr4 import FileStream from antlr4.TokenStreamRewriter import TokenStreamRewriter from joblib import Parallel, delayed import understand as und -from gen.java.JavaLexer import JavaLexer -from gen.javaLabeled.JavaParserLabeled import JavaParserLabeled from java8speedy.parser import sa_javalabeled -from java8speedy.parser import JavaLabeledLexer -from sbse import config +from codart import config def git_restore(project_dir): diff --git a/codart/utility/setup_understand.py b/codart/utility/setup_understand.py index ebcbf74f..7406832f 100644 --- a/codart/utility/setup_understand.py +++ b/codart/utility/setup_understand.py @@ -8,10 +8,7 @@ # import logging from dotenv import load_dotenv - -# logging.basicConfig(level=logging.DEBUG) -# logger = logging.getLogger(__file__) -from sbse.config import logger +from codart import config load_dotenv() @@ -30,7 +27,7 @@ # Import understand if available on the path try: import understand as und - logger.info(f"Loaded understand {und.version()} successfully") + config.logger.info(f"Loaded understand {und.version()} successfully") except ModuleNotFoundError: raise ModuleNotFoundError('Understand not found.') except ImportError: diff --git a/codart/utility/understand_install_test.py b/codart/utility/understand_install_test.py index 53d6e500..5db7389f 100644 --- a/codart/utility/understand_install_test.py +++ b/codart/utility/understand_install_test.py @@ -1,4 +1,4 @@ -# Test script to verify that the Understand Python API is setup correctly +# Test script to verify that Understand Python API is installed correctly import struct import shutil @@ -7,7 +7,7 @@ # Verify Python 3 -if (sys.version_info >= (3, 0)): +if sys.version_info >= (3, 0): print("Checking for Python Version >= 3.0 : Pass") print(" Python Version: " + str(sys.version_info.major) + "." + str(sys.version_info.minor) + "." + str( sys.version_info.micro)) @@ -25,7 +25,7 @@ print(" Error: Add scitools/bin/[SYSTEM] to PATH and restart your session") quit() undPath = os.path.normcase(re.sub(r'und(\.exe)*$', '', undPath, flags=re.IGNORECASE)) -if (undPath): +if undPath: print("Checking for Understand in PATH: Pass") print(" found at ", undPath) else: @@ -55,7 +55,7 @@ print(' Error: Unexpected Directory Structure, the Understand install directory should not be modified. ', undPath) quit() pythonBit = (struct.calcsize("P") * 8) -if (pythonBit != understandBit): +if pythonBit != understandBit: print("Checking that Bit versions match: Fail") print(" Error: Python is", pythonBit, "bit and Understand is", understandBit, "bit. They need to match") quit() @@ -85,9 +85,9 @@ cleanDir = os.path.normcase(testDir) if cleanDir == pythonDir: inPythonPath = True - if (cleanDir.find('\"') > 0): + if cleanDir.find('\"') > 0: print(" Illegal Quote characters were found in PYTHONPATH: " + cleanDir) -if (not inPythonPath): +if not inPythonPath: print("Checking that PYTHONPATH includes API: Fail") print(" Error: Add", pythonDir, "to PYTHONPATH. If it is set you may need to restart your session.") quit() @@ -113,11 +113,11 @@ candidate = os.path.join(path, 'qt.conf') if os.path.exists(candidate): qtPaths.append(path) - if (len(qtPaths) == 0): + if len(qtPaths) == 0: print(" Error: QtFiles are missing from the PATH even though", undPath, "was found") print(" Unexpected Directory Structure, the Understand install directory should not be modified.") quit() - if (len(qtPaths) > 1): + if len(qtPaths) > 1: print(" Error: Multiple Qt Installations in the PATH.") print(" Try moving the sti\\bin directory earlier in the path.") for path in qtPaths: diff --git a/docs/index.md b/docs/index.md index 7142a6a4..a07db25d 100644 --- a/docs/index.md +++ b/docs/index.md @@ -4,7 +4,7 @@ † Ph.D. Student, Iran University of Science and Technology, Tehran, Iran (m-zakeri@live.com). -Version 0.2.2 (16 March 2021) ├ Download PDF versions [v0.1.0](./pdfs/project_proposal_v1z.pdf), [v0.2.0](./pdfs/project_proposal_v2z.pdf) +Version 0.2.3 (25 May 2022) ├ Download PDF versions [v0.1.0](./pdfs/project_proposal_v1z.pdf), [v0.2.0](./pdfs/project_proposal_v2z.pdf) **Abstract—** Software refactoring is performed by changing the software structure without modifying its external behavior. Many software quality attributes can be enhanced through the source code refactoring, such as reusability, flexibility, understandability, and testability. Refactoring engines are tools that automate the application of refactorings: first, the user chooses a refactoring to apply, then the engine checks if the transformation is safe, and if so, transforms the program. Refactoring engines are a key component of modern Integrated Development Environments (IDEs), and programmers rely on them to perform refactorings. In this project, an open-source software toolkit for refactoring Java source codes, namely CodART, will be developed. ANTLR parser generator is used to create and modify the program syntax-tree and produce the refactored version of the program. To the best of our knowledge, CodART is the first open-source refactoring toolkit based on ANTLR. diff --git a/docs/metrics/testability.md b/docs/metrics/testability.md index 88948c74..eadc84fb 100644 --- a/docs/metrics/testability.md +++ b/docs/metrics/testability.md @@ -1,3 +1,3 @@ # Testability prediction -::: metrics.testability_prediction2 +::: codart.metrics.testability_prediction2 diff --git a/docs/optimization/initialize.md b/docs/optimization/initialize.md index a5134fb4..dd6f6fca 100644 --- a/docs/optimization/initialize.md +++ b/docs/optimization/initialize.md @@ -1,5 +1,5 @@ # Search-based refactoring initialization -::: sbse.initialize +::: codart.sbse.initialize diff --git a/docs/optimization/search-based_refactoring.md b/docs/optimization/search-based_refactoring.md index d4fed449..694b582d 100644 --- a/docs/optimization/search-based_refactoring.md +++ b/docs/optimization/search-based_refactoring.md @@ -1,5 +1,5 @@ # Search-based refactoring module -::: sbse.search_based_refactoring2 +::: codart.sbse.search_based_refactoring2 diff --git a/docs/refactorings/decrease_field_visibility.md b/docs/refactorings/decrease_field_visibility.md index a1d4125e..3d8683f7 100644 --- a/docs/refactorings/decrease_field_visibility.md +++ b/docs/refactorings/decrease_field_visibility.md @@ -1,3 +1,3 @@ # Decrease field visibility -::: refactorings.decrease_field_visibility +::: codart.refactorings.decrease_field_visibility diff --git a/docs/refactorings/decrease_method_visibility.md b/docs/refactorings/decrease_method_visibility.md index 4628d3da..7444cd19 100644 --- a/docs/refactorings/decrease_method_visibility.md +++ b/docs/refactorings/decrease_method_visibility.md @@ -1,3 +1,3 @@ # Decrease method visibility -::: refactorings.decrease_method_visibility +::: codart.refactorings.decrease_method_visibility diff --git a/docs/refactorings/encapsulate_field.md b/docs/refactorings/encapsulate_field.md index 3d018a87..05fb3dd7 100644 --- a/docs/refactorings/encapsulate_field.md +++ b/docs/refactorings/encapsulate_field.md @@ -1,3 +1,3 @@ # Encapsulate field -::: refactorings.encapsulate_field +::: codart.refactorings.encapsulate_field diff --git a/docs/refactorings/extract_class.md b/docs/refactorings/extract_class.md index cc0ecee4..02ac5de8 100644 --- a/docs/refactorings/extract_class.md +++ b/docs/refactorings/extract_class.md @@ -1,3 +1,3 @@ # Extract class -::: refactorings.extract_class +::: codart.refactorings.extract_class diff --git a/docs/refactorings/extract_interface.md b/docs/refactorings/extract_interface.md index 4831621f..df53b000 100644 --- a/docs/refactorings/extract_interface.md +++ b/docs/refactorings/extract_interface.md @@ -1,3 +1,3 @@ # Extract interface -::: refactorings.extract_interface +::: codart.refactorings.extract_interface diff --git a/docs/refactorings/extract_interface2.md b/docs/refactorings/extract_interface2.md index 53390dd1..2c8e33d3 100644 --- a/docs/refactorings/extract_interface2.md +++ b/docs/refactorings/extract_interface2.md @@ -1,3 +1,3 @@ # Extract interface 2 -::: refactorings.extract_interface2 +::: codart.refactorings.extract_interface2 diff --git a/docs/refactorings/extract_method.md b/docs/refactorings/extract_method.md index da2f85dc..4b1cbb43 100644 --- a/docs/refactorings/extract_method.md +++ b/docs/refactorings/extract_method.md @@ -1,3 +1,3 @@ # Extract method -::: refactorings.extract_method +::: codart.refactorings.extract_method diff --git a/docs/refactorings/extract_subclass.md b/docs/refactorings/extract_subclass.md index 9c02024d..a6f6f890 100644 --- a/docs/refactorings/extract_subclass.md +++ b/docs/refactorings/extract_subclass.md @@ -1,3 +1,3 @@ # Extract subclass -::: refactorings.extract_subclass +::: codart.refactorings.extract_subclass diff --git a/docs/refactorings/increase_field_visibility.md b/docs/refactorings/increase_field_visibility.md index cbafe70e..9f5741e7 100644 --- a/docs/refactorings/increase_field_visibility.md +++ b/docs/refactorings/increase_field_visibility.md @@ -1,3 +1,3 @@ # Increase field visibility -::: refactorings.increase_field_visibility +::: codart.refactorings.increase_field_visibility diff --git a/docs/refactorings/increase_method_visibility.md b/docs/refactorings/increase_method_visibility.md index 400480d1..0b1079b6 100644 --- a/docs/refactorings/increase_method_visibility.md +++ b/docs/refactorings/increase_method_visibility.md @@ -1,3 +1,3 @@ # Increase method visibility -::: refactorings.increase_method_visibility +::: codart.refactorings.increase_method_visibility diff --git a/docs/refactorings/inline_class.md b/docs/refactorings/inline_class.md index b37281d3..977fe6e5 100644 --- a/docs/refactorings/inline_class.md +++ b/docs/refactorings/inline_class.md @@ -1,3 +1,3 @@ # Increase method visibility -::: refactorings.inline_class +::: codart.refactorings.inline_class diff --git a/docs/refactorings/make_field_final.md b/docs/refactorings/make_field_final.md index 90742b1b..5372a798 100644 --- a/docs/refactorings/make_field_final.md +++ b/docs/refactorings/make_field_final.md @@ -1,3 +1,3 @@ # Make field final -::: refactorings.make_field_final +::: codart.refactorings.make_field_final diff --git a/docs/refactorings/make_field_non_final.md b/docs/refactorings/make_field_non_final.md index 80ec80ae..b4236dcb 100644 --- a/docs/refactorings/make_field_non_final.md +++ b/docs/refactorings/make_field_non_final.md @@ -1,3 +1,3 @@ # Make field non-final -::: refactorings.make_field_non_final +::: codart.refactorings.make_field_non_final diff --git a/docs/refactorings/make_field_non_static.md b/docs/refactorings/make_field_non_static.md index d18d545f..bc5ce84c 100644 --- a/docs/refactorings/make_field_non_static.md +++ b/docs/refactorings/make_field_non_static.md @@ -1,3 +1,3 @@ # Make field non-static -::: refactorings.make_field_non_static +::: codart.refactorings.make_field_non_static diff --git a/docs/refactorings/make_field_static.md b/docs/refactorings/make_field_static.md index 3daaf48c..c315bfa3 100644 --- a/docs/refactorings/make_field_static.md +++ b/docs/refactorings/make_field_static.md @@ -1,3 +1,3 @@ # Make field static -::: refactorings.make_field_static +::: codart.refactorings.make_field_static diff --git a/docs/refactorings/make_method_final.md b/docs/refactorings/make_method_final.md index 7154c03c..a4ce7b58 100644 --- a/docs/refactorings/make_method_final.md +++ b/docs/refactorings/make_method_final.md @@ -1,3 +1,3 @@ # Make method final -::: refactorings.make_method_final +::: codart.refactorings.make_method_final diff --git a/docs/refactorings/make_method_non_final.md b/docs/refactorings/make_method_non_final.md index 05f7d11a..18b9f377 100644 --- a/docs/refactorings/make_method_non_final.md +++ b/docs/refactorings/make_method_non_final.md @@ -1,3 +1,3 @@ # Make method non-final -::: refactorings.make_method_non_final +::: codart.refactorings.make_method_non_final diff --git a/docs/refactorings/make_method_non_static.md b/docs/refactorings/make_method_non_static.md index 96b2c16c..19beee4a 100644 --- a/docs/refactorings/make_method_non_static.md +++ b/docs/refactorings/make_method_non_static.md @@ -1,6 +1,6 @@ # Make method non-static -::: refactorings.make_method_non_static +::: codart.refactorings.make_method_non_static -::: refactorings.make_method_non_static2 \ No newline at end of file +::: codart.refactorings.make_method_non_static2 \ No newline at end of file diff --git a/docs/refactorings/make_method_static.md b/docs/refactorings/make_method_static.md index 5d17e93a..ae58f63c 100644 --- a/docs/refactorings/make_method_static.md +++ b/docs/refactorings/make_method_static.md @@ -1,9 +1,9 @@ # Make method static -::: refactorings.make_method_non_static +::: codart.refactorings.make_method_non_static # Make method static 2 -::: refactorings.make_method_static2 \ No newline at end of file +::: codart.refactorings.make_method_static2 \ No newline at end of file diff --git a/docs/refactorings/move_class.md b/docs/refactorings/move_class.md index e19266f7..86e5a689 100644 --- a/docs/refactorings/move_class.md +++ b/docs/refactorings/move_class.md @@ -1,4 +1,4 @@ # Move class -::: refactorings.move_class +::: codart.refactorings.move_class diff --git a/docs/refactorings/move_field.md b/docs/refactorings/move_field.md index ffd7e958..c512271f 100644 --- a/docs/refactorings/move_field.md +++ b/docs/refactorings/move_field.md @@ -1,6 +1,6 @@ # Move field -::: refactorings.move_field +::: codart.refactorings.move_field diff --git a/docs/refactorings/move_method.md b/docs/refactorings/move_method.md index 52206c6c..47d26bad 100644 --- a/docs/refactorings/move_method.md +++ b/docs/refactorings/move_method.md @@ -1,6 +1,6 @@ # Move method -::: refactorings.move_method +::: codart.refactorings.move_method diff --git a/docs/refactorings/pull_up_constructor.md b/docs/refactorings/pull_up_constructor.md index e4be6141..5b2fc799 100644 --- a/docs/refactorings/pull_up_constructor.md +++ b/docs/refactorings/pull_up_constructor.md @@ -1,4 +1,4 @@ # Pull-up constructor -::: refactorings.pullup_constructor +::: codart.refactorings.pullup_constructor diff --git a/docs/refactorings/pull_up_field.md b/docs/refactorings/pull_up_field.md index d668c297..ff2d5072 100644 --- a/docs/refactorings/pull_up_field.md +++ b/docs/refactorings/pull_up_field.md @@ -1,6 +1,6 @@ # Pull-up field -::: refactorings.pullup_field +::: codart.refactorings.pullup_field diff --git a/docs/refactorings/pull_up_method.md b/docs/refactorings/pull_up_method.md index 32376e1d..307bf481 100644 --- a/docs/refactorings/pull_up_method.md +++ b/docs/refactorings/pull_up_method.md @@ -1,3 +1,3 @@ # Pull-up method -::: refactorings.pullup_method +::: codart.refactorings.pullup_method diff --git a/docs/refactorings/push_down_field.md b/docs/refactorings/push_down_field.md index c62bb237..ad2575d0 100644 --- a/docs/refactorings/push_down_field.md +++ b/docs/refactorings/push_down_field.md @@ -1,9 +1,9 @@ # Push-down field -::: refactorings.pushdown_field +::: codart.refactorings.pushdown_field # Push-down field 2 -::: refactorings.pushdown_field2 \ No newline at end of file +::: codart.refactorings.pushdown_field2 \ No newline at end of file diff --git a/docs/refactorings/push_down_method.md b/docs/refactorings/push_down_method.md index 1e5a1ee1..0d1f58cd 100644 --- a/docs/refactorings/push_down_method.md +++ b/docs/refactorings/push_down_method.md @@ -1,9 +1,9 @@ # Push-down method -::: refactorings.pushdown_method +::: codart.refactorings.pushdown_method # Push-down method 2 -::: refactorings.pushdown_method2 \ No newline at end of file +::: codart.refactorings.pushdown_method2 \ No newline at end of file diff --git a/docs/refactorings/rename_class.md b/docs/refactorings/rename_class.md index 56155251..6189ca03 100644 --- a/docs/refactorings/rename_class.md +++ b/docs/refactorings/rename_class.md @@ -4,10 +4,10 @@ ## Implementation 1 -::: refactorings.rename_class +::: codart.refactorings.rename_class ## Implementation 2 -::: refactorings.rename_class2 +::: codart.refactorings.rename_class2 diff --git a/docs/refactorings/rename_field.md b/docs/refactorings/rename_field.md index 85dc51d6..74493960 100644 --- a/docs/refactorings/rename_field.md +++ b/docs/refactorings/rename_field.md @@ -1,6 +1,6 @@ # Rename field -::: refactorings.rename_field +::: codart.refactorings.rename_field diff --git a/docs/refactorings/rename_method.md b/docs/refactorings/rename_method.md index c1292ff5..160ac2ca 100644 --- a/docs/refactorings/rename_method.md +++ b/docs/refactorings/rename_method.md @@ -2,11 +2,11 @@ ## Implementation 1 -::: refactorings.rename_method +::: codart.refactorings.rename_method ## Implementation 2 -::: refactorings.rename_method2 +::: codart.refactorings.rename_method2 diff --git a/docs/refactorings/rename_package.md b/docs/refactorings/rename_package.md index 68fc2239..2f3d5151 100644 --- a/docs/refactorings/rename_package.md +++ b/docs/refactorings/rename_package.md @@ -1,5 +1,5 @@ # Rename package -::: refactorings.rename_package +::: codart.refactorings.rename_package diff --git a/docs/utilities/project_utils.md b/docs/utilities/project_utils.md index 0ab1e625..80cd0a33 100644 --- a/docs/utilities/project_utils.md +++ b/docs/utilities/project_utils.md @@ -2,7 +2,7 @@ ## Directory utils -::: codart.utility.directory_utils +::: codart.codart.utility.directory_utils diff --git a/mkdocs.yml b/mkdocs.yml index 4e9187f1..46c24a16 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -1,9 +1,9 @@ -site_name: CodART Docs (v0.1.2dev) +site_name: CodART Docs (v0.2.3dev) site_url: https://m-zakeri.github.io repo_url: https://github.com/m-zakeri/CodART site_description: Automated Source Code Refactoring Toolkit site_author: Morteza Zakeri -copyright: © 2020-2021 CodART project - Reverse engineering laboratory +copyright: © 2020-2022 CodART project - Reverse engineering laboratory theme: name: material diff --git a/sbse/utils/__init__.py b/sbse/utils/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/sbse/utils/input.txt b/sbse/utils/input.txt deleted file mode 100644 index 29eca494..00000000 --- a/sbse/utils/input.txt +++ /dev/null @@ -1,48 +0,0 @@ - , Extract Class({'source_class': 'DemandCurveParameterFrame', 'moved_fields': ['maxConstants', 'simpleLabels', 'simpleTextFields'], 'moved_methods': ['defineSimpleLabels', 'defineSimpleTextFields'], 'file_path': 'C:\\Users\\Administrator\\Downloads\\prj_src\\10_water-simulator\\src\\main\\java\\simulator\\SA\\gui\\DemandCurveParameterFrame.java', 'udb_path': 'C:/Users/Administrator/Downloads/udbs\\10_water-simulator.udb'}) - , Increase Field Visibility({'udb_path': 'C:\\Users\\Administrator\\Downloads\\udbs\\10_water-simulator.udb', 'source_package': 'simulator.SA.gui.ScenarioDesignWizard', 'source_class': 'Step3_1Frame', 'source_field': 'index'}) - , Extract Class({'source_class': 'ParameterAttributes', 'moved_fields': ['ln'], 'moved_methods': ['setLn', 'getLn'], 'file_path': 'C:\\Users\\Administrator\\Downloads\\prj_src\\10_water-simulator\\src\\main\\java\\simulator\\util\\ParameterAttributes.java', 'udb_path': 'C:/Users/Administrator/Downloads/udbs\\10_water-simulator.udb'}) - , Increase Method Visibility({'udb_path': 'C:\\Users\\Administrator\\Downloads\\udbs\\10_water-simulator.udb', 'source_package': 'simulator.ontology', 'source_class': 'StepTotalConsumption', 'source_method': 'getAllWaterPrice'}) - , Decrease Field Visibility({'udb_path': 'C:\\Users\\Administrator\\Downloads\\udbs\\10_water-simulator.udb', 'source_package': 'simulator.SA.gui', 'source_class': 'PricingPolicyFrame', 'source_field': 'cancelButton'}) - , Make Field Non-Static({'udb_path': 'C:/Users/Administrator/Downloads/udbs\\10_water-simulator.udb', 'source_class': 'BehaviourQueryConsumers', 'field_name': 'test', 'is_public': False, 'is_private': True, 'external_references': 0}) - , Extract Class({'source_class': 'ReviewGUI', 'moved_fields': ['typesCombo', 'curveCombo'], 'moved_methods': ['updateTypesCombo', 'getCombosSelections', 'updateCurveCombo'], 'file_path': 'C:\\Users\\Administrator\\Downloads\\prj_src\\10_water-simulator\\src\\main\\java\\simulator\\SA\\gui\\ReviewGUI.java', 'udb_path': 'C:/Users/Administrator/Downloads/udbs\\10_water-simulator.udb'}) - , Increase Method Visibility({'udb_path': 'C:\\Users\\Administrator\\Downloads\\udbs\\10_water-simulator.udb', 'source_package': 'simulator.CA', 'source_class': 'BehaviourContactNeighbours', 'source_method': 'fillParametersToAsk'}) - , Move Field({'udb_path': 'C:\\Users\\Administrator\\Downloads\\udbs\\10_water-simulator.udb', 'source_package': 'simulator.SA.gui.ScenarioDesignWizard', 'source_class': 'Step3Frame', 'field_name': 'controlPanel', 'is_public': False, 'is_private': True, 'external_references': 0, 'target_class': 'PriceBlock', 'target_package': 'simulator.ontology'}) - , Make Field Static({'udb_path': 'C:/Users/Administrator/Downloads/udbs\\10_water-simulator.udb', 'source_class': 'ReviewGUI', 'field_name': 'border2', 'is_public': False, 'is_private': False, 'external_references': 0}) - , Increase Method Visibility({'udb_path': 'C:\\Users\\Administrator\\Downloads\\udbs\\10_water-simulator.udb', 'source_package': 'simulator.util', 'source_class': 'Linear', 'source_method': 'valueFor'}) - , Increase Method Visibility({'udb_path': 'C:\\Users\\Administrator\\Downloads\\udbs\\10_water-simulator.udb', 'source_package': 'simulator.CA', 'source_class': 'BehaviourContactNeighbours', 'source_method': 'onSuccess'}) - , Push Down Method({'udb_path': 'C:\\Users\\Administrator\\Downloads\\udbs\\10_water-simulator.udb', 'source_class': 'Function', 'source_package': 'simulator', 'method_name': 'getFunctionName', 'target_classes': ['Random']}) - , Increase Field Visibility({'udb_path': 'C:\\Users\\Administrator\\Downloads\\udbs\\10_water-simulator.udb', 'source_package': 'simulator.SA.gui', 'source_class': 'SimulationParametersFrame', 'source_field': 'simulationStep'}) - , Increase Method Visibility({'udb_path': 'C:\\Users\\Administrator\\Downloads\\udbs\\10_water-simulator.udb', 'source_package': 'simulator.SA.gui', 'source_class': 'PricingPolicyFrame', 'source_method': 'setDataToFields'}) - , Make Field Non-Static({'udb_path': 'C:/Users/Administrator/Downloads/udbs\\10_water-simulator.udb', 'source_class': 'Step4Frame', 'field_name': 'serialVersionUID', 'is_public': False, 'is_private': True, 'external_references': 0}) - , Move Method({'source_package': 'simulator.SA', 'source_class': 'GridGenerator', 'method_name': 'getNeighbours', 'target_package': 'simulator.util', 'target_class': 'ConsumerAttributes', 'udb_path': 'C:/Users/Administrator/Downloads/udbs\\10_water-simulator.udb'}) - , Decrease Method Visibility({'udb_path': 'C:\\Users\\Administrator\\Downloads\\udbs\\10_water-simulator.udb', 'source_package': 'simulator.SA.gui.ScenarioDesignWizard.Step2Frame', 'source_class': 'ListRenderer', 'source_method': 'getListCellRendererComponent'}) - , Move Field({'udb_path': 'C:\\Users\\Administrator\\Downloads\\udbs\\10_water-simulator.udb', 'source_package': 'simulator.SA.gui.ScenarioDesignWizard', 'source_class': 'Step5Frame', 'field_name': 'labelStepsReview', 'is_public': False, 'is_private': True, 'external_references': 0, 'target_class': 'WaterConsumption', 'target_package': 'simulator.ontology'}) - , Make Field Non-Static({'udb_path': 'C:/Users/Administrator/Downloads/udbs\\10_water-simulator.udb', 'source_class': 'FunctionConstant', 'field_name': 'serialVersionUID', 'is_public': False, 'is_private': True, 'external_references': 0}) - , Move Method({'source_package': 'simulator.SA.gui.ScenarioDesignWizard', 'source_class': 'Step3_1Frame', 'method_name': 'createParametersPanel', 'target_package': 'simulator.util', 'target_class': 'Function', 'udb_path': 'C:/Users/Administrator/Downloads/udbs\\10_water-simulator.udb'}) - , Decrease Method Visibility({'udb_path': 'C:\\Users\\Administrator\\Downloads\\udbs\\10_water-simulator.udb', 'source_package': 'simulator.SA.gui', 'source_class': 'SuiteGUIExtracted', 'source_method': 'addToMainPanel'}) - , Make Method Static({'udb_path': 'C:/Users/Administrator/Downloads/udbs\\10_water-simulator.udb', 'source_class': 'ProgressGui', 'method_name': 'enableStartButton', 'is_public': True, 'is_private': False, 'external_references': 1}) - , Push Down Field({'project_dir': 'C:\\Users\\Administrator\\Downloads\\udbs', 'source_class': 'Function', 'source_package': 'simulator.util', 'field_name': 'functionRepresentation', 'target_classes': ['Raise', 'MetDataFunction', 'Discrete']}) - , Increase Method Visibility({'udb_path': 'C:\\Users\\Administrator\\Downloads\\udbs\\10_water-simulator.udb', 'source_package': 'simulator.CA.gui.ConsumerGUI', 'source_class': 'TableDataModel', 'source_method': 'getValueAt'}) - , Make Field Non-Static({'udb_path': 'C:/Users/Administrator/Downloads/udbs\\10_water-simulator.udb', 'source_class': 'SimulationAgent', 'field_name': 'stepId', 'is_public': False, 'is_private': True, 'external_references': 0}) - , Increase Method Visibility({'udb_path': 'C:\\Users\\Administrator\\Downloads\\udbs\\10_water-simulator.udb', 'source_package': 'simulator.SA.gui.ScenarioDesignWizard', 'source_class': 'Step1Frame', 'source_method': 'checkConstraints'}) - , Decrease Field Visibility({'udb_path': 'C:\\Users\\Administrator\\Downloads\\udbs\\10_water-simulator.udb', 'source_package': 'simulator.ontology', 'source_class': 'WDS_Ontology', 'source_field': 'PARAMETER_NAME'}) - , Decrease Method Visibility({'udb_path': 'C:\\Users\\Administrator\\Downloads\\udbs\\10_water-simulator.udb', 'source_package': 'simulator.SA.gui.DemandCurveParameterFrame', 'source_class': 'functionComboListener', 'source_method': 'actionPerformed'}) - , Increase Method Visibility({'udb_path': 'C:\\Users\\Administrator\\Downloads\\udbs\\10_water-simulator.udb', 'source_package': 'simulator.ontology', 'source_class': 'Consumes', 'source_method': 'setPricingScale'}) - , Make Field Static({'udb_path': 'C:/Users/Administrator/Downloads/udbs\\10_water-simulator.udb', 'source_class': 'ReviewGUI', 'field_name': 'titledBorder1', 'is_public': False, 'is_private': False, 'external_references': 0}) - , Extract Class({'source_class': 'ParameterAttributes', 'moved_fields': ['social'], 'moved_methods': ['setSocial', 'isSocial'], 'file_path': 'C:\\Users\\Administrator\\Downloads\\prj_src\\10_water-simulator\\src\\main\\java\\simulator\\util\\ParameterAttributes.java', 'udb_path': 'C:/Users/Administrator/Downloads/udbs\\10_water-simulator.udb'}) - , Extract Class({'source_class': 'ParameterAttributes', 'moved_fields': ['elasticity', 'ln'], 'moved_methods': ['setElasticity', 'getElasticity', 'setLn', 'getLn'], 'file_path': 'C:\\Users\\Administrator\\Downloads\\prj_src\\10_water-simulator\\src\\main\\java\\simulator\\util\\ParameterAttributes.java', 'udb_path': 'C:/Users/Administrator/Downloads/udbs\\10_water-simulator.udb'}) - , Make Method Non-Static({'udb_path': 'C:/Users/Administrator/Downloads/udbs\\10_water-simulator.udb', 'source_class': 'ParameterAttributes', 'method_name': 'getSocialFunction', 'is_public': True, 'is_private': False, 'external_references': 16}) - , Decrease Field Visibility({'udb_path': 'C:\\Users\\Administrator\\Downloads\\udbs\\10_water-simulator.udb', 'source_package': 'simulator.SA.gui', 'source_class': 'SuiteGUI', 'source_field': 'behaviourreceivepriceandmetdataByCodArt'}) - , Decrease Field Visibility({'udb_path': 'C:\\Users\\Administrator\\Downloads\\udbs\\10_water-simulator.udb', 'source_package': 'simulator.WSA', 'source_class': 'BehaviourQueryConsumers', 'source_field': 'behaviourQueryConsumersExtracted'}) - , Increase Method Visibility({'udb_path': 'C:\\Users\\Administrator\\Downloads\\udbs\\10_water-simulator.udb', 'source_package': 'simulator.MOA', 'source_class': 'MetOfficeAgent', 'source_method': 'unpackArguments'}) - , Decrease Field Visibility({'udb_path': 'C:\\Users\\Administrator\\Downloads\\udbs\\10_water-simulator.udb', 'source_package': 'simulator.SA.gui', 'source_class': 'PricingPolicyFrame', 'source_field': 'behaviourlaunchguiByCodArt'}) - , Move Class({'udb_path': 'C:\\Users\\Administrator\\Downloads\\udbs\\10_water-simulator.udb', 'class_name': 'WaterConsumption', 'source_package': 'simulator.ontology', 'target_package': 'simulator.ontology'}) - , Move Class({'udb_path': 'C:\\Users\\Administrator\\Downloads\\udbs\\10_water-simulator.udb', 'class_name': 'ConsumerGUI', 'source_package': 'simulator.CA.gui', 'target_package': 'simulator.CA.gui'}) - , Move Method({'source_package': 'simulator.SA.gui.ScenarioDesignWizard', 'source_class': 'Step3_1Frame', 'method_name': 'createParametersPanel', 'target_package': 'simulator.util', 'target_class': 'Function', 'udb_path': 'C:/Users/Administrator/Downloads/udbs\\10_water-simulator.udb'}) - , Make Method Non-Static({'udb_path': 'C:/Users/Administrator/Downloads/udbs\\10_water-simulator.udb', 'source_class': 'BehaviourQueryConsumers', 'method_name': 'handleAgree', 'is_public': False, 'is_private': False, 'external_references': 0}) - , Make Method Static({'udb_path': 'C:/Users/Administrator/Downloads/udbs\\10_water-simulator.udb', 'source_class': 'FunctionConstant', 'method_name': 'getConstantName', 'is_public': True, 'is_private': False, 'external_references': 6}) - , Make Method Static({'udb_path': 'C:/Users/Administrator/Downloads/udbs\\10_water-simulator.udb', 'source_class': 'MetOfficeAgent', 'method_name': 'setup', 'is_public': True, 'is_private': False, 'external_references': 0}) - , Increase Method Visibility({'udb_path': 'C:\\Users\\Administrator\\Downloads\\udbs\\10_water-simulator.udb', 'source_package': 'simulator.SA.gui.ReviewGUI', 'source_class': 'PriceTableModel', 'source_method': 'getValueAt'}) - , Push Down Field({'project_dir': 'C:\\Users\\Administrator\\Downloads\\udbs', 'source_class': 'Function', 'source_package': 'simulator.util', 'field_name': 'functionRepresentation', 'target_classes': ['Raise', 'MetDataFunction', 'Discrete']}) - , Extract Class({'source_class': 'SuiteGUI', 'moved_fields': ['mainPanel'], 'moved_methods': ['loadFile', 'saveFile', 'saveDirectory', 'addToMainPanel', 'errorMessage'], 'file_path': 'C:\\Users\\Administrator\\Downloads\\prj_src\\10_water-simulator\\src\\main\\java\\simulator\\SA\\gui\\SuiteGUI.java', 'udb_path': 'C:/Users/Administrator/Downloads/udbs\\10_water-simulator.udb'}) - , Make Field Non-Static({'udb_path': 'C:/Users/Administrator/Downloads/udbs\\10_water-simulator.udb', 'source_class': 'ReviewGUI', 'field_name': 'tableModel', 'is_public': False, 'is_private': False, 'external_references': 0}) \ No newline at end of file diff --git a/setup.py b/setup.py index 907845ef..937a5a62 100644 --- a/setup.py +++ b/setup.py @@ -10,7 +10,7 @@ setuptools.setup( name="codart", # Replace with your own username - version="0.1.1dev", + version="0.2.3dev", author="Morteza Zakeri", author_email="m-zakeri@live.com", description="CodART: Free source code automated refactoring toolkit", @@ -30,12 +30,14 @@ package_dir={ 'codart': 'codart', - 'gen': 'gen', - 'metrics': 'metrics', - 'refactoring_design_patterns': 'refactoring_design_patterns', - 'refactorings': 'refactorings', - 'sbse': 'sbse', - + 'codart.gen': 'codart.gen', + 'codart.metrics': 'codart.metrics', + 'codart.refactoring_design_patterns': 'codart.refactoring_design_patterns', + 'codart.refactorings': 'codart.refactorings', + 'codart.sbse': 'codart.sbse', + 'codart.smells': 'codart.smells', + 'codart.utility': 'codart.utility', + 'codart.visualization': 'codart.visualization', }, packages=setuptools.find_packages( @@ -43,19 +45,24 @@ [ 'codart', 'codart.*' - 'gen', - 'gen.*', - 'metrics', - 'metrics.*', - 'refactoring_design_patterns', - 'refactoring_design_patterns.*', - 'refactorings', - 'refactorings.*', - 'sbse', - 'sbse.*', - + 'codart.gen', + 'codart.gen.*', + 'codart.metrics', + 'codart.metrics.*', + 'codart.refactoring_design_patterns', + 'codart.refactoring_design_patterns.*', + 'codart.refactorings', + 'codart.refactorings.*', + 'codart.sbse', + 'codart.sbse.*', + 'codart.smells', + 'codart.smells.*', + 'codart.utility', + 'codart.utility.*', + 'codart.visualization', + 'codart.visualization.*', ] ), - python_requires=">=3.8", + python_requires=">=3.9", ) diff --git a/tests/extract_method/benchmark_projects_test/JSON/test_0.py b/tests/extract_method/benchmark_projects_test/JSON/test_0.py index 190f98cf..40076882 100644 --- a/tests/extract_method/benchmark_projects_test/JSON/test_0.py +++ b/tests/extract_method/benchmark_projects_test/JSON/test_0.py @@ -1,4 +1,4 @@ -from refactorings.extract_method import extract_method +from codart.refactorings.extract_method import extract_method from tests.extract_method.candidate_reader import CandidateReader import os import errno diff --git a/tests/extract_method/benchmark_projects_test/JSON/test_1.py b/tests/extract_method/benchmark_projects_test/JSON/test_1.py index b21e4734..79646cde 100644 --- a/tests/extract_method/benchmark_projects_test/JSON/test_1.py +++ b/tests/extract_method/benchmark_projects_test/JSON/test_1.py @@ -1,4 +1,4 @@ -from refactorings.extract_method import extract_method +from codart.refactorings.extract_method import extract_method from tests.extract_method.candidate_reader import CandidateReader import os import errno diff --git a/tests/extract_method/benchmark_projects_test/JSON/test_2.py b/tests/extract_method/benchmark_projects_test/JSON/test_2.py index bad126bb..7ef34985 100644 --- a/tests/extract_method/benchmark_projects_test/JSON/test_2.py +++ b/tests/extract_method/benchmark_projects_test/JSON/test_2.py @@ -1,4 +1,4 @@ -from refactorings.extract_method import extract_method +from codart.refactorings.extract_method import extract_method from tests.extract_method.candidate_reader import CandidateReader import os import errno diff --git a/tests/extract_method/benchmark_projects_test/JSON/test_3.py b/tests/extract_method/benchmark_projects_test/JSON/test_3.py index f0b3e667..3aa9f16a 100644 --- a/tests/extract_method/benchmark_projects_test/JSON/test_3.py +++ b/tests/extract_method/benchmark_projects_test/JSON/test_3.py @@ -1,4 +1,4 @@ -from refactorings.extract_method import extract_method +from codart.refactorings.extract_method import extract_method from tests.extract_method.candidate_reader import CandidateReader import os import errno diff --git a/tests/extract_method/benchmark_projects_test/JSON/test_5.py b/tests/extract_method/benchmark_projects_test/JSON/test_5.py index 288ba224..196429f4 100644 --- a/tests/extract_method/benchmark_projects_test/JSON/test_5.py +++ b/tests/extract_method/benchmark_projects_test/JSON/test_5.py @@ -1,4 +1,4 @@ -from refactorings.extract_method import extract_method +from codart.refactorings.extract_method import extract_method from tests.extract_method.candidate_reader import CandidateReader import os import errno diff --git a/tests/extract_method/benchmark_projects_test/xerces2-j/test.py b/tests/extract_method/benchmark_projects_test/xerces2-j/test.py index d7b38452..66f3214d 100644 --- a/tests/extract_method/benchmark_projects_test/xerces2-j/test.py +++ b/tests/extract_method/benchmark_projects_test/xerces2-j/test.py @@ -1,7 +1,7 @@ import unittest -from refactorings.extract_method import extract_method +from codart.refactorings.extract_method import extract_method from tests.extract_method.candidate_reader import CandidateReader from tests.extract_method.java_file_equality_checker import is_equal diff --git a/tests/extract_method/java_file_equality_checker.py b/tests/extract_method/java_file_equality_checker.py index 2933505b..bf433092 100644 --- a/tests/extract_method/java_file_equality_checker.py +++ b/tests/extract_method/java_file_equality_checker.py @@ -1,9 +1,8 @@ from antlr4 import * -from gen.javaLabeled.JavaLexer import JavaLexer +from codart.gen.javaLabeled.JavaLexer import JavaLexer - -def is_equal(file1,file2): +def is_equal(file1, file2): input_stream1 = FileStream(file1) lexer1 = JavaLexer(input_stream1) @@ -37,7 +36,7 @@ def is_equal(file1,file2): else: print(token1.line) print(token2.line) - print(token1.text ,'!=', token2.text,' = ',token1.text != token2.text) + print(token1.text, '!=', token2.text, ' = ', token1.text != token2.text) return False elif token1.type == lexer1.LPAREN: @@ -54,4 +53,3 @@ def is_equal(file1,file2): token2 = lexer2.nextToken() return True - diff --git a/tests/extract_method/test_1.py b/tests/extract_method/test_1.py index ddc2e128..9d1a1f55 100644 --- a/tests/extract_method/test_1.py +++ b/tests/extract_method/test_1.py @@ -4,17 +4,19 @@ test status: pass """ -from refactorings.extract_method import extract_method +from codart.refactorings.extract_method import extract_method + def main(): base_dir = '/mnt/d/Sajad/Uni/Spring00/Compiler/CodART/' _conf = { - 'target_file': base_dir +"tests/extract_method/in/ExtractMethodTest.java", - 'output_file': base_dir +"tests/extract_method/out/ExtractMethodTest.java", - 'lines': [7,8 ], + 'target_file': base_dir + "tests/extract_method/in/ExtractMethodTest.java", + 'output_file': base_dir + "tests/extract_method/out/ExtractMethodTest.java", + 'lines': [7, 8], 'new_method_name': 'printAllDetails', } extract_method(_conf) + if __name__ == '__main__': - main() \ No newline at end of file + main() diff --git a/tests/extract_method/test_2.py b/tests/extract_method/test_2.py index ad093683..35a1742b 100644 --- a/tests/extract_method/test_2.py +++ b/tests/extract_method/test_2.py @@ -4,25 +4,29 @@ test status: pass """ -from refactorings.extract_method import extract_method +from codart.refactorings.extract_method import extract_method import os import errno + def main(): base_dir = '/mnt/d/Sajad/Uni/Spring00/Compiler/CodART/' - if not os.path.exists(os.path.dirname(base_dir+"tests/extract_method/out/benchmark_projects/ganttproject/biz.ganttproject.core/src/main/java/org/w3c/util/DateParser.java")): + if not os.path.exists(os.path.dirname( + base_dir + "tests/extract_method/out/benchmark_projects/ganttproject/biz.ganttproject.core/src/main/java/org/w3c/util/DateParser.java")): try: - os.makedirs(os.path.dirname(base_dir+"tests/extract_method/out/benchmark_projects/ganttproject/biz.ganttproject.core/src/main/java/org/w3c/util/DateParser.java")) + os.makedirs(os.path.dirname( + base_dir + "tests/extract_method/out/benchmark_projects/ganttproject/biz.ganttproject.core/src/main/java/org/w3c/util/DateParser.java")) except OSError as exc: # Guard against race condition if exc.errno != errno.EEXIST: raise _conf = { - 'target_file': base_dir+"benchmark_projects/ganttproject/biz.ganttproject.core/src/main/java/org/w3c/util/DateParser.java", - 'output_file': base_dir+"tests/extract_method/out/benchmark_projects/ganttproject/biz.ganttproject.core/src/main/java/org/w3c/util/DateParser_test_2.java", - 'lines': [255,256,257,258 ], + 'target_file': base_dir + "benchmark_projects/ganttproject/biz.ganttproject.core/src/main/java/org/w3c/util/DateParser.java", + 'output_file': base_dir + "tests/extract_method/out/benchmark_projects/ganttproject/biz.ganttproject.core/src/main/java/org/w3c/util/DateParser_test_2.java", + 'lines': [255, 256, 257, 258], 'new_method_name': 'printDivider', } extract_method(_conf) + if __name__ == '__main__': - main() \ No newline at end of file + main() diff --git a/tests/extract_method/test_3.py b/tests/extract_method/test_3.py index e878d53a..107d478d 100644 --- a/tests/extract_method/test_3.py +++ b/tests/extract_method/test_3.py @@ -4,10 +4,11 @@ test status: pass """ -from refactorings.extract_method import extract_method +from codart.refactorings.extract_method import extract_method import os import errno + def main(): base_dir = '/mnt/d/Sajad/Uni/Spring00/Compiler/CodART/' if not os.path.exists(os.path.dirname( diff --git a/tests/extract_method/test_4.py b/tests/extract_method/test_4.py index 4a002433..8c3e521a 100644 --- a/tests/extract_method/test_4.py +++ b/tests/extract_method/test_4.py @@ -4,10 +4,11 @@ test status: pass """ -from refactorings.extract_method import extract_method +from codart.refactorings.extract_method import extract_method import os import errno + def main(): base_dir = '/mnt/d/Sajad/Uni/Spring00/Compiler/CodART/' if not os.path.exists(os.path.dirname( @@ -21,7 +22,7 @@ def main(): _conf = { 'target_file': base_dir + "benchmark_projects/ganttproject/biz.ganttproject.core/src/main/java/biz/ganttproject/core/calendar/WeekendCalendarImpl.java", 'output_file': base_dir + "tests/extract_method/out/benchmark_projects/ganttproject/biz.ganttproject.core/src/main/java/biz/ganttproject/core/calendar/WeekendCalendarImpl.java", - 'lines': [87,88], + 'lines': [87, 88], 'new_method_name': 'clearMap', } extract_method(_conf) diff --git a/tests/extract_method/test_5.py b/tests/extract_method/test_5.py index 4f0c9593..a4e27370 100644 --- a/tests/extract_method/test_5.py +++ b/tests/extract_method/test_5.py @@ -4,10 +4,11 @@ test status: pass """ -from refactorings.extract_method import extract_method +from codart.refactorings.extract_method import extract_method import os import errno + def main(): base_dir = '/mnt/d/Sajad/Uni/Spring00/Compiler/CodART/' if not os.path.exists(os.path.dirname( @@ -21,7 +22,7 @@ def main(): _conf = { 'target_file': base_dir + "benchmark_projects/ganttproject/biz.ganttproject.core/src/main/java/biz/ganttproject/core/calendar/WeekendCalendarImpl.java", 'output_file': base_dir + "tests/extract_method/out/benchmark_projects/ganttproject/biz.ganttproject.core/src/main/java/biz/ganttproject/core/calendar/WeekendCalendarImpl_test_5.java", - 'lines': [294,295,296,297,298,299,300,301,302], + 'lines': [294, 295, 296, 297, 298, 299, 300, 301, 302], 'new_method_name': 'iterateOnCalender', } extract_method(_conf) diff --git a/tests/extract_method/test_6.py b/tests/extract_method/test_6.py index 69d27dc4..4ad67913 100644 --- a/tests/extract_method/test_6.py +++ b/tests/extract_method/test_6.py @@ -4,10 +4,11 @@ test status: pass """ -from refactorings.extract_method import extract_method +from codart.refactorings.extract_method import extract_method import os import errno + def main(): base_dir = '/mnt/d/Sajad/Uni/Spring00/Compiler/CodART/' if not os.path.exists(os.path.dirname( @@ -21,7 +22,7 @@ def main(): _conf = { 'target_file': base_dir + "benchmark_projects/ganttproject/biz.ganttproject.core/src/main/java/biz/ganttproject/core/calendar/WeekendCalendarImpl.java", 'output_file': base_dir + "tests/extract_method/out/benchmark_projects/ganttproject/biz.ganttproject.core/src/main/java/biz/ganttproject/core/calendar/WeekendCalendarImpl_test_6.java", - 'lines': [181,182,183], + 'lines': [181, 182, 183], 'new_method_name': 'checkTypeCondition', } extract_method(_conf) diff --git a/tests/extract_method/test_7.py b/tests/extract_method/test_7.py index c9365a19..ded65a26 100644 --- a/tests/extract_method/test_7.py +++ b/tests/extract_method/test_7.py @@ -4,10 +4,11 @@ test status: pass """ -from refactorings.extract_method import extract_method +from codart.refactorings.extract_method import extract_method import os import errno + def main(): base_dir = '/mnt/d/Sajad/Uni/Spring00/Compiler/CodART/' if not os.path.exists(os.path.dirname( @@ -22,7 +23,7 @@ def main(): 'target_package': 'biz.ganttproject.core.chart.render', 'target_file': base_dir + "benchmark_projects/ganttproject/biz.ganttproject.core/src/main/java/biz/ganttproject/core/chart/render/Style.java", 'output_file': base_dir + "tests/extract_method/out/benchmark_projects/ganttproject/biz.ganttproject.core/src/main/java/biz/ganttproject/core/chart/render/Style.java", - 'lines': [108,109,110,111,112,113,114,115,116,117,118,119], + 'lines': [108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119], 'new_method_name': 'checkResult', } extract_method(_conf)