/** {@inheritDoc} */
    public boolean visit(VariableDeclarationStatement node) {
      if (fAddFinalLocals) handleFragments(node.fragments(), node);

      List fragments = node.fragments();
      for (Iterator iterator = fragments.iterator(); iterator.hasNext(); ) {
        VariableDeclarationFragment fragment = (VariableDeclarationFragment) iterator.next();
        Expression initializer = fragment.getInitializer();
        if (initializer != null) {
          initializer.accept(this);
        }
      }

      return false;
    }
Пример #2
0
 /**
  * Looks for local variable declarations. For every declaration of a variable, the parent {@link
  * Block} denoting the variable's scope is stored in {variableScope} map.
  *
  * @param node the node to visit
  */
 @Override
 public boolean visit(final VariableDeclarationStatement node) {
   for (final Object fragment : node.fragments()) {
     final VariableDeclarationFragment frag = (VariableDeclarationFragment) fragment;
     addBinding(node, frag.getName(), node.getType());
   }
   return true;
 }
Пример #3
0
 @Override
 public boolean visit(VariableDeclarationStatement node) {
   Type typ = node.getType();
   if (typ.isSimpleType()) {
     SimpleType simple = (SimpleType) typ;
     String typName = simple.getName().getFullyQualifiedName();
     List<VariableDeclarationFragment> vars = node.fragments();
     for (VariableDeclarationFragment var : vars) {
       map.put(var.getName().getIdentifier(), typName);
     }
   }
   if (typ.isQualifiedType()) {
     QualifiedType qual = (QualifiedType) typ;
     String typName = qual.getName().getFullyQualifiedName();
     List<VariableDeclarationFragment> vars = node.fragments();
     for (VariableDeclarationFragment var : vars) {
       map.put(var.getName().getIdentifier(), typName);
     }
   }
   if (typ.isPrimitiveType()) {
     PrimitiveType prim = (PrimitiveType) typ;
     String typName = prim.getPrimitiveTypeCode().toString();
     List<VariableDeclarationFragment> vars = node.fragments();
     for (VariableDeclarationFragment var : vars) {
       map.put(var.getName().getIdentifier(), typName);
     }
   }
   if (typ.isParameterizedType()) {
     ParameterizedType prim = (ParameterizedType) typ;
     String typName = prim.getType().toString();
     List<VariableDeclarationFragment> vars = node.fragments();
     for (VariableDeclarationFragment var : vars) {
       map.put(var.getName().getIdentifier(), typName);
     }
   }
   if (typ.isArrayType()) {
     ArrayType prim = (ArrayType) typ;
     String typName = "Array";
     List<VariableDeclarationFragment> vars = node.fragments();
     for (VariableDeclarationFragment var : vars) {
       map.put(var.getName().getIdentifier(), typName);
     }
   }
   return true;
 }
