private void makeFinal() {
   for (PsiVariable var : getVariablesToFix()) {
     if (var.isValid()) {
       PsiUtil.setModifierProperty(var, PsiModifier.FINAL, true);
     }
   }
 }
    @Override
    public int compare(PsiVariable o1, PsiVariable o2) {

      if (o1 instanceof PsiParameter && ((PsiParameter) o1).isVarArgs()) return 1;
      if (o2 instanceof PsiParameter && ((PsiParameter) o2).isVarArgs()) return -1;

      if (o1 instanceof PsiField && o2 instanceof PsiField) {
        return o1.getTextOffset() - o2.getTextOffset();
      }
      if (o1 instanceof PsiParameter && o2 instanceof PsiParameter) {
        return myParameterList.getParameterIndex((PsiParameter) o1)
            - myParameterList.getParameterIndex((PsiParameter) o2);
      }

      if (o1 instanceof PsiField && o2 instanceof PsiParameter) {
        final PsiField field =
            FieldFromParameterUtils.getParameterAssignedToField((PsiParameter) o2);
        if (field == null) return 1;
        return o1.getTextOffset() - field.getTextOffset();
      }
      if (o1 instanceof PsiParameter && o2 instanceof PsiField) {
        final PsiField field =
            FieldFromParameterUtils.getParameterAssignedToField((PsiParameter) o1);
        if (field == null) return -1;
        return field.getTextOffset() - o2.getTextOffset();
      }

      return 0;
    }
 @Override
 public void visitReferenceExpression(final PsiReferenceExpression reference) {
   if (myLineRange.intersects(reference.getTextRange())) {
     final PsiElement psiElement = reference.resolve();
     if (psiElement instanceof PsiVariable) {
       final PsiVariable var = (PsiVariable) psiElement;
       if (var instanceof PsiField) {
         if (myCollectExpressions
             && !DebuggerUtils.hasSideEffectsOrReferencesMissingVars(
                 reference, myVisibleLocals)) {
           /*
           if (var instanceof PsiEnumConstant && reference.getQualifier() == null) {
             final PsiClass enumClass = ((PsiEnumConstant)var).getContainingClass();
             if (enumClass != null) {
               final PsiExpression expression = JavaPsiFacade.getInstance(var.getProject()).getParserFacade().createExpressionFromText(enumClass.getName() + "." + var.getName(), var);
               final PsiReference ref = expression.getReference();
               if (ref != null) {
                 ref.bindToElement(var);
                 myExpressions.add(new TextWithImportsImpl(expression));
               }
             }
           }
           else {
             myExpressions.add(new TextWithImportsImpl(reference));
           }
           */
           final PsiModifierList modifierList = var.getModifierList();
           boolean isConstant =
               (var instanceof PsiEnumConstant)
                   || (modifierList != null
                       && modifierList.hasModifierProperty(PsiModifier.STATIC)
                       && modifierList.hasModifierProperty(PsiModifier.FINAL));
           if (!isConstant) {
             myExpressions.add(new TextWithImportsImpl(reference));
           }
         }
       } else {
         if (myVisibleLocals.contains(var.getName())) {
           myVars.add(var.getName());
         } else {
           // fix for variables used in inner classes
           if (!Comparing.equal(
               PsiTreeUtil.getParentOfType(reference, PsiClass.class),
               PsiTreeUtil.getParentOfType(var, PsiClass.class))) {
             myExpressions.add(new TextWithImportsImpl(reference));
           }
         }
       }
     }
   }
   super.visitReferenceExpression(reference);
 }
 private void copyToFinal() throws IncorrectOperationException {
   PsiManager psiManager = myClass.getManager();
   PsiElementFactory factory =
       JavaPsiFacade.getInstance(psiManager.getProject()).getElementFactory();
   PsiExpression initializer = factory.createExpressionFromText(myVariable.getName(), myClass);
   String newName = suggestNewName(psiManager.getProject(), myVariable);
   PsiType type = myVariable.getType();
   PsiDeclarationStatement copyDecl =
       factory.createVariableDeclarationStatement(newName, type, initializer);
   PsiVariable newVariable = (PsiVariable) copyDecl.getDeclaredElements()[0];
   PsiUtil.setModifierProperty(newVariable, PsiModifier.FINAL, true);
   PsiElement statement = getStatementToInsertBefore();
   if (statement == null) return;
   statement.getParent().addBefore(copyDecl, statement);
   PsiExpression newExpression = factory.createExpressionFromText(newName, myVariable);
   replaceReferences(myClass, myVariable, newExpression);
 }
 public MoveInstanceMethodProcessor(
     final Project project,
     final PsiMethod method,
     final PsiVariable targetVariable,
     final String newVisibility,
     final Map<PsiClass, String> oldClassParameterNames) {
   super(project);
   myMethod = method;
   myTargetVariable = targetVariable;
   myOldClassParameterNames = oldClassParameterNames;
   LOG.assertTrue(
       myTargetVariable instanceof PsiParameter || myTargetVariable instanceof PsiField);
   LOG.assertTrue(myTargetVariable.getType() instanceof PsiClassType);
   final PsiType type = myTargetVariable.getType();
   LOG.assertTrue(type instanceof PsiClassType);
   myTargetClass = ((PsiClassType) type).resolve();
   myNewVisibility = newVisibility;
 }
 @Override
 public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
   return myClass != null
       && myClass.isValid()
       && myClass.getManager().isInProject(myClass)
       && myVariable != null
       && myVariable.isValid()
       && myFixType != -1
       && !getVariablesToFix().isEmpty()
       && !inOwnInitializer(myVariable, myClass);
 }
  private static String getConstantValueText(Object value, @Nullable PsiVariable constant) {
    if (constant != null) {
      return constant instanceof PsiMember
          ? PsiUtil.getMemberQualifiedName((PsiMember) constant)
          : constant.getName();
    }

    return value instanceof String
        ? "\"" + StringUtil.escapeStringCharacters((String) value) + "\""
        : String.valueOf(value);
  }
  public static Set<String> suggestExpressionOfType(
      final PsiClassType type, final PsiLiteralExpression context) {
    PsiVariable[] variables = MacroUtil.getVariablesVisibleAt(context, "");
    Set<String> result = new LinkedHashSet<String>();
    for (PsiVariable var : variables) {
      PsiType varType = var.getType();
      if (type == null || type.isAssignableFrom(varType)) {
        result.add(var.getNameIdentifier().getText());
      }
    }

    PsiExpression[] expressions = MacroUtil.getStandardExpressionsOfType(context, type);
    for (PsiExpression expression : expressions) {
      result.add(expression.getText());
    }
    if (type != null) {
      addAvailableMethodsOfType(type, context, result);
    }
    return result;
  }
 @Override
 @NotNull
 public String getText() {
   @NonNls String message;
   switch (myFixType) {
     case MAKE_FINAL:
       message = "make.final.text";
       break;
     case MAKE_ARRAY:
       message = "make.final.transform.to.one.element.array";
       break;
     case COPY_TO_FINAL:
       return QuickFixBundle.message("make.final.copy.to.temp", myVariable.getName());
     default:
       return "";
   }
   Collection<PsiVariable> vars = getVariablesToFix();
   String varNames = vars.size() == 1 ? "'" + myVariable.getName() + "'" : "variables";
   return QuickFixBundle.message(message, varNames);
 }
 private static String getUniqueParameterName(
     PsiParameter[] parameters, PsiVariable variable, HashMap<PsiField, String> usedNames) {
   final JavaCodeStyleManager styleManager =
       JavaCodeStyleManager.getInstance(variable.getProject());
   final SuggestedNameInfo nameInfo =
       styleManager.suggestVariableName(
           VariableKind.PARAMETER,
           styleManager.variableNameToPropertyName(variable.getName(), VariableKind.FIELD),
           null,
           variable.getType());
   String newName = nameInfo.names[0];
   int n = 1;
   while (true) {
     if (isUnique(parameters, newName, usedNames)) {
       break;
     }
     newName = nameInfo.names[0] + n++;
   }
   return newName;
 }
 private static String suggestNewName(Project project, PsiVariable variable) {
   // new name should not conflict with another variable at the variable declaration level and
   // usage level
   String name = variable.getName();
   // trim last digit to suggest variable names like i1,i2, i3...
   if (name.length() > 1 && Character.isDigit(name.charAt(name.length() - 1))) {
     name = name.substring(0, name.length() - 1);
   }
   name = "final" + StringUtil.capitalize(StringUtil.trimStart(name, "final"));
   return JavaCodeStyleManager.getInstance(project)
       .suggestUniqueVariableName(name, variable, true);
 }
  protected void performRefactoring(UsageInfo[] usages) {
    if (!CommonRefactoringUtil.checkReadOnlyStatus(myProject, myTargetClass)) return;

    PsiMethod patternMethod = createMethodToAdd();
    final List<PsiReference> docRefs = new ArrayList<PsiReference>();
    for (UsageInfo usage : usages) {
      if (usage instanceof InheritorUsageInfo) {
        final PsiClass inheritor = ((InheritorUsageInfo) usage).getInheritor();
        addMethodToClass(inheritor, patternMethod, true);
      } else if (usage instanceof MethodCallUsageInfo
          && !((MethodCallUsageInfo) usage).isInternal()) {
        final PsiElement expression = ((MethodCallUsageInfo) usage).getMethodCallExpression();
        if (expression instanceof PsiMethodCallExpression) {
          correctMethodCall((PsiMethodCallExpression) expression, false);
        } else if (expression instanceof PsiMethodReferenceExpression) {
          PsiExpression newQualifier =
              JavaPsiFacade.getInstance(myProject)
                  .getElementFactory()
                  .createExpressionFromText(myTargetVariable.getType().getCanonicalText(), null);
          ((PsiMethodReferenceExpression) expression).setQualifierExpression(newQualifier);
        }
      } else if (usage instanceof JavadocUsageInfo) {
        docRefs.add(usage.getElement().getReference());
      }
    }

    try {
      if (myTargetClass.isInterface()) patternMethod.getBody().delete();

      final PsiMethod method = addMethodToClass(myTargetClass, patternMethod, false);
      myMethod.delete();
      for (PsiReference reference : docRefs) {
        reference.bindToElement(method);
      }
      VisibilityUtil.fixVisibility(UsageViewUtil.toElements(usages), method, myNewVisibility);

      if (myOpenInEditor) {
        EditorHelper.openInEditor(method);
      }
    } catch (IncorrectOperationException e) {
      LOG.error(e);
    }
  }
  private void makeArray(PsiVariable variable) throws IncorrectOperationException {
    PsiType type = variable.getType();

    PsiElementFactory factory = JavaPsiFacade.getInstance(myClass.getProject()).getElementFactory();
    PsiType newType = type.createArrayType();

    PsiDeclarationStatement variableDeclarationStatement;
    PsiExpression initializer = variable.getInitializer();
    if (initializer == null) {
      String expression = "[1]";
      while (type instanceof PsiArrayType) {
        expression += "[1]";
        type = ((PsiArrayType) type).getComponentType();
      }
      PsiExpression init =
          factory.createExpressionFromText("new " + type.getCanonicalText() + expression, variable);
      variableDeclarationStatement =
          factory.createVariableDeclarationStatement(variable.getName(), newType, init);
    } else {
      PsiExpression init =
          factory.createExpressionFromText("{ " + initializer.getText() + " }", variable);
      variableDeclarationStatement =
          factory.createVariableDeclarationStatement(variable.getName(), newType, init);
    }
    PsiVariable newVariable = (PsiVariable) variableDeclarationStatement.getDeclaredElements()[0];
    PsiUtil.setModifierProperty(newVariable, PsiModifier.FINAL, true);
    PsiElement newExpression =
        factory.createExpressionFromText(variable.getName() + "[0]", variable);

    PsiElement outerCodeBlock = PsiUtil.getVariableCodeBlock(variable, null);
    if (outerCodeBlock == null) return;
    List<PsiReferenceExpression> outerReferences = new ArrayList<PsiReferenceExpression>();
    collectReferences(outerCodeBlock, variable, outerReferences);
    replaceReferences(outerReferences, newExpression);
    variable.replace(newVariable);
  }
  private void addTypesByVariable(
      HashSet<PsiType> typesSet,
      PsiVariable var,
      PsiFile scopeFile,
      HashSet<PsiVariable> checkedVariables,
      int flags,
      TextRange rangeToIgnore) {
    if (!checkedVariables.add(var)) return;
    // System.out.println("analyzing usages of " + var + " in file " + scopeFile);
    SearchScope searchScope = new LocalSearchScope(scopeFile);

    if (BitUtil.isSet(flags, CHECK_USAGE) || BitUtil.isSet(flags, CHECK_DOWN)) {
      for (PsiReference varRef : ReferencesSearch.search(var, searchScope, false)) {
        PsiElement ref = varRef.getElement();

        if (BitUtil.isSet(flags, CHECK_USAGE)) {
          PsiType type = guessElementTypeFromReference(myMethodPatternMap, ref, rangeToIgnore);
          if (type != null && !(type instanceof PsiPrimitiveType)) {
            typesSet.add(type);
          }
        }

        if (BitUtil.isSet(flags, CHECK_DOWN)) {
          if (ref.getParent() instanceof PsiExpressionList
              && ref.getParent().getParent() instanceof PsiMethodCallExpression) { // TODO : new
            PsiExpressionList list = (PsiExpressionList) ref.getParent();
            PsiExpression[] args = list.getExpressions();
            int argIndex = -1;
            for (int j = 0; j < args.length; j++) {
              PsiExpression arg = args[j];
              if (arg.equals(ref)) {
                argIndex = j;
                break;
              }
            }

            PsiMethodCallExpression methodCall = (PsiMethodCallExpression) list.getParent();
            PsiMethod method = (PsiMethod) methodCall.getMethodExpression().resolve();
            if (method != null) {
              PsiParameter[] parameters = method.getParameterList().getParameters();
              if (argIndex < parameters.length) {
                addTypesByVariable(
                    typesSet,
                    parameters[argIndex],
                    method.getContainingFile(),
                    checkedVariables,
                    flags | CHECK_USAGE,
                    rangeToIgnore);
              }
            }
          }
        }
      }
    }

    if (BitUtil.isSet(flags, CHECK_UP)) {
      if (var instanceof PsiParameter
          && var.getParent() instanceof PsiParameterList
          && var.getParent().getParent() instanceof PsiMethod) {
        PsiParameterList list = (PsiParameterList) var.getParent();
        PsiParameter[] parameters = list.getParameters();
        int argIndex = -1;
        for (int i = 0; i < parameters.length; i++) {
          PsiParameter parameter = parameters[i];
          if (parameter.equals(var)) {
            argIndex = i;
            break;
          }
        }

        PsiMethod method = (PsiMethod) var.getParent().getParent();
        // System.out.println("analyzing usages of " + method + " in file " + scopeFile);
        for (PsiReference methodRef : ReferencesSearch.search(method, searchScope, false)) {
          PsiElement ref = methodRef.getElement();
          if (ref.getParent() instanceof PsiMethodCallExpression) {
            PsiMethodCallExpression methodCall = (PsiMethodCallExpression) ref.getParent();
            PsiExpression[] args = methodCall.getArgumentList().getExpressions();
            if (args.length <= argIndex) continue;
            PsiExpression arg = args[argIndex];
            if (arg instanceof PsiReferenceExpression) {
              PsiElement refElement = ((PsiReferenceExpression) arg).resolve();
              if (refElement instanceof PsiVariable) {
                addTypesByVariable(
                    typesSet,
                    (PsiVariable) refElement,
                    scopeFile,
                    checkedVariables,
                    flags | CHECK_USAGE,
                    rangeToIgnore);
              }
            }
            // TODO : constructor
          }
        }
      }
    }
  }
 /**
  * @param sideEffects if null, delete usages, otherwise collect side effects
  * @return true if there are at least one unrecoverable side effect found, false if no side
  *     effects, null if read usage found (may happen if interval between fix creation in invoke()
  *     call was long enough)
  * @throws com.intellij.util.IncorrectOperationException
  */
 static Boolean processUsage(
     PsiElement element, PsiVariable variable, List<PsiElement> sideEffects, int deleteMode)
     throws IncorrectOperationException {
   if (!element.isValid()) return null;
   PsiElementFactory factory =
       JavaPsiFacade.getInstance(variable.getProject()).getElementFactory();
   while (element != null) {
     if (element instanceof PsiAssignmentExpression) {
       PsiAssignmentExpression expression = (PsiAssignmentExpression) element;
       PsiExpression lExpression = expression.getLExpression();
       // there should not be read access to the variable, otherwise it is not unused
       if (!(lExpression instanceof PsiReferenceExpression)
           || variable != ((PsiReferenceExpression) lExpression).resolve()) {
         return null;
       }
       PsiExpression rExpression = expression.getRExpression();
       rExpression = PsiUtil.deparenthesizeExpression(rExpression);
       if (rExpression == null) return true;
       // replace assignment with expression and resimplify
       boolean sideEffectFound = checkSideEffects(rExpression, variable, sideEffects);
       if (!(element.getParent() instanceof PsiExpressionStatement)
           || PsiUtil.isStatement(rExpression)) {
         if (deleteMode == MAKE_STATEMENT
             || deleteMode == DELETE_ALL
                 && !(element.getParent() instanceof PsiExpressionStatement)) {
           element = replaceElementWithExpression(rExpression, factory, element);
           while (element.getParent() instanceof PsiParenthesizedExpression) {
             element = element.getParent().replace(element);
           }
           List<PsiElement> references = new ArrayList<PsiElement>();
           collectReferences(element, variable, references);
           deleteReferences(variable, references, deleteMode);
         } else if (deleteMode == DELETE_ALL) {
           deleteWholeStatement(element, factory);
         }
         return true;
       } else {
         if (deleteMode != CANCEL) {
           deleteWholeStatement(element, factory);
         }
         return !sideEffectFound;
       }
     } else if (element instanceof PsiExpressionStatement && deleteMode != CANCEL) {
       final PsiElement parent = element.getParent();
       if (parent instanceof PsiIfStatement
           || parent instanceof PsiLoopStatement
               && ((PsiLoopStatement) parent).getBody() == element) {
         element.replace(
             JavaPsiFacade.getElementFactory(element.getProject())
                 .createStatementFromText(";", element));
       } else {
         element.delete();
       }
       break;
     } else if (element instanceof PsiVariable && element == variable) {
       PsiExpression expression = variable.getInitializer();
       if (expression != null) {
         expression = PsiUtil.deparenthesizeExpression(expression);
       }
       boolean sideEffectsFound = checkSideEffects(expression, variable, sideEffects);
       if (expression != null
           && PsiUtil.isStatement(expression)
           && variable instanceof PsiLocalVariable
           && !(variable.getParent() instanceof PsiDeclarationStatement
               && ((PsiDeclarationStatement) variable.getParent()).getDeclaredElements().length
                   > 1)) {
         if (deleteMode == MAKE_STATEMENT) {
           element = element.replace(createStatementIfNeeded(expression, factory, element));
           List<PsiElement> references = new ArrayList<PsiElement>();
           collectReferences(element, variable, references);
           deleteReferences(variable, references, deleteMode);
         } else if (deleteMode == DELETE_ALL) {
           element.delete();
         }
         return true;
       } else {
         if (deleteMode != CANCEL) {
           if (element instanceof PsiField) {
             ((PsiField) element).normalizeDeclaration();
           }
           element.delete();
         }
         return !sideEffectsFound;
       }
     }
     element = element.getParent();
   }
   return true;
 }
  private void correctMethodCall(
      final PsiMethodCallExpression expression, final boolean isInternalCall) {
    try {
      final PsiManager manager = myMethod.getManager();
      PsiReferenceExpression methodExpression = expression.getMethodExpression();
      if (!methodExpression.isReferenceTo(myMethod)) return;
      final PsiExpression oldQualifier = methodExpression.getQualifierExpression();
      PsiExpression newQualifier = null;
      final PsiClass classReferencedByThis =
          MoveInstanceMembersUtil.getClassReferencedByThis(methodExpression);
      if (myTargetVariable instanceof PsiParameter) {
        final int index =
            myMethod.getParameterList().getParameterIndex((PsiParameter) myTargetVariable);
        final PsiExpression[] arguments = expression.getArgumentList().getExpressions();
        if (index < arguments.length) {
          newQualifier = (PsiExpression) arguments[index].copy();
          arguments[index].delete();
        }
      } else {
        VisibilityUtil.escalateVisibility((PsiField) myTargetVariable, expression);
        String newQualifierName = myTargetVariable.getName();
        if (myTargetVariable instanceof PsiField && oldQualifier != null) {
          final PsiClass aClass = PsiUtil.resolveClassInClassTypeOnly(oldQualifier.getType());
          if (aClass == ((PsiField) myTargetVariable).getContainingClass()) {
            newQualifierName = oldQualifier.getText() + "." + newQualifierName;
          }
        }
        newQualifier =
            JavaPsiFacade.getInstance(manager.getProject())
                .getElementFactory()
                .createExpressionFromText(newQualifierName, null);
      }

      PsiExpression newArgument = null;

      if (classReferencedByThis != null) {
        @NonNls String thisArgumentText = null;
        if (manager.areElementsEquivalent(myMethod.getContainingClass(), classReferencedByThis)) {
          if (myOldClassParameterNames.containsKey(myMethod.getContainingClass())) {
            thisArgumentText = "this";
          }
        } else {
          thisArgumentText = classReferencedByThis.getName() + ".this";
        }

        if (thisArgumentText != null) {
          newArgument =
              JavaPsiFacade.getInstance(manager.getProject())
                  .getElementFactory()
                  .createExpressionFromText(thisArgumentText, null);
        }
      } else {
        if (!isInternalCall && oldQualifier != null) {
          final PsiType type = oldQualifier.getType();
          if (type instanceof PsiClassType) {
            final PsiClass resolved = ((PsiClassType) type).resolve();
            if (resolved != null && getParameterNameToCreate(resolved) != null) {
              newArgument =
                  replaceRefsToTargetVariable(
                      oldQualifier); // replace is needed in case old qualifier is e.g. the same as
                                     // field as target variable
            }
          }
        }
      }

      if (newArgument != null) {
        expression.getArgumentList().add(newArgument);
      }

      if (newQualifier != null) {
        if (newQualifier instanceof PsiThisExpression
            && ((PsiThisExpression) newQualifier).getQualifier() == null) {
          // Remove now redundant 'this' qualifier
          if (oldQualifier != null) oldQualifier.delete();
        } else {
          final PsiReferenceExpression refExpr =
              (PsiReferenceExpression)
                  JavaPsiFacade.getInstance(manager.getProject())
                      .getElementFactory()
                      .createExpressionFromText("q." + myMethod.getName(), null);
          refExpr.getQualifierExpression().replace(newQualifier);
          methodExpression.replace(refExpr);
        }
      }
    } catch (IncorrectOperationException e) {
      LOG.error(e);
    }
  }
  private static boolean addParameterToConstructor(
      final Project project,
      final PsiFile file,
      final Editor editor,
      final PsiMethod constructor,
      final PsiField[] fields)
      throws IncorrectOperationException {
    final PsiParameterList parameterList = constructor.getParameterList();
    final PsiParameter[] parameters = parameterList.getParameters();
    ParameterInfoImpl[] newParamInfos = new ParameterInfoImpl[parameters.length + fields.length];
    final List<PsiVariable> params = new ArrayList<PsiVariable>(Arrays.asList(parameters));
    Collections.addAll(params, fields);
    Collections.sort(params, new FieldParameterComparator(parameterList));

    int i = 0;
    final HashMap<PsiField, String> usedFields = new HashMap<PsiField, String>();
    for (PsiVariable param : params) {
      final PsiType paramType = param.getType();
      if (param instanceof PsiParameter) {
        newParamInfos[i++] =
            new ParameterInfoImpl(
                parameterList.getParameterIndex((PsiParameter) param),
                param.getName(),
                paramType,
                param.getName());
      } else {
        final String uniqueParameterName = getUniqueParameterName(parameters, param, usedFields);
        usedFields.put((PsiField) param, uniqueParameterName);
        newParamInfos[i++] =
            new ParameterInfoImpl(-1, uniqueParameterName, paramType, uniqueParameterName);
      }
    }
    final SmartPointerManager manager = SmartPointerManager.getInstance(project);
    final SmartPsiElementPointer constructorPointer =
        manager.createSmartPsiElementPointer(constructor);

    final PsiMethod fromText =
        JavaPsiFacade.getElementFactory(project)
            .createMethodFromText(createDummyMethod(constructor, newParamInfos), constructor);
    final PsiClass containingClass = constructor.getContainingClass();
    if (containingClass == null) return false;
    final int minUsagesNumber =
        containingClass.findMethodsBySignature(fromText, false).length > 0 ? 0 : 1;
    final List<ParameterInfoImpl> parameterInfos =
        ChangeMethodSignatureFromUsageFix.performChange(
            project, editor, file, constructor, minUsagesNumber, newParamInfos, true, true);

    final ParameterInfoImpl[] resultParams =
        parameterInfos != null
            ? parameterInfos.toArray(new ParameterInfoImpl[parameterInfos.size()])
            : newParamInfos;
    return ApplicationManager.getApplication()
        .runWriteAction(
            new Computable<Boolean>() {
              @Override
              public Boolean compute() {
                return doCreate(
                    project, editor, parameters, constructorPointer, resultParams, usedFields);
              }
            });
  }
  @Nullable
  private static PsiExpression createDefaultValue(
      JavaChangeInfo changeInfo,
      final PsiElementFactory factory,
      final JavaParameterInfo info,
      final PsiExpressionList list)
      throws IncorrectOperationException {
    if (info.isUseAnySingleVariable()) {
      final PsiResolveHelper resolveHelper =
          JavaPsiFacade.getInstance(list.getProject()).getResolveHelper();
      final PsiType type = info.getTypeWrapper().getType(changeInfo.getMethod(), list.getManager());
      final VariablesProcessor processor =
          new VariablesProcessor(false) {
            protected boolean check(PsiVariable var, ResolveState state) {
              if (var instanceof PsiField
                  && !resolveHelper.isAccessible((PsiField) var, list, null)) return false;
              if (var instanceof PsiLocalVariable
                  && list.getTextRange().getStartOffset() <= var.getTextRange().getStartOffset())
                return false;
              if (PsiTreeUtil.isAncestor(var, list, false)) return false;
              final PsiType varType = state.get(PsiSubstitutor.KEY).substitute(var.getType());
              return type.isAssignableFrom(varType);
            }

            public boolean execute(PsiElement pe, ResolveState state) {
              super.execute(pe, state);
              return size() < 2;
            }
          };
      PsiScopesUtil.treeWalkUp(processor, list, null);
      if (processor.size() == 1) {
        final PsiVariable result = processor.getResult(0);
        return factory.createExpressionFromText(result.getName(), list);
      }
      if (processor.size() == 0) {
        final PsiClass parentClass = PsiTreeUtil.getParentOfType(list, PsiClass.class);
        if (parentClass != null) {
          PsiClass containingClass = parentClass;
          final Set<PsiClass> containingClasses = new HashSet<PsiClass>();
          while (containingClass != null) {
            if (type.isAssignableFrom(factory.createType(containingClass, PsiSubstitutor.EMPTY))) {
              containingClasses.add(containingClass);
            }
            containingClass = PsiTreeUtil.getParentOfType(containingClass, PsiClass.class);
          }
          if (containingClasses.size() == 1) {
            return RefactoringUtil.createThisExpression(
                parentClass.getManager(),
                containingClasses.contains(parentClass)
                    ? null
                    : containingClasses.iterator().next());
          }
        }
      }
    }
    final PsiCallExpression callExpression =
        PsiTreeUtil.getParentOfType(list, PsiCallExpression.class);
    final String defaultValue = info.getDefaultValue();
    return callExpression != null
        ? info.getValue(callExpression)
        : defaultValue.length() > 0 ? factory.createExpressionFromText(defaultValue, list) : null;
  }
 private void processVariable(final PsiVariable variable) {
   if (myLineRange.intersects(variable.getTextRange())
       && myVisibleLocals.contains(variable.getName())) {
     myVars.add(variable.getName());
   }
 }
  private static void reportConstantReferenceValues(
      ProblemsHolder holder, StandardInstructionVisitor visitor, Set<PsiElement> reportedAnchors) {
    for (Pair<PsiReferenceExpression, DfaConstValue> pair : visitor.getConstantReferenceValues()) {
      PsiReferenceExpression ref = pair.first;
      if (!reportedAnchors.add(ref)) {
        continue;
      }

      final Object value = pair.second.getValue();
      PsiVariable constant = pair.second.getConstant();
      final String presentableName = constant != null ? constant.getName() : String.valueOf(value);
      final String exprText = getConstantValueText(value, constant);
      if (presentableName == null || exprText == null) {
        continue;
      }

      holder.registerProblem(
          ref,
          "Value <code>#ref</code> #loc is always '" + presentableName + "'",
          new LocalQuickFix() {
            @NotNull
            @Override
            public String getName() {
              return "Replace with '" + presentableName + "'";
            }

            @NotNull
            @Override
            public String getFamilyName() {
              return "Replace with constant value";
            }

            @Override
            public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
              if (!FileModificationService.getInstance()
                  .preparePsiElementsForWrite(descriptor.getPsiElement())) {
                return;
              }

              JavaPsiFacade facade = JavaPsiFacade.getInstance(project);
              PsiElement newElement =
                  descriptor
                      .getPsiElement()
                      .replace(facade.getElementFactory().createExpressionFromText(exprText, null));
              newElement =
                  JavaCodeStyleManager.getInstance(project).shortenClassReferences(newElement);
              if (newElement instanceof PsiJavaCodeReferenceElement) {
                PsiJavaCodeReferenceElement ref = (PsiJavaCodeReferenceElement) newElement;
                PsiElement target = ref.resolve();
                String shortName = ref.getReferenceName();
                if (target != null
                    && shortName != null
                    && ref.isQualified()
                    && facade.getResolveHelper().resolveReferencedVariable(shortName, newElement)
                        == target) {
                  newElement.replace(
                      facade.getElementFactory().createExpressionFromText(shortName, null));
                }
              }
            }
          });
    }
  }
  private static void reportConstantReferenceValues(
      ProblemsHolder holder, StandardInstructionVisitor visitor, Set<PsiElement> reportedAnchors) {
    for (Pair<PsiReferenceExpression, DfaConstValue> pair : visitor.getConstantReferenceValues()) {
      PsiReferenceExpression ref = pair.first;
      if (ref.getParent() instanceof PsiReferenceExpression || !reportedAnchors.add(ref)) {
        continue;
      }

      final Object value = pair.second.getValue();
      PsiVariable constant = pair.second.getConstant();
      final String presentableName = constant != null ? constant.getName() : String.valueOf(value);
      final String exprText = String.valueOf(value);
      if (presentableName == null || exprText == null) {
        continue;
      }

      holder.registerProblem(
          ref,
          "Value <code>#ref</code> #loc is always '" + presentableName + "'",
          new LocalQuickFix() {
            @NotNull
            @Override
            public String getName() {
              return "Replace with '" + presentableName + "'";
            }

            @NotNull
            @Override
            public String getFamilyName() {
              return "Replace with constant value";
            }

            @Override
            public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
              if (!FileModificationService.getInstance()
                  .preparePsiElementsForWrite(descriptor.getPsiElement())) {
                return;
              }

              PsiElement problemElement = descriptor.getPsiElement();
              if (problemElement == null) return;

              PsiMethodCallExpression call =
                  problemElement.getParent() instanceof PsiExpressionList
                          && problemElement.getParent().getParent()
                              instanceof PsiMethodCallExpression
                      ? (PsiMethodCallExpression) problemElement.getParent().getParent()
                      : null;
              PsiMethod targetMethod = call == null ? null : call.resolveMethod();

              JavaPsiFacade facade = JavaPsiFacade.getInstance(project);
              problemElement.replace(
                  facade.getElementFactory().createExpressionFromText(exprText, null));

              if (targetMethod != null) {
                ExtractMethodUtil.addCastsToEnsureResolveTarget(targetMethod, call);
              }
            }
          });
    }
  }
