/*
   * Evaluates possible return expressions. The favourite expression is returned.
   */
  private Expression evaluateReturnExpressions(
      AST ast, ITypeBinding returnBinding, int returnOffset) {
    CompilationUnit root = (CompilationUnit) fMethodDecl.getRoot();

    Expression result = null;
    if (returnBinding != null) {
      ScopeAnalyzer analyzer = new ScopeAnalyzer(root);
      IBinding[] bindings =
          analyzer.getDeclarationsInScope(
              returnOffset, ScopeAnalyzer.VARIABLES | ScopeAnalyzer.CHECK_VISIBILITY);
      for (int i = 0; i < bindings.length; i++) {
        IVariableBinding curr = (IVariableBinding) bindings[i];
        ITypeBinding type = curr.getType();
        if (type != null && type.isAssignmentCompatible(returnBinding) && testModifier(curr)) {
          if (result == null) {
            result = ast.newSimpleName(curr.getName());
          }
          addLinkedPositionProposal(RETURN_EXPRESSION_KEY, curr.getName(), null);
        }
      }
    }
    Expression defaultExpression =
        ASTNodeFactory.newDefaultExpression(
            ast, fMethodDecl.getReturnType2(), fMethodDecl.getExtraDimensions());
    addLinkedPositionProposal(RETURN_EXPRESSION_KEY, ASTNodes.asString(defaultExpression), null);
    if (result == null) {
      return defaultExpression;
    }
    return result;
  }
  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 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 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);
  }
 @Override
 public boolean visit(MethodDeclaration node) {
   if (node.getBody() == null) {
     return VISIT_SUBTREE;
   }
   List<Statement> bodyStmts = statements(node.getBody());
   if (bodyStmts.size() == 1) {
     SuperMethodInvocation bodyMi = asExpression(bodyStmts.get(0), SuperMethodInvocation.class);
     if (bodyMi != null) {
       IMethodBinding bodyMethodBinding = bodyMi.resolveMethodBinding();
       IMethodBinding declMethodBinding = node.resolveBinding();
       if (declMethodBinding != null
           && bodyMethodBinding != null
           && declMethodBinding.overrides(bodyMethodBinding)
           && !hasSignificantAnnotations(declMethodBinding)
           && haveSameModifiers(bodyMethodBinding, declMethodBinding)) {
         if (Modifier.isProtected(declMethodBinding.getModifiers())
             && !declaredInSamePackage(bodyMethodBinding, declMethodBinding)) {
           // protected also means package visibility, so check if it is required
           if (!isMethodUsedInItsPackage(declMethodBinding, node)) {
             this.ctx.getRefactorings().remove(node);
             return DO_NOT_VISIT_SUBTREE;
           }
         } else {
           this.ctx.getRefactorings().remove(node);
           return DO_NOT_VISIT_SUBTREE;
         }
       }
     }
   }
   return VISIT_SUBTREE;
 }
