com.intellij.psi.util.PsiUtil Java Examples

The following examples show how to use com.intellij.psi.util.PsiUtil. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HaxePullUpDialog.java    From intellij-haxe with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isMemberEnabled(MemberInfo member) {
  final PsiClass currentSuperClass = getSuperClass();
  if(currentSuperClass == null) return true;
  if (myMemberInfoStorage.getDuplicatedMemberInfos(currentSuperClass).contains(member)) return false;
  if (myMemberInfoStorage.getExtending(currentSuperClass).contains(member.getMember())) return false;
  final boolean isInterface = currentSuperClass.isInterface();
  if (!isInterface) return true;
  PsiElement element = member.getMember();
  if (element instanceof PsiClass && ((PsiClass) element).isInterface()) return true;
  if (element instanceof PsiField) {
    return ((PsiModifierListOwner) element).hasModifierProperty(PsiModifier.STATIC);
  }
  if (element instanceof PsiMethod) {
    final PsiSubstitutor superSubstitutor = TypeConversionUtil
      .getSuperClassSubstitutor(currentSuperClass, myClass, PsiSubstitutor.EMPTY);
    final MethodSignature signature = ((PsiMethod) element).getSignature(superSubstitutor);
    final PsiMethod superClassMethod = MethodSignatureUtil.findMethodBySignature(currentSuperClass, signature, false);
    if (superClassMethod != null && !PsiUtil.isLanguageLevel8OrHigher(currentSuperClass)) return false;
    return !((PsiModifierListOwner) element).hasModifierProperty(PsiModifier.STATIC) || PsiUtil.isLanguageLevel8OrHigher(currentSuperClass);
  }
  return true;
}
 
Example #2
Source File: InnerBuilderUtils.java    From innerbuilder with Apache License 2.0 6 votes vote down vote up
/**
 * @param file   psi file
 * @param editor editor
 * @return psiClass if class is static or top level. Otherwise returns {@code null}
 */
@Nullable
public static PsiClass getStaticOrTopLevelClass(PsiFile file, Editor editor) {
    final int offset = editor.getCaretModel().getOffset();
    final PsiElement element = file.findElementAt(offset);
    if (element == null) {
        return null;
    }

    PsiClass topLevelClass = PsiUtil.getTopLevelClass(element);
    PsiClass psiClass = PsiTreeUtil.getParentOfType(element, PsiClass.class);
    if (psiClass != null && (psiClass.hasModifierProperty(PsiModifier.STATIC) ||
            psiClass.getManager().areElementsEquivalent(psiClass, topLevelClass)))
        return psiClass;
    else
        return null;
}
 
Example #3
Source File: InnerBuilderGenerator.java    From innerbuilder with Apache License 2.0 6 votes vote down vote up
private PsiMethod generateCopyConstructor(final PsiClass targetClass, final PsiType builderType,
                                          final Collection<PsiFieldMember> nonFinalFields,
                                          final Set<InnerBuilderOption> options) {

    final PsiMethod copyConstructor = psiElementFactory.createConstructor(builderType.getPresentableText());
    PsiUtil.setModifierProperty(copyConstructor, PsiModifier.PUBLIC, true);

    final PsiType targetClassType = psiElementFactory.createType(targetClass);
    final PsiParameter constructorParameter = psiElementFactory.createParameter("copy", targetClassType);
    final PsiModifierList parameterModifierList = constructorParameter.getModifierList();

    if (parameterModifierList != null) {
        if (options.contains(InnerBuilderOption.JSR305_ANNOTATIONS))
            parameterModifierList.addAnnotation(JSR305_NONNULL);
        if (options.contains(InnerBuilderOption.FINDBUGS_ANNOTATION))
            parameterModifierList.addAnnotation(FINDBUGS_NONNULL);
    }
    copyConstructor.getParameterList().add(constructorParameter);
    addCopyBody(nonFinalFields, copyConstructor, "this.");
    return copyConstructor;
}
 
