// 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");
   }
 }
  /* 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;
  }
예제 #3
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;
 }
예제 #4
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;
 }
예제 #5
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;
 }
  /*
   * 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;
 }
 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();
 }
 /*
  * @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 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);
       }
     }
   }
 }
 @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];
   }
 }
  /*
   * [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;
  }
  @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;
    }
 /* (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;
 }
 // !! - 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;
 }
 /*
  * @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 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 createConstantDeclaration() throws CoreException {
    Type type = getConstantType();

    IExpressionFragment fragment = getSelectedExpression();
    Expression initializer =
        getSelectedExpression().createCopyTarget(fCuRewrite.getASTRewrite(), true);

    AST ast = fCuRewrite.getAST();
    VariableDeclarationFragment variableDeclarationFragment = ast.newVariableDeclarationFragment();
    variableDeclarationFragment.setName(ast.newSimpleName(fConstantName));
    variableDeclarationFragment.setInitializer(initializer);

    FieldDeclaration fieldDeclaration = ast.newFieldDeclaration(variableDeclarationFragment);
    fieldDeclaration.setType(type);
    Modifier.ModifierKeyword accessModifier = Modifier.ModifierKeyword.toKeyword(fVisibility);
    if (accessModifier != null) fieldDeclaration.modifiers().add(ast.newModifier(accessModifier));
    fieldDeclaration.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.STATIC_KEYWORD));
    fieldDeclaration.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.FINAL_KEYWORD));

    boolean createComments =
        JavaPreferencesSettings.getCodeGenerationSettings(fCu.getJavaProject()).createComments;
    if (createComments) {
      String comment =
          CodeGeneration.getFieldComment(
              fCu, getConstantTypeName(), fConstantName, StubUtility.getLineDelimiterUsed(fCu));
      if (comment != null && comment.length() > 0) {
        Javadoc doc =
            (Javadoc) fCuRewrite.getASTRewrite().createStringPlaceholder(comment, ASTNode.JAVADOC);
        fieldDeclaration.setJavadoc(doc);
      }
    }

    AbstractTypeDeclaration parent = getContainingTypeDeclarationNode();
    ListRewrite listRewrite =
        fCuRewrite.getASTRewrite().getListRewrite(parent, parent.getBodyDeclarationsProperty());
    TextEditGroup msg =
        fCuRewrite.createGroupDescription(
            RefactoringCoreMessages.ExtractConstantRefactoring_declare_constant);
    if (insertFirst()) {
      listRewrite.insertFirst(fieldDeclaration, msg);
    } else {
      listRewrite.insertAfter(fieldDeclaration, getNodeToInsertConstantDeclarationAfter(), msg);
    }

    if (fLinkedProposalModel != null) {
      ASTRewrite rewrite = fCuRewrite.getASTRewrite();
      LinkedProposalPositionGroup nameGroup = fLinkedProposalModel.getPositionGroup(KEY_NAME, true);
      nameGroup.addPosition(rewrite.track(variableDeclarationFragment.getName()), true);

      String[] nameSuggestions = guessConstantNames();
      if (nameSuggestions.length > 0 && !nameSuggestions[0].equals(fConstantName)) {
        nameGroup.addProposal(fConstantName, null, nameSuggestions.length + 1);
      }
      for (int i = 0; i < nameSuggestions.length; i++) {
        nameGroup.addProposal(nameSuggestions[i], null, nameSuggestions.length - i);
      }

      LinkedProposalPositionGroup typeGroup = fLinkedProposalModel.getPositionGroup(KEY_TYPE, true);
      typeGroup.addPosition(rewrite.track(type), true);

      ITypeBinding typeBinding = guessBindingForReference(fragment.getAssociatedExpression());
      if (typeBinding != null) {
        ITypeBinding[] relaxingTypes = ASTResolving.getNarrowingTypes(ast, typeBinding);
        for (int i = 0; i < relaxingTypes.length; i++) {
          typeGroup.addProposal(relaxingTypes[i], fCuRewrite.getCu(), relaxingTypes.length - i);
        }
      }
      boolean isInterface =
          parent.resolveBinding() != null && parent.resolveBinding().isInterface();
      ModifierCorrectionSubProcessor.installLinkedVisibilityProposals(
          fLinkedProposalModel, rewrite, fieldDeclaration.modifiers(), isInterface);
    }
  }
예제 #20
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;
  }
  private ASTRewrite doAddField(CompilationUnit astRoot) {
    SimpleName node = fOriginalNode;
    boolean isInDifferentCU = false;

    ASTNode newTypeDecl = astRoot.findDeclaringNode(fSenderBinding);
    if (newTypeDecl == null) {
      astRoot = ASTResolving.createQuickFixAST(getCompilationUnit(), null);
      newTypeDecl = astRoot.findDeclaringNode(fSenderBinding.getKey());
      isInDifferentCU = true;
    }
    ImportRewrite imports = createImportRewrite(astRoot);
    ImportRewriteContext importRewriteContext =
        new ContextSensitiveImportRewriteContext(
            ASTResolving.findParentBodyDeclaration(node), imports);

    if (newTypeDecl != null) {
      AST ast = newTypeDecl.getAST();

      ASTRewrite rewrite = ASTRewrite.create(ast);

      VariableDeclarationFragment fragment = ast.newVariableDeclarationFragment();
      fragment.setName(ast.newSimpleName(node.getIdentifier()));

      Type type = evaluateVariableType(ast, imports, importRewriteContext, fSenderBinding);

      FieldDeclaration newDecl = ast.newFieldDeclaration(fragment);
      newDecl.setType(type);
      newDecl
          .modifiers()
          .addAll(ASTNodeFactory.newModifiers(ast, evaluateFieldModifiers(newTypeDecl)));

      if (fSenderBinding.isInterface() || fVariableKind == CONST_FIELD) {
        fragment.setInitializer(ASTNodeFactory.newDefaultExpression(ast, type, 0));
      }

      ChildListPropertyDescriptor property = ASTNodes.getBodyDeclarationsProperty(newTypeDecl);
      List<BodyDeclaration> decls =
          ASTNodes.<BodyDeclaration>getChildListProperty(newTypeDecl, property);

      int maxOffset = isInDifferentCU ? -1 : node.getStartPosition();

      int insertIndex = findFieldInsertIndex(decls, newDecl, maxOffset);

      ListRewrite listRewriter = rewrite.getListRewrite(newTypeDecl, property);
      listRewriter.insertAt(newDecl, insertIndex, null);

      ModifierCorrectionSubProcessor.installLinkedVisibilityProposals(
          getLinkedProposalModel(), rewrite, newDecl.modifiers(), fSenderBinding.isInterface());

      addLinkedPosition(rewrite.track(newDecl.getType()), false, KEY_TYPE);
      if (!isInDifferentCU) {
        addLinkedPosition(rewrite.track(node), true, KEY_NAME);
      }
      addLinkedPosition(rewrite.track(fragment.getName()), false, KEY_NAME);

      if (fragment.getInitializer() != null) {
        addLinkedPosition(rewrite.track(fragment.getInitializer()), false, KEY_INITIALIZER);
      }
      return rewrite;
    }
    return null;
  }
  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;
  }
예제 #23
0
  private void process(
      FieldDeclaration astNode,
      final JstType jstType,
      final Annotation anno,
      final CustomType cType,
      final CustomInfo cInfo) {

    String value = null;
    if (anno instanceof NormalAnnotation) {
      List<MemberValuePair> annos = getAnnoMemberPairs(anno);
      String name;
      if (annos.size() > 0) {
        for (MemberValuePair pair : annos) {
          name = getName(pair);
          if (ANNO_NAME.equals(name) || ANNO_VALUE.equals(name)) {
            if (pair.getValue() instanceof QualifiedName) {
              value = getValue((QualifiedName) pair.getValue(), astNode, jstType);
            } else {
              value = getValue(pair.getValue(), astNode, jstType);
            }
            cInfo.setName(value);
            break;
          }
        }
      }
    } else if (anno instanceof SingleMemberAnnotation) {
      value = getValue(((SingleMemberAnnotation) anno).getValue(), astNode, jstType);
      cInfo.setName(value);
    }

    if (value == null) {
      return;
    }

    String fName = null;
    String tName = null;

    if (value != null) {
      cInfo.setName(value);
      int index = value.lastIndexOf(".");
      if (index < 0) {
        fName = value;
      } else {
        fName = value.substring(index + 1, value.length());
        tName = value.substring(0, index);
      }
    }

    VariableDeclarationFragment v;
    String vName;
    CustomField cField;
    for (Object o : astNode.fragments()) {
      if (o instanceof VariableDeclarationFragment) {
        v = (VariableDeclarationFragment) o;
        vName = v.getName().toString();
        cField = cType.getCustomField(vName);
        if (cField == null) {
          cField = new CustomField(vName);
          cType.addCustomField(cField);
        }
        cField.setAttr(cInfo.getAttr());
        cField.setJstName(fName);
        cField.setJstOwnerTypeName(tName);
      }
    }
  }
예제 #24
0
  // generate a variable declaration with an initializer specified by the given expression
  // e.g. given x.f(a,b) ==> int y = x.f(a,b);
  public static List<Statement> genVarDeclStatement(Expression exp) {

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

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

    ExpressionStatement assignmentStmt = genAssignmentStatement(exp);

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

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

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

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

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

    result.add(decl);

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

    result.add(assignStmt);

    return result;
  }
예제 #25
0
 public boolean visit(VariableDeclarationFragment node) {
   if (found(node, node.getName()) && this.resolveBinding)
     this.foundBinding = node.resolveBinding();
   return true;
 }
예제 #26
0
  @Override
  public Pair<List<Pair<String, Name>>, Boolean> tryMatch(
      Statement s, Map<String, String> var2type, VariableContext context) {

    List<Pair<String, Name>> matchedVarList = new ArrayList<Pair<String, Name>>();
    Boolean matchedSuccessful = false;

    // An assignment statement pattern should match both
    //				assignment statements
    //  as well as  variabledelcaration statements

    if (s instanceof ExpressionStatement) {
      Expression exp = ((ExpressionStatement) s).getExpression();
      if (exp instanceof Assignment) {
        Assignment assignment = (Assignment) exp;

        // Note that the left hand side expression of an assignment expression is always a *name*
        Name lhsExp = null;
        ;
        try {
          lhsExp = (Name) assignment.getLeftHandSide();
        } catch (Exception e) {
          ErrorManager.error(
              "AssignStmtPattrn@58",
              "The left hand side pattern is not a name, instead: " + assignment);
          return new Pair<List<Pair<String, Name>>, Boolean>(matchedVarList, matchedSuccessful);
        }

        // Debugging types
        TypeHandler.printTypeMatchInfo(lhsExp, var2type.get(this.variable), "AssignStmtPattern@57");
        // Check the type between the lhs metavariable and the name

        // TypeHandler.typeMatchCheck(lhsExp, var2type.get(this.variable))
        if (context.variableMatchCheck(lhsExp, this.variable)) {
          matchedVarList.add(new Pair<String, Name>(this.variable.getName(), lhsExp));
        } else {
          // Type of the lhs expression does not match
          matchedSuccessful = false;
        }

        // Try to match the expression pattern
        Expression rhsExp = assignment.getRightHandSide();
        Pair<List<Pair<String, Name>>, Boolean> expMatch =
            this.expression.tryMatch(rhsExp, var2type, context);

        if (expMatch.getSecond()) {
          for (Pair<String, Name> p : expMatch.getFirst()) {
            matchedVarList.add(p);
          }
          matchedSuccessful = true;
        }
      }
    } else if (s instanceof VariableDeclarationStatement) {

      VariableDeclarationStatement vds = (VariableDeclarationStatement) s;

      if (vds.fragments().size() != 1) {
        // If the error occurs, go and fix the bug in
        ErrorManager.error(
            "AssignStmtPattern@lien81", "The size of variable declaration fragments is not 1");
      }

      VariableDeclarationFragment vdf = (VariableDeclarationFragment) vds.fragments().get(0);

      // Print debugging info for the lhs expression and its corresponding type pattern name
      TypeHandler.printTypeMatchInfo(
          vdf.getName(), var2type.get(this.variable), "AssignStmtPattern@line83");

      // Type check on the lhs variable
      // if (TypeHandler.typeMatchCheck(vdf.getName(), var2type.get(this.variable)))
      if (context.variableMatchCheck(vdf.getName(), this.variable))
        matchedVarList.add(new Pair<String, Name>(this.variable.getName(), vdf.getName()));

      Pair<List<Pair<String, Name>>, Boolean> expMatch =
          this.expression.tryMatch(vdf.getInitializer(), var2type, context);

      if (expMatch.getSecond()) {
        for (Pair<String, Name> p : expMatch.getFirst()) {
          matchedVarList.add(p);
        }
        matchedSuccessful = true;
      }
    }

    return new Pair<List<Pair<String, Name>>, Boolean>(matchedVarList, matchedSuccessful);
  }
  private void createTryCatchStatement(org.eclipse.jdt.core.IBuffer buffer, String lineDelimiter)
      throws CoreException {
    List<Statement> result = new ArrayList<>(1);
    TryStatement tryStatement = getAST().newTryStatement();
    ITypeBinding[] exceptions = fAnalyzer.getExceptions();
    ImportRewriteContext context =
        new ContextSensitiveImportRewriteContext(
            fAnalyzer.getEnclosingBodyDeclaration(), fImportRewrite);

    if (!fIsMultiCatch) {
      for (int i = 0; i < exceptions.length; i++) {
        ITypeBinding exception = exceptions[i];
        CatchClause catchClause = getAST().newCatchClause();
        tryStatement.catchClauses().add(catchClause);
        SingleVariableDeclaration decl = getAST().newSingleVariableDeclaration();
        String varName = StubUtility.getExceptionVariableName(fCUnit.getJavaProject());

        String name = fScope.createName(varName, false);
        decl.setName(getAST().newSimpleName(name));
        Type type = fImportRewrite.addImport(exception, getAST(), context);
        decl.setType(type);
        catchClause.setException(decl);
        Statement st = getCatchBody(ASTNodes.getQualifiedTypeName(type), name, lineDelimiter);
        if (st != null) {
          catchClause.getBody().statements().add(st);
        }
        fLinkedProposalModel
            .getPositionGroup(GROUP_EXC_TYPE + i, true)
            .addPosition(fRewriter.track(decl.getType()), i == 0);
        fLinkedProposalModel
            .getPositionGroup(GROUP_EXC_NAME + i, true)
            .addPosition(fRewriter.track(decl.getName()), false);
      }
    } else {
      List<ITypeBinding> filteredExceptions = filterSubtypeExceptions(exceptions);
      CatchClause catchClause = getAST().newCatchClause();
      SingleVariableDeclaration decl = getAST().newSingleVariableDeclaration();
      String varName = StubUtility.getExceptionVariableName(fCUnit.getJavaProject());
      String name = fScope.createName(varName, false);
      decl.setName(getAST().newSimpleName(name));

      UnionType unionType = getAST().newUnionType();
      List<Type> types = unionType.types();
      int i = 0;
      for (ITypeBinding exception : filteredExceptions) {
        Type type = fImportRewrite.addImport(exception, getAST(), context);
        types.add(type);
        fLinkedProposalModel
            .getPositionGroup(GROUP_EXC_TYPE + i, true)
            .addPosition(fRewriter.track(type), i == 0);
        i++;
      }

      decl.setType(unionType);
      catchClause.setException(decl);
      fLinkedProposalModel
          .getPositionGroup(GROUP_EXC_NAME + 0, true)
          .addPosition(fRewriter.track(decl.getName()), false);
      Statement st = getCatchBody("Exception", name, lineDelimiter); // $NON-NLS-1$
      if (st != null) {
        catchClause.getBody().statements().add(st);
      }
      tryStatement.catchClauses().add(catchClause);
    }
    List<ASTNode> variableDeclarations = getSpecialVariableDeclarationStatements();
    ListRewrite statements =
        fRewriter.getListRewrite(tryStatement.getBody(), Block.STATEMENTS_PROPERTY);
    boolean selectedNodeRemoved = false;
    ASTNode expressionStatement = null;
    for (int i = 0; i < fSelectedNodes.length; i++) {
      ASTNode node = fSelectedNodes[i];
      if (node instanceof VariableDeclarationStatement && variableDeclarations.contains(node)) {
        AST ast = getAST();
        VariableDeclarationStatement statement = (VariableDeclarationStatement) node;
        // Create a copy and remove the initializer
        VariableDeclarationStatement copy =
            (VariableDeclarationStatement) ASTNode.copySubtree(ast, statement);
        List<IExtendedModifier> modifiers = copy.modifiers();
        for (Iterator<IExtendedModifier> iter = modifiers.iterator(); iter.hasNext(); ) {
          IExtendedModifier modifier = iter.next();
          if (modifier.isModifier()
              && Modifier.isFinal(((Modifier) modifier).getKeyword().toFlagValue())) {
            iter.remove();
          }
        }
        List<VariableDeclarationFragment> fragments = copy.fragments();
        for (Iterator<VariableDeclarationFragment> iter = fragments.iterator(); iter.hasNext(); ) {
          VariableDeclarationFragment fragment = iter.next();
          fragment.setInitializer(null);
        }
        CompilationUnit root = (CompilationUnit) statement.getRoot();
        int extendedStart = root.getExtendedStartPosition(statement);
        // we have a leading comment and the comment is covered by the selection
        if (extendedStart != statement.getStartPosition()
            && extendedStart >= fSelection.getOffset()) {
          String commentToken =
              buffer.getText(extendedStart, statement.getStartPosition() - extendedStart);
          commentToken = Strings.trimTrailingTabsAndSpaces(commentToken);
          Type type = statement.getType();
          String typeName = buffer.getText(type.getStartPosition(), type.getLength());
          copy.setType(
              (Type)
                  fRewriter.createStringPlaceholder(commentToken + typeName, type.getNodeType()));
        }
        result.add(copy);
        // convert the fragments into expression statements
        fragments = statement.fragments();
        if (!fragments.isEmpty()) {
          List<ExpressionStatement> newExpressionStatements = new ArrayList<>();
          for (Iterator<VariableDeclarationFragment> iter = fragments.iterator();
              iter.hasNext(); ) {
            VariableDeclarationFragment fragment = iter.next();
            Expression initializer = fragment.getInitializer();
            if (initializer != null) {
              Assignment assignment = ast.newAssignment();
              assignment.setLeftHandSide(
                  (Expression) fRewriter.createCopyTarget(fragment.getName()));
              assignment.setRightHandSide((Expression) fRewriter.createCopyTarget(initializer));
              newExpressionStatements.add(ast.newExpressionStatement(assignment));
            }
          }
          if (!newExpressionStatements.isEmpty()) {
            if (fSelectedNodes.length == 1) {
              expressionStatement =
                  fRewriter.createGroupNode(
                      newExpressionStatements.toArray(new ASTNode[newExpressionStatements.size()]));
            } else {
              fRewriter.replace(
                  statement,
                  fRewriter.createGroupNode(
                      newExpressionStatements.toArray(new ASTNode[newExpressionStatements.size()])),
                  null);
            }
          } else {
            fRewriter.remove(statement, null);
            selectedNodeRemoved = true;
          }
        } else {
          fRewriter.remove(statement, null);
          selectedNodeRemoved = true;
        }
      }
    }
    result.add(tryStatement);
    ASTNode replacementNode;
    if (result.size() == 1) {
      replacementNode = result.get(0);
    } else {
      replacementNode = fRewriter.createGroupNode(result.toArray(new ASTNode[result.size()]));
    }
    if (fSelectedNodes.length == 1) {
      ASTNode selectedNode = fSelectedNodes[0];

      if (selectedNode instanceof MethodReference) {
        MethodReference methodReference = (MethodReference) selectedNode;
        IMethodBinding functionalMethod =
            QuickAssistProcessor.getFunctionalMethodForMethodReference(methodReference);
        // functionalMethod is non-null and non-generic. See
        // ExceptionAnalyzer.handleMethodReference(MethodReference node).
        Assert.isTrue(functionalMethod != null && !functionalMethod.isGenericMethod());
        LambdaExpression lambda =
            QuickAssistProcessor.convertMethodRefernceToLambda(
                methodReference, functionalMethod, fRootNode, fRewriter, null, true);
        ASTNode statementInBlock = (ASTNode) ((Block) lambda.getBody()).statements().get(0);
        fRewriter.replace(statementInBlock, replacementNode, null);
        statements.insertLast(statementInBlock, null);
        return;
      }

      LambdaExpression enclosingLambda = ASTResolving.findEnclosingLambdaExpression(selectedNode);
      if (enclosingLambda != null
          && selectedNode.getLocationInParent() == LambdaExpression.BODY_PROPERTY
          && enclosingLambda.resolveMethodBinding() != null) {
        QuickAssistProcessor.changeLambdaBodyToBlock(enclosingLambda, getAST(), fRewriter);
        Block blockBody = (Block) fRewriter.get(enclosingLambda, LambdaExpression.BODY_PROPERTY);
        ASTNode statementInBlock = (ASTNode) blockBody.statements().get(0);
        fRewriter.replace(statementInBlock, replacementNode, null);
        statements.insertLast(statementInBlock, null);
        return;
      }

      if (expressionStatement != null) {
        statements.insertLast(expressionStatement, null);
      } else {
        if (!selectedNodeRemoved)
          statements.insertLast(fRewriter.createMoveTarget(selectedNode), null);
      }
      fRewriter.replace(selectedNode, replacementNode, null);
    } else {
      ListRewrite source =
          fRewriter.getListRewrite(
              fSelectedNodes[0].getParent(),
              (ChildListPropertyDescriptor) fSelectedNodes[0].getLocationInParent());
      ASTNode toMove =
          source.createMoveTarget(
              fSelectedNodes[0], fSelectedNodes[fSelectedNodes.length - 1], replacementNode, null);
      statements.insertLast(toMove, null);
    }
  }