org.eclipse.jdt.core.dom.rewrite.ListRewrite Java Examples

The following examples show how to use org.eclipse.jdt.core.dom.rewrite.ListRewrite. 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: LocalCorrectionsSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
public static void addCasesOmittedProposals(IInvocationContext context, IProblemLocationCore problem, Collection<ChangeCorrectionProposal> proposals) {
	ASTNode selectedNode = problem.getCoveringNode(context.getASTRoot());
	if (selectedNode instanceof Expression && selectedNode.getLocationInParent() == SwitchStatement.EXPRESSION_PROPERTY) {
		AST ast = selectedNode.getAST();
		SwitchStatement parent = (SwitchStatement) selectedNode.getParent();

		for (Statement statement : (List<Statement>) parent.statements()) {
			if (statement instanceof SwitchCase && ((SwitchCase) statement).isDefault()) {

				// insert //$CASES-OMITTED$:
				ASTRewrite rewrite = ASTRewrite.create(ast);
				rewrite.setTargetSourceRangeComputer(new NoCommentSourceRangeComputer());
				ListRewrite listRewrite = rewrite.getListRewrite(parent, SwitchStatement.STATEMENTS_PROPERTY);
				ASTNode casesOmittedComment = rewrite.createStringPlaceholder("//$CASES-OMITTED$", ASTNode.EMPTY_STATEMENT); //$NON-NLS-1$
				listRewrite.insertBefore(casesOmittedComment, statement, null);

				String label = CorrectionMessages.LocalCorrectionsSubProcessor_insert_cases_omitted;
				ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, CodeActionKind.QuickFix, context.getCompilationUnit(), rewrite, IProposalRelevance.INSERT_CASES_OMITTED);
				proposals.add(proposal);
				break;
			}
		}
	}
}
 
Example #2
Source File: StagedBuilderCreationWithMethodAdder.java    From SparkBuilderGenerator with MIT License 6 votes vote down vote up
public void addBuilderMethodToCompilationUnit(CompilationUnitModificationDomain modificationDomain, TypeDeclaration builderType,
        StagedBuilderProperties currentStage) {
    AST ast = modificationDomain.getAst();
    ListRewrite listRewrite = modificationDomain.getListRewrite();
    BuilderField firstField = currentStage.getNamedVariableDeclarationField().get(0);

    StagedBuilderProperties nextStage = currentStage.getNextStage().orElse(currentStage);
    MethodDeclaration staticWithMethod = stagedBuilderWithMethodDefiniationCreatorFragment.createNewWithMethod(ast, firstField, nextStage);
    staticWithMethod.modifiers().add(ast.newModifier(ModifierKeyword.STATIC_KEYWORD));

    String parameterName = firstField.getBuilderFieldName();
    String withMethodName = staticWithMethod.getName().toString();
    Block block = newBuilderAndWithMethodCallCreationFragment.createReturnBlock(ast, builderType, withMethodName, parameterName);

    javadocAdder.addJavadocForWithBuilderMethod(ast, builderType.getName().toString(), parameterName, staticWithMethod);

    staticWithMethod.setBody(block);

    listRewrite.insertLast(staticWithMethod, null);
}
 
Example #3
Source File: ASTUtil.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
private static void addImports(ListRewrite importRewrite, Comparator<? super ImportDeclaration> comparator,
        Iterator<ImportDeclaration> newImports) {
    try {
        ImportDeclaration newImport = newImports.next();
        List<?> imports = importRewrite.getRewrittenList();
        for (Object importObj : imports) {
            ImportDeclaration anImport = (ImportDeclaration) importObj;
            int comp = comparator.compare(newImport, anImport);
            if (comp > 0) {
                continue;
            }
            if (comp < 0) {
                importRewrite.insertBefore(newImport, anImport, null);
            }
            newImport = newImports.next();
        }
        importRewrite.insertLast(newImport, null);
        while (newImports.hasNext()) {
            importRewrite.insertLast(newImports.next(), null);
        }
    } catch (NoSuchElementException e) {
        // do nothing
    }
}
 
