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

The following examples show how to use org.eclipse.jdt.core.dom.ClassInstanceCreation. 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 Project: jdt-codemining   Author: angelozerr   File: JavaDebugElementCodeMiningASTVisitor.java    License: Eclipse Public License 1.0 6 votes vote down vote up
@Override
public boolean visit(ClassInstanceCreation node) {
	if (inFrame) {
		List arguments = node.arguments();
		if (arguments.size() > 0) {
			for (int i = 0; i < arguments.size(); i++) {
				Expression exp = (Expression) arguments.get(i);
				if (exp instanceof SimpleName) {
					AbstractDebugVariableCodeMining<IJavaStackFrame> m = new JavaDebugElementCodeMining(
							(SimpleName) exp, fFrame, viewer, provider);
					minings.add(m);
				}
			}
		}
	}
	return super.visit(node);
}
 
Example #2
Source Project: jdt-codemining   Author: angelozerr   File: JavaMethodParameterCodeMining.java    License: Eclipse Public License 1.0 6 votes vote down vote up
private void updateLabel() {
	IMethodBinding calledMethodBinding = ((node instanceof MethodInvocation)
			? ((MethodInvocation) node).resolveMethodBinding()
			: ((ClassInstanceCreation) node).resolveConstructorBinding());
	try {
		IMethod method = getMethod(calledMethodBinding);
		if (method == null || !acceptMethod(method)) {
			super.setLabel("");
		} else {
			String label = calledMethodBinding != null
					? getParameterLabel(method, calledMethodBinding.getDeclaringClass())
					: null;
			super.setLabel(label != null ? label : "");
		}
	} catch (JavaModelException e) {
		super.setLabel("");
	}
}
 
Example #3
Source Project: jdt-codemining   Author: angelozerr   File: JavaCodeMiningASTVisitor.java    License: Eclipse Public License 1.0 6 votes vote down vote up
@Override
public boolean visit(ClassInstanceCreation node) {
	/*
	 * if (Utils.isGeneratedByLombok(node)) { return super.visit(node); }
	 */
	if (showParameterName || showParameterType) {
		List arguments = node.arguments();
		if (arguments.size() > 0 && acceptMethod(node)) {
			for (int i = 0; i < arguments.size(); i++) {
				Expression exp = (Expression) arguments.get(i);
				if (showParameterOnlyForLiteral && !isLiteral(exp)) {
					continue;
				}
				minings.add(new JavaMethodParameterCodeMining(node, exp, i, cu, provider, showParameterName,
						showParameterType, showParameterByUsingFilters));
			}
		}
	}
	return super.visit(node);
}
 
Example #4
Source Project: JDeodorant   Author: tsantalis   File: PDGSliceUnion.java    License: MIT License 6 votes vote down vote up
private boolean duplicatedSliceNodeWithClassInstantiationHasDependenceOnRemovableNode() {
	Set<PDGNode> duplicatedNodes = new LinkedHashSet<PDGNode>();
	duplicatedNodes.addAll(sliceNodes);
	duplicatedNodes.retainAll(indispensableNodes);
	for(PDGNode duplicatedNode : duplicatedNodes) {
		if(duplicatedNode.containsClassInstanceCreation()) {
			Map<VariableDeclaration, ClassInstanceCreation> classInstantiations = duplicatedNode.getClassInstantiations();
			for(VariableDeclaration variableDeclaration : classInstantiations.keySet()) {
				for(GraphEdge edge : duplicatedNode.outgoingEdges) {
					PDGDependence dependence = (PDGDependence)edge;
					if(subgraph.edgeBelongsToBlockBasedRegion(dependence) && dependence instanceof PDGDependence) {
						PDGDependence dataDependence = (PDGDependence)dependence;
						PDGNode dstPDGNode = (PDGNode)dataDependence.dst;
						if(removableNodes.contains(dstPDGNode)) {
							if(dstPDGNode.changesStateOfReference(variableDeclaration) ||
									dstPDGNode.assignsReference(variableDeclaration) || dstPDGNode.accessesReference(variableDeclaration))
								return true;
						}
					}
				}
			}
		}
	}
	return false;
}
 
