org.eclipse.jdt.core.dom.Block Java Examples

The following examples show how to use org.eclipse.jdt.core.dom.Block. 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: Eclipse-Postfix-Code-Completion   Author: trylimits   File: FlowAnalyzer.java    License: Eclipse Public License 1.0 6 votes vote down vote up
@Override
public boolean visit(TryStatement node) {
	if (traverseNode(node)) {
		fFlowContext.pushExcptions(node);
		node.getBody().accept(this);
		fFlowContext.popExceptions();
		List<CatchClause> catchClauses= node.catchClauses();
		for (Iterator<CatchClause> iter= catchClauses.iterator(); iter.hasNext();) {
			iter.next().accept(this);
		}
		Block finallyBlock= node.getFinally();
		if (finallyBlock != null) {
			finallyBlock.accept(this);
		}
	}
	return false;
}
 
Example #2
Source Project: SimFix   Author: xgdsmileboy   File: NodeUtils.java    License: GNU General Public License v2.0 6 votes vote down vote up
public boolean visit(VariableDeclarationExpression node) {
	ASTNode parent = node.getParent();
	while(parent != null){
		if(parent instanceof Block || parent instanceof ForStatement){
			break;
		}
		parent = parent.getParent();
	}
	if(parent != null) {
		int start = _unit.getLineNumber(node.getStartPosition());
		int end = _unit.getLineNumber(parent.getStartPosition() + parent.getLength());
		for (Object o : node.fragments()) {
			VariableDeclarationFragment vdf = (VariableDeclarationFragment) o;
			Pair<String, Type> pair = new Pair<String, Type>(vdf.getName().getFullyQualifiedName(), node.getType());
			Pair<Integer, Integer> range = new Pair<Integer, Integer>(start, end);
			_tmpVars.put(pair, range);
		}
	}
	return true;
}
 
Example #3
Source Project: SparkBuilderGenerator   Author: helospark   File: RegularBuilderWithMethodAdderFragment.java    License: MIT License 6 votes vote down vote up
private Block createWithMethodBody(AST ast, String originalFieldName, String builderFieldName) {
    Block newBlock = ast.newBlock();
    ReturnStatement builderReturnStatement = ast.newReturnStatement();
    builderReturnStatement.setExpression(ast.newThisExpression());

    Assignment newAssignment = ast.newAssignment();

    FieldAccess fieldAccess = ast.newFieldAccess();
    fieldAccess.setExpression(ast.newThisExpression());
    fieldAccess.setName(ast.newSimpleName(originalFieldName));
    newAssignment.setLeftHandSide(fieldAccess);
    newAssignment.setRightHandSide(ast.newSimpleName(builderFieldName));

    newBlock.statements().add(ast.newExpressionStatement(newAssignment));
    newBlock.statements().add(builderReturnStatement);
    return newBlock;
}
 
Example #4
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: ExtractTempRefactoring.java    License: Eclipse Public License 1.0 6 votes vote down vote up
private void createAndInsertTempDeclaration() throws CoreException {
	Expression initializer= getSelectedExpression().createCopyTarget(fCURewrite.getASTRewrite(), true);
	VariableDeclarationStatement vds= createTempDeclaration(initializer);

	if ((!fReplaceAllOccurrences) || (retainOnlyReplacableMatches(getMatchingFragments()).length <= 1)) {
		insertAt(getSelectedExpression().getAssociatedNode(), vds);
		return;
	}

	ASTNode[] firstReplaceNodeParents= getParents(getFirstReplacedExpression().getAssociatedNode());
	ASTNode[] commonPath= findDeepestCommonSuperNodePathForReplacedNodes();
	Assert.isTrue(commonPath.length <= firstReplaceNodeParents.length);

	ASTNode deepestCommonParent= firstReplaceNodeParents[commonPath.length - 1];
	if (deepestCommonParent instanceof Block)
		insertAt(firstReplaceNodeParents[commonPath.length], vds);
	else
		insertAt(deepestCommonParent, vds);
}
 