Example #4
Source File: AbstractPsiElementNavigationHandler.java    From NutzCodeInsight with Apache License 2.0 6 votes vote down vote up
@Override
public void navigate(MouseEvent mouseEvent, PsiElement psiElement) {
    if (canNavigate(psiElement)) {
        final Project project = psiElement.getProject();
        final List<PsiElement> psiElements = findReferences(psiElement);
        if (psiElements.size() == 1) {
            FileEditorManager.getInstance(project).openFile(PsiUtil.getVirtualFile(psiElements.get(0)), true);
        } else if (psiElements.size() > 1) {
            NavigationUtil.getPsiElementPopup(psiElements.toArray(new PsiElement[0]), title).show(new RelativePoint(mouseEvent));
        } else {
            if (Objects.isNull(psiElements) || psiElements.size() <= 0) {
                Messages.showErrorDialog("没有找到这个调用的方法,请检查!", "错误提示");
            }
        }
    }
}
 
Example #5
Source File: ReplaceConditionalWithPolymorphism.java    From IntelliJDeodorant with MIT License 6 votes vote down vote up
private void setPublicModifierToSourceTypeDeclaration() {
    InheritanceTree tree = null;
    if (typeCheckElimination.getExistingInheritanceTree() != null) {
        tree = typeCheckElimination.getExistingInheritanceTree();
    } else if (typeCheckElimination.getInheritanceTreeMatchingWithStaticTypes() != null) {
        tree = typeCheckElimination.getInheritanceTreeMatchingWithStaticTypes();
    }

    String abstractClassName = null;
    if (tree != null) {
        DefaultMutableTreeNode root = tree.getRootNode();
        abstractClassName = (String) root.getUserObject();
    }
    String sourcePackageName = PsiUtil.getPackageName(sourceTypeDeclaration);
    if (sourcePackageName != null && abstractClassName != null && abstractClassName.contains(".")) {
        String targetPackageName = abstractClassName.substring(0, abstractClassName.lastIndexOf("."));
        if (!sourcePackageName.equals(targetPackageName)) {
            PsiUtil.setModifierProperty(sourceTypeDeclaration, PsiModifier.PUBLIC, true);
        }
    }
}
 
Example #6
Source File: HaxePullUpHelper.java    From intellij-haxe with Apache License 2.0 5 votes vote down vote up
@Override
public void setCorrectVisibility(MemberInfo info) {
  PsiModifierListOwner modifierListOwner = info.getMember();
  if (myIsTargetInterface) {
    PsiUtil.setModifierProperty(modifierListOwner, PsiModifier.PUBLIC, true);
  }
  else if (modifierListOwner.hasModifierProperty(PsiModifier.PRIVATE)) {
    if (info.isToAbstract() || willBeUsedInSubclass(modifierListOwner, myTargetSuperClass, mySourceClass)) {
      PsiUtil.setModifierProperty(modifierListOwner, PsiModifier.PROTECTED, true);
    }
    if (modifierListOwner instanceof PsiClass) {
      modifierListOwner.accept(new JavaRecursiveElementWalkingVisitor() {
        @Override
        public void visitMethod(PsiMethod method) {
          check(method);
        }

        @Override
        public void visitField(PsiField field) {
          check(field);
        }

        @Override
        public void visitClass(PsiClass aClass) {
          check(aClass);
          super.visitClass(aClass);
        }

        private void check(PsiMember member) {
          if (member.hasModifierProperty(PsiModifier.PRIVATE)) {
            if (willBeUsedInSubclass(member, myTargetSuperClass, mySourceClass)) {
              PsiUtil.setModifierProperty(member, PsiModifier.PROTECTED, true);
            }
          }
        }
      });
    }
  }
}
 
