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 File: ExtractTempRefactoring.java    From Eclipse-Postfix-Code-Completion with 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 #2
Source File: NodeUtils.java    From SimFix with 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 File: CreateDoPrivilegedBlockResolution.java    From spotbugs with 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 #4
Source File: CreateSuperCallResolution.java    From spotbugs with 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 #5
Source File: StringBuilderChainGenerator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@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 #6
Source File: FlowAnalyzer.java    From Eclipse-Postfix-Code-Completion with 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 #7
Source File: RegularBuilderWithMethodAdderFragment.java    From SparkBuilderGenerator with 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 #8
Source File: SequenceDiagramVisitor.java    From txtUML with 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 #9
Source File: ControlStatementsFix.java    From Eclipse-Postfix-Code-Completion with 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 #10
Source File: CloneInstanceMapper.java    From JDeodorant with 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 #11
Source File: TypeCheckingEvolution.java    From JDeodorant with 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 #12
Source File: VariableDeclarationFix.java    From Eclipse-Postfix-Code-Completion with 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 #13
Source File: StatementRewrite.java    From Eclipse-Postfix-Code-Completion with 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 File: ExtractMethodFragmentRefactoring.java    From JDeodorant with 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 #15
Source File: GenerateHashCodeEqualsOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
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 #16
Source File: AdvancedQuickAssistProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
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 #17
Source File: ExpressionExtractor.java    From JDeodorant with 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 #18
Source File: TryStatementWriter.java    From juniversal with MIT License 5 votes vote down vote up
@Override
public void write(TryStatement tryStatement) {
    if (tryStatement.resources().size() > 0)
        writeTryWithResources(tryStatement);
    else {
        matchAndWrite("try");

        copySpaceAndComments();
        writeNode(tryStatement.getBody());

        forEach(tryStatement.catchClauses(), (CatchClause catchClause) -> {
            copySpaceAndComments();
            matchAndWrite("catch");

            copySpaceAndComments();
            matchAndWrite("(");

            copySpaceAndComments();
            writeNode(catchClause.getException());

            copySpaceAndComments();
            matchAndWrite(")");

            copySpaceAndComments();
            writeNode(catchClause.getBody());
        });

        @Nullable Block finallyBlock = tryStatement.getFinally();
        if (finallyBlock != null) {
            copySpaceAndComments();
            matchAndWrite("finally");

            copySpaceAndComments();
            writeNode(finallyBlock);
        }
    }
}
 
Example #19
Source File: JavaASTFlattener.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public boolean visit(final TryStatement node) {
  this.appendToBuffer("try ");
  final List<ASTNode> resources = this._aSTFlattenerUtils.genericChildListProperty(node, "resources");
  boolean _isNullOrEmpty = IterableExtensions.isNullOrEmpty(resources);
  boolean _not = (!_isNullOrEmpty);
  if (_not) {
    this.appendToBuffer("(");
    for (final ASTNode child : resources) {
      child.accept(this);
    }
    this.appendToBuffer(")");
    this.addProblem(node, "Try with resource is not yet supported.");
  }
  node.getBody().accept(this);
  final Consumer<Object> _function = (Object it) -> {
    ((ASTNode) it).accept(this);
  };
  node.catchClauses().forEach(_function);
  Block _finally = node.getFinally();
  boolean _tripleNotEquals = (_finally != null);
  if (_tripleNotEquals) {
    this.appendToBuffer(" finally ");
    node.getFinally().accept(this);
  } else {
    this.appendLineWrapToBuffer();
  }
  return false;
}
 
Example #20
Source File: SequenceDiagramVisitor.java    From txtUML with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns true if there is a send or a fragment in the method body, which
 * was invoked
 */
private boolean checkSendOrFragmentInMethodInvocation(MethodInvocation methodInvocation) {
	if (Utils.isSendInvocation(methodInvocation)) {
		return true;
	}
	Block body = Utils.getMethodBodyFromInvocation(methodInvocation);
	if (body == null) {
		return false;
	}
	return checkSendOrFragmentInBlock(body);
}
 
Example #21
Source File: FlowAnalyzer.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void endVisit(Block node) {
	if (skipNode(node)) {
		return;
	}
	BlockFlowInfo info = createBlock();
	setFlowInfo(node, info);
	process(info, node.statements());
}
 