Example #5
private IMethodBinding getSuperConstructorBinding() {
    //workaround for missing java core functionality - finding a
    // super constructor for an anonymous class creation
    IMethodBinding anonConstr= ((ClassInstanceCreation) fAnonymousInnerClassNode.getParent()).resolveConstructorBinding();
    if (anonConstr == null)
        return null;
    ITypeBinding superClass= anonConstr.getDeclaringClass().getSuperclass();
    IMethodBinding[] superMethods= superClass.getDeclaredMethods();
    for (int i= 0; i < superMethods.length; i++) {
        IMethodBinding superMethod= superMethods[i];
        if (superMethod.isConstructor() && parameterTypesMatch(superMethod, anonConstr))
            return superMethod;
    }
    Assert.isTrue(false);//there's no way - it must be there
    return null;
}
 
Example #6
private ASTNode createNewClassInstanceCreation(CompilationUnitRewrite rewrite, ITypeBinding[] parameters) {
	AST ast= fAnonymousInnerClassNode.getAST();
	ClassInstanceCreation newClassCreation= ast.newClassInstanceCreation();
	newClassCreation.setAnonymousClassDeclaration(null);
	Type type= null;
	SimpleName newNameNode= ast.newSimpleName(fClassName);
	if (parameters.length > 0) {
		final ParameterizedType parameterized= ast.newParameterizedType(ast.newSimpleType(newNameNode));
		for (int index= 0; index < parameters.length; index++)
			parameterized.typeArguments().add(ast.newSimpleType(ast.newSimpleName(parameters[index].getName())));
		type= parameterized;
	} else
		type= ast.newSimpleType(newNameNode);
	newClassCreation.setType(type);
	copyArguments(rewrite, newClassCreation);
	addArgumentsForLocalsUsedInInnerClass(newClassCreation);

	addLinkedPosition(KEY_TYPE_NAME, newNameNode, rewrite.getASTRewrite(), true);

	return newClassCreation;
}
 
Example #7
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: ChangeSignatureProcessor.java    License: Eclipse Public License 1.0 6 votes vote down vote up
protected String getFullTypeName() {
	ASTNode node= getNode();
	while (true) {
		node= node.getParent();
		if (node instanceof AbstractTypeDeclaration) {
			String typeName= ((AbstractTypeDeclaration) node).getName().getIdentifier();
			if (getNode() instanceof LambdaExpression) {
				return Messages.format(RefactoringCoreMessages.ChangeSignatureRefactoring_lambda_expression, typeName);
			}
			return typeName;
		} else if (node instanceof ClassInstanceCreation) {
			ClassInstanceCreation cic= (ClassInstanceCreation) node;
			return Messages.format(RefactoringCoreMessages.ChangeSignatureRefactoring_anonymous_subclass, BasicElementLabels.getJavaElementName(ASTNodes.asString(cic.getType())));
		} else if (node instanceof EnumConstantDeclaration) {
			EnumDeclaration ed= (EnumDeclaration) node.getParent();
			return Messages.format(RefactoringCoreMessages.ChangeSignatureRefactoring_anonymous_subclass, BasicElementLabels.getJavaElementName(ASTNodes.asString(ed.getName())));
		}
	}
}
 
Example #8
Source Project: JDeodorant   Author: tsantalis   File: PDGObjectSliceUnion.java    License: MIT License 6 votes vote down vote up
private boolean duplicatedSliceNodeWithClassInstantiationHasDependenceOnRemovableNode() {
	Set<PDGNode> duplicatedNodes = new LinkedHashSet<PDGNode>();
	duplicatedNodes.addAll(sliceNodes);
	duplicatedNodes.retainAll(indispensableNodes);
	for(PDGNode duplicatedNode : duplicatedNodes) {
		if(duplicatedNode.containsClassInstanceCreation()) {
			Map<VariableDeclaration, ClassInstanceCreation> classInstantiations = duplicatedNode.getClassInstantiations();
			for(VariableDeclaration variableDeclaration : classInstantiations.keySet()) {
				for(GraphEdge edge : duplicatedNode.outgoingEdges) {
					PDGDependence dependence = (PDGDependence)edge;
					if(subgraph.edgeBelongsToBlockBasedRegion(dependence) && dependence instanceof PDGDependence) {
						PDGDependence dataDependence = (PDGDependence)dependence;
						PDGNode dstPDGNode = (PDGNode)dataDependence.dst;
						if(removableNodes.contains(dstPDGNode)) {
							if(dstPDGNode.changesStateOfReference(variableDeclaration) ||
									dstPDGNode.assignsReference(variableDeclaration) || dstPDGNode.accessesReference(variableDeclaration))
								return true;
						}
					}
				}
			}
		}
	}
	return false;
}
 