Example #7
Source File: GodClassUserInputDialog.java    From IntelliJDeodorant with MIT License 5 votes vote down vote up
public GodClassUserInputDialog(AbstractExtractClassRefactoring abstractRefactoring, AbstractRefactoringPanel godClassPanel) {
    super(abstractRefactoring.getRefactoring().getSourceFile().getProject(), true);
    this.abstractRefactoring = abstractRefactoring;
    this.refactoring = abstractRefactoring.getRefactoring();
    String packageName = PsiUtil.getPackageName(refactoring.getSourceClass());
    parentPackage = JavaPsiFacade.getInstance(refactoring.getProject()).findPackage(packageName);
    this.godClassPanel = godClassPanel;
    initialiseControls();
    setTitle(IntelliJDeodorantBundle.message("god.class.dialog.title"));
    init();
}
 
Example #8
Source File: InnerBuilderGenerator.java    From innerbuilder with Apache License 2.0 5 votes vote down vote up
@NotNull
private PsiClass createBuilderClass(final PsiClass targetClass) {
    final PsiClass builderClass = (PsiClass) targetClass.add(psiElementFactory.createClass(BUILDER_CLASS_NAME));
    PsiUtil.setModifierProperty(builderClass, PsiModifier.STATIC, true);
    PsiUtil.setModifierProperty(builderClass, PsiModifier.FINAL, true);
    setBuilderComment(builderClass, targetClass);
    setBuilderAnnotation(builderClass);
    return builderClass;
}
 
Example #9
Source File: InnerBuilderGenerator.java    From innerbuilder with Apache License 2.0 5 votes vote down vote up
private PsiMethod generateNewBuilderMethod(final PsiType builderType, final Collection<PsiFieldMember> finalFields,
                                           final Set<InnerBuilderOption> options) {
    final PsiMethod newBuilderMethod = psiElementFactory.createMethod("newBuilder", builderType);
    PsiUtil.setModifierProperty(newBuilderMethod, PsiModifier.STATIC, true);
    PsiUtil.setModifierProperty(newBuilderMethod, PsiModifier.PUBLIC, true);

    final StringBuilder fieldList = new StringBuilder();
    if (!finalFields.isEmpty()) {
        for (final PsiFieldMember member : finalFields) {
            final PsiField field = member.getElement();
            final PsiType fieldType = field.getType();
            final String fieldName = field.getName();

            final PsiParameter parameter = psiElementFactory.createParameter(fieldName, fieldType);
            final PsiModifierList parameterModifierList = parameter.getModifierList();
            if (parameterModifierList != null) {

                if (!InnerBuilderUtils.isPrimitive(field)) {
                    if (options.contains(InnerBuilderOption.JSR305_ANNOTATIONS))
                        parameterModifierList.addAnnotation(JSR305_NONNULL);
                    if (options.contains(InnerBuilderOption.FINDBUGS_ANNOTATION))
                        parameterModifierList.addAnnotation(FINDBUGS_NONNULL);
                }
            }
            newBuilderMethod.getParameterList().add(parameter);
            if (fieldList.length() > 0) {
                fieldList.append(", ");
            }
            fieldList.append(fieldName);
        }
    }
    final PsiCodeBlock newBuilderMethodBody = newBuilderMethod.getBody();
    if (newBuilderMethodBody != null) {
        final PsiStatement newStatement = psiElementFactory.createStatementFromText(String.format(
                        "return new %s(%s);", builderType.getPresentableText(), fieldList.toString()),
                newBuilderMethod);
        newBuilderMethodBody.add(newStatement);
    }
    return newBuilderMethod;
}
 