Пример #4
0
 @Override
 public void endVisit(VariableDeclarationStatement node) {
   Collection<VMVariableDeclarationFragment> vars = new ArrayList<VMVariableDeclarationFragment>();
   for (int i = 0; i < node.fragments().size(); i++) {
     vars.add((VMVariableDeclarationFragment) (expressions.pop()));
   }
   VMVariableDeclarationStatement statement = VM.asVariableDeclarationStatement(node, vars);
   topBlock.getStatements().add(statement);
 }
  // https://bugs.eclipse.org/bugs/show_bug.cgi?id=388137
  public void testbug388137() throws Exception {
    this.workingCopies = new ICompilationUnit[1];
    IJavaProject project =
        createJavaProject("P1", new String[] {""}, new String[] {"CONVERTER_JCL15_LIB"}, "", "1.5");
    try {
      String contents =
          "package p;\n"
              + "import java.util.List;\n"
              + "public class X {\n"
              + "	public X(List list) {}\n"
              + "	public static class ListHandler implements Handler {\n"
              + "		List list = null;\n"
              + "		public ListHandler(List list) {\n"
              + " 	 		this.list = list;\n"
              + "		}\n"
              + "	}\n"
              + "}\n"
              + "interface Handler {}\n";
      addLibrary(project, "lib.jar", "src.zip", new String[] {"/P1/p/X.java", contents}, "1.5");

      this.workingCopies[0] = getWorkingCopy("/P1/q/Y.java", true);
      contents =
          "package q;\n"
              + "import p.X.ListHandler;\n"
              + "public class Y {\n"
              + "	public Object foo() {\n"
              + "		ListHandler sortHandler = new ListHandler(null);\n"
              + "		return sortHandler;"
              + "	}\n"
              + "}\n";
      ASTNode node = buildAST(contents, this.workingCopies[0], true);

      assertTrue("Should be a compilation unit", node instanceof CompilationUnit);
      CompilationUnit unit = (CompilationUnit) node;
      node = getASTNode(unit, 0, 0, 0);
      assertEquals(
          "Not an expression statement",
          ASTNode.VARIABLE_DECLARATION_STATEMENT,
          node.getNodeType());
      VariableDeclarationStatement statement = (VariableDeclarationStatement) node;
      List fragments = statement.fragments();
      assertEquals("Wrong size", 1, fragments.size());
      VariableDeclarationFragment fragment = (VariableDeclarationFragment) fragments.get(0);
      Expression expression = fragment.getInitializer();
      assertEquals(
          "Not a constructor invocation",
          ASTNode.CLASS_INSTANCE_CREATION,
          expression.getNodeType());
      ClassInstanceCreation classInstanceCreation = (ClassInstanceCreation) expression;
      IMethodBinding binding = classInstanceCreation.resolveConstructorBinding();
      JavaElement element = (JavaElement) binding.getJavaElement();
      assertNotNull("Null Element info", element.getElementInfo());
    } finally {
      deleteProject(project);
    }
  }
 /*
  * @see ASTVisitor#visit(VariableDeclarationStatement)
  */
 public boolean visit(VariableDeclarationStatement node) {
   if (node.getAST().apiLevel() >= AST.JLS3) {
     printModifiers(node.modifiers());
   }
   node.getType().accept(this);
   this.fBuffer.append(" "); // $NON-NLS-1$
   for (Iterator it = node.fragments().iterator(); it.hasNext(); ) {
     VariableDeclarationFragment f = (VariableDeclarationFragment) it.next();
     f.accept(this);
     if (it.hasNext()) {
       this.fBuffer.append(", "); // $NON-NLS-1$
     }
   }
   this.fBuffer.append(";"); // $NON-NLS-1$
   return false;
 }
  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;
  }
