예제 #1
0
  public SNode convertField(PsiField x, SNode parentConcept) {
    SNode field;
    if (isStatic(x)
        || SConceptOperations.isSubConceptOf(
            parentConcept, "jetbrains.mps.baseLanguage.structure.Interface")) {
      field =
          SConceptOperations.createNewNode(
              "jetbrains.mps.baseLanguage.structure.StaticFieldDeclaration", null);
    } else {
      field =
          SConceptOperations.createNewNode(
              "jetbrains.mps.baseLanguage.structure.FieldDeclaration", null);
      SPropertyOperations.set(
          SNodeOperations.cast(field, "jetbrains.mps.baseLanguage.structure.FieldDeclaration"),
          "isVolatile",
          "" + (x.hasModifierProperty(PsiModifier.VOLATILE)));
      SPropertyOperations.set(
          SNodeOperations.cast(field, "jetbrains.mps.baseLanguage.structure.FieldDeclaration"),
          "isTransient",
          "" + (x.hasModifierProperty(PsiModifier.TRANSIENT)));
    }

    SPropertyOperations.set(field, "name", x.getName());
    SLinkOperations.setTarget(
        SNodeOperations.cast(field, "jetbrains.mps.baseLanguage.structure.ClassifierMember"),
        "visibility",
        getVisibility(x),
        true);
    SPropertyOperations.set(field, "isFinal", "" + (isFinal(x)));
    SLinkOperations.setTarget(field, "type", convertType(x.getType()), true);
    addAnnotations(x, field);

    return field;
  }
예제 #2
0
 private static PsiField convertFieldToLanguage(PsiField field, Language language) {
   if (field.getLanguage().equals(language)) {
     return field;
   }
   return JVMElementFactories.getFactory(language, field.getProject())
       .createField(field.getName(), field.getType());
 }
 private static boolean doCreate(
     Project project,
     Editor editor,
     PsiParameter[] parameters,
     SmartPsiElementPointer constructorPointer,
     ParameterInfoImpl[] parameterInfos,
     HashMap<PsiField, String> fields) {
   PsiMethod constructor = (PsiMethod) constructorPointer.getElement();
   assert constructor != null;
   PsiParameter[] newParameters = constructor.getParameterList().getParameters();
   if (newParameters == parameters) return false; // user must have canceled dialog
   boolean created = false;
   // do not introduce assignment in chanined constructor
   if (JavaHighlightUtil.getChainedConstructors(constructor) == null) {
     for (PsiField field : fields.keySet()) {
       final String defaultParamName = fields.get(field);
       PsiParameter parameter =
           findParamByName(defaultParamName, field.getType(), newParameters, parameterInfos);
       if (parameter == null) {
         continue;
       }
       notNull(project, field, parameter);
       AssignFieldFromParameterAction.addFieldAssignmentStatement(
           project, field, parameter, editor);
       created = true;
     }
   }
   return created;
 }
  protected void generatePsiElements(
      @NotNull PsiField psiField,
      @NotNull PsiAnnotation psiAnnotation,
      @NotNull List<? super PsiElement> target) {
    final String fieldName = psiField.getName();
    final PsiType psiFieldType = psiField.getType();

    final String methodName = getFindByName(psiField);

    PsiClass psiClass = psiField.getContainingClass();
    assert psiClass != null;

    UserMapKeys.addWriteUsageFor(psiField);

    LombokLightMethodBuilder method =
        new LombokLightMethodBuilder(psiField.getManager(), methodName)
            .withMethodReturnType(PsiTypesUtil.getClassType(psiClass))
            .withContainingClass(psiClass)
            .withParameter(fieldName, psiFieldType)
            .withNavigationElement(psiField);
    method.withModifier(PsiModifier.STATIC);
    method.withModifier(PsiModifier.PUBLIC);

    target.add(method);
  }
 private static String gettext(PsiField field, PsiType uiComponentType) {
   return UIDesignerBundle.message(
       "action.change.field.type",
       field.getName(),
       field.getType().getCanonicalText(),
       uiComponentType.getCanonicalText());
 }
  private static PsiAnnotationMemberValue[] readFromClass(
      @NonNls String attributeName, @NotNull PsiAnnotation magic, PsiType type) {
    PsiAnnotationMemberValue fromClassAttr = magic.findAttributeValue(attributeName);
    PsiType fromClassType =
        fromClassAttr instanceof PsiClassObjectAccessExpression
            ? ((PsiClassObjectAccessExpression) fromClassAttr).getOperand().getType()
            : null;
    PsiClass fromClass =
        fromClassType instanceof PsiClassType ? ((PsiClassType) fromClassType).resolve() : null;
    if (fromClass == null) return null;
    String fqn = fromClass.getQualifiedName();
    if (fqn == null) return null;
    List<PsiAnnotationMemberValue> constants = new ArrayList<PsiAnnotationMemberValue>();
    for (PsiField field : fromClass.getFields()) {
      if (!field.hasModifierProperty(PsiModifier.PUBLIC)
          || !field.hasModifierProperty(PsiModifier.STATIC)
          || !field.hasModifierProperty(PsiModifier.FINAL)) continue;
      PsiType fieldType = field.getType();
      if (!Comparing.equal(fieldType, type)) continue;
      PsiAssignmentExpression e =
          (PsiAssignmentExpression)
              JavaPsiFacade.getElementFactory(field.getProject())
                  .createExpressionFromText("x=" + fqn + "." + field.getName(), field);
      PsiReferenceExpression refToField = (PsiReferenceExpression) e.getRExpression();
      constants.add(refToField);
    }
    if (constants.isEmpty()) return null;

    return constants.toArray(new PsiAnnotationMemberValue[constants.size()]);
  }
 @Nullable
 private static PsiClass resolveExtensionPointClass(PsiField psiField) {
   final PsiType typeParameter =
       PsiUtil.substituteTypeParameter(
           psiField.getType(), ExtensionPointName.class.getName(), 0, false);
   return PsiUtil.resolveClassInClassTypeOnly(typeParameter);
 }
  private static boolean isExtensionPointNameDeclarationField(PsiField psiField) {
    // *do* allow non-public
    if (!psiField.hasModifierProperty(PsiModifier.FINAL)
        || !psiField.hasModifierProperty(PsiModifier.STATIC)
        || psiField.hasModifierProperty(PsiModifier.ABSTRACT)) {
      return false;
    }

    if (!psiField.hasInitializer()) {
      return false;
    }

    final PsiExpression initializer = psiField.getInitializer();
    if (!(initializer instanceof PsiMethodCallExpression)
        && !(initializer instanceof PsiNewExpression)) {
      return false;
    }

    final PsiClass fieldClass = PsiTypesUtil.getPsiClass(psiField.getType());
    if (fieldClass == null) {
      return false;
    }

    return ExtensionPointName.class.getName().equals(fieldClass.getQualifiedName());
  }