Example #10
Source File: InnerBuilderGenerator.java    From innerbuilder with Apache License 2.0 5 votes vote down vote up
private PsiMethod generateBuilderConstructor(final PsiClass builderClass,
                                             final Collection<PsiFieldMember> finalFields,
                                             final Set<InnerBuilderOption> options) {

    final PsiMethod builderConstructor = psiElementFactory.createConstructor(builderClass.getName());
    if (options.contains(InnerBuilderOption.NEW_BUILDER_METHOD)) {
        PsiUtil.setModifierProperty(builderConstructor, PsiModifier.PRIVATE, true);
    } else {
        PsiUtil.setModifierProperty(builderConstructor, PsiModifier.PUBLIC, true);
    }
    final PsiCodeBlock builderConstructorBody = builderConstructor.getBody();
    if (builderConstructorBody != null) {
        for (final PsiFieldMember member : finalFields) {
            final PsiField field = member.getElement();
            final PsiType fieldType = field.getType();
            final String fieldName = field.getName();

            final PsiParameter parameter = psiElementFactory.createParameter(fieldName, fieldType);
            final PsiModifierList parameterModifierList = parameter.getModifierList();
            final boolean useJsr305 = options.contains(InnerBuilderOption.JSR305_ANNOTATIONS);
            final boolean useFindbugs = options.contains(InnerBuilderOption.FINDBUGS_ANNOTATION);

            if (!InnerBuilderUtils.isPrimitive(field) && parameterModifierList != null) {
                if (useJsr305) parameterModifierList.addAnnotation(JSR305_NONNULL);
                if (useFindbugs) parameterModifierList.addAnnotation(FINDBUGS_NONNULL);
            }

            builderConstructor.getParameterList().add(parameter);
            final PsiStatement assignStatement = psiElementFactory.createStatementFromText(String.format(
                    "this.%1$s = %1$s;", fieldName), builderConstructor);
            builderConstructorBody.add(assignStatement);
        }
    }

    return builderConstructor;
}
 
Example #11
Source File: ReplaceTypeCodeWithStateStrategyDialog.java    From IntelliJDeodorant with MIT License 5 votes vote down vote up
public ReplaceTypeCodeWithStateStrategyDialog(ReplaceTypeCodeWithStateStrategy refactoring,
                                              Runnable applyRefactoringCallback) {
    super(refactoring.getProject(), true);

    this.refactoring = refactoring;
    String packageName = PsiUtil.getPackageName(refactoring.getSourceTypeDeclaration());
    parentPackage = JavaPsiFacade.getInstance(refactoring.getProject()).findPackage(packageName);
    this.applyRefactoringCallback = applyRefactoringCallback;
    init();
    setTitle(IntelliJDeodorantBundle.message("replace.type.code.with.state.strategy.name"));
    setListeners();
}
 
Example #12
Source File: BaseLombokHandler.java    From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private boolean haveAllMethodsSameAccessLevel(Collection<PsiMethod> psiMethods) {
  final Set<Integer> accessLevelSet = new HashSet<>();
  for (PsiMethod psiMethod : psiMethods) {
    accessLevelSet.add(PsiUtil.getAccessLevel(psiMethod.getModifierList()));
  }
  return accessLevelSet.size() <= 1;
}
 
Example #13
Source File: BaseLombokHandler.java    From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private boolean isNotAnnotatedWithOrSameAccessLevelAs(PsiClass psiClass, PsiMethod firstPropertyMethod, Class<? extends Annotation> annotationClass) {
  final PsiAnnotation presentAnnotation = PsiAnnotationSearchUtil.findAnnotation(psiClass, annotationClass);
  if (null != presentAnnotation) {

    final String presentAccessModifier = LombokProcessorUtil.getMethodModifier(presentAnnotation);
    final String currentAccessModifier = PsiUtil.getAccessModifier(PsiUtil.getAccessLevel(firstPropertyMethod.getModifierList()));

    return (presentAccessModifier == null && currentAccessModifier == null) ||
      (presentAccessModifier != null && presentAccessModifier.equals(currentAccessModifier));
  }
  return true;
}
 
Example #14
Source File: PsiTypeUtil.java    From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static PsiType substituteTypeParameter(@NotNull PsiType psiType, String superClass, int paramIndex) {
  PsiType oneElementType = PsiUtil.substituteTypeParameter(psiType, superClass, paramIndex, true);
  if (oneElementType instanceof PsiWildcardType) {
    oneElementType = ((PsiWildcardType) oneElementType).getBound();
  }
  return oneElementType;
}
 
