org.eclipse.jdt.core.dom.CastExpression Java Examples

The following examples show how to use org.eclipse.jdt.core.dom.CastExpression. 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: BaseTranslator.java    From junion with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public Expression methodB(String methodName, Type castType, Object... args) {
		MethodInvocation p = ast.newMethodInvocation();
		p.setExpression(name(MEM0_B));
//		p.setName(name(Translator.StringCache.getString(
//				type,
//				t,
//				opsymbol)));
		p.setName(name(methodName));

		for(Object arg : args)
			p.arguments().add(arg);
		
		if(castType != null) {
			CastExpression cast = ast.newCastExpression();			
			cast.setType(castType);
			cast.setExpression(p);
			cast.setProperty(TYPEBIND_PROP, FieldType.OBJECT);
			return cast;
		}
		return p;
	}
 
Example #2
Source File: ASTNodeMatcher.java    From JDeodorant with MIT License 6 votes vote down vote up
protected boolean isTypeHolder(Object o) {
	if(o.getClass().equals(MethodInvocation.class) || o.getClass().equals(SuperMethodInvocation.class)			
			|| o.getClass().equals(NumberLiteral.class) || o.getClass().equals(StringLiteral.class)
			|| o.getClass().equals(CharacterLiteral.class) || o.getClass().equals(BooleanLiteral.class)
			|| o.getClass().equals(TypeLiteral.class) || o.getClass().equals(NullLiteral.class)
			|| o.getClass().equals(ArrayCreation.class)
			|| o.getClass().equals(ClassInstanceCreation.class)
			|| o.getClass().equals(ArrayAccess.class) || o.getClass().equals(FieldAccess.class)
			|| o.getClass().equals(SuperFieldAccess.class) || o.getClass().equals(ParenthesizedExpression.class)
			|| o.getClass().equals(SimpleName.class) || o.getClass().equals(QualifiedName.class)
			|| o.getClass().equals(CastExpression.class) || o.getClass().equals(InfixExpression.class)
			|| o.getClass().equals(PrefixExpression.class) || o.getClass().equals(InstanceofExpression.class)
			|| o.getClass().equals(ThisExpression.class) || o.getClass().equals(ConditionalExpression.class))
		return true;
	return false;
}
 
Example #3
Source File: UnusedCodeFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static void replaceCast(CastExpression castExpression, Expression replacement, ASTRewrite rewrite, TextEditGroup group) {
	boolean castEnclosedInNecessaryParentheses= castExpression.getParent() instanceof ParenthesizedExpression
			&& NecessaryParenthesesChecker.needsParentheses(castExpression, castExpression.getParent().getParent(), castExpression.getParent().getLocationInParent());
	
	ASTNode toReplace= castEnclosedInNecessaryParentheses ? castExpression.getParent() : castExpression;
	ASTNode move;
	if (NecessaryParenthesesChecker.needsParentheses(replacement, toReplace.getParent(), toReplace.getLocationInParent())) {
		if (replacement.getParent() instanceof ParenthesizedExpression) {
			move= rewrite.createMoveTarget(replacement.getParent());
		} else if (castEnclosedInNecessaryParentheses) {
			toReplace= castExpression;
			move= rewrite.createMoveTarget(replacement);
		} else {
			ParenthesizedExpression parentheses= replacement.getAST().newParenthesizedExpression();
			parentheses.setExpression((Expression) rewrite.createMoveTarget(replacement));
			move= parentheses;
		}
	} else {
		move= rewrite.createMoveTarget(replacement);
	}
	rewrite.replace(toReplace, move, group);
}
 