예제 #9
0
 @NotNull
 private Field fieldToField(@NotNull PsiField field, PsiClass psiClass) {
   Set<String> modifiers = modifiersListToModifiersSet(field.getModifierList());
   if (field instanceof PsiEnumConstant) // TODO: remove instanceof
   {
     return new EnumConstant(
         new IdentifierImpl(field.getName()), // TODO
         modifiers,
         typeToType(field.getType()),
         elementToElement(((PsiEnumConstant) field).getArgumentList()));
   }
   return new Field(
       new IdentifierImpl(field.getName()), // TODO
       modifiers,
       typeToType(field.getType(), ConverterUtil.isAnnotatedAsNotNull(field.getModifierList())),
       createSureCallOnlyForChain(field.getInitializer(), field.getType()), // TODO: add modifiers
       countWritingAccesses(field, psiClass));
 }
 @Override
 public void visitField(@NotNull PsiField field) {
   super.visitField(field);
   final PsiType type = field.getType();
   if (!type.equalsToText(CommonClassNames.JAVA_LANG_STRING_BUFFER)
       && !type.equalsToText(CommonClassNames.JAVA_LANG_STRING_BUILDER)) {
     return;
   }
   registerFieldError(field, type);
 }
예제 #11
0
  public static PsiMethod generateSetterPrototype(
      PsiField field, final PsiClass containingClass, boolean returnSelf) {
    Project project = field.getProject();
    JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project);
    PsiElementFactory factory = JavaPsiFacade.getInstance(field.getProject()).getElementFactory();

    String name = field.getName();
    boolean isStatic = field.hasModifierProperty(PsiModifier.STATIC);
    VariableKind kind = codeStyleManager.getVariableKind(field);
    String propertyName = codeStyleManager.variableNameToPropertyName(name, kind);
    String setName = suggestSetterName(project, field);
    try {
      PsiMethod setMethod =
          factory.createMethod(
              setName, returnSelf ? factory.createType(containingClass) : PsiType.VOID);
      String parameterName =
          codeStyleManager.propertyNameToVariableName(propertyName, VariableKind.PARAMETER);
      PsiParameter param = factory.createParameter(parameterName, field.getType());

      annotateWithNullableStuff(field, factory, param);

      setMethod.getParameterList().add(param);
      PsiUtil.setModifierProperty(setMethod, PsiModifier.PUBLIC, true);
      PsiUtil.setModifierProperty(setMethod, PsiModifier.STATIC, isStatic);

      @NonNls StringBuffer buffer = new StringBuffer();
      buffer.append("{\n");
      if (name.equals(parameterName)) {
        if (!isStatic) {
          buffer.append("this.");
        } else {
          String className = containingClass.getName();
          if (className != null) {
            buffer.append(className);
            buffer.append(".");
          }
        }
      }
      buffer.append(name);
      buffer.append("=");
      buffer.append(parameterName);
      buffer.append(";\n");
      if (returnSelf) {
        buffer.append("return this;\n");
      }
      buffer.append("}");
      PsiCodeBlock body = factory.createCodeBlockFromText(buffer.toString(), null);
      setMethod.getBody().replace(body);
      setMethod = (PsiMethod) CodeStyleManager.getInstance(project).reformat(setMethod);
      return setMethod;
    } catch (IncorrectOperationException e) {
      LOG.error(e);
      return null;
    }
  }
  private PsiMethod generateMethodFor(
      PsiField field, String methodName, String parameterName, PsiElementFactory elementFactory) {
    PsiMethod withMethod =
        elementFactory.createMethod(
            methodName, elementFactory.createType(field.getContainingClass()));
    PsiParameter parameter = elementFactory.createParameter(parameterName, field.getType());
    withMethod.getParameterList().add(parameter);
    PsiUtil.setModifierProperty(withMethod, PsiModifier.PUBLIC, true);

    return withMethod;
  }
 private static boolean isCompileTimeFlagReference(PsiElement element) {
   PsiElement resolved =
       element instanceof PsiReferenceExpression
           ? ((PsiReferenceExpression) element).resolve()
           : null;
   if (!(resolved instanceof PsiField)) return false;
   PsiField field = (PsiField) resolved;
   return field.hasModifierProperty(PsiModifier.FINAL)
       && field.hasModifierProperty(PsiModifier.STATIC)
       && PsiType.BOOLEAN.equals(field.getType());
 }
