コード例 #1
0
ファイル: BindingUtil.java プロジェクト: mmaxiaolei/j2objc
 private static void appendParameterSignature(ITypeBinding parameter, StringBuilder sb) {
   if (!parameter.isPrimitive() && !parameter.isArray()) {
     sb.append('L');
   }
   sb.append(parameter.getBinaryName().replace('.', '/'));
   if (!parameter.isPrimitive() && !parameter.isArray()) {
     sb.append(';');
   }
 }
コード例 #2
0
 // 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()));
     }
   }
 }
コード例 #3
0
ファイル: TypeName.java プロジェクト: janblok/docgenerator-ui
 public TypeName(ITypeBinding binding, boolean varargs) {
   this.varargs = varargs;
   ITypeBinding inner = binding;
   if (varargs) {
     dimensions = 1;
   } else {
     int dims = 0;
     while (inner.isArray()) {
       inner = inner.getComponentType();
       dims += 1;
     }
     dimensions = dims;
   }
   if (inner.isParameterizedType()) {
     inner = inner.getErasure();
   }
   ITypeBinding parent = inner;
   int nesting = 0;
   while (parent.isNested()) {
     nesting++;
     parent = parent.getDeclaringClass();
   }
   nestingLevel = nesting;
   primitive = inner.isPrimitive();
   baseQualifiedName = adaptQualifiedName(inner.getQualifiedName());
   baseBinaryName = inner.getBinaryName();
   shortName = buildShortName();
   qualifiedName = buildQualifiedName();
   binaryName = buildBinaryName();
 }
コード例 #4
0
ファイル: TypeURIHelper.java プロジェクト: iloveeclipse/xtext
 /** @since 2.4 */
 protected URI getFullURI(ITypeBinding typeBinding, SegmentSequence.Builder builder) {
   if (typeBinding.isPrimitive()) {
     builder.append(PRIMITIVE_URIS[typeBinding.getKey().charAt(0) - 'B'].fragment());
     return PRIMITIVES_URI;
   }
   if (typeBinding.isClass()
       || typeBinding.isInterface()
       || typeBinding.isAnnotation()
       || typeBinding.isEnum()) {
     ITypeBinding declaringClass = typeBinding.getDeclaringClass();
     if (declaringClass != null) {
       URI uri = getFullURI(declaringClass, builder);
       builder.append("$");
       builder.append(typeBinding.getName());
       return uri;
     }
     String qualifiedName = typeBinding.getErasure().getQualifiedName();
     URI uri = COMMON_URIS.get(qualifiedName);
     if (uri == null) {
       uri = OBJECTS_URI.appendSegment(qualifiedName);
     }
     builder.append(uri.lastSegment());
     return uri;
   }
   if (typeBinding.isArray()) {
     URI uri = getFullURI(typeBinding.getComponentType(), builder);
     builder.append("[]");
     return uri;
   }
   if (typeBinding.isTypeVariable()) {
     ITypeBinding declaringClass = typeBinding.getDeclaringClass();
     if (declaringClass != null) {
       URI uri = getFullURI(declaringClass, builder);
       builder.append("/");
       builder.append(typeBinding.getName());
       return uri;
     }
     IMethodBinding declaringMethod = typeBinding.getDeclaringMethod();
     URI uri = getFullURI(declaringMethod.getDeclaringClass(), builder);
     builder.append(".");
     builder.append(declaringMethod.getName());
     builder.append("(");
     ITypeBinding[] parameterTypes = declaringMethod.getParameterTypes();
     for (int i = 0; i < parameterTypes.length; i++) {
       if (i != 0) {
         builder.append(",");
       }
       getQualifiedName(parameterTypes[i], builder);
     }
     builder.append(")");
     builder.append("/");
     builder.append(typeBinding.getName());
     return uri;
   }
   throw new IllegalStateException("Unexpected type: " + typeBinding);
 }
