Java Code Examples for org.eclipse.jdt.core.dom.Expression#getNodeType()

The following examples show how to use org.eclipse.jdt.core.dom.Expression#getNodeType() . 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: SnippetFinder.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
static boolean isLeftHandSideOfAssignment(ASTNode node) {
	Assignment assignment = (Assignment) ASTNodes.getParent(node, ASTNode.ASSIGNMENT);
	if (assignment != null) {
		Expression leftHandSide = assignment.getLeftHandSide();
		if (leftHandSide == node) {
			return true;
		}
		if (ASTNodes.isParent(node, leftHandSide)) {
			switch (leftHandSide.getNodeType()) {
				case ASTNode.SIMPLE_NAME:
					return true;
				case ASTNode.FIELD_ACCESS:
					return node == ((FieldAccess) leftHandSide).getName();
				case ASTNode.QUALIFIED_NAME:
					return node == ((QualifiedName) leftHandSide).getName();
				case ASTNode.SUPER_FIELD_ACCESS:
					return node == ((SuperFieldAccess) leftHandSide).getName();
				default:
					return false;
			}
		}
	}
	return false;
}
 
Example 2
Source File: Invocations.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static boolean isResolvedTypeInferredFromExpectedType(Expression invocation) {
	if (invocation == null)
		return false;
	
	switch (invocation.getNodeType()) {
		case ASTNode.METHOD_INVOCATION:
			return ((MethodInvocation) invocation).isResolvedTypeInferredFromExpectedType();
		case ASTNode.SUPER_METHOD_INVOCATION:
			return ((SuperMethodInvocation) invocation).isResolvedTypeInferredFromExpectedType();
		case ASTNode.CLASS_INSTANCE_CREATION:
			return ((ClassInstanceCreation) invocation).isResolvedTypeInferredFromExpectedType();
			
		default:
			return false;
	}
}
 
Example 3
Source File: ExtractTempRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private boolean isLiteralNodeSelected() throws JavaModelException {
	IExpressionFragment fragment= getSelectedExpression();
	if (fragment == null)
		return false;
	Expression expression= fragment.getAssociatedExpression();
	if (expression == null)
		return false;
	switch (expression.getNodeType()) {
		case ASTNode.BOOLEAN_LITERAL:
		case ASTNode.CHARACTER_LITERAL:
		case ASTNode.NULL_LITERAL:
		case ASTNode.NUMBER_LITERAL:
			return true;

		default:
			return false;
	}
}
 
Example 4
Source File: ExtractConstantRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private boolean isLiteralNodeSelected() throws JavaModelException {
	IExpressionFragment fragment= getSelectedExpression();
	if (fragment == null)
		return false;
	Expression expression= fragment.getAssociatedExpression();
	if (expression == null)
		return false;
	switch (expression.getNodeType()) {
		case ASTNode.BOOLEAN_LITERAL :
		case ASTNode.CHARACTER_LITERAL :
		case ASTNode.NULL_LITERAL :
		case ASTNode.NUMBER_LITERAL :
			return true;

		default :
			return false;
	}
}
 
Example 5
Source File: JavaASTUtils.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private static boolean containsAnnotationValue(Expression annotationValue,
    String value) {
  if (annotationValue.getNodeType() == ASTNode.STRING_LITERAL) {
    String valueString = ((StringLiteral) annotationValue).getLiteralValue();
    return value.equals(valueString);
  } else if (annotationValue.getNodeType() == ASTNode.ARRAY_INITIALIZER) {
    // If the annotation value is actually an array, check each element
    List<Expression> warningTypes = ((ArrayInitializer) annotationValue).expressions();
    for (Expression warningType : warningTypes) {
      if (containsAnnotationValue(warningType, value)) {
        return true;
      }
    }
  }

  return false;
}
 