Example #4
Source File: UnusedCodeFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static UnusedCodeFix createRemoveUnusedCastFix(CompilationUnit compilationUnit, IProblemLocation problem) {
	if (problem.getProblemId() != IProblem.UnnecessaryCast)
		return null;

	ASTNode selectedNode= problem.getCoveringNode(compilationUnit);

	ASTNode curr= selectedNode;
	while (curr instanceof ParenthesizedExpression) {
		curr= ((ParenthesizedExpression) curr).getExpression();
	}

	if (!(curr instanceof CastExpression))
		return null;

	return new UnusedCodeFix(FixMessages.UnusedCodeFix_RemoveCast_description, compilationUnit, new CompilationUnitRewriteOperation[] {new RemoveCastOperation((CastExpression)curr)});
}
 
Example #5
Source File: UnusedCodeFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel model) throws CoreException {

	TextEditGroup group= createTextEditGroup(FixMessages.UnusedCodeFix_RemoveCast_description, cuRewrite);

	ASTRewrite rewrite= cuRewrite.getASTRewrite();

	CastExpression cast= fCast;
	Expression expression= cast.getExpression();
	if (expression instanceof ParenthesizedExpression) {
		Expression childExpression= ((ParenthesizedExpression) expression).getExpression();
		if (NecessaryParenthesesChecker.needsParentheses(childExpression, cast, CastExpression.EXPRESSION_PROPERTY)) {
			expression= childExpression;
		}
	}
	
	replaceCast(cast, expression, rewrite, group);
}
 
Example #6
Source File: GenerateHashCodeEqualsOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private Expression createShiftAssignment(Expression shift1, Expression shift2) {
	// (int)(element ^ (element >>> 32));
	// see implementation in Arrays.hashCode(), Double.hashCode() and
	// Long.hashCode()
	CastExpression ce= fAst.newCastExpression();
	ce.setType(fAst.newPrimitiveType(PrimitiveType.INT));

	InfixExpression unsignedShiftRight= fAst.newInfixExpression();
	unsignedShiftRight.setLeftOperand(shift1);
	unsignedShiftRight.setRightOperand(fAst.newNumberLiteral("32")); //$NON-NLS-1$
	unsignedShiftRight.setOperator(Operator.RIGHT_SHIFT_UNSIGNED);

	InfixExpression xor= fAst.newInfixExpression();
	xor.setLeftOperand(shift2);
	xor.setRightOperand(parenthesize(unsignedShiftRight));
	xor.setOperator(InfixExpression.Operator.XOR);

	ce.setExpression(parenthesize(xor));
	return ce;
}
 
Example #7
Source File: FullConstraintCreator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public ITypeConstraint[] create(CastExpression castExpression){
	Expression expression= castExpression.getExpression();
	Type type= castExpression.getType();
	ITypeConstraint[] definesConstraint= fTypeConstraintFactory.createDefinesConstraint(fConstraintVariableFactory.makeExpressionOrTypeVariable(castExpression, getContext()),
			                                                                        fConstraintVariableFactory.makeTypeVariable(castExpression.getType()));
	if (isClassBinding(expression.resolveTypeBinding()) && isClassBinding(type.resolveBinding())){
		ConstraintVariable expressionVariable= fConstraintVariableFactory.makeExpressionOrTypeVariable(expression, getContext());
		ConstraintVariable castExpressionVariable= fConstraintVariableFactory.makeExpressionOrTypeVariable(castExpression, getContext());
		ITypeConstraint[] c2 = createOrOrSubtypeConstraint(expressionVariable, castExpressionVariable);
		if (definesConstraint.length == 0){
			return c2;
		} else {
			ITypeConstraint c1 = definesConstraint[0];
			Collection<ITypeConstraint> constraints= new ArrayList<ITypeConstraint>();
			constraints.add(c1);
			constraints.addAll(Arrays.asList(c2));
			return constraints.toArray(new ITypeConstraint[constraints.size()]);
		}
	} else
		return definesConstraint;
}
 