Example #9
Source Project: spotbugs   Author: spotbugs   File: CreateDoPrivilegedBlockResolution.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
private MethodDeclaration createRunMethodDeclaration(ASTRewrite rewrite, ClassInstanceCreation classLoaderCreation) {
    AST ast = rewrite.getAST();

    MethodDeclaration methodDeclaration = ast.newMethodDeclaration();
    SimpleName methodName = ast.newSimpleName("run");
    Type returnType = (Type) rewrite.createCopyTarget(classLoaderCreation.getType());
    Block methodBody = createRunMethodBody(rewrite, classLoaderCreation);
    List<Modifier> modifiers = checkedList(methodDeclaration.modifiers());

    modifiers.add(ast.newModifier(PUBLIC_KEYWORD));
    methodDeclaration.setName(methodName);
    methodDeclaration.setReturnType2(returnType);
    methodDeclaration.setBody(methodBody);

    return methodDeclaration;
}
 
Example #10
Source Project: spotbugs   Author: spotbugs   File: UseValueOfResolution.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
protected MethodInvocation createValueOfInvocation(ASTRewrite rewrite, CompilationUnit compilationUnit,
        ClassInstanceCreation primitiveTypeCreation) {
    Assert.isNotNull(rewrite);
    Assert.isNotNull(primitiveTypeCreation);

    final AST ast = rewrite.getAST();
    MethodInvocation valueOfInvocation = ast.newMethodInvocation();
    valueOfInvocation.setName(ast.newSimpleName(VALUE_OF_METHOD_NAME));

    ITypeBinding binding = primitiveTypeCreation.getType().resolveBinding();
    if (isStaticImport()) {
        addStaticImports(rewrite, compilationUnit, binding.getQualifiedName() + "." + VALUE_OF_METHOD_NAME);
    } else {
        valueOfInvocation.setExpression(ast.newSimpleName(binding.getName()));
    }

    List<?> arguments = primitiveTypeCreation.arguments();
    List<Expression> newArguments = valueOfInvocation.arguments();
    for (Object argument : arguments) {
        Expression expression = (Expression) rewrite.createCopyTarget((ASTNode) argument);
        newArguments.add(expression);
    }

    return valueOfInvocation;
}
 
Example #11
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: Invocations.java    License: Eclipse Public License 1.0 6 votes vote down vote up
public static ITypeBinding[] getInferredTypeArguments(Expression invocation) {
	IMethodBinding methodBinding;
	switch (invocation.getNodeType()) {
		case ASTNode.METHOD_INVOCATION:
			methodBinding= ((MethodInvocation) invocation).resolveMethodBinding();
			return methodBinding == null ? null : methodBinding.getTypeArguments();
		case ASTNode.SUPER_METHOD_INVOCATION:
			methodBinding= ((SuperMethodInvocation) invocation).resolveMethodBinding();
			return methodBinding == null ? null : methodBinding.getTypeArguments();
		case ASTNode.CLASS_INSTANCE_CREATION:
			Type type= ((ClassInstanceCreation) invocation).getType();
			ITypeBinding typeBinding= type.resolveBinding();
			return typeBinding == null ? null : typeBinding.getTypeArguments();
			
		default:
			throw new IllegalArgumentException(invocation.toString());
	}
}
 