Example 6
Source File: ExtractClassRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private Expression getAssignedValue(ParameterObjectFactory pof, String parameterName, IJavaProject javaProject, RefactoringStatus status, ASTRewrite rewrite, ParameterInfo pi, boolean useSuper, ITypeBinding typeBinding, Expression qualifier, ASTNode replaceNode, ITypeRoot typeRoot) {
	AST ast= rewrite.getAST();
	boolean is50OrHigher= JavaModelUtil.is50OrHigher(javaProject);
	Expression assignedValue= handleSimpleNameAssignment(replaceNode, pof, parameterName, ast, javaProject, useSuper);
	if (assignedValue == null) {
		NullLiteral marker= qualifier == null ? null : ast.newNullLiteral();
		Expression fieldReadAccess= pof.createFieldReadAccess(pi, parameterName, ast, javaProject, useSuper, marker);
		assignedValue= GetterSetterUtil.getAssignedValue(replaceNode, rewrite, fieldReadAccess, typeBinding, is50OrHigher);
		boolean markerReplaced= replaceMarker(rewrite, qualifier, assignedValue, marker);
		if (markerReplaced) {
			switch (qualifier.getNodeType()) {
				case ASTNode.METHOD_INVOCATION:
				case ASTNode.CLASS_INSTANCE_CREATION:
				case ASTNode.SUPER_METHOD_INVOCATION:
				case ASTNode.PARENTHESIZED_EXPRESSION:
					status.addWarning(RefactoringCoreMessages.ExtractClassRefactoring_warning_semantic_change, JavaStatusContext.create(typeRoot, replaceNode));
					break;
			}
		}
	}
	return assignedValue;
}
 
Example 7
Source File: ExtractClassRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private Expression handleSimpleNameAssignment(ASTNode replaceNode, ParameterObjectFactory pof, String parameterName, AST ast, IJavaProject javaProject, boolean useSuper) {
	if (replaceNode instanceof Assignment) {
		Assignment assignment= (Assignment) replaceNode;
		Expression rightHandSide= assignment.getRightHandSide();
		if (rightHandSide.getNodeType() == ASTNode.SIMPLE_NAME) {
			SimpleName sn= (SimpleName) rightHandSide;
			IVariableBinding binding= ASTNodes.getVariableBinding(sn);
			if (binding != null && binding.isField()) {
				if (fDescriptor.getType().getFullyQualifiedName().equals(binding.getDeclaringClass().getQualifiedName())) {
					FieldInfo fieldInfo= getFieldInfo(binding.getName());
					if (fieldInfo != null && binding == fieldInfo.pi.getOldBinding()) {
						return pof.createFieldReadAccess(fieldInfo.pi, parameterName, ast, javaProject, useSuper, null);
					}
				}
			}
		}
	}
	return null;
}
 
Example 8
Source File: ExpressionVariable.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public ExpressionVariable(Expression expression){
	super(expression.resolveTypeBinding());
	fSource= expression.toString();
	ICompilationUnit cu= ASTCreator.getCu(expression);
	Assert.isNotNull(cu);
	fRange= new CompilationUnitRange(cu, expression);
	fExpressionBinding= resolveBinding(expression);
	fExpressionType= expression.getNodeType();
}
 