Example #4
Source File: AbstractCreateMethodProposal.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected ASTRewrite getRewrite() {
  CompilationUnit targetAstRoot = ASTResolving.createQuickFixAST(
      getCompilationUnit(), null);
  createImportRewrite(targetAstRoot);

  // Find the target type declaration
  TypeDeclaration typeDecl = JavaASTUtils.findTypeDeclaration(targetAstRoot,
      targetQualifiedTypeName);
  if (typeDecl == null) {
    return null;
  }

  ASTRewrite rewrite = ASTRewrite.create(targetAstRoot.getAST());

  // Generate the new method declaration
  MethodDeclaration methodDecl = createMethodDeclaration(rewrite.getAST());

  // Add the new method declaration to the interface
  ChildListPropertyDescriptor property = ASTNodes.getBodyDeclarationsProperty(typeDecl);
  ListRewrite listRewriter = rewrite.getListRewrite(typeDecl, property);
  listRewriter.insertLast(methodDecl, null);

  return rewrite;
}
 
Example #5
Source File: QuickAssistProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static ASTNode getCopyOfInner(ASTRewrite rewrite, ASTNode statement, boolean toControlStatementBody) {
	if (statement.getNodeType() == ASTNode.BLOCK) {
		Block block= (Block) statement;
		List<Statement> innerStatements= block.statements();
		int nStatements= innerStatements.size();
		if (nStatements == 1) {
			return rewrite.createCopyTarget(innerStatements.get(0));
		} else if (nStatements > 1) {
			if (toControlStatementBody) {
				return rewrite.createCopyTarget(block);
			}
			ListRewrite listRewrite= rewrite.getListRewrite(block, Block.STATEMENTS_PROPERTY);
			ASTNode first= innerStatements.get(0);
			ASTNode last= innerStatements.get(nStatements - 1);
			return listRewrite.createCopyTarget(first, last);
		}
		return null;
	} else {
		return rewrite.createCopyTarget(statement);
	}
}
 
Example #6
Source File: MoveMethodRefactoring.java    From JDeodorant with MIT License 6 votes vote down vote up
private SimpleName addSourceClassParameterToMovedMethod(MethodDeclaration newMethodDeclaration, ASTRewrite targetRewriter) {
	AST ast = newMethodDeclaration.getAST();
	SingleVariableDeclaration parameter = ast.newSingleVariableDeclaration();
	SimpleName typeName = ast.newSimpleName(sourceTypeDeclaration.getName().getIdentifier());
	Type parameterType = ast.newSimpleType(typeName);
	targetRewriter.set(parameter, SingleVariableDeclaration.TYPE_PROPERTY, parameterType, null);
	String sourceTypeName = sourceTypeDeclaration.getName().getIdentifier();
	SimpleName parameterName = ast.newSimpleName(sourceTypeName.replaceFirst(Character.toString(sourceTypeName.charAt(0)), Character.toString(Character.toLowerCase(sourceTypeName.charAt(0)))));
	targetRewriter.set(parameter, SingleVariableDeclaration.NAME_PROPERTY, parameterName, null);
	ListRewrite parametersRewrite = targetRewriter.getListRewrite(newMethodDeclaration, MethodDeclaration.PARAMETERS_PROPERTY);
	parametersRewrite.insertLast(parameter, null);
	this.additionalArgumentsAddedToMovedMethod.add("this");
	this.additionalTypeBindingsToBeImportedInTargetClass.add(sourceTypeDeclaration.resolveBinding());
	addParamTagElementToJavadoc(newMethodDeclaration, targetRewriter, parameterName.getIdentifier());
	setPublicModifierToSourceTypeDeclaration();
	return parameterName;
}
 
Example #7
Source File: TypeParametersFix.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 {
	TextEditGroup group= createTextEditGroup(FixMessages.TypeParametersFix_insert_inferred_type_arguments_description, cuRewrite);

	ASTRewrite rewrite= cuRewrite.getASTRewrite();
	ImportRewrite importRewrite= cuRewrite.getImportRewrite();
	AST ast= cuRewrite.getRoot().getAST();

	for (int i= 0; i < fCreatedTypes.length; i++) {
		ParameterizedType createdType= fCreatedTypes[i];

		ITypeBinding[] typeArguments= createdType.resolveBinding().getTypeArguments();
		ContextSensitiveImportRewriteContext importContext= new ContextSensitiveImportRewriteContext(cuRewrite.getRoot(), createdType.getStartPosition(), importRewrite);

		ListRewrite argumentsRewrite= rewrite.getListRewrite(createdType, ParameterizedType.TYPE_ARGUMENTS_PROPERTY);
		for (int j= 0; j < typeArguments.length; j++) {
			ITypeBinding typeArgument= typeArguments[j];
			Type argumentNode= importRewrite.addImport(typeArgument, ast, importContext);
			argumentsRewrite.insertLast(argumentNode, group);
		}
	}
}
 
