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 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; }
private static void addEnhancedForWithoutTypeProposals(ICompilationUnit cu, ASTNode selectedNode, Collection<CUCorrectionProposal> proposals) { if (selectedNode instanceof SimpleName && (selectedNode.getLocationInParent() == SimpleType.NAME_PROPERTY || selectedNode.getLocationInParent() == NameQualifiedType.NAME_PROPERTY)) { ASTNode type= selectedNode.getParent(); if (type.getLocationInParent() == SingleVariableDeclaration.TYPE_PROPERTY) { SingleVariableDeclaration svd= (SingleVariableDeclaration) type.getParent(); if (svd.getLocationInParent() == EnhancedForStatement.PARAMETER_PROPERTY) { if (svd.getName().getLength() == 0) { SimpleName simpleName= (SimpleName) selectedNode; String name= simpleName.getIdentifier(); int relevance= StubUtility.hasLocalVariableName(cu.getJavaProject(), name) ? 10 : 7; String label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_create_loop_variable_description, BasicElementLabels.getJavaElementName(name)); proposals.add(new NewVariableCorrectionProposal(label, cu, NewVariableCorrectionProposal.LOCAL, simpleName, null, relevance)); } } } } }
public List getAllSuperTypes(TypeDeclaration typeDeclaration) { List list = new ArrayList(); Type superclassType = typeDeclaration.getSuperclassType(); if (superclassType != null) { list.add(superclassType); } List superInterfaceTypes = typeDeclaration.superInterfaceTypes(); for (Iterator itSuperInterfacesIterator = superInterfaceTypes.iterator(); itSuperInterfacesIterator.hasNext();) { Object next = itSuperInterfacesIterator.next(); if (next instanceof SimpleType) { list.add(next); } } return list; }
public static Java50Fix createRawTypeReferenceFix( CompilationUnit compilationUnit, IProblemLocation problem) { List<CompilationUnitRewriteOperation> operations = new ArrayList<CompilationUnitRewriteOperation>(); SimpleType node = createRawTypeReferenceOperations( compilationUnit, new IProblemLocation[] {problem}, operations); if (operations.size() == 0) return null; return new Java50Fix( Messages.format( FixMessages.Java50Fix_AddTypeArguments_description, BasicElementLabels.getJavaElementName(node.getName().getFullyQualifiedName())), compilationUnit, operations.toArray(new CompilationUnitRewriteOperation[operations.size()])); }
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; }
/** * 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; }
private Class<?> retrieveTypeClass(SimpleType simpleType) { ITypeBinding binding = simpleType.resolveBinding(); if (binding == null) { String result = imports.get(simpleType.toString()); if (result != null) { try { return Class.forName(result); } catch (ClassNotFoundException exc) { throw new RuntimeException("Classpath incomplete?", exc); } } } assert binding != null : "Could not resolve binding for " + simpleType + ". Missing sources folder?"; return retrieveTypeClass(binding); }
private Type createAstType(final String type, final AST ast) { if(type.startsWith("[")) // does type specify an array? { return this.createAstArrayType(type, ast); } else { final String[] fragments = type.split("\\."); if(fragments.length == 1) { return ast.newSimpleType(ast.newSimpleName(fragments[0])); } final String[] pkgArray = new String[fragments.length - 1]; System.arraycopy(fragments, 0, pkgArray, 0, pkgArray.length); final SimpleType pkgType = ast.newSimpleType(ast.newName(pkgArray)); return ast.newQualifiedType( pkgType, ast.newSimpleName(fragments[fragments.length - 1])); } }
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); } } } }
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 static boolean isRawTypeReference(ASTNode node) { if (!(node instanceof SimpleType)) return false; ITypeBinding typeBinding= ((SimpleType) node).resolveBinding(); if (typeBinding == null) return false; ITypeBinding binding= typeBinding.getTypeDeclaration(); if (binding == null) return false; ITypeBinding[] parameters= binding.getTypeParameters(); if (parameters.length == 0) return false; return true; }
public static ITypeBinding guessBindingForTypeReference(ASTNode node) { StructuralPropertyDescriptor locationInParent= node.getLocationInParent(); if (locationInParent == QualifiedName.QUALIFIER_PROPERTY) { return null; // can't guess type for X.A } if (locationInParent == SimpleType.NAME_PROPERTY || locationInParent == NameQualifiedType.NAME_PROPERTY) { node= node.getParent(); } ITypeBinding binding= Bindings.normalizeTypeBinding(getPossibleTypeBinding(node)); if (binding != null) { if (binding.isWildcardType()) { return normalizeWildcardType(binding, true, node.getAST()); } } return binding; }
private static ITypeBinding extractExpressionType(SimpleType variableIdentifier) { ScopeAnalyzer analyzer= new ScopeAnalyzer((CompilationUnit) variableIdentifier.getRoot()); // get the name of the variable to search the type for Name name= null; if (variableIdentifier.getName() instanceof SimpleName) { name= variableIdentifier.getName(); } else if (variableIdentifier.getName() instanceof QualifiedName) { name= ((QualifiedName) variableIdentifier.getName()).getName(); } // analyze variables which are available in the scope at the position of the quick assist invokation IBinding[] declarationsInScope= analyzer.getDeclarationsInScope(name.getStartPosition(), ScopeAnalyzer.VARIABLES); for (int i= 0; i < declarationsInScope.length; i++) { IBinding currentVariable= declarationsInScope[i]; if (((IVariableBinding) currentVariable).getName().equals(name.getFullyQualifiedName())) { return ((IVariableBinding) currentVariable).getType(); } } return null; }
private static void addEnhancedForWithoutTypeProposals(ICompilationUnit cu, ASTNode selectedNode, Collection<ICommandAccess> proposals) { if (selectedNode instanceof SimpleName && (selectedNode.getLocationInParent() == SimpleType.NAME_PROPERTY || selectedNode.getLocationInParent() == NameQualifiedType.NAME_PROPERTY)) { ASTNode type= selectedNode.getParent(); if (type.getLocationInParent() == SingleVariableDeclaration.TYPE_PROPERTY) { SingleVariableDeclaration svd= (SingleVariableDeclaration) type.getParent(); if (svd.getLocationInParent() == EnhancedForStatement.PARAMETER_PROPERTY) { if (svd.getName().getLength() == 0) { SimpleName simpleName= (SimpleName) selectedNode; String name= simpleName.getIdentifier(); int relevance= StubUtility.hasLocalVariableName(cu.getJavaProject(), name) ? 10 : 7; String label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_create_loop_variable_description, BasicElementLabels.getJavaElementName(name)); Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL); proposals.add(new NewVariableCorrectionProposal(label, cu, NewVariableCorrectionProposal.LOCAL, simpleName, null, relevance, image)); } } } } }
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())) { current= current.getParent(); } // normalize parameterized types if (ParameterizedType.TYPE_PROPERTY.equals(current.getLocationInParent())) { current= current.getParent(); } return current; }
public static SimpleType getLeftMostSimpleType(QualifiedType type) { final SimpleType[] result= new SimpleType[1]; ASTVisitor visitor= new ASTVisitor() { @Override public boolean visit(QualifiedType qualifiedType) { Type left= qualifiedType.getQualifier(); if (left instanceof SimpleType) result[0]= (SimpleType)left; else left.accept(this); return false; } }; type.accept(visitor); return result[0]; }
@Override public boolean visit(ClassInstanceCreation node) { // match with the constructor and the type. Type type= node.getType(); if (type instanceof ParameterizedType) { type= ((ParameterizedType) type).getType(); } if (type instanceof SimpleType) { Name name= ((SimpleType) type).getName(); if (name instanceof QualifiedName) name= ((QualifiedName)name).getName(); addUsage(name, node.resolveConstructorBinding()); } return super.visit(node); }
public static ITypeBinding guessBindingForTypeReference(ASTNode node) { StructuralPropertyDescriptor locationInParent= node.getLocationInParent(); if (locationInParent == QualifiedName.QUALIFIER_PROPERTY) { return null; // can't guess type for X.A } if (locationInParent == SimpleType.NAME_PROPERTY) { node= node.getParent(); } ITypeBinding binding= Bindings.normalizeTypeBinding(getPossibleTypeBinding(node)); if (binding != null) { if (binding.isWildcardType()) { return normalizeWildcardType(binding, true, node.getAST()); } } return binding; }
@Override public boolean visit(ClassInstanceCreation node) { if (badBigDecimalConstructor != null) { return false; } Type type = node.getType(); if (type instanceof SimpleType && "BigDecimal".equals(((SimpleType) type).getName().getFullyQualifiedName())) { @SuppressWarnings("unchecked") List<Expression> args = node.arguments(); if (args.size() == 1 && args.get(0) instanceof NumberLiteral) { badBigDecimalConstructor = node; this.decimalVar = (NumberLiteral) node.arguments().get(0); } } return true; }
private VariableDeclarationStatement makeNewValueStatement(EntrySetResolutionVisitor visitor) { SimpleName nameOfNewVar; if (visitor.badMapGetVariableFragment != null) { nameOfNewVar = visitor.badMapGetVariableFragment.getName(); } else if (valueType instanceof SimpleType) { StringBuilder tempName = new StringBuilder(((SimpleName) ((SimpleType) valueType).getName()).getIdentifier()); tempName.setCharAt(0, Character.toLowerCase(tempName.charAt(0))); nameOfNewVar = ast.newSimpleName(tempName.toString()); } else { nameOfNewVar = ast.newSimpleName("mapValue"); } newValueVariableName = nameOfNewVar; return makeNewVariableStatement(nameOfNewVar, "getValue", valueType); }
public static String toClassName(IProject project, Type type) { Name name = null; if (type instanceof SimpleType) { name = ((SimpleType) type).getName(); } else if (type instanceof QualifiedType) { name = ((QualifiedType) type).getName(); } else if (type instanceof ParameterizedType) { return toClassName(project, ((ParameterizedType) type).getType()); } else { // Unsupported type, i.e., primitive types are not supported at the moment return null; } return name.isQualifiedName() ? name.getFullyQualifiedName() : tryResolveFQNameFromImports(project, type.getRoot(), name.getFullyQualifiedName()); }
private Type replaceType(ParameterizedType type) { AST ast = type.getAST(); Type basicType = type.getType(); if (basicType.isSimpleType()) { type.setType(replaceType((SimpleType)basicType)); } else if (basicType.isParameterizedType()) { type.setType(replaceType((ParameterizedType)basicType)); } for (int i = 0; i < type.typeArguments().size(); i++) { Type paramType = (Type)type.typeArguments().get(i); if (paramType.isSimpleType()) { type.typeArguments().set(i, replaceType((SimpleType)paramType)); } else if (paramType.isParameterizedType()) { type.typeArguments().set(i, replaceType((ParameterizedType)paramType)); } } return (Type)ASTNode.copySubtree(ast, type); }
public boolean visit(MethodDeclaration node) { Type returnType = node.getReturnType2(); if (returnType != null) { if (returnType.isSimpleType()) { node.setReturnType2(replaceType((SimpleType)returnType)); } else if (returnType.isParameterizedType()) { node.setReturnType2(replaceType((ParameterizedType)returnType)); } } for (int i = 0; i < node.parameters().size(); i++) { SingleVariableDeclaration svd = (SingleVariableDeclaration)node.parameters().get(i); Type varType = svd.getType(); if (varType.isSimpleType()) { svd.setType(replaceType((SimpleType)varType)); } else if (varType.isParameterizedType()) { svd.setType(replaceType((ParameterizedType)varType)); } } return false; }
/** * Determines if a given TypeDeclaration node implements the interface ExtensionPoint. */ @Override protected boolean isWanted(TypeDeclaration typeDecl) { if (typeDecl.isInterface()) { return false; } String nodeName = typeDecl.getName().getIdentifier(); List<Type> interfaces = (List<Type>)typeDecl.superInterfaceTypes(); for (int i = 0; i < interfaces.size(); i++) { Type iface_ = interfaces.get(i); if (iface_.isSimpleType()) { SimpleType iface = (SimpleType)iface_; Name name = iface.getName(); String fullName = name.getFullyQualifiedName(); if (fullName.equals("ExtensionPoint") || fullName.endsWith(".ExtensionPoint")) { Logger.info("extension point " + nodeName + " found"); return true; } } } return false; }
protected boolean tryToResolve(Type type) { boolean result = false; if (underResolution.getResolverMap().containsKey(type)) { result = true; } else { if (type.isPrimitiveType()) { result = tryToResolve((PrimitiveType)type); } else if (type.isQualifiedType()) { result = tryToResolve((QualifiedType)type); } else if (type.isArrayType()) { result = tryToResolve(((ArrayType)type).getElementType()); } else if (type.isSimpleType()) { result = tryToResolve((SimpleType)type); } else if (type.isParameterizedType()) { result = tryToResolve((ParameterizedType)type); } else if (type.isWildcardType()) { result = tryToResolve((WildcardType)type); } else { CoreActivator.log(IStatus.INFO, "Type not handled " + type.toString()); } } return result; }
protected boolean tryToResolve(SimpleType simpleType) { boolean result = false; if (underResolution.getResolverMap().containsKey(simpleType)) { result = true; } else { ITypeBinding resolveBinding = simpleType.resolveBinding(); if (resolveBinding != null) { String qualifiedName = resolveBinding.getBinaryName(); if (qualifiedName != null) { Classifier classifier = searchClassifierInModels(qualifiedName); if (classifier != null) { underResolution.getResolverMap().put(simpleType, classifier); result = true; } } } } // No sub types to resolve return result; }
@Override public boolean visit(SimpleType node) { ITypeBinding resolvedBinding = node.resolveBinding(); if (resolvedBinding == null) { return true; } String qualifiedName = null; if (resolvedBinding.isParameterizedType()) { ITypeBinding erasure = resolvedBinding.getErasure(); if (erasure != null && !erasure.isRecovered()) { qualifiedName = erasure.getQualifiedName(); } } else if (!resolvedBinding.isRecovered()) { qualifiedName = resolvedBinding.getQualifiedName(); } if (qualifiedName != null) { node.setName(node.getAST().newName(qualifiedName)); this.modified = true; } return true; }
/** * Return a name instance from a Type instance */ public static Name getName(Type t) { if (t.isArrayType()) { ArrayType arrayType = (ArrayType) t; return getName(ASTArrayTypeHelper.getComponentType(arrayType)); } else if (t.isParameterizedType()) { return getName(((ParameterizedType) t).getType()); } else if (t.isPrimitiveType()) { return null; } else if (t.isQualifiedType()) { return ((QualifiedType) t).getName(); } else if (t.isSimpleType()) { return ((SimpleType) t).getName(); } return null; }
/** * @return a String representation of 'type'. Handles qualified, simple and parameterized types. */ @Nullable private String getNameOfType(Type type) { if (type instanceof QualifiedType) { return extractTypeNameWithoutGenerics((QualifiedType) type); } if (type instanceof SimpleType) { return ((SimpleType) type).getName().getFullyQualifiedName(); } if (type instanceof ParameterizedType) { return getNameOfType(((ParameterizedType) type).getType()); } return null; }
@Override public void endVisit(SimpleType node) { if (skipNode(node)) { return; } assignFlowInfo(node, node.getName()); }
private boolean testTypeEquals(final Class<?> expected, Type actual) { if(actual.isSimpleType()) { SimpleType simpleDeclaration = (SimpleType)actual; return testNameEquals(expected, simpleDeclaration.getName()); } else if (actual.isPrimitiveType()) { PrimitiveType primitive = (PrimitiveType)actual; return testPrimitiveTypeEquals(expected, primitive.getPrimitiveTypeCode()); } else { //unbekannter Typ System.err.println("warning: not simple type, feature not implemented. type is: " + actual.getClass()); throw new UnsupportedOperationException(); } }
private static boolean isRawTypeReference(ASTNode node) { if (!(node instanceof SimpleType)) return false; ITypeBinding typeBinding = ((SimpleType) node).resolveBinding(); if (typeBinding == null) return false; ITypeBinding binding = typeBinding.getTypeDeclaration(); if (binding == null) return false; ITypeBinding[] parameters = binding.getTypeParameters(); if (parameters.length == 0) return false; return true; }
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()]); }