Example 9
Source File: RefactorProposalUtility.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public static CUCorrectionProposal getAssignVariableProposal(CodeActionParams params, IInvocationContext context, boolean problemsAtLocation, Map formatterOptions, boolean returnAsCommand,
		IProblemLocationCore[] locations)
		throws CoreException {
	ASTNode node = context.getCoveringNode();
	Statement statement = ASTResolving.findParentStatement(node);
	if (!(statement instanceof ExpressionStatement)) {
		return null;
	}
	ExpressionStatement expressionStatement = (ExpressionStatement) statement;
	Expression expression = expressionStatement.getExpression();
	if (expression.getNodeType() == ASTNode.ASSIGNMENT) {
		return null;
	}
	ITypeBinding typeBinding = expression.resolveTypeBinding();
	typeBinding = Bindings.normalizeTypeBinding(typeBinding);
	if (typeBinding == null) {
		return null;
	}
	if (containsMatchingProblem(locations, IProblem.UnusedObjectAllocation)) {
		return null;
	}
	final ICompilationUnit cu = context.getCompilationUnit();
	int relevance;
	if (context.getSelectionLength() == 0) {
		relevance = IProposalRelevance.EXTRACT_LOCAL_ZERO_SELECTION;
	} else if (problemsAtLocation) {
		relevance = IProposalRelevance.EXTRACT_LOCAL_ERROR;
	} else {
		relevance = IProposalRelevance.EXTRACT_LOCAL;
	}
	if (returnAsCommand) {
		return new AssignToVariableAssistCommandProposal(cu, JavaCodeActionKind.REFACTOR_ASSIGN_VARIABLE, AssignToVariableAssistProposal.LOCAL, expressionStatement, typeBinding, relevance, APPLY_REFACTORING_COMMAND_ID,
				Arrays.asList(ASSIGN_VARIABLE_COMMAND, params));
	} else {
		return new AssignToVariableAssistProposal(cu, JavaCodeActionKind.REFACTOR_ASSIGN_VARIABLE, AssignToVariableAssistProposal.LOCAL, expressionStatement, typeBinding, relevance);
	}
}
 
Example 10
Source File: RefactorProposalUtility.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public static CUCorrectionProposal getAssignFieldProposal(CodeActionParams params, IInvocationContext context, boolean problemsAtLocation, Map formatterOptions, boolean returnAsCommand,
		IProblemLocationCore[] locations) throws CoreException {
	ASTNode node = context.getCoveringNode();
	Statement statement = ASTResolving.findParentStatement(node);
	if (!(statement instanceof ExpressionStatement)) {
		return null;
	}
	ExpressionStatement expressionStatement = (ExpressionStatement) statement;
	Expression expression = expressionStatement.getExpression();
	if (expression.getNodeType() == ASTNode.ASSIGNMENT) {
		return null;
	}
	ITypeBinding typeBinding = expression.resolveTypeBinding();
	typeBinding = Bindings.normalizeTypeBinding(typeBinding);
	if (typeBinding == null) {
		return null;
	}
	if (containsMatchingProblem(locations, IProblem.UnusedObjectAllocation)) {
		return null;
	}
	final ICompilationUnit cu = context.getCompilationUnit();
	ASTNode type = ASTResolving.findParentType(expression);
	if (type != null) {
		int relevance;
		if (context.getSelectionLength() == 0) {
			relevance = IProposalRelevance.EXTRACT_LOCAL_ZERO_SELECTION;
		} else if (problemsAtLocation) {
			relevance = IProposalRelevance.EXTRACT_LOCAL_ERROR;
		} else {
			relevance = IProposalRelevance.EXTRACT_LOCAL;
		}
		if (returnAsCommand) {
			return new AssignToVariableAssistCommandProposal(cu, JavaCodeActionKind.REFACTOR_ASSIGN_FIELD, AssignToVariableAssistProposal.FIELD, expressionStatement, typeBinding, relevance, APPLY_REFACTORING_COMMAND_ID,
					Arrays.asList(ASSIGN_FIELD_COMMAND, params));
		} else {
			return new AssignToVariableAssistProposal(cu, JavaCodeActionKind.REFACTOR_ASSIGN_FIELD, AssignToVariableAssistProposal.FIELD, expressionStatement, typeBinding, relevance);
		}
	}
	return null;
}
 
Example 11
Source File: Invocations.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static ListRewrite getInferredTypeArgumentsRewrite(ASTRewrite rewrite, Expression invocation) {
	switch (invocation.getNodeType()) {
		case ASTNode.METHOD_INVOCATION:
			return rewrite.getListRewrite(invocation, MethodInvocation.TYPE_ARGUMENTS_PROPERTY);
		case ASTNode.SUPER_METHOD_INVOCATION:
			return rewrite.getListRewrite(invocation, SuperMethodInvocation.TYPE_ARGUMENTS_PROPERTY);
		case ASTNode.CLASS_INSTANCE_CREATION:
			Type type= ((ClassInstanceCreation) invocation).getType();
			return rewrite.getListRewrite(type, ParameterizedType.TYPE_ARGUMENTS_PROPERTY);
			
		default:
			throw new IllegalArgumentException(invocation.toString());
	}
}
 
