Exemplo n.º 1
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 ITypeBinding getReturnTypeBinding() {
   IMethodBinding methodBinding = fMethodDecl.resolveBinding();
   if (methodBinding != null && methodBinding.getReturnType() != null) {
     return methodBinding.getReturnType();
   }
   return null;
 }
 @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;
 }
Exemplo n.º 4
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);
          }
        }
      }
    }
  }
Exemplo n.º 5
0
  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);
        }
      }
    }
  }
  // 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);
  }
Exemplo n.º 7
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 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;
  }
 @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;
 }
Exemplo n.º 10
0
  /* METHOD DECLARATION PART */
  @Override
  public boolean visit(MethodDeclaration node) {
    IMethodBinding binding = node.resolveBinding();

    List<MethodPathItem> inhMethods = new ArrayList<MethodPathItem>();

    boolean foundInhMethods = initializeAndCollectInhData(binding, inhMethods);

    if (foundInhMethods) {

      handleInheritedAbstractMethodImplementation(node, binding, inhMethods);
      handleOverridingRelationshipViolation(node, binding, inhMethods);
    }

    return super.visit(node);
  }
    private boolean isWrittenInTypeConstructors(ArrayList writes, ITypeBinding declaringClass) {

      for (int i = 0; i < writes.size(); i++) {
        SimpleName name = (SimpleName) writes.get(i);

        MethodDeclaration methodDeclaration = getWritingConstructor(name);
        if (methodDeclaration == null) return false;

        if (!methodDeclaration.isConstructor()) return false;

        IMethodBinding constructor = methodDeclaration.resolveBinding();
        if (constructor == null) return false;

        ITypeBinding declaringClass2 = constructor.getDeclaringClass();
        if (!declaringClass.equals(declaringClass2)) return false;
      }

      return true;
    }
 private void checkOverridden(RefactoringStatus status, IProgressMonitor pm)
     throws JavaModelException {
   pm.beginTask("", 9); // $NON-NLS-1$
   pm.setTaskName(RefactoringCoreMessages.InlineMethodRefactoring_checking_overridden);
   MethodDeclaration decl = fSourceProvider.getDeclaration();
   IMethod method = (IMethod) decl.resolveBinding().getJavaElement();
   if (method == null || Flags.isPrivate(method.getFlags())) {
     pm.worked(8);
     return;
   }
   IType type = method.getDeclaringType();
   ITypeHierarchy hierarchy = type.newTypeHierarchy(new SubProgressMonitor(pm, 6));
   checkSubTypes(status, method, hierarchy.getAllSubtypes(type), new SubProgressMonitor(pm, 1));
   checkSuperClasses(
       status, method, hierarchy.getAllSuperclasses(type), new SubProgressMonitor(pm, 1));
   checkSuperInterfaces(
       status, method, hierarchy.getAllSuperInterfaces(type), new SubProgressMonitor(pm, 1));
   pm.setTaskName(""); // $NON-NLS-1$
 }
  @Override
  protected ASTRewrite getRewrite() throws CoreException {
    CompilationUnit targetAstRoot = ASTResolving.createQuickFixAST(getCompilationUnit(), null);
    createImportRewrite(targetAstRoot);

    ASTRewrite rewrite = ASTRewrite.create(targetAstRoot.getAST());

    // Find the method declaration in the AST we just generated (the one that
    // the AST rewriter is hooked up to).
    MethodDeclaration rewriterAstMethodDecl =
        JavaASTUtils.findMethodDeclaration(targetAstRoot, methodDecl.resolveBinding().getKey());
    if (rewriterAstMethodDecl == null) {
      return null;
    }

    // Remove the extra method declaration
    rewrite.remove(rewriterAstMethodDecl, null);

    return rewrite;
  }
  /** @see HierarchicalASTVisitor#visit(org.eclipse.jdt.core.dom.AbstractTypeDeclaration) */
  public boolean visit(AbstractTypeDeclaration node) {
    progressMonitorWorked(1);
    if (!isFurtherTraversalNecessary(node)) {
      return false;
    }

    if (isNodeWithinMethod(node)) {
      List bodyDeclarations = node.bodyDeclarations();
      for (Iterator iter = bodyDeclarations.iterator(); iter.hasNext(); ) {
        BodyDeclaration bodyDeclaration = (BodyDeclaration) iter.next();
        if (bodyDeclaration instanceof MethodDeclaration) {
          MethodDeclaration child = (MethodDeclaration) bodyDeclaration;
          if (child.isConstructor()) {
            addMethodCall(child.resolveBinding(), child.getName());
          }
        }
      }
      return false;
    }

    return true;
  }
  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));
    }
  }
    private boolean fieldCanBeFinal(
        VariableDeclarationFragment fragment, IVariableBinding binding) {
      if (Modifier.isStatic(((FieldDeclaration) fragment.getParent()).getModifiers())) return false;

      if (!fWrittenVariables.containsKey(binding)) {
        // variable is not written
        if (fragment.getInitializer() == null) { // variable is not initialized
          return false;
        } else {
          return true;
        }
      }

      if (fragment.getInitializer() != null) // variable is initialized and written
      return false;

      ITypeBinding declaringClass = binding.getDeclaringClass();
      if (declaringClass == null) return false;

      ArrayList writes = (ArrayList) fWrittenVariables.get(binding);
      if (!isWrittenInTypeConstructors(writes, declaringClass)) return false;

      HashSet writingConstructorBindings = new HashSet();
      ArrayList writingConstructors = new ArrayList();
      for (int i = 0; i < writes.size(); i++) {
        SimpleName name = (SimpleName) writes.get(i);
        MethodDeclaration constructor = getWritingConstructor(name);
        if (writingConstructors.contains(
            constructor)) // variable is written twice or more in constructor
        return false;

        if (canReturn(constructor)) return false;

        writingConstructors.add(constructor);
        IMethodBinding constructorBinding = constructor.resolveBinding();
        if (constructorBinding == null) return false;

        writingConstructorBindings.add(constructorBinding);
      }

      for (int i = 0; i < writingConstructors.size(); i++) {
        MethodDeclaration constructor = (MethodDeclaration) writingConstructors.get(i);
        if (callsWritingConstructor(
            constructor,
            writingConstructorBindings)) // writing constructor calls other writing constructor
        return false;
      }

      MethodDeclaration constructor = (MethodDeclaration) writingConstructors.get(0);
      TypeDeclaration typeDecl =
          (TypeDeclaration) ASTNodes.getParent(constructor, TypeDeclaration.class);
      if (typeDecl == null) return false;

      MethodDeclaration[] methods = typeDecl.getMethods();
      for (int i = 0; i < methods.length; i++) {
        if (methods[i].isConstructor()) {
          IMethodBinding methodBinding = methods[i].resolveBinding();
          if (methodBinding == null) return false;

          if (!writingConstructorBindings.contains(methodBinding)) {
            if (!callsWritingConstructor(
                methods[i],
                writingConstructorBindings)) // non writing constructor does not call a writing
              // constructor
              return false;
          }
        }
      }

      return true;
    }