Example #12
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: Invocations.java    License: Eclipse Public License 1.0 6 votes vote down vote up
public static ChildListPropertyDescriptor getArgumentsProperty(ASTNode invocation) {
	switch (invocation.getNodeType()) {
		case ASTNode.METHOD_INVOCATION:
			return MethodInvocation.ARGUMENTS_PROPERTY;
		case ASTNode.SUPER_METHOD_INVOCATION:
			return SuperMethodInvocation.ARGUMENTS_PROPERTY;
			
		case ASTNode.CONSTRUCTOR_INVOCATION:
			return ConstructorInvocation.ARGUMENTS_PROPERTY;
		case ASTNode.SUPER_CONSTRUCTOR_INVOCATION:
			return SuperConstructorInvocation.ARGUMENTS_PROPERTY;
			
		case ASTNode.CLASS_INSTANCE_CREATION:
			return ClassInstanceCreation.ARGUMENTS_PROPERTY;
		case ASTNode.ENUM_CONSTANT_DECLARATION:
			return EnumConstantDeclaration.ARGUMENTS_PROPERTY;
			
		default:
			throw new IllegalArgumentException(invocation.toString());
	}
}
 
Example #13
Source Project: jdt2famix   Author: feenkcom   File: AstVisitor.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * handles new Class()
 */
@SuppressWarnings("unchecked")
@Override
public boolean visit(ClassInstanceCreation node) {
	IMethodBinding binding = node.resolveConstructorBinding();
	if (binding != null) {
		Invocation invocation = importer.createInvocationFromMethodBinding(binding, node.toString().trim());
		importer.createLightweightSourceAnchor(invocation, node.getType());
	} else {
		String name = node.getType().toString();
		importer.ensureBasicMethod(name, name, importer.ensureTypeNamedInUnknownNamespace(name),
				m -> importer.createInvocationToMethod(m, node.toString().trim()));
	}

	node.arguments().stream().forEach(arg -> importer.createAccessFromExpression((Expression) arg));
	return true;
}
 
Example #14
@Override
public boolean visit(final ClassInstanceCreation node) {
	Assert.isNotNull(node);
	if (fCreateInstanceField) {
		final AST ast= node.getAST();
		final Type type= node.getType();
		final ITypeBinding binding= type.resolveBinding();
		if (binding != null && binding.getDeclaringClass() != null && !Bindings.equals(binding, fTypeBinding) && fSourceRewrite.getRoot().findDeclaringNode(binding) != null) {
			if (!Modifier.isStatic(binding.getModifiers())) {
				Expression expression= null;
				if (fCodeGenerationSettings.useKeywordThis || fEnclosingInstanceFieldName.equals(fNameForEnclosingInstanceConstructorParameter)) {
					final FieldAccess access= ast.newFieldAccess();
					access.setExpression(ast.newThisExpression());
					access.setName(ast.newSimpleName(fEnclosingInstanceFieldName));
					expression= access;
				} else
					expression= ast.newSimpleName(fEnclosingInstanceFieldName);
				if (node.getExpression() != null)
					fSourceRewrite.getImportRemover().registerRemovedNode(node.getExpression());
				fSourceRewrite.getASTRewrite().set(node, ClassInstanceCreation.EXPRESSION_PROPERTY, expression, fGroup);
			} else
				addTypeQualification(type, fSourceRewrite, fGroup);
		}
	}
	return true;
}
 
