/*
  * @see ASTVisitor#visit(MethodInvocation)
  */
 public boolean visit(MethodInvocation node) {
   if (node.getExpression() != null) {
     node.getExpression().accept(this);
     this.fBuffer.append("."); // $NON-NLS-1$
   }
   if (node.getAST().apiLevel() >= AST.JLS3) {
     if (!node.typeArguments().isEmpty()) {
       this.fBuffer.append("<"); // $NON-NLS-1$
       for (Iterator it = node.typeArguments().iterator(); it.hasNext(); ) {
         Type t = (Type) it.next();
         t.accept(this);
         if (it.hasNext()) {
           this.fBuffer.append(","); // $NON-NLS-1$
         }
       }
       this.fBuffer.append(">"); // $NON-NLS-1$
     }
   }
   node.getName().accept(this);
   this.fBuffer.append("("); // $NON-NLS-1$
   for (Iterator it = node.arguments().iterator(); it.hasNext(); ) {
     Expression e = (Expression) it.next();
     e.accept(this);
     if (it.hasNext()) {
       this.fBuffer.append(","); // $NON-NLS-1$
     }
   }
   this.fBuffer.append(")"); // $NON-NLS-1$
   return false;
 }
 /*
  * @see ASTVisitor#visit(ClassInstanceCreation)
  */
 public boolean visit(ClassInstanceCreation node) {
   if (node.getExpression() != null) {
     node.getExpression().accept(this);
     this.fBuffer.append("."); // $NON-NLS-1$
   }
   this.fBuffer.append("new "); // $NON-NLS-1$
   if (node.getAST().apiLevel() >= AST.JLS3) {
     if (!node.typeArguments().isEmpty()) {
       this.fBuffer.append("<"); // $NON-NLS-1$
       for (Iterator it = node.typeArguments().iterator(); it.hasNext(); ) {
         Type t = (Type) it.next();
         t.accept(this);
         if (it.hasNext()) {
           this.fBuffer.append(","); // $NON-NLS-1$
         }
       }
       this.fBuffer.append(">"); // $NON-NLS-1$
     }
     node.getType().accept(this);
   }
   this.fBuffer.append("("); // $NON-NLS-1$
   for (Iterator it = node.arguments().iterator(); it.hasNext(); ) {
     Expression e = (Expression) it.next();
     e.accept(this);
     if (it.hasNext()) {
       this.fBuffer.append(","); // $NON-NLS-1$
     }
   }
   this.fBuffer.append(")"); // $NON-NLS-1$
   if (node.getAnonymousClassDeclaration() != null) {
     node.getAnonymousClassDeclaration().accept(this);
   }
   return false;
 }