Example #8
Source File: CodeBlock.java    From SimFix with GNU General Public License v2.0 5 votes vote down vote up
private CastExpr visit(CastExpression node) {
	int startLine = _cunit.getLineNumber(node.getStartPosition());
	int endLine = _cunit.getLineNumber(node.getStartPosition() + node.getLength());
	CastExpr castExpr = new CastExpr(startLine, endLine, node);
	
	castExpr.setCastType(node.getType());
	Expr expression = (Expr) process(node.getExpression());
	expression.setParent(castExpr);
	castExpr.setExpression(expression);
	castExpr.setType(node.getType());

	return castExpr;
}
 
Example #9
Source File: TypenameScopeExtractor.java    From codemining-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public boolean visit(CastExpression node) {
	final String type = node.getType().toString();
	if (topMethod != null && methodsAsRoot) {
		types.put(topMethod, type);
	} else if (topClass != null) {
		types.put(topClass, type);
	}
	return super.visit(node);
}
 
Example #10
Source File: StyledStringVisitor.java    From JDeodorant with MIT License 5 votes vote down vote up
public boolean visit(CastExpression expr) {
	/*
	 * CastExpression: ( Type ) Expression
	 */
	activateDiffStyle(expr);
	appendOpenParenthesis();
	handleType(expr.getType());
	appendClosedParenthesis();
	handleExpression((Expression) expr.getExpression());
	deactivateDiffStyle(expr);
	return false;
}
 
Example #11
Source File: ReplaceConditionalWithPolymorphism.java    From JDeodorant with MIT License 5 votes vote down vote up
private void replaceCastExpressionWithThisExpression(List<Expression> oldCastExpressions, List<Expression> newCastExpressions, TypeDeclaration subclassTypeDeclaration, AST subclassAST, ASTRewrite subclassRewriter) {
	int j = 0;
	for(Expression expression : oldCastExpressions) {
		CastExpression castExpression = (CastExpression)expression;
		if(castExpression.getType().resolveBinding().isEqualTo(subclassTypeDeclaration.resolveBinding())) {
			if(castExpression.getExpression() instanceof SimpleName) {
				SimpleName castSimpleName = (SimpleName)castExpression.getExpression();
				if(typeVariable != null && typeVariable.getName().resolveBinding().isEqualTo(castSimpleName.resolveBinding())) {
					subclassRewriter.replace(newCastExpressions.get(j), subclassAST.newThisExpression(), null);
				}
			}
			else if(castExpression.getExpression() instanceof MethodInvocation) {
				MethodInvocation castMethodInvocation = (MethodInvocation)castExpression.getExpression();
				if(typeMethodInvocation != null && typeMethodInvocation.subtreeMatch(new ASTMatcher(), castMethodInvocation)) {
					subclassRewriter.replace(newCastExpressions.get(j), subclassAST.newThisExpression(), null);
				}
			}
		}
		j++;
	}
}
 
Example #12
Source File: CastCorrectionProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private Type getNewCastTypeNode(ASTRewrite rewrite, ImportRewrite importRewrite) {
	AST ast= rewrite.getAST();

	ImportRewriteContext context= new ContextSensitiveImportRewriteContext((CompilationUnit) fNodeToCast.getRoot(), fNodeToCast.getStartPosition(), importRewrite);

	if (fCastType != null) {
		return importRewrite.addImport(fCastType, ast,context);
	}

	ASTNode node= fNodeToCast;
	ASTNode parent= node.getParent();
	if (parent instanceof CastExpression) {
		node= parent;
		parent= parent.getParent();
	}
	while (parent instanceof ParenthesizedExpression) {
		node= parent;
		parent= parent.getParent();
	}
	if (parent instanceof MethodInvocation) {
		MethodInvocation invocation= (MethodInvocation) node.getParent();
		if (invocation.getExpression() == node) {
			IBinding targetContext= ASTResolving.getParentMethodOrTypeBinding(node);
			ITypeBinding[] bindings= ASTResolving.getQualifierGuess(node.getRoot(), invocation.getName().getIdentifier(), invocation.arguments(), targetContext);
			if (bindings.length > 0) {
				ITypeBinding first= getCastFavorite(bindings, fNodeToCast.resolveTypeBinding());

				Type newTypeNode= importRewrite.addImport(first, ast, context);
				addLinkedPosition(rewrite.track(newTypeNode), true, "casttype"); //$NON-NLS-1$
				for (int i= 0; i < bindings.length; i++) {
					addLinkedPositionProposal("casttype", bindings[i]); //$NON-NLS-1$
				}
				return newTypeNode;
			}
		}
	}
	Type newCastType= ast.newSimpleType(ast.newSimpleName("Object")); //$NON-NLS-1$
	addLinkedPosition(rewrite.track(newCastType), true, "casttype"); //$NON-NLS-1$
	return newCastType;
}
 