Example #8
Source File: MoveInnerToTopRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void addEnclosingInstanceTypeParameters(final ITypeBinding[] parameters, final AbstractTypeDeclaration declaration, final ASTRewrite rewrite) {
	Assert.isNotNull(parameters);
	Assert.isNotNull(declaration);
	Assert.isNotNull(rewrite);
	if (declaration instanceof TypeDeclaration) {
		final TypeDeclaration type= (TypeDeclaration) declaration;
		final List<TypeParameter> existing= type.typeParameters();
		final Set<String> names= new HashSet<String>();
		TypeParameter parameter= null;
		for (final Iterator<TypeParameter> iterator= existing.iterator(); iterator.hasNext();) {
			parameter= iterator.next();
			names.add(parameter.getName().getIdentifier());
		}
		final ListRewrite rewriter= rewrite.getListRewrite(type, TypeDeclaration.TYPE_PARAMETERS_PROPERTY);
		String name= null;
		for (int index= 0; index < parameters.length; index++) {
			name= parameters[index].getName();
			if (!names.contains(name)) {
				parameter= type.getAST().newTypeParameter();
				parameter.setName(type.getAST().newSimpleName(name));
				rewriter.insertLast(parameter, null);
			}
		}
	}
}
 
Example #9
Source File: MoveMethodRefactoring.java    From JDeodorant with MIT License 6 votes vote down vote up
private void removeSourceMethod() {
	ASTRewrite sourceRewriter = ASTRewrite.create(sourceCompilationUnit.getAST());
	ListRewrite classBodyRewrite = sourceRewriter.getListRewrite(sourceTypeDeclaration, TypeDeclaration.BODY_DECLARATIONS_PROPERTY);
	classBodyRewrite.remove(sourceMethod, null);
	Set<MethodDeclaration> methodsToBeMoved = new LinkedHashSet<MethodDeclaration>(additionalMethodsToBeMoved.values());
	for(MethodDeclaration methodDeclaration : methodsToBeMoved) {
		classBodyRewrite.remove(methodDeclaration, null);
	}
	try {
		TextEdit sourceEdit = sourceRewriter.rewriteAST();
		sourceMultiTextEdit.addChild(sourceEdit);
		sourceCompilationUnitChange.addTextEditGroup(new TextEditGroup("Remove moved method", new TextEdit[] {sourceEdit}));
	}
	catch(JavaModelException javaModelException) {
		javaModelException.printStackTrace();
	}
}
 
Example #10
Source File: MoveMethodRefactoring.java    From JDeodorant with MIT License 6 votes vote down vote up
private void addParameterToMovedMethod(MethodDeclaration newMethodDeclaration, SimpleName fieldName, ASTRewrite targetRewriter) {
	AST ast = newMethodDeclaration.getAST();
	SingleVariableDeclaration parameter = ast.newSingleVariableDeclaration();
	Type fieldType = null;
	FieldDeclaration[] fields = sourceTypeDeclaration.getFields();
	for(FieldDeclaration field : fields) {
		List<VariableDeclarationFragment> fragments = field.fragments();
		for(VariableDeclarationFragment fragment : fragments) {
			if(fragment.getName().getIdentifier().equals(fieldName.getIdentifier())) {
				fieldType = field.getType();
				break;
			}
		}
	}
	targetRewriter.set(parameter, SingleVariableDeclaration.TYPE_PROPERTY, fieldType, null);
	targetRewriter.set(parameter, SingleVariableDeclaration.NAME_PROPERTY, ast.newSimpleName(fieldName.getIdentifier()), null);
	ListRewrite parametersRewrite = targetRewriter.getListRewrite(newMethodDeclaration, MethodDeclaration.PARAMETERS_PROPERTY);
	parametersRewrite.insertLast(parameter, null);
	this.additionalArgumentsAddedToMovedMethod.add(fieldName.getIdentifier());
	this.additionalTypeBindingsToBeImportedInTargetClass.add(fieldType.resolveBinding());
	addParamTagElementToJavadoc(newMethodDeclaration, targetRewriter, fieldName.getIdentifier());
}
 