Ejemplo n.º 3
0
      @Override
      public boolean visit(MethodInvocation node) {
        String mName = node.getName().getFullyQualifiedName().toString();
        Expression e = node.getExpression();
        String typName = "";
        if (e instanceof StringLiteral) {
          typName = "string";
        } else if (e instanceof FieldAccess) {
          FieldAccess field = (FieldAccess) e;
          typName = field.getName().getFullyQualifiedName();
        } else if (e instanceof Name) {
          typName = ((Name) e).getFullyQualifiedName();
          if (varTypMap.containsKey(typName)) {
            typName = varTypMap.get(typName);
          }
        } else {
          if (e != null) {
            typName = e.toString();
            if (typName.contains(".")) typName = typName.substring(0, typName.indexOf('.', 0));
            if (varTypMap.containsKey(typName)) typName = varTypMap.get(typName);
          }
        }

        String key = typName + "->" + mName;
        if (freqRecord.containsKey(key)) {
          freqRecord.put(key, freqRecord.get(key) + 1);
        } else {
          freqRecord.put(key, 1);
        }
        return super.visit(node);
      }
  private RefactoringStatus checkExpression() throws JavaModelException {
    RefactoringStatus result = new RefactoringStatus();
    result.merge(checkExpressionBinding());
    if (result.hasFatalError()) return result;
    checkAllStaticFinal();

    IExpressionFragment selectedExpression = getSelectedExpression();
    Expression associatedExpression = selectedExpression.getAssociatedExpression();
    if (associatedExpression instanceof NullLiteral)
      result.merge(
          RefactoringStatus.createFatalErrorStatus(
              RefactoringCoreMessages.ExtractConstantRefactoring_null_literals));
    else if (!ConstantChecks.isLoadTimeConstant(selectedExpression))
      result.merge(
          RefactoringStatus.createFatalErrorStatus(
              RefactoringCoreMessages.ExtractConstantRefactoring_not_load_time_constant));
    else if (associatedExpression instanceof SimpleName) {
      if (associatedExpression.getParent() instanceof QualifiedName
              && associatedExpression.getLocationInParent() == QualifiedName.NAME_PROPERTY
          || associatedExpression.getParent() instanceof FieldAccess
              && associatedExpression.getLocationInParent() == FieldAccess.NAME_PROPERTY)
        return RefactoringStatus.createFatalErrorStatus(
            RefactoringCoreMessages.ExtractConstantRefactoring_select_expression);
    }

    return result;
  }
 /*
  * @see ASTVisitor#visit(ConstructorInvocation)
  */
 @Override
 public boolean visit(ConstructorInvocation node) {
   if (node.getAST().apiLevel() >= JLS3) {
     if (!node.typeArguments().isEmpty()) {
       this.fBuffer.append("<"); // $NON-NLS-1$
       for (Iterator<Type> it = node.typeArguments().iterator(); it.hasNext(); ) {
         Type t = it.next();
         t.accept(this);
         if (it.hasNext()) {
           this.fBuffer.append(","); // $NON-NLS-1$
         }
       }
       this.fBuffer.append(">"); // $NON-NLS-1$
     }
   }
   this.fBuffer.append("this("); // $NON-NLS-1$
   for (Iterator<Expression> it = node.arguments().iterator(); it.hasNext(); ) {
     Expression e = it.next();
     e.accept(this);
     if (it.hasNext()) {
       this.fBuffer.append(","); // $NON-NLS-1$
     }
   }
   this.fBuffer.append(");"); // $NON-NLS-1$
   return false;
 }
 /*
  * @see ASTVisitor#visit(SuperMethodInvocation)
  */
 @Override
 public boolean visit(SuperMethodInvocation node) {
   if (node.getQualifier() != null) {
     node.getQualifier().accept(this);
     this.fBuffer.append("."); // $NON-NLS-1$
   }
   this.fBuffer.append("super."); // $NON-NLS-1$
   if (node.getAST().apiLevel() >= JLS3) {
     if (!node.typeArguments().isEmpty()) {
       this.fBuffer.append("<"); // $NON-NLS-1$
       for (Iterator<Type> it = node.typeArguments().iterator(); it.hasNext(); ) {
         Type t = it.next();
         t.accept(this);
         if (it.hasNext()) {
           this.fBuffer.append(","); // $NON-NLS-1$
         }
       }
       this.fBuffer.append(">"); // $NON-NLS-1$
     }
   }
   node.getName().accept(this);
   this.fBuffer.append("("); // $NON-NLS-1$
   for (Iterator<Expression> it = node.arguments().iterator(); it.hasNext(); ) {
     Expression e = it.next();
     e.accept(this);
     if (it.hasNext()) {
       this.fBuffer.append(","); // $NON-NLS-1$
     }
   }
   this.fBuffer.append(")"); // $NON-NLS-1$
   return false;
 }
 @Override
 public boolean visit(SingleMemberAnnotation node) {
   if (nestLevel != 1) return false;
   String typeFqn = node.resolveTypeBinding().getQualifiedName();
   if ("org.apache.ibatis.annotations.Select".equals(typeFqn)
       || "org.apache.ibatis.annotations.Update".equals(typeFqn)
       || "org.apache.ibatis.annotations.Insert".equals(typeFqn)
       || "org.apache.ibatis.annotations.Delete".equals(typeFqn)) {
     Expression value = node.getValue();
     int valueType = value.getNodeType();
     if (valueType == ASTNode.STRING_LITERAL) {
       mapperMethod.setStatement(((StringLiteral) value).getLiteralValue());
     } else if (valueType == ASTNode.ARRAY_INITIALIZER) {
       StringBuilder buffer = new StringBuilder();
       @SuppressWarnings("unchecked")
       List<Expression> expressions =
           (List<Expression>) ((ArrayInitializer) value).expressions();
       for (Expression expression : expressions) {
         int expressionType = expression.getNodeType();
         if (expressionType == ASTNode.STRING_LITERAL) {
           if (buffer.length() > 0) buffer.append(' ');
           buffer.append(((StringLiteral) expression).getLiteralValue());
         } else if (expressionType == ASTNode.INFIX_EXPRESSION) {
           buffer.append(parseInfixExpression((InfixExpression) expression));
         }
       }
       mapperMethod.setStatement(buffer.toString());
     } else if (valueType == ASTNode.INFIX_EXPRESSION) {
       mapperMethod.setStatement(parseInfixExpression((InfixExpression) value));
     }
   }
   return false;
 }
  // 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);
    }
  }
