private ParameterizedType createPrivilegedActionType(ASTRewrite rewrite, ClassInstanceCreation classLoaderCreation) { AST ast = rewrite.getAST(); Name privilegedActionName; if (isUpdateImports()) { privilegedActionName = ast.newSimpleName(PrivilegedAction.class.getSimpleName()); } else { privilegedActionName = ast.newName(PrivilegedAction.class.getName()); } SimpleType rawPrivilegedActionType = ast.newSimpleType(privilegedActionName); ParameterizedType privilegedActionType = ast.newParameterizedType(rawPrivilegedActionType); Type typeArgument = (Type) rewrite.createCopyTarget(classLoaderCreation.getType()); List<Type> typeArguments = checkedList(privilegedActionType.typeArguments()); typeArguments.add(typeArgument); return privilegedActionType; }
public boolean isInvariant(Type type) { if (this.C() != type.C()) return false; if (t == null || ! t.isParameterizedType()) // this type is not yet concretized or not parametric return true; if (! type.T().isParameterizedType()) return false; // sanity check ParameterizedType pt1 = (ParameterizedType) T(); ParameterizedType pt2 = (ParameterizedType) type.T(); int n1 = pt1.typeArguments().size(); int n2 = pt2.typeArguments().size(); if (n1 != n2) throw new SynthesisException(SynthesisException.GenericTypeVariableMismatch); for (int i = 0; i < n1; i++) { Type t1 = new Type((org.eclipse.jdt.core.dom.Type) pt1.typeArguments().get(i)); Type t2 = new Type((org.eclipse.jdt.core.dom.Type) pt2.typeArguments().get(i)); if (! t1.isInvariant(t2)) return false; } return true; }
private void autoConcretize() { concretization = new HashMap<>(); // check sanity of types if (! t.isParameterizedType()) { if (c.getTypeParameters().length > 0) throw new SynthesisException(SynthesisException.GenericTypeVariableMismatch); if (t.isArrayType() && !c.isArray()) throw new SynthesisException(SynthesisException.InvalidKindOfType); return; } ParameterizedType pType = (ParameterizedType) t; int n1 = pType.typeArguments().size(); int n2 = c.getTypeParameters().length; if (n1 != n2) throw new SynthesisException(SynthesisException.GenericTypeVariableMismatch); // unify generic names with their actual types for (int i = 0; i < n1; i++) { String name = c.getTypeParameters()[i].getName(); Type type = new Type((org.eclipse.jdt.core.dom.Type) pType.typeArguments().get(i)); concretization.put(name, type); } }
public static Object provideAnswer(InvocationOnMock inv) { Type type = ((BuilderField) inv.getArguments()[0]).getFieldType(); if (type instanceof ParameterizedType) { Type baseType = ((ParameterizedType) type).getType(); if (baseType instanceof SimpleType) { String name = ((SimpleType) baseType).getName().getFullyQualifiedName(); // if name is fully qualified if (recognisedClasses.contains(name)) { return Optional.ofNullable(name); } Optional<String> found = recognisedClasses.stream() .filter(fqn -> fqn.endsWith("." + name)) .findFirst(); if (found.isPresent()) { return found; } } } return Optional.of("some.other.value"); }
/** * For {@link Name} or {@link Type} nodes, returns the topmost {@link Type} node * that shares the same type binding as the given node. * * @param node an ASTNode * @return the normalized {@link Type} node or the original node */ public static ASTNode getNormalizedNode(ASTNode node) { ASTNode current= node; // normalize name if (QualifiedName.NAME_PROPERTY.equals(current.getLocationInParent())) { current= current.getParent(); } // normalize type if (QualifiedType.NAME_PROPERTY.equals(current.getLocationInParent()) || SimpleType.NAME_PROPERTY.equals(current.getLocationInParent()) || NameQualifiedType.NAME_PROPERTY.equals(current.getLocationInParent())) { current= current.getParent(); } // normalize parameterized types if (ParameterizedType.TYPE_PROPERTY.equals(current.getLocationInParent())) { current= current.getParent(); } return current; }
/** * Create a Type suitable as the creationType in a ClassInstanceCreation expression. * @param ast The AST to create the nodes for. * @param typeBinding binding representing the given class type * @param importRewrite the import rewrite to use * @param importContext the import context used to determine which (null) annotations to consider * @return a Type suitable as the creationType in a ClassInstanceCreation expression. */ public static Type newCreationType(AST ast, ITypeBinding typeBinding, ImportRewrite importRewrite, ImportRewriteContext importContext) { if (typeBinding.isParameterizedType()) { Type baseType= newCreationType(ast, typeBinding.getTypeDeclaration(), importRewrite, importContext); IAnnotationBinding[] typeAnnotations= importContext.removeRedundantTypeAnnotations(typeBinding.getTypeAnnotations(), TypeLocation.NEW, typeBinding); for (IAnnotationBinding typeAnnotation : typeAnnotations) { ((AnnotatableType)baseType).annotations().add(importRewrite.addAnnotation(typeAnnotation, ast, importContext)); } ParameterizedType parameterizedType= ast.newParameterizedType(baseType); for (ITypeBinding typeArgument : typeBinding.getTypeArguments()) { typeArgument= StubUtility2.replaceWildcardsAndCaptures(typeArgument); parameterizedType.typeArguments().add(importRewrite.addImport(typeArgument, ast, importContext, TypeLocation.TYPE_ARGUMENT)); } return parameterizedType; } else { return importRewrite.addImport(typeBinding, ast, importContext, TypeLocation.NEW); } }
private static String[] getVariableNameSuggestions(int variableKind, IJavaProject project, Type expectedType, Collection<String> excluded, boolean evaluateDefault) { int dim= 0; if (expectedType.isArrayType()) { ArrayType arrayType= (ArrayType)expectedType; dim= arrayType.getDimensions(); expectedType= arrayType.getElementType(); } if (expectedType.isParameterizedType()) { expectedType= ((ParameterizedType)expectedType).getType(); } String typeName= ASTNodes.getTypeName(expectedType); if (typeName.length() > 0) { return getVariableNameSuggestions(variableKind, project, typeName, dim, excluded, evaluateDefault); } return EMPTY; }
/** * Returns the declaration node for the originally selected node. * * @param name * the name of the node * * @return the declaration node */ private static ASTNode getDeclarationNode(SimpleName name) { ASTNode parent = name.getParent(); if (!(parent instanceof AbstractTypeDeclaration)) { parent = parent.getParent(); if (parent instanceof ParameterizedType || parent instanceof Type) { parent = parent.getParent(); } if (parent instanceof ClassInstanceCreation) { final ClassInstanceCreation creation = (ClassInstanceCreation) parent; parent = creation.getAnonymousClassDeclaration(); } } return parent; }
@Override public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel positionGroups) throws CoreException { final ASTRewrite rewrite = cuRewrite.getASTRewrite(); VariableDeclarationFragment fragment = null; for (int i = 0; i < fNodes.length; i++) { final ASTNode node = fNodes[i]; final AST ast = node.getAST(); fragment = ast.newVariableDeclarationFragment(); fragment.setName(ast.newSimpleName(NAME_FIELD)); final FieldDeclaration declaration = ast.newFieldDeclaration(fragment); declaration.setType(ast.newPrimitiveType(PrimitiveType.LONG)); declaration.modifiers().addAll(ASTNodeFactory.newModifiers(ast, Modifier.PRIVATE | Modifier.STATIC | Modifier.FINAL)); if (!addInitializer(fragment, node)) { continue; } if (fragment.getInitializer() != null) { final TextEditGroup editGroup = createTextEditGroup(FixMessages.SerialVersion_group_description, cuRewrite); if (node instanceof AbstractTypeDeclaration) { rewrite.getListRewrite(node, ((AbstractTypeDeclaration) node).getBodyDeclarationsProperty()).insertAt(declaration, 0, editGroup); } else if (node instanceof AnonymousClassDeclaration) { rewrite.getListRewrite(node, AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY).insertAt(declaration, 0, editGroup); } else if (node instanceof ParameterizedType) { final ParameterizedType type = (ParameterizedType) node; final ASTNode parent = type.getParent(); if (parent instanceof ClassInstanceCreation) { final ClassInstanceCreation creation = (ClassInstanceCreation) parent; final AnonymousClassDeclaration anonymous = creation.getAnonymousClassDeclaration(); if (anonymous != null) { rewrite.getListRewrite(anonymous, AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY).insertAt(declaration, 0, editGroup); } } } else { Assert.isTrue(false); } addLinkedPositions(rewrite, fragment, positionGroups); } final String comment = CodeGeneration.getFieldComment(fUnit, declaration.getType().toString(), NAME_FIELD, "\n" /* StubUtility.getLineDelimiterUsed(fUnit) */); if (comment != null && comment.length() > 0 && !"/**\n *\n */\n".equals(comment)) { final Javadoc doc = (Javadoc) rewrite.createStringPlaceholder(comment, ASTNode.JAVADOC); declaration.setJavadoc(doc); } } if (fragment == null) { return; } positionGroups.setEndPosition(rewrite.track(fragment)); }
private static String[] getVariableNameSuggestions( int variableKind, IJavaProject project, Type expectedType, Collection<String> excluded, boolean evaluateDefault) { int dim = 0; if (expectedType.isArrayType()) { ArrayType arrayType = (ArrayType) expectedType; dim = arrayType.getDimensions(); expectedType = arrayType.getElementType(); } if (expectedType.isParameterizedType()) { expectedType = ((ParameterizedType) expectedType).getType(); } String typeName = ASTNodes.getTypeName(expectedType); if (typeName.length() > 0) { return getVariableNameSuggestions( variableKind, project, typeName, dim, excluded, evaluateDefault); } return EMPTY; }
/** * Returns the declaration node for the originally selected node. * * @param name the name of the node * @return the declaration node */ private static ASTNode getDeclarationNode(SimpleName name) { ASTNode parent = name.getParent(); if (!(parent instanceof AbstractTypeDeclaration)) { parent = parent.getParent(); if (parent instanceof ParameterizedType || parent instanceof Type) parent = parent.getParent(); if (parent instanceof ClassInstanceCreation) { final ClassInstanceCreation creation = (ClassInstanceCreation) parent; parent = creation.getAnonymousClassDeclaration(); } } return parent; }
/** {@inheritDoc} */ @Override public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel model) throws CoreException { TextEditGroup group = createTextEditGroup( FixMessages.TypeParametersFix_remove_redundant_type_arguments_description, cuRewrite); ASTRewrite rewrite = cuRewrite.getASTRewrite(); rewrite.setTargetSourceRangeComputer(new NoCommentSourceRangeComputer()); ListRewrite listRewrite = rewrite.getListRewrite(fParameterizedType, ParameterizedType.TYPE_ARGUMENTS_PROPERTY); List<Type> typeArguments = fParameterizedType.typeArguments(); for (Iterator<Type> iterator = typeArguments.iterator(); iterator.hasNext(); ) { listRewrite.remove(iterator.next(), group); } }
public static TypeParametersFix createInsertInferredTypeArgumentsFix( CompilationUnit compilationUnit, ParameterizedType node) { if (node == null) return null; final ArrayList<ASTNode> changedNodes = new ArrayList<ASTNode>(); node.accept(new InsertTypeArgumentsVisitor(changedNodes)); if (changedNodes.isEmpty()) return null; CompilationUnitRewriteOperation op = new InsertTypeArgumentsOperation(new ParameterizedType[] {node}); return new TypeParametersFix( FixMessages.TypeParametersFix_insert_inferred_type_arguments_name, compilationUnit, new CompilationUnitRewriteOperation[] {op}); }
/** {@inheritDoc} */ @Override public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel positionGroups) throws CoreException { final ASTRewrite rewrite = cuRewrite.getASTRewrite(); VariableDeclarationFragment fragment = null; for (int i = 0; i < fNodes.length; i++) { final ASTNode node = fNodes[i]; final AST ast = node.getAST(); fragment = ast.newVariableDeclarationFragment(); fragment.setName(ast.newSimpleName(NAME_FIELD)); final FieldDeclaration declaration = ast.newFieldDeclaration(fragment); declaration.setType(ast.newPrimitiveType(PrimitiveType.LONG)); declaration .modifiers() .addAll( ASTNodeFactory.newModifiers( ast, Modifier.PRIVATE | Modifier.STATIC | Modifier.FINAL)); if (!addInitializer(fragment, node)) continue; if (fragment.getInitializer() != null) { final TextEditGroup editGroup = createTextEditGroup(FixMessages.SerialVersion_group_description, cuRewrite); if (node instanceof AbstractTypeDeclaration) rewrite .getListRewrite(node, ((AbstractTypeDeclaration) node).getBodyDeclarationsProperty()) .insertAt(declaration, 0, editGroup); else if (node instanceof AnonymousClassDeclaration) rewrite .getListRewrite(node, AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY) .insertAt(declaration, 0, editGroup); else if (node instanceof ParameterizedType) { final ParameterizedType type = (ParameterizedType) node; final ASTNode parent = type.getParent(); if (parent instanceof ClassInstanceCreation) { final ClassInstanceCreation creation = (ClassInstanceCreation) parent; final AnonymousClassDeclaration anonymous = creation.getAnonymousClassDeclaration(); if (anonymous != null) rewrite .getListRewrite(anonymous, AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY) .insertAt(declaration, 0, editGroup); } } else Assert.isTrue(false); addLinkedPositions(rewrite, fragment, positionGroups); } final String comment = CodeGeneration.getFieldComment( fUnit, declaration.getType().toString(), NAME_FIELD, StubUtility.getLineDelimiterUsed(fUnit)); if (comment != null && comment.length() > 0) { final Javadoc doc = (Javadoc) rewrite.createStringPlaceholder(comment, ASTNode.JAVADOC); declaration.setJavadoc(doc); } } if (fragment == null) return; positionGroups.setEndPosition(rewrite.track(fragment)); }
private static ParameterizedType rewriteConstraintVariable( ConstraintVariable2 cv, CompilationUnitRewrite rewrite, InferTypeArgumentsTCModel tCModel, boolean leaveUnconstraindRaw, SimpleType[] types) { if (cv instanceof CollectionElementVariable2) { ConstraintVariable2 parentElement = ((CollectionElementVariable2) cv).getParentConstraintVariable(); if (parentElement instanceof TypeVariable2) { TypeVariable2 typeCv = (TypeVariable2) parentElement; return rewriteTypeVariable(typeCv, rewrite, tCModel, leaveUnconstraindRaw, types); } else { // only rewrite type variables } } return null; }
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; }
/** * Sets the type being instantiated in the given constructor call, including specifying any * necessary type arguments. * * @param newCtorCall the constructor call to modify * @param ctorTypeName the simple name of the type being instantiated * @param ctorOwnerTypeParameters the formal type parameters of the type being instantiated * @param ast utility object used to create AST nodes */ private void setCtorTypeArguments( ClassInstanceCreation newCtorCall, String ctorTypeName, ITypeBinding[] ctorOwnerTypeParameters, AST ast) { if (ctorOwnerTypeParameters.length == 0) // easy, just a simple type newCtorCall.setType(ASTNodeFactory.newType(ast, ctorTypeName)); else { Type baseType = ast.newSimpleType(ast.newSimpleName(ctorTypeName)); ParameterizedType newInstantiatedType = ast.newParameterizedType(baseType); List<Type> newInstTypeArgs = newInstantiatedType.typeArguments(); for (int i = 0; i < ctorOwnerTypeParameters.length; i++) { Type typeArg = ASTNodeFactory.newType(ast, ctorOwnerTypeParameters[i].getName()); newInstTypeArgs.add(typeArg); } newCtorCall.setType(newInstantiatedType); } }
/** * Sets the return type of the factory method, including any necessary type arguments. E.g., for * constructor <code>Foo()</code> in <code>Foo<T></code>, the factory method defines a * method type parameter <code><T></code> and returns a <code>Foo<T></code>. * * @param newMethod the method whose return type is to be set * @param retTypeName the simple name of the return type (without type parameters) * @param ctorOwnerTypeParameters the formal type parameters of the type that the factory method * instantiates (whose constructor is being encapsulated) * @param ast utility object used to create AST nodes */ private void setMethodReturnType( MethodDeclaration newMethod, String retTypeName, ITypeBinding[] ctorOwnerTypeParameters, AST ast) { if (ctorOwnerTypeParameters.length == 0) newMethod.setReturnType2(ast.newSimpleType(ast.newSimpleName(retTypeName))); else { Type baseType = ast.newSimpleType(ast.newSimpleName(retTypeName)); ParameterizedType newRetType = ast.newParameterizedType(baseType); List<Type> newRetTypeArgs = newRetType.typeArguments(); for (int i = 0; i < ctorOwnerTypeParameters.length; i++) { Type retTypeArg = ASTNodeFactory.newType(ast, ctorOwnerTypeParameters[i].getName()); newRetTypeArgs.add(retTypeArg); } newMethod.setReturnType2(newRetType); } }
public static void removeMismatchedArguments( IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) { ICompilationUnit cu = context.getCompilationUnit(); ASTNode selectedNode = problem.getCoveredNode(context.getASTRoot()); if (!(selectedNode instanceof SimpleName)) { return; } ASTNode normalizedNode = ASTNodes.getNormalizedNode(selectedNode); if (normalizedNode instanceof ParameterizedType) { ASTRewrite rewrite = ASTRewrite.create(normalizedNode.getAST()); ParameterizedType pt = (ParameterizedType) normalizedNode; ASTNode mt = rewrite.createMoveTarget(pt.getType()); rewrite.replace(pt, mt, null); String label = CorrectionMessages.TypeArgumentMismatchSubProcessor_removeTypeArguments; Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal( label, cu, rewrite, IProposalRelevance.REMOVE_TYPE_ARGUMENTS, image); proposals.add(proposal); } }
/** * For {@link Name} or {@link org.eclipse.jdt.core.dom.Type} nodes, returns the topmost {@link * org.eclipse.jdt.core.dom.Type} node that shares the same type binding as the given node. * * @param node an ASTNode * @return the normalized {@link org.eclipse.jdt.core.dom.Type} node or the original node */ public static ASTNode getNormalizedNode(ASTNode node) { ASTNode current = node; // normalize name if (QualifiedName.NAME_PROPERTY.equals(current.getLocationInParent())) { current = current.getParent(); } // normalize type if (QualifiedType.NAME_PROPERTY.equals(current.getLocationInParent()) || SimpleType.NAME_PROPERTY.equals(current.getLocationInParent()) || NameQualifiedType.NAME_PROPERTY.equals(current.getLocationInParent())) { current = current.getParent(); } // normalize parameterized types if (ParameterizedType.TYPE_PROPERTY.equals(current.getLocationInParent())) { current = current.getParent(); } return current; }
@SuppressWarnings("unchecked") private static ITypeBinding getOwnerTypeBinding( TypeDeclaration uiBinderSubtype) { List<Type> superInterfaces = uiBinderSubtype.superInterfaceTypes(); for (Type superInterface : superInterfaces) { ITypeBinding binding = superInterface.resolveBinding(); if (binding != null) { if (binding.getErasure().getQualifiedName().equals( UiBinderConstants.UI_BINDER_TYPE_NAME)) { if (superInterface instanceof ParameterizedType) { ParameterizedType uiBinderType = (ParameterizedType) superInterface; List<Type> typeArgs = uiBinderType.typeArguments(); if (typeArgs.size() == 2) { Type ownerType = typeArgs.get(1); return ownerType.resolveBinding(); } } } } } return null; }
private void addTypeQualification(final Type type, final CompilationUnitRewrite targetRewrite, final TextEditGroup group) { Assert.isNotNull(type); Assert.isNotNull(targetRewrite); final ITypeBinding binding= type.resolveBinding(); if (binding != null) { final ITypeBinding declaring= binding.getDeclaringClass(); if (declaring != null) { if (type instanceof SimpleType) { final SimpleType simpleType= (SimpleType) type; addSimpleTypeQualification(targetRewrite, declaring, simpleType, group); } else if (type instanceof ParameterizedType) { final ParameterizedType parameterizedType= (ParameterizedType) type; final Type rawType= parameterizedType.getType(); if (rawType instanceof SimpleType) addSimpleTypeQualification(targetRewrite, declaring, (SimpleType) rawType, group); } } } }
private void updateCu(CompilationUnit unit, Set<ConstraintVariable> vars, CompilationUnitChange unitChange, ASTRewrite unitRewriter, String typeName) throws JavaModelException { // use custom SourceRangeComputer to avoid losing comments unitRewriter.setTargetSourceRangeComputer(new SourceRangeComputer()); for (Iterator<ConstraintVariable> it=vars.iterator(); it.hasNext(); ){ ConstraintVariable cv = it.next(); ASTNode decl= findDeclaration(unit, cv); if ((decl instanceof SimpleName || decl instanceof QualifiedName) && cv instanceof ExpressionVariable) { ASTNode gp= decl.getParent().getParent(); updateType(unit, getType(gp), unitChange, unitRewriter, typeName); // local variable or parameter } else if (decl instanceof MethodDeclaration || decl instanceof FieldDeclaration) { updateType(unit, getType(decl), unitChange, unitRewriter, typeName); // method return or field type } else if (decl instanceof ParameterizedType){ updateType(unit, getType(decl), unitChange, unitRewriter, typeName); } } }
/** * Creates the appropriate ParameterizedType node. Recursion is needed to * handle the nested case (e.g., Vector<Vector<String>>). * @param ast * @param typeBinding * @return the created type */ private Type createParameterizedType(AST ast, ITypeBinding typeBinding){ if (typeBinding.isParameterizedType() && !typeBinding.isRawType()){ Type baseType= ast.newSimpleType(ASTNodeFactory.newName(ast, typeBinding.getErasure().getName())); ParameterizedType newType= ast.newParameterizedType(baseType); for (int i=0; i < typeBinding.getTypeArguments().length; i++){ ITypeBinding typeArg= typeBinding.getTypeArguments()[i]; Type argType= createParameterizedType(ast, typeArg); // recursive call newType.typeArguments().add(argType); } return newType; } else { if (!typeBinding.isTypeVariable()){ return ast.newSimpleType(ASTNodeFactory.newName(ast, typeBinding.getErasure().getName())); } else { return ast.newSimpleType(ast.newSimpleName(typeBinding.getName())); } } }
/** * The selection corresponds to a ParameterizedType (return type of method) * @param pt the type * @return the message */ private String parameterizedTypeSelected(ParameterizedType pt) { ASTNode parent= pt.getParent(); if (parent.getNodeType() == ASTNode.METHOD_DECLARATION){ fMethodBinding= ((MethodDeclaration)parent).resolveBinding(); fParamIndex= -1; fEffectiveSelectionStart= pt.getStartPosition(); fEffectiveSelectionLength= pt.getLength(); setOriginalType(pt.resolveBinding()); } else if (parent.getNodeType() == ASTNode.SINGLE_VARIABLE_DECLARATION){ return singleVariableDeclarationSelected((SingleVariableDeclaration)parent); } else if (parent.getNodeType() == ASTNode.VARIABLE_DECLARATION_STATEMENT){ return variableDeclarationStatementSelected((VariableDeclarationStatement)parent); } else if (parent.getNodeType() == ASTNode.FIELD_DECLARATION){ return fieldDeclarationSelected((FieldDeclaration)parent); } else { return nodeTypeNotSupported(); } return null; }
public static ParameterizedType[] inferArguments(SimpleType[] types, InferTypeArgumentsUpdate update, InferTypeArgumentsTCModel model, CompilationUnitRewrite rewrite) { for (int i= 0; i < types.length; i++) { types[i].setProperty(REWRITTEN, null); } List<ParameterizedType> result= new ArrayList<ParameterizedType>(); HashMap<ICompilationUnit, CuUpdate> updates= update.getUpdates(); Set<Entry<ICompilationUnit, CuUpdate>> entrySet= updates.entrySet(); for (Iterator<Entry<ICompilationUnit, CuUpdate>> iter= entrySet.iterator(); iter.hasNext();) { Entry<ICompilationUnit, CuUpdate> entry= iter.next(); rewrite.setResolveBindings(false); CuUpdate cuUpdate= entry.getValue(); for (Iterator<CollectionElementVariable2> cvIter= cuUpdate.getDeclarations().iterator(); cvIter.hasNext();) { ConstraintVariable2 cv= cvIter.next(); ParameterizedType newNode= rewriteConstraintVariable(cv, rewrite, model, false, types); if (newNode != null) result.add(newNode); } } return result.toArray(new ParameterizedType[result.size()]); }
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; }
/** * Sets the type being instantiated in the given constructor call, including * specifying any necessary type arguments. * @param newCtorCall the constructor call to modify * @param ctorTypeName the simple name of the type being instantiated * @param ctorOwnerTypeParameters the formal type parameters of the type being * instantiated * @param ast utility object used to create AST nodes */ private void setCtorTypeArguments(ClassInstanceCreation newCtorCall, String ctorTypeName, ITypeBinding[] ctorOwnerTypeParameters, AST ast) { if (ctorOwnerTypeParameters.length == 0) // easy, just a simple type newCtorCall.setType(ASTNodeFactory.newType(ast, ctorTypeName)); else { Type baseType= ast.newSimpleType(ast.newSimpleName(ctorTypeName)); ParameterizedType newInstantiatedType= ast.newParameterizedType(baseType); List<Type> newInstTypeArgs= newInstantiatedType.typeArguments(); for(int i= 0; i < ctorOwnerTypeParameters.length; i++) { Type typeArg= ASTNodeFactory.newType(ast, ctorOwnerTypeParameters[i].getName()); newInstTypeArgs.add(typeArg); } newCtorCall.setType(newInstantiatedType); } }
/** * Sets the return type of the factory method, including any necessary type * arguments. E.g., for constructor <code>Foo()</code> in <code>Foo<T></code>, * the factory method defines a method type parameter <code><T></code> and * returns a <code>Foo<T></code>. * @param newMethod the method whose return type is to be set * @param retTypeName the simple name of the return type (without type parameters) * @param ctorOwnerTypeParameters the formal type parameters of the type that the * factory method instantiates (whose constructor is being encapsulated) * @param ast utility object used to create AST nodes */ private void setMethodReturnType(MethodDeclaration newMethod, String retTypeName, ITypeBinding[] ctorOwnerTypeParameters, AST ast) { if (ctorOwnerTypeParameters.length == 0) newMethod.setReturnType2(ast.newSimpleType(ast.newSimpleName(retTypeName))); else { Type baseType= ast.newSimpleType(ast.newSimpleName(retTypeName)); ParameterizedType newRetType= ast.newParameterizedType(baseType); List<Type> newRetTypeArgs= newRetType.typeArguments(); for(int i= 0; i < ctorOwnerTypeParameters.length; i++) { Type retTypeArg= ASTNodeFactory.newType(ast, ctorOwnerTypeParameters[i].getName()); newRetTypeArgs.add(retTypeArg); } newMethod.setReturnType2(newRetType); } }
/** * Returns the declaration node for the originally selected node. * @param name the name of the node * * @return the declaration node */ private static ASTNode getDeclarationNode(SimpleName name) { ASTNode parent= name.getParent(); if (!(parent instanceof AbstractTypeDeclaration)) { parent= parent.getParent(); if (parent instanceof ParameterizedType || parent instanceof Type) parent= parent.getParent(); if (parent instanceof ClassInstanceCreation) { final ClassInstanceCreation creation= (ClassInstanceCreation) parent; parent= creation.getAnonymousClassDeclaration(); } } return parent; }
private static String getTypeName(int typeKind, Name node) { String name= ASTNodes.getSimpleNameIdentifier(node); if (typeKind == K_CLASS || typeKind == K_INTERFACE) { ASTNode parent= node.getParent(); if (parent.getLocationInParent() == ParameterizedType.TYPE_PROPERTY) { String typeArgBaseName= name.startsWith(String.valueOf('T')) ? String.valueOf('S') : String.valueOf('T'); // use 'S' or 'T' int nTypeArgs= ((ParameterizedType) parent.getParent()).typeArguments().size(); StringBuffer buf= new StringBuffer(name); buf.append('<'); if (nTypeArgs == 1) { buf.append(typeArgBaseName); } else { for (int i= 0; i < nTypeArgs; i++) { if (i != 0) buf.append(", "); //$NON-NLS-1$ buf.append(typeArgBaseName).append(i + 1); } } buf.append('>'); return buf.toString(); } } return name; }
@Override public boolean consumes(SemanticToken token) { // 1: match types SimpleName name= token.getNode(); ASTNode node= name.getParent(); int nodeType= node.getNodeType(); if (nodeType != ASTNode.SIMPLE_TYPE && nodeType != ASTNode.QUALIFIED_TYPE) return false; // 2: match type arguments StructuralPropertyDescriptor locationInParent= node.getLocationInParent(); if (locationInParent == ParameterizedType.TYPE_ARGUMENTS_PROPERTY) return true; return false; }
public static void removeMismatchedArguments(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals){ ICompilationUnit cu= context.getCompilationUnit(); ASTNode selectedNode= problem.getCoveredNode(context.getASTRoot()); if (!(selectedNode instanceof SimpleName)) { return; } ASTNode normalizedNode=ASTNodes.getNormalizedNode(selectedNode); if (normalizedNode instanceof ParameterizedType) { ASTRewrite rewrite = ASTRewrite.create(normalizedNode.getAST()); ParameterizedType pt = (ParameterizedType) normalizedNode; ASTNode mt = rewrite.createMoveTarget(pt.getType()); rewrite.replace(pt, mt, null); String label= CorrectionMessages.TypeArgumentMismatchSubProcessor_removeTypeArguments; Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, IProposalRelevance.REMOVE_TYPE_ARGUMENTS, image); proposals.add(proposal); } }
public boolean visit(AnonymousClassDeclaration node) { ASTNode name; ASTNode parent = node.getParent(); switch (parent.getNodeType()) { case ASTNode.CLASS_INSTANCE_CREATION: name = ((ClassInstanceCreation) parent).getType(); if (name.getNodeType() == ASTNode.PARAMETERIZED_TYPE) { name = ((ParameterizedType) name).getType(); } break; case ASTNode.ENUM_CONSTANT_DECLARATION: name = ((EnumConstantDeclaration) parent).getName(); break; default: return true; } if (found(node, name) && this.resolveBinding) this.foundBinding = node.resolveBinding(); return true; }
@SuppressWarnings("unchecked") private void transferTypeArguments(ParameterizedType existingType, ParameterizedType newType) { List<Type> oldTypeArgs = existingType.typeArguments(); int i = 0; while (!oldTypeArgs.isEmpty()) { // This is the only way I could find to copy the Types. rewrite.createCopyTarget didn't help // because the types seemed to be in a limbo between attached and not attached. // If I try to copy w/o deleting them from the original list, some sort of infinite loop happens // on clone Type oldType = oldTypeArgs.get(0); oldType.delete(); if (i == 0) { this.keyType = copy(oldType); } else if (i == 1) { this.valueType = copy(oldType); } // oldType is okay to add now w/o a clone, because it is detached. newType.typeArguments().add(oldType); i++; } }