// We generate the runtime debug method -memDebugStrongReferences.
 // This method will return an array of information about a strong reference,
 // including pointer to object and name.
 private void printStrongReferencesMethod(List<VariableDeclarationFragment> properties) {
   if (Options.memoryDebug()) {
     if (!Options.useReferenceCounting()) {
       println("- (NSArray *)memDebugStrongReferences {");
       println("  return nil;");
       println("}");
       return;
     }
     println("- (NSArray *)memDebugStrongReferences {");
     println("  NSMutableArray *result =");
     println("      [[[super memDebugStrongReferences] mutableCopy] autorelease];");
     for (VariableDeclarationFragment property : properties) {
       String propName = NameTable.getName(property.getName());
       String objCFieldName = NameTable.javaFieldToObjC(propName);
       if (isStrongReferenceProperty(property)) {
         println(
             String.format(
                 "  [result addObject:[JreMemDebugStrongReference "
                     + "strongReferenceWithObject:%s name:@\"%s\"]];",
                 objCFieldName, propName));
       }
     }
     println("  return result;");
     println("}\n");
   }
 }
 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;
 }
  /* bd is a static field declaration or static initializer */
  private static boolean depends(IExpressionFragment selected, BodyDeclaration bd) {
    /* We currently consider selected to depend on bd only if db includes a declaration
     * of a static field on which selected depends.
     *
     * A more accurate strategy might be to also check if bd contains (or is) a
     * static initializer containing code which changes the value of a static field on
     * which selected depends.  However, if a static is written to multiple times within
     * during class initialization, it is difficult to predict which value should be used.
     * This would depend on which value is used by expressions instances for which the new
     * constant will be substituted, and there may be many of these; in each, the
     * static field in question may have taken on a different value (if some of these uses
     * occur within static initializers).
     */

    if (bd instanceof FieldDeclaration) {
      FieldDeclaration fieldDecl = (FieldDeclaration) bd;
      for (Iterator<VariableDeclarationFragment> fragments = fieldDecl.fragments().iterator();
          fragments.hasNext(); ) {
        VariableDeclarationFragment fragment = fragments.next();
        SimpleName staticFieldName = fragment.getName();
        if (selected.getSubFragmentsMatching(
                    ASTFragmentFactory.createFragmentForFullSubtree(staticFieldName))
                .length
            != 0) return true;
      }
    }
    return false;
  }
예제 #4
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;
 }
예제 #5
0
 /* (non-Javadoc)
  * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.Javadoc)
  */
 public boolean visit(Javadoc node) {
   List tags = node.tags();
   ASTNode parent = node.getParent();
   if (parent != null) {
     switch (parent.getNodeType()) {
       case ASTNode.TYPE_DECLARATION:
         {
           TypeDeclaration type = (TypeDeclaration) parent;
           if (type.isInterface()) {
             processTags(
                 fType,
                 pruneTags(tags, type),
                 IApiJavadocTag.TYPE_INTERFACE,
                 IApiJavadocTag.MEMBER_NONE);
           } else {
             processTags(
                 fType,
                 pruneTags(tags, type),
                 IApiJavadocTag.TYPE_CLASS,
                 IApiJavadocTag.MEMBER_NONE);
           }
           break;
         }
       case ASTNode.METHOD_DECLARATION:
         {
           MethodDeclaration method = (MethodDeclaration) parent;
           String signature = Signatures.getMethodSignatureFromNode(method);
           if (signature != null) {
             String methodname = method.getName().getFullyQualifiedName();
             int member = IApiJavadocTag.MEMBER_METHOD;
             if (method.isConstructor()) {
               member = IApiJavadocTag.MEMBER_CONSTRUCTOR;
               methodname = "<init>"; // $NON-NLS-1$
             }
             IMethodDescriptor descriptor = fType.getMethod(methodname, signature);
             processTags(descriptor, pruneTags(tags, method), getEnclosingType(method), member);
           }
           break;
         }
       case ASTNode.FIELD_DECLARATION:
         {
           FieldDeclaration field = (FieldDeclaration) parent;
           List fields = field.fragments();
           VariableDeclarationFragment fragment = null;
           for (Iterator iter = fields.iterator(); iter.hasNext(); ) {
             fragment = (VariableDeclarationFragment) iter.next();
             processTags(
                 fType.getField(fragment.getName().getFullyQualifiedName()),
                 pruneTags(tags, field),
                 getEnclosingType(field),
                 IApiJavadocTag.MEMBER_FIELD);
           }
           break;
         }
     }
   }
   return false;
 }
  /*
   * Must be one of:
   * <ul>
   * <li>[result]= 0</li>
   * </ul>
   */
  private IVariableBinding getIndexBindingFromFragment(VariableDeclarationFragment fragment) {
    Expression initializer = fragment.getInitializer();
    if (!(initializer instanceof NumberLiteral)) return null;

    NumberLiteral number = (NumberLiteral) initializer;
    if (!LITERAL_0.equals(number.getToken())) return null;

    return (IVariableBinding) fragment.getName().resolveBinding();
  }