Example #5
Source Project: txtUML   Author: ELTE-Soft   File: SequenceDiagramVisitor.java    License: Eclipse Public License 1.0 6 votes vote down vote up
private void checkSendInIfNode(IfStatement ifNode) {
	boolean showErrorHere = placeOfError == ifNode;
	Statement thenStatement = ifNode.getThenStatement();
	if (showErrorHere) {
		placeOfError = thenStatement;
	}
	if (thenStatement instanceof Block) {
		checkSendInBlock((Block) thenStatement, showErrorHere);
	} else {
		checkSendInStatement(thenStatement);
	}
	Statement elseStatement = ifNode.getElseStatement();
	if (showErrorHere) {
		placeOfError = elseStatement;
	}
	if (elseStatement == null) {
		return;
	}
	if (elseStatement instanceof IfStatement) {
		checkSendInIfNode((IfStatement) elseStatement);
	} else if (elseStatement instanceof Block) {
		checkSendInBlock((Block) elseStatement, showErrorHere);
	} else {
		checkSendInStatement(elseStatement);
	}
}
 
Example #6
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: ControlStatementsFix.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel model) throws CoreException {
	ASTRewrite rewrite= cuRewrite.getASTRewrite();
	String label;
	if (fBodyProperty == IfStatement.THEN_STATEMENT_PROPERTY) {
		label = FixMessages.CodeStyleFix_ChangeIfToBlock_desription;
	} else if (fBodyProperty == IfStatement.ELSE_STATEMENT_PROPERTY) {
		label = FixMessages.CodeStyleFix_ChangeElseToBlock_description;
	} else {
		label = FixMessages.CodeStyleFix_ChangeControlToBlock_description;
	}

	TextEditGroup group= createTextEditGroup(label, cuRewrite);
	ASTNode moveTarget= rewrite.createMoveTarget(fBody);
	Block replacingBody= cuRewrite.getRoot().getAST().newBlock();
	replacingBody.statements().add(moveTarget);
	rewrite.set(fControlStatement, fBodyProperty, replacingBody, group);
}
 
Example #7
Source Project: JDeodorant   Author: tsantalis   File: TypeCheckingEvolution.java    License: MIT License 6 votes vote down vote up
private List<TypeCheckElimination> generateTypeCheckEliminationsWithinTypeDeclaration(TypeDeclaration typeDeclaration, TypeCheckElimination originalTypeCheckElimination) {
	List<TypeCheckElimination> typeCheckEliminations = new ArrayList<TypeCheckElimination>();
	for(MethodDeclaration method : typeDeclaration.getMethods()) {
		Block methodBody = method.getBody();
		if(methodBody != null) {
			List<TypeCheckElimination> list = generateTypeCheckEliminationsWithinMethodBody(methodBody);
			for(TypeCheckElimination typeCheckElimination : list) {
				if(!typeCheckElimination.allTypeCheckBranchesAreEmpty()) {
					TypeCheckCodeFragmentAnalyzer analyzer = new TypeCheckCodeFragmentAnalyzer(typeCheckElimination, typeDeclaration, method, null);
					if((typeCheckElimination.getTypeField() != null || typeCheckElimination.getTypeLocalVariable() != null || typeCheckElimination.getTypeMethodInvocation() != null) &&
							typeCheckElimination.allTypeCheckingsContainStaticFieldOrSubclassType() && typeCheckElimination.isApplicable()) {
						if(originalTypeCheckElimination.matchingStatesOrSubTypes(typeCheckElimination))
							typeCheckEliminations.add(typeCheckElimination);
					}
				}
			}
		}
	}
	return typeCheckEliminations;
}
 
Example #8
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: VariableDeclarationFix.java    License: Eclipse Public License 1.0 6 votes vote down vote up
private MethodDeclaration getWritingConstructor(SimpleName name) {
Assignment assignement= (Assignment)ASTNodes.getParent(name, Assignment.class);
if (assignement == null)
	return null;

ASTNode expression= assignement.getParent();
if (!(expression instanceof ExpressionStatement))
	return null;

ASTNode block= expression.getParent();
if (!(block instanceof Block))
	return null;

ASTNode methodDeclaration= block.getParent();
if (!(methodDeclaration instanceof MethodDeclaration))
	return null;

      return (MethodDeclaration)methodDeclaration;
     }
 
