// Função auxiliar para copiar o tipo da variável
 // considerando que um tipo nao pode pertencer a outra AST
 private Type getType(ITypeBinding typeBinding, AST newAST) {
   if (typeBinding.isPrimitive()) {
     return newAST.newPrimitiveType(PrimitiveType.toCode(typeBinding.getName()));
   } else if (typeBinding.isArray()) {
     return newAST.newArrayType(
         this.getType(typeBinding.getElementType(), newAST), typeBinding.getDimensions());
   } else if (typeBinding.isParameterizedType()) {
     ParameterizedType pt =
         newAST.newParameterizedType(this.getType(typeBinding.getTypeDeclaration(), newAST));
     for (ITypeBinding itb : typeBinding.getTypeArguments()) {
       pt.typeArguments().add(this.getType(itb, newAST));
     }
     return pt;
   } else if (typeBinding.isWildcardType()) {
     WildcardType wt = newAST.newWildcardType();
     wt.setBound(
         typeBinding.getBound() == null ? null : this.getType(typeBinding.getBound(), newAST),
         typeBinding.isUpperbound());
     return wt;
   } else {
     try {
       return newAST.newSimpleType(newAST.newName(typeBinding.getQualifiedName()));
     } catch (Exception e) {
       return newAST.newSimpleType(newAST.newName(typeBinding.getName()));
     }
   }
 }
  private Type evaluateVariableType(
      AST ast,
      ImportRewrite imports,
      ImportRewriteContext importRewriteContext,
      IBinding targetContext) {
    if (fOriginalNode.getParent() instanceof MethodInvocation) {
      MethodInvocation parent = (MethodInvocation) fOriginalNode.getParent();
      if (parent.getExpression() == fOriginalNode) {
        // _x_.foo() -> guess qualifier type by looking for a type with method 'foo'
        ITypeBinding[] bindings =
            ASTResolving.getQualifierGuess(
                fOriginalNode.getRoot(),
                parent.getName().getIdentifier(),
                parent.arguments(),
                targetContext);
        if (bindings.length > 0) {
          for (int i = 0; i < bindings.length; i++) {
            addLinkedPositionProposal(KEY_TYPE, bindings[i]);
          }
          return imports.addImport(bindings[0], ast, importRewriteContext);
        }
      }
    }

    ITypeBinding binding = ASTResolving.guessBindingForReference(fOriginalNode);
    if (binding != null) {
      if (binding.isWildcardType()) {
        binding = ASTResolving.normalizeWildcardType(binding, isVariableAssigned(), ast);
        if (binding == null) {
          // only null binding applies
          binding = ast.resolveWellKnownType("java.lang.Object"); // $NON-NLS-1$
        }
      }

      if (isVariableAssigned()) {
        ITypeBinding[] typeProposals = ASTResolving.getRelaxingTypes(ast, binding);
        for (int i = 0; i < typeProposals.length; i++) {
          addLinkedPositionProposal(KEY_TYPE, typeProposals[i]);
        }
      }
      return imports.addImport(binding, ast, importRewriteContext);
    }
    // no binding, find type AST node instead -> ABC a= x-> use 'ABC' as is
    Type type = ASTResolving.guessTypeForReference(ast, fOriginalNode);
    if (type != null) {
      return type;
    }
    if (fVariableKind == CONST_FIELD) {
      return ast.newSimpleType(ast.newSimpleName("String")); // $NON-NLS-1$
    }
    return ast.newSimpleType(ast.newSimpleName("Object")); // $NON-NLS-1$
  }
