/**
  * Collects the existing tags on the {@link IJavaElement} we have been activated on
  *
  * @param element
  * @param jcontext
  * @throws JavaModelException
  * @throws BadLocationException
  */
 private void collectExistingTags(
     IJavaElement element, JavaContentAssistInvocationContext jcontext) throws JavaModelException {
   if (element instanceof IMember) {
     IMember member = (IMember) element;
     ICompilationUnit cunit = jcontext.getCompilationUnit();
     if (cunit != null) {
       if (cunit.isWorkingCopy()) {
         cunit.reconcile(ICompilationUnit.NO_AST, false, false, null, null);
       }
       fParser.setSource(member.getSource().toCharArray());
       fParser.setKind(ASTParser.K_CLASS_BODY_DECLARATIONS);
       Map<String, String> options = element.getJavaProject().getOptions(true);
       options.put(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, JavaCore.ENABLED);
       fParser.setCompilerOptions(options);
       fParser.setStatementsRecovery(false);
       fParser.setResolveBindings(false);
       fParser.setBindingsRecovery(false);
       ASTNode ast = fParser.createAST(null);
       TagCollector collector = new TagCollector();
       if (ast.getNodeType() == ASTNode.TYPE_DECLARATION) {
         TypeDeclaration typeDeclaration = (TypeDeclaration) ast;
         List<BodyDeclaration> bodyDeclarations = typeDeclaration.bodyDeclarations();
         if (bodyDeclarations.size() == 1) {
           // only one element should be there as we are parsing a
           // specific member
           BodyDeclaration bodyDeclaration = bodyDeclarations.iterator().next();
           Javadoc javadoc = bodyDeclaration.getJavadoc();
           if (javadoc != null) {
             javadoc.accept(collector);
           }
         }
       }
     }
   }
 }
 /**
  * Updates a javadoc tag, by either adding a new one or removing an existing one
  *
  * @param body
  */
 private void updateTag(BodyDeclaration body) {
   Javadoc docnode = body.getJavadoc();
   AST ast = body.getAST();
   if (docnode == null) {
     docnode = ast.newJavadoc();
     rewrite.set(body, body.getJavadocProperty(), docnode, null);
   }
   ListRewrite lrewrite = rewrite.getListRewrite(docnode, Javadoc.TAGS_PROPERTY);
   if (remove) {
     List<TagElement> tags =
         (List<TagElement>) docnode.getStructuralProperty(Javadoc.TAGS_PROPERTY);
     if (tags != null) {
       TagElement tag = null;
       for (int i = 0; i < tags.size(); i++) {
         tag = tags.get(i);
         if (tagname.equals(tag.getTagName())) {
           lrewrite.remove(tag, null);
         }
       }
     }
   } else {
     TagElement newtag = ast.newTagElement();
     newtag.setTagName(tagname);
     lrewrite.insertLast(newtag, null);
   }
 }
