spoon.reflect.declaration.CtElement Java Examples

The following examples show how to use spoon.reflect.declaration.CtElement. 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: SpoonStatementLibrary.java    From nopol with GNU General Public License v2.0 6 votes vote down vote up
public static boolean isLastStatementOfMethod(CtStatement statement) {
    CtElement statementParent = statement.getParent();
    if (!isStatementList(statementParent)) {
        return isLastStatementOfMethod((CtStatement) statementParent);
    }
    CtStatementList block = (CtStatementList) statementParent;
    if (isLastStatementOf(block, statement)) {
        CtElement blockParent = block.getParent();
        if (isStatement(blockParent)) {
            return isLastStatementOfMethod((CtStatement) blockParent);
        } else {
            return isMethod(blockParent);
        }
    }
    return false;
}
 
Example #2
Source File: LogicalExpressionAnalyzer.java    From coming with MIT License 6 votes vote down vote up
public boolean isBooleanExpression(CtElement currentexpression) {
	
	if (currentexpression == null|| currentexpression instanceof CtVariableAccess)
		return false;
	
	if (isLogicalExpression(currentexpression)) {
		return true;
	}
	
	if(currentexpression instanceof CtExpression) {
		CtExpression exper= (CtExpression) currentexpression;
	   try {
	      if (exper.getType() != null
			&& exper.getType().unbox().toString().equals("boolean")) {
		  return true;
	     }
	   } catch (Exception e) {
		   return false;
	   }
	}

	return false;
}
 
Example #3
Source File: ASTInfoResolver.java    From coming with MIT License 6 votes vote down vote up
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 #4
Source File: EnhancedRepairGenerator.java    From coming with MIT License 6 votes vote down vote up
private Set<CtElement> fuzzyLocator(CtElement statement) {
    Set<CtElement> locations = new HashSet<>();
    if (statement instanceof CtMethod || statement instanceof CtClass || statement instanceof CtIf || statement instanceof CtStatementList) {
        locations.add(statement);
    } else {
        // "int a;" is not CtStatement?
        CtElement parent = statement.getParent();
        if (parent != null) {
            List<CtElement> statements = parent.getElements(new TypeFilter<>(CtElement.class));
            if (parent instanceof CtStatement) {
                statements = statements.subList(1, statements.size());
            }
            int idx = statements.indexOf(statement);
            if (idx >= 0) {
                if (idx > 0)
                    locations.add(statements.get(idx - 1));
                locations.add(statements.get(idx));
                if (idx < statements.size() - 1)
                    locations.add(statements.get(idx + 1));
            }
        }
    }
    return locations;
}
 
Example #5
Source File: UnwrapfromMethodCallOp.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
private MapList<CtInvocation, Ingredient> retrieveMethodHasCompatibleParameterAndReturnSameMethod(
		CtElement suspiciousElement) {

	MapList<CtInvocation, Ingredient> result = new MapList<CtInvocation, Ingredient>();
	List<CtInvocation> invocations = suspiciousElement.getElements(e -> (e instanceof CtInvocation)).stream()
			.map(CtInvocation.class::cast).collect(Collectors.toList());

	for (CtInvocation invocation : invocations) {

		for (Object oparameter : invocation.getArguments()) {
			CtExpression argument = (CtExpression) oparameter;

			if (SupportOperators.checkIsSubtype(argument.getType(), invocation.getType())) {

				CtExpression clonedExpressionArgument = argument.clone();
				MutationSupporter.clearPosition(clonedExpressionArgument);
				Ingredient newIngredient = new Ingredient(clonedExpressionArgument);
				result.add(invocation, newIngredient);

			}

		}
	}
	return result;
}
 
Example #6
Source File: AbstractCodeAnalyzer.java    From coming with MIT License 6 votes vote down vote up
public boolean isElementBeforeVariable(CtVariableAccess variableAffected, CtElement element) {

		try {
			CtStatement stst = (element instanceof CtStatement) ? (CtStatement) element
					: element.getParent(CtStatement.class);

			CtStatement target = (variableAffected instanceof CtStatement) ? (CtStatement) variableAffected
					: variableAffected.getParent(CtStatement.class);

			return target.getPosition() != null && getParentNotBlock(stst) != null
					&& target.getPosition().getSourceStart() > stst.getPosition().getSourceStart();
		} catch (Exception e) {
			// e.printStackTrace();
		}
		return false;

	}
 