Example #11
Source File: JavadocTagsSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private void insertAllMissingTypeTags(ASTRewrite rewriter, TypeDeclaration typeDecl) {
	AST ast= typeDecl.getAST();
	Javadoc javadoc= typeDecl.getJavadoc();
	ListRewrite tagsRewriter= rewriter.getListRewrite(javadoc, Javadoc.TAGS_PROPERTY);

	List<TypeParameter> typeParams= typeDecl.typeParameters();
	for (int i= typeParams.size() - 1; i >= 0; i--) {
		TypeParameter decl= typeParams.get(i);
		String name= '<' + decl.getName().getIdentifier() + '>';
		if (findTag(javadoc, TagElement.TAG_PARAM, name) == null) {
			TagElement newTag= ast.newTagElement();
			newTag.setTagName(TagElement.TAG_PARAM);
			TextElement text= ast.newTextElement();
			text.setText(name);
			newTag.fragments().add(text);
			insertTabStop(rewriter, newTag.fragments(), "typeParam" + i); //$NON-NLS-1$
			insertTag(tagsRewriter, newTag, getPreviousTypeParamNames(typeParams, decl));
		}
	}
}
 
Example #12
Source File: ReorgPolicyFactory.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private void copyImportsToDestination(IImportContainer container, ASTRewrite rewrite, CompilationUnit sourceCuNode, CompilationUnit destinationCuNode) throws JavaModelException {
	ListRewrite listRewrite= rewrite.getListRewrite(destinationCuNode, CompilationUnit.IMPORTS_PROPERTY);

	IJavaElement[] importDeclarations= container.getChildren();
	for (int i= 0; i < importDeclarations.length; i++) {
		IImportDeclaration declaration= (IImportDeclaration) importDeclarations[i];

		ImportDeclaration sourceNode= ASTNodeSearchUtil.getImportDeclarationNode(declaration, sourceCuNode);
		ImportDeclaration copiedNode= (ImportDeclaration) ASTNode.copySubtree(rewrite.getAST(), sourceNode);

		if (getLocation() == IReorgDestination.LOCATION_BEFORE) {
			listRewrite.insertFirst(copiedNode, null);
		} else {
			listRewrite.insertLast(copiedNode, null);
		}
	}
}
 
Example #13
Source File: ChangeSignatureProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void addExceptionToNodeList(ExceptionInfo exceptionInfo, ListRewrite exceptionListRewrite) {
	String fullyQualified= exceptionInfo.getFullyQualifiedName();
	for (Iterator<? extends ASTNode> iter= exceptionListRewrite.getOriginalList().iterator(); iter.hasNext(); ) {
		Type exType= (Type) iter.next();
		//XXX: existing superclasses of the added exception are redundant and could be removed
		ITypeBinding typeBinding= exType.resolveBinding();
		if (typeBinding == null)
			continue; // newly added or unresolvable type
		if (typeBinding.getQualifiedName().equals(fullyQualified))
			return; // don't add it again
	}
	String importedType= getImportRewrite().addImport(exceptionInfo.getFullyQualifiedName());
	getImportRemover().registerAddedImport(importedType);
	ASTNode exNode= getASTRewrite().createStringPlaceholder(importedType, ASTNode.SIMPLE_TYPE);
	exceptionListRewrite.insertLast(exNode, fDescription);
}
 
Example #14
Source File: StatementRewrite.java    From eclipse.jdt.ls with Eclipse Public License 2.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 #15
Source File: ExtractClassRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private List<ResourceChange> createParameterObject(ParameterObjectFactory pof, IPackageFragmentRoot packageRoot) throws CoreException {
	FieldUpdate fieldUpdate= new FieldUpdate();
	if (fDescriptor.isCreateTopLevel())
		return pof.createTopLevelParameterObject(packageRoot, fieldUpdate);
	else {
		CompilationUnit root= fBaseCURewrite.getRoot();
		TypeDeclaration typeDecl= ASTNodeSearchUtil.getTypeDeclarationNode(fDescriptor.getType(), root);
		ASTRewrite rewrite= fBaseCURewrite.getASTRewrite();
		ListRewrite listRewrite= rewrite.getListRewrite(typeDecl, TypeDeclaration.BODY_DECLARATIONS_PROPERTY);
		TypeDeclaration paramClass= pof.createClassDeclaration(typeDecl.getName().getFullyQualifiedName(), fBaseCURewrite, fieldUpdate);
		paramClass.modifiers().add(rewrite.getAST().newModifier(ModifierKeyword.PUBLIC_KEYWORD));
		if (shouldParamClassBeStatic(typeDecl)) {
			paramClass.modifiers().add(rewrite.getAST().newModifier(ModifierKeyword.STATIC_KEYWORD));
		}
		listRewrite.insertFirst(paramClass, fBaseCURewrite.createGroupDescription(RefactoringCoreMessages.ExtractClassRefactoring_group_insert_parameter));
		return new ArrayList<ResourceChange>(); //Change will be generated later for fBaseCURewrite
	}

}
 