Example #15
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: StringFormatGenerator.java    License: Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected Expression createMemberAccessExpression(Object member, boolean ignoreArraysCollections, boolean ignoreNulls) {
	ITypeBinding type= getMemberType(member);
	if (!getContext().is50orHigher() && type.isPrimitive()) {
		String nonPrimitiveType= null;
		String typeName= type.getName();
		if (typeName.equals("byte"))nonPrimitiveType= "java.lang.Byte"; //$NON-NLS-1$ //$NON-NLS-2$
		if (typeName.equals("short"))nonPrimitiveType= "java.lang.Short"; //$NON-NLS-1$ //$NON-NLS-2$
		if (typeName.equals("char"))nonPrimitiveType= "java.lang.Character"; //$NON-NLS-1$ //$NON-NLS-2$
		if (typeName.equals("int"))nonPrimitiveType= "java.lang.Integer"; //$NON-NLS-1$ //$NON-NLS-2$
		if (typeName.equals("long"))nonPrimitiveType= "java.lang.Long"; //$NON-NLS-1$ //$NON-NLS-2$
		if (typeName.equals("float"))nonPrimitiveType= "java.lang.Float"; //$NON-NLS-1$ //$NON-NLS-2$
		if (typeName.equals("double"))nonPrimitiveType= "java.lang.Double"; //$NON-NLS-1$ //$NON-NLS-2$
		if (typeName.equals("boolean"))nonPrimitiveType= "java.lang.Boolean"; //$NON-NLS-1$ //$NON-NLS-2$
		ClassInstanceCreation classInstance= fAst.newClassInstanceCreation();
		classInstance.setType(fAst.newSimpleType(addImport(nonPrimitiveType)));
		classInstance.arguments().add(super.createMemberAccessExpression(member, true, true));
		return classInstance;
	}
	return super.createMemberAccessExpression(member, ignoreArraysCollections, ignoreNulls);
}
 
Example #16
Source Project: JDeodorant   Author: tsantalis   File: PDGSlice.java    License: MIT License 6 votes vote down vote up
private boolean duplicatedSliceNodeWithClassInstantiationHasDependenceOnRemovableNode() {
	Set<PDGNode> duplicatedNodes = new LinkedHashSet<PDGNode>();
	duplicatedNodes.addAll(sliceNodes);
	duplicatedNodes.retainAll(indispensableNodes);
	for(PDGNode duplicatedNode : duplicatedNodes) {
		if(duplicatedNode.containsClassInstanceCreation()) {
			Map<VariableDeclaration, ClassInstanceCreation> classInstantiations = duplicatedNode.getClassInstantiations();
			for(VariableDeclaration variableDeclaration : classInstantiations.keySet()) {
				for(GraphEdge edge : duplicatedNode.outgoingEdges) {
					PDGDependence dependence = (PDGDependence)edge;
					if(edges.contains(dependence) && dependence instanceof PDGDependence) {
						PDGDependence dataDependence = (PDGDependence)dependence;
						PDGNode dstPDGNode = (PDGNode)dataDependence.dst;
						if(removableNodes.contains(dstPDGNode)) {
							if(dstPDGNode.changesStateOfReference(variableDeclaration) ||
									dstPDGNode.assignsReference(variableDeclaration) || dstPDGNode.accessesReference(variableDeclaration))
								return true;
						}
					}
				}
			}
		}
	}
	return false;
}
 
Example #17
Source Project: jdt-codemining   Author: angelozerr   File: MethodFilterManager.java    License: Eclipse Public License 1.0 5 votes vote down vote up
public boolean match(ClassInstanceCreation node) {
	initializeIfNeeded();
	for (MethodFilter methodFilter : filters) {
		if (methodFilter.match(node)) {
			return true;
		}
	}
	return false;
}
 
Example #18
private static Expression getBooleanExpression(ASTNode node) {
	if (!(node instanceof Expression)) {
		return null;
	}

	// check if the node is a location where it can be negated
	StructuralPropertyDescriptor locationInParent= node.getLocationInParent();
	if (locationInParent == QualifiedName.NAME_PROPERTY) {
		node= node.getParent();
		locationInParent= node.getLocationInParent();
	}
	while (locationInParent == ParenthesizedExpression.EXPRESSION_PROPERTY) {
		node= node.getParent();
		locationInParent= node.getLocationInParent();
	}
	Expression expression= (Expression) node;
	if (!isBoolean(expression)) {
		return null;
	}
	if (expression.getParent() instanceof InfixExpression) {
		return expression;
	}
	if (locationInParent == Assignment.RIGHT_HAND_SIDE_PROPERTY || locationInParent == IfStatement.EXPRESSION_PROPERTY
			|| locationInParent == WhileStatement.EXPRESSION_PROPERTY || locationInParent == DoStatement.EXPRESSION_PROPERTY
			|| locationInParent == ReturnStatement.EXPRESSION_PROPERTY || locationInParent == ForStatement.EXPRESSION_PROPERTY
			|| locationInParent == AssertStatement.EXPRESSION_PROPERTY || locationInParent == MethodInvocation.ARGUMENTS_PROPERTY
			|| locationInParent == ConstructorInvocation.ARGUMENTS_PROPERTY || locationInParent == SuperMethodInvocation.ARGUMENTS_PROPERTY
			|| locationInParent == EnumConstantDeclaration.ARGUMENTS_PROPERTY || locationInParent == SuperConstructorInvocation.ARGUMENTS_PROPERTY
			|| locationInParent == ClassInstanceCreation.ARGUMENTS_PROPERTY || locationInParent == ConditionalExpression.EXPRESSION_PROPERTY
			|| locationInParent == PrefixExpression.OPERAND_PROPERTY) {
		return expression;
	}
	return null;
}
 