Example #15
Source File: LombokProcessorUtil.java    From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@NotNull
public static PsiAnnotation createAnnotationWithAccessLevel(@NotNull Class<? extends Annotation> annotationClass, @NotNull PsiModifierListOwner psiModifierListOwner) {
  String value = "";
  final PsiModifierList modifierList = psiModifierListOwner.getModifierList();
  if (null != modifierList) {
    final int accessLevelCode = PsiUtil.getAccessLevel(modifierList);

    final AccessLevel accessLevel = ACCESS_LEVEL_MAP.get(accessLevelCode);
    if (null != accessLevel && !AccessLevel.PUBLIC.equals(accessLevel)) {
      value = AccessLevel.class.getName() + "." + accessLevel;
    }
  }

  return PsiAnnotationUtil.createPsiAnnotation(psiModifierListOwner, annotationClass, value);
}
 
Example #16
Source File: DelegateHandler.java    From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void addMethodsOfType(PsiType psiType, Collection<Pair<PsiMethod, PsiSubstitutor>> allMethods) {
  final PsiClassType.ClassResolveResult resolveResult = PsiUtil.resolveGenericsClassInType(psiType);

  final PsiClass psiClass = resolveResult.getElement();
  if (null != psiClass) {
    collectAllMethods(allMethods, psiClass, resolveResult.getSubstitutor());
  }
}
 
Example #17
Source File: HaxePullUpHelper.java    From intellij-haxe with Apache License 2.0 5 votes vote down vote up
private void doMoveField(PsiSubstitutor substitutor, MemberInfo info) {
  PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(myProject);
  PsiField field = (PsiField)info.getMember();

  field.normalizeDeclaration();
  RefactoringUtil.replaceMovedMemberTypeParameters(field, PsiUtil.typeParametersIterable(mySourceClass), substitutor, elementFactory);
  fixReferencesToStatic(field);
  if (myIsTargetInterface) {
    PsiUtil.setModifierProperty(field, PsiModifier.PUBLIC, true);
  }
  final PsiMember movedElement = (PsiMember)myTargetSuperClass.addBefore(convertFieldToLanguage(field, myTargetSuperClass.getLanguage()), myTargetSuperClass.getRBrace());
  myMembersAfterMove.add(movedElement);
  field.delete();
}
 
Example #18
Source File: HaxePullUpDialog.java    From intellij-haxe with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isAbstractEnabled(MemberInfo member) {
  PsiClass currentSuperClass = getSuperClass();
  if (currentSuperClass == null || !currentSuperClass.isInterface()) return true;
  if (PsiUtil.isLanguageLevel8OrHigher(currentSuperClass)) {
    return true;
  }
  return false;
}
 
Example #19
Source File: PushDownProcessor.java    From intellij-haxe with Apache License 2.0 5 votes vote down vote up
private void removeFromTargetClass() throws IncorrectOperationException {
  for (MemberInfo memberInfo : myMemberInfos) {
    final PsiElement member = memberInfo.getMember();

    if (member instanceof PsiField) {
      member.delete();
    }
    else if (member instanceof PsiMethod) {
      if (memberInfo.isToAbstract()) {
        final PsiMethod method = (PsiMethod)member;
        if (method.hasModifierProperty(PsiModifier.PRIVATE)) {
          PsiUtil.setModifierProperty(method, PsiModifier.PROTECTED, true);
        }
        RefactoringUtil.makeMethodAbstract(myClass, method);
        myJavaDocPolicy.processOldJavaDoc(method.getDocComment());
      }
      else {
        member.delete();
      }
    }
    else if (member instanceof PsiClass) {
      //if (Boolean.FALSE.equals(memberInfo.getOverrides())) {
        //RefactoringUtil.removeFromReferenceList(myClass.getImplementsList(), (PsiClass)member);
      //}
      //else {
      //}

      member.delete();
    }
  }
}
 
