Exemplo n.º 1
0
  private static void docheckClass(final PsiClass aClass, ProblemsHolder holder) {
    if (aClass.isInterface()) return;
    final PsiField[] fields = aClass.getFields();
    final Set<PsiField> candidates = new LinkedHashSet<PsiField>();
    for (PsiField field : fields) {
      if (field.hasModifierProperty(PsiModifier.PRIVATE)
          && !(field.hasModifierProperty(PsiModifier.STATIC)
              && field.hasModifierProperty(PsiModifier.FINAL))) {
        candidates.add(field);
      }
    }

    removeFieldsReferencedFromInitializers(aClass, candidates);
    if (candidates.isEmpty()) return;

    final Set<PsiField> usedFields = new THashSet<PsiField>();
    removeReadFields(aClass, candidates, usedFields);

    if (candidates.isEmpty()) return;
    final ImplicitUsageProvider[] implicitUsageProviders =
        Extensions.getExtensions(ImplicitUsageProvider.EP_NAME);

    for (PsiField field : candidates) {
      if (usedFields.contains(field)
          && !hasImplicitReadOrWriteUsage(field, implicitUsageProviders)) {
        final String message =
            InspectionsBundle.message("inspection.field.can.be.local.problem.descriptor");
        holder.registerProblem(field.getNameIdentifier(), message, new MyQuickFix(field));
      }
    }
  }
  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()]);
  }
  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());
  }
 @Nullable
 private static String getCannotRefactorMessage(PsiMember member) {
   if (member == null) {
     return RefactoringBundle.message("locate.caret.inside.a.method");
   }
   if (member instanceof PsiMethod) {
     if (((PsiMethod) member).isConstructor()) {
       return RefactoringBundle.message("replace.with.method.call.does.not.work.for.constructors");
     }
     final PsiCodeBlock body = ((PsiMethod) member).getBody();
     if (body == null) {
       return RefactoringBundle.message("method.does.not.have.a.body", member.getName());
     }
     final PsiStatement[] statements = body.getStatements();
     if (statements.length == 0) {
       return RefactoringBundle.message("method.has.an.empty.body", member.getName());
     }
   } else if (member instanceof PsiField) {
     final PsiField field = (PsiField) member;
     if (field.getInitializer() == null) {
       return "Field " + member.getName() + " doesn't have initializer";
     }
     final PsiClass containingClass = field.getContainingClass();
     if (!field.hasModifierProperty(PsiModifier.FINAL)
         || !field.hasModifierProperty(PsiModifier.STATIC)
         || containingClass == null
         || containingClass.getQualifiedName() == null) {
       return "Replace Duplicates works with constants only";
     }
   } else {
     return "Caret should be inside method or constant";
   }
   return null;
 }