示例#6
0
  private static void gatherDuplicateFixes(
      HashMap<String, ArrayList<IProblem>> duplicates,
      HashMap<String, ArrayList<FixTypes>> ret,
      SourceKey src) {
    for (Map.Entry<String, ArrayList<IProblem>> ent : duplicates.entrySet()) {
      IProblem p = ent.getValue().get(0);
      TypeDeclaration cls = null;
      for (TypeDeclaration t : src.classes) {
        if (t.getStartPosition() <= p.getSourceStart()
            && (t.getStartPosition() + t.getLength()) >= p.getSourceEnd()) {
          cls = t;
          break;
        }
      }
      if (cls == null) {
        System.out.println("WTF! COULD NOT FIND DUPLICATE CLASS");
        System.exit(1);
      }

      for (MethodDeclaration mtd : cls.getMethods()) {
        if (mtd.getName().toString().equals(ent.getKey())) {
          // Resolving will fail on duplicate methods.. HOPE that the real
          // one is the first one, only real case is the synthetic method
          // in Mooshroom, which this works
          if (mtd.resolveBinding() == null) {
            String clsName = cls.resolveBinding().getQualifiedName().replace('.', '/');
            if (!ret.containsKey(clsName)) ret.put(clsName, new ArrayList<FixTypes>());
            ret.get(clsName).add(new FixTypes.RemoveMethod(mtd));
          }
        }
      }
    }
  }
    private boolean callsWritingConstructor(
        MethodDeclaration methodDeclaration,
        HashSet writingConstructorBindings,
        Set visitedMethodDeclarations) {
      Block body = methodDeclaration.getBody();
      if (body == null) return false;

      List statements = body.statements();
      if (statements.size() == 0) return false;

      Statement statement = (Statement) statements.get(0);
      if (!(statement instanceof ConstructorInvocation)) return false;

      ConstructorInvocation invocation = (ConstructorInvocation) statement;
      IMethodBinding constructorBinding = invocation.resolveConstructorBinding();
      if (constructorBinding == null) return false;

      if (writingConstructorBindings.contains(constructorBinding)) {
        return true;
      } else {
        ASTNode declaration =
            ASTNodes.findDeclaration(constructorBinding, methodDeclaration.getParent());
        if (!(declaration instanceof MethodDeclaration)) return false;

        if (visitedMethodDeclarations.contains(declaration)) {
          return false;
        }
        visitedMethodDeclarations.add(methodDeclaration);
        return callsWritingConstructor(
            (MethodDeclaration) declaration, writingConstructorBindings, visitedMethodDeclarations);
      }
    }
示例#8
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);
          }
        }
      }
    }
  }
  /** Adds the onReceive method to the broadcast receiver class */
  @SuppressWarnings("unchecked")
  private void addOnReceiveMethod() {
    MethodDeclaration onReceiveMethod = ast.newMethodDeclaration();
    onReceiveMethod.modifiers().add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD));
    onReceiveMethod.setReturnType2(ast.newPrimitiveType(PrimitiveType.VOID));
    onReceiveMethod.setName(ast.newSimpleName(ONRECEIVE_METHOD_NAME));
    addMethodParameter(
        onReceiveMethod,
        getName(CONTEXT_CLASS).toLowerCase(),
        ast.newSimpleType(ast.newSimpleName(getName(CONTEXT_CLASS))));
    addMethodParameter(
        onReceiveMethod,
        getName(INTENT_CLASS).toLowerCase(),
        ast.newSimpleType(ast.newSimpleName(getName(INTENT_CLASS))));
    addEmptyBlock(onReceiveMethod);
    classDecl.bodyDeclarations().add(onReceiveMethod);

    // Adds JavaDoc to the method
    addComment(
        onReceiveMethod, CodeUtilsNLS.MODEL_BroadcastReceiverClass_onReceiveMethodDescription);
    addMethodReference(
        onReceiveMethod,
        BROADCAST_RECEIVER_SUPERCLASS,
        ONRECEIVE_METHOD_NAME,
        new Type[] {
          ast.newSimpleType(ast.newSimpleName(getName(CONTEXT_CLASS))),
          ast.newSimpleType(ast.newSimpleName(getName(INTENT_CLASS)))
        });
  }
 private void printStaticInterface(
     AbstractTypeDeclaration node,
     String typeName,
     List<FieldDeclaration> fields,
     List<MethodDeclaration> methods) {
   List<IVariableBinding> staticFields =
       getStaticFieldsNeedingAccessors(fields, /* isInterface */ true);
   if (staticFields.isEmpty()) {
     if (!Options.stripReflection()) {
       printf("\n@interface %s : NSObject\n@end\n", typeName);
     } else {
       return;
     }
   }
   printf("\n@implementation %s\n\n", typeName);
   printStaticVars(fields, /* isInterface */ true);
   printStaticFieldAccessors(staticFields, methods);
   for (MethodDeclaration method : methods) {
     if (method.getBody() != null) {
       printNormalMethod(method);
     }
   }
   if (!Options.stripReflection()) {
     printMetadata(node);
   }
   println("@end");
 }
  /**
   * Visits the method invocation to get number of assertion in this test method.
   *
   * @param md Visit method declaration in source code.
   * @return False because we don't look into child nodes.
   */
  public boolean visit(MethodDeclaration md) {
    if (md.getName() != null) {
      this.numOfMethods++;

      if (md.getName().getIdentifier().startsWith("test")) {
        this.numOfTestMethods++;
      } else if (isJUnit4Test(md)) {
        this.numOfTestMethods++;
      }

      // Check test method body to look for assertion statement.
      Block methodBody = md.getBody();
      if (methodBody != null && methodBody.statements() != null) {
        List stmts = methodBody.statements();
        this.numOfStatements += stmts.size();
        // Looks through all statements in this method body.
        for (Iterator i = stmts.iterator(); i.hasNext(); ) {
          Statement stmt = (Statement) i.next(); // NOPMD
          // MethodInvocation is one kind of expression statement.
          if (stmt instanceof ExpressionStatement) {
            ExpressionStatement estmt = (ExpressionStatement) stmt;
            checkAssertions(estmt);
          }
        }
      }
    }

    // No need to visit child nodes anymore.
    return false;
  }
  private static boolean canAddFinal(IBinding binding, ASTNode declNode) {
    if (!(binding instanceof IVariableBinding)) return false;

    IVariableBinding varbinding = (IVariableBinding) binding;
    int modifiers = varbinding.getModifiers();
    if (Modifier.isFinal(modifiers)
        || Modifier.isVolatile(modifiers)
        || Modifier.isTransient(modifiers)) return false;

    ASTNode parent = ASTNodes.getParent(declNode, VariableDeclarationExpression.class);
    if (parent != null && ((VariableDeclarationExpression) parent).fragments().size() > 1)
      return false;

    if (varbinding.isField() && !Modifier.isPrivate(modifiers)) return false;

    if (varbinding.isParameter()) {
      ASTNode varDecl = declNode.getParent();
      if (varDecl instanceof MethodDeclaration) {
        MethodDeclaration declaration = (MethodDeclaration) varDecl;
        if (declaration.getBody() == null) return false;
      }
    }

    return true;
  }
 public boolean visit(MethodDeclaration node) {
   if (null != m_methodFilter) {
     return node.getName().getIdentifier().equals(m_methodFilter.getElementName())
         && node.parameters().size() == m_methodFilter.getNumberOfParameters();
   } else {
     return true;
   }
 }
