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;
 }
Пример #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;
 }
  // 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);
    }
  }
    /** {@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;
    }
  /**
   * Removes the current variable declaration from the AST and inserts it into the lowest possible
   * scope where the variable is first used. Returns the modification to the AST within a Change
   * object.
   */
  private Change recordASTModifications() {
    AST ast = compilationUnit.getAST();
    ASTRewrite rewriter = ASTRewrite.create(ast);

    // duplicate the original variable declaration in lower scope before getting rid of it
    VariableDeclarationStatement oldDeclaration =
        (VariableDeclarationStatement) variableVisitor.getDeclaration();

    assert variableVisitor.getFirstAssignment() instanceof Assignment;
    Assignment variableAssignment = (Assignment) variableVisitor.getFirstAssignment();
    ASTNode newScopeParent = variableAssignment.getParent().getParent();

    String codeString = oldDeclaration.toString();
    ASTNode newDeclaration =
        rewriter.createStringPlaceholder(
            codeString.substring(0, codeString.length() - 1),
            ASTNode.VARIABLE_DECLARATION_STATEMENT);

    ListRewrite listRewrite = rewriter.getListRewrite(newScopeParent, Block.STATEMENTS_PROPERTY);
    listRewrite.insertAt(newDeclaration, 0, null);

    // get rid of the higher scope declaration
    rewriter.remove(oldDeclaration, null);

    ICompilationUnit iCompUnit = method.getCompilationUnit();

    final String description = "ReduceScopeOfVariable";
    final String comment = "ReduceScopeOfVariable does blah...";

    // record the change
    CompilationUnitChange change =
        new CompilationUnitChange("Reduce scope of variable", iCompUnit) {
          public ChangeDescriptor getDescriptor() {
            Map<Object, Object> arguments = new HashMap<Object, Object>();
            arguments.put("method", method);
            arguments.put("var", varName);
            return new RefactoringChangeDescriptor(
                new ReduceScopeOfVariableDescriptor(
                    method.getJavaProject().getElementName(), description, comment, arguments));
          }
        };
    try {
      change.setEdit(rewriter.rewriteAST());
    } catch (Exception e) {
    }

    return change;
  }
 /*
  * @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;
 }
Пример #7
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);
 }
Пример #8
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;
 }
 @Override
 public void endVisit(VariableDeclarationStatement node) {
   checkTypeInDeclaration(node.getType());
   super.endVisit(node);
 }
  private ASTRewrite doAddLocal(CompilationUnit cu) {
    AST ast = cu.getAST();

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

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

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

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

    SimpleName node = names[0];

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

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

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

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

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

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

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

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

      rewrite.replace(assignment, expression, null);

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

      setEndPosition(rewrite.track(expression));

      return rewrite;

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

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

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

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

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

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

      setEndPosition(rewrite.track(expression));

      return rewrite;
    }

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

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

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

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

    Statement statement = dominantStatement;
    List<? extends ASTNode> list = ASTNodes.getContainingList(statement);
    while (list == null
        && statement.getParent() instanceof Statement) { // parent must be if, for or while
      statement = (Statement) statement.getParent();
      list = ASTNodes.getContainingList(statement);
    }
    if (list != null) {
      ASTNode parent = statement.getParent();
      StructuralPropertyDescriptor childProperty = statement.getLocationInParent();
      if (childProperty.isChildListProperty()) {
        rewrite
            .getListRewrite(parent, (ChildListPropertyDescriptor) childProperty)
            .insertBefore(newDecl, statement, null);
        return rewrite;
      } else {
        return null;
      }
    }
    return rewrite;
  }
  private 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;
  }
Пример #12
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);
  }
Пример #13
0
  // generate a variable declaration with an initializer specified by the given expression
  // e.g. given x.f(a,b) ==> int y = x.f(a,b);
  public static List<Statement> genVarDeclStatement(Expression exp) {

    List<Statement> result = new ArrayList<Statement>();

    VariableDeclarationFragment fragment = AST.newAST(AST.JLS8).newVariableDeclarationFragment();

    ExpressionStatement assignmentStmt = genAssignmentStatement(exp);

    // The type of the generated variable
    Type varType = AST.newAST(AST.JLS8).newWildcardType();
    if (exp.resolveTypeBinding() != null) {
      if (exp.resolveTypeBinding().isPrimitive()) {
        switch (exp.resolveTypeBinding().getName()) {
          case "void":
            varType = AST.newAST(AST.JLS8).newPrimitiveType(PrimitiveType.VOID);
            break;
          case "int":
            varType = AST.newAST(AST.JLS8).newPrimitiveType(PrimitiveType.INT);
            break;
          case "char":
            varType = AST.newAST(AST.JLS8).newPrimitiveType(PrimitiveType.CHAR);
            break;
          case "long":
            varType = AST.newAST(AST.JLS8).newPrimitiveType(PrimitiveType.LONG);
            break;
          case "boolean":
            varType = AST.newAST(AST.JLS8).newPrimitiveType(PrimitiveType.BOOLEAN);
            break;
          case "float":
            varType = AST.newAST(AST.JLS8).newPrimitiveType(PrimitiveType.FLOAT);
            break;
          case "short":
            varType = AST.newAST(AST.JLS8).newPrimitiveType(PrimitiveType.SHORT);
            break;
          case "byte":
            varType = AST.newAST(AST.JLS8).newPrimitiveType(PrimitiveType.BYTE);
            break;
          case "double":
            varType = AST.newAST(AST.JLS8).newPrimitiveType(PrimitiveType.DOUBLE);
            break;
        }
      } else {

        // Option 1: only use the simplename
        /*
        SimpleName typeName = AST.newAST(AST.JLS8).newSimpleName(exp.resolveTypeBinding().getName());
        AST tempAST = AST.newAST(AST.JLS8);
        varType = tempAST.newSimpleType((Name) ASTNode.copySubtree(tempAST, typeName));
        */

        varType = resolveQualifiedType(exp.resolveTypeBinding().getQualifiedName());
      }
    }
    // Declaration Fragment
    fragment.setName(
        (SimpleName)
            ASTNode.copySubtree(
                fragment.getAST(),
                ((SimpleName) ((Assignment) assignmentStmt.getExpression()).getLeftHandSide())));
    // fragment.setInitializer((Expression) ASTNode.copySubtree(fragment.getAST(), exp));

    AST varDeclFragAST = AST.newAST(AST.JLS8);
    VariableDeclarationStatement decl =
        varDeclFragAST.newVariableDeclarationStatement(
            (VariableDeclarationFragment) ASTNode.copySubtree(varDeclFragAST, fragment));

    decl.setType((Type) ASTNode.copySubtree(decl.getAST(), varType));

    result.add(decl);

    // initializer is defined here as a separate statement
    Assignment assign = varDeclFragAST.newAssignment();
    assign.setLeftHandSide((Expression) ASTNode.copySubtree(varDeclFragAST, fragment.getName()));
    assign.setRightHandSide((Expression) ASTNode.copySubtree(varDeclFragAST, exp));
    ExpressionStatement assignStmt = varDeclFragAST.newExpressionStatement(assign);

    result.add(assignStmt);

    return result;
  }
Пример #14
0
 public static void addFinalAndValAnnotationToVariableDeclarationStatement(
     Object converter, VariableDeclarationStatement out, LocalDeclaration in) {
   @SuppressWarnings("unchecked")
   List<IExtendedModifier> modifiers = out.modifiers();
   addFinalAndValAnnotationToModifierList(converter, modifiers, out.getAST(), in);
 }
  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);
    }
  }