Ejemplo n.º 9
0
  /**
   * Negates the provided expression and applies the provided copy operation on the returned
   * expression.
   *
   * @param expr the expression to negate
   * @param copy the copy operation to perform
   * @return the negated expression, copied according to the copy operation
   */
  public Expression negate(Expression expr, Copy copy) {
    final Expression exprNoParen = removeParentheses(expr);
    if (exprNoParen.getNodeType() == PREFIX_EXPRESSION) {
      final PrefixExpression pe = (PrefixExpression) exprNoParen;
      if (hasOperator(pe, NOT)) {
        return copy.perform(this, removeParentheses(pe.getOperand()));
      }
    }

    return not(parenthesizeIfNeeded(copy.perform(this, expr)));
  }
Ejemplo n.º 10
0
  public void testPartialCU1() throws Exception {
    IPackageFragment pack1 = fSourceFolder.createPackageFragment("test1", false, null);
    StringBuffer buf = new StringBuffer();
    buf.append("package test1;\n");
    buf.append("import java.util.Vector;\n");
    buf.append("public class E {\n");
    buf.append("    private int fField1;\n");
    buf.append("    private int fField2;\n");
    buf.append("    public void foo1() {\n");
    buf.append("        fField1 = fField2;\n");
    buf.append("    }\n");
    buf.append("    public int foo1(int i) {\n");
    buf.append("        return i;\n");
    buf.append("    }\n");
    buf.append("}");
    String existing = buf.toString();
    ICompilationUnit cu = pack1.createCompilationUnit("E.java", existing, false, null);

    String statement = "fField1 = fField2;";
    int offset = existing.indexOf(statement);

    CompilationUnit astRoot = getPartialCompilationUnit(cu, offset);
    String string = ASTNodes.asFormattedString(astRoot, 0, String.valueOf('\n'), null);

    buf = new StringBuffer();
    buf.append("package test1;\n");
    buf.append("import java.util.Vector;\n");
    buf.append("public class E {\n");
    buf.append("    private int fField1;\n");
    buf.append("    private int fField2;\n");
    buf.append("    public void foo1() {\n");
    buf.append("        fField1 = fField2;\n");
    buf.append("    }\n");
    buf.append("    public int foo1(int i) {\n");
    buf.append("    }\n");
    buf.append("}");
    String expected = buf.toString();

    assertEqualString(string, expected);

    offset = expected.indexOf(statement);

    ASTNode node = NodeFinder.perform(astRoot, offset, statement.length());
    Assignment assignment = (Assignment) ((ExpressionStatement) node).getExpression();
    Expression e1 = assignment.getLeftHandSide();
    Expression e2 = assignment.getRightHandSide();
    assertNotNull(e1.resolveTypeBinding());
    assertNotNull(e2.resolveTypeBinding());

    assertTrue(((SimpleName) e1).resolveBinding() instanceof IVariableBinding);
    assertTrue(((SimpleName) e2).resolveBinding() instanceof IVariableBinding);

    assertAllBindings(astRoot);
  }
 /*
  * @see ASTVisitor#visit(ArrayInitializer)
  */
 public boolean visit(ArrayInitializer node) {
   this.fBuffer.append("{"); // $NON-NLS-1$
   for (Iterator it = node.expressions().iterator(); it.hasNext(); ) {
     Expression e = (Expression) it.next();
     e.accept(this);
     if (it.hasNext()) {
       this.fBuffer.append(","); // $NON-NLS-1$
     }
   }
   this.fBuffer.append("}"); // $NON-NLS-1$
   return false;
 }
  // test is for fourth calloutMapping in Testdata (Role)
  public void testGetExpression_InstanceType3() {
    CalloutMappingDeclaration calloutDecl =
        (CalloutMappingDeclaration) _role.bodyDeclarations().get(7);
    List parameterMappings = calloutDecl.getParameterMappings();

    ParameterMapping testObj = (ParameterMapping) parameterMappings.get(0);
    Expression actual = (Expression) testObj.getExpression();

    assertTrue(
        "Wrong Type of given expression, type is  " + actual.getClass(),
        actual instanceof SimpleName);
  }
 /*
  * Visit the AST expression and get the ParseTree Expression.
  * This is used by the individual visits when parsing a tree.
  * It passes to the top method (createExpression), which can
  * handle the InvalidExpressionException.
  *
  * If any visit doesn't return an expression, then an invalid
  * expression exception will be thrown to indicate this. If the
  * incoming expression is <code>null</code>, then return of <code>null</code> is ok because
  * this would be for an optional expression which didn't exist.
  *
  * @return The new ParseTree Expression or <code>null</code> if incoming expression was null.
  *
  * @see createExpression(org.eclipse.jdt.core.dom.Expression)
  * @exception InvalidExpressionException
  * @since 1.0.0
  */
 protected final PTExpression perform(Expression astExpression) {
   if (astExpression != null) {
     expression = null;
     astExpression.accept(this);
     if (expression == null)
       throw new InvalidExpressionException(
           MessageFormat.format(
               WorkbenchUtilityMessages.ParseTreeCreationFromAST_ExpressionTooComplicated_EXC_,
               new Object[] {astExpression.toString()}));
     return expression;
   } else return null; // This is ok. It means an optional expression was being processed and the
   // expression didn't exist.
 }
 private boolean visitLiteral(Expression node) {
   fToken.update(node);
   for (int i = 0, n = fJobSemanticHighlightings.length; i < n; i++) {
     SemanticHighlighting semanticHighlighting = fJobSemanticHighlightings[i];
     if (fJobHighlightings[i].isEnabled() && semanticHighlighting.consumesLiteral(fToken)) {
       int offset = node.getStartPosition();
       int length = node.getLength();
       if (offset > -1 && length > 0) addPosition(offset, length, fJobHighlightings[i]);
       break;
     }
   }
   fToken.clear();
   return false;
 }
    /** {@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;
    }
  //	 !!! -- same as in ExtractTempRefactoring
  private boolean isLiteralNodeSelected() throws JavaModelException {
    IExpressionFragment fragment = getSelectedExpression();
    if (fragment == null) return false;
    Expression expression = fragment.getAssociatedExpression();
    if (expression == null) return false;
    switch (expression.getNodeType()) {
      case ASTNode.BOOLEAN_LITERAL:
      case ASTNode.CHARACTER_LITERAL:
      case ASTNode.NULL_LITERAL:
      case ASTNode.NUMBER_LITERAL:
        return true;

      default:
        return false;
    }
  }
 private ITypeBinding guessBindingForReference(Expression expression) {
   ITypeBinding binding = expression.resolveTypeBinding();
   if (binding == null) {
     binding = ASTResolving.guessBindingForReference(expression);
   }
   return binding;
 }
 /**
  * If given expression is constant value expression, return its value string; or return null.
  *
  * @param node
  * @return
  */
 protected String checkConstantValue(Expression node) {
   Object constValue = node.resolveConstantExpressionValue();
   if (constValue != null
       && (constValue instanceof Number
           || constValue instanceof Character
           || constValue instanceof Boolean)) {
     StringBuffer buffer = new StringBuffer();
     if (constValue instanceof Character) {
       buffer.append('\'');
       char charValue = ((Character) constValue).charValue();
       buffer.append(checkCharValue(charValue));
       buffer.append('\'');
     } else {
       buffer.append(constValue);
     }
     return buffer.toString();
   }
   if (constValue != null && (constValue instanceof String)) {
     StringBuffer buffer = new StringBuffer();
     String str = (String) constValue;
     int length = str.length();
     /*
     if (length > 20) {
     	return null;
     }*/
     buffer.append("\"");
     for (int i = 0; i < length; i++) {
       char c = str.charAt(i);
       buffer.append(checkCharValue(c));
     }
     buffer.append("\"");
     return buffer.toString();
   }
   return null;
 }
