public VariableDeclarationStatement variableDeclarationStatement(String name, Type type, Expression initializer) { VariableDeclarationFragment variableDeclarationFragment = variableDeclarationFragment(name); variableDeclarationFragment.setInitializer(initializer); VariableDeclarationStatement statement = ast.get().newVariableDeclarationStatement(variableDeclarationFragment); statement.setType(type); return statement; }
@Override public boolean visit(FieldDeclaration fieldDeclaration) { Type fieldType = fieldDeclaration.getType(); int fieldModifiers = fieldDeclaration.getModifiers(); Visibility visibility = getVisibility(fieldModifiers); // boolean isFinal = (fieldModifiers & Modifier.FINAL) != 0; boolean isStatic = (fieldModifiers & Modifier.STATIC) != 0; List<VariableDeclarationFragment> fragments = fieldDeclaration.fragments(); for (VariableDeclarationFragment fragment : fragments) { String fieldName = fragment.getName().getIdentifier(); final SDAttribute attribute = model.createAttribute(fieldName, containerStack.peek()); attribute.setStatic(isStatic); attribute.setVisibility(visibility); attribute.setType(AstUtils.normalizeTypeName(fieldType, fragment.getExtraDimensions(), false)); Expression expression = fragment.getInitializer(); if (expression != null) { //attribute.setAssignment(srbForAttributes.buildSourceRepresentation(fileContent, expression.getStartPosition(), expression.getLength())); addClientCode(attribute.key().toString(), srbForAttributes.buildPartialSourceRepresentation(fileContent, expression)); } attribute.setClientCode(srbForAttributes.buildEmptySourceRepresentation()); } return true; }
private Type getNewCastTypeNode(ASTRewrite rewrite, ImportRewrite importRewrite) { AST ast= rewrite.getAST(); ImportRewriteContext context= new ContextSensitiveImportRewriteContext((CompilationUnit) fNodeToCast.getRoot(), fNodeToCast.getStartPosition(), importRewrite); if (fCastType != null) { return importRewrite.addImport(fCastType, ast,context, TypeLocation.CAST); } ASTNode node= fNodeToCast; ASTNode parent= node.getParent(); if (parent instanceof CastExpression) { node= parent; parent= parent.getParent(); } while (parent instanceof ParenthesizedExpression) { node= parent; parent= parent.getParent(); } if (parent instanceof MethodInvocation) { MethodInvocation invocation= (MethodInvocation) node.getParent(); if (invocation.getExpression() == node) { IBinding targetContext= ASTResolving.getParentMethodOrTypeBinding(node); ITypeBinding[] bindings= ASTResolving.getQualifierGuess(node.getRoot(), invocation.getName().getIdentifier(), invocation.arguments(), targetContext); if (bindings.length > 0) { ITypeBinding first= getCastFavorite(bindings, fNodeToCast.resolveTypeBinding()); Type newTypeNode= importRewrite.addImport(first, ast, context, TypeLocation.CAST); return newTypeNode; } } } Type newCastType= ast.newSimpleType(ast.newSimpleName("Object")); //$NON-NLS-1$ return newCastType; }
private static void createTypeParameters( ImportRewrite imports, ImportRewriteContext context, AST ast, IMethodBinding binding, MethodDeclaration decl) { ITypeBinding[] typeParams = binding.getTypeParameters(); List<TypeParameter> typeParameters = decl.typeParameters(); for (int i = 0; i < typeParams.length; i++) { ITypeBinding curr = typeParams[i]; TypeParameter newTypeParam = ast.newTypeParameter(); newTypeParam.setName(ast.newSimpleName(curr.getName())); ITypeBinding[] typeBounds = curr.getTypeBounds(); if (typeBounds.length != 1 || !"java.lang.Object".equals(typeBounds[0].getQualifiedName())) { // $NON-NLS-1$ List<Type> newTypeBounds = newTypeParam.typeBounds(); for (int k = 0; k < typeBounds.length; k++) { newTypeBounds.add(imports.addImport(typeBounds[k], ast, context)); } } typeParameters.add(newTypeParam); } }
private FieldDeclaration createNewFieldDeclaration(ASTRewrite rewrite) { AST ast = getAST(); VariableDeclarationFragment fragment = ast.newVariableDeclarationFragment(); SimpleName variableName = ast.newSimpleName(fFieldName); fragment.setName(variableName); addLinkedName(rewrite, variableName, false); List<Dimension> extraDimensions = DimensionRewrite.copyDimensions(fTempDeclarationNode.extraDimensions(), rewrite); fragment.extraDimensions().addAll(extraDimensions); if (fInitializeIn == INITIALIZE_IN_FIELD && tempHasInitializer()) { Expression initializer = (Expression) rewrite.createCopyTarget(getTempInitializer()); fragment.setInitializer(initializer); } FieldDeclaration fieldDeclaration = ast.newFieldDeclaration(fragment); VariableDeclarationStatement vds = getTempDeclarationStatement(); Type type = (Type) rewrite.createCopyTarget(vds.getType()); fieldDeclaration.setType(type); fieldDeclaration.modifiers().addAll(ASTNodeFactory.newModifiers(ast, getModifiers())); return fieldDeclaration; }
ClassModel(ASTNodeFactory astNodeFactory, String className, Type superClassType, PackageDeclaration packageDeclaration, List<FieldDeclaration> fields, List<MethodModel> methods, List<ImportDeclaration> imports, List<TypeModel> innerTypes, List<ASTNode> modifiers) { groovism = provide(); this.className = className; this.packageDeclaration = packageDeclaration; this.fields = fieldDeclarations(fields); this.methods = unmodifiableList(new LinkedList<>(methods)); this.modifiers = unmodifiableList(new LinkedList<>(modifiers)); this.imports = imports; this.innerTypes = unmodifiableList(new LinkedList<>(innerTypes)); if (isTestClass(methods)) { this.superClassType = Optional.of(astNodeFactory.simpleType(Specification.class.getSimpleName())); imports.add(0, astNodeFactory.importDeclaration(Specification.class)); } else { this.superClassType = Optional.ofNullable(superClassType); } }
InterfaceModel(String typeName, Type superClassType, PackageDeclaration packageDeclaration, List<FieldDeclaration> fields, List<MethodModel> methods, List<ImportDeclaration> imports, List<ASTNode> modifiers) { groovism = provide(); LinkedList<ImportDeclaration> importDeclarations = new LinkedList<>(imports); this.superClassType = Optional.ofNullable(superClassType).map(Object::toString); this.typeName = typeName; this.packageDeclaration = packageDeclaration; this.fields = unmodifiableList(new LinkedList<>(fields)); this.methods = unmodifiableList(new LinkedList<>(methods)); this.imports = unmodifiableList(importDeclarations); this.modifiers = unmodifiableList(modifiers); }
public static String getSignatureFromMethodDeclaration(MethodDeclaration methodDeclaration) { String methodName = methodDeclaration.isConstructor() ? "" : methodDeclaration.getName().getIdentifier(); // if (methodName.equals("allObjectsSorted")) { // System.out.println(); // } StringBuilder sb = new StringBuilder(); sb.append(methodName); sb.append('('); @SuppressWarnings("unchecked") Iterator<SingleVariableDeclaration> parameters = methodDeclaration.parameters().iterator(); while (parameters.hasNext()) { SingleVariableDeclaration parameter = parameters.next(); Type parameterType = parameter.getType(); String typeName = normalizeTypeName(parameterType, parameter.getExtraDimensions(), parameter.isVarargs()); sb.append(typeName); if (parameters.hasNext()) { sb.append(", "); } } sb.append(')'); String methodSignature = sb.toString(); return methodSignature; }
private List<FieldInfo> createFieldInfos(FieldDeclaration node, String belongTo) { List<FieldInfo> fieldInfos = new ArrayList<>(); Type type = node.getType(); Set<String> types = getTypes(type); String typeString = type.toString(); String visibility = getVisibility(node); boolean isStatic = isStatic(node); boolean isFinal = isFinal(node); String comment = ""; if (node.getJavadoc() != null) comment = sourceContent.substring(node.getJavadoc().getStartPosition(), node.getJavadoc().getStartPosition() + node.getJavadoc().getLength()); List<VariableDeclarationFragment> fragments = node.fragments(); for (VariableDeclarationFragment fragment : fragments) { FieldInfo fieldInfo = new FieldInfo(); fieldInfo.belongTo = belongTo; fieldInfo.name = fragment.getName().getFullyQualifiedName(); fieldInfo.typeString = typeString; fieldInfo.types = types; fieldInfo.visibility = visibility; fieldInfo.isFinal = isFinal; fieldInfo.isStatic = isStatic; fieldInfo.comment = comment; fieldInfos.add(fieldInfo); } return fieldInfos; }
private Set<String> getTypes(Type oType) { Set<String> types = new HashSet<>(); if (oType == null) return types; ITypeBinding typeBinding = oType.resolveBinding(); if (typeBinding == null) return types; String str = typeBinding.getQualifiedName(); String[] eles = str.split("[^A-Za-z0-9_\\.]+"); for (String e : eles) { if (e.equals("extends")) continue; types.add(e); } return types; }
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"); }
/** * Returns the type node for the given declaration. * * @param declaration the declaration * @return the type node or <code>null</code> if the given declaration represents a type * inferred parameter in lambda expression */ public static Type getType(VariableDeclaration declaration) { if (declaration instanceof SingleVariableDeclaration) { return ((SingleVariableDeclaration)declaration).getType(); } else if (declaration instanceof VariableDeclarationFragment) { ASTNode parent= ((VariableDeclarationFragment)declaration).getParent(); if (parent instanceof VariableDeclarationExpression) { return ((VariableDeclarationExpression)parent).getType(); } else if (parent instanceof VariableDeclarationStatement) { return ((VariableDeclarationStatement)parent).getType(); } else if (parent instanceof FieldDeclaration) { return ((FieldDeclaration)parent).getType(); } else if (parent instanceof LambdaExpression) { return null; } } Assert.isTrue(false, "Unknown VariableDeclaration"); //$NON-NLS-1$ return null; }
public static int getDimensions(VariableDeclaration declaration) { int dim= declaration.getExtraDimensions(); if (declaration instanceof VariableDeclarationFragment && declaration.getParent() instanceof LambdaExpression) { LambdaExpression lambda= (LambdaExpression) declaration.getParent(); IMethodBinding methodBinding= lambda.resolveMethodBinding(); if (methodBinding != null) { ITypeBinding[] parameterTypes= methodBinding.getParameterTypes(); int index= lambda.parameters().indexOf(declaration); ITypeBinding typeBinding= parameterTypes[index]; return typeBinding.getDimensions(); } } else { Type type= getType(declaration); if (type instanceof ArrayType) { dim+= ((ArrayType) type).getDimensions(); } } return dim; }
/** * Returns the topmost ancestor of <code>node</code> that is a {@link Type} (but not a {@link UnionType}). * <p> * <b>Note:</b> The returned node often resolves to a different binding than the given <code>node</code>! * * @param node the starting node, can be <code>null</code> * @return the topmost type or <code>null</code> if the node is not a descendant of a type node * @see #getNormalizedNode(ASTNode) */ public static Type getTopMostType(ASTNode node) { ASTNode result= null; while (node instanceof Type && !(node instanceof UnionType) || node instanceof Name || node instanceof Annotation || node instanceof MemberValuePair || node instanceof Expression) { // Expression could maybe be reduced to expression node types that can appear in an annotation result= node; node= node.getParent(); } if (result instanceof Type) { return (Type) result; } return null; }
/** * Creates a {@link ASTRewrite#createCopyTarget(ASTNode) copy} of <code>type</code> * and adds <code>extraDimensions</code> to it. * * @param type the type to copy * @param extraDimensions the dimensions to add * @param rewrite the ASTRewrite with which to create new nodes * @return the copy target with added dimensions */ public static Type copyTypeAndAddDimensions(Type type, List<Dimension> extraDimensions, ASTRewrite rewrite) { AST ast= rewrite.getAST(); if (extraDimensions.isEmpty()) { return (Type) rewrite.createCopyTarget(type); } ArrayType result; if (type instanceof ArrayType) { ArrayType arrayType= (ArrayType) type; Type varElementType= (Type) rewrite.createCopyTarget(arrayType.getElementType()); result= ast.newArrayType(varElementType, 0); result.dimensions().addAll(copyDimensions(extraDimensions, rewrite)); result.dimensions().addAll(copyDimensions(arrayType.dimensions(), rewrite)); } else { Type elementType= (Type) rewrite.createCopyTarget(type); result= ast.newArrayType(elementType, 0); result.dimensions().addAll(copyDimensions(extraDimensions, rewrite)); } return result; }
private static Type newType(LambdaExpression lambdaExpression, VariableDeclarationFragment declaration, AST ast, ImportRewrite importRewrite, ImportRewriteContext context) { IMethodBinding method= lambdaExpression.resolveMethodBinding(); if (method != null) { ITypeBinding[] parameterTypes= method.getParameterTypes(); int index= lambdaExpression.parameters().indexOf(declaration); ITypeBinding typeBinding= parameterTypes[index]; if (importRewrite != null) { return importRewrite.addImport(typeBinding, ast, context); } else { String qualifiedName= typeBinding.getQualifiedName(); if (qualifiedName.length() > 0) { return newType(ast, qualifiedName); } } } // fall-back return ast.newSimpleType(ast.newSimpleName("Object")); //$NON-NLS-1$ }
/** * Returns the new type node representing the return type of <code>lambdaExpression</code> * including the extra dimensions. * * @param lambdaExpression the lambda expression * @param ast the AST to create the return type with * @param importRewrite the import rewrite to use, or <code>null</code> * @param context the import rewrite context, or <code>null</code> * @return a new type node created with the given AST representing the return type of * <code>lambdaExpression</code> * * @since 3.10 */ public static Type newReturnType(LambdaExpression lambdaExpression, AST ast, ImportRewrite importRewrite, ImportRewriteContext context) { IMethodBinding method= lambdaExpression.resolveMethodBinding(); if (method != null) { ITypeBinding returnTypeBinding= method.getReturnType(); if (importRewrite != null) { return importRewrite.addImport(returnTypeBinding, ast); } else { String qualifiedName= returnTypeBinding.getQualifiedName(); if (qualifiedName.length() > 0) { return newType(ast, qualifiedName); } } } // fall-back return ast.newSimpleType(ast.newSimpleName("Object")); //$NON-NLS-1$ }
/** * 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 void createTypeParameters(ImportRewrite imports, ImportRewriteContext context, AST ast, IMethodBinding binding, MethodDeclaration decl) { ITypeBinding[] typeParams= binding.getTypeParameters(); List<TypeParameter> typeParameters= decl.typeParameters(); for (int i= 0; i < typeParams.length; i++) { ITypeBinding curr= typeParams[i]; TypeParameter newTypeParam= ast.newTypeParameter(); newTypeParam.setName(ast.newSimpleName(curr.getName())); ITypeBinding[] typeBounds= curr.getTypeBounds(); if (typeBounds.length != 1 || !"java.lang.Object".equals(typeBounds[0].getQualifiedName())) {//$NON-NLS-1$ List<Type> newTypeBounds= newTypeParam.typeBounds(); for (int k= 0; k < typeBounds.length; k++) { newTypeBounds.add(imports.addImport(typeBounds[k], ast, context, TypeLocation.TYPE_BOUND)); } } typeParameters.add(newTypeParam); } }
public static String[] getVariableNameSuggestions(int variableKind, IJavaProject project, Type expectedType, Expression assignedExpression, Collection<String> excluded) { LinkedHashSet<String> res= new LinkedHashSet<>(); // avoid duplicates but keep order if (assignedExpression != null) { String nameFromExpression= getBaseNameFromExpression(project, assignedExpression, variableKind); if (nameFromExpression != null) { add(getVariableNameSuggestions(variableKind, project, nameFromExpression, 0, excluded, false), res); // pass 0 as dimension, base name already contains plural. } String nameFromParent= getBaseNameFromLocationInParent(assignedExpression); if (nameFromParent != null) { add(getVariableNameSuggestions(variableKind, project, nameFromParent, 0, excluded, false), res); // pass 0 as dimension, base name already contains plural. } } if (expectedType != null) { String[] names= getVariableNameSuggestions(variableKind, project, expectedType, excluded, false); for (int i= 0; i < names.length; i++) { res.add(names[i]); } } if (res.isEmpty()) { return getDefaultVariableNameSuggestions(variableKind, excluded); } return res.toArray(new String[res.size()]); }
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; }
private void splitUpDeclarations(ASTRewrite rewrite, TextEditGroup group, VariableDeclarationFragment frag, VariableDeclarationStatement originalStatement, List<Expression> sideEffects) { if (sideEffects.size() > 0) { ListRewrite statementRewrite= rewrite.getListRewrite(originalStatement.getParent(), (ChildListPropertyDescriptor) originalStatement.getLocationInParent()); Statement previousStatement= originalStatement; for (int i= 0; i < sideEffects.size(); i++) { Expression sideEffect= sideEffects.get(i); Expression movedInit= (Expression) rewrite.createMoveTarget(sideEffect); ExpressionStatement wrapped= rewrite.getAST().newExpressionStatement(movedInit); statementRewrite.insertAfter(wrapped, previousStatement, group); previousStatement= wrapped; } VariableDeclarationStatement newDeclaration= null; List<VariableDeclarationFragment> fragments= originalStatement.fragments(); int fragIndex= fragments.indexOf(frag); ListIterator<VariableDeclarationFragment> fragmentIterator= fragments.listIterator(fragIndex+1); while (fragmentIterator.hasNext()) { VariableDeclarationFragment currentFragment= fragmentIterator.next(); VariableDeclarationFragment movedFragment= (VariableDeclarationFragment) rewrite.createMoveTarget(currentFragment); if (newDeclaration == null) { newDeclaration= rewrite.getAST().newVariableDeclarationStatement(movedFragment); Type copiedType= (Type) rewrite.createCopyTarget(originalStatement.getType()); newDeclaration.setType(copiedType); } else { newDeclaration.fragments().add(movedFragment); } } if (newDeclaration != null){ statementRewrite.insertAfter(newDeclaration, previousStatement, group); if (originalStatement.fragments().size() == newDeclaration.fragments().size() + 1){ rewrite.remove(originalStatement, group); } } } }
public static void addMethodReturnsVoidProposals(IInvocationContext context, IProblemLocation problem, Collection<CUCorrectionProposal> proposals) throws JavaModelException { CompilationUnit astRoot= context.getASTRoot(); ASTNode selectedNode= problem.getCoveringNode(astRoot); if (!(selectedNode instanceof ReturnStatement)) { return; } ReturnStatement returnStatement= (ReturnStatement) selectedNode; Expression expression= returnStatement.getExpression(); if (expression == null) { return; } BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(selectedNode); if (decl instanceof MethodDeclaration) { MethodDeclaration methDecl= (MethodDeclaration) decl; Type retType= methDecl.getReturnType2(); if (retType == null || retType.resolveBinding() == null) { return; } TypeMismatchSubProcessor.addChangeSenderTypeProposals(context, expression, retType.resolveBinding(), false, IProposalRelevance.METHOD_RETURNS_VOID, proposals); } }
@Override protected ASTRewrite getRewrite() throws CoreException { ASTNode boundNode= fAstRoot.findDeclaringNode(fBinding); ASTNode declNode= null; CompilationUnit newRoot= fAstRoot; if (boundNode != null) { declNode= boundNode; // is same CU } else { newRoot= ASTResolving.createQuickFixAST(getCompilationUnit(), null); declNode= newRoot.findDeclaringNode(fBinding.getKey()); } ImportRewrite imports= createImportRewrite(newRoot); if (declNode instanceof TypeDeclaration) { AST ast= declNode.getAST(); ASTRewrite rewrite= ASTRewrite.create(ast); ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(declNode, imports); Type newInterface= imports.addImport(fNewInterface, ast, importRewriteContext, TypeLocation.OTHER); ListRewrite listRewrite= rewrite.getListRewrite(declNode, TypeDeclaration.SUPER_INTERFACE_TYPES_PROPERTY); listRewrite.insertLast(newInterface, null); return rewrite; } return null; }
private Type evaluateVariableType(AST ast, ImportRewrite imports, ImportRewriteContext importRewriteContext, IBinding targetContext, TypeLocation location) { if (fOriginalNode.getParent() instanceof MethodInvocation) { MethodInvocation parent= (MethodInvocation) fOriginalNode.getParent(); if (parent.getExpression() == fOriginalNode) { // _x_.foo() -> guess qualifier type by looking for a type with method 'foo' ITypeBinding[] bindings= ASTResolving.getQualifierGuess(fOriginalNode.getRoot(), parent.getName().getIdentifier(), parent.arguments(), targetContext); if (bindings.length > 0) { return imports.addImport(bindings[0], ast, importRewriteContext, location); } } } ITypeBinding binding= ASTResolving.guessBindingForReference(fOriginalNode); if (binding != null) { if (binding.isWildcardType()) { binding= ASTResolving.normalizeWildcardType(binding, isVariableAssigned(), ast); if (binding == null) { // only null binding applies binding= ast.resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$ } } return imports.addImport(binding, ast, importRewriteContext, location); } // no binding, find type AST node instead -> ABC a= x-> use 'ABC' as is Type type = ASTResolving.guessTypeForReference(ast, fOriginalNode); if (type != null) { return type; } if (fVariableKind == CONST_FIELD) { return ast.newSimpleType(ast.newSimpleName("String")); //$NON-NLS-1$ } return ast.newSimpleType(ast.newSimpleName("Object")); //$NON-NLS-1$ }
private Type getNewType(ASTRewrite rewrite) { AST ast= rewrite.getAST(); Type newTypeNode= null; ITypeBinding binding= null; if (fInvocationNode.getLocationInParent() == MemberValuePair.NAME_PROPERTY) { Expression value= ((MemberValuePair) fInvocationNode.getParent()).getValue(); binding= value.resolveTypeBinding(); } else if (fInvocationNode instanceof Expression) { binding= ((Expression) fInvocationNode).resolveTypeBinding(); } if (binding != null) { ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(fInvocationNode, getImportRewrite()); newTypeNode= getImportRewrite().addImport(binding, ast, importRewriteContext); } if (newTypeNode == null) { newTypeNode= ast.newSimpleType(ast.newSimpleName("String")); //$NON-NLS-1$ } return newTypeNode; }
@Override protected void addNewParameters(ASTRewrite rewrite, List<String> takenNames, List<SingleVariableDeclaration> params, ImportRewriteContext context) throws CoreException { AST ast= rewrite.getAST(); List<Expression> arguments= fArguments; for (int i= 0; i < arguments.size(); i++) { Expression elem= arguments.get(i); SingleVariableDeclaration param= ast.newSingleVariableDeclaration(); // argument type String argTypeKey= "arg_type_" + i; //$NON-NLS-1$ Type type= evaluateParameterType(ast, elem, argTypeKey, context); param.setType(type); // argument name String argNameKey= "arg_name_" + i; //$NON-NLS-1$ String name= evaluateParameterName(takenNames, elem, type, argNameKey); param.setName(ast.newSimpleName(name)); params.add(param); } }
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; }
Type getDeclaredType(VariableDeclarationFragment frg) { ASTNode parent = frg.getParent(); if(parent instanceof VariableDeclarationStatement ) { VariableDeclarationStatement varDecl = (VariableDeclarationStatement)parent; return varDecl.getType(); } else if (parent instanceof VariableDeclarationExpression ) { VariableDeclarationExpression varExpr = (VariableDeclarationExpression)parent; return varExpr.getType(); } return null; }
public static boolean hasConstructor(TypeDeclaration typeDecl, Map<ast.Type, TypeDeclaration> types, QualifiedClassName cThis) { boolean hasConstr = false; if (!hasFieldInitializers(typeDecl)) hasConstr = true; else { for (MethodDeclaration md : typeDecl.getMethods()) { if (md.isConstructor()) hasConstr = true; } } Type superclassType = typeDecl.getSuperclassType(); if (superclassType == null) return hasConstr; if (superclassType.resolveBinding().getQualifiedName().equals(Utils.JAVA_LANG_OBJECT)) return hasConstr; TypeDeclaration superTypeDecl = types.get(new QualifiedClassName(superclassType.resolveBinding(), cThis) .getType()); if (superTypeDecl != null) { hasConstr = hasConstr && hasConstructor(superTypeDecl, types, cThis); } return hasConstr; }
/** * returns all method declarations in a type, and its supertype recursively. * call MethodDeclaration.getBody() to get the body of the method. TODO: * actual/formal substitution * */ public static Set<MethodDeclaration> mBody(TypeDeclaration typeDecl, TypeHierarchy hierarchy, Map<ast.Type, TypeDeclaration> types, QualifiedClassName cThis) { Set<MethodDeclaration> returnSet = new HashSet<MethodDeclaration>(); for (MethodDeclaration md : typeDecl.getMethods()) { returnSet.add(md); } Type superclassType = typeDecl.getSuperclassType(); if (superclassType == null) return returnSet; if (superclassType.resolveBinding().getQualifiedName().equals(Utils.JAVA_LANG_OBJECT)) return returnSet; TypeDeclaration superTypeDecl = types.get(new QualifiedClassName(superclassType.resolveBinding(), cThis) .getType()); if (superTypeDecl != null) { Set<MethodDeclaration> auxSet = mBody(superTypeDecl, hierarchy, types, cThis); returnSet.addAll(auxSet); // TODO: here you don't want to add OverrideMethod // TODO: find a way to uniquely identify methods: define mtype. } return returnSet; }
/** * returns all field bodies declared in a type, and its supertype, * recursively TODO: actual/formal substitution * */ public static Set<FieldDeclaration> fieldBody(TypeDeclaration typeDecl, TypeHierarchy hierarchy, Map<ast.Type, TypeDeclaration> types, QualifiedClassName cThis) { Set<FieldDeclaration> returnSet = new HashSet<FieldDeclaration>(); for (FieldDeclaration fd : typeDecl.getFields()) returnSet.add(fd); Type superclassType = typeDecl.getSuperclassType(); if (superclassType == null) return returnSet; if (superclassType.resolveBinding().getQualifiedName().equals(Utils.JAVA_LANG_OBJECT)) return returnSet; TypeDeclaration superTypeDecl = types.get(new QualifiedClassName(superclassType.resolveBinding(), cThis) .getType()); if (superTypeDecl != null) { Set<FieldDeclaration> auxSet = fieldBody(superTypeDecl, hierarchy, types, cThis); returnSet.addAll(auxSet); } return returnSet; }
@Override public boolean visit(MethodDeclaration methodDeclaration) { IBinding binding = methodDeclaration.resolveBinding(); if (binding == null) return false; currentMethod = (IMethod) binding.getJavaElement(); if (currentMethod != null) { methodDetails = new MethodDetails(); String handleIdentifier = currentMethod.getHandleIdentifier(); allDetails.put(handleIdentifier, methodDetails); methodDetails.setModifiers(methodDeclaration.getModifiers()); methodDetails.setParameters(getParameters(methodDeclaration.parameters())); Type returnType2 = methodDeclaration.getReturnType2(); if (returnType2 != null) { ITypeBinding typeBinding = returnType2.resolveBinding(); IJavaElement returnType = typeBinding.getJavaElement(); if (returnType instanceof IType) { methodDetails.setReturnType((IType) returnType); } } } return true; }
private List<IType> getParameters(List list) { List<IType> params = new ArrayList<IType>(); for (Object elem : list) { if (elem instanceof SingleVariableDeclaration) { SingleVariableDeclaration param = (SingleVariableDeclaration) elem; Type type = param.getType(); if (type != null && type.resolveBinding() != null && type.resolveBinding().getJavaElement() instanceof IType) { params.add((IType) type.resolveBinding().getJavaElement()); } else { if (type.resolveBinding() != null && type.isPrimitiveType()) { params.add(new PrimitiveTypeHack(type.resolveBinding().getName())); } } } } return params; }
private VariableDeclarationFragment addFieldDeclaration( ASTRewrite rewrite, ASTNode newTypeDecl, int modifiers, Expression expression) { if (fExistingFragment != null) { return fExistingFragment; } ChildListPropertyDescriptor property = ASTNodes.getBodyDeclarationsProperty(newTypeDecl); List<BodyDeclaration> decls = ASTNodes.getBodyDeclarations(newTypeDecl); AST ast = newTypeDecl.getAST(); String[] varNames = suggestFieldNames(fTypeBinding, expression, modifiers); for (int i = 0; i < varNames.length; i++) { addLinkedPositionProposal(KEY_NAME, varNames[i], null); } String varName = varNames[0]; VariableDeclarationFragment newDeclFrag = ast.newVariableDeclarationFragment(); newDeclFrag.setName(ast.newSimpleName(varName)); FieldDeclaration newDecl = ast.newFieldDeclaration(newDeclFrag); Type type = evaluateType(ast); newDecl.setType(type); newDecl.modifiers().addAll(ASTNodeFactory.newModifiers(ast, modifiers)); ModifierCorrectionSubProcessor.installLinkedVisibilityProposals( getLinkedProposalModel(), rewrite, newDecl.modifiers(), false); int insertIndex = findFieldInsertIndex(decls, fNodeToAssign.getStartPosition()); rewrite.getListRewrite(newTypeDecl, property).insertAt(newDecl, insertIndex, null); return newDeclFrag; }
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])); } }