Example #13
Source File: UnresolvedElementsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static boolean useExistingParentCastProposal(ICompilationUnit cu, CastExpression expression, Expression accessExpression, SimpleName accessSelector, ITypeBinding[] paramTypes, Collection<ICommandAccess> proposals) {
	ITypeBinding castType= expression.getType().resolveBinding();
	if (castType == null) {
		return false;
	}
	if (paramTypes != null) {
		if (Bindings.findMethodInHierarchy(castType, accessSelector.getIdentifier(), paramTypes) == null) {
			return false;
		}
	} else if (Bindings.findFieldInHierarchy(castType, accessSelector.getIdentifier()) == null) {
		return false;
	}
	ITypeBinding bindingToCast= accessExpression.resolveTypeBinding();
	if (bindingToCast != null && !bindingToCast.isCastCompatible(castType)) {
		return false;
	}

	IMethodBinding res= Bindings.findMethodInHierarchy(castType, accessSelector.getIdentifier(), paramTypes);
	if (res != null) {
		AST ast= expression.getAST();
		ASTRewrite rewrite= ASTRewrite.create(ast);
		CastExpression newCast= ast.newCastExpression();
		newCast.setType((Type) ASTNode.copySubtree(ast, expression.getType()));
		newCast.setExpression((Expression) rewrite.createCopyTarget(accessExpression));
		ParenthesizedExpression parents= ast.newParenthesizedExpression();
		parents.setExpression(newCast);

		ASTNode node= rewrite.createCopyTarget(expression.getExpression());
		rewrite.replace(expression, node, null);
		rewrite.replace(accessExpression, parents, null);

		String label= CorrectionMessages.UnresolvedElementsSubProcessor_missingcastbrackets_description;
		Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CAST);
		ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, IProposalRelevance.ADD_PARENTHESES_AROUND_CAST, image);
		proposals.add(proposal);
		return true;
	}
	return false;
}
 
Example #14
Source File: ExceptionOccurrencesFinder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean visit(CastExpression node) {
	if ("java.lang.ClassCastException".equals(fException.getQualifiedName())) { //$NON-NLS-1$
		Type type= node.getType();
		fResult.add(new OccurrenceLocation(type.getStartPosition(), type.getLength(), 0, fDescription));
	}
	return super.visit(node);
}
 
Example #15
Source File: GetterSetterUtil.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Checks if the assignment needs a downcast and inserts it if necessary
 *
 * @param expression the right hand-side
 * @param expressionType the type of the right hand-side. Can be null
 * @param ast the AST
 * @param variableType the Type of the variable the expression will be assigned to
 * @param is50OrHigher if <code>true</code> java 5.0 code will be assumed
 * @return the casted expression if necessary
 */