Example #16
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 #17
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 #18
Source File: ClientBundleResource.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
public MethodDeclaration createMethodDeclaration(IType clientBundle, ASTRewrite astRewrite,
    ImportRewrite importRewrite, boolean addComments) throws CoreException {
  AST ast = astRewrite.getAST();
  MethodDeclaration methodDecl = ast.newMethodDeclaration();

  // Method is named after the resource it accesses
  methodDecl.setName(ast.newSimpleName(getMethodName()));

  // Method return type is a ResourcePrototype subtype
  ITypeBinding resourceTypeBinding = JavaASTUtils.resolveType(clientBundle.getJavaProject(), getReturnTypeName());
  Type resourceType = importRewrite.addImport(resourceTypeBinding, ast);
  methodDecl.setReturnType2(resourceType);

  // Add @Source annotation if necessary
  String sourceAnnotationValue = getSourceAnnotationValue(clientBundle);
  if (sourceAnnotationValue != null) {
    // Build the annotation
    SingleMemberAnnotation sourceAnnotation = ast.newSingleMemberAnnotation();
    sourceAnnotation.setTypeName(ast.newName("Source"));
    StringLiteral annotationValue = ast.newStringLiteral();
    annotationValue.setLiteralValue(sourceAnnotationValue);
    sourceAnnotation.setValue(annotationValue);

    // Add the annotation to the method
    ChildListPropertyDescriptor modifiers = methodDecl.getModifiersProperty();
    ListRewrite modifiersRewriter = astRewrite.getListRewrite(methodDecl, modifiers);
    modifiersRewriter.insertFirst(sourceAnnotation, null);
  }

  return methodDecl;
}
 
Example #19
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 #20
Source File: SurroundWith.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private SplitUnselectedOperator(List<VariableDeclaration> accessedInside, ListRewrite blockRewrite, ASTRewrite rewrite) {
	super();
	fAccessedInside= accessedInside;
	fBlockRewrite= blockRewrite;
	fRewrite= rewrite;
	fLastStatement= null;
}
 
Example #21
Source File: FieldModifierResolution.java    From spotbugs with GNU Lesser General Public License v2.1 5 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());
    FieldDeclaration field = getFieldDeclaration(type, bug.getPrimaryField());

    Modifier finalModifier = workingUnit.getAST().newModifier(getModifierToAdd());

    ListRewrite modRewrite = rewrite.getListRewrite(field, FieldDeclaration.MODIFIERS2_PROPERTY);
    modRewrite.insertLast(finalModifier, null);
}
 
Example #22
Source File: InlineConstantRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void addExplicitTypeArgumentsIfNecessary(Expression invocation) {
	if (Invocations.isResolvedTypeInferredFromExpectedType(invocation)) {
		ASTNode referenceContext= fNewLocation.getParent();
		if (! (referenceContext instanceof VariableDeclarationFragment
				|| referenceContext instanceof SingleVariableDeclaration
				|| referenceContext instanceof Assignment)) {
			ITypeBinding[] typeArguments= Invocations.getInferredTypeArguments(invocation);
			ListRewrite typeArgsRewrite= Invocations.getInferredTypeArgumentsRewrite(fInitializerRewrite, invocation);
			for (int i= 0; i < typeArguments.length; i++) {
				Type typeArgument= fNewLocationCuRewrite.getImportRewrite().addImport(typeArguments[i], fNewLocationCuRewrite.getAST(), fNewLocationContext);
				fNewLocationCuRewrite.getImportRemover().registerAddedImports(typeArgument);
				typeArgsRewrite.insertLast(typeArgument, null);
			}
			
			if (invocation instanceof MethodInvocation) {
				MethodInvocation methodInvocation= (MethodInvocation) invocation;
				Expression expression= methodInvocation.getExpression();
				if (expression == null) {
					IMethodBinding methodBinding= methodInvocation.resolveMethodBinding();
					if (methodBinding != null) {
						expression= fNewLocationCuRewrite.getAST().newName(fNewLocationCuRewrite.getImportRewrite().addImport(methodBinding.getDeclaringClass().getTypeDeclaration(), fNewLocationContext));
						fInitializerRewrite.set(invocation, MethodInvocation.EXPRESSION_PROPERTY, expression, null);
					}
				}
			}
		}
	}
}
 