Example #7
Source File: DiffImpl.java    From gumtree-spoon-ast-diff with Apache License 2.0 6 votes vote down vote up
private String toDebugString(List<Operation> ops) {
	String result = "";
	for (Operation operation : ops) {
		ITree node = operation.getAction().getNode();
		final CtElement nodeElement = operation.getNode();
		String nodeType = context.getTypeLabel(node.getType());
		if (nodeElement != null) {
			nodeType += "(" + nodeElement.getClass().getSimpleName() + ")";
		}
		result += "OperationKind." + operation.getAction().getClass().getSimpleName() + ", \"" + nodeType + "\", \"" + node.getLabel()+ "\"";

		if (operation instanceof UpdateOperation) {
			// adding the new value for update
			result += ",  \"" + ((Update) operation.getAction()).getValue() + "\"";
		}

		result += " (size: " + node.getDescendants().size() + ")" + node.toTreeString();
	}
	return result;
}
 
Example #8
Source File: AstComparatorTest.java    From gumtree-spoon-ast-diff with Apache License 2.0 6 votes vote down vote up
@Test
public void test_t_204225() throws Exception {
	AstComparator diff = new AstComparator();
	// meld
	// src/test/resources/examples/t_204225/left_UMLModelElementStereotypeComboBoxModel_1.3.java
	// src/test/resources/examples/t_204225/right_UMLModelElementStereotypeComboBoxModel_1.4.java
	File fl = new File("src/test/resources/examples/t_204225/left_UMLModelElementStereotypeComboBoxModel_1.3.java");
	File fr = new File(
			"src/test/resources/examples/t_204225/right_UMLModelElementStereotypeComboBoxModel_1.4.java");
	Diff result = diff.compare(fl, fr);

	CtElement ancestor = result.commonAncestor();
	assertTrue(ancestor instanceof CtReturn);

	List<Operation> actions = result.getRootOperations();
	// result.debugInformation();
	assertEquals(actions.size(), 2);
	assertTrue(result.containsOperation(OperationKind.Insert, "BinaryOperator", "OR"));
	assertTrue(result.containsOperation(OperationKind.Move, "BinaryOperator", "AND"));

}
 
Example #9
Source File: VariableResolver.java    From coming with MIT License 6 votes vote down vote up
/**
 * 
 * @param var
 * @param rootElement
 * @return
 */
private static boolean checkParent(CtVariable var, CtElement rootElement) {

	if (rootElement == null)
		logger.error("Error! root element null");
	CtElement parent = var;
	while (parent != null
			&& !(parent instanceof CtPackage)/*
												 * && !CtPackage. TOP_LEVEL_PACKAGE_NAME. equals(parent.toString())
												 */) {
		if (parent.equals(rootElement))
			return true;
		parent = parent.getParent();
	}

	return false;
}
 
Example #10
Source File: Prediction.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Override
public JsonElement toJson() {

	JsonObject root = new JsonObject();

	for (PredictionElement predictedElement : this.getElementsWithPrediction()) {
		CtElement element = predictedElement.getElement();
		root.addProperty("code", element.toString());
		root.addProperty("type", element.getClass().getSimpleName());
		root.addProperty("path", element.getPath().toString());
		root.addProperty("index", predictedElement.getIndex());
		JsonArray ops = new JsonArray();
		root.add("ops", ops);
		for (AstorOperator op : this.get(predictedElement)) {
			if (op != null)
				ops.add(op.name());
		}

	}

	return root;
}
 
Example #11
Source File: CodeFeatureDetector.java    From coming with MIT License 6 votes vote down vote up
public CtElement retrieveElementToStudy(CtElement element) {

        if (element instanceof CtIf) {
            return (((CtIf) element).getCondition());
        } else if (element instanceof CtWhile) {
            return (((CtWhile) element).getLoopingExpression());
        } else if (element instanceof CtFor) {
            return (((CtFor) element).getExpression());
        } else if (element instanceof CtDo) {
            return (((CtDo) element).getLoopingExpression());
//		} else if (element instanceof CtConditional) {
//			return (((CtConditional) element).getCondition());
        } else if (element instanceof CtForEach) {
            return (((CtForEach) element).getExpression());
        } else if (element instanceof CtSwitch) {
            return (((CtSwitch) element).getSelector());
        } else
            return (element);

    }
 