Example #9
Source Project: JDeodorant   Author: tsantalis   File: ExtractMethodFragmentRefactoring.java    License: MIT License 6 votes vote down vote up
protected ListRewrite createTryStatementIfNeeded(ASTRewrite sourceRewriter, AST ast, ListRewrite bodyRewrite, PDGNode node) {
	Statement statement = node.getASTStatement();
	ASTNode statementParent = statement.getParent();
	if(statementParent != null && statementParent instanceof Block)
		statementParent = statementParent.getParent();
	if(statementParent != null && statementParent instanceof TryStatement) {
		TryStatement tryStatementParent = (TryStatement)statementParent;
		if(tryStatementsToBeRemoved.contains(tryStatementParent) || tryStatementsToBeCopied.contains(tryStatementParent)) {
			if(tryStatementBodyRewriteMap.containsKey(tryStatementParent)) {
				bodyRewrite = tryStatementBodyRewriteMap.get(tryStatementParent);
			}
			else {
				TryStatement newTryStatement = copyTryStatement(sourceRewriter, ast, tryStatementParent);
				Block tryMethodBody = ast.newBlock();
				sourceRewriter.set(newTryStatement, TryStatement.BODY_PROPERTY, tryMethodBody, null);
				ListRewrite tryBodyRewrite = sourceRewriter.getListRewrite(tryMethodBody, Block.STATEMENTS_PROPERTY);
				tryStatementBodyRewriteMap.put(tryStatementParent, tryBodyRewrite);
				bodyRewrite.insertLast(newTryStatement, null);
				bodyRewrite = tryBodyRewrite;
			}
		}
	}
	return bodyRewrite;
}
 
Example #10
private MethodDeclaration createGetOuterHelper() {
	String outerTypeName= fType.getDeclaringClass().getTypeDeclaration().getName();

	MethodDeclaration helperMethod= fAst.newMethodDeclaration();
	helperMethod.modifiers().addAll(ASTNodeFactory.newModifiers(fAst, Modifier.PRIVATE));
	helperMethod.setName(fAst.newSimpleName(METHODNAME_OUTER_TYPE));
	helperMethod.setConstructor(false);
	helperMethod.setReturnType2(fAst.newSimpleType(fAst.newSimpleName(outerTypeName)));

	Block body= fAst.newBlock();
	helperMethod.setBody(body);

	ThisExpression thisExpression= fAst.newThisExpression();
	thisExpression.setQualifier(fAst.newSimpleName(outerTypeName));

	ReturnStatement endReturn= fAst.newReturnStatement();
	endReturn.setExpression(thisExpression);
	body.statements().add(endReturn);

	return helperMethod;
}
 
Example #11
private static boolean isLastStatementInEnclosingMethodOrLambda(Statement statement) {
	ASTNode currentStructure= statement;
	ASTNode currentParent= statement.getParent();
	while (!(currentParent instanceof MethodDeclaration || currentParent instanceof LambdaExpression)) {
		// should not be in a loop
		if (currentParent instanceof ForStatement || currentParent instanceof EnhancedForStatement
				|| currentParent instanceof WhileStatement || currentParent instanceof DoStatement) {
			return false;
		}
		if (currentParent instanceof Block) {
			Block parentBlock= (Block) currentParent;
			if (parentBlock.statements().indexOf(currentStructure) != parentBlock.statements().size() - 1) { // not last statement in the block
				return false;
			}
		}
		currentStructure= currentParent;
		currentParent= currentParent.getParent();
	}
	return true;
}
 
Example #12
Source Project: JDeodorant   Author: tsantalis   File: ExpressionExtractor.java    License: MIT License 6 votes vote down vote up
private List<Expression> getExpressions(AnonymousClassDeclaration anonymousClassDeclaration) {
	List<Expression> expressionList = new ArrayList<Expression>();
	List<BodyDeclaration> bodyDeclarations = anonymousClassDeclaration.bodyDeclarations();
	for(BodyDeclaration bodyDeclaration : bodyDeclarations) {
		if(bodyDeclaration instanceof MethodDeclaration) {
			MethodDeclaration methodDeclaration = (MethodDeclaration)bodyDeclaration;
			Block body = methodDeclaration.getBody();
			if(body != null) {
				List<Statement> statements = body.statements();
				for(Statement statement : statements) {
					expressionList.addAll(getExpressions(statement));
				}
			}
		}
	}
	return expressionList;
}
 