コード例 #5
0
  /*
   * Must be one of:
   * <ul>
   * <li>[result].length</li>
   * </ul>
   */
  private boolean validateLengthQuery(Expression lengthQuery) {
    if (lengthQuery instanceof QualifiedName) {
      QualifiedName qualifiedName = (QualifiedName) lengthQuery;
      SimpleName name = qualifiedName.getName();
      if (!LENGTH_QUERY.equals(name.getIdentifier())) return false;

      Name arrayAccess = qualifiedName.getQualifier();
      ITypeBinding accessType = arrayAccess.resolveTypeBinding();
      if (accessType == null) return false;

      if (!accessType.isArray()) return false;

      IBinding arrayBinding = arrayAccess.resolveBinding();
      if (arrayBinding == null) return false;

      fArrayBinding = arrayBinding;
      fArrayAccess = arrayAccess;
      return true;
    } else if (lengthQuery instanceof FieldAccess) {
      FieldAccess fieldAccess = (FieldAccess) lengthQuery;
      SimpleName name = fieldAccess.getName();
      if (!LENGTH_QUERY.equals(name.getIdentifier())) return false;

      Expression arrayAccess = fieldAccess.getExpression();
      ITypeBinding accessType = arrayAccess.resolveTypeBinding();
      if (accessType == null) return false;

      if (!accessType.isArray()) return false;

      IBinding arrayBinding = getBinding(arrayAccess);
      if (arrayBinding == null) return false;

      fArrayBinding = arrayBinding;
      fArrayAccess = arrayAccess;
      return true;
    }

    return false;
  }
コード例 #6
0
ファイル: TypeURIHelper.java プロジェクト: iloveeclipse/xtext
 /** @since 2.4 */
 protected SegmentSequence.Builder getQualifiedName(
     ITypeBinding binding, SegmentSequence.Builder builder) {
   if (binding.isParameterizedType()) {
     getQualifiedName(binding.getErasure(), builder);
   } else if (binding.isArray()) {
     getQualifiedName(binding.getComponentType(), builder).append("[]");
   } else if (binding.isTopLevel() || binding.isTypeVariable() || binding.isPrimitive()) {
     builder.append(binding.getQualifiedName());
   } else {
     getQualifiedName(binding.getDeclaringClass(), builder).append('$').append(binding.getName());
   }
   return builder;
 }
コード例 #7
0
ファイル: CastResolver.java プロジェクト: hellojory/j2objc
 private FunctionInvocation createCastCheck(ITypeBinding type, Expression expr) {
   type = type.getErasure();
   ITypeBinding idType = typeEnv.resolveIOSType("id");
   FunctionInvocation invocation = null;
   if ((type.isInterface() && !type.isAnnotation())
       || (type.isArray() && !type.getComponentType().isPrimitive())) {
     FunctionBinding binding = new FunctionBinding("cast_check", idType, null);
     binding.addParameters(idType, typeEnv.getIOSClass());
     invocation = new FunctionInvocation(binding, idType);
     invocation.getArguments().add(TreeUtil.remove(expr));
     invocation.getArguments().add(new TypeLiteral(type, typeEnv));
   } else if (type.isClass() || type.isArray() || type.isAnnotation() || type.isEnum()) {
     FunctionBinding binding = new FunctionBinding("cast_chk", idType, null);
     binding.addParameters(idType, idType);
     invocation = new FunctionInvocation(binding, idType);
     invocation.getArguments().add(TreeUtil.remove(expr));
     IOSMethodBinding classBinding =
         IOSMethodBinding.newMethod("class", Modifier.STATIC, idType, type);
     MethodInvocation classInvocation = new MethodInvocation(classBinding, new SimpleName(type));
     invocation.getArguments().add(classInvocation);
   }
   return invocation;
 }
コード例 #8
0
ファイル: TypeURIHelper.java プロジェクト: iloveeclipse/xtext
 /** @since 2.4 */
 public StringBuilder getQualifiedName(ITypeBinding binding, StringBuilder stringBuilder) {
   if (binding.isParameterizedType()) {
     getQualifiedName(binding.getErasure(), stringBuilder);
   } else if (binding.isArray()) {
     getQualifiedName(binding.getComponentType(), stringBuilder).append("[]");
   } else if (binding.isTopLevel() || binding.isTypeVariable() || binding.isPrimitive()) {
     stringBuilder.append(binding.getQualifiedName());
   } else {
     getQualifiedName(binding.getDeclaringClass(), stringBuilder)
         .append('$')
         .append(binding.getName());
   }
   return stringBuilder;
 }