示例#14
0
 public static MethodDeclaration findMethodDeclarationByName(TypeDeclaration owner, String name) {
   for (MethodDeclaration methodDeclaration : owner.getMethods()) {
     if (methodDeclaration.getName().getFullyQualifiedName().equals(name)) {
       return methodDeclaration;
     }
   }
   return null;
 }
示例#15
0
 /* (non-Javadoc)
  * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.Javadoc)
  */
 public boolean visit(Javadoc node) {
   List tags = node.tags();
   ASTNode parent = node.getParent();
   if (parent != null) {
     switch (parent.getNodeType()) {
       case ASTNode.TYPE_DECLARATION:
         {
           TypeDeclaration type = (TypeDeclaration) parent;
           if (type.isInterface()) {
             processTags(
                 fType,
                 pruneTags(tags, type),
                 IApiJavadocTag.TYPE_INTERFACE,
                 IApiJavadocTag.MEMBER_NONE);
           } else {
             processTags(
                 fType,
                 pruneTags(tags, type),
                 IApiJavadocTag.TYPE_CLASS,
                 IApiJavadocTag.MEMBER_NONE);
           }
           break;
         }
       case ASTNode.METHOD_DECLARATION:
         {
           MethodDeclaration method = (MethodDeclaration) parent;
           String signature = Signatures.getMethodSignatureFromNode(method);
           if (signature != null) {
             String methodname = method.getName().getFullyQualifiedName();
             int member = IApiJavadocTag.MEMBER_METHOD;
             if (method.isConstructor()) {
               member = IApiJavadocTag.MEMBER_CONSTRUCTOR;
               methodname = "<init>"; // $NON-NLS-1$
             }
             IMethodDescriptor descriptor = fType.getMethod(methodname, signature);
             processTags(descriptor, pruneTags(tags, method), getEnclosingType(method), member);
           }
           break;
         }
       case ASTNode.FIELD_DECLARATION:
         {
           FieldDeclaration field = (FieldDeclaration) parent;
           List fields = field.fragments();
           VariableDeclarationFragment fragment = null;
           for (Iterator iter = fields.iterator(); iter.hasNext(); ) {
             fragment = (VariableDeclarationFragment) iter.next();
             processTags(
                 fType.getField(fragment.getName().getFullyQualifiedName()),
                 pruneTags(tags, field),
                 getEnclosingType(field),
                 IApiJavadocTag.MEMBER_FIELD);
           }
           break;
         }
     }
   }
   return false;
 }
 private String extractNativeMethodBody(MethodDeclaration m) {
   assert (m.getModifiers() & Modifier.NATIVE) > 0;
   String nativeCode = extractNativeCode(m.getStartPosition(), m.getLength());
   if (nativeCode == null) {
     ErrorUtil.warning(m, "no native code found");
     return "";
   }
   return '{' + nativeCode + '}';
 }
 public boolean visit(MethodDeclaration node) {
   String signature = getSignature(node);
   push(
       node.isConstructor() ? JavaNode.CONSTRUCTOR : JavaNode.METHOD,
       signature,
       node.getStartPosition(),
       node.getLength());
   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;
  }
  /*
   * (non-Javadoc)
   *
   * @see org.eclipse.andmore.android.model.java.JavaClass#addComments()
   */
  @Override
  protected void addComments() throws AndroidException {
    ASTNode todoComment;

    ASTParser parser = ASTParser.newParser(AST.JLS3);
    parser.setSource(document.get().toCharArray());

    compUnit = (CompilationUnit) parser.createAST(null);
    ast = compUnit.getAST();
    rewrite = ASTRewrite.create(ast);

    todoComment =
        rewrite.createStringPlaceholder(
            CodeUtilsNLS.MODEL_Common_ToDoPutYourCodeHere, ASTNode.EMPTY_STATEMENT);

    TypeDeclaration receiverClass = (TypeDeclaration) compUnit.types().get(0);
    MethodDeclaration method;
    Block block;

    // Adds the Override annotation and ToDo comment to all overridden
    // methods
    for (int i = 0; i < receiverClass.bodyDeclarations().size(); i++) {
      method = (MethodDeclaration) receiverClass.bodyDeclarations().get(i);

      // Adds the Override annotation
      rewrite
          .getListRewrite(method, method.getModifiersProperty())
          .insertFirst(OVERRIDE_ANNOTATION, null);

      // Adds the ToDo comment
      block = method.getBody();
      rewrite.getListRewrite(block, Block.STATEMENTS_PROPERTY).insertFirst(todoComment, null);
    }

    try {
      // Writes the modifications
      TextEdit modifications = rewrite.rewriteAST(document, null);
      modifications.apply(document);
    } catch (IllegalArgumentException e) {
      String errMsg = NLS.bind(CodeUtilsNLS.EXC_JavaClass_ErrorApplyingCommentsToCode, className);

      AndmoreLogger.error(BroadcastReceiverClass.class, errMsg, e);
      throw new AndroidException(errMsg);
    } catch (MalformedTreeException e) {
      String errMsg = NLS.bind(CodeUtilsNLS.EXC_JavaClass_ErrorApplyingCommentsToCode, className);

      AndmoreLogger.error(BroadcastReceiverClass.class, errMsg, e);
      throw new AndroidException(errMsg);
    } catch (BadLocationException e) {
      String errMsg = NLS.bind(CodeUtilsNLS.EXC_JavaClass_ErrorApplyingCommentsToCode, className);

      AndmoreLogger.error(BroadcastReceiverClass.class, errMsg, e);
      throw new AndroidException(errMsg);
    }
  }
 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;
 }
