Java Code Examples for spoon.reflect.declaration.CtElement#getParent()
The following examples show how to use
spoon.reflect.declaration.CtElement#getParent() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ASTInfoResolver.java From coming with MIT License | 6 votes |
public static List<CtElement> getNSubsequentParents(CtElement node, int n) { List<CtElement> lst = new ArrayList<CtElement>(); lst.add(node); CtElement curPar = node.getParent(); for (int i = 0; i < n; i++) { if (curPar == null) break; lst.add(curPar); curPar = curPar.getParent(); } return lst; }
Example 2
Source File: LogicalExpressionMetaMutator.java From metamutator with GNU General Public License v3.0 | 5 votes |
/** * Check if this sub expression was already inside an uppermost expression * that was processed has a hot spot. This version does not allowed * conflicting hot spots * * @param element * the current expression to test * @return true if this expression is descendant of an already processed * expression */ private boolean alreadyInHotsSpot(CtElement element) { CtElement parent = element.getParent(); while (!isTopLevel(parent) && parent != null) { if (hostSpots.contains(parent)) return true; parent = parent.getParent(); } return false; }
Example 3
Source File: AbstractCodeAnalyzer.java From coming with MIT License | 5 votes |
public boolean isNullCheckGuard(CtElement element, CtStatement parentStatement) { // Two cases: if and conditional CtExpression condition = null; CtConditional parentConditional = element.getParent(CtConditional.class); if (parentConditional != null) {// TODO, maybe force that the var must be in the condition, or not. CtConditional cond = (CtConditional) parentConditional; condition = cond.getCondition(); return checkNullCheckGuardCondition(condition); } else { CtElement parentElement = getParentNotBlock(parentStatement); // First, find the condition if (parentElement instanceof CtIf) { CtIf guardCandidateIf = (CtIf) parentElement; if (whethereffectiveguard(guardCandidateIf, parentStatement)) { condition = guardCandidateIf.getCondition(); boolean isConditionAGuard = checkNullCheckGuardCondition(condition); return isConditionAGuard; } } } return false; }
Example 4
Source File: CtGlobalIngredientScope.java From astor with GNU General Public License v2.0 | 5 votes |
/** * We find the root package (empty package) */ @Override public CtElement calculateLocation(CtElement elementToModify) { CtElement root = null; CtElement parent = elementToModify; do { root = parent; parent = root.getParent(getCtElementForSplitSpace()); } while (parent != null); return root; }
Example 5
Source File: S4RORepairAnalyzer.java From coming with MIT License | 5 votes |
public List<CtElement> getCandidateLocalVars(CtElement element, Type type) { List<CtElement> ret = new ArrayList<>(); CtMethod ownedMethod = element.getParent(new TypeFilter<>(CtMethod.class)); if (ownedMethod != null) { for (CtLocalVariable tmp : ownedMethod.getElements(new TypeFilter<>(CtLocalVariable.class))) { if (tmp.getClass().getGenericSuperclass() == type) { ret.add(tmp); } } } return ret; }
Example 6
Source File: EnhancedRepairAnalyzer.java From coming with MIT License | 5 votes |
public Set<CtElement> getGlobalCandidateExprs(CtElement element) { Set<CtElement> ret = new HashSet<>(); CtClass ownedClass = element.getParent(new TypeFilter<>(CtClass.class)); if (ownedClass != null) { ret.addAll(ownedClass.getElements(new TypeFilter<>(CtExpression.class))); } return ret; }
Example 7
Source File: VariableResolver.java From coming with MIT License | 5 votes |
/** * Return the local variables of a block from the beginning until the element * located at positionEl. * * @param positionEl analyze variables from the block until that position. * @param pb a block to search the local variables * @return */ protected static List<CtLocalVariable> retrieveLocalVariables(int positionEl, CtBlock pb) { List stmt = pb.getStatements(); List<CtLocalVariable> variables = new ArrayList<CtLocalVariable>(); for (int i = 0; i < positionEl; i++) { CtElement ct = (CtElement) stmt.get(i); if (ct instanceof CtLocalVariable) { variables.add((CtLocalVariable) ct); } } CtElement beforei = pb; CtElement parenti = pb.getParent(); boolean continueSearch = true; // We find the parent block while (continueSearch) { if (parenti == null) { continueSearch = false; parenti = null; } else if (parenti instanceof CtBlock) { continueSearch = false; } else { beforei = parenti; parenti = parenti.getParent(); } } if (parenti != null) { int pos = ((CtBlock) parenti).getStatements().indexOf(beforei); variables.addAll(retrieveLocalVariables(pos, (CtBlock) parenti)); } return variables; }
Example 8
Source File: EnhancedFeatureExtractor.java From coming with MIT License | 5 votes |
private void getNearbyStmts(Repair repair, List<CtElement> stmtsF, List<CtElement> stmtsL) { final int LOOKUP_DIS = 3; CtElement srcElem = repair.srcElem; CtElement parent = srcElem.getParent(); if (parent instanceof CtStatementList) { CtStatementList CS = (CtStatementList) parent; List<CtStatement> tmp = new ArrayList<>(); int idx = 0; boolean found = false; for (CtStatement stmt: CS.getStatements()) { if (stmt.equals(srcElem)) { found = true; idx = tmp.size(); } tmp.add(stmt); } assert(found); int s = 0; if (idx > LOOKUP_DIS) s = idx - LOOKUP_DIS; int e = tmp.size(); if (idx + LOOKUP_DIS + 1 < tmp.size()) e = idx + LOOKUP_DIS + 1; boolean above = true; for (int i = s; i < e; i++) { if (tmp.get(i).equals(srcElem)) { if (above) stmtsF.add(tmp.get(i)); else stmtsL.add(tmp.get(i)); } if (tmp.get(i).equals(srcElem)) above = false; } } if (!repair.isReplace) stmtsL.add(srcElem); }
Example 9
Source File: S4RORepairAnalyzer.java From coming with MIT License | 5 votes |
public List<CtElement> getCondCandidateVars(CtElement element) { List<CtElement> ret = new ArrayList<>(); // Global variables CtClass ownedClass = element.getParent(new TypeFilter<>(CtClass.class)); if (ownedClass != null) { ret.addAll(ownedClass.getElements(new TypeFilter<>(CtVariableAccess.class))); ret.addAll(ownedClass.getElements(new TypeFilter<>(CtArrayAccess.class))); } // Local variables CtMethod ownedMethod = element.getParent(new TypeFilter<>(CtMethod.class)); if (ownedMethod != null) { ret.addAll(ownedMethod.getElements(new TypeFilter<>(CtLocalVariable.class))); } return ret; }
Example 10
Source File: ConditionAddTransform.java From astor with GNU General Public License v2.0 | 5 votes |
@SuppressWarnings({ "rawtypes", "static-access", "unchecked" }) private void writeIfReturn(String type, CtBlock parent, int id) { CtExpression conditionExp = ExpressionGenerator.fetchEXP(this.mutSupporter, this.modificationPoint, type, querytype); CtIf ifstmt = this.mutSupporter.getFactory().Core().createIf(); ifstmt.setCondition(conditionExp); CtElement parentmethod=parent; do { parentmethod=parentmethod.getParent(); } while (!(parentmethod instanceof CtMethod)); String returntype="void"; returntype=((CtMethod)parentmethod).getType().getQualifiedName(); returntype = returntype.replaceAll("\\d",""); CtReturn returnstmt = this.mutSupporter.getFactory().Core().createReturn(); if (!returntype.toLowerCase().equals("void")) { CtExpression returnexp = ExpressionGenerator.fetchEXP(this.mutSupporter, this.modificationPoint, returntype, "EXP"); returnstmt.setReturnedExpression(returnexp); } ifstmt.setThenStatement(returnstmt); parent.addStatement(id, ifstmt); saveSketchAndSynthesize(); parent.removeStatement(ifstmt); resoreDiskFile(); }
Example 11
Source File: ReplaceReturnOp.java From astor with GNU General Public License v2.0 | 5 votes |
@SuppressWarnings({ "rawtypes", "unchecked", "static-access" }) private CtElement createReturn(CtElement rootElement) { CtMethod method = rootElement.getParent(CtMethod.class); if (method == null) { log.info("Element without method parent"); return null; } // We create the "if(true)"{} CtIf ifReturn = MutationSupporter.getFactory().Core().createIf(); CtExpression ifTrueExpression = MutationSupporter.getFactory().Code().createCodeSnippetExpression("true"); ifReturn.setCondition(ifTrueExpression); // Now we create the return statement CtReturn<?> returnStatement = null; CtTypeReference typeR = method.getType(); if (typeR == null || "void".equals(typeR.getSimpleName())) { returnStatement = MutationSupporter.getFactory().Core().createReturn(); } else { String codeExpression = ""; if (prim.contains(typeR.getSimpleName())) { codeExpression = getZeroValue(typeR.getSimpleName().toLowerCase()); } else if (typeR.getSimpleName().toLowerCase().equals("boolean")) { codeExpression = "false"; } else { codeExpression = "null"; } CtExpression returnExpression = MutationSupporter.getFactory().Code() .createCodeSnippetExpression(codeExpression); returnStatement = MutationSupporter.getFactory().Core().createReturn(); returnStatement.setReturnedExpression(returnExpression); } // Now, we associate if(true){return [...]} ifReturn.setThenStatement(returnStatement); return ifReturn; }
Example 12
Source File: S4RORepairAnalyzer.java From coming with MIT License | 5 votes |
public Set<CtElement> getGlobalCandidateExprs(CtElement element) { Set<CtElement> ret = new HashSet<>(); CtClass ownedClass = element.getParent(new TypeFilter<>(CtClass.class)); if (ownedClass != null) { ret.addAll(ownedClass.getElements(new TypeFilter<>(CtExpression.class))); } return ret; }
Example 13
Source File: EnhancedRepairAnalyzer.java From coming with MIT License | 5 votes |
public List<CtElement> getCondCandidateVars(CtElement element) { List<CtElement> ret = new ArrayList<>(); // Global variables CtClass ownedClass = element.getParent(new TypeFilter<>(CtClass.class)); if (ownedClass != null) { ret.addAll(ownedClass.getElements(new TypeFilter<>(CtVariableAccess.class))); ret.addAll(ownedClass.getElements(new TypeFilter<>(CtArrayAccess.class))); } // Local variables CtMethod ownedMethod = element.getParent(new TypeFilter<>(CtMethod.class)); if (ownedMethod != null) { ret.addAll(ownedMethod.getElements(new TypeFilter<>(CtLocalVariable.class))); } return ret; }
Example 14
Source File: Selector.java From metamutator with GNU General Public License v3.0 | 5 votes |
public static CtClass<?> getTopLevelClass(CtElement element) { CtClass parent = element.getParent(CtClass.class); while (!parent.isTopLevel()) { parent = parent.getParent(CtClass.class); } return parent; }
Example 15
Source File: SpoonPredicate.java From nopol with GNU General Public License v2.0 | 4 votes |
public static boolean canBeRepairedByAddingPrecondition(final CtElement element) { CtElement parent = element.getParent(); if (parent == null) { return false; } if (element.toString().startsWith("super(")) { return false; } boolean isCtStatement = element instanceof CtStatement && !(element instanceof CtBlock); boolean isCtReturn = element instanceof CtReturn; boolean isInsideIf = parent.getParent() instanceof CtIf; // Checking parent isn't enough, parent will be CtBlock and grandpa will be CtIf boolean isCtLocalVariable = element instanceof CtLocalVariable; boolean isInBlock = parent instanceof CtBlock; if (isInBlock) { boolean isInMethod = parent.getParent() instanceof CtMethod; if (isInMethod) { if (((CtBlock) parent).getLastStatement() == element && !((CtMethod) parent.getParent()).getType().box().equals(element.getFactory().Class().VOID)) { return false; } } } boolean isInsideIfLoopCaseBlock = (parent instanceof CtIf || parent instanceof CtLoop || parent instanceof CtCase || parent instanceof CtBlock); boolean isInsideForDeclaration = parent instanceof CtFor ? ((CtFor) (parent)).getForUpdate().contains(element) || ((CtFor) (parent)).getForInit().contains(element) : false; boolean isCtSynchronized = element instanceof CtSynchronized; boolean result = isCtStatement // element instanceof CtClass || // cannot insert code before '{}', for example would try to add code between 'Constructor()' and '{}' // element instanceof CtBlock || && !isCtSynchronized // cannot insert a conditional before 'return', it won't compile. && !(isCtReturn && !(isInsideIf)) // cannot insert a conditional before a variable declaration, it won't compile if the variable is used // later on. && !isCtLocalVariable // Avoids ClassCastException's. @see spoon.support.reflect.code.CtStatementImpl#insertBefore(CtStatement // target, CtStatementList<?> statements) && isInsideIfLoopCaseBlock // cannot insert if inside update statement in for loop declaration && !isInsideForDeclaration ; return result; }
Example 16
Source File: CodeFeatureDetector.java From coming with MIT License | 4 votes |
public Cntx<?> analyzeFeatures(CtElement element) { CtClass parentClass = element instanceof CtClass ? (CtClass) element : element.getParent(CtClass.class); CtElement elementToStudy = retrieveElementToStudy(element); List<CtExpression> expressionssFromFaultyLine = elementToStudy.getElements(e -> (e instanceof CtExpression)).stream() .map(CtExpression.class::cast).collect(Collectors.toList()); LinkedHashSet<CtExpression> hashSetExpressions = new LinkedHashSet<>(expressionssFromFaultyLine); ArrayList<CtExpression> listExpressionWithoutDuplicates = new ArrayList<>(hashSetExpressions); ArrayList<CtExpression> removeUndesirable = new ArrayList<>(); for (int index = 0; index < listExpressionWithoutDuplicates.size(); index++) { CtExpression certainExpression = listExpressionWithoutDuplicates.get(index); if (certainExpression instanceof CtVariableAccess || certainExpression instanceof CtLiteral || certainExpression instanceof CtInvocation || certainExpression instanceof CtConstructorCall || certainExpression instanceof CtArrayRead || analyzeWhetherAE(certainExpression)) removeUndesirable.add(certainExpression); } List<CtExpression> logicalExpressions = new ArrayList(); for (int index = 0; index < expressionssFromFaultyLine.size(); index++) { if (isBooleanExpressionNew(expressionssFromFaultyLine.get(index)) && !whetherparentboolean(expressionssFromFaultyLine.get(index)) && !logicalExpressions.contains(expressionssFromFaultyLine.get(index))) { logicalExpressions.add(expressionssFromFaultyLine.get(index)); } } List<CtBinaryOperator> allBinOperators = parentClass.getElements(e -> (e instanceof CtBinaryOperator)).stream() .map(CtBinaryOperator.class::cast).collect(Collectors.toList()); // element, desirableExpressions, logicalExpressions, binoperators return analyzeFeatures(element, removeUndesirable, logicalExpressions, allBinOperators); }
Example 17
Source File: JGenProgTest.java From astor with GNU General Public License v2.0 | 4 votes |
@SuppressWarnings("rawtypes") @Test public void testMath70ThisKeyword() throws Exception { AstorMain main1 = new AstorMain(); String dep = new File("./examples/libs/junit-4.4.jar").getAbsolutePath(); File out = new File(ConfigurationProperties.getProperty("workingDirectory")); int generations = 0; String[] args = commandMath70(dep, out, generations); CommandSummary cs = new CommandSummary(args); cs.command.put("-flthreshold", "1"); cs.command.put("-stopfirst", "true"); cs.command.put("-loglevel", "INFO"); cs.command.put("-saveall", "true"); cs.append("-parameters", ("logtestexecution:true")); System.out.println(Arrays.toString(cs.flat())); main1.execute(cs.flat()); assertEquals(1, main1.getEngine().getVariants().size()); ProgramVariant variant = main1.getEngine().getVariants().get(0); JGenProg jgp = (JGenProg) main1.getEngine(); ReplaceOp rop = new ReplaceOp(); CtElement elMP1 = variant.getModificationPoints().get(0).getCodeElement(); assertEquals(elMP1.toString(), "return solve(min, max)"); System.out.println(elMP1); List<Ingredient> ingredients = jgp.getIngredientSearchStrategy().getIngredientSpace().getIngredients(elMP1, elMP1.getClass().getSimpleName()); System.out.println(ingredients); Optional<Ingredient> patchOptional = ingredients.stream() .filter(e -> e.getCode().toString().equals("return solve(f, min, max)")).findAny(); assertTrue(patchOptional.isPresent()); CtElement patch = patchOptional.get().getCode(); assertEquals(patch.toString(), "return solve(f, min, max)"); StatementOperatorInstance operation = new StatementOperatorInstance(); operation.setOriginal(elMP1); operation.setOperationApplied(rop); operation.setModificationPoint(variant.getModificationPoints().get(0)); operation.defineParentInformation(variant.getModificationPoints().get(0)); operation.setModified(patch); variant.putModificationInstance(0, operation); boolean changed = VariableResolver.changeShadowedVars(elMP1, patch); assertTrue(changed); System.out.println("Pach code before: " + patch); CtMethod mep = (CtMethod) elMP1.getParent(spoon.reflect.declaration.CtMethod.class); System.out.println("Parent before:\n" + mep); elMP1.replace(patch); System.out.println("Parent after:\n" + mep); System.out.println("Pach code after: " + patch); // assertEquals(patch.toString(),"return solve(this.f, min, max)"); assertEquals(patch.toString(), "return solve(f, min, max)"); patch.setImplicit(false); System.out.println("Pach code after impl: " + patch); }
Example 18
Source File: VariableResolver.java From astor with GNU General Public License v2.0 | 4 votes |
/** * Returns all variables in scope, reachable from the ctelement passes as * argument * * @param element * @return */ @SuppressWarnings({ "rawtypes", "unchecked" }) public static List<CtVariable> searchVariablesInScope(CtElement element) { List<CtVariable> variables = new ArrayList(); if (element == null) { return variables; } if (element instanceof CtField) { return variables; } // We find the CtClass and returns the fields CtClass ctclass = element.getParent(CtClass.class); if (ctclass != null) { Collection<CtFieldReference<?>> vars = ctclass.getAllFields(); for (CtFieldReference<?> ctFieldReference : vars) { // We dont add private fields from parent classes if ((!ctFieldReference.getModifiers().contains(ModifierKind.PRIVATE) || ctclass.getFields().contains(ctFieldReference.getDeclaration()))) { // We ignore "serialVersionUID' if ((ctFieldReference.getDeclaration() != null) && !"serialVersionUID".equals(ctFieldReference.getDeclaration().getSimpleName())) variables.add(ctFieldReference.getDeclaration()); } } } // We find the parent method and we extract the parameters CtMethod method = element.getParent(CtMethod.class); if (method != null) { List<CtParameter> pars = method.getParameters(); for (CtParameter ctParameter : pars) { variables.add(ctParameter); } } // We find the parent block and we extract the local variables before // the element under analysis CtBlock parentblock = element.getParent(CtBlock.class); CtElement currentElement = element; if (parentblock != null) { int positionEl = parentblock.getStatements().indexOf(currentElement); variables.addAll(VariableResolver.retrieveLocalVariables(positionEl, parentblock)); if (ConfigurationProperties.getPropertyBool("consideryvarloops")) { variables.addAll(getVarsInFor(currentElement)); variables.addAll(getVarsInForEach(currentElement)); } } return variables; }
Example 19
Source File: DetectorChangePatternInstanceEngine.java From coming with MIT License | 4 votes |
/** * Match the element affected by an operation from the diff and the elements in * the pattern specification * * @param affectedOperation * @param affectedEntity * @return */ private List<MatchingEntity> matchElements(Operation affectedOperation, PatternEntity affectedEntity) { List<MatchingEntity> matching = new ArrayList<>(); int parentLevel = 1; PatternEntity parentEntity = affectedEntity; // Let's get the parent of the affected CtElement currentNodeFromAction = null; boolean matchnewvalue = false; // Search the node to select according to the type of operation and the pattern if (affectedOperation.getDstNode() != null && affectedEntity.getNewValue() != null) { currentNodeFromAction = affectedOperation.getDstNode(); matchnewvalue = true; } else if (affectedOperation instanceof UpdateOperation && (affectedEntity.getOldValue() != null)) { currentNodeFromAction = affectedOperation.getSrcNode(); matchnewvalue = false; } else { matchnewvalue = true; currentNodeFromAction = affectedOperation.getNode(); } int i_levels = 1; // Scale the parent hierarchy and check types. while (currentNodeFromAction != null && i_levels <= parentLevel) { String typeOfNode = EntityTypesInfoResolver.getNodeLabelFromCtElement(currentNodeFromAction); String valueOfNode = currentNodeFromAction.toString(); String roleInParent = (currentNodeFromAction.getRoleInParent() != null) ? currentNodeFromAction.getRoleInParent().toString().toLowerCase() : ""; String patternEntityValue = (matchnewvalue) ? parentEntity.getNewValue() : parentEntity.getOldValue(); if ( // type of element ("*".equals(parentEntity.getEntityType()) // || (typeOfNode != null && typeOfNode.equals(parentEntity.getEntityType()))) || (typeOfNode != null && EntityTypesInfoResolver.getInstance().isAChildOf(typeOfNode, parentEntity.getEntityType()))) /// && // value of element ("*".equals(patternEntityValue) || (valueOfNode != null && valueOfNode.equals(patternEntityValue))) // && // role ("*".equals(parentEntity.getRoleInParent()) || (roleInParent != null && roleInParent.equals(parentEntity.getRoleInParent().toLowerCase())))) { MatchingEntity match = new MatchingEntity(currentNodeFromAction, parentEntity); matching.add(match); ParentPatternEntity parentEntityFromPattern = parentEntity.getParentPatternEntity(); if (parentEntityFromPattern == null) { return matching; } i_levels = 1; parentLevel = parentEntityFromPattern.getParentLevel(); parentEntity = parentEntityFromPattern.getParent(); } else { // Not match i_levels++; } currentNodeFromAction = currentNodeFromAction.getParent(); } // Not all matched return null; }
Example 20
Source File: ExpressionReplaceOperator.java From astor with GNU General Public License v2.0 | 3 votes |
public boolean isStatement(CtElement toModif) { if (!(toModif instanceof CtStatement)) return false; if (toModif.getParent() instanceof CtBlock) return true; CtRole roleInParent = toModif.getRoleInParent(); if (CtRole.BODY.equals(roleInParent) || CtRole.THEN.equals(roleInParent) || CtRole.ELSE.equals(roleInParent)) return true; return false; }