예제 #7
0
 @Override
 public boolean visit(FieldDeclaration node) {
   String typName = node.getType().toString();
   List<VariableDeclarationFragment> vars = node.fragments();
   for (VariableDeclarationFragment var : vars) {
     map.put(var.getName().getIdentifier(), typName);
   }
   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);
    }
  }
 /*
  * @see ASTVisitor#visit(VariableDeclarationFragment)
  */
 public boolean visit(VariableDeclarationFragment node) {
   node.getName().accept(this);
   for (int i = 0; i < node.getExtraDimensions(); i++) {
     this.fBuffer.append("[]"); // $NON-NLS-1$
   }
   if (node.getInitializer() != null) {
     this.fBuffer.append("="); // $NON-NLS-1$
     node.getInitializer().accept(this);
   }
   return false;
 }
 private String getFieldName(VariableDeclarationFragment node) {
   StringBuffer buffer = new StringBuffer();
   buffer.append(node.getName().toString());
   ASTNode parent = node.getParent();
   if (parent instanceof FieldDeclaration) {
     FieldDeclaration fd = (FieldDeclaration) parent;
     buffer.append(" : "); // $NON-NLS-1$
     buffer.append(getType(fd.getType()));
   }
   return buffer.toString();
 }
 private void printFieldAnnotationMethods(List<FieldDeclaration> fields) {
   for (FieldDeclaration field : fields) {
     List<Annotation> runtimeAnnotations =
         ASTUtil.getRuntimeAnnotations(ASTUtil.getModifiers(field));
     if (runtimeAnnotations.size() > 0) {
       for (VariableDeclarationFragment var : ASTUtil.getFragments(field)) {
         printf("+ (IOSObjectArray *)__annotations_%s_ {\n", var.getName().getIdentifier());
         printAnnotationCreate(runtimeAnnotations);
       }
     }
   }
 }
  /*
   * [lengthBinding]= [arrayBinding].length
   */
  private boolean validateLengthFragment(VariableDeclarationFragment fragment) {
    Expression initializer = fragment.getInitializer();
    if (initializer == null) return false;

    if (!validateLengthQuery(initializer)) return false;

    IVariableBinding lengthBinding = (IVariableBinding) fragment.getName().resolveBinding();
    if (lengthBinding == null) return false;
    fLengthBinding = lengthBinding;

    return true;
  }
    /** {@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;
    }
 /*
  * @see ASTVisitor#visit(VariableDeclarationExpression)
  */
 public boolean visit(VariableDeclarationExpression 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$
     }
   }
   return false;
 }