Example 12
Source File: NecessaryParenthesesChecker.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static boolean expressionTypeNeedsParentheses(Expression expression) {
	int type= expression.getNodeType();
	return type == ASTNode.INFIX_EXPRESSION
			|| type == ASTNode.CONDITIONAL_EXPRESSION
			|| type == ASTNode.PREFIX_EXPRESSION
			|| type == ASTNode.POSTFIX_EXPRESSION
			|| type == ASTNode.CAST_EXPRESSION
			|| type == ASTNode.INSTANCEOF_EXPRESSION
			|| type == ASTNode.ARRAY_CREATION
			|| type == ASTNode.ASSIGNMENT;
}
 
Example 13
Source File: TypeMismatchSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public static ASTRewriteCorrectionProposal createCastProposal(IInvocationContext context, ITypeBinding castTypeBinding, Expression nodeToCast, int relevance) {
	ICompilationUnit cu= context.getCompilationUnit();

	String label;
	String castType= BindingLabelProviderCore.getBindingLabel(castTypeBinding, JavaElementLabels.ALL_DEFAULT);
	if (nodeToCast.getNodeType() == ASTNode.CAST_EXPRESSION) {
		label= Messages.format(CorrectionMessages.TypeMismatchSubProcessor_changecast_description, castType);
	} else {
		label= Messages.format(CorrectionMessages.TypeMismatchSubProcessor_addcast_description, castType);
	}
	return new CastCorrectionProposal(label, cu, nodeToCast, castTypeBinding, relevance);
}
 
Example 14
Source File: RemoveDeclarationCorrectionProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Remove the field or variable declaration including the initializer.
 * @param rewrite the ast rewrite
 * @param reference the reference
 */
private void removeVariableReferences(ASTRewrite rewrite, SimpleName reference) {
	ASTNode parent= reference.getParent();
	while (parent instanceof QualifiedName) {
		parent= parent.getParent();
	}
	if (parent instanceof FieldAccess) {
		parent= parent.getParent();
	}

	int nameParentType= parent.getNodeType();
	if (nameParentType == ASTNode.ASSIGNMENT) {
		Assignment assignment= (Assignment) parent;
		Expression rightHand= assignment.getRightHandSide();

		ASTNode assignParent= assignment.getParent();
		if (assignParent.getNodeType() == ASTNode.EXPRESSION_STATEMENT && rightHand.getNodeType() != ASTNode.ASSIGNMENT) {
			removeVariableWithInitializer(rewrite, rightHand, assignParent);
		}	else {
			rewrite.replace(assignment, rewrite.createCopyTarget(rightHand), null);
		}
	} else if (nameParentType == ASTNode.SINGLE_VARIABLE_DECLARATION) {
		rewrite.remove(parent, null);
	} else if (nameParentType == ASTNode.VARIABLE_DECLARATION_FRAGMENT) {
		VariableDeclarationFragment frag= (VariableDeclarationFragment) parent;
		ASTNode varDecl= frag.getParent();
		List<VariableDeclarationFragment> fragments;
		if (varDecl instanceof VariableDeclarationExpression) {
			fragments= ((VariableDeclarationExpression) varDecl).fragments();
		} else if (varDecl instanceof FieldDeclaration) {
			fragments= ((FieldDeclaration) varDecl).fragments();
		} else {
			fragments= ((VariableDeclarationStatement) varDecl).fragments();
		}
		if (fragments.size() == 1) {
			rewrite.remove(varDecl, null);
		} else {
			rewrite.remove(frag, null); // don't try to preserve
		}
	}
}
 
