Java Code Examples for org.eclipse.jdt.core.dom.CompilationUnit#getJavaElement()

The following examples show how to use org.eclipse.jdt.core.dom.CompilationUnit#getJavaElement() . 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: ConvertForLoopOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public IStatus satisfiesPreconditions() {
	ForStatement statement= getForStatement();
	CompilationUnit ast= (CompilationUnit)statement.getRoot();

	IJavaElement javaElement= ast.getJavaElement();
	if (javaElement == null)
		return ERROR_STATUS;

	if (!JavaModelUtil.is50OrHigher(javaElement.getJavaProject()))
		return ERROR_STATUS;

	if (!validateInitializers(statement))
		return ERROR_STATUS;

	if (!validateExpression(statement))
		return ERROR_STATUS;

	if (!validateUpdaters(statement))
		return ERROR_STATUS;

	if (!validateBody(statement))
		return ERROR_STATUS;

	return Status.OK_STATUS;
}
 
Example 2
Source File: NullAnnotationsCorrectionProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Fix for {@link IProblem#NullableFieldReference}
 * @param context context
 * @param problem problem to be fixed
 * @param proposals accumulator for computed proposals
 */
public static void addExtractCheckedLocalProposal(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
	CompilationUnit compilationUnit = context.getASTRoot();
	ICompilationUnit cu= (ICompilationUnit) compilationUnit.getJavaElement();

	ASTNode selectedNode= problem.getCoveringNode(compilationUnit);

	SimpleName name= findProblemFieldName(selectedNode, problem.getProblemId());
	if (name == null)
		return;

	ASTNode method= ASTNodes.getParent(selectedNode, MethodDeclaration.class);
	if (method == null)
		method= ASTNodes.getParent(selectedNode, Initializer.class);
	if (method == null)
		return;
	
	proposals.add(new ExtractToNullCheckedLocalProposal(cu, compilationUnit, name, method));
}
 
Example 3
Source File: RedundantNullnessTypeAnnotationsFilter.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
public static /* @Nullable */ RedundantNullnessTypeAnnotationsFilter createIfConfigured(/* @Nullable */ ASTNode node) {
	if (node == null) {
		return null;
	}
	final ASTNode root= node.getRoot();
	if (root instanceof CompilationUnit) {
		CompilationUnit compilationUnit= (CompilationUnit) root;
		IJavaElement javaElement= compilationUnit.getJavaElement();
		IJavaProject javaProject= javaElement == null ? null : javaElement.getJavaProject();
		if (javaProject != null) {
			if (JavaCore.ENABLED.equals(javaProject.getOption(JavaCore.COMPILER_ANNOTATION_NULL_ANALYSIS, true))) {
				String nonNullAnnotationName= javaProject.getOption(JavaCore.COMPILER_NONNULL_ANNOTATION_NAME, true);
				String nullableAnnotationName= javaProject.getOption(JavaCore.COMPILER_NULLABLE_ANNOTATION_NAME, true);
				String nonNullByDefaultName= javaProject.getOption(JavaCore.COMPILER_NONNULL_BY_DEFAULT_ANNOTATION_NAME, true);
				if (nonNullAnnotationName == null || nullableAnnotationName == null || nonNullByDefaultName == null) {
					return null;
				}
				EnumSet<TypeLocation> nonNullByDefaultLocations= determineNonNullByDefaultLocations(node, nonNullByDefaultName);
				return new RedundantNullnessTypeAnnotationsFilter(nonNullAnnotationName, nullableAnnotationName, nonNullByDefaultLocations);
			}
		}
	}
	return null;
}
 
Example 4
Source File: StringCleanUp.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public int computeNumberOfFixes(CompilationUnit compilationUnit) {
	try {
		ICompilationUnit cu= (ICompilationUnit)compilationUnit.getJavaElement();
		if (!cu.isStructureKnown())
			return 0; //[clean up] 'Remove unnecessary $NLS-TAGS$' removes necessary ones in case of syntax errors: https://bugs.eclipse.org/bugs/show_bug.cgi?id=285814 : 
	} catch (JavaModelException e) {
		return 0;
	}
	
	int result= 0;
	IProblem[] problems= compilationUnit.getProblems();
	if (isEnabled(CleanUpConstants.ADD_MISSING_NLS_TAGS))
		result+= getNumberOfProblems(problems, IProblem.NonExternalizedStringLiteral);

	if (isEnabled(CleanUpConstants.REMOVE_UNNECESSARY_NLS_TAGS))
		result+= getNumberOfProblems(problems, IProblem.UnnecessaryNLSTag);

	return result;
}
 
Example 5
Source File: AddUnimplementedMethodsOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Creates a new add unimplemented methods operation.
 *
 * @param astRoot the compilation unit AST node
 * @param type the type to add the methods to
 * @param methodsToImplement the method bindings to implement or <code>null</code> to implement all unimplemented methods
 * 	@param insertPos the insertion point, or <code>-1</code>
 * @param imports <code>true</code> if the import edits should be applied, <code>false</code> otherwise
 * @param apply <code>true</code> if the resulting edit should be applied, <code>false</code> otherwise
 * @param save <code>true</code> if the changed compilation unit should be saved, <code>false</code> otherwise
 */
public AddUnimplementedMethodsOperation(CompilationUnit astRoot, ITypeBinding type, IMethodBinding[] methodsToImplement, int insertPos, final boolean imports, final boolean apply, final boolean save) {
	if (astRoot == null || !(astRoot.getJavaElement() instanceof ICompilationUnit)) {
		throw new IllegalArgumentException("AST must not be null and has to be created from a ICompilationUnit"); //$NON-NLS-1$
	}
	if (type == null) {
		throw new IllegalArgumentException("The type must not be null"); //$NON-NLS-1$
	}
	ASTNode node= astRoot.findDeclaringNode(type);
	if (!(node instanceof AnonymousClassDeclaration || node instanceof AbstractTypeDeclaration)) {
		throw new IllegalArgumentException("type has to map to a type declaration in the AST"); //$NON-NLS-1$
	}

	fType= type;
	fInsertPos= insertPos;
	fASTRoot= astRoot;
	fMethodsToImplement= methodsToImplement;
	fSave= save;
	fApply= apply;
	fImports= imports;

	fDoCreateComments= StubUtility.doAddComments(astRoot.getJavaElement().getJavaProject());
}
 
Example 6
Source File: AssociativeInfixExpressionFragment.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public Expression createCopyTarget(ASTRewrite rewrite, boolean removeSurroundingParenthesis) throws JavaModelException {
		List<Expression> allOperands= findGroupMembersInOrderFor(fGroupRoot);
		if (allOperands.size() == fOperands.size()) {
			return (Expression) rewrite.createCopyTarget(fGroupRoot);
		}

		CompilationUnit root= (CompilationUnit) fGroupRoot.getRoot();
		ICompilationUnit cu= (ICompilationUnit) root.getJavaElement();
		String source= cu.getBuffer().getText(getStartPosition(), getLength());
		return (Expression) rewrite.createStringPlaceholder(source, ASTNode.INFIX_EXPRESSION);

//		//Todo: see whether we could copy bigger chunks of the original selection
//		// (probably only possible from extendedOperands list or from nested InfixExpressions)
//		InfixExpression result= rewrite.getAST().newInfixExpression();
//		result.setOperator(getOperator());
//		Expression first= (Expression) fOperands.get(0);
//		Expression second= (Expression) fOperands.get(1);
//		result.setLeftOperand((Expression) rewrite.createCopyTarget(first));
//		result.setRightOperand((Expression) rewrite.createCopyTarget(second));
//		for (int i= 2; i < fOperands.size(); i++) {
//			Expression next= (Expression) fOperands.get(i);
//			result.extendedOperands().add(rewrite.createCopyTarget(next));
//		}
//		return result;
	}
 
Example 7
Source File: PromoteTempToFieldRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Creates a new promote temp to field refactoring.
 * @param declaration the variable declaration node to convert to a field
 */
public PromoteTempToFieldRefactoring(VariableDeclaration declaration) {
	Assert.isTrue(declaration != null);
	fTempDeclarationNode= declaration;
	IVariableBinding resolveBinding= declaration.resolveBinding();
	Assert.isTrue(resolveBinding != null && !resolveBinding.isParameter() && !resolveBinding.isField());

	ASTNode root= declaration.getRoot();
	Assert.isTrue(root instanceof CompilationUnit);
	fCompilationUnitNode= (CompilationUnit) root;

	IJavaElement input= fCompilationUnitNode.getJavaElement();
	Assert.isTrue(input instanceof ICompilationUnit);
	fCu= (ICompilationUnit) input;

	fSelectionStart= declaration.getStartPosition();
	fSelectionLength= declaration.getLength();

       fFieldName= ""; //$NON-NLS-1$
       fVisibility= Modifier.PRIVATE;
       fDeclareStatic= false;
       fDeclareFinal= false;
       fInitializeIn= INITIALIZE_IN_METHOD;
       fLinkedProposalModel= null;
}
 
Example 8
Source File: MoveMethodRefactoring.java    From JDeodorant with MIT License 5 votes vote down vote up
public MoveMethodRefactoring(CompilationUnit sourceCompilationUnit, CompilationUnit targetCompilationUnit, 
		TypeDeclaration sourceTypeDeclaration, TypeDeclaration targetTypeDeclaration, MethodDeclaration sourceMethod,
		Map<MethodInvocation, MethodDeclaration> additionalMethodsToBeMoved, boolean leaveDelegate, String movedMethodName) {
	this.sourceCompilationUnit = sourceCompilationUnit;
	this.targetCompilationUnit = targetCompilationUnit;
	this.sourceTypeDeclaration = sourceTypeDeclaration;
	this.targetTypeDeclaration = targetTypeDeclaration;
	this.sourceMethod = sourceMethod;
	this.targetClassVariableName = null;
	this.additionalArgumentsAddedToMovedMethod = new LinkedHashSet<String>();
	this.additionalTypeBindingsToBeImportedInTargetClass = new LinkedHashSet<ITypeBinding>();
	this.additionalMethodsToBeMoved = additionalMethodsToBeMoved;
	this.fieldDeclarationsChangedWithPublicModifier = new LinkedHashSet<FieldDeclaration>();
	this.memberTypeDeclarationsChangedWithPublicModifier = new LinkedHashSet<BodyDeclaration>();
	this.leaveDelegate = leaveDelegate;
	this.movedMethodName = movedMethodName;
	this.isTargetClassVariableParameter = false;
	this.targetClassVariableParameterIndex = -1;
	this.fChanges = new LinkedHashMap<ICompilationUnit, CompilationUnitChange>();
	
	ICompilationUnit sourceICompilationUnit = (ICompilationUnit)sourceCompilationUnit.getJavaElement();
	this.sourceMultiTextEdit = new MultiTextEdit();
	this.sourceCompilationUnitChange = new CompilationUnitChange("", sourceICompilationUnit);
	sourceCompilationUnitChange.setEdit(sourceMultiTextEdit);
	fChanges.put(sourceICompilationUnit, sourceCompilationUnitChange);
	
	ICompilationUnit targetICompilationUnit = (ICompilationUnit)targetCompilationUnit.getJavaElement();
	if(sourceICompilationUnit.equals(targetICompilationUnit)) {
		this.targetMultiTextEdit = sourceMultiTextEdit;
		this.targetCompilationUnitChange = sourceCompilationUnitChange;
	}
	else {
		this.targetMultiTextEdit = new MultiTextEdit();
		this.targetCompilationUnitChange = new CompilationUnitChange("", targetICompilationUnit);
		targetCompilationUnitChange.setEdit(targetMultiTextEdit);
		fChanges.put(targetICompilationUnit, targetCompilationUnitChange);
	}
}
 
Example 9
Source File: ExtractMethodRefactoring.java    From JDeodorant with MIT License 5 votes vote down vote up
public ExtractMethodRefactoring(CompilationUnit sourceCompilationUnit, ASTSlice slice) {
	super();
	this.slice = slice;
	this.sourceCompilationUnit = sourceCompilationUnit;
	this.sourceTypeDeclaration = slice.getSourceTypeDeclaration();
	this.sourceMethodDeclaration = slice.getSourceMethodDeclaration();
	ICompilationUnit sourceICompilationUnit = (ICompilationUnit)sourceCompilationUnit.getJavaElement();
	this.compilationUnitChange = new CompilationUnitChange("", sourceICompilationUnit);
	this.exceptionTypesThatShouldBeThrownByExtractedMethod = new LinkedHashSet<ITypeBinding>();
	for(PDGNode pdgNode : slice.getSliceNodes()) {
		CFGNode cfgNode = pdgNode.getCFGNode();
		if(cfgNode instanceof CFGBranchDoLoopNode) {
			CFGBranchDoLoopNode cfgDoLoopNode = (CFGBranchDoLoopNode)cfgNode;
			doLoopNodes.add(cfgDoLoopNode);
		}
	}
	StatementExtractor statementExtractor = new StatementExtractor();
	List<Statement> tryStatements = statementExtractor.getTryStatements(sourceMethodDeclaration.getBody());
	for(Statement tryStatement : tryStatements) {
		processTryStatement((TryStatement)tryStatement);
	}
	for(Statement sliceStatement : slice.getSliceStatements()) {
		Set<ITypeBinding> thrownExceptionTypes = getThrownExceptionTypes(sliceStatement);
		if(thrownExceptionTypes.size() > 0) {
			TryStatement surroundingTryBlock = surroundingTryBlock(sliceStatement);
			if(surroundingTryBlock == null || !slice.getSliceStatements().contains(surroundingTryBlock)) {
				exceptionTypesThatShouldBeThrownByExtractedMethod.addAll(thrownExceptionTypes);
			}
			if(surroundingTryBlock != null && slice.getSliceStatements().contains(surroundingTryBlock)) {
				for(ITypeBinding thrownExceptionType : thrownExceptionTypes) {
					if(!tryBlockCatchesExceptionType(surroundingTryBlock, thrownExceptionType))
						exceptionTypesThatShouldBeThrownByExtractedMethod.add(thrownExceptionType);
				}
			}
		}
	}
}
 
Example 10
Source File: PolymorphismRefactoring.java    From JDeodorant with MIT License 5 votes vote down vote up
public PolymorphismRefactoring(IFile sourceFile, CompilationUnit sourceCompilationUnit,
		TypeDeclaration sourceTypeDeclaration, TypeCheckElimination typeCheckElimination) {
	this.sourceFile = sourceFile;
	this.sourceCompilationUnit = sourceCompilationUnit;
	this.sourceTypeDeclaration = sourceTypeDeclaration;
	this.typeCheckElimination = typeCheckElimination;
	this.compilationUnitChanges = new LinkedHashMap<ICompilationUnit, CompilationUnitChange>();
	ICompilationUnit sourceICompilationUnit = (ICompilationUnit)sourceCompilationUnit.getJavaElement();
	MultiTextEdit sourceMultiTextEdit = new MultiTextEdit();
	CompilationUnitChange sourceCompilationUnitChange = new CompilationUnitChange("", sourceICompilationUnit);
	sourceCompilationUnitChange.setEdit(sourceMultiTextEdit);
	compilationUnitChanges.put(sourceICompilationUnit, sourceCompilationUnitChange);
	this.javaElementsToOpenInEditor = new LinkedHashSet<IJavaElement>();
	this.fieldDeclarationsChangedWithPublicModifier = new LinkedHashSet<FieldDeclaration>();
}
 
Example 11
Source File: ConvertAnonymousToNestedRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public ConvertAnonymousToNestedRefactoring(AnonymousClassDeclaration declaration) {
	Assert.isTrue(declaration != null);

	ASTNode astRoot= declaration.getRoot();
	Assert.isTrue(astRoot instanceof CompilationUnit);
	fCompilationUnitNode= (CompilationUnit) astRoot;

 	IJavaElement javaElement= fCompilationUnitNode.getJavaElement();
    Assert.isTrue(javaElement instanceof ICompilationUnit);

    fCu= (ICompilationUnit) javaElement;
    fSelectionStart= declaration.getStartPosition();
    fSelectionLength= declaration.getLength();
}
 
Example 12
Source File: InferTypeArgumentsConstraintCreator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean visit(CompilationUnit node) {
	fTCModel.newCu(); //TODO: make sure that accumulators are reset after last CU!
	fCU= (ICompilationUnit) node.getJavaElement();
	fTCModel.getTypeEnvironment().initializeJavaLangObject(fCU.getJavaProject());
	return super.visit(node);
}
 
Example 13
Source File: RenameAnalyzeUtil.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * This method analyzes a set of local variable renames inside one cu. It checks whether
 * any new compile errors have been introduced by the rename(s) and whether the correct
 * node(s) has/have been renamed.
 *
 * @param analyzePackages the LocalAnalyzePackages containing the information about the local renames
 * @param cuChange the TextChange containing all local variable changes to be applied.
 * @param oldCUNode the fully (incl. bindings) resolved AST node of the original compilation unit
 * @param recovery whether statements and bindings recovery should be performed when parsing the changed CU
 * @return a RefactoringStatus containing errors if compile errors or wrongly renamed nodes are found
 * @throws CoreException thrown if there was an error greating the preview content of the change
 */
public static RefactoringStatus analyzeLocalRenames(LocalAnalyzePackage[] analyzePackages, TextChange cuChange, CompilationUnit oldCUNode, boolean recovery) throws CoreException {

	RefactoringStatus result= new RefactoringStatus();
	ICompilationUnit compilationUnit= (ICompilationUnit) oldCUNode.getJavaElement();

	String newCuSource= cuChange.getPreviewContent(new NullProgressMonitor());
	CompilationUnit newCUNode= new RefactoringASTParser(IASTSharedValues.SHARED_AST_LEVEL).parse(newCuSource, compilationUnit, true, recovery, null);

	result.merge(analyzeCompileErrors(newCuSource, newCUNode, oldCUNode));
	if (result.hasError()) {
		return result;
	}

	for (int i= 0; i < analyzePackages.length; i++) {
		ASTNode enclosing= getEnclosingBlockOrMethodOrLambda(analyzePackages[i].fDeclarationEdit, cuChange, newCUNode);

		// get new declaration
		IRegion newRegion= RefactoringAnalyzeUtil.getNewTextRange(analyzePackages[i].fDeclarationEdit, cuChange);
		ASTNode newDeclaration= NodeFinder.perform(newCUNode, newRegion.getOffset(), newRegion.getLength());
		Assert.isTrue(newDeclaration instanceof Name);

		VariableDeclaration declaration= getVariableDeclaration((Name) newDeclaration);
		Assert.isNotNull(declaration);

		SimpleName[] problemNodes= ProblemNodeFinder.getProblemNodes(enclosing, declaration, analyzePackages[i].fOccurenceEdits, cuChange);
		result.merge(RefactoringAnalyzeUtil.reportProblemNodes(newCuSource, problemNodes));
	}
	return result;
}
 
Example 14
Source File: CopyrightManager.java    From hybris-commerce-eclipse-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Adds copyright header to the compilation unit
 *
 * @param compilationUnit
 *            compilation unit affected
 * @return compilation unit change
 */
public CompilationUnitChange addCopyrightsHeader(final CompilationUnit compilationUnit) {
	final ICompilationUnit unit = (ICompilationUnit) compilationUnit.getJavaElement();
	change = new CompilationUnitChange(ADD_COPYRIGHT, unit);
	rewriter = ASTRewrite.create(compilationUnit.getAST());
	final ListRewrite listRewrite = rewriter.getListRewrite(compilationUnit.getPackage(),
			PackageDeclaration.ANNOTATIONS_PROPERTY);
	final Comment placeHolder = (Comment) rewriter.createStringPlaceholder(getCopyrightText() + NEW_LINE_SEPARATOR,
			ASTNode.BLOCK_COMMENT);
	listRewrite.insertFirst(placeHolder, null);
	rewriteCompilationUnit(unit, getNewUnitSource(unit, null));
	return change;
}
 
Example 15
Source File: Java50Fix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public static ICleanUpFix createCleanUp(CompilationUnit compilationUnit,
		boolean addOverrideAnnotation,
		boolean addOverrideInterfaceAnnotation,
		boolean addDeprecatedAnnotation,
		boolean rawTypeReference) {

	ICompilationUnit cu= (ICompilationUnit)compilationUnit.getJavaElement();
	if (!JavaModelUtil.is50OrHigher(cu.getJavaProject()))
		return null;

	if (!addOverrideAnnotation && !addDeprecatedAnnotation && !rawTypeReference)
		return null;

	List<CompilationUnitRewriteOperation> operations= new ArrayList<CompilationUnitRewriteOperation>();

	IProblem[] problems= compilationUnit.getProblems();
	IProblemLocation[] locations= new IProblemLocation[problems.length];
	for (int i= 0; i < problems.length; i++) {
		locations[i]= new ProblemLocation(problems[i]);
	}

	if (addOverrideAnnotation)
		createAddOverrideAnnotationOperations(compilationUnit, addOverrideInterfaceAnnotation, locations, operations);

	if (addDeprecatedAnnotation)
		createAddDeprecatedAnnotationOperations(compilationUnit, locations, operations);

	if (rawTypeReference)
		createRawTypeReferenceOperations(compilationUnit, locations, operations);

	if (operations.size() == 0)
		return null;

	String fixName;
	if (rawTypeReference) {
		fixName= FixMessages.Java50Fix_add_type_parameters_change_name;
	} else {
		fixName= FixMessages.Java50Fix_add_annotations_change_name;
	}

	CompilationUnitRewriteOperation[] operationsArray= operations.toArray(new CompilationUnitRewriteOperation[operations.size()]);
	return new Java50Fix(fixName, compilationUnit, operationsArray);
}
 
Example 16
Source File: JavaASTUtils.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Gets the compilation unit containing a particular Java AST node.
 */
public static ICompilationUnit getCompilationUnit(ASTNode node) {
  CompilationUnit root = (CompilationUnit) node.getRoot();
  ICompilationUnit cu = (ICompilationUnit) root.getJavaElement();
  return cu;
}
 
Example 17
Source File: RefactorProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private static boolean getConvertVarTypeToResolvedTypeProposal(IInvocationContext context, ASTNode node, Collection<ChangeCorrectionProposal> proposals) {
	CompilationUnit astRoot = context.getASTRoot();
	IJavaElement root = astRoot.getJavaElement();
	if (root == null) {
		return false;
	}
	IJavaProject javaProject = root.getJavaProject();
	if (javaProject == null) {
		return false;
	}
	if (!JavaModelUtil.is10OrHigher(javaProject)) {
		return false;
	}

	if (!(node instanceof SimpleName)) {
		return false;
	}
	SimpleName name = (SimpleName) node;
	IBinding binding = name.resolveBinding();
	if (!(binding instanceof IVariableBinding)) {
		return false;
	}
	IVariableBinding varBinding = (IVariableBinding) binding;
	if (varBinding.isField() || varBinding.isParameter()) {
		return false;
	}

	ASTNode varDeclaration = astRoot.findDeclaringNode(varBinding);
	if (varDeclaration == null) {
		return false;
	}

	ITypeBinding typeBinding = varBinding.getType();
	if (typeBinding == null || typeBinding.isAnonymous() || typeBinding.isIntersectionType() || typeBinding.isWildcardType()) {
		return false;
	}

	Type type = null;
	if (varDeclaration instanceof SingleVariableDeclaration) {
		type = ((SingleVariableDeclaration) varDeclaration).getType();
	} else if (varDeclaration instanceof VariableDeclarationFragment) {
		ASTNode parent = varDeclaration.getParent();
		if (parent instanceof VariableDeclarationStatement) {
			type = ((VariableDeclarationStatement) parent).getType();
		} else if (parent instanceof VariableDeclarationExpression) {
			type = ((VariableDeclarationExpression) parent).getType();
		}
	}
	if (type == null || !type.isVar()) {
		return false;
	}

	TypeChangeCorrectionProposal proposal = new TypeChangeCorrectionProposal(context.getCompilationUnit(), varBinding, astRoot, typeBinding, false, IProposalRelevance.CHANGE_VARIABLE);
	proposal.setKind(CodeActionKind.Refactor);
	proposals.add(proposal);
	return true;
}
 
Example 18
Source File: NullAnnotationsRewriteOperations.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private static SignatureAnnotationRewriteOperation createAddAnnotationToOverriddenOperation(CompilationUnit compilationUnit, IProblemLocation problem, String annotationToAdd,
		String annotationToRemove, boolean allowRemove) {
	ICompilationUnit cu= (ICompilationUnit) compilationUnit.getJavaElement();
	if (!JavaModelUtil.is50OrHigher(cu.getJavaProject()))
		return null;

	ASTNode selectedNode= problem.getCoveringNode(compilationUnit);
	if (selectedNode == null)
		return null;

	ASTNode declaringNode= getDeclaringNode(selectedNode);
	switch (problem.getProblemId()) {
		case IProblem.IllegalDefinitionToNonNullParameter:
		case IProblem.IllegalRedefinitionToNonNullParameter:
			break;
		case IProblem.IllegalReturnNullityRedefinition:
			if (declaringNode == null)
				declaringNode= selectedNode;
			break;
		default:
			return null;
	}

	String annotationNameLabel= annotationToAdd;
	int lastDot= annotationToAdd.lastIndexOf('.');
	if (lastDot != -1)
		annotationNameLabel= annotationToAdd.substring(lastDot + 1);
	annotationNameLabel= BasicElementLabels.getJavaElementName(annotationNameLabel);

	if (declaringNode instanceof MethodDeclaration) {
		// complaint is in signature of this method
		MethodDeclaration declaration= (MethodDeclaration) declaringNode;
		switch (problem.getProblemId()) {
			case IProblem.IllegalDefinitionToNonNullParameter:
			case IProblem.IllegalRedefinitionToNonNullParameter:
				return createChangeOverriddenParameterOperation(compilationUnit, cu, declaration, selectedNode, allowRemove, annotationToAdd, annotationToRemove, annotationNameLabel);
			case IProblem.IllegalReturnNullityRedefinition:
				if (hasNullAnnotation(declaration)) { // don't adjust super if local has no explicit annotation (?)
					return createChangeOverriddenReturnOperation(compilationUnit, cu, declaration, allowRemove, annotationToAdd, annotationToRemove, annotationNameLabel);
				}
		}
	}
	return null;
}
 
Example 19
Source File: StringFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private StringFix(String name, CompilationUnit compilationUnit, TextEditGroup[] groups) {
	fName= name;
	fCompilationUnit= (ICompilationUnit)compilationUnit.getJavaElement();
	fEditGroups= groups;
}
 
Example 20
Source File: UnimplementedCodeFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public static IProposableFix createAddUnimplementedMethodsFix(final CompilationUnit root, IProblemLocation problem) {
	ASTNode typeNode= getSelectedTypeNode(root, problem);
	if (typeNode == null)
		return null;

	if (isTypeBindingNull(typeNode))
		return null;

	AddUnimplementedMethodsOperation operation= new AddUnimplementedMethodsOperation(typeNode);
	if (operation.getMethodsToImplement().length > 0) {
		return new UnimplementedCodeFix(CorrectionMessages.UnimplementedMethodsCorrectionProposal_description, root, new CompilationUnitRewriteOperation[] { operation });
	} else {
		return new IProposableFix() {
			public CompilationUnitChange createChange(IProgressMonitor progressMonitor) throws CoreException {
				CompilationUnitChange change= new CompilationUnitChange(CorrectionMessages.UnimplementedMethodsCorrectionProposal_description, (ICompilationUnit) root.getJavaElement()) {
					@Override
					public Change perform(IProgressMonitor pm) throws CoreException {
						Shell shell= PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
						String dialogTitle= CorrectionMessages.UnimplementedMethodsCorrectionProposal_description;
						IStatus status= getStatus();
						ErrorDialog.openError(shell, dialogTitle, CorrectionMessages.UnimplementedCodeFix_DependenciesErrorMessage, status);

						return new NullChange();
					}
				};
				change.setEdit(new MultiTextEdit());
				return change;
			}

			public String getAdditionalProposalInfo() {
				return new String();
			}

			public String getDisplayString() {
				return CorrectionMessages.UnimplementedMethodsCorrectionProposal_description;
			}

			public IStatus getStatus() {
				return new Status(IStatus.ERROR, JavaUI.ID_PLUGIN, CorrectionMessages.UnimplementedCodeFix_DependenciesStatusMessage);
			}
		};
	}
}