Exemplo n.º 5
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;
  }
 @Override
 public void visitField(@NotNull PsiField field) {
   if (!field.hasModifierProperty(PsiModifier.STATIC)
       || field.hasModifierProperty(PsiModifier.FINAL)) {
     return;
   }
   registerFieldError(field, field);
 }
 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());
 }
  private void generateAccessors() {
    // generate accessors
    myNameToGetter = new HashMap<String, PsiMethod>();
    myNameToSetter = new HashMap<String, PsiMethod>();

    for (FieldDescriptor fieldDescriptor : myFieldDescriptors) {
      final DocCommentPolicy<PsiDocComment> commentPolicy =
          new DocCommentPolicy<PsiDocComment>(myDescriptor.getJavadocPolicy());

      PsiField field = fieldDescriptor.getField();
      final PsiDocComment docComment = field.getDocComment();
      if (myDescriptor.isToEncapsulateGet()) {
        final PsiMethod prototype = fieldDescriptor.getGetterPrototype();
        assert prototype != null;
        final PsiMethod getter = addOrChangeAccessor(prototype, myNameToGetter);
        if (docComment != null) {
          final PsiDocComment getterJavadoc =
              (PsiDocComment) getter.addBefore(docComment, getter.getFirstChild());
          commentPolicy.processNewJavaDoc(getterJavadoc);
        }
      }
      if (myDescriptor.isToEncapsulateSet() && !field.hasModifierProperty(PsiModifier.FINAL)) {
        PsiMethod prototype = fieldDescriptor.getSetterPrototype();
        assert prototype != null;
        addOrChangeAccessor(prototype, myNameToSetter);
      }

      if (docComment != null) {
        commentPolicy.processOldJavaDoc(docComment);
      }
    }
  }
  public FieldConflictsResolver(String name, GrCodeBlock scope) {
    myScope = scope;
    if (myScope == null) return;

    final GroovyPsiElement resolved = ResolveUtil.resolveProperty(myScope, name);
    if (resolved instanceof GrReferenceExpression || resolved == null) return;

    assert resolved instanceof PsiVariable;
    final PsiVariable oldVariable = (PsiVariable) resolved;
    myField = oldVariable instanceof PsiField ? (PsiField) oldVariable : null;
    if (!(oldVariable instanceof PsiField)) return;

    myReferenceExpressions = new ArrayList<>();
    for (PsiReference reference :
        ReferencesSearch.search(myField, new LocalSearchScope(myScope), false)) {
      final PsiElement element = reference.getElement();
      if (element instanceof GrReferenceExpression) {
        final GrReferenceExpression referenceExpression = (GrReferenceExpression) element;
        if (referenceExpression.getQualifier() == null) {
          myReferenceExpressions.add(referenceExpression);
        }
      }
    }
    if (myField.hasModifierProperty(PsiModifier.STATIC)) {
      myQualifyingClass = myField.getContainingClass();
    }
  }
 public FieldConflictsResolver(String name, PsiCodeBlock scope) {
   myScope = scope;
   if (myScope == null) {
     myField = null;
     myReferenceExpressions = null;
     return;
   }
   JavaPsiFacade facade = JavaPsiFacade.getInstance(myScope.getProject());
   final PsiVariable oldVariable =
       facade.getResolveHelper().resolveAccessibleReferencedVariable(name, myScope);
   myField = oldVariable instanceof PsiField ? (PsiField) oldVariable : null;
   if (!(oldVariable instanceof PsiField)) {
     myReferenceExpressions = null;
     return;
   }
   myReferenceExpressions = new ArrayList<PsiReferenceExpression>();
   for (PsiReference reference :
       ReferencesSearch.search(myField, new LocalSearchScope(myScope), false)) {
     final PsiElement element = reference.getElement();
     if (element instanceof PsiReferenceExpression) {
       final PsiReferenceExpression referenceExpression = (PsiReferenceExpression) element;
       if (referenceExpression.getQualifierExpression() == null) {
         myReferenceExpressions.add(referenceExpression);
       }
     }
   }
   if (myField.hasModifierProperty(PsiModifier.STATIC)) {
     myQualifyingClass = myField.getContainingClass();
   }
 }
Exemplo n.º 11
0
 public static void checkFieldConflicts(
     @Nullable PsiClass aClass, String newName, final Map<PsiElement, String> conflicts) {
   PsiField existingField = aClass != null ? aClass.findFieldByName(newName, true) : null;
   if (existingField != null) {
     if (aClass.equals(existingField.getContainingClass())) {
       String className =
           aClass instanceof PsiAnonymousClass
               ? RefactoringBundle.message("current.class")
               : RefactoringUIUtil.getDescription(aClass, false);
       final String conflict =
           RefactoringBundle.message(
               "field.0.is.already.defined.in.the.1", existingField.getName(), className);
       conflicts.put(existingField, conflict);
     } else { // method somewhere in base class
       if (!existingField.hasModifierProperty(PsiModifier.PRIVATE)) {
         String fieldInfo =
             PsiFormatUtil.formatVariable(
                 existingField,
                 PsiFormatUtil.SHOW_NAME | PsiFormatUtil.SHOW_TYPE | PsiFormatUtil.TYPE_AFTER,
                 PsiSubstitutor.EMPTY);
         String className =
             RefactoringUIUtil.getDescription(existingField.getContainingClass(), false);
         final String descr =
             RefactoringBundle.message(
                 "field.0.will.hide.field.1.of.the.base.class", newName, fieldInfo, className);
         conflicts.put(existingField, descr);
       }
     }
   }
 }