예제 #14
0
 public ChangeFieldTypeFix(GuiEditor uiEditor, PsiField field, PsiType uiComponentType) {
   super(
       uiEditor,
       MessageFormat.format(
           UIDesignerBundle.message("action.change.field.type"),
           field.getName(),
           field.getType().getCanonicalText(),
           uiComponentType.getCanonicalText()),
       null);
   myField = field;
   myNewType = uiComponentType;
 }
  @Test
  public void shouldNotVerifyThatFieldIsSetInConstructorIfConstructorHasDifferentParameterName() {
    // given
    prepareBehaviourForReturningParameter();
    given(parameter.getType()).willReturn(psiType);
    given(psiField.getType()).willReturn(psiType);
    given(parameter.getName()).willReturn(name);
    given(psiField.getName()).willReturn("differentName");

    // when
    boolean result = psiFieldVerifier.isSetInConstructor(psiField, psiClass);

    // then
    assertThat(result, is(false));
  }
 @Override
 public String readValue(PsiField field, String in) {
   String fieldName = field.getName();
   String tmpFieldName = NameUtil.upperCaseFirstLetter(fieldName);
   String format =
       "int tmp%s = %s.readInt();" + "this.%s = tmp%s == -1 ? null : %s.values()[tmp%s];";
   return String.format(
       format,
       tmpFieldName,
       in,
       fieldName,
       tmpFieldName,
       field.getType().getCanonicalText(),
       tmpFieldName);
 }
예제 #17
0
    private PsiElement addDeclarationWithFieldInitializerAndRetargetReferences(
        final PsiElementFactory elementFactory,
        final String localName,
        final PsiCodeBlock anchorBlock,
        final PsiElement anchor,
        final Set<PsiReference> refs)
        throws IncorrectOperationException {
      final PsiDeclarationStatement decl =
          elementFactory.createVariableDeclarationStatement(
              localName, myField.getType(), myField.getInitializer());
      final PsiElement newDeclaration = anchorBlock.addBefore(decl, anchor);

      retargetReferences(elementFactory, localName, refs);
      return newDeclaration;
    }
 public boolean satisfiedBy(PsiElement element) {
   if (!(element instanceof PsiSwitchStatement)) {
     return false;
   }
   final PsiSwitchStatement switchStatement = (PsiSwitchStatement) element;
   final PsiCodeBlock body = switchStatement.getBody();
   if (body == null) {
     return false;
   }
   final PsiExpression expression = switchStatement.getExpression();
   if (expression == null) {
     return false;
   }
   final PsiType type = expression.getType();
   if (!(type instanceof PsiClassType)) {
     return false;
   }
   final PsiClass enumClass = ((PsiClassType) type).resolve();
   if (enumClass == null || !enumClass.isEnum()) {
     return false;
   }
   final PsiField[] fields = enumClass.getFields();
   final Set<String> enumElements = new HashSet<String>(fields.length);
   for (final PsiField field : fields) {
     final PsiType fieldType = field.getType();
     if (fieldType.equals(type)) {
       final String fieldName = field.getName();
       enumElements.add(fieldName);
     }
   }
   final PsiStatement[] statements = body.getStatements();
   for (PsiStatement statement : statements) {
     if (statement instanceof PsiSwitchLabelStatement) {
       final PsiSwitchLabelStatement labelStatement = (PsiSwitchLabelStatement) statement;
       final PsiExpression value = labelStatement.getCaseValue();
       if (value != null) {
         final String valueText = value.getText();
         enumElements.remove(valueText);
       }
     }
   }
   if (enumElements.isEmpty()) {
     return false;
   }
   return !ErrorUtil.containsError(element);
 }