Example 15
Source File: ASTNodeMatcher.java    From JDeodorant with MIT License 4 votes vote down vote up
public boolean match(VariableDeclarationStatement node, Object other) {
	List fragments = node.fragments();
	if(fragments.size() == 1 && other instanceof ExpressionStatement) {
		VariableDeclarationFragment fragment = (VariableDeclarationFragment)fragments.get(0);
		ExpressionStatement expressionStatement = (ExpressionStatement)other;
		Expression expression = expressionStatement.getExpression();
		if(expression instanceof Assignment) {
			Assignment assignment = (Assignment)expression;
			Expression leftHandSide = assignment.getLeftHandSide();
			if(leftHandSide instanceof SimpleName) {
				SimpleName simpleName = (SimpleName)leftHandSide;
				boolean variableMatch = safeSubtreeMatch(fragment.getName(), simpleName);
				boolean variableTypeMatch = false;
				IBinding simpleNameBinding = simpleName.resolveBinding();
				IBinding fragmentNameBinding = fragment.getName().resolveBinding();
				if(simpleNameBinding.getKind() == IBinding.VARIABLE && fragmentNameBinding.getKind() == IBinding.VARIABLE) {
					IVariableBinding simpleNameVariableBinding = (IVariableBinding)simpleNameBinding;
					IVariableBinding fragmentNameVariableBinding = (IVariableBinding)fragmentNameBinding;
					variableTypeMatch = simpleNameVariableBinding.getType().isEqualTo(fragmentNameVariableBinding.getType()) &&
							simpleNameVariableBinding.getType().getQualifiedName().equals(fragmentNameVariableBinding.getType().getQualifiedName());;
				}
				boolean initializerMatch = false;
				boolean initializerTypeMatch = false;
				Expression initializer = fragment.getInitializer();
				Expression rightHandSide = assignment.getRightHandSide();
				if(initializer != null && initializer.getNodeType() == rightHandSide.getNodeType()) {
					initializerMatch = safeSubtreeMatch(initializer, rightHandSide);
					initializerTypeMatch = initializer.resolveTypeBinding().isEqualTo(rightHandSide.resolveTypeBinding()) &&
							initializer.resolveTypeBinding().getQualifiedName().equals(rightHandSide.resolveTypeBinding().getQualifiedName());
				}
				if(variableMatch && variableTypeMatch && initializerMatch && initializerTypeMatch) {
					VariableDeclaration variableDeclaration = AbstractLoopUtilities.getVariableDeclaration(simpleName);
					if(variableDeclaration != null && hasEmptyInitializer(variableDeclaration)) {
						safeSubtreeMatch(fragment.getName(), variableDeclaration.getName());
						List<ASTNode> astNodes = new ArrayList<ASTNode>();
						astNodes.add(variableDeclaration);
						ASTInformationGenerator.setCurrentITypeRoot(typeRoot2);
						reportAdditionalFragments(astNodes, this.additionallyMatchedFragments2);
						return true;
					}
				}
			}
		}
	}
	return super.match(node, other);
}
 
Example 16
Source File: UnusedCodeFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Remove the field or variable declaration including the initializer.
 * @param rewrite the AST rewriter to use
 * @param reference a reference to the variable to remove
 * @param group the text edit group to use
 */