Example #22
Source File: ASTFlattenerUtils.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
private ASTNode findDeclarationBlocks(final ASTNode simpleName) {
  ASTNode block = this.<Block>findParentOfType(simpleName, Block.class);
  if ((block == null)) {
    block = this.<MethodDeclaration>findParentOfType(simpleName, MethodDeclaration.class);
  }
  if ((block == null)) {
    block = this.<TypeDeclaration>findParentOfType(simpleName, TypeDeclaration.class);
  }
  return block;
}
 
Example #23
Source File: SelfEncapsulateFieldRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private MethodDeclaration createGetterMethod(AST ast, ASTRewrite rewriter, String lineDelimiter) throws CoreException {
	FieldDeclaration field= (FieldDeclaration)ASTNodes.getParent(fFieldDeclaration, FieldDeclaration.class);
	Type type= field.getType();
	MethodDeclaration result= ast.newMethodDeclaration();
	result.setName(ast.newSimpleName(fGetterName));
	result.modifiers().addAll(ASTNodeFactory.newModifiers(ast, createModifiers()));
	Type returnType= DimensionRewrite.copyTypeAndAddDimensions(type, fFieldDeclaration.extraDimensions(), rewriter);
	result.setReturnType2(returnType);

	Block block= ast.newBlock();
	result.setBody(block);

	String body= CodeGeneration.getGetterMethodBodyContent(fField.getCompilationUnit(), getTypeName(field.getParent()), fGetterName, fField.getElementName(), lineDelimiter);
	if (body != null) {
		ASTNode getterNode= rewriter.createStringPlaceholder(body, ASTNode.BLOCK);
    	block.statements().add(getterNode);
	} else {
		ReturnStatement rs= ast.newReturnStatement();
		rs.setExpression(ast.newSimpleName(fField.getElementName()));
		block.statements().add(rs);
	}
    if (fGenerateJavadoc) {
		String string= CodeGeneration.getGetterComment(
			fField.getCompilationUnit() , getTypeName(field.getParent()), fGetterName,
			fField.getElementName(), ASTNodes.asString(type),
			StubUtility.getBaseName(fField),
			lineDelimiter);
		if (string != null) {
			Javadoc javadoc= (Javadoc)fRewriter.createStringPlaceholder(string, ASTNode.JAVADOC);
			result.setJavadoc(javadoc);
		}
	}
	return result;
}
 
Example #24
Source File: QuickAssistProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static boolean getExtractMethodProposal(IInvocationContext context, ASTNode coveringNode, boolean problemsAtLocation, Collection<ICommandAccess> proposals) throws CoreException {
	if (!(coveringNode instanceof Expression) && !(coveringNode instanceof Statement) && !(coveringNode instanceof Block)) {
		return false;
	}
	if (coveringNode instanceof Block) {
		List<Statement> statements= ((Block) coveringNode).statements();
		int startIndex= getIndex(context.getSelectionOffset(), statements);
		if (startIndex == -1)
			return false;
		int endIndex= getIndex(context.getSelectionOffset() + context.getSelectionLength(), statements);
		if (endIndex == -1 || endIndex <= startIndex)
			return false;
	}

	if (proposals == null) {
		return true;
	}

	final ICompilationUnit cu= context.getCompilationUnit();
	final ExtractMethodRefactoring extractMethodRefactoring= new ExtractMethodRefactoring(context.getASTRoot(), context.getSelectionOffset(), context.getSelectionLength());
	extractMethodRefactoring.setMethodName("extracted"); //$NON-NLS-1$
	if (extractMethodRefactoring.checkInitialConditions(new NullProgressMonitor()).isOK()) {
		String label= CorrectionMessages.QuickAssistProcessor_extractmethod_description;
		LinkedProposalModel linkedProposalModel= new LinkedProposalModel();
		extractMethodRefactoring.setLinkedProposalModel(linkedProposalModel);

		Image image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PUBLIC);
		int relevance= problemsAtLocation ? IProposalRelevance.EXTRACT_METHOD_ERROR : IProposalRelevance.EXTRACT_METHOD;
		RefactoringCorrectionProposal proposal= new RefactoringCorrectionProposal(label, cu, extractMethodRefactoring, relevance, image);
		proposal.setCommandId(EXTRACT_METHOD_INPLACE_ID);
		proposal.setLinkedProposalModel(linkedProposalModel);
		proposals.add(proposal);
	}
	return true;
}
 
Example #25
Source File: ASTNodeSearchUtil.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public static Initializer getInitializerNode(IInitializer initializer, CompilationUnit cuNode) throws JavaModelException {
	ASTNode node= findNode(initializer.getSourceRange(), cuNode);
	if (node instanceof Initializer) {
		return (Initializer) node;
	}
	if (node instanceof Block && node.getParent() instanceof Initializer) {
		return (Initializer) node.getParent();
	}
	return null;
}
 