Example #12
Source File: ExtendedRepairGenerator.java    From coming with MIT License 6 votes vote down vote up
private Set<CtElement> fuzzyLocator(CtElement statement) {
    Set<CtElement> locations = new HashSet<>();
    if (statement instanceof CtMethod || statement instanceof CtClass || statement instanceof CtIf || statement instanceof CtStatementList) {
        locations.add(statement);
    } else {
        // "int a;" is not CtStatement?
        CtElement parent = statement.getParent();
        if (parent != null) {
            List<CtElement> statements = parent.getElements(new TypeFilter<>(CtElement.class));
            if (parent instanceof CtStatement) {
                statements = statements.subList(1, statements.size());
            }
            int idx = statements.indexOf(statement);
            if (idx >= 0) {
                if (idx > 0)
                    locations.add(statements.get(idx - 1));
                locations.add(statements.get(idx));
                if (idx < statements.size() - 1)
                    locations.add(statements.get(idx + 1));
            }
        }
    }
    return locations;
}
 
Example #13
Source File: CtLocationIngredientSpace.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creation of fix space from a CtClass
 * 
 * @param root
 */
public void determineScopeOfIngredient(List<CtCodeElement> ingredients) {

	for (CtCodeElement ctCodeElement : ingredients) {
		Ingredient ing = new Ingredient(ctCodeElement);
		CtElement key = mapKey(ctCodeElement);
		if (getFixSpace().containsKey(key)) {
			getFixSpace().get(key).add(ing);
		} else {
			List<Ingredient> ingr = new ArrayList<>();
			ingr.add(ing);
			getFixSpace().put(key, ingr);
		}

	}
	recreateTypesStructures();

}
 
Example #14
Source File: VariableResolver.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
public static IngredientPoolScope determineIngredientScope(CtElement ingredient, CtElement fix) {

		File ingp = ingredient.getPosition().getFile();
		File fixp = fix.getPosition().getFile();

		if (ingp == null || fixp == null)
			return null;

		if (ingp.getAbsolutePath().equals(fixp.getAbsolutePath())) {
			return IngredientPoolScope.LOCAL;
		}
		if (ingp.getParentFile().getAbsolutePath().equals(fixp.getParentFile().getAbsolutePath())) {
			return IngredientPoolScope.PACKAGE;
		}
		return IngredientPoolScope.GLOBAL;
	}
 
Example #15
Source File: SupportOperators.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Retrieves all variables from the target element and all ingredients
 * 
 * @param elementtochange
 * @param candidates
 * @return
 */
public static List<CtVariableAccess> collectAllVars(CtElement elementtochange, List<Ingredient> candidates) {
	List<CtVariableAccess> varAccess = VariableResolver.collectVariableAccess(elementtochange);

	for (Ingredient candidateIngr : candidates) {
		CtElement candidate = candidateIngr.getCode();
		List<CtVariableAccess> varAccessCandidate = VariableResolver.collectVariableAccess(candidate);
		for (CtVariableAccess varX : varAccessCandidate) {
			if (!varAccess.contains(varX)) {
				varAccess.add(varX);
			}
		}
	}

	return varAccess;
}
 
Example #16
Source File: TOSEntity.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Override
public CtElement getCode() {
	if (this.ingredientCode == null) {
		return this.generateCodeofTOS();
	}
	return super.getCode();
}
 
Example #17
Source File: VariabletoNullMetaMutator.java    From metamutator with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 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 #18
Source File: VariableAnalyzer.java    From coming with MIT License 5 votes vote down vote up
private CtElement getPotentionalParentCondition (CtStatement toStudy) {
	CtElement parent;
	parent=toStudy;
	do {
		parent= parent.getParent();
	} while (!whetherConditionalStat(parent) && parent!=null);
	
	return parent;
}
 
Example #19
Source File: ValuesCollectorTest.java    From nopol with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings({"unchecked", "rawtypes"})
private CtElement elementFromSnippet(File sourceFile, String codeSnippet) {
	Factory model = SpoonModelLibrary.modelFor(new File[]{sourceFile});
	Filter filter = new CodeSnippetFilter(sourceFile, codeSnippet);
	// used to debug when the pretty-printed format of Spoon changes
	// for (CtType t : model.getModel().getAllTypes()) {
	//	System.out.println(t);
	//}
	List<CtElement> elements = SpoonElementLibrary.filteredElements(model, filter);
	assertEquals(1, elements.size());
	return elements.get(0);
}
 
