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 File: JavaDebugElementCodeMiningASTVisitor.java    From jdt-codemining with 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 File: PDGSliceUnion.java    From JDeodorant with 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 #3
Source File: Invocations.java    From Eclipse-Postfix-Code-Completion with 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 #4
Source File: Invocations.java    From Eclipse-Postfix-Code-Completion with 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 #5
Source File: JavaCodeMiningASTVisitor.java    From jdt-codemining with 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 #6
Source File: JavaMethodParameterCodeMining.java    From jdt-codemining with 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 #7
Source File: UseValueOfResolution.java    From spotbugs with 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 #8
Source File: AstVisitor.java    From jdt2famix with 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 #9
Source File: CreateDoPrivilegedBlockResolution.java    From spotbugs with 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 File: ConvertAnonymousToNestedRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
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 #11
Source File: ConvertAnonymousToNestedRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
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 #12
Source File: ChangeSignatureProcessor.java    From Eclipse-Postfix-Code-Completion with 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 #13
Source File: PDGSlice.java    From JDeodorant with 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 #14
Source File: StringFormatGenerator.java    From Eclipse-Postfix-Code-Completion with 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 #15
Source File: MoveInnerToTopRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@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 #16
Source File: PDGObjectSliceUnion.java    From JDeodorant with 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 #17
Source File: UseValueOfResolution.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public boolean visit(ClassInstanceCreation node) {
    if (primitiveTypeCreation == null) {
        if (!isPrimitiveTypeCreation(node)) {
            return true;
        }
        this.primitiveTypeCreation = node;
    }
    return false;
}
 
Example #18
Source File: MethodExitsFinder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean visit(ClassInstanceCreation node) {
	if (isExitPoint(node.resolveConstructorBinding())) {
		Type name= node.getType();
		fResult.add(new OccurrenceLocation(name.getStartPosition(), name.getLength(), 0, fExitDescription));
	}
	return true;
}
 
Example #19
Source File: ClassInstanceCreationWriter.java    From juniversal with MIT License 5 votes vote down vote up
@Override
public void write(ASTNode node) {
	ClassInstanceCreation classInstanceCreation = (ClassInstanceCreation) node;

	//TODO: Handle type arguments
	//TODO: Handle different reference operator used for stack objects

	// TODO: Support inner class creation via object.new
	if (classInstanceCreation.getExpression() != null)
		throw sourceNotSupported("Inner classes not yet supported");

	matchAndWrite("new");
	copySpaceAndComments();

       swiftASTWriters.writeNode(classInstanceCreation.getType());
	copySpaceAndComments();

	matchAndWrite("(");
	copySpaceAndComments();

	List<?> arguments = classInstanceCreation.arguments();

	boolean first = true;
	for (Object object : arguments) {
		Expression argument = (Expression) object;

		if (! first) {
			matchAndWrite(",");
			copySpaceAndComments();
		}

           swiftASTWriters.writeNode(argument);
		copySpaceAndComments();

		first = false;
	}

	matchAndWrite(")");
}
 
Example #20
Source File: UseValueOfResolution.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
protected void repairBug(ASTRewrite rewrite, CompilationUnit workingUnit, BugInstance bug) throws BugResolutionException {
    Assert.isNotNull(rewrite);
    Assert.isNotNull(workingUnit);

    ClassInstanceCreation primitiveTypeCreation = findPrimitiveTypeCreation(getASTNode(workingUnit,
            bug.getPrimarySourceLineAnnotation()));
    if (primitiveTypeCreation == null) {
        throw new BugResolutionException("Primitive type creation not found.");
    }
    MethodInvocation valueOfInvocation = createValueOfInvocation(rewrite, workingUnit, primitiveTypeCreation);
    rewrite.replace(primitiveTypeCreation, valueOfInvocation, null);
}
 