Ejemplo n.º 19
0
 @Override
 public int hashCode() {
   final int prime = 31;
   int result = 1;
   result = prime * result + ((matchExpression == null) ? 0 : matchExpression.hashCode());
   return result;
 }
 /**
  * Converts an assignment, postfix expression or prefix expression into an assignable equivalent
  * expression using the getter.
  *
  * @param node the assignment/prefix/postfix node
  * @param astRewrite the astRewrite to use
  * @param getterExpression the expression to insert for read accesses or <code>null</code> if such
  *     an expression does not exist
  * @param variableType the type of the variable that the result will be assigned to
  * @param is50OrHigher <code>true</code> if a 5.0 or higher environment can be used
  * @return an expression that can be assigned to the type variableType with node being replaced by
  *     a equivalent expression using the getter
  */
 public static Expression getAssignedValue(
     ASTNode node,
     ASTRewrite astRewrite,
     Expression getterExpression,
     ITypeBinding variableType,
     boolean is50OrHigher) {
   InfixExpression.Operator op = null;
   AST ast = astRewrite.getAST();
   if (isNotInBlock(node)) return null;
   if (node.getNodeType() == ASTNode.ASSIGNMENT) {
     Assignment assignment = ((Assignment) node);
     Expression rightHandSide = assignment.getRightHandSide();
     Expression copiedRightOp = (Expression) astRewrite.createCopyTarget(rightHandSide);
     if (assignment.getOperator() == Operator.ASSIGN) {
       ITypeBinding rightHandSideType = rightHandSide.resolveTypeBinding();
       copiedRightOp =
           createNarrowCastIfNessecary(
               copiedRightOp, rightHandSideType, ast, variableType, is50OrHigher);
       return copiedRightOp;
     }
     if (getterExpression != null) {
       InfixExpression infix = ast.newInfixExpression();
       infix.setLeftOperand(getterExpression);
       infix.setOperator(ASTNodes.convertToInfixOperator(assignment.getOperator()));
       infix.setRightOperand(copiedRightOp);
       ITypeBinding infixType = infix.resolveTypeBinding();
       return createNarrowCastIfNessecary(infix, infixType, ast, variableType, is50OrHigher);
     }
   } else if (node.getNodeType() == ASTNode.POSTFIX_EXPRESSION) {
     PostfixExpression po = (PostfixExpression) node;
     if (po.getOperator() == PostfixExpression.Operator.INCREMENT)
       op = InfixExpression.Operator.PLUS;
     if (po.getOperator() == PostfixExpression.Operator.DECREMENT)
       op = InfixExpression.Operator.MINUS;
   } else if (node.getNodeType() == ASTNode.PREFIX_EXPRESSION) {
     PrefixExpression pe = (PrefixExpression) node;
     if (pe.getOperator() == PrefixExpression.Operator.INCREMENT)
       op = InfixExpression.Operator.PLUS;
     if (pe.getOperator() == PrefixExpression.Operator.DECREMENT)
       op = InfixExpression.Operator.MINUS;
   }
   if (op != null && getterExpression != null) {
     return createInfixInvocationFromPostPrefixExpression(
         op, getterExpression, ast, variableType, is50OrHigher);
   }
   return null;
 }
  @Override
  public boolean visit(IfStatement node) {
    final ASTBuilder b = this.ctx.getASTBuilder();
    final Refactorings r = this.ctx.getRefactorings();

    final Statement thenStmt = node.getThenStatement();
    final Statement elseStmt = node.getElseStatement();
    final Expression condition = node.getExpression();
    if (elseStmt != null && asList(elseStmt).isEmpty()) {
      r.remove(elseStmt);
      return DO_NOT_VISIT_SUBTREE;
    } else if (thenStmt != null && asList(thenStmt).isEmpty()) {
      if (elseStmt != null) {
        r.replace(node, b.if0(b.negate(condition), b.move(elseStmt)));
      } else {
        final List<Expression> sideEffectExprs = new ArrayList<Expression>();
        collectSideEffects(condition, sideEffectExprs);
        if (!sideEffectExprs.isEmpty()) {
          for (Expression sideEffectExpr : sideEffectExprs) {
            r.insertBefore(b.toStmt(b.move(sideEffectExpr)), node);
          }
        }
        r.remove(node);
      }
      return DO_NOT_VISIT_SUBTREE;
    }

    final Object constantCondition = condition.resolveConstantExpressionValue();
    if (Boolean.TRUE.equals(constantCondition)) {
      r.replace(node, b.copy(thenStmt));
      if (lastStmtIsThrowOrReturn(thenStmt)) {
        r.remove(getNextSiblings(node));
      }
      return DO_NOT_VISIT_SUBTREE;
    } else if (Boolean.FALSE.equals(constantCondition)) {
      if (elseStmt != null) {
        r.replace(node, b.copy(elseStmt));
        if (lastStmtIsThrowOrReturn(elseStmt)) {
          r.remove(getNextSiblings(node));
        }
      } else {
        r.remove(node);
      }
      return DO_NOT_VISIT_SUBTREE;
    }
    return VISIT_SUBTREE;
  }