示例#21
0
 @Override
 public boolean visit(MethodDeclaration node) {
   methods.add(
       new OutlineMethod(
           node.getName().toString(),
           node.getReturnType2(),
           node.isConstructor(),
           node.getModifiers(),
           node.parameters(),
           clazz));
   return super.visit(node);
 }
 @Override
 public boolean visit(MethodDeclaration node) {
   if (nestLevel != 1) return false;
   if (targetMethod.getElementName().equals(node.getName().getFullyQualifiedName())) {
     IMethod method = (IMethod) node.resolveBinding().getJavaElement();
     if (targetMethod.isSimilar(method)) {
       mapperMethod = new MapperMethod();
       mapperMethod.setMethodDeclaration(node);
       return true;
     }
   }
   return false;
 }
示例#23
0
  private Delta deduplicate(CompilationUnit root, ASTRewrite rewrite, Cause cause) {

    final List<ASTNode> nodes = cause.getAffectedNodes();
    final int size = nodes.size();
    final int cloneNumber = size == 0 ? size : size - 1; // minus the original declaration

    if (cloneNumber == 0) {
      throw new RuntimeException("calling deduplicate() when there are no detected clones");
    } else if (cloneNumber >= 1) {
      // NOTE: THIS WORKS ONLY AT METHOD LEVEL, other forms of duplication will
      // will be ignored.

      // The strategy this code follows to perform deduplication is the following:
      // per duplicated method declaration, find all of its invocations. Then
      // rename each found invocation using the name of the original method declaration.
      // After that, remove the duplicated method declaration.
      if (AstUtil.isOfType(MethodDeclaration.class, nodes.get(0))) {
        final MethodDeclaration original = AstUtil.exactCast(MethodDeclaration.class, nodes.get(0));
        final Iterable<ASTNode> rest = Iterables.skip(nodes, 1);
        for (ASTNode eachClone : rest) {
          final MethodDeclaration duplicate = AstUtil.exactCast(MethodDeclaration.class, eachClone);
          final MethodDeclaration copied =
              AstUtil.copySubtree(MethodDeclaration.class, root.getAST(), duplicate);
          final boolean sameReturn = sameReturnType(original, copied);

          if (!sameReturn) { // all or none. We don't do partial deduplication
            throw new RuntimeException(
                "automatic deduplication cannot be done on methods "
                    + "with different return types; please consider "
                    + "manual deduplication.");
          }

          final MethodInvocationVisitor invokesOfDuplication =
              new MethodInvocationVisitor(copied.getName());
          root.accept(invokesOfDuplication);
          final Set<MethodInvocation> invokes = invokesOfDuplication.getMethodInvocations();

          for (MethodInvocation each : invokes) {
            final MethodInvocation copiedInvoke =
                AstUtil.copySubtree(MethodInvocation.class, root.getAST(), each);
            copiedInvoke.setName(root.getAST().newSimpleName(original.getName().getIdentifier()));
            rewrite.replace(each, copiedInvoke, null);
          }

          rewrite.remove(duplicate, null);
        }
      }
    }

    return createDelta(root, rewrite);
  }
  /**
   * Constructor.
   *
   * @param methodDeclarationNode the method declaration of this manager handles.
   */
  public StubMethodBindingManager(MethodDeclaration methodDeclarationNode) {
    this.methodDeclarationNode = methodDeclarationNode;

    this.stubMethodLen = methodDeclarationNode.getLength();
    this.stubMethodStartPosition = methodDeclarationNode.getStartPosition();

    ASTNode astNode = methodDeclarationNode.getRoot();

    System.out.println(
        "Stub Method, stubMethodLen = "
            + stubMethodLen
            + ", StubMethodStartPosition = "
            + stubMethodStartPosition);
  }
 private void addMethodDoc(MethodDeclaration node) {
   if (node.getJavadoc() != null && node.getParent() instanceof AbstractTypeDeclaration) {
     String typeName =
         ((AbstractTypeDeclaration) node.getParent()).getName().getFullyQualifiedName();
     String fullTypeName = currentPackage + "." + removeSpecialSymbols(typeName);
     TypeJavadoc typeJavadoc = typeJavadocs.get(fullTypeName);
     if (typeJavadoc != null) {
       typeJavadoc
           .getMethodJavadocs()
           .add(
               new MethodJavadoc(
                   node.getName().getFullyQualifiedName(), node.getJavadoc().toString()));
     }
   }
 }
  @Override
  public void run(IProgressMonitor monitor) throws CoreException {
    if (monitor == null) monitor = new NullProgressMonitor();
    try {
      monitor.beginTask("", 1); // $NON-NLS-1$
      monitor.setTaskName(CodeGenerationMessages.GenerateToStringOperation_description);

      AbstractTypeDeclaration declaration =
          (AbstractTypeDeclaration)
              ASTNodes.findDeclaration(fContext.getTypeBinding(), fRewrite.getRoot());
      ListRewrite rewriter =
          fRewrite
              .getASTRewrite()
              .getListRewrite(declaration, declaration.getBodyDeclarationsProperty());
      if (fContext.getTypeBinding() != null && rewriter != null) {

        MethodDeclaration toStringMethod = fGenerator.generateToStringMethod();

        List<BodyDeclaration> list = declaration.bodyDeclarations();
        BodyDeclaration replace = findMethodToReplace(list, toStringMethod);
        if (replace == null
            || ((Boolean)
                    toStringMethod.getProperty(AbstractToStringGenerator.OVERWRITE_METHOD_PROPERTY))
                .booleanValue()) insertMethod(toStringMethod, rewriter, replace);

        List<MethodDeclaration> helperMethods = fGenerator.generateHelperMethods();
        for (Iterator<MethodDeclaration> iterator = helperMethods.iterator();
            iterator.hasNext(); ) {
          MethodDeclaration method = iterator.next();
          replace = findMethodToReplace(list, method);
          if (replace == null
              || ((Boolean) method.getProperty(AbstractToStringGenerator.OVERWRITE_METHOD_PROPERTY))
                  .booleanValue()) {
            insertMethod(method, rewriter, replace);
          }
        }

        JavaModelUtil.applyEdit(
            (ICompilationUnit) fUnit.getJavaElement(),
            fRewrite.createChange(true).getEdit(),
            false,
            monitor);
      }

    } finally {
      monitor.done();
    }
  }
 private ITypeBinding getReturnTypeBinding() {
   IMethodBinding methodBinding = fMethodDecl.resolveBinding();
   if (methodBinding != null && methodBinding.getReturnType() != null) {
     return methodBinding.getReturnType();
   }
   return null;
 }
