@NotNull public PsiReference[] getReferences() { ProgressManager.checkCanceled(); final ASTNode startTagName = XmlChildRole.START_TAG_NAME_FINDER.findChild(this); if (startTagName == null) return PsiReference.EMPTY_ARRAY; final ASTNode endTagName = XmlChildRole.CLOSING_TAG_NAME_FINDER.findChild(this); List<PsiReference> refs = new ArrayList<PsiReference>(); String prefix = getNamespacePrefix(); TagNameReference startTagRef = TagNameReference.createTagNameReference(this, startTagName, true); refs.add(startTagRef); if (prefix.length() > 0) { refs.add(createPrefixReference(startTagName, prefix, startTagRef)); } if (endTagName != null) { TagNameReference endTagRef = TagNameReference.createTagNameReference(this, endTagName, false); refs.add(endTagRef); prefix = XmlUtil.findPrefixByQualifiedName(endTagName.getText()); if (StringUtil.isNotEmpty(prefix)) { refs.add(createPrefixReference(endTagName, prefix, endTagRef)); } } // ArrayList.addAll() makes a clone of the collection //noinspection ManualArrayToCollectionCopy for (PsiReference ref : ReferenceProvidersRegistry.getReferencesFromProviders(this, XmlTag.class)) { refs.add(ref); } return ContainerUtil.toArray(refs, new PsiReference[refs.size()]); }
private static String[] getSuggestionsByValue(final String stringValue) { List<String> result = new ArrayList<String>(); StringBuffer currentWord = new StringBuffer(); boolean prevIsUpperCase = false; for (int i = 0; i < stringValue.length(); i++) { final char c = stringValue.charAt(i); if (Character.isUpperCase(c)) { if (currentWord.length() > 0 && !prevIsUpperCase) { result.add(currentWord.toString()); currentWord = new StringBuffer(); } currentWord.append(c); } else if (Character.isLowerCase(c)) { currentWord.append(Character.toUpperCase(c)); } else if (Character.isJavaIdentifierPart(c) && c != '_') { if (Character.isJavaIdentifierStart(c) || currentWord.length() > 0 || !result.isEmpty()) { currentWord.append(c); } } else { if (currentWord.length() > 0) { result.add(currentWord.toString()); currentWord = new StringBuffer(); } } prevIsUpperCase = Character.isUpperCase(c); } if (currentWord.length() > 0) { result.add(currentWord.toString()); } return ArrayUtil.toStringArray(result); }
@NotNull public XmlTag[] findSubTags(final String name, final String namespace) { final XmlTag[] subTags = getSubTags(); final List<XmlTag> result = new ArrayList<XmlTag>(); for (final XmlTag subTag : subTags) { if (namespace == null) { if (name.equals(subTag.getName())) result.add(subTag); } else if (name.equals(subTag.getLocalName()) && namespace.equals(subTag.getNamespace())) { result.add(subTag); } } return ContainerUtil.toArray(result, new XmlTag[result.size()]); }
private static void processCallerMethod( JavaChangeInfo changeInfo, PsiMethod caller, PsiMethod baseMethod, boolean toInsertParams, boolean toInsertThrows) throws IncorrectOperationException { LOG.assertTrue(toInsertParams || toInsertThrows); if (toInsertParams) { List<PsiParameter> newParameters = new ArrayList<PsiParameter>(); ContainerUtil.addAll(newParameters, caller.getParameterList().getParameters()); final JavaParameterInfo[] primaryNewParms = changeInfo.getNewParameters(); PsiSubstitutor substitutor = baseMethod == null ? PsiSubstitutor.EMPTY : ChangeSignatureProcessor.calculateSubstitutor(caller, baseMethod); for (JavaParameterInfo info : primaryNewParms) { if (info.getOldIndex() < 0) newParameters.add(createNewParameter(changeInfo, info, substitutor)); } PsiParameter[] arrayed = newParameters.toArray(new PsiParameter[newParameters.size()]); boolean[] toRemoveParm = new boolean[arrayed.length]; Arrays.fill(toRemoveParm, false); resolveParameterVsFieldsConflicts(arrayed, caller, caller.getParameterList(), toRemoveParm); } if (toInsertThrows) { List<PsiJavaCodeReferenceElement> newThrowns = new ArrayList<PsiJavaCodeReferenceElement>(); final PsiReferenceList throwsList = caller.getThrowsList(); ContainerUtil.addAll(newThrowns, throwsList.getReferenceElements()); final ThrownExceptionInfo[] primaryNewExns = changeInfo.getNewExceptions(); for (ThrownExceptionInfo thrownExceptionInfo : primaryNewExns) { if (thrownExceptionInfo.getOldIndex() < 0) { final PsiClassType type = (PsiClassType) thrownExceptionInfo.createType(caller, caller.getManager()); final PsiJavaCodeReferenceElement ref = JavaPsiFacade.getInstance(caller.getProject()) .getElementFactory() .createReferenceElementByType(type); newThrowns.add(ref); } } PsiJavaCodeReferenceElement[] arrayed = newThrowns.toArray(new PsiJavaCodeReferenceElement[newThrowns.size()]); boolean[] toRemoveParm = new boolean[arrayed.length]; Arrays.fill(toRemoveParm, false); ChangeSignatureUtil.synchronizeList( throwsList, Arrays.asList(arrayed), ThrowsList.INSTANCE, toRemoveParm); } }
private void processUsagesPerFile(UsageInfo[] usages) { Map<PsiFile, List<EncapsulateFieldUsageInfo>> usagesInFiles = new HashMap<PsiFile, List<EncapsulateFieldUsageInfo>>(); for (UsageInfo usage : usages) { PsiElement element = usage.getElement(); if (element == null) continue; final PsiFile file = element.getContainingFile(); List<EncapsulateFieldUsageInfo> usagesInFile = usagesInFiles.get(file); if (usagesInFile == null) { usagesInFile = new ArrayList<EncapsulateFieldUsageInfo>(); usagesInFiles.put(file, usagesInFile); } usagesInFile.add(((EncapsulateFieldUsageInfo) usage)); } for (List<EncapsulateFieldUsageInfo> usageInfos : usagesInFiles.values()) { // this is to avoid elements to become invalid as a result of processUsage final EncapsulateFieldUsageInfo[] infos = usageInfos.toArray(new EncapsulateFieldUsageInfo[usageInfos.size()]); CommonRefactoringUtil.sortDepthFirstRightLeftOrder(infos); for (EncapsulateFieldUsageInfo info : infos) { EncapsulateFieldHelper helper = EncapsulateFieldHelper.getHelper(info.getElement().getLanguage()); helper.processUsage( info, myDescriptor, myNameToSetter.get(info.getFieldDescriptor().getSetterName()), myNameToGetter.get(info.getFieldDescriptor().getGetterName())); } } }
private static PsiClassType[] filterCheckedExceptions(PsiClassType[] exceptions) { List<PsiClassType> result = new ArrayList<PsiClassType>(); for (PsiClassType exceptionType : exceptions) { if (!ExceptionUtil.isUncheckedException(exceptionType)) result.add(exceptionType); } return result.toArray(new PsiClassType[result.size()]); }
@NotNull private static PsiSubstitutor replaceVariables(Collection<InferenceVariable> inferenceVariables) { final List<InferenceVariable> targetVars = new ArrayList<InferenceVariable>(); PsiSubstitutor substitutor = PsiSubstitutor.EMPTY; final InferenceVariable[] oldVars = inferenceVariables.toArray(new InferenceVariable[inferenceVariables.size()]); for (InferenceVariable variable : oldVars) { final InferenceVariable newVariable = new InferenceVariable( variable.getCallContext(), variable.getParameter(), variable.getName()); substitutor = substitutor.put( variable, JavaPsiFacade.getElementFactory(variable.getProject()).createType(newVariable)); targetVars.add(newVariable); if (variable.isThrownBound()) { newVariable.setThrownBound(); } } for (int i = 0; i < targetVars.size(); i++) { InferenceVariable var = targetVars.get(i); for (InferenceBound boundType : InferenceBound.values()) { for (PsiType bound : oldVars[i].getBounds(boundType)) { var.addBound(substitutor.substitute(bound), boundType, null); } } } return substitutor; }
@Override public Result<PsiModifierList> compute() { List<PsiModifierList> list = new ArrayList<PsiModifierList>(); for (PsiDirectory directory : getDirectories()) { PsiFile file = directory.findFile(PACKAGE_INFO_FILE); if (file != null) { PsiPackageStatement stmt = PsiTreeUtil.getChildOfType(file, PsiPackageStatement.class); if (stmt != null) { final PsiModifierList modifierList = stmt.getAnnotationList(); if (modifierList != null) { list.add(modifierList); } } } } final JavaPsiFacade facade = getFacade(); final GlobalSearchScope scope = allScope(); for (PsiClass aClass : facade.findClasses(getQualifiedName() + ".package-info", scope)) { ContainerUtil.addIfNotNull(aClass.getModifierList(), list); } return new Result<PsiModifierList>( list.isEmpty() ? null : new PsiCompositeModifierList(getManager(), list), OOCB_DEPENDENCY); }
private void collectUncaughtExceptions(@NotNull PsiMethod method) { if (isExternalOverride()) return; if (getRefManager().isOfflineView()) return; @NonNls final String name = method.getName(); if (getOwnerClass().isTestCase() && name.startsWith("test")) return; if (getSuperMethods().isEmpty()) { PsiClassType[] throwsList = method.getThrowsList().getReferencedTypes(); if (throwsList.length > 0) { myUnThrownExceptions = throwsList.length == 1 ? new SmartList<String>() : new ArrayList<String>(throwsList.length); for (final PsiClassType type : throwsList) { PsiClass aClass = type.resolve(); String fqn = aClass == null ? null : aClass.getQualifiedName(); if (fqn != null) { myUnThrownExceptions.add(fqn); } } } } final PsiCodeBlock body = method.getBody(); if (body == null) return; final Collection<PsiClassType> exceptionTypes = ExceptionUtil.collectUnhandledExceptions(body, method, false); for (final PsiClassType exceptionType : exceptionTypes) { updateThrowsList(exceptionType); } }
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()]); }
@NotNull private static List<PsiMethod> findMethodsBySignature( @NotNull PsiClass aClass, @NotNull PsiMethod patternMethod, boolean checkBases, boolean stopOnFirst) { final PsiMethod[] methodsByName = aClass.findMethodsByName(patternMethod.getName(), checkBases); if (methodsByName.length == 0) return Collections.emptyList(); final List<PsiMethod> methods = new SmartList<PsiMethod>(); final MethodSignature patternSignature = patternMethod.getSignature(PsiSubstitutor.EMPTY); for (final PsiMethod method : methodsByName) { final PsiClass superClass = method.getContainingClass(); final PsiSubstitutor substitutor; if (checkBases && !aClass.equals(superClass)) { substitutor = TypeConversionUtil.getSuperClassSubstitutor(superClass, aClass, PsiSubstitutor.EMPTY); } else { substitutor = PsiSubstitutor.EMPTY; } final MethodSignature signature = method.getSignature(substitutor); if (signature.equals(patternSignature)) { methods.add(method); if (stopOnFirst) { break; } } } return methods; }
private static PsiClassType[] filterUnhandledExceptions( PsiClassType[] exceptions, PsiElement place) { List<PsiClassType> result = new ArrayList<PsiClassType>(); for (PsiClassType exception : exceptions) { if (!ExceptionUtil.isHandled(exception, place)) result.add(exception); } return result.toArray(new PsiClassType[result.size()]); }
public void markExtended(RefMethodImpl method) { if (!getDerivedMethods().contains(method) && !method.getDerivedMethods().contains(this)) { if (myDerivedMethods == null) { myDerivedMethods = new ArrayList<RefMethod>(1); } myDerivedMethods.add(method); } }
public void addSuperMethod(RefMethodImpl refSuperMethod) { if (!getSuperMethods().contains(refSuperMethod) && !refSuperMethod.getSuperMethods().contains(this)) { if (mySuperMethods == null) { mySuperMethods = new ArrayList<RefMethod>(1); } mySuperMethods.add(refSuperMethod); } }
public static PsiClass[] getInterfaces(GrTypeDefinition grType) { final PsiClassType[] implementsListTypes = grType.getImplementsListTypes(); List<PsiClass> result = new ArrayList<PsiClass>(implementsListTypes.length); for (PsiClassType type : implementsListTypes) { final PsiClass psiClass = type.resolve(); if (psiClass != null) result.add(psiClass); } return result.toArray(new PsiClass[result.size()]); }
public static void addExpandingReflectedMethods(List<PsiMethod> result, PsiMethod method) { if (method instanceof GrMethod) { final GrReflectedMethod[] reflectedMethods = ((GrMethod) method).getReflectedMethods(); if (reflectedMethods.length > 0) { result.addAll(Arrays.asList(reflectedMethods)); return; } } result.add(method); }
@Nullable @Override protected RefactoringEventData getBeforeData() { RefactoringEventData data = new RefactoringEventData(); final List<PsiElement> fields = new ArrayList<PsiElement>(); for (FieldDescriptor fieldDescriptor : myFieldDescriptors) { fields.add(fieldDescriptor.getField()); } data.addElements(fields); return data; }
@NotNull public static PsiClass[] getSupers(GrTypeDefinition grType) { PsiClassType[] superTypes = grType.getSuperTypes(); List<PsiClass> result = new ArrayList<PsiClass>(); for (PsiClassType superType : superTypes) { PsiClass superClass = superType.resolve(); if (superClass != null) { result.add(superClass); } } return result.toArray(new PsiClass[result.size()]); }
@NotNull private static List<PsiMember> findByMap( @NotNull PsiClass aClass, String name, boolean checkBases, @NotNull MemberType type) { if (name == null) return Collections.emptyList(); if (checkBases) { Map<String, List<Pair<PsiMember, PsiSubstitutor>>> allMethodsMap = getMap(aClass, type); List<Pair<PsiMember, PsiSubstitutor>> list = allMethodsMap.get(name); if (list == null) return Collections.emptyList(); List<PsiMember> ret = new ArrayList<PsiMember>(list.size()); for (final Pair<PsiMember, PsiSubstitutor> info : list) { ret.add(info.getFirst()); } return ret; } else { PsiMember[] members = null; switch (type) { case METHOD: members = aClass.getMethods(); break; case CLASS: members = aClass.getInnerClasses(); break; case FIELD: members = aClass.getFields(); break; } List<PsiMember> list = new ArrayList<PsiMember>(); for (PsiMember member : members) { if (name.equals(member.getName())) { list.add(member); } } return list; } }
public static List<PsiExpression> getReturnExpressions(PsiLambdaExpression lambdaExpression) { final PsiElement body = lambdaExpression.getBody(); if (body instanceof PsiExpression) { // if (((PsiExpression)body).getType() != PsiType.VOID) return Collections.emptyList(); return Collections.singletonList((PsiExpression) body); } final List<PsiExpression> result = new ArrayList<PsiExpression>(); for (PsiReturnStatement returnStatement : getReturnStatements(lambdaExpression)) { final PsiExpression returnValue = returnStatement.getReturnValue(); if (returnValue != null) { result.add(returnValue); } } return result; }
private static List<PsiImportStaticStatement> getMatchingImports( @NotNull PsiImportList importList, @NotNull String className) { final List<PsiImportStaticStatement> imports = new ArrayList(); for (PsiImportStaticStatement staticStatement : importList.getImportStaticStatements()) { final PsiClass psiClass = staticStatement.resolveTargetClass(); if (psiClass == null) { continue; } if (!className.equals(psiClass.getQualifiedName())) { continue; } imports.add(staticStatement); } return imports; }
@NotNull private static <T extends PsiMember> List<T> getAllByMap( @NotNull PsiClass aClass, @NotNull MemberType type) { List<Pair<T, PsiSubstitutor>> pairs = getAllWithSubstitutorsByMap(aClass, type); final List<T> ret = new ArrayList<T>(pairs.size()); //noinspection ForLoopReplaceableByForEach for (int i = 0; i < pairs.size(); i++) { Pair<T, PsiSubstitutor> pair = pairs.get(i); T t = pair.getFirst(); LOG.assertTrue(t != null, aClass); ret.add(t); } return ret; }
@NotNull public static PsiClass[] getInterfaces(@NotNull PsiTypeParameter typeParameter) { final PsiClassType[] referencedTypes = typeParameter.getExtendsListTypes(); if (referencedTypes.length == 0) { return PsiClass.EMPTY_ARRAY; } final List<PsiClass> result = new ArrayList<PsiClass>(referencedTypes.length); for (PsiClassType referencedType : referencedTypes) { final PsiClass psiClass = referencedType.resolve(); if (psiClass != null && psiClass.isInterface()) { result.add(psiClass); } } return result.toArray(new PsiClass[result.size()]); }
private String[] getSuggestionsByName( String name, VariableKind variableKind, boolean isArray, boolean correctKeywords) { boolean upperCaseStyle = variableKind == VariableKind.STATIC_FINAL_FIELD; boolean preferLongerNames = getSettings().PREFER_LONGER_NAMES; String prefix = getPrefixByVariableKind(variableKind); String suffix = getSuffixByVariableKind(variableKind); List<String> answer = new ArrayList<String>(); for (String suggestion : NameUtil.getSuggestionsByName( name, prefix, suffix, upperCaseStyle, preferLongerNames, isArray)) { answer.add(correctKeywords ? changeIfNotIdentifier(suggestion) : suggestion); } return ArrayUtil.toStringArray(answer); }
private static PsiMethod[] findMethodsByName( GrTypeDefinition grType, String name, boolean checkBases, boolean includeSyntheticAccessors) { if (!checkBases) { List<PsiMethod> result = new ArrayList<PsiMethod>(); for (PsiMethod method : CollectClassMembersUtil.getMethods(grType, includeSyntheticAccessors)) { if (name.equals(method.getName())) result.add(method); } return result.toArray(new PsiMethod[result.size()]); } Map<String, List<CandidateInfo>> methodsMap = CollectClassMembersUtil.getAllMethods(grType, includeSyntheticAccessors); return PsiImplUtil.mapToMethods(methodsMap.get(name)); }
@Override @Nullable public PsiClass[] getUnThrownExceptions() { if (getRefManager().isOfflineView()) { LOG.debug("Should not traverse graph offline"); } if (myUnThrownExceptions == null) return null; JavaPsiFacade facade = JavaPsiFacade.getInstance(myManager.getProject()); List<PsiClass> result = new ArrayList<PsiClass>(myUnThrownExceptions.size()); for (String exception : myUnThrownExceptions) { PsiClass element = facade.findClass(exception, GlobalSearchScope.allScope(myManager.getProject())); if (element != null) result.add(element); } return result.toArray(new PsiClass[result.size()]); }
private static void getImplementListsInner( GrTypeDefinition grType, List<PsiClassType> result, Set<PsiClass> visited) { if (!visited.add(grType)) return; final PsiClassType[] implementsTypes = getReferenceListTypes(grType.getImplementsClause()); List<PsiClassType> fromDelegates = getImplementsFromDelegate(grType, visited); if (fromDelegates != null) { result.addAll(fromDelegates); } result.addAll(Arrays.asList(implementsTypes)); if (!grType.isInterface() && !ContainerUtil.or(implementsTypes, IS_GROOVY_OBJECT) && !ContainerUtil.or(getReferenceListTypes(grType.getExtendsClause()), IS_GROOVY_OBJECT)) { result.add(getGroovyObjectType(grType)); } }
private static void resolveParameterVsFieldsConflicts( final PsiParameter[] newParms, final PsiMethod method, final PsiParameterList list, boolean[] toRemoveParm) throws IncorrectOperationException { List<FieldConflictsResolver> conflictResolvers = new ArrayList<FieldConflictsResolver>(); for (PsiParameter parameter : newParms) { conflictResolvers.add(new FieldConflictsResolver(parameter.getName(), method.getBody())); } ChangeSignatureUtil.synchronizeList( list, Arrays.asList(newParms), ParameterList.INSTANCE, toRemoveParm); JavaCodeStyleManager.getInstance(list.getProject()).shortenClassReferences(list); for (FieldConflictsResolver fieldConflictsResolver : conflictResolvers) { fieldConflictsResolver.fix(); } }
private static void insertGenerationInfos( InsertionContext context, List<PsiGenerationInfo<PsiMethod>> infos) { List<PsiGenerationInfo<PsiMethod>> newInfos = GenerateMembersUtil.insertMembersAtOffset( context.getFile(), context.getStartOffset(), infos); if (!newInfos.isEmpty()) { final List<PsiElement> elements = new ArrayList<PsiElement>(); for (GenerationInfo member : newInfos) { if (!(member instanceof TemplateGenerationInfo)) { final PsiMember psiMember = member.getPsiMember(); if (psiMember != null) { elements.add(psiMember); } } } GlobalInspectionContextBase.cleanupElements( context.getProject(), null, elements.toArray(new PsiElement[elements.size()])); newInfos.get(0).positionCaret(context.getEditor(), true); } }
/** @param self should be this */ @NotNull private static List<PyAssignmentStatement> findAttributesStatic(@NotNull final PsiElement self) { final List<PyAssignmentStatement> result = new ArrayList<>(); for (final PyAssignmentStatement statement : new PsiQuery(self).siblings(PyAssignmentStatement.class).getElements()) { for (final PyQualifiedExpression targetExpression : new PsiQuery(statement.getTargets()).filter(PyQualifiedExpression.class).getElements()) { final PyExpression qualifier = targetExpression.getQualifier(); if (qualifier == null) { continue; } final PsiReference qualifierReference = qualifier.getReference(); if (qualifierReference == null) { continue; } if (qualifierReference.isReferenceTo(self)) { result.add(statement); } } } return result; }