Example #13
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: StatementRewrite.java    License: Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected void handleOneMany(ASTNode[] replacements, TextEditGroup description) {
	AST ast= fToReplace[0].getAST();
	// to replace == 1, but more than one replacement. Have to check if we
	// need to insert a block to not change structure
	if (ASTNodes.isControlStatementBody(fDescriptor)) {
		Block block= ast.newBlock();
		ListRewrite statements= fRewrite.getListRewrite(block, Block.STATEMENTS_PROPERTY);
		for (int i= 0; i < replacements.length; i++) {
			statements.insertLast(replacements[i], description);
		}
		fRewrite.replace(fToReplace[0], block, description);
	} else {
		ListRewrite container= fRewrite.getListRewrite(fToReplace[0].getParent(), (ChildListPropertyDescriptor)fDescriptor);
		container.replace(fToReplace[0], replacements[0], description);
		for (int i= 1; i < replacements.length; i++) {
			container.insertAfter(replacements[i], replacements[i - 1], description);
		}
	}
}
 
Example #14
Source Project: JDeodorant   Author: tsantalis   File: CloneInstanceMapper.java    License: MIT License 6 votes vote down vote up
private boolean isNestedUnderElse(ASTNode astNode) {
	if(astNode.getParent() instanceof IfStatement) {
		IfStatement ifParent = (IfStatement)astNode.getParent();
		if(ifParent.getElseStatement()!=null && ifParent.getElseStatement().equals(astNode))
			return true;
	}
	if(astNode.getParent() instanceof Block) {
		Block blockParent = (Block)astNode.getParent();
		if(blockParent.getParent() instanceof IfStatement) {
			IfStatement ifGrandParent = (IfStatement)blockParent.getParent();
			if(ifGrandParent.getElseStatement()!=null && ifGrandParent.getElseStatement().equals(blockParent))
				return true;
		}
	}
	return false;
}
 
Example #15
@Override
protected void addMemberCheckNull(Object member, boolean addSeparator) {
	IfStatement ifStatement= fAst.newIfStatement();
	ifStatement.setExpression(createInfixExpression(createMemberAccessExpression(member, true, true), Operator.NOT_EQUALS, fAst.newNullLiteral()));
	Block thenBlock= fAst.newBlock();
	flushTemporaryExpression();
	String[] arrayString= getContext().getTemplateParser().getBody();
	for (int i= 0; i < arrayString.length; i++) {
		addElement(processElement(arrayString[i], member), thenBlock);
	}
	if (addSeparator)
		addElement(getContext().getTemplateParser().getSeparator(), thenBlock);
	flushTemporaryExpression();

	if (thenBlock.statements().size() == 1 && !getContext().isForceBlocks()) {
		ifStatement.setThenStatement((Statement)ASTNode.copySubtree(fAst, (ASTNode)thenBlock.statements().get(0)));
	} else {
		ifStatement.setThenStatement(thenBlock);
	}
	toStringMethod.getBody().statements().add(ifStatement);
}
 
Example #16
Source Project: spotbugs   Author: spotbugs   File: CreateSuperCallResolution.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
protected void repairBug(ASTRewrite rewrite, CompilationUnit workingUnit, BugInstance bug) throws BugResolutionException {
    Assert.isNotNull(rewrite);
    Assert.isNotNull(workingUnit);
    Assert.isNotNull(bug);

    TypeDeclaration type = getTypeDeclaration(workingUnit, bug.getPrimaryClass());
    MethodDeclaration method = getMethodDeclaration(type, bug.getPrimaryMethod());

    AST ast = rewrite.getAST();

    SuperMethodInvocation superCall = createSuperMethodInvocation(rewrite, method);
    ExpressionStatement statement = ast.newExpressionStatement(superCall);
    Block methodBody = method.getBody();
    ListRewrite listRewrite = rewrite.getListRewrite(methodBody, Block.STATEMENTS_PROPERTY);
    if (isInsertFirst()) {
        listRewrite.insertFirst(statement, null);
    } else {
        listRewrite.insertLast(statement, null);
    }
}
 
Example #17
Source Project: spotbugs   Author: spotbugs   File: CreateDoPrivilegedBlockResolution.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
private MethodDeclaration createRunMethodDeclaration(ASTRewrite rewrite, ClassInstanceCreation classLoaderCreation) {
    AST ast = rewrite.getAST();

    MethodDeclaration methodDeclaration = ast.newMethodDeclaration();
    SimpleName methodName = ast.newSimpleName("run");
    Type returnType = (Type) rewrite.createCopyTarget(classLoaderCreation.getType());
    Block methodBody = createRunMethodBody(rewrite, classLoaderCreation);
    List<Modifier> modifiers = checkedList(methodDeclaration.modifiers());

    modifiers.add(ast.newModifier(PUBLIC_KEYWORD));
    methodDeclaration.setName(methodName);
    methodDeclaration.setReturnType2(returnType);
    methodDeclaration.setBody(methodBody);

    return methodDeclaration;
}
 