private static Expression createNarrowCastIfNessecary(Expression expression, ITypeBinding expressionType, AST ast, ITypeBinding variableType, boolean is50OrHigher) {
	PrimitiveType castTo= null;
	if (variableType.isEqualTo(expressionType))
		return expression; //no cast for same type
	if (is50OrHigher) {
		if (ast.resolveWellKnownType("java.lang.Character").isEqualTo(variableType)) //$NON-NLS-1$
			castTo= ast.newPrimitiveType(PrimitiveType.CHAR);
		if (ast.resolveWellKnownType("java.lang.Byte").isEqualTo(variableType)) //$NON-NLS-1$
			castTo= ast.newPrimitiveType(PrimitiveType.BYTE);
		if (ast.resolveWellKnownType("java.lang.Short").isEqualTo(variableType)) //$NON-NLS-1$
			castTo= ast.newPrimitiveType(PrimitiveType.SHORT);
	}
	if (ast.resolveWellKnownType("char").isEqualTo(variableType)) //$NON-NLS-1$
		castTo= ast.newPrimitiveType(PrimitiveType.CHAR);
	if (ast.resolveWellKnownType("byte").isEqualTo(variableType)) //$NON-NLS-1$
		castTo= ast.newPrimitiveType(PrimitiveType.BYTE);
	if (ast.resolveWellKnownType("short").isEqualTo(variableType)) //$NON-NLS-1$
		castTo= ast.newPrimitiveType(PrimitiveType.SHORT);
	if (castTo != null) {
		CastExpression cast= ast.newCastExpression();
		if (NecessaryParenthesesChecker.needsParentheses(expression, cast, CastExpression.EXPRESSION_PROPERTY)) {
			ParenthesizedExpression parenthesized= ast.newParenthesizedExpression();
			parenthesized.setExpression(expression);
			cast.setExpression(parenthesized);
		} else
			cast.setExpression(expression);
		cast.setType(castTo);
		return cast;
	}
	return expression;
}
 
Example #16
Source File: OperatorPrecedence.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the precedence of the expression. Expression
 * with higher precedence are executed before expressions
 * with lower precedence.
 * i.e. in:
 * <br><code> int a= ++3--;</code></br>
 *
 * the  precedence order is
 * <ul>
 * <li>3</li>
 * <li>++</li>
 * <li>--</li>
 * <li>=</li>
 * </ul>
 * 1. 3 -(++)-> 4<br>
 * 2. 4 -(--)-> 3<br>
 * 3. 3 -(=)-> a<br>
 *
 * @param expression the expression to determine the precedence for
 * @return the precedence the higher to stronger the binding to its operand(s)
 */
public static int getExpressionPrecedence(Expression expression) {
	if (expression instanceof InfixExpression) {
		return getOperatorPrecedence(((InfixExpression)expression).getOperator());
	} else if (expression instanceof Assignment) {
		return ASSIGNMENT;
	} else if (expression instanceof ConditionalExpression) {
		return CONDITIONAL;
	} else if (expression instanceof InstanceofExpression) {
		return RELATIONAL;
	} else if (expression instanceof CastExpression) {
		return TYPEGENERATION;
	} else if (expression instanceof ClassInstanceCreation) {
		return POSTFIX;
	} else if (expression instanceof PrefixExpression) {
		return PREFIX;
	} else if (expression instanceof FieldAccess) {
		return POSTFIX;
	} else if (expression instanceof MethodInvocation) {
		return POSTFIX;
	} else if (expression instanceof ArrayAccess) {
		return POSTFIX;
	} else if (expression instanceof PostfixExpression) {
		return POSTFIX;
	}
	return Integer.MAX_VALUE;
}
 