Example #20
Source File: SymbolicConditionalAdder.java    From nopol with GNU General Public License v2.0 5 votes vote down vote up
public void process(CtStatement element) {
    logger.debug("##### {} ##### Before:\n{}", element, element.getParent());
    CtElement parent = element.getParent();
    CtIf newIf = element.getFactory().Core().createIf();
    CtCodeSnippetExpression<Boolean> condition;
    if (getValue() != null) {
        switch (getValue()) {
            case "1":
                condition = element.getFactory().Code()
                        .createCodeSnippetExpression("true");
                break;
            case "0":
                condition = element.getFactory().Code()
                        .createCodeSnippetExpression("false");
                break;
            default:
                condition = element.getFactory().Code()
                        .createCodeSnippetExpression(getValue());
        }
    } else {
        condition = element
                .getFactory()
                .Code()
                .createCodeSnippetExpression(
                        Debug.class.getCanonicalName()
                                + ".makeSymbolicBoolean(\"guess_fix\")");
    }
    newIf.setCondition(condition);
    // Fix : warning: ignoring inconsistent parent for [CtElem1] ( [CtElem2] != [CtElem3] )
    newIf.setParent(parent);
    element.replace(newIf);
    // this should be after the replace to avoid an StackOverflowException caused by the circular reference.
    newIf.setThenStatement(element);
    // Fix : warning: ignoring inconsistent parent for [CtElem1] ( [CtElem2] != [CtElem3] )
    newIf.getThenStatement().setParent(newIf);
    logger.debug("##### {} ##### After:\n{}", element, element.getParent().getParent());
}
 
Example #21
Source File: PatchGenerator.java    From nopol with GNU General Public License v2.0 5 votes vote down vote up
private CtElement getTarget() {
	CtType type = factory.Type().get(patch.getSourceLocation().getRootClassName());
	EarlyTerminatingScanner<CtElement> targetFinder = new EarlyTerminatingScanner<CtElement>() {
		@Override
		protected void enter(CtElement e) {
			if (e.getPosition() instanceof NoSourcePosition) {
				return;
			}
			if (e.getPosition().getSourceStart() == patch.getSourceLocation().getBeginSource()
					&& e.getPosition().getSourceEnd() == patch.getSourceLocation().getEndSource() && e.isImplicit() == false) {
				if (patch.getType() == RepairType.CONDITIONAL && e instanceof CtIf) {
					setResult(((CtIf) e).getCondition());
				} else {
					setResult(e);
				}
				terminate();
				return;
			}
			if (e.getPosition().getSourceStart() <= patch.getSourceLocation().getBeginSource()
					&& e.getPosition().getSourceEnd() >= patch.getSourceLocation().getEndSource()) {
				super.enter(e);
			}
		}
	};
	type.accept(targetFinder);
	return targetFinder.getResult();
}
 
Example #22
Source File: ExpressionTypeIngredientSpace.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Override
public String calculateLocation(CtElement elementToModify) {

	if (IngredientPoolScope.PACKAGE.equals(scope)) {
		return elementToModify.getParent(CtPackage.class).getQualifiedName();
	} else if (IngredientPoolScope.LOCAL.equals(scope)) {
		return elementToModify.getParent(CtType.class).getQualifiedName();
	} else if (IngredientPoolScope.GLOBAL.equals(scope))
		return "Global";

	return null;

}
 
Example #23
Source File: SpoonSupport.java    From gumtree-spoon-ast-diff with Apache License 2.0 5 votes vote down vote up
public CtElement getMappedElement(Diff diff, CtElement elementToMatch, boolean isFromSource) {

		for (Mapping mapping : diff.getMappingsComp().asSet()) {
			ITree matchingNode = isFromSource ? mapping.getFirst() : mapping.getSecond();
			CtElement associatedElement = (CtElement) matchingNode.getMetadata(SpoonGumTreeBuilder.SPOON_OBJECT);
			if (elementToMatch == associatedElement) {
				ITree linked = isFromSource ? diff.getMappingsComp().getDst(matchingNode)
						: diff.getMappingsComp().getSrc(matchingNode);
				return (CtElement) linked.getMetadata(SpoonGumTreeBuilder.SPOON_OBJECT);
			}
		}

		return null;
	}
 
Example #24
Source File: ValuesCollectorTest.java    From nopol with GNU General Public License v2.0 5 votes vote down vote up
@Test
@Ignore
public void reachedVariablesInExample4() {
	elementInNopolProject(4, "int uninitializedVariableShouldNotBeCollected");
	CtElement element = elementInNopolProject(4, "a = a.substring(1)");
	testReachedVariableNames(element, "a", "initializedVariableShouldBeCollected", "otherInitializedVariableShouldBeCollected");
}
 
Example #25
Source File: Nopol.java    From coming with MIT License 5 votes vote down vote up
private CtElement getWrapperIfConditoin(CtElement node) {
	List<CtElement> pathToRoot = ASTInfoResolver.getPathToRootNode(node);

	for (int i = pathToRoot.size() - 1; i >= 0; i--) {
		if (pathToRoot.get(i).getRoleInParent().equals(CtRole.CONDITION) && pathToRoot.get(i - 1) instanceof CtIf) {
			return pathToRoot.get(i);
		}
	}

	return null;
}
 