Ejemplo n.º 3
0
 private Type type(String typeName) {
   final String[] names = typeName.split("\\.");
   if (names.length == 1) {
     return ast.newSimpleType(ast.newSimpleName(names[0]));
   } else {
     throw new NotImplementedException(null);
   }
 }
  /**
   * Create an AST type node with a type string (possibly partitioned with "." and "[]").
   *
   * @param ast The {@link org.eclipse.jdt.core.dom.AST} object.
   * @param type The type.
   * @return The AST type node.
   */
  public static org.eclipse.jdt.core.dom.Type createType(AST ast, String type) {
    String elementName = Type.getElementType(type);

    org.eclipse.jdt.core.dom.Type elementType;

    if (Type.isPrimitive(elementName)) {
      elementType = ast.newPrimitiveType(PrimitiveType.toCode(elementName));
    } else {
      Name element = createName(ast, elementName);
      elementType = ast.newSimpleType(element);
    }

    org.eclipse.jdt.core.dom.Type returnType = elementType;

    for (int i = 0; i < Type.dimensions(type); i++) {
      returnType = ast.newArrayType(returnType);
    }

    return returnType;
  }
  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;
  }
Ejemplo n.º 6
0
 public SingleVariableDeclaration newVariableDecl(String name, String type) {
   SingleVariableDeclaration exceptionDecl = ast.newSingleVariableDeclaration();
   exceptionDecl.setName(ast.newSimpleName(name));
   exceptionDecl.setType(ast.newSimpleType(ast.newName(type)));
   return exceptionDecl;
 }
Ejemplo n.º 7
0
 public Type newType(String typeName) {
   return ast.newSimpleType(ast.newName(typeName));
 }
Ejemplo n.º 8
0
 private SimpleType newSimpleType(final String typeName) {
   return ast.newSimpleType(ast.newName(typeName));
 }
Ejemplo n.º 9
0
  private static Type resolveQualifiedType(String s) {

    if (s.equals("byte")) {
      return AST.newAST(AST.JLS8).newPrimitiveType(PrimitiveType.BYTE);
    }

    if (s.equals("")) {
      return AST.newAST(AST.JLS8).newWildcardType();
    }

    // It's a type parameter
    if (s.contains("<") && s.contains(">")) {
      // TODO: resolve type parameters
      String s0 = s.substring(0, s.indexOf("<"));
      Type hd = resolveQualifiedType(s0);
      AST tAST = AST.newAST(AST.JLS8);
      ParameterizedType pt = tAST.newParameterizedType((Type) ASTNode.copySubtree(tAST, hd));

      for (String i : splitTypeArgs(s.substring(s.indexOf("<") + 1, s.lastIndexOf(">")))) {
        pt.typeArguments().add(ASTNode.copySubtree(tAST, resolveQualifiedType(i)));
      }
      return pt;
    }

    // It's an array type
    if (s.contains("[") && s.contains("]")) {
      String s0 = s.substring(0, s.indexOf("["));
      Type hd = resolveQualifiedType(s0);
      AST tast = AST.newAST(AST.JLS8);
      ArrayType pt = tast.newArrayType((Type) ASTNode.copySubtree(tast, hd));
      return pt;
    }

    if (!s.contains(".")) {
      AST ast = AST.newAST(AST.JLS8);
      if (s == null || s.equals("null")) {
        return ast.newSimpleType((Name) ASTNode.copySubtree(ast, genSimpleName("String")));
      }
      switch (s) {
        case "void":
          return AST.newAST(AST.JLS8).newPrimitiveType(PrimitiveType.VOID);
        case "int":
          return AST.newAST(AST.JLS8).newPrimitiveType(PrimitiveType.INT);
        case "char":
          return AST.newAST(AST.JLS8).newPrimitiveType(PrimitiveType.CHAR);
        case "long":
          return AST.newAST(AST.JLS8).newPrimitiveType(PrimitiveType.LONG);
        case "boolean":
          return AST.newAST(AST.JLS8).newPrimitiveType(PrimitiveType.BOOLEAN);
        case "float":
          return AST.newAST(AST.JLS8).newPrimitiveType(PrimitiveType.FLOAT);
        case "short":
          return AST.newAST(AST.JLS8).newPrimitiveType(PrimitiveType.SHORT);
        case "byte":
          return AST.newAST(AST.JLS8).newPrimitiveType(PrimitiveType.BYTE);
        case "double":
          return AST.newAST(AST.JLS8).newPrimitiveType(PrimitiveType.DOUBLE);
      }
      return ast.newSimpleType((Name) ASTNode.copySubtree(ast, genSimpleName(s)));
    } else {
      int last = s.lastIndexOf(".");
      AST ast = AST.newAST(AST.JLS8);
      String lastFrag = s.substring(last + 1);
      return ast.newQualifiedType(
          (Type) ASTNode.copySubtree(ast, resolveQualifiedType(s.substring(0, last))),
          (SimpleName) ASTNode.copySubtree(ast, genSimpleName(lastFrag)));
    }
  }