Example #21
Source File: ReferenceResolvingVisitor.java    From windup with Eclipse Public License 1.0 5 votes vote down vote up
public boolean visit(org.eclipse.jdt.core.dom.ThrowStatement node)
{
    if (node.getExpression() instanceof ClassInstanceCreation)
    {
        ClassInstanceCreation cic = (ClassInstanceCreation) node.getExpression();
        Type type = cic.getType();
        processType(type, TypeReferenceLocation.THROW_STATEMENT, compilationUnit.getLineNumber(node.getStartPosition()),
                    compilationUnit.getColumnNumber(cic.getStartPosition()), cic.getLength(), node.toString());
    }

    return super.visit(node);
}
 
Example #22
Source File: LambdaExpressionsFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static LambdaExpressionsFix createConvertToLambdaFix(ClassInstanceCreation cic) {
	CompilationUnit root= (CompilationUnit) cic.getRoot();
	if (!JavaModelUtil.is18OrHigher(root.getJavaElement().getJavaProject()))
		return null;

	if (!LambdaExpressionsFix.isFunctionalAnonymous(cic))
		return null;

	CreateLambdaOperation op= new CreateLambdaOperation(Collections.singletonList(cic));
	return new LambdaExpressionsFix(FixMessages.LambdaExpressionsFix_convert_to_lambda_expression, root, new CompilationUnitRewriteOperation[] { op });
}
 
Example #23
Source File: SourceAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean visit(ClassInstanceCreation node) {
	if (fTypeCounter == 0) {
		Expression receiver= node.getExpression();
		if (receiver == null) {
			if (node.resolveTypeBinding().isLocal())
				fImplicitReceivers.add(node);
		}
	}
	return true;
}
 
Example #24
Source File: SemanticHighlightings.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Extracts the binding from the token's simple name.
 * Works around bug 62605 to return the correct constructor binding in a ClassInstanceCreation.
 *
 * @param token the token to extract the binding from
 * @return the token's binding, or <code>null</code>
 */
private static IBinding getBinding(SemanticToken token) {
	ASTNode node= token.getNode();
	ASTNode normalized= ASTNodes.getNormalizedNode(node);
	if (normalized.getLocationInParent() == ClassInstanceCreation.TYPE_PROPERTY) {
		// work around: https://bugs.eclipse.org/bugs/show_bug.cgi?id=62605
		return ((ClassInstanceCreation) normalized.getParent()).resolveConstructorBinding();
	}
	return token.getBinding();
}
 
Example #25
Source File: CodeStyleFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel model) throws CoreException {
	TextEditGroup group= createTextEditGroup(FixMessages.CodeStyleFix_ChangeAccessUsingDeclaring_description, cuRewrite);

	if (fQualifier instanceof MethodInvocation || fQualifier instanceof ClassInstanceCreation)
		extractQualifier(fQualifier, cuRewrite, group);

	Type type= importType(fDeclaringTypeBinding, fQualifier, cuRewrite.getImportRewrite(), cuRewrite.getRoot());
	cuRewrite.getASTRewrite().replace(fQualifier, type, group);
}
 
Example #26
Source File: CreateDoPrivilegedBlockResolution.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
protected void repairBug(ASTRewrite rewrite, CompilationUnit workingUnit, BugInstance bug) throws BugResolutionException {
    Assert.isNotNull(rewrite);
    Assert.isNotNull(workingUnit);
    Assert.isNotNull(bug);

    ClassInstanceCreation classLoaderCreation = findClassLoaderCreation(getASTNode(workingUnit,
            bug.getPrimarySourceLineAnnotation()));
    if (classLoaderCreation == null) {
        throw new BugResolutionException("No matching class loader creation found at the specified source line.");
    }
    updateVariableReferences(rewrite, classLoaderCreation);
    rewrite.replace(classLoaderCreation, createDoPrivilegedInvocation(rewrite, classLoaderCreation), null);
    updateImportDeclarations(rewrite, workingUnit);
}
 
