Java Code Examples for spoon.reflect.declaration.CtElement

The following examples show how to use spoon.reflect.declaration.CtElement. These examples are extracted from open source projects. 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 Project: astor   Source File: VariableResolver.java    License: 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 2
Source Project: coming   Source File: EnhancedRepairGenerator.java    License: 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 3
Source Project: nopol   Source File: SpoonStatementLibrary.java    License: 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 4
Source Project: coming   Source File: VariableResolver.java    License: 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 5
Source Project: astor   Source File: UnwrapfromMethodCallOp.java    License: 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 Project: coming   Source File: ASTInfoResolver.java    License: 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 7
Source Project: coming   Source File: AbstractCodeAnalyzer.java    License: 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 8
Source Project: gumtree-spoon-ast-diff   Source File: DiffImpl.java    License: 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 9
Source Project: gumtree-spoon-ast-diff   Source File: AstComparatorTest.java    License: 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 10
Source Project: astor   Source File: SupportOperators.java    License: 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 11
Source Project: coming   Source File: ExtendedRepairGenerator.java    License: 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 12
Source Project: coming   Source File: LogicalExpressionAnalyzer.java    License: 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 13
/**
 * 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 Project: astor   Source File: Prediction.java    License: 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 15
Source Project: coming   Source File: CodeFeatureDetector.java    License: 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 16
/**
 * 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 17
Source Project: astor   Source File: VariableResolver.java    License: GNU General Public License v2.0 5 votes vote down vote up
private static List<CtLocalVariable> getVarsInFor(CtElement element) {
	List<CtLocalVariable> variables = new ArrayList<CtLocalVariable>();
	CtElement currentElement = element;
	CtFor ff = currentElement.getParent(CtFor.class);
	while (ff != null) {
		variables.addAll(ff.getForInit().stream().filter(e -> e instanceof CtLocalVariable)
				.map(CtLocalVariable.class::cast).collect(Collectors.toList()));

		ff = ff.getParent(CtFor.class);

	}
	return variables;
}
 
Example 18
Source Project: coming   Source File: EnhancedRepairAnalyzer.java    License: MIT License 5 votes vote down vote up
public Set<CtElement> getGlobalCandidateIfStmts(CtElement element) {
    Set<CtElement> ret = new HashSet<>();
    CtClass ownedClass = element.getParent(new TypeFilter<>(CtClass.class));
    if (ownedClass != null) {
        ret.addAll(ownedClass.getElements(new TypeFilter<>(CtIf.class)));
    }
    return ret;
}
 
Example 19
/**
 * 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 20
private boolean alreadyInHotsSpot(CtElement element) {
	CtElement parent = element.getParent();
	while (!isTopLevel(parent) && parent != null) {
		if (hotSpots.contains(parent))
			return true;

		parent = parent.getParent();
	}

	return false;
}
 
Example 21
Source Project: gumtree-spoon-ast-diff   Source File: TreeTest.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void scan(CtElement element) {
	if (element != null) {
		CtPath path = element.getPath();
		assertNotNull(path);

	}
	// to avoid visiting all childs
	super.scan(element);
}
 
Example 22
Source Project: coming   Source File: EnhancedFeatureVisitor.java    License: 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 23
Source Project: astor   Source File: VariableResolver.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Retrieves the variables out of scope from the element given a context.
 */
public static List<CtVariableAccess> retriveVariablesOutOfContext(List<CtVariable> varContext,
		CtElement ingredientCtElement) {
	boolean duplicated = true;
	List<CtVariableAccess> allVariablesFromElement = collectVariableAccess(ingredientCtElement, duplicated);
	return retriveVariablesOutOfContext(varContext, allVariablesFromElement);
}
 
Example 24
Source Project: nopol   Source File: SpoonModelLibrary.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static CtTry newTryCatch(Factory factory, CtStatement tryBlock, List<CtCatch> catchers, CtElement parent) {
    CtTry tryCatch = factory.Core().createTry();
    tryCatch.setBody(asBlock(tryBlock, tryCatch));
    tryCatch.setCatchers(catchers);
    setParent(tryCatch, catchers);
    setParent(parent, tryCatch);
    return tryCatch;
}
 
Example 25
protected List<CtInvocation> getInvocations(CtElement suspiciousElement) {
	List<CtInvocation> invocations = null;
	if (targetElement == null)
		invocations = suspiciousElement.getElements(e -> (e instanceof CtInvocation));
	else {
		invocations = new ArrayList<>();
		invocations.add((CtInvocation) targetElement);
	}
	return invocations;
}
 
Example 26
Source Project: astor   Source File: InvocationResolver.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Return all variables related to the element passed as argument
 * 
 * @param element
 * @return
 */
@SuppressWarnings("rawtypes")
public static List<CtAbstractInvocation> collectInvocation(CtElement element, boolean duplicates) {
	List<CtAbstractInvocation> varaccess = new ArrayList<>();

	CtScanner sc = new CtScanner() {

		public void add(CtAbstractInvocation e) {
			if (duplicates || !varaccess.contains(e))
				varaccess.add(e);
		}

		@Override
		public <T> void visitCtInvocation(CtInvocation<T> invocation) {
			super.visitCtInvocation(invocation);
			add(invocation);
		}

		@Override
		public <T> void visitCtConstructorCall(CtConstructorCall<T> ctConstructorCall) {
			super.visitCtConstructorCall(ctConstructorCall);
			add(ctConstructorCall);
		}

	};

	sc.scan(element);

	return varaccess;

}
 
Example 27
Source Project: gumtree-spoon-ast-diff   Source File: TreeScanner.java    License: Apache License 2.0 5 votes vote down vote up
private String getNodeType(CtElement element) {
	String nodeTypeName = NOTYPE;
	if (element != null) {
		nodeTypeName = getTypeName(element.getClass().getSimpleName());
	}
	if (element instanceof CtBlock) {
		nodeTypeName = element.getRoleInParent().toString();
	}
	return nodeTypeName;
}
 
Example 28
Source Project: coming   Source File: ASTInfoResolver.java    License: MIT License 5 votes vote down vote up
public static CtElement getFirstAncestorOfType(CtElement node, CtEntityType type) {
	String typeStr = type.toString();

	List<CtElement> pathToRoot = getPathToRootNode(node);
	for (int i = pathToRoot.size() - 1; i >= 0; i--) {
		CtElement parent = pathToRoot.get(i);
		if (EntityTypesInfoResolver.getInstance()
				.isAChildOf(EntityTypesInfoResolver.getNodeLabelFromCtElement(parent), typeStr)) {
			return parent;
		}
	}
	return null;
}
 
Example 29
Source Project: nopol   Source File: PatchGenerator.java    License: 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 30
Source Project: astor   Source File: TOSEntity.java    License: 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();
}