Ejemplo n.º 22
0
  @Override
  public boolean visit(NormalAnnotation node) {
    //
    // Test method?
    //
    if (isTestAnnotation(node.getTypeName().toString())) {
      ASTNode parent = node.getParent();
      if (parent instanceof MethodDeclaration) {
        addTestMethod((MethodDeclaration) parent, JDK15_ANNOTATION);
      } else if (parent instanceof TypeDeclaration) {
        m_typeIsTest = true;
        m_annotationType = JDK15_ANNOTATION;
      }

      List pairs = node.values();
      for (Iterator it = pairs.iterator(); it.hasNext(); ) {
        MemberValuePair mvp = (MemberValuePair) it.next();
        Name attribute = mvp.getName();
        String name = attribute.getFullyQualifiedName();
        if ("groups".equals(name)) {
          Expression value = mvp.getValue();
          // Array?
          if (value instanceof ArrayInitializer) {
            ArrayInitializer ai = (ArrayInitializer) value;
            List expressions = ai.expressions();
            for (Iterator it2 = expressions.iterator(); it2.hasNext(); ) {
              Expression e = (Expression) it2.next();
              addGroup(e.toString());
            }
          } else if (value instanceof SimpleName) {
            Object boundValue = value.resolveConstantExpressionValue();
            addGroup(boundValue.toString());
          } else if (value instanceof StringLiteral) {
            addGroup(value.toString());
          }
        }
      }
    } else if (isFactoryAnnotation(node.getTypeName().toString())) {
      if (node.getParent() instanceof MethodDeclaration) {
        m_annotationType = JDK15_ANNOTATION;
        addFactoryMethod((MethodDeclaration) node.getParent(), JDK15_ANNOTATION);
      }
    }

    return false;
  }
 /*
  * @see ASTVisitor#visit(InfixExpression)
  */
 public boolean visit(InfixExpression node) {
   node.getLeftOperand().accept(this);
   this.fBuffer.append(' '); // for cases like x= i - -1; or x= i++ + ++i;
   this.fBuffer.append(node.getOperator().toString());
   this.fBuffer.append(' ');
   node.getRightOperand().accept(this);
   final List extendedOperands = node.extendedOperands();
   if (extendedOperands.size() != 0) {
     this.fBuffer.append(' ');
     for (Iterator it = extendedOperands.iterator(); it.hasNext(); ) {
       this.fBuffer.append(node.getOperator().toString()).append(' ');
       Expression e = (Expression) it.next();
       e.accept(this);
     }
   }
   return false;
 }
 /* (non-Javadoc)
  * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.ArrayAccess)
  */
 public boolean visit(ArrayAccess node) {
   PTArrayAccess aa = InstantiationFactory.eINSTANCE.createPTArrayAccess();
   List indexes = aa.getIndexes();
   Expression arrayExp = node;
   while (arrayExp.getNodeType() == ASTNode.ARRAY_ACCESS) {
     // Visit the index to get the index expression.
     ArrayAccess array = (ArrayAccess) arrayExp;
     indexes.add(
         0,
         perform(
             array
                 .getIndex())); // We're trying to create the final expression from inside out, the
     // indexes are created in reverse order.
     arrayExp = array.getArray();
   }
   aa.setArray(perform(arrayExp)); // Final arrayExp is the true expression.
   expression = aa; // Set the return expression for this visit.
   return false;
 }
 /*
  * @see ASTVisitor#visit(ForStatement)
  */
 public boolean visit(ForStatement node) {
   this.fBuffer.append("for ("); // $NON-NLS-1$
   for (Iterator it = node.initializers().iterator(); it.hasNext(); ) {
     Expression e = (Expression) it.next();
     e.accept(this);
   }
   this.fBuffer.append("; "); // $NON-NLS-1$
   if (node.getExpression() != null) {
     node.getExpression().accept(this);
   }
   this.fBuffer.append("; "); // $NON-NLS-1$
   for (Iterator it = node.updaters().iterator(); it.hasNext(); ) {
     Expression e = (Expression) it.next();
     e.accept(this);
   }
   this.fBuffer.append(") "); // $NON-NLS-1$
   node.getBody().accept(this);
   return false;
 }
 /**
  * If the passed node is a method invocation or class creation then return the return type of the
  * method based on what is the returned value assigned to.
  *
  * @param node
  * @return return type
  */
 private String getReturnType(Expression node) {
   ASTNode parent = node.getParent();
   if (parent instanceof VariableDeclarationFragment) {
     ASTNode grandParent = parent.getParent();
     if (grandParent instanceof VariableDeclarationStatement) {
       Type typ = ((VariableDeclarationStatement) grandParent).getType();
       return removeSpecialSymbols(getFullyQualifiedNameFor(typ.toString()));
     }
   }
   return null;
 }
