/*
   * 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;
  }
  /**
   * 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);
  }
Esempio n. 3
0
  /**
   * Add a method's data, words and its mappings to the database. This method is called externally
   * from {@link MyASTVisitor}.
   *
   * @param method A AST node of MethodDeclaration type
   */
  public void addMethodToDb(MethodDeclaration method) {
    System.out.println("Processing method: " + method.getName());

    CompilationUnit unit = (CompilationUnit) method.getRoot();
    IPath path = unit.getJavaElement().getResource().getLocation();

    dbManager.insertMethod(
        new MethodData(
            method.resolveBinding().getKey(), method.getName().toString(), path.toString()));

    // Gets camel case split words
    List<String> words = TFIDFIndex.getTokens(method.toString());

    for (String word : words) {
      addWordToDb(word, method.resolveBinding().getKey());
    }
  }
  private Example makeExample(
      MethodDeclaration node,
      Set<? extends Expression> envolvedInvocations,
      List<ApiMethod> envolvedApiMethods) {

    //  Visitor responsável por realizar o slicing de programas
    SlicingStatementVisitor visitor =
        new SlicingStatementVisitor(node, new HashSet<ASTNode>(envolvedInvocations));
    node.accept(visitor);

    Collection<Statement> relatedStatements = visitor.getSlicedStatements();

    ASTNode newAST =
        ASTUtil.copyStatements(node.getBody(), relatedStatements, AST.newAST(AST.JLS3));
    if (!relatedStatements.isEmpty()) {
      LOGGER.error("Some statements were not included!");
    }

    if (newAST == null) {
      LOGGER.error("Slicing process failed for node ");
      // TODO Se AST retornada for nula é porque faltou incluir statement(s)
      return null;
    } else if (((Block) newAST).statements().isEmpty()) {
      LOGGER.error("Slicing process failed for node ");
      // TODO Se o Block retornado for vazio é porque faltou incluir statement(s)
      return null;
    }

    ASTUtil.removeEmptyBlocks((Block) newAST);

    // Adiciona declarações de variáveis que não foram encontradas no escopo do método
    // Para facilitar, tipos iguais são declarados no mesmo Statement
    Set<String> additionalDeclarationLines = new HashSet<String>();
    Map<ITypeBinding, List<IVariableBinding>> typesMap =
        new HashMap<ITypeBinding, List<IVariableBinding>>();
    for (IVariableBinding ivb : visitor.getUndiscoveredDeclarations()) {
      if (!typesMap.containsKey(ivb.getType())) {
        typesMap.put(ivb.getType(), new ArrayList<IVariableBinding>(2));
      }
      typesMap.get(ivb.getType()).add(ivb);
    }

    for (ITypeBinding typeBinding : typesMap.keySet()) {
      List<IVariableBinding> variableBindings = typesMap.get(typeBinding);

      Stack<VariableDeclarationFragment> fragments = new Stack<VariableDeclarationFragment>();
      for (IVariableBinding ivb : variableBindings) {
        VariableDeclarationFragment declarationFragment =
            newAST.getAST().newVariableDeclarationFragment();
        declarationFragment.setName(newAST.getAST().newSimpleName(ivb.getName()));
        fragments.add(declarationFragment);
      }

      VariableDeclarationStatement statement =
          newAST.getAST().newVariableDeclarationStatement(fragments.pop());
      while (!fragments.isEmpty()) {
        statement.fragments().add(fragments.pop());
      }

      statement.setType(this.getType(typeBinding, newAST.getAST()));

      additionalDeclarationLines.add(statement.toString());
      ((Block) newAST).statements().add(0, statement);
    }

    Example example = new Example();
    example.setAttachment(this.attachmentMap.get(node.getRoot()));
    example.setApiMethods(new HashSet<ApiElement>(envolvedApiMethods));
    example.setImports(visitor.getImports());

    for (Expression seed : envolvedInvocations) {
      example.getSeeds().add(seed.toString());
    }

    example.setSourceMethod(node.toString());
    example.setAddedAt(new Date(System.currentTimeMillis()));

    try {
      IMethodBinding nodeBinding = node.resolveBinding();
      if (!this.methodMap.containsKey(nodeBinding)) {
        ApiClass newApiClass = new ApiClass(nodeBinding.getDeclaringClass().getQualifiedName());
        methodDeclarationHandler(node, newApiClass);
      }
      example.setSourceMethodCall(this.methodMap.get(nodeBinding).getFullName());
    } catch (Exception e) {
      LOGGER.error(e);
      if (example.getSourceMethodCall() == null) {
        example.setSourceMethodCall("?");
      }
    }

    String codeExample = newAST.toString();
    for (String line : additionalDeclarationLines) {
      codeExample =
          codeExample.replace(
              line,
              line.replace("\n", "").concat("  ").concat("//initialized previously").concat("\n"));
    }

    // FIXME
    codeExample = codeExample.replaceAll("(\\{\n)(\\s+)(\\})", "$1 //do something \n$3");

    try {
      example.setCodeExample(codeExample);
      example.setFormattedCodeExample(ASTUtil.codeFormatter(codeExample));
    } catch (Exception e) {
      LOGGER.error(e);
      if (example.getFormattedCodeExample() == null) {
        example.setFormattedCodeExample(codeExample);
      }
    }

    // TODO Obter métricas do exemplo
    example
        .getMetrics()
        .put(ExampleMetric.LOC.name(), example.getFormattedCodeExample().split("\n").length - 1);
    example.getMetrics().put(ExampleMetric.ARGUMENTS.name(), visitor.getNumberOfArguments());
    example
        .getMetrics()
        .put(ExampleMetric.DECISION_STATEMENTS.name(), visitor.getNumberOfDecisionStatements());
    example.getMetrics().put(ExampleMetric.INVOCATIONS.name(), visitor.getNumberOfInvocations());
    example
        .getMetrics()
        .put(ExampleMetric.NULL_ARGUMENTS.name(), visitor.getNumberOfNullArguments());
    example
        .getMetrics()
        .put(ExampleMetric.PRIMITIVE_ARGUMENTS.name(), visitor.getNumberOfPrimitiveArguments());
    example
        .getMetrics()
        .put(ExampleMetric.FIELD_ARGUMENTS.name(), visitor.getNumberOfFieldArguments());
    example
        .getMetrics()
        .put(
            ExampleMetric.UNDISCOVERED_DECLARATIONS.name(),
            visitor.getNumberOfUndiscoveredDeclarations());
    example
        .getMetrics()
        .put(ExampleMetric.UNHANDLED_EXCEPTIONS.name(), visitor.getNumberOfUnhandledExceptions());

    return example;
  }
    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));
          }
        }
      }
    }