private void removeVariableReferences(ASTRewrite rewrite, SimpleName reference, TextEditGroup group) {
	ASTNode parent= reference.getParent();
	while (parent instanceof QualifiedName) {
		parent= parent.getParent();
	}
	if (parent instanceof FieldAccess) {
		parent= parent.getParent();
	}

	int nameParentType= parent.getNodeType();
	if (nameParentType == ASTNode.ASSIGNMENT) {
		Assignment assignment= (Assignment) parent;
		Expression rightHand= assignment.getRightHandSide();

		ASTNode assignParent= assignment.getParent();
		if (assignParent.getNodeType() == ASTNode.EXPRESSION_STATEMENT && rightHand.getNodeType() != ASTNode.ASSIGNMENT) {
			removeVariableWithInitializer(rewrite, rightHand, assignParent, group);
		}	else {
			rewrite.replace(assignment, rewrite.createCopyTarget(rightHand), group);
		}
	} else if (nameParentType == ASTNode.SINGLE_VARIABLE_DECLARATION) {
		rewrite.remove(parent, group);
	} else if (nameParentType == ASTNode.VARIABLE_DECLARATION_FRAGMENT) {
		VariableDeclarationFragment frag= (VariableDeclarationFragment) parent;
		ASTNode varDecl= frag.getParent();
		List<VariableDeclarationFragment> fragments;
		if (varDecl instanceof VariableDeclarationExpression) {
			fragments= ((VariableDeclarationExpression) varDecl).fragments();
		} else if (varDecl instanceof FieldDeclaration) {
			fragments= ((FieldDeclaration) varDecl).fragments();
		} else {
			fragments= ((VariableDeclarationStatement) varDecl).fragments();
		}
		Expression initializer = frag.getInitializer();
		ArrayList<Expression> sideEffects= new ArrayList<Expression>();
		if (initializer != null) {
			initializer.accept(new SideEffectFinder(sideEffects));
		}
		boolean sideEffectInitializer= sideEffects.size() > 0;
		if (fragments.size() == fUnusedNames.length) {
			if (fForceRemove) {
				rewrite.remove(varDecl, group);
				return;
			}
			if (parent.getParent() instanceof FieldDeclaration) {
				rewrite.remove(varDecl, group);
				return;
			}
			if (sideEffectInitializer) {
				Statement[] wrapped= new Statement[sideEffects.size()];
				for (int i= 0; i < wrapped.length; i++) {
					Expression sideEffect= sideEffects.get(i);
					Expression movedInit= (Expression) rewrite.createMoveTarget(sideEffect);
					wrapped[i]= rewrite.getAST().newExpressionStatement(movedInit);
				}
				StatementRewrite statementRewrite= new StatementRewrite(rewrite, new ASTNode[] { varDecl });
				statementRewrite.replace(wrapped, group);
			} else {
				rewrite.remove(varDecl, group);
			}
		} else {
			if (fForceRemove) {
				rewrite.remove(frag, group);
				return;
			}
			//multiple declarations in one line
			ASTNode declaration = parent.getParent();
			if (declaration instanceof FieldDeclaration) {
				rewrite.remove(frag, group);
				return;
			}
			if (declaration instanceof VariableDeclarationStatement) {
				splitUpDeclarations(rewrite, group, frag, (VariableDeclarationStatement) declaration, sideEffects);
				rewrite.remove(frag, group);
				return;
			}
			if (declaration instanceof VariableDeclarationExpression) {
				//keep constructors and method invocations
				if (!sideEffectInitializer){
					rewrite.remove(frag, group);
				}
			}
		}
	} else if (nameParentType == ASTNode.POSTFIX_EXPRESSION || nameParentType == ASTNode.PREFIX_EXPRESSION) {
		Expression expression= (Expression)parent;
		ASTNode expressionParent= expression.getParent();
		if (expressionParent.getNodeType() == ASTNode.EXPRESSION_STATEMENT) {
			removeStatement(rewrite, expressionParent, group);
		} else {
			rewrite.remove(expression, group);
		}
	}
}
 
Example 17
Source File: SemanticHighlightings.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public boolean consumesLiteral(SemanticToken token) {
	Expression expr= token.getLiteral();
	return expr != null && expr.getNodeType() == ASTNode.NUMBER_LITERAL;
}
 
