-
Notifications
You must be signed in to change notification settings - Fork 1
Implementation of JMove algorithm #49
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
emironovich
wants to merge
14
commits into
master
Choose a base branch
from
origin/JMove
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 11 commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
4a705b2
first draft of an algorithm
emironovich 7cf22d0
naive approach
emironovich a6e0dde
approach that should work (fixed the problem with finding ClassEntity…
emironovich 6be7cd4
added JMove to ALGORITHMS array
emironovich 3e63a26
Got annotations and exceptions in Dependencies done
emironovich 33d2c3d
Added a bit of logger; now calculating all the Dependencies at once; …
emironovich 0e3f03a
added finding of object instantiations for dependencies class by fini…
emironovich f65c786
now ignoring primitive types and types and annotations from java.lang…
emironovich 038d4e6
added getter/setter check
emironovich 479cb9c
made one set of dependencies instead of several + added formal parame…
emironovich ee9f333
made function checking for util or lang packaging
emironovich 9232fc0
added logging and error handeling
emironovich 5a9d622
improved finding of best class
emironovich 5df403b
extremly important negation
emironovich File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
276 changes: 276 additions & 0 deletions
276
src/main/java/org/ml_methods_group/algorithm/JMove.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,276 @@ | ||
| /* | ||
| * Copyright 2018 Machine Learning Methods in Software Engineering Group of JetBrains Research | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
|
|
||
| package org.ml_methods_group.algorithm; | ||
|
|
||
|
|
||
| import com.intellij.psi.*; | ||
| import org.apache.log4j.Logger; | ||
| import org.jetbrains.annotations.NotNull; | ||
| import org.jetbrains.annotations.Nullable; | ||
| import org.ml_methods_group.algorithm.entity.ClassEntity; | ||
| import org.ml_methods_group.algorithm.entity.MethodEntity; | ||
| import org.ml_methods_group.config.Logging; | ||
|
|
||
| import java.util.*; | ||
|
|
||
| public class JMove extends Algorithm { | ||
| private static final Logger LOGGER = Logging.getLogger(JMove.class); | ||
| private final int MIN_NUMBER_OF_CANDIDATE_CLASSES = 3; | ||
| private final int MIN_NUMBER_OF_DEPENDENCIES = 4; | ||
| private final double MIN_DIFF_BETWEEN_SIMILARITY_COEFF_PERS = 0.25; | ||
|
|
||
| public JMove() { | ||
| super("JMove", false); | ||
| } | ||
|
|
||
| @Override | ||
| protected List<Refactoring> calculateRefactorings(ExecutionContext context, boolean enableFieldRefactorings) { | ||
| LOGGER.info("Starting calculating refactorings"); | ||
| List<MethodEntity> allMethods = context.getEntities().getMethods(); | ||
| List<ClassEntity> allClasses = context.getEntities().getClasses(); | ||
| LOGGER.info("Found " + allMethods.size() + " methods and " + allClasses.size() + " classes"); | ||
| List<Refactoring> refactorings = new ArrayList<>(); | ||
|
|
||
| Map<String, ClassEntity> nameToClassEntity = new HashMap<>(); | ||
| Map<String, Dependencies> nameToDependencies = new HashMap<>(); | ||
|
|
||
| for(ClassEntity classEntity : allClasses) { | ||
| nameToClassEntity.put(classEntity.getName(), classEntity); | ||
| } | ||
|
|
||
| for(MethodEntity methodEntity : allMethods) { | ||
| nameToDependencies.put(methodEntity.getName(), new Dependencies(methodEntity, nameToClassEntity)); | ||
| } | ||
|
|
||
|
|
||
| for(MethodEntity curMethod : allMethods) { | ||
| if(!curMethod.isMovable()) | ||
| continue; | ||
| LOGGER.info("Checking " + curMethod.getName()); // todo some logging | ||
|
|
||
| Dependencies curDependencies = nameToDependencies.get(curMethod.getName()); | ||
| ClassEntity curClass = nameToClassEntity.get(curMethod.getClassName()); | ||
| if(curDependencies.cardinality() < MIN_NUMBER_OF_DEPENDENCIES //experimental | ||
| || curClass.getRelevantProperties().getMethods().size() == 1 //because we calculate similarity between this method and all remaining in curClass | ||
| || isGetter(curMethod) //this methods are rarely implemented in the wrong classes | ||
| || isSetter(curMethod)) //todo: check if we need this check here and not in other place | ||
| continue; | ||
| double curSimilarity = calculateSimilarity(curMethod, curClass, nameToDependencies); | ||
| Map<ClassEntity, Double> potentialClasses = new HashMap<>(); | ||
| for(ClassEntity potentialClass : allClasses) { | ||
| double potentialClassSimilarity = calculateSimilarity(curMethod, potentialClass, nameToDependencies); | ||
| if (potentialClassSimilarity > curSimilarity) { | ||
| potentialClasses.put(potentialClass, potentialClassSimilarity); | ||
| } | ||
| } | ||
|
|
||
| if(potentialClasses.size() < MIN_NUMBER_OF_CANDIDATE_CLASSES) | ||
| continue; | ||
|
|
||
| ClassEntity bestClass = findBestClass(potentialClasses); | ||
| if(bestClass != null) { | ||
| double diff = (potentialClasses.get(bestClass) - curSimilarity)/potentialClasses.get(bestClass); //may be idk | ||
| if(diff >= MIN_DIFF_BETWEEN_SIMILARITY_COEFF_PERS) | ||
| refactorings.add(new Refactoring(curMethod.getName(), bestClass.getName(), diff, false)); //accuracy ~ difference between coeff ?? idk | ||
| } | ||
| //todo may be i should check weither it is possible to make this refactoring oops | ||
| } | ||
| return refactorings; | ||
| } | ||
|
|
||
| private double calculateSimilarity(@NotNull MethodEntity methodEntity, @NotNull ClassEntity classEntity, Map<String, Dependencies> nameToDependencies) { | ||
| double similarity = 0; | ||
| Set<String> methodNames = classEntity.getRelevantProperties().getMethods(); | ||
|
|
||
| for(String curMethodName : methodNames) { | ||
| if(!methodEntity.getName().equals(curMethodName)) | ||
| similarity += methodSimilarity(nameToDependencies.get(methodEntity.getName()), nameToDependencies.get(curMethodName)); | ||
| } | ||
| if(methodEntity.getClassName().equals(classEntity.getName())) | ||
| return similarity / methodNames.size(); | ||
| else | ||
| return similarity / (methodNames.size() - 1); | ||
| } | ||
|
|
||
| private double methodSimilarity (@NotNull Dependencies depFst,@NotNull Dependencies depSnd) { | ||
| int depCardinalityFst = depFst.cardinality(); | ||
| int depCardinalitySnd = depSnd.cardinality(); | ||
| int depCardinalityIntersection = depFst.calculateIntersectionCardinality(depSnd); | ||
| return (double)depCardinalityIntersection/(depCardinalityFst + depCardinalitySnd - depCardinalityIntersection); // Jaccard Coefficient | ||
| } | ||
|
|
||
| private class Dependencies { | ||
|
|
||
| //method calls | ||
| //field accesses | ||
| //object instantiations | ||
| //local declarations | ||
| // formal parameters | ||
| //return type | ||
| //exceptions | ||
| //annotations | ||
|
|
||
| private Set<String> all; | ||
|
|
||
| //ignoring primitive types and types and annotations from java.lang and java.util | ||
|
|
||
| protected Dependencies(@NotNull MethodEntity methodForDependencies, @NotNull Map<String, ClassEntity> nameToClassEntity ) { | ||
| all = new HashSet<>(); //todo use | ||
|
|
||
| //classes of methods that are called inside this method | ||
| for(String methodName : methodForDependencies.getRelevantProperties().getMethods()) { | ||
| if(!methodName.equals(methodForDependencies.getName())) //because it's somehow always there | ||
| all.add(methodName.substring(0, methodName.lastIndexOf('.'))); | ||
| } | ||
|
|
||
| // classes of fields that the method accesses | ||
| for(String fieldName : methodForDependencies.getRelevantProperties().getFields()) { | ||
| PsiType psiType = nameToClassEntity.get(fieldName.substring(0, fieldName.lastIndexOf('.'))).getPsiClass().findFieldByName(fieldName.substring(fieldName.lastIndexOf('.') + 1), false).getType(); | ||
| if(!(psiType instanceof PsiPrimitiveType) || fromUtilOrLang(psiType.getCanonicalText())) | ||
| all.add(psiType.getCanonicalText()); | ||
| } | ||
|
|
||
| //return type | ||
| PsiType returnType = methodForDependencies.getPsiMethod().getReturnType(); | ||
| if(!(returnType instanceof PsiPrimitiveType ||fromUtilOrLang(returnType.getCanonicalText()))) | ||
| all.add(returnType.getCanonicalText()); | ||
|
|
||
|
|
||
| //exceptions | ||
| //idk check for internal exception handling may be | ||
| PsiClassType[] referencedTypes = methodForDependencies.getPsiMethod().getThrowsList().getReferencedTypes(); | ||
| for(PsiClassType classType : referencedTypes) { | ||
| if(!(fromUtilOrLang(classType.getCanonicalText()))) | ||
| all.add(classType.getCanonicalText()); | ||
| } | ||
|
|
||
| //annotations | ||
| PsiAnnotation[] psiAnnotations = methodForDependencies.getPsiMethod().getModifierList().getAnnotations(); | ||
| for(PsiAnnotation psiAnnotation : psiAnnotations) { | ||
| if(!fromUtilOrLang(psiAnnotation.getQualifiedName())) | ||
| all.add(psiAnnotation.getQualifiedName()); | ||
| } | ||
|
|
||
| //formal parameters | ||
| for(PsiParameter parameter: methodForDependencies.getPsiMethod().getParameterList().getParameters()) { | ||
| if(!((parameter.getType() instanceof PsiPrimitiveType) || fromUtilOrLang(parameter.getType().getCanonicalText()))) | ||
| all.add(parameter.getType().getCanonicalText()); | ||
| } | ||
|
|
||
|
|
||
| methodForDependencies.getPsiMethod().accept(new JavaRecursiveElementVisitor() { | ||
| @Override | ||
| public void visitLocalVariable(PsiLocalVariable variable) { | ||
| super.visitLocalVariable(variable); | ||
| if(!(variable.getType() instanceof PsiPrimitiveType || fromUtilOrLang(variable.getType().getCanonicalText()))) | ||
| all.add(variable.getType().getCanonicalText()); | ||
| } | ||
| @Override | ||
| public void visitNewExpression(PsiNewExpression expression) { | ||
| super.visitNewExpression(expression); | ||
| if (!(fromUtilOrLang(expression.getClassOrAnonymousClassReference().getQualifiedName()))) | ||
| all.add(expression.getClassOrAnonymousClassReference().getQualifiedName()); | ||
| } | ||
|
|
||
| // @Override idk this way I will find all annotations may be I shouldn't | ||
| // public void visitAnnotation(PsiAnnotation annotation) { | ||
| // super.visitAnnotation(annotation); | ||
| // if(!annotation.getQualifiedName().startsWith("java.lang.") || | ||
| // annotation.getQualifiedName().startsWith("java.util.")) | ||
| // annotations.add(annotation.getQualifiedName()); | ||
| // } | ||
|
|
||
|
|
||
| }); | ||
| } | ||
|
|
||
| public int cardinality() { | ||
|
|
||
| return all.size(); | ||
| } | ||
|
|
||
| public int calculateIntersectionCardinality(@NotNull Dependencies depSnd) { | ||
|
|
||
| Set<String> intersection = new HashSet<>(all); | ||
| intersection.retainAll(depSnd.all); | ||
|
|
||
| // Set<String> methodCallIntersection = new HashSet<>(methodCalls); | ||
| // methodCallIntersection.retainAll(depSnd.methodCalls); | ||
| // intersectionCardinality += methodCallIntersection.size(); | ||
| // | ||
| // Set<String> instancesIntersection = new HashSet<>(fieldAccesses); | ||
| // instancesIntersection.retainAll(depSnd.fieldAccesses); | ||
| // intersectionCardinality += instancesIntersection.size(); | ||
| // | ||
| // if(returnType.equals(depSnd.returnType)) | ||
| // intersectionCardinality++; | ||
| // | ||
| // Set<String> exceptionsIntersection = new HashSet<>(exceptions); | ||
| // exceptionsIntersection.retainAll(depSnd.exceptions); | ||
| // intersectionCardinality += exceptionsIntersection.size(); | ||
| // | ||
| // Set<String> annotationsIntersection = new HashSet<>(exceptions); | ||
| // annotationsIntersection.retainAll(depSnd.exceptions); | ||
| // intersectionCardinality += annotationsIntersection.size(); | ||
| // | ||
| // Set<String> localVariablesIntersection = new HashSet<>(localDeclarations); | ||
| // localVariablesIntersection.retainAll(depSnd.localDeclarations); | ||
| // intersectionCardinality += localVariablesIntersection.size(); | ||
|
|
||
| return intersection.size(); | ||
| } | ||
|
|
||
| } | ||
|
|
||
| @Nullable | ||
| private ClassEntity findBestClass(@NotNull Map<ClassEntity, Double> potentialClasses) { //choose movable class with the biggest coefficient | ||
| if(potentialClasses.size() < MIN_NUMBER_OF_CANDIDATE_CLASSES) | ||
| return null; | ||
| ClassEntity bestClass = null; | ||
| Double bestCoefficient = 0.0; | ||
| for(Map.Entry<ClassEntity, Double> entry : potentialClasses.entrySet()) { | ||
| if(entry.getValue() > bestCoefficient) { | ||
| bestCoefficient = entry.getValue(); | ||
| bestClass = entry.getKey(); | ||
| } | ||
| } | ||
| return bestClass; | ||
| } | ||
|
|
||
| private boolean isGetter (@NotNull MethodEntity methodEntity) { | ||
| PsiMethod psiMethod = methodEntity.getPsiMethod(); | ||
| int numSt = psiMethod.getBody().getStatements().length; | ||
| if(psiMethod.getParameterList().getParametersCount() == 0 && numSt == 1) | ||
| return true; | ||
| return false; | ||
| } | ||
|
|
||
| private boolean isSetter(@NotNull MethodEntity methodEntity) { | ||
| PsiMethod psiMethod = methodEntity.getPsiMethod(); | ||
| int numSt = psiMethod.getBody().getStatements().length; | ||
| if(psiMethod.getParameterList().getParametersCount() == 1 && numSt == 1) | ||
| return true; | ||
| return false; | ||
| } | ||
|
|
||
| private boolean fromUtilOrLang (String fullName) { | ||
| if(fullName.startsWith("java.lang.") || fullName.startsWith("java.util.")) | ||
|
||
| return true; | ||
| else | ||
| return false; | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
there is no need to store all potential target classes, you can simply introduce counter variable and use single potential class entity