Example #19
Source Project: JDeodorant   Author: tsantalis   File: AbstractMethodFragment.java    License: MIT License 5 votes vote down vote up
protected void processThrowStatement(ThrowStatement throwStatement) {
	Expression expression = throwStatement.getExpression();
	if(expression instanceof ClassInstanceCreation) {
		ClassInstanceCreation creation = (ClassInstanceCreation)expression;
		ITypeBinding typeBinding = creation.getType().resolveBinding();
		addExceptionInThrowStatement(typeBinding.getQualifiedName());
	}
}
 
Example #20
Source Project: JDeodorant   Author: tsantalis   File: PDGNode.java    License: MIT License 5 votes vote down vote up
protected void processArgumentsOfInternalClassInstanceCreation(ClassInstanceCreationObject classInstanceCreationObject, AbstractVariable variable) {
	SystemObject systemObject = ASTReader.getSystemObject();
	ClassInstanceCreation classInstanceCreation = classInstanceCreationObject.getClassInstanceCreation();
	IMethodBinding methodBinding = classInstanceCreation.resolveConstructorBinding();
	ClassObject classObject = systemObject.getClassObject(classInstanceCreationObject.getType().getClassType());
	ConstructorObject constructorObject = null;
	if(classObject != null) {
		constructorObject = classObject.getConstructor(classInstanceCreationObject);
	}
	if((classObject == null && !methodBinding.getDeclaringClass().isAnonymous() && !methodBinding.getDeclaringClass().isLocal()) || constructorObject != null) {
		//classObject == null && !methodBinding.getDeclaringClass().isAnonymous() => external constructor call that is not an anonymous class declaration
		//constructorObject != null => the internal constructor might not exist, in the case the default constructor is called
		methodCallAnalyzer.processArgumentsOfInternalMethodInvocation(classObject, constructorObject, classInstanceCreation.arguments(), methodBinding, variable);
	}
}
 
Example #21
Source Project: SparkBuilderGenerator   Author: helospark   File: BuildMethodBodyCreatorFragment.java    License: MIT License 5 votes vote down vote up
public Block createBody(AST ast, TypeDeclaration originalType) {
    ClassInstanceCreation newClassInstanceCreation = ast.newClassInstanceCreation();
    newClassInstanceCreation.setType(ast.newSimpleType(ast.newName(originalType.getName().toString())));
    newClassInstanceCreation.arguments().add(ast.newThisExpression());

    ReturnStatement statement = ast.newReturnStatement();
    statement.setExpression(newClassInstanceCreation);

    Block block = ast.newBlock();
    block.statements().add(statement);
    return block;
}
 