예제 #15
0
  @Override
  public boolean visit(VariableDeclarationFragment node) {
    for (Map.Entry<String, Object> entry : replaceVariablesMap.entrySet()) {
      String key = entry.getKey();
      if (variablesMap.containsKey(key) && variablesMap.get(key) == getLine(node)) {
        AST ast = rewrite.getAST();
        VariableDeclarationFragment fragment = ast.newVariableDeclarationFragment();
        fragment.setName(ast.newSimpleName(key));
        fragment.setInitializer(createNewObject(replaceVariablesMap.get(key)));
        rewrite.replace(node, fragment, null);
      }
    }

    return true;
  }
 /* (non-Javadoc)
  * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.FieldDeclaration)
  */
 public boolean visit(FieldDeclaration node) {
   if (signature != null) {
     return false;
   }
   List<VariableDeclarationFragment> fields = node.fragments();
   VariableDeclarationFragment fragment = null;
   for (Iterator<VariableDeclarationFragment> iter = fields.iterator(); iter.hasNext(); ) {
     fragment = iter.next();
     if (fragment.getName().getFullyQualifiedName().equals(name)) {
       break;
     }
   }
   if (fragment != null) {
     updateTag(node);
   }
   return false;
 }
 /*
  * @see ASTVisitor#visit(VariableDeclarationStatement)
  */
 @Override
 public boolean visit(VariableDeclarationStatement node) {
   if (node.getAST().apiLevel() >= JLS3) {
     printModifiers(node.modifiers());
   }
   node.getType().accept(this);
   this.fBuffer.append(" "); // $NON-NLS-1$
   for (Iterator<VariableDeclarationFragment> it = node.fragments().iterator(); it.hasNext(); ) {
     VariableDeclarationFragment f = it.next();
     f.accept(this);
     if (it.hasNext()) {
       this.fBuffer.append(", "); // $NON-NLS-1$
     }
   }
   this.fBuffer.append(";"); // $NON-NLS-1$
   return false;
 }
예제 #18
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;
 }