Example #26
Source File: AbstractCodeAnalyzer.java    From coming with MIT License 5 votes vote down vote up
public String adjustIdentifyInJson(CtElement spoonElement) {

		if (spoonElement.getAllMetadata().containsKey("gtnode")) {
			ITree gumtreeObject = (ITree) spoonElement.getMetadata("gtnode");

			return gumtreeObject.getLabel();
		} else {
			return spoonElement.getShortRepresentation();
		}
	}
 
Example #27
Source File: FineGrainedExpressionReplaceOperator.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("rawtypes")
@Override
public boolean applyChangesInModel(OperatorInstance opInstance, ProgramVariant p) {

	CtExpression elementToModify = (CtExpression) opInstance.getOriginal();
	CtExpression elementOriginalCloned = (CtExpression) MutationSupporter.clone(elementToModify);

	CtElement elFixIngredient = opInstance.getModified();

	MetaGenerator.getSourceTarget().put(elementToModify, elFixIngredient);

	// MetaGenerator.targetSource.put(elementToModify, elFixIngredient);

	this.originalParent = elementToModify.getParent();
	// we transform the Spoon model
	try {
		elementToModify.replace(elFixIngredient);
	} catch (Exception e) {
		log.error("error to modify " + elementOriginalCloned + " to " + elFixIngredient);
		log.error(e);
		e.printStackTrace();
		opInstance.setExceptionAtApplied(e);
		return false;
	}
	opInstance.setOriginal(elementToModify);

	boolean change = !opInstance.getModificationPoint().getCodeElement().toString()
			.equals(elementOriginalCloned.toString());

	if (!change)
		log.error("Replacement does not work for  modify " + elementOriginalCloned + " to " + elFixIngredient);

	return true;
}
 
Example #28
Source File: OriginalFeatureVisitor.java    From coming with MIT License 5 votes vote down vote up
private void putValueFeature(CtElement v, AtomicFeature af) {
        if (v == null) {
            if (!resMap.containsKey("@")) {
                resMap.put("@", new HashSet<>());
            }
            resMap.get("@").add(af);
        }
        else {
//            CtExpression e = stripParenAndCast(v);
//            std::string tmp = stmtToString(*ast, e);
            String tmp = v.toString();
            // i can not know why there is one return here
//            if (v instanceof CtAssignment) {
//                return;
//            }
            // CtInvocation or CtExecutable todo check
//            if (v.getElements(new TypeFilter<>(CtInvocation.class)).size() > 0 && !isAbstractStub(v)) {
//                return;
//            }
            if (!resMap.containsKey(tmp)) {
                resMap.put(tmp, new HashSet<>());
            }
            resMap.get(tmp).add(af);
            if (!valueExprInfo.containsKey(tmp)) {
                valueExprInfo.put(tmp, v);
            }
        }
    }
 
Example #29
Source File: MethodAnalyzer.java    From coming with MIT License 5 votes vote down vote up
private int[] argumentDiffMethod(List<CtElement> argumentsoriginal, List<CtElement> argumentsother, 
	   CtInvocation invocationaccess) {
	
	int numberdiffargument =0;
	int numberdiffmethodreplacebyvar =0;
	int numberdiffmethodreplacebymethod =0;
	
	for(int index=0; index<argumentsoriginal.size(); index++) {
		
		CtElement original = argumentsoriginal.get(index);
		CtElement other = argumentsother.get(index);
		
		if(original.equals(other) || original.toString().equals(other.toString())) {
			// same
		} else {
			numberdiffargument+=1;
			if(original instanceof CtInvocation && original.equals(invocationaccess)) {
				if(other instanceof CtVariableAccess)
					numberdiffmethodreplacebyvar+=1;
				else if(other instanceof CtInvocation || other instanceof CtConstructorCall)
					numberdiffmethodreplacebymethod+=1;
				else {
					// do nothing
				}
			}
		}
	}

	int diffarray[]=new int[3];
	diffarray[0]=numberdiffargument;
	diffarray[1]=numberdiffmethodreplacebyvar;
	diffarray[2]=numberdiffmethodreplacebymethod;

      return diffarray;
}
 
Example #30
Source File: jMutRepairEvolutionary.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
private CtExpression getExpressionFromElement(CtElement element) {

		if (element instanceof CtExpression)
			return (CtExpression) element;

		if (element instanceof CtIf) {
			return ((CtIf) element).getCondition();
		}
		// TODO: to continue

		return null;
	}