Example #18
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: ParameterObjectFactory.java    License: Eclipse Public License 1.0 5 votes vote down vote up
private MethodDeclaration createGetter(ParameterInfo pi, String declaringType, CompilationUnitRewrite cuRewrite) throws CoreException {
	AST ast= cuRewrite.getAST();
	ICompilationUnit cu= cuRewrite.getCu();
	IJavaProject project= cu.getJavaProject();

	MethodDeclaration methodDeclaration= ast.newMethodDeclaration();
	String fieldName= pi.getNewName();
	String getterName= getGetterName(pi, ast, project);
	String lineDelim= StubUtility.getLineDelimiterUsed(cu);
	String bareFieldname= NamingConventions.getBaseName(NamingConventions.VK_INSTANCE_FIELD, fieldName, project);
	if (createComments(project)) {
		String comment= CodeGeneration.getGetterComment(cu, declaringType, getterName, fieldName, pi.getNewTypeName(), bareFieldname, lineDelim);
		if (comment != null)
			methodDeclaration.setJavadoc((Javadoc) cuRewrite.getASTRewrite().createStringPlaceholder(comment, ASTNode.JAVADOC));
	}
	methodDeclaration.setName(ast.newSimpleName(getterName));
	methodDeclaration.setReturnType2(importBinding(pi.getNewTypeBinding(), cuRewrite));
	methodDeclaration.modifiers().add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD));
	Block block= ast.newBlock();
	methodDeclaration.setBody(block);
	boolean useThis= StubUtility.useThisForFieldAccess(project);
	if (useThis) {
		fieldName= "this." + fieldName; //$NON-NLS-1$
	}
	String bodyContent= CodeGeneration.getGetterMethodBodyContent(cu, declaringType, getterName, fieldName, lineDelim);
	ASTNode getterBody= cuRewrite.getASTRewrite().createStringPlaceholder(bodyContent, ASTNode.EXPRESSION_STATEMENT);
	block.statements().add(getterBody);
	return methodDeclaration;
}
 
Example #19
Source Project: JDeodorant   Author: tsantalis   File: ASTNodeDifference.java    License: MIT License 5 votes vote down vote up
private boolean isExpressionOfIfStatementNestedAtLevelZero() {
	if(expression1.getExpression().getParent() instanceof IfStatement &&
			expression2.getExpression().getParent() instanceof IfStatement) {
		IfStatement if1 = (IfStatement)expression1.getExpression().getParent();
		IfStatement if2 = (IfStatement)expression2.getExpression().getParent();
		boolean noElsePart = if1.getElseStatement() == null && if2.getElseStatement() == null;
		ASTNode parent1 = if1.getParent();
		while(parent1 instanceof Block) {
			parent1 = parent1.getParent();
		}
		ASTNode parent2 = if2.getParent();
		while(parent2 instanceof Block) {
			parent2 = parent2.getParent();
		}
		if(parent1 instanceof MethodDeclaration && parent2 instanceof MethodDeclaration) {
			return noElsePart;
		}
		if(parent1 instanceof TryStatement && parent2 instanceof TryStatement) {
			TryStatement try1 = (TryStatement)parent1;
			TryStatement try2 = (TryStatement)parent2;
			parent1 = try1.getParent();
			while(parent1 instanceof Block) {
				parent1 = parent1.getParent();
			}
			parent2 = try2.getParent();
			while(parent2 instanceof Block) {
				parent2 = parent2.getParent();
			}
			if(parent1 instanceof MethodDeclaration && parent2 instanceof MethodDeclaration) {
				return noElsePart;
			}
		}
	}
	return false;
}
 
Example #20
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: StringBuilderGenerator.java    License: Eclipse Public License 1.0 5 votes vote down vote up
protected void addElement(Object element, Block block) {
	if (element instanceof String)
		fBuffer.append((String)element);
	if (element instanceof Expression) {
		flushBuffer(block);
		block.statements().add(fAst.newExpressionStatement(createMethodInvocation(fBuilderVariableName, APPEND_METHOD_NAME, (Expression)element)));
	}
}
 