Ejemplo n.º 10
0
  @SuppressWarnings("unchecked")
  @Before
  public void setUp() {
    manager = ModelManager.getInstance();
    manager.clearModel();

    AST ast2 = AST.newAST(AST.JLS3);
    CompilationUnit cu2 = ast2.newCompilationUnit();
    PackageDeclaration pack2 = ast2.newPackageDeclaration();
    pack2.setName(ast2.newName("be.ac.ua.test.otherpack"));
    cu2.setPackage(pack2);
    TypeDeclaration type2 = ast2.newTypeDeclaration();
    type2.setName(ast2.newSimpleName("Foo"));

    cu2.types().add(type2); // created mock compilationunit containing package and class

    PackageRecorder prec2 = new PackageRecorder(pack2);
    prec2.storeChange(new Add()); // store the package addition
    ClassRecorder crec2 = new ClassRecorder(type2);
    declaredclassadd = new Add();
    crec2.storeChange(declaredclassadd);

    AST ast = AST.newAST(AST.JLS3);
    CompilationUnit cu = ast.newCompilationUnit();
    PackageDeclaration pack = ast.newPackageDeclaration();
    pack.setName(ast.newName(packname));
    cu.setPackage(pack);
    TypeDeclaration type = ast.newTypeDeclaration();
    type.setName(ast.newSimpleName(classname));

    cu.types().add(type);

    PackageRecorder prec = new PackageRecorder(pack);
    prec.storeChange(new Add()); // store the package addition
    ClassRecorder crec = new ClassRecorder(type);
    classadd = new Add();
    crec.storeChange(classadd);

    // Class and package created and changes logged, now create the Field.

    VariableDeclarationFragment frag1 = ast.newVariableDeclarationFragment();
    frag1.setName(ast.newSimpleName(intfieldname));
    FieldDeclaration field = ast.newFieldDeclaration(frag1);
    field.setType(ast.newPrimitiveType(PrimitiveType.INT)); // field has type int
    type.bodyDeclarations().add(field);

    VariableDeclarationFragment frag2 = ast.newVariableDeclarationFragment();
    frag2.setName(ast.newSimpleName(fieldname));
    FieldDeclaration field2 = ast.newFieldDeclaration(frag2);
    field2.setType(ast.newSimpleType(ast.newName(declaredTypeName))); // field has type Foo
    type.bodyDeclarations().add(field2);

    VariableDeclarationFragment frag3 = ast.newVariableDeclarationFragment();
    frag3.setName(ast.newSimpleName(field3Name));
    FieldDeclaration field3 = ast.newFieldDeclaration(frag3);
    field3.setType(ast.newSimpleType(ast.newName("Foo"))); // field has type Foo
    type.bodyDeclarations().add(field3);

    ImportDeclaration imp = ast.newImportDeclaration();
    imp.setName(ast.newName(declaredTypeName));
    cu.imports().add(imp);

    // created mock compilationunit containing package and class

    recorder1 = new FieldRecorder(field);
    recorder2 = new FieldRecorder(field2);
    recorder3 = new FieldRecorder(field3);
  }