Java Code Examples for spoon.reflect.code.CtBlock#getStatements()

The following examples show how to use spoon.reflect.code.CtBlock#getStatements() . 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: AbstractCodeAnalyzer.java    From coming with MIT License 6 votes vote down vote up
public static boolean whethereffectiveguard(CtIf ifstatement, CtStatement targetstatement) {
	CtBlock thenBlock = ifstatement.getThenStatement();
	CtBlock elseBlock = ifstatement.getElseStatement();

	if (thenBlock != null) {
		List<CtStatement> thenstatements = thenBlock.getStatements();
		if (thenstatements.size() > 0 && thenstatements.get(0) == targetstatement)
			return true;
	}

	if (elseBlock != null) {
		List<CtStatement> elsestatements = elseBlock.getStatements();
		if (elsestatements.size() > 0 && elsestatements.get(0) == targetstatement)
			return true;
	}

	return false;
}
 
Example 2
Source File: APICheckingProcessor.java    From spoon-examples with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void process(CtMethod method) {
    final Factory factory = method.getFactory();

    CtBlock methodBody = method.getBody();

    List<CtComment> bodyComments = new ArrayList<>();

    ArrayList<CtStatement> ctStatements = new ArrayList<>(methodBody.getStatements());
    for (CtStatement ctStatement : ctStatements) {
        String statement = ctStatement.toString();
        bodyComments.add(factory.createInlineComment(statement));
        methodBody.removeStatement(ctStatement);
    }

    CtClass<? extends Throwable> myExceptionClass = factory.Class().get(EXCEPTION_FQN);
    CtConstructorCall<? extends Throwable> myNewException = factory.createConstructorCall(myExceptionClass.getReference());

    CtThrow throwMyException = factory.createThrow();
    throwMyException.setThrownExpression(myNewException);
    methodBody.addStatement(throwMyException);

    bodyComments.add(factory.createInlineComment("FIXME: The private API type should never be return in a public API."));

    for (CtComment bodyComment : bodyComments) {
        throwMyException.addComment(bodyComment);
    }
}
 
Example 3
Source File: AbstractCodeAnalyzer.java    From coming with MIT License 5 votes vote down vote up
public static boolean whethereffectivetrycatch(CtTry trystatement, CtStatement targetstatement) {

		CtBlock tryblock = trystatement.getBody();

		if (tryblock != null) {
			List<CtStatement> trystatements = tryblock.getStatements();
			// if(trystatements.size()>0 && trystatements.get(0)==targetstatement)
			if (trystatements.size() > 0)
				return true;
		}

		return false;
	}
 
Example 4
Source File: VariableResolver.java    From coming with MIT License 5 votes vote down vote up
/**
 * 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 5
Source File: ConditionAddTransform.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("rawtypes")
@Override
public <R> void visitCtBlock(CtBlock<R> block) {
	int id = 0;
	List<CtStatement>  statlist = block.getStatements();
	boolean flag = false;
	for (; id < statlist.size(); id++)
		if (statlist.get(id).equals((CtStatement) this.modificationPoint.getCodeElement())) {
			flag = true;
			break;
		}
	if (!flag)
		return;
	
	List<CtVariable> varsavilable = modificationPoint.getContextOfModificationPoint();
	PriorityQueue<CtVariable> queue = new PriorityQueue<CtVariable>(new Comparator<CtVariable>() {
		@Override
		public int compare(CtVariable o1, CtVariable o2) {
			return o2.getPosition().getLine()-o1.getPosition().getLine();
		}
	});	
	queue.addAll(varsavilable);
	
	List<String> types = new ArrayList<String>();
	while (!queue.isEmpty()) {
		CtVariable var = queue.poll();
	    String type = var.getType().getQualifiedName();
		type = type.replaceAll("\\d","");
		if (!types.contains(type)) {
			types.add(type);
			log.info(type);
			writeCondition(type, block, id);
			writeIfReturn(type, block, id);
		}
	}
}
 
Example 6
Source File: StatementOperatorInstance.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Return the position of the element in the block. It searches the same object
 * instance
 * 
 * @param parentBlock
 * @param line
 * @param element
 * @return
 */
public int locationInParent(CtBlock parentBlock, CtElement element) {
	int pos = 0;
	for (CtStatement s : parentBlock.getStatements()) {
		if (s == element)
			return pos;
		pos++;
	}

	return -1;

}
 
Example 7
Source File: VariableResolver.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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: BigTransfoScenarioTest.java    From spoon-examples with GNU General Public License v2.0 4 votes vote down vote up
@SuppressWarnings("all")
@Test
public void main() {
    MavenLauncher launcher = new MavenLauncher(
            "./src/test/resources/project/",
            MavenLauncher.SOURCE_TYPE.APP_SOURCE);

    CtModel model = launcher.buildModel();
    List<CtMethod> methodList = model.
            filterChildren(new NamedElementFilter<CtPackage>(CtPackage.class, "ow2con")).
            filterChildren(new NamedElementFilter<CtPackage>(CtPackage.class, "publicapi")).
            filterChildren(new TypeFilter<CtMethod>(CtMethod.class)).
            filterChildren(new Filter<CtMethod>() {
                @Override
                public boolean matches(CtMethod element) {
                    boolean isPublic = element.isPublic();
                    CtTypeReference returnType = element.getType();
                    String privateApiPackage = "ow2con.privateapi";
                    boolean isTypeFromPrivateApi = returnType.getQualifiedName().contains(privateApiPackage);
                    return isPublic && isTypeFromPrivateApi;
                }
            }).list();

    Factory factory = launcher.getFactory();
    CtClass<? extends Throwable> exceptionClass = factory.createClass("ow2con.PrivateAPIException");
    CtConstructorCall<? extends Throwable> exceptionInstance = factory.createConstructorCall(exceptionClass.getReference());

    for (CtMethod method : methodList) {
        CtBlock methodBody = method.getBody();
        List<CtComment> bodyComments = new ArrayList<>();

        ArrayList<CtStatement> ctStatements = new ArrayList<>(methodBody.getStatements());

        for (CtStatement ctStatement : ctStatements) {
            String statement = ctStatement.toString();
            CtComment statementAsComment = factory.createInlineComment(statement);
            bodyComments.add(statementAsComment);
            methodBody.removeStatement(ctStatement);
        }

        CtThrow throwMyException = factory.createThrow();
        CtConstructorCall<? extends Throwable> constructorCall = exceptionInstance.clone();
        throwMyException.setThrownExpression(constructorCall);
        methodBody.addStatement(throwMyException);

        bodyComments.add(
                factory.createInlineComment(
                "FIXME: The private API type should never be return in a public API."
                )
        );

        for (CtComment bodyComment : bodyComments) {
            throwMyException.addComment(bodyComment);
        }
    }

    Environment environment = launcher.getEnvironment();
    environment.setCommentEnabled(true);
    environment.setAutoImports(true);
    // the transformation must produce compilable code
    environment.setShouldCompile(true);
    launcher.prettyprint();

    // look in folder spooned/ow2con/publicapi/ the transformed code
}