Example #20
Source File: HaxeStructureViewElement.java    From intellij-haxe with Apache License 2.0 5 votes vote down vote up
@Override
public int getAccessLevel() {
  HaxeNamedComponent namedComponent = null;
  if (myElement instanceof HaxeNamedComponent) {
    namedComponent = (HaxeNamedComponent)myElement;
  }
  else if (myElement.getParent() instanceof HaxeNamedComponent) {
    namedComponent = (HaxeNamedComponent)myElement.getParent();
  }
  return namedComponent == null || !namedComponent.isPublic() ? PsiUtil.ACCESS_LEVEL_PROTECTED : PsiUtil.ACCESS_LEVEL_PUBLIC;
}
 
Example #21
Source File: JavaClassUtils.java    From camel-idea-plugin with Apache License 2.0 5 votes vote down vote up
public PsiClass resolveClassReference(@NotNull PsiReference reference) {
    final PsiElement resolveElement = reference.resolve();

    if (resolveElement instanceof PsiClass) {
        return (PsiClass) resolveElement;
    } else if (resolveElement instanceof PsiField) {
        final PsiType psiType = PsiUtil.getTypeByPsiElement(resolveElement);
        if (psiType != null) {
            return ((PsiClassReferenceType) psiType).resolve();
        }
    }

    return null;
}
 
Example #22
Source File: AbstractMethodFragment.java    From IntelliJDeodorant with MIT License 5 votes vote down vote up
private Set<PsiPrefixExpression> getMatchingPrefixAssignments(PsiVariable variable, List<PsiExpression> prefixExpressions) {
    Set<PsiPrefixExpression> matchingPrefixAssignments = new LinkedHashSet<>();
    for (PsiExpression expression : prefixExpressions) {
        if (expression instanceof PsiPrefixExpression) {
            PsiPrefixExpression prefixExpression = (PsiPrefixExpression) expression;
            PsiExpression operand = prefixExpression.getOperand();
            if (operand == null) continue;
            PsiElement element = operand.getLastChild();
            if (element != null && element.equals(variable) && PsiUtil.isIncrementDecrementOperation(operand)) {
                matchingPrefixAssignments.add(prefixExpression);
            }
        }
    }
    return matchingPrefixAssignments;
}
 
Example #23
Source File: AbstractMethodFragment.java    From IntelliJDeodorant with MIT License 5 votes vote down vote up
void processThrowStatement(PsiThrowStatement throwStatement) {
    PsiExpression expression = throwStatement.getException();
    if (expression instanceof PsiNewExpression) {
        PsiNewExpression newExpression = (PsiNewExpression) expression;
        if (newExpression.getArrayDimensions().length == 0) {
            PsiMethod constructorCall = newExpression.resolveConstructor();
            if (constructorCall != null) {
                addExceptionInThrowStatement(PsiUtil.getMemberQualifiedName(constructorCall));
            }
        }
    }
}
 
Example #24
Source File: PolymorphismRefactoring.java    From IntelliJDeodorant with MIT License 4 votes vote down vote up
protected void setPublicModifierToAccessedMethods() {
    for (PsiMethod methodDeclaration : typeCheckElimination.getAccessedMethods()) {
        PsiUtil.setModifierProperty(methodDeclaration, PsiModifier.PUBLIC, true);
    }
}
 
Example #25
Source File: ElementUtils.java    From aircon with MIT License 4 votes vote down vote up
static String getPackageName(final PsiField configField) {
	return PsiUtil.getPackageName(configField.getContainingClass());
}
 