Example #21
private void handleResourceDeclarations(TryStatement tryStatement) {
	List<VariableDeclarationExpression> resources= tryStatement.resources();
	for (Iterator<VariableDeclarationExpression> iterator= resources.iterator(); iterator.hasNext();) {
		iterator.next().accept(this);
	}

	//check if the exception is thrown as a result of resource#close()
	boolean exitMarked= false;
	for (VariableDeclarationExpression variable : resources) {
		Type type= variable.getType();
		IMethodBinding methodBinding= Bindings.findMethodInHierarchy(type.resolveBinding(), "close", new ITypeBinding[0]); //$NON-NLS-1$
		if (methodBinding != null) {
			ITypeBinding[] exceptionTypes= methodBinding.getExceptionTypes();
			for (int j= 0; j < exceptionTypes.length; j++) {
				if (matches(exceptionTypes[j])) { // a close() throws the caught exception
					// mark name of resource
					for (VariableDeclarationFragment fragment : (List<VariableDeclarationFragment>) variable.fragments()) {
						SimpleName name= fragment.getName();
						fResult.add(new OccurrenceLocation(name.getStartPosition(), name.getLength(), 0, fDescription));
					}
					if (!exitMarked) {
						// mark exit position
						exitMarked= true;
						Block body= tryStatement.getBody();
						int offset= body.getStartPosition() + body.getLength() - 1; // closing bracket of try block
						fResult.add(new OccurrenceLocation(offset, 1, 0, Messages.format(SearchMessages.ExceptionOccurrencesFinder_occurrence_implicit_close_description,
								BasicElementLabels.getJavaElementName(fException.getName()))));
					}
				}
			}
		}
	}
}
 
Example #22
Source Project: JDeodorant   Author: tsantalis   File: ASTNodeMatcher.java    License: MIT License 5 votes vote down vote up
public boolean match(Block node, Object other) {
	if (!(other instanceof Block)) {
		return false;
	}
	Block o = (Block)other;
	if(isNestedUnderAnonymousClassDeclaration(node) && isNestedUnderAnonymousClassDeclaration(o)) {
		return super.match(node, o);
	}
	return true;
}
 
Example #23
Source Project: SimFix   Author: xgdsmileboy   File: CodeBlock.java    License: GNU General Public License v2.0 5 votes vote down vote up
private Blk visit(Block node) {
	int startLine = _cunit.getLineNumber(node.getStartPosition());
	int endLine  = _cunit.getLineNumber(node.getStartPosition() + node.getLength());
	Blk blk = new Blk(startLine, endLine, node);
	List<Stmt> stmts = new ArrayList<>();
	for(Object object : node.statements()){
		Stmt stmt = (Stmt) process((ASTNode) object);
		stmt.setParent(blk);
		stmts.add(stmt);
	}
	blk.setStatement(stmts);
	return blk;
}
 
Example #24
Source Project: SparkBuilderGenerator   Author: helospark   File: BuildMethodBodyCreatorFragment.java    License: MIT License 5 votes vote down vote up
public Block createBody(AST ast, TypeDeclaration originalType) {
    ClassInstanceCreation newClassInstanceCreation = ast.newClassInstanceCreation();
    newClassInstanceCreation.setType(ast.newSimpleType(ast.newName(originalType.getName().toString())));
    newClassInstanceCreation.arguments().add(ast.newThisExpression());

    ReturnStatement statement = ast.newReturnStatement();
    statement.setExpression(newClassInstanceCreation);

    Block block = ast.newBlock();
    block.statements().add(statement);
    return block;
}
 
Example #25
Source Project: SparkBuilderGenerator   Author: helospark   File: StagedBuilderWithMethodAdderFragment.java    License: MIT License 5 votes vote down vote up
public void addWithMethodToBuilder(AST ast, TypeDeclaration stagedBuilderType,
        BuilderField builderField,
        StagedBuilderProperties nextStage) {
    Block newBlock = createWithMethodBody(ast, builderField);
    MethodDeclaration newWithMethod = stagedBuilderWithMethodDefiniationCreatorFragment.createNewWithMethod(ast,
            builderField, nextStage);
    newWithMethod.setBody(newBlock);
    markerAnnotationAttacher.attachAnnotation(ast, newWithMethod, OVERRIDE_ANNOTATION);
    stagedBuilderType.bodyDeclarations().add(newWithMethod);
}
 