Example #17
Source File: CastCorrectionProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private Type getNewCastTypeNode(ASTRewrite rewrite, ImportRewrite importRewrite) {
	AST ast= rewrite.getAST();

	ImportRewriteContext context= new ContextSensitiveImportRewriteContext((CompilationUnit) fNodeToCast.getRoot(), fNodeToCast.getStartPosition(), importRewrite);

	if (fCastType != null) {
		return importRewrite.addImport(fCastType, ast,context, TypeLocation.CAST);
	}

	ASTNode node= fNodeToCast;
	ASTNode parent= node.getParent();
	if (parent instanceof CastExpression) {
		node= parent;
		parent= parent.getParent();
	}
	while (parent instanceof ParenthesizedExpression) {
		node= parent;
		parent= parent.getParent();
	}
	if (parent instanceof MethodInvocation) {
		MethodInvocation invocation= (MethodInvocation) node.getParent();
		if (invocation.getExpression() == node) {
			IBinding targetContext= ASTResolving.getParentMethodOrTypeBinding(node);
			ITypeBinding[] bindings= ASTResolving.getQualifierGuess(node.getRoot(), invocation.getName().getIdentifier(), invocation.arguments(), targetContext);
			if (bindings.length > 0) {
				ITypeBinding first= getCastFavorite(bindings, fNodeToCast.resolveTypeBinding());

				Type newTypeNode= importRewrite.addImport(first, ast, context, TypeLocation.CAST);
				return newTypeNode;
			}
		}
	}
	Type newCastType= ast.newSimpleType(ast.newSimpleName("Object")); //$NON-NLS-1$
	return newCastType;
}
 
Example #18
Source File: TypenameScopeExtractor.java    From api-mining with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean visit(CastExpression node) {
	final String type = node.getType().toString();
	if (topMethod != null && methodsAsRoot) {
		types.put(topMethod, type);
	} else if (topClass != null) {
		types.put(topClass, type);
	}
	return super.visit(node);
}
 
Example #19
Source File: Visitor.java    From RefactoringMiner with MIT License 5 votes vote down vote up
public boolean visit(CastExpression node) {
	Expression castExpression = node.getExpression();
	if(castExpression instanceof SimpleName) {
		variables.add(node.toString());
		if(current.getUserObject() != null) {
			AnonymousClassDeclarationObject anonymous = (AnonymousClassDeclarationObject)current.getUserObject();
			anonymous.getVariables().add(node.toString());
		}
	}
	return super.visit(node);
}
 
Example #20
Source File: JavaASTFlattener.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public boolean visit(final CastExpression node) {
  ASTNode _parent = node.getParent();
  final boolean parantesis = (!(_parent instanceof Assignment));
  if (parantesis) {
    this.appendToBuffer("(");
  }
  node.getExpression().accept(this);
  this.appendToBuffer(" as ");
  node.getType().accept(this);
  if (parantesis) {
    this.appendToBuffer(")");
  }
  return false;
}
 
Example #21
Source File: TypenameScopeExtractor.java    From tassal with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public boolean visit(CastExpression node) {
	final String type = node.getType().toString();
	if (topMethod != null && methodsAsRoot) {
		types.put(topMethod, type);
	} else if (topClass != null) {
		types.put(topClass, type);
	}
	return super.visit(node);
}
 
Example #22
Source File: SuperTypeConstraintsModel.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates a cast variable.
 *
 * @param expression the cast expression
 * @param variable the associated constraint variable
 * @return the created cast variable, or <code>null</code>
 */
public final ConstraintVariable2 createCastVariable(final CastExpression expression, final ConstraintVariable2 variable) {
	ITypeBinding binding= expression.resolveTypeBinding();
	if (binding.isArray())
		binding= binding.getElementType();
	if (isConstrainedType(binding)) {
		final CastVariable2 result= new CastVariable2(createTType(binding), new CompilationUnitRange(RefactoringASTParser.getCompilationUnit(expression), expression), variable);
		fCastVariables.add(result);
		return result;
	}
	return null;
}
 
Example #23
Source File: SuperTypeConstraintsCreator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public final void endVisit(final CastExpression node) {
	final ConstraintVariable2 first= (ConstraintVariable2) node.getType().getProperty(PROPERTY_CONSTRAINT_VARIABLE);
	if (first != null) {
		node.setProperty(PROPERTY_CONSTRAINT_VARIABLE, first);
		final ConstraintVariable2 second= (ConstraintVariable2) node.getExpression().getProperty(PROPERTY_CONSTRAINT_VARIABLE);
		if (second != null)
			fModel.createCastVariable(node, second);
	}
}
 