예제 #19
0
  @Nullable
  public static PsiField findPropertyFieldWithType(
      Project project,
      String propertyName,
      boolean isStatic,
      PsiType type,
      Iterator<PsiField> fields) {
    while (fields.hasNext()) {
      PsiField field = fields.next();
      if (field.hasModifierProperty(PsiModifier.STATIC) != isStatic) continue;
      if (propertyName.equals(suggestPropertyName(project, field))) {
        if (type.equals(field.getType())) return field;
      }
    }

    return null;
  }
 @Override
 public void visitField(@NotNull PsiField field) {
   if (field.hasModifierProperty(PsiModifier.STATIC)) {
     return;
   }
   if (field.getInitializer() != null) {
     return;
   }
   final PsiAnnotation annotation = AnnotationUtil.findAnnotation(field, annotationNames);
   if (annotation != null) {
     return;
   }
   if (m_ignorePrimitives) {
     final PsiType fieldType = field.getType();
     if (ClassUtils.isPrimitive(fieldType)) {
       return;
     }
   }
   final PsiClass aClass = field.getContainingClass();
   if (aClass == null) {
     return;
   }
   for (ImplicitUsageProvider provider :
       Extensions.getExtensions(ImplicitUsageProvider.EP_NAME)) {
     if (provider.isImplicitWrite(field)) {
       return;
     }
   }
   final UninitializedReadCollector uninitializedReadsCollector =
       new UninitializedReadCollector();
   if (!isInitializedInInitializer(field, uninitializedReadsCollector)) {
     final PsiMethod[] constructors = aClass.getConstructors();
     for (final PsiMethod constructor : constructors) {
       final PsiCodeBlock body = constructor.getBody();
       uninitializedReadsCollector.blockAssignsVariable(body, field);
     }
   }
   final PsiExpression[] badReads = uninitializedReadsCollector.getUninitializedReads();
   for (PsiExpression expression : badReads) {
     registerError(expression);
   }
 }
  /**
   * Create a new {@link FieldElement} object.
   *
   * @param field the {@link com.intellij.psi.PsiField} to get the information from.
   * @return a new {@link FieldElement} object.
   */
  public static FieldElement newFieldElement(PsiField field, boolean useAccessor) {
    FieldElement fe = new FieldElement();
    fe.setName(field.getName());
    final PsiMethod getterForField = useAccessor ? PropertyUtil.findGetterForField(field) : null;
    fe.setAccessor(getterForField != null ? getterForField.getName() + "()" : field.getName());

    if (PsiAdapter.isConstantField(field)) fe.setConstant(true);
    if (PsiAdapter.isEnumField(field)) fe.setEnum(true);
    PsiModifierList modifiers = field.getModifierList();
    if (modifiers != null) {
      if (modifiers.hasModifierProperty(PsiModifier.TRANSIENT)) fe.setModifierTransient(true);
      if (modifiers.hasModifierProperty(PsiModifier.VOLATILE)) fe.setModifierVolatile(true);
    }

    PsiElementFactory factory = JavaPsiFacade.getInstance(field.getProject()).getElementFactory();
    PsiType type = field.getType();
    setElementInfo(fe, factory, type, modifiers);

    return fe;
  }
  @Override
  public void readMethod(PsiCodeBlock methodBody, PsiElementFactory factory, PsiField field) {
    if (null == methodBody) {
      return;
    }

    String fieldName = field.getName();
    String parameterType =
        ((PsiClassReferenceType) field.getType()).getParameters()[0].getPresentableText();

    //        // phones = new ArrayList<>();
    //        // in.readTypedList(phones, Phone.CREATOR);
    //        methodBody.add(factory.createStatementFromText(fieldName + " = new ArrayList<" +
    // parameterType + ">();", null));
    //        methodBody.add(factory.createStatementFromText("in.readTypedList(" + fieldName + ", "
    // + parameterType + ".CREATOR);", null));

    // phones = in.createTypedArrayList(Phone.CREATOR);
    methodBody.add(
        factory.createStatementFromText(
            fieldName + " = in.createTypedArrayList(" + parameterType + ".CREATOR);", null));
  }
  private static void addParameters(
      @NotNull PsiClass psiClass,
      GrLightMethodBuilder fieldsConstructor,
      boolean includeProperties,
      boolean includeFields,
      boolean optional,
      Set<String> excludes) {

    PsiMethod[] methods = CollectClassMembersUtil.getMethods(psiClass, false);
    if (includeProperties) {
      for (PsiMethod method : methods) {
        if (!method.hasModifierProperty(PsiModifier.STATIC)
            && PropertyUtil.isSimplePropertySetter(method)) {
          final String name = PropertyUtil.getPropertyNameBySetter(method);
          if (!excludes.contains(name)) {
            final PsiType type = PropertyUtil.getPropertyType(method);
            assert type != null : method;
            fieldsConstructor.addParameter(
                new GrLightParameter(name, type, fieldsConstructor).setOptional(optional));
          }
        }
      }
    }

    final Map<String, PsiMethod> properties = PropertyUtil.getAllProperties(true, false, methods);
    for (PsiField field : CollectClassMembersUtil.getFields(psiClass, false)) {
      final String name = field.getName();
      if (includeFields
          || includeProperties && field instanceof GrField && ((GrField) field).isProperty()) {
        if (!excludes.contains(name)
            && !field.hasModifierProperty(PsiModifier.STATIC)
            && !properties.containsKey(name)) {
          fieldsConstructor.addParameter(
              new GrLightParameter(name, field.getType(), fieldsConstructor).setOptional(optional));
        }
      }
    }
  }