Beispiel #3
0
  @SuppressWarnings("rawtypes")
  private void getASTConstructor(
      final AbstractTypeDeclaration typeDecl, final List<ConstructorDeclaration> results) {

    final List bodyDecls = typeDecl.bodyDeclarations();
    IFile file = null;
    for (int i = 0, len = bodyDecls.size(); i < len; i++) {
      final BodyDeclaration bodyDecl = (BodyDeclaration) bodyDecls.get(i);
      if (bodyDecl.getNodeType() == ASTNode.METHOD_DECLARATION) {
        final org.eclipse.jdt.core.dom.MethodDeclaration methodDecl =
            (org.eclipse.jdt.core.dom.MethodDeclaration) bodyDecl;

        if (methodDecl.isConstructor()) {
          final IMethodBinding methodBinding = methodDecl.resolveBinding();
          // built an ast based representation.
          if (methodBinding == null) {
            if (file == null) file = getResource();
            ConstructorDeclaration mirrorDecl =
                (ConstructorDeclaration) Factory.createDeclaration(methodDecl, file, _env);
            if (mirrorDecl != null) results.add(mirrorDecl);
          }
        }
      }
    }
  }
 @SuppressWarnings("deprecation")
 protected IValueList parseExtendedModifiers(BodyDeclaration node) {
   if (node.getAST().apiLevel() == AST.JLS2) {
     return parseModifiers(node.getModifiers());
   } else {
     return parseExtendedModifiers(node.modifiers());
   }
 }
 /*
  * @see ASTVisitor#visit(AnonymousClassDeclaration)
  */
 public boolean visit(AnonymousClassDeclaration node) {
   this.fBuffer.append("{"); // $NON-NLS-1$
   for (Iterator it = node.bodyDeclarations().iterator(); it.hasNext(); ) {
     BodyDeclaration b = (BodyDeclaration) it.next();
     b.accept(this);
   }
   this.fBuffer.append("}"); // $NON-NLS-1$
   return false;
 }
  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;
  }
  public static void getMissingJavadocTagProposals(
      IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
    ASTNode node = problem.getCoveringNode(context.getASTRoot());
    if (node == null) {
      return;
    }
    node = ASTNodes.getNormalizedNode(node);

    BodyDeclaration bodyDeclaration = ASTResolving.findParentBodyDeclaration(node);
    if (bodyDeclaration == null) {
      return;
    }
    Javadoc javadoc = bodyDeclaration.getJavadoc();
    if (javadoc == null) {
      return;
    }

    String label;
    StructuralPropertyDescriptor location = node.getLocationInParent();
    if (location == SingleVariableDeclaration.NAME_PROPERTY) {
      label = CorrectionMessages.JavadocTagsSubProcessor_addjavadoc_paramtag_description;
      if (node.getParent().getLocationInParent() != MethodDeclaration.PARAMETERS_PROPERTY) {
        return; // paranoia checks
      }
    } else if (location == TypeParameter.NAME_PROPERTY) {
      label = CorrectionMessages.JavadocTagsSubProcessor_addjavadoc_paramtag_description;
      StructuralPropertyDescriptor parentLocation = node.getParent().getLocationInParent();
      if (parentLocation != MethodDeclaration.TYPE_PARAMETERS_PROPERTY
          && parentLocation != TypeDeclaration.TYPE_PARAMETERS_PROPERTY) {
        return; // paranoia checks
      }
    } else if (location == MethodDeclaration.RETURN_TYPE2_PROPERTY) {
      label = CorrectionMessages.JavadocTagsSubProcessor_addjavadoc_returntag_description;
    } else if (location == MethodDeclaration.THROWN_EXCEPTION_TYPES_PROPERTY) {
      label = CorrectionMessages.JavadocTagsSubProcessor_addjavadoc_throwstag_description;
    } else {
      return;
    }
    ASTRewriteCorrectionProposal proposal =
        new AddMissingJavadocTagProposal(
            label,
            context.getCompilationUnit(),
            bodyDeclaration,
            node,
            IProposalRelevance.ADD_MISSING_TAG);
    proposals.add(proposal);

    String label2 = CorrectionMessages.JavadocTagsSubProcessor_addjavadoc_allmissing_description;
    ASTRewriteCorrectionProposal addAllMissing =
        new AddAllMissingJavadocTagsProposal(
            label2,
            context.getCompilationUnit(),
            bodyDeclaration,
            IProposalRelevance.ADD_ALL_MISSING_TAGS);
    proposals.add(addAllMissing);
  }
 /*
  * @see ASTVisitor#visit(AnonymousClassDeclaration)
  */
 @Override
 public boolean visit(AnonymousClassDeclaration node) {
   this.fBuffer.append("{"); // $NON-NLS-1$
   List<BodyDeclaration> bodyDeclarations = node.bodyDeclarations();
   for (Iterator<BodyDeclaration> it = bodyDeclarations.iterator(); it.hasNext(); ) {
     BodyDeclaration b = it.next();
     b.accept(this);
   }
   this.fBuffer.append("}"); // $NON-NLS-1$
   return false;
 }
 private int findFieldInsertIndex(
     List<BodyDeclaration> decls, FieldDeclaration newDecl, int maxOffset) {
   if (maxOffset != -1) {
     for (int i = decls.size() - 1; i >= 0; i--) {
       BodyDeclaration curr = decls.get(i);
       if (maxOffset > curr.getStartPosition() + curr.getLength()) {
         return ASTNodes.getInsertionIndex(newDecl, decls.subList(0, i + 1));
       }
     }
     return 0;
   }
   return ASTNodes.getInsertionIndex(newDecl, decls);
 }
 /*
  * @see ASTVisitor#visit(AnnotationTypeDeclaration)
  * @since 3.0
  */
 public boolean visit(AnnotationTypeDeclaration node) {
   if (node.getJavadoc() != null) {
     node.getJavadoc().accept(this);
   }
   printModifiers(node.modifiers());
   this.fBuffer.append("@interface "); // $NON-NLS-1$
   node.getName().accept(this);
   this.fBuffer.append(" {"); // $NON-NLS-1$
   for (Iterator it = node.bodyDeclarations().iterator(); it.hasNext(); ) {
     BodyDeclaration d = (BodyDeclaration) it.next();
     d.accept(this);
   }
   this.fBuffer.append("}"); // $NON-NLS-1$
   return false;
 }
 private ITypeBinding[] computeTypeVariables(ITypeBinding[] bindings) {
   Selection selection = getSelection();
   Set<ITypeBinding> result = new HashSet<>();
   // first remove all type variables that come from outside of the method
   // or are covered by the selection
   CompilationUnit compilationUnit = (CompilationUnit) fEnclosingBodyDeclaration.getRoot();
   for (int i = 0; i < bindings.length; i++) {
     ASTNode decl = compilationUnit.findDeclaringNode(bindings[i]);
     if (decl == null
         || (!selection.covers(decl) && decl.getParent() instanceof MethodDeclaration))
       result.add(bindings[i]);
   }
   // all all type variables which are needed since a local variable uses it
   for (int i = 0; i < fArguments.length; i++) {
     IVariableBinding arg = fArguments[i];
     ITypeBinding type = arg.getType();
     if (type != null && type.isTypeVariable()) {
       ASTNode decl = compilationUnit.findDeclaringNode(type);
       if (decl == null
           || (!selection.covers(decl) && decl.getParent() instanceof MethodDeclaration))
         result.add(type);
     }
   }
   return result.toArray(new ITypeBinding[result.size()]);
 }
 @Override
 protected ASTRewrite getRewrite() throws CoreException {
   AST ast = fBodyDecl.getAST();
   ASTRewrite rewrite = ASTRewrite.create(ast);
   insertMissingJavadocTag(rewrite, fMissingNode, fBodyDecl);
   return rewrite;
 }
  // Método para configurar os modificadores
  @SuppressWarnings("unchecked")
  private void setModifiers(ApiElement apiElement, BodyDeclaration node) {

    for (Object o : node.modifiers()) {
      if (o instanceof Modifier) {
        Modifier modifier = (Modifier) o;
        if (modifier.isAbstract()) {
          apiElement.setAbstract(true);
        } else if (modifier.isFinal()) {
          apiElement.setFinal(true);
        } else if (modifier.isPrivate()) {
          apiElement.setPrivate(true);
        } else if (modifier.isProtected()) {
          apiElement.setProtected(true);
        } else if (modifier.isPublic()) {
          apiElement.setPublic(true);
        } else if (modifier.isStatic()) {
          apiElement.setFinal(true);
        }
      }
    }

    apiElement.setDefault(
        !(apiElement.isPrivate() || apiElement.isPublic() || apiElement.isProtected()));

    Javadoc javadoc = node.getJavadoc();
    if (javadoc != null) {
      apiElement.setHasJavadoc(true);
      apiElement.setHidden(false);
      Stack<Object> tags = new Stack<Object>();
      tags.addAll(javadoc.tags());
      while (!tags.isEmpty()) {
        Object tag = tags.pop();
        if (tag instanceof TagElement) {
          String tagName = ((TagElement) tag).getTagName();
          if (tagName != null && tagName.equalsIgnoreCase("@hide")) {
            apiElement.setHidden(true);
            break;
          }
          tags.addAll(((TagElement) tag).fragments());
        }
      }
    } else {
      apiElement.setHasJavadoc(false);
      apiElement.setHidden(true);
    }
  }
 @Override
 protected ASTRewrite getRewrite() throws CoreException {
   ASTRewrite rewrite = ASTRewrite.create(fBodyDecl.getAST());
   if (fBodyDecl instanceof MethodDeclaration) {
     insertAllMissingMethodTags(rewrite, (MethodDeclaration) fBodyDecl);
   } else {
     insertAllMissingTypeTags(rewrite, (TypeDeclaration) fBodyDecl);
   }
   return rewrite;
 }