コード例 #9
0
ファイル: TypeURIHelper.java プロジェクト: iloveeclipse/xtext
 public String getQualifiedName(ITypeBinding binding) {
   if (binding.isParameterizedType()) {
     return getQualifiedName(binding.getErasure());
   }
   if (binding.isArray()) {
     return getQualifiedName(binding.getComponentType(), new StringBuilder())
         .append("[]")
         .toString();
   }
   if (binding.isTopLevel() || binding.isTypeVariable() || binding.isPrimitive())
     return binding.getQualifiedName();
   return getQualifiedName(binding.getDeclaringClass(), new StringBuilder())
       .append('$')
       .append(binding.getName())
       .toString();
 }
コード例 #10
0
ファイル: Types.java プロジェクト: hellojory/j2objc
 /**
  * Given a JDT type binding created by the parser, either replace it with an iOS equivalent, or
  * return the given type.
  */
 public ITypeBinding mapType(ITypeBinding binding) {
   if (binding == null) { // happens when mapping a primitive type
     return null;
   }
   // getTypeDeclaration will return the canonical binding for the type with
   // type parameters and type annotations removed. Note that getErasure() does
   // not strip type annotations.
   binding = binding.getTypeDeclaration();
   if (binding.isArray()) {
     return resolveArrayType(binding.getComponentType());
   }
   ITypeBinding newBinding = typeMap.get(binding);
   if (newBinding == null && binding.isAssignmentCompatible(javaClassType)) {
     newBinding = typeMap.get(javaClassType);
   }
   return newBinding != null ? newBinding : binding;
 }
コード例 #11
0
ファイル: TypeURIHelper.java プロジェクト: iloveeclipse/xtext
 protected void createResourceURI(ITypeBinding typeBinding, StringBuilder uriBuilder) {
   if (typeBinding.isPrimitive()) {
     createResourceURIForPrimitive(uriBuilder);
     return;
   }
   if (typeBinding.isClass()
       || typeBinding.isInterface()
       || typeBinding.isAnnotation()
       || typeBinding.isEnum()) {
     createResourceURIForClass(typeBinding, uriBuilder);
     return;
   }
   if (typeBinding.isArray()) {
     createResourceURIForArray(typeBinding, uriBuilder);
     return;
   }
   if (typeBinding.isTypeVariable()) {
     createResourceURIForTypeVariable(typeBinding, uriBuilder);
     return;
   }
   throw new IllegalStateException("Unexpected type: " + typeBinding);
 }
コード例 #12
0
  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;
  }