Exemplo n.º 12
0
 private static void checkCodeBlock(
     final PsiCodeBlock body, final Set<PsiField> candidates, Set<PsiField> usedFields) {
   try {
     final ControlFlow controlFlow =
         ControlFlowFactory.getInstance(body.getProject())
             .getControlFlow(body, AllVariablesControlFlowPolicy.getInstance());
     final List<PsiVariable> usedVars =
         ControlFlowUtil.getUsedVariables(controlFlow, 0, controlFlow.getSize());
     for (PsiVariable usedVariable : usedVars) {
       if (usedVariable instanceof PsiField) {
         final PsiField usedField = (PsiField) usedVariable;
         if (!usedFields.add(usedField)) {
           candidates.remove(usedField); // used in more than one code block
         }
       }
     }
     final List<PsiReferenceExpression> readBeforeWrites =
         ControlFlowUtil.getReadBeforeWrite(controlFlow);
     for (final PsiReferenceExpression readBeforeWrite : readBeforeWrites) {
       final PsiElement resolved = readBeforeWrite.resolve();
       if (resolved instanceof PsiField) {
         final PsiField field = (PsiField) resolved;
         PsiElement parent = body.getParent();
         if (!(parent instanceof PsiMethod)
             || !((PsiMethod) parent).isConstructor()
             || field.getInitializer() == null
             || field.hasModifierProperty(PsiModifier.STATIC)) {
           candidates.remove(field);
         }
       }
     }
   } catch (AnalysisCanceledException e) {
     candidates.clear();
   }
 }
  @Nullable
  static HighlightInfo checkFinalFieldInitialized(@NotNull PsiField field) {
    if (!field.hasModifierProperty(PsiModifier.FINAL)) return null;
    if (isFieldInitializedAfterObjectConstruction(field)) return null;

    String description = JavaErrorMessages.message("variable.not.initialized", field.getName());
    TextRange range = HighlightNamesUtil.getFieldDeclarationTextRange(field);
    HighlightInfo highlightInfo =
        HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR)
            .range(range)
            .descriptionAndTooltip(description)
            .create();
    QuickFixAction.registerQuickFixAction(
        highlightInfo,
        HighlightMethodUtil.getFixRange(field),
        QUICK_FIX_FACTORY.createCreateConstructorParameterFromFieldFix(field));
    QuickFixAction.registerQuickFixAction(
        highlightInfo,
        HighlightMethodUtil.getFixRange(field),
        QUICK_FIX_FACTORY.createInitializeFinalFieldInConstructorFix(field));
    final PsiClass containingClass = field.getContainingClass();
    if (containingClass != null && !containingClass.isInterface()) {
      QuickFixAction.registerQuickFixAction(
          highlightInfo,
          QUICK_FIX_FACTORY.createModifierListFix(field, PsiModifier.FINAL, false, false));
    }
    QuickFixAction.registerQuickFixAction(
        highlightInfo, QUICK_FIX_FACTORY.createAddVariableInitializerFix(field));
    return highlightInfo;
  }
  private static boolean isCompileConstantInIfCondition(PsiElement element) {
    if (!(element instanceof PsiReferenceExpression)) return false;
    PsiElement resolved = ((PsiReferenceExpression) element).resolve();
    if (!(resolved instanceof PsiField)) return false;
    PsiField field = (PsiField) resolved;

    if (!field.hasModifierProperty(PsiModifier.FINAL)) return false;
    if (!field.hasModifierProperty(PsiModifier.STATIC)) return false;

    PsiElement parent = element.getParent();
    if (parent instanceof PsiPrefixExpression
        && ((PsiPrefixExpression) parent).getOperationTokenType() == JavaTokenType.EXCL) {
      element = parent;
      parent = parent.getParent();
    }
    return parent instanceof PsiIfStatement && ((PsiIfStatement) parent).getCondition() == element;
  }
  public Collection<PsiElement> getAdditionalElementsToDelete(
      @NotNull final PsiElement element,
      @NotNull final Collection<PsiElement> allElementsToDelete,
      final boolean askUser) {
    if (element instanceof PsiField) {
      PsiField field = (PsiField) element;
      final Project project = element.getProject();
      String propertyName =
          JavaCodeStyleManager.getInstance(project)
              .variableNameToPropertyName(field.getName(), VariableKind.FIELD);

      PsiClass aClass = field.getContainingClass();
      if (aClass != null) {
        boolean isStatic = field.hasModifierProperty(PsiModifier.STATIC);
        PsiMethod[] getters =
            GetterSetterPrototypeProvider.findGetters(aClass, propertyName, isStatic);
        if (getters != null) {
          final List<PsiMethod> validGetters = new ArrayList<>(1);
          for (PsiMethod getter : getters) {
            if (!allElementsToDelete.contains(getter) && (getter != null && getter.isPhysical())) {
              validGetters.add(getter);
            }
          }
          getters =
              validGetters.isEmpty()
                  ? null
                  : validGetters.toArray(new PsiMethod[validGetters.size()]);
        }

        PsiMethod setter = PropertyUtil.findPropertySetter(aClass, propertyName, isStatic, false);
        if (allElementsToDelete.contains(setter) || setter != null && !setter.isPhysical())
          setter = null;
        if (askUser && (getters != null || setter != null)) {
          final String message =
              RefactoringMessageUtil.getGetterSetterMessage(
                  field.getName(),
                  RefactoringBundle.message("delete.title"),
                  getters != null ? getters[0] : null,
                  setter);
          if (!ApplicationManager.getApplication().isUnitTestMode()
              && Messages.showYesNoDialog(
                      project,
                      message,
                      RefactoringBundle.message("safe.delete.title"),
                      Messages.getQuestionIcon())
                  != Messages.YES) {
            getters = null;
            setter = null;
          }
        }
        List<PsiElement> elements = new ArrayList<>();
        if (setter != null) elements.add(setter);
        if (getters != null) Collections.addAll(elements, getters);
        return elements;
      }
    }
    return null;
  }
 public RemoveMiddlemanProcessor(PsiField field, List<MemberInfo> memberInfos) {
   super(field.getProject());
   this.field = field;
   containingClass = field.getContainingClass();
   final String propertyName = PropertyUtil.suggestPropertyName(field);
   final boolean isStatic = field.hasModifierProperty(PsiModifier.STATIC);
   getter = PropertyUtil.findPropertyGetter(containingClass, propertyName, isStatic, false);
   myDelegateMethodInfos = memberInfos;
 }
 private static boolean isAvailable(PsiField field) {
   PsiClass containingClass = field == null ? null : field.getContainingClass();
   return field != null
       && field.getManager().isInProject(field)
       && !field.hasModifierProperty(PsiModifier.STATIC)
       && containingClass != null
       && !(containingClass instanceof PsiSyntheticClass)
       && containingClass.getName() != null;
 }
  @Override
  protected ClassMember[] getAllOriginalMembers(PsiClass aClass) {
    PsiField[] fields = aClass.getFields();
    ArrayList<ClassMember> array = new ArrayList<ClassMember>();
    ImplicitUsageProvider[] implicitUsageProviders =
        Extensions.getExtensions(ImplicitUsageProvider.EP_NAME);
    fieldLoop:
    for (PsiField field : fields) {
      if (field.hasModifierProperty(PsiModifier.STATIC)) continue;

      if (field.hasModifierProperty(PsiModifier.FINAL) && field.getInitializer() != null) continue;

      for (ImplicitUsageProvider provider : implicitUsageProviders) {
        if (provider.isImplicitWrite(field)) continue fieldLoop;
      }
      array.add(new PsiFieldMember(field));
    }
    return array.toArray(new ClassMember[array.size()]);
  }
