private static ASTNode getRawReference(SimpleName name, CompilationUnit compilationUnit) { SimpleName[] names = LinkedNodeFinder.findByNode(compilationUnit, name); for (int j = 0; j < names.length; j++) { if (names[j].getParent() instanceof VariableDeclarationFragment) { VariableDeclarationFragment fragment = (VariableDeclarationFragment) names[j].getParent(); if (fragment.getParent() instanceof VariableDeclarationStatement) { VariableDeclarationStatement statement = (VariableDeclarationStatement) fragment.getParent(); ASTNode result = (ASTNode) statement.getStructuralProperty(VariableDeclarationStatement.TYPE_PROPERTY); if (isRawTypeReference(result)) return result; } else if (fragment.getParent() instanceof FieldDeclaration) { FieldDeclaration declaration = (FieldDeclaration) fragment.getParent(); ASTNode result = (ASTNode) declaration.getStructuralProperty(FieldDeclaration.TYPE_PROPERTY); if (isRawTypeReference(result)) return result; } } else if (names[j].getParent() instanceof SingleVariableDeclaration) { SingleVariableDeclaration declaration = (SingleVariableDeclaration) names[j].getParent(); ASTNode result = (ASTNode) declaration.getStructuralProperty(SingleVariableDeclaration.TYPE_PROPERTY); if (isRawTypeReference(result)) return result; } else if (names[j].getParent() instanceof MethodDeclaration) { MethodDeclaration methodDecl = (MethodDeclaration) names[j].getParent(); ASTNode result = (ASTNode) methodDecl.getStructuralProperty(MethodDeclaration.RETURN_TYPE2_PROPERTY); if (isRawTypeReference(result)) return result; } } return null; }
private void assertAllBindings(CompilationUnit astRoot) { List<AbstractTypeDeclaration> list = astRoot.types(); for (int i = 0; i < list.size(); i++) { TypeDeclaration decl = (TypeDeclaration) list.get(i); assertTrue(decl.resolveBinding() != null); if (!decl.isInterface() && decl.getSuperclassType() != null) { assertTrue(decl.getSuperclassType().resolveBinding() != null); } List<Type> interfaces = decl.superInterfaceTypes(); for (int j = 0; j < interfaces.size(); j++) { assertTrue(interfaces.get(j).resolveBinding() != null); } MethodDeclaration[] declarations = decl.getMethods(); for (int k = 0; k < declarations.length; k++) { MethodDeclaration meth = declarations[k]; assertTrue(meth.resolveBinding() != null); List<SingleVariableDeclaration> params = meth.parameters(); for (int n = 0; n < params.size(); n++) { SingleVariableDeclaration arg = params.get(n); assertTrue(arg.resolveBinding() != null); } if (!meth.isConstructor()) { assertTrue(meth.getReturnType2().resolveBinding() != null); } } } }
private MethodDecl getMethodDecl(MethodDeclaration node) { String qualifiedTypeName = currentPackage + "." + Joiner.on(".").skipNulls().join(typesInFile); SimpleName nameNode = node.getName(); String methodName = nameNode.toString(); String returnType = ""; if (node.getReturnType2() != null) { returnType = getNameOfType(node.getReturnType2()); } Map<String, String> params = new HashMap<>(); for (Object p : node.parameters()) { String typeName = OBJECT_TYPE; if (p instanceof SingleVariableDeclaration) { SingleVariableDeclaration svd = (SingleVariableDeclaration) p; String varName = svd.getName().toString(); Type type = svd.getType(); typeName = getNameOfType(type); params.put(varName, typeName); } else { System.err.println("Unxepected AST node type for param - " + p); } } return new MethodDecl( methodName, qualifiedTypeName, returnType, nameNode.getStartPosition(), params); }
public static MethodDescriptor fromMethodDeclaration( MethodDeclaration md, BinaryNameResolver resolver) { MethodDescriptor desc = new MethodDescriptor(); for (Object fragment : md.parameters()) { SingleVariableDeclaration parameter = (SingleVariableDeclaration) fragment; Type t = parameter.getType(); if (t.isPrimitiveType()) { PrimitiveType type = (PrimitiveType) t; desc.fParameters.add(DescriptorPart.fromPrimitiveType(type)); } else if (t.isArrayType()) { ArrayType type = (ArrayType) t; desc.fParameters.add(DescriptorPart.fromArrayType(type, resolver)); } else if (t.isSimpleType()) { SimpleType type = (SimpleType) t; desc.fParameters.add(DescriptorPart.fromSimpleType(type, resolver)); } else if (t.isQualifiedType()) { /* QualifiedType type = (QualifiedType) t; System.out.println("DESCRIPTOR QUALIFIED"); */ } else if (t.isNameQualifiedType()) { /* NameQualifiedType type = (NameQualifiedType) t; System.out.println("DESCRIPTOR NAME_QUALIFIED"); */ } } return desc; }
/* * @see ASTVisitor#visit(MethodDeclaration) */ public boolean visit(MethodDeclaration node) { if (node.getJavadoc() != null) { node.getJavadoc().accept(this); } if (node.getAST().apiLevel() >= AST.JLS3) { printModifiers(node.modifiers()); if (!node.typeParameters().isEmpty()) { this.fBuffer.append("<"); // $NON-NLS-1$ for (Iterator it = node.typeParameters().iterator(); it.hasNext(); ) { TypeParameter t = (TypeParameter) it.next(); t.accept(this); if (it.hasNext()) { this.fBuffer.append(", "); // $NON-NLS-1$ } } this.fBuffer.append("> "); // $NON-NLS-1$ } } if (!node.isConstructor()) { if (node.getReturnType2() != null) { node.getReturnType2().accept(this); } else { // methods really ought to have a return type this.fBuffer.append("void"); // $NON-NLS-1$ } this.fBuffer.append(" "); // $NON-NLS-1$ } node.getName().accept(this); this.fBuffer.append("("); // $NON-NLS-1$ for (Iterator it = node.parameters().iterator(); it.hasNext(); ) { SingleVariableDeclaration v = (SingleVariableDeclaration) it.next(); v.accept(this); if (it.hasNext()) { this.fBuffer.append(", "); // $NON-NLS-1$ } } this.fBuffer.append(")"); // $NON-NLS-1$ for (int i = 0; i < node.getExtraDimensions(); i++) { this.fBuffer.append("[]"); // $NON-NLS-1$ } if (!node.thrownExceptions().isEmpty()) { this.fBuffer.append(" throws "); // $NON-NLS-1$ for (Iterator it = node.thrownExceptions().iterator(); it.hasNext(); ) { Name n = (Name) it.next(); n.accept(this); if (it.hasNext()) { this.fBuffer.append(", "); // $NON-NLS-1$ } } this.fBuffer.append(" "); // $NON-NLS-1$ } if (node.getBody() == null) { this.fBuffer.append(";"); // $NON-NLS-1$ } else { node.getBody().accept(this); } return false; }
private boolean isEnhancedForStatementVariable(Statement statement, SimpleName name) { if (statement instanceof EnhancedForStatement) { EnhancedForStatement forStatement = (EnhancedForStatement) statement; SingleVariableDeclaration param = forStatement.getParameter(); return param.getType() == name.getParent(); // strange recovery, see https://bugs.eclipse.org/180456 } return false; }
@Override public boolean visit(MethodDeclaration node) { for (Object param : node.parameters()) { SingleVariableDeclaration arg = (SingleVariableDeclaration) param; String name = arg.getName().getFullyQualifiedName(); String typName = arg.getType().toString(); map.put(name, typName); } return true; }
private static Set<String> getPreviousParamNames( List<SingleVariableDeclaration> params, ASTNode missingNode) { Set<String> previousNames = new HashSet<>(); for (int i = 0; i < params.size(); i++) { SingleVariableDeclaration curr = params.get(i); if (curr == missingNode) { return previousNames; } previousNames.add(curr.getName().getIdentifier()); } return previousNames; }
private Statement createInnerConstructorInvocation(MethodDeclaration m) { ConstructorInvocation invocation = m.getAST().newConstructorInvocation(); Types.addBinding(invocation, Types.getBinding(m)); for (SingleVariableDeclaration param : ASTUtil.getParameters(m)) { SimpleName paramName = param.getName(); IVariableBinding paramBinding = Types.getVariableBinding(paramName); SimpleName argName = m.getAST().newSimpleName(paramName.getIdentifier()); Types.addBinding(argName, paramBinding); ASTUtil.getArguments(invocation).add(argName); } return invocation; }
/** * Builds a new {@link CatchClause} instance. * * @param exceptionTypeName the exception type name * @param caughtExceptionName the local name for the caught exception * @param stmts the statements to add to the catch clause * @return a new catch clause */ public CatchClause catch0( String exceptionTypeName, String caughtExceptionName, Statement... stmts) { final CatchClause cc = ast.newCatchClause(); final SingleVariableDeclaration svd = ast.newSingleVariableDeclaration(); svd.setType(newSimpleType(exceptionTypeName)); svd.setName(ast.newSimpleName(caughtExceptionName)); cc.setException(svd); final Block block = ast.newBlock(); addAll(statements(block), stmts); cc.setBody(block); return cc; }
/** {@inheritDoc} */ public boolean visit(SingleVariableDeclaration node) { SimpleName name = node.getName(); IBinding binding = name.resolveBinding(); if (!(binding instanceof IVariableBinding)) return false; IVariableBinding varBinding = (IVariableBinding) binding; if (fWrittenVariables.containsKey(varBinding)) return false; if (fAddFinalParameters && fAddFinalLocals) { ModifierChangeOperation op = createAddFinalOperation(name, node); if (op == null) return false; fResult.add(op); return false; } else if (fAddFinalParameters) { if (!varBinding.isParameter()) return false; ModifierChangeOperation op = createAddFinalOperation(name, node); if (op == null) return false; fResult.add(op); return false; } else if (fAddFinalLocals) { if (varBinding.isParameter()) return false; ModifierChangeOperation op = createAddFinalOperation(name, node); if (op == null) return false; fResult.add(op); return false; } return false; }
private String getSignature(MethodDeclaration node) { StringBuffer buffer = new StringBuffer(); buffer.append(node.getName().toString()); buffer.append('('); boolean first = true; Iterator iterator = node.parameters().iterator(); while (iterator.hasNext()) { Object parameterDecl = iterator.next(); if (parameterDecl instanceof SingleVariableDeclaration) { SingleVariableDeclaration svd = (SingleVariableDeclaration) parameterDecl; if (!first) buffer.append(", "); // $NON-NLS-1$ buffer.append(getType(svd.getType())); if (svd.isVarargs()) buffer.append("..."); // $NON-NLS-1$ first = false; } } buffer.append(')'); return buffer.toString(); }
private ASTRewrite doAddParam(CompilationUnit cu) { AST ast = cu.getAST(); SimpleName node = fOriginalNode; BodyDeclaration decl = ASTResolving.findParentBodyDeclaration(node); if (decl instanceof MethodDeclaration) { MethodDeclaration methodDeclaration = (MethodDeclaration) decl; ASTRewrite rewrite = ASTRewrite.create(ast); ImportRewrite imports = createImportRewrite((CompilationUnit) decl.getRoot()); ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(decl, imports); SingleVariableDeclaration newDecl = ast.newSingleVariableDeclaration(); newDecl.setType( evaluateVariableType( ast, imports, importRewriteContext, methodDeclaration.resolveBinding())); newDecl.setName(ast.newSimpleName(node.getIdentifier())); ListRewrite listRewriter = rewrite.getListRewrite(decl, MethodDeclaration.PARAMETERS_PROPERTY); listRewriter.insertLast(newDecl, null); addLinkedPosition(rewrite.track(node), true, KEY_NAME); // add javadoc tag Javadoc javadoc = methodDeclaration.getJavadoc(); if (javadoc != null) { HashSet<String> leadingNames = new HashSet<String>(); for (Iterator<SingleVariableDeclaration> iter = methodDeclaration.parameters().iterator(); iter.hasNext(); ) { SingleVariableDeclaration curr = iter.next(); leadingNames.add(curr.getName().getIdentifier()); } SimpleName newTagRef = ast.newSimpleName(node.getIdentifier()); TagElement newTagElement = ast.newTagElement(); newTagElement.setTagName(TagElement.TAG_PARAM); newTagElement.fragments().add(newTagRef); TextElement commentStart = ast.newTextElement(); newTagElement.fragments().add(commentStart); addLinkedPosition(rewrite.track(newTagRef), false, KEY_NAME); addLinkedPosition(rewrite.track(commentStart), false, "comment_start"); // $NON-NLS-1$ ListRewrite tagsRewriter = rewrite.getListRewrite(javadoc, Javadoc.TAGS_PROPERTY); JavadocTagsSubProcessor.insertTag(tagsRewriter, newTagElement, leadingNames); } addLinkedPosition(rewrite.track(newDecl.getType()), false, KEY_TYPE); addLinkedPosition(rewrite.track(newDecl.getName()), false, KEY_NAME); return rewrite; } return null; }
private SingleVariableDeclaration createParameterDeclaration( String parameterName, VariableDeclarationFragment fragement, Expression arrayAccess, ForStatement statement, ImportRewrite importRewrite, ASTRewrite rewrite, TextEditGroup group, LinkedProposalPositionGroup pg, boolean makeFinal) { CompilationUnit compilationUnit = (CompilationUnit) arrayAccess.getRoot(); AST ast = compilationUnit.getAST(); SingleVariableDeclaration result = ast.newSingleVariableDeclaration(); SimpleName name = ast.newSimpleName(parameterName); pg.addPosition(rewrite.track(name), true); result.setName(name); ITypeBinding arrayTypeBinding = arrayAccess.resolveTypeBinding(); Type type = importType(arrayTypeBinding.getElementType(), statement, importRewrite, compilationUnit); if (arrayTypeBinding.getDimensions() != 1) { type = ast.newArrayType(type, arrayTypeBinding.getDimensions() - 1); } result.setType(type); if (fragement != null) { VariableDeclarationStatement declaration = (VariableDeclarationStatement) fragement.getParent(); ModifierRewrite.create(rewrite, result).copyAllModifiers(declaration, group); } if (makeFinal && (fragement == null || ASTNodes.findModifierNode(Modifier.FINAL, ASTNodes.getModifiers(fragement)) == null)) { ModifierRewrite.create(rewrite, result).setModifiers(Modifier.FINAL, 0, group); } return result; }
@SuppressWarnings("unchecked") public boolean doesMethodTakeTypes(MethodDeclaration methodDecl, List<Type> types) { List parameters = methodDecl.parameters(); if (parameters.size() == types.size()) { boolean typesEqual = true; for (int i = 0; i < parameters.size(); i++) { SingleVariableDeclaration param = (SingleVariableDeclaration) parameters.get(i); assert param != null; if (!param.getType().toString().equals(types.get(i).toString())) { typesEqual = false; break; } } if (typesEqual) return true; } return false; }
/* * @see ASTVisitor#visit(SingleVariableDeclaration) */ public boolean visit(SingleVariableDeclaration node) { if (node.getAST().apiLevel() >= AST.JLS3) { printModifiers(node.modifiers()); } node.getType().accept(this); if (node.getAST().apiLevel() >= AST.JLS3) { if (node.isVarargs()) { this.fBuffer.append("..."); // $NON-NLS-1$ } } this.fBuffer.append(" "); // $NON-NLS-1$ node.getName().accept(this); for (int i = 0; i < node.getExtraDimensions(); i++) { this.fBuffer.append("[]"); // $NON-NLS-1$ } if (node.getInitializer() != null) { this.fBuffer.append("="); // $NON-NLS-1$ node.getInitializer().accept(this); } return false; }
/** Looks for Method Parameters. */ @Override public boolean visit(final SingleVariableDeclaration node) { addBinding(node, node.getName(), node.getType()); return true; }
/* * @see ASTVisitor#visit(SingleVariableDeclaration) */ @Override public boolean visit(SingleVariableDeclaration node) { if (node.getAST().apiLevel() >= JLS3) { printModifiers(node.modifiers()); } node.getType().accept(this); if (node.getAST().apiLevel() >= JLS3) { if (node.isVarargs()) { if (node.getAST().apiLevel() >= AST.JLS8) { this.fBuffer.append(' '); List<Annotation> annotations = node.varargsAnnotations(); printAnnotationsList(annotations); } this.fBuffer.append("..."); // $NON-NLS-1$ } } this.fBuffer.append(" "); // $NON-NLS-1$ node.getName().accept(this); if (node.getAST().apiLevel() >= AST.JLS8) { List<Dimension> dimensions = node.extraDimensions(); for (Iterator<Dimension> it = dimensions.iterator(); it.hasNext(); ) { Dimension e = it.next(); e.accept(this); } } else { for (int i = 0; i < node.getExtraDimensions(); i++) { this.fBuffer.append("[]"); // $NON-NLS-1$ } } if (node.getInitializer() != null) { this.fBuffer.append("="); // $NON-NLS-1$ node.getInitializer().accept(this); } return false; }
private List<ClassObject> parseAST(CompilationUnit compilationUnit, IFile iFile) { List<ClassObject> classObjects = new ArrayList<ClassObject>(); List<AbstractTypeDeclaration> topLevelTypeDeclarations = compilationUnit.types(); for (AbstractTypeDeclaration abstractTypeDeclaration : topLevelTypeDeclarations) { if (abstractTypeDeclaration instanceof TypeDeclaration) { TypeDeclaration topLevelTypeDeclaration = (TypeDeclaration) abstractTypeDeclaration; List<TypeDeclaration> typeDeclarations = new ArrayList<TypeDeclaration>(); typeDeclarations.add(topLevelTypeDeclaration); typeDeclarations.addAll(getRecursivelyInnerTypes(topLevelTypeDeclaration)); for (TypeDeclaration typeDeclaration : typeDeclarations) { final ClassObject classObject = new ClassObject(); classObject.setIFile(iFile); classObject.setName(typeDeclaration.resolveBinding().getQualifiedName()); classObject.setTypeDeclaration(typeDeclaration); if (typeDeclaration.isInterface()) { classObject.setInterface(true); } int modifiers = typeDeclaration.getModifiers(); if ((modifiers & Modifier.ABSTRACT) != 0) classObject.setAbstract(true); if ((modifiers & Modifier.PUBLIC) != 0) classObject.setAccess(Access.PUBLIC); else if ((modifiers & Modifier.PROTECTED) != 0) classObject.setAccess(Access.PROTECTED); else if ((modifiers & Modifier.PRIVATE) != 0) classObject.setAccess(Access.PRIVATE); else classObject.setAccess(Access.NONE); if ((modifiers & Modifier.STATIC) != 0) classObject.setStatic(true); Type superclassType = typeDeclaration.getSuperclassType(); if (superclassType != null) { ITypeBinding binding = superclassType.resolveBinding(); String qualifiedName = binding.getQualifiedName(); TypeObject typeObject = TypeObject.extractTypeObject(qualifiedName); classObject.setSuperclass(typeObject); } List<Type> superInterfaceTypes = typeDeclaration.superInterfaceTypes(); for (Type interfaceType : superInterfaceTypes) { ITypeBinding binding = interfaceType.resolveBinding(); String qualifiedName = binding.getQualifiedName(); TypeObject typeObject = TypeObject.extractTypeObject(qualifiedName); classObject.addInterface(typeObject); } FieldDeclaration[] fieldDeclarations = typeDeclaration.getFields(); for (FieldDeclaration fieldDeclaration : fieldDeclarations) { Type fieldType = fieldDeclaration.getType(); ITypeBinding binding = fieldType.resolveBinding(); List<VariableDeclarationFragment> fragments = fieldDeclaration.fragments(); for (VariableDeclarationFragment fragment : fragments) { String qualifiedName = binding.getQualifiedName(); TypeObject typeObject = TypeObject.extractTypeObject(qualifiedName); typeObject.setArrayDimension( typeObject.getArrayDimension() + fragment.getExtraDimensions()); FieldObject fieldObject = new FieldObject(typeObject, fragment.getName().getIdentifier()); fieldObject.setClassName(classObject.getName()); fieldObject.setVariableDeclarationFragment(fragment); int fieldModifiers = fieldDeclaration.getModifiers(); if ((fieldModifiers & Modifier.PUBLIC) != 0) fieldObject.setAccess(Access.PUBLIC); else if ((fieldModifiers & Modifier.PROTECTED) != 0) fieldObject.setAccess(Access.PROTECTED); else if ((fieldModifiers & Modifier.PRIVATE) != 0) fieldObject.setAccess(Access.PRIVATE); else fieldObject.setAccess(Access.NONE); if ((fieldModifiers & Modifier.STATIC) != 0) fieldObject.setStatic(true); classObject.addField(fieldObject); } } MethodDeclaration[] methodDeclarations = typeDeclaration.getMethods(); for (MethodDeclaration methodDeclaration : methodDeclarations) { String methodName = methodDeclaration.getName().getIdentifier(); final ConstructorObject constructorObject = new ConstructorObject(); constructorObject.setMethodDeclaration(methodDeclaration); constructorObject.setName(methodName); constructorObject.setClassName(classObject.getName()); int methodModifiers = methodDeclaration.getModifiers(); if ((methodModifiers & Modifier.PUBLIC) != 0) constructorObject.setAccess(Access.PUBLIC); else if ((methodModifiers & Modifier.PROTECTED) != 0) constructorObject.setAccess(Access.PROTECTED); else if ((methodModifiers & Modifier.PRIVATE) != 0) constructorObject.setAccess(Access.PRIVATE); else constructorObject.setAccess(Access.NONE); List<SingleVariableDeclaration> parameters = methodDeclaration.parameters(); for (SingleVariableDeclaration parameter : parameters) { Type parameterType = parameter.getType(); ITypeBinding binding = parameterType.resolveBinding(); String qualifiedName = binding.getQualifiedName(); TypeObject typeObject = TypeObject.extractTypeObject(qualifiedName); typeObject.setArrayDimension( typeObject.getArrayDimension() + parameter.getExtraDimensions()); if (parameter.isVarargs()) { typeObject.setArrayDimension(1); } ParameterObject parameterObject = new ParameterObject(typeObject, parameter.getName().getIdentifier()); parameterObject.setSingleVariableDeclaration(parameter); constructorObject.addParameter(parameterObject); } Block methodBody = methodDeclaration.getBody(); if (methodBody != null) { MethodBodyObject methodBodyObject = new MethodBodyObject(methodBody); constructorObject.setMethodBody(methodBodyObject); } if (methodDeclaration.isConstructor()) { classObject.addConstructor(constructorObject); } else { MethodObject methodObject = new MethodObject(constructorObject); List<IExtendedModifier> extendedModifiers = methodDeclaration.modifiers(); for (IExtendedModifier extendedModifier : extendedModifiers) { if (extendedModifier.isAnnotation()) { Annotation annotation = (Annotation) extendedModifier; if (annotation.getTypeName().getFullyQualifiedName().equals("Test")) { methodObject.setTestAnnotation(true); break; } } } Type returnType = methodDeclaration.getReturnType2(); ITypeBinding binding = returnType.resolveBinding(); String qualifiedName = binding.getQualifiedName(); TypeObject typeObject = TypeObject.extractTypeObject(qualifiedName); methodObject.setReturnType(typeObject); if ((methodModifiers & Modifier.ABSTRACT) != 0) methodObject.setAbstract(true); if ((methodModifiers & Modifier.STATIC) != 0) methodObject.setStatic(true); if ((methodModifiers & Modifier.SYNCHRONIZED) != 0) methodObject.setSynchronized(true); if ((methodModifiers & Modifier.NATIVE) != 0) methodObject.setNative(true); classObject.addMethod(methodObject); FieldInstructionObject fieldInstruction = methodObject.isGetter(); if (fieldInstruction != null) systemObject.addGetter(methodObject.generateMethodInvocation(), fieldInstruction); fieldInstruction = methodObject.isSetter(); if (fieldInstruction != null) systemObject.addSetter(methodObject.generateMethodInvocation(), fieldInstruction); fieldInstruction = methodObject.isCollectionAdder(); if (fieldInstruction != null) systemObject.addCollectionAdder( methodObject.generateMethodInvocation(), fieldInstruction); MethodInvocationObject methodInvocation = methodObject.isDelegate(); if (methodInvocation != null) systemObject.addDelegate(methodObject.generateMethodInvocation(), methodInvocation); } } classObjects.add(classObject); } } } return classObjects; }
/* * @see ASTVisitor#visit(MethodDeclaration) */ @Override public boolean visit(MethodDeclaration node) { if (node.getJavadoc() != null) { node.getJavadoc().accept(this); } if (node.getAST().apiLevel() >= JLS3) { printModifiers(node.modifiers()); if (!node.typeParameters().isEmpty()) { this.fBuffer.append("<"); // $NON-NLS-1$ for (Iterator<TypeParameter> it = node.typeParameters().iterator(); it.hasNext(); ) { TypeParameter t = it.next(); t.accept(this); if (it.hasNext()) { this.fBuffer.append(", "); // $NON-NLS-1$ } } this.fBuffer.append("> "); // $NON-NLS-1$ } } if (!node.isConstructor()) { if (node.getReturnType2() != null) { node.getReturnType2().accept(this); } else { // methods really ought to have a return type this.fBuffer.append("void"); // $NON-NLS-1$ } this.fBuffer.append(" "); // $NON-NLS-1$ } node.getName().accept(this); this.fBuffer.append("("); // $NON-NLS-1$ if (node.getAST().apiLevel() >= AST.JLS8) { Type receiverType = node.getReceiverType(); if (receiverType != null) { receiverType.accept(this); this.fBuffer.append(' '); SimpleName qualifier = node.getReceiverQualifier(); if (qualifier != null) { qualifier.accept(this); this.fBuffer.append('.'); } this.fBuffer.append("this"); // $NON-NLS-1$ if (node.parameters().size() > 0) { this.fBuffer.append(','); } } } for (Iterator<SingleVariableDeclaration> it = node.parameters().iterator(); it.hasNext(); ) { SingleVariableDeclaration v = it.next(); v.accept(this); if (it.hasNext()) { this.fBuffer.append(", "); // $NON-NLS-1$ } } this.fBuffer.append(")"); // $NON-NLS-1$ if (node.getAST().apiLevel() >= AST.JLS8) { List<Dimension> dimensions = node.extraDimensions(); for (Iterator<Dimension> it = dimensions.iterator(); it.hasNext(); ) { Dimension e = it.next(); e.accept(this); } } else { for (int i = 0; i < node.getExtraDimensions(); i++) { this.fBuffer.append("[]"); // $NON-NLS-1$ } } List<? extends ASTNode> thrownExceptions = node.getAST().apiLevel() >= AST.JLS8 ? node.thrownExceptionTypes() : getThrownExceptions(node); if (!thrownExceptions.isEmpty()) { this.fBuffer.append(" throws "); // $NON-NLS-1$ for (Iterator<? extends ASTNode> it = thrownExceptions.iterator(); it.hasNext(); ) { ASTNode n = it.next(); n.accept(this); if (it.hasNext()) { this.fBuffer.append(", "); // $NON-NLS-1$ } } this.fBuffer.append(" "); // $NON-NLS-1$ } if (node.getBody() == null) { this.fBuffer.append(";"); // $NON-NLS-1$ } else { node.getBody().accept(this); } return false; }
public static void addFinalAndValAnnotationToSingleVariableDeclaration( Object converter, SingleVariableDeclaration out, LocalDeclaration in) { @SuppressWarnings("unchecked") List<IExtendedModifier> modifiers = out.modifiers(); addFinalAndValAnnotationToModifierList(converter, modifiers, out.getAST(), in); }
public SingleVariableDeclaration newVariableDecl(String name, String type) { SingleVariableDeclaration exceptionDecl = ast.newSingleVariableDeclaration(); exceptionDecl.setName(ast.newSimpleName(name)); exceptionDecl.setType(ast.newSimpleType(ast.newName(type))); return exceptionDecl; }
public boolean isFinal() { return Modifier.isFinal(fDeclaration.getModifiers()); }
private void insertAllMissingMethodTags(ASTRewrite rewriter, MethodDeclaration methodDecl) { AST ast = methodDecl.getAST(); Javadoc javadoc = methodDecl.getJavadoc(); ListRewrite tagsRewriter = rewriter.getListRewrite(javadoc, Javadoc.TAGS_PROPERTY); List<TypeParameter> typeParams = methodDecl.typeParameters(); ASTNode root = methodDecl.getRoot(); if (root instanceof CompilationUnit) { ITypeRoot typeRoot = ((CompilationUnit) root).getTypeRoot(); if (typeRoot != null && !StubUtility.shouldGenerateMethodTypeParameterTags(typeRoot.getJavaProject())) typeParams = Collections.emptyList(); } List<String> typeParamNames = new ArrayList<>(); for (int i = typeParams.size() - 1; i >= 0; i--) { TypeParameter decl = typeParams.get(i); String name = '<' + decl.getName().getIdentifier() + '>'; if (findTag(javadoc, TagElement.TAG_PARAM, name) == null) { TagElement newTag = ast.newTagElement(); newTag.setTagName(TagElement.TAG_PARAM); TextElement text = ast.newTextElement(); text.setText(name); newTag.fragments().add(text); insertTabStop(rewriter, newTag.fragments(), "typeParam" + i); // $NON-NLS-1$ insertTag(tagsRewriter, newTag, getPreviousTypeParamNames(typeParams, decl)); } typeParamNames.add(name); } List<SingleVariableDeclaration> params = methodDecl.parameters(); for (int i = params.size() - 1; i >= 0; i--) { SingleVariableDeclaration decl = params.get(i); String name = decl.getName().getIdentifier(); if (findTag(javadoc, TagElement.TAG_PARAM, name) == null) { TagElement newTag = ast.newTagElement(); newTag.setTagName(TagElement.TAG_PARAM); newTag.fragments().add(ast.newSimpleName(name)); insertTabStop(rewriter, newTag.fragments(), "methParam" + i); // $NON-NLS-1$ Set<String> sameKindLeadingNames = getPreviousParamNames(params, decl); sameKindLeadingNames.addAll(typeParamNames); insertTag(tagsRewriter, newTag, sameKindLeadingNames); } } if (!methodDecl.isConstructor()) { Type type = methodDecl.getReturnType2(); if (!type.isPrimitiveType() || (((PrimitiveType) type).getPrimitiveTypeCode() != PrimitiveType.VOID)) { if (findTag(javadoc, TagElement.TAG_RETURN, null) == null) { TagElement newTag = ast.newTagElement(); newTag.setTagName(TagElement.TAG_RETURN); insertTabStop(rewriter, newTag.fragments(), "return"); // $NON-NLS-1$ insertTag(tagsRewriter, newTag, null); } } } List<Type> thrownExceptions = methodDecl.thrownExceptionTypes(); for (int i = thrownExceptions.size() - 1; i >= 0; i--) { Type exception = thrownExceptions.get(i); ITypeBinding binding = exception.resolveBinding(); if (binding != null) { String name = binding.getName(); if (findThrowsTag(javadoc, name) == null) { TagElement newTag = ast.newTagElement(); newTag.setTagName(TagElement.TAG_THROWS); TextElement excNode = ast.newTextElement(); excNode.setText(ASTNodes.getQualifiedTypeName(exception)); newTag.fragments().add(excNode); insertTabStop(rewriter, newTag.fragments(), "exception" + i); // $NON-NLS-1$ insertTag(tagsRewriter, newTag, getPreviousExceptionNames(thrownExceptions, exception)); } } } }
private void createTryCatchStatement(org.eclipse.jdt.core.IBuffer buffer, String lineDelimiter) throws CoreException { List<Statement> result = new ArrayList<>(1); TryStatement tryStatement = getAST().newTryStatement(); ITypeBinding[] exceptions = fAnalyzer.getExceptions(); ImportRewriteContext context = new ContextSensitiveImportRewriteContext( fAnalyzer.getEnclosingBodyDeclaration(), fImportRewrite); if (!fIsMultiCatch) { for (int i = 0; i < exceptions.length; i++) { ITypeBinding exception = exceptions[i]; CatchClause catchClause = getAST().newCatchClause(); tryStatement.catchClauses().add(catchClause); SingleVariableDeclaration decl = getAST().newSingleVariableDeclaration(); String varName = StubUtility.getExceptionVariableName(fCUnit.getJavaProject()); String name = fScope.createName(varName, false); decl.setName(getAST().newSimpleName(name)); Type type = fImportRewrite.addImport(exception, getAST(), context); decl.setType(type); catchClause.setException(decl); Statement st = getCatchBody(ASTNodes.getQualifiedTypeName(type), name, lineDelimiter); if (st != null) { catchClause.getBody().statements().add(st); } fLinkedProposalModel .getPositionGroup(GROUP_EXC_TYPE + i, true) .addPosition(fRewriter.track(decl.getType()), i == 0); fLinkedProposalModel .getPositionGroup(GROUP_EXC_NAME + i, true) .addPosition(fRewriter.track(decl.getName()), false); } } else { List<ITypeBinding> filteredExceptions = filterSubtypeExceptions(exceptions); CatchClause catchClause = getAST().newCatchClause(); SingleVariableDeclaration decl = getAST().newSingleVariableDeclaration(); String varName = StubUtility.getExceptionVariableName(fCUnit.getJavaProject()); String name = fScope.createName(varName, false); decl.setName(getAST().newSimpleName(name)); UnionType unionType = getAST().newUnionType(); List<Type> types = unionType.types(); int i = 0; for (ITypeBinding exception : filteredExceptions) { Type type = fImportRewrite.addImport(exception, getAST(), context); types.add(type); fLinkedProposalModel .getPositionGroup(GROUP_EXC_TYPE + i, true) .addPosition(fRewriter.track(type), i == 0); i++; } decl.setType(unionType); catchClause.setException(decl); fLinkedProposalModel .getPositionGroup(GROUP_EXC_NAME + 0, true) .addPosition(fRewriter.track(decl.getName()), false); Statement st = getCatchBody("Exception", name, lineDelimiter); // $NON-NLS-1$ if (st != null) { catchClause.getBody().statements().add(st); } tryStatement.catchClauses().add(catchClause); } List<ASTNode> variableDeclarations = getSpecialVariableDeclarationStatements(); ListRewrite statements = fRewriter.getListRewrite(tryStatement.getBody(), Block.STATEMENTS_PROPERTY); boolean selectedNodeRemoved = false; ASTNode expressionStatement = null; for (int i = 0; i < fSelectedNodes.length; i++) { ASTNode node = fSelectedNodes[i]; if (node instanceof VariableDeclarationStatement && variableDeclarations.contains(node)) { AST ast = getAST(); VariableDeclarationStatement statement = (VariableDeclarationStatement) node; // Create a copy and remove the initializer VariableDeclarationStatement copy = (VariableDeclarationStatement) ASTNode.copySubtree(ast, statement); List<IExtendedModifier> modifiers = copy.modifiers(); for (Iterator<IExtendedModifier> iter = modifiers.iterator(); iter.hasNext(); ) { IExtendedModifier modifier = iter.next(); if (modifier.isModifier() && Modifier.isFinal(((Modifier) modifier).getKeyword().toFlagValue())) { iter.remove(); } } List<VariableDeclarationFragment> fragments = copy.fragments(); for (Iterator<VariableDeclarationFragment> iter = fragments.iterator(); iter.hasNext(); ) { VariableDeclarationFragment fragment = iter.next(); fragment.setInitializer(null); } CompilationUnit root = (CompilationUnit) statement.getRoot(); int extendedStart = root.getExtendedStartPosition(statement); // we have a leading comment and the comment is covered by the selection if (extendedStart != statement.getStartPosition() && extendedStart >= fSelection.getOffset()) { String commentToken = buffer.getText(extendedStart, statement.getStartPosition() - extendedStart); commentToken = Strings.trimTrailingTabsAndSpaces(commentToken); Type type = statement.getType(); String typeName = buffer.getText(type.getStartPosition(), type.getLength()); copy.setType( (Type) fRewriter.createStringPlaceholder(commentToken + typeName, type.getNodeType())); } result.add(copy); // convert the fragments into expression statements fragments = statement.fragments(); if (!fragments.isEmpty()) { List<ExpressionStatement> newExpressionStatements = new ArrayList<>(); for (Iterator<VariableDeclarationFragment> iter = fragments.iterator(); iter.hasNext(); ) { VariableDeclarationFragment fragment = iter.next(); Expression initializer = fragment.getInitializer(); if (initializer != null) { Assignment assignment = ast.newAssignment(); assignment.setLeftHandSide( (Expression) fRewriter.createCopyTarget(fragment.getName())); assignment.setRightHandSide((Expression) fRewriter.createCopyTarget(initializer)); newExpressionStatements.add(ast.newExpressionStatement(assignment)); } } if (!newExpressionStatements.isEmpty()) { if (fSelectedNodes.length == 1) { expressionStatement = fRewriter.createGroupNode( newExpressionStatements.toArray(new ASTNode[newExpressionStatements.size()])); } else { fRewriter.replace( statement, fRewriter.createGroupNode( newExpressionStatements.toArray(new ASTNode[newExpressionStatements.size()])), null); } } else { fRewriter.remove(statement, null); selectedNodeRemoved = true; } } else { fRewriter.remove(statement, null); selectedNodeRemoved = true; } } } result.add(tryStatement); ASTNode replacementNode; if (result.size() == 1) { replacementNode = result.get(0); } else { replacementNode = fRewriter.createGroupNode(result.toArray(new ASTNode[result.size()])); } if (fSelectedNodes.length == 1) { ASTNode selectedNode = fSelectedNodes[0]; if (selectedNode instanceof MethodReference) { MethodReference methodReference = (MethodReference) selectedNode; IMethodBinding functionalMethod = QuickAssistProcessor.getFunctionalMethodForMethodReference(methodReference); // functionalMethod is non-null and non-generic. See // ExceptionAnalyzer.handleMethodReference(MethodReference node). Assert.isTrue(functionalMethod != null && !functionalMethod.isGenericMethod()); LambdaExpression lambda = QuickAssistProcessor.convertMethodRefernceToLambda( methodReference, functionalMethod, fRootNode, fRewriter, null, true); ASTNode statementInBlock = (ASTNode) ((Block) lambda.getBody()).statements().get(0); fRewriter.replace(statementInBlock, replacementNode, null); statements.insertLast(statementInBlock, null); return; } LambdaExpression enclosingLambda = ASTResolving.findEnclosingLambdaExpression(selectedNode); if (enclosingLambda != null && selectedNode.getLocationInParent() == LambdaExpression.BODY_PROPERTY && enclosingLambda.resolveMethodBinding() != null) { QuickAssistProcessor.changeLambdaBodyToBlock(enclosingLambda, getAST(), fRewriter); Block blockBody = (Block) fRewriter.get(enclosingLambda, LambdaExpression.BODY_PROPERTY); ASTNode statementInBlock = (ASTNode) blockBody.statements().get(0); fRewriter.replace(statementInBlock, replacementNode, null); statements.insertLast(statementInBlock, null); return; } if (expressionStatement != null) { statements.insertLast(expressionStatement, null); } else { if (!selectedNodeRemoved) statements.insertLast(fRewriter.createMoveTarget(selectedNode), null); } fRewriter.replace(selectedNode, replacementNode, null); } else { ListRewrite source = fRewriter.getListRewrite( fSelectedNodes[0].getParent(), (ChildListPropertyDescriptor) fSelectedNodes[0].getLocationInParent()); ASTNode toMove = source.createMoveTarget( fSelectedNodes[0], fSelectedNodes[fSelectedNodes.length - 1], replacementNode, null); statements.insertLast(toMove, null); } }
public String getName() { return fDeclaration.getName().getIdentifier(); }
public ITypeBinding getTypeBinding() { return fDeclaration.resolveBinding().getType(); }