Beispiel #15
0
 @Override
 public int hashCode() {
   final int prime = 31;
   int result = 1;
   result = prime * result + ((body == null) ? 0 : body.hashCode());
   result = prime * result + ((document == null) ? 0 : document.hashCode());
   result = prime * result + ((enclosingType == null) ? 0 : enclosingType.hashCode());
   result = prime * result + ((unit == null) ? 0 : unit.hashCode());
   return result;
 }
 private IVariableBinding[] removeSelectedDeclarations(IVariableBinding[] bindings) {
   List<IVariableBinding> result = new ArrayList<>(bindings.length);
   Selection selection = getSelection();
   for (int i = 0; i < bindings.length; i++) {
     ASTNode decl =
         ((CompilationUnit) fEnclosingBodyDeclaration.getRoot()).findDeclaringNode(bindings[i]);
     if (!selection.covers(decl)) result.add(bindings[i]);
   }
   return result.toArray(new IVariableBinding[result.size()]);
 }
 /*
  * @see ASTVisitor#visit(EnumDeclaration)
  * @since 3.0
  */
 @Override
 public boolean visit(EnumDeclaration node) {
   if (node.getJavadoc() != null) {
     node.getJavadoc().accept(this);
   }
   printModifiers(node.modifiers());
   this.fBuffer.append("enum "); // $NON-NLS-1$
   node.getName().accept(this);
   this.fBuffer.append(" "); // $NON-NLS-1$
   if (!node.superInterfaceTypes().isEmpty()) {
     this.fBuffer.append("implements "); // $NON-NLS-1$
     for (Iterator<Type> it = node.superInterfaceTypes().iterator(); it.hasNext(); ) {
       Type t = it.next();
       t.accept(this);
       if (it.hasNext()) {
         this.fBuffer.append(", "); // $NON-NLS-1$
       }
     }
     this.fBuffer.append(" "); // $NON-NLS-1$
   }
   this.fBuffer.append("{"); // $NON-NLS-1$
   for (Iterator<EnumConstantDeclaration> it = node.enumConstants().iterator(); it.hasNext(); ) {
     EnumConstantDeclaration d = it.next();
     d.accept(this);
     // enum constant declarations do not include punctuation
     if (it.hasNext()) {
       // enum constant declarations are separated by commas
       this.fBuffer.append(", "); // $NON-NLS-1$
     }
   }
   if (!node.bodyDeclarations().isEmpty()) {
     this.fBuffer.append("; "); // $NON-NLS-1$
     for (Iterator<BodyDeclaration> it = node.bodyDeclarations().iterator(); it.hasNext(); ) {
       BodyDeclaration d = it.next();
       d.accept(this);
       // other body declarations include trailing punctuation
     }
   }
   this.fBuffer.append("}"); // $NON-NLS-1$
   return false;
 }
  @SuppressWarnings("unchecked")
  public void removeUnallowedAssignments() {
    CompilationUnit cu = catroidSource.getSourceAst();
    final List<AbstractTypeDeclaration> types = cu.types();
    assert types.size() > 0;

    for (AbstractTypeDeclaration abstractTypeDecl : types) {
      for (BodyDeclaration bodyDecl :
          new ArrayList<BodyDeclaration>(abstractTypeDecl.bodyDeclarations())) {
        if (bodyDecl.getNodeType() != ASTNode.METHOD_DECLARATION) {
          continue;
        }

        MethodDeclaration methodDeclaration = (MethodDeclaration) bodyDecl;
        Block body = methodDeclaration.getBody();
        if ((body == null) || (body.statements().size() == 0)) {
          continue;
        }
        methodDeclaration.accept(this);
      }
    }
  }