Example 18
Source File: ExtractMethodAnalyzer.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private void initReturnType(ImportRewrite rewriter) {
	AST ast = fEnclosingBodyDeclaration.getAST();
	fReturnType = null;
	fReturnTypeBinding = null;
	switch (fReturnKind) {
		case ACCESS_TO_LOCAL:
			VariableDeclaration declaration = ASTNodes.findVariableDeclaration(fReturnValue, fEnclosingBodyDeclaration);
			fReturnType = ASTNodeFactory.newType(ast, declaration, rewriter, new ContextSensitiveImportRewriteContext(declaration, rewriter));
			if (declaration.resolveBinding() != null) {
				fReturnTypeBinding = declaration.resolveBinding().getType();
			}
			break;
		case EXPRESSION:
			Expression expression = (Expression) getFirstSelectedNode();
			if (expression.getNodeType() == ASTNode.CLASS_INSTANCE_CREATION) {
				fExpressionBinding = ((ClassInstanceCreation) expression).getType().resolveBinding();
			} else {
				fExpressionBinding = expression.resolveTypeBinding();
			}
			if (fExpressionBinding != null) {
				if (fExpressionBinding.isNullType()) {
					getStatus().addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_null_type, JavaStatusContext.create(fCUnit, expression));
				} else {
					ITypeBinding normalizedBinding = Bindings.normalizeForDeclarationUse(fExpressionBinding, ast);
					if (normalizedBinding != null) {
						ImportRewriteContext context = new ContextSensitiveImportRewriteContext(fEnclosingBodyDeclaration, rewriter);
						fReturnType = rewriter.addImport(normalizedBinding, ast, context, TypeLocation.RETURN_TYPE);
						fReturnTypeBinding = normalizedBinding;
					}
				}
			} else {
				fReturnType = ast.newPrimitiveType(PrimitiveType.VOID);
				fReturnTypeBinding = ast.resolveWellKnownType("void"); //$NON-NLS-1$
				getStatus().addError(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_determine_return_type, JavaStatusContext.create(fCUnit, expression));
			}
			break;
		case RETURN_STATEMENT_VALUE:
			LambdaExpression enclosingLambdaExpr = ASTResolving.findEnclosingLambdaExpression(getFirstSelectedNode());
			if (enclosingLambdaExpr != null) {
				fReturnType = ASTNodeFactory.newReturnType(enclosingLambdaExpr, ast, rewriter, null);
				IMethodBinding methodBinding = enclosingLambdaExpr.resolveMethodBinding();
				fReturnTypeBinding = methodBinding != null ? methodBinding.getReturnType() : null;
			} else if (fEnclosingBodyDeclaration.getNodeType() == ASTNode.METHOD_DECLARATION) {
				fReturnType = ((MethodDeclaration) fEnclosingBodyDeclaration).getReturnType2();
				fReturnTypeBinding = fReturnType != null ? fReturnType.resolveBinding() : null;
			}
			break;
		default:
			fReturnType = ast.newPrimitiveType(PrimitiveType.VOID);
			fReturnTypeBinding = ast.resolveWellKnownType("void"); //$NON-NLS-1$
	}
	if (fReturnType == null) {
		fReturnType = ast.newPrimitiveType(PrimitiveType.VOID);
		fReturnTypeBinding = ast.resolveWellKnownType("void"); //$NON-NLS-1$
	}
}
 