Exemplo n.º 19
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;
    }
  }
  public void updateReturnValueTemplate(PsiExpression expression) {
    if (myReturnValueTemplate == null) return;

    if (!getSuperMethods().isEmpty()) {
      for (final RefMethod refMethod : getSuperMethods()) {
        RefMethodImpl refSuper = (RefMethodImpl) refMethod;
        refSuper.updateReturnValueTemplate(expression);
      }
    } else {
      String newTemplate = null;
      final RefJavaUtil refUtil = RefJavaUtil.getInstance();
      if (expression instanceof PsiLiteralExpression) {
        PsiLiteralExpression psiLiteralExpression = (PsiLiteralExpression) expression;
        newTemplate = psiLiteralExpression.getText();
      } else if (expression instanceof PsiReferenceExpression) {
        PsiReferenceExpression referenceExpression = (PsiReferenceExpression) expression;
        PsiElement resolved = referenceExpression.resolve();
        if (resolved instanceof PsiField) {
          PsiField psiField = (PsiField) resolved;
          if (psiField.hasModifierProperty(PsiModifier.STATIC)
              && psiField.hasModifierProperty(PsiModifier.FINAL)
              && refUtil.compareAccess(refUtil.getAccessModifier(psiField), getAccessModifier())
                  >= 0) {
            newTemplate =
                PsiFormatUtil.formatVariable(
                    psiField,
                    PsiFormatUtilBase.SHOW_NAME
                        | PsiFormatUtilBase.SHOW_CONTAINING_CLASS
                        | PsiFormatUtilBase.SHOW_FQ_NAME,
                    PsiSubstitutor.EMPTY);
          }
        }
      } else if (refUtil.isCallToSuperMethod(expression, (PsiMethod) getElement())) return;

      //noinspection StringEquality
      if (myReturnValueTemplate == RETURN_VALUE_UNDEFINED) {
        myReturnValueTemplate = newTemplate;
      } else if (!Comparing.equal(myReturnValueTemplate, newTemplate)) {
        myReturnValueTemplate = null;
      }
    }
  }
 private static boolean isFieldInitializedInOtherFieldInitializer(
     @NotNull PsiClass aClass, @NotNull PsiField field, final boolean fieldStatic) {
   PsiField[] fields = aClass.getFields();
   for (PsiField psiField : fields) {
     if (psiField != field
         && psiField.hasModifierProperty(PsiModifier.STATIC) == fieldStatic
         && variableDefinitelyAssignedIn(field, psiField)) {
       return true;
     }
   }
   return false;
 }
 protected static List<ClassMember> preselect(ClassMember[] members) {
   final List<ClassMember> preselection = new ArrayList<ClassMember>();
   for (ClassMember member : members) {
     if (member instanceof PsiFieldMember) {
       final PsiField psiField = ((PsiFieldMember) member).getElement();
       if (psiField != null && psiField.hasModifierProperty(PsiModifier.FINAL)) {
         preselection.add(member);
       }
     }
   }
   return preselection;
 }