Beispiel #19
0
 public static Expression obtainSingleMemberAnnotationValue(
     BodyDeclaration declaration, Class<?> annotationClass) {
   for (Object mod : declaration.modifiers()) {
     IExtendedModifier modifier = (IExtendedModifier) mod;
     if (modifier.isAnnotation()) {
       Annotation annotation = (Annotation) modifier;
       if (annotation.isSingleMemberAnnotation()
           && identicalAnnotations(annotation, annotationClass)) {
         SingleMemberAnnotation singleMemberAnnot = (SingleMemberAnnotation) annotation;
         return singleMemberAnnot.getValue();
       }
     }
   }
   return null;
 }
  // similar to
  // org.eclipse.jdt.internal.ui.text.correction.ModifierCorrectionSubProcessor.removeOverrideAnnotationProposal(..)
  public void removeDeprecatedAnnotation(
      IDocument document, ICompilationUnit cu, BodyDeclaration decl) {
    Annotation annot = findAnnotation(decl.modifiers());
    if (annot != null) {
      ASTRewrite rewrite = ASTRewrite.create(annot.getAST());
      rewrite.remove(annot, null);

      callASTRewriteCorrectionProposal(getDisplayString(), cu, rewrite, 6, getImage(), document);

      ITextViewer viewer = getViewer(JavaPlugin.getActivePage().getActiveEditor());
      ITrackedNodePosition trackPos = rewrite.track(decl);
      if (trackPos != null && viewer != null) {
        viewer.setSelectedRange(trackPos.getStartPosition(), 0);
      }
    }
  }
 /** {@inheritDoc} */
 public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel model)
     throws CoreException {
   AST ast = cuRewrite.getRoot().getAST();
   ListRewrite listRewrite =
       cuRewrite
           .getASTRewrite()
           .getListRewrite(fBodyDeclaration, fBodyDeclaration.getModifiersProperty());
   Annotation newAnnotation = ast.newMarkerAnnotation();
   newAnnotation.setTypeName(ast.newSimpleName(fAnnotation));
   TextEditGroup group =
       createTextEditGroup(
           Messages.format(
               FixMessages.Java50Fix_AddMissingAnnotation_description,
               BasicElementLabels.getJavaElementName(fAnnotation)),
           cuRewrite);
   listRewrite.insertFirst(newAnnotation, group);
 }
  public RefactoringStatus checkInitialConditions(ImportRewrite rewriter) {
    RefactoringStatus result = getStatus();
    checkExpression(result);
    if (result.hasFatalError()) return result;

    List<ASTNode> validDestinations = new ArrayList<>();
    ASTNode destination = ASTResolving.findParentType(fEnclosingBodyDeclaration.getParent());
    while (destination != null) {
      if (isValidDestination(destination)) {
        validDestinations.add(destination);
      }
      destination = ASTResolving.findParentType(destination.getParent());
    }
    if (validDestinations.size() == 0) {
      result.addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_no_valid_destination_type);
      return result;
    }

    fReturnKind = UNDEFINED;
    fMaxVariableId = LocalVariableIndex.perform(fEnclosingBodyDeclaration);
    if (analyzeSelection(result).hasFatalError()) return result;

    int returns = fReturnKind == NO ? 0 : 1;
    if (fReturnValue != null) {
      fReturnKind = ACCESS_TO_LOCAL;
      returns++;
    }
    if (isExpressionSelected()) {
      fReturnKind = EXPRESSION;
      returns++;
    }

    if (returns > 1) {
      result.addFatalError(
          RefactoringCoreMessages.ExtractMethodAnalyzer_ambiguous_return_value,
          JavaStatusContext.create(fCUnit, getSelection()));
      fReturnKind = MULTIPLE;
      return result;
    }
    initReturnType(rewriter);
    return result;
  }