Ejemplo n.º 27
0
 @Override
 public boolean equals(Object obj) {
   if (this == obj) return true;
   if (obj == null) return false;
   if (getClass() != obj.getClass()) return false;
   final SwitchLabel other = (SwitchLabel) obj;
   if (matchExpression == null) {
     if (other.matchExpression != null) return false;
   } else if (!matchExpression.equals(other.matchExpression)) return false;
   return true;
 }
  private SingleVariableDeclaration createParameterDeclaration(
      String parameterName,
      VariableDeclarationFragment fragement,
      Expression arrayAccess,
      ForStatement statement,
      ImportRewrite importRewrite,
      ASTRewrite rewrite,
      TextEditGroup group,
      LinkedProposalPositionGroup pg,
      boolean makeFinal) {
    CompilationUnit compilationUnit = (CompilationUnit) arrayAccess.getRoot();
    AST ast = compilationUnit.getAST();

    SingleVariableDeclaration result = ast.newSingleVariableDeclaration();

    SimpleName name = ast.newSimpleName(parameterName);
    pg.addPosition(rewrite.track(name), true);
    result.setName(name);

    ITypeBinding arrayTypeBinding = arrayAccess.resolveTypeBinding();
    Type type =
        importType(arrayTypeBinding.getElementType(), statement, importRewrite, compilationUnit);
    if (arrayTypeBinding.getDimensions() != 1) {
      type = ast.newArrayType(type, arrayTypeBinding.getDimensions() - 1);
    }
    result.setType(type);

    if (fragement != null) {
      VariableDeclarationStatement declaration =
          (VariableDeclarationStatement) fragement.getParent();
      ModifierRewrite.create(rewrite, result).copyAllModifiers(declaration, group);
    }
    if (makeFinal
        && (fragement == null
            || ASTNodes.findModifierNode(Modifier.FINAL, ASTNodes.getModifiers(fragement))
                == null)) {
      ModifierRewrite.create(rewrite, result).setModifiers(Modifier.FINAL, 0, group);
    }

    return result;
  }
 @Override
 public String getIntroducedVariableName() {
   if (fElementDeclaration != null) {
     return fElementDeclaration.getName().getIdentifier();
   } else {
     ForStatement forStatement = getForStatement();
     IJavaProject javaProject =
         ((CompilationUnit) forStatement.getRoot()).getJavaElement().getJavaProject();
     String[] proposals = getVariableNameProposals(fArrayAccess.resolveTypeBinding(), javaProject);
     return proposals[0];
   }
 }
  @Override
  protected Statement convert(
      CompilationUnitRewrite cuRewrite, TextEditGroup group, LinkedProposalModel positionGroups)
      throws CoreException {
    ASTRewrite rewrite = cuRewrite.getASTRewrite();
    ImportRewrite importRewrite = cuRewrite.getImportRewrite();

    ForStatement forStatement = getForStatement();

    IJavaProject javaProject =
        ((CompilationUnit) forStatement.getRoot()).getJavaElement().getJavaProject();
    String[] proposals = getVariableNameProposals(fArrayAccess.resolveTypeBinding(), javaProject);

    String parameterName;
    if (fElementDeclaration != null) {
      parameterName = fElementDeclaration.getName().getIdentifier();
    } else {
      parameterName = proposals[0];
    }

    LinkedProposalPositionGroup pg = positionGroups.getPositionGroup(parameterName, true);
    if (fElementDeclaration != null) pg.addProposal(parameterName, null, 10);
    for (int i = 0; i < proposals.length; i++) {
      pg.addProposal(proposals[i], null, 10);
    }

    AST ast = forStatement.getAST();
    EnhancedForStatement result = ast.newEnhancedForStatement();

    SingleVariableDeclaration parameterDeclaration =
        createParameterDeclaration(
            parameterName,
            fElementDeclaration,
            fArrayAccess,
            forStatement,
            importRewrite,
            rewrite,
            group,
            pg,
            fMakeFinal);
    result.setParameter(parameterDeclaration);

    result.setExpression((Expression) rewrite.createCopyTarget(fArrayAccess));

    convertBody(
        forStatement.getBody(), fIndexBinding, fArrayBinding, parameterName, rewrite, group, pg);
    result.setBody(getBody(cuRewrite, group, positionGroups));

    positionGroups.setEndPosition(rewrite.track(result));

    return result;
  }