Example #24
Source File: InferTypeArgumentsRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static ASTNode rewriteCastVariable(CastVariable2 castCv, CompilationUnitRewrite rewrite, InferTypeArgumentsTCModel tCModel) {//, List positionGroups) {
	ASTNode node= castCv.getRange().getNode(rewrite.getRoot());

	ConstraintVariable2 expressionVariable= castCv.getExpressionVariable();
	ConstraintVariable2 methodReceiverCv= tCModel.getMethodReceiverCv(expressionVariable);
	if (methodReceiverCv != null) {
		TType chosenReceiverType= InferTypeArgumentsConstraintsSolver.getChosenType(methodReceiverCv);
		if (chosenReceiverType == null)
			return null;
		else if (! InferTypeArgumentsTCModel.isAGenericType(chosenReceiverType))
			return null;
		else if (hasUnboundElement(methodReceiverCv, tCModel))
			return null;
	}

	CastExpression castExpression= (CastExpression) node;
	Expression expression= castExpression.getExpression();
	ASTNode nodeToReplace;
	if (castExpression.getParent() instanceof ParenthesizedExpression)
		nodeToReplace= castExpression.getParent();
	else
		nodeToReplace= castExpression;

	Expression newExpression= (Expression) rewrite.getASTRewrite().createMoveTarget(expression);
	rewrite.getASTRewrite().replace(nodeToReplace, newExpression, rewrite.createGroupDescription(RefactoringCoreMessages.InferTypeArgumentsRefactoring_removeCast));
	rewrite.getImportRemover().registerRemovedNode(nodeToReplace);
	return newExpression;
}
 
Example #25
Source File: ExtractFieldRefactoring.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private RefactoringStatus checkTempTypeForLocalTypeUsage() throws JavaModelException {
	Expression expression = getSelectedExpression().getAssociatedExpression();
	Type resultingType = null;
	ITypeBinding typeBinding = expression.resolveTypeBinding();
	AST ast = fCURewrite.getAST();

	if (expression instanceof ClassInstanceCreation && (typeBinding == null || typeBinding.getTypeArguments().length == 0)) {
		resultingType = ((ClassInstanceCreation) expression).getType();
	} else if (expression instanceof CastExpression) {
		resultingType = ((CastExpression) expression).getType();
	} else {
		if (typeBinding == null) {
			typeBinding = ASTResolving.guessBindingForReference(expression);
		}
		if (typeBinding != null) {
			typeBinding = Bindings.normalizeForDeclarationUse(typeBinding, ast);
			ImportRewrite importRewrite = fCURewrite.getImportRewrite();
			ImportRewriteContext context = new ContextSensitiveImportRewriteContext(expression, importRewrite);
			resultingType = importRewrite.addImport(typeBinding, ast, context, TypeLocation.LOCAL_VARIABLE);
		} else {
			resultingType = ast.newSimpleType(ast.newSimpleName("Object")); //$NON-NLS-1$
		}
	}

	IMethodBinding declaringMethodBinding = getMethodDeclaration().resolveBinding();
	ITypeBinding[] methodTypeParameters = declaringMethodBinding == null ? new ITypeBinding[0] : declaringMethodBinding.getTypeParameters();
	LocalTypeAndVariableUsageAnalyzer analyzer = new LocalTypeAndVariableUsageAnalyzer(methodTypeParameters);
	resultingType.accept(analyzer);
	boolean usesLocalTypes = !analyzer.getUsageOfEnclosingNodes().isEmpty();
	if (usesLocalTypes) {
		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractFieldRefactoring_uses_type_declared_locally);
	}
	return null;
}
 
Example #26
Source File: FlowAnalyzer.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void endVisit(CastExpression node) {
	if (skipNode(node)) {
		return;
	}
	processSequential(node, node.getType(), node.getExpression());
}
 
