use of org.eclipse.jdt.core.IJavaProject in project che by eclipse.
the class QuickAssistProcessor method getConvertEnhancedForLoopProposal.
private static boolean getConvertEnhancedForLoopProposal(IInvocationContext context, ASTNode node, Collection<ICommandAccess> resultingCollections) {
EnhancedForStatement enhancedForStatement = getEnclosingHeader(node, EnhancedForStatement.class, EnhancedForStatement.PARAMETER_PROPERTY, EnhancedForStatement.EXPRESSION_PROPERTY);
if (enhancedForStatement == null) {
return false;
}
SingleVariableDeclaration parameter = enhancedForStatement.getParameter();
IVariableBinding parameterBinding = parameter.resolveBinding();
if (parameterBinding == null) {
return false;
}
Expression initializer = enhancedForStatement.getExpression();
ITypeBinding initializerTypeBinding = initializer.resolveTypeBinding();
if (initializerTypeBinding == null) {
return false;
}
if (resultingCollections == null) {
return true;
}
Statement topLabelStatement = enhancedForStatement;
while (topLabelStatement.getLocationInParent() == LabeledStatement.BODY_PROPERTY) {
topLabelStatement = (Statement) topLabelStatement.getParent();
}
IJavaProject project = context.getCompilationUnit().getJavaProject();
AST ast = node.getAST();
Statement enhancedForBody = enhancedForStatement.getBody();
Collection<String> usedVarNames = Arrays.asList(ASTResolving.getUsedVariableNames(enhancedForBody));
boolean initializerIsArray = initializerTypeBinding.isArray();
//$NON-NLS-1$
ITypeBinding initializerListType = Bindings.findTypeInHierarchy(initializerTypeBinding, "java.util.List");
//$NON-NLS-1$
ITypeBinding initializerIterableType = Bindings.findTypeInHierarchy(initializerTypeBinding, "java.lang.Iterable");
if (initializerIterableType != null) {
String label = CorrectionMessages.QuickAssistProcessor_convert_to_iterator_for_loop;
Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
//$NON-NLS-1$
String iterNameKey = "iterName";
ASTRewrite rewrite = ASTRewrite.create(ast);
LinkedCorrectionProposal proposal = new LinkedCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.CONVERT_TO_ITERATOR_FOR_LOOP, image);
// convert 'for' statement
ForStatement forStatement = ast.newForStatement();
// create initializer
MethodInvocation iterInitializer = ast.newMethodInvocation();
//$NON-NLS-1$
iterInitializer.setName(ast.newSimpleName("iterator"));
ImportRewrite imports = proposal.createImportRewrite(context.getASTRoot());
ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(node, imports);
//$NON-NLS-1$
Type iterType = ast.newSimpleType(ast.newName(imports.addImport("java.util.Iterator", importRewriteContext)));
if (initializerIterableType.getTypeArguments().length == 1) {
Type iterTypeArgument = imports.addImport(Bindings.normalizeTypeBinding(initializerIterableType.getTypeArguments()[0]), ast, importRewriteContext);
ParameterizedType parameterizedIterType = ast.newParameterizedType(iterType);
parameterizedIterType.typeArguments().add(iterTypeArgument);
iterType = parameterizedIterType;
}
String[] iterNames = StubUtility.getVariableNameSuggestions(NamingConventions.VK_LOCAL, project, iterType, iterInitializer, usedVarNames);
String iterName = iterNames[0];
SimpleName initializerIterName = ast.newSimpleName(iterName);
VariableDeclarationFragment iterFragment = ast.newVariableDeclarationFragment();
iterFragment.setName(initializerIterName);
proposal.addLinkedPosition(rewrite.track(initializerIterName), 0, iterNameKey);
for (int i = 0; i < iterNames.length; i++) {
proposal.addLinkedPositionProposal(iterNameKey, iterNames[i], null);
}
Expression initializerExpression = (Expression) rewrite.createCopyTarget(initializer);
iterInitializer.setExpression(initializerExpression);
iterFragment.setInitializer(iterInitializer);
VariableDeclarationExpression iterVariable = ast.newVariableDeclarationExpression(iterFragment);
iterVariable.setType(iterType);
forStatement.initializers().add(iterVariable);
// create condition
MethodInvocation condition = ast.newMethodInvocation();
//$NON-NLS-1$
condition.setName(ast.newSimpleName("hasNext"));
SimpleName conditionExpression = ast.newSimpleName(iterName);
proposal.addLinkedPosition(rewrite.track(conditionExpression), LinkedPositionGroup.NO_STOP, iterNameKey);
condition.setExpression(conditionExpression);
forStatement.setExpression(condition);
// create 'for' body element variable
VariableDeclarationFragment elementFragment = ast.newVariableDeclarationFragment();
elementFragment.extraDimensions().addAll(DimensionRewrite.copyDimensions(parameter.extraDimensions(), rewrite));
elementFragment.setName((SimpleName) rewrite.createCopyTarget(parameter.getName()));
SimpleName elementIterName = ast.newSimpleName(iterName);
proposal.addLinkedPosition(rewrite.track(elementIterName), LinkedPositionGroup.NO_STOP, iterNameKey);
MethodInvocation getMethodInvocation = ast.newMethodInvocation();
//$NON-NLS-1$
getMethodInvocation.setName(ast.newSimpleName("next"));
getMethodInvocation.setExpression(elementIterName);
elementFragment.setInitializer(getMethodInvocation);
VariableDeclarationStatement elementVariable = ast.newVariableDeclarationStatement(elementFragment);
ModifierRewrite.create(rewrite, elementVariable).copyAllModifiers(parameter, null);
elementVariable.setType((Type) rewrite.createCopyTarget(parameter.getType()));
Block newBody = ast.newBlock();
List<Statement> statements = newBody.statements();
statements.add(elementVariable);
if (enhancedForBody instanceof Block) {
List<Statement> oldStatements = ((Block) enhancedForBody).statements();
if (oldStatements.size() > 0) {
ListRewrite statementsRewrite = rewrite.getListRewrite(enhancedForBody, Block.STATEMENTS_PROPERTY);
Statement oldStatementsCopy = (Statement) statementsRewrite.createCopyTarget(oldStatements.get(0), oldStatements.get(oldStatements.size() - 1));
statements.add(oldStatementsCopy);
}
} else {
statements.add((Statement) rewrite.createCopyTarget(enhancedForBody));
}
forStatement.setBody(newBody);
rewrite.replace(enhancedForStatement, forStatement, null);
resultingCollections.add(proposal);
}
if (initializerIsArray || initializerListType != null) {
String label = CorrectionMessages.QuickAssistProcessor_convert_to_indexed_for_loop;
Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
//$NON-NLS-1$
String varNameKey = "varName";
//$NON-NLS-1$
String indexNameKey = "indexName";
ASTRewrite rewrite = ASTRewrite.create(ast);
LinkedCorrectionProposal proposal = new LinkedCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.CONVERT_TO_INDEXED_FOR_LOOP, image);
// create temp variable from initializer if necessary
String varName;
boolean varNameGenerated;
if (initializer instanceof SimpleName) {
varName = ((SimpleName) initializer).getIdentifier();
varNameGenerated = false;
} else {
VariableDeclarationFragment varFragment = ast.newVariableDeclarationFragment();
String[] varNames = StubUtility.getVariableNameSuggestions(NamingConventions.VK_LOCAL, project, initializerTypeBinding, initializer, usedVarNames);
varName = varNames[0];
usedVarNames = new ArrayList<String>(usedVarNames);
usedVarNames.add(varName);
varNameGenerated = true;
SimpleName varNameNode = ast.newSimpleName(varName);
varFragment.setName(varNameNode);
proposal.addLinkedPosition(rewrite.track(varNameNode), 0, varNameKey);
for (int i = 0; i < varNames.length; i++) {
proposal.addLinkedPositionProposal(varNameKey, varNames[i], null);
}
varFragment.setInitializer((Expression) rewrite.createCopyTarget(initializer));
VariableDeclarationStatement varDeclaration = ast.newVariableDeclarationStatement(varFragment);
Type varType;
if (initializerIsArray) {
Type copiedType = DimensionRewrite.copyTypeAndAddDimensions(parameter.getType(), parameter.extraDimensions(), rewrite);
varType = ASTNodeFactory.newArrayType(copiedType);
} else {
ImportRewrite imports = proposal.createImportRewrite(context.getASTRoot());
ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(node, imports);
varType = imports.addImport(Bindings.normalizeForDeclarationUse(initializerTypeBinding, ast), ast, importRewriteContext);
}
varDeclaration.setType(varType);
if (!(topLabelStatement.getParent() instanceof Block)) {
Block block = ast.newBlock();
List<Statement> statements = block.statements();
statements.add(varDeclaration);
statements.add((Statement) rewrite.createCopyTarget(topLabelStatement));
rewrite.replace(topLabelStatement, block, null);
} else {
rewrite.getListRewrite(topLabelStatement.getParent(), Block.STATEMENTS_PROPERTY).insertBefore(varDeclaration, topLabelStatement, null);
}
}
// convert 'for' statement
ForStatement forStatement = ast.newForStatement();
// create initializer
VariableDeclarationFragment indexFragment = ast.newVariableDeclarationFragment();
NumberLiteral indexInitializer = ast.newNumberLiteral();
indexFragment.setInitializer(indexInitializer);
PrimitiveType indexType = ast.newPrimitiveType(PrimitiveType.INT);
String[] indexNames = StubUtility.getVariableNameSuggestions(NamingConventions.VK_LOCAL, project, indexType, indexInitializer, usedVarNames);
String indexName = indexNames[0];
SimpleName initializerIndexName = ast.newSimpleName(indexName);
indexFragment.setName(initializerIndexName);
proposal.addLinkedPosition(rewrite.track(initializerIndexName), 0, indexNameKey);
for (int i = 0; i < indexNames.length; i++) {
proposal.addLinkedPositionProposal(indexNameKey, indexNames[i], null);
}
VariableDeclarationExpression indexVariable = ast.newVariableDeclarationExpression(indexFragment);
indexVariable.setType(indexType);
forStatement.initializers().add(indexVariable);
// create condition
InfixExpression condition = ast.newInfixExpression();
condition.setOperator(InfixExpression.Operator.LESS);
SimpleName conditionLeft = ast.newSimpleName(indexName);
proposal.addLinkedPosition(rewrite.track(conditionLeft), LinkedPositionGroup.NO_STOP, indexNameKey);
condition.setLeftOperand(conditionLeft);
SimpleName conditionRightName = ast.newSimpleName(varName);
if (varNameGenerated) {
proposal.addLinkedPosition(rewrite.track(conditionRightName), LinkedPositionGroup.NO_STOP, varNameKey);
}
Expression conditionRight;
if (initializerIsArray) {
//$NON-NLS-1$
conditionRight = ast.newQualifiedName(conditionRightName, ast.newSimpleName("length"));
} else {
MethodInvocation sizeMethodInvocation = ast.newMethodInvocation();
//$NON-NLS-1$
sizeMethodInvocation.setName(ast.newSimpleName("size"));
sizeMethodInvocation.setExpression(conditionRightName);
conditionRight = sizeMethodInvocation;
}
condition.setRightOperand(conditionRight);
forStatement.setExpression(condition);
// create updater
SimpleName indexUpdaterName = ast.newSimpleName(indexName);
proposal.addLinkedPosition(rewrite.track(indexUpdaterName), LinkedPositionGroup.NO_STOP, indexNameKey);
PostfixExpression indexUpdater = ast.newPostfixExpression();
indexUpdater.setOperator(PostfixExpression.Operator.INCREMENT);
indexUpdater.setOperand(indexUpdaterName);
forStatement.updaters().add(indexUpdater);
// create 'for' body element variable
VariableDeclarationFragment elementFragment = ast.newVariableDeclarationFragment();
elementFragment.extraDimensions().addAll(DimensionRewrite.copyDimensions(parameter.extraDimensions(), rewrite));
elementFragment.setName((SimpleName) rewrite.createCopyTarget(parameter.getName()));
SimpleName elementVarName = ast.newSimpleName(varName);
if (varNameGenerated) {
proposal.addLinkedPosition(rewrite.track(elementVarName), LinkedPositionGroup.NO_STOP, varNameKey);
}
SimpleName elementIndexName = ast.newSimpleName(indexName);
proposal.addLinkedPosition(rewrite.track(elementIndexName), LinkedPositionGroup.NO_STOP, indexNameKey);
Expression elementAccess;
if (initializerIsArray) {
ArrayAccess elementArrayAccess = ast.newArrayAccess();
elementArrayAccess.setArray(elementVarName);
elementArrayAccess.setIndex(elementIndexName);
elementAccess = elementArrayAccess;
} else {
MethodInvocation getMethodInvocation = ast.newMethodInvocation();
//$NON-NLS-1$
getMethodInvocation.setName(ast.newSimpleName("get"));
getMethodInvocation.setExpression(elementVarName);
getMethodInvocation.arguments().add(elementIndexName);
elementAccess = getMethodInvocation;
}
elementFragment.setInitializer(elementAccess);
VariableDeclarationStatement elementVariable = ast.newVariableDeclarationStatement(elementFragment);
ModifierRewrite.create(rewrite, elementVariable).copyAllModifiers(parameter, null);
elementVariable.setType((Type) rewrite.createCopyTarget(parameter.getType()));
Block newBody = ast.newBlock();
List<Statement> statements = newBody.statements();
statements.add(elementVariable);
if (enhancedForBody instanceof Block) {
List<Statement> oldStatements = ((Block) enhancedForBody).statements();
if (oldStatements.size() > 0) {
ListRewrite statementsRewrite = rewrite.getListRewrite(enhancedForBody, Block.STATEMENTS_PROPERTY);
Statement oldStatementsCopy = (Statement) statementsRewrite.createCopyTarget(oldStatements.get(0), oldStatements.get(oldStatements.size() - 1));
statements.add(oldStatementsCopy);
}
} else {
statements.add((Statement) rewrite.createCopyTarget(enhancedForBody));
}
forStatement.setBody(newBody);
rewrite.replace(enhancedForStatement, forStatement, null);
resultingCollections.add(proposal);
}
return true;
}
use of org.eclipse.jdt.core.IJavaProject in project che by eclipse.
the class QuickFixProcessor method process.
private void process(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) throws CoreException {
int id = problem.getProblemId();
if (id == 0) {
// no proposals for none-problem locations
return;
}
switch(id) {
case IProblem.UnterminatedString:
String quoteLabel = CorrectionMessages.JavaCorrectionProcessor_addquote_description;
//$NON-NLS-1$
int pos = moveBack(problem.getOffset() + problem.getLength(), problem.getOffset(), "\n\r", context.getCompilationUnit());
//$NON-NLS-1$
proposals.add(new ReplaceCorrectionProposal(quoteLabel, context.getCompilationUnit(), pos, 0, "\"", IProposalRelevance.ADD_QUOTE));
break;
case IProblem.UnusedImport:
case IProblem.DuplicateImport:
case IProblem.CannotImportPackage:
case IProblem.ConflictingImport:
ReorgCorrectionsSubProcessor.removeImportStatementProposals(context, problem, proposals);
break;
case IProblem.ImportNotFound:
ReorgCorrectionsSubProcessor.importNotFoundProposals(context, problem, proposals);
ReorgCorrectionsSubProcessor.removeImportStatementProposals(context, problem, proposals);
break;
case IProblem.UndefinedMethod:
UnresolvedElementsSubProcessor.getMethodProposals(context, problem, false, proposals);
break;
case IProblem.UndefinedConstructor:
UnresolvedElementsSubProcessor.getConstructorProposals(context, problem, proposals);
break;
case IProblem.UndefinedAnnotationMember:
UnresolvedElementsSubProcessor.getAnnotationMemberProposals(context, problem, proposals);
break;
case IProblem.ParameterMismatch:
UnresolvedElementsSubProcessor.getMethodProposals(context, problem, true, proposals);
break;
case IProblem.MethodButWithConstructorName:
ReturnTypeSubProcessor.addMethodWithConstrNameProposals(context, problem, proposals);
break;
case IProblem.UndefinedField:
case IProblem.UndefinedName:
case IProblem.UnresolvedVariable:
UnresolvedElementsSubProcessor.getVariableProposals(context, problem, null, proposals);
break;
case IProblem.AmbiguousType:
case IProblem.JavadocAmbiguousType:
UnresolvedElementsSubProcessor.getAmbiguosTypeReferenceProposals(context, problem, proposals);
break;
case IProblem.PublicClassMustMatchFileName:
ReorgCorrectionsSubProcessor.getWrongTypeNameProposals(context, problem, proposals);
break;
case IProblem.PackageIsNotExpectedPackage:
ReorgCorrectionsSubProcessor.getWrongPackageDeclNameProposals(context, problem, proposals);
break;
case IProblem.UndefinedType:
case IProblem.JavadocUndefinedType:
UnresolvedElementsSubProcessor.getTypeProposals(context, problem, proposals);
break;
case IProblem.TypeMismatch:
case IProblem.ReturnTypeMismatch:
TypeMismatchSubProcessor.addTypeMismatchProposals(context, problem, proposals);
break;
case IProblem.IncompatibleTypesInForeach:
TypeMismatchSubProcessor.addTypeMismatchInForEachProposals(context, problem, proposals);
break;
case IProblem.IncompatibleReturnType:
TypeMismatchSubProcessor.addIncompatibleReturnTypeProposals(context, problem, proposals);
break;
case IProblem.IncompatibleExceptionInThrowsClause:
TypeMismatchSubProcessor.addIncompatibleThrowsProposals(context, problem, proposals);
break;
case IProblem.UnhandledException:
case IProblem.UnhandledExceptionOnAutoClose:
LocalCorrectionsSubProcessor.addUncaughtExceptionProposals(context, problem, proposals);
break;
case IProblem.UnreachableCatch:
case IProblem.InvalidCatchBlockSequence:
case IProblem.InvalidUnionTypeReferenceSequence:
LocalCorrectionsSubProcessor.addUnreachableCatchProposals(context, problem, proposals);
break;
case IProblem.RedundantSuperinterface:
LocalCorrectionsSubProcessor.addRedundantSuperInterfaceProposal(context, problem, proposals);
break;
case IProblem.VoidMethodReturnsValue:
ReturnTypeSubProcessor.addVoidMethodReturnsProposals(context, problem, proposals);
break;
case IProblem.MethodReturnsVoid:
ReturnTypeSubProcessor.addMethodRetunsVoidProposals(context, problem, proposals);
break;
case IProblem.MissingReturnType:
ReturnTypeSubProcessor.addMissingReturnTypeProposals(context, problem, proposals);
break;
case IProblem.ShouldReturnValue:
case IProblem.ShouldReturnValueHintMissingDefault:
ReturnTypeSubProcessor.addMissingReturnStatementProposals(context, problem, proposals);
break;
case IProblem.NonExternalizedStringLiteral:
LocalCorrectionsSubProcessor.addNLSProposals(context, problem, proposals);
break;
case IProblem.UnnecessaryNLSTag:
LocalCorrectionsSubProcessor.getUnnecessaryNLSTagProposals(context, problem, proposals);
break;
case IProblem.NonStaticAccessToStaticField:
case IProblem.NonStaticAccessToStaticMethod:
case IProblem.NonStaticOrAlienTypeReceiver:
case IProblem.IndirectAccessToStaticField:
case IProblem.IndirectAccessToStaticMethod:
LocalCorrectionsSubProcessor.addCorrectAccessToStaticProposals(context, problem, proposals);
break;
case IProblem.StaticMethodRequested:
case IProblem.NonStaticFieldFromStaticInvocation:
case IProblem.InstanceMethodDuringConstructorInvocation:
case IProblem.InstanceFieldDuringConstructorInvocation:
ModifierCorrectionSubProcessor.addNonAccessibleReferenceProposal(context, problem, proposals, ModifierCorrectionSubProcessor.TO_STATIC, IProposalRelevance.CHANGE_MODIFIER_TO_STATIC);
break;
case IProblem.NonBlankFinalLocalAssignment:
case IProblem.DuplicateFinalLocalInitialization:
case IProblem.FinalFieldAssignment:
case IProblem.DuplicateBlankFinalFieldInitialization:
case IProblem.AnonymousClassCannotExtendFinalClass:
case IProblem.ClassExtendFinalClass:
ModifierCorrectionSubProcessor.addNonAccessibleReferenceProposal(context, problem, proposals, ModifierCorrectionSubProcessor.TO_NON_FINAL, IProposalRelevance.REMOVE_FINAL_MODIFIER);
break;
case IProblem.InheritedMethodReducesVisibility:
case IProblem.MethodReducesVisibility:
case IProblem.OverridingNonVisibleMethod:
ModifierCorrectionSubProcessor.addChangeOverriddenModifierProposal(context, problem, proposals, ModifierCorrectionSubProcessor.TO_VISIBLE);
break;
case IProblem.FinalMethodCannotBeOverridden:
ModifierCorrectionSubProcessor.addChangeOverriddenModifierProposal(context, problem, proposals, ModifierCorrectionSubProcessor.TO_NON_FINAL);
break;
case IProblem.CannotOverrideAStaticMethodWithAnInstanceMethod:
ModifierCorrectionSubProcessor.addChangeOverriddenModifierProposal(context, problem, proposals, ModifierCorrectionSubProcessor.TO_NON_STATIC);
break;
case IProblem.CannotHideAnInstanceMethodWithAStaticMethod:
case IProblem.IllegalModifierForInterfaceMethod:
case IProblem.IllegalModifierForInterface:
case IProblem.IllegalModifierForClass:
case IProblem.IllegalModifierForInterfaceField:
case IProblem.UnexpectedStaticModifierForField:
case IProblem.IllegalModifierCombinationFinalVolatileForField:
case IProblem.IllegalModifierForMemberInterface:
case IProblem.IllegalModifierForMemberClass:
case IProblem.IllegalModifierForLocalClass:
case IProblem.IllegalModifierForArgument:
case IProblem.IllegalModifierForField:
case IProblem.IllegalModifierForMethod:
case IProblem.IllegalModifierForConstructor:
case IProblem.IllegalModifierForVariable:
case IProblem.IllegalModifierForEnum:
case IProblem.IllegalModifierForEnumConstant:
case IProblem.IllegalModifierForEnumConstructor:
case IProblem.IllegalModifierForMemberEnum:
case IProblem.IllegalVisibilityModifierForInterfaceMemberType:
case IProblem.UnexpectedStaticModifierForMethod:
case IProblem.IllegalModifierForInterfaceMethod18:
ModifierCorrectionSubProcessor.addRemoveInvalidModifiersProposal(context, problem, proposals, IProposalRelevance.REMOVE_INVALID_MODIFIERS);
break;
case IProblem.NotVisibleField:
GetterSetterCorrectionSubProcessor.addGetterSetterProposal(context, problem, proposals, IProposalRelevance.GETTER_SETTER_NOT_VISIBLE_FIELD);
ModifierCorrectionSubProcessor.addNonAccessibleReferenceProposal(context, problem, proposals, ModifierCorrectionSubProcessor.TO_VISIBLE, IProposalRelevance.CHANGE_VISIBILITY);
break;
case IProblem.NotVisibleMethod:
case IProblem.NotVisibleConstructor:
case IProblem.NotVisibleType:
case IProblem.JavadocNotVisibleType:
ModifierCorrectionSubProcessor.addNonAccessibleReferenceProposal(context, problem, proposals, ModifierCorrectionSubProcessor.TO_VISIBLE, IProposalRelevance.CHANGE_VISIBILITY);
break;
case IProblem.BodyForAbstractMethod:
case IProblem.AbstractMethodInAbstractClass:
case IProblem.AbstractMethodInEnum:
case IProblem.EnumAbstractMethodMustBeImplemented:
ModifierCorrectionSubProcessor.addAbstractMethodProposals(context, problem, proposals);
break;
case IProblem.AbstractMethodsInConcreteClass:
ModifierCorrectionSubProcessor.addAbstractTypeProposals(context, problem, proposals);
break;
case IProblem.AbstractMethodMustBeImplemented:
case IProblem.EnumConstantMustImplementAbstractMethod:
LocalCorrectionsSubProcessor.addUnimplementedMethodsProposals(context, problem, proposals);
break;
case IProblem.ShouldImplementHashcode:
LocalCorrectionsSubProcessor.addMissingHashCodeProposals(context, problem, proposals);
break;
case IProblem.MissingValueForAnnotationMember:
LocalCorrectionsSubProcessor.addValueForAnnotationProposals(context, problem, proposals);
break;
case IProblem.BodyForNativeMethod:
ModifierCorrectionSubProcessor.addNativeMethodProposals(context, problem, proposals);
break;
case IProblem.MethodRequiresBody:
ModifierCorrectionSubProcessor.addMethodRequiresBodyProposals(context, problem, proposals);
break;
case IProblem.OuterLocalMustBeFinal:
ModifierCorrectionSubProcessor.addNonFinalLocalProposal(context, problem, proposals);
break;
case IProblem.UninitializedLocalVariable:
case IProblem.UninitializedLocalVariableHintMissingDefault:
LocalCorrectionsSubProcessor.addUninitializedLocalVariableProposal(context, problem, proposals);
break;
case IProblem.UnhandledExceptionInDefaultConstructor:
case IProblem.UndefinedConstructorInDefaultConstructor:
case IProblem.NotVisibleConstructorInDefaultConstructor:
LocalCorrectionsSubProcessor.addConstructorFromSuperclassProposal(context, problem, proposals);
break;
case IProblem.UnusedPrivateMethod:
case IProblem.UnusedPrivateConstructor:
case IProblem.UnusedPrivateField:
case IProblem.UnusedPrivateType:
case IProblem.LocalVariableIsNeverUsed:
case IProblem.ArgumentIsNeverUsed:
LocalCorrectionsSubProcessor.addUnusedMemberProposal(context, problem, proposals);
break;
case IProblem.NeedToEmulateFieldReadAccess:
case IProblem.NeedToEmulateFieldWriteAccess:
case IProblem.NeedToEmulateMethodAccess:
case IProblem.NeedToEmulateConstructorAccess:
ModifierCorrectionSubProcessor.addNonAccessibleReferenceProposal(context, problem, proposals, ModifierCorrectionSubProcessor.TO_NON_PRIVATE, IProposalRelevance.CHANGE_VISIBILITY_TO_NON_PRIVATE);
break;
case IProblem.SuperfluousSemicolon:
LocalCorrectionsSubProcessor.addSuperfluousSemicolonProposal(context, problem, proposals);
break;
case IProblem.UnnecessaryCast:
LocalCorrectionsSubProcessor.addUnnecessaryCastProposal(context, problem, proposals);
break;
case IProblem.UnnecessaryInstanceof:
LocalCorrectionsSubProcessor.addUnnecessaryInstanceofProposal(context, problem, proposals);
break;
case IProblem.UnusedMethodDeclaredThrownException:
case IProblem.UnusedConstructorDeclaredThrownException:
LocalCorrectionsSubProcessor.addUnnecessaryThrownExceptionProposal(context, problem, proposals);
break;
case IProblem.UnqualifiedFieldAccess:
GetterSetterCorrectionSubProcessor.addGetterSetterProposal(context, problem, proposals, IProposalRelevance.GETTER_SETTER_UNQUALIFIED_FIELD_ACCESS);
LocalCorrectionsSubProcessor.addUnqualifiedFieldAccessProposal(context, problem, proposals);
break;
case IProblem.Task:
proposals.add(new TaskMarkerProposal(context.getCompilationUnit(), problem, 10));
break;
case IProblem.JavadocMissing:
JavadocTagsSubProcessor.getMissingJavadocCommentProposals(context, problem, proposals);
break;
case IProblem.JavadocMissingParamTag:
case IProblem.JavadocMissingReturnTag:
case IProblem.JavadocMissingThrowsTag:
JavadocTagsSubProcessor.getMissingJavadocTagProposals(context, problem, proposals);
break;
case IProblem.JavadocInvalidThrowsClassName:
case IProblem.JavadocDuplicateThrowsClassName:
case IProblem.JavadocDuplicateReturnTag:
case IProblem.JavadocDuplicateParamName:
case IProblem.JavadocInvalidParamName:
case IProblem.JavadocUnexpectedTag:
case IProblem.JavadocInvalidTag:
JavadocTagsSubProcessor.getRemoveJavadocTagProposals(context, problem, proposals);
break;
case IProblem.JavadocInvalidMemberTypeQualification:
JavadocTagsSubProcessor.getInvalidQualificationProposals(context, problem, proposals);
break;
case IProblem.LocalVariableHidingLocalVariable:
case IProblem.LocalVariableHidingField:
case IProblem.FieldHidingLocalVariable:
case IProblem.FieldHidingField:
case IProblem.ArgumentHidingLocalVariable:
case IProblem.ArgumentHidingField:
case IProblem.UseAssertAsAnIdentifier:
case IProblem.UseEnumAsAnIdentifier:
case IProblem.RedefinedLocal:
case IProblem.RedefinedArgument:
case IProblem.DuplicateField:
case IProblem.DuplicateMethod:
case IProblem.DuplicateTypeVariable:
case IProblem.DuplicateNestedType:
LocalCorrectionsSubProcessor.addInvalidVariableNameProposals(context, problem, proposals);
break;
case IProblem.NoMessageSendOnArrayType:
UnresolvedElementsSubProcessor.getArrayAccessProposals(context, problem, proposals);
break;
case IProblem.InvalidOperator:
LocalCorrectionsSubProcessor.getInvalidOperatorProposals(context, problem, proposals);
break;
case IProblem.MissingSerialVersion:
SerialVersionSubProcessor.getSerialVersionProposals(context, problem, proposals);
break;
case IProblem.UnnecessaryElse:
LocalCorrectionsSubProcessor.getUnnecessaryElseProposals(context, problem, proposals);
break;
case IProblem.SuperclassMustBeAClass:
LocalCorrectionsSubProcessor.getInterfaceExtendsClassProposals(context, problem, proposals);
break;
case IProblem.CodeCannotBeReached:
case IProblem.DeadCode:
LocalCorrectionsSubProcessor.getUnreachableCodeProposals(context, problem, proposals);
break;
case IProblem.InvalidUsageOfTypeParameters:
case IProblem.InvalidUsageOfStaticImports:
case IProblem.InvalidUsageOfForeachStatements:
case IProblem.InvalidUsageOfTypeArguments:
case IProblem.InvalidUsageOfEnumDeclarations:
case IProblem.InvalidUsageOfVarargs:
case IProblem.InvalidUsageOfAnnotations:
case IProblem.InvalidUsageOfAnnotationDeclarations:
ReorgCorrectionsSubProcessor.getNeedHigherComplianceProposals(context, problem, proposals, JavaCore.VERSION_1_5);
break;
case IProblem.DiamondNotBelow17:
TypeArgumentMismatchSubProcessor.getInferDiamondArgumentsProposal(context, problem, proposals);
//$FALL-THROUGH$
case IProblem.AutoManagedResourceNotBelow17:
case IProblem.MultiCatchNotBelow17:
case IProblem.PolymorphicMethodNotBelow17:
case IProblem.BinaryLiteralNotBelow17:
case IProblem.UnderscoresInLiteralsNotBelow17:
case IProblem.SwitchOnStringsNotBelow17:
ReorgCorrectionsSubProcessor.getNeedHigherComplianceProposals(context, problem, proposals, JavaCore.VERSION_1_7);
break;
case IProblem.ExplicitThisParameterNotBelow18:
case IProblem.DefaultMethodNotBelow18:
case IProblem.StaticInterfaceMethodNotBelow18:
case IProblem.LambdaExpressionNotBelow18:
case IProblem.MethodReferenceNotBelow18:
case IProblem.ConstructorReferenceNotBelow18:
case IProblem.IntersectionCastNotBelow18:
case IProblem.InvalidUsageOfTypeAnnotations:
ReorgCorrectionsSubProcessor.getNeedHigherComplianceProposals(context, problem, proposals, JavaCore.VERSION_1_8);
break;
case IProblem.NonGenericType:
TypeArgumentMismatchSubProcessor.removeMismatchedArguments(context, problem, proposals);
break;
case IProblem.MissingOverrideAnnotation:
case IProblem.MissingOverrideAnnotationForInterfaceMethodImplementation:
ModifierCorrectionSubProcessor.addOverrideAnnotationProposal(context, problem, proposals);
break;
case IProblem.MethodMustOverride:
case IProblem.MethodMustOverrideOrImplement:
ModifierCorrectionSubProcessor.removeOverrideAnnotationProposal(context, problem, proposals);
break;
case IProblem.FieldMissingDeprecatedAnnotation:
case IProblem.MethodMissingDeprecatedAnnotation:
case IProblem.TypeMissingDeprecatedAnnotation:
ModifierCorrectionSubProcessor.addDeprecatedAnnotationProposal(context, problem, proposals);
break;
case IProblem.OverridingDeprecatedMethod:
ModifierCorrectionSubProcessor.addOverridingDeprecatedMethodProposal(context, problem, proposals);
break;
case IProblem.IsClassPathCorrect:
ReorgCorrectionsSubProcessor.getIncorrectBuildPathProposals(context, problem, proposals);
break;
case IProblem.ForbiddenReference:
case IProblem.DiscouragedReference:
ReorgCorrectionsSubProcessor.getAccessRulesProposals(context, problem, proposals);
break;
case IProblem.AssignmentHasNoEffect:
LocalCorrectionsSubProcessor.getAssignmentHasNoEffectProposals(context, problem, proposals);
break;
case IProblem.UnsafeTypeConversion:
case IProblem.RawTypeReference:
case IProblem.UnsafeRawMethodInvocation:
LocalCorrectionsSubProcessor.addDeprecatedFieldsToMethodsProposals(context, problem, proposals);
//$FALL-THROUGH$
case IProblem.UnsafeElementTypeConversion:
LocalCorrectionsSubProcessor.addTypePrametersToRawTypeReference(context, problem, proposals);
break;
case IProblem.RedundantSpecificationOfTypeArguments:
LocalCorrectionsSubProcessor.addRemoveRedundantTypeArgumentsProposals(context, problem, proposals);
break;
case IProblem.FallthroughCase:
LocalCorrectionsSubProcessor.addFallThroughProposals(context, problem, proposals);
break;
case IProblem.UnhandledWarningToken:
SuppressWarningsSubProcessor.addUnknownSuppressWarningProposals(context, problem, proposals);
break;
case IProblem.UnusedWarningToken:
SuppressWarningsSubProcessor.addRemoveUnusedSuppressWarningProposals(context, problem, proposals);
break;
case IProblem.MissingEnumConstantCase:
case IProblem.MissingEnumDefaultCase:
LocalCorrectionsSubProcessor.getMissingEnumConstantCaseProposals(context, problem, proposals);
break;
case IProblem.MissingDefaultCase:
LocalCorrectionsSubProcessor.addMissingDefaultCaseProposal(context, problem, proposals);
break;
case IProblem.MissingEnumConstantCaseDespiteDefault:
LocalCorrectionsSubProcessor.getMissingEnumConstantCaseProposals(context, problem, proposals);
LocalCorrectionsSubProcessor.addCasesOmittedProposals(context, problem, proposals);
break;
case IProblem.MissingSynchronizedModifierInInheritedMethod:
ModifierCorrectionSubProcessor.addSynchronizedMethodProposal(context, problem, proposals);
break;
case IProblem.UnusedObjectAllocation:
LocalCorrectionsSubProcessor.getUnusedObjectAllocationProposals(context, problem, proposals);
break;
case IProblem.MethodCanBeStatic:
case IProblem.MethodCanBePotentiallyStatic:
ModifierCorrectionSubProcessor.addStaticMethodProposal(context, problem, proposals);
break;
case IProblem.PotentialHeapPollutionFromVararg:
VarargsWarningsSubProcessor.addAddSafeVarargsProposals(context, problem, proposals);
break;
case IProblem.UnsafeGenericArrayForVarargs:
VarargsWarningsSubProcessor.addAddSafeVarargsToDeclarationProposals(context, problem, proposals);
break;
case IProblem.SafeVarargsOnFixedArityMethod:
case IProblem.SafeVarargsOnNonFinalInstanceMethod:
VarargsWarningsSubProcessor.addRemoveSafeVarargsProposals(context, problem, proposals);
break;
case IProblem.IllegalReturnNullityRedefinition:
case IProblem.IllegalDefinitionToNonNullParameter:
case IProblem.IllegalRedefinitionToNonNullParameter:
boolean isArgProblem = id != IProblem.IllegalReturnNullityRedefinition;
NullAnnotationsCorrectionProcessor.addNullAnnotationInSignatureProposal(context, problem, proposals, ChangeKind.LOCAL, isArgProblem);
NullAnnotationsCorrectionProcessor.addNullAnnotationInSignatureProposal(context, problem, proposals, ChangeKind.OVERRIDDEN, isArgProblem);
break;
case IProblem.RequiredNonNullButProvidedSpecdNullable:
case IProblem.RequiredNonNullButProvidedUnknown:
NullAnnotationsCorrectionProcessor.addExtractCheckedLocalProposal(context, problem, proposals);
//$FALL-THROUGH$
case IProblem.RequiredNonNullButProvidedNull:
case IProblem.RequiredNonNullButProvidedPotentialNull:
case IProblem.ParameterLackingNonNullAnnotation:
case IProblem.ParameterLackingNullableAnnotation:
NullAnnotationsCorrectionProcessor.addReturnAndArgumentTypeProposal(context, problem, ChangeKind.LOCAL, proposals);
NullAnnotationsCorrectionProcessor.addReturnAndArgumentTypeProposal(context, problem, ChangeKind.TARGET, proposals);
break;
case IProblem.SpecdNonNullLocalVariableComparisonYieldsFalse:
case IProblem.RedundantNullCheckOnSpecdNonNullLocalVariable:
IJavaProject prj = context.getCompilationUnit().getJavaProject();
if (prj != null && JavaCore.ENABLED.equals(prj.getOption(JavaCore.COMPILER_ANNOTATION_NULL_ANALYSIS, true))) {
NullAnnotationsCorrectionProcessor.addReturnAndArgumentTypeProposal(context, problem, ChangeKind.LOCAL, proposals);
}
break;
case IProblem.RedundantNullAnnotation:
case IProblem.RedundantNullDefaultAnnotationPackage:
case IProblem.RedundantNullDefaultAnnotationType:
case IProblem.RedundantNullDefaultAnnotationMethod:
NullAnnotationsCorrectionProcessor.addRemoveRedundantAnnotationProposal(context, problem, proposals);
break;
case IProblem.UnusedTypeParameter:
LocalCorrectionsSubProcessor.addUnusedTypeParameterProposal(context, problem, proposals);
break;
case IProblem.NullableFieldReference:
NullAnnotationsCorrectionProcessor.addExtractCheckedLocalProposal(context, problem, proposals);
break;
case IProblem.ConflictingNullAnnotations:
case IProblem.ConflictingInheritedNullAnnotations:
NullAnnotationsCorrectionProcessor.addReturnAndArgumentTypeProposal(context, problem, ChangeKind.LOCAL, proposals);
NullAnnotationsCorrectionProcessor.addReturnAndArgumentTypeProposal(context, problem, ChangeKind.INVERSE, proposals);
break;
default:
}
if (JavaModelUtil.is50OrHigher(context.getCompilationUnit().getJavaProject())) {
SuppressWarningsSubProcessor.addSuppressWarningsProposals(context, problem, proposals);
}
}
use of org.eclipse.jdt.core.IJavaProject in project che by eclipse.
the class ReorgCorrectionsSubProcessor method getWrongTypeNameProposals.
public static void getWrongTypeNameProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
ICompilationUnit cu = context.getCompilationUnit();
boolean isLinked = cu.getResource().isLinked();
IJavaProject javaProject = cu.getJavaProject();
String sourceLevel = javaProject.getOption(JavaCore.COMPILER_SOURCE, true);
String compliance = javaProject.getOption(JavaCore.COMPILER_COMPLIANCE, true);
CompilationUnit root = context.getASTRoot();
ASTNode coveredNode = problem.getCoveredNode(root);
if (!(coveredNode instanceof SimpleName))
return;
ASTNode parentType = coveredNode.getParent();
if (!(parentType instanceof AbstractTypeDeclaration))
return;
String currTypeName = ((SimpleName) coveredNode).getIdentifier();
String newTypeName = JavaCore.removeJavaLikeExtension(cu.getElementName());
boolean hasOtherPublicTypeBefore = false;
boolean found = false;
List<AbstractTypeDeclaration> types = root.types();
for (int i = 0; i < types.size(); i++) {
AbstractTypeDeclaration curr = types.get(i);
if (parentType != curr) {
if (newTypeName.equals(curr.getName().getIdentifier())) {
return;
}
if (!found && Modifier.isPublic(curr.getModifiers())) {
hasOtherPublicTypeBefore = true;
}
} else {
found = true;
}
}
if (!JavaConventions.validateJavaTypeName(newTypeName, sourceLevel, compliance).matches(IStatus.ERROR)) {
proposals.add(new CorrectMainTypeNameProposal(cu, context, currTypeName, newTypeName, IProposalRelevance.RENAME_TYPE));
}
if (!hasOtherPublicTypeBefore) {
String newCUName = JavaModelUtil.getRenamedCUName(cu, currTypeName);
ICompilationUnit newCU = ((IPackageFragment) (cu.getParent())).getCompilationUnit(newCUName);
if (!newCU.exists() && !isLinked && !JavaConventions.validateCompilationUnitName(newCUName, sourceLevel, compliance).matches(IStatus.ERROR)) {
RenameCompilationUnitChange change = new RenameCompilationUnitChange(cu, newCUName);
// rename CU
String label = Messages.format(CorrectionMessages.ReorgCorrectionsSubProcessor_renamecu_description, BasicElementLabels.getResourceName(newCUName));
proposals.add(new ChangeCorrectionProposal(label, change, IProposalRelevance.RENAME_CU, JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_RENAME)));
}
}
}
use of org.eclipse.jdt.core.IJavaProject in project che by eclipse.
the class AdvancedQuickAssistProcessor method getReplaceIfElseWithConditionalProposals.
private static boolean getReplaceIfElseWithConditionalProposals(IInvocationContext context, ASTNode node, Collection<ICommandAccess> resultingCollections) {
if (!(node instanceof IfStatement)) {
return false;
}
IfStatement ifStatement = (IfStatement) node;
Statement thenStatement = getSingleStatement(ifStatement.getThenStatement());
Statement elseStatement = getSingleStatement(ifStatement.getElseStatement());
if (thenStatement == null || elseStatement == null) {
return false;
}
Expression assigned = null;
Expression thenExpression = null;
Expression elseExpression = null;
ITypeBinding exprBinding = null;
if (thenStatement instanceof ReturnStatement && elseStatement instanceof ReturnStatement) {
thenExpression = ((ReturnStatement) thenStatement).getExpression();
elseExpression = ((ReturnStatement) elseStatement).getExpression();
MethodDeclaration declaration = ASTResolving.findParentMethodDeclaration(node);
if (declaration == null || declaration.isConstructor()) {
return false;
}
exprBinding = declaration.getReturnType2().resolveBinding();
} else if (thenStatement instanceof ExpressionStatement && elseStatement instanceof ExpressionStatement) {
Expression inner1 = ((ExpressionStatement) thenStatement).getExpression();
Expression inner2 = ((ExpressionStatement) elseStatement).getExpression();
if (inner1 instanceof Assignment && inner2 instanceof Assignment) {
Assignment assign1 = (Assignment) inner1;
Assignment assign2 = (Assignment) inner2;
Expression left1 = assign1.getLeftHandSide();
Expression left2 = assign2.getLeftHandSide();
if (left1 instanceof Name && left2 instanceof Name && assign1.getOperator() == assign2.getOperator()) {
IBinding bind1 = ((Name) left1).resolveBinding();
IBinding bind2 = ((Name) left2).resolveBinding();
if (bind1 == bind2 && bind1 instanceof IVariableBinding) {
assigned = left1;
exprBinding = ((IVariableBinding) bind1).getType();
thenExpression = assign1.getRightHandSide();
elseExpression = assign2.getRightHandSide();
}
}
}
}
if (thenExpression == null || elseExpression == null) {
return false;
}
// we could produce quick assist
if (resultingCollections == null) {
return true;
}
//
AST ast = node.getAST();
ASTRewrite rewrite = ASTRewrite.create(ast);
TightSourceRangeComputer sourceRangeComputer = new TightSourceRangeComputer();
sourceRangeComputer.addTightSourceNode(ifStatement);
rewrite.setTargetSourceRangeComputer(sourceRangeComputer);
String label = CorrectionMessages.AdvancedQuickAssistProcessor_replaceIfWithConditional;
Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.REPLACE_IF_ELSE_WITH_CONDITIONAL, image);
// prepare conditional expression
ConditionalExpression conditionalExpression = ast.newConditionalExpression();
Expression conditionCopy = (Expression) rewrite.createCopyTarget(ifStatement.getExpression());
conditionalExpression.setExpression(conditionCopy);
Expression thenCopy = (Expression) rewrite.createCopyTarget(thenExpression);
Expression elseCopy = (Expression) rewrite.createCopyTarget(elseExpression);
IJavaProject project = context.getCompilationUnit().getJavaProject();
if (!JavaModelUtil.is50OrHigher(project)) {
ITypeBinding thenBinding = thenExpression.resolveTypeBinding();
ITypeBinding elseBinding = elseExpression.resolveTypeBinding();
if (thenBinding != null && elseBinding != null && exprBinding != null && !elseBinding.isAssignmentCompatible(thenBinding)) {
CastExpression castException = ast.newCastExpression();
ImportRewrite importRewrite = proposal.createImportRewrite(context.getASTRoot());
ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(node, importRewrite);
castException.setType(importRewrite.addImport(exprBinding, ast, importRewriteContext));
castException.setExpression(elseCopy);
elseCopy = castException;
}
} else if (JavaModelUtil.is17OrHigher(project)) {
addExplicitTypeArgumentsIfNecessary(rewrite, proposal, thenExpression);
addExplicitTypeArgumentsIfNecessary(rewrite, proposal, elseExpression);
}
conditionalExpression.setThenExpression(thenCopy);
conditionalExpression.setElseExpression(elseCopy);
// replace 'if' statement with conditional expression
if (assigned == null) {
ReturnStatement returnStatement = ast.newReturnStatement();
returnStatement.setExpression(conditionalExpression);
rewrite.replace(ifStatement, returnStatement, null);
} else {
Assignment assignment = ast.newAssignment();
assignment.setLeftHandSide((Expression) rewrite.createCopyTarget(assigned));
assignment.setRightHandSide(conditionalExpression);
assignment.setOperator(((Assignment) assigned.getParent()).getOperator());
ExpressionStatement expressionStatement = ast.newExpressionStatement(assignment);
rewrite.replace(ifStatement, expressionStatement, null);
}
// add correction proposal
resultingCollections.add(proposal);
return true;
}
use of org.eclipse.jdt.core.IJavaProject in project che by eclipse.
the class AbstractJavaInitHandler method onProjectInitialized.
@Override
public final void onProjectInitialized(ProjectRegistry registry, FolderEntry projectFolder) throws ServerException, ForbiddenException, ConflictException, NotFoundException {
IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectFolder.getPath().toString());
IJavaProject javaProject = JavaCore.create(project);
initializeClasspath(javaProject);
}
Aggregations