Example #23
Source File: ReplaceTypeCodeWithStateStrategy.java    From JDeodorant with MIT License 5 votes vote down vote up
private void removePrimitiveStateField() {
	ASTRewrite sourceRewriter = ASTRewrite.create(sourceTypeDeclaration.getAST());
	AST contextAST = sourceTypeDeclaration.getAST();
	ListRewrite contextBodyRewrite = sourceRewriter.getListRewrite(sourceTypeDeclaration, TypeDeclaration.BODY_DECLARATIONS_PROPERTY);
	FieldDeclaration[] fieldDeclarations = sourceTypeDeclaration.getFields();
	for(FieldDeclaration fieldDeclaration : fieldDeclarations) {
		List<VariableDeclarationFragment> fragments = fieldDeclaration.fragments();
		for(VariableDeclarationFragment fragment : fragments) {
			if(fragment.equals(typeCheckElimination.getTypeField())) {
				if(fragments.size() == 1) {
					contextBodyRewrite.remove(fragment.getParent(), null);
				}
				else {
					ListRewrite fragmentRewrite = sourceRewriter.getListRewrite(fragment.getParent(), FieldDeclaration.FRAGMENTS_PROPERTY);
					fragmentRewrite.remove(fragment, null);
				}
			}
		}
	}
	try {
		TextEdit sourceEdit = sourceRewriter.rewriteAST();
		ICompilationUnit sourceICompilationUnit = (ICompilationUnit)sourceCompilationUnit.getJavaElement();
		CompilationUnitChange change = compilationUnitChanges.get(sourceICompilationUnit);
		change.getEdit().addChild(sourceEdit);
		change.addTextEditGroup(new TextEditGroup("Remove primitive field holding the current state", new TextEdit[] {sourceEdit}));
	} catch (JavaModelException e) {
		e.printStackTrace();
	}
}
 
Example #24
Source File: NewAnnotationMemberProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected ASTRewrite getRewrite() throws CoreException {
	CompilationUnit astRoot= ASTResolving.findParentCompilationUnit(fInvocationNode);
	ASTNode typeDecl= astRoot.findDeclaringNode(fSenderBinding);
	ASTNode newTypeDecl= null;
	if (typeDecl != null) {
		newTypeDecl= typeDecl;
	} else {
		astRoot= ASTResolving.createQuickFixAST(getCompilationUnit(), null);
		newTypeDecl= astRoot.findDeclaringNode(fSenderBinding.getKey());
	}
	createImportRewrite(astRoot);

	if (newTypeDecl instanceof AnnotationTypeDeclaration) {
		AnnotationTypeDeclaration newAnnotationTypeDecl= (AnnotationTypeDeclaration) newTypeDecl;

		ASTRewrite rewrite= ASTRewrite.create(astRoot.getAST());

		AnnotationTypeMemberDeclaration newStub= getStub(rewrite, newAnnotationTypeDecl);

		List<BodyDeclaration> members= newAnnotationTypeDecl.bodyDeclarations();
		int insertIndex= members.size();

		ListRewrite listRewriter= rewrite.getListRewrite(newAnnotationTypeDecl, AnnotationTypeDeclaration.BODY_DECLARATIONS_PROPERTY);
		listRewriter.insertAt(newStub, insertIndex, null);

		return rewrite;
	}
	return null;
}
 