Example #26
Source File: HaxeCallReferenceProcessor.java    From intellij-haxe with Apache License 2.0 4 votes vote down vote up
@Override
public boolean process(@NotNull PsiReference reference, @NotNull JavaCallHierarchyData jchdata) {
  if (!(jchdata instanceof CallData)) {
    String msg = "Internal error, unexpected call data type passed in.";
    LOG.error(msg);
    throw new UnsupportedOperationException(msg);
  }
  CallData data = (CallData)jchdata;

  PsiClass originalClass = data.getOriginalClass();
  PsiMethod method = data.getMethod();
  Set<PsiMethod> methodsToFind = data.getMethodsToFind();
  PsiMethod methodToFind = data.getMethodToFind();
  PsiClassType originalType = data.getOriginalType();
  Map<PsiMember, NodeDescriptor> methodToDescriptorMap = data.getResultMap();
  Project myProject = data.getProject();
  HaxeHierarchyTimeoutHandler timeoutHandler = data.getTimeoutHandler();

  // All done, if we time out.
  if (timeoutHandler.checkAndCancelIfNecessary()) {
    return false;
  }

  if (reference instanceof HaxeReferenceExpression) {
    final PsiElement qualifierElement = ((HaxeReferenceExpression)reference).getQualifier();
    final HaxeReferenceExpression qualifier = (HaxeReferenceExpression) qualifierElement;
    if (qualifier instanceof HaxeSuperExpression) { // filter super.foo() call inside foo() and similar cases (bug 8411)
      final PsiClass superClass = PsiUtil.resolveClassInType(qualifier.getPsiType());
      if (superClass == null || originalClass.isInheritor(superClass, true)) {
        return true;
      }
    }
    if (qualifier != null && !methodToFind.hasModifierProperty(PsiModifier.STATIC)) {
      final PsiType qualifierType = qualifier.getPsiType();
      if (qualifierType instanceof PsiClassType &&
          !TypeConversionUtil.isAssignable(qualifierType, originalType) &&
          methodToFind != method) {
        final PsiClass psiClass = ((PsiClassType)qualifierType).resolve();
        if (psiClass != null) {
          final PsiMethod callee = psiClass.findMethodBySignature(methodToFind, true);
          if (callee != null && !methodsToFind.contains(callee)) {
            // skip sibling methods
            return true;
          }
        }
      }
    }
  }
  else {
    if (!(reference instanceof PsiElement)) {
      return true;
    }

    final PsiElement parent = ((PsiElement)reference).getParent();
    // If the parent is a 'new x' expression, but the reference isn't the primary
    // expression, then keep looking.
    if (parent instanceof HaxeNewExpression) {
      if (((HaxeNewExpression)parent).getType().getReferenceExpression() != reference) {
        return true;
      }
    }
    // If the reference isn't the primary expression of an anonymous class, then keep looking?
    else if (parent instanceof PsiAnonymousClass) {
      // XXX: This appears to be an optimization, knowing that an anonymous class can't be
      //      referenced from outside of itself, there's no need to load the class by
      //      calling for the base reference (the first child of the class).  The haxe
      //      PSI doesn't appear to be built in that fashion any way...
      // if (((PsiAnonymousClass)parent).getBaseClassReference() != reference) {
      //   return true;
      // }

      // let it be processed.
    }
    else {
      return true;
    }
  }

  final PsiElement element = reference.getElement();
  final PsiMember key = CallHierarchyNodeDescriptor.getEnclosingElement(element);

  synchronized (methodToDescriptorMap) {
    CallHierarchyNodeDescriptor d = (CallHierarchyNodeDescriptor)methodToDescriptorMap.get(key);
    if (d == null) {
      d = new CallHierarchyNodeDescriptor(myProject, (CallHierarchyNodeDescriptor)data.getNodeDescriptor(), element, false, true);
      methodToDescriptorMap.put(key, d);
    }
    else if (!d.hasReference(reference)) {
      d.incrementUsageCount();
    }
    d.addReference(reference);
  }
  return false;
}
 
Example #27
Source File: PsiTypeUtil.java    From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Nullable
public static String getQualifiedName(@NotNull PsiType psiType) {
  final PsiClass psiFieldClass = PsiUtil.resolveClassInType(psiType);
  return psiFieldClass != null ? psiFieldClass.getQualifiedName() : null;
}
 