예제 #19
0
 @Override
 public void endVisit(VariableDeclarationFragment node) {
   VMExpression initializer =
       (node.getInitializer() == null) ? null : (VMExpression) (expressions.pop());
   VMVariableReference reference = (VMVariableReference) (expressions.pop());
   VMVariableDeclarationFragment vardecl =
       new VMVariableDeclarationFragment(node, reference.getVariable(), initializer);
   expressions.push(vardecl);
 }
 // !! - like one in ExtractTempRefactoring
 private static boolean canReplace(IASTFragment fragment) {
   ASTNode node = fragment.getAssociatedNode();
   ASTNode parent = node.getParent();
   if (parent instanceof VariableDeclarationFragment) {
     VariableDeclarationFragment vdf = (VariableDeclarationFragment) parent;
     if (node.equals(vdf.getName())) return false;
   }
   if (parent instanceof ExpressionStatement) return false;
   if (parent instanceof SwitchCase) {
     if (node instanceof Name) {
       Name name = (Name) node;
       ITypeBinding typeBinding = name.resolveTypeBinding();
       if (typeBinding != null) {
         return !typeBinding.isEnum();
       }
     }
   }
   return true;
 }
 @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;
  }
    /** {@inheritDoc} */
    public boolean visit(VariableDeclarationFragment node) {
      SimpleName name = node.getName();

      IBinding binding = name.resolveBinding();
      if (binding == null) return true;

      if (fWrittenVariables.containsKey(binding)) return true;

      ModifierChangeOperation op = createAddFinalOperation(name, node);
      if (op == null) return true;

      fResult.add(op);
      return true;
    }
    private boolean handleFragments(List list, ASTNode declaration) {
      List toChange = new ArrayList();

      for (Iterator iter = list.iterator(); iter.hasNext(); ) {
        VariableDeclarationFragment fragment = (VariableDeclarationFragment) iter.next();
        SimpleName name = fragment.getName();
        IBinding resolveBinding = name.resolveBinding();
        if (canAddFinal(resolveBinding, declaration)) {
          IVariableBinding varbinding = (IVariableBinding) resolveBinding;
          if (varbinding.isField()) {
            if (fieldCanBeFinal(fragment, varbinding)) toChange.add(fragment);
          } else {
            if (!fWrittenVariables.containsKey(resolveBinding)) toChange.add(fragment);
          }
        }
      }

      if (toChange.size() == 0) return false;

      ModifierChangeOperation op =
          new ModifierChangeOperation(declaration, toChange, Modifier.FINAL, Modifier.NONE);
      fResult.add(op);
      return false;
    }
 private void printStaticVars(List<FieldDeclaration> fields, boolean isInterface) {
   boolean hadStaticVar = false;
   for (FieldDeclaration f : fields) {
     if (Modifier.isStatic(f.getModifiers()) || isInterface) {
       for (VariableDeclarationFragment var : ASTUtil.getFragments(f)) {
         IVariableBinding binding = Types.getVariableBinding(var);
         if (!BindingUtil.isPrimitiveConstant(binding)) {
           String name = NameTable.getStaticVarQualifiedName(binding);
           String objcType = NameTable.getObjCType(binding.getType());
           Expression initializer = var.getInitializer();
           if (initializer != null) {
             printf("static %s %s = %s;\n", objcType, name, generateExpression(initializer));
           } else {
             printf("static %s %s;\n", objcType, name);
           }
           hadStaticVar = true;
         }
       }
     }
   }
   if (hadStaticVar) {
     newline();
   }
 }
 @Override
 public boolean visit(VariableDeclarationFragment node) {
   boolean result = super.visit(node);
   if (isFirstSelectedNode(node)) {
     if (node.getParent() instanceof FieldDeclaration) {
       invalidSelection(
           RefactoringCoreMessages
               .ExtractMethodAnalyzer_cannot_extract_variable_declaration_fragment_from_field,
           JavaStatusContext.create(fCUnit, node));
     } else {
       invalidSelection(
           RefactoringCoreMessages
               .ExtractMethodAnalyzer_cannot_extract_variable_declaration_fragment,
           JavaStatusContext.create(fCUnit, node));
     }
     return false;
   }
   return result;
 }
  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;
  }
 /*
  * @see ASTVisitor#visit(VariableDeclarationFragment)
  */
 @Override
 public boolean visit(VariableDeclarationFragment node) {
   node.getName().accept(this);
   if (node.getAST().apiLevel() >= AST.JLS8) {
     List<Dimension> dimensions = node.extraDimensions();
     for (Iterator<Dimension> it = dimensions.iterator(); it.hasNext(); ) {
       Dimension e = it.next();
       e.accept(this);
     }
   } else {
     for (int i = 0; i < node.getExtraDimensions(); i++) {
       this.fBuffer.append("[]"); // $NON-NLS-1$
     }
   }
   if (node.getInitializer() != null) {
     this.fBuffer.append("="); // $NON-NLS-1$
     node.getInitializer().accept(this);
   }
   return false;
 }
    private boolean fieldCanBeFinal(
        VariableDeclarationFragment fragment, IVariableBinding binding) {
      if (Modifier.isStatic(((FieldDeclaration) fragment.getParent()).getModifiers())) return false;

      if (!fWrittenVariables.containsKey(binding)) {
        // variable is not written
        if (fragment.getInitializer() == null) { // variable is not initialized
          return false;
        } else {
          return true;
        }
      }

      if (fragment.getInitializer() != null) // variable is initialized and written
      return false;

      ITypeBinding declaringClass = binding.getDeclaringClass();
      if (declaringClass == null) return false;

      ArrayList writes = (ArrayList) fWrittenVariables.get(binding);
      if (!isWrittenInTypeConstructors(writes, declaringClass)) return false;

      HashSet writingConstructorBindings = new HashSet();
      ArrayList writingConstructors = new ArrayList();
      for (int i = 0; i < writes.size(); i++) {
        SimpleName name = (SimpleName) writes.get(i);
        MethodDeclaration constructor = getWritingConstructor(name);
        if (writingConstructors.contains(
            constructor)) // variable is written twice or more in constructor
        return false;

        if (canReturn(constructor)) return false;

        writingConstructors.add(constructor);
        IMethodBinding constructorBinding = constructor.resolveBinding();
        if (constructorBinding == null) return false;

        writingConstructorBindings.add(constructorBinding);
      }

      for (int i = 0; i < writingConstructors.size(); i++) {
        MethodDeclaration constructor = (MethodDeclaration) writingConstructors.get(i);
        if (callsWritingConstructor(
            constructor,
            writingConstructorBindings)) // writing constructor calls other writing constructor
        return false;
      }

      MethodDeclaration constructor = (MethodDeclaration) writingConstructors.get(0);
      TypeDeclaration typeDecl =
          (TypeDeclaration) ASTNodes.getParent(constructor, TypeDeclaration.class);
      if (typeDecl == null) return false;

      MethodDeclaration[] methods = typeDecl.getMethods();
      for (int i = 0; i < methods.length; i++) {
        if (methods[i].isConstructor()) {
          IMethodBinding methodBinding = methods[i].resolveBinding();
          if (methodBinding == null) return false;

          if (!writingConstructorBindings.contains(methodBinding)) {
            if (!callsWritingConstructor(
                methods[i],
                writingConstructorBindings)) // non writing constructor does not call a writing
              // constructor
              return false;
          }
        }
      }

      return true;
    }