Example #25
Source File: JavadocTagsSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public static void insertTag(ListRewrite rewriter, TagElement newElement, Set<String> sameKindLeadingNames, TextEditGroup groupDescription) {
	List<? extends ASTNode> tags= rewriter.getRewrittenList();

	String insertedTagName= newElement.getTagName();

	ASTNode after= null;
	int tagRanking= getTagRanking(insertedTagName);
	for (int i= tags.size() - 1; i >= 0; i--) {
		TagElement curr= (TagElement) tags.get(i);
		String tagName= curr.getTagName();
		if (tagName == null || tagRanking > getTagRanking(tagName)) {
			after= curr;
			break;
		}
		if (sameKindLeadingNames != null && isSameTag(insertedTagName, tagName)) {
			String arg= getArgument(curr);
			if (arg != null && sameKindLeadingNames.contains(arg)) {
				after= curr;
				break;
			}
		}
	}
	if (after != null) {
		rewriter.insertAfter(newElement, after, groupDescription);
	} else {
		rewriter.insertFirst(newElement, groupDescription);
	}
}
 
Example #26
Source File: AddResourcesToClientBundleAction.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
public void run(IProgressMonitor monitor) throws CoreException {
  ICompilationUnit icu = clientBundle.getCompilationUnit();
  CompilationUnit cu = JavaASTUtils.parseCompilationUnit(icu);
  ImportRewrite importRewrite = StubUtility.createImportRewrite(cu, true);

  // Find the target type declaration
  TypeDeclaration typeDecl = JavaASTUtils.findTypeDeclaration(cu,
      clientBundle.getFullyQualifiedName());
  if (typeDecl == null) {
    throw new CoreException(
        StatusUtilities.newErrorStatus("Missing ClientBundle type "
            + clientBundle.getFullyQualifiedName(), GWTPlugin.PLUGIN_ID));
  }

  // We need to rewrite the AST of the ClientBundle type declaration
  ASTRewrite astRewrite = ASTRewrite.create(cu.getAST());
  ChildListPropertyDescriptor property = ASTNodes.getBodyDeclarationsProperty(typeDecl);
  ListRewrite listRewriter = astRewrite.getListRewrite(typeDecl, property);

  // Add the new resource methods
  boolean addComments = StubUtility.doAddComments(icu.getJavaProject());
  for (ClientBundleResource resource : resources) {
    listRewriter.insertLast(resource.createMethodDeclaration(clientBundle,
        astRewrite, importRewrite, addComments), null);
  }

  // Create the edit to add the methods and update the imports
  TextEdit rootEdit = new MultiTextEdit();
  rootEdit.addChild(astRewrite.rewriteAST());
  rootEdit.addChild(importRewrite.rewriteImports(null));

  // Apply the change to the compilation unit
  CompilationUnitChange cuChange = new CompilationUnitChange(
      "Update ClientBundle", icu);
  cuChange.setSaveMode(TextFileChange.KEEP_SAVE_STATE);
  cuChange.setEdit(rootEdit);
  cuChange.perform(new NullProgressMonitor());
}
 
Example #27
Source File: ExtractSupertypeProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates the necessary constructors for the extracted supertype.
 *
 * @param targetRewrite
 *            the target compilation unit rewrite
 * @param superType
 *            the super type, or <code>null</code> if no super type (ie.
 *            <code>java.lang.Object</code>) is available
 * @param targetDeclaration
 *            the type declaration of the target type
 * @param status
 *            the refactoring status
 */
protected final void createNecessaryConstructors(final CompilationUnitRewrite targetRewrite, final IType superType, final AbstractTypeDeclaration targetDeclaration, final RefactoringStatus status) {
	Assert.isNotNull(targetRewrite);
	Assert.isNotNull(targetDeclaration);
	if (superType != null) {
		final ITypeBinding binding= targetDeclaration.resolveBinding();
		if (binding != null && binding.isClass()) {
			final IMethodBinding[] bindings= StubUtility2.getVisibleConstructors(binding, true, true);
			int deprecationCount= 0;
			for (int i= 0; i < bindings.length; i++) {
				if (bindings[i].isDeprecated())
					deprecationCount++;
			}
			final ListRewrite rewrite= targetRewrite.getASTRewrite().getListRewrite(targetDeclaration, TypeDeclaration.BODY_DECLARATIONS_PROPERTY);
			if (rewrite != null) {
				boolean createDeprecated= deprecationCount == bindings.length;
				for (int i= 0; i < bindings.length; i++) {
					IMethodBinding curr= bindings[i];
					if (!curr.isDeprecated() || createDeprecated) {
						MethodDeclaration stub;
						try {
							ImportRewriteContext context= new ContextSensitiveImportRewriteContext(targetDeclaration, targetRewrite.getImportRewrite());
							stub= StubUtility2.createConstructorStub(targetRewrite.getCu(), targetRewrite.getASTRewrite(), targetRewrite.getImportRewrite(), context, curr, binding.getName(),
									Modifier.PUBLIC, false, false, fSettings);
							if (stub != null)
								rewrite.insertLast(stub, null);
						} catch (CoreException exception) {
							JavaPlugin.log(exception);
							status.merge(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractSupertypeProcessor_unexpected_exception_on_layer));
						}
					}
				}
			}
		}
	}
}
 