Example #27
Source File: InferTypeArgumentsTCModel.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public CastVariable2 makeCastVariable(CastExpression castExpression, ConstraintVariable2 expressionCv) {
	ITypeBinding typeBinding= castExpression.resolveTypeBinding();
	ICompilationUnit cu= RefactoringASTParser.getCompilationUnit(castExpression);
	CompilationUnitRange range= new CompilationUnitRange(cu, castExpression);
	CastVariable2 castCv= new CastVariable2(createTType(typeBinding), range, expressionCv);
	fCastVariables.add(castCv);
	return castCv;
}
 
Example #28
Source File: BindingSignatureVisitor.java    From JDeodorant with MIT License 4 votes vote down vote up
public boolean visit(CastExpression expr) {
	handleType(expr.getType());
	handleExpression(expr.getExpression());
	return false;
}
 
Example #29
Source File: LocalCorrectionsSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private static void addRemoveIncludingConditionProposal(IInvocationContext context, ASTNode toRemove, ASTNode replacement, Collection<ChangeCorrectionProposal> proposals) {
	String label = CorrectionMessages.LocalCorrectionsSubProcessor_removeunreachablecode_including_condition_description;
	AST ast = toRemove.getAST();
	ASTRewrite rewrite = ASTRewrite.create(ast);
	ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, CodeActionKind.QuickFix, context.getCompilationUnit(), rewrite, IProposalRelevance.REMOVE_UNREACHABLE_CODE_INCLUDING_CONDITION);

	if (replacement == null || replacement instanceof EmptyStatement || replacement instanceof Block && ((Block) replacement).statements().size() == 0) {
		if (ASTNodes.isControlStatementBody(toRemove.getLocationInParent())) {
			rewrite.replace(toRemove, toRemove.getAST().newBlock(), null);
		} else {
			rewrite.remove(toRemove, null);
		}

	} else if (toRemove instanceof Expression && replacement instanceof Expression) {
		Expression moved = (Expression) rewrite.createMoveTarget(replacement);
		Expression toRemoveExpression = (Expression) toRemove;
		Expression replacementExpression = (Expression) replacement;
		ITypeBinding explicitCast = ASTNodes.getExplicitCast(replacementExpression, toRemoveExpression);
		if (explicitCast != null) {
			CastExpression cast = ast.newCastExpression();
			if (NecessaryParenthesesChecker.needsParentheses(replacementExpression, cast, CastExpression.EXPRESSION_PROPERTY)) {
				ParenthesizedExpression parenthesized = ast.newParenthesizedExpression();
				parenthesized.setExpression(moved);
				moved = parenthesized;
			}
			cast.setExpression(moved);
			ImportRewrite imports = proposal.createImportRewrite(context.getASTRoot());
			ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(toRemove, imports);
			cast.setType(imports.addImport(explicitCast, ast, importRewriteContext, TypeLocation.CAST));
			moved = cast;
		}
		rewrite.replace(toRemove, moved, null);

	} else {
		ASTNode parent = toRemove.getParent();
		ASTNode moveTarget;
		if ((parent instanceof Block || parent instanceof SwitchStatement) && replacement instanceof Block) {
			ListRewrite listRewrite = rewrite.getListRewrite(replacement, Block.STATEMENTS_PROPERTY);
			List<Statement> list = ((Block) replacement).statements();
			int lastIndex = list.size() - 1;
			moveTarget = listRewrite.createMoveTarget(list.get(0), list.get(lastIndex));
		} else {
			moveTarget = rewrite.createMoveTarget(replacement);
		}

		rewrite.replace(toRemove, moveTarget, null);
	}

	proposals.add(proposal);
}
 
Example #30
Source File: InstanceOfCastExpression.java    From JDeodorant with MIT License 4 votes vote down vote up
public boolean instanceOf(Expression expression) {
	if(expression instanceof CastExpression)
		return true;
	else
		return false;
}