Example #22
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: ASTNodeDeleteUtil.java    License: Eclipse Public License 1.0 5 votes vote down vote up
private static ASTNode[] getNodesToDelete(IJavaElement element, CompilationUnit cuNode) throws JavaModelException {
	// fields are different because you don't delete the whole declaration but only a fragment of it
	if (element.getElementType() == IJavaElement.FIELD) {
		if (JdtFlags.isEnum((IField) element))
			return new ASTNode[] { ASTNodeSearchUtil.getEnumConstantDeclaration((IField) element, cuNode)};
		else
			return new ASTNode[] { ASTNodeSearchUtil.getFieldDeclarationFragmentNode((IField) element, cuNode)};
	}
	if (element.getElementType() == IJavaElement.TYPE && ((IType) element).isLocal()) {
		IType type= (IType) element;
		if (type.isAnonymous()) {
			if (type.getParent().getElementType() == IJavaElement.FIELD) {
				EnumConstantDeclaration enumDecl= ASTNodeSearchUtil.getEnumConstantDeclaration((IField) element.getParent(), cuNode);
				if (enumDecl != null && enumDecl.getAnonymousClassDeclaration() != null)  {
					return new ASTNode[] { enumDecl.getAnonymousClassDeclaration() };
				}
			}
			ClassInstanceCreation creation= ASTNodeSearchUtil.getClassInstanceCreationNode(type, cuNode);
			if (creation != null) {
				if (creation.getLocationInParent() == ExpressionStatement.EXPRESSION_PROPERTY) {
					return new ASTNode[] { creation.getParent() };
				} else if (creation.getLocationInParent() == VariableDeclarationFragment.INITIALIZER_PROPERTY) {
					return new ASTNode[] { creation};
				}
				return new ASTNode[] { creation.getAnonymousClassDeclaration() };
			}
			return new ASTNode[0];
		} else {
			ASTNode[] nodes= ASTNodeSearchUtil.getDeclarationNodes(element, cuNode);
			// we have to delete the TypeDeclarationStatement
			nodes[0]= nodes[0].getParent();
			return nodes;
		}
	}
	return ASTNodeSearchUtil.getDeclarationNodes(element, cuNode);
}
 
Example #23
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: TargetProvider.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean visit(ClassInstanceCreation node) {
	if (matches(node.resolveConstructorBinding()) && fCurrent != null) {
		fCurrent.addInvocation(node);
	}
	return true;
}
 
Example #24
Source Project: SparkBuilderGenerator   Author: helospark   File: BlockWithNewBuilderCreationFragment.java    License: MIT License 5 votes vote down vote up
public Block createReturnBlock(AST ast, TypeDeclaration builderType) {
    Block builderMethodBlock = ast.newBlock();
    ReturnStatement returnStatement = ast.newReturnStatement();
    ClassInstanceCreation newClassInstanceCreation = ast.newClassInstanceCreation();
    newClassInstanceCreation.setType(ast.newSimpleType(ast.newName(builderType.getName().toString())));
    returnStatement.setExpression(newClassInstanceCreation);
    builderMethodBlock.statements().add(returnStatement);
    return builderMethodBlock;
}
 
Example #25
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: ASTNodes.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns whether an expression at the given location needs explicit boxing.
 * 
 * @param expression the expression
 * @return <code>true</code> iff an expression at the given location needs explicit boxing
 * @since 3.6
 */
private static boolean needsExplicitBoxing(Expression expression) {
	StructuralPropertyDescriptor locationInParent= expression.getLocationInParent();
	if (locationInParent == ParenthesizedExpression.EXPRESSION_PROPERTY)
		return needsExplicitBoxing((ParenthesizedExpression) expression.getParent());
	
	if (locationInParent == ClassInstanceCreation.EXPRESSION_PROPERTY
			|| locationInParent == FieldAccess.EXPRESSION_PROPERTY
			|| locationInParent == MethodInvocation.EXPRESSION_PROPERTY)
		return true;
	
	return false;
}
 
Example #26
Source Project: eclipse.jdt.ls   Author: eclipse   File: FlowAnalyzer.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void endVisit(ClassInstanceCreation node) {
	if (skipNode(node)) {
		return;
	}
	GenericSequentialFlowInfo info = processSequential(node, node.getExpression());
	process(info, node.getType());
	process(info, node.arguments());
	process(info, node.getAnonymousClassDeclaration());
}
 