Example #28
Source File: SuperTypeRefactoringProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates the type parameters of the new supertype.
 *
 * @param targetRewrite
 *            the target compilation unit rewrite
 * @param subType
 *            the subtype
 * @param sourceDeclaration
 *            the type declaration of the source type
 * @param targetDeclaration
 *            the type declaration of the target type
 */
protected final void createTypeParameters(final ASTRewrite targetRewrite, final IType subType, final AbstractTypeDeclaration sourceDeclaration, final AbstractTypeDeclaration targetDeclaration) {
	Assert.isNotNull(targetRewrite);
	Assert.isNotNull(sourceDeclaration);
	Assert.isNotNull(targetDeclaration);
	if (sourceDeclaration instanceof TypeDeclaration) {
		TypeParameter parameter= null;
		final ListRewrite rewrite= targetRewrite.getListRewrite(targetDeclaration, TypeDeclaration.TYPE_PARAMETERS_PROPERTY);
		for (final Iterator<TypeParameter> iterator= ((TypeDeclaration) sourceDeclaration).typeParameters().iterator(); iterator.hasNext();) {
			parameter= iterator.next();
			rewrite.insertLast(ASTNode.copySubtree(targetRewrite.getAST(), parameter), null);
			ImportRewriteUtil.collectImports(subType.getJavaProject(), sourceDeclaration, fTypeBindings, fStaticBindings, false);
		}
	}
}
 
Example #29
Source File: ExtractMethodFragmentRefactoring.java    From JDeodorant with MIT License 5 votes vote down vote up
public ExtractMethodFragmentRefactoring() {
	this.tryStatementsToBeRemoved = new LinkedHashSet<TryStatement>();
	this.tryStatementsToBeCopied = new LinkedHashSet<TryStatement>();
	this.tryStatementBodyRewriteMap = new LinkedHashMap<TryStatement, ListRewrite>();
	this.doLoopNodes = new ArrayList<CFGBranchDoLoopNode>();
	this.labeledStatementsToBeRemoved = new LinkedHashSet<LabeledStatement>();
}
 
Example #30
Source File: AbstractMethodCorrectionProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected ASTRewrite getRewrite() throws CoreException {
	CompilationUnit astRoot= ASTResolving.findParentCompilationUnit(fNode);
	ASTNode typeDecl= astRoot.findDeclaringNode(fSenderBinding);
	ASTNode newTypeDecl= null;
	boolean isInDifferentCU;
	if (typeDecl != null) {
		isInDifferentCU= false;
		newTypeDecl= typeDecl;
	} else {
		isInDifferentCU= true;
		astRoot= ASTResolving.createQuickFixAST(getCompilationUnit(), null);
		newTypeDecl= astRoot.findDeclaringNode(fSenderBinding.getKey());
	}
	createImportRewrite(astRoot);

	if (newTypeDecl != null) {
		ASTRewrite rewrite= ASTRewrite.create(astRoot.getAST());

		MethodDeclaration newStub= getStub(rewrite, newTypeDecl);

		ChildListPropertyDescriptor property= ASTNodes.getBodyDeclarationsProperty(newTypeDecl);
		List<BodyDeclaration> members= ASTNodes.getBodyDeclarations(newTypeDecl);

		int insertIndex;
		if (isConstructor()) {
			insertIndex= findConstructorInsertIndex(members);
		} else if (!isInDifferentCU) {
			insertIndex= findMethodInsertIndex(members, fNode.getStartPosition());
		} else {
			insertIndex= members.size();
		}
		ListRewrite listRewriter= rewrite.getListRewrite(newTypeDecl, property);
		listRewriter.insertAt(newStub, insertIndex, null);

		return rewrite;
	}
	return null;
}