Exemplo n.º 23
0
  @Nullable
  public static PsiField findPropertyField(
      Project project, PsiClass aClass, String propertyName, boolean isStatic) {
    PsiField[] fields = aClass.getAllFields();

    for (PsiField field : fields) {
      if (field.hasModifierProperty(PsiModifier.STATIC) != isStatic) continue;
      if (propertyName.equals(suggestPropertyName(project, field))) return field;
    }

    return null;
  }
Exemplo n.º 24
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;
  }
    public void visitClass(PsiClass aClass) {
      super.visitClass(aClass);
      if (isConcreteClass(aClass)) {
        final PsiField[] allFields = aClass.getAllFields();
        int numInheritedFields = 0;
        for (final PsiField field : allFields) {
          final PsiClass containingClass = field.getContainingClass();
          if (containingClass != null
              && !containingClass.equals(aClass)
              && !field.hasModifierProperty(PsiModifier.STATIC)) {
            numInheritedFields++;
          }
        }

        postMetric(aClass, numInheritedFields);
      }
    }
  public static boolean isFieldInitializedAfterObjectConstruction(@NotNull PsiField field) {
    if (field.hasInitializer()) return true;
    final boolean isFieldStatic = field.hasModifierProperty(PsiModifier.STATIC);
    final PsiClass aClass = field.getContainingClass();
    if (aClass != null) {
      // field might be assigned in the other field initializers
      if (isFieldInitializedInOtherFieldInitializer(aClass, field, isFieldStatic)) return true;
    }
    final PsiClassInitializer[] initializers;
    if (aClass != null) {
      initializers = aClass.getInitializers();
    } else {
      return false;
    }
    for (PsiClassInitializer initializer : initializers) {
      if (initializer.hasModifierProperty(PsiModifier.STATIC) == isFieldStatic
          && variableDefinitelyAssignedIn(field, initializer.getBody())) {
        return true;
      }
    }
    if (isFieldStatic) {
      return false;
    } else {
      // instance field should be initialized at the end of the each constructor
      final PsiMethod[] constructors = aClass.getConstructors();

      if (constructors.length == 0) return false;
      nextConstructor:
      for (PsiMethod constructor : constructors) {
        PsiCodeBlock ctrBody = constructor.getBody();
        if (ctrBody == null) return false;
        final List<PsiMethod> redirectedConstructors =
            JavaHighlightUtil.getChainedConstructors(constructor);
        for (int j = 0; redirectedConstructors != null && j < redirectedConstructors.size(); j++) {
          PsiMethod redirectedConstructor = redirectedConstructors.get(j);
          final PsiCodeBlock body = redirectedConstructor.getBody();
          if (body != null && variableDefinitelyAssignedIn(field, body)) continue nextConstructor;
        }
        if (!ctrBody.isValid() || variableDefinitelyAssignedIn(field, ctrBody)) {
          continue;
        }
        return false;
      }
      return true;
    }
  }
 @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);
   }
 }
 @Override
 public void visitField(@NotNull PsiField field) {
   super.visitField(field);
   if (!field.hasModifierProperty(PsiModifier.PRIVATE)) {
     return;
   }
   if (HighlightUtil.isSerializationImplicitlyUsedField(field)) {
     return;
   }
   final PsiClass containingClass = PsiUtil.getTopLevelClass(field);
   if (!shouldCheckVariable(field, containingClass)) {
     return;
   }
   final ArrayReadWriteVisitor visitor =
       new ArrayReadWriteVisitor(field, !isSimpleArrayExpression(field.getInitializer()));
   containingClass.accept(visitor);
   final boolean written = visitor.isWritten();
   if (!visitor.isReferenced() || written == visitor.isRead()) {
     return;
   }
   registerFieldError(field, Boolean.valueOf(written));
 }
  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));
        }
      }
    }
  }
  private static boolean containsOnlyPrivates(final PsiClass aClass) {
    final PsiField[] fields = aClass.getFields();
    for (PsiField field : fields) {
      if (!field.hasModifierProperty(PsiModifier.PRIVATE)) return false;
    }

    final PsiMethod[] methods = aClass.getMethods();
    for (PsiMethod method : methods) {
      if (!method.hasModifierProperty(PsiModifier.PRIVATE)) {
        if (method.isConstructor()) { // skip non-private constructors with call to super only
          final PsiCodeBlock body = method.getBody();
          if (body != null) {
            final PsiStatement[] statements = body.getStatements();
            if (statements.length == 0) continue;
            if (statements.length == 1 && statements[0] instanceof PsiExpressionStatement) {
              final PsiExpression expression =
                  ((PsiExpressionStatement) statements[0]).getExpression();
              if (expression instanceof PsiMethodCallExpression) {
                PsiReferenceExpression methodExpression =
                    ((PsiMethodCallExpression) expression).getMethodExpression();
                if (methodExpression.getText().equals(PsiKeyword.SUPER)) {
                  continue;
                }
              }
            }
          }
        }
        return false;
      }
    }

    final PsiClass[] inners = aClass.getInnerClasses();
    for (PsiClass inner : inners) {
      if (!inner.hasModifierProperty(PsiModifier.PRIVATE)) return false;
    }

    return true;
  }