Exemplo n.º 17
0
  @Override
  public Object execute(ExecutionEvent event) throws ExecutionException {
    // TODO: this wrapping try is for debug only. Remove later.
    final int TIMES = 10;
    List<Long> runsTimer = new ArrayList<Long>(TIMES);
    for (int i = 0; i < TIMES; i++) {
      long startTimer = System.currentTimeMillis();
      try {
        ISelection selection = HandlerUtil.getCurrentSelectionChecked(event);
        Shell shell = HandlerUtil.getActiveShellChecked(event);

        if (!(selection instanceof ITextSelection))
          throw new ExecutionException("Not a text selection");

        IFile textSelectionFile =
            (IFile)
                HandlerUtil.getActiveEditorChecked(event).getEditorInput().getAdapter(IFile.class);

        ITextSelection textSelection = (ITextSelection) selection;
        SelectionNodesVisitor selectionNodesVisitor = new SelectionNodesVisitor(textSelection);

        ICompilationUnit compilationUnit = JavaCore.createCompilationUnitFrom(textSelectionFile);
        ASTParser parser = ASTParser.newParser(AST.JLS3);
        parser.setSource(compilationUnit);
        parser.setKind(ASTParser.K_COMPILATION_UNIT);
        parser.setResolveBindings(true);
        CompilationUnit jdtCompilationUnit = (CompilationUnit) parser.createAST(null);
        jdtCompilationUnit.accept(selectionNodesVisitor);

        Set<ASTNode> selectionNodes = selectionNodesVisitor.getNodes();
        System.out.println("Selection" + selectionNodes);

        IFeatureExtracter extracter = CIDEFeatureExtracterFactory.getInstance().newExtracter();

        String correspondentClasspath =
            MethodDeclarationSootMethodBridge.getCorrespondentClasspath(textSelectionFile);
        SootManager.configure(correspondentClasspath);
        MethodDeclaration methodDeclaration =
            MethodDeclarationSootMethodBridge.getParentMethod(selectionNodes.iterator().next());
        String declaringMethodClass =
            methodDeclaration.resolveBinding().getDeclaringClass().getQualifiedName();
        MethodDeclarationSootMethodBridge mdsm =
            new MethodDeclarationSootMethodBridge(methodDeclaration);
        SootMethod sootMethod =
            SootManager.getMethodBySignature(
                declaringMethodClass, mdsm.getSootMethodSubSignature());
        Body body = sootMethod.retrieveActiveBody();

        Collection<Unit> unitsInSelection =
            ASTNodeUnitBridge.getUnitsFromLines(
                ASTNodeUnitBridge.getLinesFromASTNodes(selectionNodes, jdtCompilationUnit), body);
        if (unitsInSelection.isEmpty()) {
          System.out.println("the selection doesn't map to any Soot Unit");
          return null;
        }

        FeatureModelInstrumentorTransformer instrumentorTransformer =
            new FeatureModelInstrumentorTransformer(extracter, correspondentClasspath);
        instrumentorTransformer.transform2(body, correspondentClasspath);

        FeatureTag<Set<String>> bodyFeatureTag =
            (FeatureTag<Set<String>>) body.getTag("FeatureTag");

        BriefUnitGraph bodyGraph = new BriefUnitGraph(body);
        LiftedReachingDefinitions reachingDefinitions =
            new LiftedReachingDefinitions(bodyGraph, bodyFeatureTag.getFeatures());
        reachingDefinitions.execute();

        Map<Pair<Unit, Set<String>>, Set<Unit>> createProvidesConfigMap =
            createProvidesConfigMap(unitsInSelection, reachingDefinitions, body);
        System.out.println(createProvidesConfigMap);
        String message = createMessage(createProvidesConfigMap);

        // EmergentPopup.pop(shell, message);
      } catch (Exception ex) {
        ex.printStackTrace();
      } finally {
        G.v().reset();
      }
      long estimatedTime = System.currentTimeMillis() - startTimer;
      runsTimer.add(estimatedTime);
    }
    System.out.println(runsTimer);
    return null;
  }
  private static void generate(IRSEDiagramEngine diagramEngine) {
    if (diagramEngine == null) return;

    LinkedHashMap<IType, List<Invocation>> history =
        SeqUtil.getNavigationHistory(numNavigationsToInclude);
    List<CodeUnit> classUnits = new ArrayList<CodeUnit>();
    List<CodeUnit> methodUnits = new ArrayList<CodeUnit>();
    List<ArtifactFragment> toAddToDiagram = new ArrayList<ArtifactFragment>();

    for (IType type : history.keySet()) {
      if (!openTabs.contains(type)) continue;

      Resource classOfNavigationRes =
          RJCore.jdtElementToResource(StoreUtil.getDefaultStoreRepository(), type);
      CodeUnit classOfNavigationCU =
          GenerateUtil.getCodeUnitForRes(classOfNavigationRes, null, classUnits, null);

      // Add method calls
      for (Invocation invocation : history.get(type)) {

        IType container = null;
        if (invocation.getMethodElement() != null) {
          IMethod method = invocation.getMethodElement();
          container = method.getDeclaringType();
        }
        if (container == null) continue;

        boolean containerIsAnOpenTab = false;
        for (IType navigatedType : openTabs) {
          if (navigatedType.equals(container)) {
            containerIsAnOpenTab = true;
            break;
          }
        }
        if (!containerIsAnOpenTab) continue;

        // Find the method declaration in which the invocation is made
        CompilationUnit cu = ASTUtil.getAst(IJEUtils.ije_getTypeRoot(type));
        MethodDeclarationFinder finder = new MethodDeclarationFinder(cu);
        MethodDeclaration declaration = finder.findDeclaration(invocation.getStartPosition());
        if (declaration == null
            || declaration.resolveBinding() == null
            || declaration.resolveBinding().getJavaElement() == null) continue;

        Resource declarationRes =
            RJCore.jdtElementToResource(
                StoreUtil.getDefaultStoreRepository(),
                declaration.resolveBinding().getJavaElement());
        CodeUnit declarationThatMakesInvocation =
            GenerateUtil.getCodeUnitForRes(declarationRes, null, methodUnits, classOfNavigationCU);

        String instanceName =
            (invocation.getInvocation() instanceof SuperMethodInvocation)
                ? null
                : MethodUtil.getInstanceCalledOn(invocation);
        CodeUnit containerOfDeclOfInvokedMethod =
            GenerateUtil.getCodeUnitForRes(
                RJCore.jdtElementToResource(StoreUtil.getDefaultStoreRepository(), container),
                instanceName,
                classUnits,
                null);
        Resource declOfInvokedMethodRes =
            RJCore.jdtElementToResource(
                StoreUtil.getDefaultStoreRepository(), invocation.getMethodElement());
        CodeUnit declOfInvokedMethodCU =
            GenerateUtil.getCodeUnitForRes(
                declOfInvokedMethodRes, null, methodUnits, containerOfDeclOfInvokedMethod);

        ArtifactRel rel =
            new ArtifactRel(declarationThatMakesInvocation, declOfInvokedMethodCU, RJCore.calls);

        declarationThatMakesInvocation.addSourceConnection(rel);
        declOfInvokedMethodCU.addTargetConnection(rel);
      }

      // Add inheritance relationships among classes
      for (Resource superClassRes : InstanceUtil.getSuperClasses(classOfNavigationRes)) {
        CodeUnit superClassCU =
            GenerateUtil.getCodeUnitForRes(superClassRes, null, classUnits, null);

        IJavaElement superClassElt =
            RJCore.resourceToJDTElement(StoreUtil.getDefaultStoreRepository(), superClassRes);
        if (!history.keySet().contains(superClassElt))
          continue; // superclass has not been recently navigated
        if (!openTabs.contains(superClassElt)) continue; // superclass is not an open tab

        ArtifactRel inheritanceRel =
            new ArtifactRel(classOfNavigationCU, superClassCU, RJCore.inherits);
        classOfNavigationCU.addSourceConnection(inheritanceRel);
        superClassCU.addTargetConnection(inheritanceRel);
      }
    }

    for (CodeUnit classUnit : classUnits) {
      if (classUnit.getShownChildren().size() > 0) toAddToDiagram.add(classUnit);
    }

    int numBeingAdded = toAddToDiagram.size();
    if (numBeingAdded < numNavigationsToInclude) {
      // Diagram going to be small, so add a reasonable number
      // of the open tabs that were most recently activated
      // (openTabs list is ordered with most recently activated first)
      for (int i = 0; i < openTabs.size() && numBeingAdded < numNavigationsToInclude; i++) {
        IType type = openTabs.get(i);

        // only adding top level tabs here, not any nested classes
        if (!(type instanceof SourceType)
            || ((SourceType) type).getParent().getElementType() == IJavaElement.TYPE) continue;

        Resource classOfNavigationRes =
            RJCore.jdtElementToResource(StoreUtil.getDefaultStoreRepository(), type);
        CodeUnit classOfNavigationCU =
            GenerateUtil.getCodeUnitForRes(classOfNavigationRes, null, classUnits, null);
        if (!toAddToDiagram.contains(classOfNavigationCU)) {
          toAddToDiagram.add(classOfNavigationCU);
          numBeingAdded++;
        }
      }
    }
    diagramEngine.openDiagramFromNavigatedTabs(
        toAddToDiagram, new ArrayList<ArtifactFragment>(classUnits));
  }
Exemplo n.º 19
0
 @Override
 public boolean visit(MethodDeclaration node) {
   IBinding binding = node.resolveBinding();
   if (binding.getJavaElement().equals(method)) this.declaration = node;
   return super.visit(node);
 }
Exemplo n.º 20
0
 public boolean visit(MethodDeclaration node) {
   if (found(node, node.getName()) && this.resolveBinding)
     this.foundBinding = node.resolveBinding();
   return true;
 }
  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;
  }