예제 #24
0
  public static PsiMethod generateGetterPrototype(PsiField field) {
    PsiElementFactory factory = JavaPsiFacade.getInstance(field.getProject()).getElementFactory();
    Project project = field.getProject();
    String name = field.getName();
    String getName = suggestGetterName(project, field);
    try {
      PsiMethod getMethod = factory.createMethod(getName, field.getType());
      PsiUtil.setModifierProperty(getMethod, PsiModifier.PUBLIC, true);
      if (field.hasModifierProperty(PsiModifier.STATIC)) {
        PsiUtil.setModifierProperty(getMethod, PsiModifier.STATIC, true);
      }

      annotateWithNullableStuff(field, factory, getMethod);

      PsiCodeBlock body = factory.createCodeBlockFromText("{\nreturn " + name + ";\n}", null);
      getMethod.getBody().replace(body);
      getMethod = (PsiMethod) CodeStyleManager.getInstance(project).reformat(getMethod);
      return getMethod;
    } catch (IncorrectOperationException e) {
      LOG.error(e);
      return null;
    }
  }
  @Override
  public void processElement(
      @NotNull PsiClass parent, @NotNull PsiField psiField, @NotNull List<PsiElement> result) {
    LightMethodBuilder builder =
        new LightMethodBuilder(
            parent.getManager(), parent.getLanguage(), PropertyUtil.suggestSetterName(psiField));
    builder.setMethodReturnType(PsiType.VOID);
    builder.setContainingClass(parent);
    builder.setNavigationElement(psiField);

    builder.addParameter(psiField.getName(), psiField.getType());

    if (psiField.hasModifierProperty(PsiModifier.STATIC)) {
      builder.addModifier(PsiModifier.STATIC);
    }

    PsiAnnotation annotation = getAffectedAnnotation(psiField);

    LombokUtil.setAccessModifierFromAnnotation(
        annotation, builder, PsiAnnotation.DEFAULT_REFERENCED_METHOD_NAME);

    result.add(builder);
  }
  /**
   * spring bean reference annotator
   *
   * @param psiElement psi element
   * @param holder annotation holder
   */
  public void annotate(PsiElement psiElement, AnnotationHolder holder) {
    if (!(psiElement instanceof PsiJavaFile)) {
      return;
    }

    // Get java classes
    for (PsiClass javaClass : ((PsiJavaFile) psiElement).getClasses()) {

      PsiClass superClass = javaClass.getSuperClass();
      PsiField[] superClassFields =
          superClass != null ? superClass.getAllFields() : new PsiField[] {};
      for (PsiField field : javaClass.getAllFields()) {
        // We don't need scan super class fields
        if (isContain(superClassFields, field)) {
          continue;
        }

        PsiModifierList modifierList = field.getModifierList();
        if (modifierList == null) {
          continue;
        }
        for (PsiAnnotation psiAnnotation : modifierList.getAnnotations()) {
          String qcName = psiAnnotation.getQualifiedName();
          if (qcName == null || !qcName.startsWith("org.unitils.spring.annotation.")) {
            continue;
          }

          SpringManager springManager = SpringManager.getInstance(psiElement.getProject());
          SpringModel springModel =
              springManager.getCombinedModel(ModuleUtil.findModuleForPsiElement(psiElement));
          if (springModel == null) {
            continue;
          }

          // by type
          if (qcName.endsWith("SpringBeanByType")) {
            final PsiType type = field.getType();
            if (!(type instanceof PsiClassType)) {
              continue;
            }
            final PsiClass typeClass = ((PsiClassType) type).resolve();
            if (typeClass == null) {
              continue;
            }
            List<SpringBaseBeanPointer> springBaseBeanPointerList =
                springModel.findBeansByPsiClass(typeClass);
            if (springBaseBeanPointerList.size() > 0) {
              List<PsiElement> elements = new ArrayList<PsiElement>();
              for (SpringBaseBeanPointer springBaseBeanPointer : springBaseBeanPointerList) {
                elements.add(springBaseBeanPointer.getPsiElement());
              }
              NavigationGutterIconBuilder.create(SpringIcons.SPRING_BEAN_ICON)
                  .setTooltipText("Navigate to the spring bean declaration(s)")
                  .setTargets(elements)
                  .install(holder, field.getNameIdentifier());
            }
          }
          // by name
          else {
            String beanName = field.getName();
            if (qcName.endsWith("SpringBean")) {
              PsiAnnotationMemberValue attributeValue = psiAnnotation.findAttributeValue("value");
              if (attributeValue != null && attributeValue.getText() != null) {
                beanName = attributeValue.getText().replace("\"", "");
              }
            }
            if (beanName != null && StringUtil.isNotEmpty(beanName)) {
              SpringBeanPointer springBeanPointer = springModel.findBeanByName(beanName);
              if (springBeanPointer != null) {
                NavigationGutterIconBuilder.create(SpringIcons.SPRING_BEAN_ICON)
                    .setTooltipText("Navigate to the spring bean declaration(s)")
                    .setTarget(springBeanPointer.getPsiElement())
                    .install(holder, field.getNameIdentifier());
              }
            }
          }
        }
      }
    }
  }
 @Override
 @NotNull
 public PsiElement[] getSecondaryElements() {
   PsiElement element = getPsiElement();
   if (ApplicationManager.getApplication().isUnitTestMode()) return PsiElement.EMPTY_ARRAY;
   if (element instanceof PsiField) {
     final PsiField field = (PsiField) element;
     PsiClass containingClass = field.getContainingClass();
     if (containingClass != null) {
       String fieldName = field.getName();
       final String propertyName =
           JavaCodeStyleManager.getInstance(getProject())
               .variableNameToPropertyName(fieldName, VariableKind.FIELD);
       Set<PsiMethod> accessors = new THashSet<PsiMethod>();
       boolean isStatic = field.hasModifierProperty(PsiModifier.STATIC);
       PsiMethod getter =
           PropertyUtil.findPropertyGetterWithType(
               propertyName,
               isStatic,
               field.getType(),
               ContainerUtil.iterate(containingClass.getMethods()));
       if (getter != null) accessors.add(getter);
       PsiMethod setter =
           PropertyUtil.findPropertySetterWithType(
               propertyName,
               isStatic,
               field.getType(),
               ContainerUtil.iterate(containingClass.getMethods()));
       if (setter != null) accessors.add(setter);
       accessors.addAll(PropertyUtil.getAccessors(containingClass, fieldName));
       if (!accessors.isEmpty()) {
         final boolean doSearch;
         boolean containsPhysical =
             ContainerUtil.find(
                     accessors,
                     new Condition<PsiMethod>() {
                       @Override
                       public boolean value(PsiMethod psiMethod) {
                         return psiMethod.isPhysical();
                       }
                     })
                 != null;
         if (!containsPhysical) {
           doSearch = true;
         } else {
           doSearch =
               Messages.showOkCancelDialog(
                       FindBundle.message("find.field.accessors.prompt", fieldName),
                       FindBundle.message("find.field.accessors.title"),
                       CommonBundle.getYesButtonText(),
                       CommonBundle.getNoButtonText(),
                       Messages.getQuestionIcon())
                   == DialogWrapper.OK_EXIT_CODE;
         }
         if (doSearch) {
           final Set<PsiElement> elements = new THashSet<PsiElement>();
           for (PsiMethod accessor : accessors) {
             ContainerUtil.addAll(
                 elements, SuperMethodWarningUtil.checkSuperMethods(accessor, ACTION_STRING));
           }
           return PsiUtilBase.toPsiElementArray(elements);
         }
       }
     }
   }
   return super.getSecondaryElements();
 }
  public static PsiMethod generateConstructorPrototype(
      PsiClass aClass, PsiMethod baseConstructor, boolean copyJavaDoc, PsiField[] fields)
      throws IncorrectOperationException {
    PsiManager manager = aClass.getManager();
    JVMElementFactory factory =
        JVMElementFactories.requireFactory(aClass.getLanguage(), aClass.getProject());
    CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(manager.getProject());

    PsiMethod constructor = factory.createConstructor(aClass.getName(), aClass);
    String modifier = PsiUtil.getMaximumModifierForMember(aClass, false);

    if (modifier != null) {
      PsiUtil.setModifierProperty(constructor, modifier, true);
    }

    if (baseConstructor != null) {
      PsiJavaCodeReferenceElement[] throwRefs =
          baseConstructor.getThrowsList().getReferenceElements();
      for (PsiJavaCodeReferenceElement ref : throwRefs) {
        constructor.getThrowsList().add(ref);
      }

      if (copyJavaDoc) {
        final PsiDocComment docComment =
            ((PsiMethod) baseConstructor.getNavigationElement()).getDocComment();
        if (docComment != null) {
          constructor.addAfter(docComment, null);
        }
      }
    }

    boolean isNotEnum = false;
    if (baseConstructor != null) {
      PsiClass superClass = aClass.getSuperClass();
      LOG.assertTrue(superClass != null);
      if (!CommonClassNames.JAVA_LANG_ENUM.equals(superClass.getQualifiedName())) {
        isNotEnum = true;
        if (baseConstructor instanceof PsiCompiledElement) { // to get some parameter names
          PsiClass dummyClass =
              JVMElementFactories.requireFactory(
                      baseConstructor.getLanguage(), baseConstructor.getProject())
                  .createClass("Dummy");
          baseConstructor = (PsiMethod) dummyClass.add(baseConstructor);
        }
        PsiParameter[] params = baseConstructor.getParameterList().getParameters();
        for (PsiParameter param : params) {
          PsiParameter newParam = factory.createParameter(param.getName(), param.getType(), aClass);
          GenerateMembersUtil.copyOrReplaceModifierList(param, newParam);
          constructor.getParameterList().add(newParam);
        }
      }
    }

    JavaCodeStyleManager javaStyle = JavaCodeStyleManager.getInstance(aClass.getProject());

    final PsiMethod dummyConstructor = factory.createConstructor(aClass.getName());
    dummyConstructor.getParameterList().replace(constructor.getParameterList().copy());
    List<PsiParameter> fieldParams = new ArrayList<PsiParameter>();
    for (PsiField field : fields) {
      String fieldName = field.getName();
      String name = javaStyle.variableNameToPropertyName(fieldName, VariableKind.FIELD);
      String parmName = javaStyle.propertyNameToVariableName(name, VariableKind.PARAMETER);
      parmName = javaStyle.suggestUniqueVariableName(parmName, dummyConstructor, true);
      PsiParameter parm = factory.createParameter(parmName, field.getType(), aClass);

      final NullableNotNullManager nullableManager =
          NullableNotNullManager.getInstance(field.getProject());
      final String notNull = nullableManager.getNotNull(field);
      if (notNull != null) {
        parm.getModifierList()
            .addAfter(factory.createAnnotationFromText("@" + notNull, field), null);
      }

      constructor.getParameterList().add(parm);
      dummyConstructor.getParameterList().add(parm.copy());
      fieldParams.add(parm);
    }

    ConstructorBodyGenerator generator =
        ConstructorBodyGenerator.INSTANCE.forLanguage(aClass.getLanguage());
    if (generator != null) {
      @NonNls StringBuilder buffer = new StringBuilder();
      generator.start(buffer, constructor.getName(), PsiParameter.EMPTY_ARRAY);
      if (isNotEnum) {
        generator.generateSuperCallIfNeeded(
            buffer, baseConstructor.getParameterList().getParameters());
      }
      generator.generateFieldInitialization(
          buffer, fields, fieldParams.toArray(new PsiParameter[fieldParams.size()]));
      generator.finish(buffer);
      PsiMethod stub = factory.createMethodFromText(buffer.toString(), aClass);
      constructor.getBody().replace(stub.getBody());
    }

    constructor = (PsiMethod) codeStyleManager.reformat(constructor);
    return constructor;
  }
  private static void prepareFieldRenaming(
      PsiField field, String newName, final Map<PsiElement, String> allRenames) {
    // search for getters/setters
    PsiClass aClass = field.getContainingClass();

    Project project = field.getProject();
    final JavaCodeStyleManager manager = JavaCodeStyleManager.getInstance(project);

    final String propertyName = PropertyUtil.suggestPropertyName(field, field.getName());
    final String newPropertyName = PropertyUtil.suggestPropertyName(field, newName);

    boolean isStatic = field.hasModifierProperty(PsiModifier.STATIC);

    PsiMethod[] getters = GetterSetterPrototypeProvider.findGetters(aClass, propertyName, isStatic);

    PsiMethod setter = PropertyUtil.findPropertySetter(aClass, propertyName, isStatic, false);

    boolean shouldRenameSetterParameter = false;

    if (setter != null) {
      shouldRenameSetterParameter = shouldRenameSetterParameter(manager, propertyName, setter);
    }

    if (getters != null) {
      List<PsiMethod> validGetters = new ArrayList<>();
      for (PsiMethod getter : getters) {
        String newGetterName =
            GetterSetterPrototypeProvider.suggestNewGetterName(
                propertyName, newPropertyName, getter);
        String getterId = null;
        if (newGetterName == null) {
          getterId = getter.getName();
          newGetterName =
              PropertyUtil.suggestGetterName(newPropertyName, field.getType(), getterId);
        }
        if (newGetterName.equals(getterId)) {
          continue;
        } else {
          boolean valid = true;
          for (PsiMethod method : getter.findDeepestSuperMethods()) {
            if (method instanceof PsiCompiledElement) {
              valid = false;
              break;
            }
          }
          if (!valid) continue;
        }
        validGetters.add(getter);
      }
      getters =
          validGetters.isEmpty() ? null : validGetters.toArray(new PsiMethod[validGetters.size()]);
    }

    String newSetterName = "";
    if (setter != null) {
      newSetterName = PropertyUtil.suggestSetterName(newPropertyName);
      final String newSetterParameterName =
          manager.propertyNameToVariableName(newPropertyName, VariableKind.PARAMETER);
      if (newSetterName.equals(setter.getName())) {
        setter = null;
        newSetterName = null;
        shouldRenameSetterParameter = false;
      } else if (newSetterParameterName.equals(
          setter.getParameterList().getParameters()[0].getName())) {
        shouldRenameSetterParameter = false;
      } else {
        for (PsiMethod method : setter.findDeepestSuperMethods()) {
          if (method instanceof PsiCompiledElement) {
            setter = null;
            shouldRenameSetterParameter = false;
            break;
          }
        }
      }
    }

    if ((getters != null || setter != null)
        && askToRenameAccesors(getters != null ? getters[0] : null, setter, newName, project)) {
      getters = null;
      setter = null;
      shouldRenameSetterParameter = false;
    }

    if (getters != null) {
      for (PsiMethod getter : getters) {
        String newGetterName =
            GetterSetterPrototypeProvider.suggestNewGetterName(
                propertyName, newPropertyName, getter);
        if (newGetterName == null) {
          newGetterName =
              PropertyUtil.suggestGetterName(newPropertyName, field.getType(), getter.getName());
        }
        addOverriddenAndImplemented(getter, newGetterName, null, propertyName, manager, allRenames);
      }
    }

    if (setter != null) {
      addOverriddenAndImplemented(
          setter,
          newSetterName,
          shouldRenameSetterParameter ? newPropertyName : null,
          propertyName,
          manager,
          allRenames);
    }
  }
 private boolean checkCondition(
     @Nullable PsiExpression condition,
     @NotNull PsiStatement context,
     List<PsiExpression> notUpdated) {
   if (condition == null) {
     return false;
   }
   if (PsiUtil.isConstantExpression(condition) || PsiKeyword.NULL.equals(condition.getText())) {
     return true;
   }
   if (condition instanceof PsiInstanceOfExpression) {
     final PsiInstanceOfExpression instanceOfExpression = (PsiInstanceOfExpression) condition;
     final PsiExpression operand = instanceOfExpression.getOperand();
     return checkCondition(operand, context, notUpdated);
   } else if (condition instanceof PsiParenthesizedExpression) {
     // catch stuff like "while ((x)) { ... }"
     final PsiExpression expression = ((PsiParenthesizedExpression) condition).getExpression();
     return checkCondition(expression, context, notUpdated);
   } else if (condition instanceof PsiPolyadicExpression) {
     // while (value != x) { ... }
     // while (value != (x + y)) { ... }
     // while (b1 && b2) { ... }
     final PsiPolyadicExpression polyadicExpression = (PsiPolyadicExpression) condition;
     for (PsiExpression operand : polyadicExpression.getOperands()) {
       if (!checkCondition(operand, context, notUpdated)) {
         return false;
       }
     }
     return true;
   } else if (condition instanceof PsiReferenceExpression) {
     final PsiReferenceExpression referenceExpression = (PsiReferenceExpression) condition;
     final PsiElement element = referenceExpression.resolve();
     if (element instanceof PsiField) {
       final PsiField field = (PsiField) element;
       final PsiType type = field.getType();
       if (field.hasModifierProperty(PsiModifier.FINAL) && type.getArrayDimensions() == 0) {
         if (field.hasModifierProperty(PsiModifier.STATIC)) {
           return true;
         }
         final PsiExpression qualifier = referenceExpression.getQualifierExpression();
         if (qualifier == null) {
           return true;
         } else if (checkCondition(qualifier, context, notUpdated)) {
           return true;
         }
       }
     } else if (element instanceof PsiVariable) {
       final PsiVariable variable = (PsiVariable) element;
       if (variable.hasModifierProperty(PsiModifier.FINAL)) {
         // final variables cannot be updated, don't bother to
         // flag them
         return true;
       } else if (element instanceof PsiLocalVariable || element instanceof PsiParameter) {
         if (!VariableAccessUtils.variableIsAssigned(variable, context)) {
           notUpdated.add(referenceExpression);
           return true;
         }
       }
     }
   } else if (condition instanceof PsiPrefixExpression) {
     final PsiPrefixExpression prefixExpression = (PsiPrefixExpression) condition;
     final IElementType tokenType = prefixExpression.getOperationTokenType();
     if (JavaTokenType.EXCL.equals(tokenType)
         || JavaTokenType.PLUS.equals(tokenType)
         || JavaTokenType.MINUS.equals(tokenType)) {
       final PsiExpression operand = prefixExpression.getOperand();
       return checkCondition(operand, context, notUpdated);
     }
   } else if (condition instanceof PsiArrayAccessExpression) {
     // Actually the contents of the array could change nevertheless
     // if it is accessed through a different reference like this:
     //   int[] local_ints = new int[]{1, 2};
     //   int[] other_ints = local_ints;
     //   while (local_ints[0] > 0) { other_ints[0]--; }
     //
     // Keep this check?
     final PsiArrayAccessExpression accessExpression = (PsiArrayAccessExpression) condition;
     final PsiExpression indexExpression = accessExpression.getIndexExpression();
     return checkCondition(indexExpression, context, notUpdated)
         && checkCondition(accessExpression.getArrayExpression(), context, notUpdated);
   } else if (condition instanceof PsiConditionalExpression) {
     final PsiConditionalExpression conditionalExpression = (PsiConditionalExpression) condition;
     final PsiExpression thenExpression = conditionalExpression.getThenExpression();
     final PsiExpression elseExpression = conditionalExpression.getElseExpression();
     if (thenExpression == null || elseExpression == null) {
       return false;
     }
     return checkCondition(conditionalExpression.getCondition(), context, notUpdated)
         && checkCondition(thenExpression, context, notUpdated)
         && checkCondition(elseExpression, context, notUpdated);
   } else if (condition instanceof PsiThisExpression) {
     return true;
   } else if (condition instanceof PsiMethodCallExpression && !ignoreIterators) {
     final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression) condition;
     if (!IteratorUtils.isCallToHasNext(methodCallExpression)) {
       return false;
     }
     final PsiReferenceExpression methodExpression = methodCallExpression.getMethodExpression();
     final PsiExpression qualifierExpression = methodExpression.getQualifierExpression();
     if (qualifierExpression instanceof PsiReferenceExpression) {
       final PsiReferenceExpression referenceExpression =
           (PsiReferenceExpression) qualifierExpression;
       final PsiElement element = referenceExpression.resolve();
       if (!(element instanceof PsiVariable)) {
         return false;
       }
       final PsiVariable variable = (PsiVariable) element;
       if (!IteratorUtils.containsCallToScannerNext(context, variable, true)) {
         notUpdated.add(qualifierExpression);
         return true;
       }
     } else {
       if (!IteratorUtils.containsCallToScannerNext(context, null, true)) {
         notUpdated.add(methodCallExpression);
         return true;
       }
     }
   }
   return false;
 }