Example #28
Source File: IdeaUtils.java    From camel-idea-plugin with Apache License 2.0 4 votes vote down vote up
/**
 * Is the element from XML language
 */
public boolean isXmlLanguage(PsiElement element) {
    return element != null && PsiUtil.getNotAnyLanguage(element.getNode()).is(XMLLanguage.INSTANCE);
}
 
Example #29
Source File: IdeaUtils.java    From camel-idea-plugin with Apache License 2.0 4 votes vote down vote up
/**
 * Is the element from Java language
 */
public boolean isJavaLanguage(PsiElement element) {
    return element != null && PsiUtil.getNotAnyLanguage(element.getNode()).is(JavaLanguage.INSTANCE);
}
 
Example #30
Source File: InnerBuilderGenerator.java    From innerbuilder with Apache License 2.0 4 votes vote down vote up
@Override
public void run() {
    final PsiClass targetClass = InnerBuilderUtils.getStaticOrTopLevelClass(file, editor);
    if (targetClass == null) {
        return;
    }
    final Set<InnerBuilderOption> options = currentOptions();
    final PsiClass builderClass = findOrCreateBuilderClass(targetClass);
    final PsiType builderType = psiElementFactory.createTypeFromText(BUILDER_CLASS_NAME, null);
    final PsiMethod constructor = generateConstructor(targetClass, builderType);

    addMethod(targetClass, null, constructor, true);
    final Collection<PsiFieldMember> finalFields = new ArrayList<PsiFieldMember>();
    final Collection<PsiFieldMember> nonFinalFields = new ArrayList<PsiFieldMember>();

    PsiElement lastAddedField = null;
    for (final PsiFieldMember fieldMember : selectedFields) {
        lastAddedField = findOrCreateField(builderClass, fieldMember, lastAddedField);
        if (fieldMember.getElement().hasModifierProperty(PsiModifier.FINAL)
                && !options.contains(InnerBuilderOption.FINAL_SETTERS)) {
            finalFields.add(fieldMember);
            PsiUtil.setModifierProperty((PsiField) lastAddedField, PsiModifier.FINAL, true);
        } else {
            nonFinalFields.add(fieldMember);
        }
    }
    if (options.contains(InnerBuilderOption.NEW_BUILDER_METHOD)) {
        final PsiMethod newBuilderMethod = generateNewBuilderMethod(builderType, finalFields, options);
        addMethod(targetClass, null, newBuilderMethod, false);
    }

    // builder constructor, accepting the final fields
    final PsiMethod builderConstructorMethod = generateBuilderConstructor(builderClass, finalFields, options);
    addMethod(builderClass, null, builderConstructorMethod, false);

    // builder copy constructor or static copy method
    if (options.contains(InnerBuilderOption.COPY_CONSTRUCTOR)) {
        if (options.contains(InnerBuilderOption.NEW_BUILDER_METHOD)) {
            final PsiMethod copyBuilderMethod = generateCopyBuilderMethod(targetClass, builderType,
                    nonFinalFields, options);
            addMethod(targetClass, null, copyBuilderMethod, true);
        } else {
            final PsiMethod copyConstructorBuilderMethod = generateCopyConstructor(targetClass, builderType,
                    selectedFields, options);
            addMethod(builderClass, null, copyConstructorBuilderMethod, true);
        }
    }

    // builder methods
    PsiElement lastAddedElement = null;
    for (final PsiFieldMember member : nonFinalFields) {
        final PsiMethod setterMethod = generateBuilderSetter(builderType, member, options);
        lastAddedElement = addMethod(builderClass, lastAddedElement, setterMethod, false);
    }

    // builder.build() method
    final PsiMethod buildMethod = generateBuildMethod(targetClass, options);
    addMethod(builderClass, lastAddedElement, buildMethod, false);

    JavaCodeStyleManager.getInstance(project).shortenClassReferences(file);
    CodeStyleManager.getInstance(project).reformat(builderClass);
}