Example #27
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 #28
Source File: VarargsWarningsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static void addAddSafeVarargsToDeclarationProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
	if (!JavaModelUtil.is17OrHigher(context.getCompilationUnit().getJavaProject()))
		return;

	ASTNode coveringNode= problem.getCoveringNode(context.getASTRoot());
	IMethodBinding methodBinding;
	if (coveringNode instanceof MethodInvocation) {
		methodBinding= ((MethodInvocation) coveringNode).resolveMethodBinding();
	} else if (coveringNode instanceof ClassInstanceCreation) {
		methodBinding= ((ClassInstanceCreation) coveringNode).resolveConstructorBinding();
	} else {
		return;
	}
	if (methodBinding == null)
		return;
	
	String label= Messages.format(CorrectionMessages.VarargsWarningsSubProcessor_add_safevarargs_to_method_label, methodBinding.getName());

	ITypeBinding declaringType= methodBinding.getDeclaringClass();
	CompilationUnit astRoot= (CompilationUnit) coveringNode.getRoot();
	if (declaringType != null && declaringType.isFromSource()) {
		try {
			ICompilationUnit targetCu= ASTResolving.findCompilationUnitForBinding(context.getCompilationUnit(), astRoot, declaringType);
			if (targetCu != null) {
				AddSafeVarargsProposal proposal= new AddSafeVarargsProposal(label, targetCu, null, methodBinding.getMethodDeclaration(), IProposalRelevance.ADD_SAFEVARARGS);
				proposals.add(proposal);
			}
		} catch (JavaModelException e) {
			return;
		}
	}
}
 
Example #29
Source File: ReferenceResolvingVisitor.java    From windup with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean visit(ReturnStatement node)
{
    if (node.getExpression() instanceof ClassInstanceCreation)
    {
        ClassInstanceCreation cic = (ClassInstanceCreation) node.getExpression();
        ITypeBinding typeBinding = cic.getType().resolveBinding();
        if (typeBinding == null)
        {
            String qualifiedClass = cic.getType().toString();
            ResolveClassnameResult result = resolveClassname(qualifiedClass);
            qualifiedClass = result.result;
            ResolutionStatus resolutionStatus = result.found ? ResolutionStatus.RECOVERED : ResolutionStatus.UNRESOLVED;
            PackageAndClassName packageAndClassName = PackageAndClassName.parseFromQualifiedName(qualifiedClass);

            processTypeAsString(qualifiedClass, packageAndClassName.packageName, packageAndClassName.className, resolutionStatus,
                        TypeReferenceLocation.CONSTRUCTOR_CALL,
                        compilationUnit.getLineNumber(node.getStartPosition()),
                        compilationUnit.getColumnNumber(cic.getStartPosition()), cic.getLength(), node.toString());
        }
        else
        {
            processTypeBinding(typeBinding, ResolutionStatus.RESOLVED, TypeReferenceLocation.CONSTRUCTOR_CALL,
                        compilationUnit.getLineNumber(node.getStartPosition()),
                        compilationUnit.getColumnNumber(cic.getStartPosition()), cic.getLength(), node.toString());
        }
    }
    return super.visit(node);
}
 
Example #30
Source File: CreateDoPrivilegedBlockResolution.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
private AnonymousClassDeclaration createAnonymousClassDeclaration(ASTRewrite rewrite,
        ClassInstanceCreation classLoaderCreation) {
    AST ast = rewrite.getAST();

    AnonymousClassDeclaration anonymousClassDeclaration = ast.newAnonymousClassDeclaration();
    MethodDeclaration runMethodDeclaration = createRunMethodDeclaration(rewrite, classLoaderCreation);
    List<BodyDeclaration> bodyDeclarations = checkedList(anonymousClassDeclaration.bodyDeclarations());

    bodyDeclarations.add(runMethodDeclaration);

    return anonymousClassDeclaration;
}