示例#28
0
  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;
  }
  // Metodo para tratamento de declarações de métodos
  private void methodDeclarationHandler(MethodDeclaration methodDeclaration, ApiClass apiClass) {
    IMethodBinding mb = methodDeclaration.resolveBinding();
    if (mb == null) {
      return;
    }

    LinkedList<String> paramsType = new LinkedList<String>();
    for (ITypeBinding pt : mb.getParameterTypes()) {
      paramsType.add(pt.getQualifiedName().toString());
    }

    ApiMethod apiMethod = new ApiMethod(apiClass, mb.getName(), paramsType);
    this.setModifiers(apiMethod, methodDeclaration);

    if (mb.isConstructor()) {
      apiMethod.setConstructor(true);
      apiMethod.setVoid(false);
      apiMethod.setFunction(false);
      apiMethod.setReturnType(null);
    } else if (mb.getReturnType().getQualifiedName().equalsIgnoreCase("void")) {
      apiMethod.setVoid(true);
      apiMethod.setFunction(false);
      apiMethod.setReturnType(null);
    } else {
      apiMethod.setVoid(false);
      apiMethod.setFunction(true);
      apiMethod.setReturnType(mb.getReturnType().getQualifiedName());
    }

    apiClass.getApiMethods().add(apiMethod);
    this.methodMap.put(mb, apiMethod);
  }
 /* (non-Javadoc)
  * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.MethodDeclaration)
  */
 @Override
 public boolean visit(MethodDeclaration node) {
   String[] specialMethods = {
     "initEvoSuiteFramework",
     "initializeClasses",
     "resetClasses",
     "setSystemProperties",
     "clearEvoSuiteFramework"
   };
   if (!ArrayUtil.contains(specialMethods, node.getName().toString())) {
     // System.out.println("Listing method to add:\n"+node.toString());
     result += node.toString();
     methods.add(node);
   }
   return super.visit(node);
 }