Пример #8
0
  @Override
  public Pair<List<Pair<String, Name>>, Boolean> tryMatch(
      Statement s, Map<String, String> var2type, VariableContext context) {

    List<Pair<String, Name>> matchedVarList = new ArrayList<Pair<String, Name>>();
    Boolean matchedSuccessful = false;

    // An assignment statement pattern should match both
    //				assignment statements
    //  as well as  variabledelcaration statements

    if (s instanceof ExpressionStatement) {
      Expression exp = ((ExpressionStatement) s).getExpression();
      if (exp instanceof Assignment) {
        Assignment assignment = (Assignment) exp;

        // Note that the left hand side expression of an assignment expression is always a *name*
        Name lhsExp = null;
        ;
        try {
          lhsExp = (Name) assignment.getLeftHandSide();
        } catch (Exception e) {
          ErrorManager.error(
              "AssignStmtPattrn@58",
              "The left hand side pattern is not a name, instead: " + assignment);
          return new Pair<List<Pair<String, Name>>, Boolean>(matchedVarList, matchedSuccessful);
        }

        // Debugging types
        TypeHandler.printTypeMatchInfo(lhsExp, var2type.get(this.variable), "AssignStmtPattern@57");
        // Check the type between the lhs metavariable and the name

        // TypeHandler.typeMatchCheck(lhsExp, var2type.get(this.variable))
        if (context.variableMatchCheck(lhsExp, this.variable)) {
          matchedVarList.add(new Pair<String, Name>(this.variable.getName(), lhsExp));
        } else {
          // Type of the lhs expression does not match
          matchedSuccessful = false;
        }

        // Try to match the expression pattern
        Expression rhsExp = assignment.getRightHandSide();
        Pair<List<Pair<String, Name>>, Boolean> expMatch =
            this.expression.tryMatch(rhsExp, var2type, context);

        if (expMatch.getSecond()) {
          for (Pair<String, Name> p : expMatch.getFirst()) {
            matchedVarList.add(p);
          }
          matchedSuccessful = true;
        }
      }
    } else if (s instanceof VariableDeclarationStatement) {

      VariableDeclarationStatement vds = (VariableDeclarationStatement) s;

      if (vds.fragments().size() != 1) {
        // If the error occurs, go and fix the bug in
        ErrorManager.error(
            "AssignStmtPattern@lien81", "The size of variable declaration fragments is not 1");
      }

      VariableDeclarationFragment vdf = (VariableDeclarationFragment) vds.fragments().get(0);

      // Print debugging info for the lhs expression and its corresponding type pattern name
      TypeHandler.printTypeMatchInfo(
          vdf.getName(), var2type.get(this.variable), "AssignStmtPattern@line83");

      // Type check on the lhs variable
      // if (TypeHandler.typeMatchCheck(vdf.getName(), var2type.get(this.variable)))
      if (context.variableMatchCheck(vdf.getName(), this.variable))
        matchedVarList.add(new Pair<String, Name>(this.variable.getName(), vdf.getName()));

      Pair<List<Pair<String, Name>>, Boolean> expMatch =
          this.expression.tryMatch(vdf.getInitializer(), var2type, context);

      if (expMatch.getSecond()) {
        for (Pair<String, Name> p : expMatch.getFirst()) {
          matchedVarList.add(p);
        }
        matchedSuccessful = true;
      }
    }

    return new Pair<List<Pair<String, Name>>, Boolean>(matchedVarList, matchedSuccessful);
  }
  private void createTryCatchStatement(org.eclipse.jdt.core.IBuffer buffer, String lineDelimiter)
      throws CoreException {
    List<Statement> result = new ArrayList<>(1);
    TryStatement tryStatement = getAST().newTryStatement();
    ITypeBinding[] exceptions = fAnalyzer.getExceptions();
    ImportRewriteContext context =
        new ContextSensitiveImportRewriteContext(
            fAnalyzer.getEnclosingBodyDeclaration(), fImportRewrite);

    if (!fIsMultiCatch) {
      for (int i = 0; i < exceptions.length; i++) {
        ITypeBinding exception = exceptions[i];
        CatchClause catchClause = getAST().newCatchClause();
        tryStatement.catchClauses().add(catchClause);
        SingleVariableDeclaration decl = getAST().newSingleVariableDeclaration();
        String varName = StubUtility.getExceptionVariableName(fCUnit.getJavaProject());

        String name = fScope.createName(varName, false);
        decl.setName(getAST().newSimpleName(name));
        Type type = fImportRewrite.addImport(exception, getAST(), context);
        decl.setType(type);
        catchClause.setException(decl);
        Statement st = getCatchBody(ASTNodes.getQualifiedTypeName(type), name, lineDelimiter);
        if (st != null) {
          catchClause.getBody().statements().add(st);
        }
        fLinkedProposalModel
            .getPositionGroup(GROUP_EXC_TYPE + i, true)
            .addPosition(fRewriter.track(decl.getType()), i == 0);
        fLinkedProposalModel
            .getPositionGroup(GROUP_EXC_NAME + i, true)
            .addPosition(fRewriter.track(decl.getName()), false);
      }
    } else {
      List<ITypeBinding> filteredExceptions = filterSubtypeExceptions(exceptions);
      CatchClause catchClause = getAST().newCatchClause();
      SingleVariableDeclaration decl = getAST().newSingleVariableDeclaration();
      String varName = StubUtility.getExceptionVariableName(fCUnit.getJavaProject());
      String name = fScope.createName(varName, false);
      decl.setName(getAST().newSimpleName(name));

      UnionType unionType = getAST().newUnionType();
      List<Type> types = unionType.types();
      int i = 0;
      for (ITypeBinding exception : filteredExceptions) {
        Type type = fImportRewrite.addImport(exception, getAST(), context);
        types.add(type);
        fLinkedProposalModel
            .getPositionGroup(GROUP_EXC_TYPE + i, true)
            .addPosition(fRewriter.track(type), i == 0);
        i++;
      }

      decl.setType(unionType);
      catchClause.setException(decl);
      fLinkedProposalModel
          .getPositionGroup(GROUP_EXC_NAME + 0, true)
          .addPosition(fRewriter.track(decl.getName()), false);
      Statement st = getCatchBody("Exception", name, lineDelimiter); // $NON-NLS-1$
      if (st != null) {
        catchClause.getBody().statements().add(st);
      }
      tryStatement.catchClauses().add(catchClause);
    }
    List<ASTNode> variableDeclarations = getSpecialVariableDeclarationStatements();
    ListRewrite statements =
        fRewriter.getListRewrite(tryStatement.getBody(), Block.STATEMENTS_PROPERTY);
    boolean selectedNodeRemoved = false;
    ASTNode expressionStatement = null;
    for (int i = 0; i < fSelectedNodes.length; i++) {
      ASTNode node = fSelectedNodes[i];
      if (node instanceof VariableDeclarationStatement && variableDeclarations.contains(node)) {
        AST ast = getAST();
        VariableDeclarationStatement statement = (VariableDeclarationStatement) node;
        // Create a copy and remove the initializer
        VariableDeclarationStatement copy =
            (VariableDeclarationStatement) ASTNode.copySubtree(ast, statement);
        List<IExtendedModifier> modifiers = copy.modifiers();
        for (Iterator<IExtendedModifier> iter = modifiers.iterator(); iter.hasNext(); ) {
          IExtendedModifier modifier = iter.next();
          if (modifier.isModifier()
              && Modifier.isFinal(((Modifier) modifier).getKeyword().toFlagValue())) {
            iter.remove();
          }
        }
        List<VariableDeclarationFragment> fragments = copy.fragments();
        for (Iterator<VariableDeclarationFragment> iter = fragments.iterator(); iter.hasNext(); ) {
          VariableDeclarationFragment fragment = iter.next();
          fragment.setInitializer(null);
        }
        CompilationUnit root = (CompilationUnit) statement.getRoot();
        int extendedStart = root.getExtendedStartPosition(statement);
        // we have a leading comment and the comment is covered by the selection
        if (extendedStart != statement.getStartPosition()
            && extendedStart >= fSelection.getOffset()) {
          String commentToken =
              buffer.getText(extendedStart, statement.getStartPosition() - extendedStart);
          commentToken = Strings.trimTrailingTabsAndSpaces(commentToken);
          Type type = statement.getType();
          String typeName = buffer.getText(type.getStartPosition(), type.getLength());
          copy.setType(
              (Type)
                  fRewriter.createStringPlaceholder(commentToken + typeName, type.getNodeType()));
        }
        result.add(copy);
        // convert the fragments into expression statements
        fragments = statement.fragments();
        if (!fragments.isEmpty()) {
          List<ExpressionStatement> newExpressionStatements = new ArrayList<>();
          for (Iterator<VariableDeclarationFragment> iter = fragments.iterator();
              iter.hasNext(); ) {
            VariableDeclarationFragment fragment = iter.next();
            Expression initializer = fragment.getInitializer();
            if (initializer != null) {
              Assignment assignment = ast.newAssignment();
              assignment.setLeftHandSide(
                  (Expression) fRewriter.createCopyTarget(fragment.getName()));
              assignment.setRightHandSide((Expression) fRewriter.createCopyTarget(initializer));
              newExpressionStatements.add(ast.newExpressionStatement(assignment));
            }
          }
          if (!newExpressionStatements.isEmpty()) {
            if (fSelectedNodes.length == 1) {
              expressionStatement =
                  fRewriter.createGroupNode(
                      newExpressionStatements.toArray(new ASTNode[newExpressionStatements.size()]));
            } else {
              fRewriter.replace(
                  statement,
                  fRewriter.createGroupNode(
                      newExpressionStatements.toArray(new ASTNode[newExpressionStatements.size()])),
                  null);
            }
          } else {
            fRewriter.remove(statement, null);
            selectedNodeRemoved = true;
          }
        } else {
          fRewriter.remove(statement, null);
          selectedNodeRemoved = true;
        }
      }
    }
    result.add(tryStatement);
    ASTNode replacementNode;
    if (result.size() == 1) {
      replacementNode = result.get(0);
    } else {
      replacementNode = fRewriter.createGroupNode(result.toArray(new ASTNode[result.size()]));
    }
    if (fSelectedNodes.length == 1) {
      ASTNode selectedNode = fSelectedNodes[0];

      if (selectedNode instanceof MethodReference) {
        MethodReference methodReference = (MethodReference) selectedNode;
        IMethodBinding functionalMethod =
            QuickAssistProcessor.getFunctionalMethodForMethodReference(methodReference);
        // functionalMethod is non-null and non-generic. See
        // ExceptionAnalyzer.handleMethodReference(MethodReference node).
        Assert.isTrue(functionalMethod != null && !functionalMethod.isGenericMethod());
        LambdaExpression lambda =
            QuickAssistProcessor.convertMethodRefernceToLambda(
                methodReference, functionalMethod, fRootNode, fRewriter, null, true);
        ASTNode statementInBlock = (ASTNode) ((Block) lambda.getBody()).statements().get(0);
        fRewriter.replace(statementInBlock, replacementNode, null);
        statements.insertLast(statementInBlock, null);
        return;
      }

      LambdaExpression enclosingLambda = ASTResolving.findEnclosingLambdaExpression(selectedNode);
      if (enclosingLambda != null
          && selectedNode.getLocationInParent() == LambdaExpression.BODY_PROPERTY
          && enclosingLambda.resolveMethodBinding() != null) {
        QuickAssistProcessor.changeLambdaBodyToBlock(enclosingLambda, getAST(), fRewriter);
        Block blockBody = (Block) fRewriter.get(enclosingLambda, LambdaExpression.BODY_PROPERTY);
        ASTNode statementInBlock = (ASTNode) blockBody.statements().get(0);
        fRewriter.replace(statementInBlock, replacementNode, null);
        statements.insertLast(statementInBlock, null);
        return;
      }

      if (expressionStatement != null) {
        statements.insertLast(expressionStatement, null);
      } else {
        if (!selectedNodeRemoved)
          statements.insertLast(fRewriter.createMoveTarget(selectedNode), null);
      }
      fRewriter.replace(selectedNode, replacementNode, null);
    } else {
      ListRewrite source =
          fRewriter.getListRewrite(
              fSelectedNodes[0].getParent(),
              (ChildListPropertyDescriptor) fSelectedNodes[0].getLocationInParent());
      ASTNode toMove =
          source.createMoveTarget(
              fSelectedNodes[0], fSelectedNodes[fSelectedNodes.length - 1], replacementNode, null);
      statements.insertLast(toMove, null);
    }
  }