Example #27
Source Project: eclipse.jdt.ls   Author: eclipse   File: ExtractFieldRefactoring.java    License: 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 #28
Source Project: eclipse.jdt.ls   Author: eclipse   File: ASTNodeDeleteUtil.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private static ASTNode[] getNodesToDelete(IJavaElement element, CompilationUnit cuNode) throws JavaModelException {
	// fields are different because you don't delete the whole declaration but only a fragment of it
	if (element.getElementType() == IJavaElement.FIELD) {
		if (JdtFlags.isEnum((IField) element)) {
			return new ASTNode[] { ASTNodeSearchUtil.getEnumConstantDeclaration((IField) element, cuNode)};
		} else {
			return new ASTNode[] { ASTNodeSearchUtil.getFieldDeclarationFragmentNode((IField) element, cuNode)};
		}
	}
	if (element.getElementType() == IJavaElement.TYPE && ((IType) element).isLocal()) {
		IType type= (IType) element;
		if (type.isAnonymous()) {
			if (type.getParent().getElementType() == IJavaElement.FIELD) {
				EnumConstantDeclaration enumDecl= ASTNodeSearchUtil.getEnumConstantDeclaration((IField) element.getParent(), cuNode);
				if (enumDecl != null && enumDecl.getAnonymousClassDeclaration() != null)  {
					return new ASTNode[] { enumDecl.getAnonymousClassDeclaration() };
				}
			}
			ClassInstanceCreation creation= ASTNodeSearchUtil.getClassInstanceCreationNode(type, cuNode);
			if (creation != null) {
				if (creation.getLocationInParent() == ExpressionStatement.EXPRESSION_PROPERTY) {
					return new ASTNode[] { creation.getParent() };
				} else if (creation.getLocationInParent() == VariableDeclarationFragment.INITIALIZER_PROPERTY) {
					return new ASTNode[] { creation};
				}
				return new ASTNode[] { creation.getAnonymousClassDeclaration() };
			}
			return new ASTNode[0];
		} else {
			ASTNode[] nodes= ASTNodeSearchUtil.getDeclarationNodes(element, cuNode);
			// we have to delete the TypeDeclarationStatement
			nodes[0]= nodes[0].getParent();
			return nodes;
		}
	}
	return ASTNodeSearchUtil.getDeclarationNodes(element, cuNode);
}
 
Example #29
Source Project: eclipse.jdt.ls   Author: eclipse   File: ExceptionAnalyzer.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Override
public boolean visit(ClassInstanceCreation node) {
	if (!isSelected(node)) {
		return false;
	}
	return handleExceptions(node.resolveConstructorBinding(), node);
}
 
Example #30
Source Project: JDeodorant   Author: tsantalis   File: TypeCheckElimination.java    License: MIT License 5 votes vote down vote up
public boolean isTypeCheckMethodStateSetter() {
	InheritanceTree tree = null;
	if(existingInheritanceTree != null)
		tree = existingInheritanceTree;
	else if(inheritanceTreeMatchingWithStaticTypes != null)
		tree = inheritanceTreeMatchingWithStaticTypes;
	if(tree != null) {
		DefaultMutableTreeNode root = tree.getRootNode();
		DefaultMutableTreeNode leaf = root.getFirstLeaf();
		List<String> subclassNames = new ArrayList<String>();
		while(leaf != null) {
			subclassNames.add((String)leaf.getUserObject());
			leaf = leaf.getNextLeaf();
		}
		Block typeCheckMethodBody = typeCheckMethod.getBody();
		List<Statement> statements = typeCheckMethodBody.statements();
		if(statements.size() > 0 && statements.get(0) instanceof SwitchStatement) {
			SwitchStatement switchStatement = (SwitchStatement)statements.get(0);
			List<Statement> statements2 = switchStatement.statements();
			ExpressionExtractor expressionExtractor = new ExpressionExtractor();
			int matchCounter = 0;
			for(Statement statement2 : statements2) {
				if(!(statement2 instanceof SwitchCase) && !(statement2 instanceof BreakStatement)) {
					List<Expression> classInstanceCreations = expressionExtractor.getClassInstanceCreations(statement2);
					if(classInstanceCreations.size() == 1) {
						ClassInstanceCreation classInstanceCreation = (ClassInstanceCreation)classInstanceCreations.get(0);
						Type classInstanceCreationType = classInstanceCreation.getType();
						if(subclassNames.contains(classInstanceCreationType.resolveBinding().getQualifiedName())) {
							matchCounter++;
						}
					}
				}
			}
			if(matchCounter == subclassNames.size())
				return true;
		}
	}
	return false;
}