예제 #30
0
  private List<ClassObject> parseAST(CompilationUnit compilationUnit, IFile iFile) {
    List<ClassObject> classObjects = new ArrayList<ClassObject>();
    List<AbstractTypeDeclaration> topLevelTypeDeclarations = compilationUnit.types();
    for (AbstractTypeDeclaration abstractTypeDeclaration : topLevelTypeDeclarations) {
      if (abstractTypeDeclaration instanceof TypeDeclaration) {
        TypeDeclaration topLevelTypeDeclaration = (TypeDeclaration) abstractTypeDeclaration;
        List<TypeDeclaration> typeDeclarations = new ArrayList<TypeDeclaration>();
        typeDeclarations.add(topLevelTypeDeclaration);
        typeDeclarations.addAll(getRecursivelyInnerTypes(topLevelTypeDeclaration));
        for (TypeDeclaration typeDeclaration : typeDeclarations) {
          final ClassObject classObject = new ClassObject();
          classObject.setIFile(iFile);
          classObject.setName(typeDeclaration.resolveBinding().getQualifiedName());
          classObject.setTypeDeclaration(typeDeclaration);

          if (typeDeclaration.isInterface()) {
            classObject.setInterface(true);
          }

          int modifiers = typeDeclaration.getModifiers();
          if ((modifiers & Modifier.ABSTRACT) != 0) classObject.setAbstract(true);

          if ((modifiers & Modifier.PUBLIC) != 0) classObject.setAccess(Access.PUBLIC);
          else if ((modifiers & Modifier.PROTECTED) != 0) classObject.setAccess(Access.PROTECTED);
          else if ((modifiers & Modifier.PRIVATE) != 0) classObject.setAccess(Access.PRIVATE);
          else classObject.setAccess(Access.NONE);

          if ((modifiers & Modifier.STATIC) != 0) classObject.setStatic(true);

          Type superclassType = typeDeclaration.getSuperclassType();
          if (superclassType != null) {
            ITypeBinding binding = superclassType.resolveBinding();
            String qualifiedName = binding.getQualifiedName();
            TypeObject typeObject = TypeObject.extractTypeObject(qualifiedName);
            classObject.setSuperclass(typeObject);
          }

          List<Type> superInterfaceTypes = typeDeclaration.superInterfaceTypes();
          for (Type interfaceType : superInterfaceTypes) {
            ITypeBinding binding = interfaceType.resolveBinding();
            String qualifiedName = binding.getQualifiedName();
            TypeObject typeObject = TypeObject.extractTypeObject(qualifiedName);
            classObject.addInterface(typeObject);
          }

          FieldDeclaration[] fieldDeclarations = typeDeclaration.getFields();
          for (FieldDeclaration fieldDeclaration : fieldDeclarations) {
            Type fieldType = fieldDeclaration.getType();
            ITypeBinding binding = fieldType.resolveBinding();
            List<VariableDeclarationFragment> fragments = fieldDeclaration.fragments();
            for (VariableDeclarationFragment fragment : fragments) {
              String qualifiedName = binding.getQualifiedName();
              TypeObject typeObject = TypeObject.extractTypeObject(qualifiedName);
              typeObject.setArrayDimension(
                  typeObject.getArrayDimension() + fragment.getExtraDimensions());
              FieldObject fieldObject =
                  new FieldObject(typeObject, fragment.getName().getIdentifier());
              fieldObject.setClassName(classObject.getName());
              fieldObject.setVariableDeclarationFragment(fragment);

              int fieldModifiers = fieldDeclaration.getModifiers();
              if ((fieldModifiers & Modifier.PUBLIC) != 0) fieldObject.setAccess(Access.PUBLIC);
              else if ((fieldModifiers & Modifier.PROTECTED) != 0)
                fieldObject.setAccess(Access.PROTECTED);
              else if ((fieldModifiers & Modifier.PRIVATE) != 0)
                fieldObject.setAccess(Access.PRIVATE);
              else fieldObject.setAccess(Access.NONE);

              if ((fieldModifiers & Modifier.STATIC) != 0) fieldObject.setStatic(true);

              classObject.addField(fieldObject);
            }
          }

          MethodDeclaration[] methodDeclarations = typeDeclaration.getMethods();
          for (MethodDeclaration methodDeclaration : methodDeclarations) {
            String methodName = methodDeclaration.getName().getIdentifier();
            final ConstructorObject constructorObject = new ConstructorObject();
            constructorObject.setMethodDeclaration(methodDeclaration);
            constructorObject.setName(methodName);
            constructorObject.setClassName(classObject.getName());

            int methodModifiers = methodDeclaration.getModifiers();
            if ((methodModifiers & Modifier.PUBLIC) != 0)
              constructorObject.setAccess(Access.PUBLIC);
            else if ((methodModifiers & Modifier.PROTECTED) != 0)
              constructorObject.setAccess(Access.PROTECTED);
            else if ((methodModifiers & Modifier.PRIVATE) != 0)
              constructorObject.setAccess(Access.PRIVATE);
            else constructorObject.setAccess(Access.NONE);

            List<SingleVariableDeclaration> parameters = methodDeclaration.parameters();
            for (SingleVariableDeclaration parameter : parameters) {
              Type parameterType = parameter.getType();
              ITypeBinding binding = parameterType.resolveBinding();
              String qualifiedName = binding.getQualifiedName();
              TypeObject typeObject = TypeObject.extractTypeObject(qualifiedName);
              typeObject.setArrayDimension(
                  typeObject.getArrayDimension() + parameter.getExtraDimensions());
              if (parameter.isVarargs()) {
                typeObject.setArrayDimension(1);
              }
              ParameterObject parameterObject =
                  new ParameterObject(typeObject, parameter.getName().getIdentifier());
              parameterObject.setSingleVariableDeclaration(parameter);
              constructorObject.addParameter(parameterObject);
            }

            Block methodBody = methodDeclaration.getBody();
            if (methodBody != null) {
              MethodBodyObject methodBodyObject = new MethodBodyObject(methodBody);
              constructorObject.setMethodBody(methodBodyObject);
            }

            if (methodDeclaration.isConstructor()) {
              classObject.addConstructor(constructorObject);
            } else {
              MethodObject methodObject = new MethodObject(constructorObject);
              List<IExtendedModifier> extendedModifiers = methodDeclaration.modifiers();
              for (IExtendedModifier extendedModifier : extendedModifiers) {
                if (extendedModifier.isAnnotation()) {
                  Annotation annotation = (Annotation) extendedModifier;
                  if (annotation.getTypeName().getFullyQualifiedName().equals("Test")) {
                    methodObject.setTestAnnotation(true);
                    break;
                  }
                }
              }
              Type returnType = methodDeclaration.getReturnType2();
              ITypeBinding binding = returnType.resolveBinding();
              String qualifiedName = binding.getQualifiedName();
              TypeObject typeObject = TypeObject.extractTypeObject(qualifiedName);
              methodObject.setReturnType(typeObject);

              if ((methodModifiers & Modifier.ABSTRACT) != 0) methodObject.setAbstract(true);
              if ((methodModifiers & Modifier.STATIC) != 0) methodObject.setStatic(true);
              if ((methodModifiers & Modifier.SYNCHRONIZED) != 0)
                methodObject.setSynchronized(true);
              if ((methodModifiers & Modifier.NATIVE) != 0) methodObject.setNative(true);

              classObject.addMethod(methodObject);
              FieldInstructionObject fieldInstruction = methodObject.isGetter();
              if (fieldInstruction != null)
                systemObject.addGetter(methodObject.generateMethodInvocation(), fieldInstruction);
              fieldInstruction = methodObject.isSetter();
              if (fieldInstruction != null)
                systemObject.addSetter(methodObject.generateMethodInvocation(), fieldInstruction);
              fieldInstruction = methodObject.isCollectionAdder();
              if (fieldInstruction != null)
                systemObject.addCollectionAdder(
                    methodObject.generateMethodInvocation(), fieldInstruction);
              MethodInvocationObject methodInvocation = methodObject.isDelegate();
              if (methodInvocation != null)
                systemObject.addDelegate(methodObject.generateMethodInvocation(), methodInvocation);
            }
          }
          classObjects.add(classObject);
        }
      }
    }
    return classObjects;
  }