Example #26
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: PasteAction.java    License: Eclipse Public License 1.0 5 votes vote down vote up
public static List<ParsedCu> parseCus(IJavaProject javaProject, String compilerCompliance, String text) {
	ASTParser parser= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
	if (javaProject != null) {
		parser.setProject(javaProject);
	} else if (compilerCompliance != null) {
		Map<String, String> options= JavaCore.getOptions();
		JavaModelUtil.setComplianceOptions(options, compilerCompliance);
		parser.setCompilerOptions(options);
	}
	parser.setSource(text.toCharArray());
	parser.setStatementsRecovery(true);
	CompilationUnit unit= (CompilationUnit) parser.createAST(null);

	if (unit.types().size() > 0)
		return parseAsTypes(text, unit);

	parser.setProject(javaProject);
	parser.setSource(text.toCharArray());
	parser.setStatementsRecovery(true);
	parser.setKind(ASTParser.K_CLASS_BODY_DECLARATIONS);
	ASTNode root= parser.createAST(null);
	if (root instanceof TypeDeclaration) {
		List<BodyDeclaration> bodyDeclarations= ((TypeDeclaration) root).bodyDeclarations();
		if (bodyDeclarations.size() > 0)
			return Collections.singletonList(new ParsedCu(text, ASTParser.K_CLASS_BODY_DECLARATIONS, null, null));
	}

	parser.setProject(javaProject);
	parser.setSource(text.toCharArray());
	parser.setStatementsRecovery(true);
	parser.setKind(ASTParser.K_STATEMENTS);
	root= parser.createAST(null);
	if (root instanceof Block) {
		List<Statement> statements= ((Block) root).statements();
		if (statements.size() > 0)
			return Collections.singletonList(new ParsedCu(text, ASTParser.K_STATEMENTS, null, null));
	}

	return Collections.emptyList();
}
 
Example #27
Source Project: SparkBuilderGenerator   Author: helospark   File: RegularBuilderWithMethodAdderFragment.java    License: MIT License 5 votes vote down vote up
public void addWithMethodToBuilder(AST ast, TypeDeclaration newType,
        BuilderField builderField) {
    String originalFieldName = builderField.getOriginalFieldName();
    String builderFieldName = builderField.getBuilderFieldName();
    Block newBlock = createWithMethodBody(ast, originalFieldName, builderFieldName);
    SingleVariableDeclaration methodParameterDeclaration = withMethodParameterCreatorFragment.createWithMethodParameter(ast,
            builderField.getFieldType(), builderFieldName);
    MethodDeclaration newMethod = createNewWithMethod(ast, builderFieldName, newBlock, methodParameterDeclaration,
            newType, builderField);
    newType.bodyDeclarations().add(newMethod);
}
 
Example #28
public static RearrangeStrategy create(Statement origStmt, ASTRewrite rewrite, TextEditGroup group) {
	ASTNode parent = origStmt.getParent();
	if (parent instanceof Block) {
		Block block= (Block)parent;
		if (origStmt instanceof VariableDeclarationStatement)
			return new ModifyBlockWithLocalDecl(origStmt, block, rewrite, group);
		else
			return new ModifyBlock(origStmt, block, rewrite, group);
	} else {
		return new ReplaceStatement(origStmt, rewrite, group);
	}
}
 
Example #29
Source Project: JDeodorant   Author: tsantalis   File: CloneInstanceMapper.java    License: MIT License 5 votes vote down vote up
private boolean isFinallyBlockOfTryStatement(ASTNode node) {
	ASTNode parent = node.getParent();
	if(parent != null && parent instanceof TryStatement) {
		TryStatement tryStatement = (TryStatement)parent;
		Block finallyBlock = tryStatement.getFinally();
		if(node instanceof Block && finallyBlock != null) {
			return finallyBlock.equals((Block)node);
		}
	}
	return false;
}
 
Example #30
Source Project: SparkBuilderGenerator   Author: helospark   File: SuperFieldSetterMethodAdderFragment.java    License: MIT License 5 votes vote down vote up
public void populateBodyWithSuperSetterCalls(AST ast, String builderName, Block body, List<SuperSetterBasedBuilderField> builderFields) {
    for (SuperSetterBasedBuilderField field : builderFields) {
        FieldAccess builderFieldAccess = builderFieldAccessCreatorFragment.createBuilderFieldAccess(ast, builderName, field);

        SuperMethodInvocation superInvocation = ast.newSuperMethodInvocation();
        superInvocation.setName(ast.newSimpleName(field.getSetterName()));
        superInvocation.arguments().add(builderFieldAccess);

        body.statements().add(ast.newExpressionStatement(superInvocation));
    }
}