コード例 #13
0
  private ClipboardData getClipboardData(ITypeRoot inputElement, int offset, int length) {
    CompilationUnit astRoot =
        SharedASTProvider.getAST(inputElement, SharedASTProvider.WAIT_ACTIVE_ONLY, null);
    if (astRoot == null) {
      return null;
    }

    // do process import if selection spans over import declaration or package
    List<ImportDeclaration> list = astRoot.imports();
    if (!list.isEmpty()) {
      if (offset < ((ASTNode) list.get(list.size() - 1)).getStartPosition()) {
        return null;
      }
    } else if (astRoot.getPackage() != null) {
      if (offset < ((ASTNode) astRoot.getPackage()).getStartPosition()) {
        return null;
      }
    }

    ArrayList<SimpleName> typeImportsRefs = new ArrayList<SimpleName>();
    ArrayList<SimpleName> staticImportsRefs = new ArrayList<SimpleName>();

    ImportReferencesCollector.collect(
        astRoot,
        inputElement.getJavaProject(),
        new Region(offset, length),
        typeImportsRefs,
        staticImportsRefs);

    if (typeImportsRefs.isEmpty() && staticImportsRefs.isEmpty()) {
      return null;
    }

    HashSet<String> namesToImport = new HashSet<String>(typeImportsRefs.size());
    for (int i = 0; i < typeImportsRefs.size(); i++) {
      Name curr = typeImportsRefs.get(i);
      IBinding binding = curr.resolveBinding();
      if (binding != null && binding.getKind() == IBinding.TYPE) {
        ITypeBinding typeBinding = (ITypeBinding) binding;
        if (typeBinding.isArray()) {
          typeBinding = typeBinding.getElementType();
        }
        if (typeBinding.isTypeVariable()
            || typeBinding.isCapture()
            || typeBinding.isWildcardType()) { // can be removed when bug 98473 is fixed
          continue;
        }

        if (typeBinding.isMember() || typeBinding.isTopLevel()) {
          String name = Bindings.getRawQualifiedName(typeBinding);
          if (name.length() > 0) {
            namesToImport.add(name);
          }
        }
      }
    }

    HashSet<String> staticsToImport = new HashSet<String>(staticImportsRefs.size());
    for (int i = 0; i < staticImportsRefs.size(); i++) {
      Name curr = staticImportsRefs.get(i);
      IBinding binding = curr.resolveBinding();
      if (binding != null) {
        StringBuffer buf = new StringBuffer(Bindings.getImportName(binding));
        if (binding.getKind() == IBinding.METHOD) {
          buf.append("()"); // $NON-NLS-1$
        }
        staticsToImport.add(buf.toString());
      }
    }

    if (namesToImport.isEmpty() && staticsToImport.isEmpty()) {
      return null;
    }

    String[] typeImports = namesToImport.toArray(new String[namesToImport.size()]);
    String[] staticImports = staticsToImport.toArray(new String[staticsToImport.size()]);
    return new ClipboardData(inputElement, typeImports, staticImports);
  }
コード例 #14
0
ファイル: Types.java プロジェクト: hellojory/j2objc
 /** Returns whether a given type has an iOS equivalent. */
 public boolean hasIOSEquivalent(ITypeBinding binding) {
   return binding.isArray() || typeMap.containsKey(binding.getTypeDeclaration());
 }
コード例 #15
0
ファイル: TypeName.java プロジェクト: janblok/docgenerator-ui
 /**
  * Create an instance based on a JDT type.
  *
  * <p>The location, context and warnings parameters are used for raising warnings when the type
  * bindings cannot be resolved.
  */
 public TypeName(
     Type t,
     boolean varargs,
     String location,
     String context,
     Set<DocumentationWarning> warnings) {
   this.varargs = varargs;
   // Try to resolve the binding.
   ITypeBinding binding = t.resolveBinding();
   // If binding was resolved, then use it to extract the names.
   if (binding != null) {
     ITypeBinding inner = binding;
     if (varargs) {
       dimensions = 1;
     } else {
       int dims = 0;
       while (inner.isArray()) {
         inner = inner.getComponentType();
         dims += 1;
       }
       dimensions = dims;
     }
     if (inner.isParameterizedType()) {
       inner = inner.getErasure();
     }
     ITypeBinding parent = inner;
     int nesting = 0;
     while (parent.isNested()) {
       nesting++;
       parent = parent.getDeclaringClass();
     }
     nestingLevel = nesting;
     primitive = inner.isPrimitive();
     baseQualifiedName = adaptQualifiedName(inner.getQualifiedName());
     baseBinaryName = inner.getBinaryName();
   }
   // If the binding was not resolved, then use the type name anyway.
   // This may not be accurate, but is better than nothing.
   // Also raise a warning in this case.
   else {
     String rawName = t.toString();
     int idx = rawName.indexOf("[");
     if (idx >= 0) {
       baseQualifiedName = rawName.substring(0, idx);
       String dimPart = rawName.substring(idx);
       dimensions = dimPart.length() / 2;
     } else {
       baseQualifiedName = rawName;
       dimensions = 0;
     }
     nestingLevel = 0;
     baseBinaryName = baseQualifiedName;
     primitive = t.isPrimitiveType();
     DocumentationWarning dw =
         new DocumentationWarning(
             WarningType.UnresolvedBinding,
             location,
             "Cannot resolve binding for " + context + " type: '" + baseQualifiedName + "'.");
     warnings.add(dw);
   }
   shortName = buildShortName();
   qualifiedName = buildQualifiedName();
   binaryName = buildBinaryName();
 }