Beispiel #23
0
 @Override
 public boolean equals(Object obj) {
   if (this == obj) return true;
   if (obj == null) return false;
   if (getClass() != obj.getClass()) return false;
   AbstractJavaSource<?> other = (AbstractJavaSource<?>) obj;
   if (body == null) {
     if (other.body != null) return false;
   } else if (!body.equals(other.body)) return false;
   if (document == null) {
     if (other.document != null) return false;
   } else if (!document.equals(other.document)) return false;
   if (enclosingType == null) {
     if (other.enclosingType != null) return false;
   } else if (!enclosingType.equals(other.enclosingType)) return false;
   if (unit == null) {
     if (other.unit != null) return false;
   } else if (!unit.equals(other.unit)) return false;
   return true;
 }
 private boolean isVoidMethod() {
   ITypeBinding binding = null;
   LambdaExpression enclosingLambdaExpr =
       ASTResolving.findEnclosingLambdaExpression(getFirstSelectedNode());
   if (enclosingLambdaExpr != null) {
     IMethodBinding methodBinding = enclosingLambdaExpr.resolveMethodBinding();
     if (methodBinding != null) {
       binding = methodBinding.getReturnType();
     }
   } else {
     // if we have an initializer
     if (fEnclosingMethodBinding == null) return true;
     binding = fEnclosingMethodBinding.getReturnType();
   }
   if (fEnclosingBodyDeclaration
       .getAST()
       .resolveWellKnownType("void")
       .equals(binding)) // $NON-NLS-1$
   return true;
   return false;
 }
 private void initReturnType(ImportRewrite rewriter) {
   AST ast = fEnclosingBodyDeclaration.getAST();
   fReturnType = null;
   fReturnTypeBinding = null;
   switch (fReturnKind) {
     case ACCESS_TO_LOCAL:
       VariableDeclaration declaration =
           ASTNodes.findVariableDeclaration(fReturnValue, fEnclosingBodyDeclaration);
       fReturnType =
           ASTNodeFactory.newType(
               ast,
               declaration,
               rewriter,
               new ContextSensitiveImportRewriteContext(declaration, rewriter));
       if (declaration.resolveBinding() != null) {
         fReturnTypeBinding = declaration.resolveBinding().getType();
       }
       break;
     case EXPRESSION:
       Expression expression = (Expression) getFirstSelectedNode();
       if (expression.getNodeType() == ASTNode.CLASS_INSTANCE_CREATION) {
         fExpressionBinding = ((ClassInstanceCreation) expression).getType().resolveBinding();
       } else {
         fExpressionBinding = expression.resolveTypeBinding();
       }
       if (fExpressionBinding != null) {
         if (fExpressionBinding.isNullType()) {
           getStatus()
               .addFatalError(
                   RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_null_type,
                   JavaStatusContext.create(fCUnit, expression));
         } else {
           ITypeBinding normalizedBinding =
               Bindings.normalizeForDeclarationUse(fExpressionBinding, ast);
           if (normalizedBinding != null) {
             ImportRewriteContext context =
                 new ContextSensitiveImportRewriteContext(fEnclosingBodyDeclaration, rewriter);
             fReturnType = rewriter.addImport(normalizedBinding, ast, context);
             fReturnTypeBinding = normalizedBinding;
           }
         }
       } else {
         fReturnType = ast.newPrimitiveType(PrimitiveType.VOID);
         fReturnTypeBinding = ast.resolveWellKnownType("void"); // $NON-NLS-1$
         getStatus()
             .addError(
                 RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_determine_return_type,
                 JavaStatusContext.create(fCUnit, expression));
       }
       break;
     case RETURN_STATEMENT_VALUE:
       LambdaExpression enclosingLambdaExpr =
           ASTResolving.findEnclosingLambdaExpression(getFirstSelectedNode());
       if (enclosingLambdaExpr != null) {
         fReturnType = ASTNodeFactory.newReturnType(enclosingLambdaExpr, ast, rewriter, null);
         IMethodBinding methodBinding = enclosingLambdaExpr.resolveMethodBinding();
         fReturnTypeBinding = methodBinding != null ? methodBinding.getReturnType() : null;
       } else if (fEnclosingBodyDeclaration.getNodeType() == ASTNode.METHOD_DECLARATION) {
         fReturnType = ((MethodDeclaration) fEnclosingBodyDeclaration).getReturnType2();
         fReturnTypeBinding = fReturnType != null ? fReturnType.resolveBinding() : null;
       }
       break;
     default:
       fReturnType = ast.newPrimitiveType(PrimitiveType.VOID);
       fReturnTypeBinding = ast.resolveWellKnownType("void"); // $NON-NLS-1$
   }
   if (fReturnType == null) {
     fReturnType = ast.newPrimitiveType(PrimitiveType.VOID);
     fReturnTypeBinding = ast.resolveWellKnownType("void"); // $NON-NLS-1$
   }
 }
  private ASTRewrite doAddLocal(CompilationUnit cu) {
    AST ast = cu.getAST();

    Block body;
    BodyDeclaration decl = ASTResolving.findParentBodyDeclaration(fOriginalNode);
    IBinding targetContext = null;
    if (decl instanceof MethodDeclaration) {
      body = (((MethodDeclaration) decl).getBody());
      targetContext = ((MethodDeclaration) decl).resolveBinding();
    } else if (decl instanceof Initializer) {
      body = (((Initializer) decl).getBody());
      targetContext = Bindings.getBindingOfParentType(decl);
    } else {
      return null;
    }
    ASTRewrite rewrite = ASTRewrite.create(ast);

    ImportRewrite imports = createImportRewrite((CompilationUnit) decl.getRoot());
    ImportRewriteContext importRewriteContext =
        new ContextSensitiveImportRewriteContext(decl, imports);

    SimpleName[] names = getAllReferences(body);
    ASTNode dominant = getDominantNode(names);

    Statement dominantStatement = ASTResolving.findParentStatement(dominant);
    if (ASTNodes.isControlStatementBody(dominantStatement.getLocationInParent())) {
      dominantStatement = (Statement) dominantStatement.getParent();
    }

    SimpleName node = names[0];

    if (isAssigned(dominantStatement, node)) {
      // x = 1; -> int x = 1;
      Assignment assignment = (Assignment) node.getParent();

      // trick to avoid comment removal around the statement: keep the expression statement
      // and replace the assignment with an VariableDeclarationExpression
      VariableDeclarationFragment newDeclFrag = ast.newVariableDeclarationFragment();
      VariableDeclarationExpression newDecl = ast.newVariableDeclarationExpression(newDeclFrag);
      newDecl.setType(evaluateVariableType(ast, imports, importRewriteContext, targetContext));

      Expression placeholder = (Expression) rewrite.createCopyTarget(assignment.getRightHandSide());
      newDeclFrag.setInitializer(placeholder);
      newDeclFrag.setName(ast.newSimpleName(node.getIdentifier()));
      rewrite.replace(assignment, newDecl, null);

      addLinkedPosition(rewrite.track(newDecl.getType()), false, KEY_TYPE);
      addLinkedPosition(rewrite.track(newDeclFrag.getName()), true, KEY_NAME);

      setEndPosition(rewrite.track(assignment.getParent()));

      return rewrite;
    } else if ((dominant != dominantStatement) && isForStatementInit(dominantStatement, node)) {
      //	for (x = 1;;) ->for (int x = 1;;)

      Assignment assignment = (Assignment) node.getParent();

      VariableDeclarationFragment frag = ast.newVariableDeclarationFragment();
      VariableDeclarationExpression expression = ast.newVariableDeclarationExpression(frag);
      frag.setName(ast.newSimpleName(node.getIdentifier()));
      Expression placeholder = (Expression) rewrite.createCopyTarget(assignment.getRightHandSide());
      frag.setInitializer(placeholder);
      expression.setType(evaluateVariableType(ast, imports, importRewriteContext, targetContext));

      rewrite.replace(assignment, expression, null);

      addLinkedPosition(rewrite.track(expression.getType()), false, KEY_TYPE);
      addLinkedPosition(rewrite.track(frag.getName()), true, KEY_NAME);

      setEndPosition(rewrite.track(expression));

      return rewrite;

    } else if ((dominant != dominantStatement)
        && isEnhancedForStatementVariable(dominantStatement, node)) {
      //	for (x: collectionOfT) -> for (T x: collectionOfT)

      EnhancedForStatement enhancedForStatement = (EnhancedForStatement) dominantStatement;
      SingleVariableDeclaration parameter = enhancedForStatement.getParameter();
      Expression expression = enhancedForStatement.getExpression();

      SimpleName newName = (SimpleName) rewrite.createMoveTarget(node);
      rewrite.set(parameter, SingleVariableDeclaration.NAME_PROPERTY, newName, null);

      ITypeBinding elementBinding = null;
      ITypeBinding typeBinding = expression.resolveTypeBinding();
      if (typeBinding != null) {
        if (typeBinding.isArray()) {
          elementBinding = typeBinding.getElementType();
        } else {
          ITypeBinding iterable =
              Bindings.findTypeInHierarchy(typeBinding, "java.lang.Iterable"); // $NON-NLS-1$
          if (iterable != null) {
            ITypeBinding[] typeArguments = iterable.getTypeArguments();
            if (typeArguments.length == 1) {
              elementBinding = typeArguments[0];
              elementBinding = Bindings.normalizeForDeclarationUse(elementBinding, ast);
            }
          }
        }
      }
      Type type;
      if (elementBinding != null) {
        type = imports.addImport(elementBinding, ast, importRewriteContext);
      } else {
        type = ast.newSimpleType(ast.newSimpleName("Object")); // $NON-NLS-1$
      }

      rewrite.set(parameter, SingleVariableDeclaration.TYPE_PROPERTY, type, null);

      addLinkedPosition(rewrite.track(type), false, KEY_TYPE);
      addLinkedPosition(rewrite.track(newName), true, KEY_NAME);

      setEndPosition(rewrite.track(expression));

      return rewrite;
    }

    //	foo(x) -> int x; foo(x)

    VariableDeclarationFragment newDeclFrag = ast.newVariableDeclarationFragment();
    VariableDeclarationStatement newDecl = ast.newVariableDeclarationStatement(newDeclFrag);

    newDeclFrag.setName(ast.newSimpleName(node.getIdentifier()));
    newDecl.setType(evaluateVariableType(ast, imports, importRewriteContext, targetContext));
    //		newDeclFrag.setInitializer(ASTNodeFactory.newDefaultExpression(ast, newDecl.getType(), 0));

    addLinkedPosition(rewrite.track(newDecl.getType()), false, KEY_TYPE);
    addLinkedPosition(rewrite.track(node), true, KEY_NAME);
    addLinkedPosition(rewrite.track(newDeclFrag.getName()), false, KEY_NAME);

    Statement statement = dominantStatement;
    List<? extends ASTNode> list = ASTNodes.getContainingList(statement);
    while (list == null
        && statement.getParent() instanceof Statement) { // parent must be if, for or while
      statement = (Statement) statement.getParent();
      list = ASTNodes.getContainingList(statement);
    }
    if (list != null) {
      ASTNode parent = statement.getParent();
      StructuralPropertyDescriptor childProperty = statement.getLocationInParent();
      if (childProperty.isChildListProperty()) {
        rewrite
            .getListRewrite(parent, (ChildListPropertyDescriptor) childProperty)
            .insertBefore(newDecl, statement, null);
        return rewrite;
      } else {
        return null;
      }
    }
    return rewrite;
  }
    private void insertMissingJavadocTag(
        ASTRewrite rewrite, ASTNode missingNode, BodyDeclaration bodyDecl) {
      AST ast = bodyDecl.getAST();
      Javadoc javadoc = bodyDecl.getJavadoc();
      if (javadoc == null) {
        javadoc = ast.newJavadoc();
        rewrite.set(bodyDecl, bodyDecl.getJavadocProperty(), javadoc, null);
      }

      ListRewrite tagsRewriter = rewrite.getListRewrite(javadoc, Javadoc.TAGS_PROPERTY);

      StructuralPropertyDescriptor location = missingNode.getLocationInParent();
      TagElement newTag;
      if (location == SingleVariableDeclaration.NAME_PROPERTY) {
        // normal parameter
        SingleVariableDeclaration decl = (SingleVariableDeclaration) missingNode.getParent();

        String name = ((SimpleName) missingNode).getIdentifier();
        newTag = ast.newTagElement();
        newTag.setTagName(TagElement.TAG_PARAM);
        newTag.fragments().add(ast.newSimpleName(name));

        MethodDeclaration methodDeclaration = (MethodDeclaration) bodyDecl;
        List<SingleVariableDeclaration> params = methodDeclaration.parameters();

        Set<String> sameKindLeadingNames = getPreviousParamNames(params, decl);

        List<TypeParameter> typeParams = methodDeclaration.typeParameters();
        for (int i = 0; i < typeParams.size(); i++) {
          String curr = '<' + typeParams.get(i).getName().getIdentifier() + '>';
          sameKindLeadingNames.add(curr);
        }
        insertTag(tagsRewriter, newTag, sameKindLeadingNames);
      } else if (location == TypeParameter.NAME_PROPERTY) {
        // type parameter
        TypeParameter typeParam = (TypeParameter) missingNode.getParent();

        String name = '<' + ((SimpleName) missingNode).getIdentifier() + '>';
        newTag = ast.newTagElement();
        newTag.setTagName(TagElement.TAG_PARAM);
        TextElement text = ast.newTextElement();
        text.setText(name);
        newTag.fragments().add(text);
        List<TypeParameter> params;
        if (bodyDecl instanceof TypeDeclaration) {
          params = ((TypeDeclaration) bodyDecl).typeParameters();
        } else {
          params = ((MethodDeclaration) bodyDecl).typeParameters();
        }
        insertTag(tagsRewriter, newTag, getPreviousTypeParamNames(params, typeParam));
      } else if (location == MethodDeclaration.RETURN_TYPE2_PROPERTY) {
        newTag = ast.newTagElement();
        newTag.setTagName(TagElement.TAG_RETURN);
        insertTag(tagsRewriter, newTag, null);
      } else if (location == MethodDeclaration.THROWN_EXCEPTION_TYPES_PROPERTY) {
        newTag = ast.newTagElement();
        newTag.setTagName(TagElement.TAG_THROWS);
        TextElement excNode = ast.newTextElement();
        excNode.setText(ASTNodes.getQualifiedTypeName((Type) missingNode));
        newTag.fragments().add(excNode);
        List<Type> exceptions = ((MethodDeclaration) bodyDecl).thrownExceptionTypes();
        insertTag(tagsRewriter, newTag, getPreviousExceptionNames(exceptions, missingNode));
      } else {
        Assert.isTrue(
            false, "AddMissingJavadocTagProposal: unexpected node location"); // $NON-NLS-1$
        return;
      }

      TextElement textElement = ast.newTextElement();
      textElement.setText(""); // $NON-NLS-1$
      newTag.fragments().add(textElement);

      addLinkedPosition(rewrite.track(textElement), false, "comment_start"); // $NON-NLS-1$

      if (bodyDecl.getJavadoc() == null) {
        // otherwise the linked position spans over a line delimiter
        newTag.fragments().add(ast.newTextElement());
      }
    }
  public static void getMissingJavadocCommentProposals(
      IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals)
      throws CoreException {
    ASTNode node = problem.getCoveringNode(context.getASTRoot());
    if (node == null) {
      return;
    }
    BodyDeclaration declaration = ASTResolving.findParentBodyDeclaration(node);
    if (declaration == null) {
      return;
    }
    ICompilationUnit cu = context.getCompilationUnit();
    ITypeBinding binding = Bindings.getBindingOfParentType(declaration);
    if (binding == null) {
      return;
    }

    if (declaration instanceof MethodDeclaration) {
      MethodDeclaration methodDecl = (MethodDeclaration) declaration;
      IMethodBinding methodBinding = methodDecl.resolveBinding();
      IMethodBinding overridden = null;
      if (methodBinding != null) {
        overridden = Bindings.findOverriddenMethod(methodBinding, true);
      }

      String string =
          CodeGeneration.getMethodComment(
              cu, binding.getName(), methodDecl, overridden, String.valueOf('\n'));
      if (string != null) {
        String label = CorrectionMessages.JavadocTagsSubProcessor_addjavadoc_method_description;
        proposals.add(
            new AddJavadocCommentProposal(
                label,
                cu,
                IProposalRelevance.ADD_JAVADOC_METHOD,
                declaration.getStartPosition(),
                string));
      }
    } else if (declaration instanceof AbstractTypeDeclaration) {
      String typeQualifiedName = Bindings.getTypeQualifiedName(binding);
      String[] typeParamNames;
      if (declaration instanceof TypeDeclaration) {
        List<TypeParameter> typeParams = ((TypeDeclaration) declaration).typeParameters();
        typeParamNames = new String[typeParams.size()];
        for (int i = 0; i < typeParamNames.length; i++) {
          typeParamNames[i] = (typeParams.get(i)).getName().getIdentifier();
        }
      } else {
        typeParamNames = new String[0];
      }
      String string =
          CodeGeneration.getTypeComment(
              cu, typeQualifiedName, typeParamNames, String.valueOf('\n'));
      if (string != null) {
        String label = CorrectionMessages.JavadocTagsSubProcessor_addjavadoc_type_description;
        proposals.add(
            new AddJavadocCommentProposal(
                label,
                cu,
                IProposalRelevance.ADD_JAVADOC_TYPE,
                declaration.getStartPosition(),
                string));
      }
    } else if (declaration instanceof FieldDeclaration) {
      String comment = "/**\n *\n */\n"; // $NON-NLS-1$
      List<VariableDeclarationFragment> fragments = ((FieldDeclaration) declaration).fragments();
      if (fragments != null && fragments.size() > 0) {
        VariableDeclaration decl = fragments.get(0);
        String fieldName = decl.getName().getIdentifier();
        String typeName = binding.getName();
        comment = CodeGeneration.getFieldComment(cu, typeName, fieldName, String.valueOf('\n'));
      }
      if (comment != null) {
        String label = CorrectionMessages.JavadocTagsSubProcessor_addjavadoc_field_description;
        proposals.add(
            new AddJavadocCommentProposal(
                label,
                cu,
                IProposalRelevance.ADD_JAVADOC_FIELD,
                declaration.getStartPosition(),
                comment));
      }
    } else if (declaration instanceof EnumConstantDeclaration) {
      EnumConstantDeclaration enumDecl = (EnumConstantDeclaration) declaration;
      String id = enumDecl.getName().getIdentifier();
      String comment =
          CodeGeneration.getFieldComment(cu, binding.getName(), id, String.valueOf('\n'));
      String label = CorrectionMessages.JavadocTagsSubProcessor_addjavadoc_enumconst_description;
      proposals.add(
          new AddJavadocCommentProposal(
              label,
              cu,
              IProposalRelevance.ADD_JAVADOC_ENUM,
              declaration.getStartPosition(),
              comment));
    }
  }
 @Override
 public void endVisit(CompilationUnit node) {
   RefactoringStatus status = getStatus();
   superCall:
   {
     if (status.hasFatalError()) break superCall;
     if (!hasSelectedNodes()) {
       ASTNode coveringNode = getLastCoveringNode();
       if (coveringNode instanceof Block
           && coveringNode.getParent() instanceof MethodDeclaration) {
         MethodDeclaration methodDecl = (MethodDeclaration) coveringNode.getParent();
         Message[] messages = ASTNodes.getMessages(methodDecl, ASTNodes.NODE_ONLY);
         if (messages.length > 0) {
           status.addFatalError(
               Messages.format(
                   RefactoringCoreMessages.ExtractMethodAnalyzer_compile_errors,
                   BasicElementLabels.getJavaElementName(methodDecl.getName().getIdentifier())),
               JavaStatusContext.create(fCUnit, methodDecl));
           break superCall;
         }
       }
       status.addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_invalid_selection);
       break superCall;
     }
     fEnclosingBodyDeclaration =
         (BodyDeclaration) ASTNodes.getParent(getFirstSelectedNode(), BodyDeclaration.class);
     if (fEnclosingBodyDeclaration == null
         || (fEnclosingBodyDeclaration.getNodeType() != ASTNode.METHOD_DECLARATION
             && fEnclosingBodyDeclaration.getNodeType() != ASTNode.FIELD_DECLARATION
             && fEnclosingBodyDeclaration.getNodeType() != ASTNode.INITIALIZER)) {
       status.addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_invalid_selection);
       break superCall;
     } else if (ASTNodes.getEnclosingType(fEnclosingBodyDeclaration) == null) {
       status.addFatalError(
           RefactoringCoreMessages.ExtractMethodAnalyzer_compile_errors_no_parent_binding);
       break superCall;
     } else if (fEnclosingBodyDeclaration.getNodeType() == ASTNode.METHOD_DECLARATION) {
       fEnclosingMethodBinding = ((MethodDeclaration) fEnclosingBodyDeclaration).resolveBinding();
     }
     if (!isSingleExpressionOrStatementSet()) {
       status.addFatalError(
           RefactoringCoreMessages.ExtractMethodAnalyzer_single_expression_or_set);
       break superCall;
     }
     if (isExpressionSelected()) {
       ASTNode expression = getFirstSelectedNode();
       if (expression instanceof Name) {
         Name name = (Name) expression;
         if (name.resolveBinding() instanceof ITypeBinding) {
           status.addFatalError(
               RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_type_reference);
           break superCall;
         }
         if (name.resolveBinding() instanceof IMethodBinding) {
           status.addFatalError(
               RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_method_name_reference);
           break superCall;
         }
         if (name.resolveBinding() instanceof IVariableBinding) {
           StructuralPropertyDescriptor locationInParent = name.getLocationInParent();
           if (locationInParent == QualifiedName.NAME_PROPERTY
               || (locationInParent == FieldAccess.NAME_PROPERTY
                   && !(((FieldAccess) name.getParent()).getExpression()
                       instanceof ThisExpression))) {
             status.addFatalError(
                 RefactoringCoreMessages
                     .ExtractMethodAnalyzer_cannot_extract_part_of_qualified_name);
             break superCall;
           }
         }
         if (name.isSimpleName() && ((SimpleName) name).isDeclaration()) {
           status.addFatalError(
               RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_name_in_declaration);
           break superCall;
         }
       }
       fForceStatic =
           ASTNodes.getParent(expression, ASTNode.SUPER_CONSTRUCTOR_INVOCATION) != null
               || ASTNodes.getParent(expression, ASTNode.CONSTRUCTOR_INVOCATION) != null;
     }
     status.merge(LocalTypeAnalyzer.perform(fEnclosingBodyDeclaration, getSelection()));
     computeLastStatementSelected();
   }
   super.endVisit(node);
 }
 /*
  * @see ASTVisitor#visit(TypeDeclaration)
  */
 public boolean visit(TypeDeclaration node) {
   if (node.getJavadoc() != null) {
     node.getJavadoc().accept(this);
   }
   if (node.getAST().apiLevel() >= AST.JLS3) {
     printModifiers(node.modifiers());
   }
   this.fBuffer.append(node.isInterface() ? "interface " : "class "); // $NON-NLS-2$//$NON-NLS-1$
   node.getName().accept(this);
   if (node.getAST().apiLevel() >= AST.JLS3) {
     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$
     }
   }
   this.fBuffer.append(" "); // $NON-NLS-1$
   if (node.getAST().apiLevel() >= AST.JLS3) {
     if (node.getSuperclassType() != null) {
       this.fBuffer.append("extends "); // $NON-NLS-1$
       node.getSuperclassType().accept(this);
       this.fBuffer.append(" "); // $NON-NLS-1$
     }
     if (!node.superInterfaceTypes().isEmpty()) {
       this.fBuffer.append(
           node.isInterface() ? "extends " : "implements "); // $NON-NLS-2$//$NON-NLS-1$
       for (Iterator it = node.superInterfaceTypes().iterator(); it.hasNext(); ) {
         Type t = (Type) it.next();
         t.accept(this);
         if (it.hasNext()) {
           this.fBuffer.append(", "); // $NON-NLS-1$
         }
       }
       this.fBuffer.append(" "); // $NON-NLS-1$
     }
   }
   this.fBuffer.append("{"); // $NON-NLS-1$
   BodyDeclaration prev = null;
   for (Iterator it = node.bodyDeclarations().iterator(); it.hasNext(); ) {
     BodyDeclaration d = (BodyDeclaration) it.next();
     if (prev instanceof EnumConstantDeclaration) {
       // enum constant declarations do not include punctuation
       if (d instanceof EnumConstantDeclaration) {
         // enum constant declarations are separated by commas
         this.fBuffer.append(", "); // $NON-NLS-1$
       } else {
         // semicolon separates last enum constant declaration from
         // first class body declarations
         this.fBuffer.append("; "); // $NON-NLS-1$
       }
     }
     d.accept(this);
     prev = d;
   }
   this.fBuffer.append("}"); // $NON-NLS-1$
   return false;
 }