Example #26
Source File: ASTFlattenerUtils.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
public Iterable<Expression> findAssignmentsInBlock(final Block scope, final VariableDeclaration varDecl) {
  final Function1<Expression, Boolean> _function = (Expression it) -> {
    Expression name = null;
    boolean _matched = false;
    if (it instanceof Assignment) {
      _matched=true;
      name = ((Assignment)it).getLeftHandSide();
    }
    if (!_matched) {
      if (it instanceof PrefixExpression) {
        _matched=true;
        name = ((PrefixExpression)it).getOperand();
      }
    }
    if (!_matched) {
      if (it instanceof PostfixExpression) {
        _matched=true;
        name = ((PostfixExpression)it).getOperand();
      }
    }
    if ((name instanceof Name)) {
      final IBinding binding = ((Name)name).resolveBinding();
      if ((binding instanceof IVariableBinding)) {
        final IVariableBinding declBinding = varDecl.resolveBinding();
        return Boolean.valueOf((varDecl.getName().getIdentifier().equals(this.toSimpleName(((Name)name))) && ((IVariableBinding)binding).equals(declBinding)));
      }
    }
    return Boolean.valueOf(false);
  };
  return this.findAssignmentsInBlock(scope, _function);
}
 
Example #27
Source File: ExtractTempRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void insertAt(ASTNode target, Statement declaration) {
	ASTRewrite rewrite= fCURewrite.getASTRewrite();
	TextEditGroup groupDescription= fCURewrite.createGroupDescription(RefactoringCoreMessages.ExtractTempRefactoring_declare_local_variable);

	ASTNode parent= target.getParent();
	StructuralPropertyDescriptor locationInParent= target.getLocationInParent();
	while (locationInParent != Block.STATEMENTS_PROPERTY && locationInParent != SwitchStatement.STATEMENTS_PROPERTY) {
		if (locationInParent == IfStatement.THEN_STATEMENT_PROPERTY
				|| locationInParent == IfStatement.ELSE_STATEMENT_PROPERTY
				|| locationInParent == ForStatement.BODY_PROPERTY
				|| locationInParent == EnhancedForStatement.BODY_PROPERTY
				|| locationInParent == DoStatement.BODY_PROPERTY
				|| locationInParent == WhileStatement.BODY_PROPERTY) {
			// create intermediate block if target was the body property of a control statement:
			Block replacement= rewrite.getAST().newBlock();
			ListRewrite replacementRewrite= rewrite.getListRewrite(replacement, Block.STATEMENTS_PROPERTY);
			replacementRewrite.insertFirst(declaration, null);
			replacementRewrite.insertLast(rewrite.createMoveTarget(target), null);
			rewrite.replace(target, replacement, groupDescription);
			return;
		}
		target= parent;
		parent= parent.getParent();
		locationInParent= target.getLocationInParent();
	}
	ListRewrite listRewrite= rewrite.getListRewrite(parent, (ChildListPropertyDescriptor)locationInParent);
	listRewrite.insertBefore(declaration, target, groupDescription);
}
 
Example #28
Source File: QuickAssistProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static Block getBlockBodyForLambda(Expression bodyExpr, ITypeBinding returnTypeBinding, AST ast) {
	Statement statementInBlockBody;
	if (ast.resolveWellKnownType("void").isEqualTo(returnTypeBinding)) { //$NON-NLS-1$
		ExpressionStatement expressionStatement = ast.newExpressionStatement(bodyExpr);
		statementInBlockBody = expressionStatement;
	} else {
		ReturnStatement returnStatement = ast.newReturnStatement();
		returnStatement.setExpression(bodyExpr);
		statementInBlockBody = returnStatement;
	}
	Block blockBody = ast.newBlock();
	blockBody.statements().add(statementInBlockBody);
	return blockBody;
}
 
Example #29
Source File: ParameterObjectFactory.java    From Eclipse-Postfix-Code-Completion with 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 #30
Source File: CreateDoPrivilegedBlockResolution.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
private Block createRunMethodBody(ASTRewrite rewrite, ClassInstanceCreation classLoaderCreation) {
    AST ast = rewrite.getAST();

    Block methodBody = ast.newBlock();
    ReturnStatement returnStatement = ast.newReturnStatement();
    List<Statement> statements = checkedList(methodBody.statements());

    statements.add(returnStatement);
    returnStatement.setExpression((ClassInstanceCreation) rewrite.createCopyTarget(classLoaderCreation));

    return methodBody;
}