Example 19
Source File: ExtractMethodAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private void initReturnType(ImportRewrite rewriter) {
	AST ast= fEnclosingBodyDeclaration.getAST();
	fReturnType= null;
	fReturnTypeBinding= null;
	switch (fReturnKind) {
		case ACCESS_TO_LOCAL:
			VariableDeclaration declaration= ASTNodes.findVariableDeclaration(fReturnValue, fEnclosingBodyDeclaration);
			fReturnType= ASTNodeFactory.newType(ast, declaration, rewriter, new ContextSensitiveImportRewriteContext(declaration, rewriter));
			if (declaration.resolveBinding() != null) {
				fReturnTypeBinding= declaration.resolveBinding().getType();
			}
			break;
		case EXPRESSION:
			Expression expression= (Expression)getFirstSelectedNode();
			if (expression.getNodeType() == ASTNode.CLASS_INSTANCE_CREATION) {
				fExpressionBinding= ((ClassInstanceCreation)expression).getType().resolveBinding();
			} else {
				fExpressionBinding= expression.resolveTypeBinding();
			}
			if (fExpressionBinding != null) {
				if (fExpressionBinding.isNullType()) {
					getStatus().addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_null_type, JavaStatusContext.create(fCUnit, expression));
				} else {
					ITypeBinding normalizedBinding= Bindings.normalizeForDeclarationUse(fExpressionBinding, ast);
					if (normalizedBinding != null) {
						ImportRewriteContext context= new ContextSensitiveImportRewriteContext(fEnclosingBodyDeclaration, rewriter);
						fReturnType= rewriter.addImport(normalizedBinding, ast, context);
						fReturnTypeBinding= normalizedBinding;
					}
				}
			} else {
				fReturnType= ast.newPrimitiveType(PrimitiveType.VOID);
				fReturnTypeBinding= ast.resolveWellKnownType("void"); //$NON-NLS-1$
				getStatus().addError(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_determine_return_type, JavaStatusContext.create(fCUnit, expression));
			}
			break;
		case RETURN_STATEMENT_VALUE:
			LambdaExpression enclosingLambdaExpr= ASTResolving.findEnclosingLambdaExpression(getFirstSelectedNode());
			if (enclosingLambdaExpr != null) {
				fReturnType= ASTNodeFactory.newReturnType(enclosingLambdaExpr, ast, rewriter, null);
				IMethodBinding methodBinding= enclosingLambdaExpr.resolveMethodBinding();
				fReturnTypeBinding= methodBinding != null ? methodBinding.getReturnType() : null;
			} else if (fEnclosingBodyDeclaration.getNodeType() == ASTNode.METHOD_DECLARATION) {
				fReturnType= ((MethodDeclaration) fEnclosingBodyDeclaration).getReturnType2();
				fReturnTypeBinding= fReturnType != null ? fReturnType.resolveBinding() : null;
			}
			break;
		default:
			fReturnType= ast.newPrimitiveType(PrimitiveType.VOID);
			fReturnTypeBinding= ast.resolveWellKnownType("void"); //$NON-NLS-1$
	}
	if (fReturnType == null) {
		fReturnType= ast.newPrimitiveType(PrimitiveType.VOID);
		fReturnTypeBinding= ast.resolveWellKnownType("void"); //$NON-NLS-1$
	}
}
 
Example 20
Source File: ConstraintVariableFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public ConstraintVariable makeExpressionOrTypeVariable(Expression expression,
												       IContext context) {
	IBinding binding= ExpressionVariable.resolveBinding(expression);

	if (binding instanceof ITypeBinding){
		ICompilationUnit cu= ASTCreator.getCu(expression);
		Assert.isNotNull(cu);
		CompilationUnitRange range= new CompilationUnitRange(cu, expression);
		return makeTypeVariable((ITypeBinding)getKey(binding), expression.toString(), range);
	}

	if (ASTNodes.isLiteral(expression)){
		Integer nodeType= new Integer(expression.getNodeType());
		if (! fLiteralMap.containsKey(nodeType)){
			fLiteralMap.put(nodeType, new ExpressionVariable(expression));
			if (REPORT) nrCreated++;
		} else {
			if (REPORT) nrRetrieved++;
		}
		if (REPORT) dumpConstraintStats();
		return fLiteralMap.get(nodeType);
	}

	// For ExpressionVariables, there are two cases. If the expression has a binding
	// we use that as the key. Otherwise, we use the CompilationUnitRange. See
	// also ExpressionVariable.equals()
	ExpressionVariable ev;
	Object key;
	if (binding != null){
		key= getKey(binding);
	} else {
		key= new CompilationUnitRange(ASTCreator.getCu(expression), expression);
	}
	ev= fExpressionMap.get(key);

	if (ev != null){
		if (REPORT) nrRetrieved++;
	} else {
		ev= new ExpressionVariable(expression);
		fExpressionMap.put(key, ev);
		if (REPORT) nrCreated++;
		if (REPORT) dumpConstraintStats();
	}
	return ev;
}