示例#22
0
  @Override
  public void beforeCompletion(@NotNull final CompletionInitializationContext context) {
    final PsiFile file = context.getFile();

    if (file instanceof PsiJavaFile) {
      if (context.getInvocationCount() > 0) {
        autoImport(file, context.getStartOffset() - 1, context.getEditor());

        PsiElement leaf = file.findElementAt(context.getStartOffset() - 1);
        if (leaf != null) leaf = PsiTreeUtil.prevVisibleLeaf(leaf);

        PsiVariable variable = PsiTreeUtil.getParentOfType(leaf, PsiVariable.class);
        if (variable != null) {
          PsiTypeElement typeElement = variable.getTypeElement();
          if (typeElement != null) {
            PsiType type = typeElement.getType();
            if (type instanceof PsiClassType && ((PsiClassType) type).resolve() == null) {
              autoImportReference(
                  file, context.getEditor(), typeElement.getInnermostComponentReferenceElement());
            }
          }
        }
      }

      JavaCompletionUtil.initOffsets(file, context.getOffsetMap());

      if (context.getCompletionType() == CompletionType.BASIC) {
        if (semicolonNeeded(context.getEditor(), file, context.getStartOffset())) {
          context.setDummyIdentifier(CompletionInitializationContext.DUMMY_IDENTIFIER.trim() + ";");
          return;
        }

        final PsiJavaCodeReferenceElement ref =
            PsiTreeUtil.findElementOfClassAtOffset(
                file, context.getStartOffset(), PsiJavaCodeReferenceElement.class, false);
        if (ref != null && !(ref instanceof PsiReferenceExpression)) {
          if (ref.getParent() instanceof PsiTypeElement) {
            context.setDummyIdentifier(
                CompletionInitializationContext.DUMMY_IDENTIFIER.trim() + ";");
          }

          if (JavaSmartCompletionContributor.AFTER_NEW.accepts(ref)) {
            final PsiReferenceParameterList paramList = ref.getParameterList();
            if (paramList != null && paramList.getTextLength() > 0) {
              context
                  .getOffsetMap()
                  .addOffset(
                      ConstructorInsertHandler.PARAM_LIST_START,
                      paramList.getTextRange().getStartOffset());
              context
                  .getOffsetMap()
                  .addOffset(
                      ConstructorInsertHandler.PARAM_LIST_END,
                      paramList.getTextRange().getEndOffset());
            }
          }

          return;
        }

        final PsiElement element = file.findElementAt(context.getStartOffset());

        if (psiElement().inside(PsiAnnotation.class).accepts(element)) {
          return;
        }

        context.setDummyIdentifier(CompletionInitializationContext.DUMMY_IDENTIFIER_TRIMMED);
      }
    }
  }
 public void prepareForDeletion(final PsiElement element) throws IncorrectOperationException {
   if (element instanceof PsiVariable) {
     ((PsiVariable) element).normalizeDeclaration();
   }
 }