public void findAllDeclarations() { if (!myDeclarationsFound) { long before = System.currentTimeMillis(); final AnalysisScope scope = getScope(); if (scope != null) { scope.accept(myProjectIterator); } myDeclarationsFound = true; LOG.info( "Total duration of processing project usages:" + (System.currentTimeMillis() - before)); } }
private static void logStats(Collection<PsiFile> otherFiles, long start) { long time = System.currentTimeMillis() - start; final Multiset<String> stats = HashMultiset.create(); for (PsiFile file : otherFiles) { stats.add( StringUtil.notNullize(file.getViewProvider().getVirtualFile().getExtension()) .toLowerCase()); } List<String> extensions = ContainerUtil.newArrayList(stats.elementSet()); Collections.sort( extensions, new Comparator<String>() { @Override public int compare(String o1, String o2) { return stats.count(o2) - stats.count(o1); } }); String message = "Search in " + otherFiles.size() + " files with unknown types took " + time + "ms.\n" + "Mapping their extensions to an existing file type (e.g. Plain Text) might speed up the search.\n" + "Most frequent non-indexed file extensions: "; for (int i = 0; i < Math.min(10, extensions.size()); i++) { String extension = extensions.get(i); message += extension + "(" + stats.count(extension) + ") "; } LOG.info(message); }
@NotNull private static PsiClass[] resolveClassReferenceList( @NotNull PsiClassType[] listOfTypes, @NotNull PsiManager manager, @NotNull GlobalSearchScope resolveScope, boolean includeObject) { PsiClass objectClass = JavaPsiFacade.getInstance(manager.getProject()) .findClass(CommonClassNames.JAVA_LANG_OBJECT, resolveScope); if (objectClass == null) includeObject = false; if (listOfTypes.length == 0) { if (includeObject) return new PsiClass[] {objectClass}; return PsiClass.EMPTY_ARRAY; } int referenceCount = listOfTypes.length; if (includeObject) referenceCount++; PsiClass[] resolved = new PsiClass[referenceCount]; int resolvedCount = 0; if (includeObject) resolved[resolvedCount++] = objectClass; for (PsiClassType reference : listOfTypes) { PsiClass refResolved = reference.resolve(); if (refResolved != null) resolved[resolvedCount++] = refResolved; } if (resolvedCount < referenceCount) { PsiClass[] shorter = new PsiClass[resolvedCount]; System.arraycopy(resolved, 0, shorter, 0, resolvedCount); resolved = shorter; } return resolved; }
private void doPostponedFormattingInner(final FileViewProvider key) { final List<ASTNode> astNodes = myReformatElements.remove(key); final Document document = key.getDocument(); // Sort ranges by end offsets so that we won't need any offset adjustment after reformat or // reindent if (document == null) return; final VirtualFile virtualFile = key.getVirtualFile(); if (!virtualFile.isValid()) return; final TreeSet<PostprocessFormattingTask> postProcessTasks = new TreeSet<PostprocessFormattingTask>(); Collection<Disposable> toDispose = ContainerUtilRt.newArrayList(); try { // process all roots in viewProvider to find marked for reformat before elements and create // appropriate range markers handleReformatMarkers(key, postProcessTasks); toDispose.addAll(postProcessTasks); // then we create ranges by changed nodes. One per node. There ranges can intersect. Ranges // are sorted by end offset. if (astNodes != null) createActionsMap(astNodes, key, postProcessTasks); if ("true".equals(System.getProperty("check.psi.is.valid")) && ApplicationManager.getApplication().isUnitTestMode()) { checkPsiIsCorrect(key); } while (!postProcessTasks.isEmpty()) { // now we have to normalize actions so that they not intersect and ordered in most // appropriate way // (free reformatting -> reindent -> formatting under reindent) final List<PostponedAction> normalizedActions = normalizeAndReorderPostponedActions(postProcessTasks, document); toDispose.addAll(normalizedActions); // only in following loop real changes in document are made for (final PostponedAction normalizedAction : normalizedActions) { CodeStyleSettings settings = CodeStyleSettingsManager.getSettings(myPsiManager.getProject()); boolean old = settings.ENABLE_JAVADOC_FORMATTING; settings.ENABLE_JAVADOC_FORMATTING = false; try { normalizedAction.execute(key); } finally { settings.ENABLE_JAVADOC_FORMATTING = old; } } } } finally { for (Disposable disposable : toDispose) { //noinspection SSBasedInspection disposable.dispose(); } } }
private static ParameterInfoImpl[] generateParameterInfos( PsiMethod method, ParameterInfoImpl[] newParameters) { final PsiParameter[] parameters = method.getParameterList().getParameters(); ParameterInfoImpl[] result = new ParameterInfoImpl[parameters.length + newParameters.length]; for (int i = 0; i < parameters.length; i++) { result[i] = new ParameterInfoImpl(i); } System.arraycopy(newParameters, 0, result, parameters.length, newParameters.length); return result; }
@NotNull private static PsiClass[] getSupersInner(@NotNull PsiClass psiClass) { PsiClassType[] extendsListTypes = psiClass.getExtendsListTypes(); PsiClassType[] implementsListTypes = psiClass.getImplementsListTypes(); if (psiClass.isInterface()) { return resolveClassReferenceList( extendsListTypes, psiClass.getManager(), psiClass.getResolveScope(), true); } if (psiClass instanceof PsiAnonymousClass) { PsiAnonymousClass psiAnonymousClass = (PsiAnonymousClass) psiClass; PsiClassType baseClassReference = psiAnonymousClass.getBaseClassType(); PsiClass baseClass = baseClassReference.resolve(); if (baseClass != null) { if (baseClass.isInterface()) { PsiClass objectClass = JavaPsiFacade.getInstance(psiClass.getProject()) .findClass(CommonClassNames.JAVA_LANG_OBJECT, psiClass.getResolveScope()); return objectClass != null ? new PsiClass[] {objectClass, baseClass} : new PsiClass[] {baseClass}; } return new PsiClass[] {baseClass}; } PsiClass objectClass = JavaPsiFacade.getInstance(psiClass.getProject()) .findClass(CommonClassNames.JAVA_LANG_OBJECT, psiClass.getResolveScope()); return objectClass != null ? new PsiClass[] {objectClass} : PsiClass.EMPTY_ARRAY; } if (psiClass instanceof PsiTypeParameter) { if (extendsListTypes.length == 0) { final PsiClass objectClass = JavaPsiFacade.getInstance(psiClass.getProject()) .findClass(CommonClassNames.JAVA_LANG_OBJECT, psiClass.getResolveScope()); return objectClass != null ? new PsiClass[] {objectClass} : PsiClass.EMPTY_ARRAY; } return resolveClassReferenceList( extendsListTypes, psiClass.getManager(), psiClass.getResolveScope(), false); } PsiClass[] interfaces = resolveClassReferenceList( implementsListTypes, psiClass.getManager(), psiClass.getResolveScope(), false); PsiClass superClass = getSuperClass(psiClass); if (superClass == null) return interfaces; PsiClass[] types = new PsiClass[interfaces.length + 1]; types[0] = superClass; System.arraycopy(interfaces, 0, types, 1, interfaces.length); return types; }
private static ThrownExceptionInfo[] generateExceptionInfos( PsiMethod method, ThrownExceptionInfo[] newExceptions) { final PsiClassType[] exceptions = method.getThrowsList().getReferencedTypes(); ThrownExceptionInfo[] result = new ThrownExceptionInfo[exceptions.length + newExceptions.length]; for (int i = 0; i < exceptions.length; i++) { result[i] = new JavaThrownExceptionInfo(i); } System.arraycopy(newExceptions, 0, result, exceptions.length, newExceptions.length); return result; }
@NotNull public static PsiClassType[] getSuperTypes(@NotNull PsiClass psiClass) { if (psiClass instanceof PsiAnonymousClass) { PsiClassType baseClassType = ((PsiAnonymousClass) psiClass).getBaseClassType(); PsiClass baseClass = baseClassType.resolve(); if (baseClass == null || !baseClass.isInterface()) { return new PsiClassType[] {baseClassType}; } else { PsiClassType objectType = PsiType.getJavaLangObject(psiClass.getManager(), psiClass.getResolveScope()); return new PsiClassType[] {objectType, baseClassType}; } } PsiClassType[] extendsTypes = psiClass.getExtendsListTypes(); PsiClassType[] implementsTypes = psiClass.getImplementsListTypes(); boolean hasExtends = extendsTypes.length != 0; int extendsListLength = extendsTypes.length + (hasExtends ? 0 : 1); PsiClassType[] result = new PsiClassType[extendsListLength + implementsTypes.length]; System.arraycopy(extendsTypes, 0, result, 0, extendsTypes.length); if (!hasExtends) { if (CommonClassNames.JAVA_LANG_OBJECT.equals(psiClass.getQualifiedName())) { return PsiClassType.EMPTY_ARRAY; } PsiManager manager = psiClass.getManager(); PsiClassType objectType = PsiType.getJavaLangObject(manager, psiClass.getResolveScope()); result[0] = objectType; } System.arraycopy(implementsTypes, 0, result, extendsListLength, implementsTypes.length); for (int i = 0; i < result.length; i++) { PsiClassType type = result[i]; result[i] = (PsiClassType) PsiUtil.captureToplevelWildcards(type, psiClass); } return result; }
@Nullable public static DuplicatesFinder createDuplicatesFinder(PsiMember member) { PsiElement[] pattern; ReturnValue matchedReturnValue = null; if (member instanceof PsiMethod) { final PsiCodeBlock body = ((PsiMethod) member).getBody(); LOG.assertTrue(body != null); final PsiStatement[] statements = body.getStatements(); pattern = statements; matchedReturnValue = null; if (statements.length != 1 || !(statements[0] instanceof PsiReturnStatement)) { final PsiStatement lastStatement = statements.length > 0 ? statements[statements.length - 1] : null; if (lastStatement instanceof PsiReturnStatement) { final PsiExpression returnValue = ((PsiReturnStatement) lastStatement).getReturnValue(); if (returnValue instanceof PsiReferenceExpression) { final PsiElement resolved = ((PsiReferenceExpression) returnValue).resolve(); if (resolved instanceof PsiVariable) { pattern = new PsiElement[statements.length - 1]; System.arraycopy(statements, 0, pattern, 0, statements.length - 1); matchedReturnValue = new VariableReturnValue((PsiVariable) resolved); } } } } else { final PsiExpression returnValue = ((PsiReturnStatement) statements[0]).getReturnValue(); if (returnValue != null) { pattern = new PsiElement[] {returnValue}; } } } else { pattern = new PsiElement[] {((PsiField) member).getInitializer()}; } if (pattern.length == 0) { return null; } final List<? extends PsiVariable> inputVariables = member instanceof PsiMethod ? Arrays.asList(((PsiMethod) member).getParameterList().getParameters()) : new ArrayList<>(); return new DuplicatesFinder( pattern, new InputVariables( inputVariables, member.getProject(), new LocalSearchScope(pattern), false), matchedReturnValue, new ArrayList<>()); }
public static ArrayList<RefParameter> getUnusedParameters(RefMethod refMethod) { boolean checkDeep = !refMethod.isStatic() && !refMethod.isConstructor(); ArrayList<RefParameter> res = new ArrayList<RefParameter>(); RefParameter[] methodParameters = refMethod.getParameters(); RefParameter[] result = new RefParameter[methodParameters.length]; System.arraycopy(methodParameters, 0, result, 0, methodParameters.length); clearUsedParameters(refMethod, result, checkDeep); for (RefParameter parameter : result) { if (parameter != null) { res.add(parameter); } } return res; }
public static PsiAnnotation[] getTestNGAnnotations(PsiElement element) { PsiElement[] annotations = PsiTreeUtil.collectElements( element, new PsiElementFilter() { public boolean isAccepted(PsiElement element) { if (!(element instanceof PsiAnnotation)) return false; String name = ((PsiAnnotation) element).getQualifiedName(); if (null == name) return false; if (name.startsWith("org.testng.annotations")) { return true; } return false; } }); PsiAnnotation[] array = new PsiAnnotation[annotations.length]; System.arraycopy(annotations, 0, array, 0, annotations.length); return array; }
public void findUsages( @NotNull final Processor<UsageInfo> consumer, @NotNull FindUsagesProcessPresentation processPresentation) { try { myProgress.setIndeterminate(true); myProgress.setText("Scanning indexed files..."); final Set<PsiFile> filesForFastWordSearch = ApplicationManager.getApplication() .runReadAction( new Computable<Set<PsiFile>>() { @Override public Set<PsiFile> compute() { return getFilesForFastWordSearch(); } }); myProgress.setIndeterminate(false); searchInFiles(filesForFastWordSearch, processPresentation, consumer); myProgress.setIndeterminate(true); myProgress.setText("Scanning non-indexed files..."); boolean skipIndexed = canRelyOnIndices(); final Collection<PsiFile> otherFiles = collectFilesInScope(filesForFastWordSearch, skipIndexed); myProgress.setIndeterminate(false); long start = System.currentTimeMillis(); searchInFiles(otherFiles, processPresentation, consumer); if (skipIndexed && otherFiles.size() > 1000) { logStats(otherFiles, start); } } catch (ProcessCanceledException e) { // fine } if (!myLargeFiles.isEmpty()) { processPresentation.setLargeFilesWereNotScanned(myLargeFiles); } if (!myProgress.isCanceled()) { myProgress.setText(FindBundle.message("find.progress.search.completed")); } }
@Override protected void refreshElements(@NotNull PsiElement[] elements) { LOG.assertTrue(elements.length == myElements.length); System.arraycopy(elements, 0, myElements, 0, elements.length); }
private void processBatch( @NotNull final ProgressIndicator indicator, @NotNull Set<VirtualFile> files) { assert !myApplication.isDispatchThread(); final int resolvedInPreviousBatch = this.resolvedInPreviousBatch; final int totalSize = files.size() + resolvedInPreviousBatch; final ConcurrentIntObjectMap<int[]> fileToForwardIds = ContainerUtil.createConcurrentIntObjectMap(); final Set<VirtualFile> toProcess = Collections.synchronizedSet(files); indicator.setIndeterminate(false); ProgressIndicatorUtils.forceWriteActionPriority(indicator, (Disposable) indicator); long start = System.currentTimeMillis(); Processor<VirtualFile> processor = file -> { double fraction = 1 - toProcess.size() * 1.0 / totalSize; indicator.setFraction(fraction); try { if (!file.isDirectory() && toResolve(file, myProject)) { int fileId = getAbsId(file); int i = totalSize - toProcess.size(); indicator.setText(i + "/" + totalSize + ": Resolving " + file.getPresentableUrl()); int[] forwardIds = processFile(file, fileId, indicator); if (forwardIds == null) { // queueUpdate(file); return false; } fileToForwardIds.put(fileId, forwardIds); } toProcess.remove(file); return true; } catch (RuntimeException e) { indicator.checkCanceled(); } return true; }; boolean success = true; try { success = processFilesConcurrently(files, indicator, processor); } finally { this.resolvedInPreviousBatch = toProcess.isEmpty() ? 0 : totalSize - toProcess.size(); queue(toProcess, "re-added after fail. success=" + success); storeIds(fileToForwardIds); long end = System.currentTimeMillis(); log( "Resolved batch of " + (totalSize - toProcess.size()) + " from " + totalSize + " files in " + ((end - start) / 1000) + "sec. (Gap: " + storage.gap + ")"); synchronized (filesToResolve) { upToDate = filesToResolve.isEmpty(); log("upToDate = " + upToDate); if (upToDate) { for (Listener listener : myListeners) { listener.allFilesResolved(); } } } } }
protected boolean inTestsProduceExceptionOnBadRenameabilityStatus() { return System.getProperty(FORCE_RENAME_PROCESSOR_TO_THROW_EXCEPTION_ON_BAD_RENAMEABILITY) != null; }
// method1 has more general parameter types thn method2 private boolean secondMethodIsPreferable( @NotNull PsiMethod method1, @NotNull PsiSubstitutor substitutor1, @Nullable PsiElement resolveContext1, @NotNull PsiMethod method2, @NotNull PsiSubstitutor substitutor2, @Nullable PsiElement resolveContext2) { if (!method1.getName().equals(method2.getName())) return false; final Boolean custom = GrMethodComparator.checkDominated(method1, substitutor1, method2, substitutor2, this); if (custom != null) return custom; PsiType[] argTypes = myArgumentTypes; if (method1 instanceof GrGdkMethod && method2 instanceof GrGdkMethod) { method1 = ((GrGdkMethod) method1).getStaticMethod(); method2 = ((GrGdkMethod) method2).getStaticMethod(); if (myArgumentTypes != null) { argTypes = PsiType.createArray(argTypes.length + 1); System.arraycopy(myArgumentTypes, 0, argTypes, 1, myArgumentTypes.length); argTypes[0] = myThisType; } } if (myIsConstructor && argTypes != null && argTypes.length == 1) { if (method1.getParameterList().getParametersCount() == 0) return true; if (method2.getParameterList().getParametersCount() == 0) return false; } PsiParameter[] params1 = method1.getParameterList().getParameters(); PsiParameter[] params2 = method2.getParameterList().getParameters(); if (argTypes == null && params1.length != params2.length) return false; if (params1.length < params2.length) { if (params1.length == 0) return false; final PsiType lastType = params1[params1.length - 1].getType(); // varargs applicability return lastType instanceof PsiArrayType; } for (int i = 0; i < params2.length; i++) { final PsiType ptype1 = params1[i].getType(); final PsiType ptype2 = params2[i].getType(); PsiType type1 = substitutor1.substitute(ptype1); PsiType type2 = substitutor2.substitute(ptype2); if (argTypes != null && argTypes.length > i) { PsiType argType = argTypes[i]; if (argType != null) { final boolean converts1 = TypesUtil.isAssignableWithoutConversions( TypeConversionUtil.erasure(type1), argType, myPlace); final boolean converts2 = TypesUtil.isAssignableWithoutConversions( TypeConversionUtil.erasure(type2), argType, myPlace); if (converts1 != converts2) { return converts2; } // see groovy.lang.GroovyCallable if (TypesUtil.resolvesTo(type1, CommonClassNames.JAVA_UTIL_CONCURRENT_CALLABLE) && TypesUtil.resolvesTo(type2, CommonClassNames.JAVA_LANG_RUNNABLE)) { if (InheritanceUtil.isInheritor( argType, GroovyCommonClassNames.GROOVY_LANG_GROOVY_CALLABLE)) return true; } } } if (!typesAgree(TypeConversionUtil.erasure(ptype1), TypeConversionUtil.erasure(ptype2))) return false; if (resolveContext1 != null && resolveContext2 == null) { return !(TypesUtil.resolvesTo(type1, CommonClassNames.JAVA_LANG_OBJECT) && TypesUtil.resolvesTo(type2, CommonClassNames.JAVA_LANG_OBJECT)); } if (resolveContext1 == null && resolveContext2 != null) { return true; } } if (!(method1 instanceof SyntheticElement) && !(method2 instanceof SyntheticElement)) { final PsiType returnType1 = substitutor1.substitute(method1.getReturnType()); final PsiType returnType2 = substitutor2.substitute(method2.getReturnType()); if (!TypesUtil.isAssignableWithoutConversions(returnType1, returnType2, myPlace) && TypesUtil.isAssignableWithoutConversions(returnType2, returnType1, myPlace)) { return false; } } return true; }
static { System.setProperty("jbdt.test.fixture", "com.intellij.designer.dt.IJTestFixture"); }
@NotNull protected UsageViewDescriptor createUsageViewDescriptor(UsageInfo[] usages) { FieldDescriptor[] fields = new FieldDescriptor[myFieldDescriptors.length]; System.arraycopy(myFieldDescriptors, 0, fields, 0, myFieldDescriptors.length); return new EncapsulateFieldsViewDescriptor(fields); }
// This methods works equally well for primary usages as well as for propagated callers' usages private static void fixActualArgumentsList( PsiExpressionList list, JavaChangeInfo changeInfo, boolean toInsertDefaultValue, PsiSubstitutor substitutor) throws IncorrectOperationException { final PsiElementFactory factory = JavaPsiFacade.getInstance(list.getProject()).getElementFactory(); if (changeInfo.isParameterSetOrOrderChanged()) { if (changeInfo instanceof JavaChangeInfoImpl && ((JavaChangeInfoImpl) changeInfo).isPropagationEnabled) { final ParameterInfoImpl[] createdParmsInfo = ((JavaChangeInfoImpl) changeInfo).getCreatedParmsInfoWithoutVarargs(); for (ParameterInfoImpl info : createdParmsInfo) { PsiExpression newArg; if (toInsertDefaultValue) { newArg = createDefaultValue(changeInfo, factory, info, list); } else { newArg = factory.createExpressionFromText(info.getName(), list); } JavaCodeStyleManager.getInstance(list.getProject()) .shortenClassReferences(list.add(newArg)); } } else { final PsiExpression[] args = list.getExpressions(); final int nonVarargCount = getNonVarargCount(changeInfo, args); final int varargCount = args.length - nonVarargCount; if (varargCount < 0) return; PsiExpression[] newVarargInitializers = null; final int newArgsLength; final int newNonVarargCount; final JavaParameterInfo[] newParms = changeInfo.getNewParameters(); if (changeInfo.isArrayToVarargs()) { newNonVarargCount = newParms.length - 1; final JavaParameterInfo lastNewParm = newParms[newParms.length - 1]; final PsiExpression arrayToConvert = args[lastNewParm.getOldIndex()]; if (arrayToConvert instanceof PsiNewExpression) { final PsiNewExpression expression = (PsiNewExpression) arrayToConvert; final PsiArrayInitializerExpression arrayInitializer = expression.getArrayInitializer(); if (arrayInitializer != null) { newVarargInitializers = arrayInitializer.getInitializers(); } } newArgsLength = newVarargInitializers == null ? newParms.length : newNonVarargCount + newVarargInitializers.length; } else if (changeInfo.isRetainsVarargs()) { newNonVarargCount = newParms.length - 1; newArgsLength = newNonVarargCount + varargCount; } else if (changeInfo.isObtainsVarags()) { newNonVarargCount = newParms.length - 1; newArgsLength = newNonVarargCount; } else { newNonVarargCount = newParms.length; newArgsLength = newParms.length; } String[] oldVarargs = null; if (changeInfo.wasVararg() && !changeInfo.isRetainsVarargs()) { oldVarargs = new String[varargCount]; for (int i = nonVarargCount; i < args.length; i++) { oldVarargs[i - nonVarargCount] = args[i].getText(); } } final PsiExpression[] newArgs = new PsiExpression[newArgsLength]; for (int i = 0; i < newNonVarargCount; i++) { if (newParms[i].getOldIndex() == nonVarargCount && oldVarargs != null) { PsiType type = newParms[i].createType(changeInfo.getMethod(), list.getManager()); if (type instanceof PsiArrayType) { type = substitutor.substitute(type); type = TypeConversionUtil.erasure(type); String typeText = type.getCanonicalText(); if (type instanceof PsiEllipsisType) { typeText = typeText.replace("...", "[]"); } String text = "new " + typeText + "{" + StringUtil.join(oldVarargs, ",") + "}"; newArgs[i] = factory.createExpressionFromText(text, changeInfo.getMethod()); continue; } } newArgs[i] = createActualArgument(changeInfo, list, newParms[i], toInsertDefaultValue, args); } if (changeInfo.isArrayToVarargs()) { if (newVarargInitializers == null) { newArgs[newNonVarargCount] = createActualArgument( changeInfo, list, newParms[newNonVarargCount], toInsertDefaultValue, args); } else { System.arraycopy( newVarargInitializers, 0, newArgs, newNonVarargCount, newVarargInitializers.length); } } else { final int newVarargCount = newArgsLength - newNonVarargCount; LOG.assertTrue(newVarargCount == 0 || newVarargCount == varargCount); for (int i = newNonVarargCount; i < newArgsLength; i++) { final int oldIndex = newParms[newNonVarargCount].getOldIndex(); if (oldIndex >= 0 && oldIndex != nonVarargCount) { newArgs[i] = createActualArgument( changeInfo, list, newParms[newNonVarargCount], toInsertDefaultValue, args); } else { System.arraycopy(args, nonVarargCount, newArgs, newNonVarargCount, newVarargCount); break; } } } ChangeSignatureUtil.synchronizeList( list, Arrays.asList(newArgs), ExpressionList.INSTANCE, changeInfo.toRemoveParm()); } } }